When large spheres meet, Three.js/WebGL displays them as fractured

I must admit that I am not very experienced with 3D graphics.

Issue

In my WebGL model using Three.js, I have intentionally made two spheres collide. However, when the spheres are extremely large, they appear "broken" at the point of intersection, whereas smaller spheres render correctly.

I have a specific need for using such large units for certain objects, and reducing the scale of these objects is not a viable solution.

Example

Here is a fiddle showing the issue with larger spheres: http://jsfiddle.net/YSX7h/

and another fiddle displaying the behavior with smaller spheres: http://jsfiddle.net/7Lca2/

Code

var radiusUnits = 1790; // 179000000
var container;
var camera, scene, renderer;
var clock = new THREE.Clock();
var cross;
var plane;
var controls;
var cube;
var cubeMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff, vertexColors: THREE.VertexColors } );
init();
animate();

function init() {
    camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 0.1, 3500000);
    controls = new THREE.OrbitControls(camera);
    camera.position.set(2000, 2000, 2000);
    camera.position.z = 500;
    scene = new THREE.Scene();

    var texture = THREE.ImageUtils.loadTexture('http://i.imgur.com/qDAEVoo.jpg');
    var material = new THREE.MeshBasicMaterial({
        color: 0xFFFFFF,
        map: texture,
        opacity:1
    });

    var material1 = new THREE.MeshBasicMaterial({ color: 0xFF0000, wireframe: true, opacity:1 });
    var geometry = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var geometry1 = new THREE.SphereGeometry(radiusUnits, 32, 32);
    var mesh = new THREE.Mesh(geometry, material);
    var mesh1 = new THREE.Mesh(geometry1, material1);
    mesh1.position.set(0, 1000, 0);
    mesh.position.set(0, -1000, 0);

    scene.add(mesh);
    scene.add(mesh1);

    renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );

    document.body.appendChild(renderer.domElement);
    renderer.setSize( window.innerWidth, window.innerHeight );
}

function onWindowResize() {
    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
}

function animate() {
    controls.update();
    requestAnimationFrame( animate );
}

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

(function animloop(){
    requestAnimFrame(animloop);
    render();
})();

function render() {
    var delta = clock.getDelta(); 
    renderer.render( scene, camera );
}

Why does this occur exactly? And what steps can I take to address this issue without resizing the objects?

Thank you in advance.

Answer №1

To improve rendering quality, adjust your z near plane further away

Update

camera = new THREE.PerspectiveCamera(
    100, window.innerWidth / window.innerHeight, 0.1, 3500000);

to

var zNear = 1000;
var zFar = 3500000;
camera = new THREE.PerspectiveCamera(
    100, window.innerWidth / window.innerHeight, zNear, zFar);

Please note: Trying a value of 1000 might not be effective, consider using 10000 if needed.

The zBuffer, necessary for determining pixel depth in WebGL rendering, has limited resolution depending on the number of bits used (commonly 16, 24, or 32). For demonstration purposes, let's assume just 4 bits are available. This results in only 16 possible values within a given z range when set between zNear = 0.1 and zFar = 3500000:

0 = 0.100
1 = 0.107         range: 0.007
2 = 0.115         range: 0.008
3 = 0.125         range: 0.010
4 = 0.136         range: 0.011
5 = 0.150         range: 0.014
6 = 0.167         range: 0.017
7 = 0.187         range: 0.021
8 = 0.214         range: 0.027
9 = 0.250         range: 0.036
10 = 0.300        range: 0.050
11 = 0.375        range: 0.075
12 = 0.500        range: 0.125
13 = 0.750        range: 0.250
14 = 1.500        range: 0.750
15 = 3499999.993  range: 3499998.493 

This demonstrates the significant increase in distance between values as objects move farther from the camera, resulting in loss of precision. By adjusting zNear to 1000, the ranges become:

0 = 1000.000
1 = 1071.407       range: 71.407
2 = 1153.795       range: 82.389
3 = 1249.911       range: 96.115
4 = 1363.495       range: 113.584
5 = 1499.786       range: 136.291
6 = 1666.349       range: 166.564
7 = 1874.531       range: 208.182
8 = 2142.158       range: 267.626
9 = 2498.929       range: 356.771
10 = 2998.287      range: 499.358
11 = 3747.056      range: 748.769
12 = 4994.292      range: 1247.236
13 = 7486.097      range: 2491.805
14 = 14940.239     range: 7454.142
15 = 3500000.000   range: 3485059.761 

This shows an improvement in range distribution at greater distances. When utilizing a 24-bit depth buffer with zNear = 0.1 and zFar = 3500000, the differences between the last 15 units are:

16777201 = 115869.957       range: 7485.454
16777202 = 124466.066       range: 8596.109
16777203 = 134439.829       range: 9973.763
16777204 = 146151.280       range: 11711.451
16777205 = 160097.879       range: 13946.599
16777206 = 176987.000       range: 16889.122
16777207 = 197859.711       range: 20872.711
16777208 = 224313.847       range: 26454.135
16777209 = 258933.659       range: 34619.812
16777210 = 306189.940       range: 47256.281
16777211 = 374545.842       range: 68355.902
16777212 = 482194.095       range: 107648.253
16777213 = 676678.248       range: 194484.154
16777214 = 1134094.478       range: 457416.229
16777215 = 3499999.993       range: 2365905.515

Contrast this with having zNear = 1000:

