bimifc-bevy 0.1.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
//! BIMIFC Bevy 3D Viewer
//!
//! Bevy-based 3D viewer for IFC models with WebGPU/WebGL2 rendering.
//! Supports orbit/pan/zoom camera controls, entity selection, and section planes.
//!
//! Features pure Bevy UI that works on both web (WASM) and native platforms.

// Allow unexpected_cfgs from objc crate's msg_send! macro used in native_view
#![allow(unexpected_cfgs)]

pub mod camera;
pub mod loader;
pub mod mesh;
#[cfg(feature = "photometric")]
pub mod photometric;
pub mod picking;
pub mod section;
pub mod storage;

#[cfg(feature = "bevy-ui")]
pub mod ui;

#[cfg(any(target_os = "ios", target_os = "macos"))]
pub mod native_view;

#[cfg(any(target_os = "ios", target_os = "macos"))]
pub mod ffi;

use bevy::prelude::*;
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;

/// Global debug mode flag (set from URL parameter ?debug=1)
static DEBUG_MODE: AtomicBool = AtomicBool::new(false);

/// Pending meshes for unified mode (Yew -> Bevy direct transfer)
/// This avoids serialization overhead when running in same WASM
static PENDING_MESHES: Mutex<Option<Vec<IfcMesh>>> = Mutex::new(None);

/// Set pending meshes from Yew (unified mode only)
/// This is called by Yew after parsing geometry, Bevy polls this
pub fn set_pending_meshes(meshes: Vec<IfcMesh>) {
    let count = meshes.len();
    let mut guard = PENDING_MESHES.lock().unwrap();
    *guard = Some(meshes);
    log(&format!("[Bevy] Pending meshes set: {} meshes", count));
}

/// Take pending meshes (consumes them)
pub fn take_pending_meshes() -> Option<Vec<IfcMesh>> {
    let mut guard = PENDING_MESHES.lock().unwrap();
    guard.take()
}

/// Check if pending meshes are available
pub fn has_pending_meshes() -> bool {
    let guard = PENDING_MESHES.lock().unwrap();
    guard.is_some()
}

/// Check if debug mode is enabled
pub fn is_debug() -> bool {
    DEBUG_MODE.load(Ordering::Relaxed)
}

