vmf_forge/
lib.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
//! A library for parsing and manipulating Valve Map Format (VMF) files.
//!
//! This library provides functionality to parse VMF files used in Source Engine games
//! into Rust data structures, modify the data, and serialize it back into a VMF file.
//!
//! # Example
//!
//! ```
//! use vmf_forge::prelude::*;
//! use std::fs::File;
//!
//! fn main() -> Result<(), VmfError> {
//!     let mut file = File::open("your_map.vmf")?;
//!     let vmf_file = VmfFile::parse_file(&mut file)?;
//!
//!     println!("Map Version: {}", vmf_file.versioninfo.map_version);
//!
//!     Ok(())
//! }
//! ```

#![warn(missing_docs)]

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

pub mod parser;
pub(crate) mod utils;
pub mod vmf;

pub mod errors;
pub mod prelude;

pub use errors::{VmfError, VmfResult};
pub use vmf::entities::{Entities, Entity};
pub use vmf::metadata::{VersionInfo, ViewSettings, VisGroups};
pub use vmf::regions::{Cameras, Cordons};
pub use vmf::world::World;

/// A trait for types that can be serialized into a VMF string representation.
pub trait VmfSerializable {
    /// Serializes the object into a VMF string.
    ///
    /// # Arguments
    ///
    /// * `indent_level` - The indentation level to use for formatting.
    ///
    /// # Returns
    ///
    /// A string representation of the object in VMF format.
    fn to_vmf_string(&self, indent_level: usize) -> String;
}

/// Represents a parsed VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VmfFile {
    /// The path to the VMF file, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// The version info of the VMF file.
    pub versioninfo: VersionInfo,
    /// The visgroups in the VMF file.
    pub visgroups: VisGroups,
    /// The view settings in the VMF file.
    pub viewsettings: ViewSettings,
    /// The world data in the VMF file.
    pub world: World,
    /// The entities in the VMF file.
    pub entities: Entities,
    /// The hidden entities in the VMF file.
    pub hiddens: Entities,
    /// The camera data in the VMF file.
    pub cameras: Cameras,
    /// The cordon data in the VMF file.
    pub cordons: Cordons,
}

impl VmfFile {
    /// Parses a VMF file from a string.
    ///
    /// # Arguments
    ///
    /// * `content` - The string content of the VMF file.
    ///
    /// # Returns
    ///
    /// A `VmfResult` containing the parsed `VmfFile` or a `VmfError` if parsing fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use vmf_forge::VmfFile;
    ///
    /// let vmf_content = r#"
    /// versioninfo
    /// {
    ///     "editorversion" "400"
    ///     "editorbuild" "8000"
    ///     "mapversion" "1"
    ///     "formatversion" "100"
    ///     "prefab" "0"
    /// }
    /// "#;
    ///
    /// let vmf_file = VmfFile::parse(vmf_content);
    /// assert!(vmf_file.is_ok());
    /// ```
    pub fn parse(content: &str) -> VmfResult<Self> {
        Ok(parser::parse_vmf(content)?)
    }

    /// Parses a VMF file from a `File`.
    ///
    /// # Arguments
    ///
    /// * `file` - The `File` to read from.
    ///
    /// # Returns
    ///
    /// A `VmfResult` containing the parsed `VmfFile` or a `VmfError` if parsing fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use vmf_forge::VmfFile;
    /// use std::fs::File;
    ///
    /// let mut file = File::open("your_map.vmf").unwrap();
    /// let vmf_file = VmfFile::parse_file(&mut file);
    /// assert!(vmf_file.is_ok());
    /// ```
    pub fn parse_file(file: &mut File) -> VmfResult<Self> {
        let mut content = Vec::new();
        file.read_to_end(&mut content)?;
        let content = String::from_utf8_lossy(&content);

        VmfFile::parse(&content)
    }

    /// Opens and parses a VMF file from a file path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the VMF file.
    ///
    /// # Returns
    ///
    /// A `VmfResult` containing the parsed `VmfFile` or a `VmfError` if an error occurs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use vmf_forge::VmfFile;
    ///
    /// let vmf_file = VmfFile::open("your_map.vmf");
    /// assert!(vmf_file.is_ok());
    /// ```
    pub fn open(path: impl AsRef<Path>) -> VmfResult<Self> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        let mut file = File::open(path)?;
        let mut content = Vec::new();
        file.read_to_end(&mut content)?;
        let content = String::from_utf8_lossy(&content);

        let mut vmf_file = VmfFile::parse(&content)?;
        vmf_file.path = Some(path_str);
        Ok(vmf_file)
    }

    /// Saves the `VmfFile` to a file at the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to save the VMF file to.
    ///
    /// # Returns
    ///
    /// A `VmfResult` indicating success or a `VmfError` if an error occurs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use vmf_forge::VmfFile;
    ///
    /// let vmf_file = VmfFile::open("your_map.vmf").unwrap();
    /// let result = vmf_file.save("new_map.vmf");
    /// assert!(result.is_ok());
    /// ```
    pub fn save(&self, path: impl AsRef<Path>) -> VmfResult<()> {
        let mut file = File::create(path)?;
        file.write_all(self.to_vmf_string().as_bytes())?;
        Ok(())
    }

    /// Converts the `VmfFile` to a string in VMF format.
    ///
    /// # Returns
    ///
    /// A string representing the `VmfFile` in VMF format.
    pub fn to_vmf_string(&self) -> String {
        let mut output = String::new();

        // metadatas
        output.push_str(&self.versioninfo.to_vmf_string(0));
        output.push_str(&self.visgroups.to_vmf_string(0));
        output.push_str(&self.viewsettings.to_vmf_string(0));
        output.push_str(&self.world.to_vmf_string(0));

        // entities
        for entity in &*self.entities {
            output.push_str(&entity.to_vmf_string(0));
        }

        for entity in &*self.hiddens {
            output.push_str("hidden\n{\n");
            output.push_str(&entity.to_vmf_string(1));
            output.push_str("}\n");
        }

        // regions
        output.push_str(&self.cameras.to_vmf_string(0));
        output.push_str(&self.cordons.to_vmf_string(0));

        output
    }
}

/// Represents a block in a VMF file, which can contain key-value pairs and other blocks.
#[derive(Debug, Default, Clone)]
pub struct VmfBlock {
    /// The name of the block.
    pub name: String,
    /// The key-value pairs in the block.
    pub key_values: IndexMap<String, String>,
    /// The child blocks contained within this block.
    pub blocks: Vec<VmfBlock>,
}

impl VmfBlock {
    /// Serializes the `VmfBlock` into a string with the specified indentation level.
    ///
    /// # Arguments
    ///
    /// * `indent_level` - The indentation level to use for formatting.
    ///
    /// # Returns
    ///
    /// A string representation of the `VmfBlock` in VMF format.
    pub fn serialize(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::new();

        // Opens the block with its name
        output.push_str(&format!("{}{}\n", indent, self.name));
        output.push_str(&format!("{}{{\n", indent));

        // Adds all key-value pairs with the required indent
        for (key, value) in &self.key_values {
            output.push_str(&format!("{}\t\"{}\" \"{}\"\n", indent, key, value));
        }

        // Adds nested blocks with an increased indentation level
        for block in &self.blocks {
            output.push_str(&block.serialize(indent_level + 1));
        }

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

        output
    }
}