Debian Codegraph @

src/deprecated_units/castleresources.pas

raw
1 {
2 Copyright 2006-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" 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.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Manage resources with animations that may be reused by multiple instances.
17 This is in practice used for creatures and items animations in our
18 "Utilities for typical 3D games", https://castle-engine.io/manual_high_level_3d_classes.php .
19
20 Note that you @italic(do not) need this unit in many normal cases when dealing with animations.
21 It is generally simpler and more adviced to use TCastleScene and TCastleScene.PlayAnimation
22 to play animations, see https://castle-engine.io/manual_scene.php . }
23 unit CastleResources
24 deprecated 'manage scenes and their animations using TCastleScene';
25
26 {$I castleconf.inc}
27
28 interface
29
30 uses Classes, DOM, Generics.Collections,
31 CastleVectors, CastleXMLConfig, CastleTimeUtils, CastleFrustum, CastleClassUtils,
32 CastleScene, X3DNodes, CastleTransform, CastleBoxes, CastleFindFiles,
33 CastleSectors;
34
35 type
36 T3DResource = class;
37
38 { Animation defined by T3DResource. }
39 T3DResourceAnimation = class
40 private
41 type
42 { Container for a loaded TCastleScene,
43 which may be specific inside animation (T3DResourceAnimation),
44 or may be common to all animations (one scene for the whole T3DResource). }
45 TSceneState = record
46 Scene: TCastleScene;
47 InitialBox: TBox3D; //< Defined only once Scene <> nil
48
49 ForcedAnimationName: String;
50 ForcedLoop: Boolean;
51 ForcedActualTime: TFloatTime;
52
53 { Prepare scene loading from given URL.
54 Loads the scene only if URL is not empty and if it's not already loaded (that is, when Scene = nil).
55 Prepares for fast rendering and other processing by TCastleTransform.PrepareResources.
56 Calls Progress.Step 2 times, if DoProgress. }
57 procedure Prepare(const Url: String; const Resource: T3DResource;
58 const PrepareParams: TPrepareParams; const DoProgress: Boolean);
59 end;
60 var
61 FName: string;
62 FRequired: boolean;
63 FOwner: T3DResource;
64 FSceneState: TSceneState;
65 FDuration: Single;
66 FUrl: String;
67 FAnimationName: string;
68 procedure Prepare(const Params: TPrepareParams; const DoProgress: boolean);
69 procedure Release;
70 procedure LoadFromFile(ResourceConfig: TCastleConfig);
71 property Owner: T3DResource read FOwner;
72
73 { Current Scene to render for given time.
74
75 Looping is automatically done here, if parameter Loop is @true.
76 When it is @false, there is no looping, which means that
77 when Time is < 0, we show the first frame,
78 and when Time is > @link(Duration), we show the last frame forever.
79
80 This returns the scene (TCastleScene) with state reflecting given time
81 (TimeSensor forced to given time).
82
83 Note that this should not be used if owner resource uses pooling.
84 In case of pooling, not ForceAnimationPose calls should be done
85 (which is what this method does). }
86 function SceneAtTime(const Time: TFloatTime; const Loop: boolean): TCastleScene;
87 public
88 constructor Create(const AOwner: T3DResource;
89 const AName: string; const ARequired: boolean = true);
90
91 { Duration of the animation. See engine tutorial about how resources animations
92 duration is calculated. Always 0 if not @link(Defined). }
93 property Duration: Single read FDuration;
94 function BoundingBox: TBox3D;
95
96 { Was the animation state defined in resource.xml file.
97 May be @false only if @link(Required) was @false, or before we actually
98 read animation info from resource.xml file. }
99 function Defined: boolean;
100
101 { Scene URL, only when each animation is inside a separate 3D file.
102 See [https://castle-engine.io/creating_data_resources.php]
103 for documentation how you can define creature animations. }
104 property Url: String read FUrl write FUrl; {$ifdef FPC}deprecated 'do not use separate URLs for each animation; use one URL with all animations; see https://castle-engine.io/creating_data_resources.php';{$endif}
105
106 { Animation name (like for @link(TCastleSceneCore.PlayAnimation)),
107 which is equal to TimeSensor node name.
108 All animations are started by X3D TimeSensor node.
109 If not given, we assume it's just 'animation', which is fine
110 at least for castle-anim-frames and MD3 files loaded using TNodeInterpolator.
111 This refers to an X3D TimeSensor node inside
112 animation model (from @link(Url)) or, when not defined,
113 inside whole resource model (from @link(T3DResource.ModelUrl)).
114
115 See [https://castle-engine.io/creating_data_resources.php]
116 for documentation how you can define creature animations. }
117
118 property AnimationName: string read FAnimationName write FAnimationName;
119 {$ifdef FPC}
120 property TimeSensor: string read FAnimationName write FAnimationName;
121 deprecated 'use AnimationName';
122 {$endif}
123 property Name: string read FName;
124 property Required: boolean read FRequired;
125 end;
126
127 T3DResourceAnimationList = class({$ifdef FPC}specialize{$endif} TObjectList<T3DResourceAnimation>)
128 { Find an animation by name.
129 @raises Exception if not found. }
130 function FindName(const AName: string): T3DResourceAnimation;
131 end;
132
133 TAbstractLevel = class;
134
135 { Display a specified frame of the specified animation.
136 This is reliable even when multiple TResourceFrame request different frames
137 from the same animation. }
138 TResourceFrame = class(TCastleTransform)
139 strict private
140 FAnimation: T3DResourceAnimation;
141 FTime: TFloatTime;
142 FLoop: boolean;
143 CurrentChild: TCastleScene;
144 CurrentChildFromPool: Boolean;
145 ResourceObserver: TFreeNotificationObserver;
146 procedure ResourceFreeNotification(const Sender: TFreeNotificationObserver);
147 protected
148 procedure LocalRender(const Params: TRenderParams); override;
149 public
150 constructor Create(AOwner: TComponent); override;
151 destructor Destroy; override;
152 property Animation: T3DResourceAnimation read FAnimation;
153 { Time within the ResourceAnimation. }
154 property Time: TFloatTime read FTime;
155 { Should we loop within ResourceAnimation. }
156 property Loop: boolean read FLoop;
157 { Set which animation and animation frame to display. }
158 procedure SetFrame(const Level: TAbstractLevel;
159 const AnAnimation: T3DResourceAnimation;
160 const ATime: TFloatTime; const ALoop: boolean);
161 end;
162
163 { Abstract level information, with information useful to spawn resources
164 like creatures and items. }
165 TAbstractLevel = class(TComponent)
166 public
167 function GetPlayer: TCastleTransform; virtual; abstract;
168 function GetSectors: TSectorList; virtual; abstract;
169 function RootTransform: TCastleRootTransform; virtual; abstract;
170 { All creatures are children of this.
171 Allows to easily hide them. }
172 function CreaturesRoot: TCastleTransform; virtual; abstract;
173 { All items are children of this.
174 Allows to easily hide them. }
175 function ItemsRoot: TCastleTransform; virtual; abstract;
176 { Parameters to prepare rendering for,
177 see @link(TCastleViewport.PrepareParams). }
178 function PrepareParams: TPrepareParams; virtual; abstract;
179 { Use this as Owner of any TComponent, to have something automatically freed
180 when level is being unloaded (at @link(TLevel.Unload) call,
181 or at @link(TLevel.Load) of new level,
182 or at destruction of this TLevel). }
183 function FreeAtUnload: TComponent; virtual; abstract;
184 end;
185
186 { Resource used for rendering and processing of 3D objects.
187 By itself this doesn't render or do anything.
188 But some 3D objects may need to have such resource prepared to work.
189
190 It can also load it's configuration from XML config file.
191 For this purpose, it has a unique identifier in @link(Name) property.
192
193 Name (from TComponent.Name) is a unique identifier of this resource.
194 Used to refer to this resource from level placeholders
195 (see TLevel.Load about placeholders),
196 from other XML files (for example one creature may shoot another
197 creature as a missile using @link(TWalkAttackCreatureResource.FireMissileName)),
198 and in other places.
199
200 Name can use only letters, use CamelCase.
201 Reason: This must be a valid identifier in both VRML/X3D and ObjectPascal.
202 Also digits and underscores are reserved, as we may use them to get other
203 information from placeholder names. }
204 T3DResource = class(TComponent)
205 private
206 FPrepared: boolean;
207 FUsageCount: Cardinal;
208 FConfigAlwaysPrepared: boolean;
209 FFallSpeed, FGrowSpeed: Single;
210 FAnimations: T3DResourceAnimationList;
211 FReceiveShadowVolumes: boolean;
212 FCastShadowVolumes: boolean;
213 FDefaultAnimationTransition: Single;
214 FModelUrl: String;
215 { Model loaded from ModelUrl }
216 ModelState: T3DResourceAnimation.TSceneState;
217 { Non-nil only if we're using Pool to allocate scenes for resource instances.
218 See @link(Pool) description. }
219 ScenePool: TCastleSceneList;
220 { First ScenePoolUsed items on ScenePool are used, rest is unused. }
221 ScenePoolUsed: Cardinal;
222 FPool: Cardinal;
223 FOrientation: TOrientationType;
224 function AllocateSceneFromPool(const Level: TAbstractLevel): TCastleScene;
225 procedure ReleaseSceneFromPool(const Scene: TCastleScene);
226 function CreateSceneForPool(const Params: TPrepareParams): TCastleScene;
227 protected
228 { Prepare or release everything needed to use this resource.
229 PrepareCore and ReleaseCore should never be called directly,
230 they are only to be overridden in descendants.
231 These are used by actual @link(Prepare) and @link(Release)
232 when the actual allocation / deallocation should take place
233 (when UsageCount raises from zero or drops back to zero).
234
235 ReleaseCore is also called in destructor, regardless of UsageCount.
236 This is done to free resources even if user forgot to call Release
237 before destroying this resource instance.
238
239 PrepareCore must call Progress.Step exactly PrepareCoreSteps times,
240 only if DoProgress.
241 This allows to make nice progress bar in @link(Prepare).
242 In this class, PrepareCoreSteps returns 0.
243 @groupBegin }
244 procedure PrepareCore(const Params: TPrepareParams;
245 const DoProgress: boolean); virtual;
246 function PrepareCoreSteps: Cardinal; virtual;
247 procedure ReleaseCore; virtual;
248 { @groupEnd }
249 public
250 const
251 DefaultFallSpeed = 10.0;
252 DefaultGrowSpeed = 5.0;
253 DefaultReceiveShadowVolumes = true;
254 DefaultCastShadowVolumes = true;
255
256 constructor Create(AOwner: TComponent); override;
257 destructor Destroy; override;
258
259 { Are we in a (fully) prepared state. That is after a (fully successful)
260 @link(Prepare) call and before @link(Release).
261 Note that this is slightly different than checking @code(UsageCount <> 0):
262 in some situations, UsageCount may be non-zero while the preparation
263 is not finished yet. This property is guaranteed to be @true only if
264 preparation was fully successfully (no exceptions) finished. }
265 property Prepared: boolean read FPrepared;
266
267 procedure LoadFromFile(ResourceConfig: TCastleConfig); virtual;
268
269 { Release and then immediately prepare again this resource.
270 Call only when UsageCount <> 0, that is when resource is prepared.
271 Shows nice progress bar, using @link(Progress). }
272 procedure RedoPrepare(const Params: TPrepareParams);
273
274 { How many times this resource is used. Used by Prepare and Release:
275 actual allocation / deallocation happens when this raises from zero
276 or drops back to zero. }
277 property UsageCount: Cardinal
278 read FUsageCount write FUsageCount default 0;
279
280 { Prepare or release everything needed to use this resource.
281
282 There is an internal counter tracking how many times given
283 resource was prepared and released. Which means that preparing
284 and releasing resource multiple times is correct --- but make
285 sure that every single call to prepare is paired with exactly one
286 call to release. Actual allocation / deallocation
287 (when protected methods PrepareCore, ReleaseCore are called)
288 happens only when UsageCount raises from zero or drops back to zero.
289
290 Show nice progress bar, using @link(Progress).
291
292 @param(Params
293 World parameters to prepare for.
294 See @link(TCastleTransform.PrepareResources) for more comments.)
295
296 @groupBegin }
297 procedure Prepare(const Params: TPrepareParams; const GravityUp: TVector3); overload;
298 deprecated 'use Prepare overload without the GravityUp parameter';
299 procedure Prepare(const Params: TPrepareParams); overload;
300 procedure Release;
301 { @groupEnd }
302
303 { Place an instance of this resource on World, using information
304 from the placeholder on the level. }
305 procedure InstantiatePlaceholder(
306 const ALevel: TAbstractLevel;
307 const APosition, ADirection: TVector3;
308 const NumberPresent: boolean; const Number: Int64); virtual; abstract;
309
310 { Animations of this resource.
311
312 The first animation, if exists, right now determines the default radius
313 calculation. So the first animation should have the bounding box
314 representative for all animations.
315 Other than that, the order on this list doesn't matter.
316
317 The properties of these animations are automatically loaded from
318 resource.xml file in LoadFromFile. The animations are automatically
319 prepared / released by our @link(Prepare) / @link(Release) methods. }
320 property Animations: T3DResourceAnimationList read FAnimations;
321
322 { Mechanics of given game may suggest that some 3D resources should
323 always be prepared. For example, in typical 3D game when player
324 has inventory and can drop items from inventory on the ground,
325 then all items should be prepared for all levels, since you can in theory
326 drop everything anywhere.
327
328 Return @true if this is such resource.
329
330 Default implementation in T3DResource returns here the ConfigAlwaysPrepared
331 value, which may be set in resource.xml and by default is false.
332 This allows to configure this using resource.xml files.
333 Descendants may choose to override this, to override value from resource.xml
334 file. }
335 function AlwaysPrepared: boolean; virtual;
336
337 property ConfigAlwaysPrepared: boolean
338 read FConfigAlwaysPrepared write FConfigAlwaysPrepared default false;
339
340 { The speed (in units per second) of falling down because of gravity.
341 Note that the gravity direction is controlled by your level 3D model,
342 see "Which way is up" section in the engine tutorial
343 https://castle-engine.io/manual_up.php .
344
345 Currently, falling down of creatures and items just uses this constant speed.
346 In the future, we plan to add properties to control mass and air friction
347 and perform more physically-correct simulation of falling down.
348
349 This has no effect for creatures with TCreatureResource.Flying = @true.
350 This also has no effect for missile creatures (their
351 TCreatureResource.Flying is ignored, they have special approach
352 to gravity).
353
354 See TCastleTransform.FallSpeed for precise definition, this works the same,
355 except our default value is non-zero, and by default TCastleTransform.Gravity
356 and TCastleTransform.PreferredHeight are already sensible for creatures/items. }
357 property FallSpeed: Single
358 read FFallSpeed write FFallSpeed {$ifdef FPC}default DefaultFallSpeed{$endif};
359
360 { The speed (in units per second) of growing.
361
362 "Growing" is used to allow non-flying creatures to climb stairs.
363 The creature can move whenever a sphere (see TCreatureResource.MiddleHeight
364 and TCreatureResource.Radius) can move. This means that part of the bounding
365 box (part of the TCastleTransform.PreferredHeight) may temporarily
366 "sink" into the ground. Then growing, controlled by this property,
367 pushes the creature up.
368
369 See TCastleTransform.GrowSpeed, this works the same,
370 except the default value is non-zero, and by default TCastleTransform.Gravity
371 and TCastleTransform.PreferredHeight are already sensible for creatures/items. }
372 property GrowSpeed: Single
373 read FGrowSpeed write FGrowSpeed {$ifdef FPC}default DefaultGrowSpeed{$endif};
374
375 property ReceiveShadowVolumes: boolean
376 read FReceiveShadowVolumes write FReceiveShadowVolumes
377 default DefaultReceiveShadowVolumes;
378 property CastShadowVolumes: boolean
379 read FCastShadowVolumes write FCastShadowVolumes
380 default DefaultCastShadowVolumes;
381
382 { See @link(TCastleSceneCore.DefaultAnimationTransition) }
383 property DefaultAnimationTransition: Single
384 read FDefaultAnimationTransition write FDefaultAnimationTransition {$ifdef FPC}default 0.0{$endif};
385
386 { See @link(TCastleTransform.Orientation), by default this is @link(TCastleTransform.DefaultOrientation).
387
388 In the resource.xml file, this value can be specified using following strings:
389
390 @definitionList(
391 @itemLabel @code(default)
392 @item Use TCastleTransform.DefaultOrientation.
393 @itemLabel @code(up:y,direction:-z)
394 @item Use otUpYDirectionMinusZ.
395 @itemLabel @code(up:y,direction:z)
396 @item Use otUpYDirectionZ. Matches conventional glTF orientation.
397 @itemLabel @code(up:z,direction:-y)
398 @item Use otUpZDirectionMinusY.
399 @itemLabel @code(up:z,direction:x)
400 @item Use otUpZDirectionX.
401 ) }
402 property Orientation: TOrientationType read FOrientation write FOrientation;
403
404 { Model URL, only when you define multiple animations inside
405 a single 3D file. See
406 [https://castle-engine.io/creating_data_resources.php]
407 for notes about <model> element in resource.xml files. }
408 property ModelUrl: String read FModelUrl write FModelUrl;
409
410 { If non-zero, use a pool of TCastleScene to create resource instances.
411
412 To understand what this controls, some explanation is necessary:
413 Multiple instances of the same creature / item may be visible.
414 They all refer to the same "resource" holding one set of data.
415 Our resources mechanism is prepared to handle it efficiently, in 2 ways:
416
417 @orderedList(
418 @item(
419 Without pool: We have a single TCastleScene, which is internally continuosly changed
420 back-and-forth to show various animations (and various moment of these animations),
421 to display all resource instances correctly.
422
423 Advantages: Less loading time, less memory usage (no need to create pool).
424
425 Disadvantages:
426 Worse FPS (need to switch back-and-forth) and no animation blending support.
427 )
428
429 @item(
430 With pool: Each resource instance gets a copy of TCastleScene.
431 This avoids switching one scene back-and-forth.
432 It's particularly beneficial for animations like from glTF or Spine JSON
433 (in general: animations from formats other than castle-anim-frames).
434
435 We keep a pool of TCastleScene that can be allocated for the needed instances.
436
437 The "pool" attribute specifies the initial pool size.
438 It should be large enough to cover practical needs.
439 If it's not large enough then, when necessary, we will increase this pool at runtime,
440 which works but causes one-time lag during game execution
441 (as we need to make TCastleScene.Clone).
442
443 This approach also allows for animation blending. (TODO: in the future)
444
445 Disadvantages: More loading time and memory usage (for pool).
446
447 Advantages:
448 Better FPS and support for animation blending.
449 In general, this uses TCastleScene in more standard way.
450 )
451 )
452
453 Note that Pool only matters if you use a single file
454 for all resource animations. Using multiples files (separate file for each animation)
455 is deprecated anyway, see https://castle-engine.io/creating_data_resources.php .
456
457 In the @code(resource.xml), you can specify this value an explicit integer
458 (0 means to not use pool), or you can write @code("auto") to automatically guess
459 the best value. The best value means to use pool, unless the ModelUrl indicates castle-anim-frames
460 or MD3 formats.
461 }
462 property Pool: Cardinal read FPool write FPool default 0;
463 end;
464
465 T3DResourceClass = class of T3DResource;
466
467 T3DResourceList = class({$ifdef FPC}specialize{$endif} TObjectList<T3DResource>)
468 private
469 ResourceXmlReload: boolean;
470 procedure AddFromInfo(const FileInfo: TFileInfo; var StopSearch: boolean);
471 procedure AddFromFileDefaultReload(const Url: String);
472 public
473 { Find resource with given T3DResource.Name.
474 @raises Exception if not found and NilWhenNotFound = false. }
475 function FindName(const AName: string; const NilWhenNotFound: boolean = false): T3DResource;
476
477 { Load all resources (creatures and items) information from
478 resource.xml files found in given Path.
479 Overloaded version without Path just scans the whole castle-data:/
480 directory.
481
482 Note that on Android, searching the Android asset filesystem
483 recursively is not possible (this is a fault of Android NDK API...).
484 So instead of this method, you should use AddFromFile repeatedly
485 to explicitly list all resource.xml locations.
486
487 @param(Reload
488 If Reload, then we will not clear the initial list contents.
489 Instead, resource.xml files found that refer to the existing T3DResource.Name
490 will cause T3DResource.LoadFromFile call on an existing resource.
491 Using Reload is a nice debug feature, if you want to reload configuration
492 from resource.xml files (and eventually add new resources in new resource.xml files),
493 but you don't want to recreate existing resource instances.)
494
495 @groupBegin }
496 procedure LoadFromFiles(const Path: string; const Reload: boolean = false); overload;
497 procedure LoadFromFiles(const Reload: boolean = false); overload;
498 { @groupEnd }
499
500 { Load a single resource from resource.xml file.
501
502 @param(Reload If @true, and the loaded resource will have a name
503 matching existing T3DResource.Name, we will replace the current resource.
504 Otherwise, we'll make an exception.) }
505 procedure AddFromFile(const Url: String; const Reload: boolean = false);
506
507 { Reads <prepare_resources> XML element.
508 <prepare_resources> element is an optional child of given ParentElement.
509 Sets current list value with all mentioned required
510 resources (subset of @link(Resources)). }
511 procedure LoadResources(ParentElement: TDOMElement);
512
513 { Prepare / release all resources on list.
514 @groupBegin }
515 procedure Prepare(const Params: TPrepareParams;
516 const ResourcesName: string = 'resources');
517 procedure Release;
518 { @groupEnd }
519 end;
520
521 { All known resources.
522 Usually you call @link(T3DResourceList.LoadFromFiles Resources.LoadFromFiles)
523 to fill this list, based on resource.xml files present in your data. }
524 function Resources: T3DResourceList;
525
526 { Register a resource class, to allow creating resources (like a creature or item)
527 of this class by using appropriate type="xxx" inside resource.xml file. }
528 procedure RegisterResourceClass(const AClass: T3DResourceClass; const TypeName: string);
529
530 implementation
531
532 {$warnings off} // using deprecated CastleProgress in deprecated
533 uses SysUtils,
534 CastleProgress, CastleXmlUtils, CastleUtils, CastleSceneCore,
535 CastleStringUtils, CastleLog, CastleConfig, CastleApplicationProperties,
536 CastleFilesUtils, CastleInternalNodeInterpolator, CastleUriUtils;
537 {$warnings on}
538
539 var
540 UnitFinalization: Boolean;
541
542 const
543 ScenePrepareResources = [prRenderSelf, prBoundingBox, prShadowVolume];
544
545 { TResourceClasses ---------------------------------------------------------- }
546
547 type
548 TResourceClasses = class({$ifdef FPC}specialize{$endif} TDictionary<string, T3DResourceClass>)
549 strict private
550 function GetItems(const AKey: string): T3DResourceClass;
551 procedure SetItems(const AKey: string; const AValue: T3DResourceClass);
552 public
553 { Access dictionary items.
554 Setting this is allowed regardless if the key previously existed or not,
555 in other words: setting this does AddOrSetValue, contrary to the ancestor TDictionary
556 that only allows setting when the key already exists. }
557 property Items [const AKey: string]: T3DResourceClass read GetItems write SetItems; default;
558 end;
559
560 function TResourceClasses.GetItems(const AKey: string): T3DResourceClass;
561 begin
562 Result := inherited Items[AKey];
563 end;
564
565 procedure TResourceClasses.SetItems(const AKey: string; const AValue: T3DResourceClass);
566 begin
567 AddOrSetValue(AKey, AValue);
568 end;
569
570 var
571 FResourceClasses: TResourceClasses;
572
573 function ResourceClasses: TResourceClasses;
574 begin
575 if (FResourceClasses = nil) and not UnitFinalization then
576 FResourceClasses := TResourceClasses.Create;
577 Result := FResourceClasses;
578 end;
579
580 { T3DResourceAnimation.TSceneState ------------------------------------------- }
581
582 procedure T3DResourceAnimation.TSceneState.Prepare(
583 const Url: String; const Resource: T3DResource;
584 const PrepareParams: TPrepareParams; const DoProgress: Boolean);
585 begin
586 if (Url <> '') and (Scene = nil) then
587 begin
588 Scene := TCastleScene.Create(nil);
589 Scene.Load(Url);
590 Scene.ReceiveShadowVolumes := Resource.ReceiveShadowVolumes;
591
592 { save initial Scene bounding box,
593 to avoid later changing T3DResourceAnimation.BoundingBox
594 result after some animation run and modified scene.
595 This would cause creature radius change.
596
597 Testcase: examples/animations/deprecated_resource_animations,
598 load same resource 2x in a row,
599 bounding sphere should not change. }
600 InitialBox := Scene.BoundingBox;
601
602 // reset ForcedXxx fields
603 ForcedAnimationName := '';
604 ForcedLoop := false;
605 ForcedActualTime := 0;
606 end;
607 if DoProgress then Progress.Step;
608
609 {$warnings off} // using deprecated in deprecated
610 if Scene <> nil then
611 Scene.PrepareResources(ScenePrepareResources, PrepareParams);
612 {$warnings on}
613 if DoProgress then Progress.Step;
614 end;
615
616 { T3DResourceAnimation ------------------------------------------------------- }
617
618 constructor T3DResourceAnimation.Create(const AOwner: T3DResource;
619 const AName: string; const ARequired: boolean);
620 begin
621 inherited Create;
622 FName := AName;
623 FRequired := ARequired;
624 FOwner := AOwner;
625 AOwner.Animations.Add(Self);
626 end;
627
628 { $define STATISTICS_FORCING_OPTIMIZATION}
629 {$ifdef STATISTICS_FORCING_OPTIMIZATION}
630 var
631 Necessary, Avoided: Int64;
632 {$endif}
633
634 function T3DResourceAnimation.SceneAtTime(const Time: TFloatTime;
635 const Loop: boolean): TCastleScene;
636
637 procedure ForceTime(var SceneState: TSceneState);
638 var
639 GoodAnimationName: string;
640 ActualTime: TFloatTime;
641 ForceNecessary: boolean;
642 begin
643 if AnimationName <> '' then
644 GoodAnimationName := AnimationName
645 else
646 GoodAnimationName := TNodeInterpolator.DefaultAnimationName;
647
648 // if Defined and (Duration = 0) then
649 // WritelnWarning('Animation "%s" duration is zero on resource "%s"',
650 // [GoodAnimationName, Owner.Name]);
651
652 { Calculate Time with looping/clamping applied, because we want to have
653 ForceNecessary = false as often as possible (to avoid doing work).
654 Test Duration <> 0 to avoid dividing by 0 in FloatModulo(Time, 0)
655 (testcase: fps_game debug build on Android) }
656 if Loop and (Duration <> 0) then
657 ActualTime := FloatModulo(Time, Duration)
658 else
659 ActualTime := Clamped(Time, 0, Duration);
660
661 // call (costly) ForceAnimationPose only if necessary
662 ForceNecessary :=
663 (SceneState.ForcedAnimationName <> GoodAnimationName) or
664 (SceneState.ForcedLoop <> Loop) or
665 (SceneState.ForcedActualTime <> ActualTime);
666 if ForceNecessary then
667 begin
668 SceneState.ForcedAnimationName := GoodAnimationName;
669 SceneState.ForcedLoop := Loop;
670 SceneState.ForcedActualTime := ActualTime;
671 SceneState.Scene.ForceAnimationPose(GoodAnimationName, ActualTime, Loop);
672 end;
673
674 {$ifdef STATISTICS_FORCING_OPTIMIZATION}
675 if ForceNecessary then
676 Inc(Necessary)
677 else
678 Inc(Avoided);
679 if (Necessary + Avoided) mod 100 = 0 then
680 WritelnLog('T3DResourceAnimation.Scene forcing optimization: %d necessary vs %d avoided => %f fraction of work avoided',
681 [Necessary, Avoided, Avoided / (Necessary + Avoided)]);
682 {$endif}
683 end;
684
685 begin
686 if FSceneState.Scene <> nil then
687 begin
688 ForceTime(FSceneState);
689 Result := FSceneState.Scene;
690 end else
691 if Owner.ModelState.Scene <> nil then
692 begin
693 ForceTime(Owner.ModelState);
694 Result := Owner.ModelState.Scene;
695 end else
696 Result := nil;
697 end;
698
699 function T3DResourceAnimation.BoundingBox: TBox3D;
700 begin
701 if FSceneState.Scene <> nil then
702 Result := FSceneState.InitialBox
703 else
704 if Owner.ModelState.Scene <> nil then
705 Result := Owner.ModelState.InitialBox
706 else
707 { animation 3D model not loaded }
708 Result := TBox3D.Empty;
709 end;
710
711 function T3DResourceAnimation.Defined: boolean;
712 begin
713 {$warnings off} // using deprecated to keep it working
714 Result := (Url <> '') or (AnimationName <> '');
715 {$warnings on}
716 end;
717
718 procedure T3DResourceAnimation.Prepare(const Params: TPrepareParams;
719 const DoProgress: boolean);
720 begin
721 {$warnings off} // using deprecated to keep it working
722 if Url <> '' then
723 begin
724 FSceneState.Prepare(Url, Owner, Params, DoProgress);
725 if AnimationName <> '' then
726 FDuration := FSceneState.Scene.AnimationDuration(AnimationName)
727 else
728 FDuration := FSceneState.Scene.AnimationDuration(TNodeInterpolator.DefaultAnimationName);
729 end else
730 {$warnings on}
731 if AnimationName <> '' then
732 begin
733 if Owner.ModelState.Scene = nil then
734 raise Exception.CreateFmt('Animation "%s" of resource "%s": animation_name is defined, but model url is not defined (neither specific to this animation nor containing multiple animations)',
735 [Name, Owner.Name]);
736 FDuration := Owner.ModelState.Scene.AnimationDuration(AnimationName);
737 end else
738 if Required then
739 raise Exception.CreateFmt('No definition for required animation "%s" of resource "%s". You have to define url or animation_name for this animation in appropriate resource.xml file',
740 [Name, Owner.Name]);
741 end;
742
743 procedure T3DResourceAnimation.Release;
744 begin
745 FreeAndNil(FSceneState.Scene);
746 end;
747
748 procedure T3DResourceAnimation.LoadFromFile(ResourceConfig: TCastleConfig);
749 begin
750 {$warnings off} // using deprecated to keep it working
751 if ResourceConfig.GetValue('model/' + Name + '/file_name', '') <> '' then
752 begin
753 Url := ResourceConfig.GetUrl('model/' + Name + '/file_name', true);
754 WritelnWarning('Deprecated', 'Reading from deprecated "file_name" attribute inside resource.xml. Use "url" instead.');
755 end else
756 Url := ResourceConfig.GetUrl('model/' + Name + '/url', true);
757
758 if Url <> '' then
759 WritelnWarning('Animation "%s" of "%s" has it''s own URL, this is deprecated. Use one URL for all animations. See https://castle-engine.io/creating_data_resources.php .', [
760 Name,
761 Owner.Name
762 ]);
763 {$warnings on}
764
765 AnimationName := ResourceConfig.GetValue('model/' + Name + '/animation_name', '');
766 if AnimationName = '' then
767 begin
768 AnimationName := ResourceConfig.GetValue('model/' + Name + '/time_sensor', '');
769 if AnimationName <> '' then
770 WritelnWarning('Deprecated', 'Reading from deprecated "time_sensor" attribute inside resource.xml. Use "animation_name" instead.');
771 end;
772 end;
773
774 { T3DResourceAnimationList --------------------------------------------------- }
775
776 function T3DResourceAnimationList.FindName(const AName: string): T3DResourceAnimation;
777 var
778 I: Integer;
779 begin
780 for I := 0 to Count - 1 do
781 begin
782 Result := Items[I];
783 if Result.Name = AName then
784 Exit;
785 end;
786 raise Exception.CreateFmt('No resource animation named "%s"', [AName]);
787 end;
788
789 { TResourceFrame ------------------------------------------------------------- }
790
791 constructor TResourceFrame.Create(AOwner: TComponent);
792 begin
793 inherited;
794 ResourceObserver := TFreeNotificationObserver.Create(Self);
795 ResourceObserver.OnFreeNotification := {$ifdef FPC}@{$endif}ResourceFreeNotification;
796 end;
797
798 destructor TResourceFrame.Destroy;
799 begin
800 if CurrentChildFromPool then
801 begin
802 CurrentChildFromPool := false;
803 FAnimation.FOwner.ReleaseSceneFromPool(CurrentChild);
804 Remove(CurrentChild);
805 CurrentChild := nil;
806 end;
807 inherited;
808 end;
809
810 procedure TResourceFrame.LocalRender(const Params: TRenderParams);
811
812 procedure UpdateChild;
813 var
814 NewChild: TCastleScene;
815 begin
816 if (FAnimation <> nil) and FAnimation.FOwner.Prepared then
817 NewChild := FAnimation.SceneAtTime(FTime, FLoop)
818 else
819 NewChild := nil;
820
821 if CurrentChild <> NewChild then
822 begin
823 if CurrentChild <> nil then
824 Remove(CurrentChild);
825 CurrentChild := NewChild;
826 if CurrentChild <> nil then
827 Add(CurrentChild);
828 end;
829 end;
830
831 begin
832 // before rendering, set correct child with correct time
833 if not CurrentChildFromPool then
834 UpdateChild;
835 inherited;
836 end;
837
838 procedure TResourceFrame.SetFrame(const Level: TAbstractLevel;
839 const AnAnimation: T3DResourceAnimation;
840 const ATime: TFloatTime; const ALoop: boolean);
841 var
842 OldResource, NewResource: T3DResource;
843 AnimationChanges: Boolean;
844 begin
845 if FAnimation <> nil then
846 OldResource := FAnimation.Owner
847 else
848 OldResource := nil;
849 if AnAnimation <> nil then
850 NewResource := AnAnimation.Owner
851 else
852 NewResource := nil;
853
854 // if changing resource, release previous scene from pool
855 if (OldResource <> NewResource) and
856 (OldResource <> nil) and
857 CurrentChildFromPool then
858 begin
859 CurrentChildFromPool := false;
860 FAnimation.Owner.ReleaseSceneFromPool(CurrentChild);
861 Remove(CurrentChild);
862 CurrentChild := nil;
863 end;
864
865 // change current animation properties
866 AnimationChanges := FAnimation <> AnAnimation;
867 FAnimation := AnAnimation;
868 FTime := ATime;
869 FLoop := ALoop;
870
871 if FAnimation <> nil then
872 ResourceObserver.Observed := FAnimation.FOwner
873 else
874 ResourceObserver.Observed := nil;
875
876 // if setting new resource, allocate new scene from pool
877 if (not CurrentChildFromPool) and
878 (FAnimation <> nil) and
879 FAnimation.FOwner.Prepared and
880 (FAnimation.FSceneState.Scene = nil) and
881 (FAnimation.FOwner.ScenePool <> nil) then
882 begin
883 CurrentChild := FAnimation.FOwner.AllocateSceneFromPool(Level);
884 CurrentChildFromPool := true;
885 Add(CurrentChild);
886 end;
887
888 // change current animation on scene from pool
889 if CurrentChildFromPool and AnimationChanges then
890 begin
891 if AnAnimation <> nil then
892 begin
893 if not CurrentChild.PlayAnimation(FAnimation.AnimationName, FLoop) then
894 WritelnWarning('Missing animation "%s"', [FAnimation.AnimationName]);
895 end else
896 CurrentChild.StopAnimation;
897 end;
898 end;
899
900 procedure TResourceFrame.ResourceFreeNotification(const Sender: TFreeNotificationObserver);
901 begin
902 { When T3DResource (FAnimation.Owner) is freed, unassociate from FAnimation
903 (that is/will be freed alongside), to avoid later crash at TResourceFrame.Destroy.
904 The FreeAndNil(Resources) may happen before all creatures are destroyed.
905 Testcase: fps_game, crash at game exit. }
906 SetFrame(nil, nil, 0, false);
907 Assert(FAnimation = nil);
908 Assert(not CurrentChildFromPool);
909 end;
910
911 { T3DResource ---------------------------------------------------------------- }
912
913 constructor T3DResource.Create(AOwner: TComponent);
914 begin
915 inherited;
916 FFallSpeed := DefaultFallSpeed;
917 FGrowSpeed := DefaultGrowSpeed;
918 FReceiveShadowVolumes := DefaultReceiveShadowVolumes;
919 FCastShadowVolumes := DefaultCastShadowVolumes;
920 FAnimations := T3DResourceAnimationList.Create;
921 FOrientation := TCastleTransform.DefaultOrientation;
922 end;
923
924 destructor T3DResource.Destroy;
925 begin
926 FPrepared := false;
927 ReleaseCore;
928 inherited;
929 { Freeing FAnimations *after* inherited is necessary,
930 because inherited notifies all TResourceFrame about freeing of related T3DResource instance.
931 At the point of that notification, TResourceFrame may assume that referenced FAnimation
932 still exists.
933 Testcase: just run and close fps_game. }
934 FreeAndNil(FAnimations);
935 end;
936
937 function T3DResource.CreateSceneForPool(const Params: TPrepareParams): TCastleScene;
938 begin
939 Result := ModelState.Scene.Clone(nil);
940 Result.DefaultAnimationTransition := DefaultAnimationTransition;
941 {$warnings off} // using deprecated in deprecated
942 Result.PrepareResources(ScenePrepareResources, Params);
943 {$warnings on}
944 end;
945
946 procedure T3DResource.PrepareCore(const Params: TPrepareParams;
947 const DoProgress: boolean);
948 var
949 I: Integer;
950 TimeStart: TCastleProfilerTime;
951 begin
952 TimeStart := Profiler.Start('Prepare Animations of Resource ' + Name);
953
954 ModelState.Prepare(ModelUrl, Self, Params, DoProgress);
955
956 if (ModelState.Scene <> nil) and (Pool <> 0) then
957 begin
958 ScenePool := TCastleSceneList.Create(true);
959 ScenePool.Count := Pool;
960 for I := 0 to ScenePool.Count - 1 do
961 ScenePool[I] := CreateSceneForPool(Params);
962 ScenePoolUsed := 0;
963 end;
964
965 for I := 0 to Animations.Count - 1 do
966 Animations[I].Prepare(Params, DoProgress);
967
968 Profiler.Stop(TimeStart);
969 end;
970
971 function T3DResource.PrepareCoreSteps: Cardinal;
972 begin
973 Result := 2 + Animations.Count * 2;
974 end;
975
976 procedure T3DResource.ReleaseCore;
977 var
978 I: Integer;
979 begin
980 FreeAndNil(ModelState.Scene);
981 FreeAndNil(ScenePool);
982 ScenePoolUsed := 0;
983 if Animations <> nil then
984 for I := 0 to Animations.Count - 1 do
985 Animations[I].Release;
986 end;
987
988 procedure T3DResource.LoadFromFile(ResourceConfig: TCastleConfig);
989 var
990 I: Integer;
991 PoolStr: String;
992 begin
993 ConfigAlwaysPrepared := ResourceConfig.GetValue('always_prepared', false);
994 FFallSpeed := ResourceConfig.GetFloat('fall_speed', DefaultFallSpeed);
995 FGrowSpeed := ResourceConfig.GetFloat('grow_speed', DefaultGrowSpeed);
996 FReceiveShadowVolumes := ResourceConfig.GetValue('receive_shadow_volumes',
997 DefaultReceiveShadowVolumes);
998 FCastShadowVolumes := ResourceConfig.GetValue('cast_shadow_volumes',
999 DefaultCastShadowVolumes);
1000 FOrientation := StrToOrientationType(ResourceConfig.GetValue('orientation', 'default'));
1001 FDefaultAnimationTransition := ResourceConfig.GetFloat('model/default_animation_transition', 0.0);
1002 if ResourceConfig.GetValue('model/file_name', '') <> '' then
1003 begin
1004 FModelUrl := ResourceConfig.GetUrl('model/file_name', true);
1005 WritelnLog('Deprecated', 'Reading from deprecated "file_name" attribute inside resource.xml. Use "url" instead.');
1006 end else
1007 FModelUrl := ResourceConfig.GetUrl('model/url', true);
1008
1009 { calculate Pool }
1010 PoolStr := ResourceConfig.GetValue('model/pool', 'auto');
1011 if PoolStr = 'auto' then
1012 begin
1013 { Do not use Pool for model formats that are
1014 - fast to switch current frame (ForceAnimationPose is fast)
1015 - do not support animation blending anyway
1016 In practice, this means formats with precalculated animation frames, like castle-anim-frames. }
1017 if (FModelUrl <> '') and
1018 ( (UriMimeType(FModelUrl) = 'application/x-castle-anim-frames') or
1019 (UriMimeType(FModelUrl) = 'application/x-md3')
1020 ) then
1021 Pool := 0
1022 else
1023 Pool := 1;
1024 WritelnLog('Pool for "%s" auto-determined as %d', [Name, Pool]);
1025 end else
1026 Pool := StrToInt(PoolStr);
1027
1028 for I := 0 to Animations.Count - 1 do
1029 Animations[I].LoadFromFile(ResourceConfig);
1030 end;
1031
1032 procedure T3DResource.RedoPrepare(const Params: TPrepareParams);
1033 var
1034 DoProgress: boolean;
1035 begin
1036 Assert(UsageCount <> 0);
1037 DoProgress := not Progress.Active;
1038 if DoProgress then Progress.Init(PrepareCoreSteps, 'Loading ' + Name);
1039 try
1040 { It's important to do ReleaseCore after Progress.Init.
1041 That is because Progress.Init may do TCastleWindow.SaveScreenToDisplayList,
1042 and this may call Window.OnRender, and this may want to redraw
1043 the object (e.g. if creature of given resource already exists
1044 on the screen) and this requires Prepare to be already done.
1045
1046 So we should call Progress.Init before we make outselves unprepared. }
1047 FPrepared := false;
1048 ReleaseCore;
1049 PrepareCore(Params, DoProgress);
1050 FPrepared := true;
1051 finally
1052 if DoProgress then Progress.Fini;
1053 end;
1054 end;
1055
1056 procedure T3DResource.Prepare(const Params: TPrepareParams;
1057 const GravityUp: TVector3);
1058 begin
1059 Prepare(Params);
1060 end;
1061
1062 procedure T3DResource.Prepare(const Params: TPrepareParams);
1063 var
1064 List: T3DResourceList;
1065 begin
1066 List := T3DResourceList.Create(false);
1067 try
1068 List.Add(Self);
1069 List.Prepare(Params);
1070 finally FreeAndNil(List) end;
1071 end;
1072
1073 procedure T3DResource.Release;
1074 var
1075 List: T3DResourceList;
1076 begin
1077 List := T3DResourceList.Create(false);
1078 try
1079 List.Add(Self);
1080 List.Release;
1081 finally FreeAndNil(List) end;
1082 end;
1083
1084 function T3DResource.AlwaysPrepared: boolean;
1085 begin
1086 Result := ConfigAlwaysPrepared;
1087 end;
1088
1089 function T3DResource.AllocateSceneFromPool(const Level: TAbstractLevel): TCastleScene;
1090 begin
1091 Assert(ScenePool <> nil);
1092
1093 if ScenePoolUsed < ScenePool.Count then
1094 begin
1095 Result := ScenePool[ScenePoolUsed];
1096 end else
1097 begin
1098 WritelnLog('Need to increase pool of %s at runtime to %d. Better declare larger initial pool, to avoid delay at game runtime.', [
1099 Name,
1100 ScenePoolUsed + 1
1101 ]);
1102 Result := CreateSceneForPool(Level.PrepareParams);
1103 ScenePool.Add(Result);
1104 end;
1105
1106 Inc(ScenePoolUsed);
1107 end;
1108
1109 procedure T3DResource.ReleaseSceneFromPool(const Scene: TCastleScene);
1110 var
1111 I: Integer;
1112 begin
1113 // Assert(ScenePool <> nil); // possible to happen during destructor
1114 if ScenePool = nil then
1115 Exit;
1116
1117 I := ScenePool.IndexOf(Scene);
1118 Assert(I <> -1);
1119 { exchange items on ScenePool, to keep the used scenes at the beginning }
1120 if I <> ScenePoolUsed - 1 then
1121 ScenePool.Exchange(I, ScenePoolUsed - 1);
1122 Dec(ScenePoolUsed);
1123 end;
1124
1125 { T3DResourceList ------------------------------------------------------------- }
1126
1127 procedure T3DResourceList.AddFromInfo(const FileInfo: TFileInfo; var StopSearch: boolean);
1128 begin
1129 AddFromFileDefaultReload(FileInfo.Url);
1130 end;
1131
1132 procedure T3DResourceList.AddFromFileDefaultReload(const Url: String);
1133 var
1134 Xml: TCastleConfig;
1135 ResourceClassName, ResourceName: string;
1136 ResourceClass: T3DResourceClass;
1137 Resource: T3DResource;
1138 begin
1139 Xml := TCastleConfig.Create(nil);
1140 try
1141 try
1142 Xml.RootName := 'resource';
1143 Xml.NotModified; { otherwise changing RootName makes it modified, and saved back at freeing }
1144 Xml.Url := Url;
1145 // WritelnLog('Resources', Format('Loading T3DResource from "%s"', [Url]));
1146
1147 ResourceClassName := Xml.GetStringNonEmpty('type');
1148 if not ResourceClasses.TryGetValue(ResourceClassName, ResourceClass) then
1149 raise Exception.CreateFmt('Resource type "%s" not found, mentioned in file "%s"',
1150 [ResourceClassName, Url]);
1151
1152 ResourceName := Xml.GetStringNonEmpty('name');
1153 if CharsPos(AllChars - ['a'..'z', 'A'..'Z'], ResourceName) <> 0 then
1154 raise Exception.CreateFmt('Resource name "%s" is invalid. Resource names may only use English letters (not even digits or underscores are allowed).',
1155 [ResourceName]);
1156 Resource := FindName(ResourceName, true);
1157 if Resource <> nil then
1158 begin
1159 if ResourceXmlReload then
1160 begin
1161 if ResourceClass <> Resource.ClassType then
1162 raise Exception.CreateFmt('Resource name "%s" already exists, but with different type. Old class is %s, new class is %s. Cannot reload resource.xml file in this situation',
1163 [ResourceName, Resource.ClassType.ClassName, ResourceClass.ClassName]);
1164 end else
1165 raise Exception.CreateFmt('Resource name "%s" already exists. All resource names inside resource.xml files must be unique',
1166 [ResourceName]);
1167 end else
1168 begin
1169 Resource := ResourceClass.Create(nil);
1170 Resource.Name := ResourceName;
1171 Add(Resource);
1172 end;
1173
1174 Resource.LoadFromFile(Xml);
1175 except
1176 { enhance EMissingAttribute with information about the XML file where
1177 it occured }
1178 on E: EMissingAttribute do
1179 begin
1180 E.Message := E.Message + ' (When reading "' + Url + '")';
1181 raise;
1182 end;
1183 end;
1184 finally FreeAndNil(Xml) end;
1185 end;
1186
1187 procedure T3DResourceList.AddFromFile(const Url: String; const Reload: boolean);
1188 begin
1189 ResourceXmlReload := Reload;
1190 AddFromFileDefaultReload(Url);
1191 end;
1192
1193 procedure T3DResourceList.LoadFromFiles(const Path: string; const Reload: boolean);
1194 begin
1195 if not Reload then
1196 Clear;
1197 ResourceXmlReload := Reload;
1198 FindFiles(Path, 'resource.xml', false,
1199 {$ifdef FPC}@{$endif}AddFromInfo, [ffRecursive]);
1200 end;
1201
1202 procedure T3DResourceList.LoadFromFiles(const Reload: boolean);
1203 begin
1204 LoadFromFiles('castle-data:/', Reload);
1205 end;
1206
1207 function T3DResourceList.FindName(const AName: string; const NilWhenNotFound: boolean): T3DResource;
1208 var
1209 I: Integer;
1210 begin
1211 for I := 0 to Count - 1 do
1212 begin
1213 Result := Items[I];
1214 if Result.Name = AName then
1215 Exit;
1216 end;
1217
1218 if NilWhenNotFound then
1219 Result := nil else
1220 raise Exception.CreateFmt('Not existing resource name "%s"', [AName]);
1221 end;
1222
1223 procedure T3DResourceList.LoadResources(ParentElement: TDOMElement);
1224 var
1225 ResourcesElement: TDOMElement;
1226 ResourceName: string;
1227 I: TXMLElementIterator;
1228 begin
1229 Clear;
1230
1231 ResourcesElement := ParentElement.ChildElement('prepare_resources', false);
1232
1233 if ResourcesElement <> nil then
1234 begin
1235 I := ResourcesElement.ChildrenIterator;
1236 try
1237 while I.GetNext do
1238 begin
1239 if I.Current.TagName <> 'resource' then
1240 raise Exception.CreateFmt(
1241 'Element "%s" is not allowed in <prepare_resources>',
1242 [I.Current.TagName]);
1243 if not I.Current.AttributeString('name', ResourceName) then
1244 raise Exception.Create('<resource> must have a "name" attribute');
1245 Add(Resources.FindName(ResourceName));
1246 end;
1247 finally FreeAndNil(I) end;
1248 end;
1249 end;
1250
1251 procedure T3DResourceList.Prepare(const Params: TPrepareParams;
1252 const ResourcesName: string);
1253 var
1254 I: Integer;
1255 Resource: T3DResource;
1256 PrepareSteps: Cardinal;
1257 PrepareNeeded, DoProgress: boolean;
1258 TimeStart: TCastleProfilerTime;
1259 begin
1260 { We iterate two times over Items, first time only to calculate
1261 PrepareSteps, 2nd time does actual work.
1262 1st time increments UsageCount (as 2nd pass may be optimized
1263 out, if not needed). }
1264
1265 PrepareSteps := 0;
1266 PrepareNeeded := false;
1267 for I := 0 to Count - 1 do
1268 begin
1269 Resource := Items[I];
1270 Resource.UsageCount := Resource.UsageCount + 1;
1271 if Resource.UsageCount = 1 then
1272 begin
1273 PrepareSteps := PrepareSteps + Resource.PrepareCoreSteps;
1274 PrepareNeeded := true;
1275 end;
1276 end;
1277
1278 if PrepareNeeded then
1279 begin
1280 TimeStart := Profiler.Start('Loading ' + ResourcesName);
1281
1282 DoProgress := not Progress.Active;
1283 if DoProgress then Progress.Init(PrepareSteps, 'Loading ' + ResourcesName);
1284 try
1285 for I := 0 to Count - 1 do
1286 begin
1287 Resource := Items[I];
1288 if Resource.UsageCount = 1 then
1289 begin
1290 Assert(not Resource.Prepared);
1291 Resource.PrepareCore(Params, DoProgress);
1292 Resource.FPrepared := true;
1293 end;
1294 end;
1295 finally
1296 if DoProgress then Progress.Fini;
1297 end;
1298
1299 Profiler.Stop(TimeStart);
1300 end;
1301 end;
1302
1303 procedure T3DResourceList.Release;
1304 var
1305 I: Integer;
1306 Resource: T3DResource;
1307 begin
1308 for I := 0 to Count - 1 do
1309 begin
1310 Resource := Items[I];
1311 Assert(Resource.UsageCount > 0);
1312 {
1313 if Resource.UsageCount = 0 then
1314 begin
1315 WritelnWarning('Resources', Format(
1316 'Resource "%s" is already unused, but it is being released. Make sure T3DResource.Released are matched 1-1 with T3DResource.Prepare calls.', [Resource.Name]));
1317 Continue;
1318 end;
1319 }
1320
1321 Resource.UsageCount := Resource.UsageCount - 1;
1322 if Resource.UsageCount = 0 then
1323 begin
1324 WritelnLog('Resources', Format(
1325 'Resource "%s" is no longer used, releasing', [Resource.Name]));
1326 Resource.FPrepared := false;
1327 Resource.ReleaseCore;
1328 end;
1329 end;
1330 end;
1331
1332 { resource classes ----------------------------------------------------------- }
1333
1334 procedure RegisterResourceClass(const AClass: T3DResourceClass; const TypeName: string);
1335 begin
1336 ResourceClasses[TypeName] := AClass;
1337 end;
1338
1339 { initialization / finalization ---------------------------------------------- }
1340
1341 var
1342 FResources: T3DResourceList;
1343
1344 function Resources: T3DResourceList;
1345 begin
1346 if (FResources = nil) and not UnitFinalization then
1347 FResources := T3DResourceList.Create(true);
1348 Result := FResources;
1349 end;
1350
1351 initialization // Empty but Delphi needs this
1352
1353 finalization
1354 UnitFinalization := true;
1355 FreeAndNil(FResources);
1356 FreeAndNil(FResourceClasses);
1357 end.