Three.js - Why is csg.js not working?

2020-04-21 06:33发布

问题:

I tried to use csg.js-functions to cut a sphere out of a box, but it is not working? I read the tutorial on http://learningthreejs.com/blog/2011/12/10/constructive-solid-geometry-with-csg-js/ but its still not working.

<html>
    <head>
        <title>Experiment</title>
    </head>

    <body>
        <script src="three_js\build\three.min.js"></script>
        <script src="ThreeCSG.js"></script> 
        <script src="csg.js"></script>          
        <script type="text/javascript"> 

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

    var renderer = new THREE.WebGLRenderer();

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

    var geometry1 = new THREE.BoxGeometry( 10, 10, 10);
    var material = new THREE.MeshPhongMaterial( {specular: "#fdfb57", color: "#d8d613", emissive: "#6b6a0d", side: THREE.DoubleSide} );
    var box = new THREE.Mesh(geometry1, material);
    var sphere = new THREE.Mesh(new THREE.SphereGeometry(5, 32, 32), material);
    scene.add(box);
    scene.add(sphere);

    var boxCsg = THREE.CSG.toCSG(box);
    var sphereCsg = THREE.CSG.toCSG(sphere);

    boxCsg.substract(sphereCsg);    

    box = THREE.CSG.fromCSG(boxCsg);


    camera.position.z = 50;


    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    directionalLight.position.set( 5, 10, 5 );
    scene.add( directionalLight );

                var render = function () {
                    requestAnimationFrame( render );
                    renderer.render(scene, camera);
                    //Hier wird die Größe des Fensters manipuliert!
                    renderer.setSize(window.innerWidth - 20, window.innerHeight - 20);                  
                };


                render();   

            </script>
        </body>
    </html>

回答1:

The article is outdated, this is the new syntax:

var box = new THREE.Mesh( new THREE.BoxGeometry( 10, 1, 10 ) );
var box_bsp = new ThreeBSP( box );

var cutgeo = new THREE.SphereGeometry( 1, 16, 8 );
var sub = new THREE.Mesh( cutgeo );
var subtract_bsp  = new ThreeBSP( sub );
var result_bsp  = box_bsp.subtract( substract_bsp );

var result = result_bsp.toMesh();
scene.add( result );

Three.js r107: http://jsfiddle.net/r7suq1mv/2/