1use std::{
2 fs::{self, File},
3 io::{Read, Write},
4 path::Path,
5 str::FromStr,
6};
7
8use crate::{VmfBlock, VmfError, VmfResult, VmfSerializable, parser};
9#[cfg(feature = "serialization")]
10use serde::{Deserialize, Serialize};
11
12use super::entities::{Entities, Entity};
13use super::metadata::{VersionInfo, ViewSettings, VisGroups};
14use super::regions::{Cameras, Cordons};
15use super::world::{Solid, World};
16
17#[derive(Debug, Clone, PartialEq)]
19#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
20pub struct VmfFile {
21 #[cfg_attr(
23 feature = "serialization",
24 serde(default, skip_serializing_if = "Option::is_none")
25 )]
26 pub path: Option<String>,
27 pub versioninfo: VersionInfo,
29 pub visgroups: VisGroups,
31 pub viewsettings: ViewSettings,
33 pub world: World,
35 pub entities: Entities,
37 pub hiddens: Entities,
39 pub cameras: Cameras,
41 pub cordons: Cordons,
43 #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Vec::is_empty"))]
46 pub extra_blocks: Vec<VmfBlock>,
47 #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Vec::is_empty"))]
49 pub warnings: Vec<String>,
50 #[cfg_attr(feature = "serialization", serde(default))]
52 pub suppressed_warnings: usize,
53}
54
55impl Default for VmfFile {
56 fn default() -> Self {
57 Self {
58 path: None,
59 versioninfo: Default::default(),
60 visgroups: Default::default(),
61 viewsettings: Default::default(),
62 world: Default::default(),
63 entities: Entities(Vec::with_capacity(128)),
64 hiddens: Entities(Vec::with_capacity(16)),
65 cameras: Default::default(),
66 cordons: Default::default(),
67 extra_blocks: Vec::new(),
68 warnings: Vec::new(),
69 suppressed_warnings: 0,
70 }
71 }
72}
73
74impl VmfFile {
75 pub fn to_vmf_string(&self) -> String {
77 let mut output = String::new();
78
79 output.push_str(&self.versioninfo.to_vmf_string(0));
81 output.push_str(&self.visgroups.to_vmf_string(0));
82 output.push_str(&self.viewsettings.to_vmf_string(0));
83 output.push_str(&self.world.to_vmf_string(0));
84
85 for entity in &*self.entities {
87 output.push_str(&entity.to_vmf_string(0));
88 }
89
90 for entity in &*self.hiddens {
91 output.push_str("hidden\n{\n");
92 output.push_str(&entity.to_vmf_string(1));
93 output.push_str("}\n");
94 }
95
96 output.push_str(&self.cameras.to_vmf_string(0));
98 output.push_str(&self.cordons.to_vmf_string(0));
99
100 for block in &self.extra_blocks {
101 output.push_str(&block.serialize(0));
102 }
103
104 output
105 }
106
107 pub fn parse(content: &str) -> VmfResult<Self> {
129 parser::parse_vmf(content)
130 }
131
132 pub fn open(path: impl AsRef<Path>) -> VmfResult<Self> {
143 let path_str = path.as_ref().to_string_lossy().to_string();
144 let mut file = File::open(path)?;
145 let mut content = Vec::new();
146 file.read_to_end(&mut content)?;
147 let content = String::from_utf8_lossy(&content);
148
149 let mut vmf_file = VmfFile::parse(&content)?;
150 vmf_file.path = Some(path_str);
151 Ok(vmf_file)
152 }
153
154 pub fn save(&self, path: impl AsRef<Path>) -> VmfResult<()> {
168 let path = path.as_ref();
169
170 let mut name = path.file_name().unwrap_or_default().to_os_string();
171 name.push(".part");
172 let partial = path.with_file_name(name);
173
174 if let Err(e) = self.write_to(&partial) {
175 let _ = fs::remove_file(&partial);
176 return Err(e.into());
177 }
178 fs::rename(&partial, path)?;
179 Ok(())
180 }
181
182 fn write_to(&self, path: &Path) -> std::io::Result<()> {
183 let mut file = File::create(path)?;
184 file.write_all(self.to_vmf_string().as_bytes())?;
185 file.sync_all()
186 }
187
188 pub fn merge(&mut self, other: Self) {
204 self.visgroups.groups.extend(other.visgroups.groups);
205 self.world.solids.extend(other.world.solids);
206 self.world.hidden.extend(other.world.hidden);
207
208 self.entities.extend(other.entities);
209 self.hiddens.extend(other.hiddens);
210
211 self.cordons.extend(other.cordons.cordons);
212 }
213
214 pub fn get_entities_in_visgroup(
216 &self,
217 group_id: i32,
218 include_children: bool,
219 ) -> Option<impl Iterator<Item = &Entity> + '_> {
220 let ids = self.visgroups.resolve_ids(group_id, include_children)?;
221 Some(
222 self.iter_entities()
223 .map(|(_, entity)| entity)
224 .filter(move |entity| {
225 entity
226 .editor
227 .visgroup_ids
228 .iter()
229 .any(|ent_group_id| ids.contains(ent_group_id))
230 }),
231 )
232 }
233
234 pub fn get_entities_in_visgroup_mut(
236 &mut self,
237 group_id: i32,
238 include_children: bool,
239 ) -> Option<impl Iterator<Item = &mut Entity> + '_> {
240 let ids = self.visgroups.resolve_ids(group_id, include_children)?;
241 Some(
242 self.entities
243 .iter_mut()
244 .chain(self.hiddens.iter_mut())
245 .filter(move |entity| {
246 entity
247 .editor
248 .visgroup_ids
249 .iter()
250 .any(|ent_group_id| ids.contains(ent_group_id))
251 }),
252 )
253 }
254
255 pub fn get_solids_in_visgroup(
257 &self,
258 group_id: i32,
259 include_children: bool,
260 ) -> Option<impl Iterator<Item = &Solid> + '_> {
261 let ids = self.visgroups.resolve_ids(group_id, include_children)?;
262 Some(
263 self.world
264 .iter_solids()
265 .filter(move |solid| {
266 solid
267 .editor
268 .visgroup_ids
269 .iter()
270 .any(|solid_group_id| ids.contains(solid_group_id))
271 }),
272 )
273 }
274
275 pub fn get_solids_in_visgroup_mut(
277 &mut self,
278 group_id: i32,
279 include_children: bool,
280 ) -> Option<impl Iterator<Item = &mut Solid> + '_> {
281 let ids = self.visgroups.resolve_ids(group_id, include_children)?;
282 Some(
283 self.world
284 .iter_solids_mut()
285 .filter(move |solid| {
286 solid
287 .editor
288 .visgroup_ids
289 .iter()
290 .any(|solid_group_id| ids.contains(solid_group_id))
291 }),
292 )
293 }
294}
295
296impl FromStr for VmfFile {
297 type Err = VmfError;
298
299 fn from_str(s: &str) -> Result<Self, Self::Err> {
300 VmfFile::parse(s)
301 }
302}