Creating a grid in both 2D and 3D using BufferGeometry in three.js

In my BufferGeometry, I have points arranged in a 1D/2D/3D grid that are dynamically mapped to higher dimensions. The goal is for these vertices to align properly with their neighboring points, as seen in a visualization of a self-organizing map.

I am looking to draw connections between these vertices, similar to the example shown above. While achieving this for 1D is simple with new Line(myBufferGeometry), how can this be done efficiently for 2D and 3D grids? Do I need to create and update separate geometries, such as multiple LineSegments? Is there a more efficient solution or any clever tricks using the index property?

Answer №1

My breakthrough came when I stumbled upon a valuable insight from the comment left by user849. The documentation didn't explicitly cover this, but it's tucked away in some examples - the index property plays a crucial role here. Essentially, when using a GeometryBuffer with the LineSegments feature and defining the index property, the lines are formed based on pairs of indices rather than pairs of points from the position attribute.

For those looking to work with an n x n x n cube, here's a comprehensive solution:

let nn = n * n;
let nnn = n * n * n;

function mapTo3D(index) {
    let x = index % n;
    let y = Math.floor(index / n) % n;
    let z = Math.floor(index / nn);
    return { x: x, y: y, z: z };
}

function mapFrom3D(x, y, z) {
    return x + y * n + z * nn;
}

// Add nnn points to the position attribute of your myGeometryBuffer...

let indices3D = [];
for (let i = 0; i < nnn; i++) {
    var p = mapTo3D(i);
    if (p.x + 1 < n) {
        indices3D.push(i);
        indices3D.push(mapFrom3D(p.x + 1, p.y, p.z));
    }
    if (p.y + 1 < n) {
        indices3D.push(i);
        indices3D.push(mapFrom3D(p.x, p.y + 1, p.z));
    }
    if (p.z + 1 < n) {
        indices3D.push(i);
        indices3D.push(mapFrom3D(p.x, p.y, p.z + 1));
    }
}

myBufferGeometry.setIndex(indices3D);
let lines = new THREE.LineSegments(myBufferGeometry);

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

Combining various objects within an array using JavaScript

Can someone help me with merging objects in an array by their key? I've tried a few solutions but haven't been able to fix it. Here is how my array looks: [0:{PersonIds: "6",TypeIds: "2",VekilIds: "6"},1:{PersonIds: ...

Swap out the old nested array for a fresh array

Currently, I am dealing with an array nested inside another array. The structure looks like this: Structure: First Array [ { Second Array [ { } ] } ] I am attempting to replace all instances of Second Array with a new array that I have cr ...

The event fails to propagate up to the parent component

I have a project structure set up as follows: https://i.stack.imgur.com/bvmK5.jpg The todo-form component triggers the created event and I am looking to handle this event in the todos component. todo-form.component.html: <form class="todo-form" ( ...

Dispense CSS using a React element

My React component index.js contains styling in style.css. I am looking to share this component on npm, but I am unsure of how to simplify the process for other developers to use the styling. After exploring different options, I have come across three ap ...

Export individual mesh via the threejs exporter in the Blender console

I am currently working with Blender 2.76b and the threejs exporter v1.5.0. My objective is to export each individual mesh within the Blender scene. I have observed that when a single mesh is selected, the io_three exports only that specific mesh. In an att ...

Three.js reverts a 3D object back to its initial position, rotation, and geometry prior to any transformations

Is there a way to revert a 3D object (like a cube) back to its original state after making transformations? For instance, if I: Create a BufferGeometry mesh with specific position and rotation Apply various changes to it, such as rotating or moving it Th ...

What prevents a click event from reaching the <body> element?

This slider runs in an animation loop until one of the dots at the top is clicked. Once clicked, the animated elements (the <span> dots and the <figure>s) receive a style that halts the animation. <section id="slider"> <span class ...

Using PHP to query the database and render text and links in the menu

On my website, users currently choose an "event" from a dropdown menu that is populated from a database (Check out the code below). Once a user selects an event from the menu, I want to display text links or a second dropdown menu with the "locations" ass ...

JavaScript fails to load updated data that was most recently submitted

My recent query was regarding Javascript Form Submition. I am currently investigating why, after submitting the form, the create.js.erb file does not load the most recent data that was submitted. On submitting the data again, the table updates with the se ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

Elements in list appear to break apart when resizing

I had previously posted about this issue, but I deleted it after making some progress. I am currently facing a problem with my todo list project when resizing the screen. My project involves using JavaScript to create a new list item for each entry. Users ...

The onfocus event in Chrome's JavaScript add-on fails to trigger

A few months back, I encountered an issue where onFocus events added using JavaScript were not firing only in Chrome (my version Version 103.0.5060.114 (Official Build) (x86_64) OSX 12.4). Interestingly, they worked fine in iOS Chrome, other browsers, an ...

When attempting to use getElementsByClassName in Selenium, the js.executeScript function does not function as expected

Here is a method I have written: public void delayToCapture(String methodGetBy, String key){ /* List of methodGetBy: * 1. getElementById * 2. getElementsByTagName * 3. getElementsByClassName * 4. querySelectorAll */ Syste ...

When the initial page is loaded, Jquery is successfully loaded. However, when the page is reloaded within an

Upon the initial page load, all content displays correctly. However, when attempting to reload a specific section of the page using Ajax to refresh the content, there seems to be an issue with Jquery not fully loading. Could this be due to the fact that J ...

If I were to utilize my own Threejs canvas,Rephrased

Currently, I'm facing an issue while trying to showcase a globe using Three.js. Everything works perfectly until I attempt to use my own canvas. It seems that when I place my canvas before the JavaScript file in the HTML structure, it doesn't dis ...

Please upload JSON data into a database using Node.js

As a beginner in learning node.js, I have embarked on my "Hello World!" project. The premise is simple - I am requesting a JSON file from the server via an API and receiving a response that looks like this: { "files": [{ "url": "http://auction ...

Ways to extract additional information beyond just the 'Webpack Compilation Error' while using Cypress

Every time an error occurs in one of my imported modules, Cypress only provides the vague message Error: Webpack Compilation Error. It's frustrating not to have a useful error stack to troubleshoot the issue. Is there a way to access more detailed err ...

Content Security Policy: The website's security measures prevented a resource from being loaded

Recently, I added the Google Sign-In button to my ReactJS web client. However, I encountered an issue where after a successful sign-in, the page did not redirect back from "https://accounts.google.com/..." to my web-client URL, which is http://localhost:50 ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...