lessons-helper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /*
  2. * Copyright 2012, Gregg Tavares.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above
  12. * copyright notice, this list of conditions and the following disclaimer
  13. * in the documentation and/or other materials provided with the
  14. * distribution.
  15. * * Neither the name of Gregg Tavares. nor the names of his
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. /* global define */
  32. (function(root, factory) { // eslint-disable-line
  33. if (typeof define === 'function' && define.amd) {
  34. // AMD. Register as an anonymous module.
  35. define([], function() {
  36. return factory.call(root);
  37. });
  38. } else {
  39. // Browser globals
  40. root.lessonsHelper = factory.call(root);
  41. }
  42. }(this, function() {
  43. 'use strict'; // eslint-disable-line
  44. const lessonSettings = window.lessonSettings || {};
  45. const topWindow = this;
  46. /**
  47. * Check if the page is embedded.
  48. * @param {Window?) w window to check
  49. * @return {boolean} True of we are in an iframe
  50. */
  51. function isInIFrame(w) {
  52. w = w || topWindow;
  53. return w !== w.top;
  54. }
  55. function updateCSSIfInIFrame() {
  56. if (isInIFrame()) {
  57. try {
  58. document.getElementsByTagName('html')[0].className = 'iframe';
  59. } catch (e) {
  60. // eslint-disable-line
  61. }
  62. try {
  63. document.body.className = 'iframe';
  64. } catch (e) {
  65. // eslint-disable-line
  66. }
  67. }
  68. }
  69. function isInEditor() {
  70. return window.location.href.substring(0, 4) === 'blob';
  71. }
  72. /**
  73. * Creates a webgl context. If creation fails it will
  74. * change the contents of the container of the <canvas>
  75. * tag to an error message with the correct links for WebGL.
  76. * @param {HTMLCanvasElement} canvas. The canvas element to
  77. * create a context from.
  78. * @param {WebGLContextCreationAttributes} opt_attribs Any
  79. * creation attributes you want to pass in.
  80. * @return {WebGLRenderingContext} The created context.
  81. * @memberOf module:webgl-utils
  82. */
  83. function showNeedWebGL(canvas) {
  84. const doc = canvas.ownerDocument;
  85. if (doc) {
  86. const temp = doc.createElement('div');
  87. temp.innerHTML = `
  88. <div style="
  89. position: absolute;
  90. left: 0;
  91. top: 0;
  92. background-color: #DEF;
  93. width: 100%;
  94. height: 100%;
  95. display: flex;
  96. flex-flow: column;
  97. justify-content: center;
  98. align-content: center;
  99. align-items: center;
  100. ">
  101. <div style="text-align: center;">
  102. It doesn't appear your browser supports WebGL.<br/>
  103. <a href="http://get.webgl.org" target="_blank">Click here for more information.</a>
  104. </div>
  105. </div>
  106. `;
  107. const div = temp.querySelector('div');
  108. doc.body.appendChild(div);
  109. }
  110. }
  111. const origConsole = {};
  112. function setupConsole() {
  113. const style = document.createElement('style');
  114. style.innerText = `
  115. .console {
  116. font-family: monospace;
  117. font-size: medium;
  118. max-height: 50%;
  119. position: fixed;
  120. bottom: 0;
  121. left: 0;
  122. width: 100%;
  123. overflow: auto;
  124. background: rgba(221, 221, 221, 0.9);
  125. }
  126. .console .console-line {
  127. white-space: pre-line;
  128. }
  129. .console .log .warn {
  130. color: black;
  131. }
  132. .console .error {
  133. color: red;
  134. }
  135. `;
  136. const parent = document.createElement('div');
  137. parent.className = 'console';
  138. const toggle = document.createElement('div');
  139. let show = false;
  140. Object.assign(toggle.style, {
  141. position: 'absolute',
  142. right: 0,
  143. bottom: 0,
  144. background: '#EEE',
  145. 'font-size': 'smaller',
  146. cursor: 'pointer',
  147. });
  148. toggle.addEventListener('click', showHideConsole);
  149. function showHideConsole() {
  150. show = !show;
  151. toggle.textContent = show ? '☒' : '☐';
  152. parent.style.display = show ? '' : 'none';
  153. }
  154. showHideConsole();
  155. const maxLines = 100;
  156. const lines = [];
  157. let added = false;
  158. function addLine(type, str, prefix) {
  159. const div = document.createElement('div');
  160. div.textContent = (prefix + str) || ' ';
  161. div.className = `console-line ${type}`;
  162. parent.appendChild(div);
  163. lines.push(div);
  164. if (!added) {
  165. added = true;
  166. document.body.appendChild(style);
  167. document.body.appendChild(parent);
  168. document.body.appendChild(toggle);
  169. }
  170. // scrollIntoView only works in Chrome
  171. // In Firefox and Safari scrollIntoView inside an iframe moves
  172. // that element into the view. It should arguably only move that
  173. // element inside the iframe itself, otherwise that's giving
  174. // any random iframe control to bring itself into view against
  175. // the parent's wishes.
  176. //
  177. // note that even if we used a solution (which is to manually set
  178. // scrollTop) there's a UI issue that if the user manually scrolls
  179. // we want to stop scrolling automatically and if they move back
  180. // to the bottom we want to pick up scrolling automatically.
  181. // Kind of a PITA so TBD
  182. //
  183. // div.scrollIntoView();
  184. }
  185. function addLines(type, str, prefix) {
  186. while (lines.length > maxLines) {
  187. const div = lines.shift();
  188. div.parentNode.removeChild(div);
  189. }
  190. addLine(type, str, prefix);
  191. }
  192. const threePukeRE = /WebGLRenderer.*?extension not supported/;
  193. function wrapFunc(obj, funcName, prefix) {
  194. const oldFn = obj[funcName];
  195. origConsole[funcName] = oldFn.bind(obj);
  196. return function(...args) {
  197. // three.js pukes all over so filter here
  198. const src = [...args].join(' ');
  199. if (!threePukeRE.test(src)) {
  200. addLines(funcName, src, prefix);
  201. }
  202. oldFn.apply(obj, arguments);
  203. };
  204. }
  205. window.console.log = wrapFunc(window.console, 'log', '');
  206. window.console.warn = wrapFunc(window.console, 'warn', '⚠');
  207. window.console.error = wrapFunc(window.console, 'error', '❌');
  208. }
  209. function reportJSError(url, lineNo, colNo, msg) {
  210. try {
  211. const {origUrl, actualLineNo} = window.parent.getActualLineNumberAndMoveTo(url, lineNo, colNo);
  212. url = origUrl;
  213. lineNo = actualLineNo;
  214. } catch (ex) {
  215. origConsole.error(ex);
  216. }
  217. console.error(url, "line:", lineNo, ":", msg); // eslint-disable-line
  218. }
  219. /**
  220. * @typedef {Object} StackInfo
  221. * @property {string} url Url of line
  222. * @property {number} lineNo line number of error
  223. * @property {number} colNo column number of error
  224. * @property {string} [funcName] name of function
  225. */
  226. /**
  227. * @parameter {string} stack A stack string as in `(new Error()).stack`
  228. * @returns {StackInfo}
  229. */
  230. const parseStack = function() {
  231. const browser = getBrowser();
  232. let lineNdx;
  233. let matcher;
  234. if ((/chrome|opera/i).test(browser.name)) {
  235. lineNdx = 3;
  236. matcher = function(line) {
  237. const m = /at ([^(]*?)\(*(.*?):(\d+):(\d+)/.exec(line);
  238. if (m) {
  239. let userFnName = m[1];
  240. let url = m[2];
  241. const lineNo = parseInt(m[3]);
  242. const colNo = parseInt(m[4]);
  243. if (url === '') {
  244. url = userFnName;
  245. userFnName = '';
  246. }
  247. return {
  248. url: url,
  249. lineNo: lineNo,
  250. colNo: colNo,
  251. funcName: userFnName,
  252. };
  253. }
  254. return undefined;
  255. };
  256. } else if ((/firefox|safari/i).test(browser.name)) {
  257. lineNdx = 2;
  258. matcher = function(line) {
  259. const m = /@(.*?):(\d+):(\d+)/.exec(line);
  260. if (m) {
  261. const url = m[1];
  262. const lineNo = parseInt(m[2]);
  263. const colNo = parseInt(m[3]);
  264. return {
  265. url: url,
  266. lineNo: lineNo,
  267. colNo: colNo,
  268. };
  269. }
  270. return undefined;
  271. };
  272. }
  273. return function stackParser(stack) {
  274. if (matcher) {
  275. try {
  276. const lines = stack.split('\n');
  277. // window.fooLines = lines;
  278. // lines.forEach(function(line, ndx) {
  279. // origConsole.log("#", ndx, line);
  280. // });
  281. return matcher(lines[lineNdx]);
  282. } catch (e) {
  283. // do nothing
  284. }
  285. }
  286. return undefined;
  287. };
  288. }();
  289. function setupWorkerSupport() {
  290. function log(data) {
  291. const {logType, msg} = data;
  292. console[logType]('[Worker]', msg); /* eslint-disable-line no-console */
  293. }
  294. function lostContext(/* data */) {
  295. addContextLostHTML();
  296. }
  297. function jsError(data) {
  298. const {url, lineNo, colNo, msg} = data;
  299. reportJSError(url, lineNo, colNo, msg);
  300. }
  301. function jsErrorWithStack(data) {
  302. const {url, stack, msg} = data;
  303. const errorInfo = parseStack(stack);
  304. if (errorInfo) {
  305. reportJSError(errorInfo.url || url, errorInfo.lineNo, errorInfo.colNo, msg);
  306. } else {
  307. console.error(errorMsg) // eslint-disable-line
  308. }
  309. }
  310. const handlers = {
  311. log,
  312. lostContext,
  313. jsError,
  314. jsErrorWithStack,
  315. };
  316. const OrigWorker = self.Worker;
  317. class WrappedWorker extends OrigWorker {
  318. constructor(url, ...args) {
  319. super(url, ...args);
  320. let listener;
  321. this.onmessage = function(e) {
  322. if (!e || !e.data || e.data.type !== '___editor___') {
  323. if (listener) {
  324. listener(e);
  325. }
  326. return;
  327. }
  328. e.stopImmediatePropagation();
  329. const data = e.data.data;
  330. const fn = handlers[data.type];
  331. if (typeof fn !== 'function') {
  332. origConsole.error('unknown editor msg:', data.type);
  333. } else {
  334. fn(data);
  335. }
  336. return;
  337. };
  338. Object.defineProperty(this, 'onmessage', {
  339. get() {
  340. return listener;
  341. },
  342. set(fn) {
  343. listener = fn;
  344. },
  345. });
  346. }
  347. }
  348. self.Worker = WrappedWorker;
  349. }
  350. function addContextLostHTML() {
  351. const div = document.createElement('div');
  352. div.className = 'contextlost';
  353. div.innerHTML = '<div>Context Lost: Click To Reload</div>';
  354. div.addEventListener('click', function() {
  355. window.location.reload();
  356. });
  357. document.body.appendChild(div);
  358. }
  359. /**
  360. * Gets a WebGL context.
  361. * makes its backing store the size it is displayed.
  362. * @param {HTMLCanvasElement} canvas a canvas element.
  363. * @memberOf module:webgl-utils
  364. */
  365. let setupLesson = function(canvas) {
  366. // only once
  367. setupLesson = function() {};
  368. if (canvas) {
  369. canvas.addEventListener('webglcontextlost', function() {
  370. // the default is to do nothing. Preventing the default
  371. // means allowing context to be restored
  372. // e.preventDefault(); // can't do this because firefox bug - https://bugzilla.mozilla.org/show_bug.cgi?id=1633280
  373. addContextLostHTML();
  374. });
  375. /* can't do this because firefox bug - https://bugzilla.mozilla.org/show_bug.cgi?id=1633280
  376. canvas.addEventListener('webglcontextrestored', function() {
  377. // just reload the page. Easiest.
  378. window.location.reload();
  379. });
  380. */
  381. }
  382. if (isInIFrame()) {
  383. updateCSSIfInIFrame();
  384. }
  385. };
  386. // Replace requestAnimationFrame and cancelAnimationFrame with one
  387. // that only executes when the body is visible (we're in an iframe).
  388. // It's frustrating that th browsers don't do this automatically.
  389. // It's half of the point of rAF that it shouldn't execute when
  390. // content is not visible but browsers execute rAF in iframes even
  391. // if they are not visible.
  392. if (topWindow.requestAnimationFrame) {
  393. topWindow.requestAnimationFrame = (function(oldRAF, oldCancelRAF) {
  394. let nextFakeRAFId = 1;
  395. const fakeRAFIdToCallbackMap = new Map();
  396. let rafRequestId;
  397. let isBodyOnScreen;
  398. function rAFHandler(time) {
  399. rafRequestId = undefined;
  400. const ids = [...fakeRAFIdToCallbackMap.keys()]; // WTF! Map.keys() iterates over live keys!
  401. for (const id of ids) {
  402. const callback = fakeRAFIdToCallbackMap.get(id);
  403. fakeRAFIdToCallbackMap.delete(id);
  404. if (callback) {
  405. callback(time);
  406. }
  407. }
  408. }
  409. function startRAFIfIntersectingAndNeeded() {
  410. if (!rafRequestId && isBodyOnScreen && fakeRAFIdToCallbackMap.size > 0) {
  411. rafRequestId = oldRAF(rAFHandler);
  412. }
  413. }
  414. function stopRAF() {
  415. if (rafRequestId) {
  416. oldCancelRAF(rafRequestId);
  417. rafRequestId = undefined;
  418. }
  419. }
  420. function initIntersectionObserver() {
  421. const intersectionObserver = new IntersectionObserver((entries) => {
  422. entries.forEach(entry => {
  423. isBodyOnScreen = entry.isIntersecting;
  424. });
  425. if (isBodyOnScreen) {
  426. startRAFIfIntersectingAndNeeded();
  427. } else {
  428. stopRAF();
  429. }
  430. });
  431. intersectionObserver.observe(document.body);
  432. }
  433. function betterRAF(callback) {
  434. const fakeRAFId = nextFakeRAFId++;
  435. fakeRAFIdToCallbackMap.set(fakeRAFId, callback);
  436. startRAFIfIntersectingAndNeeded();
  437. return fakeRAFId;
  438. }
  439. function betterCancelRAF(id) {
  440. fakeRAFIdToCallbackMap.delete(id);
  441. }
  442. topWindow.cancelAnimationFrame = betterCancelRAF;
  443. return function(callback) {
  444. // we need to lazy init this because this code gets parsed
  445. // before body exists. We could fix it by moving lesson-helper.js
  446. // after <body> but that would require changing 100s of examples
  447. initIntersectionObserver();
  448. topWindow.requestAnimationFrame = betterRAF;
  449. return betterRAF(callback);
  450. };
  451. }(topWindow.requestAnimationFrame, topWindow.cancelAnimationFrame));
  452. }
  453. updateCSSIfInIFrame();
  454. function captureJSErrors() {
  455. // capture JavaScript Errors
  456. window.addEventListener('error', function(e) {
  457. const msg = e.message || e.error;
  458. const url = e.filename;
  459. const lineNo = e.lineno || 1;
  460. const colNo = e.colno || 1;
  461. reportJSError(url, lineNo, colNo, msg);
  462. origConsole.error(e.error);
  463. });
  464. }
  465. // adapted from http://stackoverflow.com/a/2401861/128511
  466. function getBrowser() {
  467. const userAgent = navigator.userAgent;
  468. let m = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  469. if (/trident/i.test(m[1])) {
  470. m = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
  471. return {
  472. name: 'IE',
  473. version: m[1],
  474. };
  475. }
  476. if (m[1] === 'Chrome') {
  477. const temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
  478. if (temp) {
  479. return {
  480. name: temp[1].replace('OPR', 'Opera'),
  481. version: temp[2],
  482. };
  483. }
  484. }
  485. m = m[2] ? [m[1], m[2]] : [navigator.appName, navigator.appVersion, '-?'];
  486. const version = userAgent.match(/version\/(\d+)/i);
  487. if (version) {
  488. m.splice(1, 1, version[1]);
  489. }
  490. return {
  491. name: m[0],
  492. version: m[1],
  493. };
  494. }
  495. const canvasesToTimeoutMap = new Map();
  496. const isWebGLRE = /^(webgl|webgl2|experimental-webgl)$/i;
  497. const isWebGL2RE = /^webgl2$/i;
  498. function installWebGLLessonSetup() {
  499. HTMLCanvasElement.prototype.getContext = (function(oldFn) {
  500. return function() {
  501. const timeoutId = canvasesToTimeoutMap.get(this);
  502. if (timeoutId) {
  503. clearTimeout(timeoutId);
  504. }
  505. const type = arguments[0];
  506. const isWebGL1or2 = isWebGLRE.test(type);
  507. const isWebGL2 = isWebGL2RE.test(type);
  508. if (isWebGL1or2) {
  509. setupLesson(this);
  510. }
  511. const args = [].slice.apply(arguments);
  512. args[1] = {
  513. powerPreference: 'low-power',
  514. ...args[1],
  515. };
  516. const ctx = oldFn.apply(this, args);
  517. if (!ctx) {
  518. if (isWebGL2) {
  519. // three tries webgl2 then webgl1
  520. // so wait 1/2 a second before showing the failure
  521. // message. If we get success on the same canvas
  522. // we'll cancel this.
  523. canvasesToTimeoutMap.set(this, setTimeout(() => {
  524. canvasesToTimeoutMap.delete(this);
  525. showNeedWebGL(this);
  526. }, 500));
  527. } else {
  528. showNeedWebGL(this);
  529. }
  530. }
  531. return ctx;
  532. };
  533. }(HTMLCanvasElement.prototype.getContext));
  534. }
  535. function installWebGLDebugContextCreator() {
  536. if (!self.webglDebugHelper) {
  537. return;
  538. }
  539. const {
  540. makeDebugContext,
  541. glFunctionArgToString,
  542. glEnumToString,
  543. } = self.webglDebugHelper;
  544. // capture GL errors
  545. HTMLCanvasElement.prototype.getContext = (function(oldFn) {
  546. return function() {
  547. let ctx = oldFn.apply(this, arguments);
  548. // Using bindTexture to see if it's WebGL. Could check for instanceof WebGLRenderingContext
  549. // but that might fail if wrapped by debugging extension
  550. if (ctx && ctx.bindTexture) {
  551. ctx = makeDebugContext(ctx, {
  552. maxDrawCalls: 100,
  553. errorFunc: function(err, funcName, args) {
  554. const numArgs = args.length;
  555. const enumedArgs = [].map.call(args, function(arg, ndx) {
  556. let str = glFunctionArgToString(funcName, numArgs, ndx, arg);
  557. // shorten because of long arrays
  558. if (str.length > 200) {
  559. str = str.substring(0, 200) + '...';
  560. }
  561. return str;
  562. });
  563. const errorMsg = `WebGL error ${glEnumToString(err)} in ${funcName}(${enumedArgs.join(', ')})`;
  564. const errorInfo = parseStack((new Error()).stack);
  565. if (errorInfo) {
  566. reportJSError(errorInfo.url, errorInfo.lineNo, errorInfo.colNo, errorMsg);
  567. } else {
  568. console.error(errorMsg) // eslint-disable-line
  569. }
  570. },
  571. });
  572. }
  573. return ctx;
  574. };
  575. }(HTMLCanvasElement.prototype.getContext));
  576. }
  577. installWebGLLessonSetup();
  578. if (isInEditor()) {
  579. setupWorkerSupport();
  580. setupConsole();
  581. captureJSErrors();
  582. if (lessonSettings.glDebug !== false) {
  583. installWebGLDebugContextCreator();
  584. }
  585. }
  586. return {
  587. setupLesson: setupLesson,
  588. showNeedWebGL: showNeedWebGL,
  589. };
  590. }));