/// Initialize debug mode from URL parameters
#[cfg(target_arch = "wasm32")]
fn init_debug_from_url() {
    if let Some(window) = web_sys::window() {
        if let Ok(search) = window.location().search() {
            let search_str: &str = &search;
            if search_str.contains("debug=1") || search_str.contains("debug=true") {
                DEBUG_MODE.store(true, Ordering::Relaxed);
                web_sys::console::log_1(&"[Bevy] Debug mode enabled".into());
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
fn init_debug_from_url() {
    // Native: check env var
    if std::env::var("DEBUG").is_ok() {
        DEBUG_MODE.store(true, Ordering::Relaxed);
    }
}

// Re-exports
pub use camera::{CameraController, CameraMode, CameraPlugin};
pub use loader::{LoadIfcContentEvent, LoadIfcFileEvent, LoaderPlugin, OpenFileDialogRequest};
pub use mesh::{AutoFitState, IfcEntity, IfcMesh, IfcMeshSerialized, MeshGeometry, MeshPlugin};
pub use picking::{PickingPlugin, SelectionState};
pub use section::{SectionPlane, SectionPlanePlugin};
pub use storage::*;

#[cfg(feature = "bevy-ui")]
pub use ui::{IfcUiPlugin, UiState};

#[cfg(any(target_os = "ios", target_os = "macos"))]
pub use native_view::{AppView, AppViewPlugin, AppViews};

/// Main IFC viewer plugin - combines all subsystems
pub struct IfcViewerPlugin;

impl Plugin for IfcViewerPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<IfcSceneData>()
            .init_resource::<ViewerSettings>()
            .init_resource::<IfcTimestamp>()
            .add_plugins((
                CameraPlugin,
                MeshPlugin,
                PickingPlugin,
                SectionPlanePlugin,
                LoaderPlugin,
            ))
            .add_systems(Update, (poll_scene_changes, poll_selection_from_storage));

        // Add Bevy UI when feature is enabled
        #[cfg(feature = "bevy-ui")]
        app.add_plugins(IfcUiPlugin);

        // Add photometric lighting when feature is enabled
        #[cfg(feature = "photometric")]
        app.add_plugins(photometric::PhotometricLightingPlugin);
    }
}

/// Resource containing all IFC scene data
#[derive(Resource, Default)]
pub struct IfcSceneData {
    /// All meshes in the scene
    pub meshes: Vec<IfcMesh>,
    /// Entity metadata (type, name, properties)
    pub entities: Vec<EntityInfo>,
    /// Scene bounds (AABB)
    pub bounds: Option<SceneBounds>,
    /// Data timestamp for change detection
    pub timestamp: u64,
    /// Whether scene needs rebuild
    pub dirty: bool,
}

/// Entity metadata
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EntityInfo {
    pub id: u64,
    pub entity_type: String,
    pub name: Option<String>,
    pub storey: Option<String>,
    pub storey_elevation: Option<f32>,
}

/// Axis-aligned bounding box for scene
#[derive(Clone, Debug, Default)]
pub struct SceneBounds {
    pub min: Vec3,
    pub max: Vec3,
}

impl SceneBounds {
    pub fn center(&self) -> Vec3 {
        (self.min + self.max) * 0.5
    }

    pub fn size(&self) -> Vec3 {
        self.max - self.min
    }

    pub fn diagonal(&self) -> f32 {
        self.size().length()
    }
}

/// Viewer settings and state
#[derive(Resource)]
pub struct ViewerSettings {
    /// Current theme (affects background color)
    pub theme: Theme,
    /// Show grid
    pub show_grid: bool,
    /// Show axes helper
    pub show_axes: bool,
    /// Hidden entity IDs
    pub hidden_entities: FxHashSet<u64>,
    /// Isolated entity IDs (if Some, only show these)
    pub isolated_entities: Option<FxHashSet<u64>>,
    /// Active storey filter
    pub storey_filter: Option<String>,
}

impl Default for ViewerSettings {
    fn default() -> Self {
        Self {
            theme: Theme::Dark,
            show_grid: true,
            show_axes: true,
            hidden_entities: FxHashSet::default(),
            isolated_entities: None,
            storey_filter: None,
        }
    }
}

/// Theme variants
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Theme {
    Light,
    #[default]
    Dark,
}

impl Theme {
    pub fn background_color(&self) -> Color {
        match self {
            Theme::Light => Color::srgb(0.95, 0.95, 0.95),
            Theme::Dark => Color::srgb(0.12, 0.12, 0.12),
        }
    }

    pub fn grid_color(&self) -> Color {
        match self {
            Theme::Light => Color::srgba(0.5, 0.5, 0.5, 0.3),
            Theme::Dark => Color::srgba(0.4, 0.4, 0.4, 0.3),
        }
    }
}

/// Timestamp for detecting localStorage changes (WASM)
#[derive(Resource, Default)]
pub struct IfcTimestamp(pub String);

/// System to poll for scene changes
/// Checks both direct memory (unified mode) and JS bridge (split mode)
#[allow(unused_variables, unused_mut)]
pub fn poll_scene_changes(
    mut scene_data: ResMut<IfcSceneData>,
    mut settings: ResMut<ViewerSettings>,
    mut last_timestamp: ResMut<IfcTimestamp>,
    mut auto_fit: ResMut<mesh::AutoFitState>,
) {
    // UNIFIED MODE: Check for direct memory transfer first (no serialization!)
    if let Some(meshes) = take_pending_meshes() {
        log_info(&format!(
            "[Bevy] Direct mesh transfer: {} meshes (no deserialization!)",
            meshes.len()
        ));

        // Build EntityInfo from meshes
        scene_data.entities = meshes
            .iter()
            .map(|m| EntityInfo {
                id: m.entity_id,
                entity_type: m.entity_type.clone(),
                name: m.name.clone(),
                storey: None,
                storey_elevation: None,
            })
            .collect();

        scene_data.meshes = meshes;
        scene_data.dirty = true;
        auto_fit.has_fit = false;
    } else {
        // SPLIT MODE: Fall back to JS bridge polling
        #[cfg(target_arch = "wasm32")]
        {
            if let Some(new_timestamp) = storage::get_timestamp() {
                if new_timestamp != last_timestamp.0 {
                    log(&format!(
                        "[Bevy] Timestamp changed: {} -> {}",
                        last_timestamp.0, new_timestamp
                    ));

                    // Load geometry from storage (binary deserialization)
                    if let Some(geometry) = storage::load_geometry() {
                        log(&format!(
                            "[Bevy] Loaded {} meshes from JS bridge",
                            geometry.len()
                        ));

                        // Build EntityInfo directly from meshes
                        scene_data.entities = geometry
                            .iter()
                            .map(|m| EntityInfo {
                                id: m.entity_id,
                                entity_type: m.entity_type.clone(),
                                name: m.name.clone(),
                                storey: None,
                                storey_elevation: None,
                            })
                            .collect();

                        scene_data.meshes = geometry;
                        scene_data.dirty = true;
                        auto_fit.has_fit = false;
                    }

                    // Load selection state
                    if let Some(selection) = storage::load_selection() {
                        // Selection is handled by PickingPlugin
                    }

                    // Load visibility state
                    if let Some(visibility) = storage::load_visibility() {
                        settings.hidden_entities = visibility.hidden.into_iter().collect();
                        settings.isolated_entities =
                            visibility.isolated.map(|v| v.into_iter().collect());
                    }

                    last_timestamp.0 = new_timestamp;
                }
            }
        }
    }
}

/// System to poll selection changes from localStorage (UI -> Bevy sync)
/// This allows the UI (Leptos/Yew) to update Bevy's selection via localStorage
#[allow(unused_variables)]
pub fn poll_selection_from_storage(selection: ResMut<picking::SelectionState>) {
    #[cfg(target_arch = "wasm32")]
    {
        // Check if there's a pending selection from UI
        if let Some(stored_selection) = storage::load_selection() {
            // Only update if source is "leptos" or "yew" (UI-initiated)
            // Skip if source is "bevy" to prevent loops
            if let Some(source) = storage::get_selection_source() {
                if source == "bevy" {
                    return;
                }
            }

            // Convert to HashSet for comparison
            let new_selection: FxHashSet<u64> = stored_selection.selected_ids.into_iter().collect();

            // Only update if actually different
            if selection.selected != new_selection {
                selection.selected = new_selection;
                // Mark as changed so mesh selection system updates colors
            }
        }
    }
}

/// Log to browser console (WASM) or stdout (native) - only in debug mode
#[cfg(target_arch = "wasm32")]
pub fn log(msg: &str) {
    if is_debug() {
        web_sys::console::log_1(&msg.into());
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn log(msg: &str) {
    if is_debug() {
        println!("{}", msg);
    }
}

/// Log info that should always be shown
#[cfg(target_arch = "wasm32")]
pub fn log_info(msg: &str) {
    web_sys::console::info_1(&msg.into());
}

#[cfg(not(target_arch = "wasm32"))]
pub fn log_info(msg: &str) {
    println!("{}", msg);
}

/// Run the viewer on a canvas element (WASM)
///
/// This is the unified single-WASM viewer. It starts with an empty scene
/// and the user can load IFC files using:
/// - The "Open" button in the toolbar (Bevy UI mode)
/// - Drag and drop onto the canvas
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn run_on_canvas(canvas_selector: &str) {
    console_error_panic_hook::set_once();
    init_debug_from_url();
    log_info(&format!(
        "[Bevy] Starting unified viewer on canvas: {}",
        canvas_selector
    ));

    // Start with empty scene - user will load files via UI or drag-and-drop
    let scene_data = IfcSceneData::default();

    let mut app = App::new();

    // Insert resources before plugins
    app.insert_resource(scene_data);
    app.insert_resource(ViewerSettings::default());
    app.insert_resource(IfcTimestamp::default());

    // Add plugins
    app.add_plugins(DefaultPlugins.set(WindowPlugin {
        primary_window: Some(Window {
            title: "BIMIFC Viewer".to_string(),
            canvas: Some(canvas_selector.to_string()),
            fit_canvas_to_parent: true,
            prevent_default_event_handling: false,
            ..default()
        }),
        ..default()
    }));

    app.add_plugins(IfcViewerPlugin);
    app.run();
}

/// Run the viewer in a native window (desktop)
#[cfg(not(target_arch = "wasm32"))]
pub fn run_on_canvas(_canvas_selector: &str) {
    run_native();
}

/// Run native desktop viewer
#[cfg(not(target_arch = "wasm32"))]
pub fn run_native() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "BIMIFC Viewer".to_string(),
                resolution: (1280u32, 720u32).into(),
                ..default()
            }),
            ..default()
        }))
        // Dark gray background so we can see if rendering works
        .insert_resource(ClearColor(Color::srgb(0.1, 0.1, 0.15)))
        .add_plugins(IfcViewerPlugin)
        .run();
}

