Skip to content

Commit

Permalink
utils: document horrible value bug discovered in remap[T]/5
Browse files Browse the repository at this point in the history
  • Loading branch information
larpon committed Dec 12, 2024
1 parent 7ce3bbb commit 68eb75f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
4 changes: 3 additions & 1 deletion lib/color.v
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,9 @@ pub fn (c &ColorHSV) as_rgb() Color {
else {}
}

// println('RGB: ${r} ${g} ${b} RGB*255: ${r * 255} ${g * 255} ${b * 255} ')
// println(utils.remap(f32(c.h), 0, 360, 0, 1))
// println('HSV: ${h} ${s} ${v} I ${i} FPQT: ${f} ${p} ${q} ${t}')
// println('RGBA: ${r} ${g} ${b} ${a} RGB*255(A): ${r * 255} ${g * 255} ${b * 255} (${a})')

return Color{
r: u8(r * 255)
Expand Down
23 changes: 18 additions & 5 deletions utils/utils.v
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,40 @@ pub const stdout_is_a_pipe = (os.is_atty(1) == 0)

@[inline]
pub fn remap[T](value T, min T, max T, new_min T, new_max T) T {
return (((value - min) * (new_max - new_min)) / (max - min)) + new_min
// BUG: This is carefully crafted like this because 2 hours of debugging led to this obscure corner case
// I think it is a "regression" (maybe not) with V's generics (cgen?, cast?, parenthesis?)
// `return (((value - min) * (new_max - new_min)) / (max - min)) + new_min` <- this version, incl. return T(...)
// consistently returned "0.0" until the temp var `r` was used... and I could NOT reduce the scenario.
// It was discovered while rewriting a function to procedurally generate shade colors (HSV -> RGB) for some bushes...
// The nasty thought is that something using T *elsewhere* can someday do the same in some unrelated context... nightmare
r := T((((value - min) * (new_max - new_min)) / (max - min)) + new_min)
return r
// return (((value - min) * (new_max - new_min)) / (max - min)) + new_min
// The above yields red bushes in small_world with just `v run`...
}

@[inline]
pub fn remap_u8_to_f32(value u8, min u8, max u8, new_min f32, new_max f32) f32 {
return f32((((value - min) * (new_max - new_min)) / (max - min)) + new_min)
r := f32((((value - min) * (new_max - new_min)) / (max - min)) + new_min)
return r
}

@[inline]
pub fn remap_f32_to_u8(value f32, min f32, max f32, new_min u8, new_max u8) u8 {
return u8((((value - min) * (new_max - new_min)) / (max - min)) + new_min)
r := u8((((value - min) * (new_max - new_min)) / (max - min)) + new_min)
return r
}

@[inline]
pub fn lerp[T](x T, y T, s T) T {
return x + s * (y - x)
r := T(x + s * (y - x))
return r
}

@[inline]
pub fn clamp[T](val T, min T, max T) T {
return mth.min(mth.max(val, min), max)
r := T(mth.min(mth.max(val, min), max))
return r
}

// loop_f32 loops a continious `value` in the range `from`,`to`.
Expand Down

0 comments on commit 68eb75f

Please sign in to comment.