fyroxed_base 1.0.0-rc.2

A scene editor for Fyrox game engine
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
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::command::CommandStack;
use crate::fyrox::{
    core::{algebra::Vector2, math::Rect, pool::Handle, uuid::Uuid, TypeUuidProvider},
    engine::Engine,
    gui::{
        message::{KeyCode, MouseButton},
        UiNode, UserInterface,
    },
    scene::Scene,
};
use crate::scene::nullscene::NullSceneController;
use crate::{
    highlight::HighlightRenderPass,
    interaction::{
        move_mode::MoveInteractionMode, navmesh::EditNavmeshMode,
        rotate_mode::RotateInteractionMode, scale_mode::ScaleInteractionMode,
        select_mode::SelectInteractionMode, terrain::TerrainInteractionMode,
        InteractionModeContainer,
    },
    message::MessageSender,
    scene::{controller::SceneController, GameScene, Selection},
    scene_viewer::SceneViewer,
    settings::{keys::KeyBindings, Settings},
    ui_scene::{
        interaction::move_mode::MoveWidgetsInteractionMode, interaction::UiSelectInteractionMode,
        UiScene,
    },
};
use fyrox::gui::file_browser::FileType;
use std::{cell::RefCell, path::PathBuf, rc::Rc};

pub struct EditorSceneEntry {
    pub has_unsaved_changes: bool,
    pub path: Option<PathBuf>,
    pub selection: Selection,
    pub command_stack: CommandStack,
    pub controller: Box<dyn SceneController>,
    pub interaction_modes: InteractionModeContainer,
    pub current_interaction_mode: Option<Uuid>,

    pub last_mouse_pos: Option<Vector2<f32>>,
    pub click_mouse_pos: Option<Vector2<f32>>,
    pub sender: MessageSender,
    pub id: Uuid,
}

impl EditorSceneEntry {
    // Create an entry for when there is no scene using a [`NullSceneController`].
    pub fn new_null_scene(
        engine: &mut Engine,
        settings: &mut Settings,
        message_sender: MessageSender,
    ) -> Self {
        Self {
            has_unsaved_changes: false,
            path: None,
            selection: Selection::default(),
            command_stack: CommandStack::new(false, settings.general.max_history_entries),
            controller: Box::new(NullSceneController {
                sender: message_sender.clone(),
                resource_manager: engine.resource_manager.clone(),
            }),
            interaction_modes: InteractionModeContainer::default(),
            current_interaction_mode: None,
            last_mouse_pos: None,
            click_mouse_pos: None,
            sender: message_sender,
            id: Default::default(),
        }
    }
    pub fn new_game_scene(
        scene: Scene,
        path: Option<PathBuf>,
        engine: &mut Engine,
        settings: &mut Settings,
        message_sender: MessageSender,
        scene_viewer: &SceneViewer,
        highlighter: Option<Rc<RefCell<HighlightRenderPass>>>,
    ) -> Self {
        let game_scene = GameScene::from_native_scene(
            scene,
            engine,
            path.as_deref(),
            settings,
            message_sender.clone(),
            highlighter,
        );

        let mut interaction_modes = InteractionModeContainer::default();
        interaction_modes.add(SelectInteractionMode::new(
            scene_viewer.frame(),
            scene_viewer.selection_frame(),
            message_sender.clone(),
        ));
        interaction_modes.add(MoveInteractionMode::new(
            &game_scene,
            engine,
            message_sender.clone(),
        ));
        interaction_modes.add(RotateInteractionMode::new(
            &game_scene,
            engine,
            message_sender.clone(),
        ));
        interaction_modes.add(ScaleInteractionMode::new(
            &game_scene,
            engine,
            message_sender.clone(),
        ));
        interaction_modes.add(EditNavmeshMode::new(
            &game_scene,
            engine,
            message_sender.clone(),
        ));
        interaction_modes.add(TerrainInteractionMode::new(
            &game_scene,
            engine,
            message_sender.clone(),
            scene_viewer.frame(),
        ));
        interaction_modes.sender = Some(message_sender.clone());

        let mut entry = EditorSceneEntry {
            has_unsaved_changes: false,
            interaction_modes,
            controller: Box::new(game_scene),
            current_interaction_mode: None,
            last_mouse_pos: None,
            click_mouse_pos: None,
            sender: message_sender,
            id: Uuid::new_v4(),
            path,
            selection: Default::default(),
            command_stack: CommandStack::new(false, settings.general.max_history_entries),
        };

        entry.set_interaction_mode(engine, Some(MoveInteractionMode::type_uuid()));

        entry
    }

