-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtg.mjs
1517 lines (1367 loc) · 54.5 KB
/
tg.mjs
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
// TODO: coordinate system orientation
import { vec2, mat3 } from 'gl-matrix';
const VERSION = '___VERSION___';
const TYPE = Symbol('Turtle Graphics Object');
const EPSILON = 1e-10;
const DEFAULT_FORWARD = 100;
const DEFAULT_RIGHT = 90;
const GLOBAL_LIB_NAME = 'tg';
const GLOBAL_INSTANCE_NAME = 't';
const GLOBAL_OVERWRITTEN_NAME = 'p5';
const DONT_GLOBALIZE = [ 'VERSION', 'TYPE' ];
const DONT_WARN_GLOBALIZING = [ 'self' ];
const TRANSFORM_WRT_TURTLE = true; // Scale and rotate with respect to the turtle's current position, instead of the origin
// Constructor function
export function make_turtle_graphics(...line_fns_) {
function _make_turtle_state() {
return {
x: 0, // position (x)
y: 0, // position (y)
px: 0, // previous position (x)
py: 0, // previous position (y)
a: 0, // angle (in degrees)
// untransformed state
ux: 0,
uy: 0,
upx: 0,
upy: 0,
ua: 0,
d: true, // pen down status
};
}
// Full internal state
const _state = {
turtle: _make_turtle_state(), // turtle state
turtle_stack: [], // turtle stack
matrix: mat3.create(), // transformation matrix
matrix_stack: [], // matrix stack
line_fns: [...line_fns_], // line drawing callbacks
turtle_fn: undefined, // function called to draw the turtle
mark_fn: undefined, // function called to draw a mark
};
// Aliases and deprecation mechanism
const _aliases = {};
const _aliases_deprecated = {};
function _add_aliases(orig, aliases, aliases_array = _aliases) {
if (!(orig in aliases_array)) { aliases_array[orig] = []; }
aliases_array[orig].push(...aliases);
}
function _add_aliases_deprecated(orig, aliases) {
return _add_aliases(orig, aliases, _aliases_deprecated);
}
/*********************************************************
Instance
*********************************************************/
// Add keys from obj that are missing from target_obj
// Used to copy over properties in newturtle() and clone() that might have been added later
// e.g. the plotter() function from tg-plot.mjs
function _add_missing_props(obj, target_obj, except_startswith='_') {
for (let key of Object.keys(obj)) {
// console.log('checking', key)
if ( !(key in target_obj) && !key.startsWith(except_startswith) ) {
target_obj[key] = obj[key];
}
}
}
/**
* Create a new turtle object.
*
* @function newturtle
* @returns {Object} A brand new turtle object. Has all turtle functions as properties.
*/
function newturtle(...new_line_fns) {
// use same line_fns as the current instance, if none are explicitly provided
const new_turtle = make_turtle_graphics(
...(new_line_fns.length > 0 ? new_line_fns : _state.line_fns)
);
_add_missing_props(self, new_turtle);
return new_turtle;
}
_add_aliases_deprecated('newturtle', ['maketurtle']);
/**
* Get the turtle object itself.
*
* @function self
* @returns {Object} A turtle object. Has all turtle functions as properties.
*/
function self_() {
return self;
}
/**
* Get a copy of the turtle object.
* <br>
* Starts out in the same state as the original turtle, but changes to it don't affect the original one.
*
* @function clone
* @returns {Object} An exact clone of the turtle object returned by <code>{@link self}</code>. Has all turtle functions as properties.
*/
function clone() {
const new_turtle = make_turtle_graphics(..._state.line_fns); // make new turtle with same line_fns
// clone all internal state properties except for functions (which cannot be cloned, because it containes functions)
for (let key of Object.keys(_state).filter(x => !['line_fns', 'turtle_fn', 'mark_fn'].includes(x))) {
new_turtle._state()[key] = structuredClone( _state[key] );
}
new_turtle._state().turtle_fn = _state.turtle_fn;
new_turtle._state().mark_fn = _state.mark_fn;
_add_missing_props(self, new_turtle);
return new_turtle;
}
/**
* Check whether an object is a turtle or not.
*
* @function isturtle
* @param {any} obj - The objcet to check. Can be anything.
* @returns {boolean} <code>true</code> if <code>obj</code> is a Turtle Object, <code>false</code> otherwise.
*/
function isturtle(obj) {
return obj !== null && typeof obj === 'object' && 'TYPE' in obj && obj['TYPE'] === TYPE;
}
/*********************************************************
Basic
*********************************************************/
function _draw() {
const turtle = _state.turtle;
if (!turtle.d) { return; } // don't draw if pen isn't down
for (let line_fn of _state.line_fns) {
if (typeof line_fn === 'function') {
line_fn(turtle.px, turtle.py, turtle.x, turtle.y);
}
}
}
// 50.000000000000014 -> 50
function _clean_zero(v) {
if (Math.abs(v % 1) < EPSILON) {
return Math.trunc(v);
} else {
return v;
}
}
function _clean_angle(a) {
a = a % 360;
if (a < 0) { a += 360; }
return a;
}
// transform point by matrix (defaults to current matrix)
function _transform([x, y], m = undefined) {
const p = [ x, y ];
m = m ?? _state.matrix; // use current matrix by default
vec2.transformMat3(p, p, m); // Apply given transformation
p[0] = _clean_zero(p[0]);
p[1] = _clean_zero(p[1]);
return p;
}
/**
* Move the turtle forward.
* <br>
* Draws a line, if the pen is down (see <code>{@link pendown}</code> and <code>{@link penup}</code>).
*
* @function forward
* @param [distance=100] {number} - How far to move forward, in pixels.
* @see <code>{@link back}</code> to move back.
*/
function forward(units = DEFAULT_FORWARD) {
const turtle = _state.turtle;
const matrix = _state.matrix;
// save previous position
turtle.upx = turtle.ux;
turtle.upy = turtle.uy;
turtle.px = turtle.x;
turtle.py = turtle.y;
// new position (untransformed)
const angle_rad = ( turtle.ua - 90 ) / 180 * Math.PI;
turtle.ux += units * Math.cos(angle_rad);
turtle.uy += units * Math.sin(angle_rad);
turtle.ux = _clean_zero(turtle.ux);
turtle.uy = _clean_zero(turtle.uy);
// transformed position
[ turtle.x, turtle.y ] = _transform( [turtle.ux, turtle.uy], matrix );
[ turtle.px, turtle.py ] = _transform( [turtle.upx, turtle.upy], matrix );
_draw();
}
/**
* Move the turtle back.
* <br>
* Draws a line, if the pen is down (see <code>{@link pendown}</code> and <code>{@link penup}</code>).
*
* @function back
* @param [distance=100] {number} - How far to move back, in pixels.
* @see <code>{@link forward}</code> to move forward.
*/
function back(units = DEFAULT_FORWARD) {
return forward(-units);
}
/**
* Turn turtle to the right.
*
* @function right
* @param [angle=90] {number} - How far to turn the turtle right, in degrees (0–360).
* @see <code>{@link left}</code> to turn left.
*/
function right(angle = DEFAULT_RIGHT) {
const turtle = _state.turtle;
// update untransformed angle
turtle.ua += angle;
turtle.ua = _clean_angle(turtle.ua);
// update transformed angle as well
turtle.a += angle;
turtle.a = _clean_angle(turtle.a);
}
/**
* Turn turtle to the left.
*
* @function left
* @param [angle=90] {number} - How far to turn the turtle left, in degrees (0–360).
* @see <code>{@link right}</code> to turn right.
*/
function left(angle = DEFAULT_RIGHT) {
return right(-angle);
}
/**
* Lower the pen.
* <br>
* Subsequent uses of <code>{@link forward}</code> and <code>{@link back}</code> will draw lines.
* A new turtle starts with the pen down.
*
* @function pendown
* @see <code>{@link penup}</code> to raise the pen.
*/
function pendown(down = true) {
_state.turtle.d = down;
}
/**
* Raise the pen.
* <br>
* Subsequent uses of <code>{@link forward}</code> and <code>{@link back}</code> will NOT draw lines.
* A new turtle starts with the pen down.
*
* @function penup
* @see <code>{@link penup}</code> to lower the pen.
*/
function penup(up = true) {
_state.turtle.d = !up;
}
/*********************************************************
Transformations
*********************************************************/
/**
* Translate the coordinate system.
*
* @function translate
* @param {number} tx - Amount in pixels to translate in the x-direction Positive numbers move to the right, negative numbers move to the left.
* @param {number} ty - Amount in pixels to translate in the y-direction. Positive numbers move down, negative numbers move up.
* @see <code>{@link rotate}</code> and <code>{@link scale}</code>, the other transformations.
* @see <code>{@link resetmatrix}</code> to reset transformations.
* @see <code>{@link pushmatrix}</code> to save transformations.
* @see <code>{@link popmatrix}</code> to restore previously saved transformations.
*/
function translate(tx = 0, ty = 0) {
// update transformation matrix
mat3.translate( _state.matrix, _state.matrix, [tx, ty] );
}
/**
* Rotate the coordinate system around the current position of the turtle.
*
* @function rotate
* @param {number} angle - The angle in degrees to rotate the coordinate system. A positive number rotates clockwise, a negative number counter-clockwise.
* @see <code>{@link translate}</code> and <code>{@link scale}</code>, the other transformations.
* @see <code>{@link resetmatrix}</code> to reset transformations.
* @see <code>{@link pushmatrix}</code> to save transformations.
* @see <code>{@link popmatrix}</code> to restore previously saved transformations.
*/
function rotate(ra = 0) {
const turtle = _state.turtle;
// update transformation matrix
if (TRANSFORM_WRT_TURTLE) { translate(turtle.ux, turtle.uy); } // TODO: why untransformed?
mat3.rotate( _state.matrix, _state.matrix, ra / 180 * Math.PI );
if (TRANSFORM_WRT_TURTLE) { translate(-turtle.ux, -turtle.uy); }
// update transformed angle as well
turtle.a += ra;
turtle.a = _clean_angle(turtle.a);
}
/**
* Scale the coordinate system from the current position of the turtle.
*
* @function scale
* @param {number} sx - The scaling factor in x-direction.
* @param {number} [sy] - The scaling factor in y-direction. If ommitted, takes the same value as <code>sx</code>.
* @see <code>{@link translate}</code> and <code>{@link rotate}</code>, the other transformations.
* @see <code>{@link resetmatrix}</code> to reset transformations.
* @see <code>{@link pushmatrix}</code> to save transformations.
* @see <code>{@link popmatrix}</code> to restore previously saved transformations.
*/
function scale(sx = 1, sy = undefined) {
if (sy === undefined) { sy = sx; }
// update transformation matrix
if (TRANSFORM_WRT_TURTLE) { translate(_state.turtle.ux, _state.turtle.uy); } // TODO: why untransformed?
mat3.scale( _state.matrix, _state.matrix, [sx, sy] );
if (TRANSFORM_WRT_TURTLE) { translate(-_state.turtle.ux, -_state.turtle.uy); }
}
/*********************************************************
Stacks
*********************************************************/
/**
* Push the turtle's state onto the stack.
* <br>
* Saves the current position, heading and pen state.
*
* @function pushstate
* @see <code>{@link popstate}</code> to later restore the pushed state.
*/
function pushstate() {
_state.turtle_stack.push( Object.assign({}, _state.turtle) ); // push a copy
}
_add_aliases_deprecated('pushstate', ['push_turtle']);
/**
* Restore the last pushed turtle state from the stack.
* <br>
* Restores position, heading and pen state to what they were when {@link pushstate} was last called.
*
* @function popstate
* @see <code>{@link pushstate}</code> to first save the turtle's state.
*/
function popstate() {
if (_state.turtle_stack.length > 0) {
_state.turtle = _state.turtle_stack.pop();
}
}
_add_aliases_deprecated('popstate', ['pop_turtle']);
/**
* Push the current transformation matrix onto the stack.
* <br>
* The transformation matrix contains all transformations, accumulated through calls to <code>{@link translate}</code>, <code>{@link rotate}</code> and <code>{@link scale}</code>.
*
* @function pushmatrix
* @see <code>{@link popmatrix}</code> to later restore the pushed transformation matrix.
*/
function pushmatrix() {
_state.matrix_stack.push( mat3.clone(_state.matrix) ); // push a copy
}
_add_aliases_deprecated('pushmatrix', ['push_matrix']);
/**
* Restore the last pushed transformation matrix from the stack.
*
* @function popmatrix
* @see <code>{@link pushmatrix}</code> to first save the transformation matrix.
*/
function popmatrix() {
if (_state.matrix_stack.length > 0) {
_state.matrix = _state.matrix_stack.pop();
}
}
_add_aliases_deprecated('popmatrix', ['pop_matrix']);
/**
* Push the turtle's state and transformation matrix onto the stack.
*
* @function push
* @see <code>{@link pushstate}</code> to only save the turtle's state.
* @see <code>{@link pushmatrix}</code> to only save the transformation matrix.
*/
function push() {
pushstate();
pushmatrix();
}
/**
* Restore the last pushed turtle state and transformation matrix from the stack.
*
* @function pop
* @see <code>{@link popstate}</code> to only restore the turtle's state.
* @see <code>{@link popmatrix}</code> to only restore the transformation matrix.
*/
function pop() {
popstate();
popmatrix();
}
/*********************************************************
Get state
*********************************************************/
/**
* An object describing a turtle's position.
* Used with {@link xy}, {@link setxy} and {@link jumpxy}.
*
* @typedef {Object} Position
* @property x {number} - The x-coordinate in pixels.
* @property y {number} - The y-coordinate in pixels.
* @see <code>{@link xy}</code> to get the turtle's position.
* @see <code>{@link setxy}</code> to set the turtle's position.
* @see <code>{@link jumpxy}</code> to set the turtle's position without drawing.
*/
/**
* Get the turtle's position.
*
* @function xy
* @returns {Position} A {@link Position} object containing <code>x</code> and <code>y</code>.
*/
// TODO: what is the intended behaviour?
// either xy returns untransformed and setxy transforms
// or xy returns transformed (absolute) and setxy doesn't transform
// but: if everything is done in absolyte coordinates, we can't use relative movements with setxy
function xy() {
// return untransformed position
return { x: _state.turtle.ux, y: _state.turtle.uy };
}
function absxy() {
return { x: _state.turtle.x, y: _state.turtle.y };
}
/**
* Get the turtle's x-coordinate.
*
* @function x
* @returns {number} The turtle's x-coordinate in pixels.
*/
function x() {
return _state.turtle.ux;
}
_add_aliases_deprecated('x', ['xcor']);
function absx() {
return _state.turtle.x;
}
/**
* Get the turtle's y-coordinate.
*
* @function y
* @returns {number} The turtle's y-coordinate in pixels.
*/
function y() {
return _state.turtle.uy;
}
_add_aliases_deprecated('y', ['ycor']);
function absy() {
return _state.turtle.y;
}
/**
* Get the turtle's heading.
*
* @function heading
* @returns {number} The turtle's heading angle in degrees (0–360).
*/
// TODO: should heading return untransformed? probably, because setheading applies the rotation
function heading() {
return _state.turtle.ua;
}
function absheading() {
return _state.turtle.a;
}
/**
* Get whether the pen is currently down.
*
* @function isdown
* @returns {boolean} <code>true</code> if pen is down, <code>false</code> otherwise.
*/
function isdown() {
return _state.turtle.d;
}
/**
* Get whether the pen is currently up.
*
* @function isup
* @returns {boolean} <code>true</code> if pen is up, <code>false</code> otherwise.
*/
function isup() {
return !_state.turtle.d;
}
/**
* An object describing a turtle's state. Used with <code>{@link state}</code> and <code>{@link setstate}</code>.
*
* @typedef {Object} State
* @property {number} x - The x-coordinate in pixels.
* @property {number} y - The y-coordinate in pixels.
* @property {number} a - The heading angle in degreed (0–360).
* @property {boolean} d - <code>true</code> if the pen is down, <code>false</code> otherwise.
* @see {@link state} to get the turtle's state.
* @see {@link setstate} to set the turtles's state.
*/
/**
* Get the turtle's current position, heading angle and pen position as an object.
*
* @function state
* @returns {State} A {@link State} object containing <code>x</code> (the x-coordinate), <code>y</code> (the y-coordinate), <code>a</code> (the heading angle) and <code>d</code> (the pen down state).
*/
function state() {
const turtle = _state.turtle;
return { x: turtle.x, y: turtle.y, a: turtle.a, d: turtle.d };
}
_add_aliases_deprecated('state', ['getturtle']);
/**
* Get whether the turtle is currently outside of the canvas.
*
* @function outside
* @returns {boolean} <code>true</code> if out of bounds, <code>false</code> otherwise.
* @see {@link inside} for the inverse.
*/
function outside() {
const p5 = window?.p5?.instance;
if (p5 === undefined) {
console.warn('🐢 → outside() / inside(): No p5.js detected');
return undefined;
}
return _state.turtle.x < -p5.width/2 || _state.turtle.x > p5.width/2 ||
_state.turtle.y < -p5.height/2 || _state.turtle.y > p5.height/2;
}
/**
* Get whether the turtle is currently inside of the canvas.
*
* @function inside
* @returns {boolean} <code>true</code> if inbounds, <code>false</code> otherwise.
* @see {@link outside} for the inverse.
*/
function inside() {
const out = outside();
if (out === undefined) {
return undefined;
}
return !outside();
}
/*********************************************************
Get relative state
*********************************************************/
function _to_point(x, y) {
// allow [x, y] as first parameter
// needs to be tested first, cause arrays of type 'object'
if (Array.isArray(x)) {
const arr = x;
x = arr.at(0);
y = arr.at(1);
}
// allow turtle object as first parameter
else if (isturtle(x)) {
const obj = x;
x = obj.x();
y = obj.y();
}
// allow {x, y} as first parameter
else if (typeof x === 'object' && x !== null) {
const obj = x;
x = obj?.x;
y = obj?.y;
}
return { x, y };
}
function _check_number(val, warning_domain, var_name, allow_null_undefined = false) {
if (allow_null_undefined && (val === null || val === undefined)) {
return true;
}
if (!Number.isFinite(val)) {
if (warning_domain && var_name) {
console.warn('%s: %s needs to be a proper number (cannot be NaN or Infinity)', warning_domain, var_name);
}
return false;
}
if (typeof val !== 'number') {
if (warning_domain && var_name) {
console.warn('%s: %s needs to be a number', warning_domain, var_name);
}
return false;
}
return true;
}
/**
* Get the bearing from the turtle to a given point.
* <br>
* The bearing is the angle from the turtle's heading direction to the given point.
* In other words, the bearing is the angle the turtle needs to turn <code>{@link right}</code> in order to face the given point.
*
* @function bearing
* @param {number|Position} x - The x-coordinate of the point to get the bearing to or a {@link Position} object. The other parameter (<code>y</code>) is ignored, if a {@link Position} object is given.
* @param {number} [y] - The y-coordinate of the point to get the bearing to.
* @returns {number} The bearing to the given point in degrees (-180 to +180).
* @see <code>{@link right}</code> to turn towards the point.
* @see <code>{@link face}</code> for a convenience function to face a given point.
*/
function bearing(x, y) {
({ x, y } = _to_point(x, y));
if ( ! _check_number(x, 'bearing', 'x') ) { return; }
if ( ! _check_number(y, 'bearing', 'y') ) { return; }
const turtle = _state.turtle;
// vector to point xy
const vx = x - turtle.x;
const vy = y - turtle.y;
if (vx == 0 && vy == 0) { return 0; }
let b = Math.atan2(vy, vx) / Math.PI * 180; // [-180, +180] angle between positive x-axis and vector
b = b + 90 - turtle.a;
b = _clean_angle(b);
if (b > 180) { b -= 360; } // make output [-180, 180]
return b;
}
/**
* Get the distance from the turtle to a given point.
*
* @function distance
* @param {number|Position} - The x-coordinate of the point to get the distance to or a {@link Position} object. The other parameter (<code>y</code>) is ignored, if a {@link Position} object is given.
* @param {number} [y] - The y-coordinate of the point to get the distance to.
* @returns {number} The distance to the given point in pixels.
*/
function distance(x, y) {
({ x, y } = _to_point(x, y));
if ( ! _check_number(x, 'distance', 'x') ) { return; }
if ( ! _check_number(y, 'distance', 'y') ) { return; }
[x, y] = _transform([x, y]); // apply current transformation to point
const turtle = _state.turtle;
const dx = x - turtle.x;
const dy = y - turtle.y;
return Math.sqrt(dx*dx + dy*dy);
}
/*********************************************************
Set state
*********************************************************/
/**
* Set the turtle's position.
* <br>
* Draws a line to the new position, if the pen is down (see <code>{@link pendown}</code> and <code>{@link penup}</code>).
*
* @function setxy
* @param {(number|Position)} x - The x-coordinate or a {@link Position} object. The other parameter (<code>y</code>) is ignored if a {@link Position} object is given.
* @param {number} [y] - The y-coordinate. Ignored if <code>x</code> is given a {@link Position} object.
*/
// TODO: think about naming (e.g. moveto, lineto)
function setxy(x, y) {
({ x, y } = _to_point(x, y));
if ( ! _check_number(x, 'setxy', 'x', true) ) { return; }
if ( ! _check_number(y, 'setxy', 'y', true) ) { return; }
const turtle = _state.turtle;
const matrix = _state.matrix;
if (x === null || x === undefined) { x = turtle.x; } // TODO: shouldn't this be ux ? (will be transformed below)
if (y === null || y === undefined) { y = turtle.y; }
// save previous position
turtle.upx = turtle.ux;
turtle.upy = turtle.uy;
turtle.px = turtle.x;
turtle.py = turtle.y;
// new position (untransformed)
turtle.ux = x;
turtle.uy = y;
// transformed position
[ turtle.x, turtle.y ] = _transform( [turtle.ux, turtle.uy], matrix );
[ turtle.px, turtle.py ] = _transform( [turtle.upx, turtle.upy], matrix );
_draw();
}
// TODO: function setxyabs(x,y) {}
/**
* Set the turtle's position, without drawing to the new position.
*
* @function jumpxy
* @param {number|Position} x - The x-coordinate or a {@link Position} object. The other parameter (<code>y</code>) is ignored if a {@link Position} object is given.
* @param {number} [y] - The y-coordinate.
*/
function jumpxy(x, y) {
const down = isdown(); // save pen down state
penup();
setxy(x, y);
pendown(down); // restore pen down state
}
/**
* Set the turtle's heading.
*
* @function setheading
* @param {number} angle - The heading angle (0–360).
*/
function setheading(angle) {
if ( ! _check_number(angle, 'setheading', 'angle') ) { return; }
const turtle = _state.turtle;
const rotation = turtle.a - turtle.ua; // get rotation applied via rotate()
// set untransformed angle
turtle.ua = angle;
turtle.ua = _clean_angle(turtle.ua);
// set transformed angle as well
turtle.a = angle + rotation;
turtle.a = _clean_angle(turtle.a);
}
/**
* Turn the turtle to face a given point.
*
* @function face
* @param {number|Position} - The x-coordinate of the point to face or a {@link Position} object. The other parameter (<code>y</code>) is ignored, if a {@link Position} object is given.
* @param {number} [y] - The y-coordinate of the point to face.
*/
function face(x, y) {
({ x, y } = _to_point(x, y));
if ( ! _check_number(x, 'face', 'x') ) { return; }
if ( ! _check_number(y, 'face', 'y') ) { return; }
right( bearing(x, y) );
}
function _to_turtle(x, y, a, d) {
// TODO: maybe allow x as pos, y as angle, a as down
// allow [x, y, a, d] as first parameter
// needs to be tested first, cause arrays are of type 'object'
if (Array.isArray(x)) {
const arr = x;
x = arr.at(0);
y = arr.at(1);
a = arr.at(2);
d = arr.at(3);
}
// allow turtle object as first parameter
else if (isturtle(x)) {
const obj = x;
x = obj.x();
y = obj.y();
a = obj.heading();
d = obj.isdown();
}
// allow {x, y, a, d} as first parameter
else if (typeof x === 'object' && x !== null) {
const obj = x;
x = obj?.x;
y = obj?.y;
a = obj?.a;
d = obj?.d;
}
return { x, y, a, d };
}
/**
* Set the turtle's position, heading angle and/or pen state.
*
* @function setstate
* @param {number|State} x - The x-coordinate in pixels or a {@link State} object. The other parameters are ignored if a {@link State} object is given.
* @param {number} [y] - The y-coordinate in pixels.
* @param {number} [h] - The heading angle in degrees (0–360).
* @param {number} [d] - The pen down state, <code>true</code> for down, <code>false</code> for up.
*/
// TOOD: check new_turtle
function setstate(x, y, a, d) {
const new_turtle = _to_turtle(x, y, a, d);
setxy(new_turtle.x, new_turtle.y); // tolerates undefined
if ( Number.isFinite(new_turtle.a) ) { setheading(new_turtle.a); }
if ( typeof new_turtle.d === 'boolean' ) { pendown(new_turtle.d); }
}
_add_aliases_deprecated('setstate', ['setturtle']);
/**
* Reset the turtle's state.
* <br>
* Resets the turtles position, heading and pen position to its original state, at the center (x=0, y=0), facing up (heading 0) with the pen down.
* This doesn't cause a line to be drawn to the center.
*
* @function resetstate
* @see <code>{@link resetmatrix}</code> to reset transformations.
* @see <code>{@link reset}</code> to reset everything (both state and transformations).
*/
function resetstate() {
_state.turtle = _make_turtle_state(); // turtle state
// TODO: should this happen?
_state.turtle_stack = []; // turtle stack
}
_add_aliases_deprecated('resetstate', ['reset_turtle']);
/**
* Reset the turtle's transformation matrix.
*
* @function resetmatrix
* @see <code>{@link resetstate}</code> to reset state.
* @see <code>{@link reset}</code> to reset everything (both state and transformations).
*/
function resetmatrix() {
_state.matrix = mat3.create(); // transformation matrix
// TODO: should this happen?
_state.matrix_stack = []; // matrix stack
}
_add_aliases_deprecated('resetmatrix', ['reset_matrix']);
/**
* Completetly reset the turtle to its original state.
* <br>
* Resets the turtles position (to the center at x=0, y=0), heading (facing up, at heading 0) and pen (down). Also clears all transformations, that might have been applied. After this, the turtle is like new, like it was just created.
*
* @function reset
* @see <code>{@link resetstate}</code> to reset state only.
* @see <code>{@link resetmatrix}</code> to reset transformation only.
*/
function reset() {
resetstate();
resetmatrix();
}
/*********************************************************
Markings
*********************************************************/
/**
* Draw the turtle at its current position and heading.
*
* @function show
* @param {number} [size=15] Size of the drawn turtle in pixels (height from tip to base).
* @see {@link setturtlefunction} to customize drawing of the turtle.
*/
function show(size = 15) {
const top_angle = 36;
const height = size;
const diamond_size = size / 15;
const center = 2/3; // 0 (top) .. 1 (bottom) (2/3 = center of gravity)
const base_angle = (180 - top_angle) / 2;
const side = height / Math.cos(top_angle/2 / 360 * Math.PI * 2);
const base = 2 * height * Math.tan(top_angle/2 / 360 * Math.PI * 2);
const diamond_side = Math.sqrt(2) * diamond_size / 2;
pushstate();
pendown();
if (typeof _state.turtle_fn === 'function') {
_state.turtle_fn.call(undefined, size);
} else {
// center diamond
penup();
forward(diamond_size/2);
pendown();
right(135); // 180 - 45
forward(diamond_side);
right(90);
forward(diamond_side);
right(90);
forward(diamond_side);
right(90);
forward(diamond_side);
left(45);
// turtle
penup();
forward(height * center);
pendown();
right(180 - top_angle/2);
forward(side);
right(180 - base_angle);
forward(base);
right(180 - base_angle);
forward(side);
}
popstate();
}
_add_aliases_deprecated('show', ['turtle']);
/**
* Set a custom function that draws the turtle when using {@link show}.
* <br>
* To revert to the default turtle use omit the parameter: <code>setturtlefunction();</code>
*
* @function setturtlefunction
* @param {function} [fn] - Function that will be called to draw the turtle when using {@link show}. Omit to revert to the default turtle. The function will be called with a single parameter <code>size</code>, which contains the size used in the call to {@link show}. Before the function is called, the state of the turtle is saved and the pen is lowered. After the function is called, the turtle is returned to the saved state.
* @see {@link show}
*/
function setturtlefunction(fn) {
if (typeof fn === 'function') {
_state.turtle_fn = fn;
} else {
_state.turtle_fn = undefined;
}
}
/**
* Draw a small + at the turtle's current position independent of heading.
* <br>
* The orientation of the mark is independent of the turtle's current heading and can be specified with the <code>rotation</code> parameter.
*
* @function mark
* @param {number} [size=10] - Size of the mark in pixels.
* @param {number} [rotation=0] - Rotation of the mark in degrees (0–90). Set to 45 to draw an ✕.
* @see {@link setmarkfunction} to customize drawing of the mark.
*/
function mark(size = 10, rotation = 0) {
pushstate();
setheading(rotation);
pendown();
if (typeof _state.mark_fn === 'function') {
_state.mark_fn.call(undefined, size, rotation);
} else {
penup();
pushstate();
back(size/2);
pendown();
forward(size);
penup();
popstate();
right(90);
back(size/2);
pendown();
forward(size);
}
popstate();
}
/**
* Set a custom function that draws the mark when using {@link mark}.
* <br>
* To revert to the default mark omit the parameter: <code>setmarkfunction();</code>
*
* @function setmarkfunction
* @param {function} [fn] - Function that will be called to draw the mark when using {@link mark}. Omit to revert to the default mark. The function will be called with two parameters <code>size</code> and <code>rotation</code>, which contain the size and rotation used in the call to {@link mark}. Before the function is called the state of the turtle is saved, the heading is set to <code>rotation</code> and the pen is lowered. After the function is called, the turtle is returned to the saved state.
* @see {@link mark}
*/
function setmarkfunction(fn) {
if (typeof fn === 'function') {
_state.mark_fn = fn;
} else {
_state.mark_fn = undefined;
}
}
/*********************************************************
Util
*********************************************************/
/**
* Break out of a {@link repeat} or {@link foreach} loop.
* <br>
* Can only be used within a function given to {@link repeat} or {@link foreach}. Will immediately terminate the function and cause the loop to stop.
*
* @function breakout
* @see {@link repeat}
* @see {@link foreach}
*/
let _loop_count = 0; // count of loop callbacks (from repeat or foreach) that are currently in progress
const _break_exception = Symbol('Breakout Exception');
function breakout() {
if (_loop_count > 0) {
throw _break_exception;
} else {