Three.js Study Notes (i)

Source: Internet
Author: User
Tags cos sin python script

I. Obtaining Three.js

Three.js's code is hosted on GitHub, https://github.com/mrdoob/three.js/

We can use Git to get the code, or we can download the zip file directly if we are in trouble.

Two. Directory structure

Take a look at the Three.js directory structure after you get the code.

|-build

|-custom

|-three.js

|-examples

|-gui

|-src

|-cameras

|-core

|-extras

|-lights

|-materials

|-objects

|-renderers

|-scenes

|-textures

|-three.js

|-utils

|-compiler

|-exporters

|-build.bat

|-build.sh

|-build.xml

|-build_all.bat

|-build_all.sh

    1. The build directory is the source code after the compression of the JS file, and the connection and compression of the source code of the tool in the Utils directory, in the Utils directory also has a exporters directory, is a variety of model export tools, plugins, there are blender and Max Export plugins, There is also a Python script that turns fbx into a three.js scene file.
    2. Examples directory is an example of three.js, it is worth mentioning that there are many useful shader scripts and JS scripts can be used in their own projects, such as Js/shaderextra.js provides a lot of ready-made shader code, js/ Postprocessing provides several common post-processing interfaces that are encapsulated
    3. Below the GUI are some of the packaged UI interfaces
    4. SRC, of course, is the highlight. Three.js source code is in this directory, SRC under the sub-directory is also a good embodiment of the composition of three.js, like Camera,light,object These are a scene of the base object, and scenes below is the entire scene of the management code, like scene Graph implementation, renderers is the implementation of the core renderer, Three.js is good for scenes and renderers, can render the same scene with different renderer, but for some advanced features of WEBGL support, using other renderer is certainly not possible. There is also a extras directory that is not a convenient interface on top of the core code, such as providing some common camera,material,light.
    5. The Utils directory has been mentioned above.

Three. Example analysis-WebGL Trackballcamera Earth

This example is available in the examples directory

In this example we can see:

    • One of the most basic three.js applications needs something
    • Camera creation and the addition of the camera control
    • Creation of basic forms, creation of materials
    • The creation of the particle system, which will be said later.

This is not done by line-by-line analysis, but by the code that each feature is singled out for.

The basic structure of a three.js application.

No matter what to write 3d applications, C + + 's Ogre,flash pv3d,js o3d, or use the scene editor, a 3d scene needs the most basic things are the same, a major camera, a major scene.

Of course there are objects in the general scene, there are lights, every object has a material. We can create them manually in Three.js, or we can directly load a JSON file that records the scene data.

Create a scene

New Three. Scene ();

Create a camera

New Three. Perspectivecamera (Width/height, 1e7);
camera.position.z = radius * 7;

This code determines the view cone of a camera, four parameters are the camera's angle of view, the aspect ratio of the viewport, the camera's near plane (Front Clipping Plane) and the far side (back Clipping Plane), why four parameters? In fact, the camera is essentially a projection matrix, and the creation of a perspective projection of the matrix (and orthogonal projection) requires these four parameters, the image point can be seen

As you can see, to uniquely determine a perspective of the frustum (viewing Frustum) requires at least the above four parameters.

Adjust the position and orientation of the camera

Create a camera also need to set the position and orientation of the camera, Three.js can use the Camera.lookat function for camera orientation, set the camera position with Camera.position

In this demo, the camera transform is encapsulated in the trackballcontrols that creates a trackball control effect.

If you look at the code of LookAt, actually these operations are the operation of the Matrix, the camera is essentially the same as the entity in a scene, all using the transformation matrix to do the transformation.

Here are some things to add to the scene.

We can see in the demo that there is a Earth, a one moon ball, the surrounding space, and a light that has been modelled on the Earth's sun, and if we look carefully, we will find that there is actually a layer of atmosphere outside the Earth.

Here's a list of things to add into the scene.

1. The first is the Earth

To create an object in WebGL, the most basic data we need is the vertex position of the object, and of course, if the object can be in the eye, we also need to write shader for it, need to pass in the vertex's normal data, need to pass in Texcoord to complete the texture mapping.

Speaking of shader, let's look at the basic sequence of rendering an object in WebGL:

The program will load, compile and bind the shader code, each render batch, the video card will pass these vertex data into the pipeline, in the pipeline through the vertex shader to the vertex position transformation, rasterization, Fragment shader in the calculation of each pixel color, The final depth test and so on after output to the screen.