    pub fn new_ui_scene(
        ui: UserInterface,
        path: Option<PathBuf>,
        message_sender: MessageSender,
        scene_viewer: &SceneViewer,
        engine: &mut Engine,
        settings: &Settings,
    ) -> Self {
        let mut interaction_modes = InteractionModeContainer::default();
        interaction_modes.add(UiSelectInteractionMode::new(
            scene_viewer.frame(),
            scene_viewer.selection_frame(),
            message_sender.clone(),
        ));
        interaction_modes.add(MoveWidgetsInteractionMode::new(message_sender.clone()));
        interaction_modes.sender = Some(message_sender.clone());

        let mut entry = EditorSceneEntry {
            has_unsaved_changes: false,
            interaction_modes,
            controller: Box::new(UiScene::new(ui, message_sender.clone())),
            current_interaction_mode: None,
            last_mouse_pos: None,
            click_mouse_pos: None,
            sender: message_sender,
            id: Uuid::new_v4(),
            path,
            selection: Default::default(),
            command_stack: CommandStack::new(false, settings.general.max_history_entries),
        };

        entry.set_interaction_mode(engine, Some(UiSelectInteractionMode::type_uuid()));

        entry
    }

    pub fn set_interaction_mode(&mut self, engine: &mut Engine, mode: Option<Uuid>) {
        if self.current_interaction_mode != mode {
            // Deactivate current first.
            if let Some(interaction_mode) = self
                .current_interaction_mode
                .and_then(|current_mode| self.interaction_modes.get_mut(&current_mode))
            {
                interaction_mode.deactivate(&*self.controller, engine);
            }

            self.current_interaction_mode = mode;

            // Activate new.
            if let Some(interaction_mode) = self
                .current_interaction_mode
                .and_then(|current_mode| self.interaction_modes.get_mut(&current_mode))
            {
                interaction_mode.activate(&*self.controller, engine);
            }
        }
    }

    pub fn default_file_info(&self) -> (PathBuf, FileType) {
        let file_type = self.controller.file_type();
        (file_type.make_file_name("unnamed"), file_type)
    }

    pub fn need_save(&self) -> bool {
        self.has_unsaved_changes || self.path.is_none()
    }

    pub fn before_drop(&mut self, engine: &mut Engine) {
        for mut interaction_mode in self.interaction_modes.drain() {
            interaction_mode.on_drop(engine);
        }
    }