16777201 = 3489810.475       range: 725.553
16777202 = 3490536.330       range: 725.855
16777203 = 3491262.487       range: 726.157
16777204 = 3491988.947       range: 726.459
16777205 = 3492715.709       range: 726.762
16777206 = 3493442.773       range: 727.064
16777207 = 3494170.140       range: 727.367
16777208 = 3494897.810       range: 727.670
16777209 = 3495625.784       range: 727.973
16777210 = 3496354.060       range: 728.277
16777211 = 3497082.640       range: 728.580
16777212 = 3497811.524       range: 728.884
16777213 = 3498540.712       range: 729.188
16777214 = 3499270.204       range: 729.492
16777215 = 3500000.000       range: 729.796

This adjustment offers more reasonable distribution, ensuring accurate sorting of points even at a sizeable distance from the camera.

In conclusion, setting appropriate clipping planes is crucial for optimal rendering in your specific scenario.

It's worth mentioning that while standard math is typically applied, custom vertex shaders in three.js can modify zbuffer behavior. Check out this article for further insights.

Answer №2

Your issue lies in the precision of the depth buffer. The larger the scale of your scene, the more noticeable this problem becomes - especially with objects that cover a wide distance. The depth buffer is limited to only 32 bits (as far as I know, it uses floating point). As you expand the Z-Range of your camera, the precision decreases. Typically, a standard camera has higher precision near the "near" plane and lower precision towards the distance (although I am unsure of the specific matrix used by three.js).

To address this, you can either reduce the size of your scene or adjust the near plane further from the camera. Researching depth buffers and precision will provide extensive information on this issue. It might be helpful to refer to general OpenGL resources, not just those specific to three.js or WebGL.

It's worth noting that the reason for the discrepancy between the two scenes is likely due to differences in the camera settings. Adjusting the near plane to "0.00001" in the working scene should highlight the same issue.

Answer №3

Another option to experiment with is utilizing a logarithmic depth buffer:

By setting the renderer parameter as { logarithmicDepthBuffer: true }, you can enable this feature in THREE.WebGLRenderer.

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

Retrieve data from the controller of the selected element on the subsequent page using AngularJS

Currently, I am in the process of developing an ecommerce platform using angularjs. In my controller, I have a list of various products structured like this: $scope.products = [ {imgLink: 'product1.jpg', name: 'Wingtip Cognac Oxford&apo ...

AngularJS form submission with Ajax requiring a double click to successfully submit the form

I need to perform the following activities on my HTML page: User inputs email and password for registration Form is sent to Controller when user clicks Submit Controller uses AJAX to create JSON request to RESTful Server and receives response from server ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

The duration for which an API Access Token remains valid is extremely brief

I recently started working with APIs and my current project involves using the Petfinder API v2 to develop a website that allows users to search for adoptable animals. The API utilizes OAuth, requiring a key and secret to obtain a token via CURL. However, ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

Surprise mistake: Jade's error with the length

What can I do to address this problem? The jade file in question is as follows: extends layout block content h1. User List ul each user, i in userlist li a(href="mailto:#{user.email}")= user.username U ...

Collaborating and passing on a MongoDB connection to different JavaScript files

I am currently working with Node.js/Express.js/Monk.js and attempting to share my MongoDB connection across multiple JS files. Within apps.js, I have set up the following: var mongo = require('mongodb'); var monk = require('monk'); va ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

running into an issue while attempting to utilize socket.io

Currently, I am utilising the socket.io swift client on my Iphone SE. Below is the swift code snippet: let socket = SocketIOClient(socketURL: URL(string: "http://example.com:4000")!, config: [.log(true), .forcePolling(true)]); socket.connect(); ...

Navigating through certain JSON information in AngularJS

I am facing a challenge with handling article information stored in a json file, where each article has a unique id. The format of the json data is as follows: [{"title":"ISIS No. 2 killed in US special ops raid", "id":"14589192090024090", ...

Fill a JavaScript array with values inserted in the middle position

I'm having trouble populating an array: var arr2 = ["x", "y", "z"]; I want to insert a random number/value between each original value using a for loop, like this: for (let i = 1; i < arr2.length; i+2) { arr2.splice(i, 0, Math.random()); } B ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Is there a way to use jQuery to animate scrolling on a mobile web browser?

I'm trying to make the page scroll to a specific position when a button is clicked. The code I currently have works fine on browsers like Chrome and IE, but doesn't seem to work on any mobile browser. Below is the code snippet I am using: $("#p ...

Tips for resolving the "unsafe-eval" issue in Vue3 on the client-side platform

My app is built using Express, cors, and helmet. I have incorporated Vue3 on the client-side only, with the library file being self-hosted in the public folder. To add the module to the client-side, I simply include the following script: <script type=&q ...

Implementing additional input with Jquery causes tooltips to malfunction

I am developing a form that allows users to add as many rows as needed. Each input is being treated as an array for easy data storage in the database, which is a new concept for me. $(document).ready(function() { var maxField = 10; //Limitati ...

Tips on aligning three divs horizontally within a container while maintaining a height of 100%

UPDATE: The alignment has been corrected by adding floats. However, the height still doesn't fill 100%. Check out the new look: Image Link In my footer container, I want to arrange 3 columns (colored green, white, and red for clarity). Currently, the ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

If there are multiple Monaco diff editors present on a single page, only the first instance will display the diff

I'm currently working with a Vue component that renders a diff editor using Monaco. However, when I have more than one instance of this component on the same page, only the first one displays the diff highlights. Here is the template: <template> ...