stephen-hqxu / superterrainplus

SuperTerrain+: A real-time procedural 3D infinite terrain engine with geographical features and photorealistic rendering.
MIT License
12 stars 1 forks source link

Possible optimisation for heightfield terrain texture splatting in shader #61

Open stephen-hqxu opened 1 year ago

stephen-hqxu commented 1 year ago

The terrain texture splatting currently uses a simple SHF to smooth the border transition of texture regions, which involves use of a region bin to record the frequency of occurrence of each region in a filter kernel.

https://github.com/stephen-hqxu/superterrainplus/blob/482724099a3c0da8d559b815a6543881f76f3390/SuperTerrain%2B/SuperRealism%2B/Public/SuperRealism%2B/Shader/STPHeightfieldTerrain.frag#L213

But later, it will need to loop through all entries in the bin. Even though the loop is continued when the bin is empty, I feel like this can still be quite expensive when the number of texture region is large, like a hundred of them if we are generating a complex landscape.

https://github.com/stephen-hqxu/superterrainplus/blob/482724099a3c0da8d559b815a6543881f76f3390/SuperTerrain%2B/SuperRealism%2B/Public/SuperRealism%2B/Shader/STPHeightfieldTerrain.frag#L272-L277

Possible optimisation

Taking reference from the implementation of SHF, we can use a bin index dictionary that uses a region ID to look up the index into the bin array. The bin array stores the frequency of occurrence for the current region ID.

Unlike the original SHF algorithm, filter optimisation is not used in the shader, so we are only adding new entries to the bin and never need to remove any, so it should be easier to implement.

Finally, we only need to loop through the entries presented in the bin array. This should hopefully reduce the number of iteration drastically.