-
Notifications
You must be signed in to change notification settings - Fork 4
/
polygon.js
352 lines (296 loc) · 9.83 KB
/
polygon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// @ts-check
import {
BufferAttribute,
BufferGeometry,
DoubleSide,
Group,
Mesh,
Quaternion,
RawShaderMaterial,
Vector3
} from '../../vendors/three.js';
import earcut from '../../vendors/earcut.js';
import {
copyArray3IntoBuffer,
getPopulatedCoordinateBuffer
} from '../bufferUtils.js';
import { scaleCoordinate } from '../coordinateUtils.js';
/** @typedef {import('../coordinateUtils.js').Coordinate} Coordinate */
/**
* Get the unit normal vector from the 1st, 2nd and last coordinate
* (these numbers were chosen because the vectors 1st->2nd and
* last->2nd have different directions, what is necessary for some
* calculations)
* Note: a "better" way to do this is compute an approximation plane
* by taking linear least squares, but that would be way slower and
* there would be only difference for very specific polygons.
* (see https://en.wikipedia.org/wiki/Linear_least_squares)
* @param {Array<[Coordinate, null] | [null, Coordinate]>} coordinates
* @param {import('../extent.js').Extent} extent
*/
function getNormalVector(coordinates, extent) {
const vectorA = new Vector3(
...coordinates[0][0] ?? scaleCoordinate(coordinates[0][1], extent)
);
const vectorB = new Vector3(
...coordinates[1][0] ?? scaleCoordinate(coordinates[1][1], extent)
);
const vectorC = new Vector3(
...coordinates[coordinates.length - 1][0] ?? scaleCoordinate(
/** @type {Coordinate} */(coordinates[coordinates.length - 1][1]),
extent
)
);
// cross product of 2 vectors with different directions in the plane
// (A - B) x (C - B)
return vectorA.sub(vectorB).cross(vectorC.sub(vectorB)).normalize();
}
/**
* Test if the coordinates are coplanar by checking if the distance
* of each coordinate to the plane is less than a threshold.
* We don't need to do `coordinate -= distance to the plane`
* because earcut returns the same indices for small differences.
* (the indices of different objects are the same if they have the same shape)
* @param {Array<[Coordinate, null] | [null, Coordinate]>} coordinates
* @param {import('../extent.js').Extent} extent
* @returns {boolean} whether the coordinates are coplanar.
*/
function isCoplanar(coordinates, extent) {
// normal = ⟨A, B, C⟩
const normalVector = getNormalVector(coordinates, extent);
// P = ⟨a, b, c⟩
const pointP = new Vector3(
...coordinates[0][0] ?? scaleCoordinate(coordinates[0][1], extent)
);
// D = unit normal vector ⋅ P
const D = normalVector.dot(pointP);
const threshold = 1e-2;
for (let i = 0; i < coordinates.length; i++) {
const [x, y, z] = coordinates[i][0] ?? scaleCoordinate(
/** @type {Coordinate} */(coordinates[i][1]),
extent
);
// Given a point ⟨x, y, z⟩, the distance between the point
// and the plane is: A x + B y + C z - D
// We take the absolute value because the point can be under or
// over the plane.
if (Math.abs(normalVector.x * x + normalVector.y * y + normalVector.z * z - D) > threshold) {
return false;
}
}
return true;
}
/**
* See {@link PrimitiveFunction} for more information about the
* shape of a primitive function.
* See {@link https://mathics3.github.io/mathics-threejs-backend/primitives/polygon}
* for the high-level description of what is being rendered.
* @type {import('./index.js').PrimitiveFunction}
*/
export default function ({ color = [1, 1, 1], coords, edgeForm = {}, opacity = 1, vertexNormals = [] }, uniforms, extent) {
let geometry;
if (coords.length === 3) { // triangle
geometry = new BufferGeometry().setAttribute(
'position',
new BufferAttribute(new Float32Array([
...(coords[0][0] ?? scaleCoordinate(coords[0][1], extent)),
...(coords[1][0] ?? scaleCoordinate(coords[1][1], extent)),
...(coords[2][0] ?? scaleCoordinate(coords[2][1], extent))
]), 3)
);
} else { // not a triangle
if (isCoplanar(coords, extent)) {
// We use earcut to "break" the polygon into multiple triangles.
// We can't draw if we don't do it.
// The problem is that earcut doesn't deals well with
// coplanar polygons.
// The good news is that it has a 2d mode.
const quaternion = new Quaternion().setFromUnitVectors(
getNormalVector(coords, extent),
new Vector3(0, 0, 1)
);
const coordinates2d = new Float32Array(coords.length * 2);
coords.forEach((coordinate, index) => {
// apply the quaternion "zero" all z values, we can't draw a shape with non-zero z values
const vector = new Vector3(
...(coordinate[0] ?? scaleCoordinate(coordinate[1], extent))
).applyQuaternion(quaternion);
coordinates2d[index * 2] = vector.x;
coordinates2d[index * 2 + 1] = vector.y;
});
geometry = new BufferGeometry()
.setAttribute(
'position',
new BufferAttribute(
getPopulatedCoordinateBuffer(coords, extent),
3
)
)
.setIndex(earcut(coordinates2d, 2));
} else {
// We use earcut to "break" the polygon into multiple triangles. We can't draw if we don't do it.
const coordinates = getPopulatedCoordinateBuffer(coords, extent);
geometry = new BufferGeometry()
.setAttribute(
'position',
new BufferAttribute(
coordinates,
3
)
)
.setIndex(earcut(coordinates));
}
}
// Contains elements from vertexNormals and NaNs for the other
// elements if normals.length > vertexNormals.length
// When the value is NaN, it is going to be re-calculated
// in the vertex shader (we can't do it here because each pixel
// may have a different normal value).
// @ts-expect-error: we already set the position attribute, so we are
// sure it is there.
const normals = new Float32Array(geometry.attributes.position.count * 3);
for (let i = 0; i < normals.length / 3; i++) {
copyArray3IntoBuffer(
normals,
vertexNormals[i] ?? [NaN, NaN, NaN],
i
);
}
geometry.setAttribute('normal', new BufferAttribute(normals, 3));
const polygon = new Mesh(
geometry,
// @ts-expect-error: bad three.js typing
new RawShaderMaterial({
side: DoubleSide,
depthWrite: opacity === 1,
transparent: opacity !== 1,
uniforms,
vertexShader: `#version 300 es
precision mediump float;
in vec3 normal;
in vec3 position;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
out vec3 vViewPosition;
out vec3 vNormal;
void main() {
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * mvPosition;
vViewPosition = -mvPosition.xyz;
vNormal = normal;
}
`,
fragmentShader: `#version 300 es
precision mediump float;
in vec3 vViewPosition;
in vec3 vNormal;
uniform vec3 ambientLightColor;
uniform vec3 diffuse;
uniform float opacity;
out vec4 pc_fragColor;
#define saturate(a) clamp(a, 0.0, 1.0)
${uniforms.directionalLights.value.length > 0 ? `
struct IncidentLight {
vec3 color;
vec3 direction;
};
uniform IncidentLight directionalLights[${uniforms.directionalLights.value.length}];
` : ''}
${uniforms.pointLights.value.length > 0 ? `
struct PointLight {
vec3 color;
vec3 position;
};
uniform PointLight pointLights[${uniforms.pointLights.value.length}];
` : ''}
${uniforms.spotLights.value.length > 0 ? `
struct SpotLight {
vec3 color;
float coneCos;
vec3 direction;
vec3 position;
};
uniform SpotLight spotLights[${uniforms.spotLights.value.length}];
` : ''}
void main() {
// If x is NaN, then y and z are also NaN.
vec3 normal = isnan(vNormal.x) ? normalize(cross(dFdx(vViewPosition), dFdy(vViewPosition))) : vNormal;
vec3 reflectedLight = ambientLightColor;
${uniforms.directionalLights.value.length > 0 ? `
for (int i = 0; i < ${uniforms.directionalLights.value.length}; i++) {
reflectedLight += saturate(dot(normal, directionalLights[i].direction)) * directionalLights[i].color;
}
` : ''}
${uniforms.pointLights.value.length > 0 ? `
for (int i = 0; i < ${uniforms.pointLights.value.length}; i++) {
reflectedLight += saturate(dot(
normal,
normalize(pointLights[i].position + vViewPosition))
) * pointLights[i].color;
}
` : ''}
${uniforms.spotLights.value.length > 0 ? `
vec3 direction;
for (int i = 0; i < ${uniforms.spotLights.value.length}; i++) {
direction = normalize(spotLight.position + vViewPosition);
reflectedLight += saturate(dot(normal, direction))
* spotLights[i].color
* max(
smoothstep(
spotLights[i].coneCos,
spotLights[i].coneCos,
dot(direction, spotLights[i].direction)
),
0.0
);
}
` : ''}
pc_fragColor = vec4(
reflectedLight * vec3(${color[0]}, ${color[1]}, ${color[2]}),
${opacity}
);
}
`
})
);
// Differently from cuboids and other primitives, the polygons
// DON'T have edges by default.
if (edgeForm.showEdges !== true) {
// If the edges aren't shown the work is done.
return polygon;
}
const group = new Group();
group.add(polygon);
edgeForm.color ??= [0, 0, 0];
// Differently from polyhedrons, polygons use a Mesh and a material
// with "wireframe: true". This is slower than LineSegments, but
// creating a new BufferGeometry is also slow and uses more RAM
// (LineSegments don't support indexed BufferGeometries).
group.add(new Mesh(
geometry,
// @ts-expect-error: bad three.js typing
new RawShaderMaterial({
wireframe: true,
vertexShader: `#version 300 es
in vec3 position;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1);
}
`,
fragmentShader: `#version 300 es
out lowp vec4 pc_fragColor;
void main() {
pc_fragColor = vec4(
${edgeForm.color[0]},
${edgeForm.color[1]},
${edgeForm.color[2]},
1
);
}
`
})
));
return group;
}