Skip to content

Commit

Permalink
Port Tile.update
Browse files Browse the repository at this point in the history
  • Loading branch information
kylebarron committed May 26, 2020
1 parent 2c19bbc commit d7d0b96
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions pymartini/martini.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,59 @@ def __init__(self, grid_size=257):
self.coords[k + 1] = ay
self.coords[k + 2] = bx
self.coords[k + 3] = by

def createTile(self, terrain):
return Tile(terrain, self)


class Tile:
def __init__(self, terrain, martini):
size = martini.grid_size

if len(terrain) != (size * size):
raise ValueError(
f'Expected terrain data of length {size * size} ({size} x {size}), got {len(terrain)}.'
)

self.terrain = terrain
self.martini = martini
self.errors = np.zeros(len(terrain), dtype=np.float32)
self.update()

def update(self):
num_triangles = self.martini.num_triangles
num_parent_triangles = self.martini.num_parent_triangles
coords = self.martini.coords
size = self.martini.grid_size

terrain = self.terrain
errors = self.errors

# iterate over all possible triangles, starting from the smallest level
# TODO: Make sure this range is correct
for i in range(num_triangles - 1, -1, -1):
k = i * 4
ax = coords[k + 0]
ay = coords[k + 1]
bx = coords[k + 2]
by = coords[k + 3]
mx = (ax + bx) >> 1
my = (ay + by) >> 1
cx = mx + my - ay
cy = my + ax - mx

# calculate error in the middle of the long edge of the triangle
interpolated_height = (
terrain[ay * size + ax] + terrain[by * size + bx]) / 2
middle_index = my * size + mx
middle_error = abs(interpolated_height - terrain[middle_index])

errors[middle_index] = max(errors[middle_index], middle_error)

if i < num_parent_triangles:
# bigger triangles; accumulate error with children
left_child_index = ((ay + cy) >> 1) * size + ((ax + cx) >> 1)
right_child_index = ((by + cy) >> 1) * size + ((bx + cx) >> 1)
errors[middle_index] = max(
errors[middle_index], errors[left_child_index],
errors[right_child_index])

0 comments on commit d7d0b96

Please sign in to comment.