Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ObjectBase.h"
21 :
22 : #include "graphics/ObjectManager.h"
23 : #include "lib/debug.h"
24 : #include "maths/MathUtil.h"
25 : #include "ps/CLogger.h"
26 : #include "ps/Errors.h"
27 : #include "ps/Filesystem.h"
28 : #include "ps/XMB/XMBData.h"
29 : #include "ps/XMB/XMBStorage.h"
30 : #include "ps/XML/Xeromyces.h"
31 :
32 : #include <algorithm>
33 : #include <cstddef>
34 : #include <queue>
35 : #include <string>
36 : #include <utility>
37 :
38 : namespace
39 : {
40 : /**
41 : * The maximal quality for an actor.
42 : */
43 : static constexpr int MAX_QUALITY = 255;
44 :
45 : /**
46 : * How many quality levels a given actor can have.
47 : */
48 : static constexpr int MAX_LEVELS_PER_ACTOR_DEF = 5;
49 :
50 0 : int GetQuality(const CStr& value)
51 : {
52 0 : if (value == "low")
53 : return 100;
54 0 : else if (value == "medium")
55 : return 150;
56 0 : else if (value == "high")
57 : return 200;
58 : else
59 0 : return value.ToInt();
60 : }
61 : } // anonymous namespace
62 :
63 1 : CObjectBase::CObjectBase(CObjectManager& objectManager, CActorDef& actorDef, std::uint8_t qualityLevel)
64 1 : : m_ObjectManager(objectManager), m_ActorDef(actorDef)
65 : {
66 1 : m_QualityLevel = qualityLevel;
67 1 : m_Properties.m_AnchorType = "";
68 1 : m_Properties.m_CastShadows = false;
69 1 : m_Properties.m_FloatOnWater = false;
70 :
71 : // Remove leading art/actors/ & include quality level.
72 5 : m_Identifier = fmt::format("{}{}", m_ActorDef.m_Pathname.string8().substr(11), m_QualityLevel);
73 1 : }
74 :
75 0 : std::unique_ptr<CObjectBase> CObjectBase::CopyWithQuality(std::uint8_t newQualityLevel) const
76 : {
77 0 : std::unique_ptr<CObjectBase> ret = std::make_unique<CObjectBase>(m_ObjectManager, m_ActorDef, newQualityLevel);
78 : // No need to actually change any quality-related stuff here, we assume that this is a copy for props.
79 0 : ret->m_VariantGroups = m_VariantGroups;
80 0 : ret->m_Material = m_Material;
81 0 : ret->m_Properties = m_Properties;
82 0 : return ret;
83 0 : }
84 :
85 1 : bool CObjectBase::Load(const CXeromyces& XeroFile, const XMBElement& root)
86 : {
87 : // Define all the elements used in the XML file
88 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
89 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
90 1 : EL(anchor);
91 1 : EL(castshadow);
92 1 : EL(float);
93 1 : EL(group);
94 1 : EL(material);
95 1 : AT(maxquality);
96 1 : AT(minquality);
97 : #undef AT
98 : #undef EL
99 :
100 :
101 : // Set up the group vector to avoid reallocation and copying later.
102 1 : {
103 1 : int groups = 0;
104 6 : for (XMBElement child : root.GetChildNodes())
105 : {
106 2 : if (child.GetNodeName() == el_group)
107 1 : ++groups;
108 : }
109 :
110 1 : m_VariantGroups.reserve(groups);
111 : }
112 :
113 : // (This XML-reading code is rather worryingly verbose...)
114 :
115 4 : auto shouldSkip = [&](XMBElement& node) {
116 6 : for (XMBAttribute attr : node.GetAttributes())
117 : {
118 0 : if (attr.Name == at_minquality && GetQuality(attr.Value) > m_QualityLevel)
119 : return true;
120 0 : else if (attr.Name == at_maxquality && GetQuality(attr.Value) <= m_QualityLevel)
121 : return true;
122 0 : }
123 3 : return false;
124 1 : };
125 :
126 6 : for (XMBElement child : root.GetChildNodes())
127 : {
128 2 : int child_name = child.GetNodeName();
129 :
130 2 : if (shouldSkip(child))
131 0 : continue;
132 :
133 2 : if (child_name == el_group)
134 : {
135 1 : std::vector<Variant>& currentGroup = m_VariantGroups.emplace_back();
136 1 : currentGroup.reserve(child.GetChildNodes().size());
137 4 : for (XMBElement variant : child.GetChildNodes())
138 : {
139 1 : if (shouldSkip(variant))
140 0 : continue;
141 :
142 1 : if (!LoadVariant(XeroFile, variant, currentGroup.emplace_back()))
143 0 : return false;
144 : }
145 :
146 1 : if (currentGroup.size() == 0)
147 : {
148 0 : LOGERROR("Actor group has zero variants ('{}')", m_Identifier);
149 0 : return false;
150 : }
151 : }
152 1 : else if (child_name == el_anchor)
153 0 : m_Properties.m_AnchorType = child.GetText();
154 1 : else if (child_name == el_castshadow)
155 1 : m_Properties.m_CastShadows = true;
156 0 : else if (child_name == el_float)
157 0 : m_Properties.m_FloatOnWater = true;
158 0 : else if (child_name == el_material)
159 0 : m_Material = VfsPath("art/materials") / child.GetText().FromUTF8();
160 : }
161 :
162 1 : if (m_Material.empty())
163 2 : m_Material = VfsPath("art/materials/default.xml");
164 :
165 : return true;
166 : }
167 :
168 1 : bool CObjectBase::LoadVariant(const CXeromyces& XeroFile, const XMBElement& variant, Variant& currentVariant)
169 : {
170 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
171 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
172 1 : EL(animation);
173 1 : EL(animations);
174 1 : EL(color);
175 1 : EL(decal);
176 1 : EL(mesh);
177 1 : EL(particles);
178 1 : EL(prop);
179 1 : EL(props);
180 1 : EL(texture);
181 1 : EL(textures);
182 1 : EL(variant);
183 1 : AT(actor);
184 1 : AT(angle);
185 1 : AT(attachpoint);
186 1 : AT(depth);
187 1 : AT(event);
188 1 : AT(file);
189 1 : AT(frequency);
190 1 : AT(id);
191 1 : AT(load);
192 1 : AT(maxheight);
193 1 : AT(minheight);
194 1 : AT(name);
195 1 : AT(offsetx);
196 1 : AT(offsetz);
197 1 : AT(selectable);
198 1 : AT(sound);
199 1 : AT(speed);
200 1 : AT(width);
201 : #undef AT
202 : #undef EL
203 :
204 1 : if (variant.GetNodeName() != el_variant)
205 : {
206 0 : LOGERROR("Invalid variant format (unrecognized root element '{}')",
207 : XeroFile.GetElementString(variant.GetNodeName()));
208 0 : return false;
209 : }
210 :
211 : // Load variants first, so that they can be overriden if necessary.
212 2 : for (XMBAttribute attr : variant.GetAttributes())
213 : {
214 0 : if (attr.Name == at_file)
215 : {
216 : // Open up an external file to load.
217 : // Don't crash hard when failures happen, but log them and continue
218 0 : m_ActorDef.m_UsedFiles.insert(attr.Value);
219 0 : CXeromyces XeroVariant;
220 0 : if (XeroVariant.Load(g_VFS, "art/variants/" + attr.Value) == PSRETURN_OK)
221 : {
222 0 : XMBElement variantRoot = XeroVariant.GetRoot();
223 0 : if (!LoadVariant(XeroVariant, variantRoot, currentVariant))
224 0 : return false;
225 : }
226 : else
227 : {
228 0 : LOGERROR("Could not open path {}", attr.Value);
229 0 : return false;
230 : }
231 : // Continue loading extra definitions in this variant to allow nested files
232 0 : }
233 0 : }
234 :
235 2 : for (XMBAttribute attr : variant.GetAttributes())
236 : {
237 0 : if (attr.Name == at_name)
238 0 : currentVariant.m_VariantName = attr.Value.LowerCase();
239 0 : else if (attr.Name == at_frequency)
240 0 : currentVariant.m_Frequency = attr.Value.ToInt();
241 0 : }
242 :
243 4 : for (XMBElement option : variant.GetChildNodes())
244 : {
245 1 : int option_name = option.GetNodeName();
246 :
247 1 : if (option_name == el_mesh)
248 : {
249 4 : currentVariant.m_ModelFilename = VfsPath("art/meshes") / option.GetText().FromUTF8();
250 : }
251 0 : else if (option_name == el_textures)
252 : {
253 0 : for (XMBElement textures_element : option.GetChildNodes())
254 : {
255 0 : if (textures_element.GetNodeName() != el_texture)
256 : {
257 0 : LOGERROR("<textures> can only contain <texture> elements.");
258 0 : return false;
259 : }
260 :
261 0 : Samp samp;
262 0 : for (XMBAttribute se : textures_element.GetAttributes())
263 : {
264 0 : if (se.Name == at_file)
265 0 : samp.m_SamplerFile = VfsPath("art/textures/skins") / se.Value.FromUTF8();
266 0 : else if (se.Name == at_name)
267 0 : samp.m_SamplerName = CStrIntern(se.Value);
268 0 : }
269 0 : currentVariant.m_Samplers.push_back(samp);
270 0 : }
271 : }
272 0 : else if (option_name == el_decal)
273 : {
274 0 : XMBAttributeList attrs = option.GetAttributes();
275 0 : Decal decal;
276 0 : decal.m_SizeX = attrs.GetNamedItem(at_width).ToFloat();
277 0 : decal.m_SizeZ = attrs.GetNamedItem(at_depth).ToFloat();
278 0 : decal.m_Angle = DEGTORAD(attrs.GetNamedItem(at_angle).ToFloat());
279 0 : decal.m_OffsetX = attrs.GetNamedItem(at_offsetx).ToFloat();
280 0 : decal.m_OffsetZ = attrs.GetNamedItem(at_offsetz).ToFloat();
281 0 : currentVariant.m_Decal = decal;
282 : }
283 0 : else if (option_name == el_particles)
284 : {
285 0 : XMBAttributeList attrs = option.GetAttributes();
286 0 : VfsPath file = VfsPath("art/particles") / attrs.GetNamedItem(at_file).FromUTF8();
287 0 : currentVariant.m_Particles = file;
288 :
289 : // For particle hotloading, it's easiest to reload the entire actor,
290 : // so remember the relevant particle file as a dependency for this actor
291 0 : m_ActorDef.m_UsedFiles.insert(file);
292 0 : }
293 0 : else if (option_name == el_color)
294 : {
295 0 : currentVariant.m_Color = option.GetText();
296 : }
297 0 : else if (option_name == el_animations)
298 : {
299 0 : for (XMBElement anim_element : option.GetChildNodes())
300 : {
301 0 : if (anim_element.GetNodeName() != el_animation)
302 : {
303 0 : LOGERROR("<animations> can only contain <animations> elements.");
304 0 : return false;
305 : }
306 :
307 0 : Anim anim;
308 0 : for (XMBAttribute ae : anim_element.GetAttributes())
309 : {
310 0 : if (ae.Name == at_name)
311 0 : anim.m_AnimName = ae.Value;
312 0 : else if (ae.Name == at_id)
313 0 : anim.m_ID = ae.Value;
314 0 : else if (ae.Name == at_frequency)
315 0 : anim.m_Frequency = ae.Value.ToInt();
316 0 : else if (ae.Name == at_file)
317 0 : anim.m_FileName = VfsPath("art/animation") / ae.Value.FromUTF8();
318 0 : else if (ae.Name == at_speed)
319 0 : anim.m_Speed = ae.Value.ToInt() > 0 ? ae.Value.ToInt() / 100.f : 1.f;
320 0 : else if (ae.Name == at_event)
321 0 : anim.m_ActionPos = Clamp(ae.Value.ToFloat(), 0.f, 1.f);
322 0 : else if (ae.Name == at_load)
323 0 : anim.m_ActionPos2 = Clamp(ae.Value.ToFloat(), 0.f, 1.f);
324 0 : else if (ae.Name == at_sound)
325 0 : anim.m_SoundPos = Clamp(ae.Value.ToFloat(), 0.f, 1.f);
326 0 : }
327 0 : currentVariant.m_Anims.push_back(anim);
328 0 : }
329 : }
330 0 : else if (option_name == el_props)
331 : {
332 0 : for (XMBElement prop_element : option.GetChildNodes())
333 : {
334 0 : ENSURE(prop_element.GetNodeName() == el_prop);
335 :
336 0 : Prop prop;
337 0 : for (XMBAttribute pe : prop_element.GetAttributes())
338 : {
339 0 : if (pe.Name == at_attachpoint)
340 0 : prop.m_PropPointName = pe.Value;
341 0 : else if (pe.Name == at_actor)
342 0 : prop.m_ModelName = pe.Value.FromUTF8();
343 0 : else if (pe.Name == at_minheight)
344 0 : prop.m_minHeight = pe.Value.ToFloat();
345 0 : else if (pe.Name == at_maxheight)
346 0 : prop.m_maxHeight = pe.Value.ToFloat();
347 0 : else if (pe.Name == at_selectable)
348 0 : prop.m_selectable = pe.Value != "false";
349 0 : }
350 0 : currentVariant.m_Props.push_back(prop);
351 : }
352 : }
353 : }
354 1 : return true;
355 : }
356 :
357 2 : std::vector<std::uint8_t> CObjectBase::CalculateVariationKey(
358 : const std::vector<const std::set<CStr>*>& selections) const
359 : {
360 : // (TODO: see CObjectManager::FindObjectVariation for an opportunity to
361 : // call this function a bit less frequently)
362 :
363 : // Calculate a complete list of choices, one per group, based on the
364 : // supposedly-complete selections (i.e. not making random choices at this
365 : // stage).
366 : // In each group, if one of the variants has a name matching a string in the
367 : // first 'selections', set use that one.
368 : // Otherwise, try with the next (lower priority) selections set, and repeat.
369 : // Otherwise, choose the first variant (arbitrarily).
370 :
371 2 : std::vector<std::uint8_t> choices;
372 :
373 2 : std::multimap<CStr, CStrW> chosenProps;
374 :
375 4 : for (std::vector<std::vector<CObjectBase::Variant> >::const_iterator grp = m_VariantGroups.begin();
376 4 : grp != m_VariantGroups.end();
377 4 : ++grp)
378 : {
379 : // Ignore groups with nothing inside. (A warning will have been
380 : // emitted by the loading code.)
381 2 : if (grp->size() == 0)
382 0 : continue;
383 :
384 2 : int match = -1; // -1 => none found yet
385 :
386 : // If there's only a single variant, choose that one
387 2 : if (grp->size() == 1)
388 : {
389 : match = 0;
390 : }
391 : else
392 : {
393 : // Determine the first variant that matches the provided strings,
394 : // starting with the highest priority selections set:
395 :
396 0 : for (const std::set<CStr>* selset : selections)
397 : {
398 0 : ENSURE(grp->size() < 256); // else they won't fit in 'choices'
399 :
400 0 : for (size_t i = 0; i < grp->size(); ++i)
401 : {
402 0 : if (selset->count((*grp)[i].m_VariantName))
403 : {
404 0 : match = static_cast<std::uint8_t>(i);
405 0 : break;
406 : }
407 : }
408 :
409 : // Stop after finding the first match
410 0 : if (match != -1)
411 : break;
412 : }
413 :
414 : // If no match, just choose the first
415 0 : if (match == -1)
416 2 : match = 0;
417 : }
418 :
419 2 : choices.push_back(match);
420 : // Remember which props were chosen, so we can call CalculateVariationKey on them
421 : // at the end.
422 : // Erase all existing props which are overridden by this variant:
423 2 : const Variant& var((*grp)[match]);
424 :
425 2 : for (const Prop& prop : var.m_Props)
426 0 : chosenProps.erase(prop.m_PropPointName);
427 : // and then insert the new ones:
428 2 : for (const Prop& prop : var.m_Props)
429 0 : if (!prop.m_ModelName.empty())
430 0 : chosenProps.insert(make_pair(prop.m_PropPointName, prop.m_ModelName));
431 : }
432 :
433 : // Load each prop, and add their CalculateVariationKey to our key:
434 2 : for (std::multimap<CStr, CStrW>::iterator it = chosenProps.begin(); it != chosenProps.end(); ++it)
435 : {
436 0 : if (auto [success, prop] = m_ObjectManager.FindActorDef(it->second); success)
437 : {
438 0 : std::vector<std::uint8_t> propChoices =
439 0 : prop.GetBase(m_QualityLevel)->CalculateVariationKey(selections);
440 0 : choices.insert(choices.end(), propChoices.begin(), propChoices.end());
441 0 : }
442 : }
443 :
444 2 : return choices;
445 2 : }
446 :
447 1 : const CObjectBase::Variation CObjectBase::BuildVariation(
448 : const std::vector<std::uint8_t>& variationKey) const
449 : {
450 1 : Variation variation;
451 :
452 : // variationKey should correspond with m_Variants, giving the id of the
453 : // chosen variant from each group. (Except variationKey has some bits stuck
454 : // on the end for props, but we don't care about those in here.)
455 :
456 1 : std::vector<std::vector<CObjectBase::Variant> >::const_iterator grp = m_VariantGroups.begin();
457 1 : std::vector<std::uint8_t>::const_iterator match = variationKey.begin();
458 1 : for ( ;
459 1 : grp != m_VariantGroups.end() && match != variationKey.end();
460 2 : ++grp, ++match)
461 : {
462 : // Ignore groups with nothing inside. (A warning will have been
463 : // emitted by the loading code.)
464 1 : if (grp->size() == 0)
465 0 : continue;
466 :
467 1 : size_t id = *match;
468 1 : if (id >= grp->size())
469 : {
470 : // This should be impossible
471 0 : debug_warn(L"BuildVariation: invalid variant id");
472 0 : continue;
473 0 : }
474 :
475 : // Get the matched variant
476 1 : const CObjectBase::Variant& var ((*grp)[id]);
477 :
478 : // Apply its data:
479 :
480 1 : if (! var.m_ModelFilename.empty())
481 1 : variation.model = var.m_ModelFilename;
482 :
483 1 : if (var.m_Decal.m_SizeX && var.m_Decal.m_SizeZ)
484 0 : variation.decal = var.m_Decal;
485 :
486 1 : if (! var.m_Particles.empty())
487 0 : variation.particles = var.m_Particles;
488 :
489 1 : if (! var.m_Color.empty())
490 0 : variation.color = var.m_Color;
491 :
492 : // If one variant defines one prop attached to e.g. "root", and this
493 : // variant defines two different props with the same attachpoint, the one
494 : // original should be erased, and replaced by the two new ones.
495 : //
496 : // So, erase all existing props which are overridden by this variant:
497 1 : for (std::vector<CObjectBase::Prop>::const_iterator it = var.m_Props.begin(); it != var.m_Props.end(); ++it)
498 0 : variation.props.erase(it->m_PropPointName);
499 : // and then insert the new ones:
500 1 : for (std::vector<CObjectBase::Prop>::const_iterator it = var.m_Props.begin(); it != var.m_Props.end(); ++it)
501 0 : if (! it->m_ModelName.empty()) // if the name is empty then the overridden prop is just deleted
502 0 : variation.props.insert(make_pair(it->m_PropPointName, *it));
503 :
504 : // Same idea applies for animations.
505 : // So, erase all existing animations which are overridden by this variant:
506 1 : for (std::vector<CObjectBase::Anim>::const_iterator it = var.m_Anims.begin(); it != var.m_Anims.end(); ++it)
507 0 : variation.anims.erase(it->m_AnimName);
508 : // and then insert the new ones:
509 1 : for (std::vector<CObjectBase::Anim>::const_iterator it = var.m_Anims.begin(); it != var.m_Anims.end(); ++it)
510 0 : variation.anims.insert(make_pair(it->m_AnimName, *it));
511 :
512 : // Same for samplers, though perhaps not strictly necessary:
513 1 : for (std::vector<CObjectBase::Samp>::const_iterator it = var.m_Samplers.begin(); it != var.m_Samplers.end(); ++it)
514 0 : variation.samplers.erase(it->m_SamplerName.string());
515 1 : for (std::vector<CObjectBase::Samp>::const_iterator it = var.m_Samplers.begin(); it != var.m_Samplers.end(); ++it)
516 0 : variation.samplers.insert(make_pair(it->m_SamplerName.string(), *it));
517 : }
518 :
519 1 : return variation;
520 0 : }
521 :
522 6 : std::set<CStr> CObjectBase::CalculateRandomRemainingSelections(uint32_t seed, const std::vector<std::set<CStr>>& initialSelections) const
523 : {
524 6 : rng_t rng;
525 6 : rng.seed(seed);
526 :
527 6 : std::set<CStr> remainingSelections = CalculateRandomRemainingSelections(rng, initialSelections);
528 14 : for (const std::set<CStr>& sel : initialSelections)
529 8 : remainingSelections.insert(sel.begin(), sel.end());
530 :
531 6 : return remainingSelections; // now actually a complete set of selections
532 0 : }
533 :
534 6 : std::set<CStr> CObjectBase::CalculateRandomRemainingSelections(rng_t& rng, const std::vector<std::set<CStr>>& initialSelections) const
535 : {
536 6 : std::set<CStr> remainingSelections;
537 6 : std::multimap<CStr, CStrW> chosenProps;
538 :
539 : // Calculate a complete list of selections, so there is at least one
540 : // (and in most cases only one) per group.
541 : // In each group, if one of the variants has a name matching a string in
542 : // 'selections', use that one.
543 : // If more than one matches, choose randomly from those matching ones.
544 : // If none match, choose randomly from all variants.
545 : //
546 : // When choosing randomly, make use of each variant's frequency. If all
547 : // variants have frequency 0, treat them as if they were 1.
548 :
549 6 : CObjectManager::VariantDiversity diversity = m_ObjectManager.GetVariantDiversity();
550 :
551 12 : for (std::vector<std::vector<Variant> >::const_iterator grp = m_VariantGroups.begin();
552 12 : grp != m_VariantGroups.end();
553 12 : ++grp)
554 : {
555 : // Ignore groups with nothing inside. (A warning will have been
556 : // emitted by the loading code.)
557 6 : if (grp->size() == 0)
558 0 : continue;
559 :
560 6 : int match = -1; // -1 => none found yet
561 :
562 : // If there's only a single variant, choose that one
563 6 : if (grp->size() == 1)
564 : {
565 : match = 0;
566 : }
567 : else
568 : {
569 : // See if a variant (or several, but we only care about the first)
570 : // is already matched by the selections we've made, keeping their
571 : // priority order into account
572 :
573 0 : for (size_t s = 0; s < initialSelections.size(); ++s)
574 : {
575 0 : for (size_t i = 0; i < grp->size(); ++i)
576 : {
577 0 : if (initialSelections[s].count((*grp)[i].m_VariantName))
578 : {
579 0 : match = (int)i;
580 0 : break;
581 : }
582 : }
583 :
584 0 : if (match >= 0)
585 : break;
586 : }
587 :
588 : // If there was one, we don't need to do anything now because there's
589 : // already something to choose. Otherwise, choose randomly from the others.
590 0 : if (match == -1)
591 : {
592 : // Sum the frequencies
593 : int totalFreq = 0;
594 0 : for (size_t i = 0; i < grp->size(); ++i)
595 0 : totalFreq += (*grp)[i].m_Frequency;
596 :
597 : // Someone might be silly and set all variants to have freq==0, in
598 : // which case we just pretend they're all 1
599 0 : bool allZero = (totalFreq == 0);
600 0 : if (allZero)
601 0 : totalFreq = (int)grp->size();
602 :
603 : // Choose a random number in the interval [0..totalFreq) to choose one of the variants.
604 : // If the diversity is "none", force 0 to return the first valid variant.
605 0 : int randNum = diversity == CObjectManager::VariantDiversity::NONE ? 0 : std::uniform_int_distribution<int>(0, totalFreq - 1)(rng);
606 0 : for (size_t i = 0; i < grp->size(); ++i)
607 : {
608 0 : randNum -= (allZero ? 1 : (*grp)[i].m_Frequency);
609 0 : if (randNum < 0)
610 : {
611 : // (If this change to 'remainingSelections' interferes with earlier choices, then
612 : // we'll get some non-fatal inconsistencies that just break the randomness. But that
613 : // shouldn't happen, much.)
614 : // (As an example, suppose you have a group with variants "a" and "b", and another
615 : // with variants "a" and "c"; now if random selection choses "b" for the first
616 : // and "a" for the second, then the selection of "a" from the second group will
617 : // cause "a" to be used in the first instead of the "b").
618 0 : match = (int)i;
619 :
620 : // In limited diversity, somewhat-randomly continue. This cuts variants to about a third,
621 : // though not quite because we must pick a variant so the actual probability is more complex.
622 : // (It's also dependent on actor files not containing too many 0-frequency variants)
623 0 : if (diversity == CObjectManager::VariantDiversity::LIMITED && (i % 3 != 0))
624 : {
625 : // Reset to 0 or we'll just pick every subsequent variant.
626 0 : randNum = 0;
627 0 : continue;
628 : }
629 : break;
630 : }
631 : }
632 0 : ENSURE(match != -1);
633 : // This should always succeed; otherwise it
634 : // wouldn't have chosen any of the variants.
635 0 : remainingSelections.insert((*grp)[match].m_VariantName);
636 : }
637 : }
638 :
639 : // Remember which props were chosen, so we can call CalculateRandomVariation on them
640 : // at the end.
641 6 : const Variant& var ((*grp)[match]);
642 : // Erase all existing props which are overridden by this variant:
643 6 : for (const Prop& prop : var.m_Props)
644 0 : chosenProps.erase(prop.m_PropPointName);
645 : // and then insert the new ones:
646 6 : for (const Prop& prop : var.m_Props)
647 0 : if (!prop.m_ModelName.empty())
648 0 : chosenProps.insert(make_pair(prop.m_PropPointName, prop.m_ModelName));
649 : }
650 :
651 : // Load each prop, and add their required selections to ours:
652 6 : for (std::multimap<CStr, CStrW>::iterator it = chosenProps.begin(); it != chosenProps.end(); ++it)
653 : {
654 0 : if (auto [success, prop] = m_ObjectManager.FindActorDef(it->second); success)
655 : {
656 0 : std::vector<std::set<CStr> > propInitialSelections = initialSelections;
657 0 : if (!remainingSelections.empty())
658 0 : propInitialSelections.push_back(remainingSelections);
659 :
660 0 : std::set<CStr> propRemainingSelections = prop.GetBase(m_QualityLevel)->CalculateRandomRemainingSelections(rng, propInitialSelections);
661 0 : remainingSelections.insert(propRemainingSelections.begin(), propRemainingSelections.end());
662 :
663 : // Add the prop's used files to our own (recursively) so we can hotload
664 : // when any prop is changed
665 0 : m_ActorDef.m_UsedFiles.insert(prop.m_UsedFiles.begin(), prop.m_UsedFiles.end());
666 0 : }
667 : }
668 :
669 6 : return remainingSelections;
670 6 : }
671 :
672 0 : std::vector<std::vector<CStr> > CObjectBase::GetVariantGroups() const
673 : {
674 0 : std::vector<std::vector<CStr> > groups;
675 :
676 : // Queue of objects (main actor plus props (recursively)) to be processed
677 0 : std::queue<const CObjectBase*> objectsQueue;
678 0 : objectsQueue.push(this);
679 :
680 : // Set of objects already processed, so we don't do them more than once
681 0 : std::set<const CObjectBase*> objectsProcessed;
682 :
683 0 : while (!objectsQueue.empty())
684 : {
685 0 : const CObjectBase* obj = objectsQueue.front();
686 0 : objectsQueue.pop();
687 : // Ignore repeated objects (likely to be props)
688 0 : if (objectsProcessed.find(obj) != objectsProcessed.end())
689 0 : continue;
690 :
691 0 : objectsProcessed.insert(obj);
692 :
693 : // Iterate through the list of groups
694 0 : for (size_t i = 0; i < obj->m_VariantGroups.size(); ++i)
695 : {
696 : // Copy the group's variant names into a new vector
697 0 : std::vector<CStr> group;
698 0 : group.reserve(obj->m_VariantGroups[i].size());
699 0 : for (size_t j = 0; j < obj->m_VariantGroups[i].size(); ++j)
700 0 : group.push_back(obj->m_VariantGroups[i][j].m_VariantName);
701 :
702 : // If this group is identical to one elsewhere, don't bother listing
703 : // it twice.
704 : // Linear search is theoretically not very efficient, but hopefully
705 : // we don't have enough props for that to matter...
706 0 : bool dupe = false;
707 0 : for (size_t j = 0; j < groups.size(); ++j)
708 : {
709 0 : if (groups[j] == group)
710 : {
711 : dupe = true;
712 : break;
713 : }
714 : }
715 0 : if (dupe)
716 0 : continue;
717 :
718 : // Add non-trivial groups (i.e. not just one entry) to the returned list
719 0 : if (obj->m_VariantGroups[i].size() > 1)
720 0 : groups.push_back(group);
721 :
722 : // Add all props onto the queue to be considered
723 0 : for (size_t j = 0; j < obj->m_VariantGroups[i].size(); ++j)
724 : {
725 0 : const std::vector<Prop>& props = obj->m_VariantGroups[i][j].m_Props;
726 0 : for (size_t k = 0; k < props.size(); ++k)
727 0 : if (!props[k].m_ModelName.empty())
728 0 : if (auto [success, prop] = m_ObjectManager.FindActorDef(props[k].m_ModelName.c_str()); success)
729 0 : objectsQueue.push(prop.GetBase(m_QualityLevel).get());
730 : }
731 0 : }
732 : }
733 :
734 0 : return groups;
735 0 : }
736 :
737 1 : void CObjectBase::GetQualitySplits(std::vector<std::uint8_t>& splits) const
738 : {
739 1 : std::vector<std::uint8_t>::iterator it = std::find_if(splits.begin(), splits.end(),
740 1 : [this](std::uint8_t qualityLevel) { return qualityLevel >= m_QualityLevel; });
741 1 : if (it == splits.end() || *it != m_QualityLevel)
742 0 : splits.emplace(it, m_QualityLevel);
743 :
744 2 : for (const std::vector<Variant>& group : m_VariantGroups)
745 2 : for (const Variant& variant : group)
746 1 : for (const Prop& prop : variant.m_Props)
747 : {
748 : // TODO: we probably should clean those up after XML load.
749 0 : if (prop.m_ModelName.empty())
750 0 : continue;
751 :
752 0 : auto [success, propActor] = m_ObjectManager.FindActorDef(prop.m_ModelName.c_str());
753 0 : if (!success)
754 0 : continue;
755 :
756 0 : std::vector<std::uint8_t> newSplits = propActor.QualityLevels();
757 0 : if (newSplits.size() <= 1)
758 0 : continue;
759 :
760 : // This is not entirely optimal since we might loop though redundant quality levels, but that shouldn't matter.
761 : // Custom implementation because this is inplace, std::set_union needs a 3rd vector.
762 0 : std::vector<std::uint8_t>::iterator v1 = splits.begin();
763 0 : std::vector<std::uint8_t>::iterator v2 = newSplits.begin();
764 0 : while (v2 != newSplits.end())
765 : {
766 0 : if (v1 == splits.end() || *v1 > *v2)
767 : {
768 0 : v1 = ++splits.insert(v1, *v2);
769 0 : ++v2;
770 : }
771 0 : else if (*v1 == *v2)
772 : {
773 0 : ++v1;
774 0 : ++v2;
775 : }
776 : else
777 0 : ++v1;
778 : }
779 0 : }
780 1 : }
781 :
782 3 : const CStr& CObjectBase::GetIdentifier() const
783 : {
784 3 : return m_Identifier;
785 : }
786 :
787 0 : bool CObjectBase::UsesFile(const VfsPath& pathname) const
788 : {
789 0 : return m_ActorDef.UsesFile(pathname);
790 : }
791 :
792 :
793 1 : CActorDef::CActorDef(CObjectManager& objectManager) : m_ObjectManager(objectManager)
794 : {
795 1 : }
796 :
797 2 : std::set<CStr> CActorDef::PickSelectionsAtRandom(uint32_t seed) const
798 : {
799 : // Use the selections from the highest quality actor - this lets artists maintain compatibility (or not)
800 : // when going to lower quality levels.
801 2 : std::vector<std::set<CStr>> noSelections;
802 4 : return GetBase(255)->CalculateRandomRemainingSelections(seed, noSelections);
803 2 : }
804 :
805 1 : std::vector<std::uint8_t> CActorDef::QualityLevels() const
806 : {
807 1 : std::vector<std::uint8_t> splits;
808 1 : splits.reserve(m_ObjectBases.size());
809 2 : for (const std::shared_ptr<CObjectBase>& base : m_ObjectBases)
810 1 : splits.emplace_back(base->m_QualityLevel);
811 1 : return splits;
812 0 : }
813 :
814 6 : const std::shared_ptr<CObjectBase>& CActorDef::GetBase(std::uint8_t QualityLevel) const
815 : {
816 6 : for (const std::shared_ptr<CObjectBase>& base : m_ObjectBases)
817 6 : if (base->m_QualityLevel >= QualityLevel)
818 6 : return base;
819 : // This code path ought to be impossible to take,
820 : // because by construction we must have at least one valid CObjectBase of quality MAX_QUALITY
821 : // (which necessarily fits the std::uint8_t comparison above).
822 : // However compilers will warn that we return a reference to a local temporary if I return nullptr,
823 : // so just return something sane instead.
824 0 : ENSURE(false);
825 0 : return m_ObjectBases.back();
826 : }
827 :
828 1 : bool CActorDef::Load(const VfsPath& pathname)
829 : {
830 1 : m_UsedFiles.clear();
831 1 : m_UsedFiles.insert(pathname);
832 :
833 1 : m_ObjectBases.clear();
834 :
835 1 : CXeromyces XeroFile;
836 1 : if (XeroFile.Load(g_VFS, pathname, "actor") != PSRETURN_OK)
837 : return false;
838 :
839 : // Define all the elements used in the XML file
840 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
841 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
842 1 : EL(actor);
843 1 : EL(inline);
844 1 : EL(qualitylevels);
845 1 : AT(file);
846 1 : AT(inline);
847 1 : AT(quality);
848 1 : AT(version);
849 : #undef AT
850 : #undef EL
851 :
852 1 : XMBElement root = XeroFile.GetRoot();
853 :
854 1 : if (root.GetNodeName() != el_actor && root.GetNodeName() != el_qualitylevels)
855 : {
856 0 : LOGERROR("Invalid actor format (actor '{}', unrecognized root element '{}')",
857 : pathname.string8(), XeroFile.GetElementString(root.GetNodeName()));
858 0 : return false;
859 : }
860 :
861 1 : m_Pathname = pathname;
862 :
863 1 : if (root.GetNodeName() == el_actor)
864 : {
865 1 : std::unique_ptr<CObjectBase> base = std::make_unique<CObjectBase>(m_ObjectManager, *this, MAX_QUALITY);
866 1 : if (!base->Load(XeroFile, root))
867 : {
868 0 : LOGERROR("Invalid actor (actor '{}')", pathname.string8());
869 0 : return false;
870 : }
871 1 : m_ObjectBases.emplace_back(std::move(base));
872 1 : }
873 : else
874 : {
875 0 : for (XMBAttribute attr : root.GetAttributes())
876 : {
877 0 : if (attr.Name == at_version && attr.Value.ToInt() != 1)
878 : {
879 0 : LOGERROR("Invalid actor format (actor '{}', version {} is not supported)",
880 : pathname.string8(), attr.Value.ToInt());
881 0 : return false;
882 : }
883 0 : }
884 0 : std::uint8_t quality = 0;
885 0 : XMBElement inlineActor;
886 0 : for (XMBElement child : root.GetChildNodes())
887 : {
888 0 : if (child.GetNodeName() == el_inline)
889 0 : inlineActor = child;
890 : }
891 0 : for (XMBElement actor : root.GetChildNodes())
892 : {
893 0 : if (actor.GetNodeName() != el_actor)
894 0 : continue;
895 0 : bool found_quality = false;
896 0 : bool use_inline = false;
897 0 : CStr file;
898 0 : for (XMBAttribute attr : actor.GetAttributes())
899 : {
900 0 : if (attr.Name == at_quality)
901 : {
902 0 : int v = GetQuality(attr.Value);
903 0 : if (v > MAX_QUALITY)
904 : {
905 0 : LOGERROR("Quality levels can only go up to {} (file {})",
906 : MAX_QUALITY, pathname.string8());
907 0 : return false;
908 : }
909 0 : if (v <= quality)
910 : {
911 0 : LOGERROR("Elements must be in increasing quality order (file {})",
912 : pathname.string8());
913 0 : return false;
914 : }
915 0 : quality = v;
916 0 : found_quality = true;
917 : }
918 0 : else if (attr.Name == at_file)
919 : {
920 0 : if (attr.Value.empty())
921 : {
922 0 : LOGWARNING("Empty actor file specified (file {})",
923 : pathname.string8());
924 : }
925 0 : file = attr.Value;
926 : }
927 0 : else if (attr.Name == at_inline)
928 0 : use_inline = true;
929 0 : }
930 0 : if (!found_quality)
931 0 : quality = MAX_QUALITY;
932 0 : std::unique_ptr<CObjectBase> base = std::make_unique<CObjectBase>(m_ObjectManager, *this, quality);
933 0 : if (use_inline)
934 : {
935 0 : if (inlineActor.GetNodeName() == -1)
936 : {
937 0 : LOGERROR("Actor quality level refers to inline definition, but no inline "
938 : "definition found (file {})", pathname.string8());
939 0 : return false;
940 : }
941 0 : if (!base->Load(XeroFile, inlineActor))
942 : {
943 0 : LOGERROR("Invalid inline actor (actor '{}')", pathname.string8());
944 0 : return false;
945 : }
946 :
947 : }
948 0 : else if (file.empty())
949 : {
950 0 : if (!base->Load(XeroFile, actor))
951 : {
952 0 : LOGERROR("Invalid actor (actor '{}')", pathname.string8());
953 0 : return false;
954 : }
955 : }
956 : else
957 : {
958 0 : if (actor.GetChildNodes().size() > 0)
959 : {
960 0 : LOGWARNING("Actor definition refers to file but has children elements, they "
961 : "will be ignored (file {})", pathname.string8());
962 : }
963 :
964 : // Open up an external file to load.
965 : // Don't crash hard when failures happen, but log them and continue
966 0 : CXeromyces XeroActor;
967 0 : if (XeroActor.Load(g_VFS, VfsPath("art/actors/") / file, "actor") == PSRETURN_OK)
968 : {
969 0 : const XMBElement& root = XeroActor.GetRoot();
970 0 : if (root.GetNodeName() == XeroActor.GetElementID("qualitylevels"))
971 : {
972 0 : LOGERROR("Included actors cannot define quality levels (opening {} "
973 : "from file {})", file, pathname.string8());
974 0 : return false;
975 : }
976 0 : if (!base->Load(XeroActor, root))
977 : {
978 0 : LOGERROR("Invalid actor (actor '{}' loaded from '{}')", file,
979 : pathname.string8());
980 0 : return false;
981 : }
982 : }
983 : else
984 : {
985 0 : LOGERROR("Could not open actor file at path {} (file {})", file,
986 : pathname.string8());
987 0 : return false;
988 : }
989 0 : m_UsedFiles.insert(file);
990 0 : }
991 0 : m_ObjectBases.emplace_back(std::move(base));
992 0 : }
993 0 : if (quality != MAX_QUALITY)
994 : {
995 0 : LOGERROR("The highest quality level must be {}, but the highest level found was {} "
996 : "(file {})", MAX_QUALITY, quality, pathname.string8());
997 0 : return false;
998 : }
999 : }
1000 :
1001 : // For each quality level, check if we need to further split (because of props).
1002 1 : std::vector<std::uint8_t> splits = QualityLevels();
1003 2 : for (const std::shared_ptr<CObjectBase>& base : m_ObjectBases)
1004 1 : base->GetQualitySplits(splits);
1005 1 : ENSURE(splits.size() >= 1);
1006 1 : if (splits.size() > MAX_LEVELS_PER_ACTOR_DEF)
1007 : {
1008 0 : LOGERROR("Too many quality levels ({}) for actor {} (max {})", splits.size(),
1009 : pathname.string8(), MAX_LEVELS_PER_ACTOR_DEF);
1010 0 : return false;
1011 : }
1012 :
1013 1 : std::vector<std::shared_ptr<CObjectBase>>::iterator it = m_ObjectBases.begin();
1014 1 : std::vector<std::uint8_t>::const_iterator qualityLevels = splits.begin();
1015 1 : while (it != m_ObjectBases.end())
1016 1 : if ((*it)->m_QualityLevel > *qualityLevels)
1017 : {
1018 0 : it = ++m_ObjectBases.emplace(it, (*it)->CopyWithQuality(*qualityLevels));
1019 0 : ++qualityLevels;
1020 : }
1021 1 : else if ((*it)->m_QualityLevel == *qualityLevels)
1022 : {
1023 1 : ++it;
1024 1 : ++qualityLevels;
1025 : }
1026 : else
1027 2 : ++it;
1028 :
1029 : return true;
1030 2 : }
1031 :
1032 0 : bool CActorDef::UsesFile(const VfsPath& pathname) const
1033 : {
1034 0 : return m_UsedFiles.find(pathname) != m_UsedFiles.end();
1035 : }
1036 :
1037 0 : void CActorDef::LoadErrorPlaceholder(const VfsPath& pathname)
1038 : {
1039 0 : m_UsedFiles.clear();
1040 0 : m_ObjectBases.clear();
1041 0 : m_UsedFiles.emplace(pathname);
1042 0 : m_Pathname = pathname;
1043 0 : m_ObjectBases.emplace_back(std::make_shared<CObjectBase>(m_ObjectManager, *this, MAX_QUALITY));
1044 0 : }
|