Adding points to vertices on mesh geometry based on their distance

My scene includes a THREE.Geometry with more than 5,000 vertices. I am looking to add THREE.Points to the scene for only 3 specific vertices of the mesh within the geometry. My goal is to achieve a similar outcome as shown in this example:

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

To accomplish this, I selected the 3 vertices from the first face of the existing geometry and incorporated them into the vertices of a new geometry that should contain these 3 points. I experimented with using both THREE.Points along with THREE.PointsMaterial, and also with THREE.LineSegments paired with

THREE.LineBasicMaterial</code, producing similar results (except lines instead of points).</p>

<pre><code>var vertices = [
  mesh.geometry.faces[0].a,
  mesh.geometry.faces[0].b,
  mesh.geometry.faces[0].c
];


vertices.forEach( function(vId,i){
  vertices[i].index = i;
  vertices[i] = mesh.geometry.vertices[vId].clone();
  vertices[i].l2w = mesh.localToWorld(vertices[i].clone());
  vertices[i].id = vId;
  vertices[i].distance = vertices[i].l2w.distanceTo(camera.position);

})


var plane_geom = new THREE.Geometry();
plane_geom.vertices.push(vertices[0]);
plane_geom.vertices.push(vertices[1]);
plane_geom.vertices.push(vertices[2]);


plane_geom.verticesNeedUpdate = true;
plane_geom.elementsNeedUpdate = true;
plane_geom.computeVertexNormals();


var pointsMaterial2 = new THREE.PointsMaterial({
  size: 2,
  color: "red"
});

var plane_mesh =  new THREE.Points( plane_geom, pointsMaterial2 );
 scene.add( plane_mesh );


mesh.geometry.dispose();
mesh.material.dispose();
scene.remove( mesh);

The initial geometry is globally defined as the geometry of the loaded STL-object and belongs to type THREE.Geometry. The mesh with this geometry is added to the scene in the init function. The geometry object has the following structure:

__directGeometry: Object { vertices: (30006) […], normals: (30006) […], 
colors: (30006) […], … }
__bufferGeometry: Object { uuid: "10EE834D-B19E-4C27-B831-F484D908DB06",                   
name: "", type: "BufferGeometry", … }
_listeners: Object { dispose: (1) […] }
boundingBox: Object { min: {…}, max: {…} }
boundingSphere: Object { center: {…}, radius: 135.73491999459804 }
colors: Array []
colorsNeedUpdate: false
elementsNeedUpdate: false
faceVertexUvs: Array [ [] ]
faces: Array(10002) [ {…}, {…}, {…}, … ]
groupsNeedUpdate: false
id: 2
lineDistances: Array []
lineDistancesNeedUpdate: false
morphNormals: Array []
morphTargets: Array []
name: ""
normalsNeedUpdate: false
skinIndices: Array []
skinWeights: Array []
type: "Geometry"
uuid: "0EB01FF3-E9BF-4CAD-AA97-5EC2933F0D9C"
uvsNeedUpdate: false
vertices: Array(5003) [ {…}, {…}, {…}, … ]
verticesNeedUpdate: false

Upon adding the new mesh plane_mesh with the updated geometry to the scene, all the points (representing each vertex) are displayed (exceeding 5,000 points). However, upon removing the initial mesh from the scene, only the 3 specified points appear visible. When examining plane_mesh, everything appears normal and the mesh contains just the 3 vertices... After several attempts, it became evident that all operations were affecting the initial mesh. Only after disposing of the mesh, was plane_mesh successfully integrated into the scene.

If you have any insights or solutions, they would be greatly appreciated!

Answer №1

If you want to create a triangle geometry and modify its vertices later on, you can follow this approach using Three.js (r108):

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var geom = new THREE.PlaneBufferGeometry(10, 10, 4, 4);
var mat = new THREE.MeshBasicMaterial({
  color: "aqua",
  wireframe: true
});
var mesh = new THREE.Mesh(geom, mat);
scene.add(mesh);

var pointsGeom = new THREE.BufferGeometry().setFromPoints([
  new THREE.Vector3(),
  new THREE.Vector3(),
  new THREE.Vector3()
]);
var pointsMat = new THREE.PointsMaterial({
  size: 1,
  color: "red"
});
var points = new THREE.Points(pointsGeom, pointsMat);
scene.add(points);

