Skip to content

Instantly share code, notes, and snippets.

@kim366
Last active January 23, 2022 13:11
Show Gist options
  • Save kim366/907130aa8fce88b3abfaca4857d83f7c to your computer and use it in GitHub Desktop.
Save kim366/907130aa8fce88b3abfaca4857d83f7c to your computer and use it in GitHub Desktop.
GLSL vector Swizzling in Julia
macro swizzle(vec, components)
function index(component)
(component == 'x' || component == 'r') && return 1
(component == 'y' || component == 'g') && return 2
(component == 'z' || component == 'b') && return 3
(component == 'w' || component == 'a') && return 4
error("swizzling components must be one of x, y, z, w")
end
accesses = [Expr(:ref, :vec, index(component)) for component in string(components)]
quote
let vec = $(esc(vec)), type = $Base.eltype(vec)
$(Expr(:ref, :type, accesses...))
end
end
end
myvec = [1, 2, 3, 4]
println(@swizzle myvec xyxzr) # [1, 2, 1, 3, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment