dreamwell-matter 1.0.0

DreamMatter benchmark — GPU physics materialization demo and profiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Keynote benchmark scene — AAAA PBR showcase with full visual pipeline.
//
// Open-world exhibition space with dramatic multi-light setup, ready for skybox.
// All geometry is procedural PbrVertex (64-byte). No external assets.

use dreamwell_engine::game_object::{GameObjectScene, MeshBinding, PrimitiveKind};
use dreamwell_gpu::camera::Camera;

/// Dreamlet capacity — 65536 at 64 bytes each = 4 MiB VRAM.
pub const DEFAULT_DREAMLET_CAPACITY: u32 = 65536;

/// Blue color for projectile cubes.
const PROJECTILE_COLOR: [f32; 4] = [0.15, 0.4, 0.95, 1.0];
/// Orange color for debris particles.
const DEBRIS_COLOR: [f32; 4] = [0.95, 0.5, 0.1, 1.0];

/// Create the base keynote showcase scene (static geometry only).
/// Returns the scene for later dynamic object injection.
pub fn create_base_scene() -> GameObjectScene {
    let mut scene = GameObjectScene::new("DreamMatter Keynote".to_string());

    // ── Ground: expansive open terrain ────────────────────────────────
    // Large ground plane — open space, ready for skybox above
    if let Ok(id) = scene.spawn_primitive("Ground".into(), PrimitiveKind::Plane) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.scale = [80.0, 1.0, 80.0];
        }
    }

    // ── Central Feature: Convergence Sphere ──────────────────────────
    if let Ok(id) = scene.spawn_primitive("ConvergenceTarget".into(), PrimitiveKind::Sphere) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [0.0, 3.0, 0.0];
            obj.transform.scale = [3.0, 3.0, 3.0];
        }
    }

    // ── Architecture: Three Pillars ──────────────────────────────────
    for (i, x) in [-10.0_f32, 0.0, 10.0].iter().enumerate() {
        let name = format!("Pillar_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Cylinder) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [*x, 3.5, -10.0];
                obj.transform.scale = [1.2, 7.0, 1.2];
            }
        }
    }

    // Pillar caps (spheres)
    for (i, x) in [-10.0_f32, 0.0, 10.0].iter().enumerate() {
        let name = format!("PillarCap_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Sphere) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [*x, 7.2, -10.0];
                obj.transform.scale = [1.6, 1.6, 1.6];
            }
        }
    }

    // ── Showcase Ring: Objects at various distances for LOD demo ──────
    // Near objects (LOD 0)
    if let Ok(id) = scene.spawn_primitive("NearTorus".into(), PrimitiveKind::Torus) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [-4.0, 1.2, 4.0];
            obj.transform.scale = [2.0, 2.0, 2.0];
        }
    }
    if let Ok(id) = scene.spawn_primitive("NearCone".into(), PrimitiveKind::Cone) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [4.0, 1.0, 4.0];
            obj.transform.scale = [1.5, 2.5, 1.5];
        }
    }

    // Mid-distance (LOD 1)
    for (i, (x, z)) in [(-14.0_f32, -6.0_f32), (14.0, -6.0)].iter().enumerate() {
        let name = format!("MidSphere_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Sphere) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [*x, 2.5, *z];
                obj.transform.scale = [3.0, 3.0, 3.0];
            }
        }
    }

    // Far objects (LOD 2)
    for (i, x) in [-25.0_f32, -18.0, 18.0, 25.0].iter().enumerate() {
        let name = format!("FarCapsule_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Capsule) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [*x, 2.0, -12.0];
                obj.transform.scale = [2.0, 4.0, 2.0];
            }
        }
    }

    // ── Decorative geometry ──────────────────────────────────────────
    if let Ok(id) = scene.spawn_primitive("ParticlePyramid".into(), PrimitiveKind::Pyramid) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [-7.0, 0.5, 0.0];
            obj.transform.scale = [2.5, 3.0, 2.5];
        }
    }
    if let Ok(id) = scene.spawn_primitive("Wedge".into(), PrimitiveKind::Wedge) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [7.0, 0.5, 0.0];
            obj.transform.scale = [2.5, 2.0, 2.5];
        }
    }

    // ── Dream Lighting test objects ─────────────────────────────────

    // Emissive sphere (DL-11: light source detection)
    if let Ok(id) = scene.spawn_primitive("EmissiveSphere".into(), PrimitiveKind::Sphere) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [5.0, 2.0, -3.0];
            obj.transform.scale = [1.5, 1.5, 1.5];
            obj.mesh = MeshBinding::Primitive {
                kind: PrimitiveKind::Sphere,
                color: [5.0, 4.5, 3.0, 1.0], // bright warm emissive
            };
        }
    }

    // Translucent glass cube (DL-10: translucency volume test)
    if let Ok(id) = scene.spawn_primitive("GlassCube".into(), PrimitiveKind::Cube) {
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [-5.0, 1.5, -3.0];
            obj.transform.scale = [2.0, 2.0, 2.0];
            obj.mesh = MeshBinding::Primitive {
                kind: PrimitiveKind::Cube,
                color: [0.8, 0.9, 1.0, 0.3], // translucent blue-white
            };
        }
    }

    // ── Foreground detail cubes ──────────────────────────────────────
    for i in 0..7 {
        let x = (i as f32 - 3.0) * 3.5;
        let name = format!("FrontCube_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Cube) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [x, 0.5, 8.0];
                obj.transform.scale = [0.8, 0.8, 0.8];
            }
        }
    }

    scene
}

