Client LuaCsForBarotrauma
Prefab.cs
1 #nullable enable
2 
3 using System;
4 using System.Collections.Immutable;
5 using System.Diagnostics;
6 using System.Xml.Linq;
7 
8 namespace Barotrauma
9 {
10  public abstract class Prefab
11  {
12  public readonly static ImmutableHashSet<Type> Types;
13  static Prefab()
14  {
15  Types = ReflectionUtils.GetDerivedNonAbstract<Prefab>().ToImmutableHashSet();
16  }
17 
18  private static bool potentialCallFromConstructor = false;
19  public static void DisallowCallFromConstructor()
20  {
21  if (!potentialCallFromConstructor) { return; }
22  StackTrace st = new StackTrace(skipFrames: 2, fNeedFileInfo: false);
23  for (int i = st.FrameCount - 1; i >= 0; i--)
24  {
25  if (st.GetFrame(i)?.GetMethod() is { IsConstructor: true, DeclaringType: { } declaringType }
26  && Types.Contains(declaringType))
27  {
28  throw new Exception("Called disallowed method from within a prefab's constructor!");
29  }
30  }
31  potentialCallFromConstructor = false;
32  }
33 
34  public readonly Identifier Identifier;
35  public readonly ContentFile ContentFile;
36 
38  public ContentPath FilePath => ContentFile.Path;
39 
40  public Prefab(ContentFile file, Identifier identifier)
41  {
42  potentialCallFromConstructor = true;
43  ContentFile = file;
44  Identifier = identifier;
45  if (Identifier.IsEmpty) { throw new ArgumentException($"Error creating {GetType().Name}: Identifier cannot be empty"); }
46  }
47 
48  public Prefab(ContentFile file, ContentXElement element)
49  {
50  potentialCallFromConstructor = true;
51  ContentFile = file;
52  Identifier = DetermineIdentifier(element!);
53  if (Identifier.IsEmpty) { throw new ArgumentException($"Error creating {GetType().Name}: Identifier cannot be empty"); }
54  }
55 
56  protected virtual Identifier DetermineIdentifier(XElement element)
57  {
58  return element.GetAttributeIdentifier("identifier", Identifier.Empty);
59  }
60 
61  public abstract void Dispose();
62  }
63 }
Base class for content file types, which are loaded from filelist.xml via reflection....
Definition: ContentFile.cs:23
readonly ContentPath Path
Definition: ContentFile.cs:137
readonly ContentPackage ContentPackage
Definition: ContentFile.cs:136
static readonly ImmutableHashSet< Type > Types
Definition: Prefab.cs:12
Prefab(ContentFile file, ContentXElement element)
Definition: Prefab.cs:48
virtual Identifier DetermineIdentifier(XElement element)
Definition: Prefab.cs:56
readonly ContentFile ContentFile
Definition: Prefab.cs:35
abstract void Dispose()
Prefab(ContentFile file, Identifier identifier)
Definition: Prefab.cs:40
static void DisallowCallFromConstructor()
Definition: Prefab.cs:19
readonly Identifier Identifier
Definition: Prefab.cs:34