bimifc-bevy 0.3.0

Bevy-based 3D viewer for IFC models with WebGPU/WebGL2 rendering
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Camera system with orbit, pan, and zoom controls
//!
//! Provides a flexible camera controller similar to the TypeScript version.

#[cfg(target_arch = "wasm32")]
use crate::storage::save_camera;
use crate::storage::CameraStorage;
use bevy::ecs::message::MessageReader;
use bevy::input::mouse::{MouseMotion, MouseWheel};
use bevy::input::touch::Touches;
use bevy::prelude::*;

/// System set for camera input (for ordering)
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub struct CameraInputSet;

/// Camera controller plugin
pub struct CameraPlugin;

impl Plugin for CameraPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<CameraController>()
            .add_systems(Startup, setup_camera)
            .add_systems(
                Update,
                (
                    poll_camera_commands_system,
                    camera_input_system,
                    camera_touch_system,
                    camera_update_system,
                    camera_keyboard_system,
                )
                    .chain()
                    .in_set(CameraInputSet),
            );
    }
}

impl CameraPlugin {
    /// Get the system set for camera input (for ordering picking after camera)
    pub fn input_system_set() -> CameraInputSet {
        CameraInputSet
    }
}

/// Camera operating mode
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum CameraMode {
    #[default]
    Orbit,
    Pan,
    Walk,
}

/// Camera controller resource
#[derive(Resource)]
pub struct CameraController {
    /// Current mode
    pub mode: CameraMode,
    /// Target point to orbit around
    pub target: Vec3,
    /// Distance from target
    pub distance: f32,
    /// Azimuth angle (horizontal rotation)
    pub azimuth: f32,
    /// Elevation angle (vertical rotation)
    pub elevation: f32,
    /// Damping factor for smooth movement (0.0 = instant, 1.0 = never moves)
    pub damping: f32,
    /// Velocity for inertia
    pub velocity: Vec3,
    /// Angular velocity for orbit inertia
    pub angular_velocity: Vec2,
    /// Whether camera is currently animating
    pub is_animating: bool,
    /// Animation target (for preset views)
    pub animation_target: Option<CameraAnimationTarget>,
    /// Field of view in degrees
    pub fov: f32,
    /// Near clipping plane
    pub near: f32,
    /// Far clipping plane
    pub far: f32,
    /// Walk mode speed
    pub walk_speed: f32,
    /// Orbit sensitivity
    pub orbit_sensitivity: f32,
    /// Pan sensitivity
    pub pan_sensitivity: f32,
    /// Zoom sensitivity
    pub zoom_sensitivity: f32,
    /// Is dragging (mouse down)
    pub is_dragging: bool,
    /// Last mouse position
    pub last_mouse_pos: Vec2,
    /// Mouse position when drag started (for click detection)
    pub drag_start_pos: Vec2,
    /// Did actual dragging occur (mouse moved significantly)?
    pub did_drag: bool,
    /// Was this a click (released without dragging)?
    pub just_clicked: bool,
    // Touch state
    /// Number of active touches last frame
    pub touch_count: usize,
    /// Last single-touch position (for computing deltas)
    pub last_touch_pos: Vec2,
    /// Last distance between two fingers (for pinch zoom)
    pub last_pinch_distance: f32,
    /// Last center of two fingers (for pan)
    pub last_two_touch_center: Vec2,
    /// Is a single-finger drag active?
    pub is_touch_dragging: bool,
    /// Position where touch started (for tap detection)
    pub touch_drag_start: Vec2,
    /// Did touch move significantly (not a tap)?
    pub touch_did_drag: bool,
}

