"Troubleshooting issue: Error encountered when trying to update three.js Buffer

I have been diving into the world of three.js and recently came across this tutorial to enhance my skills. However, it seems that the code provided in the tutorial is not compatible with the current version of Three.js. After consulting this helpful resource, I made some modifications to the original code as shown below:

  var k = 1;
     
  const positions = sphere.geometry.attributes.position.array;
  for (var i = 0; i < positions.length - 2; i++) {
    const v = new THREE.Vector3(
      positions[i], 
      positions[i + 1], 
      positions[i + 2]
    ).normalize()
    .multiplyScalar(
      1 + 0.3 * noise.perlin3(
      positions[i] * k + time,
      positions[i + 1] * k,
      positions[i + 2] * k));
      positions[i] = v.x;
      positions[i + 1] = v.y;
      positions[i + 2] = v.z;
  }
  
 sphere.geometry.attributes.position.needsUpdate = true;

However, despite these updates, the smoothness of vertex displacement is still lacking compared to the tutorial. Can anyone help me identify what might be missing here?

var renderer = new THREE.WebGLRenderer({ canvas : document.getElementById('canvas'), antialias:true});
// default bg canvas color //
renderer.setClearColor(0x7b7b7b);
//  use device aspect ratio //
renderer.setPixelRatio(window.devicePixelRatio);
// set size of canvas within window //
renderer.setSize(window.innerWidth, window.innerHeight);




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


var sphere_geometry = new THREE.SphereGeometry(1, 128, 128);
const material = new THREE.MeshPhongMaterial({
    color: 0x0000FF,
    shininess: 1000,
  })

var sphere = new THREE.Mesh(sphere_geometry, material);
scene.add(sphere);
const ambientLight = new THREE.AmbientLight(0x798296)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
    directionalLight.position.set(5, 10, 7)
scene.add(directionalLight);
sphere.geometry.attributes.position.needsUpdate = true;

var update = function() {

  // change '0.003' for more aggressive animation
  var time = performance.now() * 0.003;
  //console.log(time)

  //go through vertices here and reposition them
  
  // change 'k' value for more spikes
  var k = 1;
     
  const positions = sphere.geometry.attributes.position.array;
  for (var i = 0; i < positions.length - 2; i++) {
    const v = new THREE.Vector3(
      positions[i], 
      positions[i + 1], 
      positions[i + 2]
    ).normalize()
    .multiplyScalar(
      1 + 0.3 * noise.perlin3(positions[i] * k + time,                 positions[i + 1] * k,
      positions[i + 2] * k));
      positions[i] = v.x;
      positions[i + 1] = v.y;
      positions[i + 2] = v.z;
  }
  
 sphere.geometry.attributes.position.needsUpdate = true;
}

function animate() {
  sphere.rotation.x += 0.01;
  sphere.rotation.y += 0.01;

  update();
  /* render scene and camera */
  renderer.render(scene,camera);
  requestAnimationFrame(animate);
}


requestAnimationFrame(animate);
html, body {
  margin:0;
  overflow:hidden
}
<script src="https://fariskassim.com/stage/rebel9/teaf/blob/v4/js/perlin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<canvas id="canvas"></canvas>

Answer №1

Learn how to manipulate a sphere using noise with BufferGeometry:

https://i.sstatic.net/RLxkw.png

var renderer = new THREE.WebGLRenderer({ canvas : document.getElementById('canvas'), antialias:true});
// adjust canvas background color //
renderer.setClearColor(0x7b7b7b);
//  maintain device aspect ratio //
renderer.setPixelRatio(window.devicePixelRatio);
// specify size of canvas within window //
renderer.setSize(window.innerWidth, window.innerHeight);

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

var sphere_geometry = new THREE.SphereGeometry(1, 128, 128);
const material = new THREE.MeshPhongMaterial({
    color: 0x0000FF,
    shininess: 1000,
  })

var sphere = new THREE.Mesh(sphere_geometry, material);
scene.add(sphere);
const ambientLight = new THREE.AmbientLight(0x798296)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
    directionalLight.position.set(5, 10, 7)
scene.add(directionalLight);
sphere.geometry.attributes.position.needsUpdate = true;

var update = function() {
  var time = performance.now() * 0.003;
  
  // alter vertices for animation
  
  var k = 1;
  var v3 = new THREE.Vector3();   
  const positions = sphere.geometry.attributes.position;
  for (var i = 0; i < positions.count; i++) {
    v3.fromBufferAttribute(positions, i).setLength(k);
    let n = noise.perlin3(v3.x, v3.y, v3.z);
    v3.setLength(1 + 0.3 * n);
    positions.setXYZ(i, v3.x, v3.y, v3.z);
  }
  positions.needsUpdate = true;
  sphere.geometry.computeVertexNormals(); 
}