setInterval(() => {
  let faces = geom.index.count / 3;
  let face = THREE.Math.randInt(0, faces - 1);

  setTriangle(face);

}, 1000);

var v3 = new THREE.Vector3(); // temp vector

function setTriangle(face) {

  for (let i = 0; i < 3; i++) {
    v3.fromBufferAttribute(geom.attributes.position, geom.index.getX(face * 3 + i));
    pointsGeom.attributes.position.setXYZ(i, v3.x, v3.y, v3.z);
  }

  pointsGeom.attributes.position.needsUpdate = true;

}

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera)
});
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

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

How can I use a dropdown with checkbox to toggle the visibility of a specific div in React?

I have come across a relevant question, but I am struggling to apply it to multiple divs. I haven't found a solution that quite fits my needs. Show or hide element in React Currently, I am using the dropdown with checkboxes from MUI. I am seeking a ...

I am trying to set a background image specifically for one page in my application, but I am struggling to make it work. As a newcomer, I am still learning how to

I've been working on the code for a login page, but I'm having trouble setting a background image for the page. I know how to set it for the whole application by modifying the app component, but when I try to do the same for this specific compone ...

Accessing Parent and Child Values in AngularJS Selections

I am seeking advice from experts on how to achieve the following desired results: Expected workflow chart: https://i.sstatic.net/9ZmmT.png Here is the default view: https://i.sstatic.net/H6xkZ.png Scenario 1: By clicking on the number "1", all items f ...

Calculating the duration of time using JQuery with provided start and end times

I am currently utilizing a jQuery time picker to gather start and end times in a 12hr format. My goal is to calculate the time duration between the start and end times in HH:MM:SS format. The code snippet I have below is providing me with a duration like ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

jquery logic for iterating through all elements in a select menu encountering issues

In search of a solution to iterate through all options in a dropdown list using code, comparing each to a variable. When a match is found, I aim to set that particular value as the selected item in the dropdown and then exit the loop. Here's what I&ap ...

Image flipping effect malfunctioning in Safari and Internet Explorer

My image flipping effect is not functioning properly in Safari and IE browsers. Here is the code I am using: .flipcard { position: relative; width: 220px; height: 220px; perspective: 500px; margin: auto; text-align: center; } .flipcard.v:hove ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Simple steps for integrating JavaScript ads into your WordPress website

Received an advertisement from my client, a 300x250 ad in ad folder consisting of 1 HTML file, 1 JavaScript file, and 1 images folder. Questioning how to integrate these files into the side panel of my Wordpress website's homepage. I've spent a ...

What is the best method to set variables to zero using this array in JavaScript?

I am looking to extract strings from an array and set them all to zero. The original array consists of: var myArray = ["apple", "banana", "cherry", "date"]; The expected outcome should be: var apple = 0; var banana = 0; var cherry = 0; var date = 0; I ...

The proportions of the slices in a pie chart remain consistent even as the data is updated (based on the current version at the time of

I am currently experiencing an issue with a pie chart that is generated using the Google JSON schema for charts. The data for the chart is retrieved via ajax and loaded successfully, with all slices displaying correctly based on the initial values provided ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

Guide to declaring variables using jQuery

Currently tackling a school project, I stumbled upon some online example solutions and managed to decipher most of the code. However, there is one line that has me puzzled. var $newTweet = $('<div class=tweet></div>'); My assumption ...

Having trouble populating two linked html dropdowns with JSON data using jQuery?

My attempt to populate two HTML selects with JSON data is resulting in an error: Uncaught TypeError: country.map is not a function when trying to populate the cities. Can anyone point out the issue with the code? $(document).ready(function() { let $co ...

Encountering an Uncaught TypeError while trying to read properties of undefined (specifically 'remove') during a Change event is causing an issue for me

Looking to update the icons by changing the class from .fa-plus to .fa-minus for this specific menu section <div class="accordion-menu"> <h2 class="accordion-header" id="subseccOne"> ...

There are no headers present in the response from apollo-client

I am currently utilizing a graphql api along with a vue.js frontend that incorporates the apollo client for fetching data from the backend. This setup has been operating smoothly thus far. In each response header, the server sends back a new JWT-Token whi ...

Looking for assistance with ReactJs code related to implementing a filter button

I've been working on creating a filter button using ReactJs, but I can't seem to get it to work properly. I've spent a lot of time troubleshooting, but the issue persists. You can view my codePen here: https://codepen.io/tinproht123/pen/gOxe ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...