Jelajahi Sumber

Fix terrain in hlsl

ShiroSmith 6 tahun lalu
induk
melakukan
7bf5a99dee
2 mengubah file dengan 18 tambahan dan 7 penghapusan
  1. 14 3
      h3d/scene/pbr/terrain/Tile.hx
  2. 4 4
      h3d/shader/pbr/Terrain.hx

+ 14 - 3
h3d/scene/pbr/terrain/Tile.hx

@@ -15,6 +15,7 @@ class Tile extends h3d.scene.Mesh {
 	public var grid (default, null) : h3d.prim.Grid;
 	public var needAlloc = false;
 	public var needNewPixelCapture = false;
+	public var insideFrustrum = false;
 	var heightmapPixels : hxd.Pixels.PixelsFloat;
 	var shader : h3d.shader.pbr.Terrain;
 
@@ -508,8 +509,7 @@ class Tile extends h3d.scene.Mesh {
 
 	var cachedBounds : h3d.col.Bounds;
 	var cachedHeightBound : Bool = false;
-	override function emit( ctx:RenderContext ){
-		if( !isReady() ) return;
+	function computeBounds() {
 		if( cachedBounds == null ) {
 			cachedBounds = getBounds();
 			cachedBounds.zMax = 0;
@@ -523,9 +523,20 @@ class Tile extends h3d.scene.Mesh {
 					cachedBounds.zMax = cachedBounds.zMax < h ? h : cachedBounds.zMax;
 				}
 			}
+			var absPos = getAbsPos();
+			cachedBounds.zMax += absPos.tz;
+			cachedBounds.zMin += absPos.tz;
 			cachedHeightBound = true;
 		}
-		if( ctx.camera.frustum.hasBounds(cachedBounds) )
+	}
+
+	public dynamic function beforeEmit() {};
+	override function emit( ctx:RenderContext ){
+		if( !isReady() ) return;
+		computeBounds();
+		insideFrustrum = ctx.camera.frustum.hasBounds(cachedBounds);
+		beforeEmit();
+		if( insideFrustrum )
 			super.emit(ctx);
 	}
 

+ 4 - 4
h3d/shader/pbr/Terrain.hx

@@ -50,8 +50,8 @@ class Terrain extends hxsl.Shader {
 			terrainUV += 0.5 / heightMapSize;
 			transformedPosition += (vec3(0,0, textureLod(heightMap, terrainUV, 0).r) * global.modelView.mat3());
 			TBN = mat3(normalize(cross(transformedNormal, vec3(0,1,0))), normalize(cross(transformedNormal,vec3(-1,0,0))), transformedNormal);
-			tangentViewPos = TBN * camera.position;
-			tangentFragPos = TBN * transformedPosition;
+			tangentViewPos = camera.position * TBN;
+			tangentFragPos = transformedPosition * TBN;
 		}
 
 		function getWeight( i : Vec3,  uv : Vec2 ) : Vec3 {
@@ -88,7 +88,7 @@ class Terrain extends hxsl.Shader {
 				while( curLayerDepth < curDepth ) {
 					curUV += delta;
 					prevDepth = curDepth;
-					i = surfaceIndexMap.get(curUV).rgb * 255;
+					i = surfaceIndexMap.getLod(curUV, 0).rgb * 255;
 					w = getWeight(i, curUV);
 					depth = getDepth(i, curUV);
 					curDepth = depth.dot(w);
@@ -109,7 +109,7 @@ class Terrain extends hxsl.Shader {
 			var tilling = surfaceParams[id].x;
 			var worldUV = (uv + tileIndex) * tilling + offset;
 			var res = vec2( worldUV.x * cos(angle) - worldUV.y * sin(angle) , worldUV.y * cos(angle) + worldUV.x * sin(angle));
-			var surfaceUV = vec3(res, i);
+			var surfaceUV = vec3(res % 1, i);
 			return surfaceUV;
 		}