In the world of three js, we are presented with two distinct scenes featuring CubeGeometry and PointsGeometry. However

I've been trying to generate a cube and some dots that are part of a torus using the code below. However, I can only see the cube and not the dots. Despite spending hours searching for the dots, they remain elusive.

 // Generating a cube
        cube = new THREE.Mesh(
            new THREE.CubeGeometry(50, 50, 50),
            new THREE.MeshNormalMaterial({ wireframe: true }));

// Creating a mesh of the torus
        function TorusMesh(R, r, nx, ny) {
            var vertices = new Array(nx);
            var normals = new Array(nx);
            for (var i = 0; i < nx; i++) {
                vertices[i] = new Array(ny);
                normals[i] = new Array(ny);
                var u = i / nx * 2 * Math.PI;
                var cos_u = Math.cos(u);
                var sin_u = Math.sin(u);
                var cx = R * cos_u;
                var cy = R * sin_u;
                for (var j = 0; j < ny; j++) {
                    var v = j / ny * 2 * Math.PI;
                    var rcos_v = r * Math.cos(v);
                    var rsin_v = r * Math.sin(v);
                    vertices[i][j] = new THREE.Vector3(
                        cx + rcos_v * cos_u,
                        cy + rcos_v * sin_u,
                        rsin_v
                    );
                    normals[i][j] = new THREE.Vector3(
                        rcos_v * cos_u,
                        rcos_v * sin_u,
                        rsin_v
                    );
                }
            }

            var faces = Array(4);
            faces[0] = Array(2 * nx * ny);
            faces[1] = Array(2 * nx * ny);
            for (var i = 0; i < nx; i++) {
                var ip1 = (i == nx - 1 ? 0 : i + 1);
                for (var j = 0; j < ny; j++) {
                    var jp1 = (j == ny - 1 ? 0 : j + 1);
                    faces[0] = [
                        ip1 * ny + j,
                        i * ny + j,
                        i * ny + jp1,
                        [normals[ip1][j], normals[i][j], normals[i][jp1]]
                    ];
                    faces[1] = [
                        ip1 * ny + j,
                        i * ny + jp1,
                        ip1 * ny + jp1,
                        [normals[ip1][j], normals[i][jp1], normals[ip1][jp1]]
                    ];
                    var Pair = [faces[0], faces[1]];
                }
            }

            return {
                vertices: vertices,
                normals: normals
                //faces: TODO
            }
        }
 
 // Representing the vertices as a cloud of dots
        var dotGeometry = new THREE.Geometry();
        var vertices = TorusMesh(10, 3, 16, 8).vertices;
        for (var j = 0; j < 8; j++) {
            for (var i = 0; i < 15; i++) {
                dotGeometry[j * 15 + i] = vertices[i][j]
            }
        }
        var dotMaterial =
            new THREE.PointsMaterial({
                size: 5,
                sizeAttenuation: false,
                color: 0x000000
            });
        cloud = new THREE.Points(dotGeometry, dotMaterial);
        console.log(cloud);

 // Setting up the three js scene
        var aspect = window.innerWidth / window.innerHeight;
        var camera = new THREE.PerspectiveCamera(150, aspect, 1, 10000);
        var scene = new THREE.Scene();
        camera.position.set(0, 0, 20);
        scene.add(camera);

 // Controls with dat.gui -------------------------------------------------
        var dgcontrols = new function () {
            this.rotationSpeed = 0.001;
            this.zoom = 20;
        }
        var gui = new dat.GUI({ autoplace: false, width: 350 });
        gui.add(dgcontrols, 'rotationSpeed').min(0).max(0.005).name("Rotation speed");
        var controller_zoom = gui.add(dgcontrols, 'zoom').min(1).max(3000);
        controller_zoom.onFinishChange(function (value) {
            camera.position.z = value;
        });

        // Defining the render() function
        var renderer = new THREE.WebGLRenderer();
        function render() {
            renderer.render(scene, camera);
            object.rotation.x += dgcontrols.rotationSpeed;
            object.rotation.y += dgcontrols.rotationSpeed;
            requestAnimFrame(render);
        }
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        window.requestAnimFrame = (function () {
            return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
        })();

        // Adding objects to the scene
        var object = new THREE.Object3D();
        scene.add(cloud);
        scene.add(cube);

        render()
        requestAnimFrame(render);
 