impl Default for CameraController {
    fn default() -> Self {
        Self {
            mode: CameraMode::Orbit,
            target: Vec3::ZERO,
            distance: 100.0,  // Start further back for IFC models (in mm)
            azimuth: 0.785,   // 45 degrees
            elevation: 0.615, // ~35 degrees (isometric)
            damping: 0.92,
            velocity: Vec3::ZERO,
            angular_velocity: Vec2::ZERO,
            is_animating: false,
            animation_target: None,
            fov: 45.0,
            near: 0.05,        // 5cm near plane — good depth precision for buildings
            far: 10000.0,      // 10km far plane for large IFC models
            walk_speed: 500.0, // 0.5m per frame for walking in mm-scale
            orbit_sensitivity: 0.005,
            pan_sensitivity: 0.01,
            zoom_sensitivity: 0.02,
            is_dragging: false,
            last_mouse_pos: Vec2::ZERO,
            drag_start_pos: Vec2::ZERO,
            did_drag: false,
            just_clicked: false,
            touch_count: 0,
            last_touch_pos: Vec2::ZERO,
            last_pinch_distance: 0.0,
            last_two_touch_center: Vec2::ZERO,
            is_touch_dragging: false,
            touch_drag_start: Vec2::ZERO,
            touch_did_drag: false,
        }
    }
}

impl CameraController {
    /// Get camera position from spherical coordinates
    pub fn get_position(&self) -> Vec3 {
        let x = self.distance * self.elevation.cos() * self.azimuth.sin();
        let y = self.distance * self.elevation.sin();
        let z = self.distance * self.elevation.cos() * self.azimuth.cos();
        self.target + Vec3::new(x, y, z)
    }

    /// Set preset view
    pub fn set_preset_view(&mut self, azimuth: f32, elevation: f32) {
        self.animation_target = Some(CameraAnimationTarget {
            azimuth,
            elevation,
            distance: self.distance,
            target: self.target,
            duration: 0.5,
            elapsed: 0.0,
        });
        self.is_animating = true;
    }

    /// Set home/isometric view
    pub fn home(&mut self) {
        self.set_preset_view(0.785, 0.615); // 45°, 35.264°
    }

    /// Fit all - zoom to show entire scene
    pub fn fit_bounds(&mut self, min: Vec3, max: Vec3) {
        let center = (min + max) * 0.5;
        let size = max - min;
        let diagonal = size.length();

        // Calculate distance to fit the entire model
        let fov_rad = self.fov.to_radians();
        let distance = diagonal / (2.0 * (fov_rad / 2.0).tan());

        self.animation_target = Some(CameraAnimationTarget {
            azimuth: self.azimuth,
            elevation: self.elevation,
            distance: distance.max(1.0),
            target: center,
            duration: 0.5,
            elapsed: 0.0,
        });
        self.is_animating = true;
    }

    /// Frame selection - zoom to specific bounds
    pub fn frame(&mut self, min: Vec3, max: Vec3) {
        self.fit_bounds(min, max);
    }

    /// Zoom in
    pub fn zoom_in(&mut self) {
        self.distance = (self.distance * 0.8).max(1.0);
    }

    /// Zoom out
    pub fn zoom_out(&mut self) {
        self.distance = (self.distance * 1.25).min(500000.0);
    }

    /// Convert to storage format
    pub fn to_storage(&self) -> CameraStorage {
        CameraStorage {
            azimuth: self.azimuth,
            elevation: self.elevation,
            distance: self.distance,
            target: [self.target.x, self.target.y, self.target.z],
        }
    }

    /// Load from storage format
    pub fn from_storage(&mut self, storage: &CameraStorage) {
        self.azimuth = storage.azimuth;
        self.elevation = storage.elevation;
        self.distance = storage.distance;
        self.target = Vec3::new(storage.target[0], storage.target[1], storage.target[2]);
    }
}

/// Animation target for smooth camera transitions
#[derive(Clone, Debug)]
pub struct CameraAnimationTarget {
    pub azimuth: f32,
    pub elevation: f32,
    pub distance: f32,
    pub target: Vec3,
    pub duration: f32,
    pub elapsed: f32,
}

/// Marker component for the main camera
#[derive(Component)]
pub struct MainCamera;

/// Marker for architectural lighting entities (directional lights)
/// so they can be toggled by the photometric module.
#[derive(Component)]
pub struct ArchitecturalLight;