    pub fn name(&self) -> String {
        self.path
            .as_ref()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|| String::from("Unnamed Scene"))
    }

    pub fn save(
        &mut self,
        path: PathBuf,
        settings: &Settings,
        engine: &mut Engine,
    ) -> Result<String, String> {
        let result = self.controller.save(&path, settings, engine);
        self.path = Some(path);
        result
    }

    #[must_use]
    pub fn on_key_up(
        &mut self,
        key: KeyCode,
        engine: &mut Engine,
        key_bindings: &KeyBindings,
    ) -> bool {
        if self.controller.on_key_up(key, engine, key_bindings) {
            return true;
        }

        if let Some(interaction_mode) = self
            .current_interaction_mode
            .and_then(|id| self.interaction_modes.get_mut(&id))
        {
            if interaction_mode.on_key_up(key, &mut *self.controller, engine) {
                return true;
            }
        }

        false
    }

    #[must_use]
    pub fn on_key_down(
        &mut self,
        key: KeyCode,
        engine: &mut Engine,
        key_bindings: &KeyBindings,
    ) -> bool {
        if self.controller.on_key_down(key, engine, key_bindings) {
            return true;
        }

        if let Some(interaction_mode) = self
            .current_interaction_mode
            .and_then(|id| self.interaction_modes.get_mut(&id))
        {
            if interaction_mode.on_key_down(key, &self.selection, &mut *self.controller, engine) {
                return true;
            }
        }

        false
    }

    pub fn on_mouse_move(
        &mut self,
        pos: Vector2<f32>,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        let last_pos = *self.last_mouse_pos.get_or_insert(pos);
        let mouse_offset = pos - last_pos;
        let rel_pos = pos - screen_bounds.position;

        if let Some(interaction_mode) = self
            .current_interaction_mode
            .and_then(|id| self.interaction_modes.get_mut(&id))
        {
            interaction_mode.on_mouse_move(
                mouse_offset,
                rel_pos,
                &self.selection,
                &mut *self.controller,
                engine,
                screen_bounds.size,
                settings,
            );
        }

        self.last_mouse_pos = Some(pos);

        self.controller
            .on_mouse_move(pos, mouse_offset, screen_bounds, engine, settings)
    }

    pub fn on_mouse_up(
        &mut self,
        button: MouseButton,
        pos: Vector2<f32>,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        if button == MouseButton::Left {
            if let Some(interaction_mode) = self
                .current_interaction_mode
                .and_then(|id| self.interaction_modes.get_mut(&id))
            {
                let rel_pos = pos - screen_bounds.position;
                interaction_mode.on_left_mouse_button_up(
                    &self.selection,
                    &mut *self.controller,
                    engine,
                    rel_pos,
                    screen_bounds.size,
                    settings,
                );
            }
        }

        self.controller
            .on_mouse_up(button, pos, screen_bounds, engine, settings)
    }

    pub fn on_mouse_down(
        &mut self,
        button: MouseButton,
        pos: Vector2<f32>,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        if button == MouseButton::Left {
            if let Some(interaction_mode) = self
                .current_interaction_mode
                .and_then(|id| self.interaction_modes.get_mut(&id))
            {
                let rel_pos = pos - screen_bounds.position;

                interaction_mode.on_left_mouse_button_down(
                    &self.selection,
                    &mut *self.controller,
                    engine,
                    rel_pos,
                    screen_bounds.size,
                    settings,
                );
            }
        }

        self.controller
            .on_mouse_down(button, pos, screen_bounds, engine, settings)
    }

    pub fn on_mouse_wheel(&mut self, amount: f32, engine: &mut Engine, settings: &Settings) {
        self.controller.on_mouse_wheel(amount, engine, settings)
    }

    /// Called when the mouse enters the scene viewer.
    pub fn on_mouse_enter(
        &mut self,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        if let Some(interaction_mode) = self
            .current_interaction_mode
            .and_then(|id| self.interaction_modes.get_mut(&id))
        {
            interaction_mode.on_mouse_enter(
                &self.selection,
                &mut *self.controller,
                engine,
                screen_bounds.size,
                settings,
            );
        }
    }

    /// Called when the moue leaves the scene viewer.
    pub fn on_mouse_leave(
        &mut self,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        let last_pos = self
            .last_mouse_pos
            .unwrap_or_else(|| engine.user_interfaces.first().cursor_position());
        let rel_pos = last_pos - screen_bounds.position;

        if let Some(interaction_mode) = self
            .current_interaction_mode
            .and_then(|id| self.interaction_modes.get_mut(&id))
        {
            interaction_mode.on_mouse_leave(
                rel_pos,
                &self.selection,
                &mut *self.controller,
                engine,
                screen_bounds.size,
                settings,
            );
        }
        self.controller.on_mouse_leave(engine, settings)
    }

    pub fn on_drag_over(
        &mut self,
        handle: Handle<UiNode>,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        self.controller
            .on_drag_over(handle, screen_bounds, engine, settings)
    }

    pub fn on_drop(
        &mut self,
        handle: Handle<UiNode>,
        screen_bounds: Rect<f32>,
        engine: &mut Engine,
        settings: &Settings,
    ) {
        self.controller
            .on_drop(handle, screen_bounds, engine, settings)
    }
}

