Code Structure Used in the Course
Explore how the code is structured and used throughout the course.
A general structure for creating a new scene
As we know, most scenes will need pretty much the same setup. They all need some lights, a camera, a scene, and maybe a ground floor. To avoid having to add all this to each example, we’ve externalized most of these common elements to a set of helper libraries. Examples throughout the course imports functions and modules from the Three.js library and folders like utils
, bootstrap
, helpers
, and control
.
Let’s take an example of chapter-01/porsche.html:
import * as THREE from 'three'import { initScene } from '../../bootstrap/bootstrap'import { exrCubeMap } from '../../util/cubemap'import { floatingFloor } from '../../bootstrap/floor'import { intializeRendererControls } from '../../controls/renderer-control'import { initializeHelperControls } from '../../controls/helpers-control'import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'import GUI from 'lil-gui'import { visitChildren } from '../../util/modelUtil'const props = {backgroundColor: 0xffffff,fogColor: 0xffffff}const gui = new GUI()initScene(props)(({ scene, camera, renderer, orbitControls }) => {camera.position.x = -3camera.position.z = 3camera.position.y = 0orbitControls.update()floatingFloor(scene)const loader = new GLTFLoader()loader.load('/assets/gltf/porsche/scene.gltf', (loadedObject) => {const porsche = loadedObject.scene.children[0]visitChildren(porsche, (el) => {if (el.type === 'Mesh') {if (el.material.name === 'paint') {el.material.color = new THREE.Color(0xffffff)el.material.metalness = 1el.material.roughness = 0.2exrCubeMap(renderer, (texture) => {if (el.material) {el.material.envMap = textureel.material.needsUpdate = true}})}el.castShadow = trueel.receiveShadow = true}})porsche.translateZ(-1.9)porsche.translateX(0.3)porsche.translateY(0.6)porsche.rotateZ(-Math.PI / 2)scene.add(porsche)})function animate() {requestAnimationFrame(animate)renderer.render(scene, camera)orbitControls.update()}animate()intializeRendererControls(gui, renderer)initializeHelperControls(gui, scene)})
Explanation
Lines 1–17: First we import modules and functions from different libraries then we set up configuration properties for the scene, such as background and fog colors. We also initialize a graphical user interface (GUI) using the
lil-gui
library.Lines 19–54: Second, we initialized the scene using the
initScene
function, and the callback receives thescene
,camera
,renderer
, andorbitControls
parameters. We set the camera position, a floating floor, and a 3D model of a Porsche is loaded using theGLTFLoader
. We set the different properties of loaded Porsche models like colors, metalness, and roughness.Lines 56–64: Finally, we add an animation loop that continuously renders ...