Skip to content

LOD (Level Of Detail)

Description

Use LOD to show/hide different quality meshes dependent on the distance from the camera.

In this example, I load 3 different types of trees, each with 3 levels of detail being high, medium and low.

As you zoom in and out of a tree, you can see that the model changes depending on the distance from the camera.

<>

Sample Code

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import { GUI } from 'dat.gui'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import TWEEN from '@tweenjs/tween.js'

const scene = new THREE.Scene()
scene.background = new THREE.Color(0x87ceeb)

const light = new THREE.DirectionalLight(0xffffff, 10)
light.position.set(100, 100, 100)
light.castShadow = true
light.shadow.mapSize.width = 4096
light.shadow.mapSize.height = 4096
light.shadow.camera.near = 0.5
light.shadow.camera.far = 500
light.shadow.camera.left = -500
light.shadow.camera.right = 500
light.shadow.camera.top = 500
light.shadow.camera.bottom = -500
scene.add(light)

// const helper = new THREE.CameraHelper(light.shadow.camera);
// scene.add(helper);

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
camera.position.set(4, 5, 7)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.dampingFactor = 0.05
controls.enableDamping = true
controls.screenSpacePanning = false

const raycaster = new THREE.Raycaster()
const sceneMeshes = new Array()

const material = new THREE.MeshPhongMaterial({ color: 0x567d46 })
const planeGeometry = new THREE.PlaneGeometry(1, 1)
planeGeometry.scale(500, 500, 1)
const planeMesh = new THREE.Mesh(planeGeometry, material)
planeMesh.rotateX(-Math.PI / 2)
planeMesh.receiveShadow = true
scene.add(planeMesh)
sceneMeshes.push(planeMesh)

let childObjectCount = 2 //how many child meshes are in the tree model. The trunk and leaves are different meshes
const treeCount = 1200 //this many trees are drawn
let treeCounter = 0

const positions = new Array()
for (let i = 0; i < treeCount; i++) {
    positions.push({
        x: Math.random() * 400 - 200,
        y: 0,
        z: Math.random() * 400 - 200,
    })
}
const scales = new Array()
for (let i = 0; i < treeCount; i++) {
    scales.push({
        x: Math.random() * 2 + 1,
        y: Math.random() * 5 + 1,
        z: Math.random() * 2 + 1,
    })
}

const treesTypes = ['saplingTree', 'birchTreeWithLeaves', 'tree1WithLeaves']
treesTypes.forEach((treeType) => {
    let treeHighDetail = new THREE.Object3D()
    let treeMediumDetail = new THREE.Object3D()
    let treeLowDetail = new THREE.Object3D()

    const glTFLoader = new GLTFLoader()
    glTFLoader.load('models/' + treeType + '_high.glb', (gltf) => {
        for (let j = 0; j < childObjectCount; j++) {
            const geometry = (gltf.scene.children[0].children[j] as THREE.Mesh)
                .geometry
            treeHighDetail.add(
                new THREE.Mesh(
                    geometry,
                    (gltf.scene.children[0].children[j] as THREE.Mesh).material
                )
            )
        }
        treeHighDetail.traverse(function (child) {
            if ((<THREE.Mesh>child).isMesh) {
                child.castShadow = true
            }
        })

        glTFLoader.load('models/' + treeType + '_medium.glb', (gltf) => {
            for (let j = 0; j < childObjectCount; j++) {
                const geometry = (
                    gltf.scene.children[0].children[j] as THREE.Mesh
                ).geometry
                treeMediumDetail.add(
                    new THREE.Mesh(
                        geometry,
                        (
                            gltf.scene.children[0].children[j] as THREE.Mesh
                        ).material
                    )
                )
            }
            treeMediumDetail.traverse(function (child) {
                if ((<THREE.Mesh>child).isMesh) {
                    child.castShadow = true
                }
            })

            glTFLoader.load('models/' + treeType + '_low.glb', (gltf) => {
                for (let j = 0; j < childObjectCount; j++) {
                    const geometry = (
                        gltf.scene.children[0].children[j] as THREE.Mesh
                    ).geometry
                    treeLowDetail.add(
                        new THREE.Mesh(
                            geometry,
                            (
                                gltf.scene.children[0].children[j] as THREE.Mesh
                            ).material
                        )
                    )
                }
                treeLowDetail.traverse(function (child) {
                    if ((<THREE.Mesh>child).isMesh) {
                        child.castShadow = true
                    }
                })

                for (let i = 0; i < treeCount / treesTypes.length; i++) {
                    const lod = new THREE.LOD()
                    let mesh = treeHighDetail.clone()
                    mesh.scale.copy(scales[treeCounter])
                    lod.addLevel(mesh, 5)

                    mesh = treeMediumDetail.clone()
                    mesh.scale.copy(scales[treeCounter])
                    lod.addLevel(mesh, 10)

                    mesh = treeLowDetail.clone()
                    mesh.scale.copy(scales[treeCounter])
                    lod.addLevel(mesh, 30)

                    lod.position.copy(positions[treeCounter])
                    scene.add(lod)

                    treeCounter++
                }
            })
        })
    })
})

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

