How can I create distinct edges that intersect the surfaces of other objects in THREE.js?

Currently, I'm involved in a three.js project where I need to display all edges of geometries, even when those edges intersect with surfaces of other objects.

Below is the code snippet that showcases my dilemma:

var camera, scene, renderer, material, stats, group, wireframeMaterial;
init();
animate();

function init() {
    // Renderer.
    renderer = new THREE.WebGLRenderer({antialias: true, alpha:true,clearAlpha:0,clearColor: 0xff0000});
    //renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    // Add renderer to page
    document.body.appendChild(renderer.domElement);

    // Create camera.
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 400;

    // Create scene.
    scene = new THREE.Scene();
    group=new THREE.Group()

    // Create material
    material = new THREE.MeshBasicMaterial();

    wireframeMaterial=new THREE.LineBasicMaterial( { color: 0x000000, side:THREE.FrontSide ,transparent:false,opacity:1,linewidth: 1 })

    // Create cube and add to scene.
    var geometry = new THREE.BoxGeometry(200, 200, 200);
    var mesh1 = new THREE.Mesh(geometry, material);
    group.add(mesh1);
    
        
    var geometry2 = new THREE.BoxGeometry(100,100,100);
    var mesh2 = new THREE.Mesh(geometry2, material);
    group.add(mesh2);
    mesh2.position.fromArray([0,150,0])

    
    
    var edges = new THREE.EdgesGeometry( geometry );
    var line = new THREE.LineSegments( edges, wireframeMaterial );
    mesh1.add( line );


    var edges2 = new THREE.EdgesGeometry( geometry2 );
    var line2 = new THREE.LineSegments( edges2, wireframeMaterial );
    mesh2.add( line2 );


   scene.add(group)

    // Add listener for window resize.
    window.addEventListener('resize', onWindowResize, false);
}

