Debian Codegraph @

src/deprecated_units/castleitems.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 { Items, things that can be picked up, carried and used. }
17 unit CastleItems
18 deprecated 'express items logic as TCastleBehavior';
19
20 {$I castleconf.inc}
21
22 interface
23
24 {$warnings off} // using deprecated in deprecated
25 uses Generics.Collections,
26 CastleBoxes, X3DNodes, CastleScene, CastleVectors, CastleUtils,
27 CastleClassUtils, Classes, CastleImages, CastleGLUtils,
28 CastleResources, CastleGLImages, CastleTimeUtils,
29 CastleXMLConfig, CastleSoundEngine, CastleFrustum,
30 CastleTransformExtra, CastleTransform, CastleColors, CastleDebugTransform;
31 {$warnings on}
32
33 type
34 TInventoryItem = class;
35 TInventoryItemClass = class of TInventoryItem;
36
37 { Basic resource of an item that can be picked up, used and such.
38
39 A "resource" is an information shared by all items of given type,
40 for example you can have two instances of class TItemResource:
41 Sword and LifePotion. (Actually, TItemWeaponResource, which is a descendant
42 of TItemResource, sounds like a better candidate for the Sword.)
43 Using them, you can create milions of actual swords and life potions,
44 and place them of your level (as well as in inventories of creatures
45 able to carry items). Every life potion (TInventoryItem instance)
46 may keep some individual information (for example, how much of the potion
47 is already used/drunk), but all life potions will share the same
48 TItemResource instance, so e.g. they all will be displayed using the same model
49 on 3D level (TItemResource.BaseAnimation) and the same image in 2D inventory
50 (TItemResource.Image). }
51 TItemResource = class(T3DResource)
52 strict private
53 FBaseAnimation: T3DResourceAnimation;
54 FCaption: string;
55 FImageUrl: String;
56 FImage: TEncodedImage;
57 FDrawableImage: TDrawableImage;
58 private
59 { The largest possible bounding box of the 3D item,
60 taking into account that actual item 3D model will be rotated when
61 placed on world. You usually want to add current item position to this. }
62 function BoundingBoxRotated(const GravityUp: TVector3): TBox3D;
63 protected
64 procedure PrepareCore(const Params: TPrepareParams;
65 const DoProgress: boolean); override;
66 { Which TInventoryItem descendant to create when constructing item
67 of this resource by CreateItem. }
68 function ItemClass: TInventoryItemClass; virtual;
69 public
70 constructor Create(AOwner: TComponent); override;
71 destructor Destroy; override;
72 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
73
74 { Nice caption to display. }
75 property Caption: string read FCaption;
76
77 property BaseAnimation: T3DResourceAnimation read FBaseAnimation;
78
79 { 2D image representing an item, to be used when showing inventory and such.
80 The core engine itself doesn't use it, and doesn't force anything
81 about such image (whether it should have some specific size,
82 whether it should have alpha channel and such).
83 It is up to the final game to make use of these images.
84
85 If you're wondering how to generate such image:
86 one option is to open the item 3D model in
87 [https://castle-engine.io/castle-model-viewer]
88 and use "Display -> Screenshot ..." menu option (maybe the one
89 that makes transparent background).
90 It is usually a good idea to also remember the camera used for such
91 screenshot with "Console -> Print Current Camera (Viewpoint)..."
92 menu option. }
93 function Image: TEncodedImage;
94
95 property ImageUrl: String read FImageUrl;
96
97 { Resource to draw @link(Image). }
98 function DrawableImage: TDrawableImage;
99
100 {$ifdef FPC}
101 property GLImage: TDrawableImage read DrawableImage;
102 deprecated 'use DrawableImage';
103 {$endif}
104
105 { Create item. This is how you should create new TInventoryItem instances.
106 It is analogous to TCreatureResource.CreateCreature, but now for items.
107
108 Note that the item itself doesn't exist on a 3D world --- you have to
109 put it there if you want by TInventoryItem.PutOnWorld. That is because items
110 can also exist only in player's backpack and such, and then they
111 are independent from 3D world.
112
113 @bold(Examples:)
114
115 You usually define your own item resources by adding a subdirectory with
116 resource.xml file to your game data. See
117 [https://castle-engine.io/creating_data_resources.php]
118 and engine tutorial for examples how to do this. Then you load the item
119 resources with
120
121 @longCode(#
122 var
123 Sword: TItemResource;
124 ...
125 Resources.LoadFromFiles;
126 Sword := Resources.FindName('Sword') as TItemResource;
127 #)
128
129 where 'Sword' is just our example item resource, assuming that one of your
130 resource.xml files has resource with name="Sword".
131
132 Now if you want to add the sword to your 3D world by code:
133
134 Because TInventoryItem instance is automatically
135 owned (freed) by the 3D world or inventory that contains it, a simplest
136 example how to add an item to your 3D world is this:
137
138 @longCode(#
139 Sword.CreateItem(1).PutOnWorld(Level, Vector3(2, 3, 4));
140 #)
141
142 This adds 1 item of the MyItemResource to the 3D world,
143 on position (2, 3, 4).
144
145 If you want to instead add sword to the inventory of Player,
146 you can call
147
148 @longCode(#
149 Player.PickItem(Sword.CreateItem(1));
150 #)
151
152 This assumes that you have Player (TPlayer) instance.
153 It's the simplest way to have player with an inventory.
154 See engine tutorial for examples how to create player.
155 Anyway, if you have any TInventory instance, you can use
156 TInventory.Pick to add TInventoryItem this way. }
157 function CreateItem(const AQuantity: Cardinal): TInventoryItem;
158
159 { Instantiate placeholder by create new item with CreateItem
160 and putting it on level with TInventoryItem.PutOnWorld. }
161 procedure InstantiatePlaceholder(
162 const ALevel: TAbstractLevel;
163 const APosition, ADirection: TVector3;
164 const NumberPresent: boolean; const Number: Int64); override;
165
166 function AlwaysPrepared: boolean; override;
167 end;
168
169 { Weapon that can make an immiediate attack (short-range/shoot)
170 or fire a missile. }
171 TItemWeaponResource = class(TItemResource)
172 private
173 FEquippingSound: TCastleSound;
174 FAttackAnimation: T3DResourceAnimation;
175 FReadyAnimation: T3DResourceAnimation;
176 FReloadAnimation: T3DResourceAnimation;
177 FAttackTime: Single;
178 FReloadTime: Single;
179 FAttackSoundStart: TCastleSound;
180 FAttackAmmo: String;
181 FAttackAmmoCapacity: Cardinal;
182 FAttackSoundHit: TCastleSound;
183 FAttackDamageConst: Single;
184 FAttackDamageRandom: Single;
185 FAttackKnockbackDistance: Single;
186 FAttackShoot: Boolean;
187 FFireMissileName: String;
188 FFireMissileSound: TCastleSound;
189 protected
190 function ItemClass: TInventoryItemClass; override;
191 public
192 const
193 DefaultAttackTime = 0.0;
194 DefaultReloadTime = 0.0;
195 DefaultAttackDamageConst = 0.0;
196 DefaultAttackDamageRandom = 0.0;
197 DefaultAttackKnockbackDistance = 0.0;
198 DefaultAttackShoot = false;
199
200 constructor Create(AOwner: TComponent); override;
201
202 { Sound to make on equipping. Each weapon can have it's own
203 equipping sound. }
204 property EquippingSound: TCastleSound
205 read FEquippingSound write FEquippingSound;
206
207 { Animation of attack with this weapon. }
208 property AttackAnimation: T3DResourceAnimation read FAttackAnimation;
209
210 { Animation of keeping weapon ready (idle). }
211 property ReadyAnimation: T3DResourceAnimation read FReadyAnimation;
212
213 { Animation of reloading weapon, used only if @link(AttackAmmoCapacity) non-zero. }
214 property ReloadAnimation: T3DResourceAnimation read FReloadAnimation;
215
216 { Common properties for all types of attack (short-range/shoot,
217 fire missile) below. }
218
219 { A time within AttackAnimation at at which TItemWeapon.Attack
220 method will be called, which actually hits the enemy. }
221 property AttackTime: Single read FAttackTime write FAttackTime
222 {$ifdef FPC}default DefaultAttackTime{$endif};
223
224 { A time within ReloadAnimation at at which TItemWeapon.AmmoLoaded is actually refilled. }
225 property ReloadTime: Single read FReloadTime write FReloadTime
226 {$ifdef FPC}default DefaultReloadTime{$endif};
227
228 { Sound when attack starts. This is played when attack animation starts,
229 and it means that we already checked that you have necessary ammunition
230 (see AttackAmmo).
231 None (nil) by default. }
232 property AttackSoundStart: TCastleSound
233 read FAttackSoundStart write FAttackSoundStart;
234
235 { Ammunition required to make an attack (applies to both immediate attack,
236 like short-range/shoot, and firing missiles).
237 Indicates item resource name to use as ammunition (like 'Quiver' or 'Bullets').
238 It may be empty, in which case the ammunition is not necessary to make
239 an attack.
240 If it's set, we will check whether owner of the weapon (like a player)
241 has at least one item of this resource, and we'll decrease it
242 when firing.
243
244 For example, if this weapon is a pistol, then you can set
245 AttackDamageConst and AttackDamageRandom to non-zero and AttackShoot
246 to @true to perform an immediatele shooting attack.
247 And set AttackAmmo to something like 'Bullets'.
248
249 For example, if this weapon is a bow, then you can set
250 FireMissileName to 'Arrow', to fire arrows as missiles (they will
251 fly and can be avoided by fast moving enemies).
252 And set AttackAmmo to something like 'Quiver'. }
253 property AttackAmmo: string read FAttackAmmo write FAttackAmmo;
254
255 { If non-zero, it indicates that weapon has to be reloaded after making so many shots. }
256 property AttackAmmoCapacity: Cardinal read FAttackAmmoCapacity write FAttackAmmoCapacity;
257
258 { Immediate attack (short-range/shoot) damage and knockback.
259 This type of attack (along with AttackSoundHit) is only
260 done if one of these properties is non-zero. They must be >= 0.
261 @groupBegin }
262 property AttackDamageConst: Single read FAttackDamageConst write FAttackDamageConst
263 {$ifdef FPC}default DefaultAttackDamageConst{$endif};
264 property AttackDamageRandom: Single read FAttackDamageRandom write FAttackDamageRandom
265 {$ifdef FPC}default DefaultAttackDamageRandom{$endif};
266 property AttackKnockbackDistance: Single
267 read FAttackKnockbackDistance write FAttackKnockbackDistance
268 {$ifdef FPC}default DefaultAttackKnockbackDistance{$endif};
269 { @groupEnd }
270
271 { Does the immediate attack is shooting.
272
273 @unorderedList(
274 @item(Shooting means that the hit enemy is determined by casting a ray from
275 owner (like a shooting player) and seeing what it hits. Even enemies
276 far away may be hit, but you have to aim precisely.)
277
278 @item(When this is @false, we make a short-range (melee) attack.
279 In this case the hit enemy is determined by looking at the weapon
280 bounding volume near owner. Only the enemies
281 very close to the owner get hit.)
282 ) }
283 property AttackShoot: boolean read FAttackShoot write FAttackShoot
284 default DefaultAttackShoot;
285
286 { Sound on successful hit by an immediate attack (short-range/shoot). }
287 property AttackSoundHit: TCastleSound read FAttackSoundHit write FAttackSoundHit;
288
289 { Creature resource name to be created (like 'Arrow') when firing a missile.
290 Must be set to something not empty to actually fire a missile. }
291 property FireMissileName: string read FFireMissileName write FFireMissileName;
292
293 { Sound on missile fired.
294 None (nil) by default. }
295 property FireMissileSound: TCastleSound read FFireMissileSound write FFireMissileSound;
296
297 procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
298 end;
299
300 TItemOnWorld = class;
301 TAliveWithInventory = class;
302
303 { An item that can be used, kept in the inventory, or (using PutOnWorld
304 that wraps it in TItemOnWorld) dropped on 3D world.
305 Thanks to the @link(Quantity) property, this may actually represent
306 many "stacked" items, all having the same properties. }
307 TInventoryItem = class(TComponent)
308 private
309 FResource: TItemResource;
310 FQuantity: Cardinal;
311 FOwner3D: TCastleTransform;
312 protected
313 { Try to sum (stack) the given Item with current TInventoryItem.
314 The idea is that if player has 5 arrows, and picks an item representing
315 another 5 arrows, then we sum then into one TInventoryItem instance
316 representing 10 arrows.
317
318 Various games, and various items,
319 may require various approaches: for example, maybe you don't want
320 some items to stack at all (e.g. you want to only allow stacking
321 for items naturally appearing in vast quantities, like arrows and bolts
322 and bullets (if you represent them as TInventoryItem at all)).
323 Maybe you want to allow stacking only to centain number, e.g. arrows
324 are summed into groups of maximum 20 items, anything above creates new stack?
325 Overriding this procedure allows you to do all this.
326
327 You can here increase the Quantity of current item,
328 decrease the Quantity of parameter Item. In case the parameter Item
329 no longer exists (it's Quantity reaches 0) you have to free it
330 and set to @nil the Item parameter, in practice you usually want
331 to call then @code(FreeAndNil(Item)).
332
333 The default implementation of this in TInventoryItem class
334 allows stacking always, as long as the Resource matches.
335 This means that, by default, every TItemResource is existing at most once
336 in TAliveWithInventory.Inventory. }
337 procedure Stack(var Item: TInventoryItem); virtual;
338
339 { Item is picked by an alive player/creature.
340 The default implementation in this class adds the item to the Inventory
341 by calling TAliveWithInventory.PickItem.
342
343 You can override this to cause different behavior (for example,
344 to consume some items right at pickup).
345 Remember that this method must take care of memory management
346 of this item. }
347 procedure Picked(const NewOwner: TAliveWithInventory); virtual;
348
349 { Use this item.
350
351 In this class, this just prints a message "this item cannot be used".
352
353 Implementation of this method can assume for now that this is one of
354 player's owned Items. Implementation of this method can change
355 our properties, including Quantity.
356 As a very special exception, implementation of this method
357 is allowed to set Quantity of Item to 0.
358
359 Never call this method when Player.Dead. Implementation of this
360 method may assume that Player is not Dead.
361
362 Caller of this method should always be prepared to immediately
363 handle the "Quantity = 0" situation by freeing given item,
364 removing it from any list etc. }
365 procedure Use; virtual;
366 public
367 property Resource: TItemResource read FResource;
368
369 { Quantity of this item.
370 This must always be >= 1. }
371 property Quantity: Cardinal read FQuantity write FQuantity;
372
373 { Splits item (with Quantity >= 2) into two items.
374 It returns newly created object with the same properties
375 as this object, and with Quantity set to QuantitySplit.
376 And it lowers our Quantity by QuantitySplit.
377
378 Always QuantitySplit must be >= 1 and < Quantity. }
379 function Split(QuantitySplit: Cardinal): TInventoryItem;
380
381 { Create TItemOnWorld instance referencing this item,
382 and add this to the given 3D AWorld.
383 Although normal item knows (through Owner3D) the world it lives in,
384 but this method may be used for items that don't have an owner yet,
385 so we take AWorld parameter explicitly.
386 This is how you should create new TItemOnWorld instances.
387 It is analogous to TCreatureResource.CreateCreature, but now for items. }
388 function PutOnWorld(
389 const ALevel: TAbstractLevel;
390 const APosition: TVector3): TItemOnWorld;
391
392 { 3D owner of the item,
393 like a player or creature (if the item is in the backpack)
394 or the TItemOnWorld instance (if the item is lying on the world,
395 pickable). May be @nil only in special situations (when item is moved
396 from one 3D to another, and technically it's safer to @nil this
397 property).
398
399 The owner is always responsible for freeing this TInventoryItem instance
400 (in case of TItemOnWorld, it does it directly;
401 in case of player or creature, it does it by TInventory). }
402 property Owner3D: TCastleTransform read FOwner3D;
403 end;
404
405 TItemWeapon = class(TInventoryItem)
406 private
407 type
408 TWeaponState = (wsReady, wsAttack, wsReload);
409 var
410 FState: TWeaponState;
411 { Last State change time, assigned from LifeTime. }
412 FStateChangeTime: Single;
413 { If State = wsAttack, then this says whether Attack was already called. }
414 AttackDone: boolean;
415 { If State = wsReload, then this says whether AmmoLoaded was already updated. }
416 ReloadDone: boolean;
417 FAmmoLoaded: Cardinal;
418 LifeTime: TFloatTime;
419 protected
420 { Make real attack, immediate (short-range/shoot) or firing missile.
421 Called during weapon TItemWeaponResource.AttackAnimation,
422 at the time TItemWeaponResource.AttackTime.
423 The default implementation in @className does a short-range/shoot
424 attack (if AttackDamageConst or AttackDamageRandom or AttackKnockbackDistance
425 non-zero) and fires a missile (if FireMissileName not empty). }
426 procedure Attack(const Level: TAbstractLevel); virtual;
427 procedure Use; override;
428 { Make actual reload that refills AmmoLoaded. }
429 procedure ReloadNow; virtual;
430 public
431 function Resource: TItemWeaponResource;
432
433 { Owner equips this weapon. }
434 procedure Equip; virtual;
435
436 { Owner starts attack with this equipped weapon. }
437 procedure EquippedAttack(const Level: TAbstractLevel); virtual;
438
439 { Time passses for equipped weapon. }
440 procedure EquippedUpdate(const Level: TAbstractLevel; const SecondsPassed: Single;
441 const ResourceFrame: TResourceFrame); virtual;
442
443 { Currently loaded capacity in the magazine. }
444 property AmmoLoaded: Cardinal read FAmmoLoaded write FAmmoLoaded;
445
446 { Initiate reload of the equipped weapon (run "reload" animation, refill AmmoLoaded).
447 If IgnorePreviousState then it works unconditionally,
448 otherwise it works only when the current state is not in the middle of shooting/reloading. }
449 procedure EquippedReload(const IgnorePreviousState: Boolean);
450 end;
451
452 { List of items, with a 3D object (like a player or creature) owning
453 these items. Do not directly change this list, always use
454 the owner (TAliveWithInventory) methods like
455 @link(TAliveWithInventory.PickItem) or
456 @link(TAliveWithInventory.DropItem).
457 They make sure that items are correctly stacked, and that
458 TInventoryItem.Owner3D and memory management is good. }
459 TInventory = class({$ifdef FPC}specialize{$endif} TObjectList<TInventoryItem>)
460 private
461 FOwner3D: TAliveWithInventory;
462 protected
463 { Add Item to inventory. See TAliveWithInventory.PickItemUpdate description,
464 this method actually implements it. }
465 function Pick(var Item: TInventoryItem): Integer;
466
467 { Drop item with given index.
468 ItemIndex must be valid (between 0 and Items.Count - 1).
469 You @italic(must) take care yourself of returned TInventoryItem memory
470 management.
471 This is the low-level basis for TAliveWithInventory.DropItem. }
472 function Drop(const ItemIndex: Integer): TInventoryItem;
473
474 { Pass here items owned by this list, immediately after decreasing
475 their Quantity. This frees the item (removing it from the list)
476 if it's quantity reached zero. }
477 procedure CheckDepleted(const Item: TInventoryItem);
478
479 { Use the item of given index.
480 This is the low-level basis for TAliveWithInventory.UseItem. }
481 procedure Use(const Index: Integer);
482 public
483 constructor Create(const AOwner3D: TAliveWithInventory);
484
485 { Owner of the inventory (like a player or creature).
486 Never @nil, always valid for given inventory.
487 All items on this list always have the same TInventoryItem.Owner3D value
488 as the inventory they are in. }
489 property Owner3D: TAliveWithInventory read FOwner3D;
490
491 { Searches for item of given Resource. Returns index of first found,
492 or -1 if not found. }
493 function FindResource(Resource: TItemResource): Integer;
494 end;
495
496 { Item that is placed on a 3D world, ready to be picked up.
497 It's not in anyone's inventory. }
498 TItemOnWorld = class(TCastleTransform)
499 private
500 type
501 { A debug visualization that can be added to TItemOnWorld
502 to visualize the parameters of it's parent (bounding volumes and such).
503 See @link(TDebugTransform) for usage details.
504 The @link(TDebugTransform.Parent) must be an instance of TItemOnWorld. }
505 TItemDebugTransform = class(TDebugTransform)
506 strict private
507 FBoxRotated: TDebugBox;
508 strict protected
509 procedure InitializeNodes; override;
510 procedure Update; override;
511 end;
512
513 var
514 FItem: TInventoryItem;
515 FResourceFrame: TResourceFrame;
516 ItemRotation, LifeTime: TFloatTime;
517 FDebugTransform: TItemDebugTransform;
518 Level: TAbstractLevel;
519 function BoundingBoxRotated: TBox3D;
520 public
521 class var
522 { Render debug bounding boxes and captions at every creature. }
523 RenderDebug: boolean;
524
525 { Speed of the rotation of 3D item on world.
526 In radians per second, default is DefaultRotationSpeed.
527 Set to zero to disable rotation. }
528 RotationSpeed: Single;
529
530 { Does the player automatically picks up items by walking over them.
531 Default is @true. If you set this to @false, you most probably want to
532 implement some other way of picking up items, use the ExtractItem method.
533
534 More precisely, this variable controls when TInventoryItem.Picked
535 is called. When @true, it is called for player when player steps over
536 an item (otherwise it's never called).
537 You can always override TInventoryItem.Picked for particular items
538 to customize what happens at "pick" --- the default implementation
539 picks an item by adding it to inventory, but you could override it
540 e.g. to consume some potions immediately on pickup. }
541 AutoPick: boolean;
542
543 const
544 DefaultRotationSpeed = Pi;
545
546 constructor Create(AOwner: TComponent); override;
547 destructor Destroy; override;
548
549 { The Item owned by this TItemOnWorld instance. Never @nil. }
550 property Item: TInventoryItem read FItem;
551
552 procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
553
554 property Collides default false;
555 property CollidesWithMoving default true;
556
557 { Extract the @link(Item), used when picking up the TInventoryItem
558 instance referenced by this TItemOnWorld instance. This returns our
559 @link(Item) property, and clears it (clearing also TInventoryItem.Owner3D).
560 At the next @link(Update), this TItemOnWorld instance will be freed
561 and removed from 3D world.
562
563 It's up to you what to do with resulting TInventoryItem instance.
564 You can pick it up, by TAliveWithInventory.PickItem
565 (for example player is an instance of TAliveWithInventory),
566 or add it back to 3D world by TInventoryItem.PutOnWorld,
567 or at least free it (or you'll get a memory leak). }
568 function ExtractItem: TInventoryItem;
569 end;
570
571 { Alive 3D thing that has inventory (can keep items). }
572 TAliveWithInventory = class(TCastleAlive)
573 private
574 FInventory: TInventory;
575 public
576 var
577 { Set when assigning TPlayer to @link(TLevel.Player). }
578 InternalLevel: TAbstractLevel;
579
580 constructor Create(AOwner: TComponent); override;
581 destructor Destroy; override;
582
583 { Owned items. Never change the contents of this list directly,
584 always use TAliveWithInventory methods like PickItem
585 or DropItem for this. }
586 property Inventory: TInventory read FInventory;
587
588 { Add given Item to @link(Inventory).
589 Because an item may be stacked with others,
590 the actual Item instance may be freed and replaced with other by
591 this method, that is why Item parameter is "var".
592 Use PickItem method if you don't care about your Item instance.
593
594 Returns index to the added item.
595
596 Using this method means that the memory management of the item
597 becomes the responsibility of this list. }
598 function PickItemUpdate(var Item: TInventoryItem): Integer; virtual;
599
600 { Add given Item to @link(Inventory). See PickItemUpdate for details.
601
602 This is a shortcut to call PickItemUpdate and then ignore changes
603 to Item instance. Calling this method may be comfortable,
604 but remember that the Item instance possibly doesn't exist after we finish. }
605 function PickItem(Item: TInventoryItem): Integer;
606
607 { Drop item from @link(Inventory).
608 It is Ok to pass here Index out of range, it will be ignored.
609 @returns(Droppped item, or @nil if the operation was not completed due
610 to any reason (e.g. no space on 3D world to fit this item).) }
611 function DropItem(const Index: Integer): TItemOnWorld; virtual;
612
613 { Use an item from @link(Inventory).
614 Calls TInventoryItem.Use, and then checks whether
615 the item was depleted (and eventually removes it from repository).
616 It is Ok to pass here Index out of range, it will be ignored. }
617 procedure UseItem(const Index: Integer); virtual;
618 end;
619
620 TItemOnWorldExistsEvent = function(const Item: TItemOnWorld): boolean of object;
621
622 implementation
623
624 {$warnings off} // using deprecated in deprecated
625 uses SysUtils, Math,
626 CastleFilesUtils, CastlePlayer, CastleGameNotifications, CastleConfig, CastleCreatures;
627 {$warnings on}
628
629 { TItemResource ------------------------------------------------------------ }
630
631 constructor TItemResource.Create(AOwner: TComponent);
632 begin
633 inherited;
634 FBaseAnimation := T3DResourceAnimation.Create(Self, 'base');
635 end;
636
637 destructor TItemResource.Destroy;
638 begin
639 FreeAndNil(FImage);
640 FreeAndNil(FDrawableImage);
641 inherited;
642 end;
643
644 procedure TItemResource.LoadFromFile(ResourceConfig: TCastleConfig);
645 begin
646 inherited;
647
648 FImageUrl := ResourceConfig.GetUrl('image');
649
650 FCaption := ResourceConfig.GetValue('caption', '');
651 if FCaption = '' then
652 raise Exception.CreateFmt('Empty caption attribute for item "%s"', [Name]);
653 end;
654
655 function TItemResource.Image: TEncodedImage;
656 begin
657 if FImage = nil then
658 FImage := LoadEncodedImage(ImageUrl);
659 Result := FImage;
660 end;
661
662 function TItemResource.DrawableImage: TDrawableImage;
663 begin
664 if FDrawableImage = nil then
665 { TODO: this will load the ImageUrl 2nd time. }
666 FDrawableImage := TDrawableImage.Create(ImageUrl);
667 Result := FDrawableImage;
668 end;
669
670 procedure TItemResource.PrepareCore(const Params: TPrepareParams;
671 const DoProgress: boolean);
672 begin
673 inherited;
674 { prepare DrawableImage now }
675 DrawableImage;
676 end;
677
678 function TItemResource.CreateItem(const AQuantity: Cardinal): TInventoryItem;
679 begin
680 Result := ItemClass.Create(nil { for now, TInventoryItem.Owner is always nil });
681 { set properties that in practice must have other-than-default values
682 to sensibly use the item }
683 Result.FResource := Self;
684 Result.FQuantity := AQuantity;
685 Assert(Result.Quantity >= 1, 'Item''s Quantity must be >= 1');
686 end;
687
688 function TItemResource.ItemClass: TInventoryItemClass;
689 begin
690 Result := TInventoryItem;
691 end;
692
693 procedure TItemResource.InstantiatePlaceholder(
694 const ALevel: TAbstractLevel;
695 const APosition, ADirection: TVector3;
696 const NumberPresent: boolean; const Number: Int64);
697 var
698 ItemQuantity: Cardinal;
699 begin
700 { calculate ItemQuantity }
701 if NumberPresent then
702 ItemQuantity := Number else
703 ItemQuantity := 1;
704
705 CreateItem(ItemQuantity).PutOnWorld(ALevel, APosition);
706 end;
707
708 function TItemResource.AlwaysPrepared: boolean;
709 begin
710 Result := true;
711 end;
712
713 function TItemResource.BoundingBoxRotated(const GravityUp: TVector3): TBox3D;
714 var
715 B: TBox3D;
716 begin
717 B := FBaseAnimation.BoundingBox;
718 Result :=
719 B.Transform(RotationMatrixRad(DegToRad(45 ), GravityUp)) +
720 B.Transform(RotationMatrixRad(DegToRad(45 + 90 ), GravityUp)) +
721 B.Transform(RotationMatrixRad(DegToRad(45 + 90 * 2), GravityUp)) +
722 B.Transform(RotationMatrixRad(DegToRad(45 + 90 * 3), GravityUp));
723 end;
724
725 { TItemWeaponResource ------------------------------------------------------------ }
726
727 constructor TItemWeaponResource.Create(AOwner: TComponent);
728 begin
729 inherited;
730 FAttackAnimation := T3DResourceAnimation.Create(Self, 'attack');
731 FReadyAnimation := T3DResourceAnimation.Create(Self, 'ready');
732 FReloadAnimation := T3DResourceAnimation.Create(Self, 'reload', false);
733 FAttackTime := DefaultAttackTime;
734 FReloadTime := DefaultReloadTime;
735 FAttackDamageConst := DefaultAttackDamageConst;
736 FAttackDamageRandom := DefaultAttackDamageRandom;
737 FAttackKnockbackDistance := DefaultAttackKnockbackDistance;
738 FAttackShoot := DefaultAttackShoot;
739 end;
740
741 procedure TItemWeaponResource.LoadFromFile(ResourceConfig: TCastleConfig);
742 begin
743 inherited;
744
745 {$warnings off} // using deprecated SoundFromName in deprecated
746 EquippingSound := SoundEngine.SoundFromName(
747 ResourceConfig.GetValue('equipping_sound', ''));
748 AttackSoundStart := SoundEngine.SoundFromName(
749 ResourceConfig.GetValue('attack/sound_start', ''));
750 AttackSoundHit := SoundEngine.SoundFromName(
751 ResourceConfig.GetValue('attack/sound_hit', ''));
752 FireMissileSound := SoundEngine.SoundFromName(
753 ResourceConfig.GetValue('fire_missile/sound', ''));
754 {$warnings on}
755
756 AttackTime := ResourceConfig.GetFloat('attack/time', DefaultAttackTime);
757 ReloadTime := ResourceConfig.GetFloat('attack/time', DefaultReloadTime);
758 AttackAmmo := ResourceConfig.GetValue('attack/ammo', '');
759 AttackAmmoCapacity := ResourceConfig.GetValue('attack/ammo_capacity', 0);
760 AttackDamageConst := ResourceConfig.GetFloat('attack/damage/const',
761 DefaultAttackDamageConst);
762 AttackDamageRandom := ResourceConfig.GetFloat('attack/damage/random',
763 DefaultAttackDamageRandom);
764 AttackKnockbackDistance := ResourceConfig.GetFloat('attack/knockback_distance',
765 DefaultAttackKnockbackDistance);
766 AttackShoot := ResourceConfig.GetValue('attack/shoot', DefaultAttackShoot);
767 FireMissileName := ResourceConfig.GetValue('fire_missile/name', '');
768 end;
769
770 function TItemWeaponResource.ItemClass: TInventoryItemClass;
771 begin
772 Result := TItemWeapon;
773 end;
774
775 { TInventoryItem ------------------------------------------------------------ }
776
777 procedure TInventoryItem.Stack(var Item: TInventoryItem);
778 begin
779 if Item.Resource = Resource then
780 begin
781 { Stack Item with us }
782 Quantity := Quantity + Item.Quantity;
783 FreeAndNil(Item);
784 end;
785 end;
786
787 function TInventoryItem.Split(QuantitySplit: Cardinal): TInventoryItem;
788 begin
789 Check(Between(Integer(QuantitySplit), 1, Quantity - 1),
790 'You must split >= 1 and less than current Quantity');
791
792 Result := Resource.CreateItem(QuantitySplit);
793
794 FQuantity := FQuantity - QuantitySplit;
795 end;
796
797 function TInventoryItem.PutOnWorld(
798 const ALevel: TAbstractLevel;
799 const APosition: TVector3): TItemOnWorld;
800 var
801 RootTransform: TCastleRootTransform;
802 begin
803 if ALevel.ItemsRoot = nil then
804 raise Exception.CreateFmt('Cannot add item "%s" to level, as the level is not loaded yet. Execute TLevel.Load first', [
805 Name
806 ]);
807
808 RootTransform := ALevel.RootTransform;
809
810 Result := TItemOnWorld.Create(ALevel.FreeAtUnload);
811 { set properties that in practice must have other-than-default values
812 to sensibly use the item }
813 Result.Level := ALevel;
814 Result.FItem := Self;
815 FOwner3D := Result;
816 Result.Orientation := Resource.Orientation; // must be set before SetView
817 Result.SetView(APosition, AnyOrthogonalVector(RootTransform.GravityUp), RootTransform.GravityUp);
818 {$warnings off} // using deprecated in deprecated
819 Result.Gravity := true;
820 Result.FallSpeed := Resource.FallSpeed;
821 Result.GrowSpeed := Resource.GrowSpeed;
822 {$warnings on}
823 Result.CastShadows := Resource.CastShadowVolumes;
824
825 ALevel.ItemsRoot.Add(Result);
826 end;
827
828 procedure TInventoryItem.Use;
829 begin
830 Notifications.Show('This item cannot be used');
831 end;
832
833 procedure TInventoryItem.Picked(const NewOwner: TAliveWithInventory);
834 begin
835 NewOwner.PickItem(Self);
836 end;
837
838 { TItemWeapon ---------------------------------------------------------------- }
839
840 procedure TItemWeapon.Attack(const Level: TAbstractLevel);
841 var
842 {$warnings off} // using deprecated in deprecated
843 Attacker: TCastleAlive;
844 {$warnings on}
845 AttackDC, AttackDR, AttackKD: Single;
846 AttackSoundHitDone: boolean;
847
848 procedure ImmediateAttackHit(Enemy: TCastleAlive);
849 begin
850 if not AttackSoundHitDone then
851 begin
852 SoundEngine.Play(Resource.AttackSoundHit);
853 AttackSoundHitDone := true;
854 end;
855 Enemy.Hurt(AttackDC + Random * AttackDR, Attacker.Direction, AttackKD, Attacker);
856 end;
857
858 procedure ShootAttack;
859 var
860 I: Integer;
861 Hit: TRayCollision;
862 begin
863 { TODO: allow some helpers for aiming,
864 similar to TCastleViewport.ApproximateActivation
865 or maybe just collide a tube (not infinitely thin ray) with world. }
866 Hit := Attacker.Ray(Attacker.Middle, Attacker.Direction);
867 if Hit <> nil then
868 begin
869 for I := 0 to Hit.Count - 1 do
870 {$warnings off} // using deprecated in deprecated
871 if Hit[I].Item is TCastleAlive then
872 begin
873 ImmediateAttackHit(TCastleAlive(Hit[I].Item));
874 Break;
875 end;
876 {$warnings on}
877 FreeAndNil(Hit);
878 end;
879 end;
880
881 procedure ShortRangeAttack;
882 var
883 I: Integer;
884 {$warnings off} // using deprecated in deprecated
885 Enemy: TCastleAlive;
886 {$warnings on}
887 WeaponBoundingBox: TBox3D;
888 CreaturesRoot: TCastleTransform;
889 begin
890 { Attacker.Direction may be multiplied by something here for long-range weapons }
891 WeaponBoundingBox := Attacker.BoundingBox.Translate(Attacker.Direction);
892 { Tests: Writeln('WeaponBoundingBox is ', WeaponBoundingBox.ToNiceStr); }
893 CreaturesRoot := Level.CreaturesRoot;
894 { TODO: we would prefer to use CreaturesRoot.BoxCollision for this,
895 but we need to know which creature was hit. }
896 for I := 0 to CreaturesRoot.Count - 1 do
897 {$warnings off} // using deprecated in deprecated
898 if CreaturesRoot[I] is TCastleAlive then
899 begin
900 Enemy := TCastleAlive(CreaturesRoot[I]);
901 { Tests: Writeln('Creature bbox is ', C.BoundingBox.ToNiceStr); }
902 if (Enemy <> Attacker) and
903 Enemy.BoundingBox.Collision(WeaponBoundingBox) then
904 ImmediateAttackHit(Enemy);
905 end;
906 {$warnings on}
907 end;
908
909 procedure FireMissileAttack;
910 begin
911 (Resources.FindName(Resource.FireMissileName) as TCreatureResource).
912 CreateCreature(Level, Attacker.Translation, Attacker.Direction);
913 SoundEngine.Play(Resource.FireMissileSound);
914 end;
915
916 begin
917 AttackSoundHitDone := false;
918
919 { attacking only works when there's an owner (player, in the future creature
920 should also be able to use it) of the weapon }
921 {$warnings off} // using deprecated in deprecated
922 if (Owner3D <> nil) and
923 (Owner3D is TCastleAlive) then
924 begin
925 Attacker := TCastleAlive(Owner3D);
926 {$warnings on}
927
928 AttackDC := Resource.AttackDamageConst;
929 AttackDR := Resource.AttackDamageRandom;
930 AttackKD := Resource.AttackKnockbackDistance;
931
932 if (AttackDC >= 0) or
933 (AttackDR >= 0) or
934 (AttackKD >= 0) then
935 begin
936 if Resource.AttackShoot then
937 ShootAttack
938 else
939 ShortRangeAttack;
940 end;
941
942 if Resource.FireMissileName <> '' then
943 FireMissileAttack;
944 end;
945 end;
946
947 procedure TItemWeapon.Use;
948 begin
949 if (Owner3D <> nil) and
950 (Owner3D is TPlayer) then
951 TPlayer(Owner3D).EquippedWeapon := Self;
952 end;
953
954 function TItemWeapon.Resource: TItemWeaponResource;
955 begin
956 Result := (inherited Resource) as TItemWeaponResource;
957 end;
958
959 procedure TItemWeapon.Equip;
960 begin
961 SoundEngine.Play(Resource.EquippingSound);
962 { Just in case we had different State from previous weapon usage, clear it }
963 FState := wsReady;
964 FStateChangeTime := LifeTime;
965 ReloadNow;
966 end;
967
968 procedure TItemWeapon.EquippedAttack(const Level: TAbstractLevel);
969
970 { Check do you have ammunition to perform attack, and decrease it if yes. }
971 function CheckAmmo: boolean;
972 var
973 Inventory: TInventory;
974 AmmoIndex: Integer;
975 AmmoItem: TInventoryItem;
976 AmmoResource: TItemResource;
977 begin
978 { When AttackAmmo is set, check whether the owner has ammunition.
979 Currently, only Player may have Inventory with items. }
980 if Resource.AttackAmmo <> '' then
981 begin
982 if (Owner3D <> nil) and
983 (Owner3D is TAliveWithInventory) then
984 begin
985 Inventory := TAliveWithInventory(Owner3D).Inventory;
986 AmmoResource := Resources.FindName(Resource.AttackAmmo) as TItemResource;
987 AmmoIndex := Inventory.FindResource(AmmoResource);
988 Result := AmmoIndex <> -1;
989 if Result then
990 begin
991 { delete ammunition from inventory }
992 AmmoItem := Inventory[AmmoIndex];
993 AmmoItem.Quantity := AmmoItem.Quantity - 1;
994 Inventory.CheckDepleted(AmmoItem);
995 end else
996 begin
997 Notifications.Show('You have no ammunition');
998 {$warnings off} // just to keep deprecated working
999 SoundEngine.Play(stPlayerInteractFailed);
1000 {$warnings on}
1001 end;
1002 end else
1003 Result := false; // other creatures cannot have ammo for now
1004 end else
1005 Result := true; // no ammo required
1006 end;
1007
1008 begin
1009 if (FState = wsReady) and CheckAmmo then
1010 begin
1011 SoundEngine.Play(Resource.AttackSoundStart);
1012 FState := wsAttack;
1013 FStateChangeTime := LifeTime;
1014 AttackDone := false;
1015
1016 { if AttackTime = 0, attack immediately, otherwise this could get aborted
1017 by TItemWeapon.EquippedUpdate if AttackAnim.Duration = 0. }
1018 if Resource.AttackTime = 0 then
1019 begin
1020 AttackDone := true;
1021 Attack(Level);
1022 end;
1023
1024 if AmmoLoaded > 0 then
1025 Dec(FAmmoLoaded);
1026 end;
1027 end;
1028
1029 procedure TItemWeapon.EquippedReload(const IgnorePreviousState: Boolean);
1030 begin
1031 if IgnorePreviousState or (FState = wsReady) then
1032 begin
1033 FStateChangeTime := LifeTime;
1034 FState := wsReload;
1035 ReloadDone := false;
1036
1037 { if ReloadTime = 0, reload immediately. }
1038 if Resource.ReloadTime = 0 then
1039 begin
1040 ReloadDone := true;
1041 ReloadNow;
1042 end;
1043 end;
1044 end;
1045
1046 procedure TItemWeapon.ReloadNow;
1047
1048 { Limit AmmoLoaded by the currently owned ammunition number. }
1049 procedure LimitAmmoLoaded;
1050 var
1051 Inventory: TInventory;
1052 AmmoIndex: Integer;
1053 AmmoResource: TItemResource;
1054 MaxAmmoLoaded: Cardinal;
1055 begin
1056 if (Resource.AttackAmmo <> '') and
1057 (Owner3D <> nil) and
1058 (Owner3D is TAliveWithInventory) then
1059 begin
1060 Inventory := TAliveWithInventory(Owner3D).Inventory;
1061
1062 AmmoResource := Resources.FindName(Resource.AttackAmmo) as TItemResource;
1063 AmmoIndex := Inventory.FindResource(AmmoResource);
1064
1065 if AmmoIndex <> -1 then
1066 MaxAmmoLoaded := Inventory[AmmoIndex].Quantity
1067 else
1068 MaxAmmoLoaded := 0;
1069
1070 AmmoLoaded := Min(AmmoLoaded, MaxAmmoLoaded);
1071 end;
1072 end;
1073
1074 begin
1075 FAmmoLoaded := Resource.AttackAmmoCapacity;
1076 LimitAmmoLoaded;
1077 end;
1078
1079 procedure TItemWeapon.EquippedUpdate(const Level: TAbstractLevel; const SecondsPassed: Single;
1080 const ResourceFrame: TResourceFrame);
1081 var
1082 StateTime: Single;
1083 begin
1084 LifeTime := LifeTime + SecondsPassed;
1085
1086 StateTime := LifeTime - FStateChangeTime;
1087
1088 { perform action in the middle of state }
1089 case FState of
1090 wsAttack:
1091 if (not AttackDone) and (StateTime >= Resource.AttackTime) then
1092 begin
1093 AttackDone := true;
1094 Attack(Level);
1095 end;
1096 wsReload:
1097 if (not ReloadDone) and (StateTime >= Resource.ReloadTime) then
1098 begin
1099 ReloadDone := true;
1100 ReloadNow;
1101 end;
1102 else ;
1103 end;
1104
1105 { advance to next State, if necessary }
1106 case FState of
1107 wsAttack:
1108 if StateTime > Resource.AttackAnimation.Duration then
1109 begin
1110 if (Resource.AttackAmmoCapacity <> 0) and (AmmoLoaded = 0) then
1111 begin
1112 EquippedReload(true);
1113 StateTime := LifeTime - FStateChangeTime; // EquippedReload changed FState and FStateChangeTime
1114 end else
1115 begin
1116 FState := wsReady;
1117 FStateChangeTime := LifeTime;
1118 end;
1119 end;
1120 wsReload:
1121 if StateTime > Resource.ReloadAnimation.Duration then
1122 begin
1123 FState := wsReady;
1124 FStateChangeTime := LifeTime;
1125 end;
1126 else ;
1127 end;
1128
1129 { update animation frame to display }
1130 case FState of
1131 wsAttack: ResourceFrame.SetFrame(Level, Resource.AttackAnimation, StateTime, false);
1132 wsReload: ResourceFrame.SetFrame(Level, Resource.ReloadAnimation, StateTime, false);
1133 wsReady: ResourceFrame.SetFrame(Level, Resource.ReadyAnimation, StateTime, true);
1134 {$ifndef COMPILER_CASE_ANALYSIS}
1135 else raise EInternalError.Create('Weapon state?');
1136 {$endif}
1137 end;
1138 end;
1139
1140 { TInventory ------------------------------------------------------------ }
1141
1142 constructor TInventory.Create(const AOwner3D: TAliveWithInventory);
1143 begin
1144 inherited Create(true);
1145 FOwner3D := AOwner3D;
1146 end;
1147
1148 function TInventory.FindResource(Resource: TItemResource): Integer;
1149 begin
1150 for Result := 0 to Count - 1 do
1151 if Items[Result].Resource = Resource then
1152 Exit;
1153 Result := -1;
1154 end;
1155
1156 function TInventory.Pick(var Item: TInventoryItem): Integer;
1157 begin
1158 for Result := 0 to Count - 1 do
1159 begin
1160 Items[Result].Stack(Item);
1161 if Item = nil then
1162 begin
1163 // item was stacked with something
1164 Item := Items[Result];
1165 Item.FOwner3D := Owner3D;
1166 Exit;
1167 end;
1168 end;
1169
1170 Add(Item);
1171 Item.FOwner3D := Owner3D;
1172 Result := Count - 1;
1173 end;
1174
1175 function TInventory.Drop(const ItemIndex: Integer): TInventoryItem;
1176 var
1177 SelectedItem: TInventoryItem;
1178 DropQuantity: Cardinal;
1179 begin
1180 SelectedItem := Items[ItemIndex];
1181
1182 { For now, always drop 1 item.
1183 This makes it independent from message boxes, and also suitable for
1184 items owned by creatures.
1185
1186 if SelectedItem.Quantity > 1 then
1187 begin
1188 DropQuantity := SelectedItem.Quantity;
1189
1190 if not MessageInputQueryCardinal(Window,
1191 Format('You have %d items "%s". How many of them do you want to drop ?',
1192 [SelectedItem.Quantity, SelectedItem.Resource.Caption]),
1193 DropQuantity) then
1194 Exit(nil);
1195
1196 if not Between(DropQuantity, 1, SelectedItem.Quantity) then
1197 begin
1198 Notifications.Show(Format('You cannot drop %d items', [DropQuantity]));
1199 Exit(nil);
1200 end;
1201 end else }
1202 DropQuantity := 1;
1203
1204 if DropQuantity = SelectedItem.Quantity then
1205 begin
1206 Result := SelectedItem;
1207 Extract(SelectedItem); { Extract, not Remove, do not free }
1208 end else
1209 begin
1210 Result := SelectedItem.Split(DropQuantity);
1211 end;
1212
1213 Result.FOwner3D := nil;
1214 end;
1215
1216 procedure TInventory.CheckDepleted(const Item: TInventoryItem);
1217 var
1218 Index: Integer;
1219 begin
1220 if Item.Quantity = 0 then
1221 begin
1222 Index := IndexOf(Item);
1223 if Index <> -1 then
1224 Delete(Index);
1225 end;
1226 end;
1227
1228 procedure TInventory.Use(const Index: Integer);
1229 var
1230 Item: TInventoryItem;
1231 begin
1232 Item := Items[Index];
1233 Item.Use;
1234 { CheckDepleted will search for new index, since using an item
1235 may change the items list and so change the index. }
1236 CheckDepleted(Item);
1237 end;
1238
1239 { TItemOnWorld.TItemDebugTransform -------------------------------------------------------- }
1240
1241 procedure TItemOnWorld.TItemDebugTransform.InitializeNodes;
1242 begin
1243 inherited;
1244
1245 FBoxRotated := TDebugBox.Create(Self);
1246 FBoxRotated.Color := Gray;
1247 ParentSpace.AddChildren(FBoxRotated.Root);
1248 end;
1249
1250 procedure TItemOnWorld.TItemDebugTransform.Update;
1251 var
1252 BBoxRotated: TBox3D;
1253 begin
1254 inherited;
1255
1256 // show Parent.BoundingBoxRotated
1257 BBoxRotated := (Parent as TItemOnWorld).BoundingBoxRotated;
1258 FBoxRotated.Box := BBoxRotated;
1259 end;
1260
1261 { TItemOnWorld ------------------------------------------------------------ }
1262
1263 constructor TItemOnWorld.Create(AOwner: TComponent);
1264 begin
1265 inherited Create(AOwner);
1266
1267 CollidesWithMoving := true;
1268 {$warnings off} // using deprecated in deprecated
1269 Gravity := true;
1270 {$warnings on}
1271
1272 FDebugTransform := TItemDebugTransform.Create(Self);
1273 FDebugTransform.Parent := Self;
1274
1275 { Items are not collidable, player can enter them to pick them up.
1276 For now, this also means that creatures can pass through them,
1277 which isn't really troublesome now. }
1278 Collides := false;
1279
1280 FResourceFrame := TResourceFrame.Create(Self);
1281 Add(FResourceFrame);
1282 end;
1283
1284 destructor TItemOnWorld.Destroy;
1285 begin
1286 FreeAndNil(FItem);
1287 inherited;
1288 end;
1289
1290 function TItemOnWorld.BoundingBoxRotated: TBox3D;
1291 begin
1292 Result := Item.Resource.BoundingBoxRotated(World.GravityUp).Translate(Translation);
1293 end;
1294
1295 procedure TItemOnWorld.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType);
1296
1297 procedure UpdateResourceFrame;
1298 begin
1299 if Item = nil then Exit;
1300 FResourceFrame.SetFrame(Level, Item.Resource.BaseAnimation, LifeTime, true);
1301 end;
1302
1303 var
1304 DirectionZero, U: TVector3;
1305 Player: TAliveWithInventory;
1306 begin
1307 inherited;
1308 if not Exists then Exit;
1309
1310 LifeTime := LifeTime + SecondsPassed;
1311
1312 { LifeTime is used to choose animation frame in GetChild.
1313 So the item constantly changes, even when it's
1314 transformation (things taken into account in TCastleTransform) stay equal. }
1315 VisibleChangeHere([vcVisibleGeometry]);
1316
1317 ItemRotation := ItemRotation + (RotationSpeed * SecondsPassed);
1318 U := World.GravityUp; // copy to local variable for speed
1319 DirectionZero := AnyOrthogonalVector(U).Normalize;
1320 SetView(RotatePointAroundAxisRad(ItemRotation, DirectionZero, U), U);
1321
1322 FDebugTransform.Exists := RenderDebug;
1323
1324 if Level.GetPlayer is TAliveWithInventory then
1325 Player := TAliveWithInventory(Level.GetPlayer)
1326 else
1327 Player := nil;
1328
1329 if AutoPick and
1330 (Player <> nil) and
1331 (not Player.Dead) and
1332 BoundingBox.Collision(Player.BoundingBox) then
1333 ExtractItem.Picked(Player);
1334
1335 { Since we cannot live with Item = nil, we free ourselves }
1336 if Item = nil then
1337 RemoveMe := rtRemoveAndFree;
1338
1339 UpdateResourceFrame;
1340 end;
1341
1342 function TItemOnWorld.ExtractItem: TInventoryItem;
1343 begin
1344 { We no longer own this Item, so clear references. }
1345 Result := Item;
1346 Result.FOwner3D := nil;
1347 FItem := nil;
1348 end;
1349
1350 { TAliveWithInventory ------------------------------------------------------ }
1351
1352 constructor TAliveWithInventory.Create(AOwner: TComponent);
1353 begin
1354 inherited;
1355 FInventory := TInventory.Create(Self);
1356 end;
1357
1358 destructor TAliveWithInventory.Destroy;
1359 begin
1360 FreeAndNil(FInventory);
1361 inherited;
1362 end;
1363
1364 function TAliveWithInventory.PickItemUpdate(var Item: TInventoryItem): Integer;
1365 begin
1366 Result := Inventory.Pick(Item);
1367 end;
1368
1369 function TAliveWithInventory.PickItem(Item: TInventoryItem): Integer;
1370 begin
1371 Result := PickItemUpdate(Item);
1372 end;
1373
1374 function TAliveWithInventory.DropItem(const Index: Integer): TItemOnWorld;
1375
1376 function DirectionInGravityPlane: TVector3;
1377 var
1378 GravityUp: TVector3;
1379 begin
1380 GravityUp := World.GravityUp;
1381 Result := Direction;
1382 if not VectorsParallel(Result, GravityUp) then
1383 MakeVectorsOrthoOnTheirPlane(Result, GravityUp);
1384 end;
1385
1386 function GetItemDropTranslation(DroppedItemResource: TItemResource;
1387 out DropTranslation: TVector3): boolean;
1388 var
1389 ItemBox: TBox3D;
1390 ItemBoxRadius: Single;
1391 ItemBoxMiddle: TVector3;
1392 begin
1393 ItemBox := DroppedItemResource.BoundingBoxRotated(World.GravityUp);
1394 ItemBoxMiddle := ItemBox.Center;
1395 { Box3DRadius calculates radius around (0, 0, 0) and we want
1396 radius around ItemBoxMiddle }
1397 ItemBoxRadius := ItemBox.Translate(-ItemBoxMiddle).Radius;
1398
1399 { Calculate DropTranslation.
1400
1401 We must move the item a little before us to
1402 1. show visually player that the item was dropped
1403 2. to avoid automatically picking it again
1404
1405 Note that I take direction from DirectionInGravityPlane,
1406 not from Direction, otherwise when player is looking
1407 down he could be able to put item "inside the ground".
1408 Collision detection with the level below would actually
1409 prevent putting item "inside the ground", but the item
1410 would be too close to the player --- he could pick it up
1411 immediately. }
1412 {$warnings off} // using deprecated in deprecated
1413 DropTranslation := Translation +
1414 DirectionInGravityPlane *
1415 (0.6 * (PreferredHeight * Sqrt3 + ItemBox.Diagonal));
1416 {$warnings on}
1417
1418 { Now check is DropTranslation actually possible
1419 (i.e. check collisions item<->everything).
1420 The assumption is that item starts from
1421 Translation and is moved to DropTranslation.
1422
1423 But actually we must shift both these positions,
1424 so that we check positions that are ideally in the middle
1425 of item's BoundingBoxRotated. Otherwise the item
1426 could get *partially* stuck within the wall, which wouldn't
1427 look good. }
1428
1429 Result := World.WorldMoveAllowed(
1430 ItemBoxMiddle + Translation,
1431 ItemBoxMiddle + DropTranslation, true, ItemBoxRadius,
1432 ItemBox.Translate(Translation),
1433 ItemBox.Translate(DropTranslation), false);
1434 end;
1435
1436 var
1437 DropTranslation: TVector3;
1438 DropppedItem: TInventoryItem;
1439 begin
1440 Result := nil;
1441
1442 if Between(Index, 0, Inventory.Count - 1) then
1443 begin
1444 if GetItemDropTranslation(Inventory[Index].Resource, DropTranslation) then
1445 begin
1446 DropppedItem := Inventory.Drop(Index);
1447 Result := DropppedItem.PutOnWorld(InternalLevel, DropTranslation);
1448 end;
1449 end;
1450 end;
1451
1452 procedure TAliveWithInventory.UseItem(const Index: Integer);
1453 begin
1454 if Between(Index, 0, Inventory.Count - 1) then
1455 Inventory.Use(Index);
1456 end;
1457
1458 initialization
1459 TItemOnWorld.RotationSpeed := TItemOnWorld.DefaultRotationSpeed;
1460 TItemOnWorld.AutoPick := true;
1461
1462 RegisterResourceClass(TItemResource, 'Item');
1463 RegisterResourceClass(TItemWeaponResource, 'Weapon');
1464 end.