Importing a Modeled Mesh From Blender to Three.js

It has been a very long time since the last Three.js rotating cube post. Better late than never, right? Here is the next part about the import and animation of a more complex mesh created in a modeling software. Yet, as we are not designer (and a fortiori, not 3D designer), we will focus on a not too complicated mesh: the marmelab logo.

marmelab logo

Modeling Marmelab Logo with Blender

We are going to use Blender, a free and open-source 3D modeler. First, let’s create the mesh. Fortunately, marmelab logo is quite simple: it is composed of five cubes glued together to form the letter M. Here is a video describing this modeling:

Export a Blender Mesh in JSON for Three.js

Now that we got our mesh (you can download it here), let’s take a look on how to export it for Three.js. Three.js expects to get a Mesh in JSON format. Fortunately, the community has already provided a Blender to Three.js exporter. So, download it and put the io_threefolder under your ~/.config/blender/2.69/scripts/addons/ folder or its equivalent depending your operating system (check the README for more informations).

Then, open the File > User preferences and go to the Addons tab. Search for Three.js and enable the found plug-in. Now, you should be able to see a File > Export > Three.js option. On the opened tab, ensure that Face Materials checkbox is checked. Otherwise, you won’t have materials, and Three.js is going to refuse to import your mesh.

Once saved, your file should look like the following:

{
    "metadata": {
        "uvs": 0,
        "type": "Geometry",
        "normals": 31,
        "generator": "io_three",
        "materials": 6,
        "version": 3,
        "vertices": 200,
        "faces": 198
    },
    "vertices":[/* ... */],
    "uvs": [],
    "name": "CubeGeometry",
    "materials": [/* ... */],
    "normals":[/* ... */],
    "faces":[/* ... */]
}

All required data is here. The most important are vertices, faces, normals (to compute lighting correctly), and materials.

Importing Mesh From Blender in Three.js

Now we got our mesh into an understandable format, let’s import it in Three.js. Based on the last tutorial code, we just have to replace our initCube function by an initMesh one:

var mesh = null;
function initMesh() {
    var loader = new THREE.JSONLoader();
    loader.load('./marmelab-logo.json', function(geometry) {
        mesh = new THREE.Mesh(geometry);
        scene.add(mesh);
    });
}

Note that as you load a file dynamically, you can’t open your file directly with a browser. You have to use a Web server. On Linux, you can use for instance the Node.js http-server package.

npm install -g http-server
http-server .

Rotating a Mesh

Do not forget to modify the rotateCube function:

function rotateMesh() {
    if (!mesh) {
        return;
    }

    mesh.rotation.x -= SPEED * 2;
    mesh.rotation.y -= SPEED;
    mesh.rotation.z -= SPEED * 3;
}

As you can see, working with a mesh is exactly the same as working with a primitive. We just check that our mesh is loaded to avoid a warning. Indeed, the loading function is an asynchronous one and then, the rendering loop may start before our model is in memory. A cleaner way to deal with it would be to start rendering only when model is loaded, but let’s keep it simple for this tutorial.

If your refresh your browser, you should now see a wireframed rotating marmelab logo. Yet, if you look deeper, you may see a graphical glitch:

Marmelab rotation logo's glitch

It seems some edges are broken. No mesh has been hurt during this animation, I swear. It is just a concrete example of the zFardistance from this previous post schema:

Perspective camera in WebGL

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

The value provided to the camera is not enough. So, we got two solutions: either increase the camera maximum length vision, or reduce the size of our mesh. Let choose the latter. Modify the initMesh method adding this line in the callback:

mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.75;

This way, we reduce the size of our rotation logo by 25%. The glitch should have disappeared.

Changing Rotation Center Position

Rotation center is currently located at the bottom of one of the M branch. It would be far better if it occurred at the common point of all cubes. To do so, we have to translate the rotation origin, using transformation matrices. Sounds complicated? Fortunately, Three.js simplifies a lot our work:

loader.load('./marmelab-logo.json', function(geometry) {
    mesh = new THREE.Mesh(geometry);
    mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.75;
    mesh.translation = THREE.GeometryUtils.center(geometry);
    scene.add(mesh);
});

All the magic happens on the mesh.translation line. We retrieve the center of our mesh, thanks to the GeometryUtils.center, and then translate it accordingly to make it rotate on its center.

Loading Materials

Our Blender file contains several materials in order to colorize different faces. So, let’s add these materials to our mesh to get rid of this wireframe display. Materials are also loaded through the loader.load method. You just have to add a second argument materials to the callback function:

loader.load('./marmelab-logo.json', function(geometry, materials) {
    mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
    // ...
});

Do not forget to pass materials to the THREE.MeshFaceMaterial function, otherwise you would get the following error:

Cannot read property ‘uniforms’ of undefined

Let There Be Light

We don’t have wireframes anymore, but our textures are fully black. This is due to a lack of light on our scene.

Three.js mesh without lights

So, let’s create a new initLights method and let’s call it in our init function:

function initLights() {
    var light = new THREE.AmbientLight(0xffffff);
    scene.add(light);
}

We added here a white AmbientLight. This kind of light is applied everywhere, so you don’t have to worry about the light position. As we are going to see lights in more details in another post, I won’t cover it for the moment.

Woohoo! We now have a nice looking marmelab logo. As usual, demonstration and source code are both available on GitHub.

 

[출처] https://www.jonathan-petitcolas.com/2015/07/27/importing-blender-modelized-mesh-in-threejs.html

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
183 [CSS 기초] DIV 태그를 이용하여 프레임 나누기 file 졸리운_곰 2017.08.25 496
182 jQuery 스타일 & 속성 다루기 file 졸리운_곰 2017.08.25 597
181 [CSS] 절대위치를 상대위치로 잡기(?) position: relative와 absolute의 응용 file 졸리운_곰 2017.08.17 350
180 Is there a limit of vertices in WebGL? 웹지엘의 제약사항 졸리운_곰 2017.08.16 553
179 JavaScript Performance Monitor file 졸리운_곰 2017.08.16 371
178 Monitor Rendering Performance Within Three.js file 졸리운_곰 2017.08.16 541
177 List of WebGL frameworks 졸리운_곰 2017.08.16 499
176 From Unity to Three.js file 졸리운_곰 2017.08.16 1750
175 [Node.js] proxy 환경에서 node.js 설정 file 졸리운_곰 2017.08.16 485
174 Collada dae to three.js json convertor sample file 졸리운_곰 2017.08.16 579
173 THREE.WebGLShader: Shader couldn't compile - Chrome Version 44.0.2403.125 #6929 file 졸리운_곰 2017.08.10 554
172 Uniforms types 졸리운_곰 2017.08.10 547
171 Custom shaders with Three.JS: Uniforms, textures and lighting file 졸리운_곰 2017.08.10 699
170 WebGL and ThreeJS Using Blender Models file 졸리운_곰 2017.08.05 355
» Importing a Modeled Mesh From Blender to Three.js file 졸리운_곰 2017.08.05 458
168 Using SketchUp Models OrcaXS edited this page on 27 Apr · 7 revisions 졸리운_곰 2017.08.05 459
167 Three.js Loading .mtl and .obj - object stays white file 졸리운_곰 2017.08.05 541
166 Cross-origin resource sharing file 졸리운_곰 2017.08.05 403
165 HTTP 접근 제어 (CORS) 졸리운_곰 2017.08.05 290
164 [three.js] How to Build a First Person Shooter in the Browser with Three.js and WebGL/HTML5 Canvas file 졸리운_곰 2017.07.22 534
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED