DEADSOFTWARE

0123ecd695f4fbcd8769477f23d9c9529a1125ed
[d2df-sdl.git] / src / game / g_game.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_game;
18 interface
20 uses
21 {$IFNDEF HEADLESS}
22 g_gui, g_touch,
23 {$ENDIF}
24 SysUtils, Classes, MAPDEF,
25 g_base, g_basic, g_player, g_res_downloader,
26 g_sound, utils, md5, mempool, xprofiler,
27 g_weapons
28 ;
30 type
31 TGameSettings = record
32 GameType: Byte;
33 GameMode: Byte;
34 TimeLimit: Word;
35 GoalLimit: Word;
36 WarmupTime: Word;
37 SpawnInvul: Word;
38 ItemRespawnTime: Word;
39 MaxLives: Byte;
40 Options: LongWord;
41 WAD: String;
42 end;
44 TGameEvent = record
45 Name: String;
46 Command: String;
47 end;
49 TDelayedEvent = record
50 Pending: Boolean;
51 Time: LongWord;
52 DEType: Byte;
53 DENum: Integer;
54 DEStr: String;
55 end;
57 TChatSound = record
58 Sound: TPlayableSound;
59 Tags: Array of String;
60 FullWord: Boolean;
61 end;
63 TPlayerSettings = record
64 Name: String;
65 Model: String;
66 Color: TRGB;
67 Team: Byte;
68 end;
70 TMegaWADInfo = record
71 Name: String;
72 Description: String;
73 Author: String;
74 Pic: String;
75 end;
77 THearPoint = record
78 Active: Boolean;
79 Coords: TDFPoint;
80 end;
82 function g_Game_IsNet(): Boolean;
83 function g_Game_IsServer(): Boolean;
84 function g_Game_IsClient(): Boolean;
85 procedure g_Game_Init();
86 procedure g_Game_Free (freeTextures: Boolean=true);
87 procedure g_Game_LoadData();
88 procedure g_Game_FreeData();
89 procedure g_Game_Update();
90 procedure g_Game_PreUpdate();
91 procedure g_Game_Quit();
92 function g_Game_ModeToText(Mode: Byte): string;
93 function g_Game_TextToMode(Mode: string): Byte;
94 procedure g_Game_ExecuteEvent(Name: String);
95 function g_Game_DelayEvent(DEType: Byte; Time: LongWord; Num: Integer = 0; Str: String = ''): Integer;
96 procedure g_Game_AddPlayer(Team: Byte = TEAM_NONE);
97 procedure g_Game_RemovePlayer();
98 procedure g_Game_Spectate();
99 procedure g_Game_SpectateCenterView();
100 procedure g_Game_StartSingle(Map: String; TwoPlayers: Boolean; nPlayers: Byte);
101 procedure g_Game_StartCustom(Map: String; GameMode: Byte; TimeLimit, GoalLimit: Word; MaxLives: Byte; Options: LongWord; nPlayers: Byte);
102 procedure g_Game_StartServer(Map: String; GameMode: Byte; TimeLimit, GoalLimit: Word; MaxLives: Byte; Options: LongWord; nPlayers: Byte; IPAddr: LongWord; Port: Word);
103 procedure g_Game_StartClient(Addr: String; Port: Word; PW: String);
104 procedure g_Game_Restart();
105 procedure g_Game_RestartLevel();
106 procedure g_Game_RestartRound(NoMapRestart: Boolean = False);
107 function g_Game_ClientWAD (NewWAD: String; const WHash: TMD5Digest): AnsiString;
108 function g_Game_StartMap(asMegawad: Boolean; Map: String; Force: Boolean = False; const oldMapPath: AnsiString=''): Boolean;
109 procedure g_Game_ChangeMap(const MapPath: String);
110 procedure g_Game_ExitLevel(const Map: AnsiString);
111 function g_Game_GetFirstMap(WAD: String): String;
112 function g_Game_GetNextMap(): String;
113 procedure g_Game_NextLevel();
114 procedure g_Game_Pause(Enable: Boolean);
115 procedure g_Game_HolmesPause(Enable: Boolean);
116 {$IFNDEF HEADLESS}
117 procedure g_Game_InGameMenu(Show: Boolean);
118 {$ENDIF}
119 function g_Game_IsWatchedPlayer(UID: Word): Boolean;
120 function g_Game_IsWatchedTeam(Team: Byte): Boolean;
121 procedure g_Game_Message(Msg: String; Time: Word);
122 procedure g_Game_LoadMapList(FileName: String);
123 procedure g_Game_PauseAllSounds(Enable: Boolean);
124 procedure g_Game_StopAllSounds(all: Boolean);
125 procedure g_Game_UpdateTriggerSounds();
126 function g_Game_GetMegaWADInfo(WAD: String): TMegaWADInfo;
127 procedure g_Game_ChatSound(Text: String; Taunt: Boolean = True);
128 procedure g_Game_Announce_GoodShot(SpawnerUID: Word);
129 procedure g_Game_Announce_KillCombo(Param: Integer);
130 procedure g_Game_Announce_BodyKill(SpawnerUID: Word);
131 procedure g_Game_StartVote(Command, Initiator: string);
132 procedure g_Game_CheckVote;
133 {$IFNDEF HEADLESS}
134 procedure g_TakeScreenShot(Filename: string = '');
135 {$ENDIF}
136 procedure g_FatalError(Text: String);
137 procedure g_SimpleError(Text: String);
138 function g_Game_IsTestMap(): Boolean;
139 procedure g_Game_DeleteTestMap();
140 procedure GameCVars(P: SSArray);
141 procedure PlayerSettingsCVars(P: SSArray);
142 procedure SystemCommands(P: SSArray);
143 procedure GameCommands(P: SSArray);
144 procedure GameCheats(P: SSArray);
145 procedure DebugCommands(P: SSArray);
146 procedure g_Game_Process_Params;
147 procedure g_Game_SetLoadingText(Text: String; Max: Integer; reWrite: Boolean);
148 procedure g_Game_StepLoading(Value: Integer = -1);
149 procedure g_Game_ClearLoading();
150 procedure g_Game_SetDebugMode();
152 function IsActivePlayer(p: TPlayer): Boolean;
153 function GetActivePlayerID_Next(Skip: Integer = -1): Integer;
154 procedure SortGameStat(var stat: TPlayerStatArray);
156 procedure KeyPress (K: Word);
158 {$IFNDEF HEADLESS}
159 procedure CharPress (C: AnsiChar);
160 {$ENDIF}
162 { procedure SetWinPause(Enable: Boolean); }
164 const
165 GAME_TICK = 28;
167 LOADING_SHOW_STEP = 100;
168 LOADING_INTERLINE = 20;
170 GT_NONE = 0;
171 GT_SINGLE = 1;
172 GT_CUSTOM = 2;
173 GT_SERVER = 3;
174 GT_CLIENT = 4;
176 GM_NONE = 0;
177 GM_DM = 1;
178 GM_TDM = 2;
179 GM_CTF = 3;
180 GM_COOP = 4;
181 GM_SINGLE = 5;
183 EXIT_QUIT = 1;
184 EXIT_SIMPLE = 2;
185 EXIT_RESTART = 3;
186 EXIT_ENDLEVELSINGLE = 4;
187 EXIT_ENDLEVELCUSTOM = 5;
189 GAME_OPTION_RESERVED = 1;
190 GAME_OPTION_TEAMDAMAGE = 2;
191 GAME_OPTION_ALLOWEXIT = 4;
192 GAME_OPTION_WEAPONSTAY = 8;
193 GAME_OPTION_MONSTERS = 16;
194 GAME_OPTION_BOTVSPLAYER = 32;
195 GAME_OPTION_BOTVSMONSTER = 64;
196 GAME_OPTION_DMKEYS = 128;
197 GAME_OPTION_TEAMHITTRACE = 256;
198 GAME_OPTION_TEAMHITPROJECTILE = 512;
199 GAME_OPTION_TEAMABSORBDAMAGE = 1024;
201 STATE_NONE = 0;
202 STATE_MENU = 1;
203 STATE_FOLD = 2;
204 STATE_INTERCUSTOM = 3;
205 STATE_INTERSINGLE = 4;
206 STATE_INTERTEXT = 5;
207 STATE_INTERPIC = 6;
208 STATE_ENDPIC = 7;
209 STATE_SLIST = 8;
211 LMS_RESPAWN_NONE = 0;
212 LMS_RESPAWN_WARMUP = 1;
213 LMS_RESPAWN_FINAL = 2;
215 SPECT_NONE = 0;
216 SPECT_STATS = 1;
217 SPECT_MAPVIEW = 2;
218 SPECT_PLAYERS = 3;
220 DE_GLOBEVENT = 0;
221 DE_BFGHIT = 1;
222 DE_KILLCOMBO = 2;
223 DE_BODYKILL = 3;
225 ANNOUNCE_NONE = 0;
226 ANNOUNCE_ME = 1;
227 ANNOUNCE_MEPLUS = 2;
228 ANNOUNCE_ALL = 3;
230 CONFIG_FILENAME = 'Doom2DF.cfg';
232 TEST_MAP_NAME = '$$$_TEST_$$$';
234 STD_PLAYER_MODEL = 'Doomer';
236 {$IFDEF HEADLESS}
237 DEFAULT_PLAYERS = 0;
238 {$ELSE}
239 DEFAULT_PLAYERS = 1;
240 {$ENDIF}
242 STATFILE_VERSION = $03;
244 var
245 gGameSettings: TGameSettings;
246 gPlayer1Settings: TPlayerSettings;
247 gPlayer2Settings: TPlayerSettings;
248 gGameOn: Boolean;
249 gPlayerScreenSize: TDFPoint;
250 gPlayer1ScreenCoord: TDFPoint;
251 gPlayer2ScreenCoord: TDFPoint;
252 gPlayer1: TPlayer = nil;
253 gPlayer2: TPlayer = nil;
254 gPlayerDrawn: TPlayer = nil;
255 gTime: LongWord;
256 gLerpFactor: Single = 1.0;
257 gSwitchGameMode: Byte = GM_DM;
258 gHearPoint1, gHearPoint2: THearPoint;
259 gSoundEffectsDF: Boolean = False;
260 gSoundTriggerTime: Word = 0;
261 gAnnouncer: Integer = ANNOUNCE_NONE;
262 goodsnd: array[0..3] of TPlayableSound;
263 killsnd: array[0..3] of TPlayableSound;
264 hahasnd: array[0..2] of TPlayableSound;
265 sound_get_flag: array[0..1] of TPlayableSound;
266 sound_lost_flag: array[0..1] of TPlayableSound;
267 sound_ret_flag: array[0..1] of TPlayableSound;
268 sound_cap_flag: array[0..1] of TPlayableSound;
269 gBodyKillEvent: Integer = -1;
270 gDefInterTime: ShortInt = -1;
271 gInterEndTime: LongWord = 0;
272 gInterTime: LongWord = 0;
273 gServInterTime: Byte = 0;
274 gGameStartTime: LongWord = 0;
275 gTotalMonsters: Integer = 0;
276 gPauseMain: Boolean = false;
277 gPauseHolmes: Boolean = false;
278 gShowTime: Boolean = False;
279 gShowFPS: Boolean = False;
280 gShowGoals: Boolean = True;
281 gShowStat: Boolean = True;
282 gShowPIDs: Boolean = False;
283 gShowKillMsg: Boolean = True;
284 gShowLives: Boolean = True;
285 gShowPing: Boolean = False;
286 gShowMap: Boolean = False;
287 gExit: Byte = 0;
288 gState: Byte = STATE_NONE;
289 sX, sY: Integer;
290 sWidth, sHeight: Word;
291 gSpectMode: Byte = SPECT_NONE;
292 gSpectHUD: Boolean = True;
293 gSpectKeyPress: Boolean = False;
294 gSpectX: Integer = 0;
295 gSpectY: Integer = 0;
296 gSpectStep: Byte = 8;
297 gSpectViewTwo: Boolean = False;
298 gSpectPID1: Integer = -1;
299 gSpectPID2: Integer = -1;
300 gSpectAuto: Boolean = False;
301 gSpectAutoNext: LongWord;
302 gSpectAutoStepX: Integer;
303 gSpectAutoStepY: Integer;
304 gMusic: TMusic = nil;
305 gLoadGameMode: Boolean;
306 gCheats: Boolean = False;
307 gMapOnce: Boolean = False;
308 gMapToDelete: String;
309 gTempDelete: Boolean = False;
310 gLastMap: Boolean = False;
311 gScreenWidth: Word;
312 gScreenHeight: Word;
313 gResolutionChange: Boolean = False;
314 gRC_Width, gRC_Height: Integer;
315 gRC_FullScreen, gRC_Maximized: Boolean;
316 gLanguageChange: Boolean = False;
317 gDebugMode: Boolean = False;
318 g_debug_Sounds: Boolean = False;
319 g_debug_Frames: Boolean = False;
320 g_debug_WinMsgs: Boolean = False;
321 g_debug_MonsterOff: Boolean = False;
322 g_debug_BotAIOff: Byte = 0;
323 g_debug_HealthBar: Boolean = False;
324 g_Debug_Player: Boolean = False;
325 gCoopMonstersKilled: Word = 0;
326 gCoopSecretsFound: Word = 0;
327 gCoopTotalMonstersKilled: Word = 0;
328 gCoopTotalSecretsFound: Word = 0;
329 gCoopTotalMonsters: Word = 0;
330 gCoopTotalSecrets: Word = 0;
331 gStatsOff: Boolean = False;
332 gStatsPressed: Boolean = False;
333 gExitByTrigger: Boolean = False;
334 gNextMap: String = '';
335 gLMSRespawn: Byte = LMS_RESPAWN_NONE;
336 gLMSRespawnTime: Cardinal = 0;
337 gLMSSoftSpawn: Boolean = False;
338 gMissionFailed: Boolean = False;
339 gVoteInProgress: Boolean = False;
340 gVotePassed: Boolean = False;
341 gVoteCommand: string = '';
342 gVoteTimer: Cardinal = 0;
343 gVoteCmdTimer: Cardinal = 0;
344 gVoteCount: Integer = 0;
345 gVoteTimeout: Cardinal = 30;
346 gVoted: Boolean = False;
347 gVotesEnabled: Boolean = True;
348 gEvents: Array of TGameEvent;
349 gDelayedEvents: Array of TDelayedEvent;
350 gUseChatSounds: Boolean = True;
351 gChatSounds: Array of TChatSound;
352 gSelectWeapon: Array [0..1, WP_FIRST..WP_LAST] of Boolean; // [player, weapon]
353 gInterReadyCount: Integer = 0;
355 g_dbg_ignore_bounds: Boolean = false;
356 r_smallmap_h: Integer = 0; // 0: left; 1: center; 2: right
357 r_smallmap_v: Integer = 2; // 0: top; 1: center; 2: bottom
359 // move button values:
360 // bits 0-1: l/r state:
361 // 0: neither left, nor right pressed
362 // 1: left pressed
363 // 2: right pressed
364 // bits 4-5: l/r state when strafe was pressed
365 P1MoveButton: Byte = 0;
366 P2MoveButton: Byte = 0;
368 g_profile_frame_update: Boolean = false;
369 g_profile_frame_draw: Boolean = false;
370 g_profile_collision: Boolean = false;
371 g_profile_los: Boolean = false;
372 g_profile_history_size: Integer = 1000;
374 g_rlayer_back: Boolean = true;
375 g_rlayer_step: Boolean = true;
376 g_rlayer_wall: Boolean = true;
377 g_rlayer_door: Boolean = true;
378 g_rlayer_acid1: Boolean = true;
379 g_rlayer_acid2: Boolean = true;
380 g_rlayer_water: Boolean = true;
381 g_rlayer_fore: Boolean = true;
383 wNeedTimeReset: Boolean = false;
385 procedure g_ResetDynlights ();
386 procedure g_AddDynLight (x, y, radius: Integer; r, g, b, a: Single);
387 procedure g_DynLightExplosion (x, y, radius: Integer; r, g, b: Single);
389 function conIsCheatsEnabled (): Boolean; inline;
390 function gPause (): Boolean; inline;
392 type (* private state *)
393 TEndCustomGameStat = record
394 PlayerStat: TPlayerStatArray;
395 TeamStat: TTeamStat;
396 GameTime: LongWord;
397 GameMode: Byte;
398 Map, MapName: String;
399 end;
401 TEndSingleGameStat = record
402 PlayerStat: Array [0..1] of record
403 Kills: Integer;
404 Secrets: Integer;
405 end;
406 GameTime: LongWord;
407 TwoPlayers: Boolean;
408 TotalSecrets: Integer;
409 end;
411 TLoadingStat = record
412 CurValue: Integer;
413 MaxValue: Integer;
414 ShowCount: Integer;
415 Msgs: Array of String;
416 NextMsg: Word;
417 PBarWasHere: Boolean; // did we draw a progress bar for this message?
418 end;
420 TDynLight = record
421 x, y, radius: Integer;
422 r, g, b, a: Single;
423 exploCount: Integer;
424 exploRadius: Integer;
425 end;
427 var (* private state *)
428 CustomStat: TEndCustomGameStat;
429 StatShotDone: Boolean;
430 StatFilename: string = ''; // used by stat screenshot to save with the same name as the csv
431 SingleStat: TEndSingleGameStat;
432 LoadingStat: TLoadingStat;
433 MessageText: String;
434 IsDrawStat: Boolean;
435 EndingGameCounter: Byte;
436 UPS: Word;
437 g_playerLight: Boolean;
438 g_dynLights: array of TDynLight = nil;
439 g_dynLightCount: Integer = 0;
440 EndPicPath: AnsiString; // full path, used by render
442 implementation
444 uses
445 {$IFDEF ENABLE_HOLMES}
446 g_holmes,
447 {$ENDIF}
448 {$IFNDEF HEADLESS}
449 r_render, g_menu, r_playermodel, g_system,
450 {$ENDIF}
451 e_res, g_window,
452 e_input, e_log, g_console, g_items, g_map, g_panel,
453 g_playermodel, g_gfx, g_options, Math,
454 g_triggers, g_monsters, e_sound, CONFIG,
455 g_language, g_net, g_phys,
456 ENet, e_msg, g_netmsg, g_netmaster,
457 sfs, wadreader;
459 var
460 charbuff: packed array [0..15] of AnsiChar = (
461 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
462 );
464 function Translit (const S: AnsiString): AnsiString;
465 var
466 i: Integer;
467 begin
468 Result := S;
469 for i := 1 to Length(Result) do
470 begin
471 case Result[i] of
472 #$C9: Result[i] := 'Q';
473 #$D6: Result[i] := 'W';
474 #$D3: Result[i] := 'E';
475 #$CA: Result[i] := 'R';
476 #$C5: Result[i] := 'T';
477 #$CD: Result[i] := 'Y';
478 #$C3: Result[i] := 'U';
479 #$D8: Result[i] := 'I';
480 #$D9: Result[i] := 'O';
481 #$C7: Result[i] := 'P';
482 #$D5: Result[i] := '['; //Chr(219);
483 #$DA: Result[i] := ']'; //Chr(221);
484 #$D4: Result[i] := 'A';
485 #$DB: Result[i] := 'S';
486 #$C2: Result[i] := 'D';
487 #$C0: Result[i] := 'F';
488 #$CF: Result[i] := 'G';
489 #$D0: Result[i] := 'H';
490 #$CE: Result[i] := 'J';
491 #$CB: Result[i] := 'K';
492 #$C4: Result[i] := 'L';
493 #$C6: Result[i] := ';'; //Chr(186);
494 #$DD: Result[i] := #39; //Chr(222);
495 #$DF: Result[i] := 'Z';
496 #$D7: Result[i] := 'X';
497 #$D1: Result[i] := 'C';
498 #$CC: Result[i] := 'V';
499 #$C8: Result[i] := 'B';
500 #$D2: Result[i] := 'N';
501 #$DC: Result[i] := 'M';
502 #$C1: Result[i] := ','; //Chr(188);
503 #$DE: Result[i] := '.'; //Chr(190);
504 end;
505 end;
506 end;
509 function CheckCheat (ct: TStrings_Locale; eofs: Integer=0): Boolean;
510 var
511 ls1, ls2: string;
512 begin
513 ls1 := CheatEng[ct];
514 ls2 := Translit(CheatRus[ct]);
515 if length(ls1) = 0 then ls1 := '~';
516 if length(ls2) = 0 then ls2 := '~';
517 result :=
518 (Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1)) = ls1) or
519 (Translit(Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1))) = ls1) or
520 (Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2)) = ls2) or
521 (Translit(Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2))) = ls2);
523 if ct = I_GAME_CHEAT_JETPACK then
524 begin
525 e_WriteLog('ls1: ['+ls1+']', MSG_NOTIFY);
526 e_WriteLog('ls2: ['+ls2+']', MSG_NOTIFY);
527 e_WriteLog('bf0: ['+Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1))+']', MSG_NOTIFY);
528 e_WriteLog('bf1: ['+Translit(Copy(charbuff, 17-Length(ls1)-eofs, Length(ls1)))+']', MSG_NOTIFY);
529 e_WriteLog('bf2: ['+Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2))+']', MSG_NOTIFY);
530 e_WriteLog('bf3: ['+Translit(Copy(charbuff, 17-Length(ls2)-eofs, Length(ls2)))+']', MSG_NOTIFY);
531 end;
533 end;
535 procedure Cheat ();
536 const
537 CHEAT_DAMAGE = 500;
538 label
539 Cheated;
540 var
541 s, s2: string;
542 c: ShortString;
543 a: Integer;
544 begin
546 if (not gGameOn) or (not gCheats) or ((gGameSettings.GameType <> GT_SINGLE) and
547 (gGameSettings.GameMode <> GM_COOP) and (not gDebugMode))
548 or g_Game_IsNet then Exit;
550 if not gGameOn then exit;
551 if not conIsCheatsEnabled then exit;
553 s := 'SOUND_GAME_RADIO';
555 //
556 if CheckCheat(I_GAME_CHEAT_GODMODE) then
557 begin
558 if gPlayer1 <> nil then gPlayer1.GodMode := not gPlayer1.GodMode;
559 if gPlayer2 <> nil then gPlayer2.GodMode := not gPlayer2.GodMode;
560 goto Cheated;
561 end;
562 // RAMBO
563 if CheckCheat(I_GAME_CHEAT_WEAPONS) then
564 begin
565 if gPlayer1 <> nil then gPlayer1.AllRulez(False);
566 if gPlayer2 <> nil then gPlayer2.AllRulez(False);
567 goto Cheated;
568 end;
569 // TANK
570 if CheckCheat(I_GAME_CHEAT_HEALTH) then
571 begin
572 if gPlayer1 <> nil then gPlayer1.AllRulez(True);
573 if gPlayer2 <> nil then gPlayer2.AllRulez(True);
574 goto Cheated;
575 end;
576 // IDDQD
577 if CheckCheat(I_GAME_CHEAT_DEATH) then
578 begin
579 if gPlayer1 <> nil then gPlayer1.Damage(CHEAT_DAMAGE, 0, 0, 0, HIT_TRAP);
580 if gPlayer2 <> nil then gPlayer2.Damage(CHEAT_DAMAGE, 0, 0, 0, HIT_TRAP);
581 s := 'SOUND_MONSTER_HAHA';
582 goto Cheated;
583 end;
584 //
585 if CheckCheat(I_GAME_CHEAT_DOORS) then
586 begin
587 g_Triggers_OpenAll();
588 goto Cheated;
589 end;
590 // GOODBYE
591 if CheckCheat(I_GAME_CHEAT_NEXTMAP) then
592 begin
593 if gTriggers <> nil then
594 for a := 0 to High(gTriggers) do
595 if gTriggers[a].TriggerType = TRIGGER_EXIT then
596 begin
597 gExitByTrigger := True;
598 //g_Game_ExitLevel(gTriggers[a].Data.MapName);
599 g_Game_ExitLevel(gTriggers[a].tgcMap);
600 Break;
601 end;
602 goto Cheated;
603 end;
604 //
605 s2 := Copy(charbuff, 15, 2);
606 if CheckCheat(I_GAME_CHEAT_CHANGEMAP, 2) and (s2[1] >= '0') and (s2[1] <= '9') and (s2[2] >= '0') and (s2[2] <= '9') then
607 begin
608 if g_Map_Exist(gGameSettings.WAD + ':\MAP' + s2) then
609 begin
610 c := 'MAP' + s2;
611 g_Game_ExitLevel(c);
612 end;
613 goto Cheated;
614 end;
615 //
616 if CheckCheat(I_GAME_CHEAT_FLY) then
617 begin
618 gFly := not gFly;
619 goto Cheated;
620 end;
621 // BULLFROG
622 if CheckCheat(I_GAME_CHEAT_JUMPS) then
623 begin
624 VEL_JUMP := 30-VEL_JUMP;
625 goto Cheated;
626 end;
627 // FORMULA1
628 if CheckCheat(I_GAME_CHEAT_SPEED) then
629 begin
630 MAX_RUNVEL := 32-MAX_RUNVEL;
631 goto Cheated;
632 end;
633 // CONDOM
634 if CheckCheat(I_GAME_CHEAT_SUIT) then
635 begin
636 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_SUIT);
637 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_SUIT);
638 goto Cheated;
639 end;
640 //
641 if CheckCheat(I_GAME_CHEAT_AIR) then
642 begin
643 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_OXYGEN);
644 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_OXYGEN);
645 goto Cheated;
646 end;
647 // PURELOVE
648 if CheckCheat(I_GAME_CHEAT_BERSERK) then
649 begin
650 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_MEDKIT_BLACK);
651 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_MEDKIT_BLACK);
652 goto Cheated;
653 end;
654 //
655 if CheckCheat(I_GAME_CHEAT_JETPACK) then
656 begin
657 if gPlayer1 <> nil then gPlayer1.GiveItem(ITEM_JETPACK);
658 if gPlayer2 <> nil then gPlayer2.GiveItem(ITEM_JETPACK);
659 goto Cheated;
660 end;
661 // CASPER
662 if CheckCheat(I_GAME_CHEAT_NOCLIP) then
663 begin
664 if gPlayer1 <> nil then gPlayer1.SwitchNoClip;
665 if gPlayer2 <> nil then gPlayer2.SwitchNoClip;
666 goto Cheated;
667 end;
668 //
669 if CheckCheat(I_GAME_CHEAT_NOTARGET) then
670 begin
671 if gPlayer1 <> nil then gPlayer1.NoTarget := not gPlayer1.NoTarget;
672 if gPlayer2 <> nil then gPlayer2.NoTarget := not gPlayer2.NoTarget;
673 goto Cheated;
674 end;
675 // INFERNO
676 if CheckCheat(I_GAME_CHEAT_NORELOAD) then
677 begin
678 if gPlayer1 <> nil then gPlayer1.NoReload := not gPlayer1.NoReload;
679 if gPlayer2 <> nil then gPlayer2.NoReload := not gPlayer2.NoReload;
680 goto Cheated;
681 end;
682 if CheckCheat(I_GAME_CHEAT_AIMLINE) then
683 begin
684 gAimLine := not gAimLine;
685 goto Cheated;
686 end;
687 if CheckCheat(I_GAME_CHEAT_AUTOMAP) then
688 begin
689 gShowMap := not gShowMap;
690 goto Cheated;
691 end;
692 Exit;
694 Cheated:
695 g_Sound_PlayEx(s);
696 end;
699 procedure KeyPress (K: Word);
700 {$IFNDEF HEADLESS}
701 var
702 Msg: g_gui.TMessage;
703 {$ENDIF}
704 begin
705 {$IFNDEF HEADLESS}
706 case K of
707 VK_ESCAPE: // <Esc>:
708 begin
709 if (g_ActiveWindow <> nil) then
710 begin
711 Msg.Msg := WM_KEYDOWN;
712 Msg.WParam := VK_ESCAPE;
713 g_ActiveWindow.OnMessage(Msg);
714 if (not g_Game_IsNet) and (g_ActiveWindow = nil) then g_Game_Pause(false); //Fn loves to do this
715 end
716 else if (gState <> STATE_FOLD) then
717 begin
718 if gGameOn or (gState = STATE_INTERSINGLE) or (gState = STATE_INTERCUSTOM) then
719 begin
720 g_Game_InGameMenu(True);
721 end
722 else if (gExit = 0) and (gState <> STATE_SLIST) then
723 begin
724 if (gState <> STATE_MENU) then
725 begin
726 if (NetMode <> NET_NONE) then
727 begin
728 g_Game_StopAllSounds(True);
729 g_Game_Free;
730 gState := STATE_MENU;
731 Exit;
732 end;
733 end;
734 g_GUI_ShowWindow('MainMenu');
735 g_Sound_PlayEx('MENU_OPEN');
736 end;
737 end;
738 end;
740 IK_F2, IK_F3, IK_F4, IK_F5, IK_F6, IK_F7, IK_F10:
741 begin // <F2> .. <F6> � <F12>
742 if gGameOn and (not gConsoleShow) and (not gChatShow) then
743 begin
744 while (g_ActiveWindow <> nil) do g_GUI_HideWindow(False);
745 if (not g_Game_IsNet) then g_Game_Pause(True);
746 case K of
747 IK_F2: g_Menu_Show_SaveMenu();
748 IK_F3: g_Menu_Show_LoadMenu();
749 IK_F4: g_Menu_Show_GameSetGame();
750 IK_F5: g_Menu_Show_OptionsVideo();
751 IK_F6: g_Menu_Show_OptionsSound();
752 IK_F7: g_Menu_Show_EndGameMenu();
753 IK_F10: g_Menu_Show_QuitGameMenu();
754 end;
755 end;
756 end;
758 else
759 begin
760 gJustChatted := False;
761 if gConsoleShow or gChatShow then
762 begin
763 g_Console_Control(K);
764 end
765 else if (g_ActiveWindow <> nil) then
766 begin
767 Msg.Msg := WM_KEYDOWN;
768 Msg.WParam := K;
769 g_ActiveWindow.OnMessage(Msg);
770 end
771 else if (gState = STATE_MENU) then
772 begin
773 g_GUI_ShowWindow('MainMenu');
774 g_Sound_PlayEx('MENU_OPEN');
775 end;
776 end;
777 end;
778 {$ENDIF}
779 end;
781 {$IFNDEF HEADLESS}
782 procedure CharPress (C: AnsiChar);
783 var
784 Msg: g_gui.TMessage;
785 a: Integer;
786 begin
787 if gConsoleShow or gChatShow then
788 begin
789 g_Console_Char(C)
790 end
791 else if (g_ActiveWindow <> nil) then
792 begin
793 Msg.Msg := WM_CHAR;
794 Msg.WParam := Ord(C);
795 g_ActiveWindow.OnMessage(Msg);
796 end
797 else
798 begin
799 for a := 0 to 14 do charbuff[a] := charbuff[a+1];
800 charbuff[15] := upcase1251(C);
801 Cheat();
802 end;
803 end;
804 {$ENDIF}
807 // ////////////////////////////////////////////////////////////////////////// //
808 function gPause (): Boolean; inline; begin result := gPauseMain or gPauseHolmes; end;
810 procedure g_ResetDynlights ();
811 var
812 lnum, idx: Integer;
813 begin
814 if not gwin_has_stencil then begin g_dynLightCount := 0; exit; end;
815 lnum := 0;
816 for idx := 0 to g_dynLightCount-1 do
817 begin
818 if g_dynLights[idx].exploCount = -666 then
819 begin
820 // skip it
821 end
822 else
823 begin
824 // explosion
825 Inc(g_dynLights[idx].exploCount);
826 if (g_dynLights[idx].exploCount < 10) then
827 begin
828 g_dynLights[idx].radius := g_dynLights[idx].exploRadius+g_dynLights[idx].exploCount*8;
829 g_dynLights[idx].a := 0.4+g_dynLights[idx].exploCount/10;
830 if (g_dynLights[idx].a > 0.8) then g_dynLights[idx].a := 0.8;
831 if lnum <> idx then g_dynLights[lnum] := g_dynLights[idx];
832 Inc(lnum);
833 end;
834 end;
835 end;
836 g_dynLightCount := lnum;
837 end;
839 procedure g_AddDynLight (x, y, radius: Integer; r, g, b, a: Single);
840 begin
841 if not gwin_has_stencil then exit;
842 if g_dynLightCount = length(g_dynLights) then SetLength(g_dynLights, g_dynLightCount+1024);
843 g_dynLights[g_dynLightCount].x := x;
844 g_dynLights[g_dynLightCount].y := y;
845 g_dynLights[g_dynLightCount].radius := radius;
846 g_dynLights[g_dynLightCount].r := r;
847 g_dynLights[g_dynLightCount].g := g;
848 g_dynLights[g_dynLightCount].b := b;
849 g_dynLights[g_dynLightCount].a := a;
850 g_dynLights[g_dynLightCount].exploCount := -666;
851 Inc(g_dynLightCount);
852 end;
854 procedure g_DynLightExplosion (x, y, radius: Integer; r, g, b: Single);
855 begin
856 if not gwin_has_stencil then exit;
857 if g_dynLightCount = length(g_dynLights) then SetLength(g_dynLights, g_dynLightCount+1024);
858 g_dynLights[g_dynLightCount].x := x;
859 g_dynLights[g_dynLightCount].y := y;
860 g_dynLights[g_dynLightCount].radius := 0;
861 g_dynLights[g_dynLightCount].exploRadius := radius;
862 g_dynLights[g_dynLightCount].r := r;
863 g_dynLights[g_dynLightCount].g := g;
864 g_dynLights[g_dynLightCount].b := b;
865 g_dynLights[g_dynLightCount].a := 0;
866 g_dynLights[g_dynLightCount].exploCount := 0;
867 Inc(g_dynLightCount);
868 end;
870 // ////////////////////////////////////////////////////////////////////////// //
871 function conIsCheatsEnabled (): Boolean; inline;
872 begin
873 result := false;
874 if g_Game_IsNet then exit;
875 if not gDebugMode then
876 begin
877 //if not gCheats then exit;
878 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
879 if not (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) then exit;
880 end;
881 result := true;
882 end;
884 // ////////////////////////////////////////////////////////////////////////// //
885 type
886 TParamStrValue = record
887 Name: String;
888 Value: String;
889 end;
891 TParamStrValues = Array of TParamStrValue;
893 const
894 INTER_ACTION_TEXT = 1;
895 INTER_ACTION_PIC = 2;
896 INTER_ACTION_MUSIC = 3;
898 var
899 UPSCounter: Word;
900 UPSTime: LongWord;
901 DataLoaded: Boolean = False;
902 MessageTime: Word;
903 MapList: SSArray = nil;
904 MapIndex: Integer = -1;
905 InterReadyTime: Integer = -1;
906 StatDate: string = '';
907 MegaWAD: record
908 info: TMegaWADInfo;
909 endpic: String;
910 endmus: String;
911 end;
912 InterText: record
913 lines: SSArray;
914 img: String;
915 cur_line: Integer;
916 cur_char: Integer;
917 counter: Integer;
918 endtext: Boolean;
919 end;
921 function Compare(a, b: TPlayerStat): Integer;
922 begin
923 if a.Spectator then Result := 1
924 else if b.Spectator then Result := -1
925 else if a.Frags < b.Frags then Result := 1
926 else if a.Frags > b.Frags then Result := -1
927 else if a.Deaths < b.Deaths then Result := -1
928 else if a.Deaths > b.Deaths then Result := 1
929 else if a.Kills < b.Kills then Result := -1
930 else Result := 1;
931 end;
933 procedure SortGameStat(var stat: TPlayerStatArray);
934 var
935 I, J: Integer;
936 T: TPlayerStat;
937 begin
938 if stat = nil then Exit;
940 for I := High(stat) downto Low(stat) do
941 for J := Low(stat) to High(stat) - 1 do
942 if Compare(stat[J], stat[J + 1]) = 1 then
943 begin
944 T := stat[J];
945 stat[J] := stat[J + 1];
946 stat[J + 1] := T;
947 end;
948 end;
950 // saves a shitty CSV containing the game stats passed to it
951 procedure SaveGameStat(Stat: TEndCustomGameStat; Path: string);
952 var
953 s: TextFile;
954 dir, fname, map, mode, etime: String;
955 I: Integer;
956 begin
957 try
958 dir := e_GetWriteableDir(StatsDirs);
959 // stats are placed in stats/yy/mm/dd/*.csv
960 fname := e_CatPath(dir, Path);
961 ForceDirectories(fname); // ensure yy/mm/dd exists within the stats dir
962 fname := e_CatPath(fname, StatFilename + '.csv');
963 AssignFile(s, fname);
964 try
965 Rewrite(s);
966 // line 1: stats ver, datetime, server name, map name, game mode, time limit, score limit, dmflags, game time, num players
967 if g_Game_IsNet then fname := NetServerName else fname := '';
968 map := g_ExtractWadNameNoPath(gMapInfo.Map) + ':/' + g_ExtractFileName(gMapInfo.Map);
969 mode := g_Game_ModeToText(Stat.GameMode);
970 etime := Format('%d:%.2d:%.2d', [
971 Stat.GameTime div 1000 div 3600,
972 (Stat.GameTime div 1000 div 60) mod 60,
973 Stat.GameTime div 1000 mod 60
974 ]);
975 WriteLn(s, 'stats_ver,datetime,server,map,mode,timelimit,scorelimit,dmflags,time,num_players');
976 WriteLn(s, Format('%d,%s,%s,%s,%s,%u,%u,%u,%s,%d', [
977 STATFILE_VERSION,
978 StatDate,
979 dquoteStr(fname),
980 dquoteStr(map),
981 mode,
982 gGameSettings.TimeLimit,
983 gGameSettings.GoalLimit,
984 gGameSettings.Options,
985 etime,
986 Length(Stat.PlayerStat)
987 ]));
988 // line 2: game specific shit
989 // if it's a team game: red score, blue score
990 // if it's a coop game: monsters killed, monsters total, secrets found, secrets total
991 // otherwise nothing
992 if Stat.GameMode in [GM_TDM, GM_CTF] then
993 WriteLn(s,
994 Format('red_score,blue_score' + LineEnding + '%d,%d', [Stat.TeamStat[TEAM_RED].Goals, Stat.TeamStat[TEAM_BLUE].Goals]))
995 else if Stat.GameMode in [GM_COOP, GM_SINGLE] then
996 WriteLn(s,
997 Format('mon_killed,mon_total,secrets_found,secrets_total' + LineEnding + '%d,%d,%d,%d',[gCoopMonstersKilled, gTotalMonsters, gCoopSecretsFound, gSecretsCount]));
998 // lines 3-...: team, player name, frags, deaths
999 WriteLn(s, 'team,name,frags,deaths');
1000 for I := Low(Stat.PlayerStat) to High(Stat.PlayerStat) do
1001 with Stat.PlayerStat[I] do
1002 WriteLn(s, Format('%d,%s,%d,%d', [Team, dquoteStr(Name), Frags, Deaths]));
1003 except
1004 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_WRITE], [fname]));
1005 end;
1006 except
1007 g_Console_Add('could not create gamestats file "' + fname + '"');
1008 end;
1009 CloseFile(s);
1010 end;
1012 function g_Game_ModeToText(Mode: Byte): string;
1013 begin
1014 Result := '';
1015 case Mode of
1016 GM_DM: Result := _lc[I_MENU_GAME_TYPE_DM];
1017 GM_TDM: Result := _lc[I_MENU_GAME_TYPE_TDM];
1018 GM_CTF: Result := _lc[I_MENU_GAME_TYPE_CTF];
1019 GM_COOP: Result := _lc[I_MENU_GAME_TYPE_COOP];
1020 GM_SINGLE: Result := _lc[I_MENU_GAME_TYPE_SINGLE];
1021 end;
1022 end;
1024 function g_Game_TextToMode(Mode: string): Byte;
1025 begin
1026 Result := GM_NONE;
1027 Mode := UpperCase(Mode);
1028 if Mode = _lc[I_MENU_GAME_TYPE_DM] then
1029 begin
1030 Result := GM_DM;
1031 Exit;
1032 end;
1033 if Mode = _lc[I_MENU_GAME_TYPE_TDM] then
1034 begin
1035 Result := GM_TDM;
1036 Exit;
1037 end;
1038 if Mode = _lc[I_MENU_GAME_TYPE_CTF] then
1039 begin
1040 Result := GM_CTF;
1041 Exit;
1042 end;
1043 if Mode = _lc[I_MENU_GAME_TYPE_COOP] then
1044 begin
1045 Result := GM_COOP;
1046 Exit;
1047 end;
1048 if Mode = _lc[I_MENU_GAME_TYPE_SINGLE] then
1049 begin
1050 Result := GM_SINGLE;
1051 Exit;
1052 end;
1053 end;
1055 function g_Game_IsNet(): Boolean;
1056 begin
1057 Result := (gGameSettings.GameType in [GT_SERVER, GT_CLIENT]);
1058 end;
1060 function g_Game_IsServer(): Boolean;
1061 begin
1062 Result := (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM, GT_SERVER]);
1063 end;
1065 function g_Game_IsClient(): Boolean;
1066 begin
1067 Result := (gGameSettings.GameType = GT_CLIENT);
1068 end;
1070 function g_Game_GetMegaWADInfo(WAD: String): TMegaWADInfo;
1071 var
1072 w: TWADFile;
1073 cfg: TConfig;
1074 p: Pointer;
1075 len: Integer;
1076 begin
1077 Result.name := ExtractFileName(WAD);
1078 Result.description := '';
1079 Result.author := '';
1081 w := TWADFile.Create();
1082 w.ReadFile(WAD);
1084 if not w.GetResource('INTERSCRIPT', p, len) then
1085 begin
1086 w.Free();
1087 Exit;
1088 end;
1090 cfg := TConfig.CreateMem(p, len);
1091 Result.name := cfg.ReadStr('megawad', 'name', ExtractFileName(WAD));
1092 Result.description := cfg.ReadStr('megawad', 'description', '');
1093 Result.author := cfg.ReadStr('megawad', 'author', '');
1094 Result.pic := cfg.ReadStr('megawad', 'pic', '');
1095 cfg.Free();
1097 FreeMem(p);
1098 end;
1100 procedure g_Game_FreeWAD;
1101 begin
1102 EndPicPath := '';
1103 g_Sound_Delete('MUSIC_endmus');
1104 ZeroMemory(@MegaWAD, SizeOf(MegaWAD));
1105 gGameSettings.WAD := '';
1106 end;
1108 procedure g_Game_LoadWAD(WAD: string);
1109 var
1110 w: TWADFile;
1111 cfg: TConfig;
1112 p: Pointer;
1113 len: Integer;
1114 s: AnsiString;
1115 begin
1116 g_Game_FreeWAD();
1117 gGameSettings.WAD := WAD;
1118 if not (gGameSettings.GameMode in [GM_COOP, GM_SINGLE]) then
1119 Exit;
1121 MegaWAD.info := g_Game_GetMegaWADInfo(WAD);
1123 w := TWADFile.Create();
1124 w.ReadFile(WAD);
1126 if not w.GetResource('INTERSCRIPT', p, len) then
1127 begin
1128 w.Free();
1129 Exit;
1130 end;
1132 cfg := TConfig.CreateMem(p, len);
1134 EndPicPath := '';
1135 MegaWAD.endpic := cfg.ReadStr('megawad', 'endpic', '');
1136 if MegaWAD.endpic <> '' then
1137 EndPicPath := e_GetResourcePath(WadDirs, MegaWAD.endpic, WAD);
1139 MegaWAD.endmus := cfg.ReadStr('megawad', 'endmus', 'Standart.wad:D2DMUS\КОНЕЦ');
1140 if MegaWAD.endmus <> '' then
1141 begin
1142 s := e_GetResourcePath(WadDirs, MegaWAD.endmus, WAD);
1143 g_Sound_CreateWADEx('MUSIC_endmus', s, True);
1144 end;
1146 cfg.Free();
1147 FreeMem(p);
1148 w.Free();
1149 end;
1151 {procedure start_trigger(t: string);
1152 begin
1153 end;
1155 function next_trigger(): Boolean;
1156 begin
1157 end;}
1159 procedure DisableCheats();
1160 begin
1161 MAX_RUNVEL := 8;
1162 VEL_JUMP := 10;
1163 gFly := False;
1165 if gPlayer1 <> nil then gPlayer1.GodMode := False;
1166 if gPlayer2 <> nil then gPlayer2.GodMode := False;
1167 if gPlayer1 <> nil then gPlayer1.NoTarget := False;
1168 if gPlayer2 <> nil then gPlayer2.NoTarget := False;
1170 {$IF DEFINED(D2F_DEBUG)}
1171 if gPlayer1 <> nil then gPlayer1.NoTarget := True;
1172 gAimLine := g_dbg_aimline_on;
1173 {$ENDIF}
1174 end;
1176 procedure g_Game_ExecuteEvent(Name: String);
1177 var
1178 a: Integer;
1179 begin
1180 if Name = '' then
1181 Exit;
1182 if gEvents = nil then
1183 Exit;
1184 for a := 0 to High(gEvents) do
1185 if gEvents[a].Name = Name then
1186 begin
1187 if gEvents[a].Command <> '' then
1188 g_Console_Process(gEvents[a].Command, True);
1189 break;
1190 end;
1191 end;
1193 function g_Game_DelayEvent(DEType: Byte; Time: LongWord; Num: Integer = 0; Str: String = ''): Integer;
1194 var
1195 a, n: Integer;
1196 begin
1197 n := -1;
1198 if gDelayedEvents <> nil then
1199 for a := 0 to High(gDelayedEvents) do
1200 if not gDelayedEvents[a].Pending then
1201 begin
1202 n := a;
1203 break;
1204 end;
1205 if n = -1 then
1206 begin
1207 SetLength(gDelayedEvents, Length(gDelayedEvents) + 1);
1208 n := High(gDelayedEvents);
1209 end;
1210 gDelayedEvents[n].Pending := True;
1211 gDelayedEvents[n].DEType := DEType;
1212 gDelayedEvents[n].DENum := Num;
1213 gDelayedEvents[n].DEStr := Str;
1214 if DEType = DE_GLOBEVENT then
1215 gDelayedEvents[n].Time := (GetTickCount64() {div 1000}) + Time
1216 else
1217 gDelayedEvents[n].Time := gTime + Time;
1218 Result := n;
1219 end;
1221 procedure EndGame();
1222 var
1223 a: Integer;
1224 FileName: string;
1225 t: TDateTime;
1226 begin
1227 if g_Game_IsNet and g_Game_IsServer then
1228 MH_SEND_GameEvent(NET_EV_MAPEND, Byte(gMissionFailed));
1230 // Стоп игра:
1231 gPauseMain := false;
1232 gPauseHolmes := false;
1233 gGameOn := false;
1235 g_Game_StopAllSounds(False);
1237 MessageTime := 0;
1238 MessageText := '';
1240 EndingGameCounter := 0;
1242 {$IFNDEF HEADLESS}
1243 g_ActiveWindow := nil;
1244 {$ENDIF}
1246 gLMSRespawn := LMS_RESPAWN_NONE;
1247 gLMSRespawnTime := 0;
1249 case gExit of
1250 EXIT_SIMPLE: // Выход через меню или конец теста
1251 begin
1252 g_Game_Free();
1253 if gMapOnce then
1254 begin // Это был тест
1255 g_Game_Quit();
1256 end
1257 else
1258 begin // Выход в главное меню
1259 {$IFDEF HEADLESS}
1260 gState := STATE_MENU; // ???
1261 {$ELSE}
1262 gMusic.SetByName('MUSIC_MENU');
1263 gMusic.Play();
1264 if gState <> STATE_SLIST then
1265 begin
1266 g_GUI_ShowWindow('MainMenu');
1267 gState := STATE_MENU;
1268 end else
1269 begin
1270 // Обновляем список серверов
1271 slReturnPressed := True;
1272 if g_Net_Slist_Fetch(slCurrent) then
1273 begin
1274 if slCurrent = nil then
1275 slWaitStr := _lc[I_NET_SLIST_NOSERVERS];
1276 end
1277 else
1278 slWaitStr := _lc[I_NET_SLIST_ERROR];
1279 g_Serverlist_GenerateTable(slCurrent, slTable);
1280 end;
1281 {$ENDIF}
1282 g_Game_ExecuteEvent('ongameend');
1283 end;
1284 end;
1286 EXIT_RESTART: // Начать уровень сначала
1287 begin
1288 if not g_Game_IsClient then g_Game_Restart();
1289 end;
1291 EXIT_ENDLEVELCUSTOM: // Закончился уровень в Своей игре
1292 begin
1293 // Статистика Своей игры:
1294 FileName := g_ExtractWadName(gMapInfo.Map);
1296 CustomStat.GameTime := gTime;
1297 CustomStat.Map := ExtractFileName(FileName)+':'+g_ExtractFileName(gMapInfo.Map); //ResName;
1298 CustomStat.MapName := gMapInfo.Name;
1299 CustomStat.GameMode := gGameSettings.GameMode;
1300 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
1301 CustomStat.TeamStat := gTeamStat;
1303 CustomStat.PlayerStat := nil;
1305 // Статистика игроков:
1306 if gPlayers <> nil then
1307 begin
1308 for a := 0 to High(gPlayers) do
1309 if gPlayers[a] <> nil then
1310 begin
1311 SetLength(CustomStat.PlayerStat, Length(CustomStat.PlayerStat)+1);
1312 with CustomStat.PlayerStat[High(CustomStat.PlayerStat)] do
1313 begin
1314 Num := a;
1315 Name := gPlayers[a].Name;
1316 Frags := gPlayers[a].Frags;
1317 Deaths := gPlayers[a].Death;
1318 Kills := gPlayers[a].Kills;
1319 Team := gPlayers[a].Team;
1320 Color := gPlayers[a].Model.Color;
1321 Spectator := gPlayers[a].FSpectator;
1322 end;
1323 end;
1325 SortGameStat(CustomStat.PlayerStat);
1327 if (gSaveStats or gScreenshotStats) and (Length(CustomStat.PlayerStat) > 1) then
1328 begin
1329 t := Now;
1330 if g_Game_IsNet then StatFilename := NetServerName else StatFilename := 'local';
1331 StatDate := FormatDateTime('yymmdd_hhnnss', t);
1332 StatFilename := StatFilename + '_' + CustomStat.Map + '_' + g_Game_ModeToText(CustomStat.GameMode);
1333 StatFilename := sanitizeFilename(StatFilename) + '_' + StatDate;
1334 if gSaveStats then
1335 SaveGameStat(CustomStat, FormatDateTime('yyyy"/"mm"/"dd', t));
1336 end;
1338 StatShotDone := False;
1339 end;
1341 g_Game_ExecuteEvent('onmapend');
1342 if not g_Game_IsClient then g_Player_ResetReady;
1343 gInterReadyCount := 0;
1345 // Затухающий экран:
1346 EndingGameCounter := 255;
1347 gState := STATE_FOLD;
1348 gInterTime := 0;
1349 if gDefInterTime < 0 then
1350 gInterEndTime := IfThen((gGameSettings.GameType = GT_SERVER) and (gPlayer1 = nil), 15000, 25000)
1351 else
1352 gInterEndTime := gDefInterTime * 1000;
1353 end;
1355 EXIT_ENDLEVELSINGLE: // Закончился уровень в Одиночной игре
1356 begin
1357 // Статистика Одиночной игры:
1358 SingleStat.GameTime := gTime;
1359 SingleStat.TwoPlayers := gPlayer2 <> nil;
1360 SingleStat.TotalSecrets := gSecretsCount;
1361 // Статистика первого игрока:
1362 SingleStat.PlayerStat[0].Kills := gPlayer1.MonsterKills;
1363 SingleStat.PlayerStat[0].Secrets := gPlayer1.Secrets;
1364 // Статистика второго игрока (если есть):
1365 if SingleStat.TwoPlayers then
1366 begin
1367 SingleStat.PlayerStat[1].Kills := gPlayer2.MonsterKills;
1368 SingleStat.PlayerStat[1].Secrets := gPlayer2.Secrets;
1369 end;
1371 g_Game_ExecuteEvent('onmapend');
1373 // Есть еще карты:
1374 if gNextMap <> '' then
1375 begin
1376 gMusic.SetByName('MUSIC_INTERMUS');
1377 gMusic.Play();
1378 gState := STATE_INTERSINGLE;
1379 e_UnpressAllKeys();
1381 g_Game_ExecuteEvent('oninter');
1382 end
1383 else // Больше нет карт
1384 begin
1385 // Затухающий экран:
1386 EndingGameCounter := 255;
1387 gState := STATE_FOLD;
1388 end;
1389 end;
1390 end;
1392 // Окончание обработано:
1393 if gExit <> EXIT_QUIT then
1394 gExit := 0;
1395 end;
1397 procedure g_Game_Init();
1398 begin
1399 gExit := 0;
1400 gMapToDelete := '';
1401 gTempDelete := False;
1403 sfsGCDisable(); // temporary disable removing of temporary volumes
1405 try
1406 g_Game_ClearLoading();
1407 g_Game_SetLoadingText(Format('Doom 2D: Forever %s', [GAME_VERSION]), 0, False);
1408 g_Game_SetLoadingText('', 0, False);
1410 // g_Game_SetLoadingText(_lc[I_LOAD_MODELS], 0, False);
1412 gGameOn := false;
1413 gPauseMain := false;
1414 gPauseHolmes := false;
1415 gTime := 0;
1417 {e_MouseInfo.Accel := 1.0;}
1419 g_Game_SetLoadingText(_lc[I_LOAD_GAME_DATA], 0, False);
1420 g_Game_LoadData();
1422 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
1423 g_Sound_CreateWADEx('MUSIC_INTERMUS', GameWAD+':MUSIC\INTERMUS', True);
1424 g_Sound_CreateWADEx('MUSIC_MENU', GameWAD+':MUSIC\MENU', True);
1425 g_Sound_CreateWADEx('MUSIC_ROUNDMUS', GameWAD+':MUSIC\ROUNDMUS', True, True);
1426 g_Sound_CreateWADEx('MUSIC_STDENDMUS', GameWAD+':MUSIC\ENDMUS', True);
1428 gMusic := TMusic.Create();
1429 gMusic.SetByName('MUSIC_MENU');
1430 gMusic.Play();
1432 gGameSettings.WarmupTime := 30;
1434 gState := STATE_MENU;
1436 SetLength(gEvents, 6);
1437 gEvents[0].Name := 'ongamestart';
1438 gEvents[1].Name := 'ongameend';
1439 gEvents[2].Name := 'onmapstart';
1440 gEvents[3].Name := 'onmapend';
1441 gEvents[4].Name := 'oninter';
1442 gEvents[5].Name := 'onwadend';
1443 finally
1444 sfsGCEnable(); // enable releasing unused volumes
1445 end;
1446 end;
1448 procedure g_Game_Free(freeTextures: Boolean=true);
1449 begin
1450 if NetMode = NET_CLIENT then g_Net_Disconnect();
1451 if NetMode = NET_SERVER then g_Net_Host_Die();
1453 g_Map_Free(freeTextures);
1454 g_Player_Free();
1455 g_Player_RemoveAllCorpses();
1457 gGameSettings.GameType := GT_NONE;
1458 if gGameSettings.GameMode = GM_SINGLE then
1459 gGameSettings.GameMode := GM_DM;
1460 gSwitchGameMode := gGameSettings.GameMode;
1462 gChatShow := False;
1463 gExitByTrigger := False;
1464 end;
1466 function IsActivePlayer(p: TPlayer): Boolean;
1467 begin
1468 Result := False;
1469 if p = nil then
1470 Exit;
1471 Result := (not p.FDummy) and (not p.FSpectator);
1472 end;
1474 function GetActivePlayerID_Next(Skip: Integer = -1): Integer;
1475 var
1476 a, idx: Integer;
1477 ids: Array of Word;
1478 begin
1479 Result := -1;
1480 if gPlayers = nil then
1481 Exit;
1482 SetLength(ids, 0);
1483 idx := -1;
1484 for a := Low(gPlayers) to High(gPlayers) do
1485 if IsActivePlayer(gPlayers[a]) then
1486 begin
1487 SetLength(ids, Length(ids) + 1);
1488 ids[High(ids)] := gPlayers[a].UID;
1489 if gPlayers[a].UID = Skip then
1490 idx := High(ids);
1491 end;
1492 if Length(ids) = 0 then
1493 Exit;
1494 if idx = -1 then
1495 Result := ids[0]
1496 else
1497 Result := ids[(idx + 1) mod Length(ids)];
1498 end;
1500 function GetActivePlayerID_Prev(Skip: Integer = -1): Integer;
1501 var
1502 a, idx: Integer;
1503 ids: Array of Word;
1504 begin
1505 Result := -1;
1506 if gPlayers = nil then
1507 Exit;
1508 SetLength(ids, 0);
1509 idx := -1;
1510 for a := Low(gPlayers) to High(gPlayers) do
1511 if IsActivePlayer(gPlayers[a]) then
1512 begin
1513 SetLength(ids, Length(ids) + 1);
1514 ids[High(ids)] := gPlayers[a].UID;
1515 if gPlayers[a].UID = Skip then
1516 idx := High(ids);
1517 end;
1518 if Length(ids) = 0 then
1519 Exit;
1520 if idx = -1 then
1521 Result := ids[Length(ids) - 1]
1522 else
1523 Result := ids[(Length(ids) - 1 + idx) mod Length(ids)];
1524 end;
1526 function GetActivePlayerID_Random(Skip: Integer = -1): Integer;
1527 var
1528 a, idx: Integer;
1529 ids: Array of Word;
1530 begin
1531 Result := -1;
1532 if gPlayers = nil then
1533 Exit;
1534 SetLength(ids, 0);
1535 idx := -1;
1536 for a := Low(gPlayers) to High(gPlayers) do
1537 if IsActivePlayer(gPlayers[a]) then
1538 begin
1539 SetLength(ids, Length(ids) + 1);
1540 ids[High(ids)] := gPlayers[a].UID;
1541 if gPlayers[a].UID = Skip then
1542 idx := High(ids);
1543 end;
1544 if Length(ids) = 0 then
1545 Exit;
1546 if Length(ids) = 1 then
1547 begin
1548 Result := ids[0];
1549 Exit;
1550 end;
1551 Result := ids[Random(Length(ids))];
1552 a := 10;
1553 while (idx <> -1) and (Result = Skip) and (a > 0) do
1554 begin
1555 Result := ids[Random(Length(ids))];
1556 Dec(a);
1557 end;
1558 end;
1560 function GetRandomSpectMode(Current: Byte): Byte;
1561 label
1562 retry;
1563 begin
1564 Result := Current;
1565 retry:
1566 case Random(7) of
1567 0: Result := SPECT_STATS;
1568 1: Result := SPECT_MAPVIEW;
1569 2: Result := SPECT_MAPVIEW;
1570 3: Result := SPECT_PLAYERS;
1571 4: Result := SPECT_PLAYERS;
1572 5: Result := SPECT_PLAYERS;
1573 6: Result := SPECT_PLAYERS;
1574 end;
1575 if (Current in [SPECT_STATS, SPECT_MAPVIEW]) and (Current = Result) then
1576 goto retry;
1577 end;
1579 procedure ProcessPlayerControls (plr: TPlayer; p: Integer; var MoveButton: Byte);
1580 var
1581 time: Word;
1582 strafeDir: Byte;
1583 i: Integer;
1584 begin
1585 if (plr = nil) then exit;
1586 if (p = 2) then time := 1000 else time := 1;
1587 strafeDir := MoveButton shr 4;
1588 MoveButton := MoveButton and $0F;
1590 if gPlayerAction[p, ACTION_MOVELEFT] and (not gPlayerAction[p, ACTION_MOVERIGHT]) then
1591 MoveButton := 1 // Нажата только "Влево"
1592 else if (not gPlayerAction[p, ACTION_MOVELEFT]) and gPlayerAction[p, ACTION_MOVERIGHT] then
1593 MoveButton := 2 // Нажата только "Вправо"
1594 else if (not gPlayerAction[p, ACTION_MOVELEFT]) and (not gPlayerAction[p, ACTION_MOVERIGHT]) then
1595 MoveButton := 0; // Не нажаты ни "Влево", ни "Вправо"
1597 // Сейчас или раньше были нажаты "Влево"/"Вправо" => передаем игроку:
1598 if MoveButton = 1 then
1599 plr.PressKey(KEY_LEFT, time)
1600 else if MoveButton = 2 then
1601 plr.PressKey(KEY_RIGHT, time);
1603 // if we have "strafe" key, turn off old strafe mechanics
1604 if gPlayerAction[p, ACTION_STRAFE] then
1605 begin
1606 // new strafe mechanics
1607 if (strafeDir = 0) then
1608 strafeDir := MoveButton; // start strafing
1609 // now set direction according to strafe (reversed)
1610 if (strafeDir = 2) then
1611 plr.SetDirection(TDirection.D_LEFT)
1612 else if (strafeDir = 1) then
1613 plr.SetDirection(TDirection.D_RIGHT)
1614 end
1615 else
1616 begin
1617 strafeDir := 0; // not strafing anymore
1618 // Раньше была нажата "Вправо", а сейчас "Влево" => бежим вправо, смотрим влево:
1619 if (MoveButton = 2) and gPlayerAction[p, ACTION_MOVELEFT] then
1620 plr.SetDirection(TDirection.D_LEFT)
1621 // Раньше была нажата "Влево", а сейчас "Вправо" => бежим влево, смотрим вправо:
1622 else if (MoveButton = 1) and gPlayerAction[p, ACTION_MOVERIGHT] then
1623 plr.SetDirection(TDirection.D_RIGHT)
1624 // Что-то было нажато и не изменилось => куда бежим, туда и смотрим:
1625 else if MoveButton <> 0 then
1626 plr.SetDirection(TDirection(MoveButton-1))
1627 end;
1629 // fix movebutton state
1630 MoveButton := MoveButton or (strafeDir shl 4);
1632 // Остальные клавиши:
1633 if gPlayerAction[p, ACTION_JUMP] then plr.PressKey(KEY_JUMP, time);
1634 if gPlayerAction[p, ACTION_LOOKUP] then plr.PressKey(KEY_UP, time);
1635 if gPlayerAction[p, ACTION_LOOKDOWN] then plr.PressKey(KEY_DOWN, time);
1636 if gPlayerAction[p, ACTION_ATTACK] then plr.PressKey(KEY_FIRE);
1637 if gPlayerAction[p, ACTION_WEAPNEXT] then plr.PressKey(KEY_NEXTWEAPON);
1638 if gPlayerAction[p, ACTION_WEAPPREV] then plr.PressKey(KEY_PREVWEAPON);
1639 if gPlayerAction[p, ACTION_ACTIVATE] then plr.PressKey(KEY_OPEN);
1641 gPlayerAction[p, ACTION_WEAPNEXT] := False; // HACK, remove after readyweaon&pendinweapon implementation
1642 gPlayerAction[p, ACTION_WEAPPREV] := False; // HACK, remove after readyweaon&pendinweapon implementation
1644 for i := WP_FIRST to WP_LAST do
1645 begin
1646 if gSelectWeapon[p, i] then
1647 begin
1648 plr.QueueWeaponSwitch(i); // all choices are passed there, and god will take the best
1649 gSelectWeapon[p, i] := False
1650 end
1651 end;
1653 {$IFNDEF HEADLESS}
1654 // HACK: add dynlight here
1655 if gwin_k8_enable_light_experiments then
1656 begin
1657 if e_KeyPressed(IK_F8) and gGameOn and (not gConsoleShow) and (g_ActiveWindow = nil) then
1658 begin
1659 g_playerLight := true;
1660 end;
1661 if e_KeyPressed(IK_F9) and gGameOn and (not gConsoleShow) and (g_ActiveWindow = nil) then
1662 begin
1663 g_playerLight := false;
1664 end;
1665 end;
1667 if gwin_has_stencil and g_playerLight then g_AddDynLight(plr.GameX+32, plr.GameY+40, 128, 1, 1, 0, 0.6);
1668 {$ENDIF}
1669 end;
1671 // HACK: don't have a "key was pressed" function
1672 procedure InterReady();
1673 begin
1674 if InterReadyTime > gTime then Exit;
1675 InterReadyTime := gTime + 3000;
1676 MC_SEND_CheatRequest(NET_CHEAT_READY);
1677 end;
1679 procedure g_Game_PreUpdate();
1680 begin
1681 // these are in separate PreUpdate functions because they can interact during Update()
1682 // and are synced over the net
1683 // we don't care that much about corpses and gibs
1684 g_Player_PreUpdate();
1685 g_Monsters_PreUpdate();
1686 g_Items_PreUpdate();
1687 g_Weapon_PreUpdate();
1688 end;
1690 procedure g_Game_Update();
1691 var
1692 {$IFNDEF HEADLESS}
1693 Msg: g_gui.TMessage;
1694 w: Word;
1695 {$ENDIF}
1696 Time: Int64;
1697 a: Byte;
1698 i, b: Integer;
1700 function sendMonsPos (mon: TMonster): Boolean;
1701 begin
1702 result := false; // don't stop
1703 // this will also reset "need-send" flag
1704 if mon.gncNeedSend then
1705 begin
1706 MH_SEND_MonsterPos(mon.UID);
1707 end
1708 else if (mon.MonsterType = MONSTER_BARREL) then
1709 begin
1710 if (mon.GameVelX <> 0) or (mon.GameVelY <> 0) then MH_SEND_MonsterPos(mon.UID);
1711 end
1712 else if (mon.MonsterState <> MONSTATE_SLEEP) then
1713 begin
1714 if (mon.MonsterState <> MONSTATE_DEAD) or (mon.GameVelX <> 0) or (mon.GameVelY <> 0) then MH_SEND_MonsterPos(mon.UID);
1715 end;
1716 end;
1718 function sendMonsPosUnexpected (mon: TMonster): Boolean;
1719 begin
1720 result := false; // don't stop
1721 // this will also reset "need-send" flag
1722 if mon.gncNeedSend then MH_SEND_MonsterPos(mon.UID);
1723 end;
1725 var
1726 reliableUpdate: Boolean;
1727 begin
1728 g_ResetDynlights();
1729 framePool.reset();
1731 // Пора выключать игру:
1732 if gExit = EXIT_QUIT then
1733 Exit;
1734 // Игра закончилась - обрабатываем:
1735 if gExit <> 0 then
1736 begin
1737 EndGame();
1738 if gExit = EXIT_QUIT then
1739 Exit;
1740 end;
1742 // Читаем клавиатуру и джойстик, если окно активно
1743 // no need to, as we'll do it in event handler
1745 // Обновляем консоль (движение и сообщения):
1746 g_Console_Update();
1748 if (NetMode = NET_NONE) and (g_Game_IsNet) and (gGameOn or (gState in [STATE_FOLD, STATE_INTERCUSTOM])) then
1749 begin
1750 gExit := EXIT_SIMPLE;
1751 EndGame();
1752 Exit;
1753 end;
1755 // process master server communications
1756 g_Net_Slist_Pulse();
1758 case gState of
1759 STATE_INTERSINGLE, // Статистка после прохождения уровня в Одиночной игре
1760 STATE_INTERCUSTOM, // Статистка после прохождения уровня в Своей игре
1761 STATE_INTERTEXT, // Текст между уровнями
1762 STATE_INTERPIC: // Картинка между уровнями
1763 begin
1764 if g_Game_IsNet and g_Game_IsServer then
1765 begin
1766 gInterTime := gInterTime + GAME_TICK;
1767 a := Min((gInterEndTime - gInterTime) div 1000 + 1, 255);
1768 if a <> gServInterTime then
1769 begin
1770 gServInterTime := a;
1771 MH_SEND_TimeSync(gServInterTime);
1772 end;
1773 end;
1775 if (not g_Game_IsClient) and
1779 e_KeyPressed(IK_RETURN) or e_KeyPressed(IK_KPRETURN) or e_KeyPressed(IK_SPACE) or
1780 e_KeyPressed(VK_FIRE) or e_KeyPressed(VK_OPEN) or
1781 e_KeyPressed(JOY0_ATTACK) or e_KeyPressed(JOY1_ATTACK) or
1782 e_KeyPressed(JOY2_ATTACK) or e_KeyPressed(JOY3_ATTACK)
1784 and (not gJustChatted) and (not gConsoleShow) and (not gChatShow)
1785 {$IFNDEF HEADLESS}
1786 and (g_ActiveWindow = nil)
1787 {$ENDIF}
1789 or (g_Game_IsNet and ((gInterTime > gInterEndTime) or ((gInterReadyCount >= NetClientCount) and (NetClientCount > 0))))
1791 then
1792 begin // Нажали <Enter>/<Пробел> или прошло достаточно времени:
1793 g_Game_StopAllSounds(True);
1795 if gMapOnce then // Это был тест
1796 gExit := EXIT_SIMPLE
1797 else
1798 if gNextMap <> '' then // Переходим на следующую карту
1799 g_Game_ChangeMap(gNextMap)
1800 else // Следующей карты нет
1801 begin
1802 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER] then
1803 begin
1804 // Выход в главное меню:
1805 g_Game_Free;
1806 {$IFNDEF HEADLESS}
1807 g_GUI_ShowWindow('MainMenu');
1808 gMusic.SetByName('MUSIC_MENU');
1809 gMusic.Play();
1810 {$ENDIF}
1811 gState := STATE_MENU;
1812 end else
1813 begin
1814 // Финальная картинка:
1815 g_Game_ExecuteEvent('onwadend');
1816 g_Game_Free();
1817 if not gMusic.SetByName('MUSIC_endmus') then
1818 gMusic.SetByName('MUSIC_STDENDMUS');
1819 gMusic.Play();
1820 gState := STATE_ENDPIC;
1821 end;
1822 g_Game_ExecuteEvent('ongameend');
1823 end;
1825 Exit;
1826 end
1827 else if g_Game_IsClient and
1830 e_KeyPressed(IK_RETURN) or e_KeyPressed(IK_KPRETURN) or e_KeyPressed(IK_SPACE) or
1831 e_KeyPressed(VK_FIRE) or e_KeyPressed(VK_OPEN) or
1832 e_KeyPressed(JOY0_ATTACK) or e_KeyPressed(JOY1_ATTACK) or
1833 e_KeyPressed(JOY2_ATTACK) or e_KeyPressed(JOY3_ATTACK)
1835 and (not gJustChatted) and (not gConsoleShow) and (not gChatShow)
1836 {$IFNDEF HEADLESS}
1837 and (g_ActiveWindow = nil)
1838 {$ENDIF}
1840 then
1841 begin
1842 // ready / unready
1843 InterReady();
1844 end;
1846 if gState = STATE_INTERTEXT then
1847 if InterText.counter > 0 then
1848 InterText.counter := InterText.counter - 1;
1849 end;
1851 STATE_FOLD: // Затухание экрана
1852 begin
1853 if EndingGameCounter = 0 then
1854 begin
1855 // Закончился уровень в Своей игре:
1856 if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
1857 begin
1858 InterReadyTime := -1;
1859 if gLastMap and (gGameSettings.GameMode = GM_COOP) then
1860 begin
1861 g_Game_ExecuteEvent('onwadend');
1862 if not gMusic.SetByName('MUSIC_endmus') then
1863 gMusic.SetByName('MUSIC_STDENDMUS');
1864 end
1865 else
1866 gMusic.SetByName('MUSIC_ROUNDMUS');
1868 gMusic.Play();
1869 gState := STATE_INTERCUSTOM;
1870 e_UnpressAllKeys();
1871 end
1872 else // Закончилась последняя карта в Одиночной игре
1873 begin
1874 gMusic.SetByName('MUSIC_INTERMUS');
1875 gMusic.Play();
1876 gState := STATE_INTERSINGLE;
1877 e_UnpressAllKeys();
1878 end;
1879 g_Game_ExecuteEvent('oninter');
1880 end
1881 else
1882 DecMin(EndingGameCounter, 6, 0);
1883 end;
1885 STATE_ENDPIC: // Картинка окончания мегаВада
1886 begin
1887 if gMapOnce then // Это был тест
1888 begin
1889 gExit := EXIT_SIMPLE;
1890 Exit;
1891 end;
1892 end;
1894 STATE_SLIST:
1895 g_Serverlist_Control(slCurrent, slTable);
1896 end;
1898 // Статистика по Tab:
1899 if gGameOn then
1900 IsDrawStat := (not gConsoleShow) and (not gChatShow) and (gGameSettings.GameType <> GT_SINGLE) and g_Console_Action(ACTION_SCORES);
1902 // Игра идет:
1903 if gGameOn and not gPause and (gState <> STATE_FOLD) then
1904 begin
1905 // Время += 28 миллисекунд:
1906 gTime := gTime + GAME_TICK;
1908 // Сообщение посередине экрана:
1909 if MessageTime = 0 then
1910 MessageText := '';
1911 if MessageTime > 0 then
1912 MessageTime := MessageTime - 1;
1914 if (g_Game_IsServer) then
1915 begin
1916 // Был задан лимит времени:
1917 if (gGameSettings.TimeLimit > 0) then
1918 if (gTime - gGameStartTime) div 1000 >= gGameSettings.TimeLimit then
1919 begin // Он прошел => конец уровня
1920 g_Game_NextLevel();
1921 Exit;
1922 end;
1924 // Надо респавнить игроков в LMS:
1925 if (gLMSRespawn > LMS_RESPAWN_NONE) and (gLMSRespawnTime < gTime) then
1926 g_Game_RestartRound(gLMSSoftSpawn);
1928 // Проверим результат голосования, если время прошло
1929 if gVoteInProgress and (gVoteTimer < gTime) then
1930 g_Game_CheckVote
1931 else if gVotePassed and (gVoteCmdTimer < gTime) then
1932 begin
1933 g_Console_Process(gVoteCommand);
1934 gVoteCommand := '';
1935 gVotePassed := False;
1936 end;
1938 // Замеряем время захвата флагов
1939 if gFlags[FLAG_RED].State = FLAG_STATE_CAPTURED then
1940 gFlags[FLAG_RED].CaptureTime := gFlags[FLAG_RED].CaptureTime + GAME_TICK;
1941 if gFlags[FLAG_BLUE].State = FLAG_STATE_CAPTURED then
1942 gFlags[FLAG_BLUE].CaptureTime := gFlags[FLAG_BLUE].CaptureTime + GAME_TICK;
1944 // Был задан лимит побед:
1945 if (gGameSettings.GoalLimit > 0) then
1946 begin
1947 b := 0;
1949 if gGameSettings.GameMode = GM_DM then
1950 begin // В DM ищем игрока с max фрагами
1951 for i := 0 to High(gPlayers) do
1952 if gPlayers[i] <> nil then
1953 if gPlayers[i].Frags > b then
1954 b := gPlayers[i].Frags;
1955 end
1956 else
1957 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
1958 begin // В CTF/TDM выбираем команду с наибольшим счетом
1959 b := Max(gTeamStat[TEAM_RED].Goals, gTeamStat[TEAM_BLUE].Goals);
1960 end;
1962 // Лимит побед набран => конец уровня:
1963 if b >= gGameSettings.GoalLimit then
1964 begin
1965 g_Game_NextLevel();
1966 Exit;
1967 end;
1968 end;
1970 // Обрабатываем клавиши игроков:
1971 if gPlayer1 <> nil then gPlayer1.ReleaseKeys();
1972 if gPlayer2 <> nil then gPlayer2.ReleaseKeys();
1973 {$IFDEF HEADLESS}
1974 if (not gConsoleShow) and (not gChatShow) then
1975 {$ELSE}
1976 if (not gConsoleShow) and (not gChatShow) and (g_ActiveWindow = nil) then
1977 {$ENDIF}
1978 begin
1979 ProcessPlayerControls(gPlayer1, 0, P1MoveButton);
1980 ProcessPlayerControls(gPlayer2, 1, P2MoveButton);
1981 end // if not console
1982 else
1983 begin
1984 if g_Game_IsNet and (gPlayer1 <> nil) then gPlayer1.PressKey(KEY_CHAT, 10000);
1985 end;
1986 // process weapon switch queue
1987 end; // if server
1989 // Наблюдатель
1990 if (gPlayer1 = nil) and (gPlayer2 = nil)
1991 and (not gConsoleShow) and (not gChatShow)
1992 {$IFNDEF HEADLESS}
1993 and (g_ActiveWindow = nil)
1994 {$ENDIF}
1995 then
1996 begin
1997 if not gSpectKeyPress then
1998 begin
1999 if gPlayerAction[0, ACTION_JUMP] and (not gSpectAuto) then
2000 begin
2001 // switch spect mode
2002 case gSpectMode of
2003 SPECT_NONE: ; // not spectator
2004 SPECT_STATS,
2005 SPECT_MAPVIEW: Inc(gSpectMode);
2006 SPECT_PLAYERS: gSpectMode := SPECT_STATS; // reset to 1
2007 end;
2008 gSpectKeyPress := True;
2009 end;
2010 if (gSpectMode = SPECT_MAPVIEW)
2011 and (not gSpectAuto) then
2012 begin
2013 if gPlayerAction[0, ACTION_MOVELEFT] then
2014 gSpectX := Max(gSpectX - gSpectStep, 0);
2015 if gPlayerAction[0, ACTION_MOVERIGHT] then
2016 gSpectX := Min(gSpectX + gSpectStep, gMapInfo.Width - gScreenWidth);
2017 if gPlayerAction[0, ACTION_LOOKUP] then
2018 gSpectY := Max(gSpectY - gSpectStep, 0);
2019 if gPlayerAction[0, ACTION_LOOKDOWN] then
2020 gSpectY := Min(gSpectY + gSpectStep, gMapInfo.Height - gScreenHeight);
2021 if gPlayerAction[0, ACTION_WEAPPREV] then
2022 begin
2023 // decrease step
2024 if gSpectStep > 4 then gSpectStep := gSpectStep shr 1;
2025 gSpectKeyPress := True;
2026 end;
2027 if gPlayerAction[0, ACTION_WEAPNEXT] then
2028 begin
2029 // increase step
2030 if gSpectStep < 64 then gSpectStep := gSpectStep shl 1;
2031 gSpectKeyPress := True;
2032 end;
2033 end;
2034 if (gSpectMode = SPECT_PLAYERS)
2035 and (not gSpectAuto) then
2036 begin
2037 if gPlayerAction[0, ACTION_LOOKUP] then
2038 begin
2039 // add second view
2040 gSpectViewTwo := True;
2041 gSpectKeyPress := True;
2042 end;
2043 if gPlayerAction[0, ACTION_LOOKDOWN] then
2044 begin
2045 // remove second view
2046 gSpectViewTwo := False;
2047 gSpectKeyPress := True;
2048 end;
2049 if gPlayerAction[0, ACTION_MOVELEFT] then
2050 begin
2051 // prev player (view 1)
2052 gSpectPID1 := GetActivePlayerID_Prev(gSpectPID1);
2053 gSpectKeyPress := True;
2054 end;
2055 if gPlayerAction[0, ACTION_MOVERIGHT] then
2056 begin
2057 // next player (view 1)
2058 gSpectPID1 := GetActivePlayerID_Next(gSpectPID1);
2059 gSpectKeyPress := True;
2060 end;
2061 if gPlayerAction[0, ACTION_WEAPPREV] then
2062 begin
2063 // prev player (view 2)
2064 gSpectPID2 := GetActivePlayerID_Prev(gSpectPID2);
2065 gSpectKeyPress := True;
2066 end;
2067 if gPlayerAction[0, ACTION_WEAPNEXT] then
2068 begin
2069 // next player (view 2)
2070 gSpectPID2 := GetActivePlayerID_Next(gSpectPID2);
2071 gSpectKeyPress := True;
2072 end;
2073 end;
2074 if gPlayerAction[0, ACTION_ATTACK] then
2075 begin
2076 if (gSpectMode = SPECT_STATS) and (not gSpectAuto) then
2077 begin
2078 gSpectAuto := True;
2079 gSpectAutoNext := 0;
2080 gSpectViewTwo := False;
2081 gSpectKeyPress := True;
2082 end
2083 else
2084 if gSpectAuto then
2085 begin
2086 gSpectMode := SPECT_STATS;
2087 gSpectAuto := False;
2088 gSpectKeyPress := True;
2089 end;
2090 end;
2091 end
2092 else
2093 if (not gPlayerAction[0, ACTION_JUMP]) and
2094 (not gPlayerAction[0, ACTION_ATTACK]) and
2095 (not gPlayerAction[0, ACTION_MOVELEFT]) and
2096 (not gPlayerAction[0, ACTION_MOVERIGHT]) and
2097 (not gPlayerAction[0, ACTION_LOOKUP]) and
2098 (not gPlayerAction[0, ACTION_LOOKDOWN]) and
2099 (not gPlayerAction[0, ACTION_WEAPPREV]) and
2100 (not gPlayerAction[0, ACTION_WEAPNEXT]) then
2101 gSpectKeyPress := False;
2103 if gSpectAuto then
2104 begin
2105 if gSpectMode = SPECT_MAPVIEW then
2106 begin
2107 i := Min(Max(gSpectX + gSpectAutoStepX, 0), gMapInfo.Width - gScreenWidth);
2108 if i = gSpectX then
2109 gSpectAutoNext := gTime
2110 else
2111 gSpectX := i;
2112 i := Min(Max(gSpectY + gSpectAutoStepY, 0), gMapInfo.Height - gScreenHeight);
2113 if i = gSpectY then
2114 gSpectAutoNext := gTime
2115 else
2116 gSpectY := i;
2117 end;
2118 if gSpectAutoNext <= gTime then
2119 begin
2120 if gSpectAutoNext > 0 then
2121 begin
2122 gSpectMode := GetRandomSpectMode(gSpectMode);
2123 case gSpectMode of
2124 SPECT_MAPVIEW:
2125 begin
2126 gSpectX := Random(gMapInfo.Width - gScreenWidth);
2127 gSpectY := Random(gMapInfo.Height - gScreenHeight);
2128 gSpectAutoStepX := Random(9) - 4;
2129 gSpectAutoStepY := Random(9) - 4;
2130 if ((gSpectX < 800) and (gSpectAutoStepX < 0)) or
2131 ((gSpectX > gMapInfo.Width - gScreenWidth - 800) and (gSpectAutoStepX > 0)) then
2132 gSpectAutoStepX := gSpectAutoStepX * -1;
2133 if ((gSpectY < 800) and (gSpectAutoStepY < 0)) or
2134 ((gSpectY > gMapInfo.Height - gScreenHeight - 800) and (gSpectAutoStepY > 0)) then
2135 gSpectAutoStepY := gSpectAutoStepY * -1;
2136 end;
2137 SPECT_PLAYERS:
2138 begin
2139 gSpectPID1 := GetActivePlayerID_Random(gSpectPID1);
2140 end;
2141 end;
2142 end;
2143 case gSpectMode of
2144 SPECT_STATS: gSpectAutoNext := gTime + (Random(3) + 5) * 1000;
2145 SPECT_MAPVIEW: gSpectAutoNext := gTime + (Random(4) + 7) * 1000;
2146 SPECT_PLAYERS: gSpectAutoNext := gTime + (Random(7) + 8) * 1000;
2147 end;
2148 end;
2149 end;
2150 end;
2152 // Обновляем все остальное:
2153 g_Map_Update();
2154 g_Items_Update();
2155 g_Triggers_Update();
2156 g_Weapon_Update();
2157 g_Monsters_Update();
2158 g_GFX_Update();
2159 g_Player_UpdateAll();
2160 g_Player_UpdatePhysicalObjects();
2162 // server: send newly spawned monsters unconditionally
2163 if (gGameSettings.GameType = GT_SERVER) then
2164 begin
2165 if (Length(gMonstersSpawned) > 0) then
2166 begin
2167 for I := 0 to High(gMonstersSpawned) do MH_SEND_MonsterSpawn(gMonstersSpawned[I]);
2168 SetLength(gMonstersSpawned, 0);
2169 end;
2170 end;
2172 if (gSoundTriggerTime > 8) then
2173 begin
2174 g_Game_UpdateTriggerSounds();
2175 gSoundTriggerTime := 0;
2176 end
2177 else
2178 begin
2179 Inc(gSoundTriggerTime);
2180 end;
2182 if (NetMode = NET_SERVER) then
2183 begin
2184 Inc(NetTimeToUpdate);
2185 Inc(NetTimeToReliable);
2187 // send monster updates
2188 if (NetTimeToReliable >= NetRelupdRate) or (NetTimeToUpdate >= NetUpdateRate) then
2189 begin
2190 // send all monsters (periodic sync)
2191 reliableUpdate := (NetTimeToReliable >= NetRelupdRate);
2193 for I := 0 to High(gPlayers) do
2194 begin
2195 if (gPlayers[I] <> nil) then MH_SEND_PlayerPos(reliableUpdate, gPlayers[I].UID);
2196 end;
2198 g_Mons_ForEach(sendMonsPos);
2200 if reliableUpdate then
2201 begin
2202 NetTimeToReliable := 0;
2203 NetTimeToUpdate := NetUpdateRate;
2204 end
2205 else
2206 begin
2207 NetTimeToUpdate := 0;
2208 end;
2209 end
2210 else
2211 begin
2212 // send only mosters with some unexpected changes
2213 g_Mons_ForEach(sendMonsPosUnexpected);
2214 end;
2216 // send unexpected platform changes
2217 g_Map_NetSendInterestingPanels();
2219 g_Net_Slist_ServerUpdate();
2221 if NetUseMaster then
2222 begin
2223 if (gTime >= NetTimeToMaster) or g_Net_Slist_IsConnectionInProgress then
2224 begin
2225 if (not g_Net_Slist_IsConnectionActive) then g_Net_Slist_Connect(false); // non-blocking connection to the master
2226 g_Net_Slist_Update;
2227 NetTimeToMaster := gTime + NetMasterRate;
2228 end;
2229 end;
2231 end
2232 else if (NetMode = NET_CLIENT) then
2233 begin
2234 MC_SEND_PlayerPos();
2235 end;
2236 end; // if gameOn ...
2238 // Активно окно интерфейса - передаем клавиши ему:
2239 {$IFNDEF HEADLESS}
2240 if g_ActiveWindow <> nil then
2241 begin
2242 w := e_GetFirstKeyPressed();
2244 if (w <> IK_INVALID) then
2245 begin
2246 Msg.Msg := MESSAGE_DIKEY;
2247 Msg.wParam := w;
2248 g_ActiveWindow.OnMessage(Msg);
2249 end;
2251 // Если оно от этого не закрылось, то обновляем:
2252 if g_ActiveWindow <> nil then
2253 g_ActiveWindow.Update();
2255 // Нужно сменить разрешение:
2256 if gResolutionChange then
2257 begin
2258 {$IFNDEF HEADLESS}
2259 e_WriteLog('Changing resolution', TMsgType.Notify);
2260 r_Render_Apply;
2261 {$ENDIF}
2262 gResolutionChange := False;
2263 g_ActiveWindow := nil;
2264 end;
2266 // Нужно сменить язык:
2267 if gLanguageChange then
2268 begin
2269 //e_WriteLog('Read language file', MSG_NOTIFY);
2270 //g_Language_Load(DataDir + gLanguage + '.txt');
2271 g_Language_Set(gLanguage);
2272 g_Menu_Reset();
2273 gLanguageChange := False;
2274 end;
2275 end;
2277 // Горячая клавиша для вызова меню выхода из игры (F10):
2278 if e_KeyPressed(IK_F10) and
2279 gGameOn and
2280 (not gConsoleShow) and
2281 (g_ActiveWindow = nil) then
2282 begin
2283 KeyPress(IK_F10);
2284 end;
2285 {$ENDIF} // NOT HEADLESS
2287 Time := GetTickCount64() {div 1000};
2289 // Обработка отложенных событий:
2290 if gDelayedEvents <> nil then
2291 for a := 0 to High(gDelayedEvents) do
2292 if gDelayedEvents[a].Pending and
2294 ((gDelayedEvents[a].DEType = DE_GLOBEVENT) and (gDelayedEvents[a].Time <= Time)) or
2295 ((gDelayedEvents[a].DEType > DE_GLOBEVENT) and (gDelayedEvents[a].Time <= gTime))
2296 ) then
2297 begin
2298 case gDelayedEvents[a].DEType of
2299 DE_GLOBEVENT:
2300 g_Game_ExecuteEvent(gDelayedEvents[a].DEStr);
2301 DE_BFGHIT:
2302 if gGameOn then
2303 g_Game_Announce_GoodShot(gDelayedEvents[a].DENum);
2304 DE_KILLCOMBO:
2305 if gGameOn then
2306 begin
2307 g_Game_Announce_KillCombo(gDelayedEvents[a].DENum);
2308 if g_Game_IsNet and g_Game_IsServer then
2309 MH_SEND_GameEvent(NET_EV_KILLCOMBO, gDelayedEvents[a].DENum);
2310 end;
2311 DE_BODYKILL:
2312 if gGameOn then
2313 g_Game_Announce_BodyKill(gDelayedEvents[a].DENum);
2314 end;
2315 gDelayedEvents[a].Pending := False;
2316 end;
2318 // Каждую секунду обновляем счетчик обновлений:
2319 UPSCounter := UPSCounter + 1;
2320 if Time - UPSTime >= 1000 then
2321 begin
2322 UPS := UPSCounter;
2323 UPSCounter := 0;
2324 UPSTime := Time;
2325 end;
2327 if gGameOn then
2328 begin
2329 g_Weapon_AddDynLights();
2330 g_Items_AddDynLights();
2331 end;
2332 end;
2334 procedure g_Game_LoadChatSounds(Resource: string);
2335 var
2336 WAD: TWADFile;
2337 FileName, Snd: string;
2338 p: Pointer;
2339 len, cnt, tags, i, j: Integer;
2340 cfg: TConfig;
2341 begin
2342 FileName := g_ExtractWadName(Resource);
2344 WAD := TWADFile.Create();
2345 WAD.ReadFile(FileName);
2347 if not WAD.GetResource(g_ExtractFilePathName(Resource), p, len) then
2348 begin
2349 gChatSounds := nil;
2350 WAD.Free();
2351 Exit;
2352 end;
2354 cfg := TConfig.CreateMem(p, len);
2355 cnt := cfg.ReadInt('ChatSounds', 'Count', 0);
2357 SetLength(gChatSounds, cnt);
2358 for i := 0 to Length(gChatSounds) - 1 do
2359 begin
2360 gChatSounds[i].Sound := nil;
2361 Snd := Trim(cfg.ReadStr(IntToStr(i), 'Sound', ''));
2362 tags := cfg.ReadInt(IntToStr(i), 'Tags', 0);
2363 if (Snd = '') or (Tags <= 0) then
2364 continue;
2365 g_Sound_CreateWADEx('SOUND_CHAT_MACRO' + IntToStr(i), GameWAD+':'+Snd);
2366 gChatSounds[i].Sound := TPlayableSound.Create();
2367 gChatSounds[i].Sound.SetByName('SOUND_CHAT_MACRO' + IntToStr(i));
2368 SetLength(gChatSounds[i].Tags, tags);
2369 for j := 0 to tags - 1 do
2370 gChatSounds[i].Tags[j] := toLowerCase1251(cfg.ReadStr(IntToStr(i), 'Tag' + IntToStr(j), ''));
2371 gChatSounds[i].FullWord := cfg.ReadBool(IntToStr(i), 'FullWord', False);
2372 end;
2374 cfg.Free();
2375 WAD.Free();
2376 end;
2378 procedure g_Game_FreeChatSounds();
2379 var
2380 i: Integer;
2381 begin
2382 for i := 0 to Length(gChatSounds) - 1 do
2383 begin
2384 gChatSounds[i].Sound.Free();
2385 g_Sound_Delete('SOUND_CHAT_MACRO' + IntToStr(i));
2386 end;
2387 SetLength(gChatSounds, 0);
2388 gChatSounds := nil;
2389 end;
2391 procedure g_Game_LoadData();
2392 begin
2393 if DataLoaded then Exit;
2395 e_WriteLog('Loading game data...', TMsgType.Notify);
2397 g_Sound_CreateWADEx('SOUND_GAME_TELEPORT', GameWAD+':SOUNDS\TELEPORT');
2398 g_Sound_CreateWADEx('SOUND_GAME_NOTELEPORT', GameWAD+':SOUNDS\NOTELEPORT');
2399 g_Sound_CreateWADEx('SOUND_GAME_SECRET', GameWAD+':SOUNDS\SECRET');
2400 g_Sound_CreateWADEx('SOUND_GAME_DOOROPEN', GameWAD+':SOUNDS\DOOROPEN');
2401 g_Sound_CreateWADEx('SOUND_GAME_DOORCLOSE', GameWAD+':SOUNDS\DOORCLOSE');
2402 g_Sound_CreateWADEx('SOUND_GAME_BULK1', GameWAD+':SOUNDS\BULK1');
2403 g_Sound_CreateWADEx('SOUND_GAME_BULK2', GameWAD+':SOUNDS\BULK2');
2404 g_Sound_CreateWADEx('SOUND_GAME_BUBBLE1', GameWAD+':SOUNDS\BUBBLE1');
2405 g_Sound_CreateWADEx('SOUND_GAME_BUBBLE2', GameWAD+':SOUNDS\BUBBLE2');
2406 g_Sound_CreateWADEx('SOUND_GAME_BURNING', GameWAD+':SOUNDS\BURNING');
2407 g_Sound_CreateWADEx('SOUND_GAME_SWITCH1', GameWAD+':SOUNDS\SWITCH1');
2408 g_Sound_CreateWADEx('SOUND_GAME_SWITCH0', GameWAD+':SOUNDS\SWITCH0');
2409 g_Sound_CreateWADEx('SOUND_GAME_RADIO', GameWAD+':SOUNDS\RADIO');
2410 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD1', GameWAD+':SOUNDS\GOOD1');
2411 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD2', GameWAD+':SOUNDS\GOOD2');
2412 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD3', GameWAD+':SOUNDS\GOOD3');
2413 g_Sound_CreateWADEx('SOUND_ANNOUNCER_GOOD4', GameWAD+':SOUNDS\GOOD4');
2414 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL2X', GameWAD+':SOUNDS\KILL2X');
2415 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL3X', GameWAD+':SOUNDS\KILL3X');
2416 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILL4X', GameWAD+':SOUNDS\KILL4X');
2417 g_Sound_CreateWADEx('SOUND_ANNOUNCER_KILLMX', GameWAD+':SOUNDS\KILLMX');
2418 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA1', GameWAD+':SOUNDS\MUHAHA1');
2419 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA2', GameWAD+':SOUNDS\MUHAHA2');
2420 g_Sound_CreateWADEx('SOUND_ANNOUNCER_MUHAHA3', GameWAD+':SOUNDS\MUHAHA3');
2421 g_Sound_CreateWADEx('SOUND_CTF_GET1', GameWAD+':SOUNDS\GETFLAG1');
2422 g_Sound_CreateWADEx('SOUND_CTF_GET2', GameWAD+':SOUNDS\GETFLAG2');
2423 g_Sound_CreateWADEx('SOUND_CTF_LOST1', GameWAD+':SOUNDS\LOSTFLG1');
2424 g_Sound_CreateWADEx('SOUND_CTF_LOST2', GameWAD+':SOUNDS\LOSTFLG2');
2425 g_Sound_CreateWADEx('SOUND_CTF_RETURN1', GameWAD+':SOUNDS\RETFLAG1');
2426 g_Sound_CreateWADEx('SOUND_CTF_RETURN2', GameWAD+':SOUNDS\RETFLAG2');
2427 g_Sound_CreateWADEx('SOUND_CTF_CAPTURE1', GameWAD+':SOUNDS\CAPFLAG1');
2428 g_Sound_CreateWADEx('SOUND_CTF_CAPTURE2', GameWAD+':SOUNDS\CAPFLAG2');
2430 goodsnd[0] := TPlayableSound.Create();
2431 goodsnd[1] := TPlayableSound.Create();
2432 goodsnd[2] := TPlayableSound.Create();
2433 goodsnd[3] := TPlayableSound.Create();
2435 goodsnd[0].SetByName('SOUND_ANNOUNCER_GOOD1');
2436 goodsnd[1].SetByName('SOUND_ANNOUNCER_GOOD2');
2437 goodsnd[2].SetByName('SOUND_ANNOUNCER_GOOD3');
2438 goodsnd[3].SetByName('SOUND_ANNOUNCER_GOOD4');
2440 killsnd[0] := TPlayableSound.Create();
2441 killsnd[1] := TPlayableSound.Create();
2442 killsnd[2] := TPlayableSound.Create();
2443 killsnd[3] := TPlayableSound.Create();
2445 killsnd[0].SetByName('SOUND_ANNOUNCER_KILL2X');
2446 killsnd[1].SetByName('SOUND_ANNOUNCER_KILL3X');
2447 killsnd[2].SetByName('SOUND_ANNOUNCER_KILL4X');
2448 killsnd[3].SetByName('SOUND_ANNOUNCER_KILLMX');
2450 hahasnd[0] := TPlayableSound.Create();
2451 hahasnd[1] := TPlayableSound.Create();
2452 hahasnd[2] := TPlayableSound.Create();
2454 hahasnd[0].SetByName('SOUND_ANNOUNCER_MUHAHA1');
2455 hahasnd[1].SetByName('SOUND_ANNOUNCER_MUHAHA2');
2456 hahasnd[2].SetByName('SOUND_ANNOUNCER_MUHAHA3');
2458 sound_get_flag[0] := TPlayableSound.Create();
2459 sound_get_flag[1] := TPlayableSound.Create();
2460 sound_lost_flag[0] := TPlayableSound.Create();
2461 sound_lost_flag[1] := TPlayableSound.Create();
2462 sound_ret_flag[0] := TPlayableSound.Create();
2463 sound_ret_flag[1] := TPlayableSound.Create();
2464 sound_cap_flag[0] := TPlayableSound.Create();
2465 sound_cap_flag[1] := TPlayableSound.Create();
2467 sound_get_flag[0].SetByName('SOUND_CTF_GET1');
2468 sound_get_flag[1].SetByName('SOUND_CTF_GET2');
2469 sound_lost_flag[0].SetByName('SOUND_CTF_LOST1');
2470 sound_lost_flag[1].SetByName('SOUND_CTF_LOST2');
2471 sound_ret_flag[0].SetByName('SOUND_CTF_RETURN1');
2472 sound_ret_flag[1].SetByName('SOUND_CTF_RETURN2');
2473 sound_cap_flag[0].SetByName('SOUND_CTF_CAPTURE1');
2474 sound_cap_flag[1].SetByName('SOUND_CTF_CAPTURE2');
2476 g_Game_LoadChatSounds(GameWAD+':CHATSND\SNDCFG');
2478 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS_DATA], 0, False);
2479 g_Items_LoadData();
2481 g_Game_SetLoadingText(_lc[I_LOAD_WEAPONS_DATA], 0, False);
2482 g_Weapon_LoadData();
2484 g_Monsters_LoadData();
2486 DataLoaded := True;
2487 end;
2489 procedure g_Game_Quit();
2490 begin
2491 g_Game_StopAllSounds(True);
2492 gMusic.Free();
2493 g_Game_FreeData();
2494 g_PlayerModel_FreeData();
2495 {$IFNDEF HEADLESS}
2496 //g_Menu_Free(); //k8: this segfaults after resolution change; who cares?
2497 {$ENDIF}
2499 if NetInitDone then g_Net_Free;
2501 // remove map after test
2502 if gMapToDelete <> '' then
2503 g_Game_DeleteTestMap();
2505 gExit := EXIT_QUIT;
2507 {$IFNDEF HEADLESS}
2508 sys_RequestQuit;
2509 {$ENDIF}
2510 end;
2512 procedure g_Game_FreeData();
2513 begin
2514 if not DataLoaded then Exit;
2516 g_Items_FreeData();
2517 g_Weapon_FreeData();
2518 g_Monsters_FreeData();
2520 e_WriteLog('Releasing game data...', TMsgType.Notify);
2522 g_Sound_Delete('SOUND_GAME_TELEPORT');
2523 g_Sound_Delete('SOUND_GAME_NOTELEPORT');
2524 g_Sound_Delete('SOUND_GAME_SECRET');
2525 g_Sound_Delete('SOUND_GAME_DOOROPEN');
2526 g_Sound_Delete('SOUND_GAME_DOORCLOSE');
2527 g_Sound_Delete('SOUND_GAME_BULK1');
2528 g_Sound_Delete('SOUND_GAME_BULK2');
2529 g_Sound_Delete('SOUND_GAME_BUBBLE1');
2530 g_Sound_Delete('SOUND_GAME_BUBBLE2');
2531 g_Sound_Delete('SOUND_GAME_BURNING');
2532 g_Sound_Delete('SOUND_GAME_SWITCH1');
2533 g_Sound_Delete('SOUND_GAME_SWITCH0');
2535 goodsnd[0].Free();
2536 goodsnd[1].Free();
2537 goodsnd[2].Free();
2538 goodsnd[3].Free();
2540 g_Sound_Delete('SOUND_ANNOUNCER_GOOD1');
2541 g_Sound_Delete('SOUND_ANNOUNCER_GOOD2');
2542 g_Sound_Delete('SOUND_ANNOUNCER_GOOD3');
2543 g_Sound_Delete('SOUND_ANNOUNCER_GOOD4');
2545 killsnd[0].Free();
2546 killsnd[1].Free();
2547 killsnd[2].Free();
2548 killsnd[3].Free();
2550 g_Sound_Delete('SOUND_ANNOUNCER_KILL2X');
2551 g_Sound_Delete('SOUND_ANNOUNCER_KILL3X');
2552 g_Sound_Delete('SOUND_ANNOUNCER_KILL4X');
2553 g_Sound_Delete('SOUND_ANNOUNCER_KILLMX');
2555 hahasnd[0].Free();
2556 hahasnd[1].Free();
2557 hahasnd[2].Free();
2559 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA1');
2560 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA2');
2561 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA3');
2563 sound_get_flag[0].Free();
2564 sound_get_flag[1].Free();
2565 sound_lost_flag[0].Free();
2566 sound_lost_flag[1].Free();
2567 sound_ret_flag[0].Free();
2568 sound_ret_flag[1].Free();
2569 sound_cap_flag[0].Free();
2570 sound_cap_flag[1].Free();
2572 g_Sound_Delete('SOUND_CTF_GET1');
2573 g_Sound_Delete('SOUND_CTF_GET2');
2574 g_Sound_Delete('SOUND_CTF_LOST1');
2575 g_Sound_Delete('SOUND_CTF_LOST2');
2576 g_Sound_Delete('SOUND_CTF_RETURN1');
2577 g_Sound_Delete('SOUND_CTF_RETURN2');
2578 g_Sound_Delete('SOUND_CTF_CAPTURE1');
2579 g_Sound_Delete('SOUND_CTF_CAPTURE2');
2581 g_Game_FreeChatSounds();
2583 DataLoaded := False;
2584 end;
2586 procedure g_FatalError(Text: String);
2587 begin
2588 g_Console_Add(Format(_lc[I_FATAL_ERROR], [Text]), True);
2589 e_WriteLog(Format(_lc[I_FATAL_ERROR], [Text]), TMsgType.Warning);
2591 gExit := EXIT_SIMPLE;
2592 if gGameOn then EndGame;
2593 end;
2595 procedure g_SimpleError(Text: String);
2596 begin
2597 g_Console_Add(Format(_lc[I_SIMPLE_ERROR], [Text]), True);
2598 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], [Text]), TMsgType.Warning);
2599 end;
2601 procedure g_Game_AddPlayer(Team: Byte = TEAM_NONE);
2602 begin
2603 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2604 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2605 Exit;
2607 if (gGameSettings.MaxLives > 0) and (gLMSRespawn = LMS_RESPAWN_NONE) then
2608 Exit;
2610 if gPlayer1 = nil then
2611 begin
2612 if g_Game_IsClient then
2613 begin
2614 if NetPlrUID1 > -1 then
2615 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2616 Exit;
2617 end;
2619 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2620 Team := gPlayer1Settings.Team;
2622 // Создание первого игрока:
2623 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2624 gPlayer1Settings.Color,
2625 Team, False));
2626 if gPlayer1 = nil then
2627 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]))
2628 else
2629 begin
2630 gPlayer1.Name := gPlayer1Settings.Name;
2631 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer1.Name]), True);
2632 if g_Game_IsServer and g_Game_IsNet then
2633 MH_SEND_PlayerCreate(gPlayer1.UID);
2634 gPlayer1.Respawn(False, True);
2635 g_Net_Slist_ServerPlayerComes();
2636 end;
2638 Exit;
2639 end;
2640 if gPlayer2 = nil then
2641 begin
2642 if g_Game_IsClient then
2643 begin
2644 if NetPlrUID2 > -1 then
2645 gPlayer2 := g_Player_Get(NetPlrUID2);
2646 Exit;
2647 end;
2649 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2650 Team := gPlayer2Settings.Team;
2652 // Создание второго игрока:
2653 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2654 gPlayer2Settings.Color,
2655 Team, False));
2656 if gPlayer2 = nil then
2657 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]))
2658 else
2659 begin
2660 gPlayer2.Name := gPlayer2Settings.Name;
2661 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer2.Name]), True);
2662 if g_Game_IsServer and g_Game_IsNet then
2663 MH_SEND_PlayerCreate(gPlayer2.UID);
2664 gPlayer2.Respawn(False, True);
2665 g_Net_Slist_ServerPlayerComes();
2666 end;
2668 Exit;
2669 end;
2670 end;
2672 procedure g_Game_RemovePlayer();
2673 var
2674 Pl: TPlayer;
2675 begin
2676 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2677 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2678 Exit;
2679 Pl := gPlayer2;
2680 if Pl <> nil then
2681 begin
2682 if g_Game_IsServer then
2683 begin
2684 Pl.Lives := 0;
2685 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2686 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2687 g_Player_Remove(Pl.UID);
2688 g_Net_Slist_ServerPlayerLeaves();
2689 end
2690 else
2691 begin
2692 gSpectLatchPID2 := Pl.UID;
2693 gPlayer2 := nil;
2694 end;
2695 Exit;
2696 end;
2697 Pl := gPlayer1;
2698 if Pl <> nil then
2699 begin
2700 if g_Game_IsServer then
2701 begin
2702 Pl.Lives := 0;
2703 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2704 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2705 g_Player_Remove(Pl.UID);
2706 g_Net_Slist_ServerPlayerLeaves();
2707 end else
2708 begin
2709 gSpectLatchPID1 := Pl.UID;
2710 gPlayer1 := nil;
2711 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2712 end;
2713 Exit;
2714 end;
2715 g_Net_Slist_ServerPlayerLeaves();
2716 end;
2718 procedure g_Game_Spectate();
2719 begin
2720 g_Game_RemovePlayer();
2721 if gPlayer1 <> nil then
2722 g_Game_RemovePlayer();
2723 end;
2725 procedure g_Game_SpectateCenterView();
2726 begin
2727 gSpectX := Max(gMapInfo.Width div 2 - gScreenWidth div 2, 0);
2728 gSpectY := Max(gMapInfo.Height div 2 - gScreenHeight div 2, 0);
2729 end;
2731 procedure g_Game_StartSingle(Map: String; TwoPlayers: Boolean; nPlayers: Byte);
2732 var
2733 i, nPl: Integer;
2734 tmps: AnsiString;
2735 begin
2736 g_Game_Free();
2738 e_WriteLog('Starting singleplayer game...', TMsgType.Notify);
2740 g_Game_ClearLoading();
2742 // Настройки игры:
2743 FillByte(gGameSettings, SizeOf(TGameSettings), 0);
2744 gAimLine := False;
2745 gShowMap := False;
2746 gGameSettings.GameType := GT_SINGLE;
2747 gGameSettings.MaxLives := 0;
2748 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_ALLOWEXIT;
2749 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_MONSTERS;
2750 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_BOTVSMONSTER;
2751 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITPROJECTILE;
2752 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITTRACE;
2753 gSwitchGameMode := GM_SINGLE;
2755 gLMSRespawn := LMS_RESPAWN_NONE;
2756 gLMSRespawnTime := 0;
2757 gSpectLatchPID1 := 0;
2758 gSpectLatchPID2 := 0;
2760 g_Game_ExecuteEvent('ongamestart');
2762 // Создание первого игрока:
2763 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2764 gPlayer1Settings.Color,
2765 gPlayer1Settings.Team, False));
2766 if gPlayer1 = nil then
2767 begin
2768 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2769 Exit;
2770 end;
2772 gPlayer1.Name := gPlayer1Settings.Name;
2773 nPl := 1;
2775 // Создание второго игрока, если есть:
2776 if TwoPlayers then
2777 begin
2778 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2779 gPlayer2Settings.Color,
2780 gPlayer2Settings.Team, False));
2781 if gPlayer2 = nil then
2782 begin
2783 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2784 Exit;
2785 end;
2787 gPlayer2.Name := gPlayer2Settings.Name;
2788 Inc(nPl);
2789 end;
2791 // Загрузка и запуск карты:
2792 if not g_Game_StartMap(false{asMegawad}, MAP, True) then
2793 begin
2794 if (Pos(':\', Map) > 0) or (Pos(':/', Map) > 0) then tmps := Map else tmps := gGameSettings.WAD + ':\' + MAP;
2795 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [tmps]));
2796 Exit;
2797 end;
2799 // Настройки игроков и ботов:
2800 g_Player_Init();
2802 // Создаем ботов:
2803 for i := nPl+1 to nPlayers do
2804 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2805 end;
2807 procedure g_Game_StartCustom(Map: String; GameMode: Byte;
2808 TimeLimit, GoalLimit: Word;
2809 MaxLives: Byte;
2810 Options: LongWord; nPlayers: Byte);
2811 var
2812 i, nPl: Integer;
2813 begin
2814 g_Game_Free();
2816 e_WriteLog('Starting custom game...', TMsgType.Notify);
2818 g_Game_ClearLoading();
2820 // Настройки игры:
2821 gGameSettings.GameType := GT_CUSTOM;
2822 gGameSettings.GameMode := GameMode;
2823 gSwitchGameMode := GameMode;
2824 gGameSettings.TimeLimit := TimeLimit;
2825 gGameSettings.GoalLimit := GoalLimit;
2826 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2827 gGameSettings.Options := Options;
2829 gCoopTotalMonstersKilled := 0;
2830 gCoopTotalSecretsFound := 0;
2831 gCoopTotalMonsters := 0;
2832 gCoopTotalSecrets := 0;
2833 gAimLine := False;
2834 gShowMap := False;
2836 gLMSRespawn := LMS_RESPAWN_NONE;
2837 gLMSRespawnTime := 0;
2838 gSpectLatchPID1 := 0;
2839 gSpectLatchPID2 := 0;
2841 g_Game_ExecuteEvent('ongamestart');
2843 // Режим наблюдателя:
2844 if nPlayers = 0 then
2845 begin
2846 gPlayer1 := nil;
2847 gPlayer2 := nil;
2848 end;
2850 nPl := 0;
2851 if nPlayers >= 1 then
2852 begin
2853 // Создание первого игрока:
2854 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2855 gPlayer1Settings.Color,
2856 gPlayer1Settings.Team, False));
2857 if gPlayer1 = nil then
2858 begin
2859 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2860 Exit;
2861 end;
2863 gPlayer1.Name := gPlayer1Settings.Name;
2864 Inc(nPl);
2865 end;
2867 if nPlayers >= 2 then
2868 begin
2869 // Создание второго игрока:
2870 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2871 gPlayer2Settings.Color,
2872 gPlayer2Settings.Team, False));
2873 if gPlayer2 = nil then
2874 begin
2875 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2876 Exit;
2877 end;
2879 gPlayer2.Name := gPlayer2Settings.Name;
2880 Inc(nPl);
2881 end;
2883 // Загрузка и запуск карты:
2884 if not g_Game_StartMap(true{asMegawad}, Map, True) then
2885 begin
2886 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
2887 Exit;
2888 end;
2890 // Нет точек появления:
2891 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
2892 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
2893 g_Map_GetPointCount(RESPAWNPOINT_DM) +
2894 g_Map_GetPointCount(RESPAWNPOINT_RED)+
2895 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
2896 begin
2897 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
2898 Exit;
2899 end;
2901 // Настройки игроков и ботов:
2902 g_Player_Init();
2904 // Создаем ботов:
2905 for i := nPl+1 to nPlayers do
2906 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2907 end;
2909 procedure g_Game_StartServer(Map: String; GameMode: Byte;
2910 TimeLimit, GoalLimit: Word; MaxLives: Byte;
2911 Options: LongWord; nPlayers: Byte;
2912 IPAddr: LongWord; Port: Word);
2913 begin
2914 g_Game_Free();
2915 g_Net_Slist_ServerClosed();
2917 e_WriteLog('Starting net game (server)...', TMsgType.Notify);
2919 g_Game_ClearLoading();
2921 // Настройки игры:
2922 gGameSettings.GameType := GT_SERVER;
2923 gGameSettings.GameMode := GameMode;
2924 gSwitchGameMode := GameMode;
2925 gGameSettings.TimeLimit := TimeLimit;
2926 gGameSettings.GoalLimit := GoalLimit;
2927 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2928 gGameSettings.Options := Options;
2930 gCoopTotalMonstersKilled := 0;
2931 gCoopTotalSecretsFound := 0;
2932 gCoopTotalMonsters := 0;
2933 gCoopTotalSecrets := 0;
2934 gAimLine := False;
2935 gShowMap := False;
2937 gLMSRespawn := LMS_RESPAWN_NONE;
2938 gLMSRespawnTime := 0;
2939 gSpectLatchPID1 := 0;
2940 gSpectLatchPID2 := 0;
2942 g_Game_ExecuteEvent('ongamestart');
2944 // Режим наблюдателя:
2945 if nPlayers = 0 then
2946 begin
2947 gPlayer1 := nil;
2948 gPlayer2 := nil;
2949 end;
2951 if nPlayers >= 1 then
2952 begin
2953 // Создание первого игрока:
2954 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2955 gPlayer1Settings.Color,
2956 gPlayer1Settings.Team, False));
2957 if gPlayer1 = nil then
2958 begin
2959 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2960 Exit;
2961 end;
2963 gPlayer1.Name := gPlayer1Settings.Name;
2964 end;
2966 if nPlayers >= 2 then
2967 begin
2968 // Создание второго игрока:
2969 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2970 gPlayer2Settings.Color,
2971 gPlayer2Settings.Team, False));
2972 if gPlayer2 = nil then
2973 begin
2974 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2975 Exit;
2976 end;
2978 gPlayer2.Name := gPlayer2Settings.Name;
2979 end;
2981 g_Game_SetLoadingText(_lc[I_LOAD_HOST], 0, False);
2982 if NetForwardPorts then
2983 g_Game_SetLoadingText(_lc[I_LOAD_PORTS], 0, False);
2985 // Стартуем сервер
2986 if not g_Net_Host(IPAddr, Port, NetMaxClients) then
2987 begin
2988 g_FatalError(_lc[I_NET_MSG] + Format(_lc[I_NET_ERR_HOST], [Port]));
2989 Exit;
2990 end;
2992 g_Net_Slist_Set(NetMasterList);
2994 g_Net_Slist_ServerStarted();
2996 // Загрузка и запуск карты:
2997 if not g_Game_StartMap(false{asMegawad}, Map, True) then
2998 begin
2999 g_Net_Slist_ServerClosed();
3000 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
3001 Exit;
3002 end;
3004 // Нет точек появления:
3005 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
3006 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
3007 g_Map_GetPointCount(RESPAWNPOINT_DM) +
3008 g_Map_GetPointCount(RESPAWNPOINT_RED)+
3009 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
3010 begin
3011 g_Net_Slist_ServerClosed();
3012 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
3013 Exit;
3014 end;
3016 // Настройки игроков и ботов:
3017 g_Player_Init();
3019 g_Net_Slist_ServerMapStarted();
3020 NetState := NET_STATE_GAME;
3021 end;
3023 procedure g_Game_StartClient(Addr: String; Port: Word; PW: String);
3024 var
3025 Map: String;
3026 WadName: string;
3027 Ptr: Pointer;
3028 T: Cardinal;
3029 MID: Byte;
3030 State: Byte;
3031 OuterLoop: Boolean;
3032 newResPath: string;
3033 InMsg: TMsg;
3034 begin
3035 g_Game_Free();
3037 State := 0;
3038 e_WriteLog('Starting net game (client)...', TMsgType.Notify);
3039 e_WriteLog('NET: Trying to connect to ' + Addr + ':' + IntToStr(Port) + '...', TMsgType.Notify);
3041 g_Game_ClearLoading();
3043 // Настройки игры:
3044 gGameSettings.GameType := GT_CLIENT;
3046 gCoopTotalMonstersKilled := 0;
3047 gCoopTotalSecretsFound := 0;
3048 gCoopTotalMonsters := 0;
3049 gCoopTotalSecrets := 0;
3050 gAimLine := False;
3051 gShowMap := False;
3053 g_Game_ExecuteEvent('ongamestart');
3055 NetState := NET_STATE_AUTH;
3057 g_Game_SetLoadingText(_lc[I_LOAD_CONNECT], 0, False);
3059 // create (or update) map/resource databases
3060 g_Res_CreateDatabases(true);
3062 gLMSRespawn := LMS_RESPAWN_NONE;
3063 gLMSRespawnTime := 0;
3064 gSpectLatchPID1 := 0;
3065 gSpectLatchPID2 := 0;
3067 // Стартуем клиент
3068 if not g_Net_Connect(Addr, Port) then
3069 begin
3070 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
3071 NetState := NET_STATE_NONE;
3072 Exit;
3073 end;
3075 g_Game_SetLoadingText(_lc[I_LOAD_SEND_INFO], 0, False);
3076 MC_SEND_Info(PW);
3077 g_Game_SetLoadingText(_lc[I_LOAD_WAIT_INFO], 0, False);
3079 OuterLoop := True;
3080 while OuterLoop do
3081 begin
3082 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
3083 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
3084 // thank you, enet. let's ignore failures altogether then.
3085 while (enet_host_service(NetHost, @NetEvent, 50) > 0) do
3086 begin
3087 if (NetEvent.kind = ENET_EVENT_TYPE_RECEIVE) then
3088 begin
3089 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then
3090 begin
3091 // ignore all download packets, they're processed by separate code
3092 enet_packet_destroy(NetEvent.packet);
3093 continue;
3094 end;
3095 Ptr := NetEvent.packet^.data;
3096 if not InMsg.Init(Ptr, NetEvent.packet^.dataLength, True) then
3097 begin
3098 enet_packet_destroy(NetEvent.packet);
3099 continue;
3100 end;
3102 InMsg.ReadLongWord(); // skip size
3103 MID := InMsg.ReadByte();
3105 if (MID = NET_MSG_INFO) and (State = 0) then
3106 begin
3107 NetMyID := InMsg.ReadByte();
3108 NetPlrUID1 := InMsg.ReadWord();
3110 WadName := InMsg.ReadString();
3111 Map := InMsg.ReadString();
3113 gWADHash := InMsg.ReadMD5();
3115 gGameSettings.GameMode := InMsg.ReadByte();
3116 gSwitchGameMode := gGameSettings.GameMode;
3117 gGameSettings.GoalLimit := InMsg.ReadWord();
3118 gGameSettings.TimeLimit := InMsg.ReadWord();
3119 gGameSettings.MaxLives := InMsg.ReadByte();
3120 gGameSettings.Options := InMsg.ReadLongWord();
3121 T := InMsg.ReadLongWord();
3123 //newResPath := g_Res_SearchSameWAD(MapsDir, WadName, gWADHash);
3124 //if newResPath = '' then
3125 begin
3126 //g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
3127 newResPath := g_Res_DownloadMapWAD(ExtractFileName(WadName), gWADHash);
3128 if newResPath = '' then
3129 begin
3130 g_FatalError(_lc[I_NET_ERR_HASH]);
3131 enet_packet_destroy(NetEvent.packet);
3132 NetState := NET_STATE_NONE;
3133 Exit;
3134 end;
3135 e_LogWritefln('using downloaded map wad [%s] for [%s]`', [newResPath, WadName], TMsgType.Notify);
3136 end;
3137 //newResPath := ExtractRelativePath(MapsDir, newResPath);
3140 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
3141 gPlayer1Settings.Color,
3142 gPlayer1Settings.Team, False));
3144 if gPlayer1 = nil then
3145 begin
3146 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
3148 enet_packet_destroy(NetEvent.packet);
3149 NetState := NET_STATE_NONE;
3150 Exit;
3151 end;
3153 gPlayer1.Name := gPlayer1Settings.Name;
3154 gPlayer1.UID := NetPlrUID1;
3155 gPlayer1.Reset(True);
3157 if not g_Game_StartMap(false{asMegawad}, newResPath + ':\' + Map, True) then
3158 begin
3159 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [WadName + ':\' + Map]));
3161 enet_packet_destroy(NetEvent.packet);
3162 NetState := NET_STATE_NONE;
3163 Exit;
3164 end;
3166 gTime := T;
3168 State := 1;
3169 OuterLoop := False;
3170 enet_packet_destroy(NetEvent.packet);
3171 break;
3172 end
3173 else
3174 enet_packet_destroy(NetEvent.packet);
3175 end
3176 else
3177 begin
3178 if (NetEvent.kind = ENET_EVENT_TYPE_DISCONNECT) then
3179 begin
3180 State := 0;
3181 if (NetEvent.data <= NET_DISC_MAX) then
3182 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' +
3183 _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + NetEvent.data)], True);
3184 OuterLoop := False;
3185 Break;
3186 end;
3187 end;
3188 end;
3190 ProcessLoading(true);
3192 if g_Net_UserRequestExit() then
3193 begin
3194 State := 0;
3195 break;
3196 end;
3197 end;
3199 if State <> 1 then
3200 begin
3201 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
3202 NetState := NET_STATE_NONE;
3203 Exit;
3204 end;
3206 g_Player_Init();
3207 NetState := NET_STATE_GAME;
3208 MC_SEND_FullStateRequest;
3209 e_WriteLog('NET: Connection successful.', TMsgType.Notify);
3210 end;
3212 var
3213 lastAsMegaWad: Boolean = false;
3215 procedure g_Game_ChangeMap(const MapPath: String);
3216 var
3217 Force: Boolean;
3218 begin
3219 g_Game_ClearLoading();
3221 Force := gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF];
3222 // Если уровень завершился по триггеру Выход, не очищать инвентарь
3223 if gExitByTrigger then
3224 begin
3225 Force := False;
3226 gExitByTrigger := False;
3227 end;
3228 if not g_Game_StartMap(lastAsMegaWad, MapPath, Force) then
3229 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [MapPath]));
3230 end;
3232 procedure g_Game_Restart();
3233 var
3234 Map: string;
3235 begin
3236 if g_Game_IsClient then
3237 Exit;
3238 map := g_ExtractFileName(gMapInfo.Map);
3239 e_LogWritefln('g_Game_Restart: map = "%s" gCurrentMapFileName = "%s"', [map, gCurrentMapFileName]);
3241 MessageTime := 0;
3242 gGameOn := False;
3243 g_Game_ClearLoading();
3244 g_Game_StartMap(lastAsMegaWad, Map, True, gCurrentMapFileName);
3245 end;
3247 function g_Game_StartMap (asMegawad: Boolean; Map: String; Force: Boolean = False; const oldMapPath: AnsiString=''): Boolean;
3248 var
3249 NewWAD, ResName: String;
3250 I: Integer;
3251 nws: AnsiString;
3252 begin
3253 g_Map_Free((Map <> gCurrentMapFileName) and (oldMapPath <> gCurrentMapFileName));
3254 g_Player_RemoveAllCorpses();
3256 if (not g_Game_IsClient) and
3257 (gSwitchGameMode <> gGameSettings.GameMode) and
3258 (gGameSettings.GameMode <> GM_SINGLE) then
3259 begin
3260 if gSwitchGameMode = GM_CTF then
3261 gGameSettings.MaxLives := 0;
3262 gGameSettings.GameMode := gSwitchGameMode;
3263 Force := True;
3264 end else
3265 gSwitchGameMode := gGameSettings.GameMode;
3267 g_Player_ResetTeams();
3269 lastAsMegaWad := asMegawad;
3270 if isWadPath(Map) then
3271 begin
3272 NewWAD := g_ExtractWadName(Map);
3273 ResName := g_ExtractFileName(Map);
3274 if g_Game_IsServer then
3275 begin
3276 nws := findDiskWad(NewWAD);
3277 //writeln('000: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3278 if (asMegawad) then
3279 begin
3280 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3281 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3282 end
3283 else
3284 begin
3285 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3286 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3287 end;
3288 //if (length(nws) = 0) then nws := e_FindWad(MapDownloadDirs, NewWAD);
3289 //writeln('001: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3290 //nws := NewWAD;
3291 if (length(nws) = 0) then
3292 begin
3293 ResName := ''; // failed
3294 end
3295 else
3296 begin
3297 NewWAD := nws;
3298 if (g_Game_IsNet) then gWADHash := MD5File(nws);
3299 //writeln('********: nws=', nws, ' : Map=', Map, ' : nw=', NewWAD, ' : resname=', ResName);
3300 g_Game_LoadWAD(NewWAD);
3301 end;
3302 end
3303 else
3304 begin
3305 // hash received in MC_RECV_GameEvent -> NET_EV_MAPSTART
3306 NewWAD := g_Game_ClientWAD(NewWAD, gWADHash);
3307 end;
3308 end
3309 else
3310 begin
3311 NewWAD := gGameSettings.WAD;
3312 ResName := Map;
3313 end;
3315 gTime := 0;
3317 //writeln('********: gsw=', gGameSettings.WAD, '; rn=', ResName);
3318 result := false;
3319 if (ResName <> '') and (NewWAD <> '') then
3320 begin
3321 //result := g_Map_Load(gGameSettings.WAD + ':\' + ResName);
3322 result := g_Map_Load(NewWAD+':\'+ResName);
3323 {$IFNDEF HEADLESS}
3324 r_Render_LoadTextures;
3325 {$ENDIF}
3326 end;
3327 if Result then
3328 begin
3329 g_Player_ResetAll(Force or gLastMap, gGameSettings.GameType = GT_SINGLE);
3331 gState := STATE_NONE;
3332 {$IFNDEF HEADLESS}
3333 g_ActiveWindow := nil;
3334 {$ENDIF}
3335 gGameOn := True;
3337 DisableCheats();
3338 wNeedTimeReset := True;
3340 if gGameSettings.GameMode = GM_CTF then
3341 begin
3342 g_Map_ResetFlag(FLAG_RED);
3343 g_Map_ResetFlag(FLAG_BLUE);
3344 // CTF, а флагов нет:
3345 if not g_Map_HaveFlagPoints() then
3346 g_SimpleError(_lc[I_GAME_ERROR_CTF]);
3347 end;
3348 end
3349 else
3350 begin
3351 gState := STATE_MENU;
3352 gGameOn := False;
3353 end;
3355 gExit := 0;
3356 gPauseMain := false;
3357 gPauseHolmes := false;
3358 NetTimeToUpdate := 1;
3359 NetTimeToReliable := 0;
3360 NetTimeToMaster := NetMasterRate;
3361 gSpectLatchPID1 := 0;
3362 gSpectLatchPID2 := 0;
3363 gMissionFailed := False;
3364 gNextMap := '';
3366 gCoopMonstersKilled := 0;
3367 gCoopSecretsFound := 0;
3369 gVoteInProgress := False;
3370 gVotePassed := False;
3371 gVoteCount := 0;
3372 gVoted := False;
3374 gStatsOff := False;
3376 if not gGameOn then Exit;
3378 g_Game_SpectateCenterView();
3380 if g_Game_IsServer then
3381 begin
3382 if (gGameSettings.MaxLives > 0) and (gGameSettings.WarmupTime > 0) then
3383 begin
3384 gLMSRespawn := LMS_RESPAWN_WARMUP;
3385 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3386 gLMSSoftSpawn := True;
3387 if g_Game_IsNet then
3388 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3389 end
3390 else
3391 begin
3392 gLMSRespawn := LMS_RESPAWN_NONE;
3393 gLMSRespawnTime := 0;
3394 end;
3395 end;
3397 if NetMode = NET_SERVER then
3398 begin
3399 MH_SEND_GameEvent(NET_EV_MAPSTART, gGameSettings.GameMode, Map);
3401 // Мастерсервер
3402 g_Net_Slist_ServerMapStarted();
3404 if NetClients <> nil then
3405 for I := 0 to High(NetClients) do
3406 if NetClients[I].Used then
3407 begin
3408 NetClients[I].Voted := False;
3409 if NetClients[I].RequestedFullUpdate then
3410 begin
3411 MH_SEND_Everything((NetClients[I].State = NET_STATE_AUTH), I);
3412 NetClients[I].RequestedFullUpdate := False;
3413 end;
3414 end;
3416 g_Net_UnbanNonPermHosts();
3417 end;
3419 if gLastMap then
3420 begin
3421 gCoopTotalMonstersKilled := 0;
3422 gCoopTotalSecretsFound := 0;
3423 gCoopTotalMonsters := 0;
3424 gCoopTotalSecrets := 0;
3425 gLastMap := False;
3426 end;
3428 g_Game_ExecuteEvent('onmapstart');
3429 end;
3431 procedure SetFirstLevel;
3432 begin
3433 gNextMap := '';
3435 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3436 if MapList = nil then
3437 Exit;
3439 SortSArray(MapList);
3440 gNextMap := MapList[Low(MapList)];
3442 MapList := nil;
3443 end;
3445 procedure g_Game_ExitLevel(const Map: AnsiString);
3446 begin
3447 gNextMap := Map;
3449 gCoopTotalMonstersKilled := gCoopTotalMonstersKilled + gCoopMonstersKilled;
3450 gCoopTotalSecretsFound := gCoopTotalSecretsFound + gCoopSecretsFound;
3451 gCoopTotalMonsters := gCoopTotalMonsters + gTotalMonsters;
3452 gCoopTotalSecrets := gCoopTotalSecrets + gSecretsCount;
3454 // Вышли в выход в Одиночной игре:
3455 if gGameSettings.GameType = GT_SINGLE then
3456 gExit := EXIT_ENDLEVELSINGLE
3457 else // Вышли в выход в Своей игре
3458 begin
3459 gExit := EXIT_ENDLEVELCUSTOM;
3460 if gGameSettings.GameMode = GM_COOP then
3461 g_Player_RememberAll;
3463 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3464 begin
3465 gLastMap := True;
3466 if gGameSettings.GameMode = GM_COOP then
3467 gStatsOff := True;
3469 gStatsPressed := True;
3470 gNextMap := 'MAP01';
3472 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3473 g_Game_NextLevel;
3475 if g_Game_IsNet then
3476 begin
3477 MH_SEND_GameStats();
3478 MH_SEND_CoopStats();
3479 end;
3480 end;
3481 end;
3482 end;
3484 procedure g_Game_RestartLevel();
3485 var
3486 Map: string;
3487 begin
3488 if gGameSettings.GameMode = GM_SINGLE then
3489 begin
3490 g_Game_Restart();
3491 Exit;
3492 end;
3493 gExit := EXIT_ENDLEVELCUSTOM;
3494 Map := g_ExtractFileName(gMapInfo.Map);
3495 gNextMap := Map;
3496 end;
3498 function g_Game_ClientWAD (NewWAD: String; const WHash: TMD5Digest): AnsiString;
3499 var
3500 gWAD{, xwad}: String;
3501 begin
3502 result := NewWAD;
3503 if not g_Game_IsClient then Exit;
3504 //e_LogWritefln('*** g_Game_ClientWAD: `%s`', [NewWAD]);
3506 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3507 if gWAD = '' then
3508 begin
3509 result := '';
3510 g_Game_Free();
3511 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3512 Exit;
3513 end;
3515 e_LogWritefln('using downloaded client map wad [%s] for [%s]', [gWAD, NewWAD], TMsgType.Notify);
3516 NewWAD := gWAD;
3518 g_Game_LoadWAD(NewWAD);
3519 result := NewWAD;
3522 if LowerCase(NewWAD) = LowerCase(gGameSettings.WAD) then Exit;
3523 gWAD := g_Res_SearchSameWAD(MapsDir, ExtractFileName(NewWAD), WHash);
3524 if gWAD = '' then
3525 begin
3526 g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
3527 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3528 if gWAD = '' then
3529 begin
3530 g_Game_Free();
3531 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3532 Exit;
3533 end;
3534 end;
3535 NewWAD := ExtractRelativePath(MapsDir, gWAD);
3536 g_Game_LoadWAD(NewWAD);
3538 end;
3540 procedure g_Game_RestartRound(NoMapRestart: Boolean = False);
3541 var
3542 i, n, nb, nr: Integer;
3543 begin
3544 if not g_Game_IsServer then Exit;
3545 if gLMSRespawn = LMS_RESPAWN_NONE then Exit;
3546 gLMSRespawn := LMS_RESPAWN_NONE;
3547 gLMSRespawnTime := 0;
3548 MessageTime := 0;
3550 if (gGameSettings.GameMode = GM_COOP) and not NoMapRestart then
3551 begin
3552 gMissionFailed := True;
3553 g_Game_RestartLevel;
3554 Exit;
3555 end;
3557 n := 0; nb := 0; nr := 0;
3558 for i := Low(gPlayers) to High(gPlayers) do
3559 if (gPlayers[i] <> nil) and
3560 ((not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame or
3561 (gPlayers[i] is TBot)) then
3562 begin
3563 Inc(n);
3564 if gPlayers[i].Team = TEAM_RED then Inc(nr)
3565 else if gPlayers[i].Team = TEAM_BLUE then Inc(nb)
3566 end;
3568 if (n < 1) or ((gGameSettings.GameMode = GM_TDM) and ((nr = 0) or (nb = 0))) then
3569 begin
3570 // wait a second until the fuckers finally decide to join
3571 gLMSRespawn := LMS_RESPAWN_WARMUP;
3572 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3573 gLMSSoftSpawn := NoMapRestart;
3574 if g_Game_IsNet then
3575 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3576 Exit;
3577 end;
3579 g_Player_RemoveAllCorpses;
3580 g_Game_Message(_lc[I_MESSAGE_LMS_START], 144);
3581 if g_Game_IsNet then
3582 MH_SEND_GameEvent(NET_EV_LMS_START);
3584 for i := Low(gPlayers) to High(gPlayers) do
3585 begin
3586 if gPlayers[i] = nil then continue;
3587 if gPlayers[i] is TBot then gPlayers[i].FWantsInGame := True;
3588 // don't touch normal spectators
3589 if gPlayers[i].FSpectator and not gPlayers[i].FWantsInGame then
3590 begin
3591 gPlayers[i].FNoRespawn := True;
3592 gPlayers[i].Lives := 0;
3593 if g_Game_IsNet then
3594 MH_SEND_PlayerStats(gPlayers[I].UID);
3595 continue;
3596 end;
3597 gPlayers[i].FNoRespawn := False;
3598 gPlayers[i].Lives := gGameSettings.MaxLives;
3599 gPlayers[i].Respawn(False, True);
3600 if gGameSettings.GameMode = GM_COOP then
3601 begin
3602 gPlayers[i].Frags := 0;
3603 gPlayers[i].RecallState;
3604 end;
3605 if (gPlayer1 = nil) and (gSpectLatchPID1 > 0) then
3606 gPlayer1 := g_Player_Get(gSpectLatchPID1);
3607 if (gPlayer2 = nil) and (gSpectLatchPID2 > 0) then
3608 gPlayer2 := g_Player_Get(gSpectLatchPID2);
3609 end;
3611 g_Items_RestartRound();
3613 gLMSSoftSpawn := False;
3614 end;
3616 function g_Game_GetFirstMap(WAD: String): String;
3617 begin
3618 Result := '';
3620 MapList := g_Map_GetMapsList(WAD);
3621 if MapList = nil then
3622 Exit;
3624 SortSArray(MapList);
3625 Result := MapList[Low(MapList)];
3627 if not g_Map_Exist(WAD + ':\' + Result) then
3628 Result := '';
3630 MapList := nil;
3631 end;
3633 function g_Game_GetNextMap(): String;
3634 var
3635 I: Integer;
3636 Map: string;
3637 begin
3638 Result := '';
3640 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3641 if MapList = nil then
3642 Exit;
3644 Map := g_ExtractFileName(gMapInfo.Map);
3646 SortSArray(MapList);
3647 MapIndex := -255;
3648 for I := Low(MapList) to High(MapList) do
3649 if Map = MapList[I] then
3650 begin
3651 MapIndex := I;
3652 Break;
3653 end;
3655 if MapIndex <> -255 then
3656 begin
3657 if MapIndex = High(MapList) then
3658 Result := MapList[Low(MapList)]
3659 else
3660 Result := MapList[MapIndex + 1];
3662 if not g_Map_Exist(gGameSettings.WAD + ':\' + Result) then Result := Map;
3663 end;
3665 MapList := nil;
3666 end;
3668 procedure g_Game_NextLevel();
3669 begin
3670 if gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP] then
3671 gExit := EXIT_ENDLEVELCUSTOM
3672 else
3673 begin
3674 gExit := EXIT_ENDLEVELSINGLE;
3675 Exit;
3676 end;
3678 if gNextMap <> '' then Exit;
3679 gNextMap := g_Game_GetNextMap();
3680 end;
3682 function g_Game_IsTestMap(): Boolean;
3683 begin
3684 result := StrEquCI1251(TEST_MAP_NAME, g_ExtractFileName(gMapInfo.Map));
3685 end;
3687 procedure g_Game_DeleteTestMap();
3688 var
3689 a: Integer;
3690 //MapName: AnsiString;
3691 WadName: string;
3693 WAD: TWADFile;
3694 MapList: SSArray;
3695 time: Integer;
3697 begin
3698 a := Pos('.wad:\', toLowerCase1251(gMapToDelete));
3699 if (a = 0) then a := Pos('.wad:/', toLowerCase1251(gMapToDelete));
3700 if (a = 0) then exit;
3702 // Выделяем имя wad-файла и имя карты
3703 WadName := Copy(gMapToDelete, 1, a+3);
3704 Delete(gMapToDelete, 1, a+5);
3705 gMapToDelete := UpperCase(gMapToDelete);
3706 //MapName := '';
3707 //CopyMemory(@MapName[0], @gMapToDelete[1], Min(16, Length(gMapToDelete)));
3710 // Имя карты не стандартное тестовое:
3711 if MapName <> TEST_MAP_NAME then
3712 Exit;
3714 if not gTempDelete then
3715 begin
3716 time := g_GetFileTime(WadName);
3717 WAD := TWADFile.Create();
3719 // Читаем Wad-файл:
3720 if not WAD.ReadFile(WadName) then
3721 begin // Нет такого WAD-файла
3722 WAD.Free();
3723 Exit;
3724 end;
3726 // Составляем список карт и ищем нужную:
3727 WAD.CreateImage();
3728 MapList := WAD.GetResourcesList('');
3730 if MapList <> nil then
3731 for a := 0 to High(MapList) do
3732 if MapList[a] = MapName then
3733 begin
3734 // Удаляем и сохраняем:
3735 WAD.RemoveResource('', MapName);
3736 WAD.SaveTo(WadName);
3737 Break;
3738 end;
3740 WAD.Free();
3741 g_SetFileTime(WadName, time);
3742 end else
3744 if gTempDelete then DeleteFile(WadName);
3745 end;
3747 procedure GameCVars(P: SSArray);
3748 var
3749 a, b: Integer;
3750 stat: TPlayerStatArray;
3751 cmd: string;
3753 procedure ParseGameFlag(Flag: LongWord; OffMsg, OnMsg: TStrings_Locale; OnMapChange: Boolean = False);
3754 var
3755 x: Boolean;
3756 begin
3757 if Length(P) > 1 then
3758 begin
3759 x := P[1] = '1';
3761 if x then
3762 gsGameFlags := gsGameFlags or Flag
3763 else
3764 gsGameFlags := gsGameFlags and (not Flag);
3766 if g_Game_IsServer then
3767 begin
3768 if x then
3769 gGameSettings.Options := gGameSettings.Options or Flag
3770 else
3771 gGameSettings.Options := gGameSettings.Options and (not Flag);
3772 if g_Game_IsNet then MH_SEND_GameSettings;
3773 end;
3774 end;
3776 if LongBool(gsGameFlags and Flag) then
3777 g_Console_Add(_lc[OnMsg])
3778 else
3779 g_Console_Add(_lc[OffMsg]);
3781 if OnMapChange and g_Game_IsServer then
3782 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3783 end;
3785 begin
3786 stat := nil;
3787 cmd := LowerCase(P[0]);
3789 if cmd = 'g_gamemode' then
3790 begin
3791 if (Length(P) > 1) then
3792 begin
3793 a := g_Game_TextToMode(P[1]);
3794 if a = GM_SINGLE then a := GM_COOP;
3795 gsGameMode := g_Game_ModeToText(a);
3796 if g_Game_IsServer then
3797 begin
3798 gSwitchGameMode := a;
3799 if (gGameOn and (gGameSettings.GameMode = GM_SINGLE)) or
3800 (gState = STATE_INTERSINGLE) then
3801 gSwitchGameMode := GM_SINGLE;
3802 if not gGameOn then
3803 gGameSettings.GameMode := gSwitchGameMode;
3804 end;
3805 end;
3807 if gSwitchGameMode = gGameSettings.GameMode then
3808 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CURRENT],
3809 [g_Game_ModeToText(gGameSettings.GameMode)]))
3810 else
3811 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CHANGE],
3812 [g_Game_ModeToText(gGameSettings.GameMode),
3813 g_Game_ModeToText(gSwitchGameMode)]));
3814 end
3815 else if cmd = 'g_friendlyfire' then
3816 begin
3817 ParseGameFlag(GAME_OPTION_TEAMDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3818 end
3819 else if cmd = 'g_friendly_absorb_damage' then
3820 begin
3821 ParseGameFlag(GAME_OPTION_TEAMABSORBDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3822 end
3823 else if cmd = 'g_friendly_hit_trace' then
3824 begin
3825 ParseGameFlag(GAME_OPTION_TEAMHITTRACE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3826 end
3827 else if cmd = 'g_friendly_hit_projectile' then
3828 begin
3829 ParseGameFlag(GAME_OPTION_TEAMHITPROJECTILE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3830 end
3831 else if cmd = 'g_weaponstay' then
3832 begin
3833 ParseGameFlag(GAME_OPTION_WEAPONSTAY, I_MSG_WEAPONSTAY_OFF, I_MSG_WEAPONSTAY_ON);
3834 end
3835 else if cmd = 'g_allow_exit' then
3836 begin
3837 ParseGameFlag(GAME_OPTION_ALLOWEXIT, I_MSG_ALLOWEXIT_OFF, I_MSG_ALLOWEXIT_ON, True);
3838 end
3839 else if cmd = 'g_allow_monsters' then
3840 begin
3841 ParseGameFlag(GAME_OPTION_MONSTERS, I_MSG_ALLOWMON_OFF, I_MSG_ALLOWMON_ON, True);
3842 end
3843 else if cmd = 'g_bot_vsplayers' then
3844 begin
3845 ParseGameFlag(GAME_OPTION_BOTVSPLAYER, I_MSG_BOTSVSPLAYERS_OFF, I_MSG_BOTSVSPLAYERS_ON);
3846 end
3847 else if cmd = 'g_bot_vsmonsters' then
3848 begin
3849 ParseGameFlag(GAME_OPTION_BOTVSMONSTER, I_MSG_BOTSVSMONSTERS_OFF, I_MSG_BOTSVSMONSTERS_ON);
3850 end
3851 else if cmd = 'g_dm_keys' then
3852 begin
3853 ParseGameFlag(GAME_OPTION_DMKEYS, I_MSG_DMKEYS_OFF, I_MSG_DMKEYS_ON, True);
3854 end
3855 else if cmd = 'g_gameflags' then
3856 begin
3857 if Length(P) > 1 then
3858 begin
3859 gsGameFlags := StrToDWordDef(P[1], gsGameFlags);
3860 if g_Game_IsServer then
3861 begin
3862 gGameSettings.Options := gsGameFlags;
3863 if g_Game_IsNet then MH_SEND_GameSettings;
3864 end;
3865 end;
3867 g_Console_Add(Format('%s %u', [cmd, gsGameFlags]));
3868 end
3869 else if cmd = 'g_warmup_time' then
3870 begin
3871 if Length(P) > 1 then
3872 begin
3873 gsWarmupTime := nclamp(StrToIntDef(P[1], gsWarmupTime), 0, $FFFF);
3874 if g_Game_IsServer then
3875 begin
3876 gGameSettings.WarmupTime := gsWarmupTime;
3877 // extend warmup if it's already going
3878 if gLMSRespawn = LMS_RESPAWN_WARMUP then
3879 begin
3880 gLMSRespawnTime := gTime + gsWarmupTime * 1000;
3881 if g_Game_IsNet then MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3882 end;
3883 if g_Game_IsNet then MH_SEND_GameSettings;
3884 end;
3885 end;
3887 g_Console_Add(Format(_lc[I_MSG_WARMUP], [Integer(gsWarmupTime)]));
3888 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3889 end
3890 else if cmd = 'g_spawn_invul' then
3891 begin
3892 if Length(P) > 1 then
3893 begin
3894 gsSpawnInvul := nclamp(StrToIntDef(P[1], gsSpawnInvul), 0, $FFFF);
3895 if g_Game_IsServer then
3896 begin
3897 gGameSettings.SpawnInvul := gsSpawnInvul;
3898 if g_Game_IsNet then MH_SEND_GameSettings;
3899 end;
3900 end;
3902 g_Console_Add(Format('%s %d', [cmd, Integer(gsSpawnInvul)]));
3903 end
3904 else if cmd = 'g_item_respawn_time' then
3905 begin
3906 if Length(P) > 1 then
3907 begin
3908 gsItemRespawnTime := nclamp(StrToIntDef(P[1], gsItemRespawnTime), 0, $FFFF);
3909 if g_Game_IsServer then
3910 begin
3911 gGameSettings.ItemRespawnTime := gsItemRespawnTime;
3912 if g_Game_IsNet then MH_SEND_GameSettings;
3913 end;
3914 end;
3916 g_Console_Add(Format('%s %d', [cmd, Integer(gsItemRespawnTime)]));
3917 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3918 end
3919 else if cmd = 'sv_intertime' then
3920 begin
3921 if (Length(P) > 1) then
3922 gDefInterTime := Min(Max(StrToIntDef(P[1], gDefInterTime), -1), 120);
3924 g_Console_Add(cmd + ' = ' + IntToStr(gDefInterTime));
3925 end
3926 else if cmd = 'g_max_particles' then
3927 begin
3928 if Length(p) = 2 then
3929 begin
3930 a := Max(0, StrToInt(p[1]));
3931 g_GFX_SetMax(a)
3932 end
3933 else if Length(p) = 1 then
3934 begin
3935 e_LogWritefln('%s', [g_GFX_GetMax()])
3936 end
3937 else
3938 begin
3939 e_LogWritefln('usage: %s <n>', [cmd])
3940 end
3941 end
3942 else if cmd = 'g_max_shells' then
3943 begin
3944 if Length(p) = 2 then
3945 begin
3946 a := Max(0, StrToInt(p[1]));
3947 g_Shells_SetMax(a)
3948 end
3949 else if Length(p) = 1 then
3950 begin
3951 e_LogWritefln('%s', [g_Shells_GetMax()])
3952 end
3953 else
3954 begin
3955 e_LogWritefln('usage: %s <n>', [cmd])
3956 end
3957 end
3958 else if cmd = 'g_max_gibs' then
3959 begin
3960 if Length(p) = 2 then
3961 begin
3962 a := Max(0, StrToInt(p[1]));
3963 g_Gibs_SetMax(a)
3964 end
3965 else if Length(p) = 1 then
3966 begin
3967 e_LogWritefln('%s', [g_Gibs_GetMax()])
3968 end
3969 else
3970 begin
3971 e_LogWritefln('usage: %s <n>', [cmd])
3972 end
3973 end
3974 else if cmd = 'g_max_corpses' then
3975 begin
3976 if Length(p) = 2 then
3977 begin
3978 a := Max(0, StrToInt(p[1]));
3979 g_Corpses_SetMax(a)
3980 end
3981 else if Length(p) = 1 then
3982 begin
3983 e_LogWritefln('%s', [g_Corpses_GetMax()])
3984 end
3985 else
3986 begin
3987 e_LogWritefln('usage: %s <n>', [cmd])
3988 end
3989 end
3990 else if cmd = 'g_scorelimit' then
3991 begin
3992 if Length(P) > 1 then
3993 begin
3994 gsGoalLimit := nclamp(StrToIntDef(P[1], gsGoalLimit), 0, $FFFF);
3996 if g_Game_IsServer then
3997 begin
3998 b := 0;
3999 if gGameSettings.GameMode = GM_DM then
4000 begin // DM
4001 stat := g_Player_GetStats();
4002 if stat <> nil then
4003 for a := 0 to High(stat) do
4004 if stat[a].Frags > b then
4005 b := stat[a].Frags;
4006 end
4007 else // TDM/CTF
4008 b := Max(gTeamStat[TEAM_RED].Goals, gTeamStat[TEAM_BLUE].Goals);
4010 // if someone has a higher score, set it to that instead
4011 gsGoalLimit := max(gsGoalLimit, b);
4012 gGameSettings.GoalLimit := gsGoalLimit;
4014 if g_Game_IsNet then MH_SEND_GameSettings;
4015 end;
4016 end;
4018 g_Console_Add(Format(_lc[I_MSG_SCORE_LIMIT], [Integer(gsGoalLimit)]));
4019 end
4020 else if cmd = 'g_timelimit' then
4021 begin
4022 if Length(P) > 1 then
4023 begin
4024 gsTimeLimit := nclamp(StrToIntDef(P[1], gsTimeLimit), 0, $FFFF);
4025 if g_Game_IsServer then
4026 begin
4027 gGameSettings.TimeLimit := gsTimeLimit;
4028 if g_Game_IsNet then MH_SEND_GameSettings;
4029 end;
4030 end;
4031 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
4032 [gsTimeLimit div 3600,
4033 (gsTimeLimit div 60) mod 60,
4034 gsTimeLimit mod 60]));
4035 end
4036 else if cmd = 'g_maxlives' then
4037 begin
4038 if Length(P) > 1 then
4039 begin
4040 gsMaxLives := nclamp(StrToIntDef(P[1], gsMaxLives), 0, $FFFF);
4041 if g_Game_IsServer then
4042 begin
4043 gGameSettings.MaxLives := gsMaxLives;
4044 if g_Game_IsNet then MH_SEND_GameSettings;
4045 end;
4046 end;
4048 g_Console_Add(Format(_lc[I_MSG_LIVES], [Integer(gsMaxLives)]));
4049 end;
4050 end;
4052 procedure PlayerSettingsCVars(P: SSArray);
4053 var
4054 cmd: string;
4055 team: Byte;
4057 function ParseTeam(s: string): Byte;
4058 begin
4059 result := 0;
4060 case s of
4061 'red', '1': result := TEAM_RED;
4062 'blue', '2': result := TEAM_BLUE;
4063 else result := TEAM_NONE;
4064 end;
4065 end;
4066 begin
4067 cmd := LowerCase(P[0]);
4068 case cmd of
4069 'p1_name':
4070 begin
4071 if (Length(P) > 1) then
4072 begin
4073 gPlayer1Settings.Name := b_Text_Unformat(P[1]);
4074 if g_Game_IsClient then
4075 MC_SEND_PlayerSettings
4076 else if gGameOn and (gPlayer1 <> nil) then
4077 begin
4078 gPlayer1.Name := b_Text_Unformat(P[1]);
4079 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4080 end;
4081 end;
4082 end;
4083 'p2_name':
4084 begin
4085 if (Length(P) > 1) then
4086 begin
4087 gPlayer2Settings.Name := b_Text_Unformat(P[1]);
4088 if g_Game_IsClient then
4089 MC_SEND_PlayerSettings
4090 else if gGameOn and (gPlayer2 <> nil) then
4091 begin
4092 gPlayer2.Name := b_Text_Unformat(P[1]);
4093 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4094 end;
4095 end;
4096 end;
4097 'p1_color':
4098 begin
4099 if Length(P) > 3 then
4100 begin
4101 gPlayer1Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
4102 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
4103 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
4104 if g_Game_IsClient then
4105 MC_SEND_PlayerSettings
4106 else if gGameOn and (gPlayer1 <> nil) then
4107 begin
4108 gPlayer1.SetColor(gPlayer1Settings.Color);
4109 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4110 end;
4111 end;
4112 end;
4113 'p2_color':
4114 begin
4115 if Length(P) > 3 then
4116 begin
4117 gPlayer2Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
4118 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
4119 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
4120 if g_Game_IsClient then
4121 MC_SEND_PlayerSettings
4122 else if gGameOn and (gPlayer2 <> nil) then
4123 begin
4124 gPlayer2.SetColor(gPlayer2Settings.Color);
4125 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4126 end;
4127 end;
4128 end;
4129 'p1_model':
4130 begin
4131 if (Length(P) > 1) then
4132 begin
4133 gPlayer1Settings.Model := P[1];
4134 if g_Game_IsClient then
4135 MC_SEND_PlayerSettings
4136 else if gGameOn and (gPlayer1 <> nil) then
4137 begin
4138 gPlayer1.FActualModelName := gPlayer1Settings.Model;
4139 gPlayer1.SetModel(gPlayer1Settings.Model);
4140 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4141 end;
4142 end;
4143 end;
4144 'p2_model':
4145 begin
4146 if (Length(P) > 1) then
4147 begin
4148 gPlayer2Settings.Model := P[1];
4149 if g_Game_IsClient then
4150 MC_SEND_PlayerSettings
4151 else if gGameOn and (gPlayer2 <> nil) then
4152 begin
4153 gPlayer2.FActualModelName := gPlayer2Settings.Model;
4154 gPlayer2.SetModel(gPlayer2Settings.Model);
4155 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4156 end;
4157 end;
4158 end;
4159 'p1_team':
4160 begin
4161 // TODO: switch teams if in game or store this separately
4162 if (Length(P) > 1) then
4163 begin
4164 team := ParseTeam(P[1]);
4165 if team = TEAM_NONE then
4166 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4167 else if not gGameOn and not g_Game_IsNet then
4168 gPlayer1Settings.Team := team
4169 else
4170 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4171 end;
4172 end;
4173 'p2_team':
4174 begin
4175 // TODO: switch teams if in game or store this separately
4176 if (Length(P) > 1) then
4177 begin
4178 team := ParseTeam(P[1]);
4179 if team = TEAM_NONE then
4180 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4181 else if not gGameOn and not g_Game_IsNet then
4182 gPlayer2Settings.Team := team
4183 else
4184 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4185 end;
4186 end;
4187 end;
4188 end;
4190 procedure PrintHeapStats();
4191 var
4192 hs: TFPCHeapStatus;
4193 begin
4194 hs := GetFPCHeapStatus();
4195 e_LogWriteLn ('v===== heap status =====v');
4196 e_LogWriteFln('max heap size = %d k', [hs.MaxHeapSize div 1024]);
4197 e_LogWriteFln('max heap used = %d k', [hs.MaxHeapUsed div 1024]);
4198 e_LogWriteFln('cur heap size = %d k', [hs.CurrHeapSize div 1024]);
4199 e_LogWriteFln('cur heap used = %d k', [hs.CurrHeapUsed div 1024]);
4200 e_LogWriteFln('cur heap free = %d k', [hs.CurrHeapFree div 1024]);
4201 e_LogWriteLn ('^=======================^');
4202 end;
4204 procedure DebugCommands(P: SSArray);
4205 var
4206 a, b: Integer;
4207 cmd: string;
4208 //pt: TDFPoint;
4209 mon: TMonster;
4210 begin
4211 // Команды отладочного режима:
4212 if {gDebugMode}conIsCheatsEnabled then
4213 begin
4214 cmd := LowerCase(P[0]);
4215 if cmd = 'd_window' then
4216 begin
4217 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4218 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4219 end
4220 else if cmd = 'd_sounds' then
4221 begin
4222 if (Length(P) > 1) and
4223 ((P[1] = '1') or (P[1] = '0')) then
4224 g_Debug_Sounds := (P[1][1] = '1');
4226 g_Console_Add(Format('d_sounds is %d', [Byte(g_Debug_Sounds)]));
4227 end
4228 else if cmd = 'd_frames' then
4229 begin
4230 if (Length(P) > 1) and
4231 ((P[1] = '1') or (P[1] = '0')) then
4232 g_Debug_Frames := (P[1][1] = '1');
4234 g_Console_Add(Format('d_frames is %d', [Byte(g_Debug_Frames)]));
4235 end
4236 else if cmd = 'd_winmsg' then
4237 begin
4238 if (Length(P) > 1) and
4239 ((P[1] = '1') or (P[1] = '0')) then
4240 g_Debug_WinMsgs := (P[1][1] = '1');
4242 g_Console_Add(Format('d_winmsg is %d', [Byte(g_Debug_WinMsgs)]));
4243 end
4244 else if (cmd = 'd_monoff') and not g_Game_IsNet then
4245 begin
4246 if (Length(P) > 1) and
4247 ((P[1] = '1') or (P[1] = '0')) then
4248 g_Debug_MonsterOff := (P[1][1] = '1');
4250 g_Console_Add(Format('d_monoff is %d', [Byte(g_debug_MonsterOff)]));
4251 end
4252 else if (cmd = 'd_botoff') and not g_Game_IsNet then
4253 begin
4254 if Length(P) > 1 then
4255 case P[1][1] of
4256 '0': g_debug_BotAIOff := 0;
4257 '1': g_debug_BotAIOff := 1;
4258 '2': g_debug_BotAIOff := 2;
4259 '3': g_debug_BotAIOff := 3;
4260 end;
4262 g_Console_Add(Format('d_botoff is %d', [g_debug_BotAIOff]));
4263 end
4264 else if cmd = 'd_monster' then
4265 begin
4266 if gGameOn and (gPlayer1 <> nil) and (gPlayer1.alive) and (not g_Game_IsNet) then
4267 if Length(P) < 2 then
4268 begin
4269 g_Console_Add(cmd + ' [ID | Name] [behaviour]');
4270 g_Console_Add('ID | Name');
4271 for b := MONSTER_DEMON to MONSTER_MAN do
4272 g_Console_Add(Format('%2d | %s', [b, g_Mons_NameByTypeId(b)]));
4273 conwriteln('behav. num'#10'normal 0'#10'killer 1'#10'maniac 2'#10'insane 3'#10'cannibal 4'#10'good 5');
4274 end else
4275 begin
4276 a := StrToIntDef(P[1], 0);
4277 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4278 a := g_Mons_TypeIdByName(P[1]);
4280 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4281 g_Console_Add(Format(_lc[I_MSG_NO_MONSTER], [P[1]]))
4282 else
4283 begin
4284 with gPlayer1.Obj do
4285 begin
4286 mon := g_Monsters_Create(a,
4287 X + Rect.X + (Rect.Width div 2),
4288 Y + Rect.Y + Rect.Height,
4289 gPlayer1.Direction, True);
4290 end;
4291 if (Length(P) > 2) and (mon <> nil) then
4292 begin
4293 if (CompareText(P[2], 'normal') = 0) then mon.MonsterBehaviour := BH_NORMAL
4294 else if (CompareText(P[2], 'killer') = 0) then mon.MonsterBehaviour := BH_KILLER
4295 else if (CompareText(P[2], 'maniac') = 0) then mon.MonsterBehaviour := BH_MANIAC
4296 else if (CompareText(P[2], 'insane') = 0) then mon.MonsterBehaviour := BH_INSANE
4297 else if (CompareText(P[2], 'cannibal') = 0) then mon.MonsterBehaviour := BH_CANNIBAL
4298 else if (CompareText(P[2], 'good') = 0) then mon.MonsterBehaviour := BH_GOOD
4299 else if (CompareText(P[2], 'friend') = 0) then mon.MonsterBehaviour := BH_GOOD
4300 else if (CompareText(P[2], 'friendly') = 0) then mon.MonsterBehaviour := BH_GOOD
4301 else mon.MonsterBehaviour := Min(Max(StrToIntDef(P[2], BH_NORMAL), BH_NORMAL), BH_GOOD);
4302 end;
4303 end;
4304 end;
4305 end
4306 else if (cmd = 'd_health') then
4307 begin
4308 if (Length(P) > 1) and
4309 ((P[1] = '1') or (P[1] = '0')) then
4310 g_debug_HealthBar := (P[1][1] = '1');
4312 g_Console_Add(Format('d_health is %d', [Byte(g_debug_HealthBar)]));
4313 end
4314 else if (cmd = 'd_player') then
4315 begin
4316 if (Length(P) > 1) and
4317 ((P[1] = '1') or (P[1] = '0')) then
4318 g_debug_Player := (P[1][1] = '1');
4320 g_Console_Add(Format(cmd + ' is %d', [Byte(g_Debug_Player)]));
4321 end
4322 else if (cmd = 'd_mem') then
4323 begin
4324 PrintHeapStats();
4325 end;
4326 end
4327 else
4328 g_Console_Add(_lc[I_MSG_NOT_DEBUG]);
4329 end;
4332 procedure GameCheats(P: SSArray);
4333 var
4334 cmd: string;
4335 f, a: Integer;
4336 plr: TPlayer;
4337 begin
4338 if (not gGameOn) or (not conIsCheatsEnabled) then
4339 begin
4340 g_Console_Add('not available');
4341 exit;
4342 end;
4343 plr := gPlayer1;
4344 if plr = nil then
4345 begin
4346 g_Console_Add('where is the player?!');
4347 exit;
4348 end;
4349 cmd := LowerCase(P[0]);
4350 // god
4351 if cmd = 'god' then
4352 begin
4353 plr.GodMode := not plr.GodMode;
4354 if plr.GodMode then g_Console_Add('player is godlike now') else g_Console_Add('player is mortal now');
4355 exit;
4356 end;
4357 // give <health|exit|weapons|air|suit|jetpack|berserk|all>
4358 if cmd = 'give' then
4359 begin
4360 if length(P) < 2 then begin g_Console_Add('give what?!'); exit; end;
4361 for f := 1 to High(P) do
4362 begin
4363 cmd := LowerCase(P[f]);
4364 if cmd = 'health' then begin plr.RestoreHealthArmor(); g_Console_Add('player feels himself better'); continue; end;
4365 if (cmd = 'all') {or (cmd = 'weapons')} then begin plr.AllRulez(False); g_Console_Add('player got the gifts'); continue; end;
4366 if cmd = 'exit' then
4367 begin
4368 if gTriggers <> nil then
4369 begin
4370 for a := 0 to High(gTriggers) do
4371 begin
4372 if gTriggers[a].TriggerType = TRIGGER_EXIT then
4373 begin
4374 g_Console_Add('player left the map');
4375 gExitByTrigger := True;
4376 //g_Game_ExitLevel(gTriggers[a].Data.MapName);
4377 g_Game_ExitLevel(gTriggers[a].tgcMap);
4378 break;
4379 end;
4380 end;
4381 end;
4382 continue;
4383 end;
4385 if cmd = 'air' then begin plr.GiveItem(ITEM_OXYGEN); g_Console_Add('player got some air'); continue; end;
4386 if cmd = 'jetpack' then begin plr.GiveItem(ITEM_JETPACK); g_Console_Add('player got a jetpack'); continue; end;
4387 if cmd = 'suit' then begin plr.GiveItem(ITEM_SUIT); g_Console_Add('player got an envirosuit'); continue; end;
4388 if cmd = 'berserk' then begin plr.GiveItem(ITEM_MEDKIT_BLACK); g_Console_Add('player got a berserk pack'); continue; end;
4389 if cmd = 'backpack' then begin plr.GiveItem(ITEM_AMMO_BACKPACK); g_Console_Add('player got a backpack'); continue; end;
4391 if cmd = 'helmet' then begin plr.GiveItem(ITEM_HELMET); g_Console_Add('player got a helmet'); continue; end;
4392 if cmd = 'bottle' then begin plr.GiveItem(ITEM_BOTTLE); g_Console_Add('player got a bottle of health'); continue; end;
4394 if cmd = 'stimpack' then begin plr.GiveItem(ITEM_MEDKIT_SMALL); g_Console_Add('player got a stimpack'); continue; end;
4395 if (cmd = 'medkit') or (cmd = 'medikit') or (cmd = 'medpack') or (cmd = 'medipack') then begin plr.GiveItem(ITEM_MEDKIT_LARGE); g_Console_Add('player got a '+cmd); continue; end;
4397 if cmd = 'greenarmor' then begin plr.GiveItem(ITEM_ARMOR_GREEN); g_Console_Add('player got a security armor'); continue; end;
4398 if cmd = 'bluearmor' then begin plr.GiveItem(ITEM_ARMOR_BLUE); g_Console_Add('player got a combat armor'); continue; end;
4400 if (cmd = 'megasphere') or (cmd = 'mega') then begin plr.GiveItem(ITEM_SPHERE_BLUE); g_Console_Add('player got a megasphere'); continue; end;
4401 if (cmd = 'soulsphere') or (cmd = 'soul')then begin plr.GiveItem(ITEM_SPHERE_WHITE); g_Console_Add('player got a soul sphere'); continue; end;
4403 if (cmd = 'invul') or (cmd = 'invulnerability') then begin plr.GiveItem(ITEM_INVUL); g_Console_Add('player got invulnerability'); continue; end;
4404 if (cmd = 'invis') or (cmd = 'invisibility') then begin plr.GiveItem(ITEM_INVIS); g_Console_Add('player got invisibility'); continue; end;
4406 if cmd = 'redkey' then begin plr.GiveItem(ITEM_KEY_RED); g_Console_Add('player got the red key'); continue; end;
4407 if cmd = 'greenkey' then begin plr.GiveItem(ITEM_KEY_GREEN); g_Console_Add('player got the green key'); continue; end;
4408 if cmd = 'bluekey' then begin plr.GiveItem(ITEM_KEY_BLUE); g_Console_Add('player got the blue key'); continue; end;
4410 if (cmd = 'shotgun') or (cmd = 'sg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN1); g_Console_Add('player got a shotgun'); continue; end;
4411 if (cmd = 'supershotgun') or (cmd = 'ssg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN2); g_Console_Add('player got a supershotgun'); continue; end;
4412 if cmd = 'chaingun' then begin plr.GiveItem(ITEM_WEAPON_CHAINGUN); g_Console_Add('player got a chaingun'); continue; end;
4413 if (cmd = 'launcher') or (cmd = 'rocketlauncher') or (cmd = 'rl') then begin plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER); g_Console_Add('player got a rocket launcher'); continue; end;
4414 if cmd = 'plasmagun' then begin plr.GiveItem(ITEM_WEAPON_PLASMA); g_Console_Add('player got a plasma gun'); continue; end;
4415 if cmd = 'bfg' then begin plr.GiveItem(ITEM_WEAPON_BFG); g_Console_Add('player got a BFG-9000'); continue; end;
4417 if (cmd = 'shotgunzz') or (cmd = 'sgzz') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN1); plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a shotgun'); continue; end;
4418 if (cmd = 'supershotgunzz') or (cmd = 'ssgzz') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN2); plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a supershotgun'); continue; end;
4419 if cmd = 'chaingunzz' then begin plr.GiveItem(ITEM_WEAPON_CHAINGUN); plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a chaingun'); continue; end;
4420 if (cmd = 'launcherzz') or (cmd = 'rocketlauncherzz') or (cmd = 'rlzz') then begin plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER); plr.GiveItem(ITEM_AMMO_ROCKET_BOX); g_Console_Add('player got a rocket launcher'); continue; end;
4421 if cmd = 'plasmagunzz' then begin plr.GiveItem(ITEM_WEAPON_PLASMA); plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got a plasma gun'); continue; end;
4422 if cmd = 'bfgzz' then begin plr.GiveItem(ITEM_WEAPON_BFG); plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got a BFG-9000'); continue; end;
4424 if cmd = 'superchaingun' then begin plr.GiveItem(ITEM_WEAPON_SUPERPULEMET); g_Console_Add('player got a superchaingun'); continue; end;
4425 if cmd = 'superchaingunzz' then begin plr.GiveItem(ITEM_WEAPON_SUPERPULEMET); plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a superchaingun'); continue; end;
4427 if (cmd = 'flamer') or (cmd = 'flamethrower') or (cmd = 'ft') then begin plr.GiveItem(ITEM_WEAPON_FLAMETHROWER); g_Console_Add('player got a flame thrower'); continue; end;
4428 if (cmd = 'flamerzz') or (cmd = 'flamethrowerzz') or (cmd = 'ftzz') then begin plr.GiveItem(ITEM_WEAPON_FLAMETHROWER); plr.GiveItem(ITEM_AMMO_FUELCAN); g_Console_Add('player got a flame thrower'); continue; end;
4430 if cmd = 'chainsaw' then begin plr.GiveItem(ITEM_WEAPON_SAW); g_Console_Add('player got a chainsaw'); continue; end;
4432 if cmd = 'ammo' then
4433 begin
4434 plr.GiveItem(ITEM_AMMO_SHELLS_BOX);
4435 plr.GiveItem(ITEM_AMMO_BULLETS_BOX);
4436 plr.GiveItem(ITEM_AMMO_CELL_BIG);
4437 plr.GiveItem(ITEM_AMMO_ROCKET_BOX);
4438 plr.GiveItem(ITEM_AMMO_FUELCAN);
4439 g_Console_Add('player got some ammo');
4440 continue;
4441 end;
4443 if cmd = 'clip' then begin plr.GiveItem(ITEM_AMMO_BULLETS); g_Console_Add('player got some bullets'); continue; end;
4444 if cmd = 'bullets' then begin plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a box of bullets'); continue; end;
4446 if cmd = 'shells' then begin plr.GiveItem(ITEM_AMMO_SHELLS); g_Console_Add('player got some shells'); continue; end;
4447 if cmd = 'shellbox' then begin plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a box of shells'); continue; end;
4449 if cmd = 'cells' then begin plr.GiveItem(ITEM_AMMO_CELL); g_Console_Add('player got some cells'); continue; end;
4450 if cmd = 'battery' then begin plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got cell battery'); continue; end;
4452 if cmd = 'rocket' then begin plr.GiveItem(ITEM_AMMO_ROCKET); g_Console_Add('player got a rocket'); continue; end;
4453 if cmd = 'rocketbox' then begin plr.GiveItem(ITEM_AMMO_ROCKET_BOX); g_Console_Add('player got some rockets'); continue; end;
4455 if (cmd = 'fuel') or (cmd = 'fuelcan') then begin plr.GiveItem(ITEM_AMMO_FUELCAN); g_Console_Add('player got fuel canister'); continue; end;
4457 if cmd = 'weapons' then
4458 begin
4459 plr.GiveItem(ITEM_WEAPON_SHOTGUN1);
4460 plr.GiveItem(ITEM_WEAPON_SHOTGUN2);
4461 plr.GiveItem(ITEM_WEAPON_CHAINGUN);
4462 plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER);
4463 plr.GiveItem(ITEM_WEAPON_PLASMA);
4464 plr.GiveItem(ITEM_WEAPON_BFG);
4465 g_Console_Add('player got weapons');
4466 continue;
4467 end;
4469 if cmd = 'keys' then
4470 begin
4471 plr.GiveItem(ITEM_KEY_RED);
4472 plr.GiveItem(ITEM_KEY_GREEN);
4473 plr.GiveItem(ITEM_KEY_BLUE);
4474 g_Console_Add('player got all keys');
4475 continue;
4476 end;
4478 g_Console_Add('i don''t know how to give '''+cmd+'''!');
4479 end;
4480 exit;
4481 end;
4482 // open
4483 if cmd = 'open' then
4484 begin
4485 g_Console_Add('player activated sesame');
4486 g_Triggers_OpenAll();
4487 exit;
4488 end;
4489 // fly
4490 if cmd = 'fly' then
4491 begin
4492 gFly := not gFly;
4493 if gFly then g_Console_Add('player feels himself lighter') else g_Console_Add('player lost his wings');
4494 exit;
4495 end;
4496 // noclip
4497 if cmd = 'noclip' then
4498 begin
4499 plr.SwitchNoClip;
4500 g_Console_Add('wall hardeness adjusted');
4501 exit;
4502 end;
4503 // notarget
4504 if cmd = 'notarget' then
4505 begin
4506 plr.NoTarget := not plr.NoTarget;
4507 if plr.NoTarget then g_Console_Add('player hides in shadows') else g_Console_Add('player is brave again');
4508 exit;
4509 end;
4510 // noreload
4511 if cmd = 'noreload' then
4512 begin
4513 plr.NoReload := not plr.NoReload;
4514 if plr.NoReload then g_Console_Add('player is action hero now') else g_Console_Add('player is ordinary man now');
4515 exit;
4516 end;
4517 // speedy
4518 if cmd = 'speedy' then
4519 begin
4520 MAX_RUNVEL := 32-MAX_RUNVEL;
4521 g_Console_Add('speed adjusted');
4522 exit;
4523 end;
4524 // jumpy
4525 if cmd = 'jumpy' then
4526 begin
4527 VEL_JUMP := 30-VEL_JUMP;
4528 g_Console_Add('jump height adjusted');
4529 exit;
4530 end;
4531 // automap
4532 if cmd = 'automap' then
4533 begin
4534 gShowMap := not gShowMap;
4535 if gShowMap then g_Console_Add('player gains second sight') else g_Console_Add('player lost second sight');
4536 exit;
4537 end;
4538 // aimline
4539 if cmd = 'aimline' then
4540 begin
4541 gAimLine := not gAimLine;
4542 if gAimLine then g_Console_Add('player gains laser sight') else g_Console_Add('player lost laser sight');
4543 exit;
4544 end;
4545 end;
4547 procedure GameCommands(P: SSArray);
4548 var
4549 a, b: Integer;
4550 s, pw: String;
4551 chstr: string;
4552 cmd: string;
4553 pl: pTNetClient = nil;
4554 plr: TPlayer;
4555 prt: Word;
4556 nm: Boolean;
4557 listen: LongWord;
4558 found: Boolean;
4559 begin
4560 // Общие команды:
4561 cmd := LowerCase(P[0]);
4562 chstr := '';
4563 if cmd = 'pause' then
4564 begin
4565 {$IFNDEF HEADLESS}
4566 if (g_ActiveWindow = nil) then
4567 g_Game_Pause(not gPauseMain);
4568 {$ELSE}
4569 g_Game_Pause(not gPauseMain);
4570 {$ENDIF}
4571 end
4572 else if cmd = 'endgame' then
4573 gExit := EXIT_SIMPLE
4574 else if cmd = 'restart' then
4575 begin
4576 if gGameOn or (gState in [STATE_INTERSINGLE, STATE_INTERCUSTOM]) then
4577 begin
4578 if g_Game_IsClient then
4579 begin
4580 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4581 Exit;
4582 end;
4583 g_Game_Restart();
4584 end else
4585 g_Console_Add(_lc[I_MSG_NOT_GAME]);
4586 end
4587 else if cmd = 'kick' then
4588 begin
4589 if g_Game_IsServer then
4590 begin
4591 if Length(P) < 2 then
4592 begin
4593 g_Console_Add('kick <name>');
4594 Exit;
4595 end;
4596 if P[1] = '' then
4597 begin
4598 g_Console_Add('kick <name>');
4599 Exit;
4600 end;
4602 if g_Game_IsNet then
4603 pl := g_Net_Client_ByName(P[1]);
4604 if (pl <> nil) then
4605 begin
4606 s := g_Net_ClientName_ByID(pl^.ID);
4607 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4608 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4609 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4610 g_Net_Slist_ServerPlayerLeaves();
4611 end else if gPlayers <> nil then
4612 for a := Low(gPlayers) to High(gPlayers) do
4613 if gPlayers[a] <> nil then
4614 if Copy(LowerCase(gPlayers[a].Name), 1, Length(P[1])) = LowerCase(P[1]) then
4615 begin
4616 // Не отключать основных игроков в сингле
4617 if not(gPlayers[a] is TBot) and (gGameSettings.GameType = GT_SINGLE) then
4618 continue;
4619 gPlayers[a].Lives := 0;
4620 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
4621 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
4622 g_Player_Remove(gPlayers[a].UID);
4623 g_Net_Slist_ServerPlayerLeaves();
4624 // Если не перемешать, при добавлении новых ботов появятся старые
4625 g_Bot_MixNames();
4626 end;
4627 end else
4628 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4629 end
4630 else if cmd = 'kick_id' then
4631 begin
4632 if g_Game_IsServer and g_Game_IsNet then
4633 begin
4634 if Length(P) < 2 then
4635 begin
4636 g_Console_Add('kick_id <client ID>');
4637 Exit;
4638 end;
4639 if P[1] = '' then
4640 begin
4641 g_Console_Add('kick_id <client ID>');
4642 Exit;
4643 end;
4645 a := StrToIntDef(P[1], 0);
4646 if (NetClients <> nil) and (a <= High(NetClients)) then
4647 begin
4648 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4649 begin
4650 s := g_Net_ClientName_ByID(NetClients[a].ID);
4651 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_KICK);
4652 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4653 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4654 g_Net_Slist_ServerPlayerLeaves();
4655 end;
4656 end;
4657 end else
4658 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4659 end
4660 else if cmd = 'kick_pid' then
4661 begin
4662 if g_Game_IsServer and g_Game_IsNet then
4663 begin
4664 if Length(P) < 2 then
4665 begin
4666 g_Console_Add('kick_pid <player ID>');
4667 Exit;
4668 end;
4669 if P[1] = '' then
4670 begin
4671 g_Console_Add('kick_pid <player ID>');
4672 Exit;
4673 end;
4675 a := StrToIntDef(P[1], 0);
4676 pl := g_Net_Client_ByPlayer(a);
4677 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4678 begin
4679 s := g_Net_ClientName_ByID(pl^.ID);
4680 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4681 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4682 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4683 g_Net_Slist_ServerPlayerLeaves();
4684 end;
4685 end else
4686 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4687 end
4688 else if cmd = 'ban' then
4689 begin
4690 if g_Game_IsServer and g_Game_IsNet then
4691 begin
4692 if Length(P) < 2 then
4693 begin
4694 g_Console_Add('ban <name>');
4695 Exit;
4696 end;
4697 if P[1] = '' then
4698 begin
4699 g_Console_Add('ban <name>');
4700 Exit;
4701 end;
4703 pl := g_Net_Client_ByName(P[1]);
4704 if (pl <> nil) then
4705 begin
4706 s := g_Net_ClientName_ByID(pl^.ID);
4707 g_Net_BanHost(pl^.Peer^.address.host, False);
4708 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4709 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4710 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4711 g_Net_Slist_ServerPlayerLeaves();
4712 end else
4713 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4714 end else
4715 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4716 end
4717 else if cmd = 'ban_id' then
4718 begin
4719 if g_Game_IsServer and g_Game_IsNet then
4720 begin
4721 if Length(P) < 2 then
4722 begin
4723 g_Console_Add('ban_id <client ID>');
4724 Exit;
4725 end;
4726 if P[1] = '' then
4727 begin
4728 g_Console_Add('ban_id <client ID>');
4729 Exit;
4730 end;
4732 a := StrToIntDef(P[1], 0);
4733 if (NetClients <> nil) and (a <= High(NetClients)) then
4734 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4735 begin
4736 s := g_Net_ClientName_ByID(NetClients[a].ID);
4737 g_Net_BanHost(NetClients[a].Peer^.address.host, False);
4738 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_TEMPBAN);
4739 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4740 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4741 g_Net_Slist_ServerPlayerLeaves();
4742 end;
4743 end else
4744 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4745 end
4746 else if cmd = 'ban_pid' then
4747 begin
4748 if g_Game_IsServer and g_Game_IsNet then
4749 begin
4750 if Length(P) < 2 then
4751 begin
4752 g_Console_Add('ban_pid <player ID>');
4753 Exit;
4754 end;
4755 if P[1] = '' then
4756 begin
4757 g_Console_Add('ban_pid <player ID>');
4758 Exit;
4759 end;
4761 a := StrToIntDef(P[1], 0);
4762 pl := g_Net_Client_ByPlayer(a);
4763 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4764 begin
4765 s := g_Net_ClientName_ByID(pl^.ID);
4766 g_Net_BanHost(pl^.Peer^.address.host, False);
4767 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4768 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4769 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4770 g_Net_Slist_ServerPlayerLeaves();
4771 end;
4772 end else
4773 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4774 end
4775 else if cmd = 'permban' then
4776 begin
4777 if g_Game_IsServer and g_Game_IsNet then
4778 begin
4779 if Length(P) < 2 then
4780 begin
4781 g_Console_Add('permban <name>');
4782 Exit;
4783 end;
4784 if P[1] = '' then
4785 begin
4786 g_Console_Add('permban <name>');
4787 Exit;
4788 end;
4790 pl := g_Net_Client_ByName(P[1]);
4791 if (pl <> nil) then
4792 begin
4793 s := g_Net_ClientName_ByID(pl^.ID);
4794 g_Net_BanHost(pl^.Peer^.address.host);
4795 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4796 g_Net_SaveBanList();
4797 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4798 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4799 g_Net_Slist_ServerPlayerLeaves();
4800 end else
4801 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4802 end else
4803 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4804 end
4805 else if cmd = 'permban_id' then
4806 begin
4807 if g_Game_IsServer and g_Game_IsNet then
4808 begin
4809 if Length(P) < 2 then
4810 begin
4811 g_Console_Add('permban_id <client ID>');
4812 Exit;
4813 end;
4814 if P[1] = '' then
4815 begin
4816 g_Console_Add('permban_id <client ID>');
4817 Exit;
4818 end;
4820 a := StrToIntDef(P[1], 0);
4821 if (NetClients <> nil) and (a <= High(NetClients)) then
4822 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4823 begin
4824 s := g_Net_ClientName_ByID(NetClients[a].ID);
4825 g_Net_BanHost(NetClients[a].Peer^.address.host);
4826 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_BAN);
4827 g_Net_SaveBanList();
4828 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4829 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4830 g_Net_Slist_ServerPlayerLeaves();
4831 end;
4832 end else
4833 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4834 end
4835 else if cmd = 'permban_pid' then
4836 begin
4837 if g_Game_IsServer and g_Game_IsNet then
4838 begin
4839 if Length(P) < 2 then
4840 begin
4841 g_Console_Add('permban_pid <player ID>');
4842 Exit;
4843 end;
4844 if P[1] = '' then
4845 begin
4846 g_Console_Add('permban_pid <player ID>');
4847 Exit;
4848 end;
4850 a := StrToIntDef(P[1], 0);
4851 pl := g_Net_Client_ByPlayer(a);
4852 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4853 begin
4854 s := g_Net_ClientName_ByID(pl^.ID);
4855 g_Net_BanHost(pl^.Peer^.address.host);
4856 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4857 g_Net_SaveBanList();
4858 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4859 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4860 g_Net_Slist_ServerPlayerLeaves();
4861 end;
4862 end else
4863 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4864 end
4865 else if cmd = 'permban_ip' then
4866 begin
4867 if g_Game_IsServer and g_Game_IsNet then
4868 begin
4869 if Length(P) < 2 then
4870 begin
4871 g_Console_Add('permban_ip <IP address>');
4872 Exit;
4873 end;
4874 if P[1] = '' then
4875 begin
4876 g_Console_Add('permban_ip <IP address>');
4877 Exit;
4878 end;
4880 g_Net_BanHost(P[1]);
4881 g_Net_SaveBanList();
4882 g_Console_Add(Format(_lc[I_PLAYER_BAN], [P[1]]));
4883 end else
4884 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4885 end
4886 else if cmd = 'unban' then
4887 begin
4888 if g_Game_IsServer and g_Game_IsNet then
4889 begin
4890 if Length(P) < 2 then
4891 begin
4892 g_Console_Add('unban <IP Address>');
4893 Exit;
4894 end;
4895 if P[1] = '' then
4896 begin
4897 g_Console_Add('unban <IP Address>');
4898 Exit;
4899 end;
4901 if g_Net_UnbanHost(P[1]) then
4902 begin
4903 g_Console_Add(Format(_lc[I_MSG_UNBAN_OK], [P[1]]));
4904 g_Net_SaveBanList();
4905 end else
4906 g_Console_Add(Format(_lc[I_MSG_UNBAN_FAIL], [P[1]]));
4907 end else
4908 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4909 end
4910 else if cmd = 'clientlist' then
4911 begin
4912 if g_Game_IsServer and g_Game_IsNet then
4913 begin
4914 b := 0;
4915 if NetClients <> nil then
4916 for a := Low(NetClients) to High(NetClients) do
4917 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4918 begin
4919 plr := g_Player_Get(NetClients[a].Player);
4920 if plr = nil then continue;
4921 Inc(b);
4922 g_Console_Add(Format('#%2d: %-15s | %s', [a,
4923 IpToStr(NetClients[a].Peer^.address.host), plr.Name]));
4924 end;
4925 if b = 0 then
4926 g_Console_Add(_lc[I_MSG_NOCLIENTS]);
4927 end else
4928 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4929 end
4930 else if cmd = 'connect' then
4931 begin
4932 if (NetMode = NET_NONE) then
4933 begin
4934 if Length(P) < 2 then
4935 begin
4936 g_Console_Add('connect <IP> [port] [password]');
4937 Exit;
4938 end;
4939 if P[1] = '' then
4940 begin
4941 g_Console_Add('connect <IP> [port] [password]');
4942 Exit;
4943 end;
4945 if Length(P) > 2 then
4946 prt := StrToIntDef(P[2], 25666)
4947 else
4948 prt := 25666;
4950 if Length(P) > 3 then
4951 pw := P[3]
4952 else
4953 pw := '';
4955 g_Game_StartClient(P[1], prt, pw);
4956 end;
4957 end
4958 else if cmd = 'disconnect' then
4959 begin
4960 if (NetMode = NET_CLIENT) then
4961 g_Net_Disconnect();
4962 end
4963 else if cmd = 'reconnect' then
4964 begin
4965 if (NetMode = NET_SERVER) then
4966 Exit;
4968 if (NetMode = NET_CLIENT) then
4969 begin
4970 g_Net_Disconnect();
4971 gExit := EXIT_SIMPLE;
4972 EndGame;
4973 end;
4975 //TODO: Use last successful password to reconnect, instead of ''
4976 g_Game_StartClient(NetClientIP, NetClientPort, '');
4977 end
4978 else if (cmd = 'addbot') or
4979 (cmd = 'bot_add') then
4980 begin
4981 if Length(P) > 2 then
4982 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2), StrToIntDef(P[2], 100))
4983 else if Length(P) > 1 then
4984 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2))
4985 else
4986 g_Bot_Add(TEAM_NONE, 2);
4987 end
4988 else if cmd = 'bot_addlist' then
4989 begin
4990 if Length(P) > 1 then
4991 begin
4992 if Length(P) = 2 then
4993 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1))
4994 else if Length(P) = 3 then
4995 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1), StrToIntDef(P[2], 100))
4996 else
4997 g_Bot_AddList(IfThen(P[2] = 'red', TEAM_RED, TEAM_BLUE), P[1], StrToIntDef(P[1], -1));
4998 end;
4999 end
5000 else if cmd = 'bot_removeall' then
5001 g_Bot_RemoveAll()
5002 else if cmd = 'chat' then
5003 begin
5004 if g_Game_IsNet then
5005 begin
5006 if Length(P) > 1 then
5007 begin
5008 for a := 1 to High(P) do
5009 chstr := chstr + P[a] + ' ';
5011 if Length(chstr) > 200 then SetLength(chstr, 200);
5013 if Length(chstr) < 1 then
5014 begin
5015 g_Console_Add('chat <text>');
5016 Exit;
5017 end;
5019 chstr := b_Text_Format(chstr);
5020 if g_Game_IsClient then
5021 MC_SEND_Chat(chstr, NET_CHAT_PLAYER)
5022 else
5023 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_PLAYER);
5024 end
5025 else
5026 g_Console_Add('chat <text>');
5027 end else
5028 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5029 end
5030 else if cmd = 'teamchat' then
5031 begin
5032 if g_Game_IsNet and (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
5033 begin
5034 if Length(P) > 1 then
5035 begin
5036 for a := 1 to High(P) do
5037 chstr := chstr + P[a] + ' ';
5039 if Length(chstr) > 200 then SetLength(chstr, 200);
5041 if Length(chstr) < 1 then
5042 begin
5043 g_Console_Add('teamchat <text>');
5044 Exit;
5045 end;
5047 chstr := b_Text_Format(chstr);
5048 if g_Game_IsClient then
5049 MC_SEND_Chat(chstr, NET_CHAT_TEAM)
5050 else
5051 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_TEAM,
5052 gPlayer1Settings.Team);
5053 end
5054 else
5055 g_Console_Add('teamchat <text>');
5056 end else
5057 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5058 end
5059 else if cmd = 'game' then
5060 begin
5061 if gGameSettings.GameType <> GT_NONE then
5062 begin
5063 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5064 Exit;
5065 end;
5066 if Length(P) = 1 then
5067 begin
5068 g_Console_Add(cmd + ' <WAD> [MAP] [# players]');
5069 Exit;
5070 end;
5071 // game not started yet, load fist map from some wad
5072 found := false;
5073 s := addWadExtension(P[1]);
5074 found := e_FindResource(AllMapDirs, s);
5075 P[1] := s;
5076 if found then
5077 begin
5078 P[1] := ExpandFileName(P[1]);
5079 // if map not choosed then set first map
5080 if Length(P) < 3 then
5081 begin
5082 SetLength(P, 3);
5083 P[2] := g_Game_GetFirstMap(P[1]);
5084 end;
5086 s := P[1] + ':\' + UpperCase(P[2]);
5088 if g_Map_Exist(s) then
5089 begin
5090 // start game
5091 g_Game_Free();
5092 with gGameSettings do
5093 begin
5094 Options := gsGameFlags;
5095 GameMode := g_Game_TextToMode(gsGameMode);
5096 if gSwitchGameMode <> GM_NONE then
5097 GameMode := gSwitchGameMode;
5098 if GameMode = GM_NONE then GameMode := GM_DM;
5099 if GameMode = GM_SINGLE then GameMode := GM_COOP;
5100 b := 1;
5101 if Length(P) >= 4 then
5102 b := StrToIntDef(P[3], 1);
5103 g_Game_StartCustom(s, GameMode, TimeLimit,
5104 GoalLimit, MaxLives, Options, b);
5105 end;
5106 end
5107 else
5108 if P[2] = '' then
5109 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5110 else
5111 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[2]), P[1]]));
5112 end else
5113 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]));
5114 end
5115 else if cmd = 'host' then
5116 begin
5117 if gGameSettings.GameType <> GT_NONE then
5118 begin
5119 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5120 Exit;
5121 end;
5122 if Length(P) < 4 then
5123 begin
5124 g_Console_Add(cmd + ' <listen IP> <port> <WAD> [MAP] [# players]');
5125 Exit;
5126 end;
5127 if not StrToIp(P[1], listen) then
5128 Exit;
5129 prt := StrToIntDef(P[2], 25666);
5131 s := addWadExtension(P[3]);
5132 found := e_FindResource(AllMapDirs, s);
5133 P[3] := s;
5134 if found then
5135 begin
5136 // get first map in wad, if not specified
5137 if Length(P) < 5 then
5138 begin
5139 SetLength(P, 5);
5140 P[4] := g_Game_GetFirstMap(P[1]);
5141 end;
5142 s := P[3] + ':\' + UpperCase(P[4]);
5143 if g_Map_Exist(s) then
5144 begin
5145 // start game
5146 g_Game_Free();
5147 with gGameSettings do
5148 begin
5149 Options := gsGameFlags;
5150 GameMode := g_Game_TextToMode(gsGameMode);
5151 if gSwitchGameMode <> GM_NONE then GameMode := gSwitchGameMode;
5152 if GameMode = GM_NONE then GameMode := GM_DM;
5153 if GameMode = GM_SINGLE then GameMode := GM_COOP;
5154 b := 0;
5155 if Length(P) >= 6 then
5156 b := StrToIntDef(P[5], 0);
5157 g_Game_StartServer(s, GameMode, TimeLimit, GoalLimit, MaxLives, Options, b, listen, prt)
5158 end
5159 end
5160 else
5161 begin
5162 if P[4] = '' then
5163 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[3]]))
5164 else
5165 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[4]), P[3]]))
5166 end
5167 end
5168 else
5169 begin
5170 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[3]]))
5171 end
5172 end
5173 else if cmd = 'map' then
5174 begin
5175 if Length(P) = 1 then
5176 begin
5177 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5178 begin
5179 g_Console_Add(cmd + ' <MAP>');
5180 g_Console_Add(cmd + ' <WAD> [MAP]')
5181 end
5182 else
5183 begin
5184 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5185 end
5186 end
5187 else
5188 begin
5189 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5190 begin
5191 if Length(P) < 3 then
5192 begin
5193 // first param is map or wad
5194 s := UpperCase(P[1]);
5195 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5196 begin
5197 gExitByTrigger := False;
5198 if gGameOn then
5199 begin
5200 // already in game, finish current map
5201 gNextMap := s;
5202 gExit := EXIT_ENDLEVELCUSTOM;
5203 end
5204 else
5205 begin
5206 // intermission, so change map immediately
5207 g_Game_ChangeMap(s)
5208 end
5209 end
5210 else
5211 begin
5212 s := P[1];
5213 found := e_FindResource(AllMapDirs, s);
5214 P[1] := s;
5215 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, 'WAD ' + P[1]]));
5216 if found then
5217 begin
5218 // no such map, found wad
5219 pw := P[1];
5220 SetLength(P, 3);
5221 P[1] := ExpandFileName(pw);
5222 P[2] := g_Game_GetFirstMap(P[1]);
5223 s := P[1] + ':\' + P[2];
5224 if g_Map_Exist(s) then
5225 begin
5226 gExitByTrigger := False;
5227 if gGameOn then
5228 begin
5229 // already in game, finish current map
5230 gNextMap := s;
5231 gExit := EXIT_ENDLEVELCUSTOM
5232 end
5233 else
5234 begin
5235 // intermission, so change map immediately
5236 g_Game_ChangeMap(s)
5237 end
5238 end
5239 else
5240 begin
5241 if P[2] = '' then
5242 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5243 else
5244 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5245 end
5246 end
5247 else
5248 begin
5249 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5250 end
5251 end;
5252 end
5253 else
5254 begin
5255 s := addWadExtension(P[1]);
5256 found := e_FindResource(AllMapDirs, s);
5257 P[1] := s;
5258 if found then
5259 begin
5260 P[2] := UpperCase(P[2]);
5261 s := P[1] + ':\' + P[2];
5262 if g_Map_Exist(s) then
5263 begin
5264 gExitByTrigger := False;
5265 if gGameOn then
5266 begin
5267 gNextMap := s;
5268 gExit := EXIT_ENDLEVELCUSTOM
5269 end
5270 else
5271 begin
5272 g_Game_ChangeMap(s)
5273 end
5274 end
5275 else
5276 begin
5277 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5278 end
5279 end
5280 else
5281 begin
5282 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5283 end
5284 end
5285 end
5286 else
5287 begin
5288 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5289 end
5290 end
5291 end
5292 else if cmd = 'nextmap' then
5293 begin
5294 if not(gGameOn or (gState = STATE_INTERCUSTOM)) then
5295 begin
5296 g_Console_Add(_lc[I_MSG_NOT_GAME])
5297 end
5298 else
5299 begin
5300 nm := True;
5301 if Length(P) = 1 then
5302 begin
5303 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5304 begin
5305 g_Console_Add(cmd + ' <MAP>');
5306 g_Console_Add(cmd + ' <WAD> [MAP]');
5307 end
5308 else
5309 begin
5310 nm := False;
5311 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5312 end;
5313 end
5314 else
5315 begin
5316 nm := False;
5317 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5318 begin
5319 if Length(P) < 3 then
5320 begin
5321 // first param is map or wad
5322 s := UpperCase(P[1]);
5323 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5324 begin
5325 // map founded
5326 gExitByTrigger := False;
5327 gNextMap := s;
5328 nm := True;
5329 end
5330 else
5331 begin
5332 // no such map, found wad
5333 pw := addWadExtension(P[1]);
5334 found := e_FindResource(MapDirs, pw);
5335 if not found then
5336 found := e_FindResource(WadDirs, pw);
5337 P[1] := pw;
5338 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, P[1]]));
5339 if found then
5340 begin
5341 // map not specified, select first map
5342 SetLength(P, 3);
5343 P[2] := g_Game_GetFirstMap(P[1]);
5344 s := P[1] + ':\' + P[2];
5345 if g_Map_Exist(s) then
5346 begin
5347 gExitByTrigger := False;
5348 gNextMap := s;
5349 nm := True
5350 end
5351 else
5352 begin
5353 if P[2] = '' then
5354 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5355 else
5356 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5357 end
5358 end
5359 else
5360 begin
5361 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5362 end
5363 end
5364 end
5365 else
5366 begin
5367 // specified two params wad + map
5368 pw := addWadExtension(P[1]);
5369 found := e_FindResource(MapDirs, pw);
5370 if not found then
5371 found := e_FindResource(MapDirs, pw);
5372 P[1] := pw;
5373 if found then
5374 begin
5375 P[2] := UpperCase(P[2]);
5376 s := P[1] + ':\' + P[2];
5377 if g_Map_Exist(s) then
5378 begin
5379 gExitByTrigger := False;
5380 gNextMap := s;
5381 nm := True
5382 end
5383 else
5384 begin
5385 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5386 end
5387 end
5388 else
5389 begin
5390 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5391 end
5392 end
5393 end
5394 else
5395 begin
5396 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5397 end
5398 end;
5399 if nm then
5400 begin
5401 if gNextMap = '' then
5402 g_Console_Add(_lc[I_MSG_NEXTMAP_UNSET])
5403 else
5404 g_Console_Add(Format(_lc[I_MSG_NEXTMAP_SET], [gNextMap]))
5405 end
5406 end
5407 end
5408 else if (cmd = 'endmap') or (cmd = 'goodbye') then
5409 begin
5410 if not gGameOn then
5411 begin
5412 g_Console_Add(_lc[I_MSG_NOT_GAME])
5413 end
5414 else
5415 begin
5416 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5417 begin
5418 gExitByTrigger := False;
5419 // next map not specified, try to find trigger EXIT
5420 if (gNextMap = '') and (gTriggers <> nil) then
5421 begin
5422 for a := 0 to High(gTriggers) do
5423 begin
5424 if gTriggers[a].TriggerType = TRIGGER_EXIT then
5425 begin
5426 gExitByTrigger := True;
5427 //gNextMap := gTriggers[a].Data.MapName;
5428 gNextMap := gTriggers[a].tgcMap;
5429 Break
5430 end
5431 end
5432 end;
5433 if gNextMap = '' then
5434 gNextMap := g_Game_GetNextMap();
5435 if not isWadPath(gNextMap) then
5436 s := gGameSettings.WAD + ':\' + gNextMap
5437 else
5438 s := gNextMap;
5439 if g_Map_Exist(s) then
5440 gExit := EXIT_ENDLEVELCUSTOM
5441 else
5442 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [gNextMap]))
5443 end
5444 else
5445 begin
5446 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5447 end
5448 end
5449 end
5450 else if (cmd = 'event') then
5451 begin
5452 if (Length(P) <= 1) then
5453 begin
5454 for a := 0 to High(gEvents) do
5455 if gEvents[a].Command = '' then
5456 g_Console_Add(gEvents[a].Name + ' <none>')
5457 else
5458 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5459 Exit;
5460 end;
5461 if (Length(P) = 2) then
5462 begin
5463 for a := 0 to High(gEvents) do
5464 if gEvents[a].Name = P[1] then
5465 if gEvents[a].Command = '' then
5466 g_Console_Add(gEvents[a].Name + ' <none>')
5467 else
5468 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5469 Exit;
5470 end;
5471 for a := 0 to High(gEvents) do
5472 if gEvents[a].Name = P[1] then
5473 begin
5474 gEvents[a].Command := '';
5475 for b := 2 to High(P) do
5476 if Pos(' ', P[b]) = 0 then
5477 gEvents[a].Command := gEvents[a].Command + ' ' + P[b]
5478 else
5479 gEvents[a].Command := gEvents[a].Command + ' "' + P[b] + '"';
5480 gEvents[a].Command := Trim(gEvents[a].Command);
5481 Exit;
5482 end;
5483 end
5484 else if cmd = 'suicide' then
5485 begin
5486 if gGameOn then
5487 begin
5488 if g_Game_IsClient then
5489 MC_SEND_CheatRequest(NET_CHEAT_SUICIDE)
5490 else
5491 begin
5492 if gPlayer1 <> nil then
5493 gPlayer1.Damage(SUICIDE_DAMAGE, gPlayer1.UID, 0, 0, HIT_SELF);
5494 if gPlayer2 <> nil then
5495 gPlayer2.Damage(SUICIDE_DAMAGE, gPlayer2.UID, 0, 0, HIT_SELF);
5496 end;
5497 end;
5498 end
5499 else if cmd = 'screenshot' then
5500 begin
5501 {$IFNDEF HEADLESS}
5502 g_TakeScreenShot()
5503 {$ENDIF}
5504 end
5505 else if cmd = 'weapon' then
5506 begin
5507 if Length(p) = 2 then
5508 begin
5509 a := WP_FIRST + StrToInt(p[1]) - 1;
5510 if (a >= WP_FIRST) and (a <= WP_LAST) then
5511 gSelectWeapon[0, a] := True
5512 end
5513 end
5514 else if (cmd = 'p1_weapon') or (cmd = 'p2_weapon') then
5515 begin
5516 if Length(p) = 2 then
5517 begin
5518 a := WP_FIRST + StrToInt(p[1]) - 1;
5519 b := ord(cmd[2]) - ord('1');
5520 if (a >= WP_FIRST) and (a <= WP_LAST) then
5521 gSelectWeapon[b, a] := True
5522 end
5523 end
5524 // Команды Своей игры:
5525 else if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
5526 begin
5527 if cmd = 'bot_addred' then
5528 begin
5529 if Length(P) > 1 then
5530 g_Bot_Add(TEAM_RED, StrToIntDef(P[1], 2))
5531 else
5532 g_Bot_Add(TEAM_RED, 2);
5533 end
5534 else if cmd = 'bot_addblue' then
5535 begin
5536 if Length(P) > 1 then
5537 g_Bot_Add(TEAM_BLUE, StrToIntDef(P[1], 2))
5538 else
5539 g_Bot_Add(TEAM_BLUE, 2);
5540 end
5541 else if cmd = 'spectate' then
5542 begin
5543 if not gGameOn then
5544 Exit;
5545 g_Game_Spectate();
5546 end
5547 else if cmd = 'say' then
5548 begin
5549 if g_Game_IsServer and g_Game_IsNet then
5550 begin
5551 if Length(P) > 1 then
5552 begin
5553 chstr := '';
5554 for a := 1 to High(P) do
5555 chstr := chstr + P[a] + ' ';
5557 if Length(chstr) > 200 then SetLength(chstr, 200);
5559 if Length(chstr) < 1 then
5560 begin
5561 g_Console_Add('say <text>');
5562 Exit;
5563 end;
5565 chstr := b_Text_Format(chstr);
5566 MH_SEND_Chat(chstr, NET_CHAT_PLAYER);
5567 end
5568 else g_Console_Add('say <text>');
5569 end else
5570 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5571 end
5572 else if cmd = 'tell' then
5573 begin
5574 if g_Game_IsServer and g_Game_IsNet then
5575 begin
5576 if (Length(P) > 2) and (P[1] <> '') then
5577 begin
5578 chstr := '';
5579 for a := 2 to High(P) do
5580 chstr := chstr + P[a] + ' ';
5582 if Length(chstr) > 200 then SetLength(chstr, 200);
5584 if Length(chstr) < 1 then
5585 begin
5586 g_Console_Add('tell <playername> <text>');
5587 Exit;
5588 end;
5590 pl := g_Net_Client_ByName(P[1]);
5591 if pl <> nil then
5592 MH_SEND_Chat(b_Text_Format(chstr), NET_CHAT_PLAYER, pl^.ID)
5593 else
5594 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
5595 end
5596 else g_Console_Add('tell <playername> <text>');
5597 end else
5598 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5599 end
5600 else if cmd = 'centerprint' then
5601 begin
5602 if (Length(P) > 2) and (P[1] <> '') then
5603 begin
5604 chstr := '';
5605 for a := 2 to High(P) do
5606 chstr := chstr + P[a] + ' ';
5608 if Length(chstr) > 200 then SetLength(chstr, 200);
5610 if Length(chstr) < 1 then
5611 begin
5612 g_Console_Add('centerprint <timeout> <text>');
5613 Exit;
5614 end;
5616 a := StrToIntDef(P[1], 100);
5617 chstr := b_Text_Format(chstr);
5618 g_Game_Message(chstr, a);
5619 if g_Game_IsNet and g_Game_IsServer then
5620 MH_SEND_GameEvent(NET_EV_BIGTEXT, a, chstr);
5621 end
5622 else g_Console_Add('centerprint <timeout> <text>');
5623 end
5624 else if (cmd = 'overtime') and not g_Game_IsClient then
5625 begin
5626 if (Length(P) = 1) or (StrToIntDef(P[1], -1) <= 0) then
5627 Exit;
5628 // Дополнительное время:
5629 gGameSettings.TimeLimit := (gTime - gGameStartTime) div 1000 + Word(StrToIntDef(P[1], 0));
5631 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
5632 [gGameSettings.TimeLimit div 3600,
5633 (gGameSettings.TimeLimit div 60) mod 60,
5634 gGameSettings.TimeLimit mod 60]));
5635 if g_Game_IsNet then MH_SEND_GameSettings;
5636 end
5637 else if (cmd = 'rcon_password') and g_Game_IsClient then
5638 begin
5639 if (Length(P) <= 1) then
5640 g_Console_Add('rcon_password <password>')
5641 else
5642 MC_SEND_RCONPassword(P[1]);
5643 end
5644 else if cmd = 'rcon' then
5645 begin
5646 if g_Game_IsClient then
5647 begin
5648 if Length(P) > 1 then
5649 begin
5650 chstr := '';
5651 for a := 1 to High(P) do
5652 chstr := chstr + P[a] + ' ';
5654 if Length(chstr) > 200 then SetLength(chstr, 200);
5656 if Length(chstr) < 1 then
5657 begin
5658 g_Console_Add('rcon <command>');
5659 Exit;
5660 end;
5662 MC_SEND_RCONCommand(chstr);
5663 end
5664 else g_Console_Add('rcon <command>');
5665 end;
5666 end
5667 else if cmd = 'ready' then
5668 begin
5669 if g_Game_IsServer and (gLMSRespawn = LMS_RESPAWN_WARMUP) then
5670 gLMSRespawnTime := gTime + 100;
5671 end
5672 else if (cmd = 'callvote') and g_Game_IsNet then
5673 begin
5674 if Length(P) > 1 then
5675 begin
5676 chstr := '';
5677 for a := 1 to High(P) do begin
5678 if a > 1 then chstr := chstr + ' ';
5679 chstr := chstr + P[a];
5680 end;
5682 if Length(chstr) > 200 then SetLength(chstr, 200);
5684 if Length(chstr) < 1 then
5685 begin
5686 g_Console_Add('callvote <command>');
5687 Exit;
5688 end;
5690 if g_Game_IsClient then
5691 MC_SEND_Vote(True, chstr)
5692 else
5693 g_Game_StartVote(chstr, gPlayer1Settings.Name);
5694 g_Console_Process('vote', True);
5695 end
5696 else
5697 g_Console_Add('callvote <command>');
5698 end
5699 else if (cmd = 'vote') and g_Game_IsNet then
5700 begin
5701 if g_Game_IsClient then
5702 MC_SEND_Vote(False)
5703 else if gVoteInProgress then
5704 begin
5705 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
5706 a := Floor((NetClientCount+1)/2.0) + 1
5707 else
5708 a := Floor(NetClientCount/2.0) + 1;
5709 if gVoted then
5710 begin
5711 Dec(gVoteCount);
5712 gVoted := False;
5713 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_REVOKED], [gPlayer1Settings.Name, gVoteCount, a]), True);
5714 MH_SEND_VoteEvent(NET_VE_REVOKE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5715 end
5716 else
5717 begin
5718 Inc(gVoteCount);
5719 gVoted := True;
5720 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_VOTE], [gPlayer1Settings.Name, gVoteCount, a]), True);
5721 MH_SEND_VoteEvent(NET_VE_VOTE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5722 g_Game_CheckVote;
5723 end;
5724 end;
5725 end
5726 end;
5727 end;
5729 procedure SystemCommands(P: SSArray);
5730 var
5731 cmd: string;
5732 begin
5733 cmd := LowerCase(P[0]);
5734 case cmd of
5735 'exit', 'quit':
5736 begin
5737 g_Game_Free();
5738 g_Game_Quit();
5739 end;
5740 {$IFNDEF HEADLESS}
5741 'r_reset':
5742 r_Render_Apply;
5743 {$ENDIF}
5744 'r_maxfps':
5745 begin
5746 if Length(p) = 2 then
5747 begin
5748 gMaxFPS := StrToIntDef(p[1], gMaxFPS);
5749 if gMaxFPS > 0 then
5750 gFrameTime := 1000 div gMaxFPS
5751 else
5752 gFrameTime := 0;
5753 end;
5754 e_LogWritefln('r_maxfps %d', [gMaxFPS]);
5755 end;
5756 'g_language':
5757 begin
5758 if Length(p) = 2 then
5759 begin
5760 gAskLanguage := true;
5761 gLanguage := LANGUAGE_ENGLISH;
5762 case LowerCase(p[1]) of
5763 'english':
5764 begin
5765 gAskLanguage := false;
5766 gLanguage := LANGUAGE_ENGLISH;
5767 end;
5768 'russian':
5769 begin
5770 gAskLanguage := false;
5771 gLanguage := LANGUAGE_RUSSIAN;
5772 end;
5773 'ask':
5774 begin
5775 gAskLanguage := true;
5776 gLanguage := LANGUAGE_ENGLISH;
5777 end;
5778 end;
5779 g_Language_Set(gLanguage);
5780 end
5781 else
5782 begin
5783 e_LogWritefln('usage: %s <English|Russian|Ask>', [cmd]);
5784 end
5785 end;
5786 end;
5787 end;
5789 {$IFNDEF HEADLESS}
5790 procedure g_TakeScreenShot(Filename: string = '');
5791 var t: TDateTime; dir, date, name: String;
5792 begin
5793 if e_NoGraphics then
5794 Exit;
5796 dir := e_GetWriteableDir(ScreenshotDirs);
5797 if Filename = '' then
5798 begin
5799 t := Now;
5800 DateTimeToString(date, 'yyyy-mm-dd-hh-nn-ss', t);
5801 Filename := 'screenshot-' + date;
5802 end;
5804 name := e_CatPath(dir, Filename + '.png');
5805 if r_Render_WriteScreenShot(name) then
5806 g_Console_Add(Format(_lc[I_CONSOLE_SCREENSHOT], [name]))
5807 else
5808 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_WRITE], [name]));
5809 end;
5810 {$ENDIF}
5812 {$IFNDEF HEADLESS}
5813 procedure g_Game_InGameMenu(Show: Boolean);
5814 begin
5815 if (g_ActiveWindow = nil) and Show then
5816 begin
5817 if gGameSettings.GameType = GT_SINGLE then
5818 g_GUI_ShowWindow('GameSingleMenu')
5819 else
5820 begin
5821 if g_Game_IsClient then
5822 g_GUI_ShowWindow('GameClientMenu')
5823 else
5824 if g_Game_IsNet then
5825 g_GUI_ShowWindow('GameServerMenu')
5826 else
5827 g_GUI_ShowWindow('GameCustomMenu');
5828 end;
5829 g_Sound_PlayEx('MENU_OPEN');
5831 // Пауза при меню только в одиночной игре:
5832 if (not g_Game_IsNet) then
5833 g_Game_Pause(True);
5834 end
5835 else
5836 if (g_ActiveWindow <> nil) and (not Show) then
5837 begin
5838 // Пауза при меню только в одиночной игре:
5839 if (not g_Game_IsNet) then
5840 g_Game_Pause(False);
5841 end;
5842 end;
5843 {$ENDIF}
5845 procedure g_Game_Pause (Enable: Boolean);
5846 var
5847 oldPause: Boolean;
5848 begin
5849 if not gGameOn then exit;
5851 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5853 oldPause := gPause;
5854 gPauseMain := Enable;
5856 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5857 end;
5859 procedure g_Game_HolmesPause (Enable: Boolean);
5860 var
5861 oldPause: Boolean;
5862 begin
5863 if not gGameOn then exit;
5864 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5866 oldPause := gPause;
5867 gPauseHolmes := Enable;
5869 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5870 end;
5872 procedure g_Game_PauseAllSounds(Enable: Boolean);
5873 var
5874 i: Integer;
5875 begin
5876 // Триггеры:
5877 if gTriggers <> nil then
5878 for i := 0 to High(gTriggers) do
5879 with gTriggers[i] do
5880 if (TriggerType = TRIGGER_SOUND) and
5881 (Sound <> nil) and
5882 Sound.IsPlaying() then
5883 begin
5884 Sound.Pause(Enable);
5885 end;
5887 // Звуки игроков:
5888 if gPlayers <> nil then
5889 for i := 0 to High(gPlayers) do
5890 if gPlayers[i] <> nil then
5891 gPlayers[i].PauseSounds(Enable);
5893 // Музыка:
5894 if gMusic <> nil then
5895 gMusic.Pause(Enable);
5896 end;
5898 procedure g_Game_StopAllSounds(all: Boolean);
5899 var
5900 i: Integer;
5901 begin
5902 if gTriggers <> nil then
5903 for i := 0 to High(gTriggers) do
5904 with gTriggers[i] do
5905 if (TriggerType = TRIGGER_SOUND) and
5906 (Sound <> nil) then
5907 Sound.Stop();
5909 if gMusic <> nil then
5910 gMusic.Stop();
5912 if all then
5913 e_StopChannels();
5914 end;
5916 procedure g_Game_UpdateTriggerSounds;
5917 var i: Integer;
5918 begin
5919 if gTriggers <> nil then
5920 for i := 0 to High(gTriggers) do
5921 with gTriggers[i] do
5922 if (TriggerType = TRIGGER_SOUND) and (Sound <> nil) and tgcLocal and Sound.IsPlaying() then
5923 Sound.SetCoordsRect(X, Y, Width, Height, tgcVolume / 255.0)
5924 end;
5926 function g_Game_IsWatchedPlayer(UID: Word): Boolean;
5927 begin
5928 Result := False;
5929 if (gPlayer1 <> nil) and (gPlayer1.UID = UID) then
5930 begin
5931 Result := True;
5932 Exit;
5933 end;
5934 if (gPlayer2 <> nil) and (gPlayer2.UID = UID) then
5935 begin
5936 Result := True;
5937 Exit;
5938 end;
5939 if gSpectMode <> SPECT_PLAYERS then
5940 Exit;
5941 if gSpectPID1 = UID then
5942 begin
5943 Result := True;
5944 Exit;
5945 end;
5946 if gSpectViewTwo and (gSpectPID2 = UID) then
5947 begin
5948 Result := True;
5949 Exit;
5950 end;
5951 end;
5953 function g_Game_IsWatchedTeam(Team: Byte): Boolean;
5954 var
5955 Pl: TPlayer;
5956 begin
5957 Result := False;
5958 if (gPlayer1 <> nil) and (gPlayer1.Team = Team) then
5959 begin
5960 Result := True;
5961 Exit;
5962 end;
5963 if (gPlayer2 <> nil) and (gPlayer2.Team = Team) then
5964 begin
5965 Result := True;
5966 Exit;
5967 end;
5968 if gSpectMode <> SPECT_PLAYERS then
5969 Exit;
5970 Pl := g_Player_Get(gSpectPID1);
5971 if (Pl <> nil) and (Pl.Team = Team) then
5972 begin
5973 Result := True;
5974 Exit;
5975 end;
5976 if gSpectViewTwo then
5977 begin
5978 Pl := g_Player_Get(gSpectPID2);
5979 if (Pl <> nil) and (Pl.Team = Team) then
5980 begin
5981 Result := True;
5982 Exit;
5983 end;
5984 end;
5985 end;
5987 procedure g_Game_Message (Msg: string; Time: Word);
5988 begin
5989 MessageText := Msg;
5990 MessageTime := Time;
5991 end;
5993 procedure g_Game_ChatSound(Text: String; Taunt: Boolean = True);
5994 const
5995 punct: Array[0..13] of String =
5996 ('.', ',', ':', ';', '!', '?', '(', ')', '''', '"', '/', '\', '*', '^');
5997 var
5998 i, j: Integer;
5999 ok: Boolean;
6000 fpText: String;
6002 function IsPunctuation(S: String): Boolean;
6003 var
6004 i: Integer;
6005 begin
6006 Result := False;
6007 if Length(S) <> 1 then
6008 Exit;
6009 for i := Low(punct) to High(punct) do
6010 if S = punct[i] then
6011 begin
6012 Result := True;
6013 break;
6014 end;
6015 end;
6016 function FilterPunctuation(S: String): String;
6017 var
6018 i: Integer;
6019 begin
6020 for i := Low(punct) to High(punct) do
6021 S := StringReplace(S, punct[i], ' ', [rfReplaceAll]);
6022 Result := S;
6023 end;
6024 begin
6025 ok := False;
6027 if gUseChatSounds and Taunt and (gChatSounds <> nil) and (Pos(': ', Text) > 0) then
6028 begin
6029 // remove player name
6030 Delete(Text, 1, Pos(': ', Text) + 2 - 1);
6031 // for FullWord check
6032 Text := toLowerCase1251(' ' + Text + ' ');
6033 fpText := FilterPunctuation(Text);
6035 for i := 0 to Length(gChatSounds) - 1 do
6036 begin
6037 ok := True;
6038 for j := 0 to Length(gChatSounds[i].Tags) - 1 do
6039 begin
6040 if gChatSounds[i].FullWord and (not IsPunctuation(gChatSounds[i].Tags[j])) then
6041 ok := Pos(' ' + gChatSounds[i].Tags[j] + ' ', fpText) > 0
6042 else
6043 ok := Pos(gChatSounds[i].Tags[j], Text) > 0;
6044 if not ok then
6045 break;
6046 end;
6047 if ok then
6048 begin
6049 gChatSounds[i].Sound.Play();
6050 break;
6051 end;
6052 end;
6053 end;
6054 if not ok then
6055 g_Sound_PlayEx('SOUND_GAME_RADIO');
6056 end;
6058 procedure g_Game_Announce_GoodShot(SpawnerUID: Word);
6059 var
6060 a: Integer;
6061 begin
6062 case gAnnouncer of
6063 ANNOUNCE_NONE:
6064 Exit;
6065 ANNOUNCE_ME,
6066 ANNOUNCE_MEPLUS:
6067 if not g_Game_IsWatchedPlayer(SpawnerUID) then
6068 Exit;
6069 end;
6070 for a := 0 to 3 do
6071 if goodsnd[a].IsPlaying() then
6072 Exit;
6074 goodsnd[Random(4)].Play();
6075 end;
6077 procedure g_Game_Announce_KillCombo(Param: Integer);
6078 var
6079 UID: Word;
6080 c, n: Byte;
6081 Pl: TPlayer;
6082 Name: String;
6083 begin
6084 UID := Param and $FFFF;
6085 c := Param shr 16;
6086 if c < 2 then
6087 Exit;
6089 Pl := g_Player_Get(UID);
6090 if Pl = nil then
6091 Name := '?'
6092 else
6093 Name := Pl.Name;
6095 case c of
6096 2: begin
6097 n := 0;
6098 g_Console_Add(Format(_lc[I_PLAYER_KILL_2X], [Name]), True);
6099 end;
6100 3: begin
6101 n := 1;
6102 g_Console_Add(Format(_lc[I_PLAYER_KILL_3X], [Name]), True);
6103 end;
6104 4: begin
6105 n := 2;
6106 g_Console_Add(Format(_lc[I_PLAYER_KILL_4X], [Name]), True);
6107 end;
6108 else begin
6109 n := 3;
6110 g_Console_Add(Format(_lc[I_PLAYER_KILL_MX], [Name]), True);
6111 end;
6112 end;
6114 case gAnnouncer of
6115 ANNOUNCE_NONE:
6116 Exit;
6117 ANNOUNCE_ME:
6118 if not g_Game_IsWatchedPlayer(UID) then
6119 Exit;
6120 ANNOUNCE_MEPLUS:
6121 if (not g_Game_IsWatchedPlayer(UID)) and (c < 4) then
6122 Exit;
6123 end;
6125 if killsnd[n].IsPlaying() then
6126 killsnd[n].Stop();
6127 killsnd[n].Play();
6128 end;
6130 procedure g_Game_Announce_BodyKill(SpawnerUID: Word);
6131 var
6132 a: Integer;
6133 begin
6134 case gAnnouncer of
6135 ANNOUNCE_NONE:
6136 Exit;
6137 ANNOUNCE_ME:
6138 if not g_Game_IsWatchedPlayer(SpawnerUID) then
6139 Exit;
6140 end;
6141 for a := 0 to 2 do
6142 if hahasnd[a].IsPlaying() then
6143 Exit;
6145 hahasnd[Random(3)].Play();
6146 end;
6148 procedure g_Game_StartVote(Command, Initiator: string);
6149 var
6150 Need: Integer;
6151 begin
6152 if not gVotesEnabled then Exit;
6153 if gGameSettings.GameType <> GT_SERVER then Exit;
6154 if gVoteInProgress or gVotePassed then
6155 begin
6156 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_INPROGRESS], [gVoteCommand]), True);
6157 MH_SEND_VoteEvent(NET_VE_INPROGRESS, gVoteCommand);
6158 Exit;
6159 end;
6160 gVoteInProgress := True;
6161 gVotePassed := False;
6162 gVoteTimer := gTime + gVoteTimeout * 1000;
6163 gVoteCount := 0;
6164 gVoted := False;
6165 gVoteCommand := Command;
6167 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6168 Need := Floor((NetClientCount+1)/2.0)+1
6169 else
6170 Need := Floor(NetClientCount/2.0)+1;
6171 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_STARTED], [Initiator, Command, Need]), True);
6172 MH_SEND_VoteEvent(NET_VE_STARTED, Initiator, Command, Need);
6173 end;
6175 procedure g_Game_CheckVote;
6176 var
6177 I, Need: Integer;
6178 begin
6179 if gGameSettings.GameType <> GT_SERVER then Exit;
6180 if not gVoteInProgress then Exit;
6182 if (gTime >= gVoteTimer) then
6183 begin
6184 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6185 Need := Floor((NetClientCount+1)/2.0) + 1
6186 else
6187 Need := Floor(NetClientCount/2.0) + 1;
6188 if gVoteCount >= Need then
6189 begin
6190 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6191 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6192 gVotePassed := True;
6193 gVoteCmdTimer := gTime + 5000;
6194 end
6195 else
6196 begin
6197 g_Console_Add(_lc[I_MESSAGE_VOTE_FAILED], True);
6198 MH_SEND_VoteEvent(NET_VE_FAILED);
6199 end;
6200 if NetClients <> nil then
6201 for I := Low(NetClients) to High(NetClients) do
6202 if NetClients[i].Used then
6203 NetClients[i].Voted := False;
6204 gVoteInProgress := False;
6205 gVoted := False;
6206 gVoteCount := 0;
6207 end
6208 else
6209 begin
6210 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6211 Need := Floor((NetClientCount+1)/2.0) + 1
6212 else
6213 Need := Floor(NetClientCount/2.0) + 1;
6214 if gVoteCount >= Need then
6215 begin
6216 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6217 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6218 gVoteInProgress := False;
6219 gVotePassed := True;
6220 gVoteCmdTimer := gTime + 5000;
6221 gVoted := False;
6222 gVoteCount := 0;
6223 if NetClients <> nil then
6224 for I := Low(NetClients) to High(NetClients) do
6225 if NetClients[i].Used then
6226 NetClients[i].Voted := False;
6227 end;
6228 end;
6229 end;
6231 procedure g_Game_LoadMapList(FileName: string);
6232 var
6233 ListFile: TextFile;
6234 s: string;
6235 begin
6236 MapList := nil;
6237 MapIndex := -1;
6239 if not FileExists(FileName) then Exit;
6241 AssignFile(ListFile, FileName);
6242 Reset(ListFile);
6243 while not EOF(ListFile) do
6244 begin
6245 ReadLn(ListFile, s);
6247 s := Trim(s);
6248 if s = '' then Continue;
6250 SetLength(MapList, Length(MapList)+1);
6251 MapList[High(MapList)] := s;
6252 end;
6253 CloseFile(ListFile);
6254 end;
6256 procedure g_Game_SetDebugMode();
6257 begin
6258 gDebugMode := True;
6259 // Читы (даже в своей игре):
6260 gCheats := True;
6261 end;
6263 procedure g_Game_SetLoadingText(Text: String; Max: Integer; reWrite: Boolean);
6264 var
6265 i: Word;
6266 begin
6267 if Length(LoadingStat.Msgs) = 0 then
6268 Exit;
6270 with LoadingStat do
6271 begin
6272 if not reWrite then
6273 begin // Переходим на следующую строку или скроллируем:
6274 if NextMsg = Length(Msgs) then
6275 begin // scroll
6276 for i := 0 to High(Msgs)-1 do
6277 Msgs[i] := Msgs[i+1];
6278 end
6279 else
6280 Inc(NextMsg);
6281 end else
6282 if NextMsg = 0 then
6283 Inc(NextMsg);
6285 Msgs[NextMsg-1] := Text;
6286 CurValue := 0;
6287 MaxValue := Max;
6288 ShowCount := 0;
6289 PBarWasHere := false;
6290 end;
6292 {$IFNDEF HEADLESS}
6293 g_ActiveWindow := nil;
6294 {$ENDIF}
6296 ProcessLoading(true);
6297 end;
6299 procedure g_Game_StepLoading(Value: Integer = -1);
6300 begin
6301 with LoadingStat do
6302 begin
6303 if Value = -1 then
6304 begin
6305 Inc(CurValue);
6306 Inc(ShowCount);
6307 end
6308 else
6309 CurValue := Value;
6310 if (ShowCount > LOADING_SHOW_STEP) or (Value > -1) then
6311 begin
6312 ShowCount := 0;
6313 ProcessLoading();
6314 end;
6315 end;
6316 end;
6318 procedure g_Game_ClearLoading();
6319 var
6320 len: Word;
6321 begin
6322 with LoadingStat do
6323 begin
6324 CurValue := 0;
6325 MaxValue := 0;
6326 ShowCount := 0;
6327 len := ((gScreenHeight div 3)*2 - 50) div LOADING_INTERLINE;
6328 if len < 1 then len := 1;
6329 SetLength(Msgs, len);
6330 for len := Low(Msgs) to High(Msgs) do
6331 Msgs[len] := '';
6332 NextMsg := 0;
6333 PBarWasHere := false;
6334 end;
6335 end;
6337 procedure Parse_Params(var pars: TParamStrValues);
6338 var
6339 i: Integer;
6340 s: String;
6341 begin
6342 SetLength(pars, 0);
6343 i := 1;
6344 while i <= ParamCount do
6345 begin
6346 s := ParamStr(i);
6347 if (s[1] = '-') and (Length(s) > 1) then
6348 begin
6349 if (s[2] = '-') and (Length(s) > 2) then
6350 begin // Одиночный параметр
6351 SetLength(pars, Length(pars) + 1);
6352 with pars[High(pars)] do
6353 begin
6354 Name := LowerCase(s);
6355 Value := '+';
6356 end;
6357 end
6358 else
6359 if (i < ParamCount) then
6360 begin // Параметр со значением
6361 Inc(i);
6362 SetLength(pars, Length(pars) + 1);
6363 with pars[High(pars)] do
6364 begin
6365 Name := LowerCase(s);
6366 Value := LowerCase(ParamStr(i));
6367 end;
6368 end;
6369 end;
6371 Inc(i);
6372 end;
6373 end;
6375 function Find_Param_Value(var pars: TParamStrValues; aName: String): String;
6376 var
6377 i: Integer;
6378 begin
6379 Result := '';
6380 for i := 0 to High(pars) do
6381 if pars[i].Name = aName then
6382 begin
6383 Result := pars[i].Value;
6384 Break;
6385 end;
6386 end;
6388 procedure g_Game_Process_Params();
6389 var
6390 pars: TParamStrValues;
6391 map: String;
6392 GMode, n: Byte;
6393 LimT, LimS: Integer;
6394 Opt: LongWord;
6395 Lives: Integer;
6396 s: String;
6397 Port: Integer;
6398 ip: String;
6399 F: TextFile;
6400 begin
6401 Parse_Params(pars);
6403 // Debug mode:
6404 s := Find_Param_Value(pars, '--debug');
6405 if (s <> '') then
6406 begin
6407 g_Game_SetDebugMode();
6408 s := Find_Param_Value(pars, '--netdump');
6409 if (s <> '') then
6410 NetDump := True;
6411 end;
6413 // Connect when game loads
6414 ip := Find_Param_Value(pars, '-connect');
6416 if ip <> '' then
6417 begin
6418 s := Find_Param_Value(pars, '-port');
6419 if (s = '') or not TryStrToInt(s, Port) then
6420 Port := 25666;
6422 s := Find_Param_Value(pars, '-pw');
6424 g_Game_StartClient(ip, Port, s);
6425 Exit;
6426 end;
6428 s := LowerCase(Find_Param_Value(pars, '-dbg-mainwad'));
6429 if (s <> '') then
6430 begin
6431 gDefaultMegawadStart := s;
6432 end;
6434 if (Find_Param_Value(pars, '--dbg-mainwad-restore') <> '') or
6435 (Find_Param_Value(pars, '--dbg-mainwad-default') <> '') then
6436 begin
6437 gDefaultMegawadStart := DF_Default_Megawad_Start;
6438 end;
6440 // Start map when game loads:
6441 map := LowerCase(Find_Param_Value(pars, '-map'));
6442 if isWadPath(map) then
6443 begin
6444 // Game mode:
6445 s := Find_Param_Value(pars, '-gm');
6446 GMode := g_Game_TextToMode(s);
6447 if GMode = GM_NONE then GMode := GM_DM;
6448 if GMode = GM_SINGLE then GMode := GM_COOP;
6450 // Time limit:
6451 s := Find_Param_Value(pars, '-limt');
6452 if (s = '') or (not TryStrToInt(s, LimT)) then
6453 LimT := 0;
6454 if LimT < 0 then
6455 LimT := 0;
6457 // Goal limit:
6458 s := Find_Param_Value(pars, '-lims');
6459 if (s = '') or (not TryStrToInt(s, LimS)) then
6460 LimS := 0;
6461 if LimS < 0 then
6462 LimS := 0;
6464 // Lives limit:
6465 s := Find_Param_Value(pars, '-lives');
6466 if (s = '') or (not TryStrToInt(s, Lives)) then
6467 Lives := 0;
6468 if Lives < 0 then
6469 Lives := 0;
6471 // Options:
6472 s := Find_Param_Value(pars, '-opt');
6473 if (s = '') then
6474 Opt := gsGameFlags
6475 else
6476 Opt := StrToIntDef(s, 0);
6478 // Close after map:
6479 s := Find_Param_Value(pars, '--close');
6480 if (s <> '') then
6481 gMapOnce := True;
6483 // Override map to test:
6484 s := LowerCase(Find_Param_Value(pars, '-testmap'));
6485 if s <> '' then
6486 begin
6487 if e_IsValidResourceName(s) then
6488 e_FindResource(AllMapDirs, s);
6489 gTestMap := ExpandFileName(s);
6490 end;
6492 // Delete test map after play:
6493 s := Find_Param_Value(pars, '--testdelete');
6494 if (s <> '') then
6495 begin
6496 //gMapToDelete := MapsDir + map;
6497 e_WriteLog('"--testdelete" is deprecated, use --tempdelete.', TMsgType.Fatal);
6498 Halt(1);
6499 end;
6501 // Delete temporary WAD after play:
6502 s := Find_Param_Value(pars, '--tempdelete');
6503 if (s <> '') and (gTestMap <> '') then
6504 begin
6505 gMapToDelete := gTestMap;
6506 gTempDelete := True;
6507 end;
6509 // Number of players:
6510 s := Find_Param_Value(pars, '-pl');
6511 if (s = '') then
6512 n := DEFAULT_PLAYERS
6513 else
6514 n := StrToIntDef(s, DEFAULT_PLAYERS);
6516 // Start:
6517 s := Find_Param_Value(pars, '-port');
6518 if (s = '') or not TryStrToInt(s, Port) then
6519 g_Game_StartCustom(map, GMode, LimT, LimS, Lives, Opt, n)
6520 else
6521 g_Game_StartServer(map, GMode, LimT, LimS, Lives, Opt, n, 0, Port);
6522 end;
6524 // Execute script when game loads:
6525 s := Find_Param_Value(pars, '-exec');
6526 if s <> '' then
6527 begin
6528 // if not isWadPath(s) then
6529 // s := GameDir + '/' + s;
6531 {$I-}
6532 AssignFile(F, s);
6533 Reset(F);
6534 if IOResult <> 0 then
6535 begin
6536 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6537 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6538 CloseFile(F);
6539 Exit;
6540 end;
6541 e_WriteLog('Executing script: ' + s, TMsgType.Notify);
6542 g_Console_Add(Format(_lc[I_CONSOLE_EXEC], [s]));
6544 while not EOF(F) do
6545 begin
6546 ReadLn(F, s);
6547 if IOResult <> 0 then
6548 begin
6549 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6550 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6551 CloseFile(F);
6552 Exit;
6553 end;
6554 if Pos('#', s) <> 1 then // script comment
6555 g_Console_Process(s, True);
6556 end;
6558 CloseFile(F);
6559 {$I+}
6560 end;
6562 SetLength(pars, 0);
6563 end;
6565 begin
6566 conRegVar('pf_draw_frame', @g_profile_frame_draw, 'draw frame rendering profiles', 'render profiles');
6567 //conRegVar('pf_update_frame', @g_profile_frame_update, 'draw frame updating profiles', 'update profiles');
6568 conRegVar('pf_coldet', @g_profile_collision, 'draw collision detection profiles', 'coldet profiles');
6569 conRegVar('pf_los', @g_profile_los, 'draw monster LOS profiles', 'monster LOS profiles');
6571 conRegVar('r_sq_draw', @gdbg_map_use_accel_render, 'accelerated spatial queries in rendering', 'accelerated rendering');
6572 conRegVar('cd_sq_enabled', @gdbg_map_use_accel_coldet, 'accelerated spatial queries in map coldet', 'accelerated map coldet');
6573 conRegVar('mon_sq_enabled', @gmon_debug_use_sqaccel, 'accelerated spatial queries for monsters', 'accelerated monster coldet');
6574 conRegVar('wtrace_sq_enabled', @gwep_debug_fast_trace, 'accelerated spatial queries for weapon hitscan trace', 'accelerated weapon hitscan');
6576 conRegVar('pr_enabled', @gpart_dbg_enabled, 'enable/disable particles', 'particles');
6577 conRegVar('pr_phys_enabled', @gpart_dbg_phys_enabled, 'enable/disable particle physics', 'particle physics');
6579 conRegVar('los_enabled', @gmon_dbg_los_enabled, 'enable/disable monster LOS calculations', 'monster LOS', true);
6580 conRegVar('mon_think', @gmon_debug_think, 'enable/disable monster thinking', 'monster thinking', true);
6582 {$IFDEF ENABLE_HOLMES}
6583 conRegVar('dbg_holmes', @g_holmes_enabled, 'enable/disable Holmes', 'Holmes', true);
6584 {$ENDIF}
6586 conRegVar('dbg_ignore_level_bounds', @g_dbg_ignore_bounds, 'ignore level bounds', '', false);
6588 conRegVar('light_enabled', @gwin_k8_enable_light_experiments, 'enable/disable dynamic lighting', 'lighting');
6589 conRegVar('light_player_halo', @g_playerLight, 'enable/disable player halo', 'player light halo');
6591 conRegVar('r_smallmap_align_h', @r_smallmap_h, 'halign: 0: left; 1: center; 2: right', 'horizontal aligning of small maps');
6592 conRegVar('r_smallmap_align_v', @r_smallmap_v, 'valign: 0: top; 1: center; 2: bottom', 'vertial aligning of small maps');
6594 conRegVar('r_showfps', @gShowFPS, 'draw fps counter', 'draw fps counter');
6595 conRegVar('r_showtime', @gShowTime, 'show game time', 'show game time');
6596 conRegVar('r_showping', @gShowPing, 'show ping', 'show ping');
6597 conRegVar('r_showscore', @gShowGoals, 'show score', 'show score');
6598 conRegVar('r_showkillmsg', @gShowKillMsg, 'show kill log', 'show kill log');
6599 conRegVar('r_showlives', @gShowLives, 'show lives', 'show lives');
6600 conRegVar('r_showspect', @gSpectHUD, 'show spectator hud', 'show spectator hud');
6601 conRegVar('r_showstat', @gShowStat, 'show stats', 'show stats');
6602 conRegVar('r_showpids', @gShowPIDs, 'show PIDs', 'show PIDs');
6603 end.