#[cfg(target_arch = "wasm32")]
pub fn run_native() {
    run_on_canvas("#bevy-canvas");
}

/// WASM entry point
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn wasm_start() {
    log("[Bevy] wasm_start called");
    run_native();
}

/// Run Bevy with pre-loaded scene data (for unified Yew+Bevy mode)
/// This allows Yew to parse IFC and pass data directly without JS bridge
#[cfg(target_arch = "wasm32")]
pub fn run_with_data(canvas_selector: &str, scene_data: IfcSceneData) {
    console_error_panic_hook::set_once();
    init_debug_from_url();
    log_info(&format!(
        "[Bevy] Starting with data: {} meshes, {} entities",
        scene_data.meshes.len(),
        scene_data.entities.len()
    ));

    let mut app = App::new();

    // Insert scene data directly - no localStorage polling needed
    app.insert_resource(scene_data);
    app.insert_resource(ViewerSettings::default());
    app.insert_resource(IfcTimestamp::default());

    // Add plugins
    app.add_plugins(DefaultPlugins.set(WindowPlugin {
        primary_window: Some(Window {
            title: "BIMIFC Viewer".to_string(),
            canvas: Some(canvas_selector.to_string()),
            fit_canvas_to_parent: true,
            prevent_default_event_handling: false,
            ..default()
        }),
        ..default()
    }));

    app.add_plugins(IfcViewerPlugin);
    app.run();
}

#[cfg(not(target_arch = "wasm32"))]
pub fn run_with_data(_canvas_selector: &str, _scene_data: IfcSceneData) {
    run_native();
}