Three.js the management of object vertex data into the geometry interface, the management of parameters in shader and shader is encapsulated as material interface, each time the load binding shader is compiled, the incoming vertex data will be processed uniformly in webglrenderer.

var New Three. Shadermaterial ({
FragmentShader:shader.fragmentShader,
VertexShader:shader.vertexShader,
Uniforms:uniforms,
True
});

Here is the creation of a material, passed in Fragmentshader and VertexShader code, uniforms is the parameters of these two shader.

Both of these can be take doctrine.

var shader = three. shaderutils.lib["Normal"],
Uniforms = three. Uniformsutils.clone (shader.uniforms);

uniforms["Tnormal"].texture = normaltexture;
uniforms["Unormalscale"].value = 0.85;

uniforms["Tdiffuse"].texture = planettexture;
uniforms["tspecular"].texture = speculartexture;

false;
true;
true;

uniforms["Udiffusecolor"].value.sethex (0XFFFFFF);
uniforms["Uspecularcolor"].value.sethex (0x333333);
uniforms["Uambientcolor"].value.sethex (0x000000);

uniforms["ushininess"].value = 15;


So here we create a normal map of the material (about the principle of normal map, here is not much to say), and set its various parameters, where tnnormal is the normal texture, tdiffuse is diffuse texture, tspecular is a high-gloss texture,

Tdiffuse,tspecular and Tnormal

Udiffusecolor, Uspecularcolor, Uambientcolor, ushininess These four are the parameters of the Phong model illumination,

Udiffusecolor: Diffuse color

Uspecularcolor: High-Gloss color

Uambientcolor: Ambient light color

Ushininess: Surface smoothness of objects

The following paragraph is the creation of the Earth itself, and added to the scene

New Three. Spheregeometry (RADIUS, 100, 50);
Geometry.computetangents ();
New Three. Mesh (geometry, materialnormalmap);
MESHPLANET.ROTATION.Y = 1.3;
Meshplanet.rotation.z = tilt;
Scene.add (meshplanet);

Finally, take a look at the composition of the mesh added to the scene

2. The moon and clouds are also Efaro, and the clouds are translucent because they are in PNG format.

3. Create a parallel light

The creation of a light is very simple, tree.js light object is mainly to save the function of the light parameters, and the actual lighting calculation is placed in the shader, we do not care for the moment

New Three. DirectionalLight (0xFFFFFF);
DirLight.position.set (-1, 0, 1). normalize ();
Scene.add (Dirlight);

The interaction of the scene

In sample we can use the mouse to control the camera rotation, three.js to provide us with some common camera control interface, this sample uses the Trackball

New Three. Trackballcontrols (camera, renderer.domelement);
Controls.rotatespeed = 1.0;
Controls.zoomspeed = 1.2;
Controls.panspeed = 0.2;

false;
false;

false;
Controls.dynamicdampingfactor = 0.3;

controls.mindistance = radius * 1.1;
controls.maxdistance = radius * 100;

We can see a few common camera controls below the Src/extras/controls.

Rendering

Let's take a final look at the code in the render function.

var New Date (). GetTime (),
DT = (t-time)/1000;
Time = t;

MESHPLANET.ROTATION.Y + = rotationspeed * DT;
MESHCLOUDS.ROTATION.Y + = 1.25 * rotationspeed * DT;

var angle = dt * ROTATIONSPEED;

New Three. Vector3 (
Math.Cos (Angle) * Meshmoon.position.x-math.sin (angle) * meshmoon.position.z,
0,
Math.sin (Angle) * meshmoon.position.x + math.cos (angle) * meshmoon.position.z
);
MESHMOON.ROTATION.Y-= angle;

Controls.update ();

Renderer.clear ();
Renderer.render (scene, camera);

This function basically does a few things to do each frame:

    • Calculate the time of this frame
    • Rotating the Earth
    • Calculate the position of the moon
    • Update Camera Control
    • Rendering

The final render function requires two parameters, scene and camera, if we look at the code in render, we can know that every time we render, we need to iterate through scene graph to render each object that needs to be rendered. The function of the camera is simply to provide a perspective transformation matrix and a projection matrix. This will continue in depth when you look at the code in Webglrenderer.

This function uses the SetInterval timed call to achieve the effect of the animation.

Three.js Study Notes (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.