/// Upload the base scene + dynamic objects (projectiles, debris) to the GPU.
/// Retained for non-GPU-driven fallback path.
#[allow(dead_code)]
pub fn upload_scene_with_dynamics(
    device: &wgpu::Device,
    fabric: &mut dreamwell_fabric::DreamFabric,
    base_scene: &GameObjectScene,
    projectile_positions: &[glam::Vec3],
    debris: &[(glam::Vec3, f32)], // (position, age)
) {
    let mut scene = base_scene.clone();

    // Add projectile cubes (blue)
    for (i, pos) in projectile_positions.iter().enumerate() {
        let name = format!("Projectile_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Cube) {
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = pos.to_array();
                obj.transform.scale = [0.3, 0.3, 0.3];
                obj.mesh = MeshBinding::Primitive {
                    kind: PrimitiveKind::Cube,
                    color: PROJECTILE_COLOR,
                };
            }
        }
    }

    // Add debris cubes (orange, fading)
    for (i, (pos, age)) in debris.iter().enumerate() {
        let name = format!("Debris_{i}");
        if let Ok(id) = scene.spawn_primitive(name, PrimitiveKind::Cube) {
            if let Some(obj) = scene.find_mut(id) {
                let fade = (1.0 - age / super::DEBRIS_LIFETIME).max(0.0);
                let s = 0.12 * fade;
                obj.transform.position = pos.to_array();
                obj.transform.scale = [s, s, s];
                obj.mesh = MeshBinding::Primitive {
                    kind: PrimitiveKind::Cube,
                    color: [
                        DEBRIS_COLOR[0] * fade,
                        DEBRIS_COLOR[1] * fade,
                        DEBRIS_COLOR[2] * fade,
                        1.0,
                    ],
                };
            }
        }
    }

    fabric.upload_scene(device, &scene);
}