function animate() {
    requestAnimationFrame(animate);
    group.rotation.x += 0.005;
    group.rotation.y += 0.01; 
    renderer.render(scene, camera);
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
body {
    padding: 0;
    margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/97/three.min.js"></script>

On the fiddle code, there are two cubes stacked on top of each other. I am aiming to make the bottom edges of the smaller cube visible. One approach is to set the mesh basic material as transparent. However, this method would also reveal edges that are behind the cubes themselves, which is not permissible in the project.

Are there any alternative solutions available to address this issue?

Answer №1

Discovered a helpful solution involving the utilization of the polygonOffset parameters within the basic material.

var material = new THREE.MeshBasicMaterial({
  polygonOffset: true,
  polygonOffsetFactor: 1, // adjusting this value pushes polygons farther away
  polygonOffsetUnits: 1
});

Found this answer while investigating: three.js EdgesHelper showing certain diagonal lines on Collada model

The EdgesGeometry function specifically highlights hard edges.

The WireframeGeometry function showcases all edges.

var camera, scene, renderer, material, stats, group, wireframeMaterial;
init();
animate();

function init() {
    // Setting up Renderer.
    renderer = new THREE.WebGLRenderer({antialias: true, alpha:true,clearAlpha:0,clearColor: 0xff0000});
    //renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    // Placing renderer element onto page
    document.body.appendChild(renderer.domElement);

    // Creating camera.
    camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 400;

    // Establishing scene.
    scene = new THREE.Scene();
    group=new THREE.Group()

    // Configuring materials
    var material = new THREE.MeshBasicMaterial({
      polygonOffset: true,
      polygonOffsetFactor: 1, // adjusting this value pushes polygons farther away
      polygonOffsetUnits: 1
    });
    var wireframeMaterial= new THREE.LineBasicMaterial( { color: 0x000000, linewidth: 2 } );

    // Generating cube and adding it to the scene.
    var geometry = new THREE.BoxGeometry(200, 200, 200);
    var edges = new THREE.EdgesGeometry(geometry);
    var line = new THREE.LineSegments( edges, wireframeMaterial );
    var mesh = new THREE.Mesh(geometry, material);
    group.add(mesh, line);
    
     
    var geometry2 = new THREE.BoxGeometry(100,100,100);
    var wire = new THREE.EdgesGeometry(geometry2);
    var line2 = new THREE.LineSegments( wire, wireframeMaterial );
    var mesh2 = new THREE.Mesh(geometry2, material);
    line2.position.fromArray([0,150,0]);
    mesh2.position.fromArray([0,150,0]);
    group.add(mesh2, line2);
    
        scene.add(group)

    // Adding listener for window resizing.
    window.addEventListener('resize', onWindowResize, false);

    // Displaying stats on the page.
    stats = new Stats();
    document.body.appendChild( stats.dom );
}

function animate() {
    requestAnimationFrame(animate);
    group.rotation.x += 0.005;
    group.rotation.y += 0.01; 
    renderer.render(scene, camera);
    stats.update();
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.140.1/three.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/mrdoob/stats.js/r17/build/stats.min.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

Designing tab navigation in React Native

Is there a specific way to customize only the ORANGE tab's style? I am curious to learn how to address this particular scenario. I have attempted various methods to modify the style of the ORANGE tab. My application utilizes navigation 5. <Tab.Navi ...

Find the second element beneath the mouse cursor that is not a direct ancestor of the first element

I am currently developing a card drag-and-drop board using HTML5 inspired by Trello. My focus right now is on connecting the lists to specific list slots/containers. My challenge lies in determining which list container is positioned beneath the mouse po ...

What is the best way to enforce constraints on three keys when validating an object using Joi?

Currently experimenting with Joi for object validation. Able to validate objects with constraints on two keys using any.when(). Now looking to implement validation with constraints on three keys, for example: var object = { dynamicPrize: false, ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

AngularJS: Issue with Variable Value Rendering

I recently started working with Angular. In my JavaScript file, I have the following code: App.controller('ProductController', ['$scope', 'ProductService', function ($scope, ProductService) { console.clear(); console. ...

Failure to trigger on change event

I am struggling with dynamically generating input fields of the file type. Unfortunately, when I attempt to access its triggered event, nothing seems to happen. Below is the code snippet for the dynamic input file: <div id="documentlist" class="col-lg ...

javascript for transforming date format

My textfield is set to be a date field with a jQuery datepicker(). The dateFormat() is dd-mm-yy, which works perfectly. However, MySQL requires dates to be in yyyy-mm-dd format. I am wondering if I can convert the date format using PHP or JavaScript before ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...

Improved Approach for Replacing if/else Statements

I'm looking to streamline the controller used in my SQL command for filtering records based on specific criteria. The current approach below is functional, but not without its limitations. One major issue is scalability - adding more criteria in the f ...

The absence of multiple lines on the x-axis in the linear chart was noticeable

Currently, I am facing an issue with loading a single axis line chart on my Dashboard.vue. The functionality involves users selecting a 'year' and a 'loan_type' from dropdown menus, after which the chart should display a 12-month record ...

Tips for automatically activating the HTML select menu on an iPad

My website features a suburb lookup tool that allows users to input a suburb or postcode (Australian only, e.g. 4000, 2000, Brisbane, Sydney etc) and receive the corresponding suburb/state/postcode in a select menu format: <select size="4" name="contac ...

Django Website Experiencing Issues with Google Analytics Integration

I implemented google analytics by inserting the tracking script tag and code at the bottom of the head section in my base.html template which serves as the foundation for all other pages. Additionally, I set up 2 click events to track when users click on ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Using npm: Managing Redirects

Does anyone have suggestions on how to manage redirects using the Request npm from websites like bitly, tribal, or Twitter's t.co URLs? For instance, if I need to access a webpage for scraping purposes and the link provided is a shortened URL that wil ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

Have you attempted to configure a JSON file to facilitate language translations?

I need some guidance on structuring my data.json file efficiently. Currently, it is set up as shown in the example below. The goal is to have a drop-down menu where users can select a language and then display 50 different pages with specific content. I wa ...

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...

Encountered a static symbol values resolution error while working with angular 2 npm link. The issue occurred when the function 'makeDecorator' was being called

Whenever I attempt to use "npm link" to consume a different package I created, I encounter an error while running my application. The error message reads as follows: An error occurred while resolving symbol values statically during the invocation of the ...

AJAX Showdown: Comparing jQuery's AJAX API to JavaScript's XHR

tl;dr: I have two different scripts that appear to be identical, but one works while the other does not. Why is this? Let me provide some context for this post. I am working on creating an image uploading form that utilizes AJAX requests to generate a dyn ...

What is the best way to invoke a function in one View Model from within another View Model?

I am looking to divide my DevExtreme Scheduler into two separate view models. One will be responsible for displaying the Scheduler itself, while the other will handle the Popup and button functionality. Despite having everything set up, I am struggling to ...