threejs-lesson-utils.js 7.0 KB

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