source-vmf 0.6.1

A parser for Valve Map Format (VMF) files
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
//! This module provides structures for representing metadata blocks in a VMF file, such as version info, visgroups, and view settings.

use std::collections::HashSet;

use derive_more::{Deref, DerefMut, IntoIterator};

use indexmap::IndexMap;
#[cfg(feature = "serialization")]
use serde::{Deserialize, Serialize};

use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
use crate::utils::{To01String, take_bool, take_parse, take_str};
use crate::{Extras, VmfBlock, VmfSerializable};

impl_try_from_block!(VersionInfo, VisGroups, VisGroup, ViewSettings);

/// Represents the version info of a VMF file.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct VersionInfo {
    /// The editor version.
    pub editor_version: i32,
    /// The editor build number.
    pub editor_build: i32,
    /// The map version.
    pub map_version: i32,
    /// The format version.
    pub format_version: i32,
    /// Whether the VMF is a prefab.
    pub prefab: bool,
    /// Keys and blocks this struct does not model.
    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
    pub extra: Extras,
}

impl FromBlock for VersionInfo {
    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
        ctx.enter("versioninfo");
        let blocks = std::mem::take(&mut block.blocks);
        let kv = &mut block.key_values;
        let d = Self::default();
        let info = Self {
            editor_version: take_parse(kv, "editorversion", d.editor_version, ctx),
            editor_build: take_parse(kv, "editorbuild", d.editor_build, ctx),
            map_version: take_parse(kv, "mapversion", d.map_version, ctx),
            format_version: take_parse(kv, "formatversion", d.format_version, ctx),
            prefab: take_bool(kv, "prefab", d.prefab, ctx),
            extra: Extras {
                key_values: std::mem::take(kv),
                blocks,
            },
        };
        ctx.leave();
        info
    }
}

impl From<VersionInfo> for VmfBlock {
    fn from(val: VersionInfo) -> Self {
        let mut key_values = IndexMap::new();
        key_values.insert("editorversion".to_string(), val.editor_version.to_string());
        key_values.insert("editorbuild".to_string(), val.editor_build.to_string());
        key_values.insert("mapversion".to_string(), val.map_version.to_string());
        key_values.insert("formatversion".to_string(), val.format_version.to_string());
        key_values.insert("prefab".to_string(), val.prefab.to_01_string());
        key_values.extend(val.extra.key_values);

        VmfBlock {
            name: "versioninfo".to_string(),
            key_values,
            blocks: val.extra.blocks,
        }
    }
}

impl VmfSerializable for VersionInfo {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(256);

        output.push_str(&format!("{0}versioninfo\n{0}{{\n", indent));
        output.push_str(&format!(
            "{}\t\"editorversion\" \"{}\"\n",
            indent, self.editor_version
        ));
        output.push_str(&format!(
            "{}\t\"editorbuild\" \"{}\"\n",
            indent, self.editor_build
        ));
        output.push_str(&format!(
            "{}\t\"mapversion\" \"{}\"\n",
            indent, self.map_version
        ));
        output.push_str(&format!(
            "{}\t\"formatversion\" \"{}\"\n",
            indent, self.format_version
        ));
        output.push_str(&format!(
            "{}\t\"prefab\" \"{}\"\n",
            indent,
            self.prefab.to_01_string()
        ));
        self.extra.write_key_values(&mut output, indent_level + 1);
        self.extra.write_blocks(&mut output, indent_level + 1);

        output.push_str(&format!("{}}}\n", indent));
        output
    }
}

/// Represents a collection of VisGroups in a VMF file.
#[derive(Debug, Default, Clone, PartialEq, Deref, DerefMut, IntoIterator)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct VisGroups {
    /// The list of VisGroups.
    #[deref]
    #[deref_mut]
    #[into_iterator]
    pub groups: Vec<VisGroup>,
    /// Keys and blocks this struct does not model.
    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
    pub extra: Extras,
}

/// Recursively finds a VisGroup by its ID within a slice of VisGroups.
/// Returns None if not found.
fn find_visgroup_by_id(groups: &[VisGroup], id_to_find: i32) -> Option<&VisGroup> {
    for group in groups {
        if group.id == id_to_find {
            return Some(group);
        }
        if let Some(ref children) = group.children {
            if let Some(found) = find_visgroup_by_id(children, id_to_find) {
                return Some(found);
            }
        }
    }
    None
}

