threejs-primitives.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import * as THREE from '../../resources/threejs/r108/build/three.module.js';
  2. import {threejsLessonUtils} from './threejs-lesson-utils.js';
  3. {
  4. const darkColors = {
  5. lines: '#DDD',
  6. };
  7. const lightColors = {
  8. lines: '#000',
  9. };
  10. const darkMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  11. const isDarkMode = darkMatcher.matches;
  12. const colors = isDarkMode ? darkColors : lightColors;
  13. const diagrams = {
  14. BoxBufferGeometry: {
  15. create() {
  16. const width = 8;
  17. const height = 8;
  18. const depth = 8;
  19. const geometry = new THREE.BoxBufferGeometry(width, height, depth);
  20. return geometry;
  21. },
  22. },
  23. CircleBufferGeometry: {
  24. create() {
  25. const radius = 7;
  26. const segments = 24;
  27. const geometry = new THREE.CircleBufferGeometry(radius, segments);
  28. return geometry;
  29. },
  30. },
  31. ConeBufferGeometry: {
  32. create() {
  33. const radius = 6;
  34. const height = 8;
  35. const segments = 16;
  36. const geometry = new THREE.ConeBufferGeometry(radius, height, segments);
  37. return geometry;
  38. },
  39. },
  40. CylinderBufferGeometry: {
  41. create() {
  42. const radiusTop = 4;
  43. const radiusBottom = 4;
  44. const height = 8;
  45. const radialSegments = 12;
  46. const geometry = new THREE.CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments);
  47. return geometry;
  48. },
  49. },
  50. DodecahedronBufferGeometry: {
  51. create() {
  52. const radius = 7;
  53. const geometry = new THREE.DodecahedronBufferGeometry(radius);
  54. return geometry;
  55. },
  56. },
  57. ExtrudeBufferGeometry: {
  58. create() {
  59. const shape = new THREE.Shape();
  60. const x = -2.5;
  61. const y = -5;
  62. shape.moveTo(x + 2.5, y + 2.5);
  63. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  64. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  65. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  66. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  67. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  68. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  69. const extrudeSettings = {
  70. steps: 2,
  71. depth: 2,
  72. bevelEnabled: true,
  73. bevelThickness: 1,
  74. bevelSize: 1,
  75. bevelSegments: 2,
  76. };
  77. const geometry = new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  78. return geometry;
  79. },
  80. },
  81. IcosahedronBufferGeometry: {
  82. create() {
  83. const radius = 7;
  84. const geometry = new THREE.IcosahedronBufferGeometry(radius);
  85. return geometry;
  86. },
  87. },
  88. LatheBufferGeometry: {
  89. create() {
  90. const points = [];
  91. for (let i = 0; i < 10; ++i) {
  92. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  93. }
  94. const geometry = new THREE.LatheBufferGeometry(points);
  95. return geometry;
  96. },
  97. },
  98. OctahedronBufferGeometry: {
  99. create() {
  100. const radius = 7;
  101. const geometry = new THREE.OctahedronBufferGeometry(radius);
  102. return geometry;
  103. },
  104. },
  105. ParametricBufferGeometry: {
  106. /*
  107. from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  108. The MIT License
  109. Copyright © 2010-2018 three.js authors
  110. Permission is hereby granted, free of charge, to any person obtaining a copy
  111. of this software and associated documentation files (the "Software"), to deal
  112. in the Software without restriction, including without limitation the rights
  113. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  114. copies of the Software, and to permit persons to whom the Software is
  115. furnished to do so, subject to the following conditions:
  116. The above copyright notice and this permission notice shall be included in
  117. all copies or substantial portions of the Software.
  118. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  119. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  120. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  121. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  122. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  123. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  124. THE SOFTWARE.
  125. */
  126. create() {
  127. // from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  128. function klein(v, u, target) {
  129. u *= Math.PI;
  130. v *= 2 * Math.PI;
  131. u = u * 2;
  132. let x;
  133. let z;
  134. if (u < Math.PI) {
  135. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(u) * Math.cos(v);
  136. z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v);
  137. } else {
  138. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(v + Math.PI);
  139. z = -8 * Math.sin(u);
  140. }
  141. const y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v);
  142. target.set(x, y, z).multiplyScalar(0.75);
  143. }
  144. const slices = 25;
  145. const stacks = 25;
  146. const geometry = new THREE.ParametricBufferGeometry(klein, slices, stacks);
  147. return geometry;
  148. },
  149. },
  150. PlaneBufferGeometry: {
  151. create() {
  152. const width = 9;
  153. const height = 9;
  154. const widthSegments = 2;
  155. const heightSegments = 2;
  156. const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  157. return geometry;
  158. },
  159. },
  160. PolyhedronBufferGeometry: {
  161. create() {
  162. const verticesOfCube = [
  163. -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1,
  164. -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,
  165. ];
  166. const indicesOfFaces = [
  167. 2, 1, 0, 0, 3, 2,
  168. 0, 4, 7, 7, 3, 0,
  169. 0, 1, 5, 5, 4, 0,
  170. 1, 2, 6, 6, 5, 1,
  171. 2, 3, 7, 7, 6, 2,
  172. 4, 5, 6, 6, 7, 4,
  173. ];
  174. const radius = 7;
  175. const detail = 2;
  176. const geometry = new THREE.PolyhedronBufferGeometry(verticesOfCube, indicesOfFaces, radius, detail);
  177. return geometry;
  178. },
  179. },
  180. RingBufferGeometry: {
  181. create() {
  182. const innerRadius = 2;
  183. const outerRadius = 7;
  184. const segments = 18;
  185. const geometry = new THREE.RingBufferGeometry(innerRadius, outerRadius, segments);
  186. return geometry;
  187. },
  188. },
  189. ShapeBufferGeometry: {
  190. create() {
  191. const shape = new THREE.Shape();
  192. const x = -2.5;
  193. const y = -5;
  194. shape.moveTo(x + 2.5, y + 2.5);
  195. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  196. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  197. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  198. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  199. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  200. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  201. const geometry = new THREE.ShapeBufferGeometry(shape);
  202. return geometry;
  203. },
  204. },
  205. SphereBufferGeometry: {
  206. create() {
  207. const radius = 7;
  208. const widthSegments = 12;
  209. const heightSegments = 8;
  210. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  211. return geometry;
  212. },
  213. },
  214. TetrahedronBufferGeometry: {
  215. create() {
  216. const radius = 7;
  217. const geometry = new THREE.TetrahedronBufferGeometry(radius);
  218. return geometry;
  219. },
  220. },
  221. TextBufferGeometry: {
  222. async create() {
  223. const loader = new THREE.FontLoader();
  224. // promisify font loading
  225. function loadFont(url) {
  226. return new Promise((resolve, reject) => {
  227. loader.load(url, resolve, undefined, reject);
  228. });
  229. }
  230. const font = await loadFont('../resources/threejs/fonts/helvetiker_regular.typeface.json');
  231. return new THREE.TextBufferGeometry('three.js', {
  232. font: font,
  233. size: 3.0,
  234. height: .2,
  235. curveSegments: 12,
  236. bevelEnabled: true,
  237. bevelThickness: 0.15,
  238. bevelSize: .3,
  239. bevelSegments: 5,
  240. });
  241. },
  242. },
  243. TorusBufferGeometry: {
  244. create() {
  245. const radius = 5;
  246. const tubeRadius = 2;
  247. const radialSegments = 8;
  248. const tubularSegments = 24;
  249. const geometry = new THREE.TorusBufferGeometry(radius, tubeRadius, radialSegments, tubularSegments);
  250. return geometry;
  251. },
  252. },
  253. TorusKnotBufferGeometry: {
  254. create() {
  255. const radius = 3.5;
  256. const tube = 1.5;
  257. const radialSegments = 8;
  258. const tubularSegments = 64;
  259. const p = 2;
  260. const q = 3;
  261. const geometry = new THREE.TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q);
  262. return geometry;
  263. },
  264. },
  265. TubeBufferGeometry: {
  266. create() {
  267. class CustomSinCurve extends THREE.Curve {
  268. constructor(scale) {
  269. super();
  270. this.scale = scale;
  271. }
  272. getPoint(t) {
  273. const tx = t * 3 - 1.5;
  274. const ty = Math.sin(2 * Math.PI * t);
  275. const tz = 0;
  276. return new THREE.Vector3(tx, ty, tz).multiplyScalar(this.scale);
  277. }
  278. }
  279. const path = new CustomSinCurve(4);
  280. const tubularSegments = 20;
  281. const radius = 1;
  282. const radialSegments = 8;
  283. const closed = false;
  284. const geometry = new THREE.TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed);
  285. return geometry;
  286. },
  287. },
  288. EdgesGeometry: {
  289. create() {
  290. const width = 8;
  291. const height = 8;
  292. const depth = 8;
  293. const thresholdAngle = 15;
  294. const geometry = new THREE.EdgesGeometry(
  295. new THREE.BoxBufferGeometry(width, height, depth),
  296. thresholdAngle);
  297. return { lineGeometry: geometry };
  298. },
  299. nonBuffer: false,
  300. },
  301. WireframeGeometry: {
  302. create() {
  303. const width = 8;
  304. const height = 8;
  305. const depth = 8;
  306. const geometry = new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(width, height, depth));
  307. return { lineGeometry: geometry };
  308. },
  309. nonBuffer: false,
  310. },
  311. SphereBufferGeometryLow: {
  312. create() {
  313. const radius = 7;
  314. const widthSegments = 5;
  315. const heightSegments = 3;
  316. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  317. return geometry;
  318. },
  319. },
  320. SphereBufferGeometryMedium: {
  321. create() {
  322. const radius = 7;
  323. const widthSegments = 24;
  324. const heightSegments = 10;
  325. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  326. return geometry;
  327. },
  328. },
  329. SphereBufferGeometryHigh: {
  330. create() {
  331. const radius = 7;
  332. const widthSegments = 50;
  333. const heightSegments = 50;
  334. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  335. return geometry;
  336. },
  337. },
  338. SphereBufferGeometryLowSmooth: {
  339. create() {
  340. const radius = 7;
  341. const widthSegments = 5;
  342. const heightSegments = 3;
  343. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  344. return geometry;
  345. },
  346. showLines: false,
  347. flatShading: false,
  348. },
  349. SphereBufferGeometryMediumSmooth: {
  350. create() {
  351. const radius = 7;
  352. const widthSegments = 24;
  353. const heightSegments = 10;
  354. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  355. return geometry;
  356. },
  357. showLines: false,
  358. flatShading: false,
  359. },
  360. SphereBufferGeometryHighSmooth: {
  361. create() {
  362. const radius = 7;
  363. const widthSegments = 50;
  364. const heightSegments = 50;
  365. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  366. return geometry;
  367. },
  368. showLines: false,
  369. flatShading: false,
  370. },
  371. PlaneBufferGeometryLow: {
  372. create() {
  373. const width = 9;
  374. const height = 9;
  375. const widthSegments = 1;
  376. const heightSegments = 1;
  377. const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  378. return geometry;
  379. },
  380. },
  381. PlaneBufferGeometryHigh: {
  382. create() {
  383. const width = 9;
  384. const height = 9;
  385. const widthSegments = 10;
  386. const heightSegments = 10;
  387. const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  388. return geometry;
  389. },
  390. },
  391. };
  392. function addLink(parent, name) {
  393. const a = document.createElement('a');
  394. a.href = `https://threejs.org/docs/#api/geometries/${name}`;
  395. const code = document.createElement('code');
  396. code.textContent = name;
  397. a.appendChild(code);
  398. parent.appendChild(a);
  399. return a;
  400. }
  401. function addElem(parent, type, className, text) {
  402. const elem = document.createElement(type);
  403. elem.className = className;
  404. if (text) {
  405. elem.textContent = text;
  406. }
  407. parent.appendChild(elem);
  408. return elem;
  409. }
  410. function addDiv(parent, className) {
  411. return addElem(parent, 'div', className);
  412. }
  413. [...document.querySelectorAll('[data-diagram]')].forEach(createDiagram);
  414. [...document.querySelectorAll('[data-primitive]')].forEach(createPrimitiveDOM);
  415. function createPrimitiveDOM(base) {
  416. const name = base.dataset.primitive;
  417. const info = diagrams[name];
  418. if (!info) {
  419. throw new Error(`no primitive ${name}`);
  420. }
  421. const text = base.innerHTML;
  422. base.innerHTML = '';
  423. const pair = addDiv(base, 'pair');
  424. const elem = addDiv(pair, 'shape');
  425. const right = addDiv(pair, 'desc');
  426. addLink(right, name);
  427. if (info.nonBuffer !== false) {
  428. addElem(right, 'span', '', ', ');
  429. addLink(right, name.replace('Buffer', ''));
  430. }
  431. addDiv(right, '.note').innerHTML = text;
  432. const rawLines = info.create.toString()
  433. .replace(/ +return geometry;\n/, '')
  434. .replace(/ +return { lineGeometry: geometry };\n/, '')
  435. .split(/\n/);
  436. const createRE = /^( *)[^ ]/;
  437. const m = createRE.exec(rawLines[1]);
  438. const prefixLen = m[1].length;
  439. const trimmedLines = rawLines.slice(1, rawLines.length - 1).map(line => line.substring(prefixLen));
  440. addElem(base, 'pre', 'prettyprint showmods', trimmedLines.join('\n'));
  441. return createLiveImage(elem, info);
  442. }
  443. function createDiagram(base) {
  444. const name = base.dataset.diagram;
  445. const info = diagrams[name];
  446. if (!info) {
  447. throw new Error(`no primitive ${name}`);
  448. }
  449. return createLiveImage(base, info);
  450. }
  451. function createLiveImage(elem, info) {
  452. const geometry = info.create();
  453. const promise = (geometry instanceof Promise) ? geometry : Promise.resolve(geometry);
  454. promise.then((geometryInfo) => {
  455. if (geometryInfo instanceof THREE.BufferGeometry ||
  456. geometryInfo instanceof THREE.Geometry) {
  457. const geometry = geometryInfo;
  458. geometryInfo = {
  459. geometry,
  460. };
  461. }
  462. const root = new THREE.Object3D();
  463. const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry;
  464. boxGeometry.computeBoundingBox();
  465. const centerOffset = new THREE.Vector3();
  466. boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
  467. if (geometryInfo.geometry) {
  468. const material = new THREE.MeshPhongMaterial({
  469. flatShading: info.flatShading === false ? false : true,
  470. side: THREE.DoubleSide,
  471. });
  472. material.color.setHSL(Math.random(), .5, .5);
  473. const mesh = new THREE.Mesh(geometryInfo.geometry, material);
  474. mesh.position.copy(centerOffset);
  475. root.add(mesh);
  476. }
  477. if (info.showLines !== false) {
  478. const lineMesh = new THREE.LineSegments(
  479. geometryInfo.lineGeometry || geometryInfo.geometry,
  480. new THREE.LineBasicMaterial({
  481. color: geometryInfo.geometry ? 0xffffff : colors.lines,
  482. transparent: true,
  483. opacity: 0.5,
  484. }));
  485. lineMesh.position.copy(centerOffset);
  486. root.add(lineMesh);
  487. }
  488. threejsLessonUtils.addDiagram(elem, {create: () => root});
  489. });
  490. }
  491. }