Up-in-the-Air – blob

You can use Git to clone the repository via the web URL. Download snapshot (zip)
efa8d0b9bd4826f9d09bb49242b047cf0fd75fa8
[Up-in-the-Air] /
1 "use strict";
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 /**
4  * Up in the Air
5  * – a browser game created for FediJam 2024 –
6  * https://fietkau.media/up_in_the_air
7  *
8  * Copyright (c) Julian Fietkau
9  * See README.txt for details.
10  *
11  *******************************************************************************
12  *
13  * This program is free software: you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation, either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  *
26  */
28 import * as THREE from 'three';
29 import { FontLoader } from 'three/addons/loaders/FontLoader.js';
30 import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
33 window['startUpInTheAirGame'] = (game) => {
35 if(!game.hasOwnProperty('deploymentOptions')) {
36   game['deploymentOptions'] = {};
37 }
38 const deploymentDefaults = {
39   'assetUrlPrefix': '',
40 };
41 for(let k in deploymentDefaults) {
42   if(!game['deploymentOptions'].hasOwnProperty(k)) {
43     game['deploymentOptions'][k] = deploymentDefaults[k];
44   }
45 }
47 game['fn'] = {};
49 game['fn'].playRandomSound = () => {
50   if(!game.view || !game.view.audioListener) {
51     return;
52   }
53   if(!game.view.lastSoundsCache) {
54     game.view.lastSoundsCache = [];
55   }
56   let index;
57   // We remember the last two notes played and make sure not to repeat one of those.
58   do {
59     index = 1 + Math.floor(Math.random() * 5);
60   } while(game.view.lastSoundsCache.includes(index));
61   game.view.lastSoundsCache.push(index);
62   if(game.view.lastSoundsCache.length > 2) {
63     game.view.lastSoundsCache.splice(0, 1);
64   }
65   let sound = new THREE.Audio(game.view.audioListener);
66   sound.setBuffer(game.assets['audio']['sound' + index + '-' + game.settings['audio']['theme']]);
67   sound.setVolume(game.settings['audio']['sounds']);
68   if(!game.view.muted && game.settings['audio']['sounds'] > 0) {
69     sound.play();
70   }
71 }
73 game['fn'].easeInOut = (val) => {
74   return -0.5 * Math.cos(val * Math.PI) + 0.5;
75 }
77 game['fn'].lerp = (start, end, progress) => {
78   return (1.0 - progress) * start + progress * end;
79 }
81 game['fn'].loadAllAssets = (renderProgressCallback) => {
82   game.assets = {};
83   game.assets.words = {
84     'thanks': ['thank you', 'thanks'],
85     'sorry': ['sorry', 'apologize'],
86     'emotion': ['blessed', 'fortunate', 'glad', 'happy', 'joyous', 'lucky', 'overjoyed', 'thankful'],
87     'verb_general': ['adore', 'appreciate', 'cherish', 'enjoy', 'like', 'love', 'treasure', 'value'],
88     'verb_person': ['admire', 'honor', 'love', 'respect', 'treasure', 'value'],
89     'trait': ['amazing', 'compassionate', 'delightful', 'genuine', 'generous', 'incredible', 'joyful', 'kind', 'passionate', 'patient', 'principled', 'refreshing', 'sweet'],
90   };
91   game.assets.wordList = [...new Set([].concat.apply([], Object.values(game.assets.words)))]; // no need to be sorted
92   game.assets.sentences = [
93     '{thanks} for always listening.',
94     '{thanks} for being there.',
95     '{thanks} for helping me when I needed it most.',
96     '{thanks} for being with me.',
97     '{thanks} for believing in me.',
98     '{thanks} for not giving up.',
99     '{thanks} for believing in me when I myself couldn’t.',
100     '{thanks} for standing by my side.',
101     '{sorry} for what I said.',
102     '{sorry} for not being there.',
103     '{sorry} for forgetting.',
104     '{sorry} for not telling you.',
105     '{sorry} for what I did.',
106     '{sorry} for back then.',
107     '{sorry} for not being honest.',
108     'Just being around you makes me feel {emotion}.',
109     'I have no words for how {emotion} you make me feel.',
110     'I always feel {emotion} in your presence.',
111     'I’m honestly {emotion}.',
112     'I feel {emotion} just for knowing you.',
113     'Every moment with you makes me feel {emotion}.',
114     'I {verb_person} you.',
115     'I {verb_person} you more than anything.',
116     'I deeply {verb_person} you.',
117     'I honestly {verb_person} you.',
118     'I really do {verb_person} you.',
119     'I {verb_general} every moment with you.',
120     'I {verb_general} the way you see the world.',
121     'I {verb_general} you the way you are.',
122     'I {verb_general} how {trait} you are.',
123     'I {verb_general} how {trait} you are.',
124     'I {verb_general} how {trait} you are.',
125     'I always {verb_general} how {trait} you are.',
126     'I deeply {verb_general} how {trait} you are.',
127     'Thinking about how {trait} you are always improves my mood.',
128     'You are the most {trait} person I know.',
129     'You are the most {trait} person I know.',
130     'Your {trait} personality always makes my day.',
131     'Your {trait} personality is my sunshine.',
132     'Your {trait} personality gives me strength.',
133     'I’m astonished how {trait} you are.',
134     'I hope I can learn to be as {trait} as you.',
135   ];
136   return new Promise((resolve, reject) => {
137     let todoList = {
138       'audio/wind.ogg': 72482,
139       'fonts/cookie.json': 37866,
140       'textures/cloud0a.png': 568,
141       'textures/cloud0b.png': 569,
142       'textures/cloud0c.png': 568,
143       'textures/cloud1a.png': 6932,
144       'textures/cloud1b.png': 6932,
145       'textures/cloud1c.png': 6933,
146       'textures/cloud2a.png': 4365,
147       'textures/cloud2b.png': 4364,
148       'textures/cloud2c.png': 4365,
149       'textures/cloud3a.png': 4000,
150       'textures/cloud3b.png': 3999,
151       'textures/cloud3c.png': 4001,
152       'textures/cloud4a.png': 3183,
153       'textures/cloud4b.png': 3182,
154       'textures/cloud4c.png': 3184,
155       'textures/cloud5a.png': 2066,
156       'textures/cloud5b.png': 2065,
157       'textures/cloud5c.png': 2066,
158       'textures/feather-black.png': 1026,
159       'textures/feather-blue.png': 1026,
160       'textures/feather-brown.png': 1027,
161       'textures/feather-green.png': 1028,
162       'textures/feather-orange.png': 1028,
163       'textures/feather-purple.png': 1028,
164       'textures/feather-red.png': 1024,
165       'textures/highcontrast-backdrop.png': 500,
166       'textures/pinwheel.png': 904,
167       'textures/house-day-1.png': 17819,
168       'textures/house-day-2.png': 598,
169       'textures/house-day-3.png': 646,
170       'textures/house-evening-1.png': 16939,
171       'textures/house-evening-2.png': 597,
172       'textures/house-evening-3.png': 646,
173     };
174     for(let unlockable of game.settings['unlocks']) {
175       if(unlockable == 'golden') {
176         todoList['textures/feather-golden.png'] = 1027;
177       } else if(unlockable == 'ghost') {
178         todoList['textures/feather-ghost.png'] = 1023;
179       } else {
180         let unlock = game['fn'].unlockWithKey('NIbp2kW5' + unlockable + 'e2ZDFl5Y');
181         if(unlock && unlock['type'] == 'feather') {
182           todoList['data:textures/feather-' + unlock['name']] = unlock['url'];
183         }
184       }
185     }
186     game.assets.audiothemes = [];
187     const audioThemes = {
188       'classical': [1636930, 34002, 34629, 25399, 16426, 26122],
189     }
190     for(let theme of Object.keys(audioThemes)) {
191       todoList['audio/music-' + theme + '.ogg'] = audioThemes[theme][0];
192       todoList['audio/sound1-' + theme + '.ogg'] = audioThemes[theme][1];
193       todoList['audio/sound2-' + theme + '.ogg'] = audioThemes[theme][2];
194       todoList['audio/sound3-' + theme + '.ogg'] = audioThemes[theme][3];
195       todoList['audio/sound4-' + theme + '.ogg'] = audioThemes[theme][4];
196       todoList['audio/sound5-' + theme + '.ogg'] = audioThemes[theme][5];
197       game.assets.audiothemes.push(theme);
198     }
199     let total = Object.keys(todoList).filter(k => !k.startsWith('data:')).map(k => todoList[k]).reduce((a, b) => a + b, 0);
200     let progress = {};
201     const loader = {
202       'audio': new THREE.AudioLoader(),
203       'fonts': new FontLoader(),
204       'textures': new THREE.TextureLoader(),
205     };
206     for(let todo in todoList) {
207       let isDataUri = todo.startsWith('data:');
208       if(isDataUri) {
209         todo = todo.slice(5);
210       } else {
211         progress[todo] = 0;
212       }
213       let segments = todo.split('/');
214       if(!(segments[0] in game.assets)) {
215         game.assets[segments[0]] = {};
216       }
217       if(!(segments[0] in loader)) {
218         reject('Unsupported resource: ' + todo);
219       }
220       let url = todo;
221       if(isDataUri) {
222         url = todoList['data:' + todo];
223       } else {
224         url = game['deploymentOptions']['assetUrlPrefix'] + url;
225       }
226       loader[segments[0]].load(url, (result) => {
227         if(segments[0] == 'textures') {
228           result.colorSpace = THREE.SRGBColorSpace;
229           result.minFilter = THREE.NearestFilter;
230           result.magFilter = THREE.NearestFilter;
231           if(segments[1].split('.')[0].startsWith('feather-')) {
232             result.repeat = new THREE.Vector2(1, -1);
233             result.wrapT = THREE.RepeatWrapping;
234           } else if(segments[1].split('.')[0] == 'highcontrast-backdrop') {
235             result.repeat = new THREE.Vector2(25, 25);
236             result.wrapS = THREE.RepeatWrapping;
237             result.wrapT = THREE.RepeatWrapping;
238           }
239         }
240         game.assets[segments[0]][segments[1].split('.')[0]] = result;
241         if(todo in progress) {
242           progress[todo] = todoList[todo];
243           if(renderProgressCallback) {
244             renderProgressCallback(Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0) / total);
245           }
246         }
247       }, (xhr) => {
248         if(todo in progress) {
249           progress[todo] = xhr.loaded;
250           if(renderProgressCallback) {
251             renderProgressCallback(Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0) / total);
252           }
253         }
254       }, (err) => {
255         reject('Error while loading ' + todo + ': ' + err);
256       });
257     }
258     const loadingHeartbeat = () => {
259       let totalProgress = Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0);
260       if(totalProgress == total) {
261         resolve(totalProgress);
262       } else {
263         setTimeout(loadingHeartbeat, 100);
264       }
265     };
266     setTimeout(loadingHeartbeat, 100);
267   });
270 game['fn'].applyForceToFeather = (vector) => {
271   game.objects.feather.speed.add(vector);
274 game['fn'].initializeGame = (canvas) => {
275   game.timeProgress = 0;
276   game.timeTotal = 258;
277   game.courseRadius = 50;
279   game.objects = {};
280   game.view = {};
281   game.view.muted = false;
282   game.view.canvas = canvas;
283   game.ui.virtualInput = canvas.closest('.upInTheAirGame').querySelector('.virtual-input-widget');
285   const scene = new THREE.Scene();
286   game.view.camera = new THREE.PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000);
287   game.view.camera.position.z = 5;
288   game.view.ambientLight = new THREE.AmbientLight(0xffffff, 2);
289   scene.add(game.view.ambientLight);
290   game.view.directionalLight1 = new THREE.DirectionalLight(0xffffff, 1);
291   game.view.directionalLight1.position.set(1, 1, 1);
292   scene.add(game.view.directionalLight1);
293   game.view.directionalLight2 = new THREE.DirectionalLight(0xffffff, 1);
294   game.view.directionalLight2.position.set(-1, -1, 1);
295   scene.add(game.view.directionalLight2);
296   game.view.directionalLight3 = new THREE.DirectionalLight(0xffffff, 1);
297   game.view.directionalLight3.position.set(0, -1, 1);
298   scene.add(game.view.directionalLight3);
299   game.view.renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: false });
300   game.view.renderer.setSize(canvas.width, canvas.height);
301   game.view.renderer.setClearColor(0x808080, 1);
302   let resolution = Math.round(3200 / Math.pow(2, game.settings['graphics']));
303   game.view.canvas.width = resolution;
304   game.view.canvas.height = resolution;
305   game.view.camera.updateProjectionMatrix();
306   game.view.renderer.setSize(game.view.canvas.width, game.view.canvas.height);
307   game.view.clock = new THREE.Clock();
308   game.view.clock.previousTime = 0;
309   game.view.clock.getDeltaTime = () => {
310     const elapsedTime = game.view.clock.getElapsedTime();
311     const deltaTime = elapsedTime - game.view.clock.previousTime;
312     game.view.clock.previousTime = elapsedTime;
313     return deltaTime;
314   };
316   const pinwheelGeometry = new THREE.BoxGeometry(.9, .9, 0.01);
317   const pinwheelMaterial = new THREE.MeshPhongMaterial({
318     map: game.assets.textures.pinwheel,
319     transparent: true,
320     alphaTest: 0.5,
321     opacity: 0.0,
322   });
323   game.objects.pinwheel = new THREE.Mesh(pinwheelGeometry, [null, null, null, null, pinwheelMaterial, null]);
324   game.objects.pinwheel.position.setY(2);
325   game.objects.pinwheel.position.setZ(-1);
326   game.objects.pinwheel.opacity = 0;
327   scene.add(game.objects.pinwheel);
329   for(let time of ['day', 'evening']) {
330     game.objects[time + 'House'] = new THREE.Group();
331     for(let layer of [1, 2, 3]) {
332       let material = new THREE.MeshBasicMaterial({
333         map: game.assets['textures']['house-' + time + '-' + layer],
334         transparent: true,
335         alphaTest: 0.5,
336       });
337       let dimensions;
338       if(layer == 1) {
339         dimensions = [14, 14, 0, 0, -2];
340       } else if(layer == 2) {
341         dimensions = [6, 3.4455, -1.4, -3.6, -3];
342       } else if(layer == 3) {
343         dimensions = [10, 10, -4, -2, -6];
344       }
345       let mesh = new THREE.Mesh(new THREE.PlaneGeometry(dimensions[0], dimensions[1]), material);
346       mesh.position.set(dimensions[2], dimensions[3], dimensions[4]);
347       if(time == 'evening') {
348         mesh.position.setX(-mesh.position.x);
349       }
350       game.objects[time + 'House'].add(mesh);
351     }
352     game.objects[time + 'House'].position.set(-11.5, -game.courseRadius - 4, -7);
353     if(time == 'evening') {
354       game.objects[time + 'House'].position.x *= -1;
355     }
356   }
358   game.view.camera.position.set(-5, -game.courseRadius, game.view.camera.position.z);
359   game.view.scene = scene;
361   game['fn'].createMeshes();
362   game['fn'].createFeather();
363   game['fn'].reset();
365   function pinwheelPositionUpdate(game, viewportX, viewportY) {
366     const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
367     const viewportHeight = 2 * Math.tan(vFOV / 2) * (game.view.camera.position.z - game.objects.pinwheel.position.z);
368     game.controls.positionX = viewportHeight * viewportX;
369     game.controls.positionY = - viewportHeight * viewportY;
370   }
372   function cursorMoveEvent(game, target, viewportLocalX, viewportLocalY, pressed) {
373     if(game.settings['controls'] == 'mouse' || game.settings['controls'] == 'touchpad') {
374       let sensorElem = game.view.canvas;
375       if(game.settings['controls'] == 'touchpad') {
376         sensorElem = game.ui.virtualInput;
377       }
378       let bbox = sensorElem.getBoundingClientRect();
379       // Intentional division by height instead of width in the following line, since
380       // three.js controls the vertical FOV. So if we ever change the aspect ratio from 1:1,
381       // y will still be in range (-0.5, 0.5), but the range for x will be smaller or larger.
382       let x = (viewportLocalX - bbox.x - (bbox.width / 2)) / bbox.height;
383       let y = (viewportLocalY - bbox.y - (bbox.height / 2)) / bbox.height;
384       if(game.settings['controls'] == 'touchpad') {
385         sensorElem.children[0].style.left = ((0.5 + x) * 100) + '%';
386         sensorElem.children[0].style.top = ((0.5 + y) * 100) + '%';
387       }
388       if(game.settings['controls'] == 'touchpad') {
389         x *= 1.05;
390         y *= 1.05;
391       }
392       // The pinwheel gets to go a little bit past the edge of the playing field.
393       const maxDist = 0.55;
394       if(game.settings['controls'] == 'mouse' || (pressed && Math.abs(x) <= maxDist && Math.abs(y) <= maxDist)) {
395         pinwheelPositionUpdate(game, x, y);
396       }
397     }
398     if(game.settings['controls'] == 'thumbstick') {
399       if(!game.ui.virtualInput.inProgress) {
400         return;
401       }
402       let bbox = game.ui.virtualInput.getBoundingClientRect();
403       let x, y;
404       if(pressed) {
405         x = (viewportLocalX - bbox.x - (bbox.width / 2)) / bbox.height;
406         y = (viewportLocalY - bbox.y - (bbox.height / 2)) / bbox.height;
407         let vLen = Math.sqrt(4 * x * x + 4 * y * y);
408         x = x / Math.max(vLen, 0.6);
409         y = y / Math.max(vLen, 0.6);
410       } else {
411         x = 0;
412         y = 0;
413       }
414       let speedScale = 7.0;
415       let deadZone = 0.2;
416       let speedX = x * 2;
417       if(Math.abs(speedX) < deadZone) {
418         speedX = 0.0;
419       }
420       let speedY = y * 2;
421       if(Math.abs(speedY) < deadZone) {
422         speedY = 0.0;
423       }
424       game.controls.speedX = speedScale * speedX;
425       game.controls.speedY = -1 * speedScale * speedY;
426       x *= 0.6;
427       y *= 0.6;
428       game.ui.virtualInput.children[0].style.left = ((0.5 + x) * 100) + '%';
429       game.ui.virtualInput.children[0].style.top = ((0.5 + y) * 100) + '%';
430     }
431   }
433   function keyboardEvent(game, key, motion) {
434     if(game.settings['controls'] != 'keyboard') {
435       return;
436     }
437     if(motion == 'down') {
438       if(game.controls.heldKeys.includes(key)) {
439         return;
440       }
441       game.controls.heldKeys.push(key);
442     } else {
443       if(game.controls.heldKeys.includes(key)) {
444         game.controls.heldKeys.splice(game.controls.heldKeys.indexOf(key), 1);
445       }
446     }
447     if(game.settings['keyboard']['tapmode']) {
448       if(motion != 'down') {
449         return;
450       }
451       if(game.settings['keyboard']['up'].includes(key)) {
452         game.controls.speedY = Math.max(0.0, game.controls.speedY + 2.0);
453       }
454       if(game.settings['keyboard']['down'].includes(key)) {
455         game.controls.speedY = Math.min(0.0, game.controls.speedY - 2.0);
456       }
457       if(game.settings['keyboard']['right'].includes(key)) {
458         game.controls.speedX = Math.max(0.0, game.controls.speedX + 2.0);
459       }
460       if(game.settings['keyboard']['left'].includes(key)) {
461         game.controls.speedX = Math.min(0.0, game.controls.speedX - 2.0);
462       }
463       return;
464     }
465     if(motion == 'down' && game.settings['keyboard']['up'].includes(key)) {
466       game.controls.accelY = 15.0;
467       game.controls.speedY = 0.0;
468     }
469     if(motion == 'down' && game.settings['keyboard']['down'].includes(key)) {
470       game.controls.accelY = -15.0;
471       game.controls.speedY = 0.0;
472     }
473     if(motion == 'down' && game.settings['keyboard']['right'].includes(key)) {
474       game.controls.accelX = 15.0;
475       game.controls.speedX = 0.0;
476     }
477     if(motion == 'down' && game.settings['keyboard']['left'].includes(key)) {
478       game.controls.accelX = -15.0;
479       game.controls.speedX = 0.0;
480     }
481     if(motion == 'up' && game.settings['keyboard']['up'].includes(key)) {
482       game.controls.accelY = Math.min(0.0, game.controls.accelY);
483       game.controls.speedY = Math.min(0.0, game.controls.speedY);
484     }
485     if(motion == 'up' && game.settings['keyboard']['down'].includes(key)) {
486       game.controls.accelY = Math.max(0.0, game.controls.accelY);
487       game.controls.speedY = Math.max(0.0, game.controls.speedY);
488     }
489     if(motion == 'up' && game.settings['keyboard']['right'].includes(key)) {
490       game.controls.accelX = Math.min(0.0, game.controls.accelX);
491       game.controls.speedX = Math.min(0.0, game.controls.speedX);
492     }
493     if(motion == 'up' && game.settings['keyboard']['left'].includes(key)) {
494       game.controls.accelX = Math.max(0.0, game.controls.accelX);
495       game.controls.speedX = Math.max(0.0, game.controls.speedX);
496     }
497   }
499   document.body.addEventListener('mousemove', e => cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1)));
500   document.body.addEventListener('mousedown', e => {
501     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
502       if(e.target.closest('.virtual-input-widget') == game.ui.virtualInput) {
503         game.ui.virtualInput.inProgress = true;
504         game.ui.virtualInput.children[0].style.display = 'block';
505         e.preventDefault();
506       } else {
507         game.ui.virtualInput.inProgress = false;
508         if(game.settings['controls'] == 'touchpad') {
509           game.ui.virtualInput.children[0].style.display = 'none';
510         }
511       }
512     }
513     cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1));
514   });
515   document.body.addEventListener('mouseup', e => {
516     cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1));
517     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
518       game.ui.virtualInput.inProgress = false;
519       if(game.settings['controls'] == 'touchpad') {
520         game.ui.virtualInput.children[0].style.display = 'none';
521       } else {
522         game.ui.virtualInput.children[0].style.transitionDuration = '50ms';
523         setTimeout(() => { game.ui.virtualInput.children[0].style.transitionDuration = '0ms'; }, 75);
524       }
525       cursorMoveEvent(game, e.target, 0, 0, false);
526     }
527   });
528   document.body.addEventListener('touchmove', e => cursorMoveEvent(game, e.target, e.touches[0].clientX, e.touches[0].clientY, true));
529   document.body.addEventListener('touchstart', e => {
530     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
531       if(e.target.closest('.virtual-input-widget') == game.ui.virtualInput) {
532         game.ui.virtualInput.inProgress = true;
533         game.ui.virtualInput.children[0].style.display = 'block';
534         e.preventDefault();
535       } else {
536         game.ui.virtualInput.inProgress = false;
537         if(game.settings['controls'] == 'touchpad') {
538           game.ui.virtualInput.children[0].style.display = 'none';
539         }
540       }
541     }
542     cursorMoveEvent(game, e.target, e.touches[0].clientX, e.touches[0].clientY, true);
543   });
544   document.body.addEventListener('touchend', e => {
545     if(e.target.closest('.ui-container') && game.settings['controls'] != 'mouse' && ['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
546       game['fn'].moveToPage('pause', true);
547       e.preventDefault();
548     }
549     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
550       game.ui.virtualInput.inProgress = false;
551       if(game.settings['controls'] == 'touchpad') {
552         game.ui.virtualInput.children[0].style.display = 'none';
553       } else {
554         game.ui.virtualInput.children[0].style.transitionDuration = '50ms';
555         setTimeout(() => { game.ui.virtualInput.children[0].style.transitionDuration = '0ms'; }, 75);
556       }
557       cursorMoveEvent(game, e.target, 0, 0, false);
558     }
559   });
560   document.body.addEventListener('keydown', e => keyboardEvent(game, e.key, 'down'));
561   document.body.addEventListener('keyup', e => keyboardEvent(game, e.key, 'up'));
563   // All vectors used by the game loop (no allocations inside)
564   game.var = {};
565   game.var.featherLocalPos = new THREE.Vector3();
566   game.var.featherBorderForce = new THREE.Vector3();
567   game.var.pinwheelDistance = new THREE.Vector3();
568   game.var.pinwheelRotationSpeed = 0;
569   game.var.notCollectedPos = new THREE.Vector3();
570   game.var.collectedPos = new THREE.Vector3();
571   game.var.endingEntryTrajectory = new THREE.Vector3();
572   game.var.endingExitTrajectory = new THREE.Vector3();
573   game.var.endingEntryRotation = new THREE.Vector3();
574   game.var.endingExitRotation = new THREE.Vector3();
575   game.view.renderer.setAnimationLoop(() => { game['fn'].animate(scene); });
578 game['fn'].prepareWordMesh = (word) => {
579   while(word.children.length > 0) {
580     word.remove(word.children[0]);
581   }
582   if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
583     for(let letter of word.text) {
584       let geometry = game.assets.fonts.geometry[letter];
585       let material = game.view.materials.letter;
586       if(geometry.customMaterial) {
587         material = geometry.customMaterial;
588       }
589       let mesh = new THREE.Mesh(geometry, material);
590       // We wrap each letter in a surrounding group in order to move the center point
591       // from the corner of the letter to its center. This makes rotations easier.
592       let container = new THREE.Group();
593       mesh.position.set(-game.assets.fonts.geometry[letter].dx, -game.assets.fonts.geometry[letter].dy, 0);
594       container.add(mesh);
595       word.add(container);
596     }
597   } else if(game.settings['graphics'] == 3 || game.settings['highcontrast']) {
598     let mesh = new THREE.Mesh(Object.values(game.assets.fonts.geometry)[0], game.view.materials.letter);
599     word.add(mesh);
600   }
603 game['fn'].reset = () => {
604   game.controls = {};
605   game.controls.positionX = 0;
606   game.controls.positionY = 0;
607   game.controls.speedX = 0;
608   game.controls.speedY = 0;
609   game.controls.accelX = 0;
610   game.controls.accelY = 0;
611   game.controls.heldKeys = [];
612   game.ui.reachedEnd = false;
613   if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
614     for(let i = 0; i < 6; i++) {
615      game.view.materials['cloud' + i].uniforms.lerp.value = 0.0;
616     }
617   }
618   game.view.scene.add(game.objects.dayHouse);
619   game.view.scene.remove(game.objects.eveningHouse);
620   game.objects.feather.position.set(-11.45, -game.courseRadius - 4.2, -9.9);
621   game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
622   game.objects.pinwheel.material[4].opacity = 0.0;
623   setTimeout(() => {
624     game.ui.root.querySelector('.ui-page.title').classList.remove('end');
625   }, 500);
627   if(game.objects.words) {
628     for(let word of game.objects.words) {
629       game.view.scene.remove(word);
630     }
631   }
632   game.objects.words = [];
633   game.objects.words.collectedCount = 0;
634   game.ui.hud.children[1].innerText = '0';
635   const interWordDistance = new THREE.Vector3();
636   let placementSuccess;
637   let wordList = [];
638   for(let i = 0; i < 100; i++) {
639     let angleInCourse;
640     let clusteringFunction = (val) => Math.max(0.15 + val / 2, 0.7 - 3 * Math.pow(0.75 - 2 * val, 2), 1 - 3 * Math.pow(1 - val, 2));
641     do {
642       angleInCourse = Math.random();
643     } while(clusteringFunction(angleInCourse) < Math.random());
644     angleInCourse = (0.08 + 0.87 * angleInCourse);
645     if(i == 0) {
646       angleInCourse = 0.05;
647     }
648     let randomCameraX = game.courseRadius * Math.sin(angleInCourse * 2 * Math.PI);
649     let randomCameraY = game.courseRadius * -Math.cos(angleInCourse * 2 * Math.PI);
650     let word = new THREE.Group();
651     if(wordList.length == 0) {
652       wordList.push(...game.assets.wordList);
653     }
654     let wordIndex = Math.floor(Math.random() * wordList.length);
655     word.text = wordList.splice(wordIndex, 1)[0];
656     game['fn'].prepareWordMesh(word);
657     word.randomAnimOffset = Math.random();
658     const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
659     let attempts = 0;
660     do {
661       let randomPlacementRadius = Math.min(0.8, angleInCourse) * Math.tan(vFOV / 2) * Math.abs(word.position.z - game.view.camera.position.z);
662       if(i == 0) {
663         randomPlacementRadius = 0;
664       }
665       let randomPlacementAngle = Math.random() * 2 * Math.PI;
666       let randomPlacementX = Math.sin(randomPlacementAngle) * randomPlacementRadius;
667       let randomPlacementY = Math.cos(randomPlacementAngle) * randomPlacementRadius;
668       word.position.set(randomCameraX + randomPlacementX, randomCameraY + randomPlacementY, 0);
669       placementSuccess = true;
670       for(let j = 0; j < i; j++) {
671         if(interWordDistance.subVectors(word.position, game.objects.words[j].position).length() <= 1.2) {
672           placementSuccess = false;
673           break;
674         }
675       }
676       attempts += 1;
677       if(attempts >= 10) {
678         angleInCourse = 0.04 + 0.92 * Math.random();
679         attempts = 0;
680       }
681     } while(!placementSuccess);
682     game.view.scene.add(word);
683     game.objects.words.push(word);
684   }
687 game['fn'].animate = (scene) => {
688   if(!('startTime' in game)) {
689     game.startTime = game.view.clock.getElapsedTime();
690   }
691   if(game.ui.currentPage == 'pause') {
692     return;
693   }
694   let delta = Math.min(game.view.clock.getDeltaTime(), 1 / 12);
695   if(game.ui.currentPage == 'gameplay') {
696     delta = delta * (game.settings['difficulty']['speed'] / 100);
697   }
698   game.timeProgress = (game.timeProgress + delta);
700   if(game.settings['controls'] == 'gamepad') {
701     let speedScale = 7.0;
702     let deadZone = 0.2;
703     let speedX = [];
704     let speedY = [];
705     for(let gamepad of game.ui.gamepads) {
706       let sx = gamepad.axes[0];
707       if(Math.abs(sx) < deadZone) {
708         sx = 0.0;
709       }
710       speedX.push(sx);
711       let sy = gamepad.axes[1];
712       if(Math.abs(sy) < deadZone) {
713         sy = 0.0;
714       }
715       speedY.push(sy);
716     }
717     if(speedX.length > 0) {
718       speedX = speedX.reduce((s, a) => s + a, 0) / speedX.length;
719     } else {
720       speedX = 0;
721     }
722     if(speedY.length > 0) {
723       speedY = speedY.reduce((s, a) => s + a, 0) / speedY.length;
724     } else {
725       speedY = 0;
726     }
727     game.controls.speedX = speedScale * speedX;
728     game.controls.speedY = -1 * speedScale * speedY;
729   }
731   const maxPinwheelSpeed = 8.0;
732   const maxPinwheelDistance = 5.0;
733   game.controls.speedX += delta * game.controls.accelX;
734   game.controls.speedY += delta * game.controls.accelY;
735   game.controls.speedX = Math.min(maxPinwheelSpeed, Math.max(-maxPinwheelSpeed, game.controls.speedX));
736   game.controls.speedY = Math.min(maxPinwheelSpeed, Math.max(-maxPinwheelSpeed, game.controls.speedY));
737   game.controls.positionX += delta * game.controls.speedX;
738   game.controls.positionY += delta * game.controls.speedY;
739   if(game.controls.positionX > maxPinwheelDistance) {
740     game.controls.positionX = maxPinwheelDistance;
741     game.controls.speedX = Math.max(0.0, game.controls.speedX);
742     game.controls.accelX = Math.max(0.0, game.controls.accelX);
743   } else if(game.controls.positionX < -maxPinwheelDistance) {
744     game.controls.positionX = -maxPinwheelDistance;
745     game.controls.speedX = Math.min(0.0, game.controls.speedX);
746     game.controls.accelX = Math.min(0.0, game.controls.accelX);
747   }
748   if(game.controls.positionY > maxPinwheelDistance) {
749     game.controls.positionY = maxPinwheelDistance;
750     game.controls.speedY = Math.max(0.0, game.controls.speedY);
751     game.controls.accelY = Math.max(0.0, game.controls.accelY);
752   } else if(game.controls.positionY < -maxPinwheelDistance) {
753     game.controls.positionY = -maxPinwheelDistance;
754     game.controls.speedY = Math.min(0.0, game.controls.speedY);
755     game.controls.accelY = Math.min(0.0, game.controls.accelY);
756   }
758   if(game.ui.currentPage != 'gameplay') {
759     let cameraSwayFactor = 1;
760     if(game.settings['graphics'] == 3) {
761       cameraSwayFactor = 0;
762     }
763     let cameraX, cameraY;
764     if(['options', 'credits', 'outro', 'unlock'].includes(game.ui.currentPage)) {
765       cameraX = game.ui.reachedEnd ? 5 : -5;
766       cameraY = 0;
767     }
768     if(game.ui.currentPage == 'title') {
769       cameraX = -5;
770       cameraY = 0;
771       if(!game.ui.reachedEnd) {
772         game.objects.feather.position.set(cameraX - 8.45, -game.courseRadius - 6.4, -9.9);
773         game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
774       } else {
775         cameraX = 5;
776       }
777       if(!game.ui.reachedStart) {
778         if(game.timeProgress < 1) {
779           game.ui.root.querySelector('.ui-page.title h1').style.opacity = '0';
780           game.ui.root.querySelectorAll('.ui-page.title > button').forEach((btn) => {
781             btn.disabled = true;
782             btn.style.position = 'relative';
783             btn.style.left = '10em';
784             btn.style.opacity = '0';
785           });
786           game.ui.root.querySelector('.ui-page.title .footer').style.opacity = '0';
787           game.ui.root.querySelector('.ui-page.title .system-buttons').style.opacity = '0';
788           cameraX += Math.max(0.0, 1 - game['fn'].easeInOut(0.5 + game.timeProgress / 2));
789           cameraY += Math.max(0.0, 10 * Math.pow(0.5 - game.timeProgress / 2, 2));
790         } else if(game.timeProgress >= 1.0 && game.timeProgress <= 2.1) {
791           game.ui.root.querySelector('.ui-page.title h1').style.opacity = Math.min(1.0, game.timeProgress - 1.0).toFixed(2);
792         }
793         if(game.timeProgress >= 1.5 && game.timeProgress <= 3.0) {
794           game.ui.root.querySelectorAll('.ui-page.title > button').forEach((btn) => {
795             let timeOffset = Array.from(btn.parentNode.children).indexOf(btn) - 2;
796             btn.style.left = 10 * game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, 0.3 * timeOffset + 2.5 - game.timeProgress))).toFixed(2) + 'em';
797             let opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, -0.3 * timeOffset + game.timeProgress - 1.5)));
798             btn.style.opacity = opacity.toFixed(2);
799             if(opacity == 1.0) {
800               btn.disabled = false;
801             }
802           });
803         }
804         if(game.timeProgress >= 3.0 && game.timeProgress <= 4.0) {
805           game.ui.root.querySelector('.ui-page.title .footer').style.opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, game.timeProgress - 3.0))).toFixed(2);
806           game.ui.root.querySelector('.ui-page.title .system-buttons').style.opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, game.timeProgress - 3.0))).toFixed(2);
807         }
808         if(game.timeProgress > 4.0 && !game.ui.reachedStart) {
809           game.ui.root.querySelector('.ui-page.title h1').removeAttribute('style');
810           game.ui.root.querySelectorAll('.ui-page.title > button').forEach(btn => { btn.disabled = false; btn.removeAttribute('style'); });
811           game.ui.root.querySelector('.ui-page.title .footer').removeAttribute('style');
812           game.ui.root.querySelector('.ui-page.title .system-buttons').removeAttribute('style');
813           game.ui.reachedStart = true;
814         }
815       }
816     } else if(game.ui.currentPage == 'openingcutscene') {
817       cameraX = -5;
818       cameraY = 0;
819       if(game.ui.reachedEnd) {
820         game['fn'].reset();
821       }
822       if(game.timeProgress < 0.1 && !game.view.windSound.isPlaying) {
823         game.view.windSound.stop();
824         game.objects.feather.position.set(cameraX - 8.45, -game.courseRadius - 6.4, -9.9);
825         game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
826       }
827       if(game.timeProgress > 1.0 && game.timeProgress <= 1.1 && !game.ui.root.querySelector('.gameplay p')) {
828         const lines = ['Why are the simplest words…', '…often the most difficult to write?'];
829         for(let line of lines) {
830           let elem = document.createElement('p');
831           elem.innerText = line;
832           elem.style.left = (1.5 + 2 * lines.indexOf(line)) + 'em';
833           elem.style.top = (1 + 1.2 * lines.indexOf(line)) + 'em';
834           elem.style.opacity = '0';
835           document.querySelector('.ui-page.gameplay').appendChild(elem);
836         }
837         if(!game.view.windSound.isPlaying) {
838           game.view.windSound.setVolume(game.settings['audio']['sounds']);
839           game.view.windSound.offset = 0;
840           if(!game.view.muted) {
841             game.view.windSound.play();
842           }
843         }
844       }
845       if(game.timeProgress > 1.0 && game.timeProgress <= 5.0) {
846         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
847           let opacity = Math.max(0.0, Math.min(1.0, game.timeProgress - (elem.nextSibling ? 1.0 : 3.5)));
848           elem.style.transform = 'translateX(' + (Math.pow(1.0 - opacity, 2) * 10).toFixed(2) + 'em)';
849           elem.style.opacity = opacity.toFixed(2);
850         });
851       }
852       if(game.timeProgress >= 1.0 && game.timeProgress <= 3.0) {
853         let windStrength = 0.5 * (1 + Math.cos((game.timeProgress - 2.0) * Math.PI));
854         game.objects.feather.position.x = cameraX - 8.45 + 0.15 * windStrength;
855         game.objects.feather.rotation.z = Math.PI / 2.1 - 0.2 * windStrength;
856       }
857       if(game.timeProgress >= 3.0) {
858         let windStrength = Math.max(0.5 * (1 + Math.cos((game.timeProgress - 4.0) * Math.PI)), Math.min(2 * (game.timeProgress - 4.2), 1.2));
859         game.objects.feather.position.x = cameraX - 8.45 + 0.15 * windStrength + 13.45 * Math.min(1.0, Math.max(0.0, 1 - Math.pow(Math.max(0.0, 6.0 - game.timeProgress), 2)));
860         game.objects.feather.position.y = -game.courseRadius - 6.4 + 6.4 * game['fn'].easeInOut(Math.min(1,Math.max(0, game.timeProgress - 5.0) / 2));
861         game.objects.feather.position.y += (Math.cos((Math.max(5.0, Math.min(8.0, game.timeProgress)) - 5.0) * 2 * Math.PI / 3) - 1) * 2 * Math.sin(game.timeProgress * 2);
862         game.objects.feather.position.z = -9.9 + 9.9 * Math.min(1.0, Math.max(0.0, 1 - Math.pow(Math.max(0.0, 6.0 - game.timeProgress), 2)));
863         game.objects.feather.rotation.z = Math.PI / 2.1 - 0.2 * windStrength + 1.45 * Math.max(0.0, game.timeProgress - 5.0);
864         game.objects.feather.rotation.x = Math.PI + Math.max(0.0, game.timeProgress - 4.5) * Math.sin(Math.pow(game.timeProgress - 4.5, 2));
865       }
866       if(game.timeProgress > 7.0) {
867         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
868           let opacity = Math.max(0.0, Math.min(1.0, 8.0 - game.timeProgress));
869           elem.style.opacity = opacity.toFixed(2);
870         });
871       }
872       cameraSwayFactor = cameraSwayFactor * (1 - (game.timeProgress / 8));
873       cameraX = -5 + Math.pow(Math.max(0, game.timeProgress - 3) / 5, 1.6) * 5;
875       if(game.timeProgress > 6.0 && game.timeProgress < 7.0 && game.settings['controls'] != 'mouse') {
876         game.controls.positionX = 0;
877         game.controls.positionY = -3;
878       }
879       game.objects.pinwheel.material[4].opacity = game['fn'].easeInOut(Math.max(0, (game.timeProgress - 7)));
880       if(game.timeProgress >= 8.0) {
881         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
882           let opacity = Math.max(0.0, Math.min(1.0, 8.0 - game.timeProgress));
883           elem.style.opacity = opacity.toFixed(2);
884         });
885         game.view.music.offset = 0;
886         if(!game.view.muted) {
887           game.view.music.play();
888         }
889         game['fn'].moveToPage('gameplay', true);
890       }
891     } else if(game.ui.currentPage == 'endingcutscene') {
892       cameraX = -5;
893       cameraY = 0;
894       cameraSwayFactor = cameraSwayFactor * game.timeProgress / 8;
895       cameraX = 5 - Math.pow(Math.max(0, 5 - game.timeProgress) / 5, 1.6) * 5;
896       let trajectoryLerpValue = game['fn'].easeInOut(Math.min(6.0, game.timeProgress) / 6);
897       game.var.endingEntryTrajectory.addScaledVector(game.objects.feather.speed, delta);
898       game.var.endingExitTrajectory.setX(11.2 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
899       game.var.endingExitTrajectory.setY(-game.courseRadius - 7.6 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
900       game.var.endingExitTrajectory.setZ(-8.9 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
901       game.objects.feather.rotation.x = game['fn'].lerp(game.var.endingEntryRotation.x, game.var.endingExitRotation.x, trajectoryLerpValue);
902       game.objects.feather.rotation.y = game['fn'].lerp(game.var.endingEntryRotation.y, game.var.endingExitRotation.y, trajectoryLerpValue);
903       game.objects.feather.rotation.z = game['fn'].lerp(game.var.endingEntryRotation.z, game.var.endingExitRotation.z, trajectoryLerpValue);
904       game.objects.feather.position.lerpVectors(game.var.endingEntryTrajectory, game.var.endingExitTrajectory, trajectoryLerpValue);
905       game.objects.pinwheel.material[4].opacity = game['fn'].easeInOut(Math.max(0, (1 - game.timeProgress)));
906       if(!game.settings['highcontrast']) {
907         let letterScale = game['fn'].lerp(0.3, 0.0, game['fn'].easeInOut(Math.max(0, Math.min(1, game.timeProgress - 6))));
908         for(let i = 0; i < game.objects.words.length; i++) {
909           let word = game.objects.words[i];
910           if(!word.collected) {
911             continue;
912           }
913           let x, y, z;
914           let collectionAnimationDuration = 1.0;
915           for(let j = 0; j < word.children.length; j++) {
916             let letter = word.children[j];
917             let animationProgress = (((game.timeProgress + 5 * word.randomAnimOffset) % 5) / 5 + j / 37) % 1;
918             x = game.objects.feather.scale.x * 0.5 * Math.cos(animationProgress * 1 * Math.PI * 2);
919             y = 0.2 * Math.sin(animationProgress * 7 * Math.PI * 2);
920             z = 0.2 * Math.cos(animationProgress * 7 * Math.PI * 2);
921             x = x * Math.cos(game.objects.feather.rotation.z) - y * Math.sin(game.objects.feather.rotation.z);
922             y = y * Math.cos(game.objects.feather.rotation.z) + x * Math.sin(game.objects.feather.rotation.z);
923             x += game.objects.feather.position.x - word.position.x;
924             y += game.objects.feather.position.y - word.position.y;
925             z += game.objects.feather.position.z - word.position.z;
926             if(i == 0 && !word.collected) {
927               // If we don't catch this edge case here, the manually placed first word might be visible
928               // in the closing cutscene if it is not collected.
929               x = 9999;
930             }
931             letter.position.set(x, y, z);
932             let rotation = (game.timeProgress * 3 + 2 * Math.PI * word.randomAnimOffset) % (2 * Math.PI);
933             letter.rotation.set(rotation + j, rotation + 2*j, rotation + 3*j);
934             letter.scale.set(letterScale, letterScale, letterScale);
935           }
936         }
937       }
938       if(game.timeProgress >= 8) {
939         game.ui.root.querySelector('.ui-page.title').classList.add('end');
940         game['fn'].moveToPage('outro', true);
941       }
942     } else if(game.ui.reachedEnd) {
943       cameraX = 5;
944       cameraY = 0;
945     }
946     if(typeof(cameraX) == 'number' && typeof(cameraY) == 'number') {
947       game.view.camera.position.setY(cameraY - game.courseRadius + 0.07 * cameraSwayFactor * Math.sin(game.view.clock.getElapsedTime() * 0.5));
948       game.view.camera.position.setX(cameraX + 0.05 * cameraSwayFactor * Math.sin(game.view.clock.getElapsedTime() * 0.7));
949     }
950     game.view.renderer.render(scene, game.view.camera);
951     return;
952   }
953   if(game.settings['enablehud']) {
954     if(game.timeProgress < 0.5) {
955       game.ui.hud.style.opacity = Math.min(1, game.timeProgress * 4).toFixed(2);
956     }
957     const failsafe = 0.0001;
958     const radiusOuter = 0.5;
959     const radiusInner = 0.4;
960     const progress = Math.max(failsafe, Math.min(1 - failsafe, game.timeProgress / game.timeTotal));
961     const xOuter = (0.5 + radiusOuter * Math.sin(progress * 2 * Math.PI)).toFixed(4);
962     const yOuter = (0.5 + radiusOuter * Math.cos(progress * 2 * Math.PI)).toFixed(4);
963     const xInner = (0.5 + radiusInner * Math.sin(progress * 2 * Math.PI)).toFixed(4);
964     const yInner = (0.5 + radiusInner * Math.cos(progress * 2 * Math.PI)).toFixed(4);
965     for(let segment of [0, 1]) {
966       let p = 'M' + xOuter + ',' + yOuter;
967       p += 'A' + radiusOuter + ',' + radiusOuter + ' 0 ' + ((progress >= 0.5) ? (1 - segment) : segment) + ' ' + (1 - segment) + ' .5,' + (0.5 + radiusOuter);
968       p += 'V' + (0.5 + radiusInner);
969       p += 'A' + radiusInner + ',' + radiusInner + ' 0 ' + ((progress >= 0.5) ? (1 - segment) : segment) + ' ' + segment + ' ' + xInner + ',' + yInner;
970       p += 'z';
971       game.ui.hud.children[0].children[segment].setAttribute('d', p);
972     }
973     if(game.timeProgress > game.timeTotal - 0.5) {
974       game.ui.hud.style.opacity = Math.max(0, (game.timeTotal - game.timeProgress - 0.25) * 4).toFixed(2);
975     }
976   }
977   if(game.ui.root.querySelector('.ui-page.gameplay p')) {
978     game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach(elem => elem.remove());
979   }
980   if(game.timeProgress / game.timeTotal >= 1.0) {
981     game.ui.reachedEnd = true;
982     game.var.endingEntryTrajectory.set(game.objects.feather.position.x, game.objects.feather.position.y, game.objects.feather.position.z);
983     game.var.endingEntryRotation.x = game.objects.feather.rotation.x;
984     game.var.endingEntryRotation.y = game.objects.feather.rotation.y;
985     game.var.endingEntryRotation.z = game.objects.feather.rotation.z;
986     game.var.endingExitRotation.set(-0.2, 0, -0.2);
987     game['fn'].moveToPage('endingcutscene', true);
988   }
990   if(game.settings['audio']['music'] > 0.0 && game.view.music && !game.view.music.isPlaying) {
991     const remainingRealTime = (game.timeTotal - game.timeProgress) / (game.settings['difficulty']['speed'] / 100);
992     if(remainingRealTime >= game.assets['audio']['music-' + game.settings['audio']['theme']].duration - 2) {
993       game.view.music.offset = 0;
994       if(!game.view.muted) {
995         game.view.music.play();
996       }
997     }
998   }
1000   const angle = 2 * Math.PI * (game.timeProgress / game.timeTotal);
1001   game.view.camera.position.x = game.courseRadius * Math.sin(angle);
1002   game.view.camera.position.y = - game.courseRadius * Math.cos(angle);
1004   if(!game.settings['highcontrast']) {
1005     let sunsetValue = 2.0;
1006     if(!game.ui.reachedEnd) {
1007       sunsetValue = sunsetValue * game['fn'].easeInOut(Math.min(1, Math.max(0, ((game.timeProgress / game.timeTotal) - 0.3) / 0.6)));
1008     }
1009     if(game.settings['graphics'] <= 2) {
1010       for(let i = 0; i < 6; i++) {
1011         game.view.materials['cloud' + i].uniforms.lerp.value = sunsetValue;
1012       }
1013     } else {
1014       let cloudMaterialVariant = null;
1015       if(sunsetValue < 0.5 && !game.objects.clouds.children[0].material.name.endsWith('a')) {
1016         cloudMaterialVariant = 'a';
1017       } else if(sunsetValue >= 0.5 && sunsetValue < 1.5 && !game.objects.clouds.children[0].material.name.endsWith('b')) {
1018         cloudMaterialVariant = 'b';
1019       } else if(sunsetValue >= 1.5 && !game.objects.clouds.children[0].material.name.endsWith('c')) {
1020         cloudMaterialVariant = 'c';
1021       }
1022       if(cloudMaterialVariant) {
1023         for(let cloud of game.objects.clouds.children) {
1024           cloud.material = game.view.materials[cloud.material.name.slice(0, -1) + cloudMaterialVariant];
1025         }
1026         game.objects.backdrop.material = game.view.materials['cloud0' + cloudMaterialVariant];
1027       }
1028     }
1029   }
1031   if(game.timeProgress / game.timeTotal > 0.5 && game.objects.dayHouse.parent == scene) {
1032     scene.remove(game.objects.dayHouse);
1033     scene.add(game.objects.eveningHouse);
1034   }
1036   game.var.featherLocalPos.subVectors(game.objects.feather.position, game.view.camera.position).setZ(0);
1037   game.var.featherBorderForce.set(0, 0, 0);
1038   for(let coord of [0, 1]) {
1039     if(Math.abs(game.var.featherLocalPos.getComponent(coord)) > 3) {
1040       game.var.featherBorderForce.setComponent(coord, 3 * Math.sign(game.var.featherLocalPos.getComponent(coord)) - game.var.featherLocalPos.getComponent(coord));
1041     }
1042   }
1043   game['fn'].applyForceToFeather(game.var.featherBorderForce);
1044   const tiltedGravity = game.gravity.clone();
1045   game.var.pinwheelDistance.subVectors(game.objects.feather.position, game.objects.pinwheel.position).setZ(0);
1047   const pinwheelRotationTargetSpeed = 1 + Math.max(0, 2 - game.var.pinwheelDistance.length());
1048   game.var.pinwheelRotationSpeed = Math.max(1, pinwheelRotationTargetSpeed, game.var.pinwheelRotationSpeed - 2 * delta);
1049   game.objects.pinwheel.rotation.z -= game.var.pinwheelRotationSpeed * 5 * delta;
1050   game.objects.pinwheel.position.x = game.view.camera.position.x + game.controls.positionX;
1051   game.objects.pinwheel.position.y = game.view.camera.position.y + game.controls.positionY;
1053   const pinwheelForce = 0.5 * Math.max(0, Math.pow(game.var.pinwheelDistance.length(), - 0.5) - 0.5);
1054   game['fn'].applyForceToFeather(game.var.pinwheelDistance.normalize().multiplyScalar(pinwheelForce));
1055   if(pinwheelForce < 0.2) {
1056     if(game.objects.feather.swayDirection > 0 && game.objects.feather.speed.x > 1.5) {
1057       game.objects.feather.swayDirection *= -1;
1058     } else if(game.objects.feather.swayDirection < 0 && game.objects.feather.speed.x < -1.5) {
1059       game.objects.feather.swayDirection *= -1;
1060     }
1061     tiltedGravity.x += game.objects.feather.swayDirection;
1062   }
1063   if(game.objects.feather.speed.y > -1) {
1064     game['fn'].applyForceToFeather(tiltedGravity);
1065   }
1066   game.objects.feather.rotation.z = -0.1 * game.objects.feather.speed.x * game.settings['difficulty']['speed'] / 100;
1067   game.objects.feather.position.addScaledVector(game.objects.feather.speed, delta * game.settings['difficulty']['speed'] / 100);
1069   if(pinwheelForce > 0.2) {
1070     if(game.objects.feather.twistSpeed < 0.0001) {
1071       game.objects.feather.twistSpeed = (Math.random() - 0.5) * 0.01;
1072     }
1073     game.objects.feather.twistSpeed = Math.sign(game.objects.feather.twistSpeed) * 0.1 * game.objects.feather.speed.length();
1074   } else {
1075     game.objects.feather.twistSpeed = 0.98 * game.objects.feather.twistSpeed;
1076     if(Math.abs(game.objects.feather.twistSpeed < 0.1)) {
1077       let rotationDelta = game.objects.feather.rotation.x;
1078       if(rotationDelta >= Math.PI) {
1079         rotationDelta -= 2 * Math.PI;
1080       }
1081       game.objects.feather.twistSpeed -= rotationDelta * 0.02;
1082     }
1083   }
1085   game.objects.feather.twistSpeed = Math.min(0.13, game.objects.feather.twistSpeed) * game.settings['difficulty']['speed'] / 100;
1086   game.objects.feather.rotation.x = (game.objects.feather.rotation.x + game.objects.feather.twistSpeed) % (2 * Math.PI);
1088   let collectedScale = 0.0;
1089   if(!game.settings['highcontrast'] && game.settings['graphics'] <= 2) {
1090     collectedScale = game['fn'].lerp(0.6, 0.3, 1 - Math.pow(1 - game.objects.words.collectedCount / game.objects.words.length, 2));
1091   } else if(!game.settings['highcontrast'] && game.settings['graphics'] == 3) {
1092     collectedScale = 0.3;
1093   }
1094   const collectingRadius = - 0.5 + 1.5 * game.settings['difficulty']['collectingradius'];
1095   for(let i = 0; i < game.objects.words.length; i++) {
1096     let word = game.objects.words[i];
1097     if(!word.collected && new THREE.Vector3().subVectors(word.position, game.objects.feather.position).length() < collectingRadius) {
1098       word.collected = game.view.clock.getElapsedTime();
1099       game.objects.words.collectedCount += 1;
1100       game.ui.hud.children[1].innerText = game.objects.words.collectedCount;
1101       game['fn'].playRandomSound();
1102     }
1103     if(word.parent != game.view.scene) {
1104       // All that happens in here is the positional animation for the word, which
1105       // we can skip if it is no longer visible.
1106       continue;
1107     }
1108     let x, y, z;
1109     let collectionAnimationDuration = 1.0;
1110     for(let j = 0; j < word.children.length; j++) {
1111       game.var.notCollectedPos.set(0, 0, 0);
1112       game.var.collectedPos.set(0, 0, 0);
1113       let letter = word.children[j];
1114       let animationProgress = (((game.timeProgress + 5 * word.randomAnimOffset) % 5) / 5 + j / 37) % 1;
1115       if(!word.collected || game.view.clock.getElapsedTime() - word.collected <= collectionAnimationDuration) {
1116         x = word.position.x;
1117         y = word.position.y;
1118         z = 0;
1119         if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
1120           const wordAnimationRadius = 0.2;
1121           x += wordAnimationRadius * Math.cos(animationProgress * 5 * Math.PI * 2);
1122           y += wordAnimationRadius * Math.sin(animationProgress * 4 * Math.PI * 2);
1123           z += wordAnimationRadius * Math.sin(animationProgress * 6 * Math.PI * 2);
1124         }
1125         game.var.notCollectedPos.set(x, y, z);
1126       }
1127       if(word.collected) {
1128         if(!game.settings['highcontrast']) {
1129           x = game.objects.feather.scale.x * 0.5 * Math.cos(animationProgress * 1 * Math.PI * 2);
1130           y = 0.2 * Math.sin(animationProgress * 7 * Math.PI * 2);
1131           z = 0.2 * Math.cos(animationProgress * 7 * Math.PI * 2);
1132           x = x * Math.cos(game.objects.feather.rotation.z) - y * Math.sin(game.objects.feather.rotation.z);
1133           y = y * Math.cos(game.objects.feather.rotation.z) + x * Math.sin(game.objects.feather.rotation.z);
1134           x += game.objects.feather.position.x;
1135           y += game.objects.feather.position.y;
1136           z += game.objects.feather.position.z;
1137         } else {
1138           x = game.objects.feather.position.x;
1139           y = game.objects.feather.position.y;
1140           z = game.objects.feather.position.z;
1141         }
1142         game.var.collectedPos.set(x, y, z);
1143       }
1144       if(game.var.notCollectedPos.length() > 0 && game.var.collectedPos.length() > 0) {
1145         let collectingProgress = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, (game.view.clock.getElapsedTime() - word.collected) / collectionAnimationDuration)));
1146         letter.position.lerpVectors(game.var.notCollectedPos, game.var.collectedPos, collectingProgress);
1147         let scale = game['fn'].lerp(1.0, collectedScale, collectingProgress);
1148         letter.scale.set(scale, scale, scale);
1149       } else if(game.var.notCollectedPos.length() > 0) {
1150         letter.position.set(game.var.notCollectedPos.x, game.var.notCollectedPos.y, game.var.notCollectedPos.z);
1151       } else if(game.var.collectedPos.length() > 0) {
1152         letter.position.set(game.var.collectedPos.x, game.var.collectedPos.y, game.var.collectedPos.z);
1153         if(game.settings['highcontrast']) {
1154           // Special case because in high contrast mode, collected words vanish entirely.
1155           game.view.scene.remove(word);
1156         }
1157       }
1158       letter.position.sub(word.position);
1159       if(!game.settings['highcontrast']) {
1160         let rotation = (game.timeProgress * 3 + 2 * Math.PI * word.randomAnimOffset) % (2 * Math.PI);
1161         letter.rotation.set(rotation + j, rotation + 2*j, rotation + 3*j);
1162       }
1163     }
1164   }
1166   game.view.renderer.render(scene, game.view.camera);
1169 game['fn'].loadSettings = () => {
1170   let settings = {
1171     'controls': null, // set during first time launch depending on device
1172     'virtualinputleft': false,
1173     'enablehud': false,
1174     'graphics': 1,
1175     'audio': {
1176       'music': 0.5,
1177       'sounds': 0.5,
1178       'theme': null, // actual default value determined after asset loading
1179     },
1180     'feather': 'blue',
1181     'unlocks': [],
1182     'highcontrast': false,
1183     'font': 'standard',
1184     'difficulty': {
1185       'collectingradius': 1,
1186       'speed': 100,
1187     },
1188     'keyboard': {
1189       'up': ['ArrowUp', 'w'],
1190       'right': ['ArrowRight', 'd'],
1191       'down': ['ArrowDown', 's'],
1192       'left': ['ArrowLeft', 'a'],
1193       'tapmode': false,
1194     },
1195   };
1196   let stored;
1197   try {
1198     stored = window['localStorage'].getItem('upInTheAirGameSettings');
1199     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'none';
1200   } catch(error) {
1201     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'block';
1202   }
1203   if(stored) {
1204     let merge = (source, target) => {
1205       for(let k of Object.keys(source)) {
1206         if(source[k] != null && typeof(source[k]) == 'object' && typeof(target[k]) == 'object' && !Array.isArray(target[k])) {
1207           merge(source[k], target[k]);
1208         } else if(k in target) {
1209           target[k] = source[k];
1210         }
1211       }
1212     };
1213     stored = JSON.parse(stored);
1214     merge(stored, settings);
1215   }
1216   const ui = game.ui.root.querySelector('.ui-page.options');
1217   if(settings['controls']) {
1218     ui.querySelector('.controls input[value="' + settings['controls'] + '"]').checked = true;
1219     ui.querySelector('.controls .leftside input').checked = settings['virtualinputleft'];
1220     ui.querySelector('.controls .leftside').style.display = (['touchpad', 'thumbstick'].includes(settings['controls'])) ? 'block' : 'none';
1221     ui.querySelectorAll('.controls p span:not(.' + settings['controls'] + ')').forEach(span => span.style.display = 'none');
1222     ui.querySelector('.controls span.' + settings['controls']).style.display = 'block';
1223   }
1224   ui.querySelector('.hud input[name="upInTheAirGame-hud"]').checked = settings['enablehud'];
1225   game.ui.hud.style.display = settings['enablehud'] ? 'flex' : 'none';
1226   ui.querySelector('.graphics input[value="' + settings['graphics'] + '"]').checked = true;
1227   for(let audioCategory of ['music', 'sounds']) {
1228     let newValue = Math.max(0, Math.min(100, Math.round(100 * settings['audio'][audioCategory])));
1229     game.ui.root.querySelectorAll('.ui-page .audio input[type=range].' + audioCategory).forEach((elem) => {
1230       elem.value = newValue;
1231       elem.parentNode.nextElementSibling.innerText = newValue;
1232     });
1233   }
1234   let audioThemeRadio = ui.querySelector('.audiotheme input[value="' + settings['audio']['theme'] + '"]');
1235   if(audioThemeRadio) {
1236     audioThemeRadio.checked = true;
1237   }
1238   // Custom hash function that ensures our unlockables get stored in the same order,
1239   // regardless of the order in which they get unlocked.
1240   let miniHash = (input) => {
1241     return 4 * input.charCodeAt(0) + 0.1 * input.charCodeAt(1) + 3 * input.charCodeAt(2) + 2 * input.charCodeAt(3);
1242   }
1243   settings['unlocks'].sort((u1, u2) => miniHash(u1) > miniHash(u2));
1244   for(let unlockedFeather of settings['unlocks']) {
1245     if(!game.ui.root.querySelector('.ui-page.options .feather input[value="' + unlockedFeather + '"]')) {
1246       let radio = document.createElement('input');
1247       radio.type = 'radio';
1248       radio.name = 'upInTheAirGame-feather';
1249       radio.value = unlockedFeather;
1250       let img = document.createElement('img');
1251       if(unlockedFeather == 'golden' || unlockedFeather == 'ghost') {
1252         img.src = game['deploymentOptions']['assetUrlPrefix'] + 'textures/feather-' + unlockedFeather + '.png';
1253       } else {
1254         let unlock = game['fn'].unlockWithKey('NIbp2kW5' + unlockedFeather + 'e2ZDFl5Y');
1255         if(unlock && unlock['type'] == 'feather') {
1256           img.src = unlock['url'];
1257         } else {
1258           continue;
1259         }
1260       }
1261       img.alt = unlockedFeather[0].toUpperCase() + unlockedFeather.slice(1) + ' feather';
1262       let label = document.createElement('label');
1263       label.appendChild(radio);
1264       label.appendChild(img);
1265       game.ui.root.querySelector('.ui-page.options .feather').appendChild(label);
1266     }
1267   }
1268   if(!ui.querySelector('.feather input[value="' + settings['feather'] + '"]')) {
1269     settings['feather'] = 'blue';
1270   }
1271   ui.querySelector('.feather input[value=' + settings['feather'] + ']').checked = true;
1272   ui.querySelector('input[value="highcontrast"]').checked = !!settings['highcontrast'];
1273   ui.querySelector('.font input[value=' + settings['font'] + ']').checked = true;
1274   ui.querySelector('.difficulty select.collectingradius option[value="' + settings['difficulty']['collectingradius'] + '"]').selected = true;
1275   ui.querySelector('.difficulty select.speed option[value="' + settings['difficulty']['speed'] + '"]').selected = true;
1276   for(let direction of ['up', 'right', 'down', 'left']) {
1277     let keys = settings['keyboard'][direction];
1278     let btn = ui.querySelector('.keyboard button.' + direction);
1279     btn.value = keys.join('|');
1280     keys = keys.map(k => {
1281       if(k.length == 1 && k != 'ß') {
1282         k = k.toUpperCase();
1283       }
1284       switch(k) {
1285         case 'ArrowUp': return '🠕';
1286         case 'ArrowRight': return '🠖';
1287         case 'ArrowDown': return '🠗';
1288         case 'ArrowLeft': return '🠔';
1289         case ' ': return 'Space';
1290         default: return k;
1291       }
1292     });
1293     btn.innerText = keys.join(' or ');
1294   }
1295   ui.querySelector('input[value="tapmode"]').checked = !!settings['keyboard']['tapmode'];
1296   game.settings = settings;
1299 game['fn'].applySettings = () => {
1300   const ui = game.ui.root.querySelector('.ui-page.options');
1301   if(ui.querySelector('input[name="upInTheAirGame-controls"]:checked')) {
1302     game.settings['controls'] = ui.querySelector('input[name="upInTheAirGame-controls"]:checked').value;
1303   }
1304   game.settings['virtualinputleft'] = ui.querySelector('.controls .leftside input').checked;
1305   if(game.settings['virtualinputleft']) {
1306     game.ui.root.parentNode.classList.add('virtual-input-left');
1307   } else {
1308     game.ui.root.parentNode.classList.remove('virtual-input-left');
1309   }
1310   const virtualInput = game.ui.root.parentNode.querySelector('.virtual-input-widget');
1311   virtualInput.children[0].style.display = 'block';
1312   virtualInput.children[0].style.left = '50%';
1313   virtualInput.children[0].style.top = '50%';
1314   delete virtualInput.inProgress;
1315   if(game.settings['controls'] == 'touchpad') {
1316     virtualInput.classList.remove('thumbstick');
1317     virtualInput.classList.add('touchpad');
1318     game.ui.root.classList.remove('control-mouse', 'control-thumbstick');
1319     game.ui.root.classList.add('control-touchpad');
1320     virtualInput.children[0].style.display = 'none';
1321   } else if(game.settings['controls'] == 'thumbstick') {
1322     virtualInput.classList.remove('touchpad');
1323     virtualInput.classList.add('thumbstick');
1324     game.ui.root.classList.remove('control-mouse', 'control-touchpad');
1325     game.ui.root.classList.add('control-thumbstick');
1326   } else if(game.settings['controls'] == 'mouse') {
1327     virtualInput.classList.remove('touchpad', 'thumbstick');
1328     game.ui.root.classList.remove('control-touchpad', 'control-thumbstick');
1329     game.ui.root.classList.add('control-mouse');
1330   } else {
1331     virtualInput.classList.remove('touchpad', 'thumbstick');
1332     game.ui.root.classList.remove('control-mouse', 'control-touchpad', 'control-thumbstick');
1333   }
1334   for(let timeout of [10, 100, 1000]) {
1335     setTimeout(() => { game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px'; }, timeout);
1336   }
1337   game.settings['graphics'] = parseInt(ui.querySelector('input[name="upInTheAirGame-graphics"]:checked').value, 10);
1338   if(game.view) {
1339     let resolution = Math.round(3200 / Math.pow(2, game.settings['graphics']));
1340     game.view.canvas.width = resolution;
1341     game.view.canvas.height = resolution;
1342     game.view.camera.updateProjectionMatrix();
1343     game.view.renderer.setSize(game.view.canvas.width, game.view.canvas.height);
1344   }
1345   game.settings['enablehud'] = ui.querySelector('.hud input[name="upInTheAirGame-hud"]').checked;
1346   for(let audioCategory of ['music', 'sounds']) {
1347     game.settings['audio'][audioCategory] = parseInt(ui.querySelector('.audio input[type=range].' + audioCategory).value, 10) / 100;
1348   }
1349   let audioThemeRadio = ui.querySelector('.audiotheme input[name="upInTheAirGame-audiotheme"]:checked');
1350   if(audioThemeRadio) {
1351     game.settings['audio']['theme'] = audioThemeRadio.value;
1352   }
1353   game.settings['feather'] = ui.querySelector('input[name="upInTheAirGame-feather"]:checked').value;
1354   game.settings['highcontrast'] = ui.querySelector('input[value="highcontrast"]').checked;
1355   game.settings['font'] = ui.querySelector('input[name="upInTheAirGame-font"]:checked').value;
1356   game.settings['difficulty']['collectingradius'] = parseInt(ui.querySelector('.difficulty select.collectingradius').value, 10);
1357   game.settings['difficulty']['speed'] = parseInt(ui.querySelector('.difficulty select.speed').value, 10);
1358   for(let direction of ['up', 'right', 'down', 'left']) {
1359     game.settings['keyboard'][direction] = ui.querySelector('.keyboard button.' + direction).value.split('|');
1360   }
1361   game.settings['keyboard']['tapmode'] = ui.querySelector('input[value="tapmode"]').checked;
1362   try {
1363     window['localStorage'].setItem('upInTheAirGameSettings', JSON.stringify(game.settings));
1364     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'none';
1365   } catch(error) {
1366     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'block';
1367   }
1369   for(let audioCategory of ['music', 'sounds']) {
1370     game.settings['audio'][audioCategory] = parseInt(ui.querySelector('.audio input[type=range].' + audioCategory).value, 10) / 100;
1371     let value = Math.round(100 * game.settings['audio'][audioCategory]);
1372     game.ui.root.querySelectorAll('.ui-page .audio input[type=range].' + audioCategory).forEach((elem) => {
1373       elem.value = value;
1374       elem.parentNode.nextElementSibling.innerText = value;
1375     });
1376     if(audioCategory == 'music' && game.view && game.view.music) {
1377       game.view.music.setVolume(game.settings['audio'][audioCategory]);
1378     }
1379   }
1380   game.ui.root.classList.remove('font-atkinson', 'font-opendyslexic');
1381   if(game.settings['font'] != 'standard') {
1382     game.ui.root.classList.add('font-' + game.settings['font']);
1383   }
1386 game['fn'].createFeather = () => {
1387   let position, rotation;
1388   if(game.objects.feather) {
1389     position = game.objects.feather.position;
1390     rotation = game.objects.feather.rotation;
1391     game.objects.feather.geometry.dispose();
1392     game.objects.feather.material.dispose();
1393     game.view.scene.remove(game.objects.feather);
1394     delete game.objects.feather;
1395   }
1397   const featherGeometry = new THREE.PlaneGeometry(1.6, 0.5);
1398   let options = {
1399     map: game.assets.textures['feather-' + game.settings['feather']],
1400     transparent: true,
1401     alphaTest: 0.01,
1402     side: THREE.DoubleSide,
1403   }
1404   if(game.settings['feather'] == 'golden') {
1405     options.color = 0xffffff;
1406     options.emissive = 0x644a1e;
1407     options.roughness = 0.5;
1408     options.metalness = 0.4;
1409   }
1410   if(game.settings['feather'] == 'ghost') {
1411     options.opacity = 0.7;
1412   }
1413   game.view.materials.feather = new THREE.MeshStandardMaterial(options);
1414   game.objects.feather = new THREE.Mesh(featherGeometry, game.view.materials.feather);
1415   game.objects.feather.rotation.order = 'ZXY';
1416   if(position) {
1417     game.objects.feather.position.set(position.x, position.y, position.z);
1418   }
1419   if(rotation) {
1420     game.objects.feather.rotation.set(rotation.x, rotation.y, rotation.z);
1421   }
1422   game.view.scene.add(game.objects.feather);
1423   game.objects.feather.speed = new THREE.Vector3(0, 0, 0);
1424   game.gravity = new THREE.Vector3(0, -0.1, 0);
1425   game.objects.feather.swayDirection = 0.2;
1426   game.objects.feather.twistSpeed = 0.1;
1429 game['fn'].createMeshes = () => {
1430   if(game.objects.clouds && game.objects.clouds.parent == game.view.scene) {
1431     game.view.scene.remove(game.objects.clouds);
1432     if(game.objects.clouds.children.length > 0) {
1433       game.objects.clouds.children[0].geometry.dispose();
1434     }
1435     for(let mKey in game.view.materials) {
1436       game.view.materials[mKey].dispose();
1437     }
1438     delete game.objects.clouds;
1439   }
1440   if(game.objects.backdrop && game.objects.backdrop.parent == game.view.scene) {
1441     game.view.scene.remove(game.objects.backdrop);
1442     game.objects.backdrop.material.dispose();
1443     game.objects.backdrop.geometry.dispose();
1444   }
1445   if(game.assets.fonts.geometry) {
1446     for(let geom of Object.values(game.assets.fonts.geometry)) {
1447       if(geom.customMaterial) {
1448         geom.customMaterial.dispose();
1449       }
1450       geom.dispose();
1451     }
1452     delete game.assets.fonts.geometry;
1453   }
1454   if(game.view.materials) {
1455     for(let material of Object.values(game.view.materials)) {
1456       material.dispose();
1457     }
1458     delete game.view.materials;
1459   }
1461   if(game.view.materials && game.view.materials.feather) {
1462     game.view.materials = {
1463       'feather': game.view.materials['feather'],
1464     };
1465   } else {
1466     game.view.materials = {};
1467   }
1469   if(!game.settings['highcontrast']) {
1470     let cloudShaders;
1471     let cloudGeometry = new THREE.PlaneGeometry(1, 200 / 350);
1472     if(game.settings['graphics'] <= 2) {
1473       cloudShaders = {
1474         vertexShader:
1475        `
1476        precision highp float;
1477        precision highp int;
1478        varying vec2 vUv;
1479        void main() {
1480          vUv = uv;
1481          gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1482        }
1483          `,
1484         fragmentShader:
1485          `
1486        precision mediump float;
1487        uniform sampler2D texture1;
1488        uniform sampler2D texture2;
1489        uniform sampler2D texture3;
1490        uniform float lerp;
1491        varying vec2 vUv;
1492        void main() {
1493          if(lerp > 1.0) {
1494            vec4 col1 = texture2D(texture2, vUv);
1495            vec4 col2 = texture2D(texture3, vUv);
1496            gl_FragColor = mix(col1, col2, lerp - 1.0);
1497          } else {
1498            vec4 col1 = texture2D(texture1, vUv);
1499            vec4 col2 = texture2D(texture2, vUv);
1500            gl_FragColor = mix(col1, col2, lerp);
1501          }
1502          // I don't know how GLSL works: why do I need to do this to match the textures?
1503          gl_FragColor = mix(gl_FragColor, vec4(1.0, 1.0, 1.0, gl_FragColor.a), 0.5);
1504        }
1505          `
1506       };
1507     }
1508     for(let i = 0; i < 6; i++) {
1509       if(game.settings['graphics'] <= 2) {
1510         game.view.materials['cloud' + i] = new THREE.ShaderMaterial({
1511           uniforms: THREE.UniformsUtils.merge([{
1512             texture1: null,
1513             texture2: null,
1514             texture3: null,
1515             lerp: null,
1516           }]),
1517           ...cloudShaders,
1518         });
1519         game.view.materials['cloud' + i].uniforms.texture1.value = game.assets.textures['cloud' + i + 'a'];
1520         game.view.materials['cloud' + i].uniforms.texture2.value = game.assets.textures['cloud' + i + 'b'];
1521         game.view.materials['cloud' + i].uniforms.texture3.value = game.assets.textures['cloud' + i + 'c'];
1522         if(game.ui.reachedEnd) {
1523           game.view.materials['cloud' + i].uniforms.lerp.value = 2.0;
1524         } else {
1525           game.view.materials['cloud' + i].uniforms.lerp.value = 0.0;
1526         }
1527         game.view.materials['cloud' + i].transparent = true;
1528       } else {
1529         for(let variant of ['a', 'b', 'c']) {
1530           game.view.materials['cloud' + i + variant] = new THREE.MeshBasicMaterial({
1531             map: game.assets.textures['cloud' + i + variant],
1532             transparent: true,
1533             alphaTest: 0.5,
1534           });
1535           game.view.materials['cloud' + i + variant].name = 'cloud' + i + variant;
1536         }
1537       }
1538     }
1539     game.objects.clouds = new THREE.Group();
1540     let textureVariantSuffix = '';
1541     if(game.settings['graphics'] > 2) {
1542       if(game.ui.reachedEnd) {
1543         textureVariantSuffix = 'c';
1544       } else {
1545         textureVariantSuffix = 'a';
1546       }
1547     }
1548     game.view.materials.letter = new THREE.MeshStandardMaterial({
1549       color: 0xffffff,
1550       emissive: 0x606060,
1551       roughness: 0.4,
1552       metalness: 1,
1553     });
1554     if(game.settings['graphics'] <= 2) {
1555       game.assets.fonts.geometry = {};
1556       for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1557         if(game.settings['graphics'] == 1) {
1558           game.assets.fonts.geometry[letter] = new TextGeometry(letter, {
1559             font: game.assets.fonts.cookie,
1560             size: 0.2,
1561             depth: 0.03,
1562             curveSegments: 2,
1563             bevelEnabled: false,
1564           });
1565           game.assets.fonts.geometry[letter].computeBoundingBox();
1566           let bbox = game.assets.fonts.geometry[letter].boundingBox;
1567           // Add these to local 0,0 later to get the letter's center rotation point
1568           game.assets.fonts.geometry[letter].dx = (bbox.max.x - bbox.min.x) / 2;
1569           game.assets.fonts.geometry[letter].dy = (bbox.max.y - bbox.min.y) / 2;
1570         } else {
1571           let letterCanvas = document.createElement('canvas');
1572           letterCanvas.width = 64;
1573           letterCanvas.height = 64;
1574           let letterCanvasContext = letterCanvas.getContext('2d');
1575           letterCanvasContext.font = '60px Cookie';
1576           letterCanvasContext.fillStyle = '#000';
1577           letterCanvasContext.fillRect(0, 0, letterCanvas.width, letterCanvas.height);
1578           letterCanvasContext.fillStyle = '#fff';
1579           let bbox = letterCanvasContext.measureText(letter);
1580           let vOffset = bbox.actualBoundingBoxAscent - 0.5 * (bbox.actualBoundingBoxAscent + bbox.actualBoundingBoxDescent);
1581           letterCanvasContext.fillText(letter, Math.round((letterCanvas.width - bbox.width) / 2), (letterCanvas.height / 2) + vOffset);
1582           let alphaMap = new THREE.CanvasTexture(letterCanvas);
1583           alphaMap.needsUpdate = true;
1584           let letterMaterial = new THREE.MeshStandardMaterial({
1585             color: game.view.materials.letter.color,
1586             emissive: 0x303030,
1587             roughness: game.view.materials.letter.roughness,
1588             metalness: game.view.materials.letter.metalness,
1589             side: THREE.DoubleSide,
1590             alphaMap: alphaMap,
1591             transparent: true,
1592           });
1593           game.assets.fonts.geometry[letter] = new THREE.PlaneGeometry(0.3, 0.3);
1594           game.assets.fonts.geometry[letter].dx = 0;
1595           game.assets.fonts.geometry[letter].dy = 0;
1596           game.assets.fonts.geometry[letter].customMaterial = letterMaterial;
1597         }
1598       }
1599       let numClouds = 300;
1600       if(game.settings['graphics'] == 2) {
1601         numClouds = 75;
1602       }
1603       for(let i = 0; i < numClouds; i++) {
1604         let randomAngle = Math.random() * 2 * Math.PI;
1605         let randomCameraX = game.courseRadius * Math.sin(randomAngle);
1606         let randomCameraY = game.courseRadius * Math.cos(randomAngle);
1607         let cloud = new THREE.Mesh(cloudGeometry, game.view.materials['cloud' + (i % 5 + 1) + textureVariantSuffix]);
1608         cloud.position.z = -15 - Math.round(Math.random() * 40);
1609         const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
1610         let maxCameraDistance = 2 * Math.tan(vFOV / 2) * Math.abs(cloud.position.z - game.view.camera.position.z);
1611         cloud.position.x = randomCameraX + maxCameraDistance * 2 * (Math.random() - 0.5);
1612         cloud.position.y = randomCameraY + maxCameraDistance * 2 * (Math.random() - 0.5);
1613         let scale = 21 + (Math.random() * 0.5 + 0.5) * Math.abs(cloud.position.z);
1614         cloud.scale.set(scale, scale, scale);
1615         game.objects.clouds.add(cloud);
1616       }
1617     } else {
1618       const minimalLetterGeometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
1619       minimalLetterGeometry.dx = 0;
1620       minimalLetterGeometry.dy = 0;
1621       game.assets.fonts.geometry = {};
1622       for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1623         game.assets.fonts.geometry[letter] = minimalLetterGeometry;
1624       }
1625       for(let r = 0; r < game.courseRadius / 3; r++) {
1626         let angle = THREE.MathUtils.degToRad(360 * 3 * r / game.courseRadius);
1627         let cameraX = game.courseRadius * Math.sin(angle);
1628         let cameraY = game.courseRadius * Math.cos(angle);
1629         const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
1630         let z = -15;
1631         let maxCameraDistance = Math.tan(vFOV / 2) * Math.abs(z - game.view.camera.position.z);
1632         let axis = [-1, 0, 1];
1633         if(r % 2 == 0) {
1634           axis = [-0.5, 0.5];
1635         }
1636         for(let step of axis) {
1637           let shape = 1 + Math.floor(Math.random() * 5);
1638           let cloud = new THREE.Mesh(cloudGeometry, game.view.materials['cloud' + shape + textureVariantSuffix]);
1639           cloud.position.x = cameraX + step * 1.2 * maxCameraDistance * Math.sin(angle);
1640           cloud.position.y = cameraY + step * maxCameraDistance * Math.cos(angle);
1641           cloud.position.z = z;
1642           let scale = 15 + 0.5 * Math.abs(cloud.position.z);
1643           cloud.scale.set(scale, scale, scale);
1644           game.objects.clouds.add(cloud);
1645         }
1646       }
1647     }
1648     game.view.scene.add(game.objects.clouds);
1649     game.objects.backdrop = new THREE.Mesh(new THREE.PlaneGeometry(350, 350), game.view.materials['cloud0' + textureVariantSuffix]);
1650     game.objects.backdrop.position.setZ(-100);
1651   } else {
1652     game.view.materials.letter = new THREE.MeshStandardMaterial({
1653       color: 0x00ff00,
1654       emissive: 0x00ff00,
1655     });
1656     const highcontrastLetterGeometry = new THREE.SphereGeometry(0.1, 16, 16);
1657     highcontrastLetterGeometry.dx = 0;
1658     highcontrastLetterGeometry.dy = 0;
1659     game.assets.fonts.geometry = {};
1660     for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1661       game.assets.fonts.geometry[letter] = highcontrastLetterGeometry;
1662     }
1663     const highContrastBackdropMaterial = new THREE.MeshBasicMaterial({
1664       map: game.assets.textures['highcontrast-backdrop'],
1665     });
1666     game.objects.backdrop = new THREE.Mesh(new THREE.PlaneGeometry(150, 150), highContrastBackdropMaterial);
1667     game.objects.backdrop.position.setZ(-10);
1668   }
1669   if(game.objects.words) {
1670     for(let word of game.objects.words) {
1671       game['fn'].prepareWordMesh(word);
1672     }
1673   }
1674   game.view.scene.add(game.objects.backdrop);
1677 game['fn'].unlockFeather = (feather, url) => {
1678   if(game.settings['unlocks'].includes(feather)) {
1679     return false;
1680   }
1681   game.settings['unlocks'].push(feather);
1682   if(!url) {
1683     url = game['deploymentOptions']['assetUrlPrefix'] + 'textures/feather-' + feather + '.png';
1684   } else if(url.startsWith('textures/')) {
1685     url = game['deploymentOptions']['assetUrlPrefix'] + url;
1686   }
1688   if(!game.assets['textures']['feather-' + feather]) {
1689     (new THREE.TextureLoader()).load(url, (result) => {
1690       result.colorSpace = THREE.SRGBColorSpace;
1691       result.minFilter = THREE.NearestFilter;
1692       result.magFilter = THREE.NearestFilter;
1693       result.repeat = new THREE.Vector2(1, -1);
1694       result.wrapT = THREE.RepeatWrapping;
1695       game.assets['textures']['feather-' + feather] = result;
1696     }, () => {}, (err) => {
1697       console.error('Error while loading ' + feather + ' feather texture: ' + err);
1698     });
1699   }
1700   // Custom hash function that ensures our unlockables get stored in the same order,
1701   // regardless of the order in which they get unlocked.
1702   let miniHash = (input) => {
1703     return 4 * input.charCodeAt(0) + 0.1 * input.charCodeAt(1) + 3 * input.charCodeAt(2) + 2 * input.charCodeAt(3);
1704   }
1705   game.settings['unlocks'].sort((u1, u2) => miniHash(u1) > miniHash(u2));
1706   let insertAfterFeather = 'purple';
1707   if(game.settings['unlocks'].indexOf(feather) >= 1) {
1708     insertAfterFeather = game.settings['unlocks'][game.settings['unlocks'].indexOf(feather) - 1];
1709   }
1710   let radio = document.createElement('input');
1711   radio.type = 'radio';
1712   radio.name = 'upInTheAirGame-feather';
1713   radio.value = feather;
1714   radio.addEventListener('change', () => {
1715     game['fn'].applySettings();
1716     game['fn'].createFeather();
1717   });
1718   let img = document.createElement('img');
1719   img.src = url;
1720   img.alt = feather[0].toUpperCase() + feather.slice(1) + ' feather';
1721   let label = document.createElement('label');
1722   label.appendChild(radio);
1723   label.appendChild(img);
1724   game.ui.root.querySelector('.ui-page.options .feather input[value="' + insertAfterFeather + '"]').parentNode.after(label);
1725   game['fn'].applySettings();
1726   let ui = game.ui.root.querySelector('.ui-page.unlock');
1727   let img2 = ui.querySelector('img');
1728   img2.src = img.src;
1729   img2.alt = img.alt;
1730   ui.querySelector('p.name').innerText = img2.alt;
1731   return true;
1734 game['fn'].moveToPage = (target, skipFade = false) => {
1735   let fadeDuration = 250;
1736   if(skipFade) {
1737     fadeDuration = 0;
1738   }
1739   // After the gameplay page is shown for the first time, always keep it around as a backdrop
1740   game.ui.root.querySelectorAll('.ui-page:not(.' + target + '):not(.gameplay)').forEach((page) => {
1741     page.style.opacity = '0';
1742     setTimeout((page) => {
1743       page.style.display = 'none';
1744     }, fadeDuration, page);
1745   });
1746   if(game.ui.currentPage == 'title' && !game.ui.reachedStart) {
1747     setTimeout(() => {
1748       game.ui.root.querySelector('.ui-page.title h1').removeAttribute('style');
1749       game.ui.root.querySelectorAll('.ui-page.title button').forEach(btn => { btn.disabled = false; btn.removeAttribute('style'); });
1750       game.ui.root.querySelector('.ui-page.title .footer').removeAttribute('style');
1751       game.ui.root.querySelector('.ui-page.title .system-buttons').removeAttribute('style');
1752       game.ui.reachedStart = true;
1753     }, fadeDuration);
1754   }
1755   if(target == 'title' && game.view) {
1756     game.view.cheatBuffer = '';
1757   }
1758   if(target == 'title' && (!game.ui.currentPage || ['loading', 'controls'].includes(game.ui.currentPage))) {
1759     game['fn'].initializeGame(game.ui.root.querySelector('canvas'));
1760   }
1761   if(target == 'title' && game.ui.root.querySelector('.ui-page.gameplay p')) {
1762     game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach(elem => elem.remove());
1763   }
1764   if(target == 'title' && game.view && game.view.windSound && game.view.windSound.isPlaying) {
1765     game.view.windSound.stop();
1766   }
1767   if(target == 'title' && game.view && game.view.music && game.view.music.isPlaying) {
1768     game.view.music.stop();
1769     if(game.view.music.timeoutID) {
1770       clearTimeout(game.view.music.timeoutID);
1771       delete game.view.music.timeoutID;
1772     }
1773   }
1774   if((target != 'pause' && game.ui.currentPage != 'pause') || target == 'title') {
1775     game.ui.hud.style.opacity = '0';
1776   }
1777   if(target == 'outro') {
1778     if(game.view.music.isPlaying) {
1779       game.view.music.stop();
1780     }
1781     let collectedWords = game.objects.words.filter(w => w.collected).map(w => w.text);
1782     game.ui.root.querySelector('.ui-page.outro .count').innerText = game.objects.words.collectedCount;
1783     game.ui.root.querySelector('.ui-page.outro .optionalPlural').innerText = 'word' + ((game.objects.words.collectedCount == 1) ? '' : 's') + '.';
1784     let ratingElem = game.ui.root.querySelector('.ui-page.outro .rating');
1785     let exampleElems = game.ui.root.querySelectorAll('.ui-page.outro .examples');
1786     let finalParagraph = game.ui.root.querySelector('.ui-page.outro .area > p:last-child');
1787     ratingElem.style.display = 'none';
1788     exampleElems.forEach(elem => { elem.style.display = 'none'; });
1789     let returnButton = game.ui.root.querySelector('.ui-page.outro button.goto');
1790     if(game.objects.words.collectedCount == 100 || game.objects.words.collectedCount == 0) {
1791       finalParagraph.style.display = 'none';
1792       let neededUnlocking = false;
1793       if(game.objects.words.collectedCount == 100) {
1794         neededUnlocking = game['fn'].unlockFeather('golden');
1795       } else {
1796         neededUnlocking = game['fn'].unlockFeather('ghost');
1797       }
1798       if(neededUnlocking) {
1799         returnButton.innerText = 'Continue';
1800         returnButton.classList.remove('title');
1801         returnButton.classList.add('unlock');
1802       } else {
1803         returnButton.innerText = 'Return to Title Screen';
1804         returnButton.classList.remove('unlock');
1805         returnButton.classList.add('title');
1806       }
1807     } else {
1808       finalParagraph.style.display = 'block';
1809       returnButton.innerText = 'Return to Title Screen';
1810       returnButton.classList.remove('unlock');
1811       returnButton.classList.add('title');
1812     }
1813     if(game.objects.words.collectedCount > 0) {
1814       if(game.objects.words.collectedCount == 100) {
1815         ratingElem.style.display = 'block';
1816         ratingElem.innerText = 'Wow, you managed to collect all of them. Congratulations!';
1817       } else {
1818         let generateExampleSentences = (wordList) => {
1819           let container = game.ui.root.querySelector('.ui-page.outro div.examples');
1820           while(container.children.length > 0) {
1821             container.children[0].remove();
1822           }
1823           let words = {};
1824           for(let category of Object.keys(game.assets.words)) {
1825             words[category] = [];
1826             for(let word of game.assets.words[category]) {
1827               if(wordList.includes(word)) {
1828                 words[category].push(word);
1829               }
1830             }
1831           }
1832           let result = [];
1833           let failedAttempts = 0;
1834           while(result.length < 3 && failedAttempts < 1000) {
1835             let sentence = game.assets.sentences[Math.floor(Math.random() * game.assets.sentences.length)];
1836             while(sentence.indexOf('{') > -1) {
1837               let areWeStuck = true;
1838               for(let category of Object.keys(words)) {
1839                 if(sentence.includes('{' + category + '}')) {
1840                   if(words[category].length == 0) {
1841                     break;
1842                   }
1843                   let choice = words[category][Math.floor(Math.random() * words[category].length)];
1844                   if(category == 'sorry') {
1845                     if(choice == 'sorry') {
1846                       sentence = sentence.replace('{sorry}', 'I’m {sorry}');
1847                     }
1848                     if(choice == 'apologize') {
1849                       sentence = sentence.replace('{sorry}', 'I {sorry}');
1850                     }
1851                   }
1852                   if(sentence.indexOf('{' + category + '}') == 0) {
1853                     choice = choice[0].toUpperCase() + choice.slice(1);
1854                   }
1855                   sentence = sentence.replace('{' + category + '}', '<strong>' + choice + '</strong>');
1856                   words[category].splice(words[category].indexOf(choice), 1);
1857                   areWeStuck = false;
1858                 }
1859               }
1860               if(areWeStuck) {
1861                 break;
1862               }
1863             }
1864             if(sentence.indexOf('{') == -1 && !result.includes(sentence)) {
1865               result.push(sentence);
1866               failedAttempts = 0;
1867             }
1868             failedAttempts += 1;
1869           }
1870           for(let sentence of result) {
1871             let elem = document.createElement('p');
1872             elem.innerHTML = sentence;
1873             container.appendChild(elem);
1874           }
1875         };
1876         generateExampleSentences(collectedWords);
1877         game.ui.root.querySelector('.ui-page.outro button.examples').addEventListener('click', () => { generateExampleSentences(collectedWords); });
1878         exampleElems.forEach(elem => { elem.style.display = 'flex'; });
1879       }
1880     } else {
1881       ratingElem.style.display = 'block';
1882       ratingElem.innerText = 'You completed the course while dodging every word. That’s an achievement all on its own. Respect!';
1883     }
1884   }
1885   if(target == 'options') {
1886     game.ui.root.querySelectorAll('.options .areatabs button').forEach((btn) => {
1887       if(btn.classList.contains('general')) {
1888         btn.classList.add('active');
1889       } else {
1890         btn.classList.remove('active');
1891       }
1892     });
1893     game.ui.root.querySelectorAll('.options > div.area.twocol').forEach((area) => {
1894       if(area.classList.contains('general')) {
1895         area.style.display = 'flex';
1896       } else {
1897         area.style.display = 'none';
1898       }
1899     });
1900   }
1901   const targetElems = [game.ui.root.querySelector('.ui-page.' + target + '')];
1902   if(game.ui.root.querySelector('.ui-page.gameplay').style.opacity != '1' && target == 'title') {
1903     targetElems.push(game.ui.root.querySelector('.ui-page.gameplay'));
1904   }
1905   for(let targetElem of targetElems) {
1906     if(!targetElem.classList.contains('gameplay')) {
1907       targetElem.style.opacity = '0';
1908     }
1909     targetElem.style.display = 'flex';
1910     setTimeout((targetElem) => {
1911       targetElem.style.opacity = '1';
1912       if(target == 'credits') {
1913         targetElem.querySelector('.area').scrollTop = 0;
1914       }
1915     }, fadeDuration, targetElem);
1916   }
1917   if(target != 'pause' && game.ui.currentPage != 'pause') {
1918     game.timeProgress = 0;
1919   }
1920   if(target == 'pause') {
1921     game.view.music.stop();
1922     game.view.windSound.stop();
1923   } else if(game.ui.currentPage == 'pause' && target == 'openingcutscene') {
1924     if(game.timeProgress >= 1.0) {
1925       game.view.windSound.offset = game.timeProgress - 1.0;
1926       game.view.windSound.setVolume(game.settings['audio']['sounds']);
1927       if(!game.view.muted) {
1928         game.view.windSound.play();
1929       }
1930     }
1931   } else if(game.ui.currentPage == 'pause' && target == 'gameplay') {
1932     game.view.music.offset = (game.timeProgress / (game.settings['difficulty']['speed'] / 100)) % game.assets['audio']['music-' + game.settings['audio']['theme']].duration;
1933     if(!game.view.muted) {
1934       game.view.music.play();
1935     }
1936   }
1937   game.ui.previousPage = game.ui.currentPage;
1938   game.ui.currentPage = target;
1939   if(game.view) {
1940     game.startTime = game.view.clock.getElapsedTime();
1941   }
1944 game['fn'].unlockWithKey = (input) => {
1945   input = 'aBYPmb2xCwF2ilfD'+ input + 'PNHFwI2zKZejUv6c';
1946   let hash = (input) => {
1947     // Adapted with appreciation from bryc:
1948     // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
1949     let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
1950     for(let i = 0, ch; i < input.length; i++) {
1951       ch = input.charCodeAt(i);
1952       h1 = Math.imul(h1 ^ ch, 2654435761);
1953       h2 = Math.imul(h2 ^ ch, 1597334677);
1954     }
1955     h1  = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
1956     h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
1957     h2  = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
1958     h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
1959     return (h2 >>> 0).toString(16).padStart(8, 0) + (h1 >>> 0).toString(16).padStart(8, 0);
1960   }
1961   for(let unlockable of game.unlockables) {
1962     if(unlockable.accessKey == hash(input)) {
1963       let key = hash('UZx2jWen9w5jm0FB' + input + '7DZpEq4OOwv2kiJ1');
1964       let seed = parseInt(key.slice(12), 16);
1965       let prng = () => {
1966         seed |= 0;
1967         seed = seed + 0x9e3779b9 | 0;
1968         let t = seed ^ seed >>> 16;
1969         t = Math.imul(t, 0x21f0aaad);
1970         t = t ^ t >>> 15;
1971         t = Math.imul(t, 0x735a2d97);
1972         return ((t = t ^ t >>> 15) >>> 0);
1973       };
1974       let data = Uint8Array.from(atob(unlockable.payload), (c) => c.codePointAt(0));
1975       let pad;
1976       for(let i = 0; i < data.length; i++) {
1977         if(i % 4 == 0) {
1978           pad = prng();
1979           pad = [pad % 256, (pad >> 8) % 256, (pad >> 16) % 256, (pad >> 24) % 256];
1980         }
1981         data[i] = data[i] ^ pad[i % 4];
1982       }
1983       data = new TextDecoder().decode(data);
1984       let result = JSON.parse(data);
1985       if(result['type'] == 'redirect') {
1986         return game['fn'].unlockWithKey(result['target']);
1987       } else {
1988         return result;
1989       }
1990     }
1991   }
1992   return null;
1993 };
1995 game['fn'].start = () => {
1996   game.ui = {
1997     root: document.querySelector('.upInTheAirGame .ui-container'),
1998     hud: document.querySelector('.upInTheAirGame .gameplay .hud'),
1999     gamepads: [],
2000   };
2001   game.settings = {};
2002   // If you're looking at the source code and the following seems scary, don't worry, it's just a few
2003   // unlockable feather textures. I liked easter eggs and cheat codes when I was young, and I didn't
2004   // want these to be trivially bypassable for people who can read the code.
2005   game.unlockables = [
2006     {
2007       'accessKey': '5b32eb7ad08488f4',
2008       'payload': 'k4JPu3sWfEhcgleieVGghixKSI10qdRRC5tAl39Tzy1U7Rx9EEEYbLx9wCcxAf7wC8r9mJZCOj8bNa7grMbUmTeCeWWPAg==',
2009     },
2010     {
2011       'accessKey': '6273da5894b2dd8b',
2012       'payload': 'XAFLhAjcTzsWgGb7DAMCKwHXjoyUg/yxkIUyLcV/7PpktgW3MHtXhh4OkVeANr52RfdbwfVpgO4dxuyYPaFZ4x4JDmI=',
2013     },
2014     {
2015       'accessKey': 'fb8b533451a6dd68',
2016       'payload': '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',
2017     },
2018     {
2019       'accessKey': '3c78e25c7b1106b6',
2020       'payload': 'dnbO28tXI2i2+o+etuRc0/Cfxd4UpdG1IRgqB0fTwJE1xCoK+TtB/JVGTquaD/stnIkKiA==',
2021     },
2022     {
2023       'accessKey': '5f79141f861a146a',
2024       'payload': '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',
2025     },
2026     {
2027       'accessKey': 'c2cfaaebb10f00ab',
2028       'payload': 'CAVH/4AwEJzNt950XEAZP3Q92fMNasIje6K5FSBgjqchkxmrFxjlNHjadnrHWdqM+zrB',
2029     },
2030     {
2031       'accessKey': '130b037dadbe1d7a',
2032       'payload': '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',
2033     },
2034     {
2035       'accessKey': 'd8e8dd84f4b0c103',
2036       'payload': 'EGKsJYSjVVaxCBWPRUGjWuLMl3k7fB/7uKYp8wz28r/5XTaOJF7LnbPMpBwysAR8IR/whArG',
2037     },
2038   ];
2040   game['fn'].loadSettings();
2041   game['fn'].applySettings();
2043   if(game.ui.root.querySelectorAll('.ui-page.credits .area h3').length > 3) {
2044     // If the credits have more than three third-level headers, that means we are
2045     // in the freeware version and can make the CSS adjustments it needs.
2046     let css = document.styleSheets[0];
2047     css.insertRule('.upInTheAirGame .ui-page.credits .person { position: relative; height: 4em; padding-left: calc(4em + 1ex); display: flex; flex-direction: column; justify-content: center; }');
2048     css.insertRule('.upInTheAirGame .ui-page.credits .person::before { content: " "; position: absolute; left: 0; box-sizing: border-box; width: 4em; height: 4em; background-size: contain; border-radius: .6em; border: .1em solid #d53c59; }');
2049     game.ui.root.querySelectorAll('.ui-page.credits .area .person').forEach((person) => {
2050       let personName = Array.from(person.classList).filter(c => c != 'person')[0];
2051       let imageFormat = (personName == 'nina') ? 'png' : 'jpg';
2052       css.insertRule('.upInTheAirGame .ui-page.credits .person.' + personName + '::before { background-image: url("' + game['deploymentOptions']['assetUrlPrefix'] + 'textures/person-' + personName + '.' + imageFormat + '"); }');
2053     });
2054   }
2056   game.ui.root.querySelectorAll('button.goto').forEach((btn) => {
2057     btn.addEventListener('click', (e) => {
2058       if(game.view && !game.view.music) {
2059         game.view.audioListener = new THREE.AudioListener();
2060         game.view.camera.add(game.view.audioListener);
2061         game.view.music = new THREE.Audio(game.view.audioListener);
2062         game.view.music.setBuffer(game.assets['audio']['music-' + game.settings['audio']['theme']]);
2063         game.view.music.setVolume(game.settings['audio']['music']);
2064         game.view.windSound = new THREE.Audio(game.view.audioListener);
2065         game.view.windSound.setBuffer(game.assets['audio']['wind']);
2066         game.view.windSound.setVolume(game.settings['audio']['sounds']);
2067         game.view.windSound.setLoop(false);
2068       }
2069       let btn = e.target.closest('button');
2070       let target = Array.from(btn.classList).filter(c => c != 'goto')[0];
2071       if(target == 'previous') {
2072         target = game.ui.previousPage;
2073       }
2074       game['fn'].moveToPage(target);
2075     });
2076   });
2078   game.ui.root.querySelectorAll('.options .controls input, .options .graphics input, .options .hud input, .options .feather input, .options .accessibility input, .options .accessibility select').forEach((elem) => {
2079     elem.addEventListener('change', () => {
2080       game['fn'].applySettings();
2081       if(elem.name == 'upInTheAirGame-controls') {
2082         game.ui.root.querySelector('.controls .leftside').style.display = (['touchpad', 'thumbstick'].includes(game.settings['controls'])) ? 'block' : 'none';
2083         game.ui.root.querySelectorAll('.options .controls p span:not(.' + game.settings['controls'] + ')').forEach(span => span.style.display = 'none');
2084         game.ui.root.querySelector('.options .controls span.' + game.settings['controls']).style.display = 'block';
2085       } else if(elem.value == 'highcontrast' || elem.name == 'upInTheAirGame-graphics') {
2086         game['fn'].createMeshes();
2087       } else if(elem.name == 'upInTheAirGame-feather') {
2088         game['fn'].createFeather();
2089       }
2090     });
2091   });
2093   game.ui.root.querySelector('.ui-page.title .system-buttons input').addEventListener('change', (e) => {
2094     game.view.muted = e.target.checked;
2095   });
2097   game.ui.root.querySelector('.ui-page.title .system-buttons button').addEventListener('click', (e) => {
2098     if(document.fullscreenElement == game.ui.root.parentNode) {
2099       document.exitFullscreen();
2100     } else {
2101       game.ui.root.parentNode.requestFullscreen();
2102     }
2103   });
2105   game.ui.root.querySelectorAll('.ui-page .audio input[type=range]').forEach((elem) => {
2106     elem.addEventListener('input', (e) => {
2107       let audioCategory = Array.from(e.target.classList).filter(v => ['music', 'sounds'].includes(v))[0];
2108       game.ui.root.querySelector('.ui-page.options .audio input[type=range].' + audioCategory).value = e.target.value;
2109       game['fn'].applySettings();
2110     });
2111   });
2113   game.ui.root.querySelectorAll('.options .audio button').forEach((btn) => {
2114     btn.addEventListener('click', (e) => {
2115       if(e.target.classList.contains('music')) {
2116         if(game.view.music.isPlaying) {
2117           game.view.music.stop();
2118           if(game.view.music.timeoutID) {
2119             clearTimeout(game.view.music.timeoutID);
2120             delete game.view.music.timeoutID;
2121           }
2122         } else {
2123           game.view.music.offset = 36;
2124           if(!game.view.muted) {
2125             game.view.music.play();
2126           }
2127           game.view.music.timeoutID = setTimeout(() => {
2128             game.view.music.stop();
2129           }, 6000);
2130         }
2131       } else if(e.target.classList.contains('sounds')) {
2132         game['fn'].playRandomSound();
2133       }
2134     });
2135   });
2137   game.ui.root.querySelectorAll('.options .keyboard label button').forEach((btn) => {
2138     btn.addEventListener('click', () => {
2139       if(game.ui.root.querySelector('.ui-page.keyboard-modal')) {
2140         return;
2141       }
2142       const keyboardModal = document.createElement('div');
2143       keyboardModal.classList.add('ui-page', 'keyboard-modal');
2144       const instruction = document.createElement('span');
2145       const direction = btn.classList[0];
2146       keyboardModal.classList.add(direction);
2147       instruction.innerText = 'Please press the key for “' + direction[0].toUpperCase() + direction.slice(1) + '”';
2148       keyboardModal.appendChild(instruction);
2149       game.ui.root.appendChild(keyboardModal);
2150     });
2151   });
2153   game.ui.root.querySelector('.options .keyboard button[value="reset"]').addEventListener('click', (e) => {
2154     const container = e.target.parentNode;
2155     container.querySelector('button.up').value = 'ArrowUp|w';
2156     container.querySelector('button.right').value = 'ArrowRight|d';
2157     container.querySelector('button.down').value = 'ArrowDown|s';
2158     container.querySelector('button.left').value = 'ArrowLeft|a';
2159     game['fn'].applySettings();
2160     game['fn'].loadSettings();
2161   });
2163   game.ui.root.querySelectorAll('.ui-page .areatabs button').forEach((btn) => {
2164     btn.addEventListener('click', (e) => {
2165       btn.parentNode.querySelectorAll('button').forEach((otherBtn) => {
2166         otherBtn.classList.remove('active');
2167         let val = otherBtn.classList[0];
2168         otherBtn.closest('.ui-page').querySelector('div.' + val).style.display = 'none';
2169       });
2170       btn.classList.add('active');
2171       let val = Array.from(btn.classList).filter(c => c != 'active')[0];
2172       btn.closest('.ui-page').querySelector('div.' + val).style.display = 'flex';
2173     });
2174   });
2176   game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px';
2177   window.addEventListener('resize', () => {
2178     game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px';
2179   });
2181   window.addEventListener('scroll', () => {
2182     if(!['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2183       return;
2184     }
2185     let bbox = game.ui.root.querySelector('canvas').getBoundingClientRect();
2186     if(bbox.bottom < -100 || bbox.top - bbox.height > 100 || bbox.left + bbox.width < -100 || bbox.left - window.innerWidth > 100) {
2187       game['fn'].moveToPage('pause', true);
2188     }
2189   });
2190   window.addEventListener('blur', () => {
2191     if(['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2192       game['fn'].moveToPage('pause', true);
2193     }
2194   });
2196   document.addEventListener('keydown', (e) => {
2197     const keyboardModal = game.ui.root.querySelector('.keyboard-modal');
2198     if(keyboardModal) {
2199       const direction = [...keyboardModal.classList].filter(c => c != 'ui-page' && c != 'keyboard-modal')[0];
2200       if(e.key != 'Escape') {
2201         game.ui.root.querySelector('.options .keyboard label button.' + direction).value = e.key;
2202         game['fn'].applySettings();
2203         game['fn'].loadSettings();
2204       }
2205       keyboardModal.remove();
2206       e.preventDefault();
2207       e.stopPropagation();
2208       return;
2209     }
2210     if(game.ui.currentPage == 'title' && e.key.match(/[a-z]/)) {
2211       game.view.cheatBuffer = (game.view.cheatBuffer + e.key).slice(-25);
2212       for(let len = 10; len <= 25; len++) {
2213         if(game.view.cheatBuffer.length < len) {
2214           break;
2215         }
2216         let unlock = game['fn'].unlockWithKey(game.view.cheatBuffer.slice(-len));
2217         if(unlock && unlock['type'] == 'feather' && !game.settings['unlocks'].includes(unlock['name'])) {
2218           game['fn'].playRandomSound();
2219           game['fn'].unlockFeather(unlock['name'], unlock['url']);
2220           game['fn'].moveToPage('unlock');
2221         }
2222       }
2223       return;
2224     }
2225     if(e.key == 'Escape') {
2226       if(['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2227         game['fn'].moveToPage('pause', true);
2228       } else if(game.ui.currentPage == 'pause') {
2229         game['fn'].moveToPage(game.ui.previousPage, true);
2230       }
2231     }
2232   });
2234   window.addEventListener('gamepadconnected', (e) => {
2235     game.ui.gamepads.push(e.gamepad);
2236   });
2237   window.addEventListener('gamepaddisconnected', (e) => {
2238     if(game.ui.gamepads.includes(e.gamepad)) {
2239       game.ui.gamepads.splice(game.ui.gamepads.indexOf(e.gamepad), 1);
2240     }
2241   });
2243   game.ui.root.querySelector('.ui-page.pause button.title').addEventListener('click', () => {
2244     game['fn'].reset();
2245   });
2247   game['fn'].loadAllAssets((progress) => {
2248     let percentage = Math.floor(100 * progress);
2249     game.ui.root.querySelector('.ui-page.loading progress').value = percentage;
2250     game.ui.root.querySelector('.ui-page.loading span').innerText = percentage;
2251   }).then(() => {
2252     if(window.location.hostname == 'fietkau.media' && window.location.pathname == '/up_in_the_air') {
2253       game.ui.root.querySelector('.ui-page.title .footer span:last-child').remove();
2254     }
2255     let controlsInterstitial = false;
2256     if(!game.settings['controls']) {
2257       controlsInterstitial = true;
2258       let control;
2259       if(matchMedia('(hover: hover)').matches) {
2260         control = 'mouse';
2261       } else {
2262         control = 'touchpad';
2263       }
2264       game.ui.root.querySelector('.controls input[value="' + control + '"]').checked = true;
2265       game['fn'].applySettings();
2266       game['fn'].loadSettings();
2267       game.ui.root.querySelectorAll('.ui-page.controls .' + ((control == 'mouse') ? 'touchpad' : 'mouse')).forEach(elem => elem.remove());
2268     }
2269     if(!game.assets.audiothemes.includes(game.settings['audio']['theme'])) {
2270       game.settings['audio']['theme'] = game.assets.audiothemes[0];
2271     }
2272     if(game.assets.audiothemes.length == 1) {
2273       game.ui.root.querySelector('.ui-page.options .audiotheme').style.display = 'none';
2274     }
2275     let container = game.ui.root.querySelector('.ui-page.options .audiotheme');
2276     for(let audioTheme of game.assets.audiothemes) {
2277       let snippet = container.children[0].content.cloneNode(true).children[0];
2278       snippet.children[0].value = audioTheme;
2279       if(audioTheme == game.settings['audio']['theme']) {
2280         snippet.children[0].checked = true;
2281       }
2282       snippet.children[0].addEventListener('change', () => {
2283         game['fn'].applySettings();
2284         game.view.music.setBuffer(game.assets['audio']['music-' + game.settings['audio']['theme']]);
2285       });
2286       snippet.childNodes[1].textContent = ' ' + audioTheme[0].toUpperCase() + audioTheme.slice(1);
2287       container.appendChild(snippet);
2288     }
2289     if(controlsInterstitial) {
2290       game['fn'].moveToPage('controls');
2291     } else {
2292       game['fn'].moveToPage('title');
2293     }
2294   }, (err) => {
2295     console.error(err);
2296   });
2298 };
2300 // Set up name mirrors for each function that should survive most minifiers and transpilers
2301 game['fn'].animate['friendlyName'] = 'animate';
2302 game['fn'].applyForceToFeather['friendlyName'] = 'applyForceToFeather';
2303 game['fn'].applySettings['friendlyName'] = 'applySettings';
2304 game['fn'].createFeather['friendlyName'] = 'createFeather';
2305 game['fn'].createMeshes['friendlyName'] = 'createMeshes';
2306 game['fn'].easeInOut['friendlyName'] = 'easeInOut';
2307 game['fn'].initializeGame['friendlyName'] = 'initializeGame';
2308 game['fn'].lerp['friendlyName'] = 'lerp';
2309 game['fn'].loadAllAssets['friendlyName'] = 'loadAllAssets';
2310 game['fn'].loadSettings['friendlyName'] = 'loadSettings';
2311 game['fn'].moveToPage['friendlyName'] = 'moveToPage';
2312 game['fn'].playRandomSound['friendlyName'] = 'playRandomSound';
2313 game['fn'].prepareWordMesh['friendlyName'] = 'prepareWordMesh';
2314 game['fn'].reset['friendlyName'] = 'reset';
2315 game['fn'].start['friendlyName'] = 'start';
2316 game['fn'].unlockFeather['friendlyName'] = 'unlockFeather';
2317 game['fn'].unlockWithKey['friendlyName'] = 'unlockWithKey';
2319 game['fn'].start();