function animate() {
  sphere.rotation.x += 0.01;
  sphere.rotation.y += 0.01;

  update();
  /* render scene and camera */
  renderer.render(scene,camera);
  requestAnimationFrame(animate);
}

requestAnimationFrame(animate);
html, body {
  margin:0;
  overflow:hidden
}
<script src="https://fariskassim.com/stage/rebel9/teaf/blob/v4/js/perlin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<canvas id="canvas"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to evaluate the complexity of automating the user interface of a web application?

What are some common indicators of the challenges involved in automating the frontend of a web application? One example could be ensuring that all “critical” elements have stable ID attributes that do not change frequently. Are there any other similar ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

What is the correct way to retrieve a response from an async/await function?

After working with async/await functions for a few months, I have managed to get my code functioning. However, there are still some aspects of it that elude me, and I could benefit from some guidance. Within the code snippet below lies an async function t ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

The shallow render function in jest/Enzyme does not correctly render components that are wrapped in a Consumer

My current component setup looks like this: import React from 'react'; import classNames from 'classnames/bind'; import { connect } from 'react-redux'; import Topic from './components/Topics'; import AutoItem from ...

How can I sort child divs based on a data attribute containing recent date time using jQuery?

Organizing sections by their respective category names and reordering child div elements based on the data attribute, sorted in descending order from most recent to oldest published date. However, encountering issues with the function reArrangeVideosByRece ...

How can I rotate an object around its own center using Three.js instead of the world center?

I have encountered an issue with rotating objects in my scene. The cube rotates around its own center, which is what I expected. However, the shoe model's rotation axis is along the world's y-axis. In my original code, I had: cube.rotation.y += ...

Understanding the operational aspects of Typescript's target and lib settings

When the tsconfig.json file is configured like this: "target": "es5", "lib": [ "es6", "dom", "es2017" ] It appears that es2017 features are not being converted to es5. For example, code like the following will fail in IE11: var foo = [1, 2, 3].includes( ...

Is there a way to automatically initiate a 'click' event upon page load using this particular code snippet?

Is there a way to trigger this action automatically upon page load? <a onclick="$('a[href=\'#tab-review\']').trigger('click');"><?php echo $text_write; ?></a> Any suggestions would be greatly appr ...

Issue encountered when using JSON.parse() on a serialized array retrieved from sessionStorage

For my project, I needed to store an array in sessionStorage and came across a helpful answer that guided me to this solution: Storing Objects in HTML5 localStorage The process of storing the array using sessionStorage.setItem('flavors', JSON.st ...

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

Problem with the horizontal alignment of an HTML list caused by lightning-generated code

Hello, I recently inherited a small project from another developer which involves working with a calendar in a Salesforce Lightning component. The calendar is created using JavaScript to generate an unordered list filled with list items representing each d ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

Guide on how to postpone an XMLHttpRequest in GreaseMonkey until the destination page has completed loading

I have a specific request related to GreaseMonkey. I am trying to make a GET request using GM_xmlhttpRequest to fetch content from a page that loads some of its content after an initial progress bar (due to AJAX). My goal is to retrieve the complete conten ...

Update Mapbox popups following filtering

I have successfully constructed a Mapbox map with a complex custom popup structure, complete with photos and formatting. The data is being fed from a .csv file using omnivore, and the popups are being created on ready. Additionally, I have implemented a se ...

New parents, same name D3.JS

Currently utilizing d3.js to visualize a tree structure. When parsing the JSON object containing nameOfNode and NameOfParent, encountering an issue when there are two nodes with the same name. Seeking recommendations on the most effective way to address ...

The mobile devices are not showing my HTML website

I have implemented the following CSS link code on my website: <link rel="stylesheet" href="index_files/front.css" media="all" type="text/css" > Additionally, I have included the following code <meta name="HandheldFriendly" content="True"> & ...

The outcome yielded by a repeating function

This recursive function commonHint in the Meteor server is causing result to be undefined in the console, even though finalRes has a value. Any ideas on how to properly return finalRes to the caller? Thanks! // Calling the recursive method let re ...

Preserving Dimension Ratio with Full Width and Height (Trimming Overflow in CSS)

I'm currently developing a full-screen background slideshow. My query is: How can I ensure that an image fills the entire screen while maintaining its aspect ratio? Although min-height and min-width provide some assistance, they do not maintain the ...

Issue with parent-child communication in React.js causing malfunction

I am facing an issue with maintaining state between two different JavaScript files using React. The parent class, break.js, is defined as follows: export default function AlertDialog(props) { const [demoOpen, setDemoOpen] = React.useState(true); ...