bevy_map_editor 0.5.0

Full-featured map editor for Bevy games with autotile support
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
//! Project management for the map editor
//!
//! This module handles project file save/load and the Project resource.

mod file;

pub use file::*;

use bevy::prelude::Resource;
use bevy_map_animation::SpriteData;
use bevy_map_autotile::AutotileConfig;
use bevy_map_core::{EntityTypeConfig, Level, Tileset, WorldConfig};
use bevy_map_dialogue::DialogueTree;
use bevy_map_schema::Schema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use uuid::Uuid;

/// A saved tile stamp (reusable tile arrangement)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TileStamp {
    /// Unique identifier for this stamp
    pub id: Uuid,
    /// User-friendly name
    pub name: String,
    /// Width of the stamp in tiles
    pub width: u32,
    /// Height of the stamp in tiles
    pub height: u32,
    /// The tileset this stamp uses
    pub tileset_id: Uuid,
    /// Tile data in row-major order (None = empty cell)
    /// Values include flip flags encoded in the tile index
    pub tiles: Vec<Option<u32>>,
}

impl TileStamp {
    /// Create a new stamp with the given name and dimensions
    pub fn new(name: String, width: u32, height: u32, tileset_id: Uuid) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            width,
            height,
            tileset_id,
            tiles: vec![None; (width * height) as usize],
        }
    }

    /// Get tile at position (returns None if out of bounds or empty)
    pub fn get_tile(&self, x: u32, y: u32) -> Option<u32> {
        if x >= self.width || y >= self.height {
            return None;
        }
        let idx = (y * self.width + x) as usize;
        self.tiles.get(idx).copied().flatten()
    }
}

/// Configuration for an associated game project
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GameProjectConfig {
    /// Path to the game project directory (contains Cargo.toml)
    pub project_path: Option<PathBuf>,
    /// ID of the level to load when the game starts
    pub starting_level: Option<Uuid>,
    /// Project name (used for Cargo.toml package name)
    pub project_name: String,
    /// Whether to use release mode when building
    pub use_release_build: bool,

    // Code generation settings (disabled by default - opt-in)
    /// Whether to enable automatic code generation on save
    #[serde(default)]
    pub enable_codegen: bool,
    /// Output path for generated code relative to project root (default: "src/generated")
    #[serde(default = "default_codegen_output_path")]
    pub codegen_output_path: String,
    /// Whether to generate entity structs
    #[serde(default = "default_true")]
    pub generate_entities: bool,
    /// Whether to generate stub systems
    #[serde(default = "default_true")]
    pub generate_stubs: bool,
    /// Whether to generate behavior systems based on input profiles
    #[serde(default = "default_true")]
    pub generate_behaviors: bool,
    /// Whether to generate enum definitions
    #[serde(default = "default_true")]
    pub generate_enums: bool,

    /// Custom path to VS Code executable (optional - uses auto-detection if not set)
    #[serde(default)]
    pub vscode_path: Option<String>,
}

fn default_codegen_output_path() -> String {
    "src/generated".to_string()
}

fn default_true() -> bool {
    true
}

/// The entire editor project
#[derive(Debug, Clone, Serialize, Deserialize, Resource)]
pub struct Project {
    pub version: u32,
    #[serde(skip)]
    pub path: Option<PathBuf>,
    #[serde(skip)]
    pub schema_path: Option<PathBuf>,
    pub schema: Schema,
    pub tilesets: Vec<Tileset>,
    pub data: DataStore,
    pub levels: Vec<Level>,
    /// Autotile terrain configuration
    #[serde(default)]
    pub autotile_config: AutotileConfig,
    /// Sprite sheet assets (reusable sprite/animation definitions)
    #[serde(default, alias = "animations")]
    pub sprite_sheets: Vec<SpriteData>,
    /// Dialogue tree assets
    #[serde(default)]
    pub dialogues: Vec<DialogueTree>,
    /// World configuration (layout mode, connections)
    #[serde(default)]
    pub world_config: WorldConfig,
    /// Saved tile stamps (reusable tile arrangements)
    #[serde(default)]
    pub stamps: Vec<TileStamp>,
    /// Associated game project configuration
    #[serde(default)]
    pub game_config: GameProjectConfig,
    /// Entity type component configurations (physics, input, sprite per type)
    #[serde(default)]
    pub entity_type_configs: HashMap<String, EntityTypeConfig>,
    #[serde(skip)]
    pub dirty: bool,

