threejs-custom-buffergeometry.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import * as THREE from 'three';
  2. import {threejsLessonUtils} from './threejs-lesson-utils.js';
  3. {
  4. const loader = new THREE.TextureLoader();
  5. const texture = loader.load('/manual/examples/resources/images/star-light.png');
  6. texture.wrapS = THREE.RepeatWrapping;
  7. texture.wrapT = THREE.RepeatWrapping;
  8. texture.repeat.set(3, 1);
  9. function makeMesh(geometry) {
  10. const material = new THREE.MeshPhongMaterial({
  11. color: 'hsl(300,50%,50%)',
  12. side: THREE.DoubleSide,
  13. map: texture,
  14. });
  15. return new THREE.Mesh(geometry, material);
  16. }
  17. threejsLessonUtils.addDiagrams({
  18. geometryCylinder: {
  19. create() {
  20. return new THREE.Object3D();
  21. },
  22. },
  23. bufferGeometryCylinder: {
  24. create() {
  25. const numSegments = 24;
  26. const positions = [];
  27. const uvs = [];
  28. for (let s = 0; s <= numSegments; ++s) {
  29. const u = s / numSegments;
  30. const a = u * Math.PI * 2;
  31. const x = Math.sin(a);
  32. const z = Math.cos(a);
  33. positions.push(x, -1, z);
  34. positions.push(x, 1, z);
  35. uvs.push(u, 0);
  36. uvs.push(u, 1);
  37. }
  38. const indices = [];
  39. for (let s = 0; s < numSegments; ++s) {
  40. const ndx = s * 2;
  41. indices.push(
  42. ndx, ndx + 2, ndx + 1,
  43. ndx + 1, ndx + 2, ndx + 3,
  44. );
  45. }
  46. const positionNumComponents = 3;
  47. const uvNumComponents = 2;
  48. const geometry = new THREE.BufferGeometry();
  49. geometry.setAttribute(
  50. 'position',
  51. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  52. geometry.setAttribute(
  53. 'uv',
  54. new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  55. geometry.setIndex(indices);
  56. geometry.computeVertexNormals();
  57. geometry.scale(5, 5, 5);
  58. return makeMesh(geometry);
  59. },
  60. },
  61. });
  62. }