DEADSOFTWARE

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