    // Performance indices - O(1) lookups instead of O(n) iter().find()
    #[serde(skip)]
    level_index: HashMap<Uuid, usize>,
    #[serde(skip)]
    tileset_index: HashMap<Uuid, usize>,
    #[serde(skip)]
    sprite_sheet_index: HashMap<Uuid, usize>,
    #[serde(skip)]
    dialogue_index: HashMap<String, usize>,
}

impl Default for Project {
    fn default() -> Self {
        Self {
            version: 1,
            path: None,
            schema_path: None,
            schema: Schema::default(),
            tilesets: Vec::new(),
            data: DataStore::default(),
            levels: Vec::new(),
            autotile_config: AutotileConfig::default(),
            sprite_sheets: Vec::new(),
            dialogues: Vec::new(),
            world_config: WorldConfig::default(),
            stamps: Vec::new(),
            game_config: GameProjectConfig::default(),
            entity_type_configs: HashMap::new(),
            dirty: false,
            level_index: HashMap::new(),
            tileset_index: HashMap::new(),
            sprite_sheet_index: HashMap::new(),
            dialogue_index: HashMap::new(),
        }
    }
}

impl Project {
    pub fn new(schema: Schema) -> Self {
        Self {
            version: 1,
            path: None,
            schema_path: None,
            schema,
            tilesets: Vec::new(),
            data: DataStore::default(),
            levels: Vec::new(),
            autotile_config: AutotileConfig::default(),
            sprite_sheets: Vec::new(),
            dialogues: Vec::new(),
            world_config: WorldConfig::default(),
            stamps: Vec::new(),
            game_config: GameProjectConfig::default(),
            entity_type_configs: HashMap::new(),
            dirty: false,
            level_index: HashMap::new(),
            tileset_index: HashMap::new(),
            sprite_sheet_index: HashMap::new(),
            dialogue_index: HashMap::new(),
        }
    }

    /// Get entity type config by type name
    pub fn get_entity_type_config(&self, type_name: &str) -> Option<&EntityTypeConfig> {
        self.entity_type_configs.get(type_name)
    }

    /// Get mutable entity type config by type name
    pub fn get_entity_type_config_mut(&mut self, type_name: &str) -> Option<&mut EntityTypeConfig> {
        self.dirty = true;
        self.entity_type_configs.get_mut(type_name)
    }

    /// Set entity type config for a type
    pub fn set_entity_type_config(&mut self, type_name: &str, config: EntityTypeConfig) {
        self.entity_type_configs
            .insert(type_name.to_string(), config);
        self.dirty = true;
    }

    /// Remove entity type config for a type
    pub fn remove_entity_type_config(&mut self, type_name: &str) -> Option<EntityTypeConfig> {
        self.dirty = true;
        self.entity_type_configs.remove(type_name)
    }

    /// Ensure a type has an entity type config (creates default if missing)
    pub fn ensure_entity_type_config(&mut self, type_name: &str) -> &mut EntityTypeConfig {
        if !self.entity_type_configs.contains_key(type_name) {
            self.entity_type_configs
                .insert(type_name.to_string(), EntityTypeConfig::default());
            self.dirty = true;
        }
        self.entity_type_configs.get_mut(type_name).unwrap()
    }

