3/13
2.1. Introduction : Using Three.js
3D Graphics programming requires to be able to manipulate 3D data and render them efficiently as an image on the screen. There exists several frameworks and libraries to handle 3D graphics programming from low level one proposing direct communication with the GPU such as OpenGL (in C language), to high level one proposing GUI interface where users can visually place and script high level behaviors such as Unity (in C# language).
In our case, we will use the library Three.js (MIT license) in JavaScript. The use of Three.js has the following advantages
-
The JavaScript code can run natively in any recent web browser. This allows to share your code and result very easily, even online, independently of the hardware, OS, and library installation.
-
Three.js library provides a set of high-level data structure adapted to 3D graphics (graph scene, meshes, etc) allowing to efficiently setup and render a 3D scene. Three.js hides the low level code required to setup the rendering of the scene, while still proposing fully programmable API to let you free to code your expected behavior.
Terminology: Three.js and WebGL
Three.js is a JavaScript library built on top of WebGL.
WebGL - Web Graphics Library - is a JavaScript API (Application Programming Interface) designed to render 3D (and 2D) graphics in a web browser. WebGL compatibility is natively implemented by your web browser, and it doesn’t need the installation of extra libraries.
WebGL is an API for web browser following the specification called OpenGL ES (OpenGL for Embedded Systems). OpenGL ES is a subset of the OpenGL specification that describes functions to handle data for rendering purpose. Note that OpenGL is not a library of code, but a set of specifications that are implemented in various ways, depending on your graphics card (GPU), OS and drivers. OpenGL is a low level specification that only focus on presenting raw data to the GPU and performing computation with programs called shaders (in GLSL language), executed in parallel by the graphics card.
Using Three.js, you don’t have to call directly functions from WebGL, which are automatically handled from the scene graph of Three.js. Furthermore, Three.js proposes a set of basic shaders allowing you to display 3D objects with lights without having to code directly in GLSL.
Three.js is well adapted for fast prototyping and propose, non-exhaustively, the following functionalities
-
Creating 3D primitives and materials (color and appearance of the shape)
-
Modification of the position and orientation of the shapes
-
Setup of lights and cameras
-
A scene graph defining the position and orientation of each object in a tree-like structure, allowing to easily define relative positions between parent and child objects.
-
Handle picking using ray caster, ie. selecting a 3D object, or a part of it, from the mouse click on the 2D screen.