/// Setup scene lighting and DreamMatter.
pub fn setup_benchmark_scene(
    device: &wgpu::Device,
    _queue: &wgpu::Queue,
    fabric: &mut dreamwell_fabric::DreamFabric,
    base_scene: &GameObjectScene,
) {
    fabric.upload_scene(device, base_scene);
    fabric.ensure_particle_capacity(device, DEFAULT_DREAMLET_CAPACITY);

    // ── Lighting: AAA open-world studio setup ────────────────────────

    // Key light: warm sun from upper-right (orbits during benchmark)
    fabric.gpu_scene_mut().scene_lights.add_directional(
        dreamwell_engine::lighting::DirectionalLightDesc {
            direction: normalize([0.4, -0.65, 0.5]),
            color: [1.0, 0.95, 0.85],
            intensity_lux: 2.5,
        },
    );

    // Fill light: cool sky bounce from opposite side
    fabric.gpu_scene_mut().scene_lights.add_directional(
        dreamwell_engine::lighting::DirectionalLightDesc {
            direction: normalize([-0.3, -0.4, -0.5]),
            color: [0.5, 0.55, 0.7],
            intensity_lux: 0.6,
        },
    );

    // Point lights for dramatic colored accents
    let accent_lights = [
        ([0.0, 8.0, 0.0],   [1.0, 0.95, 0.9],  500.0, 25.0),  // overhead key
        ([-10.0, 3.0, 0.0],  [0.2, 0.4, 0.9],   250.0, 15.0),  // blue left
        ([10.0, 3.0, 0.0],   [0.9, 0.5, 0.1],   250.0, 15.0),  // amber right
        ([0.0, 4.0, -10.0],  [0.1, 0.7, 0.3],   180.0, 18.0),  // green rear
        ([0.0, 2.5, 10.0],   [0.6, 0.1, 0.8],   180.0, 15.0),  // purple front
        ([-6.0, 1.5, 6.0],   [0.9, 0.7, 0.4],   120.0, 10.0),  // warm foreground L
        ([6.0, 1.5, 6.0],    [0.4, 0.7, 0.9],   120.0, 10.0),  // cool foreground R
        ([0.0, 1.0, 0.0],    [1.0, 0.9, 0.7],   100.0, 8.0),   // ground fill
    ];
    for (pos, color, lumens, range) in accent_lights {
        fabric.gpu_scene_mut().scene_lights.add_point(
            dreamwell_engine::lighting::PointLightDesc {
                position: pos,
                color,
                intensity_lumens: lumens,
                range,
            },
        );
    }

    // PBR material: slightly glossy, subtle metallic sheen
    fabric.gpu_scene_mut().default_roughness = 0.35;
    fabric.gpu_scene_mut().default_metallic = 0.15;

    log::info!(
        "Keynote scene: {} objects, {} directional + {} point lights, {} Dreamlets",
        base_scene.objects.len(),
        fabric.gpu_scene().scene_lights.directional.len(),
        fabric.gpu_scene().scene_lights.point.len(),
        DEFAULT_DREAMLET_CAPACITY,
    );
}

/// Update the directional light to orbit (dramatic shadow sweep).
pub fn update_sun_orbit(fabric: &mut dreamwell_fabric::DreamFabric, elapsed: f32, duration: f32) {
    let angle = (elapsed / duration) * std::f32::consts::TAU * 0.75;
    let pitch: f32 = -0.6;
    let dir = normalize([
        angle.cos() * pitch.cos(),
        pitch.sin(),
        angle.sin() * pitch.cos(),
    ]);

    if let Some(light) = fabric.gpu_scene_mut().scene_lights.directional.first_mut() {
        light.direction = dir;
    }
}

/// Cinematic auto-orbit camera.
pub fn cinematic_camera(elapsed: f32, duration: f32, aspect_ratio: f32) -> Camera {
    let t = elapsed / duration;
    let orbit_angle = t * std::f32::consts::TAU * 0.75;
    let height = 5.0 + 3.0 * (t * std::f32::consts::TAU).sin();
    let distance = 16.0 - 4.0 * (t * std::f32::consts::PI * 2.0).sin();

    let cam_x = orbit_angle.sin() * distance;
    let cam_z = orbit_angle.cos() * distance;
    let cam_pos = glam::Vec3::new(cam_x, height, cam_z);
    let target = glam::Vec3::new(0.0, 2.0, 0.0);

    let mut camera = Camera::default();
    camera.position = cam_pos;
    camera.view_matrix = glam::Mat4::look_at_rh(cam_pos, target, glam::Vec3::Y);
    camera.update_projection(aspect_ratio, 55.0);
    camera
}

