-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathcustom_shapes.js
2145 lines (1905 loc) · 59.5 KB
/
custom_shapes.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 Custom Shapes
* @for p5
* @requires core
* @requires constants
*/
// REMINDER: remove .js extension (currently using it to run file locally)
import { Color } from '../color/p5.Color';
import { Vector } from '../math/p5.Vector';
import * as constants from '../core/constants';
// ---- UTILITY FUNCTIONS ----
function polylineLength(vertices) {
let length = 0;
for (let i = 1; i < vertices.length; i++) {
length += vertices[i-1].position.dist(vertices[i].position);
}
return length;
}
// ---- GENERAL BUILDING BLOCKS ----
class Vertex {
constructor(properties) {
for (const [key, value] of Object.entries(properties)) {
this[key] = value;
}
}
/*
get array() {
// convert to 1D array
// call `toArray()` if value is an object with a toArray() method
// handle primitive values separately
// maybe handle object literals too, with Object.values()?
// probably don’t need anything else for now?
}
*/
// TODO: make sure name of array conversion method is
// consistent with any modifications to the names of corresponding
// properties of p5.Vector and p5.Color
}
class ShapePrimitive {
vertices;
_shape = null;
_primitivesIndex = null;
_contoursIndex = null;
isClosing = false;
constructor(...vertices) {
if (this.constructor === ShapePrimitive) {
throw new Error('ShapePrimitive is an abstract class: it cannot be instantiated.');
}
if (vertices.length > 0) {
this.vertices = vertices;
}
else {
throw new Error('At least one vertex must be passed to the constructor.');
}
}
get vertexCount() {
return this.vertices.length;
}
get vertexCapacity() {
throw new Error('Getter vertexCapacity must be implemented.');
}
get _firstInterpolatedVertex() {
return this.startVertex();
}
get canOverrideAnchor() {
return false;
}
accept(visitor) {
throw new Error('Method accept() must be implemented.');
}
addToShape(shape) {
/*
TODO:
Refactor?
Test this method once more primitives are implemented.
Test segments separately (Segment adds an extra step to this method).
*/
let lastContour = shape.at(-1);
if (lastContour.primitives.length === 0) {
lastContour.primitives.push(this);
} else {
// last primitive in shape
let lastPrimitive = shape.at(-1, -1);
let hasSameType = lastPrimitive instanceof this.constructor;
let spareCapacity = lastPrimitive.vertexCapacity -
lastPrimitive.vertexCount;
// this primitive
let pushableVertices;
let remainingVertices;
if (hasSameType && spareCapacity > 0) {
pushableVertices = this.vertices.splice(0, spareCapacity);
remainingVertices = this.vertices;
lastPrimitive.vertices.push(...pushableVertices);
if (remainingVertices.length > 0) {
lastContour.primitives.push(this);
}
}
else {
lastContour.primitives.push(this);
}
}
// if primitive itself was added
// (i.e. its individual vertices weren't all added to an existing primitive)
// give it a reference to the shape and store its location within the shape
let addedToShape = this.vertices.length > 0;
if (addedToShape) {
let lastContour = shape.at(-1);
this._primitivesIndex = lastContour.primitives.length - 1;
this._contoursIndex = shape.contours.length - 1;
this._shape = shape;
}
return shape.at(-1, -1);
}
get _nextPrimitive() {
return this._belongsToShape ?
this._shape.at(this._contoursIndex, this._primitivesIndex + 1) :
null;
}
get _belongsToShape() {
return this._shape !== null;
}
handlesClose() {
return false;
}
close(vertex) {
throw new Error('Unimplemented!');
}
}
class Contour {
#kind;
primitives;
constructor(kind = constants.PATH) {
this.#kind = kind;
this.primitives = [];
}
get kind() {
const isEmpty = this.primitives.length === 0;
const isPath = this.#kind === constants.PATH;
return isEmpty && isPath ? constants.EMPTY_PATH : this.#kind;
}
accept(visitor) {
for (const primitive of this.primitives) {
primitive.accept(visitor);
}
}
}
// ---- PATH PRIMITIVES ----
class Anchor extends ShapePrimitive {
#vertexCapacity = 1;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitAnchor(this);
}
getEndVertex() {
return this.vertices[0];
}
}
// abstract class
class Segment extends ShapePrimitive {
constructor(...vertices) {
super(...vertices);
if (this.constructor === Segment) {
throw new Error('Segment is an abstract class: it cannot be instantiated.');
}
}
// segments in a shape always have a predecessor
// (either an anchor or another segment)
get _previousPrimitive() {
return this._belongsToShape ?
this._shape.at(this._contoursIndex, this._primitivesIndex - 1) :
null;
}
getStartVertex() {
return this._previousPrimitive.getEndVertex();
}
getEndVertex() {
return this.vertices.at(-1);
}
}
class LineSegment extends Segment {
#vertexCapacity = 1;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitLineSegment(this);
}
}
class BezierSegment extends Segment {
#order;
#vertexCapacity;
constructor(order, ...vertices) {
super(...vertices);
// Order m may sometimes be passed as an array [m], since arrays
// may be used elsewhere to store order of
// Bezier curves and surfaces in a common format
let numericalOrder = Array.isArray(order) ? order[0] : order;
this.#order = numericalOrder;
this.#vertexCapacity = numericalOrder;
}
get order() {
return this.#order;
}
get vertexCapacity() {
return this.#vertexCapacity;
}
#_hullLength;
hullLength() {
if (this.#_hullLength === undefined) {
this.#_hullLength = polylineLength([
this.getStartVertex(),
...this.vertices
]);
}
return this.#_hullLength;
}
accept(visitor) {
visitor.visitBezierSegment(this);
}
}
/*
To-do: Consider type and end modes -- see #6766
may want to use separate classes, but maybe not
For now, the implementation overrides
super.getEndVertex() in order to preserve current p5
endpoint behavior, but we're considering defaulting
to interpolated endpoints (a breaking change)
*/
class SplineSegment extends Segment {
#vertexCapacity = Infinity;
_splineProperties = {
ends: constants.INCLUDE,
tightness: 0
};
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitSplineSegment(this);
}
get _comesAfterSegment() {
return this._previousPrimitive instanceof Segment;
}
get canOverrideAnchor() {
return this._splineProperties.ends === constants.EXCLUDE;
}
// assuming for now that the first interpolated vertex is always
// the second vertex passed to splineVertex()
// if this spline segment doesn't follow another segment,
// the first vertex is in an anchor
get _firstInterpolatedVertex() {
if (this._splineProperties.ends === constants.EXCLUDE) {
return this._comesAfterSegment ?
this.vertices[1] :
this.vertices[0];
} else {
return this.getStartVertex()
}
}
get _chainedToSegment() {
if (this._belongsToShape && this._comesAfterSegment) {
let interpolatedStartPosition = this._firstInterpolatedVertex.position;
let predecessorEndPosition = this.getStartVertex().position;
return predecessorEndPosition.equals(interpolatedStartPosition);
}
else {
return false;
}
}
// extend addToShape() with a warning in case second vertex
// doesn't line up with end of last segment
addToShape(shape) {
const added = super.addToShape(shape);
this._splineProperties.ends = shape._splineProperties.ends;
this._splineProperties.tightness = shape._splineProperties.tightness;
if (this._splineProperties.ends !== constants.EXCLUDE) return added;
let verticesPushed = !this._belongsToShape;
let lastPrimitive = shape.at(-1, -1);
let message = (array1, array2) =>
`Spline does not start where previous path segment ends:
second spline vertex at (${array1})
expected to be at (${array2}).`;
if (verticesPushed &&
// Only check once the first interpolated vertex has been added
lastPrimitive.vertices.length === 2 &&
lastPrimitive._comesAfterSegment &&
!lastPrimitive._chainedToSegment
) {
let interpolatedStart = lastPrimitive._firstInterpolatedVertex.position;
let predecessorEnd = lastPrimitive.getStartVertex().position;
console.warn(
message(interpolatedStart.array(), predecessorEnd.array())
);
}
// Note: Could add a warning in an else-if case for when this spline segment
// is added directly to the shape instead of pushing its vertices to
// an existing spline segment. However, if we assume addToShape() is called by
// splineVertex(), it'd add a new spline segment with only one vertex in that case,
// and the check wouldn't be needed yet.
// TODO: Consider case where positions match but other vertex properties don't.
return added;
}
// override method on base class
getEndVertex() {
if (this._splineProperties.ends === constants.INCLUDE) {
return super.getEndVertex();
} else if (this._splineProperties.ends === constants.EXCLUDE) {
return this.vertices.at(-2);
} else {
return this.getStartVertex();
}
}
getControlPoints() {
let points = [];
if (this._comesAfterSegment) {
points.push(this.getStartVertex());
}
points.push(this.getStartVertex());
for (const vertex of this.vertices) {
points.push(vertex);
}
const prevVertex = this.getStartVertex();
if (this._splineProperties.ends === constants.INCLUDE) {
points.unshift(prevVertex);
points.push(this.vertices.at(-1));
} else if (this._splineProperties.ends === constants.JOIN) {
points.unshift(this.vertices.at(-1));
points.push(prevVertex, this.vertices.at(0));
}
return points;
}
handlesClose() {
if (!this._belongsToShape) return false;
// Only handle closing if the spline is the only thing in its contour after
// the anchor
const contour = this._shape.at(this._contoursIndex);
return contour.primitives.length === 2 && this._primitivesIndex === 1;
}
close() {
this._splineProperties.ends = constants.JOIN;
}
}
// ---- ISOLATED PRIMITIVES ----
class Point extends ShapePrimitive {
#vertexCapacity = 1;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitPoint(this);
}
}
class Line extends ShapePrimitive {
#vertexCapacity = 2;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitLine(this);
}
}
class Triangle extends ShapePrimitive {
#vertexCapacity = 3;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitTriangle(this);
}
}
class Quad extends ShapePrimitive {
#vertexCapacity = 4;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitQuad(this);
}
}
// ---- TESSELLATION PRIMITIVES ----
class TriangleFan extends ShapePrimitive {
#vertexCapacity = Infinity;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitTriangleFan(this);
}
}
class TriangleStrip extends ShapePrimitive {
#vertexCapacity = Infinity;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitTriangleStrip(this);
}
}
class QuadStrip extends ShapePrimitive {
#vertexCapacity = Infinity;
get vertexCapacity() {
return this.#vertexCapacity;
}
accept(visitor) {
visitor.visitQuadStrip(this);
}
}
// ---- PRIMITIVE SHAPE CREATORS ----
class PrimitiveShapeCreators {
// TODO: make creators private?
// That'd probably be better, but for now, it may be convenient to use
// native Map properties like size, e.g. for testing, and it's simpler to
// not have to wrap all the properties that might be useful
creators;
constructor() {
let creators = new Map();
/* TODO: REFACTOR BASED ON THE CODE BELOW,
ONCE CONSTANTS ARE IMPLEMENTED AS SYMBOLS
// Store Symbols as strings for use in Map keys
const EMPTY_PATH = constants.EMPTY_PATH.description;
const PATH = constants.PATH.description;
//etc.
creators.set(`vertex-${EMPTY_PATH}`, (...vertices) => new Anchor(...vertices));
// etc.
get(vertexKind, shapeKind) {
const key = `${vertexKind}-${shapeKind.description}`;
return this.creators.get(key);
}
// etc.
*/
// vertex
creators.set(`vertex-${constants.EMPTY_PATH}`, (...vertices) => new Anchor(...vertices));
creators.set(`vertex-${constants.PATH}`, (...vertices) => new LineSegment(...vertices));
creators.set(`vertex-${constants.POINTS}`, (...vertices) => new Point(...vertices));
creators.set(`vertex-${constants.LINES}`, (...vertices) => new Line(...vertices));
creators.set(`vertex-${constants.TRIANGLES}`, (...vertices) => new Triangle(...vertices));
creators.set(`vertex-${constants.QUADS}`, (...vertices) => new Quad(...vertices));
creators.set(`vertex-${constants.TRIANGLE_FAN}`, (...vertices) => new TriangleFan(...vertices));
creators.set(`vertex-${constants.TRIANGLE_STRIP}`, (...vertices) => new TriangleStrip(...vertices));
creators.set(`vertex-${constants.QUAD_STRIP}`, (...vertices) => new QuadStrip(...vertices));
// bezierVertex (constructors all take order and vertices so they can be called in a uniform way)
creators.set(`bezierVertex-${constants.EMPTY_PATH}`, (order, ...vertices) => new Anchor(...vertices));
creators.set(`bezierVertex-${constants.PATH}`, (order, ...vertices) => new BezierSegment(order, ...vertices));
// splineVertex
creators.set(`splineVertex-${constants.EMPTY_PATH}`, (...vertices) => new Anchor(...vertices));
creators.set(`splineVertex-${constants.PATH}`, (...vertices) => new SplineSegment(...vertices));
this.creators = creators;
}
get(vertexKind, shapeKind) {
const key = `${vertexKind}-${shapeKind}`;
return this.creators.get(key);
}
set(vertexKind, shapeKind, creator) {
const key = `${vertexKind}-${shapeKind}`;
this.creators.set(key, creator);
}
clear() {
this.creators.clear();
}
}
// ---- SHAPE ----
/* Note: It's assumed that Shape instances are always built through
* their beginShape()/endShape() methods. For example, this ensures
* that a segment is never the first primitive in a contour (paths
* always start with an anchor), which simplifies code elsewhere.
*/
class Shape {
#vertexProperties;
#initialVertexProperties;
#primitiveShapeCreators;
#bezierOrder = 3;
kind = null;
contours = [];
_splineProperties = {
tightness: 0,
ends: constants.INCLUDE
};
userVertexProperties = null;
constructor(
vertexProperties,
primitiveShapeCreators = new PrimitiveShapeCreators()
) {
this.#initialVertexProperties = vertexProperties;
this.#vertexProperties = vertexProperties;
this.#primitiveShapeCreators = primitiveShapeCreators;
for (const key in this.#vertexProperties) {
if (key !== 'position' && key !== 'textureCoordinates') {
this[key] = function(value) {
this.#vertexProperties[key] = value;
};
}
}
}
serializeToArray(val) {
if (val === null || val === undefined) {
return [];
} if (val instanceof Number) {
return [val];
} else if (val instanceof Array) {
return val;
} else if (val.array instanceof Function) {
return val.array();
} else {
throw new Error(`Can't convert ${val} to array!`);
}
}
vertexToArray(vertex) {
const array = [];
for (const key in this.#vertexProperties) {
if (this.userVertexProperties && key in this.userVertexProperties)
continue;
const val = vertex[key];
array.push(...this.serializeToArray(val));
}
for (const key in this.userVertexProperties) {
if (key in vertex) {
array.push(...this.serializeToArray(vertex[key]));
} else {
array.push(...new Array(this.userVertexProperties[key]).fill(0));
}
}
return array;
}
hydrateValue(queue, original) {
if (original === null) {
return null;
} else if (original instanceof Number) {
return queue.shift();
} else if (original instanceof Array) {
const array = [];
for (let i = 0; i < original.length; i++) {
array.push(queue.shift());
}
return array;
} else if (original instanceof Vector) {
return new Vector(queue.shift(), queue.shift(), queue.shift());
} else if (original instanceof Color) {
// NOTE: Not sure what intention here is, `Color` constructor signature
// has changed so needed to be reviewed
const array = [
queue.shift(),
queue.shift(),
queue.shift(),
queue.shift()
];
return new Color(array);
}
}
arrayToVertex(array) {
const vertex = {};
const queue = [...array];
for (const key in this.#vertexProperties) {
if (this.userVertexProperties && key in this.userVertexProperties)
continue;
const original = this.#vertexProperties[key];
vertex[key] = this.hydrateValue(queue, original);
}
for (const key in this.userVertexProperties) {
const original = this.#vertexProperties[key];
vertex[key] = this.hydrateValue(queue, original);
}
return vertex;
}
arrayScale(array, scale) {
return array.map(v => v * scale);
}
arraySum(first, ...rest) {
return first.map((v, i) => {
let result = v;
for (let j = 0; j < rest.length; j++) {
result += rest[j][i];
}
return result;
});
}
arrayMinus(a, b) {
return a.map((v, i) => v - b[i]);
}
evaluateCubicBezier([a, b, c, d], t) {
return this.arraySum(
this.arrayScale(a, Math.pow(1 - t, 3)),
this.arrayScale(b, 3 * Math.pow(1 - t, 2) * t),
this.arrayScale(c, 3 * (1 - t) * Math.pow(t, 2)),
this.arrayScale(d, Math.pow(t, 3))
);
}
evaluateQuadraticBezier([a, b, c], t) {
return this.arraySum(
this.arrayScale(a, Math.pow(1 - t, 2)),
this.arrayScale(b, 2 * (1 - t) * t),
this.arrayScale(c, t * t)
);
}
/*
catmullRomToBezier(vertices, tightness)
Abbreviated description:
Converts a Catmull-Rom spline to a sequence of Bezier curveTo points.
Parameters:
vertices -> Array [v0, v1, v2, v3, ...] of at least four vertices
tightness -> Number affecting shape of curve
Returns:
array of Bezier curveTo control points, each represented as [c1, c2, c3][]
TODO:
1. It seems p5 contains code for converting from Catmull-Rom to Bezier in at least two places:
catmullRomToBezier() is based on code in the legacy endShape() function:
https://github.com/processing/p5.js/blob/1b66f097761d3c2057c0cec4349247d6125f93ca/src/core/p5.Renderer2D.js#L859C1-L886C1
A different conversion can be found elsewhere in p5:
https://github.com/processing/p5.js/blob/17304ce9e9ef3f967bd828102a51b62a2d39d4f4/src/typography/p5.Font.js#L1179
A more careful review and comparison of both implementations would be helpful. They're different. I put
catmullRomToBezier() together quickly without checking the math/algorithm, when I made the proof of concept
for the refactor.
2. It may be possible to replace the code in p5.Font.js with the code here, to reduce duplication.
*/
catmullRomToBezier(vertices, tightness) {
let s = 1 - tightness;
let bezArrays = [];
for (let i = 0; i + 3 < vertices.length; i++) {
const [a, b, c, d] = vertices.slice(i, i + 4);
const bezB = this.arraySum(
b,
this.arrayScale(this.arrayMinus(c, a), s / 6)
);
const bezC = this.arraySum(
c,
this.arrayScale(this.arrayMinus(b, d), s / 6)
);
const bezD = c;
bezArrays.push([bezB, bezC, bezD]);
}
return bezArrays;
}
// TODO for at() method:
// RENAME?
// -at() indicates it works like Array.prototype.at(), e.g. with negative indices
// -get() may work better if we want to add a corresponding set() method
// -a set() method could maybe check for problematic usage (e.g. inserting a Triangle into a PATH)
// -renaming or removing would necessitate changes at call sites (it's already in use)
// REFACTOR?
// TEST
at(contoursIndex, primitivesIndex, verticesIndex) {
let contour;
let primitive;
contour = this.contours.at(contoursIndex);
switch(arguments.length) {
case 1:
return contour;
case 2:
return contour.primitives.at(primitivesIndex);
case 3:
primitive = contour.primitives.at(primitivesIndex);
return primitive.vertices.at(verticesIndex);
}
}
// maybe call this clear() for consistency with PrimitiveShapeCreators.clear()?
// note: p5.Geometry has a reset() method, but also clearColors()
// looks like reset() isn't in the public reference, so maybe we can switch
// everything to clear()? Not sure if reset/clear is used in other classes,
// but it'd be good if geometries and shapes are consistent
reset() {
this.#vertexProperties = { ...this.#initialVertexProperties };
this.kind = null;
this.contours = [];
this.userVertexProperties = null;
}
vertexProperty(name, data) {
this.userVertexProperties = this.userVertexProperties || {};
const key = this.vertexPropertyKey(name);
const dataArray = Array.isArray(data) ? data : [data];
if (!this.userVertexProperties[key]) {
this.userVertexProperties[key] = dataArray.length;
}
this.#vertexProperties[key] = dataArray;
}
vertexPropertyName(key) {
return key.replace(/Src$/, '');
}
vertexPropertyKey(name) {
return name + 'Src';
}
/**
* Influences the shape of the Bézier curve segment in a custom shape.
* By default, this is 3; the other possible parameter is 2. This
* results in quadratic Bézier curves.
*
* `bezierVertex()` adds a curved segment to custom shapes. The Bézier curves
* it creates are defined like those made by the
* <a href="#/p5/bezier">bezier()</a> function. `bezierVertex()` must be
* called between the
* <a href="#/p5/beginShape">beginShape()</a> and
* <a href="#/p5/endShape">endShape()</a> functions. There must be at least
* one call to <a href="#/p5/vertex">bezierVertex()</a>, before
* a number of `bezierVertex()` calls that is a multiple of the parameter
* set by <a href="#/p5/bezierOrder">bezierOrder(...)</a> (default 3).
*
* Each curve of order 3 requires three calls to `bezierVertex`, so
* 2 curves would need 7 calls to `bezierVertex()`:
* (1 one initial anchor point, two sets of 3 curves describing the curves)
* With `bezierOrder(2)`, two curves would need 5 calls: 1 + 2 + 2.
*
* Bézier curves can also be drawn in 3D using WebGL mode.
*
* Note: `bezierVertex()` won’t work when an argument is passed to
* <a href="#/p5/beginShape">beginShape()</a>.
*
* @method bezierOrder
* @param {Number} order can be either 2 or 3, by default 3
*
* @example
* <div>
* <code>
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Style the shape.
* noFill();
*
* // Start drawing the shape.
* beginShape();
*
* // set the order to 2 for a quadratic Bézier curve
* bezierOrder(2);
*
* // Add the first anchor point.
* bezierVertex(30, 20);
*
* // Add the Bézier vertex.
* bezierVertex(80, 20);
* bezierVertex(50, 50);
*
* // Stop drawing the shape.
* endShape();
*
* describe('A black curve drawn on a gray square. The curve starts at the top-left corner and ends at the center.');
* }
* </code>
* </div>
*/
bezierOrder(...order) {
this.#bezierOrder = order;
}
splineProperty(key, value) {
this._splineProperties[key] = value;
}
splineProperties(values) {
if (values) {
for (const key in values) {
this.splineProperty(key, values[key]);
}
} else {
return this._splineProperties;
}
}
/*
To-do: Maybe refactor #createVertex() since this has side effects that aren't advertised
in the method name?
*/
#createVertex(position, textureCoordinates) {
this.#vertexProperties.position = position;
if (textureCoordinates !== undefined) {
this.#vertexProperties.textureCoordinates = textureCoordinates;
}
return new Vertex(this.#vertexProperties);
}
#createPrimitiveShape(vertexKind, shapeKind, ...vertices) {
let primitiveShapeCreator = this.#primitiveShapeCreators.get(
vertexKind, shapeKind
);
return vertexKind === 'bezierVertex' ?
primitiveShapeCreator(this.#bezierOrder, ...vertices) :
primitiveShapeCreator(...vertices);
}
/*
#generalVertex() is reused by the special vertex functions,
including vertex(), bezierVertex(), splineVertex(), and arcVertex():
It creates a vertex, builds a primitive including that
vertex, and has the primitive add itself to the shape.
*/
#generalVertex(kind, position, textureCoordinates) {
let vertexKind = kind;
let lastContourKind = this.at(-1).kind;
let vertex = this.#createVertex(position, textureCoordinates);
let primitiveShape = this.#createPrimitiveShape(
vertexKind,
lastContourKind,
vertex
);
return primitiveShape.addToShape(this);
}
vertex(position, textureCoordinates, { isClosing = false } = {}) {
const added = this.#generalVertex('vertex', position, textureCoordinates);
added.isClosing = isClosing;
}
bezierVertex(position, textureCoordinates) {
this.#generalVertex('bezierVertex', position, textureCoordinates);
}
splineVertex(position, textureCoordinates) {
this.#generalVertex('splineVertex', position, textureCoordinates);
}
arcVertex(position, textureCoordinates) {
this.#generalVertex('arcVertex', position, textureCoordinates);
}
beginContour(shapeKind = constants.PATH) {
if (this.at(-1)?.kind === constants.EMPTY_PATH) {
this.contours.pop();
}
this.contours.push(new Contour(shapeKind));
}
endContour(closeMode = constants.OPEN, _index = this.contours.length - 1) {
const contour = this.at(_index);
if (closeMode === constants.CLOSE) {
// shape characteristics
const isPath = contour.kind === constants.PATH;
// anchor characteristics
const anchorVertex = this.at(_index, 0, 0);
const anchorHasPosition = Object.hasOwn(anchorVertex, 'position');
const lastSegment = this.at(_index, -1);
// close path
if (isPath && anchorHasPosition) {
if (lastSegment.handlesClose()) {
lastSegment.close(anchorVertex);
} else {
// Temporarily remove contours after the current one so that we add to the original
// contour again
const rest = this.contours.splice(
_index + 1,
this.contours.length - _index - 1
);
const prevVertexProperties = this.#vertexProperties;
this.#vertexProperties = { ...prevVertexProperties };
for (const key in anchorVertex) {