-
Notifications
You must be signed in to change notification settings - Fork 25
/
jquery-turtle.js
11146 lines (10652 loc) · 370 KB
/
jquery-turtle.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
(function($) {
/*
jQuery-turtle
=============
version 2.0.9
jQuery-turtle is a jQuery plugin for turtle graphics.
With jQuery-turtle, every DOM element is a turtle that can be
moved using turtle graphics methods like fd (forward), bk (back),
rt (right turn), and lt (left turn). The pen function allows
a turtle to draw on a full-document canvas as it moves.
<pre>
$('#turtle').pen('red').rt(90).fd(100).lt(90).bk(50).fadeOut();
</pre>
jQuery-turtle provides:
* Relative and absolute motion and drawing.
* Functions to ease basic input, output, and game-making for beginners.
* Operations on sets of turtles, and turtle motion of arbitrary elements.
* Accurate collision-testing of turtles with arbitrary convex hulls.
* Simplified access to CSS3 transforms, jQuery animations, Canvas, and Web Audio.
* An interactive turtle console in either Javascript or CoffeeScript.
The plugin can also create a learning environment with a default
turtle that is friendly for beginners. The following is a complete
CoffeeScript program that uses the default turtle to draw a grid of
sixteen colored polygons.
<pre>
eval $.turtle() # Create the default turtle.
speed 100
for color in [red, gold, green, blue]
for sides in [3..6]
pen color
for x in [1..sides]
fd 100 / sides
lt 360 / sides
pen null
fd 40
slide 40, -160
</pre>
[Try an interactive demo (CoffeeScript syntax) here.](
http://davidbau.github.io/jquery-turtle/demo.html)
JQuery Methods for Turtle Movement
----------------------------------
The turtle API is briefly summarized below. All the following
turtle-oriented methods operate on any jQuery object (including
the default turtle, if used):
<pre>
$(q).fd(100) // Forward relative motion in local coordinates.
$(q).bk(50) // Back.
$(q).rt(90) // Right turn. Optional second arg is turning radius.
$(q).lt(45) // Left turn. Optional second arg is turning radius.
$(q).slide(x, y) // Move right by x while moving forward by y.
$(q).leap(x, y) // Like slide, but without drawing.
$(q).moveto({pageX:x,pageY:y} | [x,y]) // Absolute motion on page.
$(q).jumpto({pageX:x,pageY:y} | [x,y]) // Like moveto, without drawing.
$(q).turnto(direction || position) // Absolute direction adjustment.
$(q).play("ccgg") // Plays notes using ABC notation and waits until done.
// Methods below happen in an instant, but line up in the animation queue.
$(q).home() // Jumps to the center of the document, with direction 0.
$(q).pen('red') // Sets a pen style, or 'none' for no drawing.
$(q).pu() // Pen up - temporarily disables the pen (also pen(false)).
$(q).pd() // Pen down - starts a new pen path.
$(q).pe() // Uses the pen 'erase' style.
$(q).fill('gold') // Fills a shape previously outlined using pen('path').
$(q).dot(12) // Draws a circular dot of diameter 12. Color second arg.
$(q).label('A') // Prints an HTML label at the turtle location.
$(q).speed(10) // Sets turtle animation speed to 10 moves per sec.
$(q).ht() // Hides the turtle.
$(q).st() // Shows the turtle.
$(q).wear('blue') // Switches to a blue shell. Use any image or color.
$(q).scale(1.5) // Scales turtle size and motion by 150%.
$(q).twist(180) // Changes which direction is considered "forward".
$(q).mirror(true) // Flips the turtle across its main axis.
$(q).reload() // Reloads the turtle's image (restarting animated gifs)
$(q).done(fn) // Like $(q).promise().done(fn). Calls after all animation.
$(q).plan(fn) // Like each, but this is set to $(elt) instead of elt,
// and the callback fn can insert into the animation queue.
// Methods below this line do not queue for animation.
$(q).getxy() // Local (center-y-up [x, y]) coordinates of the turtle.
$(q).pagexy() // Page (topleft-y-down {pageX:x, pageY:y}) coordinates.
$(q).direction([p]) // The turtles absolute direction (or direction towards p).
$(q).distance(p) // Distance to p in page coordinates.
$(q).shown() // Shorthand for is(":visible")
$(q).hidden() // Shorthand for !is(":visible")
$(q).touches(y) // Collision tests elements (uses turtleHull if present).
$(q).inside(y)// Containment collision test.
$(q).nearest(pos) // Filters to item (or items if tied) nearest pos.
$(q).within(d, t) // Filters to items with centers within d of t.pagexy().
$(q).notwithin() // The negation of within.
$(q).cell(y, x) // Selects the yth row and xth column cell in a table.
</pre>
Speed and Turtle Animation
--------------------------
When the speed of a turtle is nonzero, the first nine movement
functions animate at that speed (in moves per second), and the
remaining mutators also participate in the animation queue. The
default turtle speed is a leisurely one move per second (as
appropriate for the creature), but you may soon discover the
desire to set speed higher.
Setting the turtle speed to Infinity will make its movement synchronous,
which makes the synchronous distance, direction, and hit-testing useful
for realtime game-making.
Pen and Fill Styles
-------------------
The turtle pen respects canvas styling: any valid strokeStyle is
accepted; and also using a css-like syntax, lineWidth, lineCap,
lineJoin, miterLimit, and fillStyle can be specified, e.g.,
pen('red;lineWidth:5;lineCap:square'). The same syntax applies for
styling dot and fill (except that the default interpretation for the
first value is fillStyle instead of strokeStyle).
The fill method is used by tracing an invisible path using the
pen('path') style, and then calling the fill method. Disconnected
paths can be created using pu() and pd().
Conventions for Musical Notes
-----------------------------
The play method plays a sequence of notes specified using a subset of
standard ABC notation. Capital C denotes middle C, and lowercase c is
an octave higher. Pitches and durations can be altered with commas,
apostrophes, carets, underscores, digits, and slashes as in the
standard. Enclosing letters in square brackets represents a chord,
and z represents a rest. The default tempo is 120, but can be changed
by passing a options object as the first parameter setting tempo, e.g.,
{ tempo: 200 }.
The turtle's motion will pause while it is playing notes. A single
tone can be played immediately (without participating in the
turtle animation queue) by using the "tone" method.
Planning Logic in the Animation Queue
-------------------------------------
The plan method can be used to queue logic (including synchronous
tests or actions) by running a function in the animation queue. Unlike
jquery queue(), plan arranges things so that if further animations
are queued by the callback function, they are inserted (in natural
recursive functional execution order) instead of being appended.
Turnto and Absolute Bearings
----------------------------
The turnto method can turn to an absolute direction (if called with a
single numeric argument) or towards an absolute position on the
screen. The methods moveto and turnto accept either page or
graphing coordinates.
Moveto and Two Flavors of Cartesian Coordinates
-----------------------------------------------
Graphing coordinates are measured upwards and rightwards from the
center of the page, and they are specified as bare numeric x, y
arguments or [x, y] pairs as returned from getxy().
Page coordinates are specified by an object with pageX and pageY
properties, or with a pagexy() method that will return such an object.
That includes, usefullly, mouse events and turtle objects. Page
coordinates are measured downward from the top-left corner of the
page to the center (or transform-origin) of the given object.
Hit Testing
-----------
The hit-testing functions touches() and inside() will test for
collisions using the convex hulls of the objects in question.
The hull of an element defaults to the bounding box of the element
(as transformed) but can be overridden by the turtleHull CSS property,
if present. The default turtle is given a turtle-shaped hull.
The touches() function can also test for collisions with a color
on the canvas - use touches('red'), for example, or for collsisions
with any nontransparent color, use touches('color').
Turtle Teaching Environment
---------------------------
A default turtle together with an interactive console are created by
calling eval($.turtle()). That call exposes all the turtle methods
such as (fd, rt, getxy, etc) as global functions operating on the default
turtle. It will also set up a number of other global symbols to provide
beginners with a simplified programming environment.
In detail, after eval($.turtle()):
* An <img id="turtle"> is created if #turtle doesn't already exist.
* An eval debugging panel (see.js) is shown at the bottom of the screen.
* Turtle methods on the default turtle are packaged as globals, e.g., fd(10).
* Every #id element is turned into a global variable: window.id = $('#id').
* Default turtle animation is set to 1 move per sec so steps can be seen.
* Global event listeners are created to update global event variables.
* Methods of $.turtle.* (enumerated below) are exposed as global functions.
* String constants are defined for the 140 named CSS colors.
Beyond the functions to control the default turtle, the globals added by
$.turtle() are as follows:
<pre>
lastclick // Event object of the last click event in the doc.
lastdblclick // The last double-click event.
lastmousemove // The last mousemove event.
lastmouseup // The last mouseup event.
lastmousedown // The last mousedown event.
keydown // The last keydown event.
keyup // The last keyup event.
keypress // The last keypress event.
hatch([n,] [img]) // Creates and returns n turtles with the given img.
cs() // Clears the screen, both the canvas and the body text.
cg() // Clears the graphics canvas without clearing the text.
ct() // Clears the text without clearing the canvas.
defaultspeed(mps) // Sets $.fx.speeds.turtle to 1000 / mps.
timer(secs, fn) // Calls back fn once after secs seconds.
tick([perSec,] fn) // Repeatedly calls fn at the given rate (null clears).
done(fn) // Calls back fn after all turtle animation is complete.
random(n) // Returns a random number [0..n-1].
random(n,m) // Returns a random number [n..m-1].
random(list) // Returns a random element of the list.
random('normal') // Returns a gaussian random (mean 0 stdev 1).
random('uniform') // Returns a uniform random [0...1).
random('position') // Returns a random {pageX:x, pageY:y} coordinate.
random('color') // Returns a random hsl(*, 100%, 50%) color.
random('gray') // Returns a random hsl(0, 0, *) gray.
remove() // Removes default turtle and its globals (fd, etc).
see(a, b, c...) // Logs tree-expandable data into debugging panel.
write(html) // Appends html into the document body.
type(plaintext) // Appends preformatted text into a pre in the document.
read([label,] fn) // Makes a one-time input field, calls fn after entry.
readnum([label,] fn) // Like read, but restricted to numeric input.
readstr([label,] fn) // Like read, but never converts input to a number.
button([label,] fn) // Makes a clickable button, calls fn when clicked.
menu(choices, fn) // Makes a clickable choice, calls fn when chosen.
table(m, n) // Outputs a table with m rows and n columns.
play('[DFG][EGc]') // Plays musical notes.
send(m, arg) // Sends an async message to be received by recv(m, fn).
recv(m, fn) // Calls fn once to receive one message sent by send.
</pre>
Here is another CoffeeScript example that demonstrates some of
the functions:
<pre>
eval $.turtle() # Create the default turtle and global functions.
speed Infinity
write "Catch blue before red gets you."
bk 100
r = new Turtle red
b = new Turtle blue
tick 10, ->
turnto lastmousemove
fd 6
r.turnto turtle
r.fd 4
b.turnto direction b
b.fd 3
if b.touches(turtle)
write "You win!"
tick off
else if r.touches(turtle)
write "Red got you!"
tick off
else if not b.inside(document)
write "Blue got away!"
tick off
</pre>
The turtle teaching environment is designed to work well with either
Javascript or CoffeeScript.
JQuery CSS Hooks for Turtle Geometry
------------------------------------
Underlying turtle motion are turtle-oriented 2d transform jQuery cssHooks,
with animation support on all motion:
<pre>
$(q).css('turtleSpeed', '10'); // speed in moves per second.
$(q).css('turtleEasing', 'linear'); // animation easing, defaults to swing.
$(q).css('turtlePosition', '30 40'); // position in local coordinates.
$(q).css('turtlePositionX', '30px'); // x component.
$(q).css('turtlePositionY', '40px'); // y component.
$(q).css('turtleRotation', '90deg'); // rotation in degrees.
$(q).css('turtleScale', '2'); // double the size of any element.
$(q).css('turtleScaleX', '2'); // x stretch after twist.
$(q).css('turtleScaleY', '2'); // y stretch after twist.
$(q).css('turtleTwist', '45deg'); // turn before stretching.
$(q).css('turtleForward', '50px'); // position in direction of rotation.
$(q).css('turtleTurningRadius, '50px');// arc turning radius for rotation.
$(q).css('turtlePenStyle', 'red'); // or 'red lineWidth 2px' etc.
$(q).css('turtlePenDown', 'up'); // default 'down' to draw with pen.
$(q).css('turtleHull', '5 0 0 5 0 -5');// fine-tune shape for collisions.
$(q).css('turtleTimbre', 'square'); // quality of the sound.
$(q).css('turtleVolume', '0.3'); // volume of the sound.
</pre>
Arbitrary 2d transforms are supported, including transforms of elements
nested within other elements that have css transforms. For example, arc
paths of a turtle within a skewed div will transform to the proper elliptical
arc. Note that while turtle motion is transformed, lines and dots are not:
for example, dots are always circular. To get transformed circles, trace
out an arc.
Transforms on the turtle itself are used to infer the turtle position,
direction, and rendering of the sprite. ScaleY stretches the turtle
sprite in the direction of movement also stretches distances for
motion in all directions. ScaleX stretches the turtle sprite perpendicular
to the direction of motion and also stretches line and dot widths for
drawing.
A canvas is supported for drawing, but only created when the pen is
used; pen styles include canvas style properties such as lineWidth
and lineCap.
A convex hull polygon can be set to be used by the collision detection
and hit-testing functions (inside, touches). The turtleHull is a list
of (unrotated) x-y coordinates relative to the object's transformOrigin.
If set to 'auto' (the default) the hull is just the bounding box for the
element.
License (MIT)
-------------
Copyright (c) 2013 David Bau
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//////////////////////////////////////////////////////////////////////////
// PREREQUISTIES
// Establish support for transforms in this browser.
//////////////////////////////////////////////////////////////////////////
var undefined = void 0,
global = this,
__hasProp = {}.hasOwnProperty,
rootjQuery = jQuery(function() {}),
interrupted = false,
async_pending = 0,
global_plan_depth = 0,
global_plan_queue = [];
function nonrecursive_dequeue(elem, qname) {
if (global_plan_depth > 5) {
global_plan_queue.push({elem: elem, qname: qname});
} else {
global_plan_depth += 1;
$.dequeue(elem, qname);
while (global_plan_queue.length > 0) {
var task = global_plan_queue.shift();
$.dequeue(task.elem, task.qname);
checkForHungLoop()
}
global_plan_depth -= 1;
}
}
function __extends(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
if (!$.cssHooks) {
throw("jQuery 1.4.3+ is needed for jQuery-turtle to work");
}
// Determine the name of the 'transform' css property.
function styleSupport(prop) {
var vendorProp, supportedProp,
capProp = prop.charAt(0).toUpperCase() + prop.slice(1),
prefixes = [ "Moz", "Webkit", "O", "ms" ],
div = document.createElement("div");
if (prop in div.style) {
supportedProp = prop;
} else {
for (var i = 0; i < prefixes.length; i++) {
vendorProp = prefixes[i] + capProp;
if (vendorProp in div.style) {
supportedProp = vendorProp;
break;
}
}
}
div = null;
$.support[prop] = supportedProp;
return supportedProp;
}
function hasGetBoundingClientRect() {
var div = document.createElement("div"),
result = ('getBoundingClientRect' in div);
div = null;
return result;
}
var transform = styleSupport("transform"),
transformOrigin = styleSupport("transformOrigin");
if (!transform || !hasGetBoundingClientRect()) {
// Need transforms and boundingClientRects to support turtle methods.
return;
}
// An options string looks like a (simplified) CSS properties string,
// of the form prop:value;prop:value; etc. If defaultProp is supplied
// then the string can begin with "value" (i.e., value1;prop:value2)
// and that first value will be interpreted as defaultProp:value1.
// Some rudimentary quoting can be done, e.g., value:"prop", etc.
function parseOptionString(str, defaultProp) {
if (typeof(str) != 'string') {
if (str == null) {
return {};
}
if ($.isPlainObject(str)) {
return str;
}
str = '' + str;
}
// Each token is an identifier, a quoted or parenthesized string,
// a run of whitespace, or any other non-matching character.
var token = str.match(/[-a-zA-Z_][-\w]*|"[^"]*"|'[^']'|\([^()]*\)|\s+|./g),
result = {}, j, t, key = null, value, arg,
seencolon = false, vlist = [], firstval = true;
// While parsing, commitvalue() validates and unquotes a prop:value
// pair and commits it to the result.
function commitvalue() {
// Trim whitespace
while (vlist.length && /^\s/.test(vlist[vlist.length - 1])) { vlist.pop(); }
while (vlist.length && /^\s/.test(vlist[0])) { vlist.shift(); }
if (vlist.length == 1 && (
/^".*"$/.test(vlist[0]) || /^'.*'$/.test(vlist[0]))) {
// Unquote quoted string.
value = vlist[0].substr(1, vlist[0].length - 2);
} else if (vlist.length == 2 && vlist[0] == 'url' &&
/^(.*)$/.test(vlist[1])) {
// Remove url(....) from around a string.
value = vlist[1].substr(1, vlist[1].length - 2);
} else {
// Form the string for the value.
arg = vlist.join('');
// Convert the value to a number if it looks like a number.
if (arg == "") {
value = arg;
} else if (isNaN(arg)) {
value = arg;
} else {
value = Number(arg);
}
}
// Deal with a keyless first value.
if (!seencolon && firstval && defaultProp && vlist.length) {
// value will already have been formed.
key = defaultProp;
}
if (key) {
result[key] = value;
}
}
// Now the parsing: just iterate through all the tokens.
for (j = 0; j < token.length; ++j) {
t = token[j];
if (!seencolon) {
// Before a colon, remember the first identifier as the key.
if (!key && /^[a-zA-Z_-]/.test(t)) {
key = t;
}
// And also look for the colon.
if (t == ':') {
seencolon = true;
vlist.length = 0;
continue;
}
}
if (t == ';') {
// When a semicolon is seen, form the value and save it.
commitvalue();
// Then reset the parsing state.
key = null;
vlist.length = 0;
seencolon = false;
firstval = false;
continue;
}
// Accumulate all tokens into the vlist.
vlist.push(t);
}
commitvalue();
return result;
}
// Prints a map of options as a parsable string.
// The inverse of parseOptionString.
function printOptionAsString(obj) {
var result = [];
function quoted(s) {
if (/[\s;]/.test(s)) {
if (s.indexOf('"') < 0) {
return '"' + s + '"';
}
return "'" + s + "'";
}
return s;
}
for (var k in obj) if (obj.hasOwnProperty(k)) {
result.push(k + ':' + quoted(obj[k]) + ';');
}
return result.join(' ');
}
//////////////////////////////////////////////////////////////////////////
// MATH
// 2d matrix support functions.
//////////////////////////////////////////////////////////////////////////
function identity(x) { return x; }
// Handles both 2x2 and 2x3 matrices.
function matrixVectorProduct(a, v) {
var r = [a[0] * v[0] + a[2] * v[1], a[1] * v[0] + a[3] * v[1]];
if (a.length == 6) {
r[0] += a[4];
r[1] += a[5];
}
return r;
}
// Multiplies 2x2 or 2x3 matrices.
function matrixProduct(a, b) {
var r = [
a[0] * b[0] + a[2] * b[1],
a[1] * b[0] + a[3] * b[1],
a[0] * b[2] + a[2] * b[3],
a[1] * b[2] + a[3] * b[3]
];
var along = (a.length == 6);
if (b.length == 6) {
r.push(a[0] * b[4] + a[2] * b[5] + (along ? a[4] : 0));
r.push(a[1] * b[4] + a[3] * b[5] + (along ? a[5] : 0));
} else if (along) {
r.push(a[4]);
r.push(a[5]);
}
return r;
}
function nonzero(e) {
// Consider zero any deviations less than one in a trillion.
return Math.abs(e) > 1e-12;
}
function isone2x2(a) {
return !nonzero(a[1]) && !nonzero(a[2]) &&
!nonzero(1 - a[0]) && !nonzero(1 - a[3]);
}
function inverse2x2(a) {
if (isone2x2(a)) { return [1, 0, 0, 1]; }
var d = decomposeSVD(a);
// Degenerate matrices have no inverse.
if (!nonzero(d[2])) return null;
return matrixProduct(
rotation(-(d[3])), matrixProduct(
scale(1/d[1], 1/d[2]),
rotation(-(d[0]))));
}
// By convention, a 2x3 transformation matrix has a 2x2 transform
// in the first four slots and a 1x2 translation in the last two slots.
// The array [a, b, c, d, e, f] is shorthand for the following 3x3
// matrix where the upper-left 2x2 is an in-place transform, and the
// upper-right vector [e, f] is the translation.
//
// [a c e] The inverse of this 3x3 matrix can be formed by
// [b d f] figuring the inverse of the 2x2 upper-left corner
// [0 0 1] (call that Ai), and then negating the upper-right vector
// (call that -t) and then forming Ai * (-t).
//
// [ A t] (if Ai is the inverse of A) [ Ai Ai*(-t) ]
// [0 0 1] --- invert ---> [ 0 0 1 ]
//
// The result is of the same form, and can be represented as an array
// of six numbers.
function inverse2x3(a) {
var ai = inverse2x2(a);
if (a.length == 4) return ai;
var nait = matrixVectorProduct(ai, [-a[4], -a[5]]);
ai.push(nait[0]);
ai.push(nait[1]);
return ai;
}
function rotation(theta) {
var c = Math.cos(theta),
s = Math.sin(theta);
return [c, s, -s, c];
}
function scale(sx, sy) {
if (arguments.length == 1) { sx = sy; }
return [sx, 0, 0, sy];
}
function addVector(v, a) {
return [v[0] + a[0], v[1] + a[1]];
}
function subtractVector(v, s) {
return [v[0] - s[0], v[1] - s[1]];
}
function scaleVector(v, s) {
return [v[0] * s, v[1] * s];
}
function translatedMVP(m, v, origin) {
return addVector(matrixVectorProduct(m, subtractVector(v, origin)), origin);
}
// decomposeSVD:
//
// Decomposes an arbitrary 2d matrix into a rotation, an X-Y scaling,
// and a prescaling rotation (which we call a "twist"). The prescaling
// rotation is only nonzero when there is some skew (i.e, a stretch that
// does not preserve rectilinear angles in the source).
//
// This decomposition is stable, which means that the product of
// the three components is always within near machine precision
// (about ~1e-15) of the original matrix.
//
// Input: [m11, m21, m12, m22] in column-first order.
// Output: [rotation, scalex, scaley, twist] with rotations in radians.
//
// The decomposition is the unique 2d SVD permuted to fit the contraints:
// * twist is between +- pi/4
// * rotation is between +- pi/2
// * scalex + scaley >= 0.
function decomposeSVD(m) {
var // Compute M*M
mtm0 = m[0] * m[0] + m[1] * m[1],
mtm12 = m[0] * m[2] + m[1] * m[3],
mtm3 = m[2] * m[2] + m[3] * m[3],
// Compute right-side rotation.
phi = -0.5 * Math.atan2(mtm12 * 2, mtm0 - mtm3),
v0 = Math.cos(phi),
v1 = Math.sin(phi), // [v0 v1 -v1 v0]
// Compute left-side rotation.
mvt0 = (m[0] * v0 - m[2] * v1),
mvt1 = (m[1] * v0 - m[3] * v1),
theta = Math.atan2(mvt1, mvt0),
u0 = Math.cos(theta),
u1 = Math.sin(theta), // [u0 u1 -u1 u0]
// Compute the singular values. Notice by computing in this way,
// the sign is pushed into the smaller singular value.
sv2c = (m[1] * v1 + m[3] * v0) * u0 - (m[0] * v1 + m[2] * v0) * u1,
sv1c = (m[0] * v0 - m[2] * v1) * u0 + (m[1] * v0 - m[3] * v1) * u1,
sv1, sv2;
// Put phi between -pi/4 and pi/4.
if (phi < -Math.PI / 4) {
phi += Math.PI / 2;
sv2 = sv1c;
sv1 = sv2c;
theta -= Math.PI / 2;
} else {
sv1 = sv1c;
sv2 = sv2c;
}
// Put theta between -pi and pi.
if (theta > Math.PI) { theta -= 2 * Math.PI; }
return [theta, sv1, sv2, phi];
}
// approxBezierUnitArc:
// Returns three bezier curve control points that approximate
// a a unit circle arc from angle a1 to a2 (not including the
// beginning point, which would just be at cos(a1), sin(a1)).
// For a discussion and derivation of this formula,
// google [riskus approximating circular arcs]
function approxBezierUnitArc(a1, a2) {
var a = (a2 - a1) / 2,
x4 = Math.cos(a),
y4 = Math.sin(a),
x1 = x4,
y1 = -y4,
q2 = 1 + x1 * x4 + y1 * y4,
d = (x1 * y4 - y1 * x4),
k2 = d && (4/3 * (Math.sqrt(2 * q2) - q2) / d),
x2 = x1 - k2 * y1,
y2 = y1 + k2 * x1,
x3 = x2,
y3 = -y2,
ar = a + a1,
car = Math.cos(ar),
sar = Math.sin(ar);
return [
[x2 * car - y2 * sar, x2 * sar + y2 * car],
[x3 * car - y3 * sar, x3 * sar + y3 * car],
[Math.cos(a2), Math.sin(a2)]
];
}
//////////////////////////////////////////////////////////////////////////
// CSS TRANSFORMS
// Basic manipulation of 2d CSS transforms.
//////////////////////////////////////////////////////////////////////////
function getElementTranslation(elem) {
var ts = readTurtleTransform(elem, false);
if (ts) { return [ts.tx, ts.ty]; }
var m = readTransformMatrix(elem);
if (m) { return [m[4], m[5]]; }
return [0, 0];
}
// Reads out the 2x3 transform matrix of the given element.
function readTransformMatrix(elem) {
var ts = (global.getComputedStyle ?
global.getComputedStyle(elem)[transform] :
$.css(elem, 'transform'));
if (!ts || ts === 'none') {
return null;
}
// Quick exit on the explicit matrix() case:
var e =/^matrix\(([\-+.\de]+),\s*([\-+.\de]+),\s*([\-+.\de]+),\s*([\-+.\de]+),\s*([\-+.\de]+)(?:px)?,\s*([\-+.\de]+)(?:px)?\)$/.exec(ts);
if (e) {
return [parseFloat(e[1]), parseFloat(e[2]), parseFloat(e[3]),
parseFloat(e[4]), parseFloat(e[5]), parseFloat(e[6])];
}
// Interpret the transform string.
return transformStyleAsMatrix(ts);
}
// Reads out the css transformOrigin property, if present.
function readTransformOrigin(elem, wh) {
var hidden = ($.css(elem, 'display') === 'none'),
swapout, old, name;
if (hidden) {
// IE GetComputedStyle doesn't give pixel values for transformOrigin
// unless the element is unhidden.
swapout = { position: "absolute", visibility: "hidden", display: "block" };
old = {};
for (name in swapout) {
old[name] = elem.style[name];
elem.style[name] = swapout[name];
}
}
var gcs = (global.getComputedStyle ? global.getComputedStyle(elem) : null);
if (hidden) {
for (name in swapout) {
elem.style[name] = old[name];
}
}
var origin = (gcs && gcs[transformOrigin] || $.css(elem, 'transformOrigin'));
if (origin && origin.indexOf('%') < 0) {
return $.map(origin.split(' '), parseFloat);
}
if (wh) {
return [wh[0] / 2, wh[1] / 2];
}
var sel = $(elem);
return [sel.width() / 2, sel.height() / 2];
}
// Composes all the 2x2 transforms up to the top.
function totalTransform2x2(elem) {
var result = [1, 0, 0, 1], t;
while (elem !== null) {
t = readTransformMatrix(elem);
if (t && !isone2x2(t)) {
result = matrixProduct(t, result);
}
elem = elem.parentElement;
}
return result.slice(0, 4);
}
// Applies the css 2d transforms specification.
function transformStyleAsMatrix(transformStyle) {
// Deal with arbitrary transforms:
var result = [1, 0, 0, 1], ops = [], args = [],
pat = /(?:^\s*|)(\w*)\s*\(([^)]*)\)\s*/g,
unknown = transformStyle.replace(pat, function(m) {
ops.push(m[1].toLowerCase());
args.push($.map(m[2].split(','), function(s) {
var v = s.trim().toLowerCase();
return {
num: parseFloat(v),
unit: v.replace(/^[+-.\de]*/, '')
};
}));
return '';
});
if (unknown) { return null; }
for (var index = ops.length - 1; index >= 0; --index) {
var m = null, a, c, s, t;
var op = ops[index];
var arg = args[index];
if (op == 'matrix') {
if (arg.length >= 6) {
m = [arg[0].num, arg[1].num, arg[2].num, arg[3].num,
arg[4].num, arg[5].num];
}
} else if (op == 'rotate') {
if (arg.length == 1) {
a = convertToRadians(arg[0]);
c = Math.cos(a);
s = Math.sin(a);
m = [c, -s, c, s];
}
} else if (op == 'translate' || op == 'translatex' || op == 'translatey') {
var tx = 0, ty = 0;
if (arg.length >= 1) {
if (arg[0].unit && arg[0].unit != 'px') { return null; } // non-pixels
if (op == 'translate' || op == 'translatex') { tx = arg[0].num; }
else if (op == 'translatey') { ty = arg[0].num; }
if (op == 'translate' && arg.length >= 2) {
if (arg[1].unit && arg[1].unit != 'px') { return null; }
ty = arg[1].num;
}
m = [0, 0, 0, 0, tx, ty];
}
} else if (op == 'scale' || op == 'scalex' || op == 'scaley') {
var sx = 1, sy = 1;
if (arg.length >= 1) {
if (op == 'scale' || op == 'scalex') { sx = arg[0].num; }
else if (op == 'scaley') { sy = arg[0].num; }
if (op == 'scale' && arg.length >= 2) { sy = arg[1].num; }
m = [sx, 0, 0, sy, 0, 0];
}
} else if (op == 'skew' || op == 'skewx' || op == 'skewy') {
var kx = 0, ky = 0;
if (arg.length >= 1) {
if (op == 'skew' || op == 'skewx') {
kx = Math.tan(convertToRadians(arg[0]));
} else if (op == 'skewy') {
ky = Math.tan(convertToRadians(arg[0]));
}
if (op == 'skew' && arg.length >= 2) {
ky = Math.tan(convertToRadians(arg[0]));
}
m = [1, ky, kx, 1, 0, 0];
}
} else {
// Unrecgonized transformation.
return null;
}
result = matrixProduct(result, m);
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// ABSOLUTE PAGE POSITIONING
// Dealing with the element origin, rectangle, and direction on the page,
// taking into account nested parent transforms.
//////////////////////////////////////////////////////////////////////////
function limitMovement(start, target, limit) {
if (limit <= 0) return start;
var distx = target.pageX - start.pageX,
disty = target.pageY - start.pageY,
dist2 = distx * distx + disty * disty;
if (limit * limit >= dist2) {
return target;
}
var frac = limit / Math.sqrt(dist2);
return {
pageX: start.pageX + frac * distx,
pageY: start.pageY + frac * disty
};
}
function limitRotation(start, target, limit) {
if (limit <= 0) { target = start; }
else if (limit < 180) {
var delta = normalizeRotation(target - start);
if (delta > limit) { target = start + limit; }
else if (delta < -limit) { target = start - limit; }
}
return normalizeRotation(target);
}
function getRoundedCenterLTWH(x0, y0, w, h) {
return { pageX: Math.floor(x0 + w / 2), pageY: Math.floor(y0 + h / 2) };
}
function getStraightRectLTWH(x0, y0, w, h) {
var x1 = x0 + w, y1 = y0 + h;
return [
{ pageX: x0, pageY: y0 },
{ pageX: x0, pageY: y1 },
{ pageX: x1, pageY: y1 },
{ pageX: x1, pageY: y0 }
];
}
function cleanedStyle(trans) {
// Work around FF bug: the browser generates CSS transforms with nums
// with exponents like 1e-6px that are not allowed by the CSS spec.
// And yet it doesn't accept them when set back into the style object.
// So $.swap doesn't work in these cases. Therefore, we have a cleanedSwap
// that cleans these numbers before setting them back.
if (!/e[\-+]/.exec(trans)) {
return trans;
}
var result = trans.replace(/(?:\d+(?:\.\d*)?|\.\d+)e[\-+]\d+/g, function(e) {
return cssNum(parseFloat(e)); });
return result;
}
// Returns the turtle's origin (the absolute location of its pen and
// center of rotation when no transforms are applied) in page coordinates.
function getTurtleOrigin(elem, inverseParent, extra) {
var state = $.data(elem, 'turtleData');
if (state && state.quickhomeorigin && state.down && state.style && !extra
&& elem.classList && elem.classList.contains('turtle')) {
return state.quickhomeorigin;
}
var hidden = ($.css(elem, 'display') === 'none'),
swapout = hidden ?
{ position: "absolute", visibility: "hidden", display: "block" } : {},
substTransform = swapout[transform] = (inverseParent ? 'matrix(' +
$.map(inverseParent, cssNum).join(', ') + ', 0, 0)' : 'none'),
old = {}, name, gbcr, transformOrigin;
for (name in swapout) {
old[name] = elem.style[name];
elem.style[name] = swapout[name];
}
gbcr = getPageGbcr(elem);
transformOrigin = readTransformOrigin(elem, [gbcr.width, gbcr.height]);
for (name in swapout) {
elem.style[name] = cleanedStyle(old[name]);
}
if (extra) {
extra.gbcr = gbcr;
extra.localorigin = transformOrigin;
}
var result = addVector([gbcr.left, gbcr.top], transformOrigin);
if (state && state.down && state.style) {
state.quickhomeorigin = result;
}
return result;
}
function wh() {
// Quirks-mode compatible window height.
return global.innerHeight || $(global).height();
}
function ww() {
// Quirks-mode compatible window width.
return global.innerWidth || $(global).width();
}
function dh() {
return document.body ? $(document).height() : document.height;
}
function dw() {
return document.body ? $(document).width() : document.width;
}