forked from BabylonJS/Babylon.js
/
babylon.sceneOptimizer.ts
518 lines (380 loc) · 16.9 KB
/
babylon.sceneOptimizer.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
module BABYLON {
// Standard optimizations
export class SceneOptimization {
public apply = (scene: Scene): boolean => {
return true; // Return true if everything that can be done was applied
};
constructor(public priority: number = 0) {
}
}
export class TextureOptimization extends SceneOptimization {
constructor(public priority: number = 0, public maximumSize: number = 1024) {
super(priority);
}
public apply = (scene: Scene): boolean => {
var allDone = true;
for (var index = 0; index < scene.textures.length; index++) {
var texture = scene.textures[index];
if (!texture.canRescale || (<any>texture).getContext) {
continue;
}
var currentSize = texture.getSize();
var maxDimension = Math.max(currentSize.width, currentSize.height);
if (maxDimension > this.maximumSize) {
texture.scale(0.5);
allDone = false;
}
}
return allDone;
}
}
export class HardwareScalingOptimization extends SceneOptimization {
private _currentScale = 1;
constructor(public priority: number = 0, public maximumScale: number = 2) {
super(priority);
}
public apply = (scene: Scene): boolean => {
this._currentScale++;
scene.getEngine().setHardwareScalingLevel(this._currentScale);
return this._currentScale >= this.maximumScale;
};
}
export class ShadowsOptimization extends SceneOptimization {
public apply = (scene: Scene): boolean => {
scene.shadowsEnabled = false;
return true;
};
}
export class PostProcessesOptimization extends SceneOptimization {
public apply = (scene: Scene): boolean => {
scene.postProcessesEnabled = false;
return true;
};
}
export class LensFlaresOptimization extends SceneOptimization {
public apply = (scene: Scene): boolean => {
scene.lensFlaresEnabled = false;
return true;
};
}
export class ParticlesOptimization extends SceneOptimization {
public apply = (scene: Scene): boolean => {
scene.particlesEnabled = false;
return true;
};
}
export class RenderTargetsOptimization extends SceneOptimization {
public apply = (scene: Scene): boolean => {
scene.renderTargetsEnabled = false;
return true;
};
}
export class MergeMeshesOptimization extends SceneOptimization {
static _UpdateSelectionTree = false;
public static get UpdateSelectionTree(): boolean {
return MergeMeshesOptimization._UpdateSelectionTree;
}
public static set UpdateSelectionTree(value: boolean) {
MergeMeshesOptimization._UpdateSelectionTree = value;
}
private _canBeMerged = (abstractMesh: AbstractMesh): boolean => {
if (!(abstractMesh instanceof Mesh)) {
return false;
}
var mesh = <Mesh>abstractMesh;
if (!mesh.isVisible || !mesh.isEnabled()) {
return false;
}
if (mesh.instances.length > 0) {
return false;
}
if (mesh.skeleton || mesh.hasLODLevels) {
return false;
}
if (mesh.parent) {
return false;
}
return true;
}
public apply = (scene: Scene, updateSelectionTree?: boolean): boolean => {
var globalPool = scene.meshes.slice(0);
var globalLength = globalPool.length;
for (var index = 0; index < globalLength; index++) {
var currentPool = new Array<Mesh>();
var current = globalPool[index];
// Checks
if (!this._canBeMerged(current)) {
continue;
}
currentPool.push(<Mesh>current);
// Find compatible meshes
for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
var otherMesh = globalPool[subIndex];
if (!this._canBeMerged(otherMesh)) {
continue;
}
if (otherMesh.material !== current.material) {
continue;
}
if (otherMesh.checkCollisions !== current.checkCollisions) {
continue;
}
currentPool.push(<Mesh>otherMesh);
globalLength--;
globalPool.splice(subIndex, 1);
subIndex--;
}
if (currentPool.length < 2) {
continue;
}
// Merge meshes
Mesh.MergeMeshes(currentPool);
}
if (updateSelectionTree != undefined) {
if (updateSelectionTree) {
scene.createOrUpdateSelectionOctree();
}
}
else if (MergeMeshesOptimization.UpdateSelectionTree) {
scene.createOrUpdateSelectionOctree();
}
return true;
};
}
// Options
export class SceneOptimizerOptions {
public optimizations = new Array<SceneOptimization>();
constructor(public targetFrameRate: number = 60, public trackerDuration: number = 2000) {
}
public static LowDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions {
var result = new SceneOptimizerOptions(targetFrameRate);
var priority = 0;
result.optimizations.push(new MergeMeshesOptimization(priority));
result.optimizations.push(new ShadowsOptimization(priority));
result.optimizations.push(new LensFlaresOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new PostProcessesOptimization(priority));
result.optimizations.push(new ParticlesOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new TextureOptimization(priority, 1024));
return result;
}
public static ModerateDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions {
var result = new SceneOptimizerOptions(targetFrameRate);
var priority = 0;
result.optimizations.push(new MergeMeshesOptimization(priority));
result.optimizations.push(new ShadowsOptimization(priority));
result.optimizations.push(new LensFlaresOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new PostProcessesOptimization(priority));
result.optimizations.push(new ParticlesOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new TextureOptimization(priority, 512));
// Next priority
priority++;
result.optimizations.push(new RenderTargetsOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new HardwareScalingOptimization(priority, 2));
return result;
}
public static HighDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions {
var result = new SceneOptimizerOptions(targetFrameRate);
var priority = 0;
result.optimizations.push(new MergeMeshesOptimization(priority));
result.optimizations.push(new ShadowsOptimization(priority));
result.optimizations.push(new LensFlaresOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new PostProcessesOptimization(priority));
result.optimizations.push(new ParticlesOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new TextureOptimization(priority, 256));
// Next priority
priority++;
result.optimizations.push(new RenderTargetsOptimization(priority));
// Next priority
priority++;
result.optimizations.push(new HardwareScalingOptimization(priority, 4));
return result;
}
}
// Scene optimizer tool
export class SceneOptimizer {
static _CheckCurrentState(scene: Scene, options: SceneOptimizerOptions, currentPriorityLevel: number, onSuccess?: () => void, onFailure?: () => void) {
// TODO: add an epsilon
if (scene.getEngine().getFps() >= options.targetFrameRate) {
if (onSuccess) {
onSuccess();
}
return;
}
// Apply current level of optimizations
var allDone = true;
var noOptimizationApplied = true;
for (var index = 0; index < options.optimizations.length; index++) {
var optimization = options.optimizations[index];
if (optimization.priority === currentPriorityLevel) {
noOptimizationApplied = false;
allDone = allDone && optimization.apply(scene);
}
}
// If no optimization was applied, this is a failure :(
if (noOptimizationApplied) {
if (onFailure) {
onFailure();
}
return;
}
// If all optimizations were done, move to next level
if (allDone) {
currentPriorityLevel++;
}
// Let's the system running for a specific amount of time before checking FPS
scene.executeWhenReady(() => {
setTimeout(() => {
SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
}, options.trackerDuration);
});
}
public static OptimizeAsync(scene: Scene, options?: SceneOptimizerOptions, onSuccess?: () => void, onFailure?: () => void): void {
if (!options) {
options = SceneOptimizerOptions.ModerateDegradationAllowed();
}
// Let's the system running for a specific amount of time before checking FPS
scene.executeWhenReady(() => {
setTimeout(() => {
SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
}, options.trackerDuration);
});
}
}
/**
* ***********************************
* New proposition for scene optimizer
* ***********************************
*/
// class to controle optimizations
export class renderGradingSceneOptimizer {
// grade : preset options to optimize scene (ex : low, medium, hight)
public grades: Array<any> = new Array();
// to know on wich grade we are.
private _currentGrade: number = 0;
// to know the step of evaluation :
// 1. try to upgrading.
// 2. if fps not reached, dowgrading.
private _currentGradingStep: string = "upGrading";
// result of all fps evaluation to set a level of hardware performance
private _hardwareEval: number = 0;
/**
* @param scene : BABYLON.Scene
* @param frameToReach : fps to reach
* @param trackerDuration : duration between two fps evaluation
* @param starterGrade : on wich grade renderGradingSceneOptimizer need to start.
* @param autoRunDelay : run automaticaly fps evaluation every 'x' ms. 0 mean desactived
*/
constructor (scene : Scene, public frameToReach: number = 59, public trackerDuration: number = 1000, private starterGrade: string, private autoRunDelay: number = 0) {
// update scene with starterGrade before render
scene.registerBeforeRender(() => {
this.updateSceneByGrade(starterGrade);
});
}
// add a new grade to renderGradingSceneOptimizer
public addGrade(newGrade: grade) {
this.grades.push(newGrade);
}
// start to evaluate fps and update scene if necessary
public run(scene : Scene) {
}
// update scene by render grade name
public updateSceneByGrade(gradeName : string) {
}
// force downgrade by 1
public downgrade() {
}
// force upgrade by 1
public upgrade() {
}
// get hardware evaluation
public getHardwareEvaluation(scene: Scene) {
// get fps
var fps = scene.getEngine().getFps();
if (fps <= this.frameToReach) {
}
}
}
// class to customize grade
export class grade {
// asset we need for dynamic loading by grade and distance if AssetGeolocalisation is enabled in gradingAsset class
public gradingAssets: Array<gradingAsset> = new Array();
// priority of grade
private _priority: number;
/**
* @param name : name of grade
* @param upGradingTask : task to do when this grade is enabled
* @param downGradingTask : task to do when this grade is desabled
* @param activeDynamicAssetsLoad : active dynamic loading
*/
constructor (public name: string, public upGradingTask: Function, public downGradingTask: Function, public activeDynamicGradingAssetsLoad: boolean = false) {
}
// add entire scene asset we need to show in scene for this grade
public addSceneGradingAsset(sceneGradingAsset: sceneGradingAsset) {
this.gradingAssets.push(sceneGradingAsset);
}
// add mesh grading asset we need to show in scene for this grade
public addMeshGradingAsset(meshGradingAsset: meshGradingAsset) {
this.gradingAssets.push(meshGradingAsset);
}
// export & split original file, by gradingAsset, in separate file ( usefull to generate file on node server )
public splitAsset(sceneAndMeshExtention: 'babylon' | 'gltf', textureExtention : 'webFormat' | 'GPUFormat', zipCompression? : boolean) {
}
// add asset to scene
private _upgradeAsset() {
}
// remove asset to scene
private _downgradeAsset() {
}
}
// exemple of mesh asset to load by grade and distance
export class meshGradingAsset {
// list of LOD meshes
public LODMeshes: Array<any>;
// list of LOD textures
public LODTextures: Array<any>;
// list of LOD animation > exemple : load light version with 12key/s then add all other key to make a 60key/s animation.
public LODAnimation: Array<any>;
/**
* @param name : name of asset
* @param url : link
* @param onloading : on loading callback
* @param onloaded : on loaded callback
* @param bundingBox : if dynamic load is actived on grade class, load this asset when BoundingBox is in frustrum of the camera.
* ps : not calculate on distance between center of two object because it's not the good way for big object. That's why we need a virtual box (BoundingBox)
* @param meshAssetGeolocalisation : list of all copy of this asset/
*/
constructor (public name: string, public url: string, onloading: Function, onloaded: Function, public bundingBox?: BoundingBox, public meshAssetGeolocalisation?: Array<duplicatedAssetGeolocalisation>) {
}
// add LOD animation
addLODAnimationAsset(url: string, extention: 'babylon' | 'gltf', distance: number, zipCompression? : boolean) {
}
// add LOD mesh version
addLODMesh(url: string, extention: 'babylon' | 'gltf', distance: number, zipCompression? : boolean) {
}
// add LOD texture version
addLODTextureAsset(url: string, extention: 'webFormat' | 'GPUFormat', distance: number, zipCompression? : boolean) {
}
}
// duplicate and place mesh or scene asset and apply transform.
export class duplicatedAssetGeolocalisation {
/**
* @param copyType : create an instance or clone
*/
constructor (public copyType : 'clone' | 'instance', public position: Vector3 = new Vector3(0, 0, 0), public rotation: Vector3 = new Vector3(1, 1, 1), public scale: Vector3 = new Vector3(1, 1, 1)) {
}
}
}