-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBaseClasses.pas
More file actions
2203 lines (1884 loc) · 75.7 KB
/
BaseClasses.pas
File metadata and controls
2203 lines (1884 loc) · 75.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
@Abstract(Basic classes unit)
(C) 2006-2007 George "Mirage" Bakhtadze. <a href="http://www.casteng.com">www.casteng.com</a> <br>
The source code may be used under either MPL 1.1 or LGPL 2.1 license. See included license.txt file <br>
Unit contains basic item-related classes
*)
{$Include GDefines.inc}
unit BaseClasses;
interface
uses
Logger,
SysUtils,
BaseTypes, Basics, BaseStr, json, Models, BaseMsg, Props, BaseCompiler;
const
// Maximum possible item state flags
MaxStates = 32;
// First HiddenStates states will not be visible in editor
HiddenStates = 4;
// An item was removed from manager or marked to remove
isRemoved = 0;
// An item was marked to release
isReleased = 1;
// An item hasn't been initialized yet
isNeedInit = 2;
// Visualize item's selection information with a color defined by Globals.PickedBoxColor
isPicked = 3;
// An item should be visualised
isVisible = 4;
// Process method of an item should be called according to its ProcessingClass field
isProcessing = 5;
// Visualize item's debug information (bounding boxes, etc)
isDrawVolumes = 6;
{$IFDEF DEBUGMODE}
// Childs collection capacity increment step
ChildsCapacityStep = 1;
// Collections capacity increment step
CollectionsCapacityStep = 1;
// Items collection capacity increment step
ItemsCapacityStep = 1;
{$ELSE}
// Childs collection capacity increment step
ChildsCapacityStep = 8;
// Collections capacity increment step
CollectionsCapacityStep = 16;
// Items collection capacity increment step
ItemsCapacityStep = 16;
{$ENDIF}
// Hierarchy delimiter
HierarchyDelimiter = '\';
// A simbol to address upper level of hierarchy in relative item names
ParentAdressName = '.';
type
// Main floating point type
Float = Single;
// Item flag set
TItemFlags = TSet32;
// Item move modes
TItemMoveMode = (// insert before
mmInsertBefore,
// insert after
mmInsertAfter,
// add as first child
mmAddChildFirst,
// add as last child
mmAddChildLast,
// move up within the current level
mmMoveUp,
// move down within the current level
mmMoveDown,
// move up one level
mmMoveLeft,
// move down one level
mmMoveRight);
// @Exclude()
TItem = class;
// Item class type
CItem = class of TItem;
// Used for classes registration
TClassArray = array of TClass;
TItemsManager = class;
// General item method pointer
TItemDelegate = procedure(Item: TItem; Data: Pointer) of object;
// @Exclude()
TObjectLinkFlag = (lfAbsolute);
// @Exclude()
TObjectLinkFlags = set of TObjectLinkFlag;
// @Exclude() Item link property data
TObjectLink = record
Flags: TObjectLinkFlags;
PropName, ObjectName: AnsiString;
Item: TItem;
BaseClass: CItem;
end;
// Simple items collection
TItems = array of TItem;
// Extract condition function result flags
TExtractConditionItems = (// condition passed
ecPassed,
// do not follow current hierarchy
ecBreakHierarchy,
// completely stop traverse
ecBreak);
// Extract condition function result type
TExtractCondition = set of TExtractConditionItems;
// Condition function for conditional extraction
TExtractConditionFunc = function(Item: TItem): TExtractCondition of object;
// Abstract subsystem
TSubsystem = class(TBaseSubsystem)
public
{ This procedure is called (by editor for example) to retrieve a list of item's properties and their values.
Any TItem descendant class should override this method in order to add its own properties. }
procedure AddProperties(const Result: TProperties); virtual;
{ This procedure is called (by editor for example) to set values of item's properties.
Any TItem descendant class should override this method to allow its own properties to be set. }
procedure SetProperties(Properties: TProperties); virtual;
end;
// @Abstract(Abstract compiler class)
TAbstractCompiler = class(TSubsystem)
public
// Description of last compilation error occured
LastError: string;
// Translate the given source to an intermediate or binary form
function Compile(const Source: AnsiString): TRTData; virtual; abstract;
end;
// Scene loading error type
TSceneLoadError = class(TError)
end;
{ @Abstract(Base item class)
Provides hierarchical structure, saving/loading, properties interface and some service functions. }
TItem = class(TBaseItem)
private
FName: AnsiString;
ItemLinks: array of TObjectLink;
procedure SetName(const Value: AnsiString);
procedure DeAlloc;
procedure ChangeChildIndex(Child: TItem; NewIndex: Integer);
// Internal link management
function GetLinkIndex(const AName: AnsiString): Integer;
function SetLinkedObjectByIndex(Index: Integer; Linked: TItem): Boolean; // Called from ResolveLink
function ObtainLinkedItemNameByIndex(PropIndex: Integer): AnsiString;
procedure DoOnSceneAddForChilds(Item: TItem; Data: Pointer);
procedure DoOnSceneRemoveForChilds(Item: TItem; Data: Pointer);
procedure DoSendInitToChilds(Item: TItem; Data: Pointer);
function DoAddChild(AItem: TItem): TItem;
function GetChild(Index: Integer): TItem;
protected
{$IFDEF DEBUGMODE}
{ This flag is True when the item's internal state is valid and the item can be used or queried from outside.
If this flag is False no routines expecting that the item is valid should be called.
Only asyncronous messages allowed to be sent by an item when its FConsistent is False. }
FConsistent: Boolean;
{$ENDIF}
// Childs collection
FChilds: TItems;
// Number of childs
FTotalChilds: Integer;
// Set of state flags
FState: TItemFlags;
// Parent reference
FParent: TItem;
// Manager reference. See @Link(TItemsManager)
FManager: TItemsManager;
// Index in parent collection for internal use
IndexInParent: Integer;
// Sets a new state flags
procedure SetState(const Value: TItemFlags); virtual;
// Sets a new parent value
procedure SetParent(NewParent: TItem); virtual;
// Sets Parent to nil without removing from hierarchy, etc
procedure ClearParent;
// Sets manager for item and propagates the change to all childs if requested
procedure SetManager(AManager: TItemsManager; SetChilds: Boolean);
// Calls the specified delegate for all items in the hierarchy starting from Self. Data can be some custom generic data or nil.
procedure DoForAllChilds(Delegate: TItemDelegate; Data: Pointer);
// Calls HandleMessage with the message for all items in the hierarchy starting from Self
procedure BroadcastMessage(const Msg: TMessage);
// Sets @Link(mfNotification) flag of the message and calls HandleMessage with the message for all first-level childs
procedure NotifyChilds(const Msg: TMessage);
// Sets child and returns AItem if success or nil if index is invalid or impossible to set a child
function SetChild(Index: Integer; AItem: TItem): TItem; virtual;
// Inserts a child to the given position in childs collection
procedure InsertChild(AItem: TItem; Index: Integer);
// Removes a child with the specified index
procedure RemoveChildByIndex(Index: Integer); virtual;
// Link management
{ Adds an item link property with the given name and base class to Properties.
Use this method in order to add a property which points to another item }
procedure AddItemLink(Properties: TProperties; const PropName: AnsiString; PropOptions: TPOptions; const BaseClass: AnsiString);
// Performs initialization of internal data structures. Do not call manually
procedure BuildItemLinks;
// Resolves (with class checking) an object link and returns <b>True</b> if a NEW linked item was resolved.
function ResolveLink(const PropName: AnsiString; out Linked: TItem): Boolean;
{ Sets Linked as resolved linked object for a link property with the given name.
Returns <b>True</b> if Linked passes type checking }
function SetLinkedObject(const PropName: AnsiString; Linked: TItem): Boolean;
// Should be called from @Link(SetProperties) to handle item link property setting
function SetLinkProperty(const AName, Value: AnsiString): Boolean;
{ Called from default @Link(OnSceneLoaded) event handler.
Override to resolve all link which needed to be resolved right after scene load }
procedure ResolveLinks; virtual;
public
// Regular constructor
constructor Create(AManager: TItemsManager); virtual;
// Constructor used to construct complex objects such as windows with a header area and a client area
constructor Construct(AManager: TItemsManager); virtual;
// Copies all data and properties from ASource to the item
procedure Assign(ASource: TItem); virtual;
// Returns class reference
class function GetClass: CItem;
// Items of abstract classes can not be created in editor
class function IsAbstract: Boolean; virtual;
{ Returns full size in memory of an item in bytes.
Descendants should override this method if they have dynamic fields which sizes are not included in TObject.InstanceSize. }
function GetItemSize(CountChilds: Boolean): Integer; virtual;
// Sends the specified message according to the specified destination.
procedure SendMessage(const Msg: TMessage; Recipient: TItem; Destination: TMessageFlags);
// Main message handler
procedure HandleMessage(const Msg: TMessage); override;
// Events
// Occurs after object creation and initialization of Root variable
procedure OnInit; virtual;
// Occurs when a scene is completely loaded
procedure OnSceneLoaded; virtual;
// Occurs when the item added to a scene (usally after loading)
procedure OnSceneAdd; virtual;
// Occurs when the item being remove from scene
procedure OnSceneRemove; virtual;
// Properties system
// Do not use this procedure directly. Call @Link(AddProperties) instead
procedure GetProperties(const Result: TProperties);
{ This procedure is called (by editor for example) to retrieve a list of item's properties and their values.
Any TItem descendant class should override this method in order to add its own properties. }
procedure AddProperties(const Result: TProperties); virtual;
{ This procedure is called (by editor for example) to set values of item's properties.
Any TItem descendant class should override this method to allow its own properties to be set. }
procedure SetProperties(Properties: TProperties); virtual;
// Calls @Link(AddProperties) to return a single property identified by AName
function GetProperty(const AName: AnsiString): AnsiString;
// Calls @Link(SetProperties) to set a single property identified by AName
procedure SetProperty(const AName, AValue: AnsiString);
// Returns name of an item which linked by a property with the given name
procedure ObtainLinkedItemName(const PropName: AnsiString; out Result: AnsiString);
{ Creates and returns a clone of the item with all properties having the same value as in source.
Descendants should override this method in order to handle specific fields if any. }
function Clone: TItem; virtual;
// Saving/Loading
// Saves an item to a stream and returns <b>True</b> if success
function Save(Stream: TStream): Boolean; virtual;
// Loads an item from a stream and returns <b>True</b> if success
function Load(Stream: TStream): Boolean; virtual;
// Hierarchy routines
// Childs management
{ Adds and returns a child. Sends a @Link(TAddToSceneMsg) message to all items in scene and to manager (see @Link(TItemsManager) ) }
function AddChild(AItem: TItem): TItem;
{ Removes the given child item. Sends a @Link(TRemoveFromSceneMsg) message to all items in scene and to manager (see @Link(TItemsManager) ) }
procedure RemoveChild(AItem: TItem); virtual;
// Returns all childs of the item
function GetChilds: TItems;
// Returns item's parent, skipping the dummy ones
function GetNonDummyParent: TItem;
{ Finds child next to current assuming childs of dummy childs as own. Pass @nil as current to find the first child.
If next child found, the function returns <b>True</b> and with Current set to that child.
Otherwise returns <b>False</b> with Current set to @nil. }
function FindNextChildInclDummy(var Current: TItem): Boolean;
// Node search
// Returns item's full name in a filesystem-like format: <RootItemName>\<Parent>\<Name>
function GetFullName: AnsiString;
// Finds a child item by its name. Name is case-sensitive. If SearchChilds is False only first-level childs can be found.
function GetChildByName(const AName: AnsiString; SearchChilds: Boolean): TItem;
// Finds an item by the given path. The function supports relative paths as well as absolute ones. Path is case-sensitive.
function GetItemByPath(const APath: AnsiString): TItem;
// Finds a child next to CurrentChild
function GetNextChild(CurrentChild: TItem): TItem;
// Returns full path of an item specified by its full name relative to the item
function GetRelativeItemName(const AFullName: AnsiString): AnsiString;
// Moves a child in hierarchy as specified by Mode (see @Link(TItemMoveMode))
procedure MoveChild(Child, Target: TItem; Mode: TItemMoveMode);
// Returns <b>True</b> if the item is a child of any level of AParent. Returns <b>False</b> if Self = AParent.
function IsChildOf(AParent: TItem): Boolean;
// Returns <b>True</b> if the item is a part of the specified scene or any scene if AManager is nil
function IsInScene(AManager: TItemsManager): Boolean;
// Clean up and destruction
{ Marks item as removed from hierarchy and (if DoNotRelease is <b>False</b>) as released.
These marks will be handled by @Link(CollectGarbage). }
procedure MarkAsRemoved(DoNotRelease: Boolean);
// Frees all childs
procedure FreeChilds; virtual;
// Regular destructor. Frees item itself, all it's data and all childs.
destructor Destroy; override;
// Manager reference. See @Link(TItemsManager)
property Manager: TItemsManager read FManager;
// Specifies number of childs of an item
property TotalChilds: Integer read FTotalChilds;
// Item's childs collection
property Childs[Index: Integer]: TItem read GetChild;
{ Item's parent. You can set this property to move the item within items hierarchy.
Setting Parent to @nil will remove the item from the hierarchy. }
property Parent: TItem read FParent write SetParent;
{ A set of state flags.
See @Link(isRemoved), @Link(isReleased), @Link(isNeedInit), @Link(isPicked), @Link(isVisible), @Link(isProcessing), @Link(isDrawVolumes). }
property State: TItemFlags read FState write SetState;
// Item name. Used to reference items by name in a filesystem-like way: RootItemName\Parent\Name
property Name: AnsiString read FName write SetName;
end;
{ @Abstract(Used to group items within a hierarchy)
Forwards all notification messages to childs }
TDummyItem = class(TItem)
// Checks if the message is a notification and forwards it to childs
procedure HandleMessage(const Msg: TMessage); override;
end;
{ A hierarchy root item should be of this (or a descendant) class.
@Abstract(Provides some item extraction methods) }
TRootItem = class(TItem)
public
constructor Create(AManager: TItemsManager); override;
// Returns an item by exact name with full path. E.g. "\Root\Landscape\Tree19".
function GetItemByFullName(const AName: AnsiString): TItem;
{ Traverses through the items hierarchy and adds all items passing Condition to Items.
Returns number of items in Items. }
function Extract(Condition: TExtractConditionFunc; out Items: TItems): Integer;
{ Traverses through the items hierarchy and adds to Items all items which State contains all flags in Mask.
If Hierarchical is <b>True</b> childs of non-matching items are not considered. Returns number of items in Items. }
function ExtractByMask(Mask: TItemFlags; Hierarchical: Boolean; out Items: TItems): Integer;
{ Traverses through the items hierarchy and adds all items of the given class or its descendants to Items.
Returns number of items in Items. }
function ExtractByClass(AClass: CItem; out Items: TItems): Integer;
{ Traverses through the items hierarchy and adds all items of the given class or its descendants and with State containing all
flags in Mask to Items. Childs of items with non-matching state are not considered.
Returns number of items in Items. }
function ExtractByMaskClass(Mask: TItemFlags; AClass: CItem; out Items: TItems): Integer;
procedure HandleMessage(const Msg: TMessage); override;
end;
// @Abstract(Base class of all items which periodically updates their state)
TBaseProcessing = class(TItem)
private
// Total time processed with the @Link(Process) method since last call of ResetProcessedTime() in seconds
FTimeProcessed: TTimeUnit;
public
// Processing class specifies how an item should be processed. See @Link(TProcessingClass)
ProcessingClass: Integer;
// Resets TimeProcessed to zero
procedure ResetProcessedTime;
// Pauses processing of the item
procedure Pause; {$I inline.inc}
// Resumes processing of the item
procedure Resume; {$I inline.inc}
{ This method will be called when an item is to be processed (updated).
Actual process schedule depends on values if processing class (see @Link(TItemsManager)) to which points ProcessingClass field. }
procedure Process(const DeltaT: Float); virtual;
procedure AddProperties(const Result: TProperties); override;
procedure SetProperties(Properties: TProperties); override;
// Total time processed with the @Link(Process) method
property TimeProcessed: TTimeUnit read FTimeProcessed;
end;
{ IResource = interface
function GetData: Pointer;
function GetTotalElements: Integer;
property TotalElements: Integer read GetTotalElements;
property Data: Pointer read GetData;
end;}
// Item used for time syncronization
TSyncItem = class(TBaseProcessing)
protected
procedure SetState(const Value: TItemFlags); override;
public
// Sends TSyncTimeMsg to all sibling items and their child items
procedure Syncronize; {$I inline.inc}
end;
// Items manager state
TIMState = (// the manager is currently loading items
imsLoading,
// the manager is currently shutting down
imsShuttingDown);
// Item processing flags
TProcessingFlag = (// force processing even when pause mode is on
pfIgnorePause,
// process as frequent as possible ignoring Interval
pfDeltaTimeBased);
// Set of item processing flags
TProcessingFlags = set of TProcessingFlag;
{ Processing options for processing classes (see @Link(TItemsManager)).
Interval - process interval in seconds.
Flags - see @Link(TProcessingFlag)
TimerEventID - an ID of a corresponding timer event. -1 if none }
TProcessingClass = record
Interval: Float;
Flags: TProcessingFlags;
TimerEventID: Integer;
end;
{ @Abstract(Contains and manages a hierarchy of items starting with Root)
Contains all registered item classes. }
TItemsManager = class
private
FItemClasses: array of CItem;
FTotalItemClasses: Integer;
function GetProcClassesEnum: AnsiString;
// Sets a new root item
procedure SetRoot(const Value: TRootItem);
function GetItemClass(Index: Integer): CItem;
protected
// Root of a hierarchy
FRoot: TRootItem;
// Names of all possible state flags
StateNames: array of AnsiString;
// Current manager state
FState: set of TIMState;
// Should be <b>True</b> if world-editing capabilities are required
FEditorMode: Boolean;
// Item processing classes (see @Link(TProcessingClass))
ProcessingClasses: array of TProcessingClass;
// Asynchronous messages container
AsyncMessages: TMessageSubsystem;
// Returns number of processing classes
function GetTotalProcessingClasses: Integer;
// Adds a message to the asyncronous queue to be handled later in @Link(ProcessAsyncMessages)
procedure SendAsyncMessage(const Msg: TMessage; Recipient: TItem); virtual;
// Handles items market to remove and release
procedure CollectGarbage; virtual;
// This event occurs right before destruction of the manager
procedure OnDestroy; virtual;
public
// Scripting subsystem
Compiler: TAbstractCompiler;
constructor Create; virtual;
destructor Destroy; override;
// Handles all asyncronous messages
procedure ProcessAsyncMessages;
// Sends the specified message according to the specified destination. Can be called as class function with mfRecipient and mfChilds destinations.
procedure SendMessage(const Msg: TMessage; Recipient: TItem; Destination: TMessageFlags);
// Default core message handler
procedure HandleMessage(const Msg: TMessage); virtual;
// Returns <b>True</b> if a scene is currently loading
function IsSceneLoading: Boolean;
// Returns <b>True</b> if manager is shutting down
function IsShuttingdown: Boolean;
// Registers an item state flag
function RegisterState(const AName: AnsiString): Boolean;
// Registers an item class. Only items of registered classes can be saved/loaded or be linked to via item link property.
procedure RegisterItemClass(NewClass: CItem);
// Registers an array of item classes. Only items of registered classes can be saved/loaded or be linked to via item link property.
procedure RegisterItemClasses(NewClasses: array of TClass);
// Returns an item class by its name or @nil if not found
function FindItemClass(const AName: AnsiString): CItem; virtual;
{ Changes class of an item to <b>NewClass</b>. <br>
<b>All direct references to the item except via object linking mechanism become invalid.</b> }
function ChangeClass(Item: TItem; NewClass: CItem): TItem;
// Removes an item from the manager
procedure RemoveItem(Item: TItem);
{ Loads an item from a stream specified and adds it to AParent as a child.
Returns the loaded item. }
function LoadItem(Stream: TStream; AParent: TItem): TItem;
// Clears the current scene and loads a new scene from a stream
function LoadScene(Stream: TStream): Boolean;
// Saves the current scene to a stream
function SaveScene(Stream: TStream): Boolean;
// Clears the current scene
procedure ClearItems; virtual;
// Should be set to <b>True</b> if world-editing capabilities are required
property EditorMode: Boolean read FEditorMode;
// Number of processing classes
property TotalProcessingClasses: Integer read GetTotalProcessingClasses;
// Number of registered item classes
property TotalItemClasses: Integer read FTotalItemClasses;
// Registered item classes
property ItemClasses[Index: Integer]: CItem read GetItemClass;
// Root of a hierarchy
property Root: TRootItem read FRoot write SetRoot;
end;
// Modifies or creates (if Item is nil) item with subitems from a JSON data string. Returns the item.
function SetupFromJSON(Item: TItem; const aSrc: TJSONString; Manager: TItemsManager): TItem;
// Retuns a list of the specified classes
function GetClassList(AClasses: array of TClass): TClassArray;
// Merges the two given class lists
procedure MergeClassLists(var BaseList: TClassArray; AddOnList: array of TClass);
type
TClassRec = record
ItemClass: TClass;
ModuleName: TShortName;
end;
TClassesList = class
private
TotalClasses: Integer;
FClasses: array of TClassRec;
function GetClasses: TClassArray;
function GetClassesByModule(const AModuleName: TShortName): TClassArray;
public
destructor Destroy; override;
procedure Add(const AModuleName: TShortName; AClass: TClass); overload;
procedure Add(const AModuleName: TShortName; AClasses: array of TClass); overload;
function ClassExists(AClass: TClass): Boolean;
function FindClass(AClass: TClass): TClassRec;
function FindClassByName(const AModuleName, AClassName: TShortName): TClassRec;
property Classes: TClassArray read GetClasses;
property ClassesByModule[const AModuleName: TShortName]: TClassArray read GetClassesByModule;
end;
var
GlobalClassList: TClassesList;
implementation
uses ItemMsg;
function GetClassList(AClasses: array of TClass): TClassArray;
begin
Result := nil;
MergeClassLists(Result, AClasses);
end;
procedure MergeClassLists(var BaseList: TClassArray; AddOnList: array of TClass);
var i, OldLen: Integer;
begin
OldLen := Length(BaseList);
SetLength(BaseList, OldLen + Length(AddOnList));
for i := 0 to High(AddOnList) do BaseList[OldLen + i] := AddOnList[i];
end;
{ TItemsManager }
procedure TItemsManager.OnDestroy;
begin
ClearItems;
StateNames := nil;
FreeAndNil(AsyncMessages);
end;
constructor TItemsManager.Create;
begin
AsyncMessages := TMessageSubsystem.Create;
RegisterItemClass(TItem);
RegisterItemClass(TRootItem);
RegisterItemClass(TDummyItem);
RegisterItemClass(TSyncItem);
RegisterState('Removed');
RegisterState('Released');
RegisterState('Uninitialized');
RegisterState('Picked');
RegisterState('Render');
RegisterState('Process');
RegisterState('Draw bounds');
end;
destructor TItemsManager.Destroy;
begin
OnDestroy;
inherited;
end;
function TItemsManager.GetTotalProcessingClasses: Integer;
begin
Result := Length(ProcessingClasses);
end;
procedure TItemsManager.SendAsyncMessage(const Msg: TMessage; Recipient: TItem);
begin
Assert((Recipient = nil) or not (mfRecipient in Msg.Flags), 'TItemsManager.SendAsyncMessage: Invalid recipient');
Assert([mfRecipient, mfChilds, mfBroadcast, mfCore] * Msg.Flags <> [], 'TItemsManager.SendAsyncMessage: Invalid message flags');;
if ([mfRecipient, mfChilds] * Msg.Flags <> []) then
AsyncMessages.Add(TMessageEnvelope.Create(Recipient, Msg)) else
AsyncMessages.Add(Msg);
end;
procedure TItemsManager.SendMessage(const Msg: TMessage; Recipient: TItem; Destination: TMessageFlags);
begin
Assert(Assigned(Msg));
Assert(Destination <> [], 'Invalid destination');
// Assert((Destination <> []) and
// (not (mdRecipient in Destination) or not (mdChilds in Destination)), 'Invalid destination');
if ([mfRecipient, mfChilds] * Destination <> []) then
Assert(Assigned(Recipient))
else
Recipient := nil;
if (mfBroadcast in Destination) and not Assigned(Recipient) then begin
if Assigned(Root) then Recipient := Root else Exclude(Destination, mfBroadcast);
end;
// Msg.Flags := Destination;
{
if mdRecipient in Destination then Msg.Flags := Msg.Flags + [mfRecipient];
if mdBroadcast in Destination then Msg.Flags := Msg.Flags + [mfBroadcast];
if mdCore in Destination then Msg.Flags := Msg.Flags + [mfCore];
if mdChilds in Destination then Msg.Flags := Msg.Flags + [mfNotification];}
if mfAsync in Destination then SendAsyncMessage(Msg, Recipient) else begin
if mfCore in Destination then begin
Msg.Flags := [mfCore];
HandleMessage(Msg);
end;
if mfRecipient in Destination then begin
Msg.Flags := [mfRecipient];
Recipient.HandleMessage(Msg);
end;
if mfChilds in Destination then begin
Msg.Flags := [mfChilds];
Recipient.NotifyChilds(Msg);
end;
if mfBroadcast in Destination then begin
Msg.Flags := [mfBroadcast];
Recipient.BroadcastMessage(Msg);
end;
end;
end;
procedure TItemsManager.HandleMessage(const Msg: TMessage);
begin
{$IFDEF DEBUGMODE}
Assert(mfCore in Msg.Flags);
{$ENDIF}
// if (Msg.ClassType = TOperationMsg) and not (ofHandled in TOperationMsg(Msg).Operation.Flags) then TOperationMsg(Msg).Operation.Free;
end;
procedure TItemsManager.ProcessAsyncMessages;
var Msg: TMessage; Recipient: TItem;
begin
AsyncMessages.BeginHandle;
while AsyncMessages.ExtractMessage(Msg) do begin
if (Msg is TMessageEnvelope) then begin
Recipient := TMessageEnvelope(Msg).Recipient;
Msg := TMessageEnvelope(Msg).Message;
end else Recipient := nil;
SendMessage(Msg, Recipient, Msg.Flags - [mfAsync]);
end;
AsyncMessages.EndHandle;
end;
function TItemsManager.IsSceneLoading: Boolean;
begin
Result := imsLoading in FState;
end;
function TItemsManager.IsShuttingdown: Boolean;
begin
Result := imsShuttingDown in FState;
end;
function TItemsManager.RegisterState(const AName: AnsiString): Boolean;
begin
Result := False;
if Length(StateNames) >= MaxStates then begin
Log(Format(ClassName + '.RegisterState: Only %D states allowed', [MaxStates]), lkError);
Exit;
end;
SetLength(StateNames, Length(StateNames)+1);
StateNames[High(StateNames)] := AName;
Result := True;
end;
procedure TItemsManager.RegisterItemClass(NewClass: CItem);
begin
if FindItemClass(AnsiString(NewClass.ClassName)) <> nil then begin
Log(ClassName + '.RegisterItemClass: Class "' + NewClass.ClassName + '" already registered', lkWarning);
Exit;
end;
SetLength(FItemClasses, TotalItemClasses+1);
FItemClasses[TotalItemClasses] := NewClass;
Inc(FTotalItemClasses);
end;
procedure TItemsManager.RegisterItemClasses(NewClasses: array of TClass);
var i: Integer;
begin
for i := 0 to High(NewClasses) do if NewClasses[i].InheritsFrom(TItem) then RegisterItemClass(CItem(NewClasses[i]));
end;
function TItemsManager.FindItemClass(const AName: AnsiString): CItem;
var i: Integer;
begin
Result := nil;
i := TotalItemClasses-1;
while (i >= 0) and (ItemClasses[i].ClassName <> AName) do Dec(i);
if i >= 0 then Result := ItemClasses[i];
end;
function TItemsManager.ChangeClass(Item: TItem; NewClass: CItem): TItem;
var i: Integer; Props: TProperties;
begin
Result := nil;
if Item = nil then begin
Log(ClassName + '.ChangeClass: Item is undefined', lkError);
Exit;
end;
Result := NewClass.Construct(Item.FManager);
// Copy childs
Result.FTotalChilds := Item.TotalChilds;
SetLength(Result.FChilds, Length(Item.FChilds));
for i := 0 to High(Item.FChilds) do begin
Result.FChilds[i] := Item.FChilds[i];
if Result.FChilds[i] <> nil then Result.FChilds[i].FParent := Result;
end;
// Copy state and parent
Result.FState := Item.FState;
Result.FParent := Item.FParent;
Result.IndexInParent := Item.IndexInParent;
// Copy object links data
SetLength(Result.ItemLinks, Length(Item.ItemLinks));
for i := 0 to High(Item.ItemLinks) do Result.ItemLinks[i] := Item.ItemLinks[i];
// Replace the item in parent's collection
if Result = FRoot then begin
if not (Result is TRootItem) then begin
Log(ClassName + '.ChangeClass: Root item'' class should be TRootItem or one of its descendants', lkError);
TObject(Result).Destroy; // There is no need to call FreeChilds
Result := nil;
Exit;
end;
FRoot := Result as TRootItem;
end else Item.Parent.FChilds[Item.IndexInParent] := Result;
if isNeedInit in Result.FState then SendMessage(ItemMsg.TInitMsg.Create, Result, [mfRecipient]);
Props := TProperties.Create;
Item.GetProperties(Props);
Result.SetProperties(Props);
FreeAndNil(Props);
SendMessage(ItemMsg.TReplaceMsg.Create(Item, Result), Item, [mfRecipient, mfBroadcast, mfCore]);
Item.DeAlloc;
end;
procedure TItemsManager.RemoveItem(Item: TItem);
begin
if Item = nil then Exit;
if Item.Parent <> nil then Item.Parent.RemoveChild(Item);
if Item = FRoot then FRoot := nil;
end;
procedure TItemsManager.ClearItems;
begin
SendMessage(TSceneClearMsg.Create, nil, [mfCore]);
Include(FState, imsShuttingDown);
if FRoot <> nil then begin
FRoot.OnSceneRemove;
FRoot.FreeChilds;
FRoot.Free;
FRoot := nil;
end;
Exclude(FState, imsShuttingDown);
end;
function TItemsManager.LoadItem(Stream: TStream; AParent: TItem): TItem;
var s: AnsiString; ItemClass: CItem;
begin
Result := nil;
if not LoadString(Stream, s) then Exit;
// s := 'TItem';
// if s = 'TCBitmapFont' then s := 'TBitmapFont';
if s = 'TTextureResource' then s := 'TImageResource';
ItemClass := FindItemClass(s);
if ItemClass = nil then begin
Log(ClassName + '.LoadItem: Unknown item class "' + s + '". Substitued by TItem', lkError);
ItemClass := TItem;
end;
Result := ItemClass.Create(Self);
if Assigned(AParent) and ((FRoot = nil) or (AParent.FManager <> Self)) then begin
Log(Format('%S.%S: The specified parent "%S" not found or invalid - discarding', [ClassName, 'LoadItem', AParent.Name]), lkError);
AParent := nil;
end;
if (AParent = nil) then begin
if Result.InheritsFrom(TRootItem) then begin
if Assigned(FRoot) then Log(ClassName + '.LoadItem: replacing existing root item', lkWarning);
FRoot := Result as TRootItem;
end else begin
Log(Format('%S.%S: A descendant of TRootItem expected but an item of class "%S" got. Using existing root item.', [ClassName, 'LoadItem', Result.ClassName]), lkWarning);
if Assigned(FRoot) then
AParent := FRoot else begin
ErrorHandler(TSceneLoadError.Create(Format('%S.%S: No root item.', [ClassName, 'LoadItem'])));
FreeAndNil(Result);
Exit;
end;
end;
end else if Result.InheritsFrom(TRootItem) then begin
Log(ClassName + '.LoadItem: Additional root item found', lkNotice);
end;
if AParent <> nil then AParent.DoAddChild(Result);
if isNeedInit in Result.FState then SendMessage(ItemMsg.TInitMsg.Create, Result, [mfRecipient]);
if Result.Load(Stream) then
SendMessage(ItemMsg.TAddToSceneMsg.Create(Result), Result, [mfCore, mfRecipient])
else
Result := nil;
// if not Result.Load(Stream) then Result := nil;
end;
function TItemsManager.LoadScene(Stream: TStream): Boolean;
var Item: TItem;
begin
Result := False;
ClearItems;
Include(FState, imsLoading);
Item := LoadItem(Stream, nil);
Exclude(FState, imsLoading);
if Item is TRootItem then begin
FRoot := Item as TRootItem;
Log(ClassName + '.LoadScene: Scene load successful', lkNotice);
SendMessage(ItemMsg.TSceneLoadedMsg.Create, nil, [mfBroadcast, mfCore]);
Result := True;
end;
end;
function TItemsManager.SaveScene(Stream: TStream): Boolean;
begin
Result := FRoot.Save(Stream);
if Result then Log(ClassName + '.SaveScene: Scene save successful', lkNotice);
end;
procedure TItemsManager.CollectGarbage;
var i: Integer; Items: TItems;
begin
for i := 0 to FRoot.ExtractByMask([isRemoved], False, Items)-1 do begin
Items[i].Parent.RemoveChild(Items[i]);
if isReleased in Items[i].State then begin
Items[i].Free;
end;
end;
Items := nil;
end;
procedure TItemsManager.SetRoot(const Value: TRootItem);
begin
FRoot := Value;
FRoot.FManager := Self;
end;
function TItemsManager.GetItemClass(Index: Integer): CItem;
begin
Result := FItemClasses[Index];
end;
function TItemsManager.GetProcClassesEnum: AnsiString;
var i: Integer;
begin
Result := 'None';
// if (Parent <> nil) or (Root <> Self) then Exit;
for i := 0 to TotalProcessingClasses-1 do begin
Result := Result + '\&' + IntToStrA(i) + ':';
if pfDeltaTimeBased in ProcessingClasses[i].Flags then
Result := Result + ' Delta time-based'
else
Result := Result + ' Every ' + IntToStrA(Round(ProcessingClasses[i].Interval * 1000)) + ' ms';
if pfIgnorePause in ProcessingClasses[i].Flags then Result := Result + ', ignore pause';
end;
end;
{ TItem }
type
TLinkParam = record
CachedProps: TProperties; // Cached properties for object links management
LastCachedPropsClass: TClass; // Item class of which properties last cached in TempProps
CurLinkIndex: Integer; // Index of current object link
end;
threadvar
LinksParams: array of TLinkParam;
CurrentLinkParam: Integer;
procedure NewLinksParameters;
begin
SetLength(LinksParams, Length(LinksParams)+1);
LinksParams[High(LinksParams)].CachedProps := TProperties.Create;
end;
procedure TItem.SetName(const Value: AnsiString);
var OldName: ShortString;
begin
if FName = Value then Exit;
OldName := GetFullName();
FName := Value;
{$IFDEF DEBUGMODE} if FConsistent then {$ENDIF}
if Assigned(FManager) then SendMessage(TItemNameModifiedMsg.Create(Self, OldName), nil, [mfCore]);
end;
/// Changes childs's index to NewIndex, preserving the order of other childs
/// NewIndex clamps if it is outside childs collection
procedure TItem.ChangeChildIndex(Child: TItem; NewIndex: Integer);
var i: Integer;
begin
if not Assigned(FChilds) then Exit;
NewIndex := MaxI(0, MinI(TotalChilds-1, NewIndex));
if NewIndex = Child.IndexInParent then Exit;
// 0 1 2 3 4 5 6 7
// 0 1 4 2 3 5 6 7
// 0 1 2 3 5 6 4 7
if NewIndex < Child.IndexInParent then begin
for i := Child.IndexInParent-1 downto NewIndex do begin
FChilds[i+1] := FChilds[i];
FChilds[i+1].IndexInParent := i+1;
end;
end else begin
for i := Child.IndexInParent to NewIndex-1 do begin
FChilds[i] := FChilds[i+1];
FChilds[i].IndexInParent := i;
end;
end;
FChilds[NewIndex] := Child;
Child.IndexInParent := NewIndex;
end;
function TItem.GetLinkIndex(const AName: AnsiString): Integer;
// Returns an index in ItemLinks array by property's name
begin
for Result := 0 to High(ItemLinks) do
if ItemLinks[Result].PropName = AName then Exit;
Result := -1;
end;
function TItem.SetLinkedObjectByIndex(Index: Integer; Linked: TItem): Boolean;
// Sets Linked as resolved linked object for LinkedObjects[Index]. Returns true if Linked passes type checking
begin
Result := False;
if (Linked is ItemLinks[Index].BaseClass) then begin
ItemLinks[Index].Item := Linked;