Top method for extracting mesh vertices in three.js

Being new to Three.js, I may not be approaching this in the most optimal way,

I start by creating geometry like this:

const geometry = new THREE.PlaneBufferGeometry(10,0);

Next, I apply a rotation:

geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );

Then, I create a Mesh from it:

const mesh = new THREE.Mesh( geometry, materialNormal);

I then perform various operations on the mesh to position it correctly, such as:

mesh.position.copy(v2(10,20);
mesh.position.z = 0.5*10

mesh.position.x -= 20
mesh.position.y -= 10
mesh.rotation.z = angle;

Now, what is the best approach to access the vertices of the mesh before and after its position is adjusted? It was surprising to learn that the vertices of a mesh are not inherently stored in three.js.

Any advice or code examples would be highly appreciated.

Answer №1

It seems like there might be some confusion related to three.js objects and their properties.

1) In three.js, a Mesh object does not actually store its vertices. Instead, it holds references to a Geometry/BufferGeometry object, as well as one or more Materials. The actual vertex data is stored within the geometry property of the Mesh.

2) When using PlaneBufferGeometry, which is a type of BufferGeometry, the vertex positions are stored in the position attribute (accessed through

mesh.geometry.attributes.position
). It's important to consider that the order of the vertices may be influenced by the index property (mesh.geometry.index).

In response to your inquiry, the geometric origin of the mesh aligns with its parent Mesh's origin. Therefore, the vertex positions "before mesh transformation" remain unchanged from their initial creation. You can retrieve them directly.

To obtain the updated vertex positions after applying mesh transformations, you'll need to convert each vertex from the local space of the Mesh to world space. Fortunately, three.js offers a convenient function for this purpose:

var tempVertex = new THREE.Vector3();
// Set tempVertex based on information from mesh.geometry.attributes.position

mesh.localToWorld(tempVertex);
// TempVertex now represents the position after transforming into world coordinates

Answer №2

Check out this TypeScript example:

This code snippet retrieves the grid's position in the global coordinate system.

function getObjectCoordinates(obj: THREE.Object3D): { points: Array<THREE.Vector3>, surfaces: Array<THREE.Face3> } {
    let points: Array<THREE.Vector3> = [];
    let result = { points: points, surfaces: null };

    if (obj.hasOwnProperty("geometry")) {
        let geometry = obj["geometry"];
        
        if (geometry instanceof THREE.Geometry) {
            for (let point of geometry.vertices) {
                points.push(point.clone().applyMatrix4(obj.matrix));
            }
            result.surfaces = geometry.faces;
        } else if (geometry instanceof THREE.BufferGeometry) {
            let tempGeometry = new THREE.Geometry().fromBufferGeometry(geometry);
            
            for (let point of tempGeometry.vertices) {
                points.push(point.applyMatrix4(obj.matrix));
            }

            result.surfaces = tempGeometry.faces;
            tempGeometry.dispose();
        }
    }
    
    return result;
}

Alternatively, you can use the following code snippet:

if (geometry instanceof THREE.BufferGeometry) {
    let positions: Float32Array = geometry.attributes["position"].array;
    let pointCount = positions.length / 3;

    for (let i = 0; i < pointCount; i++) {
        let p = new THREE.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
    }
}

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

vue-dropzone fails to create thumbnails when a file is added

I am facing an issue where I want to upload files that are already stored on my server to the Dropzone. Despite searching extensively through both vue-dropzone and regular dropzone documentation, as well as various GitHub issues for solutions, I have not b ...

The Powerful Duo: JavaScript and Regex

Having some issues with the code snippet below, I know there's an error in my code but I can't seem to figure out what it is (tried enclosing the code in quotes but that didn't work...) var Regex = require('regex') var regex = new ...

Simplifying complex JSON structures by un-nesting arrays

Within my Formik form, I have 3 fields: MemberMemberID, EventEventID, and event_date. This form represents an event (such as a Tuesday club) taking place on a specific date and attended by various members. Formik stores the data in key-value pairs within ...

Alert: Mouse Exiting Window - Moodle Prompt

I have created an online exam using the Moodle platform, coded in PHP. I am now looking for a way to prevent test-takers from navigating away from the test by implementing a mouseover pop-up. Below is the code I have for triggering an alert pop-up when th ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

Issue with Parsley validation not functioning as expected

I have implemented parsley.js to validate my form, but I am facing an issue when trying to validate a checkbox using the data-mincheck attribute. Below is the snippet of my code: <form data-validate="parsley"> <p>Please choose at least 2 ...

Handling errors in chained promises and routes in Node.js/ExpressJS

I'm currently dealing with some confusion regarding how to handle errors when making function calls. To demonstrate this, I'll be using sequelizeJS as an example. Usually: First.Ctrl var second_ctrl = require( '../ctrl/second'); testC ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Encountering a 403 error while using the ajax infinite loading script

Based on recommendations from my previous inquiry, I made the decision to incorporate an infinite loading script onto my page. However, every time the script is activated, a 403 - forbidden error occurs. Here is the JavaScript code snippet: jQuery(documen ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

The error message "There is no defined window.matchMedia prefers-color-scheme window in Next.js"

I am currently working on a project with React.js alongside Next.js and encountered an issue that I need assistance with. Upon loading the page, I need to set a variable that indicates whether the user is using dark mode or not. I attempted the following ...

Updating the error state of a TextField Component in React MaterialUI upon clicking a button

After clicking a 'search' button, I want to validate input fields in my input form. Many solutions suggest validating the input live as it is entered, but I prefer not to do this because some of the validation processes are costly operations, su ...

The $scope object in AngularJS has not been properly defined and

I am facing an issue with retrieving the value of email in my controller. It always returns 'undefined'. Here is my form: <form role="form" novalidate> <div class="form-group"> <input type="email" ng-model="user.emai ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Troubleshooting a Global Search Problem with Regular Expressions in Javascript

I am facing a minor problem. Here is the snippet of code I am working with: var result1=content.match("/<a [^>]*href\s*=\s*[\"']([^>\"']*)[\"'][^>]*>/gi")[1]; This code is not returning any value. Al ...

I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause, import React, { useEffect, useState } from 'react'; import VideoCardComponent from './VideoCard'; import Grid from '@mui/material ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

In Angular 5, a variable's value becomes undefined once it is subscribed to outside of its assigned

I keep encountering an undefined value when trying to assign the subscribed value to a variable in my code snippet below. service.ts getIpAddress() : Observable<any> { return this.http .get(this.Geo_Api) .map((response: ...

What is the best way to include the application version in an Electron project using JavaScript

While attempting to publish an update for my app, I encountered a strange error. Can anyone pinpoint the issue? (Note: Node.js is included) Error Message: Unexpected token < <script> console.log(process); let output = <h2 class="page- ...

Force the page to refresh if the user navigates back using the browser's back button

Similar Question: Cross-browser onload event and the Back button I am looking for a way to automatically refresh a view or page when a user navigates back to it using the browser's back button. Any suggestions? ...