/// Recursively finds a mutable reference to a VisGroup by its ID within a slice of VisGroups.
/// Returns None if not found.
fn find_visgroup_by_id_mut(
    groups: &mut [VisGroup],
    id_to_find: i32,
) -> Option<&mut VisGroup> {
    for group in groups {
        if group.id == id_to_find {
            return Some(group);
        }
        if let Some(ref mut children) = group.children {
            if let Some(found) = find_visgroup_by_id_mut(children, id_to_find) {
                return Some(found);
            }
        }
    }
    None
}

/// Recursively finds a VisGroup by its name within a slice of VisGroups.
/// Returns None if not found.
fn find_visgroup_by_name<'a>(groups: &'a [VisGroup], name_to_find: &str) -> Option<&'a VisGroup> {
    for group in groups {
        if group.name == name_to_find {
            return Some(group);
        }
        if let Some(ref children) = group.children {
            if let Some(found) = find_visgroup_by_name(children, name_to_find) {
                return Some(found);
            }
        }
    }
    None
}

/// Recursively finds a mutable reference to a VisGroup by its name within a slice of VisGroups.
/// Returns None if not found.
fn find_visgroup_by_name_mut<'a>(
    groups: &'a mut [VisGroup],
    name_to_find: &str,
) -> Option<&'a mut VisGroup> {
    for group in groups {
        if group.name == name_to_find {
            return Some(group);
        }
        if let Some(ref mut children) = group.children {
            if let Some(found) = find_visgroup_by_name_mut(children, name_to_find) {
                return Some(found);
            }
        }
    }
    None
}

impl VisGroups {
    /// Finds a VisGroup by its name recursively within this collection.
    ///
    /// # Arguments
    ///
    /// * `name` - The exact name of the VisGroup to find.
    ///
    /// # Returns
    ///
    /// An `Option` containing a reference to the found `VisGroup`, or `None`.
    pub fn find_by_name(&self, name: &str) -> Option<&VisGroup> {
        find_visgroup_by_name(&self.groups, name)
    }

    /// Finds a mutable reference to a VisGroup by its name recursively within this collection.
    ///
    /// # Arguments
    ///
    /// * `name` - The exact name of the VisGroup to find.
    ///
    /// # Returns
    ///
    /// An `Option` containing a mutable reference to the found `VisGroup`, or `None`.
    pub fn find_by_name_mut(&mut self, name: &str) -> Option<&mut VisGroup> {
        find_visgroup_by_name_mut(&mut self.groups, name)
    }

    /// Finds a VisGroup by its ID recursively within this collection.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the VisGroup to find.
    ///
    /// # Returns
    ///
    /// An `Option` containing a reference to the found `VisGroup`, or `None`.
    pub fn find_by_id(&self, id: i32) -> Option<&VisGroup> {
        find_visgroup_by_id(&self.groups, id)
    }

    /// Finds a mutable reference to a VisGroup by its ID recursively within this collection.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the VisGroup to find.
    ///
    /// # Returns
    ///
    /// An `Option` containing a mutable reference to the found `VisGroup`, or `None`.
    pub fn find_by_id_mut(&mut self, id: i32) -> Option<&mut VisGroup> {
        find_visgroup_by_id_mut(&mut self.groups, id)
    }

    /// Returns an unused VisGroup ID (one higher than the current maximum).
    pub fn next_id(&self) -> i32 {
        fn highest(groups: &[VisGroup]) -> i32 {
            groups.iter().fold(0, |max, group| {
                max.max(group.id)
                    .max(group.children.as_deref().map_or(0, highest))
            })
        }
        highest(&self.groups) + 1
    }

    /// Adds a top-level visgroup and returns its ID.
    pub fn create(&mut self, name: impl Into<String>) -> i32 {
        let id = self.next_id();
        self.groups.push(VisGroup {
            name: name.into(),
            id,
            color: "255 255 255".to_string(),
            children: None,
            extra: Extras::default(),
        });
        id
    }

    /// Removes a visgroup and all its children by ID.
    ///
    /// Does not update entity or solid memberships; see [`Editor::leave_visgroup`].
    ///
    /// [`Editor::leave_visgroup`]: crate::vmf::common::Editor::leave_visgroup
    pub fn remove_by_id(&mut self, id: i32) -> Option<VisGroup> {
        fn remove(groups: &mut Vec<VisGroup>, id: i32) -> Option<VisGroup> {
            if let Some(at) = groups.iter().position(|group| group.id == id) {
                return Some(groups.remove(at));
            }
            for group in groups {
                let Some(children) = group.children.as_mut() else {
                    continue;
                };
                if let Some(found) = remove(children, id) {
                    if children.is_empty() {
                        group.children = None;
                    }
                    return Some(found);
                }
            }
            None
        }
        remove(&mut self.groups, id)
    }

