vmf_forge/vmf/
regions.rs

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
//! This module provides structures for representing region-specific data in a VMF file, such as cameras and cordons.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::utils::{get_key, parse_hs_key, To01String};
use crate::{
    errors::{VmfError, VmfResult},
    VmfBlock, VmfSerializable,
};

/// Represents the camera data in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Cameras {
    /// The index of the active camera.
    pub active: i8,
    /// The list of cameras.
    pub cams: Vec<Camera>,
}

impl TryFrom<VmfBlock> for Cameras {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let mut cams = Vec::with_capacity(12);
        for group in block.blocks {
            cams.push(Camera::try_from(group)?);
        }

        Ok(Self {
            active: parse_hs_key!(&block.key_values, "activecamera", i8)?,
            cams,
        })
    }
}

impl Into<VmfBlock> for Cameras {
    fn into(self) -> VmfBlock {
        let mut blocks = Vec::with_capacity(self.cams.len());

        for cam in self.cams {
            blocks.push(cam.into());
        }

        let mut key_values = IndexMap::new();
        key_values.insert("active".to_string(), self.active.to_string());

        VmfBlock {
            name: "cameras".to_string(),
            key_values,
            blocks,
        }
    }
}

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

        output.push_str(&format!("{0}cameras\n{0}{{\n", indent));
        output.push_str(&format!(
            "{}\t\"activecamera\" \"{}\"\n",
            indent, self.active
        ));

        for cam in &self.cams {
            output.push_str(&format!("{0}\tcamera\n{0}\t{{\n", indent));
            output.push_str(&format!(
                "{}\t\t\"position\" \"{}\"\n",
                indent, cam.position
            ));
            output.push_str(&format!("{}\t\t\"look\" \"{}\"\n", indent, cam.look));
            output.push_str(&format!("{}\t}}\n", indent));
        }

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

/// Represents a single camera in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Camera {
    /// The position of the camera in the VMF coordinate system.
    pub position: String, // vertex
    /// The point at which the camera is looking, in the VMF coordinate system.
    pub look: String, // vertex
}

impl TryFrom<VmfBlock> for Camera {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        Ok(Self {
            position: get_key!(&block.key_values, "position")?.to_owned(),
            look: get_key!(&block.key_values, "look")?.to_owned(),
        })
    }
}

impl Into<VmfBlock> for Camera {
    fn into(self) -> VmfBlock {
        let mut key_values = IndexMap::new();
        key_values.insert("position".to_string(), self.position);
        key_values.insert("look".to_string(), self.look);

        VmfBlock {
            name: "camera".to_string(),
            key_values,
            ..Default::default()
        }
    }
}

/// Represents the cordons data in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Cordons {
    /// The index of the active cordon.
    pub active: i8,
    /// The list of cordons.
    pub cordons: Vec<Cordon>,
}

impl TryFrom<VmfBlock> for Cordons {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let mut cordons = Vec::with_capacity(12);
        for group in block.blocks {
            cordons.push(Cordon::try_from(group)?);
        }

        Ok(Self {
            active: parse_hs_key!(&block.key_values, "active", i8)?,
            cordons,
        })
    }
}

impl Into<VmfBlock> for Cordons {
    fn into(self) -> VmfBlock {
        let mut blocks = Vec::new();

        // Converts each  Cordon to a VmfBlock and adds it to the `blocks` vector
        for cordon in self.cordons {
            blocks.push(cordon.into());
        }

        // Creates a VmfBlock for Cordons
        let mut key_values = IndexMap::new();
        key_values.insert("active".to_string(), self.active.to_string());

        VmfBlock {
            name: "cordons".to_string(),
            key_values,
            blocks,
        }
    }
}

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

        // Start of Cordons block
        output.push_str(&format!("{0}cordons\n{0}{{\n", indent));
        output.push_str(&format!("{}\t\"active\" \"{}\"\n", indent, self.active));

        // Iterates through all Cordons and adds their string representation
        for cordon in &self.cordons {
            output.push_str(&cordon.to_vmf_string(indent_level + 1));
        }

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

        output
    }
}

/// Represents a single cordon in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Cordon {
    /// The name of the cordon.
    pub name: String,
    /// Whether the cordon is active.
    pub active: bool,
    /// The minimum point of the cordon's bounding box.
    pub min: String, // vertex
    /// The maximum point of the cordon's bounding box.
    pub max: String, // vertex
}

impl TryFrom<VmfBlock> for Cordon {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let (min, max) = block
            .blocks
            .get(0)
            .ok_or_else(|| VmfError::InvalidFormat("Missing 'box' block in Cordon".to_string()))
            .and_then(|sub_block| {
                Ok((
                    get_key!(&sub_block.key_values, "mins")?,
                    get_key!(&sub_block.key_values, "maxs")?,
                ))
            })
            .or_else(|_| {
                Ok::<(_, _), VmfError>((
                    get_key!(&block.key_values, "mins")?,
                    get_key!(&block.key_values, "maxs")?,
                ))
            })?;

        Ok(Self {
            name: get_key!(&block.key_values, "name")?.to_owned(),
            active: get_key!(&block.key_values, "active")? == "1",
            min: min.to_owned(),
            max: max.to_owned(),
        })
    }
}

impl Into<VmfBlock> for Cordon {
    fn into(self) -> VmfBlock {
        // Creates key_values for Cordon
        let mut key_values = IndexMap::new();
        key_values.insert("name".to_string(), self.name);
        key_values.insert("active".to_string(), self.active.to_01_string());

        // Creates a block for the box with `mins/maxs`
        let mut box_block_key_values = IndexMap::new();
        box_block_key_values.insert("mins".to_string(), self.min);
        box_block_key_values.insert("maxs".to_string(), self.max);

        // Creates a VmfBlock for the box
        let box_block = VmfBlock {
            name: "box".to_string(),
            key_values: box_block_key_values,
            blocks: vec![],
        };

        // Creates the main VmfBlock for Cordon
        VmfBlock {
            name: "cordon".to_string(),
            key_values,
            blocks: vec![box_block],
        }
    }
}

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

        // Start of Cordon block
        output.push_str(&format!("{0}cordon\n{0}{{\n", indent));
        output.push_str(&format!("{}\t\"name\" \"{}\"\n", indent, self.name));
        output.push_str(&format!(
            "{}\t\"active\" \"{}\"\n",
            indent,
            self.active.to_01_string()
        ));

        // Adds a nested block with coordinates
        output.push_str(&format!("{0}\tbox\n{}\t{{\n", indent));
        output.push_str(&format!("{}\t\t\"mins\" \"{}\"\n", indent, self.min));
        output.push_str(&format!("{}\t\t\"maxs\" \"{}\"\n", indent, self.max));
        output.push_str(&format!("{}\t}}\n", indent)); // end of `box``

        // End of Cordon block
        output.push_str(&format!("{}}}\n", indent));

        output
    }
}