#How to use "core:math/fixed"?

1 messages · Page 1 of 1 (latest)

maiden stone
#

I couldn't figure out how to create a usable variable value and there are no example around either.

import "core:math/fixed"

Fixed :: fixed.Fixed16_16
Vec2Fixed :: [2]Fixed

main :: proc() {
    vec2 := Vec2Fixed {
        ???,
        ???,
    } 
}
ocean hill
#

You can initialize it from an f64 with init_from_f64:

vec2: Vec2Fixed
fixed.init_from_f64(&vec2[0], 1.25)
fixed.init_from_f64(&vec2[1], 2.75)

Or from an integer with init_from_parts by passing a fraction of 0

vec2: Vec2Fixed
fixed.init_from_parts(&vec2[0], 123, 0)
fixed.init_from_parts(&vec2[1], 234, 0)

For the fraction parameter of init_from_parts, it's an integer value that's basically the fractional part multiplied by 1 << Fraction_Width (which is equivalent to 2^Fraction_Width):

vec2: Vec2Fixed
fixed.init_from_parts(&vec2[0], 1, 16384) // 1.25
fixed.init_from_parts(&vec2[1], 2, 49152) // 2.75

// you can also multiply a float constant, and the compiler will allow it *if* it can be represented exactly
fixed.init_from_parts(&vec2[0], 1, 0.25 * (1 << 16)) // also 1.25
fixed.init_from_parts(&vec2[1], 2, 0.75 * (1 << 16)) // also 2.75
//fixed.init_from_parts(&vec2[1], 3, 0.1 * (1 << 16)) // error: would truncate

Alternatively, it's just a struct so you can set the backing value directly:

vec2 := Vec2Fixed {
  {65536 + 16384}, // 1.25
  {2.75 * (1 << 16)}, // 2.75, as above must be exact for the compiler to allow this
}