BufferGeometry-based Three.js mesh fails to display

Currently, I am in the process of developing a WebGL game using Three.js. In order to enhance performance, I have made the decision to transition from using THREE.Geometry to utilizing THREE.BufferGeometry. However, after making this change, I encountered an issue where the mesh is not rendering as expected. Below, I have included the relevant portions of my code for reference. Interestingly, when reverting back to a regular geometry setup, everything works perfectly.

The game I'm working on is voxel-based, where each face of every cube has been pre-created as a standard THREE.Geometry. The function positionVertices is responsible for taking the vertices and faces from each face geometry, positioning them accordingly to correspond with the voxel, and then generating the buffer data required for the THREE.BufferGeometry. Although there are no error messages or warnings displayed, the final mesh fails to display. It seems probable that the issue stems more from my limited knowledge in 3D graphics programming rather than a fault within Three.js itself. At this point, my assumption is that the problem might be related to incorrect indexes. Removing the indexes reveals the object, but half of the triangles have their normals facing in the opposite direction.

Chunk.prototype.positionVertices = function( position, vertices, faces, vertexBuffer, indexBuffer, normalBuffer, colorBuffer ) {
    var vertexOffset = vertexBuffer.length / 3;
    for( var i = 0; i < faces.length; ++i ) {
        indexBuffer.push( faces[i].a + vertexOffset );
        indexBuffer.push( faces[i].b + vertexOffset );
        indexBuffer.push( faces[i].c + vertexOffset );

        normalBuffer.push( faces[i].vertexNormals[0].x );
        normalBuffer.push( faces[i].vertexNormals[0].y );
        normalBuffer.push( faces[i].vertexNormals[0].z );

        normalBuffer.push( faces[i].vertexNormals[1].x );
        normalBuffer.push( faces[i].vertexNormals[1].y );
        normalBuffer.push( faces[i].vertexNormals[1].z );

        normalBuffer.push( faces[i].vertexNormals[2].x );
        normalBuffer.push( faces[i].vertexNormals[2].y );
        normalBuffer.push( faces[i].vertexNormals[2].z );
    }

    var color = new THREE.Color();
    color.setRGB( 0, 0, 1 );
    for( var i = 0; i < vertices.length; ++i ) {
        vertexBuffer.push( vertices[i].x + position.x );
        vertexBuffer.push( vertices[i].y + position.y );
        vertexBuffer.push( vertices[i].z + position.z );

        colorBuffer.push( color.r );
        colorBuffer.push( color.g );
        colorBuffer.push( color.b );
    }
};

// This will need to change when more than one type of block exists.
Chunk.prototype.buildMesh = function() {

    var cube = new THREE.Mesh();
    var vertexBuffer = []; // [0] = v.x, [1] = v.y, etc
    var faceBuffer = [];
    var normalBuffer = [];
    var colorBuffer = [];
    for( var k = 0; k < this.size; ++k )
    for( var j = 0; j < this.size; ++j )
    for( var i = 0; i < this.size; ++i ) {
        // Iterates over all of the voxels in this chunk and calls
        // positionVertices( position, vertices, faces, vertexBuffer, indexBuffer, normalBuffer, colorBuffer ) for each face in the chunk
    }

    var bGeo = new THREE.BufferGeometry();

    bGeo.attributes = {

        index: {
            itemSize: 1,
            array: new Uint16Array( faceBuffer ),
            numItems: faceBuffer.length
        },
        position: {
            itemSize: 3,
            array: new Float32Array( vertexBuffer ),
            numItems: vertexBuffer.length
        },
        normal: {
            itemSize: 3,
            array: new Float32Array( normalBuffer ),
            numItems: normalBuffer.length
        },
        color: {
            itemSize: 3,
            array: new Float32Array( colorBuffer ),
            numItems: colorBuffer.length
        }
    }


    var mesh = new THREE.Mesh( bGeo, VOXEL_MATERIALS["ROCK"]);

    return mesh;
}

Answer №1

I was in need of adjusting a single offset on the geometry.

    bGeo.offsets = [
        {
            start: 0,
            index: 0,
            count: faceBuffer.length
        }
    ];

Issue resolved. Despite that, the triangles are showing incorrectly, indicating potential issues with the faces. Nonetheless, I am confident I can address them without much difficulty.

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

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

How can I maintain the selected state of checkbox and radio button in ReactJS after page refresh?

I am facing an issue with my multistep form that contains radio buttons and checkboxes from material UI. Although the data is stored correctly in state and local storage, when I move to the next page and then return, the selections appear unselected to the ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

Creating a 3D visualization with three.js

My project requires me to create a 3D scatter graph using three.js. I have attempted to implement the code provided below. While the code is functional, the resulting graph appears more like a 2D representation. Adjusting the camera position can add depth ...

Is there a way to modify the starting position of my shapes in Three.js?

Is there a way to adjust the starting position of my geometry? Currently, it appears in the center of the canvas, but I would prefer it to be at the top left corner. Any suggestions on how to achieve this? scene = new THREE.Scene(); camera = new THRE ...

An Illustration of Basic Nested Controller within Directive Parameters

Check out this code snippet app.directive('hello', function() { return { restrict: "E", templateUrl: "/Angular/Modules/Selector.html", controller: function () { this.message = [enter the attribute message he ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

Email notification will be sent upon form submission to Firestore

I'm currently designing a website for booking reservations through an HTML form, with data submission to firestore. Upon submission, a confirmation email is sent to the customer. Below is the code snippet I am using to achieve this: var firestore = fi ...

Creating separate versions (development and production) of JavaScript code: a step-by-step guide

I have been working on a small web application that is distributed in a Docker container, using an nginx image. This application consists of plain html and js code, without any frameworks. Within the JS code, there is access to a remote host via WebSocket ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

OpenStreetMap is failing to display the full map within the designated div

Here is the code snippet for displaying a map when clicking on a Span text, but not showing it in full: var latitude = document.querySelector('#lati').value; var longitude = document.querySelector('#longi').value; var open_address = doc ...

JavaScript causes the browser to freeze

When I execute this code, the browser freezes and I'm not sure how to troubleshoot it, can you assist? http://jsfiddle.net/z3DjY/1/ var levelArray = new Array(); var canvas; var ctx; var playerLocation; var edge; var elementEdge = 10; // Each elemen ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...

JSON - The challenge of incorporating single quotes within double quotes

In my current scenario, I am using the following code to populate form fields. The code is designed to handle a JSON dataset that has been encoded with PHP's json_encode function. Everything works smoothly when dealing with either single or double qu ...

Unable to cut a line shape in Three.js using THREE.ExtrudeGeometry for punching

Hey everyone, I'm brand new to Three.js I'm looking to cut out some shapes from a flat board using THREE.ExtrudeGeometry. Check out the code snippet below: // Code snippet here... In my example, I've included a circular shape and t ...

Steps to showcase a form on a webpage using a button

My webpage features an HTML table with a table navigation bar that allows users to add items or inventory. However, when the "add item" button is clicked, a form appears below the table instead of on top of it. I want the form to display itself right on to ...

Is there a way for me to confirm that I am receiving the 401 error when fetching data?

When using an async function to fetch data, how can one determine if a 401 error occurred during the data retrieval process? The code example is as follows: async function getBilling(url, id, date) { let header = { method: 'GE ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...