    /// Rebuild all lookup indices. Call after loading or bulk modifications.
    pub fn rebuild_indices(&mut self) {
        self.level_index.clear();
        for (idx, level) in self.levels.iter().enumerate() {
            self.level_index.insert(level.id, idx);
        }

        self.tileset_index.clear();
        for (idx, tileset) in self.tilesets.iter().enumerate() {
            self.tileset_index.insert(tileset.id, idx);
        }

        self.sprite_sheet_index.clear();
        for (idx, sprite_sheet) in self.sprite_sheets.iter().enumerate() {
            self.sprite_sheet_index.insert(sprite_sheet.id, idx);
        }

        self.dialogue_index.clear();
        for (idx, dialogue) in self.dialogues.iter().enumerate() {
            self.dialogue_index.insert(dialogue.id.clone(), idx);
        }
    }

    /// Mark project as modified
    pub fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    /// Check if project has unsaved changes
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Get project name (from path or schema)
    pub fn name(&self) -> String {
        self.path
            .as_ref()
            .and_then(|p| p.file_stem())
            .and_then(|s| s.to_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| self.schema.project.name.clone())
    }

    /// Add a new data instance
    pub fn add_data_instance(&mut self, instance: DataInstance) {
        self.data.add(instance);
        self.dirty = true;
    }

    /// Remove a data instance by ID
    pub fn remove_data_instance(&mut self, id: Uuid) -> Option<DataInstance> {
        let result = self.data.remove(id);
        if result.is_some() {
            self.dirty = true;
        }
        result
    }

    /// Get data instance by ID
    pub fn get_data_instance(&self, id: Uuid) -> Option<&DataInstance> {
        self.data.get(id)
    }

    /// Get mutable data instance by ID
    pub fn get_data_instance_mut(&mut self, id: Uuid) -> Option<&mut DataInstance> {
        let result = self.data.get_mut(id);
        if result.is_some() {
            self.dirty = true;
        }
        result
    }

    /// Count entities of a given type across all levels
    pub fn count_entities_of_type(&self, type_name: &str) -> usize {
        self.levels
            .iter()
            .map(|level| {
                level
                    .entities
                    .iter()
                    .filter(|e| e.type_name == type_name)
                    .count()
            })
            .sum()
    }

    /// Add a new level
    pub fn add_level(&mut self, level: Level) {
        let id = level.id;
        let idx = self.levels.len();
        self.levels.push(level);
        self.level_index.insert(id, idx);
        self.dirty = true;
    }

    /// Get level by ID (O(1) lookup)
    pub fn get_level(&self, id: Uuid) -> Option<&Level> {
        self.level_index
            .get(&id)
            .and_then(|&idx| self.levels.get(idx))
    }

    /// Get mutable level by ID (O(1) lookup)
    pub fn get_level_mut(&mut self, id: Uuid) -> Option<&mut Level> {
        self.dirty = true;
        self.level_index
            .get(&id)
            .copied()
            .and_then(|idx| self.levels.get_mut(idx))
    }

    /// Get tileset by ID (O(1) lookup)
    pub fn get_tileset(&self, id: Uuid) -> Option<&Tileset> {
        self.tileset_index
            .get(&id)
            .and_then(|&idx| self.tilesets.get(idx))
    }

    /// Get mutable tileset by ID (O(1) lookup)
    pub fn get_tileset_mut(&mut self, id: Uuid) -> Option<&mut Tileset> {
        self.dirty = true;
        self.tileset_index
            .get(&id)
            .copied()
            .and_then(|idx| self.tilesets.get_mut(idx))
    }

    /// Add a new tileset
    pub fn add_tileset(&mut self, tileset: Tileset) {
        let id = tileset.id;
        let idx = self.tilesets.len();
        self.tilesets.push(tileset);
        self.tileset_index.insert(id, idx);
        self.dirty = true;
    }

    /// Remove a tileset by ID
    pub fn remove_tileset(&mut self, id: Uuid) -> Option<Tileset> {
        if let Some(&idx) = self.tileset_index.get(&id) {
            self.tileset_index.remove(&id);
            let removed = self.tilesets.remove(idx);
            // Rebuild indices after removal (indices shifted)
            self.tileset_index.clear();
            for (i, tileset) in self.tilesets.iter().enumerate() {
                self.tileset_index.insert(tileset.id, i);
            }
            self.dirty = true;
            Some(removed)
        } else {
            None
        }
    }

