Skip to main content

source_vmf/
system.rs

1//! A map together with every VMF its `func_instance`s pull in.
2//! It might be a bit of overkill, and I couldn't come up with a cleaner API.. but having this functionality is still useful
3
4use std::path::{Path, PathBuf};
5
6use crate::transform::Transform;
7use crate::vmf::entities::Entity;
8use crate::vmf::world::World;
9use crate::{EntId, VmfFile, VmfResult};
10
11/// One `func_instance` on the assembled map, nested ones included
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct Instance {
14    /// Index into [`VmfSystem::files`] of the VMF this instance places
15    pub file: usize,
16    /// Who placed this one: the parent instance (index into [`VmfSystem::instances`]) and the `func_instance`'s id in the parent's file.
17    /// `None` for the root map
18    pub parent: Option<(usize, EntId)>,
19    /// From the space of `file` to world space, through every parent
20    pub transform: Transform,
21}
22
23/// A map and every VMF its `func_instance`s pull in, each file loaded once
24///
25/// A file placed ten times is one entry in [`files`](Self::files) and ten in [`instances`](Self::instances):
26/// edits go to the file, world positions come from the instances
27///
28/// ```no_run
29/// use source_vmf::prelude::*;
30///
31/// let map = VmfSystem::open("maps/my_map.vmf")?;
32/// for inst in &map.instances {
33///     for ent in map.files[inst.file].entities.iter() {
34///         if ent.classname() == Some("light") {
35///             let [x, y, z] = inst.transform.point(Transform::from_entity(ent).origin);
36///             println!("light at {x} {y} {z}");
37///         }
38///     }
39/// }
40/// # Ok::<(), VmfError>(())
41/// ```
42#[derive(Debug)]
43pub struct VmfSystem {
44    /// `files[0]` is the root map. Never shrinks, so indices survive [`relink`](Self::relink).
45    /// Every [`VmfFile::path`] is canonical, that's the key files get deduplicated by
46    pub files: Vec<VmfFile>,
47    /// `instances[0]` is the root map. Parents always come before their children
48    pub instances: Vec<Instance>,
49    /// Searched after the placing VMF's directory and its `maps` directory, like gameinfo's `InstancePath`
50    pub search_dirs: Vec<PathBuf>,
51    /// Missing, unreadable and self-including instances found by the last [`relink`](Self::relink)
52    pub warnings: Vec<String>,
53}
54
55/// The whole map in world space, made by [`VmfSystem::flatten`]
56#[derive(Debug, Clone)]
57pub struct Flattened {
58    pub vmf: VmfFile,
59    /// Where each entity of `vmf.entities` came from: index into [`VmfSystem::instances`] and its id in that instance's file
60    pub sources: Vec<(usize, EntId)>,
61}
62
63impl VmfSystem {
64    /// Opens a map and every VMF its `func_instance`s pull in
65    pub fn open(path: impl AsRef<Path>) -> VmfResult<Self> {
66        Self::open_with(path, Vec::new())
67    }
68
69    /// Like [`open`](Self::open), also looking for instance files in `search_dirs`
70    pub fn open_with(path: impl AsRef<Path>, search_dirs: Vec<PathBuf>) -> VmfResult<Self> {
71        let root = VmfFile::open(path.as_ref().canonicalize()?)?;
72        let mut system = Self {
73            files: vec![root],
74            instances: Vec::new(),
75            search_dirs,
76            warnings: Vec::new(),
77        };
78        system.relink();
79        Ok(system)
80    }
81
82    /// Rebuilds [`instances`](Self::instances) from the visible `func_instance`s of the files, loading the files that are not loaded yet
83    ///
84    /// Call it after removing entities ([`EntId`] is a position) or editing a `func_instance`'s `file`, `origin` or `angles`
85    pub fn relink(&mut self) {
86        self.warnings.clear();
87        self.instances.clear();
88        self.instances.push(Instance {
89            file: 0,
90            parent: None,
91            transform: Transform::IDENTITY,
92        });
93
94        // `instances` doubles as the BFS queue, that's what keeps parents before their children
95        let mut current = 0;
96        while current < self.instances.len() {
97            let vmf = &self.files[self.instances[current].file];
98            let placer = vmf.path.clone().unwrap_or_default();
99            let dir = Path::new(&placer).parent().map(Path::to_path_buf);
100            let links: Vec<(u32, String, Transform)> = vmf
101                .entities
102                .iter()
103                .enumerate()
104                .filter(|(_, ent)| is_class(ent, "func_instance"))
105                .filter_map(|(idx, ent)| {
106                    Some((
107                        idx as u32,
108                        ent.get("file")?.clone(),
109                        Transform::from_entity(ent),
110                    ))
111                })
112                .collect();
113
114            for (idx, name, local) in links {
115                let Some(file) = self.load(&name, dir.as_deref(), &placer) else {
116                    continue;
117                };
118                if self.chain(current).any(|i| self.instances[i].file == file) {
119                    self.warnings
120                        .push(format!("{placer}: instance '{name}' includes itself"));
121                    continue;
122                }
123                let transform = self.instances[current].transform * local;
124                self.instances.push(Instance {
125                    file,
126                    parent: Some((current, EntId { hidden: false, idx })),
127                    transform,
128                });
129            }
130            current += 1;
131        }
132    }
133
134    /// `instance` followed by its parents up to the root map
135    pub fn chain(&self, instance: usize) -> impl Iterator<Item = usize> {
136        std::iter::successors(Some(instance), |&i| {
137            self.instances[i].parent.map(|(parent, _)| parent)
138        })
139    }
140
141    /// Every entity of every file, hidden ones included like [`VmfFile::iter_entities`].
142    /// A file placed ten times is still visited once
143    pub fn iter_entities(&self) -> impl Iterator<Item = (usize, EntId, &Entity)> {
144        self.files
145            .iter()
146            .enumerate()
147            .flat_map(|(file, vmf)| vmf.iter_entities().map(move |(id, ent)| (file, id, ent)))
148    }
149
150    /// Mutable [`iter_entities`](Self::iter_entities)
151    pub fn iter_entities_mut(&mut self) -> impl Iterator<Item = (usize, EntId, &mut Entity)> {
152        self.files.iter_mut().enumerate().flat_map(|(file, vmf)| {
153            vmf.iter_entities_mut()
154                .map(move |(id, ent)| (file, id, ent))
155        })
156    }
157
158    /// Merges the root and every placed instance into one map in world space
159    ///
160    /// Brushes and entities go through [`Transform::apply_solid`] and [`Transform::apply_entity`].
161    /// `func_instance` and `func_instance_parms` are dropped and hidden objects are left out, like VBSP does.
162    /// Names, `$replace` variables, ids and editor data are not fixed up, they stay as they are in their files
163    pub fn flatten(&self) -> Flattened {
164        let root = &self.files[0];
165        
166        // not root.clone(): that copies every root brush and entity only to throw them out right after
167        let mut vmf = VmfFile {
168            // no path, so the flattened map can't get saved over the real root by accident
169            path: None,
170            versioninfo: root.versioninfo.clone(),
171            visgroups: root.visgroups.clone(),
172            viewsettings: root.viewsettings.clone(),
173            world: World {
174                key_values: root.world.key_values.clone(),
175                groups: root.world.groups.clone(),
176                extra: root.world.extra.clone(),
177                ..Default::default()
178            },
179            cameras: root.cameras.clone(),
180            cordons: root.cordons.clone(),
181            extra_blocks: root.extra_blocks.clone(),
182            ..Default::default()
183        };
184
185        let mut sources = Vec::new();
186        for (index, inst) in self.instances.iter().enumerate() {
187            let file = &self.files[inst.file];
188            
189            for solid in &file.world.solids {
190                let mut solid = solid.clone();
191                inst.transform.apply_solid(&mut solid);
192                vmf.world.solids.push(solid);
193            }
194
195            for (idx, ent) in file.entities.iter().enumerate() {
196                if is_class(ent, "func_instance") || is_class(ent, "func_instance_parms") {
197                    continue;
198                }
199                let mut ent = ent.clone();
200                inst.transform.apply_entity(&mut ent);
201                vmf.entities.push(ent);
202                sources.push((index, EntId { hidden: false, idx: idx as u32 }));
203            }
204        }
205
206        Flattened { vmf, sources }
207    }
208
209    /// Writes EVERY FILE back to the path it was loaded from
210    pub fn save(&self) -> VmfResult<()> {
211        for vmf in &self.files {
212            if let Some(path) = &vmf.path {
213                vmf.save(path)?;
214            }
215        }
216
217        Ok(())
218    }
219
220    /// Resolves an instance's `file` key and returns its index in `files`, loading it if needed
221    fn load(&mut self, name: &str, dir: Option<&Path>, placer: &str) -> Option<usize> {
222        if name.trim().is_empty() {
223            return None;
224        }
225
226        let Some(path) = resolve(name, dir, &self.search_dirs) else {
227            self.warnings
228                .push(format!("{placer}: instance '{name}' not found"));
229            return None;
230        };
231        let loaded = self
232            .files
233            .iter()
234            .position(|vmf| vmf.path.as_deref().map(Path::new) == Some(path.as_path()));
235        
236            if loaded.is_some() {
237            return loaded;
238        }
239
240        match VmfFile::open(&path) {
241            Ok(vmf) => {
242                self.files.push(vmf);
243                Some(self.files.len() - 1)
244            }
245            Err(err) => {
246                self.warnings
247                    .push(format!("{placer}: instance '{}': {err}", path.display()));
248                None
249            }
250        }
251    }
252}
253
254fn is_class(ent: &Entity, class: &str) -> bool {
255    ent.classname()
256        .is_some_and(|name| name.eq_ignore_ascii_case(class))
257}
258
259/// Search order of `CInstancingHelper::ResolveInstancePath`: next to the VMF that places the instance,
260/// then under the outermost `maps` directory above that VMF, then `search_dirs`
261// todo: case-sens and shit like this - check & improve
262fn resolve(name: &str, dir: Option<&Path>, search_dirs: &[PathBuf]) -> Option<PathBuf> {
263    let mut relative = PathBuf::from(name.trim().replace('\\', "/"));
264    relative.set_extension("vmf");
265    let maps = dir.and_then(|dir| {
266        dir.ancestors()
267            .filter(|dir| {
268                dir.file_name()
269                    .is_some_and(|name| name.eq_ignore_ascii_case("maps"))
270            })
271            .last()
272    });
273    dir.into_iter()
274        .chain(maps)
275        .chain(search_dirs.iter().map(PathBuf::as_path))
276        .map(|base| base.join(&relative))
277        .find(|candidate| candidate.is_file())?
278        .canonicalize()
279        .ok()
280}