canvas {
            width: 100%;
            height: 100%
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.3/dat.gui.js"></script>

Answer №1

The issue arose when vertices were assigned directly to the geometry object instead of using dotGeometry.vertices. By changing the color of the points to white, you will be able to see the points rendered correctly.

To view your updated code, check out this fiddle: https://jsfiddle.net/f2Lommf5/15833/

// creating a cube
        cube = new THREE.Mesh(
            new THREE.CubeGeometry(50, 50, 50),
            new THREE.MeshNormalMaterial({ wireframe: true }));

// defining the torus mesh
        function TorusMesh(R, r, nx, ny) {
            var vertices = new Array(nx);
            var normals = new Array(nx);
            for (var i = 0; i < nx; i++) {
                vertices[i] = new Array(ny);
                normals[i] = new Array(ny);
                var u = i / nx * 2 * Math.PI;
                var cos_u = Math.cos(u);
                var sin_u = Math.sin(u);
                var cx = R * cos_u;
                var cy = R * sin_u;
                for (var j = 0; j < ny; j++) {
                    var v = j / ny * 2 * Math.PI;
                    var rcos_v = r * Math.cos(v);
                    var rsin_v = r * Math.sin(v);
                    vertices[i][j] = new THREE.Vector3(
                        cx + rcos_v * cos_u,
                        cy + rcos_v * sin_u,
                        rsin_v
                    );
                    normals[i][j] = new THREE.Vector3(
                        rcos_v * cos_u,
                        rcos_v * sin_u,
                        rsin_v
                    );
                }
            }

            var faces = Array(4);
            faces[0] = Array(2 * nx * ny);
            faces[1] = Array(2 * nx * ny);
            for (var i = 0; i < nx; i++) {
                var ip1 = (i == nx - 1 ? 0 : i + 1);
                for (var j = 0; j < ny; j++) {
                    var jp1 = (j == ny - 1 ? 0 : j + 1);
                    faces[0] = [
                        ip1 * ny + j,
                        i * ny + j,
                        i * ny + jp1,
                        [normals[ip1][j], normals[i][j], normals[i][jp1]]
                    ];
                    faces[1] = [
                        ip1 * ny + j,
                        i * ny + jp1,
                        ip1 * ny + jp1,
                        [normals[ip1][j], normals[i][jp1], normals[ip1][jp1]]
                    ];
                    var Pair = [faces[0], faces[1]];
                }
            }

            return {
                vertices: vertices,
                normals: normals
                //faces: TODO
            }
        }

// rendering vertices as a cloud of dots
        var dotGeometry = new THREE.Geometry();
        var vertices = TorusMesh(10, 3, 16, 8).vertices;
        for (var j = 0; j < 8; j++) {
            for (var i = 0; i < 15; i++) {
                dotGeometry.vertices[j * 15 + i] = vertices[i][j]
            }
        }
        var dotMaterial =
            new THREE.PointsMaterial({
                size: 5,
                sizeAttenuation: false,
                color: 0xffffff
            });
        cloud = new THREE.Points(dotGeometry, dotMaterial);

// setting up three js scene
        var aspect = window.innerWidth / window.innerHeight;
        var camera = new THREE.PerspectiveCamera(150, aspect, 1, 10000);
        var scene = new THREE.Scene();
        camera.position.set(0, 0, 20);
        scene.add(camera);

// controls using dat.gui -------------------------------------------------
        var dgcontrols = new function () {
            this.rotationSpeed = 0.001;
            this.zoom = 20;
        }
        var gui = new dat.GUI({ autoplace: false, width: 350 });
        gui.add(dgcontrols, 'rotationSpeed').min(0).max(0.005).name("Rotation speed");
        var controller_zoom = gui.add(dgcontrols, 'zoom').min(1).max(3000);
        controller_zoom.onFinishChange(function (value) {
            camera.position.z = value;
        });

        // define the render() function
        var renderer = new THREE.WebGLRenderer();
        function render() {
            renderer.render(scene, camera);
            object.rotation.x += dgcontrols.rotationSpeed;
            object.rotation.y += dgcontrols.rotationSpeed;
            requestAnimFrame(render);
        }
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        window.requestAnimFrame = (function () {
            return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
        })();

        // add objects to the scene
        var object = new THREE.Object3D();
        scene.add(cloud);
        scene.add(cube);

        render()
        requestAnimFrame(render);
 
canvas {
            width: 100%;
            height: 100%
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://threejs.org/build/three.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.3/dat.gui.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

Create a three-dimensional tree array in Typescript/Javascript by transforming a flat array

Received data is structured as follows: const worldMap = [ { "name": "Germany", "parentId": null, "type": "Country", "value": "country:unique:key:1234", "id&qu ...

Issues encountered while converting scss to css with gulp

I've been attempting to convert SCSS to CSS, and here's the code I've been working with. const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function() { return gulp.src(&apos ...

JavaScript form validation problem: Warning for identical responses in the MOST and LEAST sections

I've encountered a challenge while working on an HTML and JavaScript form for a personality test. The issue revolves around validation, particularly when the form includes multiple questions with both "MOST" and "LEAST" radio button options. One spec ...

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

Storing form data in temporary local storage using a JSON object array within a PhoneGap project

I am currently developing a data acquisition system using PhoneGap and facing an issue with storing form data temporarily on local storage using JSON. The data should remain visible even after closing and reopening the application by pressing the Get Data ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

Exploring the magic of Hover effects using CSS and JQuery

I am exploring ways to enhance the display of an element when hovering over it. I have implemented a button and my objective is for the first click to activate the hover effect, while the second click will reset it. However, I am facing an issue where the ...

I'm feeling a bit lost trying to figure out how to write insert statements using knex

I'm struggling with a specific issue related to the Knex.JS implementation that I just can't seem to figure out. It's not directly related to PostgreSQL, but more about how Knex is handling my data. The code snippet below works fine for ins ...

Validating an object's schema using AJV when there are unknown properties present

Within my platform, there is an amusing scenario that I find to be the most effective. I am currently attempting to validate a JSON Schema where an object contains unknown keys with a consistent schema as their values. Each key represents a unique ID and h ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...

Step-by-step guide to configuring preact-render-to-string with Express

Could someone guide me through setting up preact-render-to-string with express? Detailed instructions are here Installation for express can be found here I've gone through the provided links, but I'm unfamiliar with using node. I'm struggl ...

Is there a way to create dynamic documents in Firestore using Angular?

How can I use a dynamic ID to fetch the values of a document in Firestore? For example, if I have documents named document1 and document2 under the same collection, how can I specify a dynamic path with a dynamic document name to retrieve the specific do ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

No matter what, the statement will always be false when this has the class 'has-success'

i am a beginner in jquery and i am looking to implement form validation in asp.net mvc. Currently, the validation is working for each field individually, but I want to disable the submit button until certain fields are correctly filled out. Even after fill ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Safari was unable to load the webpage due to a lack of response from the server

One of the pages on my ASP.NET website is experiencing slow loading times. While it works fine on all Android and MAC operating systems, as well as on iOS versions except for 10.0.0.2 with Safari browser. When attempting to load the page on Safari in ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

Initiate automatic submission

After receiving some valuable assistance from users on stackoverflow, I've successfully implemented the following code. However, I've now realized that it needs to be triggered when the page loads instead of on a trigger. Since I am new to client ...

JavaScript code that activates several hovering elements

I am a beginner in the world of JavaScript and I'm attempting to create a simple function that will activate multiple div hover effects. I have tried various approaches so far, but I believe this code is closer to the solution. Any assistance from som ...