DEADSOFTWARE

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