/// System to poll for camera commands from Yew UI
#[allow(unused_variables, unused_mut)]
fn poll_camera_commands_system(
    mut controller: ResMut<CameraController>,
    scene_data: Res<crate::IfcSceneData>,
) {
    #[cfg(target_arch = "wasm32")]
    {
        if let Some(cmd) = crate::storage::load_camera_cmd() {
            crate::storage::clear_camera_cmd();

            match cmd.cmd.as_str() {
                "home" => {
                    controller.home();
                }
                "fit_all" => {
                    if let Some(ref bounds) = scene_data.bounds {
                        controller.fit_bounds(bounds.min, bounds.max);
                    }
                }
                "set_mode" => {
                    if let Some(mode) = cmd.mode {
                        controller.mode = match mode.as_str() {
                            "pan" => CameraMode::Pan,
                            "walk" => CameraMode::Walk,
                            _ => CameraMode::Orbit,
                        };
                    }
                }
                _ => {}
            }
        }
    }
}

/// Setup the 3D camera
fn setup_camera(mut commands: Commands, controller: Res<CameraController>) {
    use bevy::core_pipeline::tonemapping::Tonemapping;
    use bevy::render::view::Msaa;

    let position = controller.get_position();

    commands.spawn((
        Camera3d::default(),
        Transform::from_translation(position).looking_at(controller.target, Vec3::Y),
        Projection::Perspective(PerspectiveProjection {
            fov: controller.fov.to_radians(),
            near: controller.near,
            far: controller.far,
            ..default()
        }),
        MainCamera,
        // Enable 4x MSAA for smoother edges
        Msaa::Sample4,
        // AgX tonemapping for natural, filmic look
        Tonemapping::AgX,
        // Single cluster: all lights evaluated per fragment — best for stadium
        // floodlights where most lights illuminate the same area (the pitch).
        bevy::light::cluster::ClusterConfig::Single,
    ));

    // Ambient light - enough to see into shadows but not wash out
    commands.spawn(AmbientLight {
        color: Color::srgb(0.9, 0.92, 1.0), // Slightly cool ambient
        brightness: 150.0,
        affects_lightmapped_meshes: true,
    });

    // Key directional light - main light from top-right-front
    commands.spawn((
        DirectionalLight {
            color: Color::srgb(1.0, 0.98, 0.95), // Warm sunlight
            illuminance: 30000.0,
            shadows_enabled: false,
            affects_lightmapped_mesh_diffuse: true,
            ..default()
        },
        Transform::from_xyz(0.5, 1.0, 0.3).looking_at(Vec3::ZERO, Vec3::Y),
        ArchitecturalLight,
    ));

    // Fill light from opposite side - cooler, softer
    commands.spawn((
        DirectionalLight {
            color: Color::srgb(0.8, 0.88, 1.0), // Cool sky fill
            illuminance: 12000.0,
            shadows_enabled: false,
            affects_lightmapped_mesh_diffuse: true,
            ..default()
        },
        Transform::from_xyz(-0.5, 0.3, -0.5).looking_at(Vec3::ZERO, Vec3::Y),
        ArchitecturalLight,
    ));

    // Rim/back light for edge definition
    commands.spawn((
        DirectionalLight {
            color: Color::srgb(0.95, 0.95, 1.0),
            illuminance: 8000.0,
            shadows_enabled: false,
            affects_lightmapped_mesh_diffuse: true,
            ..default()
        },
        Transform::from_xyz(-0.3, 0.8, -0.8).looking_at(Vec3::ZERO, Vec3::Y),
        ArchitecturalLight,
    ));

    // Bottom fill - subtle uplight to reduce dark undersides
    commands.spawn((
        DirectionalLight {
            color: Color::srgb(0.7, 0.75, 0.85),
            illuminance: 3000.0,
            shadows_enabled: false,
            affects_lightmapped_mesh_diffuse: true,
            ..default()
        },
        Transform::from_xyz(0.0, -1.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
        ArchitecturalLight,
    ));
}

/// Handle mouse input for camera control
#[allow(unused_variables)]
fn camera_input_system(
    mouse_button: Res<ButtonInput<MouseButton>>,
    mut mouse_motion: MessageReader<MouseMotion>,
    mut mouse_wheel: MessageReader<MouseWheel>,
    mut controller: ResMut<CameraController>,
    windows: Query<&Window>,
    measure_state: Res<crate::picking::MeasurementState>,
    // Check if mouse is over any UI element with Interaction (only when bevy-ui feature is enabled)
    #[cfg(feature = "bevy-ui")] ui_interactions: Query<&Interaction, With<Node>>,
) {
    let Ok(window) = windows.single() else { return };

    // Check if mouse is over any UI element (hovered or pressed)
    #[cfg(feature = "bevy-ui")]
    let mouse_over_ui = ui_interactions
        .iter()
        .any(|interaction| matches!(interaction, Interaction::Hovered | Interaction::Pressed));
    #[cfg(not(feature = "bevy-ui"))]
    let mouse_over_ui = false;

    // Check if measure tool is active — don't start camera drag for left-click
    let is_measure = measure_state.active;

    // Handle mouse button state - only start drag if not over UI and not measuring
    if mouse_button.just_pressed(MouseButton::Left) && !mouse_over_ui && !is_measure {
        controller.is_dragging = true;
        controller.did_drag = false;
        controller.just_clicked = false; // Reset on press
        if let Some(pos) = window.cursor_position() {
            controller.last_mouse_pos = pos;
            controller.drag_start_pos = pos;
        }
    }
    if mouse_button.just_released(MouseButton::Left) {
        // Check if this was a click (no significant drag)
        if !controller.did_drag {
            controller.just_clicked = true;
        }
        controller.is_dragging = false;
    }
    // In measure mode, treat press as click (for immediate feedback)
    if is_measure && mouse_button.just_pressed(MouseButton::Left) && !mouse_over_ui {
        controller.just_clicked = true;
        if let Some(pos) = window.cursor_position() {
            controller.drag_start_pos = pos;
        }
    }

    // Handle mouse motion
    if controller.is_dragging {
        for ev in mouse_motion.read() {
            // Mark as drag if mouse moved significantly (more than 3 pixels)
            if ev.delta.length() > 3.0 {
                controller.did_drag = true;
            }

            match controller.mode {
                CameraMode::Orbit => {
                    controller.azimuth -= ev.delta.x * controller.orbit_sensitivity;
                    controller.elevation -= ev.delta.y * controller.orbit_sensitivity;
                    // Clamp elevation to avoid gimbal lock
                    controller.elevation = controller.elevation.clamp(-1.5, 1.5);
                    // Store angular velocity for inertia
                    controller.angular_velocity = ev.delta * controller.orbit_sensitivity;
                }
                CameraMode::Pan => {
                    // Calculate pan in camera space
                    let right = Vec3::new(controller.azimuth.cos(), 0.0, -controller.azimuth.sin());
                    let up = Vec3::Y;
                    let pan = right
                        * ev.delta.x
                        * controller.pan_sensitivity
                        * controller.distance
                        * 0.01
                        - up * ev.delta.y * controller.pan_sensitivity * controller.distance * 0.01;
                    controller.target += pan;
                }
                CameraMode::Walk => {
                    // First-person look
                    controller.azimuth -= ev.delta.x * controller.orbit_sensitivity * 0.5;
                    controller.elevation -= ev.delta.y * controller.orbit_sensitivity * 0.5;
                    controller.elevation = controller.elevation.clamp(-1.5, 1.5);
                }
            }
        }
    } else {
        // Apply damping to angular velocity when not dragging
        let damping = controller.damping;
        controller.angular_velocity *= damping;
        if controller.angular_velocity.length() > 0.0001 {
            controller.azimuth -= controller.angular_velocity.x;
            controller.elevation -= controller.angular_velocity.y;
            controller.elevation = controller.elevation.clamp(-1.5, 1.5);
        }
    }

    // Handle mouse wheel for zoom - only when NOT over UI
    if !mouse_over_ui {
        for ev in mouse_wheel.read() {
            let zoom_delta = ev.y * controller.zoom_sensitivity;
            controller.distance = (controller.distance * (1.0 - zoom_delta)).clamp(1.0, 500000.0);
        }
    }
}

/// Handle touch input for camera control (mobile/tablet)
///
/// Gesture mapping:
/// - 1 finger drag → orbit
/// - 2 finger drag → pan
/// - 2 finger pinch → zoom
/// - Tap (no drag) → select entity
fn camera_touch_system(touches: Res<Touches>, mut controller: ResMut<CameraController>) {
    let pressed: Vec<Vec2> = touches.iter().map(|t| t.position()).collect();
    let count = pressed.len();
    let prev_count = controller.touch_count;

    // === Single touch: orbit / tap ===
    if count == 1 {
        let pos = pressed[0];

        if prev_count == 0 {
            // Touch just started
            controller.is_touch_dragging = true;
            controller.touch_did_drag = false;
            controller.last_touch_pos = pos;
            controller.touch_drag_start = pos;
        } else if controller.is_touch_dragging && prev_count == 1 {
            // Continued single-finger drag → orbit
            let delta = pos - controller.last_touch_pos;

            if delta.length() > 2.0 {
                controller.touch_did_drag = true;
            }

            if controller.touch_did_drag {
                // Apply orbit (same math as mouse)
                controller.azimuth -= delta.x * controller.orbit_sensitivity;
                controller.elevation -= delta.y * controller.orbit_sensitivity;
                controller.elevation = controller.elevation.clamp(-1.5, 1.5);
                controller.angular_velocity = delta * controller.orbit_sensitivity;
            }

            controller.last_touch_pos = pos;
        }
    }

    // === Two touches: pan + pinch zoom ===
    if count == 2 {
        let center = (pressed[0] + pressed[1]) * 0.5;
        let distance = (pressed[0] - pressed[1]).length();

        if prev_count < 2 {
            // Just transitioned to two fingers — record baseline
            controller.last_two_touch_center = center;
            controller.last_pinch_distance = distance;
            // Cancel single-finger orbit
            controller.is_touch_dragging = false;
            controller.touch_did_drag = true; // prevent tap
        } else {
            // Pan: delta of center point
            let center_delta = center - controller.last_two_touch_center;
            let right = Vec3::new(controller.azimuth.cos(), 0.0, -controller.azimuth.sin());
            let up = Vec3::Y;
            let pan =
                right * center_delta.x * controller.pan_sensitivity * controller.distance * 0.01
                    - up * center_delta.y * controller.pan_sensitivity * controller.distance * 0.01;
            controller.target += pan;

            // Pinch zoom: ratio of finger distances
            if controller.last_pinch_distance > 10.0 {
                let zoom_ratio = distance / controller.last_pinch_distance;
                controller.distance = (controller.distance / zoom_ratio).clamp(1.0, 500000.0);
            }

            controller.last_two_touch_center = center;
            controller.last_pinch_distance = distance;
        }
    }

    // === Touch released: detect tap ===
    if count == 0 && prev_count > 0 {
        if controller.is_touch_dragging && !controller.touch_did_drag {
            // This was a tap — trigger picking
            controller.just_clicked = true;
            controller.drag_start_pos = controller.touch_drag_start;
        }
        controller.is_touch_dragging = false;
    }

    controller.touch_count = count;
}

/// Handle keyboard input for camera control
fn camera_keyboard_system(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut controller: ResMut<CameraController>,
    time: Res<Time>,
) {
    let dt = time.delta_secs();

    // Walk mode movement (WASD)
    if controller.mode == CameraMode::Walk {
        let forward = Vec3::new(
            -controller.azimuth.sin() * controller.elevation.cos(),
            controller.elevation.sin(),
            -controller.azimuth.cos() * controller.elevation.cos(),
        )
        .normalize();
        let right = Vec3::new(controller.azimuth.cos(), 0.0, -controller.azimuth.sin());

        let mut movement = Vec3::ZERO;

        if keyboard.pressed(KeyCode::KeyW) || keyboard.pressed(KeyCode::ArrowUp) {
            movement += forward;
        }
        if keyboard.pressed(KeyCode::KeyS) || keyboard.pressed(KeyCode::ArrowDown) {
            movement -= forward;
        }
        if keyboard.pressed(KeyCode::KeyA) || keyboard.pressed(KeyCode::ArrowLeft) {
            movement -= right;
        }
        if keyboard.pressed(KeyCode::KeyD) || keyboard.pressed(KeyCode::ArrowRight) {
            movement += right;
        }
        if keyboard.pressed(KeyCode::KeyQ) {
            movement -= Vec3::Y;
        }
        if keyboard.pressed(KeyCode::KeyE) {
            movement += Vec3::Y;
        }

        if movement.length() > 0.0 {
            let walk_speed = controller.walk_speed;
            controller.target += movement.normalize() * walk_speed * dt;
        }
    }

    // Preset views (number keys)
    if keyboard.just_pressed(KeyCode::Digit1) {
        controller.set_preset_view(0.0, 0.0); // Front
    }
    if keyboard.just_pressed(KeyCode::Digit2) {
        controller.set_preset_view(std::f32::consts::PI, 0.0); // Back
    }
    if keyboard.just_pressed(KeyCode::Digit3) {
        controller.set_preset_view(-std::f32::consts::FRAC_PI_2, 0.0); // Left
    }
    if keyboard.just_pressed(KeyCode::Digit4) {
        controller.set_preset_view(std::f32::consts::FRAC_PI_2, 0.0); // Right
    }
    if keyboard.just_pressed(KeyCode::Digit5) {
        controller.set_preset_view(0.0, std::f32::consts::FRAC_PI_2 - 0.001); // Top
    }
    if keyboard.just_pressed(KeyCode::Digit6) {
        controller.set_preset_view(0.0, -std::f32::consts::FRAC_PI_2 + 0.001); // Bottom
    }
    if keyboard.just_pressed(KeyCode::KeyH) {
        controller.home(); // Isometric
    }
}

/// Update camera transform
fn camera_update_system(
    mut controller: ResMut<CameraController>,
    mut camera: Query<&mut Transform, With<MainCamera>>,
    time: Res<Time>,
) {
    let dt = time.delta_secs();

    // Handle animation
    if controller.animation_target.is_some() {
        // Extract animation target data to avoid borrow conflicts
        let animation_data = {
            let target = controller.animation_target.as_mut().unwrap();
            target.elapsed += dt;
            let t = (target.elapsed / target.duration).min(1.0);
            // Ease out cubic
            let t = 1.0 - (1.0 - t).powi(3);
            let completed = target.elapsed >= target.duration;
            (
                target.azimuth,
                target.elevation,
                target.distance,
                target.target,
                t,
                completed,
            )
        };

        let (target_azimuth, target_elevation, target_distance, target_pos, t, completed) =
            animation_data;

        controller.azimuth = lerp(controller.azimuth, target_azimuth, t);
        controller.elevation = lerp(controller.elevation, target_elevation, t);
        controller.distance = lerp(controller.distance, target_distance, t);
        controller.target = controller.target.lerp(target_pos, t);

        if completed {
            controller.animation_target = None;
            controller.is_animating = false;
        }
    }

    // Update camera transform
    if let Ok(mut transform) = camera.single_mut() {
        let position = controller.get_position();

        // Apply damping for smooth movement
        transform.translation = transform
            .translation
            .lerp(position, 1.0 - controller.damping.powi(2));
        transform.look_at(controller.target, Vec3::Y);
    }

    // Save camera state periodically (WASM)
    #[cfg(target_arch = "wasm32")]
    {
        // Only save occasionally to avoid flooding localStorage
        static mut SAVE_COUNTER: u32 = 0;
        unsafe {
            SAVE_COUNTER += 1;
            if SAVE_COUNTER % 30 == 0 {
                save_camera(&controller.to_storage());
            }
        }
    }
}

/// Linear interpolation
fn lerp(a: f32, b: f32, t: f32) -> f32 {
    a + (b - a) * t
}