threejs-primitives.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. import * as THREE from '../../resources/threejs/r122/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 fontLoader = new THREE.FontLoader();
  14. const fontPromise = new Promise((resolve) => {
  15. fontLoader.load('/threejs/resources/threejs/fonts/helvetiker_regular.typeface.json', resolve);
  16. });
  17. const diagrams = {
  18. BoxBufferGeometry: {
  19. ui: {
  20. width: { type: 'range', min: 1, max: 10, precision: 1, },
  21. height: { type: 'range', min: 1, max: 10, precision: 1, },
  22. depth: { type: 'range', min: 1, max: 10, precision: 1, },
  23. widthSegments: { type: 'range', min: 1, max: 10, },
  24. heightSegments: { type: 'range', min: 1, max: 10, },
  25. depthSegments: { type: 'range', min: 1, max: 10, },
  26. },
  27. create(width = 8, height = 8, depth = 8) {
  28. return new THREE.BoxBufferGeometry(width, height, depth);
  29. },
  30. create2(width = 8, height = 8, depth = 8, widthSegments = 4, heightSegments = 4, depthSegments = 4) {
  31. return new THREE.BoxBufferGeometry(
  32. width, height, depth,
  33. widthSegments, heightSegments, depthSegments);
  34. },
  35. },
  36. CircleBufferGeometry: {
  37. ui: {
  38. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  39. segments: { type: 'range', min: 1, max: 50, },
  40. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  41. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  42. },
  43. create(radius = 7, segments = 24) {
  44. return new THREE.CircleBufferGeometry(radius, segments);
  45. },
  46. create2(radius = 7, segments = 24, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  47. return new THREE.CircleBufferGeometry(
  48. radius, segments, thetaStart, thetaLength);
  49. },
  50. },
  51. ConeBufferGeometry: {
  52. ui: {
  53. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  54. height: { type: 'range', min: 1, max: 10, precision: 1, },
  55. radialSegments: { type: 'range', min: 1, max: 50, },
  56. heightSegments: { type: 'range', min: 1, max: 10, },
  57. openEnded: { type: 'bool', },
  58. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  59. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  60. },
  61. create(radius = 6, height = 8, radialSegments = 16) {
  62. return new THREE.ConeBufferGeometry(radius, height, radialSegments);
  63. },
  64. create2(radius = 6, height = 8, radialSegments = 16, heightSegments = 2, openEnded = true, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  65. return new THREE.ConeBufferGeometry(
  66. radius, height,
  67. radialSegments, heightSegments,
  68. openEnded,
  69. thetaStart, thetaLength);
  70. },
  71. },
  72. CylinderBufferGeometry: {
  73. ui: {
  74. radiusTop: { type: 'range', min: 0, max: 10, precision: 1, },
  75. radiusBottom: { type: 'range', min: 0, max: 10, precision: 1, },
  76. height: { type: 'range', min: 1, max: 10, precision: 1, },
  77. radialSegments: { type: 'range', min: 1, max: 50, },
  78. heightSegments: { type: 'range', min: 1, max: 10, },
  79. openEnded: { type: 'bool', },
  80. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  81. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  82. },
  83. create(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12) {
  84. return new THREE.CylinderBufferGeometry(
  85. radiusTop, radiusBottom, height, radialSegments);
  86. },
  87. create2(radiusTop = 4, radiusBottom = 4, height = 8, radialSegments = 12, heightSegments = 2, openEnded = false, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  88. return new THREE.CylinderBufferGeometry(
  89. radiusTop, radiusBottom, height,
  90. radialSegments, heightSegments,
  91. openEnded,
  92. thetaStart, thetaLength);
  93. },
  94. },
  95. DodecahedronBufferGeometry: {
  96. ui: {
  97. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  98. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  99. },
  100. create(radius = 7) {
  101. return new THREE.DodecahedronBufferGeometry(radius);
  102. },
  103. create2(radius = 7, detail = 2) {
  104. return new THREE.DodecahedronBufferGeometry(radius, detail);
  105. },
  106. },
  107. ExtrudeBufferGeometry: {
  108. ui: {
  109. steps: { type: 'range', min: 1, max: 100, },
  110. depth: { type: 'range', min: 1, max: 20, precision: 1, },
  111. bevelEnabled: { type: 'bool', },
  112. bevelThickness: { type: 'range', min: 0.1, max: 3, },
  113. bevelSize: { type: 'range', min: 0.1, max:3, },
  114. bevelSegments: { type: 'range', min: 0, max: 8, },
  115. },
  116. addConstCode: false,
  117. create(steps = 2, depth = 2, bevelEnabled = true, bevelThickness = 1, bevelSize = 1, bevelSegments = 2) {
  118. const shape = new THREE.Shape();
  119. const x = -2.5;
  120. const y = -5;
  121. shape.moveTo(x + 2.5, y + 2.5);
  122. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  123. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  124. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  125. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  126. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  127. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  128. const extrudeSettings = {
  129. steps,
  130. depth,
  131. bevelEnabled,
  132. bevelThickness,
  133. bevelSize,
  134. bevelSegments,
  135. };
  136. const geometry = new THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  137. return geometry;
  138. },
  139. src: `
  140. const shape = new THREE.Shape();
  141. const x = -2.5;
  142. const y = -5;
  143. shape.moveTo(x + 2.5, y + 2.5);
  144. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  145. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  146. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  147. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  148. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  149. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  150. const extrudeSettings = {
  151. steps: 2, // ui: steps
  152. depth: 2, // ui: depth
  153. bevelEnabled: true, // ui: bevelEnabled
  154. bevelThickness: 1, // ui: bevelThickness
  155. bevelSize: 1, // ui: bevelSize
  156. bevelSegments: 2, // ui: bevelSegments
  157. };
  158. const geometry = THREE.ExtrudeBufferGeometry(shape, extrudeSettings);
  159. `,
  160. create2(steps = 100) {
  161. const outline = new THREE.Shape([
  162. [ -2, -0.1], [ 2, -0.1], [ 2, 0.6],
  163. [1.6, 0.6], [1.6, 0.1], [-2, 0.1],
  164. ].map(p => new THREE.Vector2(...p)));
  165. const x = -2.5;
  166. const y = -5;
  167. const shape = new THREE.CurvePath();
  168. const points = [
  169. [x + 2.5, y + 2.5],
  170. [x + 2.5, y + 2.5], [x + 2, y], [x, y],
  171. [x - 3, y], [x - 3, y + 3.5], [x - 3, y + 3.5],
  172. [x - 3, y + 5.5], [x - 1.5, y + 7.7], [x + 2.5, y + 9.5],
  173. [x + 6, y + 7.7], [x + 8, y + 4.5], [x + 8, y + 3.5],
  174. [x + 8, y + 3.5], [x + 8, y], [x + 5, y],
  175. [x + 3.5, y], [x + 2.5, y + 2.5], [x + 2.5, y + 2.5],
  176. ].map(p => new THREE.Vector3(...p, 0));
  177. for (let i = 0; i < points.length; i += 3) {
  178. shape.add(new THREE.CubicBezierCurve3(...points.slice(i, i + 4)));
  179. }
  180. const extrudeSettings = {
  181. steps,
  182. bevelEnabled: false,
  183. extrudePath: shape,
  184. };
  185. const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
  186. return geometry;
  187. },
  188. src2: `
  189. const outline = new THREE.Shape([
  190. [ -2, -0.1], [ 2, -0.1], [ 2, 0.6],
  191. [1.6, 0.6], [1.6, 0.1], [-2, 0.1],
  192. ].map(p => new THREE.Vector2(...p)));
  193. const x = -2.5;
  194. const y = -5;
  195. const shape = new THREE.CurvePath();
  196. const points = [
  197. [x + 2.5, y + 2.5],
  198. [x + 2.5, y + 2.5], [x + 2, y ], [x, y ],
  199. [x - 3, y ], [x - 3, y + 3.5], [x - 3, y + 3.5],
  200. [x - 3, y + 5.5], [x - 1.5, y + 7.7], [x + 2.5, y + 9.5],
  201. [x + 6, y + 7.7], [x + 8, y + 4.5], [x + 8, y + 3.5],
  202. [x + 8, y + 3.5], [x + 8, y ], [x + 5, y ],
  203. [x + 3.5, y ], [x + 2.5, y + 2.5], [x + 2.5, y + 2.5],
  204. ].map(p => new THREE.Vector3(...p, 0));
  205. for (let i = 0; i < points.length; i += 3) {
  206. shape.add(new THREE.CubicBezierCurve3(...points.slice(i, i + 4)));
  207. }
  208. const extrudeSettings = {
  209. steps: 100, // ui: steps
  210. bevelEnabled: false,
  211. extrudePath: shape,
  212. };
  213. const geometry = new THREE.ExtrudeBufferGeometry(outline, extrudeSettings);
  214. return geometry;
  215. `,
  216. },
  217. IcosahedronBufferGeometry: {
  218. ui: {
  219. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  220. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  221. },
  222. create(radius = 7) {
  223. return new THREE.IcosahedronBufferGeometry(radius);
  224. },
  225. create2(radius = 7, detail = 2) {
  226. return new THREE.IcosahedronBufferGeometry(radius, detail);
  227. },
  228. },
  229. LatheBufferGeometry: {
  230. ui: {
  231. segments: { type: 'range', min: 1, max: 50, },
  232. phiStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  233. phiLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  234. },
  235. create() {
  236. const points = [];
  237. for (let i = 0; i < 10; ++i) {
  238. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  239. }
  240. return new THREE.LatheBufferGeometry(points);
  241. },
  242. create2(segments = 12, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5) {
  243. const points = [];
  244. for (let i = 0; i < 10; ++i) {
  245. points.push(new THREE.Vector2(Math.sin(i * 0.2) * 3 + 3, (i - 5) * .8));
  246. }
  247. return new THREE.LatheBufferGeometry(
  248. points, segments, phiStart, phiLength);
  249. },
  250. },
  251. OctahedronBufferGeometry: {
  252. ui: {
  253. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  254. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  255. },
  256. create(radius = 7) {
  257. return new THREE.OctahedronBufferGeometry(radius);
  258. },
  259. create2(radius = 7, detail = 2) {
  260. return new THREE.OctahedronBufferGeometry(radius, detail);
  261. },
  262. },
  263. ParametricBufferGeometry: {
  264. ui: {
  265. stacks: { type: 'range', min: 1, max: 50, },
  266. slices: { type: 'range', min: 1, max: 50, },
  267. },
  268. /*
  269. from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  270. The MIT License
  271. Copyright © 2010-2018 three.js authors
  272. Permission is hereby granted, free of charge, to any person obtaining a copy
  273. of this software and associated documentation files (the "Software"), to deal
  274. in the Software without restriction, including without limitation the rights
  275. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  276. copies of the Software, and to permit persons to whom the Software is
  277. furnished to do so, subject to the following conditions:
  278. The above copyright notice and this permission notice shall be included in
  279. all copies or substantial portions of the Software.
  280. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  281. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  282. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  283. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  284. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  285. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  286. THE SOFTWARE.
  287. */
  288. create(slices = 25, stacks = 25) {
  289. // from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js
  290. function klein(v, u, target) {
  291. u *= Math.PI;
  292. v *= 2 * Math.PI;
  293. u = u * 2;
  294. let x;
  295. let z;
  296. if (u < Math.PI) {
  297. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(u) * Math.cos(v);
  298. z = -8 * Math.sin(u) - 2 * (1 - Math.cos(u) / 2) * Math.sin(u) * Math.cos(v);
  299. } else {
  300. x = 3 * Math.cos(u) * (1 + Math.sin(u)) + (2 * (1 - Math.cos(u) / 2)) * Math.cos(v + Math.PI);
  301. z = -8 * Math.sin(u);
  302. }
  303. const y = -2 * (1 - Math.cos(u) / 2) * Math.sin(v);
  304. target.set(x, y, z).multiplyScalar(0.75);
  305. }
  306. return new THREE.ParametricBufferGeometry(
  307. klein, slices, stacks);
  308. },
  309. },
  310. PlaneBufferGeometry: {
  311. ui: {
  312. width: { type: 'range', min: 1, max: 10, precision: 1, },
  313. height: { type: 'range', min: 1, max: 10, precision: 1, },
  314. widthSegments: { type: 'range', min: 1, max: 10, },
  315. heightSegments: { type: 'range', min: 1, max: 10, },
  316. },
  317. create(width = 9, height = 9) {
  318. return new THREE.PlaneBufferGeometry(width, height);
  319. },
  320. create2(width = 9, height = 9, widthSegments = 2, heightSegments = 2) {
  321. return new THREE.PlaneBufferGeometry(
  322. width, height,
  323. widthSegments, heightSegments);
  324. },
  325. },
  326. PolyhedronBufferGeometry: {
  327. ui: {
  328. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  329. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  330. },
  331. create(radius = 7, detail = 2) {
  332. const verticesOfCube = [
  333. -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1,
  334. -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1,
  335. ];
  336. const indicesOfFaces = [
  337. 2, 1, 0, 0, 3, 2,
  338. 0, 4, 7, 7, 3, 0,
  339. 0, 1, 5, 5, 4, 0,
  340. 1, 2, 6, 6, 5, 1,
  341. 2, 3, 7, 7, 6, 2,
  342. 4, 5, 6, 6, 7, 4,
  343. ];
  344. return new THREE.PolyhedronBufferGeometry(
  345. verticesOfCube, indicesOfFaces, radius, detail);
  346. },
  347. },
  348. RingBufferGeometry: {
  349. ui: {
  350. innerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  351. outerRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  352. thetaSegments: { type: 'range', min: 1, max: 30, },
  353. phiSegments: { type: 'range', min: 1, max: 10, },
  354. thetaStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  355. thetaLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  356. },
  357. create(innerRadius = 2, outerRadius = 7, thetaSegments = 18) {
  358. return new THREE.RingBufferGeometry(
  359. innerRadius, outerRadius, thetaSegments);
  360. },
  361. create2(innerRadius = 2, outerRadius = 7, thetaSegments = 18, phiSegments = 2, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 1.5) {
  362. return new THREE.RingBufferGeometry(
  363. innerRadius, outerRadius,
  364. thetaSegments, phiSegments,
  365. thetaStart, thetaLength);
  366. },
  367. },
  368. ShapeBufferGeometry: {
  369. ui: {
  370. curveSegments: { type: 'range', min: 1, max: 30, },
  371. },
  372. create() {
  373. const shape = new THREE.Shape();
  374. const x = -2.5;
  375. const y = -5;
  376. shape.moveTo(x + 2.5, y + 2.5);
  377. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  378. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  379. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  380. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  381. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  382. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  383. return new THREE.ShapeBufferGeometry(shape);
  384. },
  385. create2(curveSegments = 5) {
  386. const shape = new THREE.Shape();
  387. const x = -2.5;
  388. const y = -5;
  389. shape.moveTo(x + 2.5, y + 2.5);
  390. shape.bezierCurveTo(x + 2.5, y + 2.5, x + 2, y, x, y);
  391. shape.bezierCurveTo(x - 3, y, x - 3, y + 3.5, x - 3, y + 3.5);
  392. shape.bezierCurveTo(x - 3, y + 5.5, x - 1.5, y + 7.7, x + 2.5, y + 9.5);
  393. shape.bezierCurveTo(x + 6, y + 7.7, x + 8, y + 4.5, x + 8, y + 3.5);
  394. shape.bezierCurveTo(x + 8, y + 3.5, x + 8, y, x + 5, y);
  395. shape.bezierCurveTo(x + 3.5, y, x + 2.5, y + 2.5, x + 2.5, y + 2.5);
  396. return new THREE.ShapeBufferGeometry(shape, curveSegments);
  397. },
  398. },
  399. SphereBufferGeometry: {
  400. ui: {
  401. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  402. widthSegments: { type: 'range', min: 1, max: 30, },
  403. heightSegments: { type: 'range', min: 1, max: 30, },
  404. phiStart: { type: 'range', min: 0, max: 2, mult: Math.PI },
  405. phiLength: { type: 'range', min: 0, max: 2, mult: Math.PI },
  406. thetaStart: { type: 'range', min: 0, max: 1, mult: Math.PI },
  407. thetaLength: { type: 'range', min: 0, max: 1, mult: Math.PI },
  408. },
  409. create(radius = 7, widthSegments = 12, heightSegments = 8) {
  410. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  411. },
  412. create2(radius = 7, widthSegments = 12, heightSegments = 8, phiStart = Math.PI * 0.25, phiLength = Math.PI * 1.5, thetaStart = Math.PI * 0.25, thetaLength = Math.PI * 0.5) {
  413. return new THREE.SphereBufferGeometry(
  414. radius,
  415. widthSegments, heightSegments,
  416. phiStart, phiLength,
  417. thetaStart, thetaLength);
  418. },
  419. },
  420. TetrahedronBufferGeometry: {
  421. ui: {
  422. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  423. detail: { type: 'range', min: 0, max: 5, precision: 0, },
  424. },
  425. create(radius = 7) {
  426. return new THREE.TetrahedronBufferGeometry(radius);
  427. },
  428. create2(radius = 7, detail = 2) {
  429. return new THREE.TetrahedronBufferGeometry(radius, detail);
  430. },
  431. },
  432. TextBufferGeometry: {
  433. ui: {
  434. text: { type: 'text', maxLength: 30, },
  435. size: { type: 'range', min: 1, max: 10, precision: 1, },
  436. height: { type: 'range', min: 1, max: 10, precision: 1, },
  437. curveSegments: { type: 'range', min: 1, max: 20, },
  438. // font', fonts ).onChange( generateGeometry );
  439. // weight', weights ).onChange( generateGeometry );
  440. bevelEnabled: { type: 'bool', },
  441. bevelThickness: { type: 'range', min: 0.1, max: 3, },
  442. bevelSize: { type: 'range', min: 0.1, max:3, },
  443. bevelSegments: { type: 'range', min: 0, max: 8, },
  444. },
  445. addConstCode: false,
  446. create(text = 'three.js', size = 3, height = 0.2, curveSegments = 12, bevelEnabled = true, bevelThickness = 0.15, bevelSize = 0.3, bevelSegments = 5) {
  447. return new Promise((resolve) => {
  448. fontPromise.then((font) => {
  449. resolve(new THREE.TextBufferGeometry(text, {
  450. font: font,
  451. size,
  452. height,
  453. curveSegments,
  454. bevelEnabled,
  455. bevelThickness,
  456. bevelSize,
  457. bevelSegments,
  458. }));
  459. });
  460. });
  461. },
  462. src: `
  463. const loader = new THREE.FontLoader();
  464. loader.load('../resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => {
  465. const text = 'three.js'; // ui: text
  466. const geometry = new THREE.TextBufferGeometry(text, {
  467. font: font,
  468. size: 3, // ui: size
  469. height: 0.2, // ui: height
  470. curveSegments: 12, // ui: curveSegments
  471. bevelEnabled: true, // ui: bevelEnabled
  472. bevelThickness: 0.15, // ui: bevelThickness
  473. bevelSize: 0.3, // ui: bevelSize
  474. bevelSegments: 5, // ui: bevelSegments
  475. });
  476. ...
  477. });
  478. `,
  479. },
  480. TorusBufferGeometry: {
  481. ui: {
  482. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  483. tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  484. radialSegments: { type: 'range', min: 1, max: 30, },
  485. tubularSegments: { type: 'range', min: 1, max: 100, },
  486. },
  487. create(radius = 5, tubeRadius = 2, radialSegments = 8, tubularSegments = 24) {
  488. return new THREE.TorusBufferGeometry(
  489. radius, tubeRadius,
  490. radialSegments, tubularSegments);
  491. },
  492. },
  493. TorusKnotBufferGeometry: {
  494. ui: {
  495. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  496. tubeRadius: { type: 'range', min: 1, max: 10, precision: 1, },
  497. radialSegments: { type: 'range', min: 1, max: 30, },
  498. tubularSegments: { type: 'range', min: 1, max: 100, },
  499. p: { type: 'range', min: 1, max: 20, },
  500. q: { type: 'range', min: 1, max: 20, },
  501. },
  502. create(radius = 3.5, tubeRadius = 1.5, radialSegments = 8, tubularSegments = 64, p = 2, q = 3) {
  503. return new THREE.TorusKnotBufferGeometry(
  504. radius, tubeRadius, tubularSegments, radialSegments, p, q);
  505. },
  506. },
  507. TubeBufferGeometry: {
  508. ui: {
  509. tubularSegments: { type: 'range', min: 1, max: 100, },
  510. radius: { type: 'range', min: 1, max: 10, precision: 1, },
  511. radialSegments: { type: 'range', min: 1, max: 30, },
  512. closed: { type: 'bool', },
  513. },
  514. create(tubularSegments = 20, radius = 1, radialSegments = 8, closed = false) {
  515. class CustomSinCurve extends THREE.Curve {
  516. constructor(scale) {
  517. super();
  518. this.scale = scale;
  519. }
  520. getPoint(t) {
  521. const tx = t * 3 - 1.5;
  522. const ty = Math.sin(2 * Math.PI * t);
  523. const tz = 0;
  524. return new THREE.Vector3(tx, ty, tz).multiplyScalar(this.scale);
  525. }
  526. }
  527. const path = new CustomSinCurve(4);
  528. return new THREE.TubeBufferGeometry(
  529. path, tubularSegments, radius, radialSegments, closed);
  530. },
  531. },
  532. EdgesGeometry: {
  533. ui: {
  534. thresholdAngle: { type: 'range', min: 1, max: 180, },
  535. },
  536. create() {
  537. return {
  538. lineGeometry: new THREE.EdgesGeometry(
  539. new THREE.BoxBufferGeometry(8, 8, 8)),
  540. };
  541. },
  542. create2(thresholdAngle = 1) {
  543. return {
  544. lineGeometry: new THREE.EdgesGeometry(
  545. new THREE.SphereBufferGeometry(7, 6, 3), thresholdAngle),
  546. };
  547. },
  548. nonBuffer: false,
  549. addConstCode: false,
  550. src: `
  551. const size = 8;
  552. const widthSegments = 2;
  553. const heightSegments = 2;
  554. const depthSegments = 2;
  555. const boxGeometry = new THREE.BoxBufferGeometry(
  556. size, size, size,
  557. widthSegments, heightSegments, depthSegments);
  558. const geometry = new THREE.EdgesGeometry(boxGeometry);
  559. `,
  560. src2: `
  561. const radius = 7;
  562. const widthSegments = 6;
  563. const heightSegments = 3;
  564. const sphereGeometry = new THREE.SphereBufferGeometry(
  565. radius, widthSegments, heightSegments);
  566. const thresholdAngle = 1; // ui: thresholdAngle
  567. const geometry = new THREE.EdgesGeometry(sphereGeometry, thresholdAngle);
  568. `,
  569. },
  570. WireframeGeometry: {
  571. ui: {
  572. widthSegments: { type: 'range', min: 1, max: 10, },
  573. heightSegments: { type: 'range', min: 1, max: 10, },
  574. depthSegments: { type: 'range', min: 1, max: 10, },
  575. },
  576. create(widthSegments = 2, heightSegments = 2, depthSegments = 2) {
  577. const size = 8;
  578. return {
  579. lineGeometry: new THREE.WireframeGeometry(new THREE.BoxBufferGeometry(
  580. size, size, size,
  581. widthSegments, heightSegments, depthSegments)),
  582. };
  583. },
  584. nonBuffer: false,
  585. addConstCode: false,
  586. src: `
  587. const size = 8;
  588. const widthSegments = 2; // ui: widthSegments
  589. const heightSegments = 2; // ui: heightSegments
  590. const depthSegments = 2; // ui: depthSegments
  591. const geometry = new THREE.WireframeGeometry(
  592. new THREE.BoxBufferGeometry(
  593. size, size, size,
  594. widthSegments, heightSegments, depthSegments));
  595. `,
  596. },
  597. Points: {
  598. create() {
  599. const radius = 7;
  600. const widthSegments = 12;
  601. const heightSegments = 8;
  602. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  603. const material = new THREE.PointsMaterial({
  604. color: 'red',
  605. size: 0.2,
  606. });
  607. const points = new THREE.Points(geometry, material);
  608. return {
  609. showLines: false,
  610. mesh: points,
  611. };
  612. },
  613. },
  614. PointsUniformSize: {
  615. create() {
  616. const radius = 7;
  617. const widthSegments = 12;
  618. const heightSegments = 8;
  619. const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  620. const material = new THREE.PointsMaterial({
  621. color: 'red',
  622. size: 3 * window.devicePixelRatio,
  623. sizeAttenuation: false,
  624. });
  625. const points = new THREE.Points(geometry, material);
  626. return {
  627. showLines: false,
  628. mesh: points,
  629. };
  630. },
  631. },
  632. SphereBufferGeometryLow: {
  633. create(radius = 7, widthSegments = 5, heightSegments = 3) {
  634. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  635. },
  636. },
  637. SphereBufferGeometryMedium: {
  638. create(radius = 7, widthSegments = 24, heightSegments = 10) {
  639. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  640. },
  641. },
  642. SphereBufferGeometryHigh: {
  643. create(radius = 7, widthSegments = 50, heightSegments = 50) {
  644. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  645. },
  646. },
  647. SphereBufferGeometryLowSmooth: {
  648. create(radius = 7, widthSegments = 5, heightSegments = 3) {
  649. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  650. },
  651. showLines: false,
  652. flatShading: false,
  653. },
  654. SphereBufferGeometryMediumSmooth: {
  655. create(radius = 7, widthSegments = 24, heightSegments = 10) {
  656. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  657. },
  658. showLines: false,
  659. flatShading: false,
  660. },
  661. SphereBufferGeometryHighSmooth: {
  662. create(radius = 7, widthSegments = 50, heightSegments = 50) {
  663. return new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
  664. },
  665. showLines: false,
  666. flatShading: false,
  667. },
  668. PlaneBufferGeometryLow: {
  669. create(width = 9, height = 9, widthSegments = 1, heightSegments = 1) {
  670. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  671. },
  672. },
  673. PlaneBufferGeometryHigh: {
  674. create(width = 9, height = 9, widthSegments = 10, heightSegments = 10) {
  675. return new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments);
  676. },
  677. },
  678. };
  679. function addLink(parent, name, href) {
  680. const a = document.createElement('a');
  681. a.href = href || `https://threejs.org/docs/#api/geometries/${name}`;
  682. const code = document.createElement('code');
  683. code.textContent = name;
  684. a.appendChild(code);
  685. parent.appendChild(a);
  686. return a;
  687. }
  688. function addDeepLink(parent, name, href) {
  689. const a = document.createElement('a');
  690. a.href = href || `https://threejs.org/docs/#api/geometries/${name}`;
  691. a.textContent = name;
  692. a.className = 'deep-link';
  693. parent.appendChild(a);
  694. return a;
  695. }
  696. function addElem(parent, type, className, text) {
  697. const elem = document.createElement(type);
  698. elem.className = className;
  699. if (text) {
  700. elem.textContent = text;
  701. }
  702. parent.appendChild(elem);
  703. return elem;
  704. }
  705. function addDiv(parent, className) {
  706. return addElem(parent, 'div', className);
  707. }
  708. function createPrimitiveDOM(base) {
  709. const name = base.dataset.primitive;
  710. const info = diagrams[name];
  711. if (!info) {
  712. throw new Error(`no primitive ${name}`);
  713. }
  714. const text = base.innerHTML;
  715. base.innerHTML = '';
  716. const pair = addDiv(base, 'pair');
  717. const elem = addDiv(pair, 'shape');
  718. const right = addDiv(pair, 'desc');
  719. addDeepLink(right, '#', `#${base.id}`);
  720. addLink(right, name);
  721. if (info.nonBuffer !== false) {
  722. addElem(right, 'span', '', ', ');
  723. addLink(right, name.replace('Buffer', ''));
  724. }
  725. addDiv(right, '.note').innerHTML = text;
  726. // I get that this is super brittle. I think I'd have to
  727. // work through a bunch more examples to come up with a better
  728. // structure. Also, I don't want to generate actual code and
  729. // use eval. (maybe a bad striction)
  730. function makeExample(elem, createFn, src) {
  731. const rawLines = createFn.toString().replace(/return (new THREE\.[a-zA-Z]+Geometry)/, 'const geometry = $1').split(/\n/);
  732. const createRE = /^ *(?:function *)*create\d*\((.*?)\)/;
  733. const indentRE = /^( *)[^ ]/;
  734. const m = indentRE.exec(rawLines[1]);
  735. const prefixLen = m[1].length;
  736. const m2 = createRE.exec(rawLines[0]);
  737. const argString = m2[1].trim();
  738. const trimmedLines = src
  739. ? src.split('\n').slice(1, -1)
  740. : rawLines.slice(1, rawLines.length - 1).map(line => line.substring(prefixLen));
  741. if (info.addConstCode !== false && argString) {
  742. const lines = argString.split(',').map((arg) => {
  743. return `const ${arg.trim()}; // ui: ${arg.trim().split(' ')[0]}`;
  744. });
  745. const lineNdx = trimmedLines.findIndex(l => l.indexOf('const geometry') >= 0);
  746. trimmedLines.splice(lineNdx < 0 ? 0 : lineNdx, 0, ...lines);
  747. }
  748. addElem(base, 'pre', 'prettyprint showmods', trimmedLines.join('\n'));
  749. createLiveImage(elem, {...info, create: createFn}, name);
  750. }
  751. makeExample(elem, info.create, info.src);
  752. {
  753. let i = 2;
  754. for (;;) {
  755. const createFn = info[`create${i}`];
  756. if (!createFn) {
  757. break;
  758. }
  759. const shapeElem = addDiv(base, 'shape');
  760. makeExample(shapeElem, createFn, info[`src${i}`]);
  761. ++i;
  762. }
  763. }
  764. }
  765. function createDiagram(base) {
  766. const name = base.dataset.diagram;
  767. const info = diagrams[name];
  768. if (!info) {
  769. throw new Error(`no primitive ${name}`);
  770. }
  771. createLiveImage(base, info, name);
  772. }
  773. async function addGeometry(root, info, args = []) {
  774. const result = info.create(...args);
  775. const promise = (result instanceof Promise) ? result : Promise.resolve(result);
  776. let diagramInfo = await promise;
  777. if (diagramInfo instanceof THREE.BufferGeometry ||
  778. diagramInfo instanceof THREE.Geometry) {
  779. const geometry = diagramInfo;
  780. diagramInfo = {
  781. geometry,
  782. };
  783. }
  784. const geometry = diagramInfo.geometry || diagramInfo.lineGeometry || diagramInfo.mesh.geometry;
  785. geometry.computeBoundingBox();
  786. const centerOffset = new THREE.Vector3();
  787. geometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1);
  788. let mesh = diagramInfo.mesh;
  789. if (diagramInfo.geometry) {
  790. if (!info.material) {
  791. const material = new THREE.MeshPhongMaterial({
  792. flatShading: info.flatShading === false ? false : true,
  793. side: THREE.DoubleSide,
  794. });
  795. material.color.setHSL(Math.random(), .5, .5);
  796. info.material = material;
  797. }
  798. mesh = new THREE.Mesh(diagramInfo.geometry, info.material);
  799. }
  800. if (mesh) {
  801. mesh.position.copy(centerOffset);
  802. root.add(mesh);
  803. }
  804. if (info.showLines !== false) {
  805. const lineMesh = new THREE.LineSegments(
  806. diagramInfo.lineGeometry || diagramInfo.geometry,
  807. new THREE.LineBasicMaterial({
  808. color: diagramInfo.geometry ? 0xffffff : colors.lines,
  809. transparent: true,
  810. opacity: 0.5,
  811. }));
  812. lineMesh.position.copy(centerOffset);
  813. root.add(lineMesh);
  814. }
  815. }
  816. async function updateGeometry(root, info, params) {
  817. const oldChildren = root.children.slice();
  818. await addGeometry(root, info, Object.values(params));
  819. oldChildren.forEach((child) => {
  820. root.remove(child);
  821. child.geometry.dispose();
  822. });
  823. }
  824. const primitives = {};
  825. async function createLiveImage(elem, info, name) {
  826. const root = new THREE.Object3D();
  827. primitives[name] = primitives[name] || [];
  828. primitives[name].push({
  829. root,
  830. info,
  831. });
  832. await addGeometry(root, info);
  833. threejsLessonUtils.addDiagram(elem, {create: () => root});
  834. }
  835. function getValueElem(commentElem) {
  836. return commentElem.previousElementSibling &&
  837. commentElem.previousElementSibling.previousElementSibling &&
  838. commentElem.previousElementSibling.previousElementSibling.previousElementSibling;
  839. }
  840. threejsLessonUtils.onAfterPrettify(() => {
  841. document.querySelectorAll('[data-primitive]').forEach((base) => {
  842. const primitiveName = base.dataset.primitive;
  843. const infos = primitives[primitiveName];
  844. base.querySelectorAll('pre.prettyprint').forEach((shape, ndx) => {
  845. const {root, info} = infos[ndx];
  846. const params = {};
  847. [...shape.querySelectorAll('span.com')]
  848. .filter(span => span.textContent.indexOf('// ui:') >= 0)
  849. .forEach((span) => {
  850. const nameRE = /ui: ([a-zA-Z0-9_]+) *$/;
  851. const name = nameRE.exec(span.textContent)[1];
  852. span.textContent = '';
  853. if (!info.ui) {
  854. console.error(`no ui for ${primitiveName}:${ndx}`); // eslint-disable-line
  855. return;
  856. // throw new Error(`no ui for ${primitiveName}:${ndx}`);
  857. }
  858. const ui = info.ui[name];
  859. if (!ui) {
  860. throw new Error(`no ui for ${primitiveName}:${ndx} param: ${name}`);
  861. }
  862. const valueElem = getValueElem(span);
  863. if (!valueElem) {
  864. console.error(`no value element for ${primitiveName}:${ndx} param: ${name}`); // eslint-disable-line
  865. return;
  866. }
  867. const inputHolderHolder = document.createElement('div');
  868. inputHolderHolder.className = 'input';
  869. const inputHolder = document.createElement('div');
  870. span.appendChild(inputHolderHolder);
  871. inputHolderHolder.appendChild(inputHolder);
  872. switch (ui.type) {
  873. case 'range': {
  874. const valueRange = ui.max - ui.min;
  875. const input = document.createElement('input');
  876. const inputMax = 100;
  877. input.type = 'range';
  878. input.min = 0;
  879. input.max = inputMax;
  880. const value = parseFloat(valueElem.textContent);
  881. params[name] = value * (ui.mult || 1);
  882. input.value = (value - ui.min) / valueRange * inputMax;
  883. inputHolder.appendChild(input);
  884. const precision = ui.precision === undefined ? (valueRange > 4 ? 0 : 2) : ui.precision;
  885. const padding = ui.max.toFixed(precision).length;
  886. input.addEventListener('input', () => {
  887. let newValue = input.value * valueRange / inputMax + ui.min;
  888. if (precision === 0) {
  889. newValue = Math.round(newValue);
  890. }
  891. params[name] = newValue * (ui.mult || 1);
  892. valueElem.textContent = newValue.toFixed(precision).padStart(padding, ' ');
  893. updateGeometry(root, info, params);
  894. });
  895. break;
  896. }
  897. case 'bool': {
  898. const input = document.createElement('input');
  899. input.type = 'checkbox';
  900. params[name] = valueElem.textContent === 'true';
  901. input.checked = params[name];
  902. inputHolder.appendChild(input);
  903. input.addEventListener('change', () => {
  904. params[name] = input.checked;
  905. valueElem.textContent = params[name] ? 'true' : 'false';
  906. updateGeometry(root, info, params);
  907. });
  908. break;
  909. }
  910. case 'text': {
  911. const input = document.createElement('input');
  912. input.type = 'text';
  913. params[name] = valueElem.textContent.slice(1, -1);
  914. input.value = params[name];
  915. input.maxlength = ui.maxLength || 50;
  916. inputHolder.appendChild(input);
  917. input.addEventListener('input', () => {
  918. params[name] = input.value;
  919. valueElem.textContent = `'${input.value.replace(/'/g, '\'')}'`;
  920. updateGeometry(root, info, params);
  921. });
  922. break;
  923. }
  924. default:
  925. throw new Error(`unknown type for ${primitiveName}:${ndx} param: ${name}`);
  926. }
  927. });
  928. });
  929. });
  930. });
  931. document.querySelectorAll('[data-diagram]').forEach(createDiagram);
  932. document.querySelectorAll('[data-primitive]').forEach(createPrimitiveDOM);
  933. }