forked from processing/p5.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p5.Geometry.js
2329 lines (2249 loc) · 64.4 KB
/
p5.Geometry.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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Shape
* @submodule 3D Primitives
* @for p5
* @requires core
* @requires p5.Geometry
*/
//some of the functions are adjusted from Three.js(http://threejs.org)
import p5 from '../core/main';
import * as constants from '../core/constants';
/**
* A class to describe a 3D shape.
*
* Each `p5.Geometry` object represents a 3D shape as a set of connected
* points called *vertices*. All 3D shapes are made by connecting vertices to
* form triangles that are stitched together. Each triangular patch on the
* geometry's surface is called a *face*. The geometry stores information
* about its vertices and faces for use with effects such as lighting and
* texture mapping.
*
* The first parameter, `detailX`, is optional. If a number is passed, as in
* `new p5.Geometry(24)`, it sets the number of triangle subdivisions to use
* along the geometry's x-axis. By default, `detailX` is 1.
*
* The second parameter, `detailY`, is also optional. If a number is passed,
* as in `new p5.Geometry(24, 16)`, it sets the number of triangle
* subdivisions to use along the geometry's y-axis. By default, `detailX` is
* 1.
*
* The third parameter, `callback`, is also optional. If a function is passed,
* as in `new p5.Geometry(24, 16, createShape)`, it will be called once to add
* vertices to the new 3D shape.
*
* @class p5.Geometry
* @param {Integer} [detailX] number of vertices along the x-axis.
* @param {Integer} [detailY] number of vertices along the y-axis.
* @param {function} [callback] function to call once the geometry is created.
*
* @example
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let myGeometry;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Geometry object.
* myGeometry = new p5.Geometry();
*
* // Create p5.Vector objects to position the vertices.
* let v0 = createVector(-40, 0, 0);
* let v1 = createVector(0, -40, 0);
* let v2 = createVector(40, 0, 0);
*
* // Add the vertices to the p5.Geometry object's vertices array.
* myGeometry.vertices.push(v0, v1, v2);
*
* describe('A white triangle drawn on a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the p5.Geometry object.
* model(myGeometry);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let myGeometry;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Geometry object using a callback function.
* myGeometry = new p5.Geometry(1, 1, createShape);
*
* describe('A white triangle drawn on a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the p5.Geometry object.
* model(myGeometry);
* }
*
* function createShape() {
* // Create p5.Vector objects to position the vertices.
* let v0 = createVector(-40, 0, 0);
* let v1 = createVector(0, -40, 0);
* let v2 = createVector(40, 0, 0);
*
* // "this" refers to the p5.Geometry object being created.
*
* // Add the vertices to the p5.Geometry object's vertices array.
* this.vertices.push(v0, v1, v2);
*
* // Add an array to list which vertices belong to the face.
* // Vertices are listed in clockwise "winding" order from
* // left to top to right.
* this.faces.push([0, 1, 2]);
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let myGeometry;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a p5.Geometry object using a callback function.
* myGeometry = new p5.Geometry(1, 1, createShape);
*
* describe('A white triangle drawn on a gray background.');
* }
*
* function draw() {
* background(200);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Draw the p5.Geometry object.
* model(myGeometry);
* }
*
* function createShape() {
* // Create p5.Vector objects to position the vertices.
* let v0 = createVector(-40, 0, 0);
* let v1 = createVector(0, -40, 0);
* let v2 = createVector(40, 0, 0);
*
* // "this" refers to the p5.Geometry object being created.
*
* // Add the vertices to the p5.Geometry object's vertices array.
* this.vertices.push(v0, v1, v2);
*
* // Add an array to list which vertices belong to the face.
* // Vertices are listed in clockwise "winding" order from
* // left to top to right.
* this.faces.push([0, 1, 2]);
*
* // Compute the surface normals to help with lighting.
* this.computeNormals();
* }
* </code>
* </div>
*
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* // Adapted from Paul Wheeler's wonderful p5.Geometry tutorial.
* // https://www.paulwheeler.us/articles/custom-3d-geometry-in-p5js/
* // CC-BY-SA 4.0
*
* let myGeometry;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create the p5.Geometry object.
* // Set detailX to 48 and detailY to 2.
* // >>> try changing them.
* myGeometry = new p5.Geometry(48, 2, createShape);
* }
*
* function draw() {
* background(50);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Turn on the lights.
* lights();
*
* // Style the p5.Geometry object.
* strokeWeight(0.2);
*
* // Draw the p5.Geometry object.
* model(myGeometry);
* }
*
* function createShape() {
* // "this" refers to the p5.Geometry object being created.
*
* // Define the Möbius strip with a few parameters.
* let spread = 0.1;
* let radius = 30;
* let stripWidth = 15;
* let xInterval = 4 * PI / this.detailX;
* let yOffset = -stripWidth / 2;
* let yInterval = stripWidth / this.detailY;
*
* for (let j = 0; j <= this.detailY; j += 1) {
* // Calculate the "vertical" point along the strip.
* let v = yOffset + yInterval * j;
*
* for (let i = 0; i <= this.detailX; i += 1) {
* // Calculate the angle of rotation around the strip.
* let u = i * xInterval;
*
* // Calculate the coordinates of the vertex.
* let x = (radius + v * cos(u / 2)) * cos(u) - sin(u / 2) * 2 * spread;
* let y = (radius + v * cos(u / 2)) * sin(u);
* if (u < TWO_PI) {
* y += sin(u) * spread;
* } else {
* y -= sin(u) * spread;
* }
* let z = v * sin(u / 2) + sin(u / 4) * 4 * spread;
*
* // Create a p5.Vector object to position the vertex.
* let vert = createVector(x, y, z);
*
* // Add the vertex to the p5.Geometry object's vertices array.
* this.vertices.push(vert);
* }
* }
*
* // Compute the faces array.
* this.computeFaces();
*
* // Compute the surface normals to help with lighting.
* this.computeNormals();
* }
* </code>
* </div>
*/
p5.Geometry = class Geometry {
constructor(detailX, detailY, callback) {
this.vertices = [];
this.boundingBoxCache = null;
//an array containing every vertex for stroke drawing
this.lineVertices = new p5.DataArray();
// The tangents going into or out of a vertex on a line. Along a straight
// line segment, both should be equal. At an endpoint, one or the other
// will not exist and will be all 0. In joins between line segments, they
// may be different, as they will be the tangents on either side of the join.
this.lineTangentsIn = new p5.DataArray();
this.lineTangentsOut = new p5.DataArray();
// When drawing lines with thickness, entries in this buffer represent which
// side of the centerline the vertex will be placed. The sign of the number
// will represent the side of the centerline, and the absolute value will be
// used as an enum to determine which part of the cap or join each vertex
// represents. See the doc comments for _addCap and _addJoin for diagrams.
this.lineSides = new p5.DataArray();
this.vertexNormals = [];
this.faces = [];
this.uvs = [];
// a 2D array containing edge connectivity pattern for create line vertices
//based on faces for most objects;
this.edges = [];
this.vertexColors = [];
// One color per vertex representing the stroke color at that vertex
this.vertexStrokeColors = [];
// List of user attribute names to clear each beginShape call
this.userAttributes = [];
// One color per line vertex, generated automatically based on
// vertexStrokeColors in _edgesToVertices()
this.lineVertexColors = new p5.DataArray();
this.detailX = detailX !== undefined ? detailX : 1;
this.detailY = detailY !== undefined ? detailY : 1;
this.dirtyFlags = {};
this._hasFillTransparency = undefined;
this._hasStrokeTransparency = undefined;
if (callback instanceof Function) {
callback.call(this);
}
}
/**
* Calculates the position and size of the smallest box that contains the geometry.
*
* A bounding box is the smallest rectangular prism that contains the entire
* geometry. It's defined by the box's minimum and maximum coordinates along
* each axis, as well as the size (length) and offset (center).
*
* Calling `myGeometry.calculateBoundingBox()` returns an object with four
* properties that describe the bounding box:
*
* ```js
* // Get myGeometry's bounding box.
* let bbox = myGeometry.calculateBoundingBox();
*
* // Print the bounding box to the console.
* console.log(bbox);
*
* // {
* // // The minimum coordinate along each axis.
* // min: { x: -1, y: -2, z: -3 },
* //
* // // The maximum coordinate along each axis.
* // max: { x: 1, y: 2, z: 3},
* //
* // // The size (length) along each axis.
* // size: { x: 2, y: 4, z: 6},
* //
* // // The offset (center) along each axis.
* // offset: { x: 0, y: 0, z: 0}
* // }
* ```
*
* @returns {Object} bounding box of the geometry.
*
* @example
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let particles;
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* // Create a new p5.Geometry object with random spheres.
* particles = buildGeometry(createParticles);
*
* describe('Ten white spheres placed randomly against a gray background. A box encloses the spheres.');
* }
*
* function draw() {
* background(50);
*
* // Enable orbiting with the mouse.
* orbitControl();
*
* // Turn on the lights.
* lights();
*
* // Style the particles.
* noStroke();
* fill(255);
*
* // Draw the particles.
* model(particles);
*
* // Calculate the bounding box.
* let bbox = particles.calculateBoundingBox();
*
* // Translate to the bounding box's center.
* translate(bbox.offset.x, bbox.offset.y, bbox.offset.z);
*
* // Style the bounding box.
* stroke(255);
* noFill();
*
* // Draw the bounding box.
* box(bbox.size.x, bbox.size.y, bbox.size.z);
* }
*
* function createParticles() {
* for (let i = 0; i < 10; i += 1) {
* // Calculate random coordinates.
* let x = randomGaussian(0, 15);
* let y = randomGaussian(0, 15);
* let z = randomGaussian(0, 15);
*
* push();
* // Translate to the particle's coordinates.
* translate(x, y, z);
* // Draw the particle.
* sphere(3);
* pop();
* }
* }
* </code>
* </div>
*/
calculateBoundingBox() {
if (this.boundingBoxCache) {
return this.boundingBoxCache; // Return cached result if available
}
let minVertex = new p5.Vector(
Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
let maxVertex = new p5.Vector(
Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
for (let i = 0; i < this.vertices.length; i++) {
let vertex = this.vertices[i];
minVertex.x = Math.min(minVertex.x, vertex.x);
minVertex.y = Math.min(minVertex.y, vertex.y);
minVertex.z = Math.min(minVertex.z, vertex.z);
maxVertex.x = Math.max(maxVertex.x, vertex.x);
maxVertex.y = Math.max(maxVertex.y, vertex.y);
maxVertex.z = Math.max(maxVertex.z, vertex.z);
}
// Calculate size and offset properties
let size = new p5.Vector(maxVertex.x - minVertex.x,
maxVertex.y - minVertex.y, maxVertex.z - minVertex.z);
let offset = new p5.Vector((minVertex.x + maxVertex.x) / 2,
(minVertex.y + maxVertex.y) / 2, (minVertex.z + maxVertex.z) / 2);
// Cache the result for future access
this.boundingBoxCache = {
min: minVertex,
max: maxVertex,
size: size,
offset: offset
};
return this.boundingBoxCache;
}
reset() {
this._hasFillTransparency = undefined;
this._hasStrokeTransparency = undefined;
this.lineVertices.clear();
this.lineTangentsIn.clear();
this.lineTangentsOut.clear();
this.lineSides.clear();
this.vertices.length = 0;
this.edges.length = 0;
this.vertexColors.length = 0;
this.vertexStrokeColors.length = 0;
this.lineVertexColors.clear();
this.vertexNormals.length = 0;
this.uvs.length = 0;
for (const attr of this.userAttributes){
delete this[attr.name];
}
this.userAttributes.length = 0;
this.dirtyFlags = {};
}
hasFillTransparency() {
if (this._hasFillTransparency === undefined) {
this._hasFillTransparency = false;
for (let i = 0; i < this.vertexColors.length; i += 4) {
if (this.vertexColors[i + 3] < 1) {
this._hasFillTransparency = true;
break;
}
}
}
return this._hasFillTransparency;
}
hasStrokeTransparency() {
if (this._hasStrokeTransparency === undefined) {
this._hasStrokeTransparency = false;
for (let i = 0; i < this.lineVertexColors.length; i += 4) {
if (this.lineVertexColors[i + 3] < 1) {
this._hasStrokeTransparency = true;
break;
}
}
}
return this._hasStrokeTransparency;
}
/**
* Removes the geometry’s internal colors.
*
* `p5.Geometry` objects can be created with "internal colors" assigned to
* vertices or the entire shape. When a geometry has internal colors,
* <a href="#/p5/fill">fill()</a> has no effect. Calling
* `myGeometry.clearColors()` allows the
* <a href="#/p5/fill">fill()</a> function to apply color to the geometry.
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* background(200);
*
* // Create a p5.Geometry object.
* // Set its internal color to red.
* beginGeometry();
* fill(255, 0, 0);
* plane(20);
* let myGeometry = endGeometry();
*
* // Style the shape.
* noStroke();
*
* // Draw the p5.Geometry object (center).
* model(myGeometry);
*
* // Translate the origin to the bottom-right.
* translate(25, 25, 0);
*
* // Try to fill the geometry with green.
* fill(0, 255, 0);
*
* // Draw the geometry again (bottom-right).
* model(myGeometry);
*
* // Clear the geometry's colors.
* myGeometry.clearColors();
*
* // Fill the geometry with blue.
* fill(0, 0, 255);
*
* // Translate the origin up.
* translate(0, -50, 0);
*
* // Draw the geometry again (top-right).
* model(myGeometry);
*
* describe(
* 'Three squares drawn against a gray background. Red squares are at the center and the bottom-right. A blue square is at the top-right.'
* );
* }
* </code>
* </div>
*/
clearColors() {
this.vertexColors = [];
return this;
}
/**
* The `saveObj()` function exports `p5.Geometry` objects as
* 3D models in the Wavefront .obj file format.
* This way, you can use the 3D shapes you create in p5.js in other software
* for rendering, animation, 3D printing, or more.
*
* The exported .obj file will include the faces and vertices of the `p5.Geometry`,
* as well as its texture coordinates and normals, if it has them.
*
* @method saveObj
* @param {String} [fileName='model.obj'] The name of the file to save the model as.
* If not specified, the default file name will be 'model.obj'.
* @example
* <div>
* <code>
* let myModel;
* let saveBtn;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myModel = buildGeometry(() => {
* for (let i = 0; i < 5; i++) {
* push();
* translate(
* random(-75, 75),
* random(-75, 75),
* random(-75, 75)
* );
* sphere(random(5, 50));
* pop();
* }
* });
*
* saveBtn = createButton('Save .obj');
* saveBtn.mousePressed(() => myModel.saveObj());
*
* describe('A few spheres rotating in space');
* }
*
* function draw() {
* background(0);
* noStroke();
* lights();
* rotateX(millis() * 0.001);
* rotateY(millis() * 0.002);
* model(myModel);
* }
* </code>
* </div>
*/
saveObj(fileName = 'model.obj') {
let objStr= '';
// Vertices
this.vertices.forEach(v => {
objStr += `v ${v.x} ${v.y} ${v.z}\n`;
});
// Texture Coordinates (UVs)
if (this.uvs && this.uvs.length > 0) {
for (let i = 0; i < this.uvs.length; i += 2) {
objStr += `vt ${this.uvs[i]} ${this.uvs[i + 1]}\n`;
}
}
// Vertex Normals
if (this.vertexNormals && this.vertexNormals.length > 0) {
this.vertexNormals.forEach(n => {
objStr += `vn ${n.x} ${n.y} ${n.z}\n`;
});
}
// Faces, obj vertex indices begin with 1 and not 0
// texture coordinate (uvs) and vertexNormal indices
// are indicated with trailing ints vertex/normal/uv
// ex 1/1/1 or 2//2 for vertices without uvs
this.faces.forEach(face => {
let faceStr = 'f';
face.forEach(index =>{
faceStr += ' ';
faceStr += index + 1;
if (this.vertexNormals.length > 0 || this.uvs.length > 0) {
faceStr += '/';
if (this.uvs.length > 0) {
faceStr += index + 1;
}
faceStr += '/';
if (this.vertexNormals.length > 0) {
faceStr += index + 1;
}
}
});
objStr += faceStr + '\n';
});
const blob = new Blob([objStr], { type: 'text/plain' });
p5.prototype.downloadFile(blob, fileName , 'obj');
}
/**
* The `saveStl()` function exports `p5.Geometry` objects as
* 3D models in the STL stereolithography file format.
* This way, you can use the 3D shapes you create in p5.js in other software
* for rendering, animation, 3D printing, or more.
*
* The exported .stl file will include the faces, vertices, and normals of the `p5.Geometry`.
*
* By default, this method saves a text-based .stl file. Alternatively, you can save a more compact
* but less human-readable binary .stl file by passing `{ binary: true }` as a second parameter.
*
* @method saveStl
* @param {String} [fileName='model.stl'] The name of the file to save the model as.
* If not specified, the default file name will be 'model.stl'.
* @param {Object} [options] Optional settings. Options can include a boolean `binary` property, which
* controls whether or not a binary .stl file is saved. It defaults to false.
* @example
* <div>
* <code>
* let myModel;
* let saveBtn1;
* let saveBtn2;
* function setup() {
* createCanvas(200, 200, WEBGL);
* myModel = buildGeometry(() => {
* for (let i = 0; i < 5; i++) {
* push();
* translate(
* random(-75, 75),
* random(-75, 75),
* random(-75, 75)
* );
* sphere(random(5, 50));
* pop();
* }
* });
*
* saveBtn1 = createButton('Save .stl');
* saveBtn1.mousePressed(function() {
* myModel.saveStl();
* });
* saveBtn2 = createButton('Save binary .stl');
* saveBtn2.mousePressed(function() {
* myModel.saveStl('model.stl', { binary: true });
* });
*
* describe('A few spheres rotating in space');
* }
*
* function draw() {
* background(0);
* noStroke();
* lights();
* rotateX(millis() * 0.001);
* rotateY(millis() * 0.002);
* model(myModel);
* }
* </code>
* </div>
*/
saveStl(fileName = 'model.stl', { binary = false } = {}){
let modelOutput;
let name = fileName.substring(0, fileName.lastIndexOf('.'));
let faceNormals = [];
for (let f of this.faces) {
const U = p5.Vector.sub(this.vertices[f[1]], this.vertices[f[0]]);
const V = p5.Vector.sub(this.vertices[f[2]], this.vertices[f[0]]);
const nx = U.y * V.z - U.z * V.y;
const ny = U.z * V.x - U.x * V.z;
const nz = U.x * V.y - U.y * V.x;
faceNormals.push(new p5.Vector(nx, ny, nz).normalize());
}
if (binary) {
let offset = 80;
const bufferLength =
this.faces.length * 2 + this.faces.length * 3 * 4 * 4 + 80 + 4;
const arrayBuffer = new ArrayBuffer(bufferLength);
modelOutput = new DataView(arrayBuffer);
modelOutput.setUint32(offset, this.faces.length, true);
offset += 4;
for (const [key, f] of Object.entries(this.faces)) {
const norm = faceNormals[key];
modelOutput.setFloat32(offset, norm.x, true);
offset += 4;
modelOutput.setFloat32(offset, norm.y, true);
offset += 4;
modelOutput.setFloat32(offset, norm.z, true);
offset += 4;
for (let vertexIndex of f) {
const vert = this.vertices[vertexIndex];
modelOutput.setFloat32(offset, vert.x, true);
offset += 4;
modelOutput.setFloat32(offset, vert.y, true);
offset += 4;
modelOutput.setFloat32(offset, vert.z, true);
offset += 4;
}
modelOutput.setUint16(offset, 0, true);
offset += 2;
}
} else {
modelOutput = 'solid ' + name + '\n';
for (const [key, f] of Object.entries(this.faces)) {
const norm = faceNormals[key];
modelOutput +=
' facet norm ' + norm.x + ' ' + norm.y + ' ' + norm.z + '\n';
modelOutput += ' outer loop' + '\n';
for (let vertexIndex of f) {
const vert = this.vertices[vertexIndex];
modelOutput +=
' vertex ' + vert.x + ' ' + vert.y + ' ' + vert.z + '\n';
}
modelOutput += ' endloop' + '\n';
modelOutput += ' endfacet' + '\n';
}
modelOutput += 'endsolid ' + name + '\n';
}
const blob = new Blob([modelOutput], { type: 'text/plain' });
p5.prototype.downloadFile(blob, fileName, 'stl');
}
/**
* Flips the geometry’s texture u-coordinates.
*
* In order for <a href="#/p5/texture">texture()</a> to work, the geometry
* needs a way to map the points on its surface to the pixels in a rectangular
* image that's used as a texture. The geometry's vertex at coordinates
* `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`.
*
* The <a href="#/p5.Geometry/uvs">myGeometry.uvs</a> array stores the
* `(u, v)` coordinates for each vertex in the order it was added to the
* geometry. Calling `myGeometry.flipU()` flips a geometry's u-coordinates
* so that the texture appears mirrored horizontally.
*
* For example, a plane's four vertices are added clockwise starting from the
* top-left corner. Here's how calling `myGeometry.flipU()` would change a
* plane's texture coordinates:
*
* ```js
* // Print the original texture coordinates.
* // Output: [0, 0, 1, 0, 0, 1, 1, 1]
* console.log(myGeometry.uvs);
*
* // Flip the u-coordinates.
* myGeometry.flipU();
*
* // Print the flipped texture coordinates.
* // Output: [1, 0, 0, 0, 1, 1, 0, 1]
* console.log(myGeometry.uvs);
*
* // Notice the swaps:
* // Top vertices: [0, 0, 1, 0] --> [1, 0, 0, 0]
* // Bottom vertices: [0, 1, 1, 1] --> [1, 1, 0, 1]
* ```
*
* @for p5.Geometry
*
* @example
* <div>
* <code>
* let img;
*
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* background(200);
*
* // Create p5.Geometry objects.
* let geom1 = buildGeometry(createShape);
* let geom2 = buildGeometry(createShape);
*
* // Flip geom2's U texture coordinates.
* geom2.flipU();
*
* // Left (original).
* push();
* translate(-25, 0, 0);
* texture(img);
* noStroke();
* model(geom1);
* pop();
*
* // Right (flipped).
* push();
* translate(25, 0, 0);
* texture(img);
* noStroke();
* model(geom2);
* pop();
*
* describe(
* 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.'
* );
* }
*
* function createShape() {
* plane(40);
* }
* </code>
* </div>
*/
flipU() {
this.uvs = this.uvs.flat().map((val, index) => {
if (index % 2 === 0) {
return 1 - val;
} else {
return val;
}
});
}
/**
* Flips the geometry’s texture v-coordinates.
*
* In order for <a href="#/p5/texture">texture()</a> to work, the geometry
* needs a way to map the points on its surface to the pixels in a rectangular
* image that's used as a texture. The geometry's vertex at coordinates
* `(x, y, z)` maps to the texture image's pixel at coordinates `(u, v)`.
*
* The <a href="#/p5.Geometry/uvs">myGeometry.uvs</a> array stores the
* `(u, v)` coordinates for each vertex in the order it was added to the
* geometry. Calling `myGeometry.flipV()` flips a geometry's v-coordinates
* so that the texture appears mirrored vertically.
*
* For example, a plane's four vertices are added clockwise starting from the
* top-left corner. Here's how calling `myGeometry.flipV()` would change a
* plane's texture coordinates:
*
* ```js
* // Print the original texture coordinates.
* // Output: [0, 0, 1, 0, 0, 1, 1, 1]
* console.log(myGeometry.uvs);
*
* // Flip the v-coordinates.
* myGeometry.flipV();
*
* // Print the flipped texture coordinates.
* // Output: [0, 1, 1, 1, 0, 0, 1, 0]
* console.log(myGeometry.uvs);
*
* // Notice the swaps:
* // Left vertices: [0, 0] <--> [1, 0]
* // Right vertices: [1, 0] <--> [1, 1]
* ```
*
* @for p5.Geometry
*
* @example
* <div>
* <code>
* let img;
*
* function preload() {
* img = loadImage('assets/laDefense.jpg');
* }
*
* function setup() {
* createCanvas(100, 100, WEBGL);
*
* background(200);
*
* // Create p5.Geometry objects.
* let geom1 = buildGeometry(createShape);
* let geom2 = buildGeometry(createShape);
*
* // Flip geom2's V texture coordinates.
* geom2.flipV();
*
* // Left (original).
* push();
* translate(-25, 0, 0);
* texture(img);
* noStroke();
* model(geom1);
* pop();
*
* // Right (flipped).
* push();
* translate(25, 0, 0);
* texture(img);
* noStroke();
* model(geom2);
* pop();
*
* describe(
* 'Two photos of a ceiling on a gray background. The photos are mirror images of each other.'
* );
* }
*
* function createShape() {
* plane(40);
* }
* </code>
* </div>
*/
flipV() {
this.uvs = this.uvs.flat().map((val, index) => {
if (index % 2 === 0) {
return val;
} else {
return 1 - val;
}
});
}
/**
* Computes the geometry's faces using its vertices.
*
* All 3D shapes are made by connecting sets of points called *vertices*. A
* geometry's surface is formed by connecting vertices to form triangles that
* are stitched together. Each triangular patch on the geometry's surface is
* called a *face*. `myGeometry.computeFaces()` performs the math needed to
* define each face based on the distances between vertices.
*
* The geometry's vertices are stored as <a href="#/p5.Vector">p5.Vector</a>
* objects in the <a href="#/p5.Geometry/vertices">myGeometry.vertices</a>
* array. The geometry's first vertex is the
* <a href="#/p5.Vector">p5.Vector</a> object at `myGeometry.vertices[0]`,
* its second vertex is `myGeometry.vertices[1]`, its third vertex is
* `myGeometry.vertices[2]`, and so on.
*
* Calling `myGeometry.computeFaces()` fills the
* <a href="#/p5.Geometry/faces">myGeometry.faces</a> array with three-element
* arrays that list the vertices that form each face. For example, a geometry
* made from a rectangle has two faces because a rectangle is made by joining
* two triangles. <a href="#/p5.Geometry/faces">myGeometry.faces</a> for a
* rectangle would be the two-dimensional array
* `[[0, 1, 2], [2, 1, 3]]`. The first face, `myGeometry.faces[0]`, is the
* array `[0, 1, 2]` because it's formed by connecting
* `myGeometry.vertices[0]`, `myGeometry.vertices[1]`,and
* `myGeometry.vertices[2]`. The second face, `myGeometry.faces[1]`, is the
* array `[2, 1, 3]` because it's formed by connecting
* `myGeometry.vertices[2]`, `myGeometry.vertices[1]`, and
* `myGeometry.vertices[3]`.
*
* Note: `myGeometry.computeFaces()` only works when geometries have four or more vertices.
*
* @chainable
*
* @example
* <div>
* <code>
* // Click and drag the mouse to view the scene from different angles.
*
* let myGeometry;