pub struct SceneContainer {
    /// The scene entry that will be current when the container is empty.
    null_scene: EditorSceneEntry,
    pub entries: Vec<EditorSceneEntry>,
    current_scene: Option<usize>,
}

impl SceneContainer {
    pub fn new(engine: &mut Engine, settings: &mut Settings, sender: MessageSender) -> Self {
        Self {
            null_scene: EditorSceneEntry::new_null_scene(engine, settings, sender),
            entries: vec![],
            current_scene: None,
        }
    }

    pub fn has_active_scene(&self) -> bool {
        self.current_scene.is_some()
    }

    pub fn current_scene_entry_ref(&self) -> &EditorSceneEntry {
        self.current_scene
            .and_then(|i| self.entries.get(i))
            .unwrap_or(&self.null_scene)
    }

    pub fn current_scene_entry_mut(&mut self) -> &mut EditorSceneEntry {
        self.current_scene
            .and_then(|i| self.entries.get_mut(i))
            .unwrap_or(&mut self.null_scene)
    }

    pub fn current_scene_controller_ref(&self) -> &dyn SceneController {
        &*self.current_scene_entry_ref().controller
    }

    pub fn current_scene_controller_mut(&mut self) -> &mut dyn SceneController {
        &mut *self.current_scene_entry_mut().controller
    }

    pub fn first_unsaved_scene(&self) -> Option<&EditorSceneEntry> {
        self.entries.iter().find(|s| s.need_save())
    }

    pub fn unsaved_scene_count(&self) -> usize {
        self.entries.iter().filter(|s| s.need_save()).count()
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = &EditorSceneEntry> {
        self.entries.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut EditorSceneEntry> {
        self.entries.iter_mut()
    }

    pub fn try_get(&self, index: usize) -> Option<&EditorSceneEntry> {
        self.entries.get(index)
    }

    pub fn try_get_mut(&mut self, index: usize) -> Option<&mut EditorSceneEntry> {
        self.entries.get_mut(index)
    }

    pub fn current_scene_index(&self) -> Option<usize> {
        self.current_scene
    }

    pub fn set_current_scene(&mut self, id: Uuid) -> bool {
        if let Some(index) = self.entries.iter().position(|e| e.id == id) {
            self.current_scene = Some(index);
            true
        } else {
            false
        }
    }

    pub fn entry_by_scene_id(&self, id: Uuid) -> Option<&EditorSceneEntry> {
        self.entries.iter().find(|e| e.id == id)
    }

    pub fn entry_by_scene_id_mut(&mut self, id: Uuid) -> Option<&mut EditorSceneEntry> {
        self.entries.iter_mut().find(|e| e.id == id)
    }

    pub fn add_and_select(&mut self, entry: EditorSceneEntry) {
        self.current_scene = Some(self.entries.len());
        self.entries.push(entry);
    }

    pub fn take_scene(&mut self, id: Uuid) -> Option<EditorSceneEntry> {
        // Remember the UUID of the current scene, because the index is about to become invalid
        let current_id = self.current_scene_entry_ref().id;
        let scene = self
            .entries
            .iter()
            .position(|e| e.id == id)
            .map(|i| self.entries.remove(i));
        // Update the current scene index based on the UUID of the current scene.
        if !self.set_current_scene(current_id) {
            // If the scene could not be set by UUID, then the current scene was taken.
            self.current_scene = if self.entries.is_empty() {
                None
            } else {
                // TODO: Maybe set it to the previous one?
                Some(0)
            };
        }
        scene
    }
}