    /// Resolves all IDs for a given VisGroup ID, optionally including all descendant IDs.
    pub fn resolve_ids(&self, group_id: i32, include_children: bool) -> Option<HashSet<i32>> {
        let start_group = self.find_by_id(group_id)?;
        let mut ids = HashSet::new();
        if include_children {
            start_group.collect_ids(&mut ids);
        } else {
            ids.insert(start_group.id);
        }
        Some(ids)
    }
}

impl FromBlock for VisGroups {
    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
        ctx.enter("visgroups");
        let mut groups = Vec::with_capacity(block.blocks.len());
        let mut unknown = Vec::new();

        for (index, group) in block.blocks.drain(..).enumerate() {
            if group.name.eq_ignore_ascii_case("visgroup") {
                ctx.enter_indexed("visgroup", index);
                groups.push(VisGroup::from_block(group, ctx));
                ctx.leave();
            } else {
                ctx.warn(format!("unexpected block '{}', kept as-is", group.name));
                unknown.push(group);
            }
        }

        ctx.leave();
        Self {
            groups,
            extra: Extras {
                key_values: block.key_values,
                blocks: unknown,
            },
        }
    }
}

impl From<VisGroups> for VmfBlock {
    fn from(val: VisGroups) -> Self {
        let mut visgroups_block = VmfBlock {
            name: "visgroups".to_string(),
            key_values: val.extra.key_values,
            blocks: Vec::with_capacity(val.groups.len() + val.extra.blocks.len()),
        };

        for group in val.groups {
            visgroups_block.blocks.push(group.into())
        }
        visgroups_block.blocks.extend(val.extra.blocks);

        visgroups_block
    }
}

impl VmfSerializable for VisGroups {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(128);

        output.push_str(&format!("{0}visgroups\n{0}{{\n", indent));
        self.extra.write_key_values(&mut output, indent_level + 1);

        for group in &self.groups {
            output.push_str(&group.to_vmf_string(indent_level));
        }
        self.extra.write_blocks(&mut output, indent_level + 1);

        output.push_str(&format!("{}}}\n", indent));
        output
    }
}

/// Represents a VisGroup in a VMF file.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct VisGroup {
    /// The name of the VisGroup.
    pub name: String,
    /// The ID of the VisGroup.
    pub id: i32,
    /// The color of the VisGroup in the editor.
    pub color: String,
    /// The child VisGroups of this VisGroup, if any.
    #[cfg_attr(
        feature = "serialization",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub children: Option<Vec<VisGroup>>,
    /// Keys and blocks this struct does not model.
    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
    pub extra: Extras,
}

impl VisGroup {
    /// Recursively collects this group's ID and all its descendants' IDs into a set.
    pub fn collect_ids(&self, ids: &mut HashSet<i32>) {
        if !ids.insert(self.id) {
            return;
        }
        if let Some(ref children) = self.children {
            for child in children {
                child.collect_ids(ids);
            }
        }
    }
}

impl FromBlock for VisGroup {
    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
        let mut children_vec = Vec::with_capacity(block.blocks.len());
        let mut unknown = Vec::new();

        for (index, child_block) in block.blocks.drain(..).enumerate() {
            if child_block.name.eq_ignore_ascii_case("visgroup") {
                ctx.enter_indexed("visgroup", index);
                children_vec.push(VisGroup::from_block(child_block, ctx));
                ctx.leave();
            } else {
                ctx.warn(format!("unexpected block '{}', kept as-is", child_block.name));
                unknown.push(child_block);
            }
        }

        let kv = &mut block.key_values;
        Self {
            name: take_str(kv, "name", "", ctx),
            id: take_parse(kv, "visgroupid", 0, ctx),
            color: take_str(kv, "color", "255 255 255", ctx),
            children: (!children_vec.is_empty()).then_some(children_vec),
            extra: Extras {
                key_values: std::mem::take(kv),
                blocks: unknown,
            },
        }
    }
}

impl From<VisGroup> for VmfBlock {
    fn from(val: VisGroup) -> Self {
        // Create a block for VisGroup
        let mut visgroup_block = VmfBlock {
            name: "visgroup".to_string(),
            key_values: IndexMap::new(),
            blocks: Vec::new(),
        };

        // Adds key-value pairs for VisGroup
        visgroup_block
            .key_values
            .insert("name".to_string(), val.name);
        visgroup_block
            .key_values
            .insert("visgroupid".to_string(), val.id.to_string());
        visgroup_block
            .key_values
            .insert("color".to_string(), val.color);
        visgroup_block.key_values.extend(val.extra.key_values);

        // If the `VisGroup` has a child element, adds it as nested block
        if let Some(children) = val.children {
            for child in children {
                visgroup_block.blocks.push(child.into());
            }
        }
        visgroup_block.blocks.extend(val.extra.blocks);

        visgroup_block
    }
}