    /// Duplicate a data instance by ID, returns the new instance's ID
    pub fn duplicate_data_instance(&mut self, id: Uuid) -> Option<Uuid> {
        let original = self.data.get(id)?.clone();
        let mut duplicate = original;
        duplicate.id = Uuid::new_v4();

        // Append " (Copy)" to the name if there's a name property
        if let Some(bevy_map_core::Value::String(name)) = duplicate.properties.get_mut("name") {
            name.push_str(" (Copy)");
        }

        let new_id = duplicate.id;
        self.data.add(duplicate);
        self.dirty = true;
        Some(new_id)
    }

    /// Remove a level by ID
    pub fn remove_level(&mut self, id: Uuid) -> Option<Level> {
        if let Some(&idx) = self.level_index.get(&id) {
            self.level_index.remove(&id);
            let removed = self.levels.remove(idx);
            // Rebuild indices after removal (indices shifted)
            self.level_index.clear();
            for (i, level) in self.levels.iter().enumerate() {
                self.level_index.insert(level.id, i);
            }
            self.dirty = true;
            Some(removed)
        } else {
            None
        }
    }

    /// Duplicate a level by ID, returns the new level's ID
    pub fn duplicate_level(&mut self, id: Uuid) -> Option<Uuid> {
        let original = self.get_level(id)?.clone();
        let mut duplicate = original;
        duplicate.id = Uuid::new_v4();
        duplicate.name = format!("{} (Copy)", duplicate.name);

        // Also assign new IDs to all entities
        for entity in &mut duplicate.entities {
            entity.id = Uuid::new_v4();
        }

        let new_id = duplicate.id;
        let idx = self.levels.len();
        self.levels.push(duplicate);
        self.level_index.insert(new_id, idx);
        self.dirty = true;
        Some(new_id)
    }

    // Sprite sheet methods

    /// Add a new sprite sheet asset
    pub fn add_sprite_sheet(&mut self, sprite_sheet: SpriteData) {
        let id = sprite_sheet.id;
        let idx = self.sprite_sheets.len();
        self.sprite_sheets.push(sprite_sheet);
        self.sprite_sheet_index.insert(id, idx);
        self.dirty = true;
    }

    /// Get a sprite sheet by ID (O(1) lookup)
    pub fn get_sprite_sheet(&self, id: Uuid) -> Option<&SpriteData> {
        self.sprite_sheet_index
            .get(&id)
            .and_then(|&idx| self.sprite_sheets.get(idx))
    }

    /// Get mutable sprite sheet by ID (O(1) lookup)
    pub fn get_sprite_sheet_mut(&mut self, id: Uuid) -> Option<&mut SpriteData> {
        self.dirty = true;
        self.sprite_sheet_index
            .get(&id)
            .copied()
            .and_then(|idx| self.sprite_sheets.get_mut(idx))
    }

    /// Remove a sprite sheet by ID
    pub fn remove_sprite_sheet(&mut self, id: Uuid) -> Option<SpriteData> {
        if let Some(&idx) = self.sprite_sheet_index.get(&id) {
            self.sprite_sheet_index.remove(&id);
            let removed = self.sprite_sheets.remove(idx);
            // Rebuild indices after removal
            self.sprite_sheet_index.clear();
            for (i, ss) in self.sprite_sheets.iter().enumerate() {
                self.sprite_sheet_index.insert(ss.id, i);
            }
            self.dirty = true;
            Some(removed)
        } else {
            None
        }
    }

    // Dialogue methods

    /// Add a new dialogue tree
    pub fn add_dialogue(&mut self, dialogue: DialogueTree) {
        let id = dialogue.id.clone();
        let idx = self.dialogues.len();
        self.dialogues.push(dialogue);
        self.dialogue_index.insert(id, idx);
        self.dirty = true;
    }

