Skip to main content

source_vmf/vmf/
regions.rs

1//! This module provides structures for representing region-specific data in a VMF file, such as cameras and cordons.
2
3use derive_more::{Deref, DerefMut};
4use indexmap::IndexMap;
5#[cfg(feature = "serialization")]
6use serde::{Deserialize, Serialize};
7
8use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
9use crate::utils::{To01String, take_bool, take_key, take_parse, take_str};
10use crate::{Extras, VmfBlock, VmfSerializable};
11
12impl_try_from_block!(Cameras, Camera, Cordons, Cordon);
13
14/// Represents the camera data in a VMF file.
15#[derive(Debug, Default, Clone, PartialEq, Deref, DerefMut)]
16#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
17pub struct Cameras {
18    /// The index of the active camera.
19    pub active: i8,
20    /// The list of cameras.
21    #[deref]
22    #[deref_mut]
23    pub cams: Vec<Camera>,
24    /// Keys and blocks this struct does not model.
25    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
26    pub extra: Extras,
27}
28
29impl FromBlock for Cameras {
30    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
31        ctx.enter("cameras");
32        let mut cams = Vec::with_capacity(block.blocks.len());
33        let mut unknown = Vec::new();
34
35        for (index, group) in block.blocks.drain(..).enumerate() {
36            if group.name.eq_ignore_ascii_case("camera") {
37                ctx.enter_indexed("camera", index);
38                cams.push(Camera::from_block(group, ctx));
39                ctx.leave();
40            } else {
41                ctx.warn(format!("unexpected block '{}', kept as-is", group.name));
42                unknown.push(group);
43            }
44        }
45
46        let kv = &mut block.key_values;
47        let cameras = Self {
48            active: take_parse(kv, "activecamera", -1, ctx),
49            cams,
50            extra: Extras {
51                key_values: std::mem::take(kv),
52                blocks: unknown,
53            },
54        };
55        ctx.leave();
56        cameras
57    }
58}
59
60impl From<Cameras> for VmfBlock {
61    fn from(val: Cameras) -> Self {
62        let mut blocks = Vec::with_capacity(val.cams.len());
63
64        for cam in val.cams {
65            blocks.push(cam.into());
66        }
67
68        blocks.extend(val.extra.blocks);
69
70        let mut key_values = IndexMap::new();
71        key_values.insert("activecamera".to_string(), val.active.to_string());
72        key_values.extend(val.extra.key_values);
73
74        VmfBlock {
75            name: "cameras".to_string(),
76            key_values,
77            blocks,
78        }
79    }
80}
81
82impl VmfSerializable for Cameras {
83    fn to_vmf_string(&self, indent_level: usize) -> String {
84        let indent: String = "\t".repeat(indent_level);
85        let mut output = String::with_capacity(64);
86
87        output.push_str(&format!("{0}cameras\n{0}{{\n", indent));
88        output.push_str(&format!(
89            "{}\t\"activecamera\" \"{}\"\n",
90            indent, self.active
91        ));
92        self.extra.write_key_values(&mut output, indent_level + 1);
93
94        for cam in &self.cams {
95            output.push_str(&format!("{0}\tcamera\n{0}\t{{\n", indent));
96            output.push_str(&format!(
97                "{}\t\t\"position\" \"{}\"\n",
98                indent, cam.position
99            ));
100            output.push_str(&format!("{}\t\t\"look\" \"{}\"\n", indent, cam.look));
101            cam.extra.write_key_values(&mut output, indent_level + 2);
102            cam.extra.write_blocks(&mut output, indent_level + 2);
103            output.push_str(&format!("{}\t}}\n", indent));
104        }
105        self.extra.write_blocks(&mut output, indent_level + 1);
106
107        output.push_str(&format!("{}}}\n", indent));
108        output
109    }
110}
111
112/// Represents a single camera in a VMF file.
113#[derive(Debug, Default, Clone, PartialEq)]
114#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
115pub struct Camera {
116    /// The position of the camera in the VMF coordinate system.
117    pub position: String, // vertex
118    /// The point at which the camera is looking, in the VMF coordinate system.
119    pub look: String, // vertex
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
125impl FromBlock for Camera {
126    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
127        let blocks = std::mem::take(&mut block.blocks);
128        let kv = &mut block.key_values;
129        Self {
130            position: take_str(kv, "position", "0 0 0", ctx),
131            look: take_str(kv, "look", "0 0 0", ctx),
132            extra: Extras {
133                key_values: std::mem::take(kv),
134                blocks,
135            },
136        }
137    }
138}
139
140impl From<Camera> for VmfBlock {
141    fn from(val: Camera) -> Self {
142        let mut key_values = IndexMap::new();
143        key_values.insert("position".to_string(), val.position);
144        key_values.insert("look".to_string(), val.look);
145        key_values.extend(val.extra.key_values);
146
147        VmfBlock {
148            name: "camera".to_string(),
149            key_values,
150            blocks: val.extra.blocks,
151        }
152    }
153}
154
155/// Represents the cordons data in a VMF file.
156#[derive(Debug, Default, Clone, PartialEq, Deref, DerefMut)]
157#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
158pub struct Cordons {
159    /// The index of the active cordon.
160    pub active: i8,
161    /// The list of cordons.
162    #[deref]
163    #[deref_mut]
164    pub cordons: Vec<Cordon>,
165    /// Keys and blocks this struct does not model.
166    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
167    pub extra: Extras,
168}
169
170impl FromBlock for Cordons {
171    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
172        ctx.enter("cordons");
173        let mut cordons = Vec::with_capacity(block.blocks.len());
174        let mut unknown = Vec::new();
175
176        for (index, group) in block.blocks.drain(..).enumerate() {
177            if group.name.eq_ignore_ascii_case("cordon") {
178                ctx.enter_indexed("cordon", index);
179                cordons.push(Cordon::from_block(group, ctx));
180                ctx.leave();
181            } else {
182                ctx.warn(format!("unexpected block '{}', kept as-is", group.name));
183                unknown.push(group);
184            }
185        }
186
187        let kv = &mut block.key_values;
188        let result = Self {
189            active: take_parse(kv, "active", 0, ctx),
190            cordons,
191            extra: Extras {
192                key_values: std::mem::take(kv),
193                blocks: unknown,
194            },
195        };
196        ctx.leave();
197        result
198    }
199}
200
201impl From<Cordons> for VmfBlock {
202    fn from(val: Cordons) -> Self {
203        let mut blocks = Vec::new();
204
205        // Converts each  Cordon to a VmfBlock and adds it to the `blocks` vector
206        for cordon in val.cordons {
207            blocks.push(cordon.into());
208        }
209        blocks.extend(val.extra.blocks);
210
211        // Creates a VmfBlock for Cordons
212        let mut key_values = IndexMap::new();
213        key_values.insert("active".to_string(), val.active.to_string());
214        key_values.extend(val.extra.key_values);
215
216        VmfBlock {
217            name: "cordons".to_string(),
218            key_values,
219            blocks,
220        }
221    }
222}
223
224impl VmfSerializable for Cordons {
225    fn to_vmf_string(&self, indent_level: usize) -> String {
226        let indent = "\t".repeat(indent_level);
227        let mut output = String::with_capacity(256);
228
229        // Start of Cordons block
230        output.push_str(&format!("{0}cordons\n{0}{{\n", indent));
231        output.push_str(&format!("{}\t\"active\" \"{}\"\n", indent, self.active));
232        self.extra.write_key_values(&mut output, indent_level + 1);
233
234        // Iterates through all Cordons and adds their string representation
235        for cordon in &self.cordons {
236            output.push_str(&cordon.to_vmf_string(indent_level + 1));
237        }
238        self.extra.write_blocks(&mut output, indent_level + 1);
239
240        output.push_str(&format!("{}}}\n", indent));
241
242        output
243    }
244}
245
246/// Represents a single cordon in a VMF file.
247#[derive(Debug, Default, Clone, PartialEq)]
248#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
249pub struct Cordon {
250    /// The name of the cordon.
251    pub name: String,
252    /// Whether the cordon is active.
253    pub active: bool,
254    /// The minimum point of the cordon's bounding box.
255    pub min: String, // vertex
256    /// The maximum point of the cordon's bounding box.
257    pub max: String, // vertex
258    /// Keys and blocks this struct does not model.
259    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Extras::is_empty"))]
260    pub extra: Extras,
261}
262
263impl FromBlock for Cordon {
264    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
265        // Mins/maxs reside in a 'box' sub-block in newer VMFs, or directly on cordon in older ones.
266        let from_box = block.blocks.first_mut().and_then(|sub_block| {
267            let min = take_key(&mut sub_block.key_values, "mins");
268            let max = take_key(&mut sub_block.key_values, "maxs");
269            min.zip(max)
270        });
271
272        // Drop empty 'box' block so it is not preserved in extras.
273        block
274            .blocks
275            .retain(|b| !(b.name.eq_ignore_ascii_case("box") && b.key_values.is_empty()));
276        let blocks = std::mem::take(&mut block.blocks);
277
278        let kv = &mut block.key_values;
279        let (min, max) = match from_box {
280            Some(pair) => pair,
281            None => (
282                take_str(kv, "mins", "0 0 0", ctx),
283                take_str(kv, "maxs", "0 0 0", ctx),
284            ),
285        };
286
287        Self {
288            name: take_str(kv, "name", "cordon", ctx),
289            active: take_bool(kv, "active", false, ctx),
290            min,
291            max,
292            extra: Extras {
293                key_values: std::mem::take(kv),
294                blocks,
295            },
296        }
297    }
298}
299
300impl From<Cordon> for VmfBlock {
301    fn from(val: Cordon) -> Self {
302        // Creates key_values for Cordon
303        let mut key_values = IndexMap::new();
304        key_values.insert("name".to_string(), val.name);
305        key_values.insert("active".to_string(), val.active.to_01_string());
306        key_values.extend(val.extra.key_values);
307
308        // Creates a block for the box with `mins/maxs`
309        let mut box_block_key_values = IndexMap::new();
310        box_block_key_values.insert("mins".to_string(), val.min);
311        box_block_key_values.insert("maxs".to_string(), val.max);
312
313        // Creates a VmfBlock for the box
314        let box_block = VmfBlock {
315            name: "box".to_string(),
316            key_values: box_block_key_values,
317            blocks: vec![],
318        };
319
320        // Creates the main VmfBlock for Cordon
321        let mut blocks = vec![box_block];
322        blocks.extend(val.extra.blocks);
323
324        VmfBlock {
325            name: "cordon".to_string(),
326            key_values,
327            blocks,
328        }
329    }
330}
331
332impl VmfSerializable for Cordon {
333    fn to_vmf_string(&self, indent_level: usize) -> String {
334        let indent: String = "\t".repeat(indent_level);
335        let mut output = String::with_capacity(64);
336
337        // Start of Cordon block
338        output.push_str(&format!("{0}cordon\n{0}{{\n", indent));
339        output.push_str(&format!("{}\t\"name\" \"{}\"\n", indent, self.name));
340        output.push_str(&format!(
341            "{}\t\"active\" \"{}\"\n",
342            indent,
343            self.active.to_01_string()
344        ));
345        self.extra.write_key_values(&mut output, indent_level + 1);
346
347        // Adds a nested block with coordinates
348        output.push_str(&format!("{0}\tbox\n{0}\t{{\n", indent));
349        output.push_str(&format!("{}\t\t\"mins\" \"{}\"\n", indent, self.min));
350        output.push_str(&format!("{}\t\t\"maxs\" \"{}\"\n", indent, self.max));
351        output.push_str(&format!("{}\t}}\n", indent)); // end of `box``
352        self.extra.write_blocks(&mut output, indent_level + 1);
353
354        // End of Cordon block
355        output.push_str(&format!("{}}}\n", indent));
356
357        output
358    }
359}