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 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
//! This module provides structures for representing entities in a VMF file.
use crate::{
errors::{VmfError, VmfResult},
VmfBlock, VmfSerializable,
};
use derive_more::{Deref, DerefMut, IntoIterator};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use super::common::Editor;
use super::world::Solid;
/// Represents an entity in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
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,
/// Indicates if the entity is hidden within the editor. This field
/// is primarily used when parsing a `hidden` block within a VMF file,
/// and is not serialized back when writing the VMF.
#[serde(default, skip_serializing)]
pub is_hidden: bool,
}
impl Entity {
/// Creates a new `Entity` with the specified classname and ID.
///
/// # Arguments
///
/// * `classname` - The classname of the entity (e.g., "func_detail", "info_player_start").
/// * `id` - The unique ID of the entity.
///
/// # Example
///
/// ```
/// use vmf_forge::prelude::*;
///
/// let entity = Entity::new("info_player_start", 1);
/// assert_eq!(entity.classname(), Some("info_player_start"));
/// assert_eq!(entity.id(), 1);
/// ```
pub fn new(classname: impl Into<String>, id: u64) -> Self {
let mut key_values = IndexMap::new();
key_values.insert("classname".to_string(), classname.into());
key_values.insert("id".to_string(), id.to_string());
Entity {
key_values,
connections: None,
solids: None,
editor: Editor::default(),
is_hidden: false,
}
}
/// Sets a key-value pair for the entity. If the key already exists,
/// its value is updated.
///
/// # Arguments
///
/// * `key` - The key to set.
/// * `value` - The value to set for the key.
pub fn set(&mut self, key: String, value: String) {
self.key_values.insert(key, value);
}
/// Removes a key-value pair from the entity, preserving the order of other keys.
///
/// # Arguments
///
/// * `key` - The key to remove.
///
/// # Returns
///
/// An `Option` containing the removed value, if the key was present.
pub fn remove_key(&mut self, key: &str) -> Option<String> {
self.key_values.shift_remove(key)
}
/// Removes a key-value pair from the entity, potentially changing the order of other keys.
/// This is faster than `remove_key` but does not preserve insertion order.
///
/// # Arguments
///
/// * `key` - The key to remove.
///
/// # Returns
///
/// An `Option` containing the removed value, if the key was present.
pub fn swap_remove_key(&mut self, key: &str) -> Option<String> {
self.key_values.swap_remove(key)
}
/// Gets the value associated with the given key.
///
/// # Arguments
///
/// * `key` - The key to get the value for.
///
/// # Returns
///
/// An `Option` containing a reference to the value, if the key is present.
pub fn get(&self, key: &str) -> Option<&String> {
self.key_values.get(key)
}
/// Gets a mutable reference to the value associated with the given key.
///
/// # Arguments
///
/// * `key` - The key to get the value for.
///
/// # Returns
///
/// An `Option` containing a mutable reference to the value, if the key is present.
pub fn get_mut(&mut self, key: &str) -> Option<&mut String> {
self.key_values.get_mut(key)
}
/// Returns the classname of the entity.
///
/// # Returns
///
/// An `Option` containing the classname, if it exists.
pub fn classname(&self) -> Option<&str> {
self.key_values.get("classname").map(|s| s.as_str())
}
/// Returns the targetname of the entity.
///
/// # Returns
///
/// An `Option` containing the targetname, if it exists.
pub fn targetname(&self) -> Option<&str> {
self.key_values.get("targetname").map(|s| s.as_str())
}
/// Returns the ID of the entity.
pub fn id(&self) -> u64 {
self.key_values
.get("id")
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0)
}
/// Returns the model of the entity.
///
/// # Returns
///
/// An `Option` containing the model path, if it exists.
pub fn model(&self) -> Option<&str> {
self.key_values.get("model").map(|s| s.as_str())
}
/// Adds an output connection to the entity.
///
/// # Arguments
///
/// * `output` - The name of the output on this entity.
/// * `target_entity` - The targetname of the entity to connect to.
/// * `input` - The name of the input on the target entity.
/// * `parms` - The parameters to pass to the input.
/// * `delay` - The delay before the input is triggered, in seconds.
/// * `fire_limit` - The number of times the output can be fired (-1 for unlimited).
///
/// # Example
///
/// ```
/// use vmf_forge::prelude::*;
///
/// let mut entity = Entity::new("logic_relay", 1);
/// entity.add_connection("OnTrigger", "my_door", "Open", "", 0.0, -1);
/// ```
pub fn add_connection(
&mut self,
output: impl Into<String>,
target_entity: impl AsRef<str>,
input: impl AsRef<str>,
parms: impl AsRef<str>,
delay: f32,
fire_limit: i32,
) {
let input_result = format!(
"{}\x1B{}\x1B{}\x1B{}\x1B{}",
target_entity.as_ref(),
input.as_ref(),
parms.as_ref(),
delay,
fire_limit
);
if let Some(connections) = &mut self.connections {
connections.push((output.into(), input_result));
} else {
self.connections = Some(vec![(output.into(), input_result)]);
}
}
/// Removes all connections from this entity.
pub fn clear_connections(&mut self) {
self.connections = None;
}
/// Checks if a specific connection exists.
///
/// # Arguments
/// * `output` The output to check
/// * `input` The input to check
///
/// # Returns
/// * `true` if the connection exists, `false` otherwise.
pub fn has_connection(&self, output: &str, input: &str) -> bool {
if let Some(connections) = &self.connections {
connections.iter().any(|(o, i)| o == output && i == input)
} else {
false
}
}
}
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 = process_connections(block.key_values),
"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())?)
}
}
_ => {
#[cfg(feature = "debug_assert_info")]
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 From<Entity> for VmfBlock {
fn from(val: Entity) -> Self {
let editor = val.editor.into();
VmfBlock {
name: "entity".to_string(),
key_values: val.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));
}
// Solids block
if let Some(solids) = &self.solids {
for solid in solids {
output.push_str(&solid.to_vmf_string(indent_level + 1));
}
}
// 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, PartialEq, Deref, DerefMut, IntoIterator,
)]
pub struct Entities {
/// The vector of entities.
pub vec: Vec<Entity>,
}
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).is_some_and(|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).is_some_and(|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)
}
/// Removes an entity by its ID.
///
/// # Arguments
///
/// * `entity_id` - The ID of the entity to remove.
///
/// # Returns
///
/// An `Option` containing the removed `Entity`, if found. Returns `None`
/// if no entity with the given ID exists.
pub fn remove_entity(&mut self, entity_id: i32) -> Option<Entity> {
if let Some(index) = self
.vec
.iter()
.position(|e| e.key_values.get("id") == Some(&entity_id.to_string()))
{
Some(self.vec.remove(index))
} else {
None
}
}
/// Removes all entities that have a matching key-value pair.
///
/// # Arguments
///
/// * `key` - The key to check.
/// * `value` - The value to compare against.
pub fn remove_by_keyvalue(&mut self, key: &str, value: &str) {
self.vec
.retain(|ent| ent.key_values.get(key).map(|v| v != value).unwrap_or(true));
}
}
// utils func
fn process_connections(map: IndexMap<String, String>) -> Option<Vec<(String, String)>> {
if map.is_empty() {
return None;
}
let result = map
.iter()
.flat_map(|(key, value)| {
value
.split('\r')
.map(move |part| (key.clone(), part.to_string()))
})
.collect();
Some(result)
}