Skip to content

Instantly share code, notes, and snippets.

@nkint
Created December 12, 2016 11:29
Show Gist options
  • Save nkint/1e87eb56b5093c6fde2446a905731679 to your computer and use it in GitHub Desktop.
Save nkint/1e87eb56b5093c6fde2446a905731679 to your computer and use it in GitHub Desktop.
Rotate mesh points towards a direction vector with stack-gl / regl
// inspired by toxiclibs
// https://bitbucket.org/postspectacular/toxiclibs/src/44d9932dbc9f9c69a170643e2d459f449562b750/src.core/toxi/geom/mesh/TriangleMesh.java?at=default&fileviewer=file-view-default#TriangleMesh.java-703
const vec3 = require('gl-vec3')
const mat3 = require('gl-mat3')
const mat4 = require('gl-mat4')
const quat = require('gl-quat')
function transform(matrix, v) {
const temp = mat3.create()
const width = 4
for (let i = 0; i < width; i++) {
const matrixGet = (x, y) => matrix[ y + (x * width) ]
temp[i] = v[0] * matrixGet(i, 0) + v[1] * matrixGet(i, 1) + v[2] * matrixGet(i, 2) + matrixGet(i, 3)
}
const out = [ temp[0], temp[1], temp[2] ]
.map(x => x * (1.0 / temp[3]))
return out
}
const Z_AXIS = [0, 0, 1]
function pointTowards(positions, dir, forward) {
forward = forward || Z_AXIS
dir = vec3.normalize([], dir)
forward = vec3.normalize([], forward)
const ret = positions.map(point => {
const q = quat.rotationTo(quat.create(), dir, forward)
const matFromQuat = mat4.fromQuat(mat4.create(), q)
const out = transform(matFromQuat, point)
return out
})
return ret
}
module.exports = pointTowards
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment