reze-engine 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.ts CHANGED
@@ -1,2527 +1,2544 @@
1
- import { Camera } from "./camera"
2
- import { Quat, Vec3 } from "./math"
3
- import { Model } from "./model"
4
- import { PmxLoader } from "./pmx-loader"
5
- import { Physics } from "./physics"
6
- import { VMDKeyFrame, VMDLoader } from "./vmd-loader"
7
-
8
- export type EngineOptions = {
9
- ambient?: number
10
- bloomIntensity?: number
11
- rimLightIntensity?: number
12
- cameraDistance?: number
13
- cameraTarget?: Vec3
14
- }
15
-
16
- export interface EngineStats {
17
- fps: number
18
- frameTime: number // ms
19
- gpuMemory: number // MB (estimated total GPU memory)
20
- }
21
-
22
- interface DrawCall {
23
- count: number
24
- firstIndex: number
25
- bindGroup: GPUBindGroup
26
- isTransparent: boolean
27
- }
28
-
29
- type BoneKeyFrame = {
30
- boneName: string
31
- time: number
32
- rotation: Quat
33
- }
34
-
35
- export class Engine {
36
- private canvas: HTMLCanvasElement
37
- private device!: GPUDevice
38
- private context!: GPUCanvasContext
39
- private presentationFormat!: GPUTextureFormat
40
- private camera!: Camera
41
- private cameraUniformBuffer!: GPUBuffer
42
- private cameraMatrixData = new Float32Array(36)
43
- private cameraDistance: number = 26.6
44
- private cameraTarget: Vec3 = new Vec3(0, 12.5, 0)
45
- private lightUniformBuffer!: GPUBuffer
46
- private lightData = new Float32Array(64)
47
- private lightCount = 0
48
- private vertexBuffer!: GPUBuffer
49
- private indexBuffer?: GPUBuffer
50
- private resizeObserver: ResizeObserver | null = null
51
- private depthTexture!: GPUTexture
52
- // Material rendering pipelines
53
- private modelPipeline!: GPURenderPipeline
54
- private eyePipeline!: GPURenderPipeline
55
- private hairPipelineOverEyes!: GPURenderPipeline
56
- private hairPipelineOverNonEyes!: GPURenderPipeline
57
- private hairDepthPipeline!: GPURenderPipeline
58
- // Outline pipelines
59
- private outlinePipeline!: GPURenderPipeline
60
- private hairOutlinePipeline!: GPURenderPipeline
61
- private mainBindGroupLayout!: GPUBindGroupLayout
62
- private outlineBindGroupLayout!: GPUBindGroupLayout
63
- private jointsBuffer!: GPUBuffer
64
- private weightsBuffer!: GPUBuffer
65
- private skinMatrixBuffer?: GPUBuffer
66
- private worldMatrixBuffer?: GPUBuffer
67
- private inverseBindMatrixBuffer?: GPUBuffer
68
- private skinMatrixComputePipeline?: GPUComputePipeline
69
- private skinMatrixComputeBindGroup?: GPUBindGroup
70
- private boneCountBuffer?: GPUBuffer
71
- private multisampleTexture!: GPUTexture
72
- private readonly sampleCount = 4
73
- private renderPassDescriptor!: GPURenderPassDescriptor
74
- // Constants
75
- private readonly STENCIL_EYE_VALUE = 1
76
- private readonly COMPUTE_WORKGROUP_SIZE = 64
77
- private readonly BLOOM_DOWNSCALE_FACTOR = 2
78
- // Ambient light settings
79
- private ambient: number = 1.0
80
- // Bloom post-processing textures
81
- private sceneRenderTexture!: GPUTexture
82
- private sceneRenderTextureView!: GPUTextureView
83
- private bloomExtractTexture!: GPUTexture
84
- private bloomBlurTexture1!: GPUTexture
85
- private bloomBlurTexture2!: GPUTexture
86
- // Post-processing pipelines
87
- private bloomExtractPipeline!: GPURenderPipeline
88
- private bloomBlurPipeline!: GPURenderPipeline
89
- private bloomComposePipeline!: GPURenderPipeline
90
- // Fullscreen quad for post-processing
91
- private fullscreenQuadBuffer!: GPUBuffer
92
- private blurDirectionBuffer!: GPUBuffer
93
- private bloomIntensityBuffer!: GPUBuffer
94
- private bloomThresholdBuffer!: GPUBuffer
95
- private linearSampler!: GPUSampler
96
- // Bloom bind groups (created once, reused every frame)
97
- private bloomExtractBindGroup?: GPUBindGroup
98
- private bloomBlurHBindGroup?: GPUBindGroup
99
- private bloomBlurVBindGroup?: GPUBindGroup
100
- private bloomComposeBindGroup?: GPUBindGroup
101
- // Bloom settings
102
- private bloomThreshold: number = 0.3
103
- private bloomIntensity: number = 0.12
104
- // Rim light settings
105
- private rimLightIntensity: number = 0.45
106
-
107
- private currentModel: Model | null = null
108
- private modelDir: string = ""
109
- private physics: Physics | null = null
110
- private materialSampler!: GPUSampler
111
- private textureCache = new Map<string, GPUTexture>()
112
- // Draw lists
113
- private opaqueDraws: DrawCall[] = []
114
- private eyeDraws: DrawCall[] = []
115
- private hairDrawsOverEyes: DrawCall[] = []
116
- private hairDrawsOverNonEyes: DrawCall[] = []
117
- private transparentDraws: DrawCall[] = []
118
- private opaqueOutlineDraws: DrawCall[] = []
119
- private eyeOutlineDraws: DrawCall[] = []
120
- private hairOutlineDraws: DrawCall[] = []
121
- private transparentOutlineDraws: DrawCall[] = []
122
-
123
- private lastFpsUpdate = performance.now()
124
- private framesSinceLastUpdate = 0
125
- private frameTimeSamples: number[] = []
126
- private frameTimeSum: number = 0
127
- private drawCallCount: number = 0
128
- private lastFrameTime = performance.now()
129
- private stats: EngineStats = {
130
- fps: 0,
131
- frameTime: 0,
132
- gpuMemory: 0,
133
- }
134
- private animationFrameId: number | null = null
135
- private renderLoopCallback: (() => void) | null = null
136
-
137
- private animationFrames: VMDKeyFrame[] = []
138
- private animationTimeouts: number[] = []
139
- private gpuMemoryMB: number = 0
140
- private hasAnimation = false // Set to true when loadAnimation is called
141
- private playingAnimation = false // Set to true when playAnimation is called
142
- private breathingTimeout: number | null = null
143
- private breathingBaseRotations: Map<string, Quat> = new Map()
144
-
145
- constructor(canvas: HTMLCanvasElement, options?: EngineOptions) {
146
- this.canvas = canvas
147
- if (options) {
148
- this.ambient = options.ambient ?? 1.0
149
- this.bloomIntensity = options.bloomIntensity ?? 0.12
150
- this.rimLightIntensity = options.rimLightIntensity ?? 0.45
151
- this.cameraDistance = options.cameraDistance ?? 26.6
152
- this.cameraTarget = options.cameraTarget ?? new Vec3(0, 12.5, 0)
153
- }
154
- }
155
-
156
- // Step 1: Get WebGPU device and context
157
- public async init() {
158
- const adapter = await navigator.gpu?.requestAdapter()
159
- const device = await adapter?.requestDevice()
160
- if (!device) {
161
- throw new Error("WebGPU is not supported in this browser.")
162
- }
163
- this.device = device
164
-
165
- const context = this.canvas.getContext("webgpu")
166
- if (!context) {
167
- throw new Error("Failed to get WebGPU context.")
168
- }
169
- this.context = context
170
-
171
- this.presentationFormat = navigator.gpu.getPreferredCanvasFormat()
172
-
173
- this.context.configure({
174
- device: this.device,
175
- format: this.presentationFormat,
176
- alphaMode: "premultiplied",
177
- })
178
-
179
- this.setupCamera()
180
- this.setupLighting()
181
- this.createPipelines()
182
- this.createFullscreenQuad()
183
- this.createBloomPipelines()
184
- this.setupResize()
185
- }
186
-
187
- private createPipelines() {
188
- this.materialSampler = this.device.createSampler({
189
- magFilter: "linear",
190
- minFilter: "linear",
191
- addressModeU: "repeat",
192
- addressModeV: "repeat",
193
- })
194
-
195
- const shaderModule = this.device.createShaderModule({
196
- label: "model shaders",
197
- code: /* wgsl */ `
198
- struct CameraUniforms {
199
- view: mat4x4f,
200
- projection: mat4x4f,
201
- viewPos: vec3f,
202
- _padding: f32,
203
- };
204
-
205
- struct Light {
206
- direction: vec3f,
207
- _padding1: f32,
208
- color: vec3f,
209
- intensity: f32,
210
- };
211
-
212
- struct LightUniforms {
213
- ambient: f32,
214
- lightCount: f32,
215
- _padding1: f32,
216
- _padding2: f32,
217
- lights: array<Light, 4>,
218
- };
219
-
220
- struct MaterialUniforms {
221
- alpha: f32,
222
- alphaMultiplier: f32,
223
- rimIntensity: f32,
224
- _padding1: f32,
225
- rimColor: vec3f,
226
- isOverEyes: f32, // 1.0 if rendering over eyes, 0.0 otherwise
227
- };
228
-
229
- struct VertexOutput {
230
- @builtin(position) position: vec4f,
231
- @location(0) normal: vec3f,
232
- @location(1) uv: vec2f,
233
- @location(2) worldPos: vec3f,
234
- };
235
-
236
- @group(0) @binding(0) var<uniform> camera: CameraUniforms;
237
- @group(0) @binding(1) var<uniform> light: LightUniforms;
238
- @group(0) @binding(2) var diffuseTexture: texture_2d<f32>;
239
- @group(0) @binding(3) var diffuseSampler: sampler;
240
- @group(0) @binding(4) var<storage, read> skinMats: array<mat4x4f>;
241
- @group(0) @binding(5) var toonTexture: texture_2d<f32>;
242
- @group(0) @binding(6) var toonSampler: sampler;
243
- @group(0) @binding(7) var<uniform> material: MaterialUniforms;
244
-
245
- @vertex fn vs(
246
- @location(0) position: vec3f,
247
- @location(1) normal: vec3f,
248
- @location(2) uv: vec2f,
249
- @location(3) joints0: vec4<u32>,
250
- @location(4) weights0: vec4<f32>
251
- ) -> VertexOutput {
252
- var output: VertexOutput;
253
- let pos4 = vec4f(position, 1.0);
254
-
255
- // Branchless weight normalization (avoids GPU branch divergence)
256
- let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
257
- let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
258
- let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
259
-
260
- var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
261
- var skinnedNrm = vec3f(0.0, 0.0, 0.0);
262
- for (var i = 0u; i < 4u; i++) {
263
- let j = joints0[i];
264
- let w = normalizedWeights[i];
265
- let m = skinMats[j];
266
- skinnedPos += (m * pos4) * w;
267
- let r3 = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz);
268
- skinnedNrm += (r3 * normal) * w;
269
- }
270
- let worldPos = skinnedPos.xyz;
271
- output.position = camera.projection * camera.view * vec4f(worldPos, 1.0);
272
- output.normal = normalize(skinnedNrm);
273
- output.uv = uv;
274
- output.worldPos = worldPos;
275
- return output;
276
- }
277
-
278
- @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
279
- // Early alpha test - discard before expensive calculations
280
- var finalAlpha = material.alpha * material.alphaMultiplier;
281
- if (material.isOverEyes > 0.5) {
282
- finalAlpha *= 0.5; // Hair over eyes gets 50% alpha
283
- }
284
- if (finalAlpha < 0.001) {
285
- discard;
286
- }
287
-
288
- let n = normalize(input.normal);
289
- let albedo = textureSample(diffuseTexture, diffuseSampler, input.uv).rgb;
290
-
291
- var lightAccum = vec3f(light.ambient);
292
- let numLights = u32(light.lightCount);
293
- for (var i = 0u; i < numLights; i++) {
294
- let l = -light.lights[i].direction;
295
- let nDotL = max(dot(n, l), 0.0);
296
- let toonUV = vec2f(nDotL, 0.5);
297
- let toonFactor = textureSample(toonTexture, toonSampler, toonUV).rgb;
298
- let radiance = light.lights[i].color * light.lights[i].intensity;
299
- lightAccum += toonFactor * radiance * nDotL;
300
- }
301
-
302
- // Rim light calculation
303
- let viewDir = normalize(camera.viewPos - input.worldPos);
304
- var rimFactor = 1.0 - max(dot(n, viewDir), 0.0);
305
- rimFactor = rimFactor * rimFactor; // Optimized: direct multiply instead of pow(x, 2.0)
306
- let rimLight = material.rimColor * material.rimIntensity * rimFactor;
307
-
308
- let color = albedo * lightAccum + rimLight;
309
-
310
- return vec4f(color, finalAlpha);
311
- }
312
- `,
313
- })
314
-
315
- // Create explicit bind group layout for all pipelines using the main shader
316
- this.mainBindGroupLayout = this.device.createBindGroupLayout({
317
- label: "main material bind group layout",
318
- entries: [
319
- { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // camera
320
- { binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // light
321
- { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: {} }, // diffuseTexture
322
- { binding: 3, visibility: GPUShaderStage.FRAGMENT, sampler: {} }, // diffuseSampler
323
- { binding: 4, visibility: GPUShaderStage.VERTEX, buffer: { type: "read-only-storage" } }, // skinMats
324
- { binding: 5, visibility: GPUShaderStage.FRAGMENT, texture: {} }, // toonTexture
325
- { binding: 6, visibility: GPUShaderStage.FRAGMENT, sampler: {} }, // toonSampler
326
- { binding: 7, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // material
327
- ],
328
- })
329
-
330
- const mainPipelineLayout = this.device.createPipelineLayout({
331
- label: "main pipeline layout",
332
- bindGroupLayouts: [this.mainBindGroupLayout],
333
- })
334
-
335
- this.modelPipeline = this.device.createRenderPipeline({
336
- label: "model pipeline",
337
- layout: mainPipelineLayout,
338
- vertex: {
339
- module: shaderModule,
340
- buffers: [
341
- {
342
- arrayStride: 8 * 4,
343
- attributes: [
344
- { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
345
- { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
346
- { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
347
- ],
348
- },
349
- {
350
- arrayStride: 4 * 2,
351
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
352
- },
353
- {
354
- arrayStride: 4,
355
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
356
- },
357
- ],
358
- },
359
- fragment: {
360
- module: shaderModule,
361
- targets: [
362
- {
363
- format: this.presentationFormat,
364
- blend: {
365
- color: {
366
- srcFactor: "src-alpha",
367
- dstFactor: "one-minus-src-alpha",
368
- operation: "add",
369
- },
370
- alpha: {
371
- srcFactor: "one",
372
- dstFactor: "one-minus-src-alpha",
373
- operation: "add",
374
- },
375
- },
376
- },
377
- ],
378
- },
379
- primitive: { cullMode: "none" },
380
- depthStencil: {
381
- format: "depth24plus-stencil8",
382
- depthWriteEnabled: true,
383
- depthCompare: "less-equal",
384
- },
385
- multisample: {
386
- count: this.sampleCount,
387
- },
388
- })
389
-
390
- // Create bind group layout for outline pipelines
391
- this.outlineBindGroupLayout = this.device.createBindGroupLayout({
392
- label: "outline bind group layout",
393
- entries: [
394
- { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // camera
395
- { binding: 1, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // material
396
- { binding: 2, visibility: GPUShaderStage.VERTEX, buffer: { type: "read-only-storage" } }, // skinMats
397
- ],
398
- })
399
-
400
- const outlinePipelineLayout = this.device.createPipelineLayout({
401
- label: "outline pipeline layout",
402
- bindGroupLayouts: [this.outlineBindGroupLayout],
403
- })
404
-
405
- const outlineShaderModule = this.device.createShaderModule({
406
- label: "outline shaders",
407
- code: /* wgsl */ `
408
- struct CameraUniforms {
409
- view: mat4x4f,
410
- projection: mat4x4f,
411
- viewPos: vec3f,
412
- _padding: f32,
413
- };
414
-
415
- struct MaterialUniforms {
416
- edgeColor: vec4f,
417
- edgeSize: f32,
418
- isOverEyes: f32, // 1.0 if rendering over eyes, 0.0 otherwise (for hair outlines)
419
- _padding1: f32,
420
- _padding2: f32,
421
- };
422
-
423
- @group(0) @binding(0) var<uniform> camera: CameraUniforms;
424
- @group(0) @binding(1) var<uniform> material: MaterialUniforms;
425
- @group(0) @binding(2) var<storage, read> skinMats: array<mat4x4f>;
426
-
427
- struct VertexOutput {
428
- @builtin(position) position: vec4f,
429
- };
430
-
431
- @vertex fn vs(
432
- @location(0) position: vec3f,
433
- @location(1) normal: vec3f,
434
- @location(3) joints0: vec4<u32>,
435
- @location(4) weights0: vec4<f32>
436
- ) -> VertexOutput {
437
- var output: VertexOutput;
438
- let pos4 = vec4f(position, 1.0);
439
-
440
- // Branchless weight normalization (avoids GPU branch divergence)
441
- let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
442
- let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
443
- let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
444
-
445
- var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
446
- var skinnedNrm = vec3f(0.0, 0.0, 0.0);
447
- for (var i = 0u; i < 4u; i++) {
448
- let j = joints0[i];
449
- let w = normalizedWeights[i];
450
- let m = skinMats[j];
451
- skinnedPos += (m * pos4) * w;
452
- let r3 = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz);
453
- skinnedNrm += (r3 * normal) * w;
454
- }
455
- let worldPos = skinnedPos.xyz;
456
- let worldNormal = normalize(skinnedNrm);
457
-
458
- // MMD invert hull: expand vertices outward along normals
459
- let scaleFactor = 0.01;
460
- let expandedPos = worldPos + worldNormal * material.edgeSize * scaleFactor;
461
- output.position = camera.projection * camera.view * vec4f(expandedPos, 1.0);
462
- return output;
463
- }
464
-
465
- @fragment fn fs() -> @location(0) vec4f {
466
- var color = material.edgeColor;
467
-
468
- if (material.isOverEyes > 0.5) {
469
- color.a *= 0.5; // Hair outlines over eyes get 50% alpha
470
- }
471
-
472
- return color;
473
- }
474
- `,
475
- })
476
-
477
- this.outlinePipeline = this.device.createRenderPipeline({
478
- label: "outline pipeline",
479
- layout: outlinePipelineLayout,
480
- vertex: {
481
- module: outlineShaderModule,
482
- buffers: [
483
- {
484
- arrayStride: 8 * 4,
485
- attributes: [
486
- {
487
- shaderLocation: 0,
488
- offset: 0,
489
- format: "float32x3" as GPUVertexFormat,
490
- },
491
- {
492
- shaderLocation: 1,
493
- offset: 3 * 4,
494
- format: "float32x3" as GPUVertexFormat,
495
- },
496
- ],
497
- },
498
- {
499
- arrayStride: 4 * 2,
500
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
501
- },
502
- {
503
- arrayStride: 4,
504
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
505
- },
506
- ],
507
- },
508
- fragment: {
509
- module: outlineShaderModule,
510
- targets: [
511
- {
512
- format: this.presentationFormat,
513
- blend: {
514
- color: {
515
- srcFactor: "src-alpha",
516
- dstFactor: "one-minus-src-alpha",
517
- operation: "add",
518
- },
519
- alpha: {
520
- srcFactor: "one",
521
- dstFactor: "one-minus-src-alpha",
522
- operation: "add",
523
- },
524
- },
525
- },
526
- ],
527
- },
528
- primitive: {
529
- cullMode: "back",
530
- },
531
- depthStencil: {
532
- format: "depth24plus-stencil8",
533
- depthWriteEnabled: true,
534
- depthCompare: "less-equal",
535
- },
536
- multisample: {
537
- count: this.sampleCount,
538
- },
539
- })
540
-
541
- // Hair outline pipeline
542
- this.hairOutlinePipeline = this.device.createRenderPipeline({
543
- label: "hair outline pipeline",
544
- layout: outlinePipelineLayout,
545
- vertex: {
546
- module: outlineShaderModule,
547
- buffers: [
548
- {
549
- arrayStride: 8 * 4,
550
- attributes: [
551
- {
552
- shaderLocation: 0,
553
- offset: 0,
554
- format: "float32x3" as GPUVertexFormat,
555
- },
556
- {
557
- shaderLocation: 1,
558
- offset: 3 * 4,
559
- format: "float32x3" as GPUVertexFormat,
560
- },
561
- ],
562
- },
563
- {
564
- arrayStride: 4 * 2,
565
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
566
- },
567
- {
568
- arrayStride: 4,
569
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
570
- },
571
- ],
572
- },
573
- fragment: {
574
- module: outlineShaderModule,
575
- targets: [
576
- {
577
- format: this.presentationFormat,
578
- blend: {
579
- color: {
580
- srcFactor: "src-alpha",
581
- dstFactor: "one-minus-src-alpha",
582
- operation: "add",
583
- },
584
- alpha: {
585
- srcFactor: "one",
586
- dstFactor: "one-minus-src-alpha",
587
- operation: "add",
588
- },
589
- },
590
- },
591
- ],
592
- },
593
- primitive: {
594
- cullMode: "back",
595
- },
596
- depthStencil: {
597
- format: "depth24plus-stencil8",
598
- depthWriteEnabled: false, // Don't write depth - let hair geometry control depth
599
- depthCompare: "less-equal", // Only draw where hair depth exists (no stencil test needed)
600
- depthBias: -0.0001, // Small negative bias to bring outline slightly closer for depth test
601
- depthBiasSlopeScale: 0.0,
602
- depthBiasClamp: 0.0,
603
- },
604
- multisample: {
605
- count: this.sampleCount,
606
- },
607
- })
608
-
609
- // Eye overlay pipeline (renders after opaque, writes stencil)
610
- this.eyePipeline = this.device.createRenderPipeline({
611
- label: "eye overlay pipeline",
612
- layout: mainPipelineLayout,
613
- vertex: {
614
- module: shaderModule,
615
- buffers: [
616
- {
617
- arrayStride: 8 * 4,
618
- attributes: [
619
- { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
620
- { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
621
- { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
622
- ],
623
- },
624
- {
625
- arrayStride: 4 * 2,
626
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
627
- },
628
- {
629
- arrayStride: 4,
630
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
631
- },
632
- ],
633
- },
634
- fragment: {
635
- module: shaderModule,
636
- targets: [
637
- {
638
- format: this.presentationFormat,
639
- blend: {
640
- color: {
641
- srcFactor: "src-alpha",
642
- dstFactor: "one-minus-src-alpha",
643
- operation: "add",
644
- },
645
- alpha: {
646
- srcFactor: "one",
647
- dstFactor: "one-minus-src-alpha",
648
- operation: "add",
649
- },
650
- },
651
- },
652
- ],
653
- },
654
- primitive: { cullMode: "front" },
655
- depthStencil: {
656
- format: "depth24plus-stencil8",
657
- depthWriteEnabled: true, // Write depth to occlude back of head
658
- depthCompare: "less-equal", // More lenient to reduce precision conflicts
659
- depthBias: -0.00005, // Reduced bias to minimize conflicts while still occluding back face
660
- depthBiasSlopeScale: 0.0,
661
- depthBiasClamp: 0.0,
662
- stencilFront: {
663
- compare: "always",
664
- failOp: "keep",
665
- depthFailOp: "keep",
666
- passOp: "replace", // Write stencil value 1
667
- },
668
- stencilBack: {
669
- compare: "always",
670
- failOp: "keep",
671
- depthFailOp: "keep",
672
- passOp: "replace",
673
- },
674
- },
675
- multisample: { count: this.sampleCount },
676
- })
677
-
678
- // Depth-only shader for hair pre-pass (reduces overdraw by early depth rejection)
679
- const depthOnlyShaderModule = this.device.createShaderModule({
680
- label: "depth only shader",
681
- code: /* wgsl */ `
682
- struct CameraUniforms {
683
- view: mat4x4f,
684
- projection: mat4x4f,
685
- viewPos: vec3f,
686
- _padding: f32,
687
- };
688
-
689
- @group(0) @binding(0) var<uniform> camera: CameraUniforms;
690
- @group(0) @binding(4) var<storage, read> skinMats: array<mat4x4f>;
691
-
692
- @vertex fn vs(
693
- @location(0) position: vec3f,
694
- @location(1) normal: vec3f,
695
- @location(3) joints0: vec4<u32>,
696
- @location(4) weights0: vec4<f32>
697
- ) -> @builtin(position) vec4f {
698
- let pos4 = vec4f(position, 1.0);
699
-
700
- // Branchless weight normalization (avoids GPU branch divergence)
701
- let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
702
- let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
703
- let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
704
-
705
- var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
706
- for (var i = 0u; i < 4u; i++) {
707
- let j = joints0[i];
708
- let w = normalizedWeights[i];
709
- let m = skinMats[j];
710
- skinnedPos += (m * pos4) * w;
711
- }
712
- let worldPos = skinnedPos.xyz;
713
- let clipPos = camera.projection * camera.view * vec4f(worldPos, 1.0);
714
- return clipPos;
715
- }
716
-
717
- @fragment fn fs() -> @location(0) vec4f {
718
- return vec4f(0.0, 0.0, 0.0, 0.0); // Transparent - color writes disabled via writeMask
719
- }
720
- `,
721
- })
722
-
723
- // Hair depth pre-pass pipeline: depth-only with color writes disabled to eliminate overdraw
724
- this.hairDepthPipeline = this.device.createRenderPipeline({
725
- label: "hair depth pre-pass",
726
- layout: mainPipelineLayout,
727
- vertex: {
728
- module: depthOnlyShaderModule,
729
- buffers: [
730
- {
731
- arrayStride: 8 * 4,
732
- attributes: [
733
- { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
734
- { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
735
- ],
736
- },
737
- {
738
- arrayStride: 4 * 2,
739
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
740
- },
741
- {
742
- arrayStride: 4,
743
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
744
- },
745
- ],
746
- },
747
- fragment: {
748
- module: depthOnlyShaderModule,
749
- entryPoint: "fs",
750
- targets: [
751
- {
752
- format: this.presentationFormat,
753
- writeMask: 0, // Disable all color writes - we only care about depth
754
- },
755
- ],
756
- },
757
- primitive: { cullMode: "front" },
758
- depthStencil: {
759
- format: "depth24plus-stencil8",
760
- depthWriteEnabled: true,
761
- depthCompare: "less-equal", // Match the color pass compare mode for consistency
762
- depthBias: 0.0,
763
- depthBiasSlopeScale: 0.0,
764
- depthBiasClamp: 0.0,
765
- },
766
- multisample: { count: this.sampleCount },
767
- })
768
-
769
- // Hair pipeline for rendering over eyes (stencil == 1)
770
- this.hairPipelineOverEyes = this.device.createRenderPipeline({
771
- label: "hair pipeline (over eyes)",
772
- layout: mainPipelineLayout,
773
- vertex: {
774
- module: shaderModule,
775
- buffers: [
776
- {
777
- arrayStride: 8 * 4,
778
- attributes: [
779
- { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
780
- { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
781
- { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
782
- ],
783
- },
784
- {
785
- arrayStride: 4 * 2,
786
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
787
- },
788
- {
789
- arrayStride: 4,
790
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
791
- },
792
- ],
793
- },
794
- fragment: {
795
- module: shaderModule,
796
- targets: [
797
- {
798
- format: this.presentationFormat,
799
- blend: {
800
- color: {
801
- srcFactor: "src-alpha",
802
- dstFactor: "one-minus-src-alpha",
803
- operation: "add",
804
- },
805
- alpha: {
806
- srcFactor: "one",
807
- dstFactor: "one-minus-src-alpha",
808
- operation: "add",
809
- },
810
- },
811
- },
812
- ],
813
- },
814
- primitive: { cullMode: "front" },
815
- depthStencil: {
816
- format: "depth24plus-stencil8",
817
- depthWriteEnabled: false, // Don't write depth (already written in pre-pass)
818
- depthCompare: "less-equal", // More lenient than "equal" to avoid precision issues with MSAA
819
- stencilFront: {
820
- compare: "equal", // Only render where stencil == 1 (over eyes)
821
- failOp: "keep",
822
- depthFailOp: "keep",
823
- passOp: "keep",
824
- },
825
- stencilBack: {
826
- compare: "equal",
827
- failOp: "keep",
828
- depthFailOp: "keep",
829
- passOp: "keep",
830
- },
831
- },
832
- multisample: { count: this.sampleCount },
833
- })
834
-
835
- // Hair pipeline for rendering over non-eyes (stencil != 1)
836
- this.hairPipelineOverNonEyes = this.device.createRenderPipeline({
837
- label: "hair pipeline (over non-eyes)",
838
- layout: mainPipelineLayout,
839
- vertex: {
840
- module: shaderModule,
841
- buffers: [
842
- {
843
- arrayStride: 8 * 4,
844
- attributes: [
845
- { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
846
- { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
847
- { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
848
- ],
849
- },
850
- {
851
- arrayStride: 4 * 2,
852
- attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
853
- },
854
- {
855
- arrayStride: 4,
856
- attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
857
- },
858
- ],
859
- },
860
- fragment: {
861
- module: shaderModule,
862
- targets: [
863
- {
864
- format: this.presentationFormat,
865
- blend: {
866
- color: {
867
- srcFactor: "src-alpha",
868
- dstFactor: "one-minus-src-alpha",
869
- operation: "add",
870
- },
871
- alpha: {
872
- srcFactor: "one",
873
- dstFactor: "one-minus-src-alpha",
874
- operation: "add",
875
- },
876
- },
877
- },
878
- ],
879
- },
880
- primitive: { cullMode: "front" },
881
- depthStencil: {
882
- format: "depth24plus-stencil8",
883
- depthWriteEnabled: false, // Don't write depth (already written in pre-pass)
884
- depthCompare: "less-equal", // More lenient than "equal" to avoid precision issues with MSAA
885
- stencilFront: {
886
- compare: "not-equal", // Only render where stencil != 1 (over non-eyes)
887
- failOp: "keep",
888
- depthFailOp: "keep",
889
- passOp: "keep",
890
- },
891
- stencilBack: {
892
- compare: "not-equal",
893
- failOp: "keep",
894
- depthFailOp: "keep",
895
- passOp: "keep",
896
- },
897
- },
898
- multisample: { count: this.sampleCount },
899
- })
900
- }
901
-
902
- // Create compute shader for skin matrix computation
903
- private createSkinMatrixComputePipeline() {
904
- const computeShader = this.device.createShaderModule({
905
- label: "skin matrix compute",
906
- code: /* wgsl */ `
907
- struct BoneCountUniform {
908
- count: u32,
909
- _padding1: u32,
910
- _padding2: u32,
911
- _padding3: u32,
912
- _padding4: vec4<u32>,
913
- };
914
-
915
- @group(0) @binding(0) var<uniform> boneCount: BoneCountUniform;
916
- @group(0) @binding(1) var<storage, read> worldMatrices: array<mat4x4f>;
917
- @group(0) @binding(2) var<storage, read> inverseBindMatrices: array<mat4x4f>;
918
- @group(0) @binding(3) var<storage, read_write> skinMatrices: array<mat4x4f>;
919
-
920
- @compute @workgroup_size(64) // Must match COMPUTE_WORKGROUP_SIZE
921
- fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
922
- let boneIndex = globalId.x;
923
- if (boneIndex >= boneCount.count) {
924
- return;
925
- }
926
- let worldMat = worldMatrices[boneIndex];
927
- let invBindMat = inverseBindMatrices[boneIndex];
928
- skinMatrices[boneIndex] = worldMat * invBindMat;
929
- }
930
- `,
931
- })
932
-
933
- this.skinMatrixComputePipeline = this.device.createComputePipeline({
934
- label: "skin matrix compute pipeline",
935
- layout: "auto",
936
- compute: {
937
- module: computeShader,
938
- },
939
- })
940
- }
941
-
942
- // Create fullscreen quad for post-processing
943
- private createFullscreenQuad() {
944
- // Fullscreen quad vertices: two triangles covering the entire screen - Format: position (x, y), uv (u, v)
945
- const quadVertices = new Float32Array([
946
- // Triangle 1
947
- -1.0,
948
- -1.0,
949
- 0.0,
950
- 0.0, // bottom-left
951
- 1.0,
952
- -1.0,
953
- 1.0,
954
- 0.0, // bottom-right
955
- -1.0,
956
- 1.0,
957
- 0.0,
958
- 1.0, // top-left
959
- // Triangle 2
960
- -1.0,
961
- 1.0,
962
- 0.0,
963
- 1.0, // top-left
964
- 1.0,
965
- -1.0,
966
- 1.0,
967
- 0.0, // bottom-right
968
- 1.0,
969
- 1.0,
970
- 1.0,
971
- 1.0, // top-right
972
- ])
973
-
974
- this.fullscreenQuadBuffer = this.device.createBuffer({
975
- label: "fullscreen quad",
976
- size: quadVertices.byteLength,
977
- usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
978
- })
979
- this.device.queue.writeBuffer(this.fullscreenQuadBuffer, 0, quadVertices)
980
- }
981
-
982
- // Create bloom post-processing pipelines
983
- private createBloomPipelines() {
984
- // Bloom extraction shader (extracts bright areas)
985
- const bloomExtractShader = this.device.createShaderModule({
986
- label: "bloom extract",
987
- code: /* wgsl */ `
988
- struct VertexOutput {
989
- @builtin(position) position: vec4f,
990
- @location(0) uv: vec2f,
991
- };
992
-
993
- @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
994
- var output: VertexOutput;
995
- // Generate fullscreen quad from vertex index
996
- let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
997
- let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
998
- output.position = vec4f(x, y, 0.0, 1.0);
999
- output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1000
- return output;
1001
- }
1002
-
1003
- struct BloomExtractUniforms {
1004
- threshold: f32,
1005
- _padding1: f32,
1006
- _padding2: f32,
1007
- _padding3: f32,
1008
- _padding4: f32,
1009
- _padding5: f32,
1010
- _padding6: f32,
1011
- _padding7: f32,
1012
- };
1013
-
1014
- @group(0) @binding(0) var inputTexture: texture_2d<f32>;
1015
- @group(0) @binding(1) var inputSampler: sampler;
1016
- @group(0) @binding(2) var<uniform> extractUniforms: BloomExtractUniforms;
1017
-
1018
- @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1019
- let color = textureSample(inputTexture, inputSampler, input.uv);
1020
- // Extract bright areas above threshold
1021
- let threshold = extractUniforms.threshold;
1022
- let bloom = max(vec3f(0.0), color.rgb - vec3f(threshold)) / max(0.001, 1.0 - threshold);
1023
- return vec4f(bloom, color.a);
1024
- }
1025
- `,
1026
- })
1027
-
1028
- // Bloom blur shader (gaussian blur - can be used for both horizontal and vertical)
1029
- const bloomBlurShader = this.device.createShaderModule({
1030
- label: "bloom blur",
1031
- code: /* wgsl */ `
1032
- struct VertexOutput {
1033
- @builtin(position) position: vec4f,
1034
- @location(0) uv: vec2f,
1035
- };
1036
-
1037
- @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
1038
- var output: VertexOutput;
1039
- let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
1040
- let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
1041
- output.position = vec4f(x, y, 0.0, 1.0);
1042
- output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1043
- return output;
1044
- }
1045
-
1046
- struct BlurUniforms {
1047
- direction: vec2f,
1048
- _padding1: f32,
1049
- _padding2: f32,
1050
- _padding3: f32,
1051
- _padding4: f32,
1052
- _padding5: f32,
1053
- _padding6: f32,
1054
- };
1055
-
1056
- @group(0) @binding(0) var inputTexture: texture_2d<f32>;
1057
- @group(0) @binding(1) var inputSampler: sampler;
1058
- @group(0) @binding(2) var<uniform> blurUniforms: BlurUniforms;
1059
-
1060
- // 3-tap gaussian blur using bilinear filtering trick (40% fewer texture fetches!)
1061
- @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1062
- let texelSize = 1.0 / vec2f(textureDimensions(inputTexture));
1063
-
1064
- // Bilinear optimization: leverage hardware filtering to sample between pixels
1065
- // Original 5-tap: weights [0.06136, 0.24477, 0.38774, 0.24477, 0.06136] at offsets [-2, -1, 0, 1, 2]
1066
- // Optimized 3-tap: combine adjacent samples using weighted offsets
1067
- let weight0 = 0.38774; // Center sample
1068
- let weight1 = 0.24477 + 0.06136; // Combined outer samples = 0.30613
1069
- let offset1 = (0.24477 * 1.0 + 0.06136 * 2.0) / weight1; // Weighted position = 1.2
1070
-
1071
- var result = textureSample(inputTexture, inputSampler, input.uv) * weight0;
1072
- let offsetVec = offset1 * texelSize * blurUniforms.direction;
1073
- result += textureSample(inputTexture, inputSampler, input.uv + offsetVec) * weight1;
1074
- result += textureSample(inputTexture, inputSampler, input.uv - offsetVec) * weight1;
1075
-
1076
- return result;
1077
- }
1078
- `,
1079
- })
1080
-
1081
- // Bloom composition shader (combines original scene with bloom)
1082
- const bloomComposeShader = this.device.createShaderModule({
1083
- label: "bloom compose",
1084
- code: /* wgsl */ `
1085
- struct VertexOutput {
1086
- @builtin(position) position: vec4f,
1087
- @location(0) uv: vec2f,
1088
- };
1089
-
1090
- @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
1091
- var output: VertexOutput;
1092
- let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
1093
- let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
1094
- output.position = vec4f(x, y, 0.0, 1.0);
1095
- output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1096
- return output;
1097
- }
1098
-
1099
- struct BloomComposeUniforms {
1100
- intensity: f32,
1101
- _padding1: f32,
1102
- _padding2: f32,
1103
- _padding3: f32,
1104
- _padding4: f32,
1105
- _padding5: f32,
1106
- _padding6: f32,
1107
- _padding7: f32,
1108
- };
1109
-
1110
- @group(0) @binding(0) var sceneTexture: texture_2d<f32>;
1111
- @group(0) @binding(1) var sceneSampler: sampler;
1112
- @group(0) @binding(2) var bloomTexture: texture_2d<f32>;
1113
- @group(0) @binding(3) var bloomSampler: sampler;
1114
- @group(0) @binding(4) var<uniform> composeUniforms: BloomComposeUniforms;
1115
-
1116
- @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1117
- let scene = textureSample(sceneTexture, sceneSampler, input.uv);
1118
- let bloom = textureSample(bloomTexture, bloomSampler, input.uv);
1119
- // Additive blending with intensity control
1120
- let result = scene.rgb + bloom.rgb * composeUniforms.intensity;
1121
- return vec4f(result, scene.a);
1122
- }
1123
- `,
1124
- })
1125
-
1126
- // Create uniform buffer for blur direction (minimum 32 bytes for WebGPU)
1127
- const blurDirectionBuffer = this.device.createBuffer({
1128
- label: "blur direction",
1129
- size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1130
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1131
- })
1132
-
1133
- // Create uniform buffer for bloom intensity (minimum 32 bytes for WebGPU)
1134
- const bloomIntensityBuffer = this.device.createBuffer({
1135
- label: "bloom intensity",
1136
- size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1137
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1138
- })
1139
-
1140
- // Create uniform buffer for bloom threshold (minimum 32 bytes for WebGPU)
1141
- const bloomThresholdBuffer = this.device.createBuffer({
1142
- label: "bloom threshold",
1143
- size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1144
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1145
- })
1146
-
1147
- // Set default bloom values
1148
- const intensityData = new Float32Array(8) // f32 + 7 padding floats = 8 floats = 32 bytes
1149
- intensityData[0] = this.bloomIntensity
1150
- this.device.queue.writeBuffer(bloomIntensityBuffer, 0, intensityData)
1151
-
1152
- const thresholdData = new Float32Array(8) // f32 + 7 padding floats = 8 floats = 32 bytes
1153
- thresholdData[0] = this.bloomThreshold
1154
- this.device.queue.writeBuffer(bloomThresholdBuffer, 0, thresholdData)
1155
-
1156
- // Create linear sampler for post-processing
1157
- const linearSampler = this.device.createSampler({
1158
- magFilter: "linear",
1159
- minFilter: "linear",
1160
- addressModeU: "clamp-to-edge",
1161
- addressModeV: "clamp-to-edge",
1162
- })
1163
-
1164
- // Bloom extraction pipeline
1165
- this.bloomExtractPipeline = this.device.createRenderPipeline({
1166
- label: "bloom extract",
1167
- layout: "auto",
1168
- vertex: {
1169
- module: bloomExtractShader,
1170
- entryPoint: "vs",
1171
- },
1172
- fragment: {
1173
- module: bloomExtractShader,
1174
- entryPoint: "fs",
1175
- targets: [{ format: this.presentationFormat }],
1176
- },
1177
- primitive: { topology: "triangle-list" },
1178
- })
1179
-
1180
- // Bloom blur pipeline
1181
- this.bloomBlurPipeline = this.device.createRenderPipeline({
1182
- label: "bloom blur",
1183
- layout: "auto",
1184
- vertex: {
1185
- module: bloomBlurShader,
1186
- entryPoint: "vs",
1187
- },
1188
- fragment: {
1189
- module: bloomBlurShader,
1190
- entryPoint: "fs",
1191
- targets: [{ format: this.presentationFormat }],
1192
- },
1193
- primitive: { topology: "triangle-list" },
1194
- })
1195
-
1196
- // Bloom composition pipeline
1197
- this.bloomComposePipeline = this.device.createRenderPipeline({
1198
- label: "bloom compose",
1199
- layout: "auto",
1200
- vertex: {
1201
- module: bloomComposeShader,
1202
- entryPoint: "vs",
1203
- },
1204
- fragment: {
1205
- module: bloomComposeShader,
1206
- entryPoint: "fs",
1207
- targets: [{ format: this.presentationFormat }],
1208
- },
1209
- primitive: { topology: "triangle-list" },
1210
- })
1211
-
1212
- // Store buffers and sampler for later use
1213
- this.blurDirectionBuffer = blurDirectionBuffer
1214
- this.bloomIntensityBuffer = bloomIntensityBuffer
1215
- this.bloomThresholdBuffer = bloomThresholdBuffer
1216
- this.linearSampler = linearSampler
1217
- }
1218
-
1219
- private setupBloom(width: number, height: number) {
1220
- const bloomWidth = Math.floor(width / this.BLOOM_DOWNSCALE_FACTOR)
1221
- const bloomHeight = Math.floor(height / this.BLOOM_DOWNSCALE_FACTOR)
1222
- this.bloomExtractTexture = this.device.createTexture({
1223
- label: "bloom extract",
1224
- size: [bloomWidth, bloomHeight],
1225
- format: this.presentationFormat,
1226
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1227
- })
1228
- this.bloomBlurTexture1 = this.device.createTexture({
1229
- label: "bloom blur 1",
1230
- size: [bloomWidth, bloomHeight],
1231
- format: this.presentationFormat,
1232
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1233
- })
1234
- this.bloomBlurTexture2 = this.device.createTexture({
1235
- label: "bloom blur 2",
1236
- size: [bloomWidth, bloomHeight],
1237
- format: this.presentationFormat,
1238
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1239
- })
1240
-
1241
- // Create bloom bind groups
1242
- this.bloomExtractBindGroup = this.device.createBindGroup({
1243
- layout: this.bloomExtractPipeline.getBindGroupLayout(0),
1244
- entries: [
1245
- { binding: 0, resource: this.sceneRenderTexture.createView() },
1246
- { binding: 1, resource: this.linearSampler },
1247
- { binding: 2, resource: { buffer: this.bloomThresholdBuffer } },
1248
- ],
1249
- })
1250
-
1251
- this.bloomBlurHBindGroup = this.device.createBindGroup({
1252
- layout: this.bloomBlurPipeline.getBindGroupLayout(0),
1253
- entries: [
1254
- { binding: 0, resource: this.bloomExtractTexture.createView() },
1255
- { binding: 1, resource: this.linearSampler },
1256
- { binding: 2, resource: { buffer: this.blurDirectionBuffer } },
1257
- ],
1258
- })
1259
-
1260
- this.bloomBlurVBindGroup = this.device.createBindGroup({
1261
- layout: this.bloomBlurPipeline.getBindGroupLayout(0),
1262
- entries: [
1263
- { binding: 0, resource: this.bloomBlurTexture1.createView() },
1264
- { binding: 1, resource: this.linearSampler },
1265
- { binding: 2, resource: { buffer: this.blurDirectionBuffer } },
1266
- ],
1267
- })
1268
-
1269
- this.bloomComposeBindGroup = this.device.createBindGroup({
1270
- layout: this.bloomComposePipeline.getBindGroupLayout(0),
1271
- entries: [
1272
- { binding: 0, resource: this.sceneRenderTexture.createView() },
1273
- { binding: 1, resource: this.linearSampler },
1274
- { binding: 2, resource: this.bloomBlurTexture2.createView() },
1275
- { binding: 3, resource: this.linearSampler },
1276
- { binding: 4, resource: { buffer: this.bloomIntensityBuffer } },
1277
- ],
1278
- })
1279
- }
1280
-
1281
- // Step 3: Setup canvas resize handling
1282
- private setupResize() {
1283
- this.resizeObserver = new ResizeObserver(() => this.handleResize())
1284
- this.resizeObserver.observe(this.canvas)
1285
- this.handleResize()
1286
- }
1287
-
1288
- private handleResize() {
1289
- const displayWidth = this.canvas.clientWidth
1290
- const displayHeight = this.canvas.clientHeight
1291
-
1292
- const dpr = window.devicePixelRatio || 1
1293
- const width = Math.floor(displayWidth * dpr)
1294
- const height = Math.floor(displayHeight * dpr)
1295
-
1296
- if (!this.multisampleTexture || this.canvas.width !== width || this.canvas.height !== height) {
1297
- this.canvas.width = width
1298
- this.canvas.height = height
1299
-
1300
- this.multisampleTexture = this.device.createTexture({
1301
- label: "multisample render target",
1302
- size: [width, height],
1303
- sampleCount: this.sampleCount,
1304
- format: this.presentationFormat,
1305
- usage: GPUTextureUsage.RENDER_ATTACHMENT,
1306
- })
1307
-
1308
- this.depthTexture = this.device.createTexture({
1309
- label: "depth texture",
1310
- size: [width, height],
1311
- sampleCount: this.sampleCount,
1312
- format: "depth24plus-stencil8",
1313
- usage: GPUTextureUsage.RENDER_ATTACHMENT,
1314
- })
1315
-
1316
- // Create scene render texture (non-multisampled for post-processing)
1317
- this.sceneRenderTexture = this.device.createTexture({
1318
- label: "scene render texture",
1319
- size: [width, height],
1320
- format: this.presentationFormat,
1321
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1322
- })
1323
- this.sceneRenderTextureView = this.sceneRenderTexture.createView()
1324
-
1325
- // Setup bloom textures and bind groups
1326
- this.setupBloom(width, height)
1327
-
1328
- const depthTextureView = this.depthTexture.createView()
1329
-
1330
- // Render scene to texture instead of directly to canvas
1331
- const colorAttachment: GPURenderPassColorAttachment =
1332
- this.sampleCount > 1
1333
- ? {
1334
- view: this.multisampleTexture.createView(),
1335
- resolveTarget: this.sceneRenderTextureView,
1336
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
1337
- loadOp: "clear",
1338
- storeOp: "store",
1339
- }
1340
- : {
1341
- view: this.sceneRenderTextureView,
1342
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
1343
- loadOp: "clear",
1344
- storeOp: "store",
1345
- }
1346
-
1347
- this.renderPassDescriptor = {
1348
- label: "renderPass",
1349
- colorAttachments: [colorAttachment],
1350
- depthStencilAttachment: {
1351
- view: depthTextureView,
1352
- depthClearValue: 1.0,
1353
- depthLoadOp: "clear",
1354
- depthStoreOp: "store",
1355
- stencilClearValue: 0,
1356
- stencilLoadOp: "clear",
1357
- stencilStoreOp: "discard", // Discard stencil after frame to save bandwidth (we only use it during rendering)
1358
- },
1359
- }
1360
-
1361
- this.camera.aspect = width / height
1362
- }
1363
- }
1364
-
1365
- // Step 4: Create camera and uniform buffer
1366
- private setupCamera() {
1367
- this.cameraUniformBuffer = this.device.createBuffer({
1368
- label: "camera uniforms",
1369
- size: 40 * 4,
1370
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1371
- })
1372
-
1373
- this.camera = new Camera(Math.PI, Math.PI / 2.5, this.cameraDistance, this.cameraTarget)
1374
-
1375
- this.camera.aspect = this.canvas.width / this.canvas.height
1376
- this.camera.attachControl(this.canvas)
1377
- }
1378
-
1379
- // Step 5: Create lighting buffers
1380
- private setupLighting() {
1381
- this.lightUniformBuffer = this.device.createBuffer({
1382
- label: "light uniforms",
1383
- size: 64 * 4,
1384
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1385
- })
1386
-
1387
- this.lightCount = 0
1388
-
1389
- this.setAmbient(this.ambient)
1390
- this.addLight(new Vec3(-0.5, -0.8, 0.5).normalize(), new Vec3(1.0, 0.95, 0.9), 0.02)
1391
- this.addLight(new Vec3(0.7, -0.5, 0.3).normalize(), new Vec3(0.8, 0.85, 1.0), 0.015)
1392
- this.addLight(new Vec3(0.3, -0.5, -1.0).normalize(), new Vec3(0.9, 0.9, 1.0), 0.01)
1393
- this.device.queue.writeBuffer(this.lightUniformBuffer, 0, this.lightData)
1394
- }
1395
-
1396
- private addLight(direction: Vec3, color: Vec3, intensity: number = 1.0): boolean {
1397
- if (this.lightCount >= 4) return false
1398
-
1399
- const normalized = direction.normalize()
1400
- const baseIndex = 4 + this.lightCount * 8
1401
- this.lightData[baseIndex] = normalized.x
1402
- this.lightData[baseIndex + 1] = normalized.y
1403
- this.lightData[baseIndex + 2] = normalized.z
1404
- this.lightData[baseIndex + 3] = 0
1405
- this.lightData[baseIndex + 4] = color.x
1406
- this.lightData[baseIndex + 5] = color.y
1407
- this.lightData[baseIndex + 6] = color.z
1408
- this.lightData[baseIndex + 7] = intensity
1409
-
1410
- this.lightCount++
1411
- this.lightData[1] = this.lightCount
1412
- return true
1413
- }
1414
-
1415
- private setAmbient(intensity: number) {
1416
- this.lightData[0] = intensity
1417
- }
1418
-
1419
- public async loadAnimation(url: string) {
1420
- const frames = await VMDLoader.load(url)
1421
- this.animationFrames = frames
1422
- this.hasAnimation = true
1423
- }
1424
-
1425
- public playAnimation(options?: {
1426
- breathBones?: string[] | Record<string, number> // Array of bone names or map of bone name -> rotation range
1427
- breathDuration?: number // Breathing cycle duration in milliseconds
1428
- }) {
1429
- if (this.animationFrames.length === 0) return
1430
-
1431
- this.stopAnimation()
1432
- this.stopBreathing()
1433
- this.playingAnimation = true
1434
-
1435
- // Enable breathing if breathBones is provided
1436
- const enableBreath = options?.breathBones !== undefined && options.breathBones !== null
1437
- let breathBones: string[] = []
1438
- let breathRotationRanges: Record<string, number> | undefined = undefined
1439
-
1440
- if (enableBreath && options.breathBones) {
1441
- if (Array.isArray(options.breathBones)) {
1442
- breathBones = options.breathBones
1443
- } else {
1444
- breathBones = Object.keys(options.breathBones)
1445
- breathRotationRanges = options.breathBones
1446
- }
1447
- }
1448
-
1449
- const breathDuration = options?.breathDuration ?? 4000
1450
-
1451
- const allBoneKeyFrames: BoneKeyFrame[] = []
1452
- for (const keyFrame of this.animationFrames) {
1453
- for (const boneFrame of keyFrame.boneFrames) {
1454
- allBoneKeyFrames.push({
1455
- boneName: boneFrame.boneName,
1456
- time: keyFrame.time,
1457
- rotation: boneFrame.rotation,
1458
- })
1459
- }
1460
- }
1461
-
1462
- const boneKeyFramesByBone = new Map<string, BoneKeyFrame[]>()
1463
- for (const boneKeyFrame of allBoneKeyFrames) {
1464
- if (!boneKeyFramesByBone.has(boneKeyFrame.boneName)) {
1465
- boneKeyFramesByBone.set(boneKeyFrame.boneName, [])
1466
- }
1467
- boneKeyFramesByBone.get(boneKeyFrame.boneName)!.push(boneKeyFrame)
1468
- }
1469
-
1470
- for (const keyFrames of boneKeyFramesByBone.values()) {
1471
- keyFrames.sort((a, b) => a.time - b.time)
1472
- }
1473
-
1474
- const time0Rotations: Array<{ boneName: string; rotation: Quat }> = []
1475
- const bonesWithTime0 = new Set<string>()
1476
- for (const [boneName, keyFrames] of boneKeyFramesByBone.entries()) {
1477
- if (keyFrames.length > 0 && keyFrames[0].time === 0) {
1478
- time0Rotations.push({
1479
- boneName: boneName,
1480
- rotation: keyFrames[0].rotation,
1481
- })
1482
- bonesWithTime0.add(boneName)
1483
- }
1484
- }
1485
-
1486
- if (this.currentModel) {
1487
- if (time0Rotations.length > 0) {
1488
- const boneNames = time0Rotations.map((r) => r.boneName)
1489
- const rotations = time0Rotations.map((r) => r.rotation)
1490
- this.rotateBones(boneNames, rotations, 0)
1491
- }
1492
-
1493
- const skeleton = this.currentModel.getSkeleton()
1494
- const bonesToReset: string[] = []
1495
- for (const bone of skeleton.bones) {
1496
- if (!bonesWithTime0.has(bone.name)) {
1497
- bonesToReset.push(bone.name)
1498
- }
1499
- }
1500
-
1501
- if (bonesToReset.length > 0) {
1502
- const identityQuat = new Quat(0, 0, 0, 1)
1503
- const identityQuats = new Array(bonesToReset.length).fill(identityQuat)
1504
- this.rotateBones(bonesToReset, identityQuats, 0)
1505
- }
1506
-
1507
- // Reset physics immediately and upload matrices to prevent A-pose flash
1508
- if (this.physics) {
1509
- this.currentModel.evaluatePose()
1510
-
1511
- const worldMats = this.currentModel.getBoneWorldMatrices()
1512
- this.physics.reset(worldMats, this.currentModel.getBoneInverseBindMatrices())
1513
-
1514
- // Upload matrices immediately so next frame shows correct pose
1515
- this.device.queue.writeBuffer(
1516
- this.worldMatrixBuffer!,
1517
- 0,
1518
- worldMats.buffer,
1519
- worldMats.byteOffset,
1520
- worldMats.byteLength
1521
- )
1522
- const encoder = this.device.createCommandEncoder()
1523
- this.computeSkinMatrices(encoder)
1524
- this.device.queue.submit([encoder.finish()])
1525
- }
1526
- }
1527
- for (const [_, keyFrames] of boneKeyFramesByBone.entries()) {
1528
- for (let i = 0; i < keyFrames.length; i++) {
1529
- const boneKeyFrame = keyFrames[i]
1530
- const previousBoneKeyFrame = i > 0 ? keyFrames[i - 1] : null
1531
-
1532
- if (boneKeyFrame.time === 0) continue
1533
-
1534
- let durationMs = 0
1535
- if (i === 0) {
1536
- durationMs = boneKeyFrame.time * 1000
1537
- } else if (previousBoneKeyFrame) {
1538
- durationMs = (boneKeyFrame.time - previousBoneKeyFrame.time) * 1000
1539
- }
1540
-
1541
- const scheduleTime = i > 0 && previousBoneKeyFrame ? previousBoneKeyFrame.time : 0
1542
- const delayMs = scheduleTime * 1000
1543
-
1544
- if (delayMs <= 0) {
1545
- this.rotateBones([boneKeyFrame.boneName], [boneKeyFrame.rotation], durationMs)
1546
- } else {
1547
- const timeoutId = window.setTimeout(() => {
1548
- this.rotateBones([boneKeyFrame.boneName], [boneKeyFrame.rotation], durationMs)
1549
- }, delayMs)
1550
- this.animationTimeouts.push(timeoutId)
1551
- }
1552
- }
1553
- }
1554
-
1555
- // Setup breathing animation if enabled
1556
- if (enableBreath && this.currentModel) {
1557
- // Find the last frame time
1558
- let maxTime = 0
1559
- for (const keyFrame of this.animationFrames) {
1560
- if (keyFrame.time > maxTime) {
1561
- maxTime = keyFrame.time
1562
- }
1563
- }
1564
-
1565
- // Get last frame rotations directly from animation data for breathing bones
1566
- const lastFrameRotations = new Map<string, Quat>()
1567
- for (const bone of breathBones) {
1568
- const keyFrames = boneKeyFramesByBone.get(bone)
1569
- if (keyFrames && keyFrames.length > 0) {
1570
- // Find the rotation at the last frame time (closest keyframe <= maxTime)
1571
- let lastRotation: Quat | null = null
1572
- for (let i = keyFrames.length - 1; i >= 0; i--) {
1573
- if (keyFrames[i].time <= maxTime) {
1574
- lastRotation = keyFrames[i].rotation
1575
- break
1576
- }
1577
- }
1578
- if (lastRotation) {
1579
- lastFrameRotations.set(bone, lastRotation)
1580
- }
1581
- }
1582
- }
1583
-
1584
- // Start breathing after animation completes
1585
- // Use the last frame rotations directly from animation data (no need to capture from model)
1586
- const animationEndTime = maxTime * 1000 + 200 // Small buffer for final tweens to complete
1587
- this.breathingTimeout = window.setTimeout(() => {
1588
- this.startBreathing(breathBones, lastFrameRotations, breathRotationRanges, breathDuration)
1589
- }, animationEndTime)
1590
- }
1591
- }
1592
-
1593
- public stopAnimation() {
1594
- for (const timeoutId of this.animationTimeouts) {
1595
- clearTimeout(timeoutId)
1596
- }
1597
- this.animationTimeouts = []
1598
- this.playingAnimation = false
1599
- }
1600
-
1601
- private stopBreathing() {
1602
- if (this.breathingTimeout !== null) {
1603
- clearTimeout(this.breathingTimeout)
1604
- this.breathingTimeout = null
1605
- }
1606
- this.breathingBaseRotations.clear()
1607
- }
1608
-
1609
- private startBreathing(
1610
- bones: string[],
1611
- baseRotations: Map<string, Quat>,
1612
- rotationRanges?: Record<string, number>,
1613
- durationMs: number = 4000
1614
- ) {
1615
- if (!this.currentModel) return
1616
-
1617
- // Store base rotations directly from last frame of animation data
1618
- // These are the exact rotations from the animation - use them as-is
1619
- for (const bone of bones) {
1620
- const baseRot = baseRotations.get(bone)
1621
- if (baseRot) {
1622
- this.breathingBaseRotations.set(bone, baseRot)
1623
- }
1624
- }
1625
-
1626
- const halfCycleMs = durationMs / 2
1627
- const defaultRotation = 0.02 // Default rotation range if not specified per bone
1628
-
1629
- // Start breathing cycle - oscillate around exact base rotation (final pose)
1630
- // Each bone can have its own rotation range, or use default
1631
- const animate = (isInhale: boolean) => {
1632
- if (!this.currentModel) return
1633
-
1634
- const breathingBoneNames: string[] = []
1635
- const breathingQuats: Quat[] = []
1636
-
1637
- for (const bone of bones) {
1638
- const baseRot = this.breathingBaseRotations.get(bone)
1639
- if (!baseRot) continue
1640
-
1641
- // Get rotation range for this bone (per-bone or default)
1642
- const rotation = rotationRanges?.[bone] ?? defaultRotation
1643
-
1644
- // Oscillate around base rotation with the bone's rotation range
1645
- // isInhale: base * rotation, exhale: base * (-rotation)
1646
- const oscillationRot = Quat.fromEuler(isInhale ? rotation : -rotation, 0, 0)
1647
- const finalRot = baseRot.multiply(oscillationRot)
1648
-
1649
- breathingBoneNames.push(bone)
1650
- breathingQuats.push(finalRot)
1651
- }
1652
-
1653
- if (breathingBoneNames.length > 0) {
1654
- this.rotateBones(breathingBoneNames, breathingQuats, halfCycleMs)
1655
- }
1656
-
1657
- this.breathingTimeout = window.setTimeout(() => animate(!isInhale), halfCycleMs)
1658
- }
1659
-
1660
- // Start breathing from exhale position (closer to base) to minimize initial movement
1661
- animate(false)
1662
- }
1663
-
1664
- public getStats(): EngineStats {
1665
- return { ...this.stats }
1666
- }
1667
-
1668
- public runRenderLoop(callback?: () => void) {
1669
- this.renderLoopCallback = callback || null
1670
-
1671
- const loop = () => {
1672
- this.render()
1673
-
1674
- if (this.renderLoopCallback) {
1675
- this.renderLoopCallback()
1676
- }
1677
-
1678
- this.animationFrameId = requestAnimationFrame(loop)
1679
- }
1680
-
1681
- this.animationFrameId = requestAnimationFrame(loop)
1682
- }
1683
-
1684
- public stopRenderLoop() {
1685
- if (this.animationFrameId !== null) {
1686
- cancelAnimationFrame(this.animationFrameId)
1687
- this.animationFrameId = null
1688
- }
1689
- this.renderLoopCallback = null
1690
- }
1691
-
1692
- public dispose() {
1693
- this.stopRenderLoop()
1694
- this.stopAnimation()
1695
- this.stopBreathing()
1696
- if (this.camera) this.camera.detachControl()
1697
- if (this.resizeObserver) {
1698
- this.resizeObserver.disconnect()
1699
- this.resizeObserver = null
1700
- }
1701
- }
1702
-
1703
- // Step 6: Load PMX model file
1704
- public async loadModel(path: string) {
1705
- const pathParts = path.split("/")
1706
- pathParts.pop()
1707
- const dir = pathParts.join("/") + "/"
1708
- this.modelDir = dir
1709
-
1710
- const model = await PmxLoader.load(path)
1711
- // console.log({
1712
- // vertices: Array.from(model.getVertices()),
1713
- // indices: Array.from(model.getIndices()),
1714
- // materials: model.getMaterials(),
1715
- // textures: model.getTextures(),
1716
- // bones: model.getSkeleton().bones,
1717
- // skinning: { joints: Array.from(model.getSkinning().joints), weights: Array.from(model.getSkinning().weights) },
1718
- // })
1719
- this.physics = new Physics(model.getRigidbodies(), model.getJoints())
1720
- await this.setupModelBuffers(model)
1721
- }
1722
-
1723
- public rotateBones(bones: string[], rotations: Quat[], durationMs?: number) {
1724
- this.currentModel?.rotateBones(bones, rotations, durationMs)
1725
- }
1726
-
1727
- // Step 7: Create vertex, index, and joint buffers
1728
- private async setupModelBuffers(model: Model) {
1729
- this.currentModel = model
1730
- const vertices = model.getVertices()
1731
- const skinning = model.getSkinning()
1732
- const skeleton = model.getSkeleton()
1733
-
1734
- this.vertexBuffer = this.device.createBuffer({
1735
- label: "model vertex buffer",
1736
- size: vertices.byteLength,
1737
- usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1738
- })
1739
- this.device.queue.writeBuffer(this.vertexBuffer, 0, vertices)
1740
-
1741
- this.jointsBuffer = this.device.createBuffer({
1742
- label: "joints buffer",
1743
- size: skinning.joints.byteLength,
1744
- usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1745
- })
1746
- this.device.queue.writeBuffer(
1747
- this.jointsBuffer,
1748
- 0,
1749
- skinning.joints.buffer,
1750
- skinning.joints.byteOffset,
1751
- skinning.joints.byteLength
1752
- )
1753
-
1754
- this.weightsBuffer = this.device.createBuffer({
1755
- label: "weights buffer",
1756
- size: skinning.weights.byteLength,
1757
- usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1758
- })
1759
- this.device.queue.writeBuffer(
1760
- this.weightsBuffer,
1761
- 0,
1762
- skinning.weights.buffer,
1763
- skinning.weights.byteOffset,
1764
- skinning.weights.byteLength
1765
- )
1766
-
1767
- const boneCount = skeleton.bones.length
1768
- const matrixSize = boneCount * 16 * 4
1769
-
1770
- this.skinMatrixBuffer = this.device.createBuffer({
1771
- label: "skin matrices",
1772
- size: Math.max(256, matrixSize),
1773
- usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX,
1774
- })
1775
-
1776
- this.worldMatrixBuffer = this.device.createBuffer({
1777
- label: "world matrices",
1778
- size: Math.max(256, matrixSize),
1779
- usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
1780
- })
1781
-
1782
- this.inverseBindMatrixBuffer = this.device.createBuffer({
1783
- label: "inverse bind matrices",
1784
- size: Math.max(256, matrixSize),
1785
- usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
1786
- })
1787
-
1788
- const invBindMatrices = skeleton.inverseBindMatrices
1789
- this.device.queue.writeBuffer(
1790
- this.inverseBindMatrixBuffer,
1791
- 0,
1792
- invBindMatrices.buffer,
1793
- invBindMatrices.byteOffset,
1794
- invBindMatrices.byteLength
1795
- )
1796
-
1797
- this.boneCountBuffer = this.device.createBuffer({
1798
- label: "bone count uniform",
1799
- size: 32, // Minimum uniform buffer size is 32 bytes
1800
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1801
- })
1802
- const boneCountData = new Uint32Array(8) // 32 bytes total
1803
- boneCountData[0] = boneCount
1804
- this.device.queue.writeBuffer(this.boneCountBuffer, 0, boneCountData)
1805
-
1806
- this.createSkinMatrixComputePipeline()
1807
-
1808
- // Create compute bind group once (reused every frame)
1809
- this.skinMatrixComputeBindGroup = this.device.createBindGroup({
1810
- layout: this.skinMatrixComputePipeline!.getBindGroupLayout(0),
1811
- entries: [
1812
- { binding: 0, resource: { buffer: this.boneCountBuffer } },
1813
- { binding: 1, resource: { buffer: this.worldMatrixBuffer } },
1814
- { binding: 2, resource: { buffer: this.inverseBindMatrixBuffer } },
1815
- { binding: 3, resource: { buffer: this.skinMatrixBuffer } },
1816
- ],
1817
- })
1818
-
1819
- const indices = model.getIndices()
1820
- if (indices) {
1821
- this.indexBuffer = this.device.createBuffer({
1822
- label: "model index buffer",
1823
- size: indices.byteLength,
1824
- usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
1825
- })
1826
- this.device.queue.writeBuffer(this.indexBuffer, 0, indices)
1827
- } else {
1828
- throw new Error("Model has no index buffer")
1829
- }
1830
-
1831
- await this.setupMaterials(model)
1832
- }
1833
-
1834
- private async setupMaterials(model: Model) {
1835
- const materials = model.getMaterials()
1836
- if (materials.length === 0) {
1837
- throw new Error("Model has no materials")
1838
- }
1839
-
1840
- const textures = model.getTextures()
1841
-
1842
- const loadTextureByIndex = async (texIndex: number): Promise<GPUTexture | null> => {
1843
- if (texIndex < 0 || texIndex >= textures.length) {
1844
- return null
1845
- }
1846
-
1847
- const path = this.modelDir + textures[texIndex].path
1848
- const texture = await this.createTextureFromPath(path)
1849
- return texture
1850
- }
1851
-
1852
- const loadToonTexture = async (toonTextureIndex: number): Promise<GPUTexture> => {
1853
- const texture = await loadTextureByIndex(toonTextureIndex)
1854
- if (texture) return texture
1855
-
1856
- // Default toon texture fallback - cache it
1857
- const defaultToonPath = "__default_toon__"
1858
- const cached = this.textureCache.get(defaultToonPath)
1859
- if (cached) return cached
1860
-
1861
- const defaultToonData = new Uint8Array(256 * 2 * 4)
1862
- for (let i = 0; i < 256; i++) {
1863
- const factor = i / 255.0
1864
- const gray = Math.floor(128 + factor * 127)
1865
- defaultToonData[i * 4] = gray
1866
- defaultToonData[i * 4 + 1] = gray
1867
- defaultToonData[i * 4 + 2] = gray
1868
- defaultToonData[i * 4 + 3] = 255
1869
- defaultToonData[(256 + i) * 4] = gray
1870
- defaultToonData[(256 + i) * 4 + 1] = gray
1871
- defaultToonData[(256 + i) * 4 + 2] = gray
1872
- defaultToonData[(256 + i) * 4 + 3] = 255
1873
- }
1874
- const defaultToonTexture = this.device.createTexture({
1875
- label: "default toon texture",
1876
- size: [256, 2],
1877
- format: "rgba8unorm",
1878
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
1879
- })
1880
- this.device.queue.writeTexture(
1881
- { texture: defaultToonTexture },
1882
- defaultToonData,
1883
- { bytesPerRow: 256 * 4 },
1884
- [256, 2]
1885
- )
1886
- this.textureCache.set(defaultToonPath, defaultToonTexture)
1887
- return defaultToonTexture
1888
- }
1889
-
1890
- this.opaqueDraws = []
1891
- this.eyeDraws = []
1892
- this.hairDrawsOverEyes = []
1893
- this.hairDrawsOverNonEyes = []
1894
- this.transparentDraws = []
1895
- this.opaqueOutlineDraws = []
1896
- this.eyeOutlineDraws = []
1897
- this.hairOutlineDraws = []
1898
- this.transparentOutlineDraws = []
1899
- let currentIndexOffset = 0
1900
-
1901
- for (const mat of materials) {
1902
- const indexCount = mat.vertexCount
1903
- if (indexCount === 0) continue
1904
-
1905
- const diffuseTexture = await loadTextureByIndex(mat.diffuseTextureIndex)
1906
- if (!diffuseTexture) throw new Error(`Material "${mat.name}" has no diffuse texture`)
1907
-
1908
- const toonTexture = await loadToonTexture(mat.toonTextureIndex)
1909
-
1910
- const materialAlpha = mat.diffuse[3]
1911
- const EPSILON = 0.001
1912
- const isTransparent = materialAlpha < 1.0 - EPSILON
1913
-
1914
- // Create material uniform data
1915
- const materialUniformData = new Float32Array(8)
1916
- materialUniformData[0] = materialAlpha
1917
- materialUniformData[1] = 1.0 // alphaMultiplier: 1.0 for non-hair materials
1918
- materialUniformData[2] = this.rimLightIntensity
1919
- materialUniformData[3] = 0.0 // _padding1
1920
- materialUniformData[4] = 1.0 // rimColor.r
1921
- materialUniformData[5] = 1.0 // rimColor.g
1922
- materialUniformData[6] = 1.0 // rimColor.b
1923
- materialUniformData[7] = 0.0 // isOverEyes
1924
-
1925
- const materialUniformBuffer = this.device.createBuffer({
1926
- label: `material uniform: ${mat.name}`,
1927
- size: materialUniformData.byteLength,
1928
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1929
- })
1930
- this.device.queue.writeBuffer(materialUniformBuffer, 0, materialUniformData)
1931
-
1932
- // Create bind groups using the shared bind group layout - All pipelines (main, eye, hair multiply, hair opaque) use the same shader and layout
1933
- const bindGroup = this.device.createBindGroup({
1934
- label: `material bind group: ${mat.name}`,
1935
- layout: this.mainBindGroupLayout,
1936
- entries: [
1937
- { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
1938
- { binding: 1, resource: { buffer: this.lightUniformBuffer } },
1939
- { binding: 2, resource: diffuseTexture.createView() },
1940
- { binding: 3, resource: this.materialSampler },
1941
- { binding: 4, resource: { buffer: this.skinMatrixBuffer! } },
1942
- { binding: 5, resource: toonTexture.createView() },
1943
- { binding: 6, resource: this.materialSampler },
1944
- { binding: 7, resource: { buffer: materialUniformBuffer } },
1945
- ],
1946
- })
1947
-
1948
- if (mat.isEye) {
1949
- this.eyeDraws.push({
1950
- count: indexCount,
1951
- firstIndex: currentIndexOffset,
1952
- bindGroup,
1953
- isTransparent,
1954
- })
1955
- } else if (mat.isHair) {
1956
- // Hair materials: create separate bind groups for over-eyes vs over-non-eyes
1957
- const createHairBindGroup = (isOverEyes: boolean) => {
1958
- const uniformData = new Float32Array(8)
1959
- uniformData[0] = materialAlpha
1960
- uniformData[1] = 1.0 // alphaMultiplier (shader adjusts based on isOverEyes)
1961
- uniformData[2] = this.rimLightIntensity
1962
- uniformData[3] = 0.0 // _padding1
1963
- uniformData[4] = 1.0 // rimColor.rgb
1964
- uniformData[5] = 1.0
1965
- uniformData[6] = 1.0
1966
- uniformData[7] = isOverEyes ? 1.0 : 0.0 // isOverEyes
1967
-
1968
- const buffer = this.device.createBuffer({
1969
- label: `material uniform (${isOverEyes ? "over eyes" : "over non-eyes"}): ${mat.name}`,
1970
- size: uniformData.byteLength,
1971
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1972
- })
1973
- this.device.queue.writeBuffer(buffer, 0, uniformData)
1974
-
1975
- return this.device.createBindGroup({
1976
- label: `material bind group (${isOverEyes ? "over eyes" : "over non-eyes"}): ${mat.name}`,
1977
- layout: this.mainBindGroupLayout,
1978
- entries: [
1979
- { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
1980
- { binding: 1, resource: { buffer: this.lightUniformBuffer } },
1981
- { binding: 2, resource: diffuseTexture.createView() },
1982
- { binding: 3, resource: this.materialSampler },
1983
- { binding: 4, resource: { buffer: this.skinMatrixBuffer! } },
1984
- { binding: 5, resource: toonTexture.createView() },
1985
- { binding: 6, resource: this.materialSampler },
1986
- { binding: 7, resource: { buffer: buffer } },
1987
- ],
1988
- })
1989
- }
1990
-
1991
- const bindGroupOverEyes = createHairBindGroup(true)
1992
- const bindGroupOverNonEyes = createHairBindGroup(false)
1993
-
1994
- this.hairDrawsOverEyes.push({
1995
- count: indexCount,
1996
- firstIndex: currentIndexOffset,
1997
- bindGroup: bindGroupOverEyes,
1998
- isTransparent,
1999
- })
2000
-
2001
- this.hairDrawsOverNonEyes.push({
2002
- count: indexCount,
2003
- firstIndex: currentIndexOffset,
2004
- bindGroup: bindGroupOverNonEyes,
2005
- isTransparent,
2006
- })
2007
- } else if (isTransparent) {
2008
- this.transparentDraws.push({
2009
- count: indexCount,
2010
- firstIndex: currentIndexOffset,
2011
- bindGroup,
2012
- isTransparent,
2013
- })
2014
- } else {
2015
- this.opaqueDraws.push({
2016
- count: indexCount,
2017
- firstIndex: currentIndexOffset,
2018
- bindGroup,
2019
- isTransparent,
2020
- })
2021
- }
2022
-
2023
- // Edge flag is at bit 4 (0x10) in PMX format
2024
- if ((mat.edgeFlag & 0x10) !== 0 && mat.edgeSize > 0) {
2025
- const materialUniformData = new Float32Array(8)
2026
- materialUniformData[0] = mat.edgeColor[0] // edgeColor.r
2027
- materialUniformData[1] = mat.edgeColor[1] // edgeColor.g
2028
- materialUniformData[2] = mat.edgeColor[2] // edgeColor.b
2029
- materialUniformData[3] = mat.edgeColor[3] // edgeColor.a
2030
- materialUniformData[4] = mat.edgeSize
2031
- materialUniformData[5] = 0.0 // isOverEyes
2032
- materialUniformData[6] = 0.0
2033
- materialUniformData[7] = 0.0
2034
-
2035
- const materialUniformBuffer = this.device.createBuffer({
2036
- label: `outline material uniform: ${mat.name}`,
2037
- size: materialUniformData.byteLength,
2038
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
2039
- })
2040
- this.device.queue.writeBuffer(materialUniformBuffer, 0, materialUniformData)
2041
-
2042
- const outlineBindGroup = this.device.createBindGroup({
2043
- label: `outline bind group: ${mat.name}`,
2044
- layout: this.outlineBindGroupLayout,
2045
- entries: [
2046
- { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
2047
- { binding: 1, resource: { buffer: materialUniformBuffer } },
2048
- { binding: 2, resource: { buffer: this.skinMatrixBuffer! } },
2049
- ],
2050
- })
2051
-
2052
- if (mat.isEye) {
2053
- this.eyeOutlineDraws.push({
2054
- count: indexCount,
2055
- firstIndex: currentIndexOffset,
2056
- bindGroup: outlineBindGroup,
2057
- isTransparent,
2058
- })
2059
- } else if (mat.isHair) {
2060
- this.hairOutlineDraws.push({
2061
- count: indexCount,
2062
- firstIndex: currentIndexOffset,
2063
- bindGroup: outlineBindGroup,
2064
- isTransparent,
2065
- })
2066
- } else if (isTransparent) {
2067
- this.transparentOutlineDraws.push({
2068
- count: indexCount,
2069
- firstIndex: currentIndexOffset,
2070
- bindGroup: outlineBindGroup,
2071
- isTransparent,
2072
- })
2073
- } else {
2074
- this.opaqueOutlineDraws.push({
2075
- count: indexCount,
2076
- firstIndex: currentIndexOffset,
2077
- bindGroup: outlineBindGroup,
2078
- isTransparent,
2079
- })
2080
- }
2081
- }
2082
-
2083
- currentIndexOffset += indexCount
2084
- }
2085
-
2086
- this.gpuMemoryMB = this.calculateGpuMemory()
2087
- }
2088
-
2089
- private async createTextureFromPath(path: string): Promise<GPUTexture | null> {
2090
- const cached = this.textureCache.get(path)
2091
- if (cached) {
2092
- return cached
2093
- }
2094
-
2095
- try {
2096
- const response = await fetch(path)
2097
- if (!response.ok) {
2098
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
2099
- }
2100
- const imageBitmap = await createImageBitmap(await response.blob(), {
2101
- premultiplyAlpha: "none",
2102
- colorSpaceConversion: "none",
2103
- })
2104
-
2105
- const texture = this.device.createTexture({
2106
- label: `texture: ${path}`,
2107
- size: [imageBitmap.width, imageBitmap.height],
2108
- format: "rgba8unorm",
2109
- usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
2110
- })
2111
- this.device.queue.copyExternalImageToTexture({ source: imageBitmap }, { texture }, [
2112
- imageBitmap.width,
2113
- imageBitmap.height,
2114
- ])
2115
-
2116
- this.textureCache.set(path, texture)
2117
- return texture
2118
- } catch {
2119
- return null
2120
- }
2121
- }
2122
-
2123
- // Render strategy: 1) Opaque non-eye/hair 2) Eyes (stencil=1) 3) Hair (depth pre-pass + split by stencil) 4) Transparent 5) Bloom
2124
- public render() {
2125
- if (this.multisampleTexture && this.camera && this.device) {
2126
- const currentTime = performance.now()
2127
- const deltaTime = this.lastFrameTime > 0 ? (currentTime - this.lastFrameTime) / 1000 : 0.016
2128
- this.lastFrameTime = currentTime
2129
-
2130
- this.updateCameraUniforms()
2131
- this.updateRenderTarget()
2132
-
2133
- // Use single encoder for both compute and render (reduces sync points)
2134
- const encoder = this.device.createCommandEncoder()
2135
-
2136
- this.updateModelPose(deltaTime, encoder)
2137
-
2138
- // Hide model if animation is loaded but not playing yet (prevents A-pose flash)
2139
- // Still update physics and poses, just don't render visually
2140
- if (this.hasAnimation && !this.playingAnimation) {
2141
- // Submit encoder to ensure matrices are uploaded and physics initializes
2142
- this.device.queue.submit([encoder.finish()])
2143
- return
2144
- }
2145
-
2146
- const pass = encoder.beginRenderPass(this.renderPassDescriptor)
2147
-
2148
- this.drawCallCount = 0
2149
-
2150
- if (this.currentModel) {
2151
- pass.setVertexBuffer(0, this.vertexBuffer)
2152
- pass.setVertexBuffer(1, this.jointsBuffer)
2153
- pass.setVertexBuffer(2, this.weightsBuffer)
2154
- pass.setIndexBuffer(this.indexBuffer!, "uint32")
2155
-
2156
- // Pass 1: Opaque
2157
- pass.setPipeline(this.modelPipeline)
2158
- for (const draw of this.opaqueDraws) {
2159
- if (draw.count > 0) {
2160
- pass.setBindGroup(0, draw.bindGroup)
2161
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2162
- this.drawCallCount++
2163
- }
2164
- }
2165
-
2166
- // Pass 2: Eyes (writes stencil value for hair to test against)
2167
- pass.setPipeline(this.eyePipeline)
2168
- pass.setStencilReference(this.STENCIL_EYE_VALUE)
2169
- for (const draw of this.eyeDraws) {
2170
- if (draw.count > 0) {
2171
- pass.setBindGroup(0, draw.bindGroup)
2172
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2173
- this.drawCallCount++
2174
- }
2175
- }
2176
-
2177
- // Pass 3: Hair rendering (depth pre-pass + shading + outlines)
2178
- this.drawOutlines(pass, false)
2179
-
2180
- // 3a: Hair depth pre-pass (reduces overdraw via early depth rejection)
2181
- if (this.hairDrawsOverEyes.length > 0 || this.hairDrawsOverNonEyes.length > 0) {
2182
- pass.setPipeline(this.hairDepthPipeline)
2183
- for (const draw of this.hairDrawsOverEyes) {
2184
- if (draw.count > 0) {
2185
- pass.setBindGroup(0, draw.bindGroup)
2186
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2187
- }
2188
- }
2189
- for (const draw of this.hairDrawsOverNonEyes) {
2190
- if (draw.count > 0) {
2191
- pass.setBindGroup(0, draw.bindGroup)
2192
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2193
- }
2194
- }
2195
- }
2196
-
2197
- // 3b: Hair shading (split by stencil for transparency over eyes)
2198
- if (this.hairDrawsOverEyes.length > 0) {
2199
- pass.setPipeline(this.hairPipelineOverEyes)
2200
- pass.setStencilReference(this.STENCIL_EYE_VALUE)
2201
- for (const draw of this.hairDrawsOverEyes) {
2202
- if (draw.count > 0) {
2203
- pass.setBindGroup(0, draw.bindGroup)
2204
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2205
- this.drawCallCount++
2206
- }
2207
- }
2208
- }
2209
-
2210
- if (this.hairDrawsOverNonEyes.length > 0) {
2211
- pass.setPipeline(this.hairPipelineOverNonEyes)
2212
- pass.setStencilReference(this.STENCIL_EYE_VALUE)
2213
- for (const draw of this.hairDrawsOverNonEyes) {
2214
- if (draw.count > 0) {
2215
- pass.setBindGroup(0, draw.bindGroup)
2216
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2217
- this.drawCallCount++
2218
- }
2219
- }
2220
- }
2221
-
2222
- // 3c: Hair outlines
2223
- if (this.hairOutlineDraws.length > 0) {
2224
- pass.setPipeline(this.hairOutlinePipeline)
2225
- for (const draw of this.hairOutlineDraws) {
2226
- if (draw.count > 0) {
2227
- pass.setBindGroup(0, draw.bindGroup)
2228
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2229
- }
2230
- }
2231
- }
2232
-
2233
- // Pass 4: Transparent
2234
- pass.setPipeline(this.modelPipeline)
2235
- for (const draw of this.transparentDraws) {
2236
- if (draw.count > 0) {
2237
- pass.setBindGroup(0, draw.bindGroup)
2238
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2239
- this.drawCallCount++
2240
- }
2241
- }
2242
-
2243
- this.drawOutlines(pass, true)
2244
- }
2245
-
2246
- pass.end()
2247
- this.device.queue.submit([encoder.finish()])
2248
-
2249
- this.applyBloom()
2250
-
2251
- this.updateStats(performance.now() - currentTime)
2252
- }
2253
- }
2254
-
2255
- private applyBloom() {
2256
- if (!this.sceneRenderTexture || !this.bloomExtractTexture) {
2257
- return
2258
- }
2259
-
2260
- // Update bloom parameters
2261
- const thresholdData = new Float32Array(8)
2262
- thresholdData[0] = this.bloomThreshold
2263
- this.device.queue.writeBuffer(this.bloomThresholdBuffer, 0, thresholdData)
2264
-
2265
- const intensityData = new Float32Array(8)
2266
- intensityData[0] = this.bloomIntensity
2267
- this.device.queue.writeBuffer(this.bloomIntensityBuffer, 0, intensityData)
2268
-
2269
- const encoder = this.device.createCommandEncoder()
2270
-
2271
- // Extract bright areas
2272
- const extractPass = encoder.beginRenderPass({
2273
- label: "bloom extract",
2274
- colorAttachments: [
2275
- {
2276
- view: this.bloomExtractTexture.createView(),
2277
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
2278
- loadOp: "clear",
2279
- storeOp: "store",
2280
- },
2281
- ],
2282
- })
2283
-
2284
- extractPass.setPipeline(this.bloomExtractPipeline)
2285
- extractPass.setBindGroup(0, this.bloomExtractBindGroup!)
2286
- extractPass.draw(6, 1, 0, 0)
2287
- extractPass.end()
2288
-
2289
- // Horizontal blur
2290
- const hBlurData = new Float32Array(4)
2291
- hBlurData[0] = 1.0
2292
- hBlurData[1] = 0.0
2293
- this.device.queue.writeBuffer(this.blurDirectionBuffer, 0, hBlurData)
2294
- const blurHPass = encoder.beginRenderPass({
2295
- label: "bloom blur horizontal",
2296
- colorAttachments: [
2297
- {
2298
- view: this.bloomBlurTexture1.createView(),
2299
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
2300
- loadOp: "clear",
2301
- storeOp: "store",
2302
- },
2303
- ],
2304
- })
2305
-
2306
- blurHPass.setPipeline(this.bloomBlurPipeline)
2307
- blurHPass.setBindGroup(0, this.bloomBlurHBindGroup!)
2308
- blurHPass.draw(6, 1, 0, 0)
2309
- blurHPass.end()
2310
-
2311
- // Vertical blur
2312
- const vBlurData = new Float32Array(4)
2313
- vBlurData[0] = 0.0
2314
- vBlurData[1] = 1.0
2315
- this.device.queue.writeBuffer(this.blurDirectionBuffer, 0, vBlurData)
2316
- const blurVPass = encoder.beginRenderPass({
2317
- label: "bloom blur vertical",
2318
- colorAttachments: [
2319
- {
2320
- view: this.bloomBlurTexture2.createView(),
2321
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
2322
- loadOp: "clear",
2323
- storeOp: "store",
2324
- },
2325
- ],
2326
- })
2327
-
2328
- blurVPass.setPipeline(this.bloomBlurPipeline)
2329
- blurVPass.setBindGroup(0, this.bloomBlurVBindGroup!)
2330
- blurVPass.draw(6, 1, 0, 0)
2331
- blurVPass.end()
2332
-
2333
- // Compose to canvas
2334
- const composePass = encoder.beginRenderPass({
2335
- label: "bloom compose",
2336
- colorAttachments: [
2337
- {
2338
- view: this.context.getCurrentTexture().createView(),
2339
- clearValue: { r: 0, g: 0, b: 0, a: 0 },
2340
- loadOp: "clear",
2341
- storeOp: "store",
2342
- },
2343
- ],
2344
- })
2345
-
2346
- composePass.setPipeline(this.bloomComposePipeline)
2347
- composePass.setBindGroup(0, this.bloomComposeBindGroup!)
2348
- composePass.draw(6, 1, 0, 0)
2349
- composePass.end()
2350
-
2351
- this.device.queue.submit([encoder.finish()])
2352
- }
2353
-
2354
- private updateCameraUniforms() {
2355
- const viewMatrix = this.camera.getViewMatrix()
2356
- const projectionMatrix = this.camera.getProjectionMatrix()
2357
- const cameraPos = this.camera.getPosition()
2358
- this.cameraMatrixData.set(viewMatrix.values, 0)
2359
- this.cameraMatrixData.set(projectionMatrix.values, 16)
2360
- this.cameraMatrixData[32] = cameraPos.x
2361
- this.cameraMatrixData[33] = cameraPos.y
2362
- this.cameraMatrixData[34] = cameraPos.z
2363
- this.device.queue.writeBuffer(this.cameraUniformBuffer, 0, this.cameraMatrixData)
2364
- }
2365
-
2366
- private updateRenderTarget() {
2367
- const colorAttachment = (this.renderPassDescriptor.colorAttachments as GPURenderPassColorAttachment[])[0]
2368
- if (this.sampleCount > 1) {
2369
- colorAttachment.resolveTarget = this.sceneRenderTextureView
2370
- } else {
2371
- colorAttachment.view = this.sceneRenderTextureView
2372
- }
2373
- }
2374
-
2375
- private updateModelPose(deltaTime: number, encoder: GPUCommandEncoder) {
2376
- this.currentModel!.evaluatePose()
2377
- const worldMats = this.currentModel!.getBoneWorldMatrices()
2378
-
2379
- if (this.physics) {
2380
- this.physics.step(deltaTime, worldMats, this.currentModel!.getBoneInverseBindMatrices())
2381
- }
2382
-
2383
- this.device.queue.writeBuffer(
2384
- this.worldMatrixBuffer!,
2385
- 0,
2386
- worldMats.buffer,
2387
- worldMats.byteOffset,
2388
- worldMats.byteLength
2389
- )
2390
- this.computeSkinMatrices(encoder)
2391
- }
2392
-
2393
- private computeSkinMatrices(encoder: GPUCommandEncoder) {
2394
- const boneCount = this.currentModel!.getSkeleton().bones.length
2395
- const workgroupCount = Math.ceil(boneCount / this.COMPUTE_WORKGROUP_SIZE)
2396
-
2397
- const pass = encoder.beginComputePass()
2398
- pass.setPipeline(this.skinMatrixComputePipeline!)
2399
- pass.setBindGroup(0, this.skinMatrixComputeBindGroup!)
2400
- pass.dispatchWorkgroups(workgroupCount)
2401
- pass.end()
2402
- }
2403
-
2404
- private drawOutlines(pass: GPURenderPassEncoder, transparent: boolean) {
2405
- pass.setPipeline(this.outlinePipeline)
2406
- if (transparent) {
2407
- for (const draw of this.transparentOutlineDraws) {
2408
- if (draw.count > 0) {
2409
- pass.setBindGroup(0, draw.bindGroup)
2410
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2411
- }
2412
- }
2413
- } else {
2414
- for (const draw of this.opaqueOutlineDraws) {
2415
- if (draw.count > 0) {
2416
- pass.setBindGroup(0, draw.bindGroup)
2417
- pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2418
- }
2419
- }
2420
- }
2421
- }
2422
-
2423
- private updateStats(frameTime: number) {
2424
- const maxSamples = 60
2425
- this.frameTimeSamples.push(frameTime)
2426
- this.frameTimeSum += frameTime
2427
- if (this.frameTimeSamples.length > maxSamples) {
2428
- const removed = this.frameTimeSamples.shift()!
2429
- this.frameTimeSum -= removed
2430
- }
2431
- const avgFrameTime = this.frameTimeSum / this.frameTimeSamples.length
2432
- this.stats.frameTime = Math.round(avgFrameTime * 100) / 100
2433
-
2434
- const now = performance.now()
2435
- this.framesSinceLastUpdate++
2436
- const elapsed = now - this.lastFpsUpdate
2437
-
2438
- if (elapsed >= 1000) {
2439
- this.stats.fps = Math.round((this.framesSinceLastUpdate / elapsed) * 1000)
2440
- this.framesSinceLastUpdate = 0
2441
- this.lastFpsUpdate = now
2442
- }
2443
-
2444
- this.stats.gpuMemory = this.gpuMemoryMB
2445
- }
2446
-
2447
- private calculateGpuMemory(): number {
2448
- let textureMemoryBytes = 0
2449
- for (const texture of this.textureCache.values()) {
2450
- textureMemoryBytes += texture.width * texture.height * 4
2451
- }
2452
-
2453
- let bufferMemoryBytes = 0
2454
- if (this.vertexBuffer) {
2455
- const vertices = this.currentModel?.getVertices()
2456
- if (vertices) bufferMemoryBytes += vertices.byteLength
2457
- }
2458
- if (this.indexBuffer) {
2459
- const indices = this.currentModel?.getIndices()
2460
- if (indices) bufferMemoryBytes += indices.byteLength
2461
- }
2462
- if (this.jointsBuffer) {
2463
- const skinning = this.currentModel?.getSkinning()
2464
- if (skinning) bufferMemoryBytes += skinning.joints.byteLength
2465
- }
2466
- if (this.weightsBuffer) {
2467
- const skinning = this.currentModel?.getSkinning()
2468
- if (skinning) bufferMemoryBytes += skinning.weights.byteLength
2469
- }
2470
- if (this.skinMatrixBuffer) {
2471
- const skeleton = this.currentModel?.getSkeleton()
2472
- if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2473
- }
2474
- if (this.worldMatrixBuffer) {
2475
- const skeleton = this.currentModel?.getSkeleton()
2476
- if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2477
- }
2478
- if (this.inverseBindMatrixBuffer) {
2479
- const skeleton = this.currentModel?.getSkeleton()
2480
- if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2481
- }
2482
- bufferMemoryBytes += 40 * 4
2483
- bufferMemoryBytes += 64 * 4
2484
- bufferMemoryBytes += 32
2485
- bufferMemoryBytes += 32
2486
- bufferMemoryBytes += 32
2487
- bufferMemoryBytes += 32
2488
- if (this.fullscreenQuadBuffer) {
2489
- bufferMemoryBytes += 24 * 4
2490
- }
2491
- const totalMaterialDraws =
2492
- this.opaqueDraws.length +
2493
- this.eyeDraws.length +
2494
- this.hairDrawsOverEyes.length +
2495
- this.hairDrawsOverNonEyes.length +
2496
- this.transparentDraws.length
2497
- bufferMemoryBytes += totalMaterialDraws * 32
2498
-
2499
- const totalOutlineDraws =
2500
- this.opaqueOutlineDraws.length +
2501
- this.eyeOutlineDraws.length +
2502
- this.hairOutlineDraws.length +
2503
- this.transparentOutlineDraws.length
2504
- bufferMemoryBytes += totalOutlineDraws * 32
2505
-
2506
- let renderTargetMemoryBytes = 0
2507
- if (this.multisampleTexture) {
2508
- const width = this.canvas.width
2509
- const height = this.canvas.height
2510
- renderTargetMemoryBytes += width * height * 4 * this.sampleCount
2511
- renderTargetMemoryBytes += width * height * 4
2512
- }
2513
- if (this.sceneRenderTexture) {
2514
- const width = this.canvas.width
2515
- const height = this.canvas.height
2516
- renderTargetMemoryBytes += width * height * 4
2517
- }
2518
- if (this.bloomExtractTexture) {
2519
- const width = Math.floor(this.canvas.width / this.BLOOM_DOWNSCALE_FACTOR)
2520
- const height = Math.floor(this.canvas.height / this.BLOOM_DOWNSCALE_FACTOR)
2521
- renderTargetMemoryBytes += width * height * 4 * 3
2522
- }
2523
-
2524
- const totalGPUMemoryBytes = textureMemoryBytes + bufferMemoryBytes + renderTargetMemoryBytes
2525
- return Math.round((totalGPUMemoryBytes / 1024 / 1024) * 100) / 100
2526
- }
2527
- }
1
+ import { Camera } from "./camera"
2
+ import { Quat, Vec3 } from "./math"
3
+ import { Model } from "./model"
4
+ import { PmxLoader } from "./pmx-loader"
5
+ import { Physics } from "./physics"
6
+ import { VMDKeyFrame, VMDLoader } from "./vmd-loader"
7
+
8
+ export type EngineOptions = {
9
+ ambient?: number
10
+ ambientColor?: Vec3
11
+ bloomIntensity?: number
12
+ rimLightIntensity?: number
13
+ cameraDistance?: number
14
+ cameraTarget?: Vec3
15
+ }
16
+
17
+ export interface EngineStats {
18
+ fps: number
19
+ frameTime: number // ms
20
+ gpuMemory: number // MB (estimated total GPU memory)
21
+ }
22
+
23
+ interface DrawCall {
24
+ count: number
25
+ firstIndex: number
26
+ bindGroup: GPUBindGroup
27
+ isTransparent: boolean
28
+ }
29
+
30
+ type BoneKeyFrame = {
31
+ boneName: string
32
+ time: number
33
+ rotation: Quat
34
+ }
35
+
36
+ export class Engine {
37
+ private canvas: HTMLCanvasElement
38
+ private device!: GPUDevice
39
+ private context!: GPUCanvasContext
40
+ private presentationFormat!: GPUTextureFormat
41
+ private camera!: Camera
42
+ private cameraUniformBuffer!: GPUBuffer
43
+ private cameraMatrixData = new Float32Array(36)
44
+ private cameraDistance: number = 26.6
45
+ private cameraTarget: Vec3 = new Vec3(0, 12.5, 0)
46
+ private lightUniformBuffer!: GPUBuffer
47
+ private lightData = new Float32Array(64)
48
+ private lightCount = 0
49
+ private vertexBuffer!: GPUBuffer
50
+ private indexBuffer?: GPUBuffer
51
+ private resizeObserver: ResizeObserver | null = null
52
+ private depthTexture!: GPUTexture
53
+ // Material rendering pipelines
54
+ private modelPipeline!: GPURenderPipeline
55
+ private eyePipeline!: GPURenderPipeline
56
+ private hairPipelineOverEyes!: GPURenderPipeline
57
+ private hairPipelineOverNonEyes!: GPURenderPipeline
58
+ private hairDepthPipeline!: GPURenderPipeline
59
+ // Outline pipelines
60
+ private outlinePipeline!: GPURenderPipeline
61
+ private hairOutlinePipeline!: GPURenderPipeline
62
+ private mainBindGroupLayout!: GPUBindGroupLayout
63
+ private outlineBindGroupLayout!: GPUBindGroupLayout
64
+ private jointsBuffer!: GPUBuffer
65
+ private weightsBuffer!: GPUBuffer
66
+ private skinMatrixBuffer?: GPUBuffer
67
+ private worldMatrixBuffer?: GPUBuffer
68
+ private inverseBindMatrixBuffer?: GPUBuffer
69
+ private skinMatrixComputePipeline?: GPUComputePipeline
70
+ private skinMatrixComputeBindGroup?: GPUBindGroup
71
+ private boneCountBuffer?: GPUBuffer
72
+ private multisampleTexture!: GPUTexture
73
+ private readonly sampleCount = 4
74
+ private renderPassDescriptor!: GPURenderPassDescriptor
75
+ // Constants
76
+ private readonly STENCIL_EYE_VALUE = 1
77
+ private readonly COMPUTE_WORKGROUP_SIZE = 64
78
+ private readonly BLOOM_DOWNSCALE_FACTOR = 2
79
+ // Ambient light settings
80
+ private ambient: number = 1.0
81
+ private ambientColor: Vec3 = new Vec3(1.0, 1.0, 1.0)
82
+ // Bloom post-processing textures
83
+ private sceneRenderTexture!: GPUTexture
84
+ private sceneRenderTextureView!: GPUTextureView
85
+ private bloomExtractTexture!: GPUTexture
86
+ private bloomBlurTexture1!: GPUTexture
87
+ private bloomBlurTexture2!: GPUTexture
88
+ // Post-processing pipelines
89
+ private bloomExtractPipeline!: GPURenderPipeline
90
+ private bloomBlurPipeline!: GPURenderPipeline
91
+ private bloomComposePipeline!: GPURenderPipeline
92
+ // Fullscreen quad for post-processing
93
+ private fullscreenQuadBuffer!: GPUBuffer
94
+ private blurDirectionBuffer!: GPUBuffer
95
+ private bloomIntensityBuffer!: GPUBuffer
96
+ private bloomThresholdBuffer!: GPUBuffer
97
+ private linearSampler!: GPUSampler
98
+ // Bloom bind groups (created once, reused every frame)
99
+ private bloomExtractBindGroup?: GPUBindGroup
100
+ private bloomBlurHBindGroup?: GPUBindGroup
101
+ private bloomBlurVBindGroup?: GPUBindGroup
102
+ private bloomComposeBindGroup?: GPUBindGroup
103
+ // Bloom settings
104
+ private bloomThreshold: number = 0.3
105
+ private bloomIntensity: number = 0.12
106
+ // Rim light settings
107
+ private rimLightIntensity: number = 0.45
108
+
109
+ private currentModel: Model | null = null
110
+ private modelDir: string = ""
111
+ private physics: Physics | null = null
112
+ private materialSampler!: GPUSampler
113
+ private textureCache = new Map<string, GPUTexture>()
114
+ // Draw lists
115
+ private opaqueDraws: DrawCall[] = []
116
+ private eyeDraws: DrawCall[] = []
117
+ private hairDrawsOverEyes: DrawCall[] = []
118
+ private hairDrawsOverNonEyes: DrawCall[] = []
119
+ private transparentDraws: DrawCall[] = []
120
+ private opaqueOutlineDraws: DrawCall[] = []
121
+ private eyeOutlineDraws: DrawCall[] = []
122
+ private hairOutlineDraws: DrawCall[] = []
123
+ private transparentOutlineDraws: DrawCall[] = []
124
+
125
+ private lastFpsUpdate = performance.now()
126
+ private framesSinceLastUpdate = 0
127
+ private frameTimeSamples: number[] = []
128
+ private frameTimeSum: number = 0
129
+ private drawCallCount: number = 0
130
+ private lastFrameTime = performance.now()
131
+ private stats: EngineStats = {
132
+ fps: 0,
133
+ frameTime: 0,
134
+ gpuMemory: 0,
135
+ }
136
+ private animationFrameId: number | null = null
137
+ private renderLoopCallback: (() => void) | null = null
138
+
139
+ private animationFrames: VMDKeyFrame[] = []
140
+ private animationTimeouts: number[] = []
141
+ private gpuMemoryMB: number = 0
142
+ private hasAnimation = false // Set to true when loadAnimation is called
143
+ private playingAnimation = false // Set to true when playAnimation is called
144
+ private breathingTimeout: number | null = null
145
+ private breathingBaseRotations: Map<string, Quat> = new Map()
146
+
147
+ constructor(canvas: HTMLCanvasElement, options?: EngineOptions) {
148
+ this.canvas = canvas
149
+ if (options) {
150
+ this.ambient = options.ambient ?? 1.0
151
+ this.ambientColor = options.ambientColor ?? new Vec3(1.0, 1.0, 1.0)
152
+ this.bloomIntensity = options.bloomIntensity ?? 0.12
153
+ this.rimLightIntensity = options.rimLightIntensity ?? 0.45
154
+ this.cameraDistance = options.cameraDistance ?? 26.6
155
+ this.cameraTarget = options.cameraTarget ?? new Vec3(0, 12.5, 0)
156
+ }
157
+ }
158
+
159
+ // Step 1: Get WebGPU device and context
160
+ public async init() {
161
+ const adapter = await navigator.gpu?.requestAdapter()
162
+ const device = await adapter?.requestDevice()
163
+ if (!device) {
164
+ throw new Error("WebGPU is not supported in this browser.")
165
+ }
166
+ this.device = device
167
+
168
+ const context = this.canvas.getContext("webgpu")
169
+ if (!context) {
170
+ throw new Error("Failed to get WebGPU context.")
171
+ }
172
+ this.context = context
173
+
174
+ this.presentationFormat = navigator.gpu.getPreferredCanvasFormat()
175
+
176
+ this.context.configure({
177
+ device: this.device,
178
+ format: this.presentationFormat,
179
+ alphaMode: "premultiplied",
180
+ })
181
+
182
+ this.setupCamera()
183
+ this.setupLighting()
184
+ this.createPipelines()
185
+ this.createFullscreenQuad()
186
+ this.createBloomPipelines()
187
+ this.setupResize()
188
+ }
189
+
190
+ private createPipelines() {
191
+ this.materialSampler = this.device.createSampler({
192
+ magFilter: "linear",
193
+ minFilter: "linear",
194
+ addressModeU: "repeat",
195
+ addressModeV: "repeat",
196
+ })
197
+
198
+ const shaderModule = this.device.createShaderModule({
199
+ label: "model shaders",
200
+ code: /* wgsl */ `
201
+ struct CameraUniforms {
202
+ view: mat4x4f,
203
+ projection: mat4x4f,
204
+ viewPos: vec3f,
205
+ _padding: f32,
206
+ };
207
+
208
+ struct Light {
209
+ direction: vec3f,
210
+ _padding1: f32,
211
+ color: vec3f,
212
+ intensity: f32,
213
+ };
214
+
215
+ struct LightUniforms {
216
+ ambient: f32,
217
+ ambientColor: vec3f,
218
+ lightCount: f32,
219
+ _padding1: f32,
220
+ _padding2: f32,
221
+ lights: array<Light, 4>,
222
+ };
223
+
224
+ struct MaterialUniforms {
225
+ alpha: f32,
226
+ alphaMultiplier: f32,
227
+ rimIntensity: f32,
228
+ _padding1: f32,
229
+ rimColor: vec3f,
230
+ isOverEyes: f32, // 1.0 if rendering over eyes, 0.0 otherwise
231
+ };
232
+
233
+ struct VertexOutput {
234
+ @builtin(position) position: vec4f,
235
+ @location(0) normal: vec3f,
236
+ @location(1) uv: vec2f,
237
+ @location(2) worldPos: vec3f,
238
+ };
239
+
240
+ @group(0) @binding(0) var<uniform> camera: CameraUniforms;
241
+ @group(0) @binding(1) var<uniform> light: LightUniforms;
242
+ @group(0) @binding(2) var diffuseTexture: texture_2d<f32>;
243
+ @group(0) @binding(3) var diffuseSampler: sampler;
244
+ @group(0) @binding(4) var<storage, read> skinMats: array<mat4x4f>;
245
+ @group(0) @binding(5) var toonTexture: texture_2d<f32>;
246
+ @group(0) @binding(6) var toonSampler: sampler;
247
+ @group(0) @binding(7) var<uniform> material: MaterialUniforms;
248
+
249
+ @vertex fn vs(
250
+ @location(0) position: vec3f,
251
+ @location(1) normal: vec3f,
252
+ @location(2) uv: vec2f,
253
+ @location(3) joints0: vec4<u32>,
254
+ @location(4) weights0: vec4<f32>
255
+ ) -> VertexOutput {
256
+ var output: VertexOutput;
257
+ let pos4 = vec4f(position, 1.0);
258
+
259
+ // Branchless weight normalization (avoids GPU branch divergence)
260
+ let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
261
+ let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
262
+ let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
263
+
264
+ var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
265
+ var skinnedNrm = vec3f(0.0, 0.0, 0.0);
266
+ for (var i = 0u; i < 4u; i++) {
267
+ let j = joints0[i];
268
+ let w = normalizedWeights[i];
269
+ let m = skinMats[j];
270
+ skinnedPos += (m * pos4) * w;
271
+ let r3 = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz);
272
+ skinnedNrm += (r3 * normal) * w;
273
+ }
274
+ let worldPos = skinnedPos.xyz;
275
+ output.position = camera.projection * camera.view * vec4f(worldPos, 1.0);
276
+ output.normal = normalize(skinnedNrm);
277
+ output.uv = uv;
278
+ output.worldPos = worldPos;
279
+ return output;
280
+ }
281
+
282
+ @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
283
+ // Early alpha test - discard before expensive calculations
284
+ var finalAlpha = material.alpha * material.alphaMultiplier;
285
+ if (material.isOverEyes > 0.5) {
286
+ finalAlpha *= 0.5; // Hair over eyes gets 50% alpha
287
+ }
288
+ if (finalAlpha < 0.001) {
289
+ discard;
290
+ }
291
+
292
+ let n = normalize(input.normal);
293
+ let albedo = textureSample(diffuseTexture, diffuseSampler, input.uv).rgb;
294
+
295
+ var lightAccum = light.ambient * light.ambientColor;
296
+ let numLights = u32(light.lightCount);
297
+ for (var i = 0u; i < numLights; i++) {
298
+ let l = -light.lights[i].direction;
299
+ let nDotL = max(dot(n, l), 0.0);
300
+ let toonUV = vec2f(nDotL, 0.5);
301
+ let toonFactor = textureSample(toonTexture, toonSampler, toonUV).rgb;
302
+ let radiance = light.lights[i].color * light.lights[i].intensity;
303
+ lightAccum += toonFactor * radiance * nDotL;
304
+ }
305
+
306
+ // Rim light calculation
307
+ let viewDir = normalize(camera.viewPos - input.worldPos);
308
+ var rimFactor = 1.0 - max(dot(n, viewDir), 0.0);
309
+ rimFactor = rimFactor * rimFactor; // Optimized: direct multiply instead of pow(x, 2.0)
310
+ let rimLight = material.rimColor * material.rimIntensity * rimFactor;
311
+
312
+ let color = albedo * lightAccum + rimLight;
313
+
314
+ return vec4f(color, finalAlpha);
315
+ }
316
+ `,
317
+ })
318
+
319
+ // Create explicit bind group layout for all pipelines using the main shader
320
+ this.mainBindGroupLayout = this.device.createBindGroupLayout({
321
+ label: "main material bind group layout",
322
+ entries: [
323
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // camera
324
+ { binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // light
325
+ { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: {} }, // diffuseTexture
326
+ { binding: 3, visibility: GPUShaderStage.FRAGMENT, sampler: {} }, // diffuseSampler
327
+ { binding: 4, visibility: GPUShaderStage.VERTEX, buffer: { type: "read-only-storage" } }, // skinMats
328
+ { binding: 5, visibility: GPUShaderStage.FRAGMENT, texture: {} }, // toonTexture
329
+ { binding: 6, visibility: GPUShaderStage.FRAGMENT, sampler: {} }, // toonSampler
330
+ { binding: 7, visibility: GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // material
331
+ ],
332
+ })
333
+
334
+ const mainPipelineLayout = this.device.createPipelineLayout({
335
+ label: "main pipeline layout",
336
+ bindGroupLayouts: [this.mainBindGroupLayout],
337
+ })
338
+
339
+ this.modelPipeline = this.device.createRenderPipeline({
340
+ label: "model pipeline",
341
+ layout: mainPipelineLayout,
342
+ vertex: {
343
+ module: shaderModule,
344
+ buffers: [
345
+ {
346
+ arrayStride: 8 * 4,
347
+ attributes: [
348
+ { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
349
+ { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
350
+ { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
351
+ ],
352
+ },
353
+ {
354
+ arrayStride: 4 * 2,
355
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
356
+ },
357
+ {
358
+ arrayStride: 4,
359
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
360
+ },
361
+ ],
362
+ },
363
+ fragment: {
364
+ module: shaderModule,
365
+ targets: [
366
+ {
367
+ format: this.presentationFormat,
368
+ blend: {
369
+ color: {
370
+ srcFactor: "src-alpha",
371
+ dstFactor: "one-minus-src-alpha",
372
+ operation: "add",
373
+ },
374
+ alpha: {
375
+ srcFactor: "one",
376
+ dstFactor: "one-minus-src-alpha",
377
+ operation: "add",
378
+ },
379
+ },
380
+ },
381
+ ],
382
+ },
383
+ primitive: { cullMode: "none" },
384
+ depthStencil: {
385
+ format: "depth24plus-stencil8",
386
+ depthWriteEnabled: true,
387
+ depthCompare: "less-equal",
388
+ },
389
+ multisample: {
390
+ count: this.sampleCount,
391
+ },
392
+ })
393
+
394
+ // Create bind group layout for outline pipelines
395
+ this.outlineBindGroupLayout = this.device.createBindGroupLayout({
396
+ label: "outline bind group layout",
397
+ entries: [
398
+ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // camera
399
+ { binding: 1, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "uniform" } }, // material
400
+ { binding: 2, visibility: GPUShaderStage.VERTEX, buffer: { type: "read-only-storage" } }, // skinMats
401
+ ],
402
+ })
403
+
404
+ const outlinePipelineLayout = this.device.createPipelineLayout({
405
+ label: "outline pipeline layout",
406
+ bindGroupLayouts: [this.outlineBindGroupLayout],
407
+ })
408
+
409
+ const outlineShaderModule = this.device.createShaderModule({
410
+ label: "outline shaders",
411
+ code: /* wgsl */ `
412
+ struct CameraUniforms {
413
+ view: mat4x4f,
414
+ projection: mat4x4f,
415
+ viewPos: vec3f,
416
+ _padding: f32,
417
+ };
418
+
419
+ struct MaterialUniforms {
420
+ edgeColor: vec4f,
421
+ edgeSize: f32,
422
+ isOverEyes: f32, // 1.0 if rendering over eyes, 0.0 otherwise (for hair outlines)
423
+ _padding1: f32,
424
+ _padding2: f32,
425
+ };
426
+
427
+ @group(0) @binding(0) var<uniform> camera: CameraUniforms;
428
+ @group(0) @binding(1) var<uniform> material: MaterialUniforms;
429
+ @group(0) @binding(2) var<storage, read> skinMats: array<mat4x4f>;
430
+
431
+ struct VertexOutput {
432
+ @builtin(position) position: vec4f,
433
+ };
434
+
435
+ @vertex fn vs(
436
+ @location(0) position: vec3f,
437
+ @location(1) normal: vec3f,
438
+ @location(3) joints0: vec4<u32>,
439
+ @location(4) weights0: vec4<f32>
440
+ ) -> VertexOutput {
441
+ var output: VertexOutput;
442
+ let pos4 = vec4f(position, 1.0);
443
+
444
+ // Branchless weight normalization (avoids GPU branch divergence)
445
+ let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
446
+ let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
447
+ let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
448
+
449
+ var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
450
+ var skinnedNrm = vec3f(0.0, 0.0, 0.0);
451
+ for (var i = 0u; i < 4u; i++) {
452
+ let j = joints0[i];
453
+ let w = normalizedWeights[i];
454
+ let m = skinMats[j];
455
+ skinnedPos += (m * pos4) * w;
456
+ let r3 = mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz);
457
+ skinnedNrm += (r3 * normal) * w;
458
+ }
459
+ let worldPos = skinnedPos.xyz;
460
+ let worldNormal = normalize(skinnedNrm);
461
+
462
+ // MMD invert hull: expand vertices outward along normals
463
+ let scaleFactor = 0.01;
464
+ let expandedPos = worldPos + worldNormal * material.edgeSize * scaleFactor;
465
+ output.position = camera.projection * camera.view * vec4f(expandedPos, 1.0);
466
+ return output;
467
+ }
468
+
469
+ @fragment fn fs() -> @location(0) vec4f {
470
+ var color = material.edgeColor;
471
+
472
+ if (material.isOverEyes > 0.5) {
473
+ color.a *= 0.5; // Hair outlines over eyes get 50% alpha
474
+ }
475
+
476
+ return color;
477
+ }
478
+ `,
479
+ })
480
+
481
+ this.outlinePipeline = this.device.createRenderPipeline({
482
+ label: "outline pipeline",
483
+ layout: outlinePipelineLayout,
484
+ vertex: {
485
+ module: outlineShaderModule,
486
+ buffers: [
487
+ {
488
+ arrayStride: 8 * 4,
489
+ attributes: [
490
+ {
491
+ shaderLocation: 0,
492
+ offset: 0,
493
+ format: "float32x3" as GPUVertexFormat,
494
+ },
495
+ {
496
+ shaderLocation: 1,
497
+ offset: 3 * 4,
498
+ format: "float32x3" as GPUVertexFormat,
499
+ },
500
+ ],
501
+ },
502
+ {
503
+ arrayStride: 4 * 2,
504
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
505
+ },
506
+ {
507
+ arrayStride: 4,
508
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
509
+ },
510
+ ],
511
+ },
512
+ fragment: {
513
+ module: outlineShaderModule,
514
+ targets: [
515
+ {
516
+ format: this.presentationFormat,
517
+ blend: {
518
+ color: {
519
+ srcFactor: "src-alpha",
520
+ dstFactor: "one-minus-src-alpha",
521
+ operation: "add",
522
+ },
523
+ alpha: {
524
+ srcFactor: "one",
525
+ dstFactor: "one-minus-src-alpha",
526
+ operation: "add",
527
+ },
528
+ },
529
+ },
530
+ ],
531
+ },
532
+ primitive: {
533
+ cullMode: "back",
534
+ },
535
+ depthStencil: {
536
+ format: "depth24plus-stencil8",
537
+ depthWriteEnabled: true,
538
+ depthCompare: "less-equal",
539
+ },
540
+ multisample: {
541
+ count: this.sampleCount,
542
+ },
543
+ })
544
+
545
+ // Hair outline pipeline
546
+ this.hairOutlinePipeline = this.device.createRenderPipeline({
547
+ label: "hair outline pipeline",
548
+ layout: outlinePipelineLayout,
549
+ vertex: {
550
+ module: outlineShaderModule,
551
+ buffers: [
552
+ {
553
+ arrayStride: 8 * 4,
554
+ attributes: [
555
+ {
556
+ shaderLocation: 0,
557
+ offset: 0,
558
+ format: "float32x3" as GPUVertexFormat,
559
+ },
560
+ {
561
+ shaderLocation: 1,
562
+ offset: 3 * 4,
563
+ format: "float32x3" as GPUVertexFormat,
564
+ },
565
+ ],
566
+ },
567
+ {
568
+ arrayStride: 4 * 2,
569
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
570
+ },
571
+ {
572
+ arrayStride: 4,
573
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
574
+ },
575
+ ],
576
+ },
577
+ fragment: {
578
+ module: outlineShaderModule,
579
+ targets: [
580
+ {
581
+ format: this.presentationFormat,
582
+ blend: {
583
+ color: {
584
+ srcFactor: "src-alpha",
585
+ dstFactor: "one-minus-src-alpha",
586
+ operation: "add",
587
+ },
588
+ alpha: {
589
+ srcFactor: "one",
590
+ dstFactor: "one-minus-src-alpha",
591
+ operation: "add",
592
+ },
593
+ },
594
+ },
595
+ ],
596
+ },
597
+ primitive: {
598
+ cullMode: "back",
599
+ },
600
+ depthStencil: {
601
+ format: "depth24plus-stencil8",
602
+ depthWriteEnabled: false, // Don't write depth - let hair geometry control depth
603
+ depthCompare: "less-equal", // Only draw where hair depth exists (no stencil test needed)
604
+ depthBias: -0.0001, // Small negative bias to bring outline slightly closer for depth test
605
+ depthBiasSlopeScale: 0.0,
606
+ depthBiasClamp: 0.0,
607
+ },
608
+ multisample: {
609
+ count: this.sampleCount,
610
+ },
611
+ })
612
+
613
+ // Eye overlay pipeline (renders after opaque, writes stencil)
614
+ this.eyePipeline = this.device.createRenderPipeline({
615
+ label: "eye overlay pipeline",
616
+ layout: mainPipelineLayout,
617
+ vertex: {
618
+ module: shaderModule,
619
+ buffers: [
620
+ {
621
+ arrayStride: 8 * 4,
622
+ attributes: [
623
+ { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
624
+ { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
625
+ { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
626
+ ],
627
+ },
628
+ {
629
+ arrayStride: 4 * 2,
630
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
631
+ },
632
+ {
633
+ arrayStride: 4,
634
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
635
+ },
636
+ ],
637
+ },
638
+ fragment: {
639
+ module: shaderModule,
640
+ targets: [
641
+ {
642
+ format: this.presentationFormat,
643
+ blend: {
644
+ color: {
645
+ srcFactor: "src-alpha",
646
+ dstFactor: "one-minus-src-alpha",
647
+ operation: "add",
648
+ },
649
+ alpha: {
650
+ srcFactor: "one",
651
+ dstFactor: "one-minus-src-alpha",
652
+ operation: "add",
653
+ },
654
+ },
655
+ },
656
+ ],
657
+ },
658
+ primitive: { cullMode: "front" },
659
+ depthStencil: {
660
+ format: "depth24plus-stencil8",
661
+ depthWriteEnabled: true, // Write depth to occlude back of head
662
+ depthCompare: "less-equal", // More lenient to reduce precision conflicts
663
+ depthBias: -0.00005, // Reduced bias to minimize conflicts while still occluding back face
664
+ depthBiasSlopeScale: 0.0,
665
+ depthBiasClamp: 0.0,
666
+ stencilFront: {
667
+ compare: "always",
668
+ failOp: "keep",
669
+ depthFailOp: "keep",
670
+ passOp: "replace", // Write stencil value 1
671
+ },
672
+ stencilBack: {
673
+ compare: "always",
674
+ failOp: "keep",
675
+ depthFailOp: "keep",
676
+ passOp: "replace",
677
+ },
678
+ },
679
+ multisample: { count: this.sampleCount },
680
+ })
681
+
682
+ // Depth-only shader for hair pre-pass (reduces overdraw by early depth rejection)
683
+ const depthOnlyShaderModule = this.device.createShaderModule({
684
+ label: "depth only shader",
685
+ code: /* wgsl */ `
686
+ struct CameraUniforms {
687
+ view: mat4x4f,
688
+ projection: mat4x4f,
689
+ viewPos: vec3f,
690
+ _padding: f32,
691
+ };
692
+
693
+ @group(0) @binding(0) var<uniform> camera: CameraUniforms;
694
+ @group(0) @binding(4) var<storage, read> skinMats: array<mat4x4f>;
695
+
696
+ @vertex fn vs(
697
+ @location(0) position: vec3f,
698
+ @location(1) normal: vec3f,
699
+ @location(3) joints0: vec4<u32>,
700
+ @location(4) weights0: vec4<f32>
701
+ ) -> @builtin(position) vec4f {
702
+ let pos4 = vec4f(position, 1.0);
703
+
704
+ // Branchless weight normalization (avoids GPU branch divergence)
705
+ let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
706
+ let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
707
+ let normalizedWeights = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
708
+
709
+ var skinnedPos = vec4f(0.0, 0.0, 0.0, 0.0);
710
+ for (var i = 0u; i < 4u; i++) {
711
+ let j = joints0[i];
712
+ let w = normalizedWeights[i];
713
+ let m = skinMats[j];
714
+ skinnedPos += (m * pos4) * w;
715
+ }
716
+ let worldPos = skinnedPos.xyz;
717
+ let clipPos = camera.projection * camera.view * vec4f(worldPos, 1.0);
718
+ return clipPos;
719
+ }
720
+
721
+ @fragment fn fs() -> @location(0) vec4f {
722
+ return vec4f(0.0, 0.0, 0.0, 0.0); // Transparent - color writes disabled via writeMask
723
+ }
724
+ `,
725
+ })
726
+
727
+ // Hair depth pre-pass pipeline: depth-only with color writes disabled to eliminate overdraw
728
+ this.hairDepthPipeline = this.device.createRenderPipeline({
729
+ label: "hair depth pre-pass",
730
+ layout: mainPipelineLayout,
731
+ vertex: {
732
+ module: depthOnlyShaderModule,
733
+ buffers: [
734
+ {
735
+ arrayStride: 8 * 4,
736
+ attributes: [
737
+ { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
738
+ { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
739
+ ],
740
+ },
741
+ {
742
+ arrayStride: 4 * 2,
743
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
744
+ },
745
+ {
746
+ arrayStride: 4,
747
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
748
+ },
749
+ ],
750
+ },
751
+ fragment: {
752
+ module: depthOnlyShaderModule,
753
+ entryPoint: "fs",
754
+ targets: [
755
+ {
756
+ format: this.presentationFormat,
757
+ writeMask: 0, // Disable all color writes - we only care about depth
758
+ },
759
+ ],
760
+ },
761
+ primitive: { cullMode: "front" },
762
+ depthStencil: {
763
+ format: "depth24plus-stencil8",
764
+ depthWriteEnabled: true,
765
+ depthCompare: "less-equal", // Match the color pass compare mode for consistency
766
+ depthBias: 0.0,
767
+ depthBiasSlopeScale: 0.0,
768
+ depthBiasClamp: 0.0,
769
+ },
770
+ multisample: { count: this.sampleCount },
771
+ })
772
+
773
+ // Hair pipeline for rendering over eyes (stencil == 1)
774
+ this.hairPipelineOverEyes = this.device.createRenderPipeline({
775
+ label: "hair pipeline (over eyes)",
776
+ layout: mainPipelineLayout,
777
+ vertex: {
778
+ module: shaderModule,
779
+ buffers: [
780
+ {
781
+ arrayStride: 8 * 4,
782
+ attributes: [
783
+ { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
784
+ { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
785
+ { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
786
+ ],
787
+ },
788
+ {
789
+ arrayStride: 4 * 2,
790
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
791
+ },
792
+ {
793
+ arrayStride: 4,
794
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
795
+ },
796
+ ],
797
+ },
798
+ fragment: {
799
+ module: shaderModule,
800
+ targets: [
801
+ {
802
+ format: this.presentationFormat,
803
+ blend: {
804
+ color: {
805
+ srcFactor: "src-alpha",
806
+ dstFactor: "one-minus-src-alpha",
807
+ operation: "add",
808
+ },
809
+ alpha: {
810
+ srcFactor: "one",
811
+ dstFactor: "one-minus-src-alpha",
812
+ operation: "add",
813
+ },
814
+ },
815
+ },
816
+ ],
817
+ },
818
+ primitive: { cullMode: "front" },
819
+ depthStencil: {
820
+ format: "depth24plus-stencil8",
821
+ depthWriteEnabled: false, // Don't write depth (already written in pre-pass)
822
+ depthCompare: "less-equal", // More lenient than "equal" to avoid precision issues with MSAA
823
+ stencilFront: {
824
+ compare: "equal", // Only render where stencil == 1 (over eyes)
825
+ failOp: "keep",
826
+ depthFailOp: "keep",
827
+ passOp: "keep",
828
+ },
829
+ stencilBack: {
830
+ compare: "equal",
831
+ failOp: "keep",
832
+ depthFailOp: "keep",
833
+ passOp: "keep",
834
+ },
835
+ },
836
+ multisample: { count: this.sampleCount },
837
+ })
838
+
839
+ // Hair pipeline for rendering over non-eyes (stencil != 1)
840
+ this.hairPipelineOverNonEyes = this.device.createRenderPipeline({
841
+ label: "hair pipeline (over non-eyes)",
842
+ layout: mainPipelineLayout,
843
+ vertex: {
844
+ module: shaderModule,
845
+ buffers: [
846
+ {
847
+ arrayStride: 8 * 4,
848
+ attributes: [
849
+ { shaderLocation: 0, offset: 0, format: "float32x3" as GPUVertexFormat },
850
+ { shaderLocation: 1, offset: 3 * 4, format: "float32x3" as GPUVertexFormat },
851
+ { shaderLocation: 2, offset: 6 * 4, format: "float32x2" as GPUVertexFormat },
852
+ ],
853
+ },
854
+ {
855
+ arrayStride: 4 * 2,
856
+ attributes: [{ shaderLocation: 3, offset: 0, format: "uint16x4" as GPUVertexFormat }],
857
+ },
858
+ {
859
+ arrayStride: 4,
860
+ attributes: [{ shaderLocation: 4, offset: 0, format: "unorm8x4" as GPUVertexFormat }],
861
+ },
862
+ ],
863
+ },
864
+ fragment: {
865
+ module: shaderModule,
866
+ targets: [
867
+ {
868
+ format: this.presentationFormat,
869
+ blend: {
870
+ color: {
871
+ srcFactor: "src-alpha",
872
+ dstFactor: "one-minus-src-alpha",
873
+ operation: "add",
874
+ },
875
+ alpha: {
876
+ srcFactor: "one",
877
+ dstFactor: "one-minus-src-alpha",
878
+ operation: "add",
879
+ },
880
+ },
881
+ },
882
+ ],
883
+ },
884
+ primitive: { cullMode: "front" },
885
+ depthStencil: {
886
+ format: "depth24plus-stencil8",
887
+ depthWriteEnabled: false, // Don't write depth (already written in pre-pass)
888
+ depthCompare: "less-equal", // More lenient than "equal" to avoid precision issues with MSAA
889
+ stencilFront: {
890
+ compare: "not-equal", // Only render where stencil != 1 (over non-eyes)
891
+ failOp: "keep",
892
+ depthFailOp: "keep",
893
+ passOp: "keep",
894
+ },
895
+ stencilBack: {
896
+ compare: "not-equal",
897
+ failOp: "keep",
898
+ depthFailOp: "keep",
899
+ passOp: "keep",
900
+ },
901
+ },
902
+ multisample: { count: this.sampleCount },
903
+ })
904
+ }
905
+
906
+ // Create compute shader for skin matrix computation
907
+ private createSkinMatrixComputePipeline() {
908
+ const computeShader = this.device.createShaderModule({
909
+ label: "skin matrix compute",
910
+ code: /* wgsl */ `
911
+ struct BoneCountUniform {
912
+ count: u32,
913
+ _padding1: u32,
914
+ _padding2: u32,
915
+ _padding3: u32,
916
+ _padding4: vec4<u32>,
917
+ };
918
+
919
+ @group(0) @binding(0) var<uniform> boneCount: BoneCountUniform;
920
+ @group(0) @binding(1) var<storage, read> worldMatrices: array<mat4x4f>;
921
+ @group(0) @binding(2) var<storage, read> inverseBindMatrices: array<mat4x4f>;
922
+ @group(0) @binding(3) var<storage, read_write> skinMatrices: array<mat4x4f>;
923
+
924
+ @compute @workgroup_size(64) // Must match COMPUTE_WORKGROUP_SIZE
925
+ fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
926
+ let boneIndex = globalId.x;
927
+ if (boneIndex >= boneCount.count) {
928
+ return;
929
+ }
930
+ let worldMat = worldMatrices[boneIndex];
931
+ let invBindMat = inverseBindMatrices[boneIndex];
932
+ skinMatrices[boneIndex] = worldMat * invBindMat;
933
+ }
934
+ `,
935
+ })
936
+
937
+ this.skinMatrixComputePipeline = this.device.createComputePipeline({
938
+ label: "skin matrix compute pipeline",
939
+ layout: "auto",
940
+ compute: {
941
+ module: computeShader,
942
+ },
943
+ })
944
+ }
945
+
946
+ // Create fullscreen quad for post-processing
947
+ private createFullscreenQuad() {
948
+ // Fullscreen quad vertices: two triangles covering the entire screen - Format: position (x, y), uv (u, v)
949
+ const quadVertices = new Float32Array([
950
+ // Triangle 1
951
+ -1.0,
952
+ -1.0,
953
+ 0.0,
954
+ 0.0, // bottom-left
955
+ 1.0,
956
+ -1.0,
957
+ 1.0,
958
+ 0.0, // bottom-right
959
+ -1.0,
960
+ 1.0,
961
+ 0.0,
962
+ 1.0, // top-left
963
+ // Triangle 2
964
+ -1.0,
965
+ 1.0,
966
+ 0.0,
967
+ 1.0, // top-left
968
+ 1.0,
969
+ -1.0,
970
+ 1.0,
971
+ 0.0, // bottom-right
972
+ 1.0,
973
+ 1.0,
974
+ 1.0,
975
+ 1.0, // top-right
976
+ ])
977
+
978
+ this.fullscreenQuadBuffer = this.device.createBuffer({
979
+ label: "fullscreen quad",
980
+ size: quadVertices.byteLength,
981
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
982
+ })
983
+ this.device.queue.writeBuffer(this.fullscreenQuadBuffer, 0, quadVertices)
984
+ }
985
+
986
+ // Create bloom post-processing pipelines
987
+ private createBloomPipelines() {
988
+ // Bloom extraction shader (extracts bright areas)
989
+ const bloomExtractShader = this.device.createShaderModule({
990
+ label: "bloom extract",
991
+ code: /* wgsl */ `
992
+ struct VertexOutput {
993
+ @builtin(position) position: vec4f,
994
+ @location(0) uv: vec2f,
995
+ };
996
+
997
+ @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
998
+ var output: VertexOutput;
999
+ // Generate fullscreen quad from vertex index
1000
+ let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
1001
+ let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
1002
+ output.position = vec4f(x, y, 0.0, 1.0);
1003
+ output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1004
+ return output;
1005
+ }
1006
+
1007
+ struct BloomExtractUniforms {
1008
+ threshold: f32,
1009
+ _padding1: f32,
1010
+ _padding2: f32,
1011
+ _padding3: f32,
1012
+ _padding4: f32,
1013
+ _padding5: f32,
1014
+ _padding6: f32,
1015
+ _padding7: f32,
1016
+ };
1017
+
1018
+ @group(0) @binding(0) var inputTexture: texture_2d<f32>;
1019
+ @group(0) @binding(1) var inputSampler: sampler;
1020
+ @group(0) @binding(2) var<uniform> extractUniforms: BloomExtractUniforms;
1021
+
1022
+ @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1023
+ let color = textureSample(inputTexture, inputSampler, input.uv);
1024
+ // Extract bright areas above threshold
1025
+ let threshold = extractUniforms.threshold;
1026
+ let bloom = max(vec3f(0.0), color.rgb - vec3f(threshold)) / max(0.001, 1.0 - threshold);
1027
+ return vec4f(bloom, color.a);
1028
+ }
1029
+ `,
1030
+ })
1031
+
1032
+ // Bloom blur shader (gaussian blur - can be used for both horizontal and vertical)
1033
+ const bloomBlurShader = this.device.createShaderModule({
1034
+ label: "bloom blur",
1035
+ code: /* wgsl */ `
1036
+ struct VertexOutput {
1037
+ @builtin(position) position: vec4f,
1038
+ @location(0) uv: vec2f,
1039
+ };
1040
+
1041
+ @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
1042
+ var output: VertexOutput;
1043
+ let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
1044
+ let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
1045
+ output.position = vec4f(x, y, 0.0, 1.0);
1046
+ output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1047
+ return output;
1048
+ }
1049
+
1050
+ struct BlurUniforms {
1051
+ direction: vec2f,
1052
+ _padding1: f32,
1053
+ _padding2: f32,
1054
+ _padding3: f32,
1055
+ _padding4: f32,
1056
+ _padding5: f32,
1057
+ _padding6: f32,
1058
+ };
1059
+
1060
+ @group(0) @binding(0) var inputTexture: texture_2d<f32>;
1061
+ @group(0) @binding(1) var inputSampler: sampler;
1062
+ @group(0) @binding(2) var<uniform> blurUniforms: BlurUniforms;
1063
+
1064
+ // 3-tap gaussian blur using bilinear filtering trick (40% fewer texture fetches!)
1065
+ @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1066
+ let texelSize = 1.0 / vec2f(textureDimensions(inputTexture));
1067
+
1068
+ // Bilinear optimization: leverage hardware filtering to sample between pixels
1069
+ // Original 5-tap: weights [0.06136, 0.24477, 0.38774, 0.24477, 0.06136] at offsets [-2, -1, 0, 1, 2]
1070
+ // Optimized 3-tap: combine adjacent samples using weighted offsets
1071
+ let weight0 = 0.38774; // Center sample
1072
+ let weight1 = 0.24477 + 0.06136; // Combined outer samples = 0.30613
1073
+ let offset1 = (0.24477 * 1.0 + 0.06136 * 2.0) / weight1; // Weighted position = 1.2
1074
+
1075
+ var result = textureSample(inputTexture, inputSampler, input.uv) * weight0;
1076
+ let offsetVec = offset1 * texelSize * blurUniforms.direction;
1077
+ result += textureSample(inputTexture, inputSampler, input.uv + offsetVec) * weight1;
1078
+ result += textureSample(inputTexture, inputSampler, input.uv - offsetVec) * weight1;
1079
+
1080
+ return result;
1081
+ }
1082
+ `,
1083
+ })
1084
+
1085
+ // Bloom composition shader (combines original scene with bloom)
1086
+ const bloomComposeShader = this.device.createShaderModule({
1087
+ label: "bloom compose",
1088
+ code: /* wgsl */ `
1089
+ struct VertexOutput {
1090
+ @builtin(position) position: vec4f,
1091
+ @location(0) uv: vec2f,
1092
+ };
1093
+
1094
+ @vertex fn vs(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {
1095
+ var output: VertexOutput;
1096
+ let x = f32((vertexIndex << 1u) & 2u) * 2.0 - 1.0;
1097
+ let y = f32(vertexIndex & 2u) * 2.0 - 1.0;
1098
+ output.position = vec4f(x, y, 0.0, 1.0);
1099
+ output.uv = vec2f(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
1100
+ return output;
1101
+ }
1102
+
1103
+ struct BloomComposeUniforms {
1104
+ intensity: f32,
1105
+ _padding1: f32,
1106
+ _padding2: f32,
1107
+ _padding3: f32,
1108
+ _padding4: f32,
1109
+ _padding5: f32,
1110
+ _padding6: f32,
1111
+ _padding7: f32,
1112
+ };
1113
+
1114
+ @group(0) @binding(0) var sceneTexture: texture_2d<f32>;
1115
+ @group(0) @binding(1) var sceneSampler: sampler;
1116
+ @group(0) @binding(2) var bloomTexture: texture_2d<f32>;
1117
+ @group(0) @binding(3) var bloomSampler: sampler;
1118
+ @group(0) @binding(4) var<uniform> composeUniforms: BloomComposeUniforms;
1119
+
1120
+ @fragment fn fs(input: VertexOutput) -> @location(0) vec4f {
1121
+ let scene = textureSample(sceneTexture, sceneSampler, input.uv);
1122
+ let bloom = textureSample(bloomTexture, bloomSampler, input.uv);
1123
+ // Additive blending with intensity control
1124
+ let result = scene.rgb + bloom.rgb * composeUniforms.intensity;
1125
+ return vec4f(result, scene.a);
1126
+ }
1127
+ `,
1128
+ })
1129
+
1130
+ // Create uniform buffer for blur direction (minimum 32 bytes for WebGPU)
1131
+ const blurDirectionBuffer = this.device.createBuffer({
1132
+ label: "blur direction",
1133
+ size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1134
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1135
+ })
1136
+
1137
+ // Create uniform buffer for bloom intensity (minimum 32 bytes for WebGPU)
1138
+ const bloomIntensityBuffer = this.device.createBuffer({
1139
+ label: "bloom intensity",
1140
+ size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1141
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1142
+ })
1143
+
1144
+ // Create uniform buffer for bloom threshold (minimum 32 bytes for WebGPU)
1145
+ const bloomThresholdBuffer = this.device.createBuffer({
1146
+ label: "bloom threshold",
1147
+ size: 32, // Minimum 32 bytes required for uniform buffers in WebGPU
1148
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1149
+ })
1150
+
1151
+ // Set default bloom values
1152
+ const intensityData = new Float32Array(8) // f32 + 7 padding floats = 8 floats = 32 bytes
1153
+ intensityData[0] = this.bloomIntensity
1154
+ this.device.queue.writeBuffer(bloomIntensityBuffer, 0, intensityData)
1155
+
1156
+ const thresholdData = new Float32Array(8) // f32 + 7 padding floats = 8 floats = 32 bytes
1157
+ thresholdData[0] = this.bloomThreshold
1158
+ this.device.queue.writeBuffer(bloomThresholdBuffer, 0, thresholdData)
1159
+
1160
+ // Create linear sampler for post-processing
1161
+ const linearSampler = this.device.createSampler({
1162
+ magFilter: "linear",
1163
+ minFilter: "linear",
1164
+ addressModeU: "clamp-to-edge",
1165
+ addressModeV: "clamp-to-edge",
1166
+ })
1167
+
1168
+ // Bloom extraction pipeline
1169
+ this.bloomExtractPipeline = this.device.createRenderPipeline({
1170
+ label: "bloom extract",
1171
+ layout: "auto",
1172
+ vertex: {
1173
+ module: bloomExtractShader,
1174
+ entryPoint: "vs",
1175
+ },
1176
+ fragment: {
1177
+ module: bloomExtractShader,
1178
+ entryPoint: "fs",
1179
+ targets: [{ format: this.presentationFormat }],
1180
+ },
1181
+ primitive: { topology: "triangle-list" },
1182
+ })
1183
+
1184
+ // Bloom blur pipeline
1185
+ this.bloomBlurPipeline = this.device.createRenderPipeline({
1186
+ label: "bloom blur",
1187
+ layout: "auto",
1188
+ vertex: {
1189
+ module: bloomBlurShader,
1190
+ entryPoint: "vs",
1191
+ },
1192
+ fragment: {
1193
+ module: bloomBlurShader,
1194
+ entryPoint: "fs",
1195
+ targets: [{ format: this.presentationFormat }],
1196
+ },
1197
+ primitive: { topology: "triangle-list" },
1198
+ })
1199
+
1200
+ // Bloom composition pipeline
1201
+ this.bloomComposePipeline = this.device.createRenderPipeline({
1202
+ label: "bloom compose",
1203
+ layout: "auto",
1204
+ vertex: {
1205
+ module: bloomComposeShader,
1206
+ entryPoint: "vs",
1207
+ },
1208
+ fragment: {
1209
+ module: bloomComposeShader,
1210
+ entryPoint: "fs",
1211
+ targets: [{ format: this.presentationFormat }],
1212
+ },
1213
+ primitive: { topology: "triangle-list" },
1214
+ })
1215
+
1216
+ // Store buffers and sampler for later use
1217
+ this.blurDirectionBuffer = blurDirectionBuffer
1218
+ this.bloomIntensityBuffer = bloomIntensityBuffer
1219
+ this.bloomThresholdBuffer = bloomThresholdBuffer
1220
+ this.linearSampler = linearSampler
1221
+ }
1222
+
1223
+ private setupBloom(width: number, height: number) {
1224
+ const bloomWidth = Math.floor(width / this.BLOOM_DOWNSCALE_FACTOR)
1225
+ const bloomHeight = Math.floor(height / this.BLOOM_DOWNSCALE_FACTOR)
1226
+ this.bloomExtractTexture = this.device.createTexture({
1227
+ label: "bloom extract",
1228
+ size: [bloomWidth, bloomHeight],
1229
+ format: this.presentationFormat,
1230
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1231
+ })
1232
+ this.bloomBlurTexture1 = this.device.createTexture({
1233
+ label: "bloom blur 1",
1234
+ size: [bloomWidth, bloomHeight],
1235
+ format: this.presentationFormat,
1236
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1237
+ })
1238
+ this.bloomBlurTexture2 = this.device.createTexture({
1239
+ label: "bloom blur 2",
1240
+ size: [bloomWidth, bloomHeight],
1241
+ format: this.presentationFormat,
1242
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1243
+ })
1244
+
1245
+ // Create bloom bind groups
1246
+ this.bloomExtractBindGroup = this.device.createBindGroup({
1247
+ layout: this.bloomExtractPipeline.getBindGroupLayout(0),
1248
+ entries: [
1249
+ { binding: 0, resource: this.sceneRenderTexture.createView() },
1250
+ { binding: 1, resource: this.linearSampler },
1251
+ { binding: 2, resource: { buffer: this.bloomThresholdBuffer } },
1252
+ ],
1253
+ })
1254
+
1255
+ this.bloomBlurHBindGroup = this.device.createBindGroup({
1256
+ layout: this.bloomBlurPipeline.getBindGroupLayout(0),
1257
+ entries: [
1258
+ { binding: 0, resource: this.bloomExtractTexture.createView() },
1259
+ { binding: 1, resource: this.linearSampler },
1260
+ { binding: 2, resource: { buffer: this.blurDirectionBuffer } },
1261
+ ],
1262
+ })
1263
+
1264
+ this.bloomBlurVBindGroup = this.device.createBindGroup({
1265
+ layout: this.bloomBlurPipeline.getBindGroupLayout(0),
1266
+ entries: [
1267
+ { binding: 0, resource: this.bloomBlurTexture1.createView() },
1268
+ { binding: 1, resource: this.linearSampler },
1269
+ { binding: 2, resource: { buffer: this.blurDirectionBuffer } },
1270
+ ],
1271
+ })
1272
+
1273
+ this.bloomComposeBindGroup = this.device.createBindGroup({
1274
+ layout: this.bloomComposePipeline.getBindGroupLayout(0),
1275
+ entries: [
1276
+ { binding: 0, resource: this.sceneRenderTexture.createView() },
1277
+ { binding: 1, resource: this.linearSampler },
1278
+ { binding: 2, resource: this.bloomBlurTexture2.createView() },
1279
+ { binding: 3, resource: this.linearSampler },
1280
+ { binding: 4, resource: { buffer: this.bloomIntensityBuffer } },
1281
+ ],
1282
+ })
1283
+ }
1284
+
1285
+ // Step 3: Setup canvas resize handling
1286
+ private setupResize() {
1287
+ this.resizeObserver = new ResizeObserver(() => this.handleResize())
1288
+ this.resizeObserver.observe(this.canvas)
1289
+ this.handleResize()
1290
+ }
1291
+
1292
+ private handleResize() {
1293
+ const displayWidth = this.canvas.clientWidth
1294
+ const displayHeight = this.canvas.clientHeight
1295
+
1296
+ const dpr = window.devicePixelRatio || 1
1297
+ const width = Math.floor(displayWidth * dpr)
1298
+ const height = Math.floor(displayHeight * dpr)
1299
+
1300
+ if (!this.multisampleTexture || this.canvas.width !== width || this.canvas.height !== height) {
1301
+ this.canvas.width = width
1302
+ this.canvas.height = height
1303
+
1304
+ this.multisampleTexture = this.device.createTexture({
1305
+ label: "multisample render target",
1306
+ size: [width, height],
1307
+ sampleCount: this.sampleCount,
1308
+ format: this.presentationFormat,
1309
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
1310
+ })
1311
+
1312
+ this.depthTexture = this.device.createTexture({
1313
+ label: "depth texture",
1314
+ size: [width, height],
1315
+ sampleCount: this.sampleCount,
1316
+ format: "depth24plus-stencil8",
1317
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
1318
+ })
1319
+
1320
+ // Create scene render texture (non-multisampled for post-processing)
1321
+ this.sceneRenderTexture = this.device.createTexture({
1322
+ label: "scene render texture",
1323
+ size: [width, height],
1324
+ format: this.presentationFormat,
1325
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
1326
+ })
1327
+ this.sceneRenderTextureView = this.sceneRenderTexture.createView()
1328
+
1329
+ // Setup bloom textures and bind groups
1330
+ this.setupBloom(width, height)
1331
+
1332
+ const depthTextureView = this.depthTexture.createView()
1333
+
1334
+ // Render scene to texture instead of directly to canvas
1335
+ const colorAttachment: GPURenderPassColorAttachment =
1336
+ this.sampleCount > 1
1337
+ ? {
1338
+ view: this.multisampleTexture.createView(),
1339
+ resolveTarget: this.sceneRenderTextureView,
1340
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
1341
+ loadOp: "clear",
1342
+ storeOp: "store",
1343
+ }
1344
+ : {
1345
+ view: this.sceneRenderTextureView,
1346
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
1347
+ loadOp: "clear",
1348
+ storeOp: "store",
1349
+ }
1350
+
1351
+ this.renderPassDescriptor = {
1352
+ label: "renderPass",
1353
+ colorAttachments: [colorAttachment],
1354
+ depthStencilAttachment: {
1355
+ view: depthTextureView,
1356
+ depthClearValue: 1.0,
1357
+ depthLoadOp: "clear",
1358
+ depthStoreOp: "store",
1359
+ stencilClearValue: 0,
1360
+ stencilLoadOp: "clear",
1361
+ stencilStoreOp: "discard", // Discard stencil after frame to save bandwidth (we only use it during rendering)
1362
+ },
1363
+ }
1364
+
1365
+ this.camera.aspect = width / height
1366
+ }
1367
+ }
1368
+
1369
+ // Step 4: Create camera and uniform buffer
1370
+ private setupCamera() {
1371
+ this.cameraUniformBuffer = this.device.createBuffer({
1372
+ label: "camera uniforms",
1373
+ size: 40 * 4,
1374
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1375
+ })
1376
+
1377
+ this.camera = new Camera(Math.PI, Math.PI / 2.5, this.cameraDistance, this.cameraTarget)
1378
+
1379
+ this.camera.aspect = this.canvas.width / this.canvas.height
1380
+ this.camera.attachControl(this.canvas)
1381
+ }
1382
+
1383
+ // Step 5: Create lighting buffers
1384
+ private setupLighting() {
1385
+ this.lightUniformBuffer = this.device.createBuffer({
1386
+ label: "light uniforms",
1387
+ size: 64 * 4,
1388
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1389
+ })
1390
+
1391
+ this.lightCount = 0
1392
+
1393
+ this.setAmbient(this.ambient)
1394
+ this.setAmbientColor(this.ambientColor)
1395
+
1396
+ this.addLight(new Vec3(-0.5, -0.8, 0.5).normalize(), new Vec3(1.0, 0.95, 0.9), 0.02)
1397
+ this.addLight(new Vec3(0.7, -0.5, 0.3).normalize(), new Vec3(0.8, 0.85, 1.0), 0.015)
1398
+ this.addLight(new Vec3(0.3, -0.5, -1.0).normalize(), new Vec3(0.9, 0.9, 1.0), 0.01)
1399
+ this.device.queue.writeBuffer(this.lightUniformBuffer, 0, this.lightData)
1400
+ }
1401
+
1402
+ private addLight(direction: Vec3, color: Vec3, intensity: number = 1.0): boolean {
1403
+ if (this.lightCount >= 4) return false
1404
+
1405
+ const normalized = direction.normalize()
1406
+ const baseIndex = 12 + this.lightCount * 8
1407
+ this.lightData[baseIndex] = normalized.x
1408
+ this.lightData[baseIndex + 1] = normalized.y
1409
+ this.lightData[baseIndex + 2] = normalized.z
1410
+ this.lightData[baseIndex + 3] = 0
1411
+ this.lightData[baseIndex + 4] = color.x
1412
+ this.lightData[baseIndex + 5] = color.y
1413
+ this.lightData[baseIndex + 6] = color.z
1414
+ this.lightData[baseIndex + 7] = intensity
1415
+
1416
+ this.lightCount++
1417
+ // lightCount: f32 at offset 28 (index 7)
1418
+ // Layout: ambient (0), padding (1-3), ambientColor (4-6, padding 7), lightCount (8), _padding1 (9), _padding2 (10), lights start at 12
1419
+ this.lightData[8] = this.lightCount
1420
+ return true
1421
+ }
1422
+
1423
+ private setAmbient(intensity: number) {
1424
+ // ambient: f32 at offset 0 (index 0)
1425
+ this.lightData[0] = intensity
1426
+ }
1427
+
1428
+ private setAmbientColor(color: Vec3) {
1429
+ this.lightData[4] = color.x
1430
+ this.lightData[5] = color.y
1431
+ this.lightData[6] = color.z
1432
+ // Index 7 is padding for vec3f alignment (must be 0)
1433
+ this.lightData[7] = 0.0
1434
+ }
1435
+
1436
+ public async loadAnimation(url: string) {
1437
+ const frames = await VMDLoader.load(url)
1438
+ this.animationFrames = frames
1439
+ this.hasAnimation = true
1440
+ }
1441
+
1442
+ public playAnimation(options?: {
1443
+ breathBones?: string[] | Record<string, number> // Array of bone names or map of bone name -> rotation range
1444
+ breathDuration?: number // Breathing cycle duration in milliseconds
1445
+ }) {
1446
+ if (this.animationFrames.length === 0) return
1447
+
1448
+ this.stopAnimation()
1449
+ this.stopBreathing()
1450
+ this.playingAnimation = true
1451
+
1452
+ // Enable breathing if breathBones is provided
1453
+ const enableBreath = options?.breathBones !== undefined && options.breathBones !== null
1454
+ let breathBones: string[] = []
1455
+ let breathRotationRanges: Record<string, number> | undefined = undefined
1456
+
1457
+ if (enableBreath && options.breathBones) {
1458
+ if (Array.isArray(options.breathBones)) {
1459
+ breathBones = options.breathBones
1460
+ } else {
1461
+ breathBones = Object.keys(options.breathBones)
1462
+ breathRotationRanges = options.breathBones
1463
+ }
1464
+ }
1465
+
1466
+ const breathDuration = options?.breathDuration ?? 4000
1467
+
1468
+ const allBoneKeyFrames: BoneKeyFrame[] = []
1469
+ for (const keyFrame of this.animationFrames) {
1470
+ for (const boneFrame of keyFrame.boneFrames) {
1471
+ allBoneKeyFrames.push({
1472
+ boneName: boneFrame.boneName,
1473
+ time: keyFrame.time,
1474
+ rotation: boneFrame.rotation,
1475
+ })
1476
+ }
1477
+ }
1478
+
1479
+ const boneKeyFramesByBone = new Map<string, BoneKeyFrame[]>()
1480
+ for (const boneKeyFrame of allBoneKeyFrames) {
1481
+ if (!boneKeyFramesByBone.has(boneKeyFrame.boneName)) {
1482
+ boneKeyFramesByBone.set(boneKeyFrame.boneName, [])
1483
+ }
1484
+ boneKeyFramesByBone.get(boneKeyFrame.boneName)!.push(boneKeyFrame)
1485
+ }
1486
+
1487
+ for (const keyFrames of boneKeyFramesByBone.values()) {
1488
+ keyFrames.sort((a, b) => a.time - b.time)
1489
+ }
1490
+
1491
+ const time0Rotations: Array<{ boneName: string; rotation: Quat }> = []
1492
+ const bonesWithTime0 = new Set<string>()
1493
+ for (const [boneName, keyFrames] of boneKeyFramesByBone.entries()) {
1494
+ if (keyFrames.length > 0 && keyFrames[0].time === 0) {
1495
+ time0Rotations.push({
1496
+ boneName: boneName,
1497
+ rotation: keyFrames[0].rotation,
1498
+ })
1499
+ bonesWithTime0.add(boneName)
1500
+ }
1501
+ }
1502
+
1503
+ if (this.currentModel) {
1504
+ if (time0Rotations.length > 0) {
1505
+ const boneNames = time0Rotations.map((r) => r.boneName)
1506
+ const rotations = time0Rotations.map((r) => r.rotation)
1507
+ this.rotateBones(boneNames, rotations, 0)
1508
+ }
1509
+
1510
+ const skeleton = this.currentModel.getSkeleton()
1511
+ const bonesToReset: string[] = []
1512
+ for (const bone of skeleton.bones) {
1513
+ if (!bonesWithTime0.has(bone.name)) {
1514
+ bonesToReset.push(bone.name)
1515
+ }
1516
+ }
1517
+
1518
+ if (bonesToReset.length > 0) {
1519
+ const identityQuat = new Quat(0, 0, 0, 1)
1520
+ const identityQuats = new Array(bonesToReset.length).fill(identityQuat)
1521
+ this.rotateBones(bonesToReset, identityQuats, 0)
1522
+ }
1523
+
1524
+ // Reset physics immediately and upload matrices to prevent A-pose flash
1525
+ if (this.physics) {
1526
+ this.currentModel.evaluatePose()
1527
+
1528
+ const worldMats = this.currentModel.getBoneWorldMatrices()
1529
+ this.physics.reset(worldMats, this.currentModel.getBoneInverseBindMatrices())
1530
+
1531
+ // Upload matrices immediately so next frame shows correct pose
1532
+ this.device.queue.writeBuffer(
1533
+ this.worldMatrixBuffer!,
1534
+ 0,
1535
+ worldMats.buffer,
1536
+ worldMats.byteOffset,
1537
+ worldMats.byteLength
1538
+ )
1539
+ const encoder = this.device.createCommandEncoder()
1540
+ this.computeSkinMatrices(encoder)
1541
+ this.device.queue.submit([encoder.finish()])
1542
+ }
1543
+ }
1544
+ for (const [_, keyFrames] of boneKeyFramesByBone.entries()) {
1545
+ for (let i = 0; i < keyFrames.length; i++) {
1546
+ const boneKeyFrame = keyFrames[i]
1547
+ const previousBoneKeyFrame = i > 0 ? keyFrames[i - 1] : null
1548
+
1549
+ if (boneKeyFrame.time === 0) continue
1550
+
1551
+ let durationMs = 0
1552
+ if (i === 0) {
1553
+ durationMs = boneKeyFrame.time * 1000
1554
+ } else if (previousBoneKeyFrame) {
1555
+ durationMs = (boneKeyFrame.time - previousBoneKeyFrame.time) * 1000
1556
+ }
1557
+
1558
+ const scheduleTime = i > 0 && previousBoneKeyFrame ? previousBoneKeyFrame.time : 0
1559
+ const delayMs = scheduleTime * 1000
1560
+
1561
+ if (delayMs <= 0) {
1562
+ this.rotateBones([boneKeyFrame.boneName], [boneKeyFrame.rotation], durationMs)
1563
+ } else {
1564
+ const timeoutId = window.setTimeout(() => {
1565
+ this.rotateBones([boneKeyFrame.boneName], [boneKeyFrame.rotation], durationMs)
1566
+ }, delayMs)
1567
+ this.animationTimeouts.push(timeoutId)
1568
+ }
1569
+ }
1570
+ }
1571
+
1572
+ // Setup breathing animation if enabled
1573
+ if (enableBreath && this.currentModel) {
1574
+ // Find the last frame time
1575
+ let maxTime = 0
1576
+ for (const keyFrame of this.animationFrames) {
1577
+ if (keyFrame.time > maxTime) {
1578
+ maxTime = keyFrame.time
1579
+ }
1580
+ }
1581
+
1582
+ // Get last frame rotations directly from animation data for breathing bones
1583
+ const lastFrameRotations = new Map<string, Quat>()
1584
+ for (const bone of breathBones) {
1585
+ const keyFrames = boneKeyFramesByBone.get(bone)
1586
+ if (keyFrames && keyFrames.length > 0) {
1587
+ // Find the rotation at the last frame time (closest keyframe <= maxTime)
1588
+ let lastRotation: Quat | null = null
1589
+ for (let i = keyFrames.length - 1; i >= 0; i--) {
1590
+ if (keyFrames[i].time <= maxTime) {
1591
+ lastRotation = keyFrames[i].rotation
1592
+ break
1593
+ }
1594
+ }
1595
+ if (lastRotation) {
1596
+ lastFrameRotations.set(bone, lastRotation)
1597
+ }
1598
+ }
1599
+ }
1600
+
1601
+ // Start breathing after animation completes
1602
+ // Use the last frame rotations directly from animation data (no need to capture from model)
1603
+ const animationEndTime = maxTime * 1000 + 200 // Small buffer for final tweens to complete
1604
+ this.breathingTimeout = window.setTimeout(() => {
1605
+ this.startBreathing(breathBones, lastFrameRotations, breathRotationRanges, breathDuration)
1606
+ }, animationEndTime)
1607
+ }
1608
+ }
1609
+
1610
+ public stopAnimation() {
1611
+ for (const timeoutId of this.animationTimeouts) {
1612
+ clearTimeout(timeoutId)
1613
+ }
1614
+ this.animationTimeouts = []
1615
+ this.playingAnimation = false
1616
+ }
1617
+
1618
+ private stopBreathing() {
1619
+ if (this.breathingTimeout !== null) {
1620
+ clearTimeout(this.breathingTimeout)
1621
+ this.breathingTimeout = null
1622
+ }
1623
+ this.breathingBaseRotations.clear()
1624
+ }
1625
+
1626
+ private startBreathing(
1627
+ bones: string[],
1628
+ baseRotations: Map<string, Quat>,
1629
+ rotationRanges?: Record<string, number>,
1630
+ durationMs: number = 4000
1631
+ ) {
1632
+ if (!this.currentModel) return
1633
+
1634
+ // Store base rotations directly from last frame of animation data
1635
+ // These are the exact rotations from the animation - use them as-is
1636
+ for (const bone of bones) {
1637
+ const baseRot = baseRotations.get(bone)
1638
+ if (baseRot) {
1639
+ this.breathingBaseRotations.set(bone, baseRot)
1640
+ }
1641
+ }
1642
+
1643
+ const halfCycleMs = durationMs / 2
1644
+ const defaultRotation = 0.02 // Default rotation range if not specified per bone
1645
+
1646
+ // Start breathing cycle - oscillate around exact base rotation (final pose)
1647
+ // Each bone can have its own rotation range, or use default
1648
+ const animate = (isInhale: boolean) => {
1649
+ if (!this.currentModel) return
1650
+
1651
+ const breathingBoneNames: string[] = []
1652
+ const breathingQuats: Quat[] = []
1653
+
1654
+ for (const bone of bones) {
1655
+ const baseRot = this.breathingBaseRotations.get(bone)
1656
+ if (!baseRot) continue
1657
+
1658
+ // Get rotation range for this bone (per-bone or default)
1659
+ const rotation = rotationRanges?.[bone] ?? defaultRotation
1660
+
1661
+ // Oscillate around base rotation with the bone's rotation range
1662
+ // isInhale: base * rotation, exhale: base * (-rotation)
1663
+ const oscillationRot = Quat.fromEuler(isInhale ? rotation : -rotation, 0, 0)
1664
+ const finalRot = baseRot.multiply(oscillationRot)
1665
+
1666
+ breathingBoneNames.push(bone)
1667
+ breathingQuats.push(finalRot)
1668
+ }
1669
+
1670
+ if (breathingBoneNames.length > 0) {
1671
+ this.rotateBones(breathingBoneNames, breathingQuats, halfCycleMs)
1672
+ }
1673
+
1674
+ this.breathingTimeout = window.setTimeout(() => animate(!isInhale), halfCycleMs)
1675
+ }
1676
+
1677
+ // Start breathing from exhale position (closer to base) to minimize initial movement
1678
+ animate(false)
1679
+ }
1680
+
1681
+ public getStats(): EngineStats {
1682
+ return { ...this.stats }
1683
+ }
1684
+
1685
+ public runRenderLoop(callback?: () => void) {
1686
+ this.renderLoopCallback = callback || null
1687
+
1688
+ const loop = () => {
1689
+ this.render()
1690
+
1691
+ if (this.renderLoopCallback) {
1692
+ this.renderLoopCallback()
1693
+ }
1694
+
1695
+ this.animationFrameId = requestAnimationFrame(loop)
1696
+ }
1697
+
1698
+ this.animationFrameId = requestAnimationFrame(loop)
1699
+ }
1700
+
1701
+ public stopRenderLoop() {
1702
+ if (this.animationFrameId !== null) {
1703
+ cancelAnimationFrame(this.animationFrameId)
1704
+ this.animationFrameId = null
1705
+ }
1706
+ this.renderLoopCallback = null
1707
+ }
1708
+
1709
+ public dispose() {
1710
+ this.stopRenderLoop()
1711
+ this.stopAnimation()
1712
+ this.stopBreathing()
1713
+ if (this.camera) this.camera.detachControl()
1714
+ if (this.resizeObserver) {
1715
+ this.resizeObserver.disconnect()
1716
+ this.resizeObserver = null
1717
+ }
1718
+ }
1719
+
1720
+ // Step 6: Load PMX model file
1721
+ public async loadModel(path: string) {
1722
+ const pathParts = path.split("/")
1723
+ pathParts.pop()
1724
+ const dir = pathParts.join("/") + "/"
1725
+ this.modelDir = dir
1726
+
1727
+ const model = await PmxLoader.load(path)
1728
+ // console.log({
1729
+ // vertices: Array.from(model.getVertices()),
1730
+ // indices: Array.from(model.getIndices()),
1731
+ // materials: model.getMaterials(),
1732
+ // textures: model.getTextures(),
1733
+ // bones: model.getSkeleton().bones,
1734
+ // skinning: { joints: Array.from(model.getSkinning().joints), weights: Array.from(model.getSkinning().weights) },
1735
+ // })
1736
+ this.physics = new Physics(model.getRigidbodies(), model.getJoints())
1737
+ await this.setupModelBuffers(model)
1738
+ }
1739
+
1740
+ public rotateBones(bones: string[], rotations: Quat[], durationMs?: number) {
1741
+ this.currentModel?.rotateBones(bones, rotations, durationMs)
1742
+ }
1743
+
1744
+ // Step 7: Create vertex, index, and joint buffers
1745
+ private async setupModelBuffers(model: Model) {
1746
+ this.currentModel = model
1747
+ const vertices = model.getVertices()
1748
+ const skinning = model.getSkinning()
1749
+ const skeleton = model.getSkeleton()
1750
+
1751
+ this.vertexBuffer = this.device.createBuffer({
1752
+ label: "model vertex buffer",
1753
+ size: vertices.byteLength,
1754
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1755
+ })
1756
+ this.device.queue.writeBuffer(this.vertexBuffer, 0, vertices)
1757
+
1758
+ this.jointsBuffer = this.device.createBuffer({
1759
+ label: "joints buffer",
1760
+ size: skinning.joints.byteLength,
1761
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1762
+ })
1763
+ this.device.queue.writeBuffer(
1764
+ this.jointsBuffer,
1765
+ 0,
1766
+ skinning.joints.buffer,
1767
+ skinning.joints.byteOffset,
1768
+ skinning.joints.byteLength
1769
+ )
1770
+
1771
+ this.weightsBuffer = this.device.createBuffer({
1772
+ label: "weights buffer",
1773
+ size: skinning.weights.byteLength,
1774
+ usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
1775
+ })
1776
+ this.device.queue.writeBuffer(
1777
+ this.weightsBuffer,
1778
+ 0,
1779
+ skinning.weights.buffer,
1780
+ skinning.weights.byteOffset,
1781
+ skinning.weights.byteLength
1782
+ )
1783
+
1784
+ const boneCount = skeleton.bones.length
1785
+ const matrixSize = boneCount * 16 * 4
1786
+
1787
+ this.skinMatrixBuffer = this.device.createBuffer({
1788
+ label: "skin matrices",
1789
+ size: Math.max(256, matrixSize),
1790
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX,
1791
+ })
1792
+
1793
+ this.worldMatrixBuffer = this.device.createBuffer({
1794
+ label: "world matrices",
1795
+ size: Math.max(256, matrixSize),
1796
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
1797
+ })
1798
+
1799
+ this.inverseBindMatrixBuffer = this.device.createBuffer({
1800
+ label: "inverse bind matrices",
1801
+ size: Math.max(256, matrixSize),
1802
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
1803
+ })
1804
+
1805
+ const invBindMatrices = skeleton.inverseBindMatrices
1806
+ this.device.queue.writeBuffer(
1807
+ this.inverseBindMatrixBuffer,
1808
+ 0,
1809
+ invBindMatrices.buffer,
1810
+ invBindMatrices.byteOffset,
1811
+ invBindMatrices.byteLength
1812
+ )
1813
+
1814
+ this.boneCountBuffer = this.device.createBuffer({
1815
+ label: "bone count uniform",
1816
+ size: 32, // Minimum uniform buffer size is 32 bytes
1817
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1818
+ })
1819
+ const boneCountData = new Uint32Array(8) // 32 bytes total
1820
+ boneCountData[0] = boneCount
1821
+ this.device.queue.writeBuffer(this.boneCountBuffer, 0, boneCountData)
1822
+
1823
+ this.createSkinMatrixComputePipeline()
1824
+
1825
+ // Create compute bind group once (reused every frame)
1826
+ this.skinMatrixComputeBindGroup = this.device.createBindGroup({
1827
+ layout: this.skinMatrixComputePipeline!.getBindGroupLayout(0),
1828
+ entries: [
1829
+ { binding: 0, resource: { buffer: this.boneCountBuffer } },
1830
+ { binding: 1, resource: { buffer: this.worldMatrixBuffer } },
1831
+ { binding: 2, resource: { buffer: this.inverseBindMatrixBuffer } },
1832
+ { binding: 3, resource: { buffer: this.skinMatrixBuffer } },
1833
+ ],
1834
+ })
1835
+
1836
+ const indices = model.getIndices()
1837
+ if (indices) {
1838
+ this.indexBuffer = this.device.createBuffer({
1839
+ label: "model index buffer",
1840
+ size: indices.byteLength,
1841
+ usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
1842
+ })
1843
+ this.device.queue.writeBuffer(this.indexBuffer, 0, indices)
1844
+ } else {
1845
+ throw new Error("Model has no index buffer")
1846
+ }
1847
+
1848
+ await this.setupMaterials(model)
1849
+ }
1850
+
1851
+ private async setupMaterials(model: Model) {
1852
+ const materials = model.getMaterials()
1853
+ if (materials.length === 0) {
1854
+ throw new Error("Model has no materials")
1855
+ }
1856
+
1857
+ const textures = model.getTextures()
1858
+
1859
+ const loadTextureByIndex = async (texIndex: number): Promise<GPUTexture | null> => {
1860
+ if (texIndex < 0 || texIndex >= textures.length) {
1861
+ return null
1862
+ }
1863
+
1864
+ const path = this.modelDir + textures[texIndex].path
1865
+ const texture = await this.createTextureFromPath(path)
1866
+ return texture
1867
+ }
1868
+
1869
+ const loadToonTexture = async (toonTextureIndex: number): Promise<GPUTexture> => {
1870
+ const texture = await loadTextureByIndex(toonTextureIndex)
1871
+ if (texture) return texture
1872
+
1873
+ // Default toon texture fallback - cache it
1874
+ const defaultToonPath = "__default_toon__"
1875
+ const cached = this.textureCache.get(defaultToonPath)
1876
+ if (cached) return cached
1877
+
1878
+ const defaultToonData = new Uint8Array(256 * 2 * 4)
1879
+ for (let i = 0; i < 256; i++) {
1880
+ const factor = i / 255.0
1881
+ const gray = Math.floor(128 + factor * 127)
1882
+ defaultToonData[i * 4] = gray
1883
+ defaultToonData[i * 4 + 1] = gray
1884
+ defaultToonData[i * 4 + 2] = gray
1885
+ defaultToonData[i * 4 + 3] = 255
1886
+ defaultToonData[(256 + i) * 4] = gray
1887
+ defaultToonData[(256 + i) * 4 + 1] = gray
1888
+ defaultToonData[(256 + i) * 4 + 2] = gray
1889
+ defaultToonData[(256 + i) * 4 + 3] = 255
1890
+ }
1891
+ const defaultToonTexture = this.device.createTexture({
1892
+ label: "default toon texture",
1893
+ size: [256, 2],
1894
+ format: "rgba8unorm",
1895
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
1896
+ })
1897
+ this.device.queue.writeTexture(
1898
+ { texture: defaultToonTexture },
1899
+ defaultToonData,
1900
+ { bytesPerRow: 256 * 4 },
1901
+ [256, 2]
1902
+ )
1903
+ this.textureCache.set(defaultToonPath, defaultToonTexture)
1904
+ return defaultToonTexture
1905
+ }
1906
+
1907
+ this.opaqueDraws = []
1908
+ this.eyeDraws = []
1909
+ this.hairDrawsOverEyes = []
1910
+ this.hairDrawsOverNonEyes = []
1911
+ this.transparentDraws = []
1912
+ this.opaqueOutlineDraws = []
1913
+ this.eyeOutlineDraws = []
1914
+ this.hairOutlineDraws = []
1915
+ this.transparentOutlineDraws = []
1916
+ let currentIndexOffset = 0
1917
+
1918
+ for (const mat of materials) {
1919
+ const indexCount = mat.vertexCount
1920
+ if (indexCount === 0) continue
1921
+
1922
+ const diffuseTexture = await loadTextureByIndex(mat.diffuseTextureIndex)
1923
+ if (!diffuseTexture) throw new Error(`Material "${mat.name}" has no diffuse texture`)
1924
+
1925
+ const toonTexture = await loadToonTexture(mat.toonTextureIndex)
1926
+
1927
+ const materialAlpha = mat.diffuse[3]
1928
+ const EPSILON = 0.001
1929
+ const isTransparent = materialAlpha < 1.0 - EPSILON
1930
+
1931
+ // Create material uniform data
1932
+ const materialUniformData = new Float32Array(8)
1933
+ materialUniformData[0] = materialAlpha
1934
+ materialUniformData[1] = 1.0 // alphaMultiplier: 1.0 for non-hair materials
1935
+ materialUniformData[2] = this.rimLightIntensity
1936
+ materialUniformData[3] = 0.0 // _padding1
1937
+ materialUniformData[4] = 1.0 // rimColor.r
1938
+ materialUniformData[5] = 1.0 // rimColor.g
1939
+ materialUniformData[6] = 1.0 // rimColor.b
1940
+ materialUniformData[7] = 0.0 // isOverEyes
1941
+
1942
+ const materialUniformBuffer = this.device.createBuffer({
1943
+ label: `material uniform: ${mat.name}`,
1944
+ size: materialUniformData.byteLength,
1945
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1946
+ })
1947
+ this.device.queue.writeBuffer(materialUniformBuffer, 0, materialUniformData)
1948
+
1949
+ // Create bind groups using the shared bind group layout - All pipelines (main, eye, hair multiply, hair opaque) use the same shader and layout
1950
+ const bindGroup = this.device.createBindGroup({
1951
+ label: `material bind group: ${mat.name}`,
1952
+ layout: this.mainBindGroupLayout,
1953
+ entries: [
1954
+ { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
1955
+ { binding: 1, resource: { buffer: this.lightUniformBuffer } },
1956
+ { binding: 2, resource: diffuseTexture.createView() },
1957
+ { binding: 3, resource: this.materialSampler },
1958
+ { binding: 4, resource: { buffer: this.skinMatrixBuffer! } },
1959
+ { binding: 5, resource: toonTexture.createView() },
1960
+ { binding: 6, resource: this.materialSampler },
1961
+ { binding: 7, resource: { buffer: materialUniformBuffer } },
1962
+ ],
1963
+ })
1964
+
1965
+ if (mat.isEye) {
1966
+ this.eyeDraws.push({
1967
+ count: indexCount,
1968
+ firstIndex: currentIndexOffset,
1969
+ bindGroup,
1970
+ isTransparent,
1971
+ })
1972
+ } else if (mat.isHair) {
1973
+ // Hair materials: create separate bind groups for over-eyes vs over-non-eyes
1974
+ const createHairBindGroup = (isOverEyes: boolean) => {
1975
+ const uniformData = new Float32Array(8)
1976
+ uniformData[0] = materialAlpha
1977
+ uniformData[1] = 1.0 // alphaMultiplier (shader adjusts based on isOverEyes)
1978
+ uniformData[2] = this.rimLightIntensity
1979
+ uniformData[3] = 0.0 // _padding1
1980
+ uniformData[4] = 1.0 // rimColor.rgb
1981
+ uniformData[5] = 1.0
1982
+ uniformData[6] = 1.0
1983
+ uniformData[7] = isOverEyes ? 1.0 : 0.0 // isOverEyes
1984
+
1985
+ const buffer = this.device.createBuffer({
1986
+ label: `material uniform (${isOverEyes ? "over eyes" : "over non-eyes"}): ${mat.name}`,
1987
+ size: uniformData.byteLength,
1988
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
1989
+ })
1990
+ this.device.queue.writeBuffer(buffer, 0, uniformData)
1991
+
1992
+ return this.device.createBindGroup({
1993
+ label: `material bind group (${isOverEyes ? "over eyes" : "over non-eyes"}): ${mat.name}`,
1994
+ layout: this.mainBindGroupLayout,
1995
+ entries: [
1996
+ { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
1997
+ { binding: 1, resource: { buffer: this.lightUniformBuffer } },
1998
+ { binding: 2, resource: diffuseTexture.createView() },
1999
+ { binding: 3, resource: this.materialSampler },
2000
+ { binding: 4, resource: { buffer: this.skinMatrixBuffer! } },
2001
+ { binding: 5, resource: toonTexture.createView() },
2002
+ { binding: 6, resource: this.materialSampler },
2003
+ { binding: 7, resource: { buffer: buffer } },
2004
+ ],
2005
+ })
2006
+ }
2007
+
2008
+ const bindGroupOverEyes = createHairBindGroup(true)
2009
+ const bindGroupOverNonEyes = createHairBindGroup(false)
2010
+
2011
+ this.hairDrawsOverEyes.push({
2012
+ count: indexCount,
2013
+ firstIndex: currentIndexOffset,
2014
+ bindGroup: bindGroupOverEyes,
2015
+ isTransparent,
2016
+ })
2017
+
2018
+ this.hairDrawsOverNonEyes.push({
2019
+ count: indexCount,
2020
+ firstIndex: currentIndexOffset,
2021
+ bindGroup: bindGroupOverNonEyes,
2022
+ isTransparent,
2023
+ })
2024
+ } else if (isTransparent) {
2025
+ this.transparentDraws.push({
2026
+ count: indexCount,
2027
+ firstIndex: currentIndexOffset,
2028
+ bindGroup,
2029
+ isTransparent,
2030
+ })
2031
+ } else {
2032
+ this.opaqueDraws.push({
2033
+ count: indexCount,
2034
+ firstIndex: currentIndexOffset,
2035
+ bindGroup,
2036
+ isTransparent,
2037
+ })
2038
+ }
2039
+
2040
+ // Edge flag is at bit 4 (0x10) in PMX format
2041
+ if ((mat.edgeFlag & 0x10) !== 0 && mat.edgeSize > 0) {
2042
+ const materialUniformData = new Float32Array(8)
2043
+ materialUniformData[0] = mat.edgeColor[0] // edgeColor.r
2044
+ materialUniformData[1] = mat.edgeColor[1] // edgeColor.g
2045
+ materialUniformData[2] = mat.edgeColor[2] // edgeColor.b
2046
+ materialUniformData[3] = mat.edgeColor[3] // edgeColor.a
2047
+ materialUniformData[4] = mat.edgeSize
2048
+ materialUniformData[5] = 0.0 // isOverEyes
2049
+ materialUniformData[6] = 0.0
2050
+ materialUniformData[7] = 0.0
2051
+
2052
+ const materialUniformBuffer = this.device.createBuffer({
2053
+ label: `outline material uniform: ${mat.name}`,
2054
+ size: materialUniformData.byteLength,
2055
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
2056
+ })
2057
+ this.device.queue.writeBuffer(materialUniformBuffer, 0, materialUniformData)
2058
+
2059
+ const outlineBindGroup = this.device.createBindGroup({
2060
+ label: `outline bind group: ${mat.name}`,
2061
+ layout: this.outlineBindGroupLayout,
2062
+ entries: [
2063
+ { binding: 0, resource: { buffer: this.cameraUniformBuffer } },
2064
+ { binding: 1, resource: { buffer: materialUniformBuffer } },
2065
+ { binding: 2, resource: { buffer: this.skinMatrixBuffer! } },
2066
+ ],
2067
+ })
2068
+
2069
+ if (mat.isEye) {
2070
+ this.eyeOutlineDraws.push({
2071
+ count: indexCount,
2072
+ firstIndex: currentIndexOffset,
2073
+ bindGroup: outlineBindGroup,
2074
+ isTransparent,
2075
+ })
2076
+ } else if (mat.isHair) {
2077
+ this.hairOutlineDraws.push({
2078
+ count: indexCount,
2079
+ firstIndex: currentIndexOffset,
2080
+ bindGroup: outlineBindGroup,
2081
+ isTransparent,
2082
+ })
2083
+ } else if (isTransparent) {
2084
+ this.transparentOutlineDraws.push({
2085
+ count: indexCount,
2086
+ firstIndex: currentIndexOffset,
2087
+ bindGroup: outlineBindGroup,
2088
+ isTransparent,
2089
+ })
2090
+ } else {
2091
+ this.opaqueOutlineDraws.push({
2092
+ count: indexCount,
2093
+ firstIndex: currentIndexOffset,
2094
+ bindGroup: outlineBindGroup,
2095
+ isTransparent,
2096
+ })
2097
+ }
2098
+ }
2099
+
2100
+ currentIndexOffset += indexCount
2101
+ }
2102
+
2103
+ this.gpuMemoryMB = this.calculateGpuMemory()
2104
+ }
2105
+
2106
+ private async createTextureFromPath(path: string): Promise<GPUTexture | null> {
2107
+ const cached = this.textureCache.get(path)
2108
+ if (cached) {
2109
+ return cached
2110
+ }
2111
+
2112
+ try {
2113
+ const response = await fetch(path)
2114
+ if (!response.ok) {
2115
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)
2116
+ }
2117
+ const imageBitmap = await createImageBitmap(await response.blob(), {
2118
+ premultiplyAlpha: "none",
2119
+ colorSpaceConversion: "none",
2120
+ })
2121
+
2122
+ const texture = this.device.createTexture({
2123
+ label: `texture: ${path}`,
2124
+ size: [imageBitmap.width, imageBitmap.height],
2125
+ format: "rgba8unorm",
2126
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
2127
+ })
2128
+ this.device.queue.copyExternalImageToTexture({ source: imageBitmap }, { texture }, [
2129
+ imageBitmap.width,
2130
+ imageBitmap.height,
2131
+ ])
2132
+
2133
+ this.textureCache.set(path, texture)
2134
+ return texture
2135
+ } catch {
2136
+ return null
2137
+ }
2138
+ }
2139
+
2140
+ // Render strategy: 1) Opaque non-eye/hair 2) Eyes (stencil=1) 3) Hair (depth pre-pass + split by stencil) 4) Transparent 5) Bloom
2141
+ public render() {
2142
+ if (this.multisampleTexture && this.camera && this.device) {
2143
+ const currentTime = performance.now()
2144
+ const deltaTime = this.lastFrameTime > 0 ? (currentTime - this.lastFrameTime) / 1000 : 0.016
2145
+ this.lastFrameTime = currentTime
2146
+
2147
+ this.updateCameraUniforms()
2148
+ this.updateRenderTarget()
2149
+
2150
+ // Use single encoder for both compute and render (reduces sync points)
2151
+ const encoder = this.device.createCommandEncoder()
2152
+
2153
+ this.updateModelPose(deltaTime, encoder)
2154
+
2155
+ // Hide model if animation is loaded but not playing yet (prevents A-pose flash)
2156
+ // Still update physics and poses, just don't render visually
2157
+ if (this.hasAnimation && !this.playingAnimation) {
2158
+ // Submit encoder to ensure matrices are uploaded and physics initializes
2159
+ this.device.queue.submit([encoder.finish()])
2160
+ return
2161
+ }
2162
+
2163
+ const pass = encoder.beginRenderPass(this.renderPassDescriptor)
2164
+
2165
+ this.drawCallCount = 0
2166
+
2167
+ if (this.currentModel) {
2168
+ pass.setVertexBuffer(0, this.vertexBuffer)
2169
+ pass.setVertexBuffer(1, this.jointsBuffer)
2170
+ pass.setVertexBuffer(2, this.weightsBuffer)
2171
+ pass.setIndexBuffer(this.indexBuffer!, "uint32")
2172
+
2173
+ // Pass 1: Opaque
2174
+ pass.setPipeline(this.modelPipeline)
2175
+ for (const draw of this.opaqueDraws) {
2176
+ if (draw.count > 0) {
2177
+ pass.setBindGroup(0, draw.bindGroup)
2178
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2179
+ this.drawCallCount++
2180
+ }
2181
+ }
2182
+
2183
+ // Pass 2: Eyes (writes stencil value for hair to test against)
2184
+ pass.setPipeline(this.eyePipeline)
2185
+ pass.setStencilReference(this.STENCIL_EYE_VALUE)
2186
+ for (const draw of this.eyeDraws) {
2187
+ if (draw.count > 0) {
2188
+ pass.setBindGroup(0, draw.bindGroup)
2189
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2190
+ this.drawCallCount++
2191
+ }
2192
+ }
2193
+
2194
+ // Pass 3: Hair rendering (depth pre-pass + shading + outlines)
2195
+ this.drawOutlines(pass, false)
2196
+
2197
+ // 3a: Hair depth pre-pass (reduces overdraw via early depth rejection)
2198
+ if (this.hairDrawsOverEyes.length > 0 || this.hairDrawsOverNonEyes.length > 0) {
2199
+ pass.setPipeline(this.hairDepthPipeline)
2200
+ for (const draw of this.hairDrawsOverEyes) {
2201
+ if (draw.count > 0) {
2202
+ pass.setBindGroup(0, draw.bindGroup)
2203
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2204
+ }
2205
+ }
2206
+ for (const draw of this.hairDrawsOverNonEyes) {
2207
+ if (draw.count > 0) {
2208
+ pass.setBindGroup(0, draw.bindGroup)
2209
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2210
+ }
2211
+ }
2212
+ }
2213
+
2214
+ // 3b: Hair shading (split by stencil for transparency over eyes)
2215
+ if (this.hairDrawsOverEyes.length > 0) {
2216
+ pass.setPipeline(this.hairPipelineOverEyes)
2217
+ pass.setStencilReference(this.STENCIL_EYE_VALUE)
2218
+ for (const draw of this.hairDrawsOverEyes) {
2219
+ if (draw.count > 0) {
2220
+ pass.setBindGroup(0, draw.bindGroup)
2221
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2222
+ this.drawCallCount++
2223
+ }
2224
+ }
2225
+ }
2226
+
2227
+ if (this.hairDrawsOverNonEyes.length > 0) {
2228
+ pass.setPipeline(this.hairPipelineOverNonEyes)
2229
+ pass.setStencilReference(this.STENCIL_EYE_VALUE)
2230
+ for (const draw of this.hairDrawsOverNonEyes) {
2231
+ if (draw.count > 0) {
2232
+ pass.setBindGroup(0, draw.bindGroup)
2233
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2234
+ this.drawCallCount++
2235
+ }
2236
+ }
2237
+ }
2238
+
2239
+ // 3c: Hair outlines
2240
+ if (this.hairOutlineDraws.length > 0) {
2241
+ pass.setPipeline(this.hairOutlinePipeline)
2242
+ for (const draw of this.hairOutlineDraws) {
2243
+ if (draw.count > 0) {
2244
+ pass.setBindGroup(0, draw.bindGroup)
2245
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2246
+ }
2247
+ }
2248
+ }
2249
+
2250
+ // Pass 4: Transparent
2251
+ pass.setPipeline(this.modelPipeline)
2252
+ for (const draw of this.transparentDraws) {
2253
+ if (draw.count > 0) {
2254
+ pass.setBindGroup(0, draw.bindGroup)
2255
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2256
+ this.drawCallCount++
2257
+ }
2258
+ }
2259
+
2260
+ this.drawOutlines(pass, true)
2261
+ }
2262
+
2263
+ pass.end()
2264
+ this.device.queue.submit([encoder.finish()])
2265
+
2266
+ this.applyBloom()
2267
+
2268
+ this.updateStats(performance.now() - currentTime)
2269
+ }
2270
+ }
2271
+
2272
+ private applyBloom() {
2273
+ if (!this.sceneRenderTexture || !this.bloomExtractTexture) {
2274
+ return
2275
+ }
2276
+
2277
+ // Update bloom parameters
2278
+ const thresholdData = new Float32Array(8)
2279
+ thresholdData[0] = this.bloomThreshold
2280
+ this.device.queue.writeBuffer(this.bloomThresholdBuffer, 0, thresholdData)
2281
+
2282
+ const intensityData = new Float32Array(8)
2283
+ intensityData[0] = this.bloomIntensity
2284
+ this.device.queue.writeBuffer(this.bloomIntensityBuffer, 0, intensityData)
2285
+
2286
+ const encoder = this.device.createCommandEncoder()
2287
+
2288
+ // Extract bright areas
2289
+ const extractPass = encoder.beginRenderPass({
2290
+ label: "bloom extract",
2291
+ colorAttachments: [
2292
+ {
2293
+ view: this.bloomExtractTexture.createView(),
2294
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
2295
+ loadOp: "clear",
2296
+ storeOp: "store",
2297
+ },
2298
+ ],
2299
+ })
2300
+
2301
+ extractPass.setPipeline(this.bloomExtractPipeline)
2302
+ extractPass.setBindGroup(0, this.bloomExtractBindGroup!)
2303
+ extractPass.draw(6, 1, 0, 0)
2304
+ extractPass.end()
2305
+
2306
+ // Horizontal blur
2307
+ const hBlurData = new Float32Array(4)
2308
+ hBlurData[0] = 1.0
2309
+ hBlurData[1] = 0.0
2310
+ this.device.queue.writeBuffer(this.blurDirectionBuffer, 0, hBlurData)
2311
+ const blurHPass = encoder.beginRenderPass({
2312
+ label: "bloom blur horizontal",
2313
+ colorAttachments: [
2314
+ {
2315
+ view: this.bloomBlurTexture1.createView(),
2316
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
2317
+ loadOp: "clear",
2318
+ storeOp: "store",
2319
+ },
2320
+ ],
2321
+ })
2322
+
2323
+ blurHPass.setPipeline(this.bloomBlurPipeline)
2324
+ blurHPass.setBindGroup(0, this.bloomBlurHBindGroup!)
2325
+ blurHPass.draw(6, 1, 0, 0)
2326
+ blurHPass.end()
2327
+
2328
+ // Vertical blur
2329
+ const vBlurData = new Float32Array(4)
2330
+ vBlurData[0] = 0.0
2331
+ vBlurData[1] = 1.0
2332
+ this.device.queue.writeBuffer(this.blurDirectionBuffer, 0, vBlurData)
2333
+ const blurVPass = encoder.beginRenderPass({
2334
+ label: "bloom blur vertical",
2335
+ colorAttachments: [
2336
+ {
2337
+ view: this.bloomBlurTexture2.createView(),
2338
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
2339
+ loadOp: "clear",
2340
+ storeOp: "store",
2341
+ },
2342
+ ],
2343
+ })
2344
+
2345
+ blurVPass.setPipeline(this.bloomBlurPipeline)
2346
+ blurVPass.setBindGroup(0, this.bloomBlurVBindGroup!)
2347
+ blurVPass.draw(6, 1, 0, 0)
2348
+ blurVPass.end()
2349
+
2350
+ // Compose to canvas
2351
+ const composePass = encoder.beginRenderPass({
2352
+ label: "bloom compose",
2353
+ colorAttachments: [
2354
+ {
2355
+ view: this.context.getCurrentTexture().createView(),
2356
+ clearValue: { r: 0, g: 0, b: 0, a: 0 },
2357
+ loadOp: "clear",
2358
+ storeOp: "store",
2359
+ },
2360
+ ],
2361
+ })
2362
+
2363
+ composePass.setPipeline(this.bloomComposePipeline)
2364
+ composePass.setBindGroup(0, this.bloomComposeBindGroup!)
2365
+ composePass.draw(6, 1, 0, 0)
2366
+ composePass.end()
2367
+
2368
+ this.device.queue.submit([encoder.finish()])
2369
+ }
2370
+
2371
+ private updateCameraUniforms() {
2372
+ const viewMatrix = this.camera.getViewMatrix()
2373
+ const projectionMatrix = this.camera.getProjectionMatrix()
2374
+ const cameraPos = this.camera.getPosition()
2375
+ this.cameraMatrixData.set(viewMatrix.values, 0)
2376
+ this.cameraMatrixData.set(projectionMatrix.values, 16)
2377
+ this.cameraMatrixData[32] = cameraPos.x
2378
+ this.cameraMatrixData[33] = cameraPos.y
2379
+ this.cameraMatrixData[34] = cameraPos.z
2380
+ this.device.queue.writeBuffer(this.cameraUniformBuffer, 0, this.cameraMatrixData)
2381
+ }
2382
+
2383
+ private updateRenderTarget() {
2384
+ const colorAttachment = (this.renderPassDescriptor.colorAttachments as GPURenderPassColorAttachment[])[0]
2385
+ if (this.sampleCount > 1) {
2386
+ colorAttachment.resolveTarget = this.sceneRenderTextureView
2387
+ } else {
2388
+ colorAttachment.view = this.sceneRenderTextureView
2389
+ }
2390
+ }
2391
+
2392
+ private updateModelPose(deltaTime: number, encoder: GPUCommandEncoder) {
2393
+ this.currentModel!.evaluatePose()
2394
+ const worldMats = this.currentModel!.getBoneWorldMatrices()
2395
+
2396
+ if (this.physics) {
2397
+ this.physics.step(deltaTime, worldMats, this.currentModel!.getBoneInverseBindMatrices())
2398
+ }
2399
+
2400
+ this.device.queue.writeBuffer(
2401
+ this.worldMatrixBuffer!,
2402
+ 0,
2403
+ worldMats.buffer,
2404
+ worldMats.byteOffset,
2405
+ worldMats.byteLength
2406
+ )
2407
+ this.computeSkinMatrices(encoder)
2408
+ }
2409
+
2410
+ private computeSkinMatrices(encoder: GPUCommandEncoder) {
2411
+ const boneCount = this.currentModel!.getSkeleton().bones.length
2412
+ const workgroupCount = Math.ceil(boneCount / this.COMPUTE_WORKGROUP_SIZE)
2413
+
2414
+ const pass = encoder.beginComputePass()
2415
+ pass.setPipeline(this.skinMatrixComputePipeline!)
2416
+ pass.setBindGroup(0, this.skinMatrixComputeBindGroup!)
2417
+ pass.dispatchWorkgroups(workgroupCount)
2418
+ pass.end()
2419
+ }
2420
+
2421
+ private drawOutlines(pass: GPURenderPassEncoder, transparent: boolean) {
2422
+ pass.setPipeline(this.outlinePipeline)
2423
+ if (transparent) {
2424
+ for (const draw of this.transparentOutlineDraws) {
2425
+ if (draw.count > 0) {
2426
+ pass.setBindGroup(0, draw.bindGroup)
2427
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2428
+ }
2429
+ }
2430
+ } else {
2431
+ for (const draw of this.opaqueOutlineDraws) {
2432
+ if (draw.count > 0) {
2433
+ pass.setBindGroup(0, draw.bindGroup)
2434
+ pass.drawIndexed(draw.count, 1, draw.firstIndex, 0, 0)
2435
+ }
2436
+ }
2437
+ }
2438
+ }
2439
+
2440
+ private updateStats(frameTime: number) {
2441
+ const maxSamples = 60
2442
+ this.frameTimeSamples.push(frameTime)
2443
+ this.frameTimeSum += frameTime
2444
+ if (this.frameTimeSamples.length > maxSamples) {
2445
+ const removed = this.frameTimeSamples.shift()!
2446
+ this.frameTimeSum -= removed
2447
+ }
2448
+ const avgFrameTime = this.frameTimeSum / this.frameTimeSamples.length
2449
+ this.stats.frameTime = Math.round(avgFrameTime * 100) / 100
2450
+
2451
+ const now = performance.now()
2452
+ this.framesSinceLastUpdate++
2453
+ const elapsed = now - this.lastFpsUpdate
2454
+
2455
+ if (elapsed >= 1000) {
2456
+ this.stats.fps = Math.round((this.framesSinceLastUpdate / elapsed) * 1000)
2457
+ this.framesSinceLastUpdate = 0
2458
+ this.lastFpsUpdate = now
2459
+ }
2460
+
2461
+ this.stats.gpuMemory = this.gpuMemoryMB
2462
+ }
2463
+
2464
+ private calculateGpuMemory(): number {
2465
+ let textureMemoryBytes = 0
2466
+ for (const texture of this.textureCache.values()) {
2467
+ textureMemoryBytes += texture.width * texture.height * 4
2468
+ }
2469
+
2470
+ let bufferMemoryBytes = 0
2471
+ if (this.vertexBuffer) {
2472
+ const vertices = this.currentModel?.getVertices()
2473
+ if (vertices) bufferMemoryBytes += vertices.byteLength
2474
+ }
2475
+ if (this.indexBuffer) {
2476
+ const indices = this.currentModel?.getIndices()
2477
+ if (indices) bufferMemoryBytes += indices.byteLength
2478
+ }
2479
+ if (this.jointsBuffer) {
2480
+ const skinning = this.currentModel?.getSkinning()
2481
+ if (skinning) bufferMemoryBytes += skinning.joints.byteLength
2482
+ }
2483
+ if (this.weightsBuffer) {
2484
+ const skinning = this.currentModel?.getSkinning()
2485
+ if (skinning) bufferMemoryBytes += skinning.weights.byteLength
2486
+ }
2487
+ if (this.skinMatrixBuffer) {
2488
+ const skeleton = this.currentModel?.getSkeleton()
2489
+ if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2490
+ }
2491
+ if (this.worldMatrixBuffer) {
2492
+ const skeleton = this.currentModel?.getSkeleton()
2493
+ if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2494
+ }
2495
+ if (this.inverseBindMatrixBuffer) {
2496
+ const skeleton = this.currentModel?.getSkeleton()
2497
+ if (skeleton) bufferMemoryBytes += Math.max(256, skeleton.bones.length * 16 * 4)
2498
+ }
2499
+ bufferMemoryBytes += 40 * 4
2500
+ bufferMemoryBytes += 64 * 4
2501
+ bufferMemoryBytes += 32
2502
+ bufferMemoryBytes += 32
2503
+ bufferMemoryBytes += 32
2504
+ bufferMemoryBytes += 32
2505
+ if (this.fullscreenQuadBuffer) {
2506
+ bufferMemoryBytes += 24 * 4
2507
+ }
2508
+ const totalMaterialDraws =
2509
+ this.opaqueDraws.length +
2510
+ this.eyeDraws.length +
2511
+ this.hairDrawsOverEyes.length +
2512
+ this.hairDrawsOverNonEyes.length +
2513
+ this.transparentDraws.length
2514
+ bufferMemoryBytes += totalMaterialDraws * 32
2515
+
2516
+ const totalOutlineDraws =
2517
+ this.opaqueOutlineDraws.length +
2518
+ this.eyeOutlineDraws.length +
2519
+ this.hairOutlineDraws.length +
2520
+ this.transparentOutlineDraws.length
2521
+ bufferMemoryBytes += totalOutlineDraws * 32
2522
+
2523
+ let renderTargetMemoryBytes = 0
2524
+ if (this.multisampleTexture) {
2525
+ const width = this.canvas.width
2526
+ const height = this.canvas.height
2527
+ renderTargetMemoryBytes += width * height * 4 * this.sampleCount
2528
+ renderTargetMemoryBytes += width * height * 4
2529
+ }
2530
+ if (this.sceneRenderTexture) {
2531
+ const width = this.canvas.width
2532
+ const height = this.canvas.height
2533
+ renderTargetMemoryBytes += width * height * 4
2534
+ }
2535
+ if (this.bloomExtractTexture) {
2536
+ const width = Math.floor(this.canvas.width / this.BLOOM_DOWNSCALE_FACTOR)
2537
+ const height = Math.floor(this.canvas.height / this.BLOOM_DOWNSCALE_FACTOR)
2538
+ renderTargetMemoryBytes += width * height * 4 * 3
2539
+ }
2540
+
2541
+ const totalGPUMemoryBytes = textureMemoryBytes + bufferMemoryBytes + renderTargetMemoryBytes
2542
+ return Math.round((totalGPUMemoryBytes / 1024 / 1024) * 100) / 100
2543
+ }
2544
+ }