-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathGeometryHelper.js
More file actions
545 lines (478 loc) · 16.1 KB
/
GeometryHelper.js
File metadata and controls
545 lines (478 loc) · 16.1 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var Vec3 = require('../math/Vec3');
var Vec2 = require('../math/Vec2');
var outputs = [
new Vec3(),
new Vec3(),
new Vec3(),
new Vec2(),
new Vec2()
];
/**
* A helper object used to calculate buffers for complicated geometries.
* Tailored for the WebGLRenderer, used by most primitives.
*
* @static
* @class GeometryHelper
* @return {undefined} undefined
*/
var GeometryHelper = {};
/**
* A function that iterates through vertical and horizontal slices
* based on input detail, and generates vertices and indices for each
* subdivision.
*
* @static
* @method
*
* @param {Number} detailX Amount of slices to iterate through.
* @param {Number} detailY Amount of stacks to iterate through.
* @param {Function} func Function used to generate vertex positions at each point.
* @param {Boolean} wrap Optional parameter (default: Pi) for setting a custom wrap range
*
* @return {Object} Object containing generated vertices and indices.
*/
GeometryHelper.generateParametric = function generateParametric(detailX, detailY, func, wrap) {
var vertices = [];
var i;
var theta;
var phi;
var j;
// We can wrap around slightly more than once for uv coordinates to look correct.
var offset = (Math.PI / (detailX - 1));
var Xrange = wrap ? Math.PI + offset : Math.PI;
var out = [];
for (i = 0; i < detailX + 1; i++) {
theta = (i === 0 ? 0.0001 : i) * Math.PI / detailX;
for (j = 0; j < detailY; j++) {
phi = j * 2.0 * Xrange / detailY;
func(theta, phi, out);
vertices.push(out[0], out[1], out[2]);
}
}
var indices = [],
v = 0,
next;
for (i = 0; i < detailX; i++) {
for (j = 0; j < detailY; j++) {
next = (j + 1) % detailY;
indices.push(v + j, v + j + detailY, v + next);
indices.push(v + next, v + j + detailY, v + next + detailY);
}
v += detailY;
}
return {
vertices: vertices,
indices: indices
};
};
/**
* Calculates normals belonging to each face of a geometry.
* Assumes clockwise declaration of vertices.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry.
* @param {Array} indices Indices declaring faces of geometry.
* @param {Array} out Array to be filled and returned.
*
* @return {Array} Calculated face normals.
*/
GeometryHelper.computeNormals = function computeNormals(vertices, indices, out) {
var normals = out || [];
var indexOne;
var indexTwo;
var indexThree;
var normal;
var j;
var len = indices.length / 3;
var i;
var x;
var y;
var z;
var length;
for (i = 0; i < len; i++) {
indexTwo = indices[i*3 + 0] * 3;
indexOne = indices[i*3 + 1] * 3;
indexThree = indices[i*3 + 2] * 3;
outputs[0].set(vertices[indexOne], vertices[indexOne + 1], vertices[indexOne + 2]);
outputs[1].set(vertices[indexTwo], vertices[indexTwo + 1], vertices[indexTwo + 2]);
outputs[2].set(vertices[indexThree], vertices[indexThree + 1], vertices[indexThree + 2]);
normal = outputs[2].subtract(outputs[0]).cross(outputs[1].subtract(outputs[0])).normalize();
normals[indexOne + 0] = (normals[indexOne + 0] || 0) + normal.x;
normals[indexOne + 1] = (normals[indexOne + 1] || 0) + normal.y;
normals[indexOne + 2] = (normals[indexOne + 2] || 0) + normal.z;
normals[indexTwo + 0] = (normals[indexTwo + 0] || 0) + normal.x;
normals[indexTwo + 1] = (normals[indexTwo + 1] || 0) + normal.y;
normals[indexTwo + 2] = (normals[indexTwo + 2] || 0) + normal.z;
normals[indexThree + 0] = (normals[indexThree + 0] || 0) + normal.x;
normals[indexThree + 1] = (normals[indexThree + 1] || 0) + normal.y;
normals[indexThree + 2] = (normals[indexThree + 2] || 0) + normal.z;
}
for (i = 0; i < normals.length; i += 3) {
x = normals[i];
y = normals[i+1];
z = normals[i+2];
length = Math.sqrt(x * x + y * y + z * z);
for(j = 0; j< 3; j++) {
normals[i+j] /= length;
}
}
return normals;
};
/**
* Divides all inserted triangles into four sub-triangles. Alters the
* passed in arrays.
*
* @static
* @method
*
* @param {Array} indices Indices declaring faces of geometry
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} textureCoords Texture coordinates of all points on the geometry
* @return {undefined} undefined
*/
GeometryHelper.subdivide = function subdivide(indices, vertices, textureCoords) {
var triangleIndex = indices.length / 3;
var face;
var i;
var j;
var k;
var pos;
var tex;
while (triangleIndex--) {
face = indices.slice(triangleIndex * 3, triangleIndex * 3 + 3);
pos = face.map(function(vertIndex) {
return new Vec3(vertices[vertIndex * 3], vertices[vertIndex * 3 + 1], vertices[vertIndex * 3 + 2]);
});
vertices.push.apply(vertices, Vec3.scale(Vec3.add(pos[0], pos[1], outputs[0]), 0.5, outputs[1]).toArray());
vertices.push.apply(vertices, Vec3.scale(Vec3.add(pos[1], pos[2], outputs[0]), 0.5, outputs[1]).toArray());
vertices.push.apply(vertices, Vec3.scale(Vec3.add(pos[0], pos[2], outputs[0]), 0.5, outputs[1]).toArray());
if (textureCoords) {
tex = face.map(function(vertIndex) {
return new Vec2(textureCoords[vertIndex * 2], textureCoords[vertIndex * 2 + 1]);
});
textureCoords.push.apply(textureCoords, Vec2.scale(Vec2.add(tex[0], tex[1], outputs[3]), 0.5, outputs[4]).toArray());
textureCoords.push.apply(textureCoords, Vec2.scale(Vec2.add(tex[1], tex[2], outputs[3]), 0.5, outputs[4]).toArray());
textureCoords.push.apply(textureCoords, Vec2.scale(Vec2.add(tex[0], tex[2], outputs[3]), 0.5, outputs[4]).toArray());
}
i = vertices.length - 3;
j = i + 1;
k = i + 2;
indices.push(i, j, k);
indices.push(face[0], i, k);
indices.push(i, face[1], j);
indices[triangleIndex] = k;
indices[triangleIndex + 1] = j;
indices[triangleIndex + 2] = face[2];
}
};
/**
* Creates duplicate of vertices that are shared between faces.
* Alters the input vertex and index arrays.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} indices Indices declaring faces of geometry
* @return {undefined} undefined
*/
GeometryHelper.getUniqueFaces = function getUniqueFaces(vertices, indices) {
var triangleIndex = indices.length / 3,
registered = [],
index;
while (triangleIndex--) {
for (var i = 0; i < 3; i++) {
index = indices[triangleIndex * 3 + i];
if (registered[index]) {
vertices.push(vertices[index * 3], vertices[index * 3 + 1], vertices[index * 3 + 2]);
indices[triangleIndex * 3 + i] = vertices.length / 3 - 1;
}
else {
registered[index] = true;
}
}
}
};
/**
* Divides all inserted triangles into four sub-triangles while maintaining
* a radius of one. Alters the passed in arrays.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} indices Indices declaring faces of geometry
* @return {undefined} undefined
*/
GeometryHelper.subdivideSpheroid = function subdivideSpheroid(vertices, indices) {
var triangleIndex = indices.length / 3,
abc,
face,
i, j, k;
while (triangleIndex--) {
face = indices.slice(triangleIndex * 3, triangleIndex * 3 + 3);
abc = face.map(function(vertIndex) {
return new Vec3(vertices[vertIndex * 3], vertices[vertIndex * 3 + 1], vertices[vertIndex * 3 + 2]);
});
vertices.push.apply(vertices, Vec3.normalize(Vec3.add(abc[0], abc[1], outputs[0]), outputs[1]).toArray());
vertices.push.apply(vertices, Vec3.normalize(Vec3.add(abc[1], abc[2], outputs[0]), outputs[1]).toArray());
vertices.push.apply(vertices, Vec3.normalize(Vec3.add(abc[0], abc[2], outputs[0]), outputs[1]).toArray());
i = vertices.length / 3 - 3;
j = i + 1;
k = i + 2;
indices.push(i, j, k);
indices.push(face[0], i, k);
indices.push(i, face[1], j);
indices[triangleIndex * 3] = k;
indices[triangleIndex * 3 + 1] = j;
indices[triangleIndex * 3 + 2] = face[2];
}
};
/**
* Divides all inserted triangles into four sub-triangles while maintaining
* a radius of one. Alters the passed in arrays.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} out Optional array to be filled with resulting normals.
*
* @return {Array} New list of calculated normals.
*/
GeometryHelper.getSpheroidNormals = function getSpheroidNormals(vertices, out) {
out = out || [];
var length = vertices.length / 3;
var normalized;
for (var i = 0; i < length; i++) {
normalized = new Vec3(
vertices[i * 3 + 0],
vertices[i * 3 + 1],
vertices[i * 3 + 2]
).normalize().toArray();
out[i * 3 + 0] = normalized[0];
out[i * 3 + 1] = normalized[1];
out[i * 3 + 2] = normalized[2];
}
return out;
};
/**
* Calculates texture coordinates for spheroid primitives based on
* input vertices.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} out Optional array to be filled with resulting texture coordinates.
*
* @return {Array} New list of calculated texture coordinates
*/
GeometryHelper.getSpheroidUV = function getSpheroidUV(vertices, out) {
out = out || [];
var length = vertices.length / 3;
var vertex;
var uv = [];
for(var i = 0; i < length; i++) {
vertex = outputs[0].set(
vertices[i * 3],
vertices[i * 3 + 1],
vertices[i * 3 + 2]
)
.normalize()
.toArray();
var azimuth = this.getAzimuth(vertex);
var altitude = this.getAltitude(vertex);
uv[0] = azimuth * 0.5 / Math.PI + 0.5;
uv[1] = altitude / Math.PI + 0.5;
out.push.apply(out, uv);
}
return out;
};
/**
* Iterates through and normalizes a list of vertices.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} out Optional array to be filled with resulting normalized vectors.
*
* @return {Array} New list of normalized vertices
*/
GeometryHelper.normalizeAll = function normalizeAll(vertices, out) {
out = out || [];
var len = vertices.length / 3;
for (var i = 0; i < len; i++) {
Array.prototype.push.apply(out, new Vec3(vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]).normalize().toArray());
}
return out;
};
/**
* Normalizes a set of vertices to model space.
*
* @static
* @method
*
* @param {Array} vertices Vertices of all points on the geometry
* @param {Array} out Optional array to be filled with model space position vectors.
*
* @return {Array} Output vertices.
*/
GeometryHelper.normalizeVertices = function normalizeVertices(vertices, out) {
out = out || [];
var len = vertices.length / 3;
var vectors = [];
var minX;
var maxX;
var minY;
var maxY;
var minZ;
var maxZ;
var v;
var i;
for (i = 0; i < len; i++) {
v = vectors[i] = new Vec3(
vertices[i * 3],
vertices[i * 3 + 1],
vertices[i * 3 + 2]
);
if (minX == null || v.x < minX) minX = v.x;
if (maxX == null || v.x > maxX) maxX = v.x;
if (minY == null || v.y < minY) minY = v.y;
if (maxY == null || v.y > maxY) maxY = v.y;
if (minZ == null || v.z < minZ) minZ = v.z;
if (maxZ == null || v.z > maxZ) maxZ = v.z;
}
var translation = new Vec3(
getTranslationFactor(maxX, minX),
getTranslationFactor(maxY, minY),
getTranslationFactor(maxZ, minZ)
);
var scale = Math.min(
getScaleFactor(maxX + translation.x, minX + translation.x),
getScaleFactor(maxY + translation.y, minY + translation.y),
getScaleFactor(maxZ + translation.z, minZ + translation.z)
);
for (i = 0; i < vectors.length; i++) {
out.push.apply(out, vectors[i].add(translation).scale(scale).toArray());
}
return out;
};
/**
* Determines translation amount for a given axis to normalize model coordinates.
*
* @method
* @private
*
* @param {Number} max Maximum position value of given axis on the model.
* @param {Number} min Minimum position value of given axis on the model.
*
* @return {Number} Number by which the given axis should be translated for all vertices.
*/
function getTranslationFactor(max, min) {
return -(min + (max - min) / 2);
}
/**
* Determines scale amount for a given axis to normalize model coordinates.
*
* @method
* @private
*
* @param {Number} max Maximum scale value of given axis on the model.
* @param {Number} min Minimum scale value of given axis on the model.
*
* @return {Number} Number by which the given axis should be scaled for all vertices.
*/
function getScaleFactor(max, min) {
return 1 / ((max - min) / 2);
}
/**
* Finds the azimuth, or angle above the XY plane, of a given vector.
*
* @static
* @method
*
* @param {Array} v Vertex to retreive azimuth from.
*
* @return {Number} Azimuth value in radians.
*/
GeometryHelper.getAzimuth = function azimuth(v) {
return Math.atan2(v[2], -v[0]);
};
/**
* Finds the altitude, or angle above the XZ plane, of a given vector.
*
* @static
* @method
*
* @param {Array} v Vertex to retreive altitude from.
*
* @return {Number} Altitude value in radians.
*/
GeometryHelper.getAltitude = function altitude(v) {
return Math.atan2(-v[1], Math.sqrt((v[0] * v[0]) + (v[2] * v[2])));
};
/**
* Converts a list of indices from 'triangle' to 'line' format.
*
* @static
* @method
*
* @param {Array} indices Indices of all faces on the geometry
* @param {Array} out Indices of all faces on the geometry
*
* @return {Array} New list of line-formatted indices
*/
GeometryHelper.trianglesToLines = function triangleToLines(indices, out) {
var numVectors = indices.length / 3;
out = out || [];
var i;
for (i = 0; i < numVectors; i++) {
out.push(indices[i * 3 + 0], indices[i * 3 + 1]);
out.push(indices[i * 3 + 1], indices[i * 3 + 2]);
out.push(indices[i * 3 + 2], indices[i * 3 + 0]);
}
return out;
};
/**
* Adds a reverse order triangle for every triangle in the mesh. Adds extra
* indices to input array.
*
* @static
* @method
*
* @param {Array} indices Indices of all faces on the geometry
* @return {undefined} undefined
*/
GeometryHelper.addBackfaceTriangles = function addBackfaceTriangles(indices) {
for (var face = 0, len = indices.length; face < len; face += 3)
indices.push(indices[face], indices[face + 2], indices[face + 1]);
};
module.exports = GeometryHelper;