Search code examples
floating-pointnim-lang

Nim ignores variable assignment


I have the following bit of code in a ray casting demo I'm working on:

var texture_offset: float64
if int(abs(ray.last_point.z / 90) mod 2) == 1:
  texture_offset = round(64f * (ray.last_point.x / TILE_SIZE - floor(ray.last_point.x / TILE_SIZE)))
else: 
  texture_offset = round(64f * (ray.last_point.y / TILE_SIZE - floor(ray.last_point.y / TILE_SIZE)))
echo texture_offset, " ", round(64f * (ray.last_point.x / TILE_SIZE - floor(ray.last_point.x / TILE_SIZE))), " ", round(64f * (ray.last_point.y / TILE_SIZE - floor(ray.last_point.y / TILE_SIZE)))

For clarity, I will rewrite it in the following way:

if horizontal:
  texture_offset = round(64f * ray.hit_point.x) # ray.hit_point.x here would be a float between 0 and 1, obtained from a linear interpolation related to the tile it hit.
else:
  texture_offset = round(64f * ray.hit_point.y)
echo texture_offset, " ", round(64f * ray.hit_point.x), " ", round(64f * ray.hit_point.y)

For some odd reason, the output of the code is the following:

0.0 49.0 0.0 # Example for horizontal edges
0.0 0.0 21.0 # Example for vertical edges

As you can see, the variable texture_offset is always set to 0.0, like it was never assigned a value. I tried manually assigning to it outside the the if statements, and that seems to work with arbitrary values, but assigning the result of that operation to the variable seems to set it to 0.0, which is obviously wrong, since the exact same operation in the echo statement returns non-0 values, way too high to even be accidentally approximated to 0. What is going on?


Solution

  • I figured it out. It was the stupidest mistake ever and I didn't notice it for hours. The if statements determines which component of the hitpoint vector is used to find the correct slice of texture. If the wall is horizontal, we want the x component, and if it is vertical, the y component. Turns out that my if statement was flipped, and casually, if a wall is vertical, doing the calculations with the x component returns 0, as seen in the example output.