Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

в этом коде каждая точка должна иметь разный размер, но сейчас они все одинаковые, в чем…

  1. User

    в этом коде каждая точка должна иметь разный размер, но сейчас они все одинаковые, в чем ошибка? код: import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

    const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);

    const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false;

    controls.enableDamping = true; controls.dampingFactor = 0.05;

    const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb';

    loader.load(url, function (gltf) { const model = gltf.scene;

    model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry;

      const texture = new THREE.TextureLoader().load('texture3.png');
      
      const sizeVariation = 0.001;
    
      const geometryPoint = new THREE.BufferGeometry();
    
      const positions = geometry.getAttribute('position').array;
    
      
      const randomSize = [];
      for (let i = 0; i < positions.length; i += 3) {
        const startSize = 0.06;
        const size = startSize + (Math.random() * sizeVariation);
        randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] 
      }
      // let startSize = 0.06;
      
      const materialPoint = new THREE.PointsMaterial({
        size: 1, // задаем произвольный стартовый размер, он будет изменен в цикле анимации
        sizeAttenuation: true,
        map: texture,
        alphaTest: 0.01,
        transparent: true,
        color: new THREE.Color(1., 1., 1.),
        opacity: 1.
      });
      
      geometryPoint.setAttribute('size', new THREE.BufferAttribute(new Float32Array(randomSize), 3));
    
      const randomPosition = [];
      for (let i = 0; i < positions.length; i += 3) {
        randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0);
      }
      const randomPositionCopy = [...randomPosition];
    
      let increment = 0.002;
    
      geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    
      const points = new THREE.Points(geometryPoint, materialPoint);
    
    
      geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      function updateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < positions[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > positions[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - positions[i]) < 0.002) {
              randomPosition[i] = positions[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
      function reverseUpdateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
              randomPosition[i] = randomPositionCopy[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
    
      let time = 0;
      let sinPosition;
      let sinPosition2;
      let cosPosition;
      let randSignArray = [];
      let sign;
      let ratio = 1.0;
    
      for(let i = 0; i<randomPosition.length; i++) {
        sign = Math.random() < 0.5 ? -1.0 : 1.0;
        randSignArray[i] = sign;
      }
      geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      // animateVerticles();
      // function animateVerticles() {
      //   requestAnimationFrame(animateVerticles);
      //   time += 0.1;
      //   sinPosition = Math.sin(time)*0.1;
      //   cosPosition = Math.cos(time*0.1)*0.1;
      //   sinPosition2 = Math.sin(time/Math.PI)*0.1;
      //   for(let i = 0; i<randomPosition.length; i++) {
      //     randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
      //   }
      //   geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      // }
    
      window.addEventListener('wheel', function(event) {
        if (event.deltaY > 0) {
          updateArray(increment);
          if(ratio > 0.0) {
            ratio -= 0.01;
          }
        } else {
          reverseUpdateArray(increment);
          ratio += 0.01;
        }
        console.log(ratio);
    
      });
    
      scene.add(points);
      points.rotateX(Math.PI/2.0);
    }
    

    }); camera.position.z = 3;

    function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera); } animate(); });

  2. Assistant

    Ошибка заключается в том, что настройки размера частиц задаются в объекте BufferAttribute, который передается в PointsMaterial через свойство size. В данном случае свойство size имеет значение 1, что означает, что все частицы будут одинакового размера. Чтобы каждая частица имела свой уникальный размер, необходимо передать массив размеров через атрибут size объекта BufferGeometry. Это делается следующим образом:

    const sizes = new Float32Array(randomSize);
    geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
    

    Здесь randomSize - это массив случайных размеров, а sizes - это Float32Array, созданный на основе randomSize. Затем sizes передается в setAttribute объекта BufferGeometry через свойство size.

  3. User

    по-прежнему точки одинакового размера код: import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

    const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);

    const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false;

    controls.enableDamping = true; controls.dampingFactor = 0.05;

    const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb';

    loader.load(url, function (gltf) { const model = gltf.scene;

    model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry;

      const texture = new THREE.TextureLoader().load('texture3.png');
      
      const sizeVariation = 0.001;
    
      const geometryPoint = new THREE.BufferGeometry();
    
      const positions = geometry.getAttribute('position').array;
    
      
      const randomSize = [];
      for (let i = 0; i < positions.length; i += 3) {
        const startSize = 0.06;
        const size = startSize + (Math.random() * sizeVariation);
        randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] 
      }
      // let startSize = 0.06;
      
      const materialPoint = new THREE.PointsMaterial({
        sizeAttenuation: true,
        map: texture,
        alphaTest: 0.01,
        transparent: true,
        color: new THREE.Color(1., 1., 1.),
        opacity: 1.
      });
      
      const sizes = new Float32Array(randomSize);
      geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
    
      const randomPosition = [];
      for (let i = 0; i < positions.length; i += 3) {
        randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0);
      }
      const randomPositionCopy = [...randomPosition];
    
      let increment = 0.002;
    
      geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    
      const points = new THREE.Points(geometryPoint, materialPoint);
    
    
      geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      function updateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < positions[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > positions[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - positions[i]) < 0.002) {
              randomPosition[i] = positions[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
      function reverseUpdateArray(increment) {
        for(let j = 0; j < 75; j++) {
          for(let i = 0; i<randomPosition.length; i++) {
            if (randomPosition[i] < randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] + increment;
            } else if(randomPosition[i] > randomPositionCopy[i]) {
              randomPosition[i] = randomPosition[i] - increment;
            } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) {
              randomPosition[i] = randomPositionCopy[i];
            }
          }
        }
        geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      }
    
      let time = 0;
      let sinPosition;
      let sinPosition2;
      let cosPosition;
      let randSignArray = [];
      let sign;
      let ratio = 1.0;
    
      for(let i = 0; i<randomPosition.length; i++) {
        sign = Math.random() < 0.5 ? -1.0 : 1.0;
        randSignArray[i] = sign;
      }
      geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      // animateVerticles();
      // function animateVerticles() {
      //   requestAnimationFrame(animateVerticles);
      //   time += 0.1;
      //   sinPosition = Math.sin(time)*0.1;
      //   cosPosition = Math.cos(time*0.1)*0.1;
      //   sinPosition2 = Math.sin(time/Math.PI)*0.1;
      //   for(let i = 0; i<randomPosition.length; i++) {
      //     randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio;
      //   }
      //   geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3));
      // }
    
      window.addEventListener('wheel', function(event) {
        if (event.deltaY > 0) {
          updateArray(increment);
          if(ratio > 0.0) {
            ratio -= 0.01;
          }
        } else {
          reverseUpdateArray(increment);
          ratio += 0.01;
        }
        console.log(ratio);
    
      });
    
      scene.add(points);
      points.rotateX(Math.PI/2.0);
    }
    

    }); camera.position.z = 3;

    function animate() { requestAnimationFrame(animate); controls.update(); renderer.render(scene, camera); } animate(); });

  4. Assistant

    Возможно, проблема в том, что в materialPoint нет значения size, которое бы непосредственно определяло размер точек. Попробуйте добавить это значение и передать ему массив размеров, заданный через атрибут size BufferGeometry:

    const materialPoint = new THREE.PointsMaterial({
        size: 1,
        sizeAttenuation: true,
        map: texture,
        alphaTest: 0.01,
        transparent: true,
        color: new THREE.Color(1., 1., 1.),
        opacity: 1.
    });
    
    geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1));
    

    Также необходимо обновить materialPoint в объекте Points:

    const points = new THREE.Points(geometryPoint, materialPoint);
    

    После этих изменений каждая точка должна иметь уникальный размер.

  5. User

    как изменить этот же код так, чтобы вместо точек были сферы

  6. Assistant

    Чтобы заменить точки на сферы, нужно вместо THREE.Points использовать THREE.Mesh, и создать для каждой сферы свою геометрию и материал:

    const geometrySphere = new THREE.SphereBufferGeometry(0.5, 16, 16);
    const materialSphere = new THREE.MeshBasicMaterial({
      color: new THREE.Color(1., 1., 1.),
      opacity: 0.2,
      transparent: true,
      map: texture,
      side: THREE.DoubleSide
    });
    
    // ...
    
    const spheres = new THREE.Group();
    for (let i = 0; i < randomPosition.length; i += 3) {
      const sphere = new THREE.Mesh(geometrySphere, materialSphere);
      sphere.position.set(randomPosition[i], randomPosition[i + 1], randomPosition[i + 2]);
      const size = sizes[Math.floor(i / 3)];
      sphere.scale.set(size, size, size);
      spheres.add(sphere);
    }
    
    // ...
    
    scene.add(spheres);
    

    Также нужно будет изменить функции updateArray и reverseUpdateArray, чтобы они изменяли позицию и масштаб каждой сферы в группе:

    function updateArray(increment) {
      for(let j = 0; j < 75; j++) {
        for(let i = 0; i < spheres.children.length; i++) {
          const sphere = spheres.children[i];
          const position = sphere.position;
          if (position.x < positions[3 * i]) {
            position.x += increment;
          } else if(position.x > positions[3 * i]) {
            position.x -= increment;
          } else if(Math.abs(position.x - positions[3 * i]) < 0.002) {
            position.x = positions[3 * i];
          }
          if (position.y < positions[3 * i + 1]) {
            position.y += increment;
          } else if(position.y > positions[3 * i + 1]) {
            position.y -= increment;
          } else if(Math.abs(position.y - positions[3 * i + 1]) < 0.002) {
            position.y = positions[3 * i + 1];
          }
          if (position.z < positions[3 * i + 2]) {
            position.z += increment;
          } else if(position.z > positions[3 * i + 2]) {
            position.z -= increment;
          } else if(Math.abs(position.z - positions[3 * i + 2]) < 0.002) {
            position.z = positions[3 * i + 2];
          }
          sphere.scale.set(sizes[i], sizes[i], sizes[i]);
        }
      }
    }
    
    function reverseUpdateArray(increment) {
      for(let j = 0; j < 75; j++) {
        for(let i = 0; i < spheres.children.length; i++) {
          const sphere = spheres.children[i];
          const position = sphere.position;
          const copyPosition = randomPositionCopy.slice(3 * i, 3 * i + 3);
          if (position.x < copyPosition[0]) {
            position.x += increment;
          } else if(position.x > copyPosition[0]) {
            position.x -= increment;
          } else if(Math.abs(position.x - copyPosition[0]) < 0.002) {
            position.x = copyPosition[0];
          }
          if (position.y < copyPosition[1]) {
            position.y += increment;
          } else if(position.y > copyPosition[1]) {
            position.y -= increment;
          } else if(Math.abs(position.y - copyPosition[1]) < 0.002) {
            position.y = copyPosition[1];
          }
          if (position.z < copyPosition[2]) {
            position.z += increment;
          } else if(position.z > copyPosition[2]) {
            position.z -= increment;
          } else if(Math.abs(position.z - copyPosition[2]) < 0.002) {
            position.z = copyPosition[2];
          }
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.