Skip to main content

source_vmf/vmf/
metadata.rs

1//! This module provides structures for representing metadata blocks in a VMF file, such as version info, visgroups, and view settings.
2
3use std::collections::HashSet;
4
5use derive_more::{Deref, DerefMut, IntoIterator};
6
7use indexmap::IndexMap;
8#[cfg(feature = "serialization")]
9use serde::{Deserialize, Serialize};
10
11use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
12use crate::utils::{To01String, take_bool, take_parse, take_str};
13use crate::{Extras, VmfBlock, VmfSerializable};
14
15impl_try_from_block!(VersionInfo, VisGroups, VisGroup, ViewSettings);
16
17/// Represents the version info of a VMF file.
18#[derive(Debug, Default, Clone, PartialEq)]
19#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
20pub struct VersionInfo {
21    /// The editor version.
22    pub editor_version: i32,
23    /// The editor build number.
24    pub editor_build: i32,
25    /// The map version.
26    pub map_version: i32,
27    /// The format version.
28    pub format_version: i32,
29    /// Whether the VMF is a prefab.
30    pub prefab: bool,
31    /// Keys and blocks this struct does not model.
32    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
33    pub extra: Extras,
34}
35
36impl FromBlock for VersionInfo {
37    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
38        ctx.enter("versioninfo");
39        let blocks = std::mem::take(&mut block.blocks);
40        let kv = &mut block.key_values;
41        let d = Self::default();
42        let info = Self {
43            editor_version: take_parse(kv, "editorversion", d.editor_version, ctx),
44            editor_build: take_parse(kv, "editorbuild", d.editor_build, ctx),
45            map_version: take_parse(kv, "mapversion", d.map_version, ctx),
46            format_version: take_parse(kv, "formatversion", d.format_version, ctx),
47            prefab: take_bool(kv, "prefab", d.prefab, ctx),
48            extra: Extras {
49                key_values: std::mem::take(kv),
50                blocks,
51            },
52        };
53        ctx.leave();
54        info
55    }
56}
57
58impl From<VersionInfo> for VmfBlock {
59    fn from(val: VersionInfo) -> Self {
60        let mut key_values = IndexMap::new();
61        key_values.insert("editorversion".to_string(), val.editor_version.to_string());
62        key_values.insert("editorbuild".to_string(), val.editor_build.to_string());
63        key_values.insert("mapversion".to_string(), val.map_version.to_string());
64        key_values.insert("formatversion".to_string(), val.format_version.to_string());
65        key_values.insert("prefab".to_string(), val.prefab.to_01_string());
66        key_values.extend(val.extra.key_values);
67
68        VmfBlock {
69            name: "versioninfo".to_string(),
70            key_values,
71            blocks: val.extra.blocks,
72        }
73    }
74}
75
76impl VmfSerializable for VersionInfo {
77    fn to_vmf_string(&self, indent_level: usize) -> String {
78        let indent = "\t".repeat(indent_level);
79        let mut output = String::with_capacity(256);
80
81        output.push_str(&format!("{0}versioninfo\n{0}{{\n", indent));
82        output.push_str(&format!(
83            "{}\t\"editorversion\" \"{}\"\n",
84            indent, self.editor_version
85        ));
86        output.push_str(&format!(
87            "{}\t\"editorbuild\" \"{}\"\n",
88            indent, self.editor_build
89        ));
90        output.push_str(&format!(
91            "{}\t\"mapversion\" \"{}\"\n",
92            indent, self.map_version
93        ));
94        output.push_str(&format!(
95            "{}\t\"formatversion\" \"{}\"\n",
96            indent, self.format_version
97        ));
98        output.push_str(&format!(
99            "{}\t\"prefab\" \"{}\"\n",
100            indent,
101            self.prefab.to_01_string()
102        ));
103        self.extra.write_key_values(&mut output, indent_level + 1);
104        self.extra.write_blocks(&mut output, indent_level + 1);
105
106        output.push_str(&format!("{}}}\n", indent));
107        output
108    }
109}
110
111/// Represents a collection of VisGroups in a VMF file.
112#[derive(Debug, Default, Clone, PartialEq, Deref, DerefMut, IntoIterator)]
113#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
114pub struct VisGroups {
115    /// The list of VisGroups.
116    #[deref]
117    #[deref_mut]
118    #[into_iterator]
119    pub groups: Vec<VisGroup>,
120    /// Keys and blocks this struct does not model.
121    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
122    pub extra: Extras,
123}
124
125/// Recursively finds a VisGroup by its ID within a slice of VisGroups.
126/// Returns None if not found.
127fn find_visgroup_by_id(groups: &[VisGroup], id_to_find: i32) -> Option<&VisGroup> {
128    for group in groups {
129        if group.id == id_to_find {
130            return Some(group);
131        }
132        if let Some(ref children) = group.children {
133            if let Some(found) = find_visgroup_by_id(children, id_to_find) {
134                return Some(found);
135            }
136        }
137    }
138    None
139}
140
141/// Recursively finds a mutable reference to a VisGroup by its ID within a slice of VisGroups.
142/// Returns None if not found.
143fn find_visgroup_by_id_mut(
144    groups: &mut [VisGroup],
145    id_to_find: i32,
146) -> Option<&mut VisGroup> {
147    for group in groups {
148        if group.id == id_to_find {
149            return Some(group);
150        }
151        if let Some(ref mut children) = group.children {
152            if let Some(found) = find_visgroup_by_id_mut(children, id_to_find) {
153                return Some(found);
154            }
155        }
156    }
157    None
158}
159
160/// Recursively finds a VisGroup by its name within a slice of VisGroups.
161/// Returns None if not found.
162fn find_visgroup_by_name<'a>(groups: &'a [VisGroup], name_to_find: &str) -> Option<&'a VisGroup> {
163    for group in groups {
164        if group.name == name_to_find {
165            return Some(group);
166        }
167        if let Some(ref children) = group.children {
168            if let Some(found) = find_visgroup_by_name(children, name_to_find) {
169                return Some(found);
170            }
171        }
172    }
173    None
174}
175
176/// Recursively finds a mutable reference to a VisGroup by its name within a slice of VisGroups.
177/// Returns None if not found.
178fn find_visgroup_by_name_mut<'a>(
179    groups: &'a mut [VisGroup],
180    name_to_find: &str,
181) -> Option<&'a mut VisGroup> {
182    for group in groups {
183        if group.name == name_to_find {
184            return Some(group);
185        }
186        if let Some(ref mut children) = group.children {
187            if let Some(found) = find_visgroup_by_name_mut(children, name_to_find) {
188                return Some(found);
189            }
190        }
191    }
192    None
193}
194
195impl VisGroups {
196    /// Finds a VisGroup by its name recursively within this collection.
197    ///
198    /// # Arguments
199    ///
200    /// * `name` - The exact name of the VisGroup to find.
201    ///
202    /// # Returns
203    ///
204    /// An `Option` containing a reference to the found `VisGroup`, or `None`.
205    pub fn find_by_name(&self, name: &str) -> Option<&VisGroup> {
206        find_visgroup_by_name(&self.groups, name)
207    }
208
209    /// Finds a mutable reference to a VisGroup by its name recursively within this collection.
210    ///
211    /// # Arguments
212    ///
213    /// * `name` - The exact name of the VisGroup to find.
214    ///
215    /// # Returns
216    ///
217    /// An `Option` containing a mutable reference to the found `VisGroup`, or `None`.
218    pub fn find_by_name_mut(&mut self, name: &str) -> Option<&mut VisGroup> {
219        find_visgroup_by_name_mut(&mut self.groups, name)
220    }
221
222    /// Finds a VisGroup by its ID recursively within this collection.
223    ///
224    /// # Arguments
225    ///
226    /// * `id` - The ID of the VisGroup to find.
227    ///
228    /// # Returns
229    ///
230    /// An `Option` containing a reference to the found `VisGroup`, or `None`.
231    pub fn find_by_id(&self, id: i32) -> Option<&VisGroup> {
232        find_visgroup_by_id(&self.groups, id)
233    }
234
235    /// Finds a mutable reference to a VisGroup by its ID recursively within this collection.
236    ///
237    /// # Arguments
238    ///
239    /// * `id` - The ID of the VisGroup to find.
240    ///
241    /// # Returns
242    ///
243    /// An `Option` containing a mutable reference to the found `VisGroup`, or `None`.
244    pub fn find_by_id_mut(&mut self, id: i32) -> Option<&mut VisGroup> {
245        find_visgroup_by_id_mut(&mut self.groups, id)
246    }
247
248    /// Returns an unused VisGroup ID (one higher than the current maximum).
249    pub fn next_id(&self) -> i32 {
250        fn highest(groups: &[VisGroup]) -> i32 {
251            groups.iter().fold(0, |max, group| {
252                max.max(group.id)
253                    .max(group.children.as_deref().map_or(0, highest))
254            })
255        }
256        highest(&self.groups) + 1
257    }
258
259    /// Adds a top-level visgroup and returns its ID.
260    pub fn create(&mut self, name: impl Into<String>) -> i32 {
261        let id = self.next_id();
262        self.groups.push(VisGroup {
263            name: name.into(),
264            id,
265            color: "255 255 255".to_string(),
266            children: None,
267            extra: Extras::default(),
268        });
269        id
270    }
271
272    /// Removes a visgroup and all its children by ID.
273    ///
274    /// Does not update entity or solid memberships; see [`Editor::leave_visgroup`].
275    ///
276    /// [`Editor::leave_visgroup`]: crate::vmf::common::Editor::leave_visgroup
277    pub fn remove_by_id(&mut self, id: i32) -> Option<VisGroup> {
278        fn remove(groups: &mut Vec<VisGroup>, id: i32) -> Option<VisGroup> {
279            if let Some(at) = groups.iter().position(|group| group.id == id) {
280                return Some(groups.remove(at));
281            }
282            for group in groups {
283                let Some(children) = group.children.as_mut() else {
284                    continue;
285                };
286                if let Some(found) = remove(children, id) {
287                    if children.is_empty() {
288                        group.children = None;
289                    }
290                    return Some(found);
291                }
292            }
293            None
294        }
295        remove(&mut self.groups, id)
296    }
297
298    /// Resolves all IDs for a given VisGroup ID, optionally including all descendant IDs.
299    pub fn resolve_ids(&self, group_id: i32, include_children: bool) -> Option<HashSet<i32>> {
300        let start_group = self.find_by_id(group_id)?;
301        let mut ids = HashSet::new();
302        if include_children {
303            start_group.collect_ids(&mut ids);
304        } else {
305            ids.insert(start_group.id);
306        }
307        Some(ids)
308    }
309}
310
311impl FromBlock for VisGroups {
312    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
313        ctx.enter("visgroups");
314        let mut groups = Vec::with_capacity(block.blocks.len());
315        let mut unknown = Vec::new();
316
317        for (index, group) in block.blocks.drain(..).enumerate() {
318            if group.name.eq_ignore_ascii_case("visgroup") {
319                ctx.enter_indexed("visgroup", index);
320                groups.push(VisGroup::from_block(group, ctx));
321                ctx.leave();
322            } else {
323                ctx.warn(format!("unexpected block '{}', kept as-is", group.name));
324                unknown.push(group);
325            }
326        }
327
328        ctx.leave();
329        Self {
330            groups,
331            extra: Extras {
332                key_values: block.key_values,
333                blocks: unknown,
334            },
335        }
336    }
337}
338
339impl From<VisGroups> for VmfBlock {
340    fn from(val: VisGroups) -> Self {
341        let mut visgroups_block = VmfBlock {
342            name: "visgroups".to_string(),
343            key_values: val.extra.key_values,
344            blocks: Vec::with_capacity(val.groups.len() + val.extra.blocks.len()),
345        };
346
347        for group in val.groups {
348            visgroups_block.blocks.push(group.into())
349        }
350        visgroups_block.blocks.extend(val.extra.blocks);
351
352        visgroups_block
353    }
354}
355
356impl VmfSerializable for VisGroups {
357    fn to_vmf_string(&self, indent_level: usize) -> String {
358        let indent = "\t".repeat(indent_level);
359        let mut output = String::with_capacity(128);
360
361        output.push_str(&format!("{0}visgroups\n{0}{{\n", indent));
362        self.extra.write_key_values(&mut output, indent_level + 1);
363
364        for group in &self.groups {
365            output.push_str(&group.to_vmf_string(indent_level));
366        }
367        self.extra.write_blocks(&mut output, indent_level + 1);
368
369        output.push_str(&format!("{}}}\n", indent));
370        output
371    }
372}
373
374/// Represents a VisGroup in a VMF file.
375#[derive(Debug, Default, Clone, PartialEq)]
376#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
377pub struct VisGroup {
378    /// The name of the VisGroup.
379    pub name: String,
380    /// The ID of the VisGroup.
381    pub id: i32,
382    /// The color of the VisGroup in the editor.
383    pub color: String,
384    /// The child VisGroups of this VisGroup, if any.
385    #[cfg_attr(
386        feature = "serialization",
387        serde(default, skip_serializing_if = "Option::is_none")
388    )]
389    pub children: Option<Vec<VisGroup>>,
390    /// Keys and blocks this struct does not model.
391    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
392    pub extra: Extras,
393}
394
395impl VisGroup {
396    /// Recursively collects this group's ID and all its descendants' IDs into a set.
397    pub fn collect_ids(&self, ids: &mut HashSet<i32>) {
398        if !ids.insert(self.id) {
399            return;
400        }
401        if let Some(ref children) = self.children {
402            for child in children {
403                child.collect_ids(ids);
404            }
405        }
406    }
407}
408
409impl FromBlock for VisGroup {
410    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
411        let mut children_vec = Vec::with_capacity(block.blocks.len());
412        let mut unknown = Vec::new();
413
414        for (index, child_block) in block.blocks.drain(..).enumerate() {
415            if child_block.name.eq_ignore_ascii_case("visgroup") {
416                ctx.enter_indexed("visgroup", index);
417                children_vec.push(VisGroup::from_block(child_block, ctx));
418                ctx.leave();
419            } else {
420                ctx.warn(format!("unexpected block '{}', kept as-is", child_block.name));
421                unknown.push(child_block);
422            }
423        }
424
425        let kv = &mut block.key_values;
426        Self {
427            name: take_str(kv, "name", "", ctx),
428            id: take_parse(kv, "visgroupid", 0, ctx),
429            color: take_str(kv, "color", "255 255 255", ctx),
430            children: (!children_vec.is_empty()).then_some(children_vec),
431            extra: Extras {
432                key_values: std::mem::take(kv),
433                blocks: unknown,
434            },
435        }
436    }
437}
438
439impl From<VisGroup> for VmfBlock {
440    fn from(val: VisGroup) -> Self {
441        // Create a block for VisGroup
442        let mut visgroup_block = VmfBlock {
443            name: "visgroup".to_string(),
444            key_values: IndexMap::new(),
445            blocks: Vec::new(),
446        };
447
448        // Adds key-value pairs for VisGroup
449        visgroup_block
450            .key_values
451            .insert("name".to_string(), val.name);
452        visgroup_block
453            .key_values
454            .insert("visgroupid".to_string(), val.id.to_string());
455        visgroup_block
456            .key_values
457            .insert("color".to_string(), val.color);
458        visgroup_block.key_values.extend(val.extra.key_values);
459
460        // If the `VisGroup` has a child element, adds it as nested block
461        if let Some(children) = val.children {
462            for child in children {
463                visgroup_block.blocks.push(child.into());
464            }
465        }
466        visgroup_block.blocks.extend(val.extra.blocks);
467
468        visgroup_block
469    }
470}
471
472impl VmfSerializable for VisGroup {
473    fn to_vmf_string(&self, indent_level: usize) -> String {
474        let indent = "\t".repeat(indent_level);
475        let mut output = String::with_capacity(64);
476
477        output.push_str(&format!("{0}\tvisgroup\n\t{0}{{\n", indent));
478        output.push_str(&format!("{}\t\t\"name\" \"{}\"\n", indent, self.name));
479        output.push_str(&format!("{}\t\t\"visgroupid\" \"{}\"\n", indent, self.id));
480        output.push_str(&format!("{}\t\t\"color\" \"{}\"\n", indent, self.color));
481        self.extra.write_key_values(&mut output, indent_level + 2);
482
483        // If there are child elements, adds them
484        if let Some(ref children) = self.children {
485            for child in children {
486                output.push_str(&child.to_vmf_string(indent_level + 1));
487            }
488        }
489        self.extra.write_blocks(&mut output, indent_level + 2);
490
491        output.push_str(&format!("{}\t}}\n", indent));
492        output
493    }
494}
495
496/// Represents the view settings of a VMF file.
497#[derive(Debug, Clone, PartialEq)]
498#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
499pub struct ViewSettings {
500    /// Whether snapping to the grid is enabled.
501    pub snap_to_grid: bool,
502    /// Whether the grid is shown in the editor.
503    pub show_grid: bool,
504    /// Whether the logical grid is shown in the editor.
505    pub show_logical_grid: bool,
506    /// The grid spacing.
507    pub grid_spacing: u16,
508    /// Whether the 3D grid is shown in the editor.
509    pub show_3d_grid: bool,
510    /// Keys and blocks this struct does not model.
511    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
512    pub extra: Extras,
513}
514
515impl Default for ViewSettings {
516    fn default() -> Self {
517        Self {
518            snap_to_grid: true,
519            show_grid: true,
520            show_logical_grid: false,
521            grid_spacing: 8,
522            show_3d_grid: false,
523            extra: Extras::default(),
524        }
525    }
526}
527
528impl FromBlock for ViewSettings {
529    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
530        ctx.enter("viewsettings");
531        let blocks = std::mem::take(&mut block.blocks);
532        let kv = &mut block.key_values;
533        let d = Self::default();
534
535        let settings = Self {
536            snap_to_grid: take_bool(kv, "bSnapToGrid", d.snap_to_grid, ctx),
537            show_grid: take_bool(kv, "bShowGrid", d.show_grid, ctx),
538            show_logical_grid: take_bool(kv, "bShowLogicalGrid", d.show_logical_grid, ctx),
539            grid_spacing: take_parse(kv, "nGridSpacing", d.grid_spacing, ctx),
540            show_3d_grid: take_bool(kv, "bShow3DGrid", d.show_3d_grid, ctx),
541            extra: Extras {
542                key_values: std::mem::take(kv),
543                blocks,
544            },
545        };
546        ctx.leave();
547        settings
548    }
549}
550
551impl From<ViewSettings> for VmfBlock {
552    fn from(val: ViewSettings) -> Self {
553        let mut key_values = IndexMap::new();
554        key_values.insert("bSnapToGrid".to_string(), val.snap_to_grid.to_01_string());
555        key_values.insert("bShowGrid".to_string(), val.show_grid.to_01_string());
556        key_values.insert(
557            "bShowLogicalGrid".to_string(),
558            val.show_logical_grid.to_01_string(),
559        );
560        key_values.insert("nGridSpacing".to_string(), val.grid_spacing.to_string());
561        key_values.insert("bShow3DGrid".to_string(), val.show_3d_grid.to_01_string());
562        key_values.extend(val.extra.key_values);
563
564        VmfBlock {
565            name: "viewsettings".to_string(),
566            key_values,
567            blocks: val.extra.blocks,
568        }
569    }
570}
571
572impl VmfSerializable for ViewSettings {
573    fn to_vmf_string(&self, indent_level: usize) -> String {
574        let indent = "\t".repeat(indent_level);
575        let mut output = String::with_capacity(64);
576
577        output.push_str(&format!("{0}viewsettings\n{0}{{\n", indent));
578        output.push_str(&format!(
579            "{}\t\"bSnapToGrid\" \"{}\"\n",
580            indent,
581            self.snap_to_grid.to_01_string()
582        ));
583        output.push_str(&format!(
584            "{}\t\"bShowGrid\" \"{}\"\n",
585            indent,
586            self.show_grid.to_01_string()
587        ));
588        output.push_str(&format!(
589            "{}\t\"bShowLogicalGrid\" \"{}\"\n",
590            indent,
591            self.show_logical_grid.to_01_string()
592        ));
593        output.push_str(&format!(
594            "{}\t\"nGridSpacing\" \"{}\"\n",
595            indent, self.grid_spacing
596        ));
597        output.push_str(&format!(
598            "{}\t\"bShow3DGrid\" \"{}\"\n",
599            indent,
600            self.show_3d_grid.to_01_string()
601        ));
602        self.extra.write_key_values(&mut output, indent_level + 1);
603        self.extra.write_blocks(&mut output, indent_level + 1);
604
605        output.push_str(&format!("{}}}\n", indent));
606        output
607    }
608}