    /// Get a dialogue by ID (O(1) lookup)
    pub fn get_dialogue(&self, id: &str) -> Option<&DialogueTree> {
        self.dialogue_index
            .get(id)
            .and_then(|&idx| self.dialogues.get(idx))
    }

    /// Get mutable dialogue by ID (O(1) lookup)
    pub fn get_dialogue_mut(&mut self, id: &str) -> Option<&mut DialogueTree> {
        self.dirty = true;
        self.dialogue_index
            .get(id)
            .copied()
            .and_then(|idx| self.dialogues.get_mut(idx))
    }

    /// Remove a dialogue by ID
    pub fn remove_dialogue(&mut self, id: &str) -> Option<DialogueTree> {
        if let Some(&idx) = self.dialogue_index.get(id) {
            self.dialogue_index.remove(id);
            let removed = self.dialogues.remove(idx);
            // Rebuild indices after removal
            self.dialogue_index.clear();
            for (i, d) in self.dialogues.iter().enumerate() {
                self.dialogue_index.insert(d.id.clone(), i);
            }
            self.dirty = true;
            Some(removed)
        } else {
            None
        }
    }

    /// Validate and clean up orphaned references in the project
    ///
    /// This removes terrain sets that reference non-existent tilesets,
    /// which can happen if a tileset was deleted before cascade delete was implemented.
    pub fn validate_and_cleanup(&mut self) {
        use std::collections::HashSet;

        let valid_tileset_ids: HashSet<Uuid> = self.tilesets.iter().map(|t| t.id).collect();

        // Remove terrain sets that reference non-existent tilesets
        let original_count = self.autotile_config.terrain_sets.len();
        self.autotile_config.terrain_sets.retain(|ts| {
            let exists = valid_tileset_ids.contains(&ts.tileset_id);
            if !exists {
                bevy::log::warn!(
                    "Removing orphaned terrain set '{}' - tileset {} no longer exists",
                    ts.name,
                    ts.tileset_id
                );
            }
            exists
        });

        let removed = original_count - self.autotile_config.terrain_sets.len();
        if removed > 0 {
            bevy::log::info!(
                "Cleaned up {} orphaned terrain set(s) from project",
                removed
            );
            self.dirty = true;
        }
    }
}

/// A data instance (non-placeable thing like an Item, Quest, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataInstance {
    pub id: Uuid,
    pub type_name: String,
    pub properties: HashMap<String, bevy_map_core::Value>,
}

impl DataInstance {
    pub fn new(type_name: String) -> Self {
        Self {
            id: Uuid::new_v4(),
            type_name,
            properties: HashMap::new(),
        }
    }
}

/// Stores all data_type instances (non-placeable things like Items, Quests)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DataStore {
    /// Key: type name (e.g., "Item", "Quest")
    /// Value: list of instances of that type
    pub instances: HashMap<String, Vec<DataInstance>>,
}

impl DataStore {
    pub fn add(&mut self, instance: DataInstance) {
        self.instances
            .entry(instance.type_name.clone())
            .or_default()
            .push(instance);
    }

    pub fn remove(&mut self, id: Uuid) -> Option<DataInstance> {
        for instances in self.instances.values_mut() {
            if let Some(pos) = instances.iter().position(|i| i.id == id) {
                return Some(instances.remove(pos));
            }
        }
        None
    }

    pub fn get(&self, id: Uuid) -> Option<&DataInstance> {
        for instances in self.instances.values() {
            if let Some(instance) = instances.iter().find(|i| i.id == id) {
                return Some(instance);
            }
        }
        None
    }

    pub fn get_mut(&mut self, id: Uuid) -> Option<&mut DataInstance> {
        for instances in self.instances.values_mut() {
            if let Some(instance) = instances.iter_mut().find(|i| i.id == id) {
                return Some(instance);
            }
        }
        None
    }

    pub fn get_by_type(&self, type_name: &str) -> &[DataInstance] {
        self.instances
            .get(type_name)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    pub fn all_instances(&self) -> impl Iterator<Item = &DataInstance> {
        self.instances.values().flatten()
    }
}