Skip to content

Instantly share code, notes, and snippets.

@nkint
Created January 31, 2020 18:16
Show Gist options
  • Save nkint/3564dcf246b09c2dfbe4e9d8af9a4713 to your computer and use it in GitHub Desktop.
Save nkint/3564dcf246b09c2dfbe4e9d8af9a4713 to your computer and use it in GitHub Desktop.
Umbrella, wireframe lines from Vec[]
import {
comp,
juxtR,
map,
mapcat,
partition,
reducer,
transduce,
wrapSides,
} from '@thi.ng/transducers'
import { Vec } from '@thi.ng/vectors'
import { ModelSpec } from '@thi.ng/webgl'
/**
* Reducer to collect unique points by ID.
* Expects tuples of `[id, point]`
*/
const uniquePoints = () => {
let ids = new Set()
return reducer<number[], [number, Vec]>(
() => [],
(acc, x) => (ids.has(x[0]) ? acc : (ids.add(x[0]), acc.push(...x[1]), acc)),
)
}
/**
* Reducer to collect point IDs
* Expects tuples of `[id, point]`
*/
const pushID = () =>
reducer<number[], [number, Vec]>(
() => [],
(acc, x) => (acc.push(x[0]), acc),
)
/**
* Converts iterable of polygons (each a Vec[]) to a
* single combined ModelSpec.
*
* @param polys
* @param size - dimensionality
*/
const wireframePolys = (polys: Iterable<Vec[]>, size = 3): Partial<ModelSpec> => {
let i = 0
const [points, indices] = transduce(
comp(
mapcat(poly =>
partition(
2,
1,
wrapSides(
map(p => [i++, p], poly),
0,
1,
),
),
),
mapcat(x => <[number, Vec][]>x),
),
// juxtaposed reducer
juxtR(uniquePoints(), pushID()),
polys,
)
return {
attribs: {
position: { data: new Float32Array(points), size },
},
indices: {
data: new Uint16Array(indices),
},
uniforms: {},
num: indices.length,
mode: 1, // gl.LINES
}
}
const polys = [
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
],
[
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
],
[
[0, 0, 2],
[1, 0, 2],
[1, 2, 2],
],
]
console.log(wireframePolys(polys))
// {
// attribs: {
// position: {
// data: Float32Array [
// 0, 0, 0, 1, 0, 0, 1, 1, 0,
// 0, 0, 1, 1, 0, 1, 1, 1, 1,
// 0, 1, 1, 0, 0, 2, 1, 0, 2,
// 1, 2, 2
// ],
// size: 3
// }
// },
// indices: {
// data: Uint16Array [
// 0, 1, 1, 2, 2, 0, 3,
// 4, 4, 5, 5, 6, 6, 3,
// 7, 8, 8, 9, 9, 7
// ]
// },
// uniforms: {},
// num: 20,
// mode: 1
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment