-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine-main.js
executable file
·1804 lines (1532 loc) · 48.2 KB
/
engine-main.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
/**
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview Doodle game engine: Main entry point.
*
* @author sfdimino@google.com (Sophia Foster-Dimino) – graphics/animation
* @author mwichary@google.com (Marcin Wichary) – code
* @author jdtang@google.com (Jonathan Tang)
* @author khom@google.com (Kristopher Hom)
*/
/**
* Creates our game engine.
*/
engine.init = function() {
if (!document.getElementById(engine.BODY_GENERAL_EL_ID) ||
engine.initialized) {
return;
}
/**
* Whether the doodle has been initialized.
*/
engine.initialized = true;
/**
* Whether general debugging/development options are enabled via
* &debug CGI parameter. Please note that engine.debugAllowed needs
* to be enabled for this to work.
*/
engine.debugEnabled = false;
/**
* Whether to use sprites (true for production) or temporary raw standalone
* images (for development/debugging).
*/
engine.useSprites = true;
/**
* The number of the current scene (first scene = 0).
*/
engine.curSceneNo = null;
/**
* Current scene id as a string, e.g. 'level-2'.
*/
engine.curSceneId = null;
/**
* Current scene as an object.
*/
engine.curScene = null;
/**
* Whether the doodle is in the “attract mode” (on page load, prior to
* any interaction), or actual game play.
*/
engine.attractMode = true;
/**
* Whether the doodle is currently in the interactive state (awaiting
* input from the user) as opposed to non-interactive state (playing
* animations).
*/
engine.interactive = false;
/**
* Whether the doodle is currently asleep due to inactivity. We do it
* to conserve resources.
*/
engine.asleep = false;
/**
* If set to true, the next frame of the doodle will exit with no effect,
* stopping the animation. Use when we go to search results.
*/
engine.stopTicking = false;
/**
* Whether the tab with the doodle is currently focused.
*/
engine.tabFocused = true;
/**
* Whether the tab is currently visible (uses Visibility API).
*/
engine.tabVisible = true;
/**
* Are we currently fast forwarding?
*/
engine.fastForwarding = false;
/**
* The current count of logical ticks per physical ticks. Equals one
* for normal gameplay, can ramp up to engine.FAST_FORWARD_TICK_COUNT
* as necessary.
*/
engine.logicalTickCount = 1;
/**
* Whether the timer is currently ticking.
*/
engine.ticking = false;
/**
* As the doodle falls asleep or wakes up, we do not simply stop it, but
* slow it down or speed it up for a nicer effect. We use this multiplier
* to achieve that.
*/
engine.tickMultiplier = 1;
/**
* As the game slows down in preparation for falling asleep, we need to
* miss some of the ticks. This counts them.
*/
engine.missedTickCount = 0;
/**
* Whether the tooltip is currently shown. We need to know this, since
* showing the tooltip implicitly pauses the game.
*/
engine.tooltipShown = false;
/**
* Whether the tooltip is showing, but not yet shown (e.g. when the doodle
* is slowing down in preparation for it).
*/
engine.tooltipShowing = false;
/**
* Whether the doodle is paused/frozen, waiting for images. We try to
* preload images far in advance, but in case we fail, we have to pause
* the doodle, show a loading message, and wait for images to load.
*/
engine.waitingForImages = false;
/**
* Current game time (in milliseconds). In normal circumstances, game time
* progresses 1:1 with physical time, but this can change sometimes.
*/
engine.curGameTime = null;
/**
* Game time at the previous clock tick.
*/
engine.lastGameTime = null;
/**
* Last real (physical) clock time. Game time can diverge from physical
* clock time for example if the frame rate is too slow.
*/
engine.lastPhysicalTime = null;
/**
* Last time a user interacted with the doodle. (Used to put the doodle
* to sleep if nothing is happening).
*/
engine.lastInteractionTime = null;
/**
* Last time a user interacted with the doodle meaningfully – e.g.
* clicking on a button rather than just clicking somewhere random.
* This is used when we decide whether to show a hint or not.
*/
engine.lastMeaningfulInteractionTime = null;
/**
* Current frame rate.
*/
engine.curFps = 0;
/**
* Rolling/average frame rate (we measure it every 100 ticks).
*/
engine.rollingFps = 0;
/**
* Counting the ticks to measure the rolling frame rate.
*/
engine.rollingFpsTicks = 0;
/**
* Counting the frame rate sum that we later average over 100 ticks.
*/
engine.rollingFpsSum = 0;
/**
* If the doodle height is lower than the ultimate height (which is true
* when we start), we put an offset here so everything’s bottom-aligned.
*/
engine.bodyOffsetY = 0;
/**
* Current mouse position with respect to the viewport.
*/
engine.mouseX = 0;
engine.mouseY = 0;
/**
* Last time the mouse was moved (in game time).
*/
engine.lastMouseMoveTime = engine.curGameTime;
/**
* Last time the mouse was moved (in physical time).
*/
engine.lastMouseMovePhysicalTime = 0;
/**
* Whether we are currently using our custom (in-game) mouse pointer.
*/
engine.customMousePointer = false;
/**
* How much padding around click/touch elements (bigger for touch).
*/
engine.clickableElPadding = engine.PADDING_CLICK;
/**
* Global play count (=0 if the game is played for the first time). This
* is stored using HTML5 Web Storage and used to allow for fast forwarding,
* change the difficulty level, etc.
*/
engine.globalPlayCount = null;
/**
* Also stored using HTML5 Web Storage, this is the number of the last
* played scene. We’re not allowing to fast forward a scene you haven’t
* seen yet if you aborted the first game play.
*/
engine.lastReachedSceneNo = null;
/**
* A two-letter country code (defaults to English).
*/
engine.country = 'en';
/**
* Whether the rect ordering (by z-index) has become invalid and needs to
* be recalculated.
*/
engine.rectOrderInvalidated = true;
/**
* Whether the Shift key is pressed. Shift enables us to fast-forward
* (debugging/development only).
*/
engine.debugShiftPressed = false;
/** A list of all browser event listeners that have been added. */
engine.listeners = [];
engine.actors = {};
engine.actions = [];
engine.scenes = [];
engine.rects = [];
engine.detectFeatures();
engine.initCountry();
engine.readDebugParams();
engine.initLanguage();
// This is Lem-specific in lem-images.js
// TODO(mwichary): Separate it better.
if (engine.prepareImageSets) {
engine.prepareImageSets();
}
engine.initImages();
};
/**
* Unregisters the doodle, stopping its effect on the page, and clears
* after it.
*/
engine.destroy = function() {
engine.removeAllEventListeners();
$a('outside-explosions').undo();
for (var i in engine.actors) {
if (engine.actors[i].rect.attachedToDocumentBody) {
engine.actors[i].rect.removeDomElement();
}
}
engine.stopTicking = true;
};
/**
* Detect various browser features such as <canvas> or touch support.
*/
engine.detectFeatures = function() {
this.features = {};
// Whether the browser supports touch. We do not query for it, but change
// it later if we encounter touch events.
this.features.touch = false;
// Whether the browser supports hiding the mouse pointer.
// Unfortunately, Opera fails at this and I don’t know of a way to
// feature-detect it.
this.features.hidingMousePointer = false;
if (navigator.userAgent.indexOf('Opera/') == -1) {
var el = document.createElement('div');
el.style.cursor = 'none';
if (el.style.cursor == 'none') {
this.features.hidingMousePointer = true;
}
}
// Whether the browser supports <canvas>.
el = document.createElement('canvas');
this.features.canvas = !!(el.getContext && el.getContext('2d'));
if (this.features.canvas) {
// Even though <canvas> is available in earlier Operas, we enable it
// only for versions >= 10.5 since before it has terrible performance
// and bugs.
if (navigator.userAgent.indexOf('Opera/') != -1) {
this.features.canvas = false;
var match = navigator.userAgent.match(/Version\/([0-9]+).([0-9]+)/);
if (match && match[1] && match[2]) {
var versionMaj = parseInt(match[1], 10);
var versionMin = parseInt(match[2], 10);
if (versionMaj && versionMin) {
if ((versionMaj >= 11) ||
((versionMaj == 10) && (versionMin >= 50))) {
this.features.canvas = true;
}
}
}
}
// We disable <canvas> on Firefox for Linux because it typically is
// slower than DOM.
if ((navigator.userAgent.indexOf('Firefox/') != -1) &&
(navigator.userAgent.indexOf('Linux') != -1)) {
this.features.canvas = false;
}
}
// Whether the browser supports opacity natively.
if (navigator.userAgent.indexOf('MSIE 5.') != -1 ||
navigator.userAgent.indexOf('MSIE 6.') != -1 ||
navigator.userAgent.indexOf('MSIE 7.') != -1 ||
navigator.userAgent.indexOf('MSIE 8.') != -1) {
this.features.filterOpacity = true;
} else {
this.features.filterOpacity = false;
}
// Whether the browser is IE <= 8.
this.features.ie8OrLower = navigator.userAgent.indexOf('MSIE 5.') != -1 ||
navigator.userAgent.indexOf('MSIE 6.') != -1 ||
navigator.userAgent.indexOf('MSIE 7.') != -1 ||
navigator.userAgent.indexOf('MSIE 8.') != -1;
// Whether we’re running on a Mac.
if (navigator.userAgent.indexOf('Macintosh') != -1) {
this.features.imAMac = true;
} else {
this.features.imAMac = false;
}
// HTML5 Web Storage.
try {
this.features.webStorage = !!window.localStorage.getItem;
} catch (e) {
this.features.webStorage = false;
}
// Fixing old IE background caching bug that causes IE to reload images
// when used as backgrounds in CSS, even if they are already cached.
try {
document.execCommand('BackgroundImageCache', false, true);
} catch (e) {
}
};
/**
* Read debug parameters.
*/
engine.readDebugParams = function() {
engine.debug = {};
var url = window.location.href;
if (engine.debugAllowed) {
if ((url.indexOf('?doodle-debug') != -1) ||
(url.indexOf('&doodle-debug') != -1)) {
engine.debugEnabled = true;
}
if (engine.debugEnabled) {
if (url.indexOf('&doodle-force-canvas') != -1) {
engine.features.canvas = true;
}
if (url.indexOf('&doodle-force-dom') != -1) {
engine.features.canvas = false;
}
if (url.indexOf('&doodle-force-raw') != -1) {
engine.useSprites = false;
}
if (url.indexOf('&doodle-show-clickable') != -1) {
engine.debug.showClickable = true;
}
if (url.indexOf('&doodle-show-debug') != -1) {
engine.debug.showDebugPanel = true;
}
if (url.indexOf('&doodle-first-run') != -1) {
engine.globalPlayCount = 0;
engine.lastReachedSceneNo = 0;
}
if (url.indexOf('&doodle-half-run') != -1) {
engine.globalPlayCount = 0;
engine.lastReachedSceneNo = 3;
}
if (url.indexOf('&doodle-second-run') != -1) {
engine.globalPlayCount = 1;
engine.lastReachedSceneNo = 0;
}
if (url.indexOf('&doodle-old-run') != -1) {
engine.globalPlayCount = 999;
engine.lastReachedSceneNo = 999;
}
if (url.indexOf('&doodle-country=') != -1) {
var match = url.match(/\&doodle-country=([a-z]+)/);
if (match && match[1]) {
engine.country = match[1];
}
}
}
}
};
/**
* Prepare the image structures and preload the initial set of images
* necessary to play the non-interactive/attract-mode part of the doodle.
*/
engine.initImages = function() {
// How many images (either sprite sets or individual images if running
// in dev/debug mode) remain to be loaded.
this.imagesToBeLoaded = 0;
// Which images have been loaded.
this.loadedImageFiles = [];
// Which images are generally available (keyed off id).
this.imageSpriteIds = [];
for (var id in engine.IMAGE_SETS) {
var imageSet = engine.IMAGE_SETS[id];
for (var j in imageSet) {
this.imageSpriteIds[imageSet[j]] = id;
}
}
var introImageSetId = 'intro-' + this.country;
if (!engine.IMAGE_SETS[introImageSetId]) {
introImageSetId = 'intro';
}
this.preloadImageSet({ id: introImageSetId,
onLoad: this.initialResourcesLoaded });
};
/**
* Start the doodle once we have all the necessary resources (images) loaded.
*/
engine.initialResourcesLoaded = function() {
engine.initBody();
engine.initScenes();
engine.readProgress();
if (engine.debug.showDebugPanel) {
engine.initDebugPanel();
}
engine.addEventListeners();
engine.initTimer();
engine.startFirstScene();
};
/**
* Initialize language based on country we’re running in.
*/
engine.initCountry = function() {
if (this.standalone) {
// Prefer reading from #hl= over from domain. The hl can typically be
// more complicated (e.g. zh-TW), but Lem doesn’t support any of those
// anyway.
var match = window.location.hash.match(/[\&\?\#]hl=([a-z]+)/);
if (match && match[1]) {
this.country = match[1];
} else {
this.country = engine.DOMAIN_TO_LANGUAGE[window.location.hostname];
}
if (!this.country) {
this.country = 'en';
}
} else {
this.country = google.kHL;
}
};
/**
* Initialize language based on country we’re running in.
*/
engine.initLanguage = function() {
if (this.LANGUAGE_MAPPINGS[this.country]) {
this.country = this.LANGUAGE_MAPPINGS[this.country];
}
// Default to English in case we don’t know the country.
if (!this.LANGUAGES[this.country]) {
this.country = 'en';
}
this.language = this.LANGUAGES[this.country];
};
/**
* Init the timer and perform the first timer tick.
*/
engine.initTimer = function() {
this.minFramerateTime = 1000 / this.MIN_FPS;
this.maxFramerateTime = 1000 / this.MAX_FPS;
this.curGameTime = 0;
this.lastGameTime = this.curGameTime;
this.lastPhysicalTime = new Date().getTime();
this.interaction({ meaningful: true });
this.updateInactiveSleepTime();
this.nextTick();
};
/**
* Set the inactive sleep time (the time of inactivity after which the doodle
* will go to sleep to conserve CPU) depending on whether the doodle started
* playing, and whether the tab is focused. */
engine.updateInactiveSleepTime = function() {
if (engine.attractMode) {
engine.inactiveSleepTime = engine.INACTIVE_SLEEP_TIME_ATTRACT_MODE;
} else {
if (engine.tabFocused) {
engine.inactiveSleepTime = engine.INACTIVE_SLEEP_TIME_FOCUSED;
} else {
engine.inactiveSleepTime = engine.INACTIVE_SLEEP_TIME_UNFOCUSED;
}
}
};
/**
* Wake the doodle up if it’s been previously asleep.
*/
engine.wakeUp = function() {
engine.lastPhysicalTime = new Date().getTime();
engine.tickMultiplier = engine.SLOW_DOWN_TICK_MULTIPLIER;
engine.missedTickCount = 0;
engine.asleep = false;
engine.nextTick();
};
/**
* Run when the doodle is interacted with (mouse click, move, etc.)
* This prevents doodle from falling asleep.
* @param {Object} params
* - {boolean} .meaningful Whether an interaction is meaningful (e.g. makes
* sense rather than a mindless wasted click)
*/
engine.interaction = function(params) {
engine.lastInteractionTime = engine.curGameTime;
if (params && params.meaningful) {
engine.lastMeaningfulInteractionTime = engine.curGameTime;
}
if (engine.asleep) {
engine.wakeUp();
}
};
/**
* Schedule the next clock tick.
*/
engine.nextTick = function() {
if (!engine.ticking) {
engine.ticking = true;
engine.requestAnimFrame.call(window, engine.physicalTick);
}
};
/**
* Init the scenes; just copy the structure to the variable.
*/
engine.initScenes = function() {
for (var id in engine.SCENES) {
this.scenes[id] = engine.SCENES[id];
}
};
/**
* Get an actor given an id. If the actor was not present before, initialize
* it.
* @param {Object} params
* - {string} .id Actor id.
*/
engine.getActor = function(params) {
if (!engine.actors[params.id]) {
engine.actors[params.id] = new EngineActor(params.id);
if (engine.actors[params.id].init) {
engine.actors[params.id].init();
}
}
return engine.actors[params.id];
};
/**
* A short-hand function allowing to call $a('test') instead of
* engine.getActor({ id: 'test' }).
* @param {Object} params
* - {string} .id Actor id.
*/
function $a(id) {
return engine.getActor({ id: id });
}
/**
* Clears anything that’s originally in the doodle wrapper div. This includes
* the standalone image placeholder. We do it after we output the first
* frame to avoid blinking.
*/
engine.clearOldDoodleElements = function() {
var bodyChildren = engine.bodyGeneralEl.children;
for (var i = 0, el; el = bodyChildren[i]; i++) {
if (el.toBeRemoved) {
el.style.display = 'none';
}
}
};
/**
* Init the doodle body element, creating <canvas> if necessary.
*/
engine.initBody = function() {
this.bodyGeneralEl = document.getElementById(this.BODY_GENERAL_EL_ID);
// Prepare any elements inside the body tag to be removed later.
var bodyChildren = this.bodyGeneralEl.children;
for (var i = 0, el; el = bodyChildren[i]; i++) {
el.toBeRemoved = true;
}
this.needToClearOldDoodleElements = true;
if (this.standalone) {
engine.startDoodleBodyTop = 200;
engine.endDoodleBodyTop = 0;
} else {
engine.startDoodleBodyTop = 95;
engine.endDoodleBodyTop = 15;
}
this.bodyEl = document.createElement('div');
this.bodyEl.style.left = engine.LEFT_MARGIN + 'px';
this.bodyEl.style.top = engine.startDoodleBodyTop + 'px';
this.bodyEl.style.position = 'absolute';
this.bodyEl.style.overflow = 'hidden';
this.bodyEl.style.width = (this.INITIAL_WIDTH + this.TOOLBAR_WIDTH) + 'px';
this.bodyEl.style.height = this.INITIAL_HEIGHT + 'px';
// We want our element focusable so it could steal page focus… but we
// don’t want to indicate it in any way.
this.bodyEl.tabIndex = 1;
this.bodyEl.style.outline = 'none';
this.bodyEl.style.webkitTapHighlightColor = 'rgba(0, 0, 0, 0)';
this.bodyEl.hideFocus = true;
this.bodyOffsetY = this.EXPANDED_HEIGHT - this.INITIAL_HEIGHT;
this.bodyGeneralEl.appendChild(this.bodyEl);
/* Create the <canvas> element we’ll be drawing on if that’s available. */
if (this.features.canvas) {
this.canvasEl = document.createElement('canvas');
this.canvasEl.width = (this.INITIAL_WIDTH + this.TOOLBAR_WIDTH);
this.canvasEl.height = this.EXPANDED_HEIGHT;
this.canvasEl.style.position = 'absolute';
this.canvasEl.style.left = 0;
this.canvasEl.style.bottom = 0;
this.bodyEl.appendChild(this.canvasEl);
this.canvasCtx = this.canvasEl.getContext('2d');
}
this.readBodyPos();
};
/**
* Handle the visibility change event. If the page becomes invisible (e.g.
* the user selected another tab in the same window), make the doodle asleep
* immediately.
*/
engine.onVisibilityChange = function() {
var hidden = document.hidden || document.webkitHidden;
engine.tabVisible = !hidden;
if (!engine.tabVisible) {
engine.asleep = true;
} else {
if (engine.asleep) {
engine.wakeUp();
}
}
};
/**
* Recalculate some things (body position) when the viewport resizes.
*/
engine.onResize = function() {
engine.readBodyPos();
};
/**
* Handle the body scrolling: Update the mouse pointer to stay in place.
*/
engine.onScroll = function() {
engine.syncMousePointer();
};
/**
* Handle the body getting focused.
*/
engine.onBodyFocus = function() {
engine.tabFocused = true;
engine.updateInactiveSleepTime();
};
/**
* Handle the body losing focus.
*/
engine.onBodyBlur = function() {
engine.tabFocused = false;
engine.updateInactiveSleepTime();
};
/**
* Handle any touch start event on the doodle. If happening for the first
* time, make sure we know we’re on a touch device.
*/
engine.onTouchStart = function() {
if (!engine.features.touch) {
engine.features.touch = true;
engine.clickableElPadding = engine.PADDING_TOUCH;
$a('mouse-pointer').setVisible({ visible: false });
}
}
/**
* Add all the necessary event listeners.
*/
engine.addEventListeners = function() {
// Keyboard event listeners.
if (engine.debugEnabled) {
engine.addEventListener({
el: document.body, type: 'keydown', handler: engine.onKeyDown });
engine.addEventListener({
el: document.body, type: 'keyup', handler: engine.onKeyUp });
}
// Resize event listener. We need to recalculate the position of the
// doodle vis-a-vis viewport whenever the window is resized.
engine.addEventListener({
el: window, type: 'resize',
handler: engine.onResize });
// Scroll event listener, to know where the mouse pointer is.
engine.addEventListener({
el: window, type: 'scroll',
handler: engine.onScroll });
// Mouse move event listener
engine.addEventListener({
el: document.body, type: 'mousemove',
handler: engine.onMouseMove });
// Mouse down listener for the doodle element.
engine.addEventListener({
el: engine.bodyEl, type: 'mousedown',
handler: engine.onBodyMouseDown });
// Click listener for the entire website, used to dismiss a tooltip
// if one is present.
engine.addEventListener({
el: document.body, type: 'click',
handler: engine.onPageClick });
// Mouse up listener for the entire website (not just doodle element,
// because the mouse button can be down on the doodle, but then be dragged
// and released outside).
engine.addEventListener({
el: document.body, type: 'mouseup',
handler: engine.onPageMouseUp });
// Touch start/end events mirrored to mouse clicks.
engine.addEventListener({
el: engine.bodyEl, type: 'touchend',
handler: engine.onBodyMouseDown });
// A separate touch start event for the entire body for us to recognize
// we’re dealing with a touch device.
engine.addEventListener({
el: engine.bodyEl, type: 'touchstart',
handler: engine.onTouchStart });
// Visibility change listener (when the tab becomes visible or invisible –
// e.g. the user switches to another tab). We’re adding 'visibilitychange'
// aspirationally, since it doesn’t exist on anything else than WebKit
// today.
engine.addEventListener({
el: document, type: 'webkitvisibilitychange',
handler: engine.onVisibilityChange });
engine.addEventListener({
el: document, type: 'visibilitychange',
handler: engine.onVisibilityChange });
// Listeners to whether the page gets or loses focus.
engine.addEventListener({
el: window, type: 'focus',
handler: engine.onBodyFocus });
engine.addEventListener({
el: window, type: 'blur',
handler: engine.onBodyBlur });
};
/**
* Handle a key down event.
* @param {Event} e Window event.
*/
engine.onKeyDown = function(e) {
var event = engine.getDomEvent({ event: e });
switch (event.keyCode) {
case engine.KEY_SHIFT:
// Quick fast forward when you hold Shift (debug only).
engine.debugShiftPressed = true;
engine.preventDefaultEvent({ event: event });
break;
case engine.KEY_T:
// Simulate target hit in the third scene if you press T (debug only).
$a('babybot-cannon').targetHit();
engine.preventDefaultEvent({ event: event });
break;
case engine.KEY_N:
// Go to the next scene if you press N (debug only).
engine.goToNextScene();
engine.preventDefaultEvent({ event: event });
break;
}
engine.interaction();
};
/**
* Handle a key up event.
* @param {Event} e Window event.
*/
engine.onKeyUp = function(e) {
var event = engine.getDomEvent({ event: e });
engine.interaction();
switch (event.keyCode) {
case engine.KEY_SHIFT:
// Quick fast forward when you hold Shift (debug only).
engine.debugShiftPressed = false;
break;
}
};
/**
* Handle a mouse down event on the entire page.
* @param {Event} e Window event.
*/
engine.onPageClick = function(e) {
var event = engine.getDomEvent({ event: e });
if ($a('tooltip').rect.visible && !$a('tooltip').curPressed) {
$a('tooltip').hide();
engine.preventDefaultEvent({ event: event });
}
};
/**
* Handle a mouse down event on the doodle.
* @param {Event} e Window event.
*/
engine.onBodyMouseDown = function(e) {
var event = engine.getDomEvent({ event: e });
engine.interaction();
// Hide the hint, if visible.
$a('hints').hide();
// Cancel the event, so the user cannot drag/select items in the
// DOM rendering mode.
engine.preventDefaultEvent({ event: event });
// Change the mouse pointer to a click state.
$a('mouse-pointer').reactToMouseDown();
};
/**
* Handle a mouse up event on the entire page.
* @param {Event} e Window event.
*/
engine.onPageMouseUp = function(e) {
engine.interaction();
/* Change the mouse pointer to its previous state. */
$a('mouse-pointer').reactToMouseUp();
};
/**
* Update our custom mouse pointer to move it according to where the
* real mouse pointer is.
*/
engine.syncMousePointer = function() {
$a('mouse-pointer').sync();
};
/**
* Handle a mouse move event.
* @param {Event} e Window event.
*/
engine.onMouseMove = function(e) {
var event = engine.getDomEvent({ event: e });
engine.interaction();
engine.mouseX = event.clientX;
engine.mouseY = event.clientY;
// Only update the mouse visually when the game processed at least one
// physical tick; this prevents moving mouse pointer from firing too
// many transforms and slowing the entire game
if (engine.lastMouseMovePhysicalTime != engine.lastPhysicalTime) {
engine.syncMousePointer();
engine.lastMouseMovePhysicalTime = engine.lastPhysicalTime;
}
engine.lastMouseMoveTime = engine.curGameTime;
// If a bird was sitting on the mouse pointer, we should let it know,
// so it can fly away. :·)
// TODO(mwichary): Nasty that this is right here. We probably need to
// add on mouse move handler to actors.
if ($a('bird').landingOnMousePointer) {
$a('bird').abortLandingOnMousePointer();
}
};
/**
* Set the doodle in the interactive state (waiting for the user to do