Vector2D helpers

In porting some vector use cases from shaders to PD my observations were it'd be good to have these vector helpers as standard, albeir they're simple enough:

  • a function for componentwise min or max i.e. (min(v1.x,v2.x),min(v1.y,v2.y))
  • a function for Hadamard product (componentwise multiplication) i.e. (v1.x * v2.x, v1.y * v2.y)
  • scalar * vector2D not just vector2D * scalar
  • clamping of vector2D components i.e. (clamp(v.x),clamp(v.y))
  • support for 3,4,N dim vectors
1 Like

I'm not sure the componentwise functions are generally useful enough to devote firmware space to them, but they're easy enough to implement yourself:

local vect = playdate.geometry.vector2D

function vect.apply1(a,f)

function vect.apply2(a,b,f)

function vect.min(a,b) return vect.apply2(a,b,math.min) end
function vect.max(a,b) return vect.apply2(a,b,math.max) end
function vect.hadamard(a,b) return vect.apply2(a,b,function(x,y) return x*y end) end

local function clamp(x) return x<0 and 0 or x>1 and 1 or x end
function vect.clamp(a) return vect.apply1(a,clamp) end

And I'm pretty sure Lua can't handle scalar * vector2D Nope, I'm wrong! It looks like if the left operand doesn't have a metatable and the right one does, it'll use the right side's __mul function. I'll file that, will definitely be handy. Thanks!

As for vectors with dimension > 2.. I'd thought about it, but decided it's not a common enough need to warrant including in the main firmware. It'd be pretty straightforward to implement it via the C API, though. The Array example in the C API/Examples folder in the SDK would give you a solid head start there.