Skip to main content

source_vmf/vmf/
entities.rs

1//! This module provides structures for representing entities in a VMF file.
2
3use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
4use crate::{Extras, VmfBlock, VmfSerializable};
5use derive_more::{Deref, DerefMut, IntoIterator};
6use indexmap::IndexMap;
7#[cfg(feature = "serialization")]
8use serde::{Deserialize, Serialize};
9
10use super::common::Editor;
11use super::world::Solid;
12use std::mem;
13
14impl_try_from_block!(Entity);
15
16// Connections live in their own module; re-exported so that
17// `vmf::entities::Connection` keeps resolving.
18pub use super::connection::{Connection, InstanceIo, Special, Target};
19
20/// Represents an entity in a VMF file.
21#[derive(Debug, Default, Clone, PartialEq)]
22#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
23pub struct Entity {
24    /// The key-value pairs associated with this entity.
25    pub key_values: IndexMap<String, String>,
26    /// The output connections of this entity.
27    #[cfg_attr(
28        feature = "serialization",
29        serde(default, skip_serializing_if = "Option::is_none")
30    )]
31    pub connections: Option<Vec<Connection>>,
32    /// The solids associated with this entity, if any.
33    #[cfg_attr(
34        feature = "serialization",
35        serde(default, skip_serializing_if = "Option::is_none")
36    )]
37    pub solids: Option<Vec<Solid>>,
38    /// The editor data for this entity.
39    pub editor: Editor,
40    /// Indicates if the entity is hidden within the editor.  This field
41    /// is primarily used when parsing a `hidden` block within a VMF file,
42    /// and is not serialized back when writing the VMF.
43    #[cfg_attr(feature = "serialization", serde(default, skip_serializing))]
44    pub is_hidden: bool,
45    /// Blocks this struct does not model. Unknown *keys* land in `key_values`.
46    #[cfg_attr(
47        feature = "serialization",
48        serde(default, skip_serializing_if = "Extras::is_empty")
49    )]
50    pub extra: Extras,
51}
52
53impl Entity {
54    /// Creates a new `Entity` with the specified classname and ID.
55    ///
56    /// # Arguments
57    ///
58    /// * `classname` - The classname of the entity (e.g., "func_detail", "info_player_start").
59    /// * `id` - The unique ID of the entity.
60    ///
61    /// # Example
62    ///
63    /// ```
64    /// use source_vmf::prelude::*;
65    ///
66    /// let entity = Entity::new("info_player_start", 1);
67    /// assert_eq!(entity.classname(), Some("info_player_start"));
68    /// assert_eq!(entity.id(), 1);
69    /// ```
70    pub fn new(classname: impl Into<String>, id: u64) -> Self {
71        let mut key_values = IndexMap::with_capacity(12);
72        key_values.insert("classname".to_string(), classname.into());
73        key_values.insert("id".to_string(), id.to_string());
74        Entity {
75            key_values,
76            connections: None,
77            solids: None,
78            editor: Editor::default(),
79            is_hidden: false,
80            extra: Extras::default(),
81        }
82    }
83
84    /// Sets a key-value pair for the entity.  If the key already exists,
85    /// its value is updated.
86    ///
87    /// # Arguments
88    ///
89    /// * `key` - The key to set.
90    /// * `value` - The value to set for the key.
91    pub fn set(&mut self, key: String, value: String) {
92        self.key_values.insert(key, value);
93    }
94
95    /// Removes a key-value pair from the entity, preserving the order of other keys.
96    ///
97    /// # Arguments
98    ///
99    /// * `key` - The key to remove.
100    ///
101    /// # Returns
102    ///
103    /// An `Option` containing the removed value, if the key was present.
104    pub fn remove_key(&mut self, key: &str) -> Option<String> {
105        self.key_values.shift_remove(key)
106    }
107
108    /// Removes a key-value pair from the entity, potentially changing the order of other keys.
109    /// This is faster than `remove_key` but does not preserve insertion order.
110    ///
111    /// # Arguments
112    ///
113    /// * `key` - The key to remove.
114    ///
115    /// # Returns
116    ///
117    /// An `Option` containing the removed value, if the key was present.
118    pub fn swap_remove_key(&mut self, key: &str) -> Option<String> {
119        self.key_values.swap_remove(key)
120    }
121
122    /// Gets the value associated with the given key.
123    ///
124    /// # Arguments
125    ///
126    /// * `key` - The key to get the value for.
127    ///
128    /// # Returns
129    ///
130    /// An `Option` containing a reference to the value, if the key is present.
131    pub fn get(&self, key: &str) -> Option<&String> {
132        self.key_values.get(key)
133    }
134
135    /// Gets a mutable reference to the value associated with the given key.
136    ///
137    /// # Arguments
138    ///
139    /// * `key` - The key to get the value for.
140    ///
141    /// # Returns
142    ///
143    /// An `Option` containing a mutable reference to the value, if the key is present.
144    pub fn get_mut(&mut self, key: &str) -> Option<&mut String> {
145        self.key_values.get_mut(key)
146    }
147
148    /// Returns the classname of the entity.
149    ///
150    /// # Returns
151    ///
152    /// An `Option` containing the classname, if it exists.
153    pub fn classname(&self) -> Option<&str> {
154        self.key_values.get("classname").map(|s| s.as_str())
155    }
156
157    /// Returns the targetname of the entity.
158    ///
159    /// # Returns
160    ///
161    /// An `Option` containing the targetname, if it exists.
162    pub fn targetname(&self) -> Option<&str> {
163        self.key_values.get("targetname").map(|s| s.as_str())
164    }
165
166    /// Returns the ID of the entity.
167    pub fn id(&self) -> u64 {
168        self.key_values
169            .get("id")
170            .and_then(|s| s.parse::<u64>().ok())
171            .unwrap_or(0)
172    }
173
174    /// Returns the model of the entity.
175    ///
176    /// # Returns
177    ///
178    /// An `Option` containing the model path, if it exists.
179    pub fn model(&self) -> Option<&str> {
180        self.key_values.get("model").map(|s| s.as_str())
181    }
182
183    /// Adds an output connection to the entity.
184    ///
185    /// # Arguments
186    ///
187    /// * `output` - The name of the output on this entity.
188    /// * `target_entity` - The targetname of the entity to connect to.
189    /// * `input` - The name of the input on the target entity.
190    /// * `parms` - The parameters to pass to the input.
191    /// * `delay` - The delay before the input is triggered, in seconds.
192    /// * `fire_limit` - The number of times the output can be fired (-1 for unlimited).
193    ///
194    /// # Example
195    ///
196    /// ```
197    /// use source_vmf::prelude::*;
198    ///
199    /// let mut entity = Entity::new("logic_relay", 1);
200    /// entity.add_connection("OnTrigger", "my_door", "Open", "", 0.0, -1);
201    /// ```
202    pub fn add_connection(
203        &mut self,
204        output: impl Into<String>,
205        target_entity: impl Into<String>,
206        input: impl Into<String>,
207        parms: impl Into<String>,
208        delay: f32,
209        fire_limit: i32,
210    ) {
211        let connection = Connection {
212            output: output.into(),
213            target: target_entity.into(),
214            input: input.into(),
215            params: parms.into(),
216            delay,
217            fire_limit,
218        };
219
220        if let Some(connections) = &mut self.connections {
221            connections.push(connection);
222        } else {
223            self.connections = Some(vec![connection]);
224        }
225    }
226
227    /// Removes all connections from this entity.
228    pub fn clear_connections(&mut self) {
229        self.connections = None;
230    }
231
232    /// Checks if a specific connection exists.
233    ///
234    /// # Arguments
235    /// * `output` The output to check
236    /// * `input` The input to check
237    ///
238    /// # Returns
239    /// * `true` if the connection exists, `false` otherwise.
240    pub fn has_connection(&self, output: &str, input: &str) -> bool {
241        if let Some(connections) = &self.connections {
242            connections
243                .iter()
244                .any(|c| c.output == output && c.input == input)
245        } else {
246            false
247        }
248    }
249}
250
251impl FromBlock for Entity {
252    fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
253        let blocks = std::mem::take(&mut block.blocks);
254
255        let mut ent = Self {
256            key_values: block.key_values,
257            ..Default::default()
258        };
259        let mut solids = Vec::with_capacity(blocks.len());
260
261        for mut inner_block in blocks {
262            let name = inner_block.name.clone();
263            if name.eq_ignore_ascii_case("editor") {
264                ctx.enter("editor");
265                ent.editor = Editor::from_block(inner_block, ctx);
266                ctx.leave();
267            } else if name.eq_ignore_ascii_case("connections") {
268                ent.connections = process_connections(inner_block.key_values);
269            } else if name.eq_ignore_ascii_case("solid") {
270                ctx.enter_indexed("solid", solids.len());
271                solids.push(Solid::from_block(inner_block, ctx));
272                ctx.leave();
273            } else if name.eq_ignore_ascii_case("hidden") {
274                // Read all solids inside the hidden wrapper.
275                for hidden_block in mem::take(&mut inner_block.blocks) {
276                    ctx.enter_indexed("hidden", solids.len());
277                    solids.push(Solid::from_block(hidden_block, ctx));
278                    ctx.leave();
279                }
280            } else {
281                ctx.warn(format!("unexpected block '{}', kept as-is", name));
282                ent.extra.blocks.push(inner_block);
283            }
284        }
285
286        if !solids.is_empty() {
287            ent.solids = Some(solids);
288        }
289
290        ent
291    }
292}
293
294impl From<Entity> for VmfBlock {
295    fn from(val: Entity) -> Self {
296        let mut blocks = Vec::with_capacity(3);
297
298        if let Some(connections) = &val.connections {
299            if !connections.is_empty() {
300                blocks.push(VmfBlock {
301                    name: "connections".to_string(),
302                    key_values: Connection::to_key_values(connections),
303                    blocks: Vec::new(),
304                });
305            }
306        }
307        if let Some(solids) = val.solids {
308            blocks.extend(solids.into_iter().map(VmfBlock::from));
309        }
310        blocks.push(val.editor.into());
311        blocks.extend(val.extra.blocks);
312
313        let mut key_values = val.key_values;
314        key_values.extend(val.extra.key_values);
315
316        VmfBlock {
317            name: "entity".to_string(),
318            key_values,
319            blocks,
320        }
321    }
322}
323
324impl VmfSerializable for Entity {
325    fn to_vmf_string(&self, indent_level: usize) -> String {
326        let indent = "\t".repeat(indent_level);
327        let mut output = String::with_capacity(256);
328
329        // Writes the main entity block
330        output.push_str(&format!("{0}entity\n{0}{{\n", indent));
331
332        // Adds key_values of the main block
333        for (key, value) in &self.key_values {
334            crate::write_key_value(&mut output, &format!("{indent}\t"), key, value);
335        }
336
337        // Adds connections block
338        if let Some(connections) = &self.connections {
339            output.push_str(&format!("{0}\tconnections\n{0}\t{{\n", indent));
340            for connection in connections {
341                output.push_str(&format!(
342                    "{}\t\t\"{}\" \"{}\"\n",
343                    indent,
344                    connection.output,
345                    connection.to_value_string()
346                ));
347            }
348            output.push_str(&format!("{}\t}}\n", indent));
349        }
350
351        // Solids block
352        if let Some(solids) = &self.solids {
353            for solid in solids {
354                output.push_str(&solid.to_vmf_string(indent_level + 1));
355            }
356        }
357
358        // Editor block
359        output.push_str(&self.editor.to_vmf_string(indent_level + 1));
360        self.extra.write_blocks(&mut output, indent_level + 1);
361
362        output.push_str(&format!("{}}}\n", indent));
363
364        output
365    }
366}
367
368/// A collection of entities.
369#[derive(Debug, Default, Clone, Deref, DerefMut, IntoIterator, PartialEq)]
370#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
371pub struct Entities(pub Vec<Entity>);
372
373impl Entities {
374    /// Returns an iterator over the entities that have the specified key-value pair.
375    ///
376    /// # Arguments
377    ///
378    /// * `key` - The key to search for.
379    /// * `value` - The value to search for.
380    pub fn find_by_keyvalue<'a>(
381        &'a self,
382        key: &'a str,
383        value: &'a str,
384    ) -> impl Iterator<Item = &'a Entity> + 'a {
385        self.iter()
386            .filter(move |ent| ent.key_values.get(key).is_some_and(|v| v == value))
387    }
388
389    /// Returns an iterator over the entities that have the specified key-value pair, allowing modification.
390    ///
391    /// # Arguments
392    ///
393    /// * `key` - The key to search for.
394    /// * `value` - The value to search for.
395    pub fn find_by_keyvalue_mut<'a>(
396        &'a mut self,
397        key: &'a str,
398        value: &'a str,
399    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
400        self.iter_mut()
401            .filter(move |ent| ent.key_values.get(key).is_some_and(|v| v == value))
402    }
403
404    /// Returns an iterator over the entities with the specified classname.
405    ///
406    /// # Arguments
407    ///
408    /// * `classname` - The classname to search for.
409    pub fn find_by_classname<'a>(
410        &'a self,
411        classname: &'a str,
412    ) -> impl Iterator<Item = &'a Entity> + 'a {
413        self.find_by_keyvalue("classname", classname)
414    }
415
416    /// Returns an iterator over the entities with the specified targetname.
417    ///
418    /// # Arguments
419    ///
420    /// * `name` - The targetname to search for.
421    pub fn find_by_name<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
422        self.find_by_keyvalue("targetname", name)
423    }
424
425    /// Returns an iterator over the entities with the specified classname, allowing modification.
426    ///
427    /// # Arguments
428    ///
429    /// * `classname` - The classname to search for.
430    pub fn find_by_classname_mut<'a>(
431        &'a mut self,
432        classname: &'a str,
433    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
434        self.find_by_keyvalue_mut("classname", classname)
435    }
436
437    /// Returns an iterator over the entities with the specified targetname, allowing modification.
438    ///
439    /// # Arguments
440    ///
441    /// * `name` - The targetname to search for.
442    pub fn find_by_name_mut<'a>(
443        &'a mut self,
444        name: &'a str,
445    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
446        self.find_by_keyvalue_mut("targetname", name)
447    }
448
449    /// Returns an iterator over the entities with the specified model.
450    ///
451    /// # Arguments
452    ///
453    /// * `model` - The model to search for.
454    pub fn find_by_model<'a>(&'a self, model: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
455        self.find_by_keyvalue("model", model)
456    }
457
458    /// Returns an iterator over the entities with the specified model, allowing modification.
459    ///
460    /// # Arguments
461    ///
462    /// * `model` - The model to search for.
463    pub fn find_by_model_mut<'a>(
464        &'a mut self,
465        model: &'a str,
466    ) -> impl Iterator<Item = &'a mut Entity> + 'a {
467        self.find_by_keyvalue_mut("model", model)
468    }
469
470    /// Removes an entity by its ID.
471    ///
472    /// # Arguments
473    ///
474    /// * `entity_id` - The ID of the entity to remove.
475    ///
476    /// # Returns
477    ///
478    /// An `Option` containing the removed `Entity`, if found. Returns `None`
479    /// if no entity with the given ID exists.
480    pub fn remove_entity(&mut self, entity_id: i32) -> Option<Entity> {
481        self.iter()
482            .position(|e| e.key_values.get("id") == Some(&entity_id.to_string()))
483            .map(|index| self.remove(index))
484    }
485
486    /// Removes all entities that have a matching key-value pair.
487    ///
488    /// # Arguments
489    ///
490    /// * `key` - The key to check.
491    /// * `value` - The value to compare against.
492    pub fn remove_by_keyvalue(&mut self, key: &str, value: &str) {
493        self.retain(|ent| ent.key_values.get(key).map(|v| v != value).unwrap_or(true));
494    }
495}
496
497fn process_connections(map: IndexMap<String, String>) -> Option<Vec<Connection>> {
498    Connection::from_key_values(&map)
499}