Terrain looks fine… until Bullet debug kicks in

I’ve got a ShaderTerrainMesh working with BulletHeightfieldShape, but I’m a bit confused about the starting position, either for the shape or the terrain itself. If I don’t apply this transform to the terrain:

terrain_node.set_pos(-TERRAIN_X/2, -TERRAIN_Y/2, -TERRAIN_H/2)

then the BulletDebugNode ends up drawing misaligned with the terrain, like you can see in the image. Any idea why that happens? I’m using the same shaders that come with the samples, just tweaked the fragment a bit for texture splatting.

Screenshot: screenshot hosted at ImgBB — ImgBB

Full code:

TERRAIN_X = 2048
TERRAIN_Y = 2048
TERRAIN_H = 250

def setup_shader_terrain(app: ShowBase):
	terrain = ShaderTerrainMesh()

	heightfield = app.loader.load_texture(asset_path("terrain", "terrain_heightmap.png"))

	terrain.set_chunk_size(32)
	terrain.set_heightfield(heightfield)
	terrain.set_target_triangle_width(10.0)

	terrain_node = app.render.attach_new_node(terrain)
	terrain_node.set_scale(TERRAIN_X, TERRAIN_Y, TERRAIN_H)
	terrain_node.set_pos(-TERRAIN_X/2, -TERRAIN_Y/2, -TERRAIN_H/2) # fixes the bullet wireframe alignment issue

	# texture splatting stuff ...

	terrain_shader = Shader.load(Shader.SL_GLSL, 
									asset_path("shaders", "terrain.vert.glsl"), 
									asset_path("shaders", "terrain.frag.glsl"))
	
	terrain_node.set_shader(terrain_shader)
	# terrain_node.set_shader_input("camera", app.camera) # not needed with my shader

	# Setup Bullet collision shape
	height_scale = terrain_node.get_sz()
	shape = BulletHeightfieldShape(heightfield, height_scale, Z_up)

	# Create a static body for the terrain and add the shape
	body = BulletRigidBodyNode('terrain-body')
	body.set_mass(0) # A mass of 0 makes it a static object?
	body.add_shape(shape)

	# Attach the body to the scene and the physics world
	terrain_body_np = app.render.attach_new_node(body)
	terrain_body_np.set_collide_mask(BitMask32.bit(0))

	app.world.attach(body)
	terrain_node.reparent_to(terrain_body_np)

	terrain.generate()

Greetings, and welcome to the forums! I hope that you find your time here to be positive! :slight_smile:

As to your question: I imagine that it’s simply that one of the modules considers the centre of the heightmap to be its origin-point, while the other considers a particular corner of the heightmap to be its origin-point.

(I’m not sure offhand of which way around it is; looking at the screenshot that you provide, it looks to me like Bullet considers the centre of the heightmap to be the origin, while ShaderTerrainMesh considers the corner to be the origin.)

As a result, the corner of one mesh is located at the centre of the other.

Looking at the manual, I see that at least one sample given there does indeed apply an offset, as you’ve found to be called for.

Oops, I missed that part :sweat_smile: You’re right, the manual explains it really well.
Thanks for your time, Thaumaturge.

1 Like