renderer.domElement.addEventListener('dblclick', onDoubleClick, false)
function onDoubleClick(event: MouseEvent) {
    const mouse = {
        x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1,
    }
    raycaster.setFromCamera(mouse, camera)

    const intersects = raycaster.intersectObjects(sceneMeshes, false)

    if (intersects.length > 0) {
        const p = intersects[0].point
        new TWEEN.Tween(controls.target)
            .to(
                {
                    x: p.x,
                    y: p.y,
                    z: p.z,
                },
                500
            )
            .easing(TWEEN.Easing.Cubic.Out)
            .start()
    }
}

const stats = new Stats()
document.body.appendChild(stats.dom)

var data = {
    color: light.color.getHex(),
    shadowMapSizeWidth: 4096,
    shadowMapSizeHeight: 4096,
    mapsEnabled: true,
}
const gui = new GUI()
const lightFolder = gui.addFolder('THREE.Light')
lightFolder.addColor(data, 'color').onChange(() => {
    light.color.setHex(Number(data.color.toString().replace('#', '0x')))
})
lightFolder.add(light, 'intensity', 0, 20, 0.01)
lightFolder.open()

const directionalLightFolder = gui.addFolder('THREE.DirectionalLight')
directionalLightFolder
    .add(light.shadow.camera, 'left', -500, 1, 1)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(light.shadow.camera, 'right', 1, 500, 1)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(light.shadow.camera, 'top', 1, 500, 1)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(light.shadow.camera, 'bottom', -500, -1, 1)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(light.shadow.camera, 'near', 0.1, 500)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(light.shadow.camera, 'far', 0.1, 500)
    .onChange(() => light.shadow.camera.updateProjectionMatrix())
directionalLightFolder
    .add(data, 'shadowMapSizeWidth', [256, 512, 1024, 2048, 4096])
    .onChange(() => updateShadowMapSize())
directionalLightFolder
    .add(data, 'shadowMapSizeHeight', [256, 512, 1024, 2048, 4096])
    .onChange(() => updateShadowMapSize())
directionalLightFolder.add(light.position, 'x', -50, 50, 0.01)
directionalLightFolder.add(light.position, 'y', -50, 50, 0.01)
directionalLightFolder.add(light.position, 'z', -50, 50, 0.01)
directionalLightFolder.open()

function updateShadowMapSize() {
    light.shadow.mapSize.width = data.shadowMapSizeWidth
    light.shadow.mapSize.height = data.shadowMapSizeHeight
    ;(light.shadow.map as any) = null
}

function animate() {
    requestAnimationFrame(animate)

    controls.update()

    TWEEN.update()

    //helper.update()

    render()

    stats.update()
}

function render() {
    renderer.render(scene, camera)
}

animate()

Comments