DEADSOFTWARE

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