Skip to main content

source_vmf/vmf/
world.rs

1//! This module provides structures for representing the world block in a VMF file, which contains world geometry, hidden entities, and groups.
2
3use indexmap::IndexMap;
4#[cfg(feature = "serialization")]
5use serde::{Deserialize, Serialize};
6
7use super::common::Editor;
8use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
9use crate::utils::{To01String, take_bool, take_opt_parse, take_parse, take_str};
10use crate::{Extras, VmfBlock, VmfSerializable};
11use std::mem;
12
13impl_try_from_block!(World, Solid, Side, DispInfo, DispRows, Group);
14
15/// Represents the world block in a VMF file.
16#[derive(Debug, Default, Clone, PartialEq)]
17#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
18pub struct World {
19    /// The key-value pairs associated with the world.
20    pub key_values: IndexMap<String, String>,
21    /// The list of solids that make up the world geometry.
22    pub solids: Vec<Solid>,
23    /// The list of hidden solids in the world.
24    pub hidden: Vec<Solid>,
25    /// The list of groups present in the world.
26    #[cfg_attr(
27        feature = "serialization",
28        serde(default, skip_serializing_if = "Vec::is_empty")
29    )]
30    pub groups: Vec<Group>,
31    /// Blocks this struct does not model. Unknown *keys* land in `key_values`.
32    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
33    pub extra: Extras,
34}
35
36impl World {
37    /// Iterates over all solids in the world, visible and hidden.
38    pub fn iter_solids(&self) -> impl Iterator<Item = &Solid> {
39        self.solids.iter().chain(self.hidden.iter())
40    }
41
42    /// Mutably iterates over all solids in the world, visible and hidden.
43    pub fn iter_solids_mut(&mut self) -> impl Iterator<Item = &mut Solid> {
44        self.solids.iter_mut().chain(self.hidden.iter_mut())
45    }
46}
47
48impl FromBlock for World {
49    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
50        ctx.enter("world");
51        let estimated_solids = block.blocks.len().saturating_sub(1);
52        let mut world = World {
53            key_values: std::mem::take(&mut block.key_values),
54            solids: Vec::with_capacity(estimated_solids),
55            hidden: Vec::with_capacity(16),
56            groups: Vec::new(),
57            extra: Extras::default(),
58        };
59
60        for mut inner_block in block.blocks.drain(..) {
61            let name = inner_block.name.clone();
62            if name.eq_ignore_ascii_case("solid") {
63                ctx.enter_indexed("solid", world.solids.len());
64                world.solids.push(Solid::from_block(inner_block, ctx));
65                ctx.leave();
66            } else if name.eq_ignore_ascii_case("group") {
67                ctx.enter_indexed("group", world.groups.len());
68                world.groups.push(Group::from_block(inner_block, ctx));
69                ctx.leave();
70            } else if name.eq_ignore_ascii_case("hidden") {
71                // Read all solids inside the hidden wrapper.
72                for hidden_block in mem::take(&mut inner_block.blocks) {
73                    ctx.enter_indexed("hidden", world.hidden.len());
74                    world.hidden.push(Solid::from_block(hidden_block, ctx));
75                    ctx.leave();
76                }
77            } else {
78                ctx.warn(format!("unexpected block '{}', kept as-is", name));
79                world.extra.blocks.push(inner_block);
80            }
81        }
82
83        ctx.leave();
84        world
85    }
86}
87
88impl From<World> for VmfBlock {
89    fn from(val: World) -> Self {
90        let mut blocks = Vec::new();
91
92        // Add solids
93        for solid in val.solids {
94            blocks.push(solid.into());
95        }
96
97        // Add hidden solids
98        for hidden_solid in val.hidden {
99            blocks.push(VmfBlock {
100                name: "hidden".to_string(),
101                key_values: IndexMap::new(),
102                blocks: vec![hidden_solid.into()],
103            });
104        }
105
106        // Add groups
107        for group in val.groups {
108            blocks.push(group.into());
109        }
110        blocks.extend(val.extra.blocks);
111
112        let mut key_values = val.key_values;
113        key_values.extend(val.extra.key_values);
114
115        VmfBlock {
116            name: "world".to_string(),
117            key_values,
118            blocks,
119        }
120    }
121}
122
123impl VmfSerializable for World {
124    fn to_vmf_string(&self, indent_level: usize) -> String {
125        let indent = "\t".repeat(indent_level);
126        let mut output = String::with_capacity(2048);
127
128        output.push_str(&format!("{0}world\n{0}{{\n", indent));
129
130        // Adds key_values of the main block
131        for (key, value) in &self.key_values {
132            crate::write_key_value(&mut output, &format!("{indent}\t"), key, value);
133        }
134
135        // Solids Block
136        if !self.solids.is_empty() {
137            for solid in &self.solids {
138                output.push_str(&solid.to_vmf_string(indent_level + 1));
139            }
140        }
141
142        // Hidden solids (one wrapper per solid)
143        for solid in &self.hidden {
144            output.push_str(&format!("{0}\thidden\n{0}\t{{\n", indent));
145            output.push_str(&solid.to_vmf_string(indent_level + 2));
146            output.push_str(&format!("{}\t}}\n", indent));
147        }
148
149        // Group Blocks
150        for group in &self.groups {
151            output.push_str(&group.to_vmf_string(indent_level + 1));
152        }
153        self.extra.write_key_values(&mut output, indent_level + 1);
154        self.extra.write_blocks(&mut output, indent_level + 1);
155
156        output.push_str(&format!("{}}}\n", indent));
157        output
158    }
159}
160
161/// Represents a solid object in the VMF world.
162#[derive(Debug, Default, Clone, PartialEq)]
163#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
164pub struct Solid {
165    /// The unique ID of the solid.
166    pub id: u64,
167    /// The sides of the solid.
168    pub sides: Vec<Side>,
169    /// The editor data for the solid.
170    pub editor: Editor,
171    /// Keys and blocks this struct does not model.
172    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
173    pub extra: Extras,
174}
175
176impl FromBlock for Solid {
177    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
178        let blocks = std::mem::take(&mut block.blocks);
179        let mut solid = Solid {
180            id: take_parse(&mut block.key_values, "id", 0, ctx),
181            sides: Vec::with_capacity(blocks.len()),
182            ..Default::default()
183        };
184
185        for inner_block in blocks {
186            let name = inner_block.name.clone();
187            if name.eq_ignore_ascii_case("side") {
188                ctx.enter_indexed("side", solid.sides.len());
189                solid.sides.push(Side::from_block(inner_block, ctx));
190                ctx.leave();
191            } else if name.eq_ignore_ascii_case("editor") {
192                ctx.enter("editor");
193                solid.editor = Editor::from_block(inner_block, ctx);
194                ctx.leave();
195            } else {
196                ctx.warn(format!("unexpected block '{}', kept as-is", name));
197                solid.extra.blocks.push(inner_block);
198            }
199        }
200
201        solid.extra.key_values = block.key_values;
202        solid
203    }
204}
205
206impl From<Solid> for VmfBlock {
207    fn from(val: Solid) -> Self {
208        let mut blocks = Vec::new();
209
210        // Adds sides
211        for side in val.sides {
212            blocks.push(side.into());
213        }
214
215        // Adds editor
216        blocks.push(val.editor.into());
217        blocks.extend(val.extra.blocks);
218
219        VmfBlock {
220            name: "solid".to_string(),
221            key_values: {
222                let mut key_values = IndexMap::new();
223                key_values.insert("id".to_string(), val.id.to_string());
224                key_values.extend(val.extra.key_values);
225                key_values
226            },
227            blocks,
228        }
229    }
230}
231
232impl VmfSerializable for Solid {
233    fn to_vmf_string(&self, indent_level: usize) -> String {
234        let indent = "\t".repeat(indent_level);
235        let mut output = String::with_capacity(256);
236
237        // Start of solid block
238        output.push_str(&format!("{0}solid\n{0}{{\n", indent));
239        output.push_str(&format!("{}\t\"id\" \"{}\"\n", indent, self.id));
240        self.extra.write_key_values(&mut output, indent_level + 1);
241
242        // Sides
243        for side in &self.sides {
244            output.push_str(&side.to_vmf_string(indent_level + 1));
245        }
246
247        // Editor block
248        output.push_str(&self.editor.to_vmf_string(indent_level + 1));
249        self.extra.write_blocks(&mut output, indent_level + 1);
250
251        output.push_str(&format!("{}}}\n", indent));
252
253        output
254    }
255}
256
257/// Represents a side of a solid object in the VMF world.
258#[derive(Debug, Default, Clone, PartialEq)]
259#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
260pub struct Side {
261    /// The unique ID of the side.
262    pub id: u32,
263    /// The plane equation of the side.
264    pub plane: String,
265    /// The material used on the side.
266    pub material: String,
267    /// The U axis of the texture coordinates.
268    pub u_axis: String,
269    /// The V axis of the texture coordinates.
270    pub v_axis: String,
271    /// The rotation of the texture.
272    #[cfg_attr(
273        feature = "serialization",
274        serde(default, skip_serializing_if = "Option::is_none")
275    )]
276    pub rotation: Option<f32>,
277    /// The scale of the lightmap.
278    pub lightmap_scale: u16,
279    /// The smoothing groups that this side belongs to.
280    pub smoothing_groups: i32,
281    /// flags
282    #[cfg_attr(
283        feature = "serialization",
284        serde(default, skip_serializing_if = "Option::is_none")
285    )]
286    pub flags: Option<u32>,
287    /// The displacement info of the side, if any.
288    #[cfg_attr(
289        feature = "serialization",
290        serde(default, skip_serializing_if = "Option::is_none")
291    )]
292    pub dispinfo: Option<DispInfo>,
293    /// Keys and blocks this struct does not model.
294    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
295    pub extra: Extras,
296}
297
298impl FromBlock for Side {
299    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
300        let mut dispinfo = None;
301        let mut unknown = Vec::new();
302
303        for inner_block in block.blocks.drain(..) {
304            if inner_block.name.eq_ignore_ascii_case("dispinfo") {
305                ctx.enter("dispinfo");
306                dispinfo = Some(DispInfo::from_block(inner_block, ctx));
307                ctx.leave();
308            } else {
309                ctx.warn(format!(
310                    "unexpected block '{}', kept as-is",
311                    inner_block.name
312                ));
313                unknown.push(inner_block);
314            }
315        }
316
317        let kv = &mut block.key_values;
318
319        let side = Side {
320            id: take_parse(kv, "id", 0, ctx),
321            plane: take_str(kv, "plane", "(0 0 0) (0 0 0) (0 0 0)", ctx),
322            material: take_str(kv, "material", "TOOLS/TOOLSNODRAW", ctx),
323            u_axis: take_str(kv, "uaxis", "[1 0 0 0] 0.25", ctx),
324            v_axis: take_str(kv, "vaxis", "[0 -1 0 0] 0.25", ctx),
325            rotation: take_opt_parse::<f32>(kv, "rotation", ctx),
326            lightmap_scale: take_opt_parse::<u16>(kv, "lightmapscale", ctx).unwrap_or(16),
327            smoothing_groups: take_opt_parse::<i32>(kv, "smoothing_groups", ctx).unwrap_or(0),
328            flags: take_opt_parse::<u32>(kv, "flags", ctx),
329            dispinfo,
330            extra: Extras::default(),
331        };
332
333        Side {
334            extra: Extras {
335                key_values: std::mem::take(kv),
336                blocks: unknown,
337            },
338            ..side
339        }
340    }
341}
342
343impl From<Side> for VmfBlock {
344    fn from(val: Side) -> Self {
345        let mut key_values = IndexMap::new();
346        key_values.insert("id".to_string(), val.id.to_string());
347        key_values.insert("plane".to_string(), val.plane);
348        key_values.insert("material".to_string(), val.material);
349        key_values.insert("uaxis".to_string(), val.u_axis);
350        key_values.insert("vaxis".to_string(), val.v_axis);
351        key_values.insert("lightmapscale".to_string(), val.lightmap_scale.to_string());
352        key_values.insert(
353            "smoothing_groups".to_string(),
354            val.smoothing_groups.to_string(),
355        );
356
357        if let Some(rotation) = val.rotation {
358            key_values.insert("rotation".to_string(), rotation.to_string());
359        }
360        if let Some(flags) = val.flags {
361            key_values.insert("flags".to_string(), flags.to_string());
362        }
363        key_values.extend(val.extra.key_values);
364
365        let mut blocks = Vec::new();
366        if let Some(dispinfo) = val.dispinfo {
367            blocks.push(dispinfo.into());
368        }
369        blocks.extend(val.extra.blocks);
370
371        VmfBlock {
372            name: "side".to_string(),
373            key_values,
374            blocks,
375        }
376    }
377}
378
379impl VmfSerializable for Side {
380    fn to_vmf_string(&self, indent_level: usize) -> String {
381        let indent = "\t".repeat(indent_level);
382        let mut output = String::with_capacity(256);
383
384        // Start of Side block
385        output.push_str(&format!("{0}side\n{0}{{\n", indent));
386
387        // Writes all key-value pairs with appropriate indentation
388        output.push_str(&format!("{}\t\"id\" \"{}\"\n", indent, self.id));
389        output.push_str(&format!("{}\t\"plane\" \"{}\"\n", indent, self.plane));
390        output.push_str(&format!("{}\t\"material\" \"{}\"\n", indent, self.material));
391        output.push_str(&format!("{}\t\"uaxis\" \"{}\"\n", indent, self.u_axis));
392        output.push_str(&format!("{}\t\"vaxis\" \"{}\"\n", indent, self.v_axis));
393
394        if let Some(rotation) = self.rotation {
395            output.push_str(&format!("{}\t\"rotation\" \"{}\"\n", indent, rotation));
396        }
397
398        output.push_str(&format!(
399            "{}\t\"lightmapscale\" \"{}\"\n",
400            indent, self.lightmap_scale
401        ));
402        output.push_str(&format!(
403            "{}\t\"smoothing_groups\" \"{}\"\n",
404            indent, self.smoothing_groups
405        ));
406
407        // Adds the flag if it exists
408        if let Some(flags) = self.flags {
409            output.push_str(&format!("{}\t\"flags\" \"{}\"\n", indent, flags));
410        }
411        self.extra.write_key_values(&mut output, indent_level + 1);
412
413        if let Some(dispinfo) = &self.dispinfo {
414            output.push_str(&dispinfo.to_vmf_string(indent_level + 1));
415        }
416        self.extra.write_blocks(&mut output, indent_level + 1);
417
418        // End of Side block
419        output.push_str(&format!("{0}}}\n", indent));
420
421        output
422    }
423}
424
425/// Finds a block by name (case-insensitively) and removes it from the vector.
426#[inline]
427fn take_block(blocks: &mut Vec<VmfBlock>, name: &str) -> Option<VmfBlock> {
428    let index = blocks.iter().position(|b| b.name.eq_ignore_ascii_case(name))?;
429    Some(blocks.remove(index))
430}
431
432/// Takes a named rows block, or warns and yields an empty one.
433fn take_rows(blocks: &mut Vec<VmfBlock>, name: &str, ctx: &mut ParseCtx) -> DispRows {
434    match take_block(blocks, name) {
435        Some(block) => {
436            ctx.enter(name);
437            let rows = DispRows::from_block(block, ctx);
438            ctx.leave();
439            rows
440        }
441        None => {
442            ctx.warn(format!("missing '{}' block, using an empty one", name));
443            DispRows::default()
444        }
445    }
446}
447
448/// Represents the displacement information for a side.
449#[derive(Debug, Default, Clone, PartialEq)]
450#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
451pub struct DispInfo {
452    /// The power of the displacement map (2, 3, or 4).
453    pub power: u8,
454    /// The starting position of the displacement.
455    pub start_position: String,
456    /// Flags for the displacement.
457    #[cfg_attr(
458        feature = "serialization",
459        serde(default, skip_serializing_if = "Option::is_none")
460    )]
461    pub flags: Option<u32>,
462    /// The elevation of the displacement.
463    pub elevation: f32,
464    /// Whether the displacement is subdivided.
465    pub subdiv: bool,
466    /// The normals for each vertex in the displacement.
467    pub normals: DispRows,
468    /// The distances for each vertex in the displacement.
469    pub distances: DispRows,
470    /// The offsets for each vertex in the displacement.
471    pub offsets: DispRows,
472    /// The offset normals for each vertex in the displacement.
473    pub offset_normals: DispRows,
474    /// The alpha values for each vertex in the displacement.
475    pub alphas: DispRows,
476    /// The triangle tags for the displacement.
477    pub triangle_tags: DispRows,
478    /// The allowed vertices for the displacement.
479    pub allowed_verts: IndexMap<String, Vec<i32>>,
480    /// Keys and blocks this struct does not model.
481    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
482    pub extra: Extras,
483}
484
485impl FromBlock for DispInfo {
486    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
487        let normals = take_rows(&mut block.blocks, "normals", ctx);
488        let distances = take_rows(&mut block.blocks, "distances", ctx);
489        let alphas = take_rows(&mut block.blocks, "alphas", ctx);
490        let triangle_tags = take_rows(&mut block.blocks, "triangle_tags", ctx);
491
492        let allowed_verts = match take_block(&mut block.blocks, "allowed_verts") {
493            Some(b) => DispInfo::parse_allowed_verts(b, ctx),
494            None => IndexMap::new(),
495        };
496
497        let offsets = take_block(&mut block.blocks, "offsets")
498            .map_or_else(DispRows::default, |b| DispRows::from_block(b, ctx));
499        let offset_normals = take_block(&mut block.blocks, "offset_normals")
500            .map_or_else(DispRows::default, |b| DispRows::from_block(b, ctx));
501
502        let unknown = std::mem::take(&mut block.blocks);
503        for leftover in &unknown {
504            ctx.warn(format!("unexpected block '{}', kept as-is", leftover.name));
505        }
506
507        let kv = &mut block.key_values;
508        DispInfo {
509            power: take_parse(kv, "power", 3, ctx),
510            start_position: take_str(kv, "startposition", "[0 0 0]", ctx),
511            flags: take_opt_parse::<u32>(kv, "flags", ctx),
512            elevation: take_parse(kv, "elevation", 0.0, ctx),
513            subdiv: take_bool(kv, "subdiv", false, ctx),
514            normals,
515            distances,
516            offsets,
517            offset_normals,
518            alphas,
519            triangle_tags,
520            allowed_verts,
521            extra: Extras {
522                key_values: std::mem::take(kv),
523                blocks: unknown,
524            },
525        }
526    }
527}
528
529impl From<DispInfo> for VmfBlock {
530    fn from(val: DispInfo) -> Self {
531        let blocks = vec![
532            val.normals.into_vmf_block("normals"),
533            val.distances.into_vmf_block("distances"),
534            val.offsets.into_vmf_block("offsets"),
535            val.offset_normals.into_vmf_block("offset_normals"),
536            val.alphas.into_vmf_block("alphas"),
537            val.triangle_tags.into_vmf_block("triangle_tags"),
538            DispInfo::allowed_verts_into_vmf_block(val.allowed_verts),
539        ];
540
541        let mut key_values = IndexMap::new();
542        key_values.insert("power".to_string(), val.power.to_string());
543        key_values.insert("startposition".to_string(), val.start_position);
544        key_values.insert("elevation".to_string(), val.elevation.to_string());
545        key_values.insert("subdiv".to_string(), val.subdiv.to_01_string());
546
547        if let Some(flags) = val.flags {
548            key_values.insert("flags".to_string(), flags.to_string());
549        }
550        key_values.extend(val.extra.key_values);
551
552        let mut blocks = blocks;
553        blocks.extend(val.extra.blocks);
554
555        VmfBlock {
556            name: "dispinfo".to_string(),
557            key_values,
558            blocks,
559        }
560    }
561}
562
563impl VmfSerializable for DispInfo {
564    fn to_vmf_string(&self, indent_level: usize) -> String {
565        let indent = "\t".repeat(indent_level);
566        let mut output = String::with_capacity(256);
567
568        output.push_str(&format!("{}dispinfo\n", indent));
569        output.push_str(&format!("{}{{\n", indent));
570        output.push_str(&format!("{}\t\"power\" \"{}\"\n", indent, self.power));
571        output.push_str(&format!(
572            "{}\t\"startposition\" \"{}\"\n",
573            indent, self.start_position
574        ));
575
576        // Adds the flag if it exists
577        if let Some(flags) = self.flags {
578            output.push_str(&format!("{}\t\"flags\" \"{}\"\n", indent, flags));
579        }
580
581        output.push_str(&format!(
582            "{}\t\"elevation\" \"{}\"\n",
583            indent, self.elevation
584        ));
585        output.push_str(&format!(
586            "{}\t\"subdiv\" \"{}\"\n",
587            indent,
588            self.subdiv.to_01_string()
589        ));
590        self.extra.write_key_values(&mut output, indent_level + 1);
591        output.push_str(&self.normals.to_vmf_string(indent_level + 1, "normals"));
592        output.push_str(&self.distances.to_vmf_string(indent_level + 1, "distances"));
593        output.push_str(&self.offsets.to_vmf_string(indent_level + 1, "offsets"));
594        output.push_str(
595            &self
596                .offset_normals
597                .to_vmf_string(indent_level + 1, "offset_normals"),
598        );
599        output.push_str(&self.alphas.to_vmf_string(indent_level + 1, "alphas"));
600        output.push_str(
601            &self
602                .triangle_tags
603                .to_vmf_string(indent_level + 1, "triangle_tags"),
604        );
605        output.push_str(&Self::allowed_verts_to_vmf_string(
606            &self.allowed_verts,
607            indent_level + 1,
608        ));
609        self.extra.write_blocks(&mut output, indent_level + 1);
610        output.push_str(&format!("{}}}\n", indent));
611
612        output
613    }
614}
615
616impl DispInfo {
617    /// Parses the allowed vertices from a `VmfBlock`.
618    ///
619    /// # Arguments
620    ///
621    /// * `block` - The `VmfBlock` containing the allowed vertices data.
622    ///
623    /// # Returns
624    ///
625    /// A `Result` containing an `IndexMap` of allowed vertices, or a `VmfError` if parsing fails.
626    fn parse_allowed_verts(block: VmfBlock, ctx: &mut ParseCtx) -> IndexMap<String, Vec<i32>> {
627        let mut allowed_verts = IndexMap::new();
628        for (key, value) in block.key_values.into_iter() {
629            let verts: Vec<i32> = value
630                .split_whitespace()
631                .filter_map(|s| match s.parse::<i32>() {
632                    Ok(v) => Some(v),
633                    Err(_) => {
634                        ctx.warn(format!("allowed_verts/{}: skipping '{}'", key, s));
635                        None
636                    }
637                })
638                .collect();
639            allowed_verts.insert(key, verts);
640        }
641        allowed_verts
642    }
643
644    /// Converts the allowed vertices data into a `VmfBlock`.
645    ///
646    /// # Arguments
647    ///
648    /// * `allowed_verts` - The `IndexMap` containing the allowed vertices data.
649    ///
650    /// # Returns
651    ///
652    /// A `VmfBlock` representing the allowed vertices data.
653    fn allowed_verts_into_vmf_block(allowed_verts: IndexMap<String, Vec<i32>>) -> VmfBlock {
654        let mut key_values = IndexMap::new();
655        for (key, values) in allowed_verts {
656            key_values.insert(
657                key,
658                values
659                    .iter()
660                    .map(|v| v.to_string())
661                    .collect::<Vec<String>>()
662                    .join(" "),
663            );
664        }
665
666        VmfBlock {
667            name: "allowed_verts".to_string(),
668            key_values,
669            blocks: Vec::new(),
670        }
671    }
672
673    /// Converts the allowed vertices data into a string representation.
674    ///
675    /// # Arguments
676    ///
677    /// * `allowed_verts` - A reference to an `IndexMap` containing the allowed vertices data.
678    /// * `indent_level` - The indentation level for formatting.
679    ///
680    /// # Returns
681    ///
682    /// A string representation of the allowed vertices data.
683    fn allowed_verts_to_vmf_string(
684        allowed_verts: &IndexMap<String, Vec<i32>>,
685        indent_level: usize,
686    ) -> String {
687        let indent = "\t".repeat(indent_level);
688        let mut output = String::new();
689
690        output.push_str(&format!("{}allowed_verts\n", indent));
691        output.push_str(&format!("{}{{\n", indent));
692        for (key, values) in allowed_verts {
693            output.push_str(&format!(
694                "{}\t\"{}\" \"{}\"\n",
695                indent,
696                key,
697                values
698                    .iter()
699                    .map(|v| v.to_string())
700                    .collect::<Vec<String>>()
701                    .join(" ")
702            ));
703        }
704        output.push_str(&format!("{}}}\n", indent));
705
706        output
707    }
708}
709
710/// Represents rows of data for displacement information, such as normals, distances, offsets, etc.
711#[derive(Debug, Default, Clone, PartialEq, Eq)]
712#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
713pub struct DispRows {
714    /// The rows of data, each represented as a string.
715    pub rows: Vec<String>,
716}
717
718impl FromBlock for DispRows {
719    fn from_block(block: VmfBlock, ctx: &mut ParseCtx) -> Self {
720        let mut rows = Vec::with_capacity(block.key_values.len());
721        for (key, value) in block.key_values {
722            let stripped = key
723                .get(..3)
724                .filter(|p| p.eq_ignore_ascii_case("row"))
725                .map(|_| &key[3..]);
726
727            let Some(stripped_idx) = stripped else {
728                ctx.warn(format!("unexpected key '{}', dropped", key));
729                continue;
730            };
731
732            match stripped_idx.parse::<usize>() {
733                Ok(index) => {
734                    if index >= rows.len() {
735                        rows.resize(index + 1, String::new());
736                    }
737                    rows[index] = value;
738                }
739                Err(_) => ctx.warn(format!("key '{}' has no valid row index, dropped", key)),
740            }
741        }
742        DispRows { rows }
743    }
744}
745
746impl DispRows {
747    /// Converts the `DispRows` data into a `VmfBlock` with the specified name.
748    ///
749    /// # Arguments
750    ///
751    /// * `self` - The `DispRows` instance to convert.
752    /// * `name` - The name of the block.
753    ///
754    /// # Returns
755    ///
756    /// A `VmfBlock` representing the `DispRows` data.
757    fn into_vmf_block(self, name: &str) -> VmfBlock {
758        let mut key_values = IndexMap::new();
759        for (i, row) in self.rows.into_iter().enumerate() {
760            key_values.insert(format!("row{}", i), row);
761        }
762
763        VmfBlock {
764            name: name.to_string(),
765            key_values,
766            blocks: Vec::new(),
767        }
768    }
769
770    /// Converts the `DispRows` data into a string representation with the specified name and indentation level.
771    ///
772    /// # Arguments
773    ///
774    /// * `self` - A reference to the `DispRows` instance.
775    /// * `indent_level` - The indentation level for formatting.
776    /// * `name` - The name of the block.
777    ///
778    /// # Returns
779    ///
780    /// A string representation of the `DispRows` data.
781    fn to_vmf_string(&self, indent_level: usize, name: &str) -> String {
782        let indent = "\t".repeat(indent_level);
783        let mut output = String::with_capacity(32);
784
785        output.push_str(&format!("{}{}\n", indent, name));
786        output.push_str(&format!("{}{{\n", indent));
787        for (i, row) in self.rows.iter().enumerate() {
788            output.push_str(&format!("{}\t\"row{}\" \"{}\"\n", indent, i, row));
789        }
790        output.push_str(&format!("{}}}\n", indent));
791
792        output
793    }
794}
795
796/// Represents a group in the VMF world.
797#[derive(Debug, Default, Clone, PartialEq, Eq)]
798#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
799pub struct Group {
800    /// The unique ID of the group.
801    pub id: u32,
802    /// The editor data for the group.
803    pub editor: Editor,
804    /// Keys and blocks this struct does not model.
805    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
806    pub extra: Extras,
807}
808
809impl FromBlock for Group {
810    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
811        let mut editor = None;
812        let mut unknown = Vec::new();
813
814        for inner_block in block.blocks.drain(..) {
815            if inner_block.name.eq_ignore_ascii_case("editor") {
816                ctx.enter("editor");
817                editor = Some(Editor::from_block(inner_block, ctx));
818                ctx.leave();
819            } else {
820                ctx.warn(format!(
821                    "unexpected block '{}', kept as-is",
822                    inner_block.name
823                ));
824                unknown.push(inner_block);
825            }
826        }
827
828        let kv = &mut block.key_values;
829        Self {
830            id: take_parse(kv, "id", 0, ctx),
831            editor: editor.unwrap_or_default(),
832            extra: Extras {
833                key_values: std::mem::take(kv),
834                blocks: unknown,
835            },
836        }
837    }
838}
839
840impl From<Group> for VmfBlock {
841    fn from(val: Group) -> Self {
842        let mut blocks = Vec::with_capacity(2);
843
844        // Adds Editor block
845        blocks.push(val.editor.into());
846        blocks.extend(val.extra.blocks);
847
848        VmfBlock {
849            name: "group".to_string(),
850            key_values: {
851                let mut key_values = IndexMap::new();
852                key_values.insert("id".to_string(), val.id.to_string());
853                key_values.extend(val.extra.key_values);
854                key_values
855            },
856            blocks,
857        }
858    }
859}
860
861impl VmfSerializable for Group {
862    fn to_vmf_string(&self, indent_level: usize) -> String {
863        let indent = "\t".repeat(indent_level);
864        let mut output = String::with_capacity(64);
865
866        // Writes the main entity block
867        output.push_str(&format!("{0}group\n{0}{{\n", indent));
868        output.push_str(&format!("{}\t\"id\" \"{}\"\n", indent, self.id));
869        self.extra.write_key_values(&mut output, indent_level + 1);
870
871        // Editor block
872        output.push_str(&self.editor.to_vmf_string(indent_level + 1));
873        self.extra.write_blocks(&mut output, indent_level + 1);
874
875        output.push_str(&format!("{}}}\n", indent));
876
877        output
878    }
879}