Debian Codegraph @

examples/deprecated_to_upgrade/fps_game_old_ai/code/gameinitialize.pas

raw
1 {
2 Copyright 2012-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 { Example of a fully-working 3D FPS game.
17 This is the main game unit, which contains most of the code.
18 This is a cross-platform game code that will work on any platform
19 (desktop or mobile). }
20 unit GameInitialize;
21
22 { Use GameViewMain with UI and level designed in CGE editor.
23 Not functional yet, but this is the future we go for. }
24 {.$define UPCOMING_FPS_GAME_REDESIGN}
25
26 interface
27
28 implementation
29
30 uses SysUtils, Classes,
31 CastleWindow, CastleApplicationProperties
32 {$ifdef UPCOMING_FPS_GAME_REDESIGN}
33 {$region 'Castle Initialization Uses'}
34 // The content here may be automatically updated by CGE editor.
35 , GameViewMain
36 {$endregion 'Castle Initialization Uses'}
37 {$else}
38 , CastleLog, CastleConfig, CastleLevels,
39 CastlePlayer, CastleSoundEngine,
40 CastleResources, CastleControls, CastleKeysMouse, CastleStringUtils,
41 CastleTransform, CastleFilesUtils, CastleGameNotifications,
42 CastleVectors, CastleUIControls, CastleGLUtils, CastleViewport,
43 CastleColors, CastleItems, CastleUtils, CastleCameras,
44 CastleCreatures, CastleRectangles, CastleImages,
45 CastleLoadGltf, CastleSceneCore, CastleScene
46 {$endif};
47
48 var
49 Window: TCastleWindow;
50
51 {$ifdef UPCOMING_FPS_GAME_REDESIGN}
52
53 { Initialize the game.
54 This is assigned to Application.OnInitialize, and will be called only once. }
55 procedure ApplicationInitialize;
56 begin
57 { Adjust container settings for a scalable UI (adjusts to any window size in a smart way). }
58 Window.Container.LoadSettings('castle-data:/CastleSettings.xml');
59
60 { Create views (see https://castle-engine.io/views ). }
61 {$region 'Castle View Creation'}
62 // The content here may be automatically updated by CGE editor.
63 ViewMain := TViewMain.Create(Application);
64 {$endregion 'Castle View Creation'}
65
66 Window.Container.View := ViewMain;
67 end;
68
69 {$else UPCOMING_FPS_GAME_REDESIGN}
70
71 var
72 Level: TLevel;
73 Player: TPlayer;
74 Viewport: TCastleViewport;
75 ExtraViewport: TCastleViewport;
76 CreaturesSpawned: Integer;
77
78 { Buttons -------------------------------------------------------------------- }
79
80 type
81 { Container for buttons and their callbacks.
82 You could as well derive descendant of TCastleWindow to keep your
83 callbacks, or place these callbacks as methods of Lazarus form. }
84 TButtons = class(TComponent)
85 ToggleMouseLookButton: TCastleButton;
86 ExitButton: TCastleButton;
87 RenderDebugCreaturesButton: TCastleButton;
88 RenderDebugItemsButton: TCastleButton;
89 ScrenshotButton: TCastleButton;
90 AddCreatureButton: TCastleButton;
91 AddItemButton: TCastleButton;
92 AttackButton: TCastleButton;
93 constructor Create(AOwner: TComponent); override;
94 procedure ToggleMouseLookButtonClick(Sender: TObject);
95 procedure ExitButtonClick(Sender: TObject);
96 procedure RenderDebugCreaturesButtonClick(Sender: TObject);
97 procedure RenderDebugItemsButtonClick(Sender: TObject);
98 procedure ScreenshotButtonClick(Sender: TObject);
99 procedure AddCreatureButtonClick(Sender: TObject);
100 procedure AddItemButtonClick(Sender: TObject);
101 procedure AttackButtonClick(Sender: TObject);
102 end;
103
104 const
105 ControlsMargin = 8;
106
107 constructor TButtons.Create(AOwner: TComponent);
108 var
109 NextButtonBottom: Single;
110 begin
111 inherited;
112
113 { We use TCastleButton from CastleControls unit for buttons drawn using CGE.
114 If you would use Lazarus and TCastleControl (instead of TCastleWindow)
115 you can also consider using Lazarus standard buttons and other components
116 on your form.
117
118 The advantage of our TCastleButton is that it is drawn completely by our
119 engine, which means that you can style the TCastleButton to match the theme
120 of your game (like medieval fantasy of futuristic sci-fi). }
121
122 NextButtonBottom := ControlsMargin;
123
124 if not ApplicationProperties.TouchDevice then
125 begin
126 { Do not show this on touch device, as mouse look navigation
127 cannot work with a touch device.
128 See also https://castle-engine.io/manual_cross_platform.php }
129 ToggleMouseLookButton := TCastleButton.Create(Application);
130 ToggleMouseLookButton.Caption := 'Mouse Look (F4)';
131 ToggleMouseLookButton.Toggle := true;
132 ToggleMouseLookButton.OnClick := {$ifdef FPC}@{$endif}ToggleMouseLookButtonClick;
133 ToggleMouseLookButton.Left := ControlsMargin;
134 ToggleMouseLookButton.Bottom := NextButtonBottom;
135 Window.Controls.InsertFront(ToggleMouseLookButton);
136 NextButtonBottom := NextButtonBottom + (ToggleMouseLookButton.EffectiveHeight + ControlsMargin);
137 end;
138
139 if ApplicationProperties.ShowUserInterfaceToQuit then
140 begin
141 { Do not show this on mobile devices / consoles, as
142 - Application.Terminate (or Window.Close, or anything similar)
143 doesn't make sense on these devices,
144 - and users are not accustomed to pressing "Quit" on these devices,
145 they just switch to home/other application.
146 See also https://castle-engine.io/manual_cross_platform.php }
147 ExitButton := TCastleButton.Create(Application);
148 ExitButton.Caption := 'Exit (Escape)';
149 ExitButton.OnClick := {$ifdef FPC}@{$endif}ExitButtonClick;
150 ExitButton.Left := ControlsMargin;
151 ExitButton.Bottom := NextButtonBottom;
152 Window.Controls.InsertFront(ExitButton);
153 NextButtonBottom := NextButtonBottom + (ExitButton.EffectiveHeight + ControlsMargin);
154 end;
155
156 RenderDebugCreaturesButton := TCastleButton.Create(Application);
157 RenderDebugCreaturesButton.Caption := 'Creatures Debug Visualization';
158 RenderDebugCreaturesButton.Toggle := true;
159 RenderDebugCreaturesButton.OnClick := {$ifdef FPC}@{$endif}RenderDebugCreaturesButtonClick;
160 RenderDebugCreaturesButton.Left := ControlsMargin;
161 RenderDebugCreaturesButton.Bottom := NextButtonBottom;
162 Window.Controls.InsertFront(RenderDebugCreaturesButton);
163 NextButtonBottom := NextButtonBottom + (RenderDebugCreaturesButton.EffectiveHeight + ControlsMargin);
164
165 RenderDebugItemsButton := TCastleButton.Create(Application);
166 RenderDebugItemsButton.Caption := 'Items Debug Visualization';
167 RenderDebugItemsButton.Toggle := true;
168 RenderDebugItemsButton.OnClick := {$ifdef FPC}@{$endif}RenderDebugItemsButtonClick;
169 RenderDebugItemsButton.Left := ControlsMargin;
170 RenderDebugItemsButton.Bottom := NextButtonBottom;
171 Window.Controls.InsertFront(RenderDebugItemsButton);
172 NextButtonBottom := NextButtonBottom + (RenderDebugItemsButton.EffectiveHeight + ControlsMargin);
173
174 ScrenshotButton := TCastleButton.Create(Application);
175 ScrenshotButton.Caption := 'Screenshot (F5)';
176 ScrenshotButton.OnClick := {$ifdef FPC}@{$endif}ScreenshotButtonClick;
177 ScrenshotButton.Left := ControlsMargin;
178 ScrenshotButton.Bottom := NextButtonBottom;
179 Window.Controls.InsertFront(ScrenshotButton);
180 NextButtonBottom := NextButtonBottom + (ScrenshotButton.EffectiveHeight + ControlsMargin);
181
182 AddCreatureButton := TCastleButton.Create(Application);
183 AddCreatureButton.Caption := 'Add creature (F9)';
184 AddCreatureButton.OnClick := {$ifdef FPC}@{$endif}AddCreatureButtonClick;
185 AddCreatureButton.Left := ControlsMargin;
186 AddCreatureButton.Bottom := NextButtonBottom;
187 Window.Controls.InsertFront(AddCreatureButton);
188 NextButtonBottom := NextButtonBottom + (AddCreatureButton.EffectiveHeight + ControlsMargin);
189
190 AddItemButton := TCastleButton.Create(Application);
191 AddItemButton.Caption := 'Add item (F10)';
192 AddItemButton.OnClick := {$ifdef FPC}@{$endif}AddItemButtonClick;
193 AddItemButton.Left := ControlsMargin;
194 AddItemButton.Bottom := NextButtonBottom;
195 Window.Controls.InsertFront(AddItemButton);
196 NextButtonBottom := NextButtonBottom + (AddItemButton.EffectiveHeight + ControlsMargin);
197
198 AttackButton := TCastleButton.Create(Application);
199 AttackButton.Caption := 'Attack (Ctrl)';
200 AttackButton.OnClick := {$ifdef FPC}@{$endif}AttackButtonClick;
201 AttackButton.Left := ControlsMargin;
202 AttackButton.Bottom := NextButtonBottom;
203 Window.Controls.InsertFront(AttackButton);
204 NextButtonBottom := NextButtonBottom + (AttackButton.EffectiveHeight + ControlsMargin);
205 end;
206
207 procedure TButtons.ToggleMouseLookButtonClick(Sender: TObject);
208 begin
209 ToggleMouseLookButton.Pressed := not ToggleMouseLookButton.Pressed;
210 Player.Navigation.MouseLook := ToggleMouseLookButton.Pressed;
211 end;
212
213 procedure TButtons.ExitButtonClick(Sender: TObject);
214 begin
215 Application.Terminate;
216 end;
217
218 procedure TButtons.RenderDebugCreaturesButtonClick(Sender: TObject);
219 begin
220 RenderDebugCreaturesButton.Pressed := not RenderDebugCreaturesButton.Pressed;
221 TCreature.RenderDebug := RenderDebugCreaturesButton.Pressed;
222 end;
223
224 procedure TButtons.RenderDebugItemsButtonClick(Sender: TObject);
225 begin
226 RenderDebugItemsButton.Pressed := not RenderDebugItemsButton.Pressed;
227 TItemOnWorld.RenderDebug := RenderDebugItemsButton.Pressed;
228 end;
229
230 procedure TButtons.ScreenshotButtonClick(Sender: TObject);
231 var
232 Url: String;
233 begin
234 { Capture a screenshot straight to a file.
235 There are more interesting things that you can do with a screenshot
236 (overloaded SaveScreen returns you a TRGBImage and we have
237 a whole image library in CastleImages unit to process such image).
238 You could also ask use to choose a file (e.g. by Window.FileDialog).
239 But this is just a simple example, and this way we also have
240 an opportunity to show how to use Notifications. }
241 Url := Window.Container.SaveScreenToDefaultFile;
242 if Url <> '' then
243 Notifications.Show('Saved screen to ' + Url);
244 // when Url = '' it means that recommended directory to store screenshots on this platform cannot be found
245 end;
246
247 procedure TButtons.AddCreatureButtonClick(Sender: TObject);
248 var
249 Translation: TVector3;
250 Direction: TVector3;
251 CreatureResource: TCreatureResource;
252 begin
253 Translation := Player.Translation + Player.Direction * 10;
254 { increase default height, as dropping from above looks better }
255 Translation.Y := Translation.Y + 5;
256 Direction := Player.Direction; { by default creature is facing back to player }
257 CreatureResource := Resources.FindName('Knight') as TCreatureResource;
258 { CreateCreature creates TCreature instance and adds it to Viewport.Items }
259 CreatureResource.CreateCreature(Level, Translation, Direction);
260
261 // update and show CreaturesSpawned
262 Inc(CreaturesSpawned);
263 AddCreatureButton.Caption := Format('Add creature (F9) (Spawned: %d)',
264 [CreaturesSpawned]);
265 end;
266
267 procedure TButtons.AddItemButtonClick(Sender: TObject);
268 var
269 Translation: TVector3;
270 ItemResource: TItemResource;
271 begin
272 Translation := Player.Translation + Player.Direction * 10;
273 { increase default height, as dropping from above looks better }
274 Translation.Y := Translation.Y + 5;
275 ItemResource := Resources.FindName('MedKit') as TItemResource;
276 { ItemResource.CreateItem(<quantity>) creates new TInventoryItem instance.
277 PutOnWorld method creates TItemOnWorld (that "wraps" the TInventoryItem
278 instance) and adds it to Viewport.Items. }
279 ItemResource.CreateItem(1).PutOnWorld(Level, Translation);
280
281 { You could instead add the item directly to someone's inventory, like this: }
282 // Player.PickItem(ItemResource.CreateItem(1));
283 end;
284
285 procedure TButtons.AttackButtonClick(Sender: TObject);
286 begin
287 Player.Attack;
288 end;
289
290 var
291 Buttons: TButtons;
292
293 { Player HUD ---------------------------------------------------------------- }
294
295 type
296 TPlayerHUD = class(TCastleUserInterface)
297 public
298 procedure Render; override;
299 end;
300
301 procedure TPlayerHUD.Render;
302
303 procedure DisplayCurrentAmmo;
304 var
305 AmmoStr: String;
306 GunResource: TItemWeaponResource;
307 GunIndex: Integer;
308 Gun: TItemWeapon;
309 begin
310 GunResource := Resources.FindName('Gun') as TItemWeaponResource;
311 GunIndex := Player.Inventory.FindResource(GunResource);
312 if GunIndex <> -1 then // owns gun?
313 begin
314 Gun := Player.Inventory[GunIndex] as TItemWeapon;
315 AmmoStr := Format('Loaded Ammo: %d / %d', [
316 Gun.AmmoLoaded,
317 GunResource.AttackAmmoCapacity
318 ]);
319 FallbackFont.Print(10, ContainerHeight - 220, Green, AmmoStr);
320 end;
321 end;
322
323 const
324 InventoryImageSize = 128;
325 var
326 I: Integer;
327 X, Y: Single;
328 S: String;
329 begin
330 inherited;
331
332 Y := ContainerHeight;
333
334 { A simple display of current/maximum player life. }
335 { Write text in the upper-left corner of the screen.
336 The (0, 0) position is always bottom-left corner,
337 (ContainerWidth, ContainerHeight) position is top-right corner.
338 You can take font measurements by FallbackFont.Height or FallbackFont.TextWidth
339 to adjust initial position as needed. }
340 Y := Y - (FallbackFont.Height + ControlsMargin);
341 FallbackFont.Print(ControlsMargin, Y, Yellow,
342 FormatDot('Player life: %f / %f', [Player.Life, Player.MaxLife]));
343
344 DisplayCurrentAmmo;
345
346 { show FPS }
347 FallbackFont.PrintRect(Window.Rect.Grow(-ControlsMargin), Red,
348 'FPS: ' + Window.Fps.ToString, hpRight, vpTop);
349
350 Y := Y - (FallbackFont.Height + InventoryImageSize);
351
352 { Mark currently chosen item. You can change currently selected item by
353 Input_InventoryPrevious, Input_InventoryNext (by default: [ ] keys or mouse
354 wheel). }
355 if Between(Player.InventoryCurrentItem, 0, Player.Inventory.Count - 1) then
356 begin
357 X := ControlsMargin + Player.InventoryCurrentItem * (InventoryImageSize + ControlsMargin);
358 { This allows to draw a standard tiActiveFrame image.
359 You could change the image by assigning Theme.ImagesPersistent[tiActiveFrame]
360 (see https://castle-engine.io/manual_2d_user_interface.php#section_theme )
361 or by creating and using TDrawableImage.Draw3x3 or TDrawableImage.Draw directly. }
362 Theme.Draw(FloatRectangle(X, Y, InventoryImageSize, InventoryImageSize), tiActiveFrame);
363 end;
364
365 { A simple way to draw player inventory.
366 The image representing each item (exactly for purposes like inventory
367 display) is specified in the resource.xml file of each item,
368 as image="xxx" attribute of the root <resource> element.
369 Based on this, the engine initializes TItemResource.Image and TItemResource.DrawableImage,
370 that you can easily use for any purpose.
371 We assume below that all item images have square size
372 InventoryImageSize x InventoryImageSize,
373 and we assume that all items will always fit within one row. }
374 for I := 0 to Player.Inventory.Count - 1 do
375 begin
376 X := ControlsMargin + I * (InventoryImageSize + ControlsMargin);
377 Player.Inventory[I].Resource.DrawableImage.Draw(FloatRectangle(X, Y, InventoryImageSize, InventoryImageSize));
378 S := Player.Inventory[I].Resource.Caption;
379 if Player.Inventory[I].Quantity <> 1 then
380 S := S + Format(' (%d)', [Player.Inventory[I].Quantity]);
381 FallbackFont.Print(X, Y - FallbackFont.Height, Yellow, S);
382 end;
383
384 { Simple color effects over the screen:
385 when player is dead,
386 when player is underwater,
387 when player has fadeout from any other cause (e.g. player is hurt).
388
389 DrawRectangle and GLFaceRectangle make simple color effects by blending.
390 They are trivial to use (by all means, do experiment with parameters below,
391 see DrawRectangle and GLFaceRectangle documentation and also OpenGL
392 glBlendFunc parameters), and they will work even on ancient GPUs.
393
394 To create more fancy effects, you can use our GLSL screen effects API.
395 See https://castle-engine.io/x3d_extensions_screen_effects.php .
396 They can be even set up completely in VRML/X3D file (no need for ObjectPascal
397 code). CGE examples/screen_effects_demo/ shows how to set them up in code. }
398 if Player.Swimming = psUnderWater then
399 DrawRectangle(ParentRect, Vector4(0, 0, 0.1, 0.5));
400 if Player.Dead then
401 GLFadeRectangleDark(ParentRect, Red, 1.0)
402 else
403 GLFadeRectangleDark(ParentRect, Player.FadeOutColor, Player.FadeOutIntensity);
404 end;
405
406 var
407 PlayerHUD: TPlayerHUD;
408
409 { Create player. Player implements:
410 - inventory,
411 - automatic picking of items by default,
412 - health (can be hurt by enemies),
413 - equipping weapon (a special item can be equipped and used to hurt enemies),
414 - footsteps
415 - and some other nice stuff.
416 - Player.Navigation is also automatically configured as Viewport.Navigation
417 and it follows level's properties like PreferredHeight (from level's
418 NavigationInfo.avatarSize). }
419 procedure CreatePlayer;
420
421 procedure SetupThirdPersonNavigation;
422 var
423 Avatar: TCastleScene;
424 begin
425 Player.UseThirdPerson := true;
426
427 // RenderOnTop makes sense only for 1st-person camera
428 Player.RenderOnTop := false;
429
430 // TPlayer already created Avatar instance for us, just use it
431 Avatar := Player.ThirdPersonNavigation.Avatar;
432 Avatar.Load('castle-data:/avatar/avatar.gltf');
433
434 { Make Player collide using a sphere.
435 Sphere is more useful than default bounding box for avatars and creatures
436 that move in the world, look ahead, can climb stairs etc. }
437 Player.MiddleHeight := 0.9;
438 Player.CollisionSphereRadius := 0.5;
439
440 { Gravity means that object tries to maintain a constant height
441 (Player.PreferredHeight) above the ground.
442 GrowSpeed means that object raises properly (makes walking up the stairs work).
443 FallSpeed means that object falls properly (makes walking down the stairs,
444 falling down pit etc. work). }
445 Player.Gravity := true;
446 Player.GrowSpeed := 10.0;
447 Player.FallSpeed := 10.0;
448
449 Player.ThirdPersonNavigation.Input_CameraCloser.Assign(keyNone, keyNone, '', false, buttonLeft, mwUp);
450 Player.ThirdPersonNavigation.Input_CameraFurther.Assign(keyNone, keyNone, '', false, buttonLeft, mwDown);
451 Player.ThirdPersonNavigation.CrouchSpeed := 2;
452 Player.ThirdPersonNavigation.MoveSpeed := 4;
453 Player.ThirdPersonNavigation.RunSpeed := 8;
454 end;
455
456 begin
457 FreeAndNil(Player);
458
459 Player := TPlayer.Create(Application);
460
461 { Use this to enable 3rd-person camera }
462 //SetupThirdPersonNavigation;
463
464 Level.Player := Player;
465
466 if Buttons <> nil then
467 Buttons.ToggleMouseLookButton.Pressed := false;
468 end;
469
470 { Window callbacks ----------------------------------------------------------- }
471
472 procedure Press(Container: TCastleContainer; const Event: TInputPressRelease);
473 begin
474 { We simulate button presses on some key presses. There is no automatic
475 mechanism to assign key shortcut to a TCastleButton right now.
476 Note that we pass Sender = nil to the callbacks, because we know that
477 our TButtons callbacks ignore Sender parameter. }
478 if Event.IsKey(keyF4) and
479 // in case we test touch input in desktop, ToggleMouseLookButton = nil
480 (Buttons.ToggleMouseLookButton <> nil) then
481 Buttons.ToggleMouseLookButtonClick(nil) else
482 if Event.IsKey(CharEscape) then
483 Buttons.ExitButtonClick(nil) else
484 if Event.IsKey(keyF5) then
485 Buttons.ScreenshotButtonClick(nil) else
486 if Event.IsKey(keyF9) then
487 Buttons.AddCreatureButtonClick(nil) else
488 if Event.IsKey(keyF10) then
489 Buttons.AddItemButtonClick(nil);
490 if Event.IsKey(keyF1) then
491 CreatePlayer;
492 end;
493
494 { Customized item ------------------------------------------------------------ }
495
496 type
497 { An example how to create new item behavior.
498
499 We override both the resource class (shared information for a given kind
500 of item; instances of it will be automatically
501 created and placed on the global Resources list, based on resource.xml files
502 referring to this class by type="xxx") and non-resource class
503 (information about a particular occurrence of this item).
504 See engine tutorial for more extensive explanation.
505 Creating new creatures looks the same.
506
507 In this simplest case, the only purpose of the TMedKitResource class is to
508 indicate the non-resource class TMedKit.
509
510 For actual item TMedKit we override the Use method
511 to increase health on use (press Enter to use item in inventory).
512
513 We also override the Stack property to avoid stacking items.
514 We do this here just to see that TPlayerHUD works for many items.
515 (Otherwise, all instances of MedKit would be "stacked" together,
516 which means you will have a single item on Player.Inventory,
517 but with Quantity possibly > 1. For real games, stacking is usually a good
518 idea.) }
519 TMedKitResource = class(TItemResource)
520 protected
521 function ItemClass: TInventoryItemClass; override;
522 end;
523
524 TMedKit = class(TInventoryItem)
525 protected
526 procedure Stack(var Item: TInventoryItem); override;
527 procedure Use; override;
528 // procedure Picked(const NewOwner: TAliveWithInventory); override;
529 end;
530
531 function TMedKitResource.ItemClass: TInventoryItemClass;
532 begin
533 Result := TMedKit;
534 end;
535
536 procedure TMedKit.Stack(var Item: TInventoryItem);
537 begin
538 { Simply do nothing to prevent stacking medkit items. }
539 end;
540
541 procedure TMedKit.Use;
542 begin
543 { Increase the life of item's owner.
544
545 We could of course do something more intelligent here, e.g. do not allow
546 increasing Life above MaxLife (by default, there is *no* such limit,
547 you can increase Life above MaxLife, because many games allow
548 increasing Life by some magical powerups above normal "maximum" value).
549
550 You could also allow partially using an item, by keeping a property
551 like Used inside TMedKit class. You would decrease this TMedKit.Used
552 property instead of Quantity (and only decrease Quantity when TMedKit.Used
553 reaches 0, which means that item was used up completely). }
554 Player.Life := Player.Life + 20;
555 Quantity := Quantity - 1;
556 Notifications.Show(Format('You use "%s"', [Resource.Caption]));
557 { A simplest demo how to play sound defined in sounds/index.xml }
558 SoundEngine.Play(SoundEngine.SoundFromName('medkit_use'));
559 end;
560
561 { If you want to do something immediately at pickup, you can override
562 Picked method. By default, it causes item to be added to inventory,
563 but you could as well e.g. immediately increase player life and destroy item.
564 Uncomment this method (and it's declaration in TMedKit class) to test it. }
565 // procedure TMedKit.Picked(const NewOwner: TAliveWithInventory);
566 // begin
567 // Use;
568 // Free;
569 // end;
570
571 { initialization ------------------------------------------------------------- }
572
573 { Initialize the game.
574 This is assigned to Application.OnInitialize, and will be called only once. }
575 procedure ApplicationInitialize;
576 var
577 TouchNavigation: TCastleTouchNavigation;
578 begin
579 { Adjust container settings for a scalable UI (adjusts to any window size in a smart way). }
580 Window.Container.LoadSettings('castle-data:/CastleSettings.xml');
581
582 { Turn on some engine optimizations not enabled by default.
583 TODO: In the future they should be default, and these variables should be ignored.
584 See their docs for description why they aren't default yet. }
585 OptimizeExtensiveTransformations := true;
586 InternalFastTransformUpdate := true;
587
588 { force using Phong lighting model instead of PBR (physically-based rendering) model.
589 Faster, less realistic. }
590 GltfForcePhongMaterials := true;
591
592 { Load user preferences file.
593 You can use it for your own user persistent data
594 (preferences or savegames), see
595 https://castle-engine.io/manual_user_prefs.php . }
596 //UserConfig.Load;
597
598 Viewport := TCastleViewport.Create(Application);
599 Viewport.FullSize := true;
600 Window.Controls.InsertFront(Viewport);
601
602 Level := TLevel.Create(Application);
603 Level.Viewport := Viewport;
604
605 { Load named sounds defined in sounds/index.xml }
606 SoundEngine.RepositoryUrl := 'castle-data:/sounds/index.xml';
607
608 { Change Theme image tiActiveFrame, used to draw rectangle under image }
609 Theme.ImagesPersistent[tiActiveFrame].Url := 'castle-data:/box.png';
610 Theme.ImagesPersistent[tiActiveFrame].ProtectedSides.AllSides := 38;
611
612 { Create extra viewport to observe the world.
613 You can always add additional viewports.
614 Each viewport has it's own camera and navigation.
615 See CGE examples/viewport_and_scenes/multiple_viewports ,
616 examples/user_interface/zombie_fighter/ for more examples of custom viewports. }
617 ExtraViewport := TCastleViewport.Create(Application);
618 ExtraViewport.Items.Remove(ExtraViewport.Camera);
619 ExtraViewport.Items := Viewport.Items; // share the same world as Viewport
620 ExtraViewport.Items.Add(ExtraViewport.Camera);
621 ExtraViewport.FullSize := false;
622 ExtraViewport.Width := 150;
623 ExtraViewport.Height := 400;
624 ExtraViewport.Anchor(vpMiddle);
625 ExtraViewport.Anchor(hpRight, -ControlsMargin);
626 Window.Controls.InsertFront(ExtraViewport);
627
628 { Initialize ExtraViewport.Camera to nicely see the level from above. }
629 ExtraViewport.Camera.SetView(
630 { position } Vector3(0, 55, -44),
631 { direction } Vector3(0, -1, 0),
632 { up } Vector3(0, 0, 1), false
633 );
634 { Allow user to actually edit this view, e.g. by mouse scroll. }
635 ExtraViewport.Navigation := TCastleExamineNavigation.Create(Application);
636
637 { Assign callbacks to some window events.
638 Note about initial events: Window.Open calls OnOpen and first OnResize events,
639 so if you want to receive them --- be sure to register them before calling
640 Window.Open. That is why we assign them here, and that is why we created
641 ExtraViewport (that is resized in Resize callback) earlier. }
642 Window.OnPress := @Press;
643
644 { Enable automatic navigation UI on touch devices. }
645 //ApplicationProperties.TouchDevice := true; // use this to test touch behavior on desktop
646 if ApplicationProperties.TouchDevice then
647 begin
648 TouchNavigation := TCastleTouchNavigation.Create(Application);
649 TouchNavigation.AutoTouchInterface := true;
650 TouchNavigation.Viewport := Viewport;
651 TouchNavigation.FullSize := true;
652 Viewport.InsertFront(TouchNavigation);
653 end;
654
655 { Allow player to drop items by "R" key. This shortcut is by default inactive
656 (no key/mouse button correspond to it), because not all games may want
657 to allow player to do this. }
658 PlayerInput_DropItem.Assign(keyR);
659 if not ApplicationProperties.TouchDevice then
660 // allow shooting by clicking or pressing Ctrl key
661 PlayerInput_Attack.Assign(keyCtrl, keyNone, '', true, buttonLeft);
662
663 { Allow using type="MedKit" inside resource.xml files,
664 to define our MedKit item. }
665 RegisterResourceClass(TMedKitResource, 'MedKit');
666
667 { Load resources (creatures and items) from resource.xml files. }
668 Resources.LoadFromFiles;
669
670 { Load available levels information from level.xml files. }
671 //Levels.LoadFromFiles; // on non-Android, this finds all level.xml files in data
672 Levels.AddFromFile('castle-data:/example_level/level.xml');
673
674 { Create player. Player implements:
675 - inventory,
676 - automatic picking of items by default,
677 - health (can be hurt by enemies),
678 - equipping weapon (a special item can be equipped and used to hurt enemies),
679 - footsteps
680 - and some other nice stuff.
681 - Player.Navigation is also automatically configured as Viewport.Navigation
682 and it follows level's properties like PreferredHeight (from level's
683 NavigationInfo.avatarSize). }
684 CreatePlayer;
685
686 { Load initial level.
687 This loads and adds 3D model of your level to the 3D world
688 (that is to Viewport.Items). It may also load initial creatures/items
689 on levels, waypoints/sectors and other information from so-called
690 "placeholders" on the level, see TLevel.Load documentation. }
691 Level.Load('example_level');
692
693 { Add some buttons }
694 Buttons := TButtons.Create(Application);
695
696 { Add the Notifications to our window.
697 We add a global Notifications object from CastleGameNotifications.
698 Of course this is completely optional, you could instead create your own
699 TCastleNotifications instance (to not see the default notifications
700 made by some engine units) or just don't use notifications at all. }
701 Notifications.TextAlignment := hpMiddle;
702 Notifications.Anchor(hpMiddle);
703 Notifications.Anchor(vpBottom, 5);
704 Notifications.Color := Yellow;
705 Window.Controls.InsertFront(Notifications);
706
707 { Create and add PlayerHUD to visualize player life, inventory and pain. }
708 PlayerHUD := TPlayerHUD.Create(Application);
709 Window.Controls.InsertFront(PlayerHUD);
710
711 { Insert default crosshair.
712 You can always draw your custom crosshair instead (using TDrawableImage.Draw
713 inside TPlayerHUD, or using TCastleImageControl). }
714 Window.Controls.InsertFront(TCastleCrosshair.Create(Application));
715 end;
716
717 {$endif UPCOMING_FPS_GAME_REDESIGN}
718
719 initialization
720 { This initialization section configures:
721 - Application.OnInitialize
722 - Application.MainWindow
723 - determines initial window size
724
725 You should not need to do anything more in this initialization section.
726 Most of your actual application initialization (in particular, any file reading)
727 should happen inside ApplicationInitialize. }
728
729 Application.OnInitialize := @ApplicationInitialize;
730
731 Window := TCastleWindow.Create(Application);
732 Application.MainWindow := Window;
733
734 { Optionally, adjust window fullscreen state and size at this point.
735 Examples:
736
737 Run fullscreen:
738
739 Window.FullScreen := true;
740
741 Run in a 600x400 window:
742
743 Window.FullScreen := false; // default
744 Window.Width := 600;
745 Window.Height := 400;
746
747 Run in a window taking 2/3 of screen (width and height):
748
749 Window.FullScreen := false; // default
750 Window.Width := Application.ScreenWidth * 2 div 3;
751 Window.Height := Application.ScreenHeight * 2 div 3;
752
753 Note that some platforms (like mobile) ignore these window sizes.
754 }
755
756 { Handle command-line parameters like --fullscreen and --window.
757 By doing this last, you let user to override your fullscreen / mode setup. }
758 Window.ParseParameters;
759 finalization
760 { In a desktop game, it's OK to store the preferences
761 in the finalization section, when the program stops.
762 In mobile games, you should store the preferences more often,
763 to make sure they are saved even when the program is killed by the OS
764 -- so the lines below should be called always after
765 user changed the preferences. }
766
767 { Save the configuration file. This is commented out here,
768 as this example program does not give user any UI to actually change
769 any configuration.
770 Saving prefe }
771 //SoundEngine.SaveToConfig(UserConfig);
772 //UserConfig.Save;
773 end.