threejs-lesson-utils.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. 'use strict';
  2. window.threejsLessonUtils = {
  3. init() {
  4. if (this.renderer) {
  5. return;
  6. }
  7. const canvas = document.querySelector('#c');
  8. const renderer = new THREE.WebGLRenderer({canvas: canvas, alpha: true});
  9. this.pixelRatio = Math.max(2, window.devicePixelRatio);
  10. this.renderer = renderer;
  11. this.renderFuncs = [];
  12. const resizeRendererToDisplaySize = (renderer) => {
  13. const canvas = renderer.domElement;
  14. const width = canvas.clientWidth * this.pixelRatio;
  15. const height = canvas.clientHeight * this.pixelRatio;
  16. const needResize = canvas.width !== width || canvas.height !== height;
  17. if (needResize) {
  18. renderer.setSize(width, height, false);
  19. }
  20. return needResize;
  21. };
  22. // Three r93 needs to render at least once for some reason.
  23. const scene = new THREE.Scene();
  24. const camera = new THREE.Camera();
  25. const render = (time) => {
  26. time *= 0.001;
  27. resizeRendererToDisplaySize(renderer);
  28. renderer.setScissorTest(false);
  29. // Three r93 needs to render at least once for some reason.
  30. renderer.render(scene, camera);
  31. renderer.setScissorTest(true);
  32. // maybe there is another way. Originally I used `position: fixed`
  33. // but the problem is if we can't render as fast as the browser
  34. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  35. // horrible but iOS would often been 1/2 a second or worse.
  36. // By doing it this way the canvas will scroll which means the
  37. // worse that happens is part of the shapes scrolling on don't
  38. // get drawn for a few frames but the shapes that are on the screen
  39. // scroll perfectly.
  40. //
  41. // I'm using `transform` on the voodoo that it doesn't affect
  42. // layout as much as `top` since AFAIK setting `top` is in
  43. // the flow but `transform` is not though thinking about it
  44. // the given we're `position: absolute` maybe there's no difference?
  45. const transform = `translateY(${window.scrollY}px)`;
  46. renderer.domElement.style.transform = transform;
  47. this.renderFuncs.forEach((fn) => {
  48. fn(renderer, time);
  49. });
  50. requestAnimationFrame(render);
  51. };
  52. requestAnimationFrame(render);
  53. },
  54. addDiagrams(diagrams) {
  55. [...document.querySelectorAll('[data-diagram]')].forEach((elem) => {
  56. const name = elem.dataset.diagram;
  57. const info = diagrams[name];
  58. if (!info) {
  59. throw new Error(`no diagram: ${name}`);
  60. }
  61. this.addDiagram(elem, info);
  62. });
  63. },
  64. addDiagram(elem, info) {
  65. this.init();
  66. const scene = new THREE.Scene();
  67. let targetFOVDeg = 60;
  68. const aspect = 1;
  69. const near = 0.1;
  70. const far = 50;
  71. let camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, near, far);
  72. camera.position.z = 15;
  73. scene.add(camera);
  74. const root = new THREE.Object3D();
  75. scene.add(root);
  76. const renderInfo = {
  77. pixelRatio: this.pixelRatio,
  78. camera,
  79. scene,
  80. root,
  81. renderer: this.renderer,
  82. elem,
  83. };
  84. const obj3D = info.create({scene, camera, renderInfo});
  85. const promise = (obj3D instanceof Promise) ? obj3D : Promise.resolve(obj3D);
  86. const updateFunctions = [];
  87. const resizeFunctions = [];
  88. const settings = {
  89. lights: true,
  90. trackball: true,
  91. // resize(renderInfo) {
  92. // },
  93. // update(time, renderInfo) {
  94. // },
  95. render(renderInfo) {
  96. renderInfo.renderer.render(renderInfo.scene, renderInfo.camera);
  97. },
  98. };
  99. promise.then((result) => {
  100. const info = result instanceof THREE.Object3D ? {
  101. obj3D: result,
  102. } : result;
  103. if (info.obj3D) {
  104. root.add(info.obj3D);
  105. }
  106. if (info.update) {
  107. updateFunctions.push(info.update);
  108. }
  109. if (info.resize) {
  110. resizeFunctions.push(info.resize);
  111. }
  112. if (info.camera) {
  113. camera = info.camera;
  114. renderInfo.camera = camera;
  115. }
  116. Object.assign(settings, info);
  117. targetFOVDeg = camera.fov;
  118. if (settings.trackball !== false) {
  119. const controls = new THREE.TrackballControls(camera, elem);
  120. controls.noZoom = true;
  121. controls.noPan = true;
  122. resizeFunctions.push(controls.handleResize.bind(controls));
  123. updateFunctions.push(controls.update.bind(controls));
  124. }
  125. // add the lights as children of the camera.
  126. // this is because TrackbacllControls move the camera.
  127. // We really want to rotate the object itself but there's no
  128. // controls for that so we fake it by putting all the lights
  129. // on the camera so they move with it.
  130. if (settings.lights !== false) {
  131. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  132. const light = new THREE.DirectionalLight(0xffffff, 1);
  133. light.position.set(-1, 2, 4 - 15);
  134. camera.add(light);
  135. }
  136. });
  137. let oldWidth = -1;
  138. let oldHeight = -1;
  139. const render = (renderer, time) => {
  140. root.rotation.x = time * .1;
  141. root.rotation.y = time * .11;
  142. const rect = elem.getBoundingClientRect();
  143. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  144. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  145. return;
  146. }
  147. renderInfo.width = (rect.right - rect.left) * this.pixelRatio;
  148. renderInfo.height = (rect.bottom - rect.top) * this.pixelRatio;
  149. renderInfo.left = rect.left * this.pixelRatio;
  150. renderInfo.top = rect.top * this.pixelRatio;
  151. if (renderInfo.width !== oldWidth || renderInfo.height !== oldHeight) {
  152. oldWidth = renderInfo.width;
  153. oldHeight = renderInfo.height;
  154. resizeFunctions.forEach(fn => fn(renderInfo));
  155. }
  156. updateFunctions.forEach(fn => fn(time, renderInfo));
  157. const aspect = renderInfo.width / renderInfo.height;
  158. const fovDeg = aspect >= 1
  159. ? targetFOVDeg
  160. : THREE.Math.radToDeg(2 * Math.atan(Math.tan(THREE.Math.degToRad(targetFOVDeg) * .5) / aspect));
  161. camera.fov = fovDeg;
  162. camera.aspect = aspect;
  163. camera.updateProjectionMatrix();
  164. renderer.setViewport(renderInfo.left, renderInfo.top, renderInfo.width, renderInfo.height);
  165. renderer.setScissor(renderInfo.left, renderInfo.top, renderInfo.width, renderInfo.height);
  166. settings.render(renderInfo);
  167. };
  168. this.renderFuncs.push(render);
  169. },
  170. };