impl VmfSerializable for VisGroup {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(64);

        output.push_str(&format!("{0}\tvisgroup\n\t{0}{{\n", indent));
        output.push_str(&format!("{}\t\t\"name\" \"{}\"\n", indent, self.name));
        output.push_str(&format!("{}\t\t\"visgroupid\" \"{}\"\n", indent, self.id));
        output.push_str(&format!("{}\t\t\"color\" \"{}\"\n", indent, self.color));
        self.extra.write_key_values(&mut output, indent_level + 2);

        // If there are child elements, adds them
        if let Some(ref children) = self.children {
            for child in children {
                output.push_str(&child.to_vmf_string(indent_level + 1));
            }
        }
        self.extra.write_blocks(&mut output, indent_level + 2);

        output.push_str(&format!("{}\t}}\n", indent));
        output
    }
}

/// Represents the view settings of a VMF file.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct ViewSettings {
    /// Whether snapping to the grid is enabled.
    pub snap_to_grid: bool,
    /// Whether the grid is shown in the editor.
    pub show_grid: bool,
    /// Whether the logical grid is shown in the editor.
    pub show_logical_grid: bool,
    /// The grid spacing.
    pub grid_spacing: u16,
    /// Whether the 3D grid is shown in the editor.
    pub show_3d_grid: bool,
    /// Keys and blocks this struct does not model.
    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
    pub extra: Extras,
}

impl Default for ViewSettings {
    fn default() -> Self {
        Self {
            snap_to_grid: true,
            show_grid: true,
            show_logical_grid: false,
            grid_spacing: 8,
            show_3d_grid: false,
            extra: Extras::default(),
        }
    }
}

impl FromBlock for ViewSettings {
    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
        ctx.enter("viewsettings");
        let blocks = std::mem::take(&mut block.blocks);
        let kv = &mut block.key_values;
        let d = Self::default();

        let settings = Self {
            snap_to_grid: take_bool(kv, "bSnapToGrid", d.snap_to_grid, ctx),
            show_grid: take_bool(kv, "bShowGrid", d.show_grid, ctx),
            show_logical_grid: take_bool(kv, "bShowLogicalGrid", d.show_logical_grid, ctx),
            grid_spacing: take_parse(kv, "nGridSpacing", d.grid_spacing, ctx),
            show_3d_grid: take_bool(kv, "bShow3DGrid", d.show_3d_grid, ctx),
            extra: Extras {
                key_values: std::mem::take(kv),
                blocks,
            },
        };
        ctx.leave();
        settings
    }
}

impl From<ViewSettings> for VmfBlock {
    fn from(val: ViewSettings) -> Self {
        let mut key_values = IndexMap::new();
        key_values.insert("bSnapToGrid".to_string(), val.snap_to_grid.to_01_string());
        key_values.insert("bShowGrid".to_string(), val.show_grid.to_01_string());
        key_values.insert(
            "bShowLogicalGrid".to_string(),
            val.show_logical_grid.to_01_string(),
        );
        key_values.insert("nGridSpacing".to_string(), val.grid_spacing.to_string());
        key_values.insert("bShow3DGrid".to_string(), val.show_3d_grid.to_01_string());
        key_values.extend(val.extra.key_values);

        VmfBlock {
            name: "viewsettings".to_string(),
            key_values,
            blocks: val.extra.blocks,
        }
    }
}

impl VmfSerializable for ViewSettings {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(64);

        output.push_str(&format!("{0}viewsettings\n{0}{{\n", indent));
        output.push_str(&format!(
            "{}\t\"bSnapToGrid\" \"{}\"\n",
            indent,
            self.snap_to_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"bShowGrid\" \"{}\"\n",
            indent,
            self.show_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"bShowLogicalGrid\" \"{}\"\n",
            indent,
            self.show_logical_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"nGridSpacing\" \"{}\"\n",
            indent, self.grid_spacing
        ));
        output.push_str(&format!(
            "{}\t\"bShow3DGrid\" \"{}\"\n",
            indent,
            self.show_3d_grid.to_01_string()
        ));
        self.extra.write_key_values(&mut output, indent_level + 1);
        self.extra.write_blocks(&mut output, indent_level + 1);

        output.push_str(&format!("{}}}\n", indent));
        output
    }
}