threejs-primitives.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. 'use strict';
  2. function main() {
  3. // even on low-res we want hi-res rendering so the lines are small
  4. const pixelRatio = 2;
  5. const primitives = {
  6. BoxBufferGeometry: {
  7. create() {
  8. const width = 8;
  9. const height = 8;
  10. const depth = 8;
  11. return new THREE.BoxBufferGeometry(width, height, depth);
  12. },
  13. },
  14. CircleBufferGeometry: {
  15. create() {
  16. const radius = 7;
  17. const segments = 24;
  18. return new THREE.CircleBufferGeometry(radius, segments);
  19. },
  20. },
  21. ConeBufferGeometry: {
  22. create() {
  23. const radius = 6;
  24. const height = 8;
  25. const segments = 16;
  26. return new THREE.ConeBufferGeometry(radius, height, segments);
  27. },
  28. },
  29. CylinderBufferGeometry: {
  30. create() {
  31. const radiusTop = 4;
  32. const radiusBottom = 4;
  33. const height = 8;
  34. const radialSegments = 12;
  35. return new THREE.CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments);
  36. },
  37. },
  38. DodecahedronBufferGeometry: {
  39. create() {
  40. const radius = 7;
  41. return new THREE.DodecahedronBufferGeometry(radius);
  42. },
  43. },
  44. ExtrudeBufferGeometry: {
  45. create() {
  46. const shape = new THREE.Shape();
  47. const x = -2.5;
  48. const y = -5;
  49. shape.moveTo(x + 2.5, y + 2.5);
  50. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  51. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  52. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  53. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  54. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  55. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  56. const extrudeSettings = {
  57. steps: 2,
  58. depth: 2,
  59. bevelEnabled: true,
  60. bevelThickness: 1,
  61. bevelSize: 1,
  62. bevelSegments: 2,
  63. };
  64. return new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  65. },
  66. },
  67. IcosahedronBufferGeometry: {
  68. create() {
  69. const radius = 7;
  70. return new THREE.IcosahedronBufferGeometry(radius);
  71. },
  72. },
  73. LatheBufferGeometry: {
  74. create() {
  75. const points = [];
  76. for (let i = 0; i < 10; ++i) {
  77. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  78. }
  79. return new THREE.LatheBufferGeometry(points);
  80. },
  81. },
  82. OctahedronBufferGeometry: {
  83. create() {
  84. const radius = 7;
  85. return new THREE.OctahedronBufferGeometry(radius);
  86. },
  87. },
  88. ParametricBufferGeometry: {
  89. create() {
  90. /*
  91. from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  92. The MIT License
  93. Copyright © 2010-2018 three.js authors
  94. Permission is hereby granted, free of charge, to any person obtaining a copy
  95. of this software and associated documentation files (the "Software"), to deal
  96. in the Software without restriction, including without limitation the rights
  97. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  98. copies of the Software, and to permit persons to whom the Software is
  99. furnished to do so, subject to the following conditions:
  100. The above copyright notice and this permission notice shall be included in
  101. all copies or substantial portions of the Software.
  102. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  103. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  105. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  106. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  107. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  108. THE SOFTWARE.
  109. */
  110. function klein(v, u, target) {
  111. u *= Math.PI;
  112. v *= 2 * Math.PI;
  113. u = u * 2;
  114. let x;
  115. let z;
  116. if (u < Math.PI) {
  117. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(u) * Math.cos(v);
  118. z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v);
  119. } else {
  120. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(v + Math.PI);
  121. z = -8 * Math.sin(u);
  122. }
  123. const y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v);
  124. target.set(x, y, z).multiplyScalar(0.75);
  125. }
  126. const slices = 25;
  127. const stacks = 25;
  128. return new THREE.ParametricBufferGeometry(klein, slices, stacks);
  129. },
  130. },
  131. PlaneBufferGeometry: {
  132. create() {
  133. const width = 9;
  134. const height = 9;
  135. const widthSegments = 2;
  136. const heightSegments = 2;
  137. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  138. },
  139. },
  140. PolyhedronBufferGeometry: {
  141. create() {
  142. const verticesOfCube = [
  143. -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1,
  144. -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,
  145. ];
  146. const indicesOfFaces = [
  147. 2, 1, 0, 0, 3, 2,
  148. 0, 4, 7, 7, 3, 0,
  149. 0, 1, 5, 5, 4, 0,
  150. 1, 2, 6, 6, 5, 1,
  151. 2, 3, 7, 7, 6, 2,
  152. 4, 5, 6, 6, 7, 4,
  153. ];
  154. const radius = 7;
  155. const detail = 2;
  156. return new THREE.PolyhedronBufferGeometry(verticesOfCube, indicesOfFaces, radius, detail);
  157. },
  158. },
  159. RingBufferGeometry: {
  160. create() {
  161. const innerRadius = 2;
  162. const outerRadius = 7;
  163. const segments = 18;
  164. return new THREE.RingBufferGeometry(innerRadius, outerRadius, segments);
  165. },
  166. },
  167. ShapeBufferGeometry: {
  168. create() {
  169. const shape = new THREE.Shape();
  170. const x = -2.5;
  171. const y = -5;
  172. shape.moveTo(x + 2.5, y + 2.5);
  173. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  174. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  175. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  176. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  177. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  178. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  179. return new THREE.ShapeBufferGeometry(shape);
  180. },
  181. },
  182. SphereBufferGeometry: {
  183. create() {
  184. const radius = 7;
  185. const widthSegments = 12;
  186. const heightSegments = 8;
  187. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  188. },
  189. },
  190. TetrahedronBufferGeometry: {
  191. create() {
  192. const radius = 7;
  193. return new THREE.TetrahedronBufferGeometry(radius);
  194. },
  195. },
  196. TextBufferGeometry: {
  197. create() {
  198. return new Promise((resolve) => {
  199. const loader = new THREE.FontLoader();
  200. loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
  201. resolve(new THREE.TextBufferGeometry('three.js', {
  202. font: font,
  203. size: 3.0,
  204. height: .2,
  205. curveSegments: 12,
  206. bevelEnabled: true,
  207. bevelThickness: 0.15,
  208. bevelSize: .3,
  209. bevelSegments: 5,
  210. }));
  211. });
  212. });
  213. },
  214. },
  215. TorusBufferGeometry: {
  216. create() {
  217. const radius = 5;
  218. const tubeRadius = 2;
  219. const radialSegments = 8;
  220. const tubularSegments = 24;
  221. return new THREE.TorusBufferGeometry(radius, tubeRadius, radialSegments, tubularSegments);
  222. },
  223. },
  224. TorusKnotBufferGeometry: {
  225. create() {
  226. const radius = 3.5;
  227. const tube = 1.5;
  228. const radialSegments = 8;
  229. const tubularSegments = 64;
  230. const p = 2;
  231. const q = 3;
  232. return new THREE.TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q);
  233. },
  234. },
  235. TubeBufferGeometry: {
  236. create() {
  237. class CustomSinCurve extends THREE.Curve {
  238. constructor(scale) {
  239. super();
  240. this.scale = scale;
  241. }
  242. getPoint(t) {
  243. const tx = t * 3 - 1.5;
  244. const ty = Math.sin(2 * Math.PI * t);
  245. const tz = 0;
  246. return new THREE.Vector3(tx, ty, tz).multiplyScalar(this.scale);
  247. }
  248. }
  249. const path = new CustomSinCurve(4);
  250. const tubularSegments = 20;
  251. const radius = 1;
  252. const radialSegments = 8;
  253. const closed = false;
  254. return new THREE.TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed);
  255. },
  256. },
  257. EdgesGeometry: {
  258. create() {
  259. const width = 8;
  260. const height = 8;
  261. const depth = 8;
  262. return {
  263. lineGeometry: new THREE.EdgesGeometry(new THREE.BoxBufferGeometry(width, height, depth)),
  264. };
  265. },
  266. nonBuffer: false,
  267. },
  268. WireframeGeometry: {
  269. create() {
  270. const width = 8;
  271. const height = 8;
  272. const depth = 8;
  273. return {
  274. lineGeometry: new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(width, height, depth)),
  275. };
  276. },
  277. nonBuffer: false,
  278. },
  279. SphereBufferGeometryLow: {
  280. create() {
  281. const radius = 7;
  282. const widthSegments = 5;
  283. const heightSegments = 3;
  284. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  285. },
  286. },
  287. SphereBufferGeometryMedium: {
  288. create() {
  289. const radius = 7;
  290. const widthSegments = 24;
  291. const heightSegments = 10;
  292. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  293. },
  294. },
  295. SphereBufferGeometryHigh: {
  296. create() {
  297. const radius = 7;
  298. const widthSegments = 50;
  299. const heightSegments = 50;
  300. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  301. },
  302. },
  303. SphereBufferGeometryLowSmooth: {
  304. create() {
  305. const radius = 7;
  306. const widthSegments = 5;
  307. const heightSegments = 3;
  308. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  309. },
  310. showLines: false,
  311. flatShading: false,
  312. },
  313. SphereBufferGeometryMediumSmooth: {
  314. create() {
  315. const radius = 7;
  316. const widthSegments = 24;
  317. const heightSegments = 10;
  318. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  319. },
  320. showLines: false,
  321. flatShading: false,
  322. },
  323. SphereBufferGeometryHighSmooth: {
  324. create() {
  325. const radius = 7;
  326. const widthSegments = 50;
  327. const heightSegments = 50;
  328. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  329. },
  330. showLines: false,
  331. flatShading: false,
  332. },
  333. PlaneBufferGeometryLow: {
  334. create() {
  335. const width = 9;
  336. const height = 9;
  337. const widthSegments = 1;
  338. const heightSegments = 1;
  339. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  340. },
  341. },
  342. PlaneBufferGeometryHigh: {
  343. create() {
  344. const width = 9;
  345. const height = 9;
  346. const widthSegments = 10;
  347. const heightSegments = 10;
  348. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  349. },
  350. },
  351. };
  352. const canvas = document.querySelector('#c');
  353. const renderer = new THREE.WebGLRenderer({canvas: canvas, alpha: true});
  354. function addLink(parent, name) {
  355. const a = document.createElement('a');
  356. a.href = `https://threejs.org/docs/#api/geometries/${name}`;
  357. const code = document.createElement('code');
  358. code.textContent = name;
  359. a.appendChild(code);
  360. parent.appendChild(a);
  361. return a;
  362. }
  363. function addElem(parent, type, className, text) {
  364. const elem = document.createElement(type);
  365. elem.className = className;
  366. if (text) {
  367. elem.textContent = text;
  368. }
  369. parent.appendChild(elem);
  370. return elem;
  371. }
  372. function addDiv(parent, className) {
  373. return addElem(parent, 'div', className);
  374. }
  375. const primRenderFuncs = [
  376. ...[...document.querySelectorAll('[data-primitive]')].map(createPrimitiveDOM),
  377. ...[...document.querySelectorAll('[data-primitive-diagram]')].map(createPrimitiveDiagram),
  378. ];
  379. function createPrimitiveDOM(base) {
  380. const name = base.dataset.primitive;
  381. const info = primitives[name];
  382. if (!info) {
  383. throw new Error(`no primitive ${name}`);
  384. }
  385. const text = base.innerHTML;
  386. base.innerHTML = '';
  387. const elem = addDiv(base, 'shape');
  388. const right = addDiv(base, 'desc');
  389. addLink(right, name);
  390. if (info.nonBuffer !== false) {
  391. addElem(right, 'span', '', ', ');
  392. addLink(right, name.replace('Buffer', ''));
  393. }
  394. addDiv(right, '.note').innerHTML = text;
  395. return createPrimitive(elem, info);
  396. }
  397. function createPrimitiveDiagram(base) {
  398. const name = base.dataset.primitiveDiagram;
  399. const info = primitives[name];
  400. if (!info) {
  401. throw new Error(`no primitive ${name}`);
  402. }
  403. return createPrimitive(base, info);
  404. }
  405. function createPrimitive(elem, info) {
  406. const geometry = info.create();
  407. const promise = (geometry instanceof Promise) ? geometry : Promise.resolve(geometry);
  408. const scene = new THREE.Scene();
  409. const root = new THREE.Object3D();
  410. scene.add(root);
  411. const fov = 60;
  412. const aspect = 1;
  413. const zNear = 0.1;
  414. const zFar = 50;
  415. const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar);
  416. camera.position.z = 15;
  417. const controls = new THREE.TrackballControls(camera, elem);
  418. controls.noZoom = true;
  419. controls.noPan = true;
  420. // add the lights as children of the camera.
  421. // this is because TrackbacllControls move the camera.
  422. // We really want to rotate the object itself but there's no
  423. // controls for that so we fake it by putting all the lights
  424. // on the camera so they move with it.
  425. camera.add(new THREE.HemisphereLight(0xaaaaaa, 0x444444, .5));
  426. const light = new THREE.DirectionalLight(0xffffff, 1);
  427. light.position.set(-1, 2, 4 - 15);
  428. camera.add(light);
  429. scene.add(camera);
  430. promise.then((geometryInfo) => {
  431. if (geometryInfo instanceof THREE.BufferGeometry ||
  432. geometryInfo instanceof THREE.Geometry) {
  433. const geometry = geometryInfo;
  434. geometryInfo = {
  435. geometry,
  436. };
  437. }
  438. const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry;
  439. boxGeometry.computeBoundingBox();
  440. const centerOffset = new THREE.Vector3();
  441. boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
  442. if (geometryInfo.geometry) {
  443. const material = new THREE.MeshPhongMaterial({
  444. flatShading: info.flatShading === false ? false : true,
  445. side: THREE.DoubleSide,
  446. });
  447. material.color.setHSL(Math.random(), .5, .5);
  448. const mesh = new THREE.Mesh(geometryInfo.geometry, material);
  449. mesh.position.copy(centerOffset);
  450. root.add(mesh);
  451. }
  452. if (info.showLines !== false) {
  453. const lineMesh = new THREE.LineSegments(
  454. geometryInfo.lineGeometry || geometryInfo.geometry,
  455. new THREE.LineBasicMaterial({
  456. color: geometryInfo.geometry ? 0xffffff : 0x000000,
  457. transparent: true,
  458. opacity: 0.5,
  459. }));
  460. lineMesh.position.copy(centerOffset);
  461. root.add(lineMesh);
  462. }
  463. });
  464. let oldWidth = -1;
  465. let oldHeight = -1;
  466. function render(renderer, time) {
  467. root.rotation.x = time * .1;
  468. root.rotation.y = time * .11;
  469. const rect = elem.getBoundingClientRect();
  470. if (rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  471. rect.right < 0 || rect.left > renderer.domElement.clientWidth) {
  472. return;
  473. }
  474. const width = (rect.right - rect.left) * pixelRatio;
  475. const height = (rect.bottom - rect.top) * pixelRatio;
  476. const left = rect.left * pixelRatio;
  477. const top = rect.top * pixelRatio;
  478. if (width !== oldWidth || height !== oldHeight) {
  479. oldWidth = width;
  480. oldHeight = height;
  481. controls.handleResize();
  482. }
  483. controls.update();
  484. const aspect = width / height;
  485. const targetFov = THREE.Math.degToRad(60);
  486. const fov = aspect >= 1
  487. ? targetFov
  488. : (2 * Math.atan(Math.tan(targetFov * .5) / aspect));
  489. camera.fov = THREE.Math.radToDeg(fov);
  490. camera.aspect = aspect;
  491. camera.updateProjectionMatrix();
  492. renderer.setViewport(left, top, width, height);
  493. renderer.setScissor(left, top, width, height);
  494. renderer.render(scene, camera);
  495. }
  496. return render;
  497. }
  498. function resizeRendererToDisplaySize(renderer) {
  499. const canvas = renderer.domElement;
  500. const width = canvas.clientWidth * pixelRatio;
  501. const height = canvas.clientHeight * pixelRatio;
  502. const needResize = canvas.width !== width || canvas.height !== height;
  503. if (needResize) {
  504. renderer.setSize(width, height, false);
  505. }
  506. return needResize;
  507. }
  508. // Three r93 needs to render at least once for some reason.
  509. const scene = new THREE.Scene();
  510. const camera = new THREE.Camera();
  511. function render(time) {
  512. time *= 0.001;
  513. resizeRendererToDisplaySize(renderer);
  514. renderer.setScissorTest(false);
  515. // Three r93 needs to render at least once for some reason.
  516. renderer.render(scene, camera);
  517. renderer.setScissorTest(true);
  518. // maybe there is another way. Originally I used `position: fixed`
  519. // but the problem is if we can't render as fast as the browser
  520. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  521. // horrible but iOS would often been 1/2 a second or worse.
  522. // By doing it this way the canvas will scroll which means the
  523. // worse that happens is part of the shapes scrolling on don't
  524. // get drawn for a few frames but the shapes that are on the screen
  525. // scroll perfectly.
  526. //
  527. // I'm using `transform` on the voodoo that it doesn't affect
  528. // layout as much as `top` since AFAIK setting `top` is in
  529. // the flow but `transform` is not though thinking about it
  530. // the given we're `position: absolute` maybe there's no difference?
  531. const transform = `translateY(${window.scrollY}px)`;
  532. renderer.domElement.style.transform = transform;
  533. primRenderFuncs.forEach((fn) => {
  534. fn(renderer, time);
  535. });
  536. requestAnimationFrame(render);
  537. }
  538. requestAnimationFrame(render);
  539. }
  540. main();