/// Fixed benchmark camera.
pub fn benchmark_camera(aspect_ratio: f32) -> Camera {
    let mut camera = Camera::default();
    camera.position = glam::Vec3::new(0.0, 5.0, 18.0);
    let target = glam::Vec3::new(0.0, 2.0, 0.0);
    camera.view_matrix = glam::Mat4::look_at_rh(camera.position, target, glam::Vec3::Y);
    camera.update_projection(aspect_ratio, 55.0);
    camera
}

/// Setup static collision bodies matching the scene geometry.
pub fn setup_physics_colliders(physics: &mut dreamwell_engine::physics::simulation::PhysicsWorld) {
    use dreamwell_engine::physics::simulation::{CollisionShape, RigidBody};

    // Ground plane
    physics.add_body(RigidBody::fixed(CollisionShape::Plane {
        normal: [0.0, 1.0, 0.0], d: 0.0,
    }));

    // Central sphere
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 1.5 })
            .with_position([0.0, 3.0, 0.0]).with_restitution(0.7)
    );

    // Three pillars
    for x in [-10.0_f32, 0.0, 10.0] {
        physics.add_body(
            RigidBody::fixed(CollisionShape::Aabb { half_extents: [0.6, 3.5, 0.6] })
                .with_position([x, 3.5, -10.0]).with_restitution(0.4)
        );
    }

    // Pillar caps
    for x in [-10.0_f32, 0.0, 10.0] {
        physics.add_body(
            RigidBody::fixed(CollisionShape::Sphere { radius: 0.8 })
                .with_position([x, 7.2, -10.0]).with_restitution(0.6)
        );
    }

    // Torus, cone, pyramid, wedge (sphere approx)
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 1.0 })
            .with_position([-4.0, 1.2, 4.0]).with_restitution(0.5)
    );
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 0.75 })
            .with_position([4.0, 1.0, 4.0]).with_restitution(0.5)
    );
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 1.2 })
            .with_position([-7.0, 0.5, 0.0]).with_restitution(0.5)
    );
    physics.add_body(
        RigidBody::fixed(CollisionShape::Aabb { half_extents: [1.25, 1.0, 1.25] })
            .with_position([7.0, 0.5, 0.0]).with_restitution(0.5)
    );

    // Foreground cubes
    for i in 0..7 {
        let x = (i as f32 - 3.0) * 3.5;
        physics.add_body(
            RigidBody::fixed(CollisionShape::Aabb { half_extents: [0.4, 0.4, 0.4] })
                .with_position([x, 0.5, 8.0]).with_restitution(0.5)
        );
    }

    // Mid-distance spheres
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 1.5 })
            .with_position([-14.0, 2.5, -6.0]).with_restitution(0.6)
    );
    physics.add_body(
        RigidBody::fixed(CollisionShape::Sphere { radius: 1.5 })
            .with_position([14.0, 2.5, -6.0]).with_restitution(0.6)
    );

    log::info!("Physics colliders: {} static bodies", physics.body_count());
}

