vmf_forge/vmf/
entities.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
//! This module provides structures for representing entities in a VMF file.

use crate::{
    errors::{VmfError, VmfResult},
    VmfBlock, VmfSerializable,
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::{
    ops::{Deref, DerefMut},
    vec,
};

use super::common::Editor;
use super::world::Solid;

/// Represents an entity in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Entity {
    /// The key-value pairs associated with this entity.
    pub key_values: IndexMap<String, String>,
    /// The output connections of this entity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connections: Option<Vec<(String, String)>>,
    /// The solids associated with this entity, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub solids: Option<Vec<Solid>>,
    /// The editor data for this entity.
    pub editor: Editor,
}

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

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        // Extract key-value pairs from the block
        let key_values = block.key_values;

        // Searches for nested blocks and extracts the necessary information
        let mut ent = Self {
            key_values,
            ..Default::default()
        };
        let mut solids = Vec::new();

        for block in block.blocks {
            match block.name.as_str() {
                "editor" => ent.editor = Editor::try_from(block)?,
                "connections" => ent.connections = Some(block.key_values.into_iter().collect()),
                "solid" => solids.push(Solid::try_from(block)?),
                "hidden" => {
                    if let Some(hidden_block) = block.blocks.first() {
                        solids.push(Solid::try_from(hidden_block.to_owned())?)
                    }
                }
                _ => {
                    debug_assert!(
                        false,
                        "Unexpected block name: {}, id: {:?}",
                        block.name,
                        ent.key_values.get("id")
                    );
                }
            }
        }

        if !solids.is_empty() {
            ent.solids = Some(solids);
        }

        Ok(ent)
    }
}

impl Into<VmfBlock> for Entity {
    fn into(self) -> VmfBlock {
        let editor = self.editor.into();

        VmfBlock {
            name: "entity".to_string(),
            key_values: self.key_values,
            blocks: vec![editor],
        }
    }
}

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

        // Writes the main entity block
        output.push_str(&format!("{0}entity\n{0}{{\n", indent));

        // Adds key_values of the main block
        for (key, value) in &self.key_values {
            output.push_str(&format!("{}\t\"{}\" \"{}\"\n", indent, key, value));
        }

        // Adds connections block
        if let Some(connections) = &self.connections {
            output.push_str(&format!("{0}\tconnections\n{0}\t{{\n", indent));
            for (out, inp) in connections {
                output.push_str(&format!("{}\t\t\"{}\" \"{}\"\n", indent, out, inp));
            }
            output.push_str(&format!("{}\t}}\n", indent));
        }

        // Editor block
        output.push_str(&self.editor.to_vmf_string(indent_level + 1));

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

        output
    }
}

/// Represents a collection of entities in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Entities {
    /// The vector of entities.
    pub vec: Vec<Entity>,
}

impl Deref for Entities {
    type Target = Vec<Entity>;

    fn deref(&self) -> &Self::Target {
        &self.vec
    }
}

impl DerefMut for Entities {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.vec
    }
}

impl Entities {
    /// Returns an iterator over the entities that have the specified key-value pair.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to search for.
    /// * `value` - The value to search for.
    pub fn find_by_keyvalue<'a>(
        &'a self,
        key: &'a str,
        value: &'a str,
    ) -> impl Iterator<Item = &'a Entity> + 'a {
        self.vec
            .iter()
            .filter(move |ent| ent.key_values.get(key).map_or(false, |v| v == value))
    }

    /// Returns an iterator over the entities that have the specified key-value pair, allowing modification.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to search for.
    /// * `value` - The value to search for.
    pub fn find_by_keyvalue_mut<'a>(
        &'a mut self,
        key: &'a str,
        value: &'a str,
    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
        self.vec
            .iter_mut()
            .filter(move |ent| ent.key_values.get(key).map_or(false, |v| v == value))
    }

    /// Returns an iterator over the entities with the specified classname.
    ///
    /// # Arguments
    ///
    /// * `classname` - The classname to search for.
    pub fn find_by_classname<'a>(
        &'a self,
        classname: &'a str,
    ) -> impl Iterator<Item = &'a Entity> + 'a {
        self.find_by_keyvalue("classname", classname)
    }

    /// Returns an iterator over the entities with the specified targetname.
    ///
    /// # Arguments
    ///
    /// * `name` - The targetname to search for.
    pub fn find_by_name<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
        self.find_by_keyvalue("targetname", name)
    }

    /// Returns an iterator over the entities with the specified classname, allowing modification.
    ///
    /// # Arguments
    ///
    /// * `classname` - The classname to search for.
    pub fn find_by_classname_mut<'a>(
        &'a mut self,
        classname: &'a str,
    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
        self.find_by_keyvalue_mut("classname", classname)
    }

    /// Returns an iterator over the entities with the specified targetname, allowing modification.
    ///
    /// # Arguments
    ///
    /// * `name` - The targetname to search for.
    pub fn find_by_name_mut<'a>(
        &'a mut self,
        name: &'a str,
    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
        self.find_by_keyvalue_mut("targetname", name)
    }

    /// Returns an iterator over the entities with the specified model.
    ///
    /// # Arguments
    ///
    /// * `model` - The model to search for.
    pub fn find_by_model<'a>(&'a self, model: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
        self.find_by_keyvalue("model", model)
    }

    /// Returns an iterator over the entities with the specified model, allowing modification.
    ///
    /// # Arguments
    ///
    /// * `model` - The model to search for.
    pub fn find_by_model_mut<'a>(
        &'a mut self,
        model: &'a str,
    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
        self.find_by_keyvalue_mut("model", model)
    }
}