-
Notifications
You must be signed in to change notification settings - Fork 2
/
GameWindow.pas
2516 lines (2156 loc) · 81.3 KB
/
GameWindow.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
{$include lem_directives.inc}
unit GameWindow;
interface
uses
System.Types, Generics.Collections,
PngInterface,
LemmixHotkeys,
Windows, Classes, Controls, Graphics, MMSystem, Forms, SysUtils, Dialogs, Math, ExtCtrls, StrUtils,
GR32, GR32_Image, GR32_Layers, GR32_Resamplers,
LemCore, LemLevel, LemRendering, LemRenderHelpers,
LemGame, LemGameMessageQueue,
GameSound, LemTypes, LemStrings, LemLemming,
LemCursor,
GameControl, GameBaseSkillPanel, GameSkillPanel, GameBaseScreenCommon,
GameWindowInterface,
SharedGlobals;
type
// For TGameSpeed see unit GameWindowInterface
TGameScroll = (
gsNone,
gsRight,
gsLeft,
gsUp,
gsDown
);
TRedrawOption = (
rdNone, // No forced redraw is needed
rdRefresh, // Needs to update (eg. from scrolling) but not fully redrawn
rdRedraw // Needs to redraw completely
);
THoldScrollData = record
Active: Boolean;
StartCursor: TPoint;
//StartImg: TFloatPoint;
end;
TSuspendState = record
OldSpeed: TGameSpeed;
OldCanPlay: Boolean;
end;
const
CURSOR_TYPES = 24;
// Special hyperspeed ends. usually only needed for forwards ones, backwards can often get the exact frame.
SHE_SHRUGGER = 1;
SHE_HIGHLIT = 2;
SPECIAL_SKIP_MAX_DURATION = 17 * 60 * 2; // 2 minutes should be plenty.
MAX_WIDTH_FOR_HQMAP = 1600;
MAX_HEIGHT_FOR_HQMAP = 640;
type
TGameWindow = class(TGameBaseScreen, IGameWindow)
private
fRanOneUpdate: Boolean;
fSaveStateReplayStream: TMemoryStream;
fCloseToScreen: TGameScreenType;
fSuspendCursor: Boolean;
fClearPhysics: Boolean;
fProjectionType: Integer;
fLastProjectionType: Integer;
fRenderInterface: TRenderInterface;
fRenderer: TRenderer;
fNeedResetMouseTrap : Boolean;
fMouseTrapped: Boolean;
fSaveList: TLemmingGameSavedStateList;
fReplayKilled: Boolean;
fInternalZoom: Integer;
fMaxZoom: Integer;
fMinimapBuffer: TBitmap32;
{ detecting if redraw is needed. These are a bit kludgy but I'm strongly considering a full rewrite of TGameWindow }
fNeedRedraw: TRedrawOption;
fLastSelectedLemming: TLemming;
fLastHighlightLemming: TLemming;
fLastSelectedSkill: TSkillPanelButton;
fLastHelperIcon: THelperIcon;
fLastDrawPaused: Boolean;
{ current gameplay }
fGameSpeed: TGameSpeed; // Do NOT set directly, set via GameSpeed property
fSpecialStartIteration: Integer;
fHyperSpeedStopCondition: Integer;
fHighlitStartCopyLemming: TLemming;
fHyperSpeedTarget: Integer;
fForceUpdateOneFrame: Boolean; // Used when paused
fHoldScrollData: THoldScrollData;
fSuspensions: TList<TSuspendState>;
HotkeyManager: TLemmixHotkeyManager;
{ game eventhandler}
procedure Game_Finished;
{ Self eventhandlers }
procedure Form_Activate(Sender: TObject);
procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Form_KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Form_KeyPress(Sender: TObject; var Key: Char);
procedure Form_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Form_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Form_MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
{ app eventhandlers }
procedure Application_Idle(Sender: TObject; var Done: Boolean);
{ gameimage eventhandlers }
procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure Img_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure Img_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
{ skillpanel eventhandlers }
procedure SkillPanel_MinimapClick(Sender: TObject; const P: TPoint);
{ internal }
procedure ReleaseMouse(releaseInFullScreen: Boolean = False);
procedure CheckResetCursor(aForce: Boolean = False);
procedure ApplyScroll(dX, dY: Integer);
function CheckScroll: Boolean;
procedure AddSaveState;
procedure CheckAdjustSpawnInterval;
procedure SetAdjustedGameCursorPoint(BitmapPoint: TPoint);
procedure InitializeCursor;
procedure CheckShifts(Shift: TShiftState);
procedure CheckUserHelpers;
procedure DoDraw;
procedure OnException(E: Exception; aCaller: String = 'Unknown');
procedure ExecuteReplayEdit;
procedure SetClearPhysics(aValue: Boolean);
function GetClearPhysics: Boolean;
procedure SetProjectionType(aValue: Integer);
procedure ProcessGameMessages;
procedure ApplyResize(NoRecenter: Boolean = False);
procedure ChangeZoom(aNewZoom: Integer; NoRedraw: Boolean = False);
procedure FreeCursors;
procedure HandleSpecialSkip(aSkipType: Integer);
procedure HandleInfiniteSkillsHotkey;
procedure HandleInfiniteTimeHotkey;
function GetLevelMusicName: String;
function ProcessMusicPriorityOrder(aOptions: String; aIsFromRotation: Boolean): String;
function GetIsHyperSpeed: Boolean;
procedure SetGameSpeed(aValue: TGameSpeed);
function GetGameSpeed: TGameSpeed;
function GetDisplayWidth: Integer; // To satisfy IGameWindow
function GetDisplayHeight: Integer; // To satisfy IGameWindow
function GetScrollSpeed: Integer;
procedure SuspendGameplay;
procedure ResumeGameplay;
function CheckHighlitLemmingChange: Boolean;
procedure SetRedraw(aRedraw: TRedrawOption);
protected
fGame : TLemmingGame; // Reference to globalgame gamemechanics
Img : TImage32; // The image in which the level is drawn (reference to inherited ScreenImg!)
SkillPanel : TBaseSkillPanel; // Our good old dos skill panel (now improved!)
fActivateCount : Integer; // Used when activating the form
GameScroll : TGameScroll; // Scrollmode
GameVScroll : TGameScroll;
IdealFrameTimeMS : Cardinal; // Normal frame speed in milliseconds
IdealFrameTimeMSSlow : Cardinal;
IdealFrameTimeSuper : Cardinal;
IdealScrollTimeMS : Cardinal; // Scroll speed in milliseconds
RewindTimer : TTimer;
FastForwardTimer : TTimer;
TurboTimer : TTimer;
PrevCallTime : Cardinal; // Last time we did something in idle
PrevScrollTime : Cardinal; // Last time we scrolled in idle
PrevPausedRRTime : Cardinal; // Last time we updated RR in idle
MouseClipRect : TRect; // We clip the mouse when there is more space
CanPlay : Boolean; // Use in idle en set to False whenever we don't want to play
Cursors : array[1..CURSOR_TYPES] of TNLCursor;
MinScroll : Single; // Scroll boundary for image
MaxScroll : Single; // Scroll boundary for image
MinVScroll : Single;
MaxVScroll : Single;
fSaveStateFrame : Integer; // List of savestates (only first is used)
fLastNukeKeyTime : Cardinal;
fScrollSpeed : Integer;
fMouseClickFrameskip : Cardinal;
fLastMousePress : Cardinal;
{ overridden}
procedure PrepareGameParams; override;
procedure CloseScreen(aNextScreen: TGameScreenType); override;
procedure SaveShot;
function IsGameplayScreen: Boolean; override;
{ internal properties }
property Game: TLemmingGame read fGame;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure ApplyMouseTrap;
procedure GotoSaveState(aTargetIteration: Integer; PauseAfterSkip: Integer = 0; aForceBeforeIteration: Integer = -1);
procedure SaveReplay;
procedure RenderMinimap;
procedure MainFormResized; override;
procedure SetCurrentCursor(aCursor: Integer = 0); // 0 = autodetect correct graphic
property HScroll: TGameScroll read GameScroll write GameScroll;
property VScroll: TGameScroll read GameVScroll write GameVScroll;
property ClearPhysics: Boolean read fClearPhysics write SetClearPhysics;
property ProjectionType: Integer read fProjectionType write SetProjectionType;
function DoSuspendCursor: Boolean;
function ShouldDisplayHQMinimap: Boolean;
procedure DoRewind(Sender: TObject);
procedure DoFastForward(Sender: TObject);
procedure DoTurbo(Sender: TObject);
property GameSpeed: TGameSpeed read GetGameSpeed write SetGameSpeed;
property HyperSpeedTarget: Integer read fHyperSpeedTarget write fHyperSpeedTarget;
property IsHyperSpeed: Boolean read GetIsHyperSpeed;
function ScreenImage: TImage32; // To satisfy IGameWindow, should be moved to TGameBaseScreen, but it causes bugs there.
property DisplayWidth: Integer read GetDisplayWidth; // To satisfy IGameWindow
property DisplayHeight: Integer read GetDisplayHeight; // To satisfy IGameWindow
procedure SetForceUpdateOneFrame(aValue: Boolean); // To satisfy IGameWindow
procedure SetHyperSpeedTarget(aValue: Integer); // To satisfy IGameWindow
function MouseFrameSkip: Integer; // Performs repeated skips when mouse buttons are held
function GetLemmingOffscreenEdge: Integer;
end;
implementation
uses FBaseDosForm, FEditReplay, LemReplay, LemNeoLevelPack;
{ TGameWindow }
procedure TGameWindow.SetGameSpeed(aValue: TGameSpeed);
begin
fGameSpeed := aValue;
// Handle Pause, Rewind and FF button selectors
SkillPanel.DrawButtonSelector(spbPause, GameSpeed = gspPause);
SkillPanel.DrawButtonSelector(spbRewind, GameSpeed = gspRewind);
SkillPanel.DrawButtonSelector(spbFastForward, GameSpeed = gspFF);
end;
function TGameWindow.GetGameSpeed: TGameSpeed;
begin
Result := fGameSpeed;
end;
procedure TGameWindow.Form_MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
var
Key: Word;
begin
Key := 0;
if WheelDelta > 0 then
Key := $05
else if WheelDelta < 0 then
Key := $06;
if Key <> 0 then
OnKeyDown(Sender, Key, Shift);
Handled := True;
end;
procedure TGameWindow.MainFormResized;
begin
ApplyResize;
DoDraw;
end;
procedure TGameWindow.ChangeZoom(aNewZoom: Integer; NoRedraw: Boolean = False);
var
Pivot: TPoint;
begin
aNewZoom := Max(Min(fMaxZoom, aNewZoom), 1);
if (aNewZoom = fInternalZoom) and not NoRedraw then
Exit;
SkillPanel.Image.BeginUpdate;
try
Pivot := Img.ScreenToClient(Mouse.CursorPos);
Pivot := Img.ControlToBitmap(Pivot);
Img.Zoom(aNewZoom, Pivot);
fInternalZoom := aNewZoom;
ApplyResize(False);
SetRedraw(rdRedraw);
CheckResetCursor(True);
finally
SkillPanel.Image.EndUpdate;
end;
end;
procedure TGameWindow.ApplyResize(NoRecenter: Boolean = False);
var
OSHorz, OSVert: Single;
VertOffset: Integer;
begin
OSHorz := Img.OffsetHorz - (Img.Width / 2);
OSVert := Img.OffsetVert - (Img.Height / 2);
ClientWidth := GameParams.MainForm.ClientWidth;
ClientHeight := GameParams.MainForm.ClientHeight;
if GameParams.ShowMinimap then
SkillPanel.Zoom := Min(GameParams.PanelZoomLevel, GameParams.MainForm.ClientWidth div 444 div ResMod)
else
SkillPanel.Zoom := Min(GameParams.PanelZoomLevel, GameParams.MainForm.ClientWidth div 336 div ResMod);
Img.Width := Min(ClientWidth, GameParams.Level.Info.Width * fInternalZoom * ResMod);
Img.Height := Min(ClientHeight - (SkillPanel.Zoom * 80), GameParams.Level.Info.Height * fInternalZoom * ResMod);
Img.Left := (ClientWidth - Img.Width) div 2;
SkillPanel.ClientWidth := ClientWidth;
// Tops are calculated later
VertOffset := ((ClientHeight - (SkillPanel.Zoom * 80) - Img.Height) div 2);
Img.Top := VertOffset;
SkillPanel.Top := Img.Top + Img.Height;
SkillPanel.Height := Max(SkillPanel.Zoom * 80, ClientHeight - SkillPanel.Top);
SkillPanel.Image.Left := (SkillPanel.ClientWidth - SkillPanel.Image.Width) div 2;
SkillPanel.Image.Update;
SkillPanel.ResetMinimapPosition;
MinScroll := -((GameParams.Level.Info.Width * fInternalZoom * ResMod) - Img.Width);
MaxScroll := 0;
MinVScroll := -((GameParams.Level.Info.Height * fInternalZoom * ResMod) - Img.Height);
MaxVScroll := 0;
if not NoRecenter then
begin
OSHorz := OSHorz + (Img.Width / 2);
OSVert := OSVert + (Img.Height / 2);
Img.OffsetHorz := Min(Max(OSHorz, MinScroll), MaxScroll);
Img.OffsetVert := Min(Max(OSVert, MinVScroll), MaxVScroll);
end;
fMaxZoom := Min(Screen.Width div 320, Screen.Height div 200) + EXTRA_ZOOM_LEVELS;
end;
function TGameWindow.IsGameplayScreen: Boolean;
begin
Result := True;
end;
function TGameWindow.GetLevelMusicName: String;
var
MusicIndex: Integer;
SL: TStringList;
begin
Result := ProcessMusicPriorityOrder(GameParams.Level.Info.MusicFile, False);
if Result = '' then
begin
SL := GameParams.CurrentLevel.Group.MusicList;
if SL.Count > 0 then
begin
if (GameParams.TestModeLevel <> nil) or (GameParams.CurrentLevel.Group = GameParams.BaseLevelPack) then
MusicIndex := Random(SL.Count)
else
MusicIndex := GameParams.CurrentLevel.MusicRotationIndex;
Result := ProcessMusicPriorityOrder(SL[MusicIndex mod SL.Count], True);
end;
end;
if LeftStr(Result, 1) = '*' then
Result := '';
end;
function TGameWindow.ProcessMusicPriorityOrder(aOptions: String; aIsFromRotation: Boolean): String;
var
SL: TStringList;
ThisName: String;
MusicIndex: Integer;
i: Integer;
begin
Result := '';
if aOptions = '' then
Exit;
SL := TStringList.Create;
try
SL.Delimiter := ';';
SL.StrictDelimiter := True;
if aOptions[1] = '!' then
begin
SL.DelimitedText := RightStr(aOptions, Length(aOptions)-1);
for i := 0 to SL.Count-2 do
SL.Move(Random(SL.Count - i) + i, i); // This is essentially a single-list Fisher-Yates shuffle
end else
SL.DelimitedText := aOptions;
for i := 0 to SL.Count-1 do
begin
ThisName := ChangeFileExt(Trim(SL[i]), '');
if ThisName = '' then Continue;
if (LeftStr(ThisName, 1) = '?') and not aIsFromRotation then
begin
if ThisName = '??' then
MusicIndex := Random(GameParams.CurrentLevel.Group.MusicList.Count)
else
MusicIndex := StrToIntDef(RightStr(ThisName, Length(ThisName)-1), -1);
if (MusicIndex >= 0) and (MusicIndex < GameParams.CurrentLevel.Group.MusicList.Count) then
begin
ThisName := ProcessMusicPriorityOrder(GameParams.CurrentLevel.Group.MusicList[MusicIndex], True);
if ThisName <> '' then
begin
Result := ThisName;
Exit;
end;
end;
end else if SoundManager.FindExtension(ThisName, True) <> '' then
begin
Result := ThisName;
Exit;
end;
end;
finally
SL.Free;
end;
end;
procedure TGameWindow.SetClearPhysics(aValue: Boolean);
begin
if fClearPhysics <> aValue then
SetRedraw(rdRedraw);
fClearPhysics := aValue;
SkillPanel.DrawButtonSelector(spbSquiggle, fClearPhysics);
end;
function TGameWindow.GetClearPhysics: Boolean;
begin
Result := fClearPhysics;
end;
function TGameWindow.ShouldDisplayHQMinimap: Boolean;
begin
Result := False;
if not GameParams.MinimapHighQuality then Exit;
if GameParams.AmigaTheme then Exit;
if Game.IsSuperLemmingMode then Exit;
if GameSpeed in [gspRewind, gspTurbo, gspFF] then Exit;
if Game.Level.Info.Width > MAX_WIDTH_FOR_HQMAP then Exit;
if Game.Level.Info.Height > MAX_HEIGHT_FOR_HQMAP then Exit;
Result := True;
end;
procedure TGameWindow.RenderMinimap;
begin
if not GameParams.ShowMinimap then Exit;
if ShouldDisplayHQMinimap then
begin
fMinimapBuffer.Clear(0);
Img.Bitmap.DrawTo(fMinimapBuffer);
SkillPanel.Minimap.Clear(0);
fMinimapBuffer.DrawTo(SkillPanel.Minimap, SkillPanel.Minimap.BoundsRect, fMinimapBuffer.BoundsRect);
fRenderer.RenderMinimap(SkillPanel.Minimap, True);
end else
fRenderer.RenderMinimap(SkillPanel.Minimap, False);
SkillPanel.DrawMinimap;
end;
procedure TGameWindow.ExecuteReplayEdit;
var
F: TFReplayEditor;
OldClearReplay: Boolean;
ModalResult: Integer;
begin
F := TFReplayEditor.Create(Self);
SuspendGameplay;
try
F.SetReplay(Game.ReplayManager, Game.CurrentIteration);
repeat
ModalResult := F.ShowModal;
if (ModalResult = mrRetry) and (F.TargetFrame <> -1) then
GoToSaveState(F.TargetFrame)
else if (ModalResult = mrCancel) and (F.TargetFrame <> -1) then
GoToSaveState(F.CurrentIteration);
if (ModalResult = mrOk) and (F.EarliestChange <= Game.CurrentIteration) then
begin
OldClearReplay := not GameParams.AutoReplayMode;
fSaveList.ClearAfterIteration(0);
GotoSaveState(Game.CurrentIteration);
GameParams.AutoReplayMode := not OldClearReplay;
end;
until ModalResult <> mrRetry;
finally
F.Free;
ResumeGameplay;
end;
end;
procedure TGameWindow.ApplyMouseTrap;
var
ClientTopLeft, ClientBottomRight: TPoint;
begin
// Only trap mouse if SLX is in the foreground
if FindControl(GetForegroundWindow()) = nil then Exit;
// For security check trapping the mouse again.
if fSuspendCursor or not GameParams.EdgeScroll then Exit;
fMouseTrapped := True;
ClientTopLeft := ClientToScreen(Point(Min(SkillPanel.Image.Left, Img.Left), Img.Top));
ClientBottomRight := ClientToScreen(Point(Max(Img.Left + Img.Width, SkillPanel.Image.Left + SkillPanel.Image.Width), SkillPanel.Top + SkillPanel.Image.Height));
MouseClipRect := Rect(ClientTopLeft, ClientBottomRight);
ClipCursor(@MouseClipRect);
end;
procedure TGameWindow.ReleaseMouse(releaseInFullScreen: Boolean = False);
begin
if GameParams.FullScreen and not releaseInFullScreen then Exit;
fMouseTrapped := False;
ClipCursor(nil);
end;
procedure TGameWindow.DoRewind(Sender: TObject);
begin
// Start-of-level check needs to give a few frames' grace to prevent infinite rewinding
if Game.CurrentIteration <= 8 then
begin
RewindTimer.Enabled := False;
Game.IsBackstepping := False;
GameSpeed := gspNormal; // Return speed to Normal at start of game
SkillPanel.DrawButtonSelector(spbRewind, False);
end else begin
Game.IsBackstepping := True;
GoToSaveState(Game.CurrentIteration - 3);
end;
end;
procedure TGameWindow.DoFastForward(Sender: TObject);
begin
fHyperSpeedTarget := Game.CurrentIteration + 1;
end;
procedure TGameWindow.DoTurbo(Sender: TObject);
begin
fHyperSpeedTarget := Game.CurrentIteration + 7
end;
procedure TGameWindow.Application_Idle(Sender: TObject; var Done: Boolean);
{-------------------------------------------------------------------------------
Main heartbeat of the program.
This method together with Game.UpdateLemmings() take care of most game-mechanics.
A bit problematic is the SpawnInterval handling:
if the game is paused, RR is handled here. if not it is handled by
Game.UpdateLemmings().
-------------------------------------------------------------------------------}
var
i: Integer;
ContinueHyper: Boolean;
CurrTime: Cardinal;
ForceOne, TimeForFrame, TimeForPausedRR, TimeForScroll, Hyper, Pause, Rewind, Fast, Turbo, Slow: Boolean;
MouseClickFrameSkip: Integer;
begin
if fCloseToScreen <> gstUnknown then
begin
// This allows any mid-processing code to finish, and averts access violations, compared to directly calling CloseScreen.
CloseScreen(fCloseToScreen);
Exit;
end;
// This makes sure this method is called very often :)
Done := False;
Game.MaybeExitToPostview;
if not CanPlay or not Game.Playing or Game.GameFinished then
begin
ProcessGameMessages; // May still be some lingering, especially the GAMEMSG_FINISH message
Exit;
end;
MouseClickFrameSkip := MouseFrameSkip;
if not (GameParams.ClassicMode or Game.IsSuperLemmingMode) then
if MouseClickFrameSkip < 0 then
begin
GotoSaveState(Max(Game.CurrentIteration-1, 0));
if not GameParams.AutoReplayMode then
Game.RegainControl(True);
end;
ForceOne := fForceUpdateOneFrame or fRenderInterface.ForceUpdate;
fForceUpdateOneFrame := (MouseClickFrameSkip > 0);
CurrTime := TimeGetTime;
Pause := GameSpeed = gspPause;
Rewind := GameSpeed = gspRewind;
Fast := GameSpeed = gspFF;
Turbo := GameSpeed = gspTurbo;
Slow := GameSpeed = gspSlowMo;
if Slow then
TimeForFrame := (not (Pause or Rewind)) and (CurrTime - PrevCallTime > IdealFrameTimeMSSlow)
else
TimeForFrame := (not (Pause or Rewind)) and (CurrTime - PrevCallTime > IdealFrameTimeMS); // Don't check for frame advancing when paused
TimeForPausedRR := (Pause) and (CurrTime - PrevPausedRRTime > IdealFrameTimeMS);
TimeForScroll := CurrTime - PrevScrollTime > IdealScrollTimeMS;
Hyper := IsHyperSpeed;
// Rewind mode
if Rewind then
begin
// Ensures that rendering has caught up before the next backwards skip is performed
if IsHyperSpeed then
RewindTimer.Enabled := False
else
RewindTimer.Enabled := True;
end else
RewindTimer.Enabled := False;
// Fast-forward
if Fast then
FastForwardTimer.Enabled := True
else
FastForwardTimer.Enabled := False;
// Turbo mode
if Turbo then
begin
TurboTimer.Enabled := True;
SkillPanel.DrawTurboHighlight;
end else begin
TurboTimer.Enabled := False;
SkillPanel.DrawTurboHighlight;
end;
// Superlemming mode
if Game.IsSuperLemmingMode then
begin
TimeForFrame := (not Pause) and (CurrTime - PrevCallTime > IdealFrameTimeSuper);
SkillPanel.DrawButtonSelector(spbRewind, True);
SkillPanel.DrawButtonSelector(spbFastForward, True);
end;
if ForceOne or Hyper then TimeForFrame := True;
// Relax CPU
if not (Hyper or Fast or Game.IsSuperLemmingMode) then
Sleep(1);
if TimeForFrame or TimeForScroll or TimeForPausedRR then
begin
fRenderInterface.ForceUpdate := False;
// Only in paused mode adjust RR. If not paused it's updated per frame.
if TimeForPausedRR and not GameParams.ClassicMode then
begin
CheckAdjustSpawnInterval;
PrevPausedRRTime := CurrTime;
end;
// Set new screen position
if TimeForScroll then
begin
PrevScrollTime := CurrTime;
if CheckScroll then
begin
if ShouldDisplayHQMinimap then
SetRedraw(rdRefresh)
else
SetRedraw(rdRedraw);
end;
end;
// Check whether we have to move the lemmings
if (TimeForFrame and not (Pause or Rewind))
or ForceOne
or Hyper then
begin
// Reset time between physics updates
PrevCallTime := CurrTime;
// Let all lemmings move
Game.UpdateLemmings;
// Save current state every 10 seconds
if (Game.CurrentIteration mod 170 = 0) then
begin
AddSaveState;
fSaveList.TidyList(Game.CurrentIteration);
end;
fRanOneUpdate := True;
end;
if Hyper and (fHyperSpeedStopCondition <> 0) then
begin
ContinueHyper := False;
if Game.CurrentIteration < fSpecialStartIteration + SPECIAL_SKIP_MAX_DURATION then
case fHyperSpeedStopCondition of
SHE_SHRUGGER: for i := 0 to fRenderInterface.LemmingList.Count-1 do
begin
if fRenderInterface.LemmingList[i].LemRemoved then Continue;
if fRenderInterface.LemmingList[i].LemAction = baShrugging then
begin
ContinueHyper := False;
Break;
end;
if fRenderInterface.LemmingList[i].LemAction in [baBuilding, baStacking, baPlatforming] then
ContinueHyper := True;
end;
SHE_HIGHLIT: if not CheckHighlitLemmingChange then ContinueHyper := True;
end;
if not ContinueHyper then
begin
fHyperSpeedTarget := Game.CurrentIteration;
fHyperSpeedStopCondition := 0;
end else
fHyperSpeedTarget := Game.CurrentIteration + 1;
end;
// Prevents large forward skips overshooting into unplayable state
if Game.StateIsUnplayable and Hyper then
fHyperSpeedTarget := Game.CurrentIteration;
// Refresh panel if in usual or fast play mode
if not Hyper then
begin
SkillPanel.RefreshInfo;
CheckResetCursor;
end else if (Game.CurrentIteration = fHyperSpeedTarget) then
begin
fHyperSpeedTarget := -1;
SkillPanel.RefreshInfo;
SetRedraw(rdRedraw);
CheckResetCursor;
end;
end;
if TimeForFrame then
SetRedraw(rdRedraw);
// Update drawing
DoDraw;
// Bookmark - use this logic for VisualSFX
{$ifdef debug}
// case GetLemmingOffscreenEdge of
// 0: Output('Lemming ' + IntToStr(i) + ' is onscreen');
// 1: Output('Lemming ' + IntToStr(i) + ' is offscreen to the top');
// 2: Output('Lemming ' + IntToStr(i) + ' is offscreen to the bottom');
// 3: Output('Lemming ' + IntToStr(i) + ' is offscreen to the left');
// 4: Output('Lemming ' + IntToStr(i) + ' is offscreen to the right');
// end;
{$endif}
if TimeForFrame then
ProcessGameMessages;
end;
function TGameWindow.GetIsHyperSpeed: Boolean;
begin
Result := (fHyperSpeedTarget > Game.CurrentIteration) or (fHyperSpeedStopCondition <> 0);
end;
function TGameWindow.GetLemmingOffscreenEdge: Integer;
var
i: Integer;
LemPoint: TPoint;
ViewportTop, ViewportBottom: Integer;
ViewportLeft, ViewportRight: Integer;
begin
Result := -1;
if fRenderInterface = nil then Exit;
ViewportTop := Abs(Trunc(Img.OffsetVert) div fInternalZoom) div ResMod;
ViewPortBottom := ((Img.Height - Trunc(Img.OffsetVert)) div fInternalZoom) div ResMod;
ViewportLeft := Abs(Trunc(Img.OffsetHorz) div fInternalZoom) div ResMod;
ViewportRight := ((Img.Width - Trunc(Img.OffsetHorz)) div fInternalZoom) div ResMod;
for i := 0 to fRenderInterface.LemmingList.Count -1 do
begin
LemPoint := fRenderInterface.LemmingList[i].Position;
if (LemPoint.X > ViewportRight) then
Result := 4
else if (LemPoint.X < ViewportLeft) then
Result := 3
else if (LemPoint.Y > ViewportBottom) then
Result := 2
else if (LemPoint.Y < ViewportTop + 1) then
Result := 1
else
Result := 0; // Onscreen
Exit;
end;
end;
procedure TGameWindow.ProcessGameMessages;
var
Msg: TGameMessage;
begin
while Game.MessageQueue.HasMessages do
begin
Msg := Game.MessageQueue.NextMessage;
case Msg.MessageType of
GAMEMSG_FINISH: Game_Finished;
// Still need to implement sound
GAMEMSG_SOUND: if not IsHyperSpeed then
SoundManager.PlaySound(Msg.MessageDataStr);
GAMEMSG_SOUND_BAL: if not IsHyperSpeed then
SoundManager.PlaySound(Msg.MessageDataStr,
(Msg.MessageDataInt - Trunc(((Img.Width / 2) - Img.OffsetHorz) / Img.Scale)) div 2);
GAMEMSG_MUSIC: SoundManager.PlayMusic;
end;
end;
end;
procedure TGameWindow.OnException(E: Exception; aCaller: String = 'Unknown');
var
SL: TStringList;
RIValid: Boolean;
begin
fGameSpeed := gspPause;
SL := TStringList.Create;
// Attempt to load existing report so we can simply add to the end.
// We don't want to trigger a second exception here, so be over-cautious with the try...excepts.
// Performance probably doesn't matter if we end up here.
try
if FileExists(ExtractFilePath(ParamStr(0)) + 'SuperLemmixException.txt') then
begin
SL.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'SuperLemmixException.txt');
SL.Add('');
SL.Add('');
end;
except
SL.Clear;
end;
SL.Add('Exception raised at ' + DateToStr(Now));
SL.Add(' Happened in: ' + aCaller);
SL.Add(' Class: ' + E.ClassName);
SL.Add(' Message: ' + E.Message);
RIValid := False;
if fRenderInterface = nil then
SL.Add(' fRenderInterface: nil')
else
try
fRenderInterface.Null;
SL.Add(' fRenderInterface: Valid');
RIValid := True;
except
SL.Add(' fRenderInterface: Exception on access attempt');
end;
if RIValid then
begin
if fRenderInterface.LemmingList = nil then
SL.Add(' fRenderInterface.LemmingList: nil')
else
try
SL.Add(' fRenderInterface.LemmingList.Count: ' + IntToStr(fRenderInterface.LemmingList.Count));
except
SL.Add(' fRenderInterface.LemmingList: Exception on access attempt');
end;
if fRenderInterface.SelectedLemming = nil then
SL.Add(' fRenderInterface.SelectedLemming: nil')
else
try
fRenderInterface.SelectedLemming.LemX := 0;
SL.Add(' fRenderInterface.SelectedLemming: Valid');
except
SL.Add(' fRenderInterface.SelectedLemming: Exception on access attempt');
end;
if fRenderInterface.HighlitLemming = nil then
SL.Add(' fRenderInterface.HighlitLemming: nil')
else
try
fRenderInterface.HighlitLemming.LemX := 0;
SL.Add(' fRenderInterface.HighlitLemming: Valid');
except
SL.Add(' fRenderInterface.HighlitLemming: Exception on access attempt');
end;
if fRenderInterface.ReplayLemming = nil then
SL.Add(' fRenderInterface.ReplayLemming: nil')
else
try
fRenderInterface.ReplayLemming.LemX := 0;
SL.Add(' fRenderInterface.ReplayLemming: Valid');
except
SL.Add(' fRenderInterface.ReplayLemming: Exception on access attempt');
end;
case fRenderInterface.SelectedSkill of
spbWalker: SL.Add(' fRenderInterface.SelectedSkill: Walker');
spbClimber: SL.Add(' fRenderInterface.SelectedSkill: Climber');
spbSwimmer: SL.Add(' fRenderInterface.SelectedSkill: Swimmer');
spbBallooner: SL.Add(' fRenderInterface.SelectedSkill: Ballooner');
spbFloater: SL.Add(' fRenderInterface.SelectedSkill: Floater');
spbGlider: SL.Add(' fRenderInterface.SelectedSkill: Glider');
spbDisarmer: SL.Add(' fRenderInterface.SelectedSkill: Disarmer');
spbTimebomber: SL.Add(' fRenderInterface.SelectedSkill: Timebomber');
spbBomber: SL.Add(' fRenderInterface.SelectedSkill: Bomber');
spbFreezer: SL.Add(' fRenderInterface.SelectedSkill: Freezer');
spbBlocker: SL.Add(' fRenderInterface.SelectedSkill: Blocker');
spbLadderer: SL.Add(' fRenderInterface.SelectedSkill: Ladderer');
spbPlatformer: SL.Add(' fRenderInterface.SelectedSkill: Platformer');
spbBuilder: SL.Add(' fRenderInterface.SelectedSkill: Builder');
spbStacker: SL.Add(' fRenderInterface.SelectedSkill: Stacker');
spbLaserer: SL.Add(' fRenderInterface.SelectedSkill: Laserer');
//spbPropeller: SL.Add(' fRenderInterface.SelectedSkill: Propeller'); // Propeller
spbBasher: SL.Add(' fRenderInterface.SelectedSkill: Basher');
spbFencer: SL.Add(' fRenderInterface.SelectedSkill: Fencer');
spbMiner: SL.Add(' fRenderInterface.SelectedSkill: Miner');
spbDigger: SL.Add(' fRenderInterface.SelectedSkill: Digger');
spbCloner: SL.Add(' fRenderInterface.SelectedSkill: Cloner');
spbShimmier: SL.Add(' fRenderInterface.SelectedSkill: Shimmier');
spbJumper: SL.Add(' fRenderInterface.SelectedSkill: Jumper');
spbSpearer: SL.Add(' fRenderInterface.SelectedSkill: Spearer');
spbGrenader: SL.Add(' fRenderInterface.SelectedSkill: Grenader');
//spbBatter: SL.Add(' fRenderInterface.SelectedSkill: Batter'); // Batter
spbSlider: SL.Add(' fRenderInterface.SelectedSkill: Slider');
else SL.Add(' fRenderInterface.SelectedSkill: None or invalid');
end;
end;
// Attempt to save report - we'd rather it just fail than crash and lose the replay data.
try
SL.SaveToFile(ExtractFilePath(ParamStr(0)) + 'SuperLemmixException.txt');
RIValid := True;
except
// We can't do much here.
RIValid := False; // Reuse is lazy. but I'm doing it anyway.
end;
if RIValid then
ShowMessage('An exception has occurred. Details have been saved to SuperLemmixException.txt. Your current replay will be' + #13 +
'saved to the "Auto" folder if possible, then you will be returned to the main menu.')
else
ShowMessage('An exception has occurred. Attempting to save details to a text file failed. Your current replay will be' + #13 +
'saved to the "Auto" folder if possible, then you will be returned to the main menu.');
try
SL.Insert(0, Game.ReplayManager.GetSaveFileName(Self, rsoAuto));
ForceDirectories(ExtractFilePath(SL[0]));
Game.EnsureCorrectReplayDetails;
Game.ReplayManager.SaveToFile(SL[0]);
ShowMessage('Your replay was saved successfully. Returning to main menu now. Restarting SuperLemmix is recommended.');
except
ShowMessage('Unfortunately, your replay could not be saved.');
end;
fCloseToScreen := gstMenu;
end;
procedure TGameWindow.CheckUserHelpers;
begin
if not GameParams.HideHelpers then
begin
fRenderInterface.UserHelper := hpi_None;
if GameParams.Hotkeys.CheckForKey(lka_FallDistance) then
fRenderInterface.UserHelper := hpi_FallDist;
end;
end;
procedure TGameWindow.DoDraw;
var
DrawRect: TRect;
DrawWidth, DrawHeight: Integer;
begin
if IsHyperSpeed then Exit;
Game.HitTest(not PtInRect(Img.BoundsRect, ScreenToClient(Mouse.CursorPos)));
CheckUserHelpers;