DEADSOFTWARE

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