-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
castlecreatures.pas
2916 lines (2494 loc) · 108 KB
/
castlecreatures.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Copyright 2006-2023 Michalis Kamburelis.
This file is part of "Castle Game Engine".
"Castle Game Engine" is free software; see the file COPYING.txt,
included in this distribution, for details about the copyright.
"Castle Game Engine" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------
}
{ Creatures. }
unit CastleCreatures
deprecated 'express creature AI as TCastleBehavior';
{$I castleconf.inc}
interface
{$warnings off} // using deprecated CastleResources in deprecated
uses Classes, Generics.Collections,
CastleVectors, CastleBoxes, CastleClassUtils, CastleUtils, CastleScene,
CastleStringUtils, CastleResources, CastleXMLConfig, CastleTransform,
CastleTransformExtra, CastleSoundEngine, CastleFrustum, X3DNodes, CastleColors,
CastleDebugTransform, CastleSectors, CastleBehaviors;
{$warnings on}
type
TCreatureState = type Integer;
const
csIdle = TCreatureState(0);
csWalk = TCreatureState(1);
csAttack = TCreatureState(2);
csFireMissile = TCreatureState(3);
csDie = TCreatureState(4);
csDieBack = TCreatureState(5);
csHurt = TCreatureState(6);
{ Maximum TCreatureState value reserved by CastleCreatures unit. }
csMax = csHurt;
type
TCreature = class;
TCreatureClass = class of TCreature;
{ Basic abstract resource used by all creatures.
Basic creature can walk or fly, has life and can be hurt,
can fall down because of gravity and such.
A "resource" is an information shared by all creatures of given type,
for example you can have two instances of TCreatureResource: Werewolf
and Knight. Actually, they would have to be instances of one of
the TCreatureResource descendants, like TWalkAttackCreatureResource,
as TCreatureResource is abstract. Using them you can create and place
on your your level milions of actual werewolves and knights
(for example instances of TWalkAttackCreature).
Every werewolf on the level will have potentially different life and
state (attacking, walking), but all werewolves will share the same
resource, so e.g. all werewolves will use the same dying animation
(TWalkAttackCreatureResource.DieAnimation) and dying sound
(TCreatureResource.SoundDie).
Note that some of the information stored in resource
is only used to initialize new creatures and can be changed later
during creature life, for example TCreatureResource.DefaultMaxLife
and TCreatureResource.Flying. }
TCreatureResource = class(T3DResource)
strict private
FFlying: boolean;
FSoundSuddenPain: TCastleSound;
FSoundDie: TCastleSound;
FSoundDieTiedToCreature: boolean;
FDefaultMaxLife: Single;
FKnockBackDistance: Single;
FKnockBackSpeed: Single;
FCollidesWhenDead: boolean;
FScaleMin, FScaleMax: Single;
FRadiusOverride: Single;
FAttackDamageConst: Single;
FAttackDamageRandom: Single;
FAttackKnockbackDistance: Single;
FFallMinHeightToSound: Single;
FFallMinHeightToDamage: Single;
FFallDamageScaleMin: Single;
FFallDamageScaleMax: Single;
FFallSound: TCastleSound;
FMiddleHeight: Single;
protected
{ Sphere radius for collision detection for alive creatures.
Must be something <> 0 for collision detection to work.
Defining it in the creature resource.xml file
(as radius="xxx" attribute on the root <resource> element)
overrides the results of this function. }
function RadiusCalculate(const GravityUp: TVector3): Single; virtual;
{ Can the "up" vector be skewed, that is: not equal to gravity up vector.
This is used when creating creature in CreateCreature.
The default implementation here returns @true,
which allows creature model to point slightly upward/downward.
Override this to return @false if given creature kind for some reason cannot
have up vector different. For example, TWalkAttackCreature AI
assumes that the non-flying creature is always standing up.
For now, non-flying TWalkAttackCreature cannot "stand up" before walking,
in case it's up vector gets skewed. }
function FlexibleUp: boolean; virtual;
public
const
{ Default value for TCreatureResource.DefaultMaxLife.
Yes, it's not a typo, this identifier starts with "DefaultDefault". }
DefaultDefaultMaxLife = 100.0;
DefaultFlying = false;
DefaultKnockBackDistance = 4.0;
DefaultSoundDieTiedToCreature = true;
DefaultAttackDamageConst = 0.0;
DefaultAttackDamageRandom = 0.0;
DefaultAttackKnockbackDistance = 0.0;
DefaultFallMinHeightToSound = 1.0;
DefaultFallSoundName = 'creature_fall';
constructor Create(AOwner: TComponent); override;
{ Flying creatures are not affected by gravity and
(in case of TWalkAttackCreatureResource) their move direction is free.
For all creatures, TCreature.Gravity (inherited from TCastleTransform.Gravity)
is set to @code("not Flying") at creation. (Except TMissileCreatureResource,
that has special approach to gravity,
see TMissileCreatureResource.DirectionFallSpeed.)
For TWalkAttackCreatureResource, additionally Flying allows to move
freely, while non-flying creatures are constrained to move
(and think about moving) only horizontally.
You can always change the Gravity property of a particular creature
during it's lifetime, so a creature may start/stop flying during game.
For example, this is how you can let your creatures to use jetpack and such.
Be careful about creature @link(Radius) and @link(MiddleHeight) properties
in this case, make sure that the values (explicitly set or automatically
calculated) are suitable for both flying and non-flying states. }
property Flying: boolean read FFlying write FFlying default DefaultFlying;
property SoundSuddenPain: TCastleSound
read FSoundSuddenPain write FSoundSuddenPain;
property SoundDie: TCastleSound
read FSoundDie write FSoundDie;
{ See TCreature.Sound3d TiedToCreature parameter docs.
You can set this to false if you want SoundDie to last even
after the creature object was destroyed. }
property SoundDieTiedToCreature: boolean
read FSoundDieTiedToCreature write FSoundDieTiedToCreature
default DefaultSoundDieTiedToCreature;
{ The default MaxLife for creatures of this resource.
Note that you can always override it for a particular creature
instance. You can use a special creature placeholder with
a specific starting life value
(see TLevel.Load for placeholders docs,
and see https://castle-engine.io/manual_high_level_3d_classes.php
about the creature placeholders).
Or you can use CreateCreature overloaded version that takes extra MaxLife
parameter.
So this is only a "suggested" default for MaxLife of this creature. }
property DefaultMaxLife: Single
read FDefaultMaxLife write FDefaultMaxLife {$ifdef FPC}default DefaultDefaultMaxLife{$endif};
{ Create the TCreature instance using this resource.
Uses TCreature descendant that can best cooperate with this resource,
e.g. if this resource has settings for short-range fight,
then the TCreature instance will be able to short-range fight.
The creature is added to the World, and is owned by World.
This is the only way to create TCreature instances.
ADirection passed here is normalized, and then used
as initial TCreature.Direction value.
@groupBegin }
function CreateCreature(
const ALevel: TAbstractLevel;
const APosition, ADirection: TVector3;
const MaxLife: Single): TCreature; overload; virtual;
function CreateCreature(
const ALevel: TAbstractLevel;
const APosition, ADirection: TVector3): TCreature; overload;
{ @groupEnd }
{ Instantiate creature placeholder, by calling CreateCreature. }
procedure InstantiatePlaceholder(
const ALevel: TAbstractLevel;
const APosition, ADirection: TVector3;
const NumberPresent: boolean; const Number: Int64); override;
function CreatureClass: TCreatureClass; virtual; abstract;
procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
{ Distance this creature is knocked back when hurt (should reflect
the creature weight, how easy it is to push this creature).
Will always be multiplied by the knocking distance of the weapon that
caused the push (which should reflect the force of the weapon blow),
see TItemWeaponResource.AttackKnockbackDistance.
Only for TWalkAttackCreature, the final distance the creature
is knocked back is capped
by the time of the HurtAnimation (HurtAnimation.Duration).
When the hurt animation ends, the knockback effect always ends,
even if the distance (creature * weapon) indicates it should be knocked
further. Otherwise knockback would work on standing creature,
which could look bad. This may be changed some day. }
property KnockBackDistance: Single
read FKnockBackDistance write FKnockBackDistance
{$ifdef FPC}default DefaultKnockBackDistance{$endif};
{ See TCastleAlive.KnockBackSpeed. }
{$warnings off} // using deprecated in deprecated
property KnockBackSpeed: Single
read FKnockBackSpeed write FKnockBackSpeed
{$ifdef FPC}default TCastleAlive.DefaultKnockBackSpeed{$endif};
{$warnings on}
{ By default dead creatures (corpses) don't collide, this usually looks better. }
property CollidesWhenDead: boolean
read FCollidesWhenDead write FCollidesWhenDead default false;
{ Minimum scale when spawning, must be <= ScaleMax.
When we spawn a creature, we set it's scale to random number in
[ScaleMin, ScaleMax] range. By default both ScaleMin and ScaleMax are 1,
resulting in no scaling. }
property ScaleMin: Single read FScaleMin write FScaleMin {$ifdef FPC}default 1{$endif};
{ Maximum scale when spawning, must be >= ScaleMin.
When we spawn a creature, we set it's scale to random number in
[ScaleMin, ScaleMax] range. By default both ScaleMin and ScaleMax are 1,
resulting in no scaling. }
property ScaleMax: Single read FScaleMax write FScaleMax {$ifdef FPC}default 1{$endif};
{ Attack damage.
Used by the creatures that actually do some kind of direct attack.
For example it is used for short-range attack by TWalkAttackCreatureResource
(if TWalkAttackCreatureResource.AttackAnimation defined)
and for hit of TMissileCreatureResource.
The damage dealt is a random float in the range
[AttackDamageConst, AttackDamageConst + AttackDamageRandom].
Both AttackDamageConst and AttackDamageRandom must be >= 0.
@groupBegin }
property AttackDamageConst: Single
read FAttackDamageConst write FAttackDamageConst
{$ifdef FPC}default DefaultAttackDamageConst{$endif};
{ Attack damage, see @link(AttackDamageConst) for documentation. }
property AttackDamageRandom: Single
read FAttackDamageRandom write FAttackDamageRandom
{$ifdef FPC}default DefaultAttackDamageRandom{$endif};
{ @groupEnd }
{ Attack knockback (how far will the victim be pushed back).
Used by the creatures that actually do some kind of direct attack.
For example it is used for short-range attack by TWalkAttackCreatureResource
(if TWalkAttackCreatureResource.AttackAnimation defined)
and for hit of TMissileCreatureResource.
Must be >= 0. Value equal exactly 0 disables any knockback. }
property AttackKnockbackDistance: Single
read FAttackKnockbackDistance write FAttackKnockbackDistance
{$ifdef FPC}default DefaultAttackKnockbackDistance{$endif};
{ Height of the eyes of the creature,
used for various collision detection routines.
See TCastleTransform.MiddleHeight for a precise documentation.
Game developers can use the RenderDebug variable to easily
visualize the bounding sphere (and other things) around resources.
The bounding sphere is centered around the point derived from MiddleHeight
setting and with given creature radius
(given in resource.xml, or automatically calculated by
@link(TCreatureResource.RadiusCalculate)). }
property MiddleHeight: Single
read FMiddleHeight write FMiddleHeight
{$ifdef FPC}default TCastleTransform.DefaultMiddleHeight{$endif};
{ When creature is falling down, it needs to fall at least the given distance
to make a "hurt" sound. }
property FallMinHeightToSound: Single
read FFallMinHeightToSound write FFallMinHeightToSound
{$ifdef FPC}default DefaultFallMinHeightToSound{$endif};
{ When creature is falling down, it needs to fall at least the given distance
to get some damage from the fall.
The amount of damage is determined by @link(FallDamageScaleMin),
@link(FallDamageScaleMax). }
property FallMinHeightToDamage: Single
read FFallMinHeightToDamage write FFallMinHeightToDamage
{$ifdef FPC}default DefaultFallMinHeightToDamage{$endif};
{ When creature is falling down (at least for @link(FallMinHeightToDamage) distance),
it will take a random damage in range [FallDamageScaleMin, FallDamageScaleMax]. }
property FallDamageScaleMin: Single
read FFallDamageScaleMin write FFallDamageScaleMin
{$ifdef FPC}default DefaultFallDamageScaleMin{$endif};
{ When creature is falling down (at least for @link(FallMinHeightToDamage) distance),
it will take a random damage in range [FallDamageScaleMin, FallDamageScaleMax]. }
property FallDamageScaleMax: Single
read FFallDamageScaleMax write FFallDamageScaleMax
{$ifdef FPC}default DefaultFallDamageScaleMax{$endif};
{ Sound when falling.
The default is the sound named 'creature_fall'. }
property FallSound: TCastleSound
read FFallSound write FFallSound;
{ Radius used for resolving (some) collisions with the alive creature.
This can be read from the @code(resource.xml) file.
When zero, the radius is automatically calculated looking at the
3D model bounding box, and taking into account gravity direction,
see @link(TCreatureResource.RadiusCalculate). }
property RadiusOverride: Single
read FRadiusOverride write FRadiusOverride;
{ Sphere radius for collision detection for alive creatures.
Must be something <> 0 for collision detection to work.
You can define it in the creature resource.xml file,
by setting radius="xxx" attribute on the root <resource> element.
If it's not defined (or zero) in resource.xml file,
then we use automatically calculated radius using RadiusCalculate,
that is adjusted to the bounding box of the animation.
This radius is used only for alive creatures, because:
@unorderedList(
@item(It would cause incorrect results on many dead creatures.
Dead creatures usually have very different boxes than alive
(tall alive humanoid creature probably has a small flat bounding
box when it's lying dead on the ground). So the same radius would not work
nicely.)
@item(It is not necessary to use sphere bounding volumes for dead creatures.
The main advantage of sphere bounding volumes (over box bounding volumes)
is for moving (alive) creatures:
sphere better avoids getting stuck into obstacles (because an animation
can change the bounding box at any moment).)
@item(Actually, the results look best when dead creatures don't collide at all.)
)
The sphere center is the Middle point ("eye position") of the given creature.
If the creature may be affected by gravity then
make sure radius is < than PreferredHeight of the creature,
see TCastleTransform.PreferredHeight, otherwise creature may get stuck into ground.
In short, if you use the default implementations,
PreferredHeight is by default @italic(MiddleHeight (default 0.5) *
bounding box height). Your radius must be smaller
for all possible bounding box heights when the creature is not dead. }
function Radius(const GravityUp: TVector3): Single;
end;
{ Creature with smart walking and attacking intelligence.
May stand still (idle), walk, attack, fire missiles, and die.
Tracks the enemy (remembers last seen enemy 3D position,
walks/flies to it, possibly through sectors/waypoints ---
so it can pass through narrow doors in a labyrinth or walk over a narrow bridge).
Attacks the enemy from the right distance (a short-range attack)
and/or shoots a missile (adds a missile to the 3D world).
Runs away from the enemy (when he's too close and/or our health is low).
There are a lot of settings to achieve particular behavior,
e.g. cowardly/brave, offensive/defensive, melee/ranged, etc. }
TWalkAttackCreatureResource = class(TCreatureResource)
private
FIdleAnimation: T3DResourceAnimation;
FIdleToWalkAnimation: T3DResourceAnimation;
FWalkAnimation: T3DResourceAnimation;
FAttackAnimation: T3DResourceAnimation;
FFireMissileAnimation: T3DResourceAnimation;
FDieAnimation: T3DResourceAnimation;
FDieBackAnimation: T3DResourceAnimation;
FHurtAnimation: T3DResourceAnimation;
FMoveSpeed: Single;
FMinLifeLossToHurt: Single;
FChanceToHurt: Single;
FMaxHeightAcceptableToFall: Single;
FRandomWalkDistance: Single;
FRemoveDead: boolean;
FPreferredDistance: Single;
FRunAwayLife: Single;
FRunAwayDistance: Single;
FVisibilityAngle: Single;
FSmellDistance: Single;
FAttackMinDelay: Single;
FAttackMaxDistance: Single;
FAttackMaxAngle: Single;
FAttackTime: Single;
FAttackSoundHit: TCastleSound;
FAttackSoundStart: TCastleSound;
FFireMissileTime: Single;
FFireMissileMinDelay: Single;
FFireMissileMaxDistance: Single;
FFireMissileMaxAngle: Single;
FFireMissileName: string;
FFireMissileHeight: Single;
FFireMissileSound: TCastleSound;
protected
function FlexibleUp: boolean; override;
public
const
DefaultMoveSpeed = 10.0;
DefaultMinLifeLossToHurt = 0.0;
DefaultChanceToHurt = 1.0;
DefaultMaxHeightAcceptableToFall = 1.5;
DefaultRandomWalkDistance = 10.0;
DefaultRemoveDead = false;
DefaultPreferredDistance = 2.0;
DefaultRunAwayLife = 0.3;
DefaultRunAwayDistance = 10.0;
DefaultVisibilityAngle = Pi * 120 / 180;
DefaultSmellDistance = 0.0;
DefaultAttackTime = 0.0;
DefaultAttackMinDelay = 2.0;
DefaultAttackMaxDistance = DefaultPreferredDistance;
DefaultAttackMaxAngle = Pi / 6;
DefaultFireMissileTime = 0.0;
DefaultFireMissileMinDelay = DefaultAttackMinDelay;
DefaultFireMissileMaxDistance = 30.0;
DefaultFireMissileMaxAngle = DefaultAttackMaxAngle;
DefaultFireMissileHeight = 0.5;
constructor Create(AOwner: TComponent); override;
procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
function CreatureClass: TCreatureClass; override;
{ An animation of standing still (being idle).
Will be played in a loop, so for best look make sure that
the beginning and end match. }
property IdleAnimation: T3DResourceAnimation read FIdleAnimation;
{ An animation when creature changes from standing still to walking.
Optional.
For best look: It's beginnig should glue with the end of IdleAnimation,
it's ending should glue with beginning of WalkAnimation. }
property IdleToWalkAnimation: T3DResourceAnimation read FIdleToWalkAnimation;
{ An animation of walking.
Will be played in a loop, so for best look make sure that
the beginning and end match. }
property WalkAnimation: T3DResourceAnimation read FWalkAnimation;
{ An animation of short-range attacking. Optional.
For best look: Beginning and end of it should roughly glue with (any)
frame of WalkAnimation and IdleAnimation.
@italic(Design notes:)
I used to have here property like AttacksWhenWalking for the creature,
to indicate whether creature changes state like
"csWalk -> csAttack -> csWalk" or
"csIdle -> csAttack -> csIdle". But this wasn't good.
Intelligent creature sometimes attacks when walking (e.g. if it just
made the distance to the enemy closer) or when standing
(when the distance was already close enough). And after performing
the attack, the creature doesn't need to go back to the original state
before the attack. }
property AttackAnimation: T3DResourceAnimation read FAttackAnimation;
{ Firing missile animation. Optional. Similar rules like AttackAnimation,
but here the "highlight" is not directly hurting enemy,
but firing a new creature (missile).
You can always override TWalkAttackCreature.FireMissile to do pretty
much anything you want, and this way treat this as an "alternate attack",
not necessarily firing a missile.
It's not really required to actually fire a missile --- it's only what
happens at the default TWalkAttackCreature.FireMissile implementation,
and it happens only if FireMissileName is not empty. }
property FireMissileAnimation: T3DResourceAnimation read FFireMissileAnimation;
{ An animation of dying.
Dying animation is not displayed in a loop, after it runs
it's duration we constantly show the final frame,
at the TCreature instance will keep existing on the level.
Unless you set RemoveDead to @true, then the dead creature
will be completely removed from the level.
For best look: Beginning should roughly glue with any point of
the idle/attack/walk animations. }
property DieAnimation: T3DResourceAnimation read FDieAnimation;
{ An optional dying animation, used when the creature is killed
by hitting it in the back. This may be useful if you want your
creature to fall face-down when killed from the back or face-up
when killed from the front. If this is defined, then DieAnimation
is only used when creature is killed by hitting it from the front.
The direction of last hit is taken from LastHurtDirection.
For best look: Just like DieAnimation, beginning should roughly
glue with any point of the idle/attack/walk animations. }
property DieBackAnimation: T3DResourceAnimation read FDieBackAnimation;
{ Animation when the creature will be hurt.
Beginning and end should *more-or-less* look like
any point of the idle/attack/walk animations. }
property HurtAnimation: T3DResourceAnimation read FHurtAnimation;
{ The moving speed: how much Direction vector will be scaled
when moving in csWalk. }
property MoveSpeed: Single read FMoveSpeed write FMoveSpeed
{$ifdef FPC}default DefaultMoveSpeed{$endif};
{ The preferred distance between enemy and the creature.
The creature will try to walk closer to the enemy if the distance is larger.
(If you want to make the creature to also walk father from the enemy
when necessary, then set RunAwayLife and RunAwayDistance.)
This should be <= AttackMaxDistance or FireMissileMaxDistance,
if you hope to actually perform a short-range or firing missile attack.
The creature can attack enemy from AttackMaxDistance
or fire missile from FireMissileMaxDistance,
but it will walk closer to the enemy if possible --- until the distance
is PreferredDistance. }
property PreferredDistance: Single
read FPreferredDistance write FPreferredDistance
{$ifdef FPC}default DefaultPreferredDistance{$endif};
{ Minimum delay between one attack and the other, in seconds.
Note that the duration of AttackAnimation also limits how often creature
can do an attack (so e.g. setting this to 0.0 doesn't mean that creature
can constantly attack, if AttackAnimation takes 1 second then at least
this 1 second will have to pass between actual attack hits). }
property AttackMinDelay: Single
read FAttackMinDelay write FAttackMinDelay
{$ifdef FPC}default DefaultAttackMinDelay{$endif};
{ Maximum distance between enemy and creature to allow creature
to start attack. The distance is measured between
enemy (see TWalkAttackCreature.Enemy) and current creature
Middle (see @link(TCastleTransform.Middle)) points. }
property AttackMaxDistance: Single
read FAttackMaxDistance write FAttackMaxDistance
{$ifdef FPC}default DefaultAttackMaxDistance{$endif};
{ The time point within AttackAnimation at which the short-range attack
happens. When exactly happens depends on the virtual
@link(TWalkAttackCreature.Attack) method implementation,
in the base TWalkAttackCreature it is a short-range
attack. }
property AttackTime: Single read FAttackTime write FAttackTime
{$ifdef FPC}default DefaultAttackTime{$endif};
{ Since most of the creatures will have their weapon
on their front (teeth, shooting hands, claws, whatever),
they can attack enemy only when they are facing the enemy.
More precisely, the attack is allowed to start only when
the angle between current creature @link(TCastleTransform.Direction Direction)
and the vector from creature's Middle to the enemy's Middle (see TCastleTransform.Middle)
is <= AttackMaxAngle.
This is in radians. }
property AttackMaxAngle: Single
read FAttackMaxAngle write FAttackMaxAngle
{$ifdef FPC}default DefaultAttackMaxAngle{$endif};
{ Sound played when short-range attack hits.
None (nil) by default. }
property AttackSoundHit: TCastleSound
read FAttackSoundHit write FAttackSoundHit;
{ Played at the start of attack animation,
that is when entering csAttack state.
To play a sound when the actual hit happens (at AttackTime)
see AttackSoundHit.
None (nil) by default. }
property AttackSoundStart: TCastleSound
read FAttackSoundStart write FAttackSoundStart;
{ The time (in seconds) since the FireMissileAnimation start when we actually
spawn a missile. By default zero, which means that we spawn the missile
right when FireMissileAnimation starts.
Must be < than the FireMissileAnimation duration, otherwise we will never
reach tthis time and missile will never be fired. }
property FireMissileTime: Single
read FFireMissileTime write FFireMissileTime
{$ifdef FPC}default DefaultFireMissileTime{$endif};
{ Minimum delay (in seconds) between firing of the missiles.
The missile will not be fired if a previous missile was fired within last
FireMissileMinDelay seconds.
(Even if all other conditions for firing the missile are satisfied.) }
property FireMissileMinDelay: Single
read FFireMissileMinDelay write FFireMissileMinDelay
{$ifdef FPC}default DefaultFireMissileMinDelay{$endif};
{ Maximum distance to the enemy to make firing missiles sensible.
The creature will only fire the missile if enemy is within this distance.
The creature will also try to shorten distance to the enemy,
to get within this distance. }
property FireMissileMaxDistance: Single
read FFireMissileMaxDistance write FFireMissileMaxDistance
{$ifdef FPC}default DefaultFireMissileMaxDistance{$endif};
{ Maximum angle (in radians) between current direction and
the direction toward enemy to make firing missiles sensible.
The creature will only fire the missile if enemy is within a cone of this angle. }
property FireMissileMaxAngle: Single
read FFireMissileMaxAngle write FFireMissileMaxAngle
{$ifdef FPC}default DefaultFireMissileMaxAngle{$endif};
{ Name of the creature to fire as missile, at AttackTime during AttackAnimation.
Leave empty to not fire any missile. }
property FireMissileName: string
read FFireMissileName write FFireMissileName;
{ Height (between Position and Middle, usually: legs and eyes)
of the fired missile (see FireMissileName). }
property FireMissileHeight: Single
read FFireMissileHeight write FFireMissileHeight
{$ifdef FPC}default DefaultFireMissileHeight{$endif};
{ Sound played when missile is fired, see FireMissileName.
None (nil) by default. }
property FireMissileSound: TCastleSound
read FFireMissileSound write FFireMissileSound;
{ Portion of life and distance when the creature decides it's best to run away
from the enemy. RunAwayLife is expressed as a fraction of MaxLife.
We run if our @code(Life <= MaxLife * RunAwayLife) and the distance
to the (last seen) enemy is < RunAwayDistance.
Set RunAwayLife = 1 to make the creature always try to keep a safe distance
from the enemy.
@groupBegin }
property RunAwayLife: Single
read FRunAwayLife write FRunAwayLife {$ifdef FPC}default DefaultRunAwayLife{$endif};
property RunAwayDistance: Single
read FRunAwayDistance write FRunAwayDistance
{$ifdef FPC}default DefaultRunAwayDistance{$endif};
{ @groupEnd }
{ Creature sees other things (like enemies) only within a cone
of this angle. This way, the creature only looks forward, and you can
sneak upon a creature from the back. Simply set this to >= 2 * Pi
to remove this limit.
Note that the creature also becomes aware of the enemy when it is
hurt by a direct attack, regardless of VisibilityAngle. This way
if you sneak and attack a creature from the back, it will turn around
and fight you.
Creature can also smell others, see SmellDistance. }
property VisibilityAngle: Single read FVisibilityAngle write FVisibilityAngle
{$ifdef FPC}default DefaultVisibilityAngle{$endif};
{ Creature smells other things (like enemies) within a sphere of this
radius. This allows to detect enemy regardless of which direction
the creature is facing, regardless of whether there is a line of sight
to the enemy, regardless if enemy is moving.
This is quite powerful ability to detect enemies,
if you set this to something large (by default it's zero).
Detecting enemies allows to more accurately/faster attack them
and/or run away from them.
Note: If you want the creature to nicely run from behind the corner,
be sure to setup good sectors/waypoints in your level.}
property SmellDistance: Single read FSmellDistance write FSmellDistance
{$ifdef FPC}default DefaultSmellDistance{$endif};
{ When creature is wounded for more than MaxLife * MinLifeLossToHurt
points and moreover Random < ChanceToHurt then creature will
change to csHurt state and be knocked back.
Changing to csHurt state means that any other state will be
interrupted (e.g. enemy can interrupt
creature's attack this way if AttackTime > 0).
It's expected that "tougher" creatures will have MinLifeLossToHurt
somewhat higher than DefaultMinLifeLossToHurt and ChanceToHurt
significantly lower than DefaultChanceToHurt. }
property MinLifeLossToHurt: Single
read FMinLifeLossToHurt write FMinLifeLossToHurt
{$ifdef FPC}default DefaultMinLifeLossToHurt{$endif};
{ See MinLifeLossToHurt. }
property ChanceToHurt: Single
read FChanceToHurt write FChanceToHurt
{$ifdef FPC}default DefaultChanceToHurt{$endif};
property MaxHeightAcceptableToFall: Single
read FMaxHeightAcceptableToFall
write FMaxHeightAcceptableToFall
{$ifdef FPC}default DefaultMaxHeightAcceptableToFall{$endif};
property RandomWalkDistance: Single
read FRandomWalkDistance
write FRandomWalkDistance
{$ifdef FPC}default DefaultRandomWalkDistance{$endif};
property RemoveDead: boolean
read FRemoveDead write FRemoveDead default DefaultRemoveDead;
end;
{ Creature that blindly moves in a given direction.
It just moves into the given direction
(with some possible twists, e.g. it can be a "homing"
missile and/or be dragged down by gravity).
On collision, it hits, potentially hurting the alive 3D object
that was colliding (player or other creatures).
Missiles ignore TCreatureResource.Flying, they use their own way to handle
gravity with DirectionFallSpeed. }
TMissileCreatureResource = class(TCreatureResource)
private
FFlyAnimation: T3DResourceAnimation;
FDieAnimation: T3DResourceAnimation;
FMoveSpeed: Single;
FSoundHit: TCastleSound;
FCloseDirectionToTargetSpeed: Single;
FPauseBetweenSoundIdle: Single;
FSoundIdle: TCastleSound;
FHitsPlayer: boolean;
FHitsCreatures: boolean;
FDirectionFallSpeed: Single;
FRemoveDead: boolean;
protected
function RadiusCalculate(const GravityUp: TVector3): Single; override;
public
const
DefaultMoveSpeed = 10.0;
DefaultCloseDirectionToTargetSpeed = 0.0;
DefaultPauseBetweenSoundIdle = 2.0;
DefaultHitsPlayer = true;
DefaultHitsCreatures = false;
DefaultDirectionFallSpeed = 0.0;
DefaultRemoveDead = true;
constructor Create(AOwner: TComponent); override;
function CreatureClass: TCreatureClass; override;
procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
function CreateCreature(
const ALevel: TAbstractLevel;
const APosition, ADirection: TVector3;
const MaxLife: Single): TCreature; override;
property FlyAnimation: T3DResourceAnimation read FFlyAnimation;
{ Die (destroying) animation of a missile. Optional.
It can depict missile explosion.
After showing this animation (or immediately when missile hits something,
if this animation is not specified) the missile is removed from the level
(unless RemoveDead = @false). }
property DieAnimation: T3DResourceAnimation read FDieAnimation;
{ The moving speed: how much Direction vector will be scaled
when moving. }
property MoveSpeed: Single read FMoveSpeed write FMoveSpeed
{$ifdef FPC}default DefaultMoveSpeed{$endif};
{ Sound when missile hits anything.
None (nil) by default. }
property SoundHit: TCastleSound
read FSoundHit write FSoundHit;
{ For "homing" missiles, how fast direction to the target is corrected.
Zero (default) means that the missile is not "homing". }
property CloseDirectionToTargetSpeed: Single
read FCloseDirectionToTargetSpeed
write FCloseDirectionToTargetSpeed
{$ifdef FPC}default DefaultCloseDirectionToTargetSpeed{$endif};
{ Sound played continuously when the missile is going.
None (nil) by default.
@seealso PauseBetweenSoundIdle }
property SoundIdle: TCastleSound
read FSoundIdle write FSoundIdle;
{ This should be synchonized with length of SoundIdle sound. }
property PauseBetweenSoundIdle: Single
read FPauseBetweenSoundIdle write FPauseBetweenSoundIdle
{$ifdef FPC}default DefaultPauseBetweenSoundIdle{$endif};
property HitsPlayer: boolean
read FHitsPlayer write FHitsPlayer default DefaultHitsPlayer;
property HitsCreatures: boolean
read FHitsCreatures write FHitsCreatures default DefaultHitsCreatures;
{ How fast is the missile pulled down by gravity.
Non-zero value causes missile direction to gradually point
downward, this way missile flies downward eventually.
This is quite different (in different units and with slightly different
effect) than TCastleTransform.FallSpeed, hence a different name and property.
TMissileCreatureResource doesn't use TCastleTransform.Gravity and so ignores
T3DResource.FallSpeed, T3DResource.GrowSpeed and other properties.
0 means to not fall down (missile is not affected by gravity). }
property DirectionFallSpeed: Single
read FDirectionFallSpeed write FDirectionFallSpeed
{$ifdef FPC}default DefaultDirectionFallSpeed{$endif};
{ Should the dead (destroyed) missiles be removed from level.
Useful if you want to see arrows stuck into walls where they hit.
This is like TWalkAttackCreatureResource.RemoveDead
and TStillCreatureResource.RemoveDead, except for missiles the default is @true.
Also, even if you switch this to @false,
it's ignored (works like @true) if the missile hit a dynamic
object (like another creature or player).
It only works when a missile hit something else than a creature/player,
which means that it probably hit a static level wall. }
property RemoveDead: boolean
read FRemoveDead write FRemoveDead default DefaultRemoveDead;
end;
{ Creature that just stays still.
This is just a single 3D animation showing a creature. }
TStillCreatureResource = class(TCreatureResource)
private
FIdleAnimation: T3DResourceAnimation;
FDieAnimation: T3DResourceAnimation;
FRemoveDead: boolean;
public
const
DefaultRemoveDead = false;
constructor Create(AOwner: TComponent); override;
function CreatureClass: TCreatureClass; override;
procedure LoadFromFile(ResourceConfig: TCastleConfig); override;
property IdleAnimation: T3DResourceAnimation read FIdleAnimation;
property DieAnimation: T3DResourceAnimation read FDieAnimation;
property RemoveDead: boolean
read FRemoveDead write FRemoveDead default DefaultRemoveDead;
end;
{ Base creature, using any TCreatureResource. }
TCreature = class(TCastleAlive)
private
FResource: TCreatureResource;
FResourceObserver: TFreeNotificationObserver;
FResourceFrame: TResourceFrame;
SoundSource: TCastleSoundSource;
FSoundDieEnabled: boolean;
FDebugCaptions: TCastleScene;
FDebugCaptionsTransform: TMatrixTransformNode;
FDebugCaptionsShape: TShapeNode;
FDebugCaptionsText: TTextNode;
FDebugCaptionsFontStyle: TFontStyleNode;
FDebugTransform: TDebugTransform;
{ Calculated @link(Radius) suitable for this creature.
This is cached result of @link(TCreatureResource.Radius). }
FRadius: Single;
procedure ResourceFreeNotification(const Sender: TFreeNotificationObserver);
protected
var
{ Set by CreateCreature. }
Level: TAbstractLevel;
procedure SetLife(const Value: Single); override;
procedure Fall(const FallHeight: Single); override;
{ LerpLegsMiddle interpolates between Position and Middle
(intuitively, legs and eye positions). }
function LerpLegsMiddle(const A: Single): TVector3;
{ Hurt given enemy. HurtEnemy may be @nil, in this case we do nothing. }
procedure AttackHurt(const HurtEnemy: TCastleAlive);
procedure UpdateDebugCaption(const Lines: TCastleStringList); virtual;
{ Sector where the middle of this 3D object is.
Used for AI. @nil if none (maybe because we're not part of any world,
maybe because sectors of the world were not initialized,
or maybe simply because we're outside of all sectors). }
function Sector(const OtherTransform: TCastleTransform): TSector; overload;
function Sector: TSector; overload;
public
class var
{ Render debug bounding boxes and captions at every creature. }
RenderDebug: boolean;
constructor Create(AOwner: TComponent; const AMaxLife: Single); reintroduce; virtual;
destructor Destroy; override;
function GetCollides: boolean; override;
property Resource: TCreatureResource read FResource;
procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override;
{ You can set this to @false to force the creature to die without
making any sound. This is really seldom needed, usefull only to avoid
a loud shriek noise when you kill many creatures at once.
Primarily for use by debug menu "kill all creatures" and similar things. }
property SoundDieEnabled: boolean read FSoundDieEnabled
write FSoundDieEnabled default true;
{ Play SoundType where the creature's position is.
Exactly, the position is between Position and Middle
--- SoundHeight = 0 means Position, SoundHeight = 1 means Middle,
SoundHeight between means ... well, between Position and Middle.
This can also be higher than 1 or lower than 0, should be treated like
lerp between Position and Middle.
If TiedToCreature then the sounds position will be updated
as the creature will move, and when the creature object will
be destroyed, sound will stop. If not TiedToCreature, then
the sound will simply be done at creature's position, but then
it will continue to be played independent of this creature. }
procedure Sound3d(const SoundType: TCastleSound; const SoundHeight: Single;
const TiedToCreature: boolean = true);
{ Can the approximate sphere be used for some collision-detection
tasks.
Set to @false in descendants if Resource.Radius
is not appropriate for this creature state.
In this class, this is implemented to return @code(not Dead).
This is usually sensible, since only alive creatures need bounding
sphere advantages (stairs climbing), and using sphere with dead
creatures would unnecessarily force the sphere radius to be small
and Middle to be high. }
function Sphere(out ARadius: Single): boolean; override;
{ Sphere radius for collision detection for alive creatures.
Must be something <> 0 for collision detection to work.
@seealso TCreatureResource.Radius }
function Radius: Single;
property CollidesWithMoving default true;
end;
TCreatureList = class({$ifdef FPC}specialize{$endif} TObjectList<TCreature>)
end;
{ Creature using TWalkAttackCreatureResource. }
TWalkAttackCreature = class(TCreature)
private
FState: TCreatureState;
FStateChangeTime: Single;
{ Time of last State change to csAttack or csFireMissile,
taken from LifeTime. }
LastAttackTime, LastFireMissileTime: Single;
{ Whether Attack or FireMissile was already called within this
csAttack or csFireMissile state. }
AttackDone, FireMissileDone: boolean;
HasAlternativeTarget: boolean;
AlternativeTarget: TVector3;
{ Time of last setting HasAlternativeTarget to true and AlternativeTarget
value, taken from LifeTime. Used to not fall into loop
when the creature tries to walk to AlternativeTarget, and is not
permanently blocked (so MoveCollision returns true all the time)
but at the same time the creature can't get close enough to the
AlternativeTarget. In such case we use this variable to resign from
AlternativeTarget after some time. }
AlternativeTargetTime: Single;
WaypointsSaved_Begin: TSector;
WaypointsSaved_End: TSector;
WaypointsSaved: TWaypointList;
InternalMiddleForceBoxTime: Single;
FDebugAlternativeTargetAxis: TDebugAxis;
FDebugLastSensedEnemyAxis: TDebugAxis;
protected
{ Last known information about enemy. }
HasLastSensedEnemy: boolean;
LastSensedEnemy: TVector3;