-
Notifications
You must be signed in to change notification settings - Fork 386
Expand file tree
/
Copy pathTileFlatteningPlugin.js
More file actions
385 lines (252 loc) · 8.5 KB
/
TileFlatteningPlugin.js
File metadata and controls
385 lines (252 loc) · 8.5 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import { Box3, DoubleSide, MathUtils, Matrix4, MeshBasicMaterial, Raycaster, Sphere, Vector3 } from 'three';
// Limitations:
// - No support for BatchedTilesPlugin when resetting or modifying geometry
// - Sharing geometry between models may result in incorrect flattening
const _sphere = /* @__PURE__ */ new Sphere();
const _vec = /* @__PURE__ */ new Vector3();
const _matrix = /* @__PURE__ */ new Matrix4();
const _invMatrix = /* @__PURE__ */ new Matrix4();
const _raycaster = /* @__PURE__ */ new Raycaster();
const _doubleSidedMaterial = /* @__PURE__ */ new MeshBasicMaterial( { side: DoubleSide } );
const _box = /* @__PURE__ */ new Box3();
const RAYCAST_DISTANCE = 1e5;
function calculateSphere( object, target ) {
if ( object.isBufferGeometry ) {
if ( object.boundingSphere === null ) {
object.computeBoundingSphere();
}
return target.copy( object.boundingSphere );
} else {
_box.setFromObject( object );
_box.getBoundingSphere( target );
return target;
}
}
/**
* Plugin that flattens tile geometry vertices onto the surface of one or more mesh
* "shapes", useful for placing flat terrain overlays or cutting roads into terrain.
* Shapes are added via `addShape()` and removed via `deleteShape()` or `clearShapes()`.
*/
export class TileFlatteningPlugin {
constructor() {
this.name = 'TILE_FLATTENING_PLUGIN';
this.priority = - 100;
this.tiles = null;
this.shapes = new Map();
this.positionsMap = new Map();
this.positionsUpdated = new Set();
this.needsUpdate = false;
}
init( tiles ) {
this.tiles = tiles;
this.needsUpdate = true;
this._updateBeforeCallback = () => {
if ( this.needsUpdate ) {
this._updateTiles();
this.needsUpdate = false;
}
};
this._disposeModelCallback = ( { tile } ) => {
this.positionsMap.delete( tile );
this.positionsUpdated.delete( tile );
};
tiles.addEventListener( 'update-before', this._updateBeforeCallback );
tiles.addEventListener( 'dispose-model', this._disposeModelCallback );
}
// update tile flattening state if it has not been made visible, yet
setTileActive( tile, active ) {
if ( active && ! this.positionsUpdated.has( tile ) ) {
this._updateTile( tile );
}
}
_updateTile( tile ) {
const { positionsUpdated, positionsMap, shapes, tiles } = this;
const { scene } = tile.engineData;
positionsUpdated.add( tile );
if ( ! scene ) {
return;
}
if ( ! positionsMap.has( tile ) ) {
// save the geometry positions for resetting after
const geomMap = new Map();
positionsMap.set( tile, geomMap );
scene.traverse( c => {
if ( c.geometry ) {
geomMap.set( c.geometry, c.geometry.attributes.position.array.slice() );
}
} );
} else {
// reset the geometry state before re-flattening tiles
const geomMap = positionsMap.get( tile );
scene.traverse( c => {
if ( c.geometry ) {
const buffer = geomMap.get( c.geometry );
if ( buffer ) {
c.geometry.attributes.position.array.set( buffer );
c.geometry.attributes.position.needsUpdate = true;
}
}
} );
}
// TODO: if we save the sphere of the original mesh we can check the height to limit the tiles checked
// TODO: we should use the tile bounding volume sphere if present
scene.updateMatrixWorld( true );
// iterate over every geometry
scene.traverse( c => {
const { geometry } = c;
if ( ! geometry ) {
return;
}
// calculate matrices
_matrix.copy( c.matrixWorld );
if ( scene.parent !== null ) {
_matrix.premultiply( tiles.group.matrixWorldInverse );
}
_invMatrix.copy( _matrix ).invert();
// calculate sphere for mesh
calculateSphere( geometry, _sphere ).applyMatrix4( _matrix );
// iterate over each shape
shapes.forEach( ( {
shape,
direction,
sphere,
thresholdMode,
threshold,
flattenRange,
} ) => {
// check if the spheres overlap so there may actually be potential of geometry overlap
_vec.subVectors( _sphere.center, sphere.center );
_vec.addScaledVector( direction, - direction.dot( _vec ) );
const r2 = ( _sphere.radius + sphere.radius ) ** 2;
if ( _vec.lengthSq() > r2 ) {
return;
}
// iterate over every vertex position
const { position } = geometry.attributes;
const { ray } = _raycaster;
ray.direction.copy( direction ).multiplyScalar( - 1 );
for ( let i = 0, l = position.count; i < l; i ++ ) {
ray.origin
.fromBufferAttribute( position, i )
.applyMatrix4( _matrix )
.addScaledVector( direction, RAYCAST_DISTANCE );
_raycaster.far = RAYCAST_DISTANCE;
const hit = _raycaster.intersectObject( shape )[ 0 ];
if ( hit ) {
let rangeAlpha = ( RAYCAST_DISTANCE - hit.distance ) / threshold;
const aboveThreshold = rangeAlpha >= 1;
if ( ! aboveThreshold || aboveThreshold && thresholdMode === 'flatten' ) {
rangeAlpha = Math.min( rangeAlpha, 1.0 );
hit.point.addScaledVector( ray.direction, MathUtils.mapLinear( rangeAlpha, 0, 1, - flattenRange, 0 ) );
hit.point.applyMatrix4( _invMatrix );
position.setXYZ( i, ...hit.point );
}
}
}
} );
} );
this.tiles.dispatchEvent( { type: 'needs-render' } );
}
_updateTiles() {
this.positionsUpdated.clear();
this.tiles.activeTiles.forEach( tile => this._updateTile( tile ) );
}
/**
* Returns whether the given object has already been added as a shape.
* @param {Object3D} mesh
* @returns {boolean}
*/
hasShape( mesh ) {
return this.shapes.has( mesh );
}
/**
* Adds the given mesh as a flattening shape. All coordinates must be in the tileset's local
* frame. Throws if the shape has already been added.
* @param {Object3D} mesh The shape mesh to flatten tile vertices onto.
* @param {Vector3} [direction] Direction to cast rays when flattening (default downward along -Z).
* @param {Object} [options]
* @param {number} [options.threshold=Infinity] Maximum distance from the shape surface within which vertices are flattened. `Infinity` always flattens; `0` never flattens.
*/
addShape( mesh, direction = new Vector3( 0, 0, - 1 ), options = {} ) {
if ( this.hasShape( mesh ) ) {
throw new Error( 'TileFlatteningPlugin: Shape is already used.' );
}
if ( typeof options === 'number' ) {
console.warn( 'TileFlatteningPlugin: "addShape" function signature has changed. Please use an options object, instead.' );
options = {
threshold: options,
};
}
this.needsUpdate = true;
const shape = mesh.clone();
shape.updateMatrixWorld( true );
shape.traverse( c => {
if ( c.material ) {
c.material = _doubleSidedMaterial;
}
} );
const sphere = calculateSphere( shape, new Sphere() );
this.shapes.set( mesh, {
shape: shape,
direction: direction.clone(),
sphere: sphere,
// "flatten": Flattens the vertices above the shape
// "none": leaves the vertices above the shape as they are
thresholdMode: 'none',
// only flatten within this range above the object
threshold: Infinity,
// the range to flatten vertices in to. 0 is completely flat
// while 0.1 means a 10cm range.
flattenRange: 0,
...options,
} );
}
/**
* Notifies the plugin that a shape's geometry or transform has changed and tile
* flattening needs to be regenerated.
* @param {Object3D} mesh
*/
updateShape( mesh ) {
if ( ! this.hasShape( mesh ) ) {
throw new Error( 'TileFlatteningPlugin: Shape is not present.' );
}
const { direction, threshold, thresholdMode, flattenRange } = this.shapes.get( mesh );
this.deleteShape( mesh );
this.addShape( mesh, direction, {
threshold,
thresholdMode,
flattenRange,
} );
}
/**
* Removes the given shape and triggers tile regeneration.
* @param {Object3D} mesh
* @returns {boolean} `true` if the shape was found and removed.
*/
deleteShape( mesh ) {
this.needsUpdate = true;
return this.shapes.delete( mesh );
}
/**
* Removes all shapes and resets flattened tiles to their original positions.
*/
clearShapes() {
if ( this.shapes.size === 0 ) {
return;
}
this.needsUpdate = true;
this.shapes.clear();
}
// reset the vertex positions and remove the update callback
dispose() {
this.tiles.removeEventListener( 'before-update', this._updateBeforeCallback );
this.tiles.removeEventListener( 'dispose-model', this._disposeModelCallback );
this.positionsMap.forEach( geomMap => {
geomMap.forEach( ( buffer, geometry ) => {
const { position } = geometry.attributes;
position.array.set( buffer );
position.needsUpdate = true;
} );
} );
}
}