Skip to main content

source_vmf/vmf/
connection.rs

1//! Entity IO: the connections that wire outputs to inputs.
2//!
3//! A connection is one line inside an entity's `connections` block:
4//! `"OnTrigger" "target<S>input<S>params<S>delay<S>fire_limit"`
5//! `<S>` is ESC (`\x1b`) in Source and in Hammer, and a comma in (old???) Hammer++.
6
7use indexmap::IndexMap;
8use indexmap::map::Entry;
9#[cfg(feature = "serialization")]
10use serde::{Deserialize, Serialize};
11
12/// The field separator Source and Hammer use.
13const SEP_ESC: char = '\x1b';
14
15/// Separator for multiple connections sharing one output name in a single KeyValues entry
16const MULTI_SEP: char = '\r';
17/// The field separator used by Hammer++
18const SEP_COMMA: char = ',';
19
20/// Prefix of the `instance:<proxy>;<io>` addressing form.
21const INSTANCE_PREFIX: &str = "instance:";
22
23/// Represents a connection between entities.
24#[derive(Debug, Clone, PartialEq)]
25#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
26pub struct Connection {
27    pub output: String,
28    pub target: String,
29    pub input: String,
30    pub params: String,
31    pub delay: f32,
32    pub fire_limit: i32,
33}
34
35impl Connection {
36    /// Parses a connection string value.
37    ///
38    /// # Arguments
39    /// * `output` - The name of the output (e.g. "OnTrigger").
40    /// * `value` - The value string from VMF (e.g. "target,input,params,0.0,-1").
41    pub fn parse(output: String, value: &str) -> Self {
42        // ESC delimiter takes precedence over comma when present.
43        let sep = if value.contains(SEP_ESC) {
44            SEP_ESC
45        } else {
46            SEP_COMMA
47        };
48
49        let mut head = value.splitn(3, sep);
50        let target = head.next().unwrap_or("");
51        let input = head.next().unwrap_or("");
52        let rest = head.next().unwrap_or("");
53
54        // Extract delay and fire_limit from the end; remaining text is assigned to params.
55        let mut tail = rest.rsplitn(3, sep);
56        let last = tail.next().unwrap_or("");
57        let mid = tail.next().unwrap_or("");
58        let (params, delay, fire_limit) = match tail.next() {
59            Some(params) => (params, mid, last),
60            None => (rest, "", ""),
61        };
62
63        Connection {
64            output,
65            target: target.to_string(),
66            input: input.to_string(),
67            params: params.to_string(),
68            delay: delay.parse().unwrap_or(0.0),
69            fire_limit: fire_limit.parse().unwrap_or(-1),
70        }
71    }
72
73    /// Formats the connection value for VMF, always with the ESC separator.
74    pub fn to_value_string(&self) -> String {
75        format!(
76            "{}{sep}{}{sep}{}{sep}{}{sep}{}",
77            self.target,
78            self.input,
79            self.params,
80            self.delay,
81            self.fire_limit,
82            sep = SEP_ESC
83        )
84    }
85
86    /// Classifies how [`Connection::target`] addresses its destination.
87    pub fn target_kind(&self) -> Target<'_> {
88        Target::parse(&self.target)
89    }
90
91    /// Reads [`Connection::input`] as `instance:<proxy>;<io>`, if it is one.
92    pub fn instance_input(&self) -> Option<InstanceIo<'_>> {
93        InstanceIo::parse(&self.input)
94    }
95
96    /// Reads [`Connection::output`] as `instance:<proxy>;<io>`, if it is one.
97    pub fn instance_output(&self) -> Option<InstanceIo<'_>> {
98        InstanceIo::parse(&self.output)
99    }
100
101    /// Rewrites [`Connection::input`] to address an entity inside an instance.
102    pub fn set_instance_input(&mut self, proxy: &str, io: &str) {
103        self.input = format!("{INSTANCE_PREFIX}{proxy};{io}");
104    }
105
106    /// Rewrites [`Connection::output`] to address an entity inside an instance.
107    pub fn set_instance_output(&mut self, proxy: &str, io: &str) {
108        self.output = format!("{INSTANCE_PREFIX}{proxy};{io}");
109    }
110
111    /// Deserializes a list of [`Connection`]s from a `connections` block key-value map.
112    pub fn from_key_values(map: &IndexMap<String, String>) -> Option<Vec<Self>> {
113        if map.is_empty() {
114            return None;
115        }
116
117        let mut result = Vec::with_capacity(map.len() * 2);
118        for (key, value) in map {
119            for part in value.split(MULTI_SEP) {
120                result.push(Connection::parse(key.clone(), part));
121            }
122        }
123        Some(result)
124    }
125
126    /// Serializes a list of [`Connection`]s into a `connections` block key-value map.
127    pub fn to_key_values(connections: &[Self]) -> IndexMap<String, String> {
128        let mut map = IndexMap::with_capacity(connections.len());
129        for conn in connections {
130            match map.entry(conn.output.clone()) {
131                Entry::Occupied(mut slot) => {
132                    let joined: &mut String = slot.get_mut();
133                    joined.push(MULTI_SEP);
134                    joined.push_str(&conn.to_value_string());
135                }
136                Entry::Vacant(slot) => {
137                    slot.insert(conn.to_value_string());
138                }
139            }
140        }
141        map
142    }
143}
144
145/// A `!`-prefixed target the engine resolves at runtime instead of by name.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Special<'a> {
148    /// `!self` - the entity holding the output.
149    SelfEnt,
150    /// `!activator` - whatever triggered the chain.
151    Activator,
152    /// `!caller` - the entity that fired the output.
153    Caller,
154    /// `!player` - the first player.
155    Player,
156    /// `!pvsplayer` - the player whose PVS contains the caller.
157    PvsPlayer,
158    /// `!picker` - the entity under the player's crosshair.
159    Picker,
160    /// Any other unmapped `!` target.
161    Other(&'a str),
162}
163
164/// How a connection's `target` string addresses its destination.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum Target<'a> {
167    /// A plain targetname. Not unique: several entities may share one.
168    Name(&'a str),
169    /// A trailing-`*` prefix match, e.g. `door_*` yields `door_`.
170    /// A bare `*` yields an empty prefix and matches every named entity.
171    Wildcard(&'a str),
172    /// A runtime-resolved `!` target.
173    Special(Special<'a>),
174}
175
176impl<'a> Target<'a> {
177    /// Classifies a raw target string. Borrows, never allocates.
178    pub fn parse(target: &'a str) -> Self {
179        if let Some(tag) = target.strip_prefix('!') {
180            let special = if tag.eq_ignore_ascii_case("self") {
181                Special::SelfEnt
182            } else if tag.eq_ignore_ascii_case("activator") {
183                Special::Activator
184            } else if tag.eq_ignore_ascii_case("caller") {
185                Special::Caller
186            } else if tag.eq_ignore_ascii_case("player") {
187                Special::Player
188            } else if tag.eq_ignore_ascii_case("pvsplayer") {
189                Special::PvsPlayer
190            } else if tag.eq_ignore_ascii_case("picker") {
191                Special::Picker
192            } else {
193                Special::Other(tag)
194            };
195            return Target::Special(special);
196        }
197
198        match target.strip_suffix('*') {
199            Some(prefix) => Target::Wildcard(prefix),
200            None => Target::Name(target),
201        }
202    }
203
204    /// The plain name, if this target is one. `None` for wildcards and `!` targets.
205    pub fn name(&self) -> Option<&'a str> {
206        match self {
207            Target::Name(name) => Some(name),
208            _ => None,
209        }
210    }
211}
212
213/// The `instance:<proxy>;<io>` form, used to address IO across a `func_instance`
214/// boundary. Applies to both input and output names.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct InstanceIo<'a> {
217    /// Name of the entity inside the instance, or of the io proxy exposing it.
218    pub proxy: &'a str,
219    /// The real input or output name on that entity.
220    pub io: &'a str,
221}
222
223impl<'a> InstanceIo<'a> {
224    /// Parses `instance:<proxy>;<io>`. Returns `None` for a plain IO name.
225    pub fn parse(value: &'a str) -> Option<Self> {
226        let head = value.get(..INSTANCE_PREFIX.len())?;
227        if !head.eq_ignore_ascii_case(INSTANCE_PREFIX) {
228            return None;
229        }
230        let (proxy, io) = value[INSTANCE_PREFIX.len()..].split_once(';')?;
231        Some(InstanceIo { proxy, io })
232    }
233}
234
235impl std::fmt::Display for InstanceIo<'_> {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        write!(f, "{INSTANCE_PREFIX}{};{}", self.proxy, self.io)
238    }
239}