/// Convert a GameObjectScene to GpuObjectData for GPU-driven rendering.
/// Each visible primitive object becomes a GpuObjectData entry in the storage buffer.
/// This is the bridge between the CPU scene graph and the GPU-driven pipeline.
pub fn scene_to_gpu_objects(
    scene: &GameObjectScene,
    default_roughness: f32,
    default_metallic: f32,
) -> Vec<dreamwell_gpu::gpu_driven::GpuObjectData> {
    use dreamwell_gpu::gpu_driven::{GpuObjectData, MergedMeshBuffer};

    let mut objects = Vec::with_capacity(scene.objects.len());

    for obj in &scene.objects {
        if !obj.visible { continue; }
        let MeshBinding::Primitive { kind, color } = &obj.mesh else { continue };

        let s = obj.transform.scale;
        let p = obj.transform.position;

        // Column-major 4x4 model matrix (scale + translate, no rotation for primitives)
        #[rustfmt::skip]
        let model = [
            s[0], 0.0,  0.0,  0.0,
            0.0,  s[1], 0.0,  0.0,
            0.0,  0.0,  s[2], 0.0,
            p[0], p[1], p[2], 1.0,
        ];

        let radius = s[0].max(s[1]).max(s[2]) * 0.75;

        // DL-11: Detect emissive objects by HDR color (any RGB component > 1.0).
        let luminance = color[0] * 0.2126 + color[1] * 0.7152 + color[2] * 0.0722;
        let emissive = if luminance > 1.0 { luminance } else { 0.0 };

        objects.push(GpuObjectData {
            model,
            base_color: *color,
            roughness: default_roughness,
            metallic: default_metallic,
            emissive_strength: emissive,
            normal_scale: 1.0,
            bounding_center: p,
            bounding_radius: radius,
            mesh_id: MergedMeshBuffer::mesh_id_lod0(*kind),
            _pad: [0; 3],
        });
    }

    objects
}

/// Add projectile + debris as GpuObjectData entries to an existing object list.
pub fn add_dynamic_gpu_objects(
    objects: &mut Vec<dreamwell_gpu::gpu_driven::GpuObjectData>,
    projectile_positions: &[glam::Vec3],
    debris: &[(glam::Vec3, f32)],
) {
    use dreamwell_gpu::gpu_driven::{GpuObjectData, MergedMeshBuffer};

    let cube_mesh_id = MergedMeshBuffer::mesh_id_lod0(PrimitiveKind::Cube);

    // Projectiles (blue cubes)
    for pos in projectile_positions {
        let p = pos.to_array();
        #[rustfmt::skip]
        let model = [
            0.3, 0.0, 0.0, 0.0,
            0.0, 0.3, 0.0, 0.0,
            0.0, 0.0, 0.3, 0.0,
            p[0], p[1], p[2], 1.0,
        ];
        objects.push(GpuObjectData {
            model,
            base_color: PROJECTILE_COLOR,
            roughness: 0.3,
            metallic: 0.8,
            emissive_strength: 0.5,
            normal_scale: 1.0,
            bounding_center: p,
            bounding_radius: 0.3,
            mesh_id: cube_mesh_id,
            _pad: [0; 3],
        });
    }

    // Debris (orange fading cubes)
    for (pos, age) in debris {
        let fade = (1.0 - age / super::DEBRIS_LIFETIME).max(0.0);
        let s = 0.12 * fade;
        let p = pos.to_array();
        #[rustfmt::skip]
        let model = [
            s,   0.0, 0.0, 0.0,
            0.0, s,   0.0, 0.0,
            0.0, 0.0, s,   0.0,
            p[0], p[1], p[2], 1.0,
        ];
        objects.push(GpuObjectData {
            model,
            base_color: [
                DEBRIS_COLOR[0] * fade,
                DEBRIS_COLOR[1] * fade,
                DEBRIS_COLOR[2] * fade,
                1.0,
            ],
            roughness: 0.5,
            metallic: 0.1,
            emissive_strength: fade * 2.0,
            normal_scale: 1.0,
            bounding_center: p,
            bounding_radius: s,
            mesh_id: cube_mesh_id,
            _pad: [0; 3],
        });
    }
}

pub fn normalize(v: [f32; 3]) -> [f32; 3] {
    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
    if len > 1e-8 { [v[0] / len, v[1] / len, v[2] / len] } else { [0.0, -1.0, 0.0] }
}