68 Three.js import OBJ format and MTL format

brief introduction

OBJ and MTL are two complementary formats, often used together. OBJ files define geometry, while MTL files define the materials used. Both OBJ and MTL are text-based formats.
Three.js can well understand OBJ files and MTL files, and Blender also supports these two file formats. So as an alternative, you can also choose OBJ/MTL files in Blender instead of JSON files in three.js. Two different loaders are provided in three.js. If you only want to load geometry, you can use OBJLoader.

Using OBJ and MTL cases together

Case view address: http://www.wjceo.com/blog/threejs/2018-03-19/128.html

  • First, introduce the plug-in:
<script src="/lib/js/loaders/OBJLoader.js"></script>
<script src="/lib/js/loaders/MTLLoader.js"></script>
  • Then, first we instantiate the THREE.MTLLoader object and load the texture in
        var mtlLoader = new THREE.MTLLoader();
        mtlLoader.setPath('/lib/assets/models/');
        //Load mtl file
        mtlLoader.load('butterfly.mtl', function (material) {
            . . . 
        });
  • Then we instantiate the THREE.OBJLoader object, set the object texture to the texture generated by the imported MTL file, load the OBJ file, and finally import it into the scene.
            var objLoader = new THREE.OBJLoader();
            //Set currently loaded texture
            objLoader.setMaterials(material);
            objLoader.setPath('/lib/assets/models/');
            objLoader.load('butterfly.obj', function (object) {
                //Scale and add the model to the scene
                scene.add(object);
            })

Case code



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        html, body {
            margin: 0;
            height: 100%;
        }

        canvas {
            display: block;
        }

    </style>
</head>
<body onload="draw();">

</body>
<script src="/lib/three.js"></script>
<script src="/lib/js/loaders/OBJLoader.js"></script>
<script src="/lib/js/loaders/MTLLoader.js"></script>
<script src="/lib/js/controls/OrbitControls.js"></script>
<script src="/lib/js/libs/stats.min.js"></script>
<script src="/lib/js/libs/dat.gui.min.js"></script>

<script>
    var renderer;
    function initRender() {
        renderer = new THREE.WebGLRenderer({antialias:true});
        renderer.setSize(window.innerWidth, window.innerHeight);
        //Tell the renderer you need shadow effects
        renderer.setClearColor(0xffffff);
        document.body.appendChild(renderer.domElement);
    }

    var camera;
    function initCamera() {
        camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
        camera.position.set(0, 40, 50);
        camera.lookAt(new THREE.Vector3(0,0,0));
    }

    var scene;
    function initScene() {
        scene = new THREE.Scene();
    }

    //Initialize dat.GUI to simplify the test process
    var gui;
    function initGui() {
        //Declare an object to save the relevant data of the requirement modification
        gui = {
        };
        var datGui = new dat.GUI();
        //Add the setting attribute to the GUI, gui.add (object, attribute, min, max)
    }

    var light;
    function initLight() {
        scene.add(new THREE.AmbientLight(0x444444));

        light = new THREE.PointLight(0xffffff);
        light.position.set(0,50,0);

        //Tell directional light to turn on shadow casting
        light.castShadow = true;

        scene.add(light);
    }

    function initModel() {

        //Auxiliary tools
        var helper = new THREE.AxesHelper(50);
        scene.add(helper);

        var mtlLoader = new THREE.MTLLoader();
        mtlLoader.setPath('/lib/assets/models/');
        //Load mtl file
        mtlLoader.load('butterfly.mtl', function (material) {
            var objLoader = new THREE.OBJLoader();
            //Set currently loaded texture
            objLoader.setMaterials(material);
            objLoader.setPath('/lib/assets/models/');
            objLoader.load('butterfly.obj', function (object) {

                //Get the position of two wings
                var wing2 = object.children[5];
                var wing1 = object.children[4];

                //Set transparency for both wings
                wing1.material.opacity = 0.6;
                wing1.material.transparent = true;
                wing1.material.depthTest = false;
                wing1.material.side = THREE.DoubleSide;

                wing2.material.opacity = 0.6;
                wing2.material.depthTest = false;
                wing2.material.transparent = true;
                wing2.material.side = THREE.DoubleSide;

                //Scale and add the model to the scene
                object.scale.set(100, 100, 100);
                scene.add(object);
            })
        });
    }

    //Initialize performance plug-ins
    var stats;
    function initStats() {
        stats = new Stats();
        document.body.appendChild(stats.dom);
    }

    //User interaction plug in left mouse button press and hold rotation, right mouse button press and hold translation, scroll wheel zoom
    var controls;
    function initControls() {

        controls = new THREE.OrbitControls( camera, renderer.domElement );

        // If you use the animate method, delete this function
        //controls.addEventListener( 'change', render );
        // Whether there is inertia in the meaning of damping or rotation when the animation is recycled
        controls.enableDamping = true;
        //Dynamic damping coefficient is the mouse drag rotation sensitivity
        //controls.dampingFactor = 0.25;
        //Can I zoom
        controls.enableZoom = true;
        //Auto rotate or not
        controls.autoRotate = true;
        //Set the maximum distance between the camera and the origin
        controls.minDistance  = 1;
        //Set the maximum distance between the camera and the origin
        controls.maxDistance  = 200;
        //Enable right drag
        controls.enablePan = true;
    }

    function render() {

        renderer.render( scene, camera );
    }

    //Function triggered by window change
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        render();
        renderer.setSize( window.innerWidth, window.innerHeight );

    }

    function animate() {
        //Update controller
        render();

        //Update performance plug-ins
        stats.update();

        controls.update();

        requestAnimationFrame(animate);
    }

    function draw() {
        initGui();
        initRender();
        initScene();
        initCamera();
        initLight();
        initModel();
        initControls();
        initStats();

        animate();
        window.onresize = onWindowResize;
    }
</script>
</html>

Tags: Attribute JSON

Posted on Thu, 02 Apr 2020 01:17:21 -0700 by MiCR0