-
Notifications
You must be signed in to change notification settings - Fork 16
/
profiler.js
503 lines (481 loc) · 14.3 KB
/
profiler.js
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
const isBrowser = require('is-browser')
let canvas = null
let ctx2d = null
const W = 250
const H = 860
const M = 10
const LINE_H = 16
const FONT_H = 11
const FONT = FONT_H + 'px Droid Sans Mono, Andale Mono, monospace'
function ms(time) {
var f = Math.floor(time * 10) / 10
var s = '' + f
if (f % 1 === 0) s += '.0'
if (f < 10) s = ' ' + s
return s + ''
}
function pa3(f) {
if (f < 10) return ' ' + f
if (f < 100) return ' ' + f
return f
}
function prop(name) {
return function(o) {
return o[name]
}
}
function groupBy(fn, list) {
return list.reduce((acc, o) => {
var val = fn(o)
if (!acc[val]) {
acc[val] = []
}
acc[val].push(o)
return acc
}, {})
}
function createProfiler(ctx, renderer) {
const gl = ctx.gl
if (isBrowser && !canvas) {
canvas = document.createElement('canvas')
canvas.id = 'pex-renderer-profiler'
canvas.width = W * 2
canvas.height = H * 2
ctx.gl.canvas.parentElement.appendChild(canvas)
canvas.style.position = 'absolute'
canvas.style.width = W + 'px'
canvas.style.height = H + 'px'
canvas.style.top = M + 'px'
canvas.style.right = M + 'px'
canvas.style.zIndex = 1000
ctx2d = canvas.getContext('2d')
}
const profiler = {
canvas: canvas,
frame: 0,
flush: true,
measurements: {},
commands: [],
ctx2d: ctx2d,
bufferCount: 0,
totalBufferCount: 0,
textureCount: 0,
totalTextureCount: 0,
programCount: 0,
totalProgramCount: 0,
framebufferCount: 0,
totalFramebufferCount: 0,
bindTextureCount: 0,
useProgramCount: 0,
setUniformCount: 0,
trianglesCount: 0,
drawElementsCount: 0,
drawElementsInstancedCount: 0,
drawArraysCount: 0,
drawArraysInstancedCount: 0,
linesCount: 0,
time: function(label, gpu) {
if (this.flush) gl.finish()
if (this.flush) gl.flush()
let m = this.measurements[label]
if (!m) {
m = this.measurements[label] = {
begin: 0,
end: 0,
last: 0,
total: 0,
count: 0,
avg: 0,
max: 0
}
if (gpu) {
m.query = ctx.query()
}
}
this.measurements[label].start = window.performance
? window.performance.now()
: Date.now()
if (m.query && m.query.result) m.gpu = m.query.result / 1000000
if (m.query) ctx.beginQuery(m.query)
},
timeEnd: function(label) {
if (this.flush) gl.finish()
if (this.flush) gl.flush()
const m = this.measurements[label]
if (!m) {
return
}
m.end = window.performance ? window.performance.now() : Date.now()
m.last = m.end - m.start
m.total += m.last
m.max = Math.max(m.max, m.last)
m.count++
m.avg = (m.avg * 9 + m.last * 1) / 10
if (m.query) ctx.endQuery(m.query)
},
add: function(command, label) {
let callStack = null
try {
throw new Error('Call stack capture')
} catch (e) {
callStack = e.stack
}
this.commands.push({
command: command,
stack: callStack,
label: label
})
},
setFlush: function(state) {
this.flush = state
},
summary: function() {
var lines = []
const frameMeasurement = this.measurements['Frame']
if (frameMeasurement) {
lines.push(`FPS: ${(1000 / frameMeasurement.avg).toFixed(3)}`)
}
const frameRAFMeasurement = this.measurements['FrameRAF']
if (frameRAFMeasurement) {
lines.push(`FPS (RAF): ${(1000 / frameRAFMeasurement.avg).toFixed(3)}`)
}
lines.push('------')
lines = lines.concat(
Object.keys(this.measurements)
.sort((a, b) => {
return this.measurements[a].start - this.measurements[b].start
})
.map((label) => {
const m = this.measurements[label]
return `${label}: ${ms(m.avg)} ${
m.gpu ? ' / ' + (Math.floor(m.gpu * 10) / 10).toFixed(1) : ''
}`
})
)
var ctx = renderer._ctx
var textures = ctx.resources.filter((r) => r.class === 'texture')
var textureVRAM = 0
var texture2DByPixelFormat = groupBy(
prop('pixelFormat'),
textures.filter((tex) => tex.target === ctx.gl.TEXTURE_2D)
)
var textureCubeByPixelFormat = groupBy(
prop('pixelFormat'),
textures.filter((tex) => tex.target === ctx.gl.TEXTURE_CUBE_MAP)
)
textures.forEach((texture) => {
var bits = 8
var channels = 4
if (texture.pixelFormat === ctx.PixelFormat.RGBA32F) {
bits = 32
}
if (texture.pixelFormat === ctx.PixelFormat.RGBA16F) {
bits = 16
}
if (texture.pixelFormat === ctx.PixelFormat.Depth) {
bits = 24 // estimate
}
var bpp = (bits / 8) * channels
if (texture.target === ctx.gl.TEXTURE_2D) {
textureVRAM += texture.width * texture.height * bpp
} else if (texture.target === ctx.gl.TEXTURE_CUBE_MAP) {
textureVRAM += texture.width * texture.height * bpp * 6
}
})
lines.push('------')
lines.push(`Entities: ${pa3(renderer.entities.length)}`)
lines.push(
`Geometries: ${pa3(renderer.getComponents('Geometry').length)}`
)
lines.push(`Materials: ${pa3(renderer.getComponents('Material').length)}`)
lines.push(`Skins: ${pa3(renderer.getComponents('Skin').length)}`)
lines.push(
`Animations: ${pa3(renderer.getComponents('Animation').length)}`
)
lines.push(`Morphs: ${pa3(renderer.getComponents('Morph').length)}`)
lines.push(`Cameras: ${pa3(renderer.getComponents('Camera').length)}`)
lines.push(`Orbiters: ${pa3(renderer.getComponents('Orbiter').length)}`)
lines.push(
`Reflection Probes: ${pa3(
renderer.getComponents('ReflectionProbe').length
)}`
)
lines.push(`Skyboxes: ${pa3(renderer.getComponents('Skybox').length)}`)
lines.push(
`Ambient Lights: ${pa3(renderer.getComponents('AmbientLight').length)}`
)
lines.push(
`Point Lights: ${pa3(renderer.getComponents('PointLight').length)}`
)
lines.push(
`Directional Lights: ${pa3(
renderer.getComponents('DirectionalLight').length
)}`
)
lines.push(
`Spot Lights: ${pa3(renderer.getComponents('SpotLight').length)}`
)
lines.push(
`Area Lights: ${pa3(renderer.getComponents('AreaLight').length)}`
)
lines.push('------')
lines.push(
`Programs: ${pa3(
renderer._ctx.resources.filter((r) => r.class === 'program').length
)}`
)
lines.push(
`Passes: ${pa3(
renderer._ctx.resources.filter((r) => r.class === 'pass').length
)}`
)
lines.push(
`Pipelines: ${pa3(
renderer._ctx.resources.filter((r) => r.class === 'pipeline').length
)}`
)
lines.push(
`Textures 2D: ${pa3(
renderer._ctx.resources.filter(
(r) => r.class === 'texture' && r.target === ctx.gl.TEXTURE_2D
).length
)}`
)
Object.keys(texture2DByPixelFormat).forEach((format) => {
lines.push(
`${format.toUpperCase()}: ${pa3(
texture2DByPixelFormat[format].length
)}`
)
})
lines.push(
`Textures Cube: ${pa3(
renderer._ctx.resources.filter(
(r) => r.class === 'texture' && r.target === ctx.gl.TEXTURE_CUBE_MAP
).length
)}`
)
Object.keys(textureCubeByPixelFormat).forEach((format) => {
lines.push(
`${format.toUpperCase()}: ${pa3(
textureCubeByPixelFormat[format].length
)}`
)
})
lines.push(`Texture VRAM: ${(textureVRAM / (1024 * 1024)).toFixed(0)}MB`)
lines.push('------')
lines.push(
`Buffers: ${pa3(profiler.bufferCount)} / ${pa3(
profiler.totalBufferCount
)}`
)
lines.push(
`Textures: ${pa3(profiler.textureCount)} / ${pa3(
profiler.totalTextureCount
)}`
)
lines.push(
`Programs: ${pa3(profiler.programCount)} / ${pa3(
profiler.totalProgramCount
)}`
)
lines.push(
`FBOs: ${pa3(profiler.framebufferCount)} / ${pa3(
profiler.totalFramebufferCount
)}`
)
lines.push('------')
lines.push(`Lines: ${profiler.linesCount}`)
lines.push(`Triangles: ${profiler.trianglesCount}`)
lines.push(`Instanced Lines: ${profiler.instancedLinesCount}`)
lines.push(`Instanced Triangles: ${profiler.instancedTrianglesCount}`)
lines.push('------')
lines.push(`Bind Texture: ${pa3(profiler.bindTextureCount)}`)
lines.push(`Use Program: ${pa3(profiler.useProgramCount)}`)
lines.push(`Set Uniform: ${pa3(profiler.setUniformCount)}`)
lines.push(`Draw Elements : ${pa3(profiler.drawElementsCount)}`)
lines.push(
`Instanced Draw Elements: ${pa3(profiler.drawElementsInstancedCount)}`
)
lines.push(`Draw Arrays : ${pa3(profiler.drawArraysCount)}`)
lines.push(
`Instanced Draw Arrays: ${pa3(profiler.drawArraysInstancedCount)}`
)
lines.push('------')
lines = lines.concat(
this.commands.map((cmd) => {
// const cpu = cmd.command.stats.cpuTime / cmd.command.stats.count
// const gpu = cmd.command.stats.gpuTime / cmd.command.stats.count
// if (cmd.command.stats.count >= 30) {
// cmd.command.stats.gpuTime = 0
// cmd.command.stats.cpuTime = 0
// cmd.command.stats.count = 0
// }
// return `${cmd.label}: ${ms(cpu)} ${ms(gpu)}`
return `${cmd.label}: N/A`
})
)
return lines
},
setEnabled: function(state) {
if (isBrowser) {
canvas.style.display = state ? 'block' : 'none'
}
},
startFrame: function() {
this.timeEnd('FrameRAF')
this.time('FrameRAF')
this.time('Frame')
resetFrameStats()
},
endFrame: function() {
this.timeEnd('Frame')
draw()
}
}
function draw() {
profiler.frame++
if (!ctx2d) {
if (profiler.frame % 30 === 0) {
console.log('profiler', profiler.summary())
}
return
}
const lines = profiler.summary()
ctx2d.save()
ctx2d.scale(2, 2)
ctx2d.fillStyle = 'rgba(0, 0, 0, 0.5)'
ctx2d.clearRect(0, 0, canvas.width, canvas.height)
ctx2d.fillRect(0, 0, canvas.width, canvas.height)
ctx2d.font = FONT
ctx2d.fillStyle = '#FFF'
lines.forEach((line, index) => {
const w = ctx2d.measureText(line).width
ctx2d.fillText(line, W - M - w, M + FONT_H + LINE_H * index)
})
ctx2d.restore()
}
// function wrapRes (fn, counter) {
// const ctxFn = ctx[fn]
// ctx[fn] = function () {
// profiler[counter]++
// return ctxFn.apply(this, arguments)
// }
// }
// TODO:
// pipelines, passes, etc
// wrapRes('vertexBuffer', 'bufferCount')
// wrapRes('elementsBuffer', 'elementsCount')
// wrapRes('texture2D', 'text')
// wrapRes('cube', 'totalTextureCubeCount')
// wrapRes('framebuffer', 'totalFramebufferCount')
function wrapGLCall(fn, callback) {
const glFn = gl[fn]
gl[fn] = function() {
callback(arguments)
return glFn.apply(this, arguments)
}
}
// TODO
wrapGLCall('createBuffer', () => {
profiler.bufferCount++
profiler.totalBufferCount++
})
wrapGLCall('deleteBuffer', () => {
profiler.bufferCount--
})
wrapGLCall('createProgram', () => {
profiler.programCount++
profiler.totalProgramCount++
})
wrapGLCall('deleteProgram', () => {
profiler.programCount--
})
wrapGLCall('createTexture', () => {
profiler.textureCount++
profiler.totalTextureCount++
})
wrapGLCall('deleteTexture', () => {
profiler.textureCount--
})
wrapGLCall('createFramebuffer', () => {
profiler.framebufferCount++
profiler.totalFramebufferCount++
})
wrapGLCall('deleteFramebuffer', () => {
profiler.framebufferCount--
})
wrapGLCall('bindTexture', () => profiler.bindTextureCount++)
wrapGLCall('useProgram', () => profiler.useProgramCount++)
wrapGLCall('drawElements', (args) => {
const mode = args[0]
const count = args[1]
if (mode === gl.LINES) profiler.linesCount += count
if (mode === gl.TRIANGLES) profiler.trianglesCount += count
profiler.drawElementsCount++
})
wrapGLCall('drawArrays', (args) => {
const mode = args[0]
const count = args[2]
if (mode === gl.LINES) profiler.linesCount += count
if (mode === gl.TRIANGLES) profiler.trianglesCount += count
profiler.drawArraysCount++
})
for (let prop in gl) {
if (prop.indexOf('uniform') === 0) {
wrapGLCall(prop, () => profiler.setUniformCount++)
}
}
function wrapGLExtCall(ext, fn, callback) {
if (!ext) {
console.log('profiler', `Ext ${ext} it not available`)
return
}
const extFn = ext[fn]
ext[fn] = function() {
callback(arguments)
return extFn.apply(ext, arguments)
}
}
// TODO: what about webgl2?
wrapGLCall(
'drawElementsInstanced',
(args) => {
const mode = args[0]
const count = args[1]
const primcount = args[4]
if (mode === gl.LINES) profiler.instancedLinesCount += count * primcount // assuming divisor 1
if (mode === gl.TRIANGLES)
profiler.instancedTrianglesCount += count * primcount // assuming divisor 1
profiler.drawElementsInstancedCount++
}
)
wrapGLCall(
'drawArraysInstanced',
(args) => {
const mode = args[0]
const count = args[2]
const primcount = args[3]
if (mode === gl.LINES)
profiler['instancedLinesCount'] += count * primcount // assuming divisor 1
if (mode === gl.TRIANGLES)
profiler['instancedTrianglesCount'] += count * primcount // assuming divisor 1
profiler.drawArraysInstancedCount++
}
)
function resetFrameStats() {
profiler.bindTextureCount = 0
profiler.useProgramCount = 0
profiler.setUniformCount = 0
profiler.linesCount = 0
profiler.trianglesCount = 0
profiler.instancedLinesCount = 0
profiler.instancedTrianglesCount = 0
profiler.drawElementsCount = 0
profiler.drawElementsInstancedCount = 0
profiler.drawArraysCount = 0
profiler.drawArraysInstancedCount = 0
}
return profiler
}
module.exports = createProfiler