DEADSOFTWARE

render: separate game logic and drawing
[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_basic, g_player, e_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;
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 g_PlayerModel_LoadData();
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 g_PlayerModel_FreeData();
2289 g_Texture_DeleteAll();
2290 g_Frames_DeleteAll();
2291 {$IFNDEF HEADLESS}
2292 //g_Menu_Free(); //k8: this segfaults after resolution change; who cares?
2293 {$ENDIF}
2295 if NetInitDone then g_Net_Free;
2297 // remove map after test
2298 if gMapToDelete <> '' then
2299 g_Game_DeleteTestMap();
2301 gExit := EXIT_QUIT;
2302 sys_RequestQuit;
2303 end;
2305 procedure g_Game_FreeData();
2306 begin
2307 if not DataLoaded then Exit;
2309 g_Items_FreeData();
2310 g_Weapon_FreeData();
2311 g_Monsters_FreeData();
2313 e_WriteLog('Releasing game data...', TMsgType.Notify);
2315 g_Texture_Delete('NOTEXTURE');
2316 g_Texture_Delete('TEXTURE_PLAYER_HUD');
2317 g_Texture_Delete('TEXTURE_PLAYER_HUDBG');
2318 g_Texture_Delete('TEXTURE_PLAYER_ARMORHUD');
2319 g_Texture_Delete('TEXTURE_PLAYER_REDFLAG');
2320 g_Texture_Delete('TEXTURE_PLAYER_REDFLAG_S');
2321 g_Texture_Delete('TEXTURE_PLAYER_REDFLAG_D');
2322 g_Texture_Delete('TEXTURE_PLAYER_BLUEFLAG');
2323 g_Texture_Delete('TEXTURE_PLAYER_BLUEFLAG_S');
2324 g_Texture_Delete('TEXTURE_PLAYER_BLUEFLAG_D');
2325 g_Texture_Delete('TEXTURE_PLAYER_TALKBUBBLE');
2326 g_Texture_Delete('TEXTURE_PLAYER_INVULPENTA');
2327 g_Frames_DeleteByName('FRAMES_TELEPORT');
2328 g_Frames_DeleteByName('FRAMES_PUNCH');
2329 g_Frames_DeleteByName('FRAMES_PUNCH_UP');
2330 g_Frames_DeleteByName('FRAMES_PUNCH_DN');
2331 g_Frames_DeleteByName('FRAMES_PUNCH_BERSERK');
2332 g_Frames_DeleteByName('FRAMES_PUNCH_BERSERK_UP');
2333 g_Frames_DeleteByName('FRAMES_PUNCH_BERSERK_DN');
2334 g_Sound_Delete('SOUND_GAME_TELEPORT');
2335 g_Sound_Delete('SOUND_GAME_NOTELEPORT');
2336 g_Sound_Delete('SOUND_GAME_SECRET');
2337 g_Sound_Delete('SOUND_GAME_DOOROPEN');
2338 g_Sound_Delete('SOUND_GAME_DOORCLOSE');
2339 g_Sound_Delete('SOUND_GAME_BULK1');
2340 g_Sound_Delete('SOUND_GAME_BULK2');
2341 g_Sound_Delete('SOUND_GAME_BUBBLE1');
2342 g_Sound_Delete('SOUND_GAME_BUBBLE2');
2343 g_Sound_Delete('SOUND_GAME_BURNING');
2344 g_Sound_Delete('SOUND_GAME_SWITCH1');
2345 g_Sound_Delete('SOUND_GAME_SWITCH0');
2347 goodsnd[0].Free();
2348 goodsnd[1].Free();
2349 goodsnd[2].Free();
2350 goodsnd[3].Free();
2352 g_Sound_Delete('SOUND_ANNOUNCER_GOOD1');
2353 g_Sound_Delete('SOUND_ANNOUNCER_GOOD2');
2354 g_Sound_Delete('SOUND_ANNOUNCER_GOOD3');
2355 g_Sound_Delete('SOUND_ANNOUNCER_GOOD4');
2357 killsnd[0].Free();
2358 killsnd[1].Free();
2359 killsnd[2].Free();
2360 killsnd[3].Free();
2362 g_Sound_Delete('SOUND_ANNOUNCER_KILL2X');
2363 g_Sound_Delete('SOUND_ANNOUNCER_KILL3X');
2364 g_Sound_Delete('SOUND_ANNOUNCER_KILL4X');
2365 g_Sound_Delete('SOUND_ANNOUNCER_KILLMX');
2367 hahasnd[0].Free();
2368 hahasnd[1].Free();
2369 hahasnd[2].Free();
2371 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA1');
2372 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA2');
2373 g_Sound_Delete('SOUND_ANNOUNCER_MUHAHA3');
2375 sound_get_flag[0].Free();
2376 sound_get_flag[1].Free();
2377 sound_lost_flag[0].Free();
2378 sound_lost_flag[1].Free();
2379 sound_ret_flag[0].Free();
2380 sound_ret_flag[1].Free();
2381 sound_cap_flag[0].Free();
2382 sound_cap_flag[1].Free();
2384 g_Sound_Delete('SOUND_CTF_GET1');
2385 g_Sound_Delete('SOUND_CTF_GET2');
2386 g_Sound_Delete('SOUND_CTF_LOST1');
2387 g_Sound_Delete('SOUND_CTF_LOST2');
2388 g_Sound_Delete('SOUND_CTF_RETURN1');
2389 g_Sound_Delete('SOUND_CTF_RETURN2');
2390 g_Sound_Delete('SOUND_CTF_CAPTURE1');
2391 g_Sound_Delete('SOUND_CTF_CAPTURE2');
2393 g_Game_FreeChatSounds();
2395 DataLoaded := False;
2396 end;
2398 procedure g_FatalError(Text: String);
2399 begin
2400 g_Console_Add(Format(_lc[I_FATAL_ERROR], [Text]), True);
2401 e_WriteLog(Format(_lc[I_FATAL_ERROR], [Text]), TMsgType.Warning);
2403 gExit := EXIT_SIMPLE;
2404 if gGameOn then EndGame;
2405 end;
2407 procedure g_SimpleError(Text: String);
2408 begin
2409 g_Console_Add(Format(_lc[I_SIMPLE_ERROR], [Text]), True);
2410 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], [Text]), TMsgType.Warning);
2411 end;
2413 procedure g_Game_SetupScreenSize();
2414 const
2415 RES_FACTOR = 4.0 / 3.0;
2416 var
2417 s: Single;
2418 rf: Single;
2419 bw, bh: Word;
2420 begin
2421 // Размер экранов игроков:
2422 gPlayerScreenSize.X := gScreenWidth-196;
2423 if (gPlayer1 <> nil) and (gPlayer2 <> nil) then
2424 gPlayerScreenSize.Y := gScreenHeight div 2
2425 else
2426 gPlayerScreenSize.Y := gScreenHeight;
2428 // Размер заднего плана:
2429 if BackID <> DWORD(-1) then
2430 begin
2431 s := SKY_STRETCH;
2432 if (gScreenWidth*s > gMapInfo.Width) or
2433 (gScreenHeight*s > gMapInfo.Height) then
2434 begin
2435 gBackSize.X := gScreenWidth;
2436 gBackSize.Y := gScreenHeight;
2437 end
2438 else
2439 begin
2440 e_GetTextureSize(BackID, @bw, @bh);
2441 rf := Single(bw) / Single(bh);
2442 if (rf > RES_FACTOR) then bw := Round(Single(bh) * RES_FACTOR)
2443 else if (rf < RES_FACTOR) then bh := Round(Single(bw) / RES_FACTOR);
2444 s := Max(gScreenWidth / bw, gScreenHeight / bh);
2445 if (s < 1.0) then s := 1.0;
2446 gBackSize.X := Round(bw*s);
2447 gBackSize.Y := Round(bh*s);
2448 end;
2449 end;
2450 end;
2452 procedure g_Game_ChangeResolution(newWidth, newHeight: Word; nowFull, nowMax: Boolean);
2453 begin
2454 sys_SetDisplayMode(newWidth, newHeight, gBPP, nowFull, nowMax);
2455 end;
2457 procedure g_Game_AddPlayer(Team: Byte = TEAM_NONE);
2458 begin
2459 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2460 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2461 Exit;
2463 if (gGameSettings.MaxLives > 0) and (gLMSRespawn = LMS_RESPAWN_NONE) then
2464 Exit;
2466 if gPlayer1 = nil then
2467 begin
2468 if g_Game_IsClient then
2469 begin
2470 if NetPlrUID1 > -1 then
2471 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2472 Exit;
2473 end;
2475 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2476 Team := gPlayer1Settings.Team;
2478 // Создание первого игрока:
2479 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2480 gPlayer1Settings.Color,
2481 Team, False));
2482 if gPlayer1 = nil then
2483 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]))
2484 else
2485 begin
2486 gPlayer1.Name := gPlayer1Settings.Name;
2487 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer1.Name]), True);
2488 if g_Game_IsServer and g_Game_IsNet then
2489 MH_SEND_PlayerCreate(gPlayer1.UID);
2490 gPlayer1.Respawn(False, True);
2491 g_Net_Slist_ServerPlayerComes();
2492 end;
2494 Exit;
2495 end;
2496 if gPlayer2 = nil then
2497 begin
2498 if g_Game_IsClient then
2499 begin
2500 if NetPlrUID2 > -1 then
2501 gPlayer2 := g_Player_Get(NetPlrUID2);
2502 Exit;
2503 end;
2505 if not (Team in [TEAM_RED, TEAM_BLUE]) then
2506 Team := gPlayer2Settings.Team;
2508 // Создание второго игрока:
2509 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2510 gPlayer2Settings.Color,
2511 Team, False));
2512 if gPlayer2 = nil then
2513 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]))
2514 else
2515 begin
2516 gPlayer2.Name := gPlayer2Settings.Name;
2517 g_Console_Add(Format(_lc[I_PLAYER_JOIN], [gPlayer2.Name]), True);
2518 if g_Game_IsServer and g_Game_IsNet then
2519 MH_SEND_PlayerCreate(gPlayer2.UID);
2520 gPlayer2.Respawn(False, True);
2521 g_Net_Slist_ServerPlayerComes();
2522 end;
2524 Exit;
2525 end;
2526 end;
2528 procedure g_Game_RemovePlayer();
2529 var
2530 Pl: TPlayer;
2531 begin
2532 if ((not gGameOn) and (gState <> STATE_INTERCUSTOM))
2533 or (not (gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT])) then
2534 Exit;
2535 Pl := gPlayer2;
2536 if Pl <> nil then
2537 begin
2538 if g_Game_IsServer then
2539 begin
2540 Pl.Lives := 0;
2541 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2542 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2543 g_Player_Remove(Pl.UID);
2544 g_Net_Slist_ServerPlayerLeaves();
2545 end
2546 else
2547 begin
2548 gSpectLatchPID2 := Pl.UID;
2549 gPlayer2 := nil;
2550 end;
2551 Exit;
2552 end;
2553 Pl := gPlayer1;
2554 if Pl <> nil then
2555 begin
2556 if g_Game_IsServer then
2557 begin
2558 Pl.Lives := 0;
2559 Pl.Kill(K_SIMPLEKILL, 0, HIT_DISCON);
2560 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [Pl.Name]), True);
2561 g_Player_Remove(Pl.UID);
2562 g_Net_Slist_ServerPlayerLeaves();
2563 end else
2564 begin
2565 gSpectLatchPID1 := Pl.UID;
2566 gPlayer1 := nil;
2567 MC_SEND_CheatRequest(NET_CHEAT_SPECTATE);
2568 end;
2569 Exit;
2570 end;
2571 g_Net_Slist_ServerPlayerLeaves();
2572 end;
2574 procedure g_Game_Spectate();
2575 begin
2576 g_Game_RemovePlayer();
2577 if gPlayer1 <> nil then
2578 g_Game_RemovePlayer();
2579 end;
2581 procedure g_Game_SpectateCenterView();
2582 begin
2583 gSpectX := Max(gMapInfo.Width div 2 - gScreenWidth div 2, 0);
2584 gSpectY := Max(gMapInfo.Height div 2 - gScreenHeight div 2, 0);
2585 end;
2587 procedure g_Game_StartSingle(Map: String; TwoPlayers: Boolean; nPlayers: Byte);
2588 var
2589 i, nPl: Integer;
2590 tmps: AnsiString;
2591 begin
2592 g_Game_Free();
2594 e_WriteLog('Starting singleplayer game...', TMsgType.Notify);
2596 g_Game_ClearLoading();
2598 // Настройки игры:
2599 FillByte(gGameSettings, SizeOf(TGameSettings), 0);
2600 gAimLine := False;
2601 gShowMap := False;
2602 gGameSettings.GameType := GT_SINGLE;
2603 gGameSettings.MaxLives := 0;
2604 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_ALLOWEXIT;
2605 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_MONSTERS;
2606 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_BOTVSMONSTER;
2607 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITPROJECTILE;
2608 gGameSettings.Options := gGameSettings.Options + GAME_OPTION_TEAMHITTRACE;
2609 gSwitchGameMode := GM_SINGLE;
2611 gLMSRespawn := LMS_RESPAWN_NONE;
2612 gLMSRespawnTime := 0;
2613 gSpectLatchPID1 := 0;
2614 gSpectLatchPID2 := 0;
2616 g_Game_ExecuteEvent('ongamestart');
2618 // Установка размеров окон игроков:
2619 g_Game_SetupScreenSize();
2621 // Создание первого игрока:
2622 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2623 gPlayer1Settings.Color,
2624 gPlayer1Settings.Team, False));
2625 if gPlayer1 = nil then
2626 begin
2627 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2628 Exit;
2629 end;
2631 gPlayer1.Name := gPlayer1Settings.Name;
2632 nPl := 1;
2634 // Создание второго игрока, если есть:
2635 if TwoPlayers then
2636 begin
2637 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2638 gPlayer2Settings.Color,
2639 gPlayer2Settings.Team, False));
2640 if gPlayer2 = nil then
2641 begin
2642 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2643 Exit;
2644 end;
2646 gPlayer2.Name := gPlayer2Settings.Name;
2647 Inc(nPl);
2648 end;
2650 // Загрузка и запуск карты:
2651 if not g_Game_StartMap(false{asMegawad}, MAP, True) then
2652 begin
2653 if (Pos(':\', Map) > 0) or (Pos(':/', Map) > 0) then tmps := Map else tmps := gGameSettings.WAD + ':\' + MAP;
2654 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [tmps]));
2655 Exit;
2656 end;
2658 // Настройки игроков и ботов:
2659 g_Player_Init();
2661 // Создаем ботов:
2662 for i := nPl+1 to nPlayers do
2663 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2664 end;
2666 procedure g_Game_StartCustom(Map: String; GameMode: Byte;
2667 TimeLimit, GoalLimit: Word;
2668 MaxLives: Byte;
2669 Options: LongWord; nPlayers: Byte);
2670 var
2671 i, nPl: Integer;
2672 begin
2673 g_Game_Free();
2675 e_WriteLog('Starting custom game...', TMsgType.Notify);
2677 g_Game_ClearLoading();
2679 // Настройки игры:
2680 gGameSettings.GameType := GT_CUSTOM;
2681 gGameSettings.GameMode := GameMode;
2682 gSwitchGameMode := GameMode;
2683 gGameSettings.TimeLimit := TimeLimit;
2684 gGameSettings.GoalLimit := GoalLimit;
2685 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2686 gGameSettings.Options := Options;
2688 gCoopTotalMonstersKilled := 0;
2689 gCoopTotalSecretsFound := 0;
2690 gCoopTotalMonsters := 0;
2691 gCoopTotalSecrets := 0;
2692 gAimLine := False;
2693 gShowMap := False;
2695 gLMSRespawn := LMS_RESPAWN_NONE;
2696 gLMSRespawnTime := 0;
2697 gSpectLatchPID1 := 0;
2698 gSpectLatchPID2 := 0;
2700 g_Game_ExecuteEvent('ongamestart');
2702 // Установка размеров окон игроков:
2703 g_Game_SetupScreenSize();
2705 // Режим наблюдателя:
2706 if nPlayers = 0 then
2707 begin
2708 gPlayer1 := nil;
2709 gPlayer2 := nil;
2710 end;
2712 nPl := 0;
2713 if nPlayers >= 1 then
2714 begin
2715 // Создание первого игрока:
2716 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2717 gPlayer1Settings.Color,
2718 gPlayer1Settings.Team, False));
2719 if gPlayer1 = nil then
2720 begin
2721 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2722 Exit;
2723 end;
2725 gPlayer1.Name := gPlayer1Settings.Name;
2726 Inc(nPl);
2727 end;
2729 if nPlayers >= 2 then
2730 begin
2731 // Создание второго игрока:
2732 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2733 gPlayer2Settings.Color,
2734 gPlayer2Settings.Team, False));
2735 if gPlayer2 = nil then
2736 begin
2737 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2738 Exit;
2739 end;
2741 gPlayer2.Name := gPlayer2Settings.Name;
2742 Inc(nPl);
2743 end;
2745 // Загрузка и запуск карты:
2746 if not g_Game_StartMap(true{asMegawad}, Map, True) then
2747 begin
2748 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
2749 Exit;
2750 end;
2752 // Нет точек появления:
2753 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
2754 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
2755 g_Map_GetPointCount(RESPAWNPOINT_DM) +
2756 g_Map_GetPointCount(RESPAWNPOINT_RED)+
2757 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
2758 begin
2759 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
2760 Exit;
2761 end;
2763 // Настройки игроков и ботов:
2764 g_Player_Init();
2766 // Создаем ботов:
2767 for i := nPl+1 to nPlayers do
2768 g_Player_Create(STD_PLAYER_MODEL, _RGB(0, 0, 0), 0, True);
2769 end;
2771 procedure g_Game_StartServer(Map: String; GameMode: Byte;
2772 TimeLimit, GoalLimit: Word; MaxLives: Byte;
2773 Options: LongWord; nPlayers: Byte;
2774 IPAddr: LongWord; Port: Word);
2775 begin
2776 g_Game_Free();
2777 g_Net_Slist_ServerClosed();
2779 e_WriteLog('Starting net game (server)...', TMsgType.Notify);
2781 g_Game_ClearLoading();
2783 // Настройки игры:
2784 gGameSettings.GameType := GT_SERVER;
2785 gGameSettings.GameMode := GameMode;
2786 gSwitchGameMode := GameMode;
2787 gGameSettings.TimeLimit := TimeLimit;
2788 gGameSettings.GoalLimit := GoalLimit;
2789 gGameSettings.MaxLives := IfThen(GameMode = GM_CTF, 0, MaxLives);
2790 gGameSettings.Options := Options;
2792 gCoopTotalMonstersKilled := 0;
2793 gCoopTotalSecretsFound := 0;
2794 gCoopTotalMonsters := 0;
2795 gCoopTotalSecrets := 0;
2796 gAimLine := False;
2797 gShowMap := False;
2799 gLMSRespawn := LMS_RESPAWN_NONE;
2800 gLMSRespawnTime := 0;
2801 gSpectLatchPID1 := 0;
2802 gSpectLatchPID2 := 0;
2804 g_Game_ExecuteEvent('ongamestart');
2806 // Установка размеров окна игрока
2807 g_Game_SetupScreenSize();
2809 // Режим наблюдателя:
2810 if nPlayers = 0 then
2811 begin
2812 gPlayer1 := nil;
2813 gPlayer2 := nil;
2814 end;
2816 if nPlayers >= 1 then
2817 begin
2818 // Создание первого игрока:
2819 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
2820 gPlayer1Settings.Color,
2821 gPlayer1Settings.Team, False));
2822 if gPlayer1 = nil then
2823 begin
2824 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
2825 Exit;
2826 end;
2828 gPlayer1.Name := gPlayer1Settings.Name;
2829 end;
2831 if nPlayers >= 2 then
2832 begin
2833 // Создание второго игрока:
2834 gPlayer2 := g_Player_Get(g_Player_Create(gPlayer2Settings.Model,
2835 gPlayer2Settings.Color,
2836 gPlayer2Settings.Team, False));
2837 if gPlayer2 = nil then
2838 begin
2839 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [2]));
2840 Exit;
2841 end;
2843 gPlayer2.Name := gPlayer2Settings.Name;
2844 end;
2846 g_Game_SetLoadingText(_lc[I_LOAD_HOST], 0, False);
2847 if NetForwardPorts then
2848 g_Game_SetLoadingText(_lc[I_LOAD_PORTS], 0, False);
2850 // Стартуем сервер
2851 if not g_Net_Host(IPAddr, Port, NetMaxClients) then
2852 begin
2853 g_FatalError(_lc[I_NET_MSG] + Format(_lc[I_NET_ERR_HOST], [Port]));
2854 Exit;
2855 end;
2857 g_Net_Slist_Set(NetMasterList);
2859 g_Net_Slist_ServerStarted();
2861 // Загрузка и запуск карты:
2862 if not g_Game_StartMap(false{asMegawad}, Map, True) then
2863 begin
2864 g_Net_Slist_ServerClosed();
2865 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Map]));
2866 Exit;
2867 end;
2869 // Нет точек появления:
2870 if (g_Map_GetPointCount(RESPAWNPOINT_PLAYER1) +
2871 g_Map_GetPointCount(RESPAWNPOINT_PLAYER2) +
2872 g_Map_GetPointCount(RESPAWNPOINT_DM) +
2873 g_Map_GetPointCount(RESPAWNPOINT_RED)+
2874 g_Map_GetPointCount(RESPAWNPOINT_BLUE)) < 1 then
2875 begin
2876 g_Net_Slist_ServerClosed();
2877 g_FatalError(_lc[I_GAME_ERROR_GET_SPAWN]);
2878 Exit;
2879 end;
2881 // Настройки игроков и ботов:
2882 g_Player_Init();
2884 g_Net_Slist_ServerMapStarted();
2885 NetState := NET_STATE_GAME;
2886 end;
2888 procedure g_Game_StartClient(Addr: String; Port: Word; PW: String);
2889 var
2890 Map: String;
2891 WadName: string;
2892 Ptr: Pointer;
2893 T: Cardinal;
2894 MID: Byte;
2895 State: Byte;
2896 OuterLoop: Boolean;
2897 newResPath: string;
2898 InMsg: TMsg;
2899 begin
2900 g_Game_Free();
2902 State := 0;
2903 e_WriteLog('Starting net game (client)...', TMsgType.Notify);
2904 e_WriteLog('NET: Trying to connect to ' + Addr + ':' + IntToStr(Port) + '...', TMsgType.Notify);
2906 g_Game_ClearLoading();
2908 // Настройки игры:
2909 gGameSettings.GameType := GT_CLIENT;
2911 gCoopTotalMonstersKilled := 0;
2912 gCoopTotalSecretsFound := 0;
2913 gCoopTotalMonsters := 0;
2914 gCoopTotalSecrets := 0;
2915 gAimLine := False;
2916 gShowMap := False;
2918 g_Game_ExecuteEvent('ongamestart');
2920 // Установка размеров окон игроков:
2921 g_Game_SetupScreenSize();
2923 NetState := NET_STATE_AUTH;
2925 g_Game_SetLoadingText(_lc[I_LOAD_CONNECT], 0, False);
2927 // create (or update) map/resource databases
2928 g_Res_CreateDatabases(true);
2930 gLMSRespawn := LMS_RESPAWN_NONE;
2931 gLMSRespawnTime := 0;
2932 gSpectLatchPID1 := 0;
2933 gSpectLatchPID2 := 0;
2935 // Стартуем клиент
2936 if not g_Net_Connect(Addr, Port) then
2937 begin
2938 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
2939 NetState := NET_STATE_NONE;
2940 Exit;
2941 end;
2943 g_Game_SetLoadingText(_lc[I_LOAD_SEND_INFO], 0, False);
2944 MC_SEND_Info(PW);
2945 g_Game_SetLoadingText(_lc[I_LOAD_WAIT_INFO], 0, False);
2947 OuterLoop := True;
2948 while OuterLoop do
2949 begin
2950 // fuck! https://www.mail-archive.com/enet-discuss@cubik.org/msg00852.html
2951 // tl;dr: on shitdows, we can get -1 sometimes, and it is *NOT* a failure.
2952 // thank you, enet. let's ignore failures altogether then.
2953 while (enet_host_service(NetHost, @NetEvent, 50) > 0) do
2954 begin
2955 if (NetEvent.kind = ENET_EVENT_TYPE_RECEIVE) then
2956 begin
2957 if (NetEvent.channelID = NET_CHAN_DOWNLOAD_EX) then
2958 begin
2959 // ignore all download packets, they're processed by separate code
2960 enet_packet_destroy(NetEvent.packet);
2961 continue;
2962 end;
2963 Ptr := NetEvent.packet^.data;
2964 if not InMsg.Init(Ptr, NetEvent.packet^.dataLength, True) then
2965 begin
2966 enet_packet_destroy(NetEvent.packet);
2967 continue;
2968 end;
2970 InMsg.ReadLongWord(); // skip size
2971 MID := InMsg.ReadByte();
2973 if (MID = NET_MSG_INFO) and (State = 0) then
2974 begin
2975 NetMyID := InMsg.ReadByte();
2976 NetPlrUID1 := InMsg.ReadWord();
2978 WadName := InMsg.ReadString();
2979 Map := InMsg.ReadString();
2981 gWADHash := InMsg.ReadMD5();
2983 gGameSettings.GameMode := InMsg.ReadByte();
2984 gSwitchGameMode := gGameSettings.GameMode;
2985 gGameSettings.GoalLimit := InMsg.ReadWord();
2986 gGameSettings.TimeLimit := InMsg.ReadWord();
2987 gGameSettings.MaxLives := InMsg.ReadByte();
2988 gGameSettings.Options := InMsg.ReadLongWord();
2989 T := InMsg.ReadLongWord();
2991 //newResPath := g_Res_SearchSameWAD(MapsDir, WadName, gWADHash);
2992 //if newResPath = '' then
2993 begin
2994 //g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
2995 newResPath := g_Res_DownloadMapWAD(ExtractFileName(WadName), gWADHash);
2996 if newResPath = '' then
2997 begin
2998 g_FatalError(_lc[I_NET_ERR_HASH]);
2999 enet_packet_destroy(NetEvent.packet);
3000 NetState := NET_STATE_NONE;
3001 Exit;
3002 end;
3003 e_LogWritefln('using downloaded map wad [%s] for [%s]`', [newResPath, WadName], TMsgType.Notify);
3004 end;
3005 //newResPath := ExtractRelativePath(MapsDir, newResPath);
3008 gPlayer1 := g_Player_Get(g_Player_Create(gPlayer1Settings.Model,
3009 gPlayer1Settings.Color,
3010 gPlayer1Settings.Team, False));
3012 if gPlayer1 = nil then
3013 begin
3014 g_FatalError(Format(_lc[I_GAME_ERROR_PLAYER_CREATE], [1]));
3016 enet_packet_destroy(NetEvent.packet);
3017 NetState := NET_STATE_NONE;
3018 Exit;
3019 end;
3021 gPlayer1.Name := gPlayer1Settings.Name;
3022 gPlayer1.UID := NetPlrUID1;
3023 gPlayer1.Reset(True);
3025 if not g_Game_StartMap(false{asMegawad}, newResPath + ':\' + Map, True) then
3026 begin
3027 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [WadName + ':\' + Map]));
3029 enet_packet_destroy(NetEvent.packet);
3030 NetState := NET_STATE_NONE;
3031 Exit;
3032 end;
3034 gTime := T;
3036 State := 1;
3037 OuterLoop := False;
3038 enet_packet_destroy(NetEvent.packet);
3039 break;
3040 end
3041 else
3042 enet_packet_destroy(NetEvent.packet);
3043 end
3044 else
3045 begin
3046 if (NetEvent.kind = ENET_EVENT_TYPE_DISCONNECT) then
3047 begin
3048 State := 0;
3049 if (NetEvent.data <= NET_DISC_MAX) then
3050 g_Console_Add(_lc[I_NET_MSG_ERROR] + _lc[I_NET_ERR_CONN] + ' ' +
3051 _lc[TStrings_Locale(Cardinal(I_NET_DISC_NONE) + NetEvent.data)], True);
3052 OuterLoop := False;
3053 Break;
3054 end;
3055 end;
3056 end;
3058 ProcessLoading(true);
3060 if g_Net_UserRequestExit() then
3061 begin
3062 State := 0;
3063 break;
3064 end;
3065 end;
3067 if State <> 1 then
3068 begin
3069 g_FatalError(_lc[I_NET_MSG] + _lc[I_NET_ERR_CONN]);
3070 NetState := NET_STATE_NONE;
3071 Exit;
3072 end;
3074 g_Player_Init();
3075 NetState := NET_STATE_GAME;
3076 MC_SEND_FullStateRequest;
3077 e_WriteLog('NET: Connection successful.', TMsgType.Notify);
3078 end;
3080 var
3081 lastAsMegaWad: Boolean = false;
3083 procedure g_Game_ChangeMap(const MapPath: String);
3084 var
3085 Force: Boolean;
3086 begin
3087 g_Game_ClearLoading();
3089 Force := gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF];
3090 // Если уровень завершился по триггеру Выход, не очищать инвентарь
3091 if gExitByTrigger then
3092 begin
3093 Force := False;
3094 gExitByTrigger := False;
3095 end;
3096 if not g_Game_StartMap(lastAsMegaWad, MapPath, Force) then
3097 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [MapPath]));
3098 end;
3100 procedure g_Game_Restart();
3101 var
3102 Map: string;
3103 begin
3104 if g_Game_IsClient then
3105 Exit;
3106 map := g_ExtractFileName(gMapInfo.Map);
3107 e_LogWritefln('g_Game_Restart: map = "%s" gCurrentMapFileName = "%s"', [map, gCurrentMapFileName]);
3109 MessageTime := 0;
3110 gGameOn := False;
3111 g_Game_ClearLoading();
3112 g_Game_StartMap(lastAsMegaWad, Map, True, gCurrentMapFileName);
3113 end;
3115 function g_Game_StartMap (asMegawad: Boolean; Map: String; Force: Boolean = False; const oldMapPath: AnsiString=''): Boolean;
3116 var
3117 NewWAD, ResName: String;
3118 I: Integer;
3119 nws: AnsiString;
3120 begin
3121 g_Map_Free((Map <> gCurrentMapFileName) and (oldMapPath <> gCurrentMapFileName));
3122 g_Player_RemoveAllCorpses();
3124 if (not g_Game_IsClient) and
3125 (gSwitchGameMode <> gGameSettings.GameMode) and
3126 (gGameSettings.GameMode <> GM_SINGLE) then
3127 begin
3128 if gSwitchGameMode = GM_CTF then
3129 gGameSettings.MaxLives := 0;
3130 gGameSettings.GameMode := gSwitchGameMode;
3131 Force := True;
3132 end else
3133 gSwitchGameMode := gGameSettings.GameMode;
3135 g_Player_ResetTeams();
3137 lastAsMegaWad := asMegawad;
3138 if isWadPath(Map) then
3139 begin
3140 NewWAD := g_ExtractWadName(Map);
3141 ResName := g_ExtractFileName(Map);
3142 if g_Game_IsServer then
3143 begin
3144 nws := findDiskWad(NewWAD);
3145 //writeln('000: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3146 if (asMegawad) then
3147 begin
3148 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3149 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3150 end
3151 else
3152 begin
3153 if (length(nws) = 0) then nws := e_FindWad(MapDirs, NewWAD);
3154 if (length(nws) = 0) then nws := e_FindWad(MegawadDirs, NewWAD);
3155 end;
3156 //if (length(nws) = 0) then nws := e_FindWad(MapDownloadDirs, NewWAD);
3157 //writeln('001: Map=[', Map, ']; nws=[', nws, ']; NewWAD=[', NewWAD, ']');
3158 //nws := NewWAD;
3159 if (length(nws) = 0) then
3160 begin
3161 ResName := ''; // failed
3162 end
3163 else
3164 begin
3165 NewWAD := nws;
3166 if (g_Game_IsNet) then gWADHash := MD5File(nws);
3167 //writeln('********: nws=', nws, ' : Map=', Map, ' : nw=', NewWAD, ' : resname=', ResName);
3168 g_Game_LoadWAD(NewWAD);
3169 end;
3170 end
3171 else
3172 begin
3173 // hash received in MC_RECV_GameEvent -> NET_EV_MAPSTART
3174 NewWAD := g_Game_ClientWAD(NewWAD, gWADHash);
3175 end;
3176 end
3177 else
3178 begin
3179 NewWAD := gGameSettings.WAD;
3180 ResName := Map;
3181 end;
3183 gTime := 0;
3185 //writeln('********: gsw=', gGameSettings.WAD, '; rn=', ResName);
3186 result := false;
3187 if (ResName <> '') and (NewWAD <> '') then
3188 begin
3189 //result := g_Map_Load(gGameSettings.WAD + ':\' + ResName);
3190 result := g_Map_Load(NewWAD+':\'+ResName);
3191 end;
3192 if Result then
3193 begin
3194 g_Player_ResetAll(Force or gLastMap, gGameSettings.GameType = GT_SINGLE);
3196 gState := STATE_NONE;
3197 g_ActiveWindow := nil;
3198 gGameOn := True;
3200 DisableCheats();
3201 ResetTimer();
3203 if gGameSettings.GameMode = GM_CTF then
3204 begin
3205 g_Map_ResetFlag(FLAG_RED);
3206 g_Map_ResetFlag(FLAG_BLUE);
3207 // CTF, а флагов нет:
3208 if not g_Map_HaveFlagPoints() then
3209 g_SimpleError(_lc[I_GAME_ERROR_CTF]);
3210 end;
3211 end
3212 else
3213 begin
3214 gState := STATE_MENU;
3215 gGameOn := False;
3216 end;
3218 gExit := 0;
3219 gPauseMain := false;
3220 gPauseHolmes := false;
3221 NetTimeToUpdate := 1;
3222 NetTimeToReliable := 0;
3223 NetTimeToMaster := NetMasterRate;
3224 gSpectLatchPID1 := 0;
3225 gSpectLatchPID2 := 0;
3226 gMissionFailed := False;
3227 gNextMap := '';
3229 gCoopMonstersKilled := 0;
3230 gCoopSecretsFound := 0;
3232 gVoteInProgress := False;
3233 gVotePassed := False;
3234 gVoteCount := 0;
3235 gVoted := False;
3237 gStatsOff := False;
3239 if not gGameOn then Exit;
3241 g_Game_SpectateCenterView();
3243 if g_Game_IsServer then
3244 begin
3245 if (gGameSettings.MaxLives > 0) and (gGameSettings.WarmupTime > 0) then
3246 begin
3247 gLMSRespawn := LMS_RESPAWN_WARMUP;
3248 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3249 gLMSSoftSpawn := True;
3250 if g_Game_IsNet then
3251 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3252 end
3253 else
3254 begin
3255 gLMSRespawn := LMS_RESPAWN_NONE;
3256 gLMSRespawnTime := 0;
3257 end;
3258 end;
3260 if NetMode = NET_SERVER then
3261 begin
3262 MH_SEND_GameEvent(NET_EV_MAPSTART, gGameSettings.GameMode, Map);
3264 // Мастерсервер
3265 g_Net_Slist_ServerMapStarted();
3267 if NetClients <> nil then
3268 for I := 0 to High(NetClients) do
3269 if NetClients[I].Used then
3270 begin
3271 NetClients[I].Voted := False;
3272 if NetClients[I].RequestedFullUpdate then
3273 begin
3274 MH_SEND_Everything((NetClients[I].State = NET_STATE_AUTH), I);
3275 NetClients[I].RequestedFullUpdate := False;
3276 end;
3277 end;
3279 g_Net_UnbanNonPermHosts();
3280 end;
3282 if gLastMap then
3283 begin
3284 gCoopTotalMonstersKilled := 0;
3285 gCoopTotalSecretsFound := 0;
3286 gCoopTotalMonsters := 0;
3287 gCoopTotalSecrets := 0;
3288 gLastMap := False;
3289 end;
3291 g_Game_ExecuteEvent('onmapstart');
3292 end;
3294 procedure SetFirstLevel;
3295 begin
3296 gNextMap := '';
3298 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3299 if MapList = nil then
3300 Exit;
3302 SortSArray(MapList);
3303 gNextMap := MapList[Low(MapList)];
3305 MapList := nil;
3306 end;
3308 procedure g_Game_ExitLevel(const Map: AnsiString);
3309 begin
3310 gNextMap := Map;
3312 gCoopTotalMonstersKilled := gCoopTotalMonstersKilled + gCoopMonstersKilled;
3313 gCoopTotalSecretsFound := gCoopTotalSecretsFound + gCoopSecretsFound;
3314 gCoopTotalMonsters := gCoopTotalMonsters + gTotalMonsters;
3315 gCoopTotalSecrets := gCoopTotalSecrets + gSecretsCount;
3317 // Вышли в выход в Одиночной игре:
3318 if gGameSettings.GameType = GT_SINGLE then
3319 gExit := EXIT_ENDLEVELSINGLE
3320 else // Вышли в выход в Своей игре
3321 begin
3322 gExit := EXIT_ENDLEVELCUSTOM;
3323 if gGameSettings.GameMode = GM_COOP then
3324 g_Player_RememberAll;
3326 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3327 begin
3328 gLastMap := True;
3329 if gGameSettings.GameMode = GM_COOP then
3330 gStatsOff := True;
3332 gStatsPressed := True;
3333 gNextMap := 'MAP01';
3335 if not g_Map_Exist(gGameSettings.WAD + ':\' + gNextMap) then
3336 g_Game_NextLevel;
3338 if g_Game_IsNet then
3339 begin
3340 MH_SEND_GameStats();
3341 MH_SEND_CoopStats();
3342 end;
3343 end;
3344 end;
3345 end;
3347 procedure g_Game_RestartLevel();
3348 var
3349 Map: string;
3350 begin
3351 if gGameSettings.GameMode = GM_SINGLE then
3352 begin
3353 g_Game_Restart();
3354 Exit;
3355 end;
3356 gExit := EXIT_ENDLEVELCUSTOM;
3357 Map := g_ExtractFileName(gMapInfo.Map);
3358 gNextMap := Map;
3359 end;
3361 function g_Game_ClientWAD (NewWAD: String; const WHash: TMD5Digest): AnsiString;
3362 var
3363 gWAD{, xwad}: String;
3364 begin
3365 result := NewWAD;
3366 if not g_Game_IsClient then Exit;
3367 //e_LogWritefln('*** g_Game_ClientWAD: `%s`', [NewWAD]);
3369 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3370 if gWAD = '' then
3371 begin
3372 result := '';
3373 g_Game_Free();
3374 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3375 Exit;
3376 end;
3378 e_LogWritefln('using downloaded client map wad [%s] for [%s]', [gWAD, NewWAD], TMsgType.Notify);
3379 NewWAD := gWAD;
3381 g_Game_LoadWAD(NewWAD);
3382 result := NewWAD;
3385 if LowerCase(NewWAD) = LowerCase(gGameSettings.WAD) then Exit;
3386 gWAD := g_Res_SearchSameWAD(MapsDir, ExtractFileName(NewWAD), WHash);
3387 if gWAD = '' then
3388 begin
3389 g_Game_SetLoadingText(_lc[I_LOAD_DL_RES], 0, False);
3390 gWAD := g_Res_DownloadMapWAD(ExtractFileName(NewWAD), WHash);
3391 if gWAD = '' then
3392 begin
3393 g_Game_Free();
3394 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [ExtractFileName(NewWAD)]));
3395 Exit;
3396 end;
3397 end;
3398 NewWAD := ExtractRelativePath(MapsDir, gWAD);
3399 g_Game_LoadWAD(NewWAD);
3401 end;
3403 procedure g_Game_RestartRound(NoMapRestart: Boolean = False);
3404 var
3405 i, n, nb, nr: Integer;
3406 begin
3407 if not g_Game_IsServer then Exit;
3408 if gLMSRespawn = LMS_RESPAWN_NONE then Exit;
3409 gLMSRespawn := LMS_RESPAWN_NONE;
3410 gLMSRespawnTime := 0;
3411 MessageTime := 0;
3413 if (gGameSettings.GameMode = GM_COOP) and not NoMapRestart then
3414 begin
3415 gMissionFailed := True;
3416 g_Game_RestartLevel;
3417 Exit;
3418 end;
3420 n := 0; nb := 0; nr := 0;
3421 for i := Low(gPlayers) to High(gPlayers) do
3422 if (gPlayers[i] <> nil) and
3423 ((not gPlayers[i].FSpectator) or gPlayers[i].FWantsInGame or
3424 (gPlayers[i] is TBot)) then
3425 begin
3426 Inc(n);
3427 if gPlayers[i].Team = TEAM_RED then Inc(nr)
3428 else if gPlayers[i].Team = TEAM_BLUE then Inc(nb)
3429 end;
3431 if (n < 1) or ((gGameSettings.GameMode = GM_TDM) and ((nr = 0) or (nb = 0))) then
3432 begin
3433 // wait a second until the fuckers finally decide to join
3434 gLMSRespawn := LMS_RESPAWN_WARMUP;
3435 gLMSRespawnTime := gTime + gGameSettings.WarmupTime*1000;
3436 gLMSSoftSpawn := NoMapRestart;
3437 if g_Game_IsNet then
3438 MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3439 Exit;
3440 end;
3442 g_Player_RemoveAllCorpses;
3443 g_Game_Message(_lc[I_MESSAGE_LMS_START], 144);
3444 if g_Game_IsNet then
3445 MH_SEND_GameEvent(NET_EV_LMS_START);
3447 for i := Low(gPlayers) to High(gPlayers) do
3448 begin
3449 if gPlayers[i] = nil then continue;
3450 if gPlayers[i] is TBot then gPlayers[i].FWantsInGame := True;
3451 // don't touch normal spectators
3452 if gPlayers[i].FSpectator and not gPlayers[i].FWantsInGame then
3453 begin
3454 gPlayers[i].FNoRespawn := True;
3455 gPlayers[i].Lives := 0;
3456 if g_Game_IsNet then
3457 MH_SEND_PlayerStats(gPlayers[I].UID);
3458 continue;
3459 end;
3460 gPlayers[i].FNoRespawn := False;
3461 gPlayers[i].Lives := gGameSettings.MaxLives;
3462 gPlayers[i].Respawn(False, True);
3463 if gGameSettings.GameMode = GM_COOP then
3464 begin
3465 gPlayers[i].Frags := 0;
3466 gPlayers[i].RecallState;
3467 end;
3468 if (gPlayer1 = nil) and (gSpectLatchPID1 > 0) then
3469 gPlayer1 := g_Player_Get(gSpectLatchPID1);
3470 if (gPlayer2 = nil) and (gSpectLatchPID2 > 0) then
3471 gPlayer2 := g_Player_Get(gSpectLatchPID2);
3472 end;
3474 g_Items_RestartRound();
3476 gLMSSoftSpawn := False;
3477 end;
3479 function g_Game_GetFirstMap(WAD: String): String;
3480 begin
3481 Result := '';
3483 MapList := g_Map_GetMapsList(WAD);
3484 if MapList = nil then
3485 Exit;
3487 SortSArray(MapList);
3488 Result := MapList[Low(MapList)];
3490 if not g_Map_Exist(WAD + ':\' + Result) then
3491 Result := '';
3493 MapList := nil;
3494 end;
3496 function g_Game_GetNextMap(): String;
3497 var
3498 I: Integer;
3499 Map: string;
3500 begin
3501 Result := '';
3503 MapList := g_Map_GetMapsList(gGameSettings.WAD);
3504 if MapList = nil then
3505 Exit;
3507 Map := g_ExtractFileName(gMapInfo.Map);
3509 SortSArray(MapList);
3510 MapIndex := -255;
3511 for I := Low(MapList) to High(MapList) do
3512 if Map = MapList[I] then
3513 begin
3514 MapIndex := I;
3515 Break;
3516 end;
3518 if MapIndex <> -255 then
3519 begin
3520 if MapIndex = High(MapList) then
3521 Result := MapList[Low(MapList)]
3522 else
3523 Result := MapList[MapIndex + 1];
3525 if not g_Map_Exist(gGameSettings.WAD + ':\' + Result) then Result := Map;
3526 end;
3528 MapList := nil;
3529 end;
3531 procedure g_Game_NextLevel();
3532 begin
3533 if gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP] then
3534 gExit := EXIT_ENDLEVELCUSTOM
3535 else
3536 begin
3537 gExit := EXIT_ENDLEVELSINGLE;
3538 Exit;
3539 end;
3541 if gNextMap <> '' then Exit;
3542 gNextMap := g_Game_GetNextMap();
3543 end;
3545 function g_Game_IsTestMap(): Boolean;
3546 begin
3547 result := StrEquCI1251(TEST_MAP_NAME, g_ExtractFileName(gMapInfo.Map));
3548 end;
3550 procedure g_Game_DeleteTestMap();
3551 var
3552 a: Integer;
3553 //MapName: AnsiString;
3554 WadName: string;
3556 WAD: TWADFile;
3557 MapList: SSArray;
3558 time: Integer;
3560 begin
3561 a := Pos('.wad:\', toLowerCase1251(gMapToDelete));
3562 if (a = 0) then a := Pos('.wad:/', toLowerCase1251(gMapToDelete));
3563 if (a = 0) then exit;
3565 // Выделяем имя wad-файла и имя карты
3566 WadName := Copy(gMapToDelete, 1, a+3);
3567 Delete(gMapToDelete, 1, a+5);
3568 gMapToDelete := UpperCase(gMapToDelete);
3569 //MapName := '';
3570 //CopyMemory(@MapName[0], @gMapToDelete[1], Min(16, Length(gMapToDelete)));
3573 // Имя карты не стандартное тестовое:
3574 if MapName <> TEST_MAP_NAME then
3575 Exit;
3577 if not gTempDelete then
3578 begin
3579 time := g_GetFileTime(WadName);
3580 WAD := TWADFile.Create();
3582 // Читаем Wad-файл:
3583 if not WAD.ReadFile(WadName) then
3584 begin // Нет такого WAD-файла
3585 WAD.Free();
3586 Exit;
3587 end;
3589 // Составляем список карт и ищем нужную:
3590 WAD.CreateImage();
3591 MapList := WAD.GetResourcesList('');
3593 if MapList <> nil then
3594 for a := 0 to High(MapList) do
3595 if MapList[a] = MapName then
3596 begin
3597 // Удаляем и сохраняем:
3598 WAD.RemoveResource('', MapName);
3599 WAD.SaveTo(WadName);
3600 Break;
3601 end;
3603 WAD.Free();
3604 g_SetFileTime(WadName, time);
3605 end else
3607 if gTempDelete then DeleteFile(WadName);
3608 end;
3610 procedure GameCVars(P: SSArray);
3611 var
3612 a, b: Integer;
3613 stat: TPlayerStatArray;
3614 cmd: string;
3616 procedure ParseGameFlag(Flag: LongWord; OffMsg, OnMsg: TStrings_Locale; OnMapChange: Boolean = False);
3617 var
3618 x: Boolean;
3619 begin
3620 if Length(P) > 1 then
3621 begin
3622 x := P[1] = '1';
3624 if x then
3625 gsGameFlags := gsGameFlags or Flag
3626 else
3627 gsGameFlags := gsGameFlags and (not Flag);
3629 if g_Game_IsServer then
3630 begin
3631 if x then
3632 gGameSettings.Options := gGameSettings.Options or Flag
3633 else
3634 gGameSettings.Options := gGameSettings.Options and (not Flag);
3635 if g_Game_IsNet then MH_SEND_GameSettings;
3636 end;
3637 end;
3639 if LongBool(gsGameFlags and Flag) then
3640 g_Console_Add(_lc[OnMsg])
3641 else
3642 g_Console_Add(_lc[OffMsg]);
3644 if OnMapChange and g_Game_IsServer then
3645 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3646 end;
3648 begin
3649 stat := nil;
3650 cmd := LowerCase(P[0]);
3652 if cmd = 'g_gamemode' then
3653 begin
3654 if (Length(P) > 1) then
3655 begin
3656 a := g_Game_TextToMode(P[1]);
3657 if a = GM_SINGLE then a := GM_COOP;
3658 gsGameMode := g_Game_ModeToText(a);
3659 if g_Game_IsServer then
3660 begin
3661 gSwitchGameMode := a;
3662 if (gGameOn and (gGameSettings.GameMode = GM_SINGLE)) or
3663 (gState = STATE_INTERSINGLE) then
3664 gSwitchGameMode := GM_SINGLE;
3665 if not gGameOn then
3666 gGameSettings.GameMode := gSwitchGameMode;
3667 end;
3668 end;
3670 if gSwitchGameMode = gGameSettings.GameMode then
3671 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CURRENT],
3672 [g_Game_ModeToText(gGameSettings.GameMode)]))
3673 else
3674 g_Console_Add(Format(_lc[I_MSG_GAMEMODE_CHANGE],
3675 [g_Game_ModeToText(gGameSettings.GameMode),
3676 g_Game_ModeToText(gSwitchGameMode)]));
3677 end
3678 else if cmd = 'g_friendlyfire' then
3679 begin
3680 ParseGameFlag(GAME_OPTION_TEAMDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3681 end
3682 else if cmd = 'g_friendly_absorb_damage' then
3683 begin
3684 ParseGameFlag(GAME_OPTION_TEAMABSORBDAMAGE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3685 end
3686 else if cmd = 'g_friendly_hit_trace' then
3687 begin
3688 ParseGameFlag(GAME_OPTION_TEAMHITTRACE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3689 end
3690 else if cmd = 'g_friendly_hit_projectile' then
3691 begin
3692 ParseGameFlag(GAME_OPTION_TEAMHITPROJECTILE, I_MSG_FRIENDLY_FIRE_OFF, I_MSG_FRIENDLY_FIRE_ON);
3693 end
3694 else if cmd = 'g_weaponstay' then
3695 begin
3696 ParseGameFlag(GAME_OPTION_WEAPONSTAY, I_MSG_WEAPONSTAY_OFF, I_MSG_WEAPONSTAY_ON);
3697 end
3698 else if cmd = 'g_allow_exit' then
3699 begin
3700 ParseGameFlag(GAME_OPTION_ALLOWEXIT, I_MSG_ALLOWEXIT_OFF, I_MSG_ALLOWEXIT_ON, True);
3701 end
3702 else if cmd = 'g_allow_monsters' then
3703 begin
3704 ParseGameFlag(GAME_OPTION_MONSTERS, I_MSG_ALLOWMON_OFF, I_MSG_ALLOWMON_ON, True);
3705 end
3706 else if cmd = 'g_bot_vsplayers' then
3707 begin
3708 ParseGameFlag(GAME_OPTION_BOTVSPLAYER, I_MSG_BOTSVSPLAYERS_OFF, I_MSG_BOTSVSPLAYERS_ON);
3709 end
3710 else if cmd = 'g_bot_vsmonsters' then
3711 begin
3712 ParseGameFlag(GAME_OPTION_BOTVSMONSTER, I_MSG_BOTSVSMONSTERS_OFF, I_MSG_BOTSVSMONSTERS_ON);
3713 end
3714 else if cmd = 'g_dm_keys' then
3715 begin
3716 ParseGameFlag(GAME_OPTION_DMKEYS, I_MSG_DMKEYS_OFF, I_MSG_DMKEYS_ON, True);
3717 end
3718 else if cmd = 'g_gameflags' then
3719 begin
3720 if Length(P) > 1 then
3721 begin
3722 gsGameFlags := StrToDWordDef(P[1], gsGameFlags);
3723 if g_Game_IsServer then
3724 begin
3725 gGameSettings.Options := gsGameFlags;
3726 if g_Game_IsNet then MH_SEND_GameSettings;
3727 end;
3728 end;
3730 g_Console_Add(Format('%s %u', [cmd, gsGameFlags]));
3731 end
3732 else if cmd = 'g_warmup_time' then
3733 begin
3734 if Length(P) > 1 then
3735 begin
3736 gsWarmupTime := nclamp(StrToIntDef(P[1], gsWarmupTime), 0, $FFFF);
3737 if g_Game_IsServer then
3738 begin
3739 gGameSettings.WarmupTime := gsWarmupTime;
3740 // extend warmup if it's already going
3741 if gLMSRespawn = LMS_RESPAWN_WARMUP then
3742 begin
3743 gLMSRespawnTime := gTime + gsWarmupTime * 1000;
3744 if g_Game_IsNet then MH_SEND_GameEvent(NET_EV_LMS_WARMUP, gLMSRespawnTime - gTime);
3745 end;
3746 if g_Game_IsNet then MH_SEND_GameSettings;
3747 end;
3748 end;
3750 g_Console_Add(Format(_lc[I_MSG_WARMUP], [Integer(gsWarmupTime)]));
3751 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3752 end
3753 else if cmd = 'g_spawn_invul' then
3754 begin
3755 if Length(P) > 1 then
3756 begin
3757 gsSpawnInvul := nclamp(StrToIntDef(P[1], gsSpawnInvul), 0, $FFFF);
3758 if g_Game_IsServer then
3759 begin
3760 gGameSettings.SpawnInvul := gsSpawnInvul;
3761 if g_Game_IsNet then MH_SEND_GameSettings;
3762 end;
3763 end;
3765 g_Console_Add(Format('%s %d', [cmd, Integer(gsSpawnInvul)]));
3766 end
3767 else if cmd = 'g_item_respawn_time' then
3768 begin
3769 if Length(P) > 1 then
3770 begin
3771 gsItemRespawnTime := nclamp(StrToIntDef(P[1], gsItemRespawnTime), 0, $FFFF);
3772 if g_Game_IsServer then
3773 begin
3774 gGameSettings.ItemRespawnTime := gsItemRespawnTime;
3775 if g_Game_IsNet then MH_SEND_GameSettings;
3776 end;
3777 end;
3779 g_Console_Add(Format('%s %d', [cmd, Integer(gsItemRespawnTime)]));
3780 if g_Game_IsServer then g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
3781 end
3782 else if cmd = 'sv_intertime' then
3783 begin
3784 if (Length(P) > 1) then
3785 gDefInterTime := Min(Max(StrToIntDef(P[1], gDefInterTime), -1), 120);
3787 g_Console_Add(cmd + ' = ' + IntToStr(gDefInterTime));
3788 end
3789 else if cmd = 'g_max_particles' then
3790 begin
3791 if Length(p) = 2 then
3792 begin
3793 a := Max(0, StrToInt(p[1]));
3794 g_GFX_SetMax(a)
3795 end
3796 else if Length(p) = 1 then
3797 begin
3798 e_LogWritefln('%s', [g_GFX_GetMax()])
3799 end
3800 else
3801 begin
3802 e_LogWritefln('usage: %s <n>', [cmd])
3803 end
3804 end
3805 else if cmd = 'g_max_shells' then
3806 begin
3807 if Length(p) = 2 then
3808 begin
3809 a := Max(0, StrToInt(p[1]));
3810 g_Shells_SetMax(a)
3811 end
3812 else if Length(p) = 1 then
3813 begin
3814 e_LogWritefln('%s', [g_Shells_GetMax()])
3815 end
3816 else
3817 begin
3818 e_LogWritefln('usage: %s <n>', [cmd])
3819 end
3820 end
3821 else if cmd = 'g_max_gibs' then
3822 begin
3823 if Length(p) = 2 then
3824 begin
3825 a := Max(0, StrToInt(p[1]));
3826 g_Gibs_SetMax(a)
3827 end
3828 else if Length(p) = 1 then
3829 begin
3830 e_LogWritefln('%s', [g_Gibs_GetMax()])
3831 end
3832 else
3833 begin
3834 e_LogWritefln('usage: %s <n>', [cmd])
3835 end
3836 end
3837 else if cmd = 'g_max_corpses' then
3838 begin
3839 if Length(p) = 2 then
3840 begin
3841 a := Max(0, StrToInt(p[1]));
3842 g_Corpses_SetMax(a)
3843 end
3844 else if Length(p) = 1 then
3845 begin
3846 e_LogWritefln('%s', [g_Corpses_GetMax()])
3847 end
3848 else
3849 begin
3850 e_LogWritefln('usage: %s <n>', [cmd])
3851 end
3852 end
3853 else if cmd = 'g_scorelimit' then
3854 begin
3855 if Length(P) > 1 then
3856 begin
3857 gsGoalLimit := nclamp(StrToIntDef(P[1], gsGoalLimit), 0, $FFFF);
3859 if g_Game_IsServer then
3860 begin
3861 b := 0;
3862 if gGameSettings.GameMode = GM_DM then
3863 begin // DM
3864 stat := g_Player_GetStats();
3865 if stat <> nil then
3866 for a := 0 to High(stat) do
3867 if stat[a].Frags > b then
3868 b := stat[a].Frags;
3869 end
3870 else // TDM/CTF
3871 b := Max(gTeamStat[TEAM_RED].Goals, gTeamStat[TEAM_BLUE].Goals);
3873 // if someone has a higher score, set it to that instead
3874 gsGoalLimit := max(gsGoalLimit, b);
3875 gGameSettings.GoalLimit := gsGoalLimit;
3877 if g_Game_IsNet then MH_SEND_GameSettings;
3878 end;
3879 end;
3881 g_Console_Add(Format(_lc[I_MSG_SCORE_LIMIT], [Integer(gsGoalLimit)]));
3882 end
3883 else if cmd = 'g_timelimit' then
3884 begin
3885 if Length(P) > 1 then
3886 begin
3887 gsTimeLimit := nclamp(StrToIntDef(P[1], gsTimeLimit), 0, $FFFF);
3888 if g_Game_IsServer then
3889 begin
3890 gGameSettings.TimeLimit := gsTimeLimit;
3891 if g_Game_IsNet then MH_SEND_GameSettings;
3892 end;
3893 end;
3894 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
3895 [gsTimeLimit div 3600,
3896 (gsTimeLimit div 60) mod 60,
3897 gsTimeLimit mod 60]));
3898 end
3899 else if cmd = 'g_maxlives' then
3900 begin
3901 if Length(P) > 1 then
3902 begin
3903 gsMaxLives := nclamp(StrToIntDef(P[1], gsMaxLives), 0, $FFFF);
3904 if g_Game_IsServer then
3905 begin
3906 gGameSettings.MaxLives := gsMaxLives;
3907 if g_Game_IsNet then MH_SEND_GameSettings;
3908 end;
3909 end;
3911 g_Console_Add(Format(_lc[I_MSG_LIVES], [Integer(gsMaxLives)]));
3912 end;
3913 end;
3915 procedure PlayerSettingsCVars(P: SSArray);
3916 var
3917 cmd: string;
3918 team: Byte;
3920 function ParseTeam(s: string): Byte;
3921 begin
3922 result := 0;
3923 case s of
3924 'red', '1': result := TEAM_RED;
3925 'blue', '2': result := TEAM_BLUE;
3926 else result := TEAM_NONE;
3927 end;
3928 end;
3929 begin
3930 cmd := LowerCase(P[0]);
3931 case cmd of
3932 'p1_name':
3933 begin
3934 if (Length(P) > 1) then
3935 begin
3936 gPlayer1Settings.Name := b_Text_Unformat(P[1]);
3937 if g_Game_IsClient then
3938 MC_SEND_PlayerSettings
3939 else if gGameOn and (gPlayer1 <> nil) then
3940 begin
3941 gPlayer1.Name := b_Text_Unformat(P[1]);
3942 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
3943 end;
3944 end;
3945 end;
3946 'p2_name':
3947 begin
3948 if (Length(P) > 1) then
3949 begin
3950 gPlayer2Settings.Name := b_Text_Unformat(P[1]);
3951 if g_Game_IsClient then
3952 MC_SEND_PlayerSettings
3953 else if gGameOn and (gPlayer2 <> nil) then
3954 begin
3955 gPlayer2.Name := b_Text_Unformat(P[1]);
3956 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
3957 end;
3958 end;
3959 end;
3960 'p1_color':
3961 begin
3962 if Length(P) > 3 then
3963 begin
3964 gPlayer1Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
3965 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
3966 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
3967 if g_Game_IsClient then
3968 MC_SEND_PlayerSettings
3969 else if gGameOn and (gPlayer1 <> nil) then
3970 begin
3971 gPlayer1.SetColor(gPlayer1Settings.Color);
3972 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
3973 end;
3974 end;
3975 end;
3976 'p2_color':
3977 begin
3978 if Length(P) > 3 then
3979 begin
3980 gPlayer2Settings.Color := _RGB(EnsureRange(StrToIntDef(P[1], 0), 0, 255),
3981 EnsureRange(StrToIntDef(P[2], 0), 0, 255),
3982 EnsureRange(StrToIntDef(P[3], 0), 0, 255));
3983 if g_Game_IsClient then
3984 MC_SEND_PlayerSettings
3985 else if gGameOn and (gPlayer2 <> nil) then
3986 begin
3987 gPlayer2.SetColor(gPlayer2Settings.Color);
3988 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
3989 end;
3990 end;
3991 end;
3992 'p1_model':
3993 begin
3994 if (Length(P) > 1) then
3995 begin
3996 gPlayer1Settings.Model := P[1];
3997 if g_Game_IsClient then
3998 MC_SEND_PlayerSettings
3999 else if gGameOn and (gPlayer1 <> nil) then
4000 begin
4001 gPlayer1.FActualModelName := gPlayer1Settings.Model;
4002 gPlayer1.SetModel(gPlayer1Settings.Model);
4003 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer1.UID);
4004 end;
4005 end;
4006 end;
4007 'p2_model':
4008 begin
4009 if (Length(P) > 1) then
4010 begin
4011 gPlayer2Settings.Model := P[1];
4012 if g_Game_IsClient then
4013 MC_SEND_PlayerSettings
4014 else if gGameOn and (gPlayer2 <> nil) then
4015 begin
4016 gPlayer2.FActualModelName := gPlayer2Settings.Model;
4017 gPlayer2.SetModel(gPlayer2Settings.Model);
4018 if g_Game_IsNet then MH_SEND_PlayerSettings(gPlayer2.UID);
4019 end;
4020 end;
4021 end;
4022 'p1_team':
4023 begin
4024 // TODO: switch teams if in game or store this separately
4025 if (Length(P) > 1) then
4026 begin
4027 team := ParseTeam(P[1]);
4028 if team = TEAM_NONE then
4029 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4030 else if not gGameOn and not g_Game_IsNet then
4031 gPlayer1Settings.Team := team
4032 else
4033 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4034 end;
4035 end;
4036 'p2_team':
4037 begin
4038 // TODO: switch teams if in game or store this separately
4039 if (Length(P) > 1) then
4040 begin
4041 team := ParseTeam(P[1]);
4042 if team = TEAM_NONE then
4043 g_Console_Add('expected ''red'', ''blue'', 1 or 2')
4044 else if not gGameOn and not g_Game_IsNet then
4045 gPlayer2Settings.Team := team
4046 else
4047 g_Console_Add(_lc[I_MSG_ONMAPCHANGE]);
4048 end;
4049 end;
4050 end;
4051 end;
4053 procedure PrintHeapStats();
4054 var
4055 hs: TFPCHeapStatus;
4056 begin
4057 hs := GetFPCHeapStatus();
4058 e_LogWriteLn ('v===== heap status =====v');
4059 e_LogWriteFln('max heap size = %d k', [hs.MaxHeapSize div 1024]);
4060 e_LogWriteFln('max heap used = %d k', [hs.MaxHeapUsed div 1024]);
4061 e_LogWriteFln('cur heap size = %d k', [hs.CurrHeapSize div 1024]);
4062 e_LogWriteFln('cur heap used = %d k', [hs.CurrHeapUsed div 1024]);
4063 e_LogWriteFln('cur heap free = %d k', [hs.CurrHeapFree div 1024]);
4064 e_LogWriteLn ('^=======================^');
4065 end;
4067 procedure DebugCommands(P: SSArray);
4068 var
4069 a, b: Integer;
4070 cmd: string;
4071 //pt: TDFPoint;
4072 mon: TMonster;
4073 begin
4074 // Команды отладочного режима:
4075 if {gDebugMode}conIsCheatsEnabled then
4076 begin
4077 cmd := LowerCase(P[0]);
4078 if cmd = 'd_window' then
4079 begin
4080 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4081 g_Console_Add(Format('gScreenWidth = %d, gScreenHeight = %d', [gScreenWidth, gScreenHeight]));
4082 end
4083 else if cmd = 'd_sounds' then
4084 begin
4085 if (Length(P) > 1) and
4086 ((P[1] = '1') or (P[1] = '0')) then
4087 g_Debug_Sounds := (P[1][1] = '1');
4089 g_Console_Add(Format('d_sounds is %d', [Byte(g_Debug_Sounds)]));
4090 end
4091 else if cmd = 'd_frames' then
4092 begin
4093 if (Length(P) > 1) and
4094 ((P[1] = '1') or (P[1] = '0')) then
4095 g_Debug_Frames := (P[1][1] = '1');
4097 g_Console_Add(Format('d_frames is %d', [Byte(g_Debug_Frames)]));
4098 end
4099 else if cmd = 'd_winmsg' then
4100 begin
4101 if (Length(P) > 1) and
4102 ((P[1] = '1') or (P[1] = '0')) then
4103 g_Debug_WinMsgs := (P[1][1] = '1');
4105 g_Console_Add(Format('d_winmsg is %d', [Byte(g_Debug_WinMsgs)]));
4106 end
4107 else if (cmd = 'd_monoff') and not g_Game_IsNet then
4108 begin
4109 if (Length(P) > 1) and
4110 ((P[1] = '1') or (P[1] = '0')) then
4111 g_Debug_MonsterOff := (P[1][1] = '1');
4113 g_Console_Add(Format('d_monoff is %d', [Byte(g_debug_MonsterOff)]));
4114 end
4115 else if (cmd = 'd_botoff') and not g_Game_IsNet then
4116 begin
4117 if Length(P) > 1 then
4118 case P[1][1] of
4119 '0': g_debug_BotAIOff := 0;
4120 '1': g_debug_BotAIOff := 1;
4121 '2': g_debug_BotAIOff := 2;
4122 '3': g_debug_BotAIOff := 3;
4123 end;
4125 g_Console_Add(Format('d_botoff is %d', [g_debug_BotAIOff]));
4126 end
4127 else if cmd = 'd_monster' then
4128 begin
4129 if gGameOn and (gPlayer1 <> nil) and (gPlayer1.alive) and (not g_Game_IsNet) then
4130 if Length(P) < 2 then
4131 begin
4132 g_Console_Add(cmd + ' [ID | Name] [behaviour]');
4133 g_Console_Add('ID | Name');
4134 for b := MONSTER_DEMON to MONSTER_MAN do
4135 g_Console_Add(Format('%2d | %s', [b, g_Mons_NameByTypeId(b)]));
4136 conwriteln('behav. num'#10'normal 0'#10'killer 1'#10'maniac 2'#10'insane 3'#10'cannibal 4'#10'good 5');
4137 end else
4138 begin
4139 a := StrToIntDef(P[1], 0);
4140 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4141 a := g_Mons_TypeIdByName(P[1]);
4143 if (a < MONSTER_DEMON) or (a > MONSTER_MAN) then
4144 g_Console_Add(Format(_lc[I_MSG_NO_MONSTER], [P[1]]))
4145 else
4146 begin
4147 with gPlayer1.Obj do
4148 begin
4149 mon := g_Monsters_Create(a,
4150 X + Rect.X + (Rect.Width div 2),
4151 Y + Rect.Y + Rect.Height,
4152 gPlayer1.Direction, True);
4153 end;
4154 if (Length(P) > 2) and (mon <> nil) then
4155 begin
4156 if (CompareText(P[2], 'normal') = 0) then mon.MonsterBehaviour := BH_NORMAL
4157 else if (CompareText(P[2], 'killer') = 0) then mon.MonsterBehaviour := BH_KILLER
4158 else if (CompareText(P[2], 'maniac') = 0) then mon.MonsterBehaviour := BH_MANIAC
4159 else if (CompareText(P[2], 'insane') = 0) then mon.MonsterBehaviour := BH_INSANE
4160 else if (CompareText(P[2], 'cannibal') = 0) then mon.MonsterBehaviour := BH_CANNIBAL
4161 else if (CompareText(P[2], 'good') = 0) then mon.MonsterBehaviour := BH_GOOD
4162 else if (CompareText(P[2], 'friend') = 0) then mon.MonsterBehaviour := BH_GOOD
4163 else if (CompareText(P[2], 'friendly') = 0) then mon.MonsterBehaviour := BH_GOOD
4164 else mon.MonsterBehaviour := Min(Max(StrToIntDef(P[2], BH_NORMAL), BH_NORMAL), BH_GOOD);
4165 end;
4166 end;
4167 end;
4168 end
4169 else if (cmd = 'd_health') then
4170 begin
4171 if (Length(P) > 1) and
4172 ((P[1] = '1') or (P[1] = '0')) then
4173 g_debug_HealthBar := (P[1][1] = '1');
4175 g_Console_Add(Format('d_health is %d', [Byte(g_debug_HealthBar)]));
4176 end
4177 else if (cmd = 'd_player') then
4178 begin
4179 if (Length(P) > 1) and
4180 ((P[1] = '1') or (P[1] = '0')) then
4181 g_debug_Player := (P[1][1] = '1');
4183 g_Console_Add(Format(cmd + ' is %d', [Byte(g_Debug_Player)]));
4184 end
4185 else if (cmd = 'd_mem') then
4186 begin
4187 PrintHeapStats();
4188 end;
4189 end
4190 else
4191 g_Console_Add(_lc[I_MSG_NOT_DEBUG]);
4192 end;
4195 procedure GameCheats(P: SSArray);
4196 var
4197 cmd: string;
4198 f, a: Integer;
4199 plr: TPlayer;
4200 begin
4201 if (not gGameOn) or (not conIsCheatsEnabled) then
4202 begin
4203 g_Console_Add('not available');
4204 exit;
4205 end;
4206 plr := gPlayer1;
4207 if plr = nil then
4208 begin
4209 g_Console_Add('where is the player?!');
4210 exit;
4211 end;
4212 cmd := LowerCase(P[0]);
4213 // god
4214 if cmd = 'god' then
4215 begin
4216 plr.GodMode := not plr.GodMode;
4217 if plr.GodMode then g_Console_Add('player is godlike now') else g_Console_Add('player is mortal now');
4218 exit;
4219 end;
4220 // give <health|exit|weapons|air|suit|jetpack|berserk|all>
4221 if cmd = 'give' then
4222 begin
4223 if length(P) < 2 then begin g_Console_Add('give what?!'); exit; end;
4224 for f := 1 to High(P) do
4225 begin
4226 cmd := LowerCase(P[f]);
4227 if cmd = 'health' then begin plr.RestoreHealthArmor(); g_Console_Add('player feels himself better'); continue; end;
4228 if (cmd = 'all') {or (cmd = 'weapons')} then begin plr.AllRulez(False); g_Console_Add('player got the gifts'); continue; end;
4229 if cmd = 'exit' then
4230 begin
4231 if gTriggers <> nil then
4232 begin
4233 for a := 0 to High(gTriggers) do
4234 begin
4235 if gTriggers[a].TriggerType = TRIGGER_EXIT then
4236 begin
4237 g_Console_Add('player left the map');
4238 gExitByTrigger := True;
4239 //g_Game_ExitLevel(gTriggers[a].Data.MapName);
4240 g_Game_ExitLevel(gTriggers[a].tgcMap);
4241 break;
4242 end;
4243 end;
4244 end;
4245 continue;
4246 end;
4248 if cmd = 'air' then begin plr.GiveItem(ITEM_OXYGEN); g_Console_Add('player got some air'); continue; end;
4249 if cmd = 'jetpack' then begin plr.GiveItem(ITEM_JETPACK); g_Console_Add('player got a jetpack'); continue; end;
4250 if cmd = 'suit' then begin plr.GiveItem(ITEM_SUIT); g_Console_Add('player got an envirosuit'); continue; end;
4251 if cmd = 'berserk' then begin plr.GiveItem(ITEM_MEDKIT_BLACK); g_Console_Add('player got a berserk pack'); continue; end;
4252 if cmd = 'backpack' then begin plr.GiveItem(ITEM_AMMO_BACKPACK); g_Console_Add('player got a backpack'); continue; end;
4254 if cmd = 'helmet' then begin plr.GiveItem(ITEM_HELMET); g_Console_Add('player got a helmet'); continue; end;
4255 if cmd = 'bottle' then begin plr.GiveItem(ITEM_BOTTLE); g_Console_Add('player got a bottle of health'); continue; end;
4257 if cmd = 'stimpack' then begin plr.GiveItem(ITEM_MEDKIT_SMALL); g_Console_Add('player got a stimpack'); continue; end;
4258 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;
4260 if cmd = 'greenarmor' then begin plr.GiveItem(ITEM_ARMOR_GREEN); g_Console_Add('player got a security armor'); continue; end;
4261 if cmd = 'bluearmor' then begin plr.GiveItem(ITEM_ARMOR_BLUE); g_Console_Add('player got a combat armor'); continue; end;
4263 if (cmd = 'megasphere') or (cmd = 'mega') then begin plr.GiveItem(ITEM_SPHERE_BLUE); g_Console_Add('player got a megasphere'); continue; end;
4264 if (cmd = 'soulsphere') or (cmd = 'soul')then begin plr.GiveItem(ITEM_SPHERE_WHITE); g_Console_Add('player got a soul sphere'); continue; end;
4266 if (cmd = 'invul') or (cmd = 'invulnerability') then begin plr.GiveItem(ITEM_INVUL); g_Console_Add('player got invulnerability'); continue; end;
4267 if (cmd = 'invis') or (cmd = 'invisibility') then begin plr.GiveItem(ITEM_INVIS); g_Console_Add('player got invisibility'); continue; end;
4269 if cmd = 'redkey' then begin plr.GiveItem(ITEM_KEY_RED); g_Console_Add('player got the red key'); continue; end;
4270 if cmd = 'greenkey' then begin plr.GiveItem(ITEM_KEY_GREEN); g_Console_Add('player got the green key'); continue; end;
4271 if cmd = 'bluekey' then begin plr.GiveItem(ITEM_KEY_BLUE); g_Console_Add('player got the blue key'); continue; end;
4273 if (cmd = 'shotgun') or (cmd = 'sg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN1); g_Console_Add('player got a shotgun'); continue; end;
4274 if (cmd = 'supershotgun') or (cmd = 'ssg') then begin plr.GiveItem(ITEM_WEAPON_SHOTGUN2); g_Console_Add('player got a supershotgun'); continue; end;
4275 if cmd = 'chaingun' then begin plr.GiveItem(ITEM_WEAPON_CHAINGUN); g_Console_Add('player got a chaingun'); continue; end;
4276 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;
4277 if cmd = 'plasmagun' then begin plr.GiveItem(ITEM_WEAPON_PLASMA); g_Console_Add('player got a plasma gun'); continue; end;
4278 if cmd = 'bfg' then begin plr.GiveItem(ITEM_WEAPON_BFG); g_Console_Add('player got a BFG-9000'); continue; end;
4280 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;
4281 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;
4282 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;
4283 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;
4284 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;
4285 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;
4287 if cmd = 'superchaingun' then begin plr.GiveItem(ITEM_WEAPON_SUPERPULEMET); g_Console_Add('player got a superchaingun'); continue; end;
4288 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;
4290 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;
4291 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;
4293 if cmd = 'chainsaw' then begin plr.GiveItem(ITEM_WEAPON_SAW); g_Console_Add('player got a chainsaw'); continue; end;
4295 if cmd = 'ammo' then
4296 begin
4297 plr.GiveItem(ITEM_AMMO_SHELLS_BOX);
4298 plr.GiveItem(ITEM_AMMO_BULLETS_BOX);
4299 plr.GiveItem(ITEM_AMMO_CELL_BIG);
4300 plr.GiveItem(ITEM_AMMO_ROCKET_BOX);
4301 plr.GiveItem(ITEM_AMMO_FUELCAN);
4302 g_Console_Add('player got some ammo');
4303 continue;
4304 end;
4306 if cmd = 'clip' then begin plr.GiveItem(ITEM_AMMO_BULLETS); g_Console_Add('player got some bullets'); continue; end;
4307 if cmd = 'bullets' then begin plr.GiveItem(ITEM_AMMO_BULLETS_BOX); g_Console_Add('player got a box of bullets'); continue; end;
4309 if cmd = 'shells' then begin plr.GiveItem(ITEM_AMMO_SHELLS); g_Console_Add('player got some shells'); continue; end;
4310 if cmd = 'shellbox' then begin plr.GiveItem(ITEM_AMMO_SHELLS_BOX); g_Console_Add('player got a box of shells'); continue; end;
4312 if cmd = 'cells' then begin plr.GiveItem(ITEM_AMMO_CELL); g_Console_Add('player got some cells'); continue; end;
4313 if cmd = 'battery' then begin plr.GiveItem(ITEM_AMMO_CELL_BIG); g_Console_Add('player got cell battery'); continue; end;
4315 if cmd = 'rocket' then begin plr.GiveItem(ITEM_AMMO_ROCKET); g_Console_Add('player got a rocket'); continue; end;
4316 if cmd = 'rocketbox' then begin plr.GiveItem(ITEM_AMMO_ROCKET_BOX); g_Console_Add('player got some rockets'); continue; end;
4318 if (cmd = 'fuel') or (cmd = 'fuelcan') then begin plr.GiveItem(ITEM_AMMO_FUELCAN); g_Console_Add('player got fuel canister'); continue; end;
4320 if cmd = 'weapons' then
4321 begin
4322 plr.GiveItem(ITEM_WEAPON_SHOTGUN1);
4323 plr.GiveItem(ITEM_WEAPON_SHOTGUN2);
4324 plr.GiveItem(ITEM_WEAPON_CHAINGUN);
4325 plr.GiveItem(ITEM_WEAPON_ROCKETLAUNCHER);
4326 plr.GiveItem(ITEM_WEAPON_PLASMA);
4327 plr.GiveItem(ITEM_WEAPON_BFG);
4328 g_Console_Add('player got weapons');
4329 continue;
4330 end;
4332 if cmd = 'keys' then
4333 begin
4334 plr.GiveItem(ITEM_KEY_RED);
4335 plr.GiveItem(ITEM_KEY_GREEN);
4336 plr.GiveItem(ITEM_KEY_BLUE);
4337 g_Console_Add('player got all keys');
4338 continue;
4339 end;
4341 g_Console_Add('i don''t know how to give '''+cmd+'''!');
4342 end;
4343 exit;
4344 end;
4345 // open
4346 if cmd = 'open' then
4347 begin
4348 g_Console_Add('player activated sesame');
4349 g_Triggers_OpenAll();
4350 exit;
4351 end;
4352 // fly
4353 if cmd = 'fly' then
4354 begin
4355 gFly := not gFly;
4356 if gFly then g_Console_Add('player feels himself lighter') else g_Console_Add('player lost his wings');
4357 exit;
4358 end;
4359 // noclip
4360 if cmd = 'noclip' then
4361 begin
4362 plr.SwitchNoClip;
4363 g_Console_Add('wall hardeness adjusted');
4364 exit;
4365 end;
4366 // notarget
4367 if cmd = 'notarget' then
4368 begin
4369 plr.NoTarget := not plr.NoTarget;
4370 if plr.NoTarget then g_Console_Add('player hides in shadows') else g_Console_Add('player is brave again');
4371 exit;
4372 end;
4373 // noreload
4374 if cmd = 'noreload' then
4375 begin
4376 plr.NoReload := not plr.NoReload;
4377 if plr.NoReload then g_Console_Add('player is action hero now') else g_Console_Add('player is ordinary man now');
4378 exit;
4379 end;
4380 // speedy
4381 if cmd = 'speedy' then
4382 begin
4383 MAX_RUNVEL := 32-MAX_RUNVEL;
4384 g_Console_Add('speed adjusted');
4385 exit;
4386 end;
4387 // jumpy
4388 if cmd = 'jumpy' then
4389 begin
4390 VEL_JUMP := 30-VEL_JUMP;
4391 g_Console_Add('jump height adjusted');
4392 exit;
4393 end;
4394 // automap
4395 if cmd = 'automap' then
4396 begin
4397 gShowMap := not gShowMap;
4398 if gShowMap then g_Console_Add('player gains second sight') else g_Console_Add('player lost second sight');
4399 exit;
4400 end;
4401 // aimline
4402 if cmd = 'aimline' then
4403 begin
4404 gAimLine := not gAimLine;
4405 if gAimLine then g_Console_Add('player gains laser sight') else g_Console_Add('player lost laser sight');
4406 exit;
4407 end;
4408 end;
4410 procedure GameCommands(P: SSArray);
4411 var
4412 a, b: Integer;
4413 s, pw: String;
4414 chstr: string;
4415 cmd: string;
4416 pl: pTNetClient = nil;
4417 plr: TPlayer;
4418 prt: Word;
4419 nm: Boolean;
4420 listen: LongWord;
4421 found: Boolean;
4422 begin
4423 // Общие команды:
4424 cmd := LowerCase(P[0]);
4425 chstr := '';
4426 if cmd = 'pause' then
4427 begin
4428 if (g_ActiveWindow = nil) then
4429 g_Game_Pause(not gPauseMain);
4430 end
4431 else if cmd = 'endgame' then
4432 gExit := EXIT_SIMPLE
4433 else if cmd = 'restart' then
4434 begin
4435 if gGameOn or (gState in [STATE_INTERSINGLE, STATE_INTERCUSTOM]) then
4436 begin
4437 if g_Game_IsClient then
4438 begin
4439 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4440 Exit;
4441 end;
4442 g_Game_Restart();
4443 end else
4444 g_Console_Add(_lc[I_MSG_NOT_GAME]);
4445 end
4446 else if cmd = 'kick' then
4447 begin
4448 if g_Game_IsServer then
4449 begin
4450 if Length(P) < 2 then
4451 begin
4452 g_Console_Add('kick <name>');
4453 Exit;
4454 end;
4455 if P[1] = '' then
4456 begin
4457 g_Console_Add('kick <name>');
4458 Exit;
4459 end;
4461 if g_Game_IsNet then
4462 pl := g_Net_Client_ByName(P[1]);
4463 if (pl <> nil) then
4464 begin
4465 s := g_Net_ClientName_ByID(pl^.ID);
4466 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4467 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4468 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4469 g_Net_Slist_ServerPlayerLeaves();
4470 end else if gPlayers <> nil then
4471 for a := Low(gPlayers) to High(gPlayers) do
4472 if gPlayers[a] <> nil then
4473 if Copy(LowerCase(gPlayers[a].Name), 1, Length(P[1])) = LowerCase(P[1]) then
4474 begin
4475 // Не отключать основных игроков в сингле
4476 if not(gPlayers[a] is TBot) and (gGameSettings.GameType = GT_SINGLE) then
4477 continue;
4478 gPlayers[a].Lives := 0;
4479 gPlayers[a].Kill(K_SIMPLEKILL, 0, HIT_DISCON);
4480 g_Console_Add(Format(_lc[I_PLAYER_LEAVE], [gPlayers[a].Name]), True);
4481 g_Player_Remove(gPlayers[a].UID);
4482 g_Net_Slist_ServerPlayerLeaves();
4483 // Если не перемешать, при добавлении новых ботов появятся старые
4484 g_Bot_MixNames();
4485 end;
4486 end else
4487 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4488 end
4489 else if cmd = 'kick_id' then
4490 begin
4491 if g_Game_IsServer and g_Game_IsNet then
4492 begin
4493 if Length(P) < 2 then
4494 begin
4495 g_Console_Add('kick_id <client ID>');
4496 Exit;
4497 end;
4498 if P[1] = '' then
4499 begin
4500 g_Console_Add('kick_id <client ID>');
4501 Exit;
4502 end;
4504 a := StrToIntDef(P[1], 0);
4505 if (NetClients <> nil) and (a <= High(NetClients)) then
4506 begin
4507 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4508 begin
4509 s := g_Net_ClientName_ByID(NetClients[a].ID);
4510 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_KICK);
4511 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4512 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4513 g_Net_Slist_ServerPlayerLeaves();
4514 end;
4515 end;
4516 end else
4517 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4518 end
4519 else if cmd = 'kick_pid' then
4520 begin
4521 if g_Game_IsServer and g_Game_IsNet then
4522 begin
4523 if Length(P) < 2 then
4524 begin
4525 g_Console_Add('kick_pid <player ID>');
4526 Exit;
4527 end;
4528 if P[1] = '' then
4529 begin
4530 g_Console_Add('kick_pid <player ID>');
4531 Exit;
4532 end;
4534 a := StrToIntDef(P[1], 0);
4535 pl := g_Net_Client_ByPlayer(a);
4536 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4537 begin
4538 s := g_Net_ClientName_ByID(pl^.ID);
4539 enet_peer_disconnect(pl^.Peer, NET_DISC_KICK);
4540 g_Console_Add(Format(_lc[I_PLAYER_KICK], [s]));
4541 MH_SEND_GameEvent(NET_EV_PLAYER_KICK, 0, s);
4542 g_Net_Slist_ServerPlayerLeaves();
4543 end;
4544 end else
4545 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4546 end
4547 else if cmd = 'ban' then
4548 begin
4549 if g_Game_IsServer and g_Game_IsNet then
4550 begin
4551 if Length(P) < 2 then
4552 begin
4553 g_Console_Add('ban <name>');
4554 Exit;
4555 end;
4556 if P[1] = '' then
4557 begin
4558 g_Console_Add('ban <name>');
4559 Exit;
4560 end;
4562 pl := g_Net_Client_ByName(P[1]);
4563 if (pl <> nil) then
4564 begin
4565 s := g_Net_ClientName_ByID(pl^.ID);
4566 g_Net_BanHost(pl^.Peer^.address.host, False);
4567 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4568 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4569 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4570 g_Net_Slist_ServerPlayerLeaves();
4571 end else
4572 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4573 end else
4574 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4575 end
4576 else if cmd = 'ban_id' then
4577 begin
4578 if g_Game_IsServer and g_Game_IsNet then
4579 begin
4580 if Length(P) < 2 then
4581 begin
4582 g_Console_Add('ban_id <client ID>');
4583 Exit;
4584 end;
4585 if P[1] = '' then
4586 begin
4587 g_Console_Add('ban_id <client ID>');
4588 Exit;
4589 end;
4591 a := StrToIntDef(P[1], 0);
4592 if (NetClients <> nil) and (a <= High(NetClients)) then
4593 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4594 begin
4595 s := g_Net_ClientName_ByID(NetClients[a].ID);
4596 g_Net_BanHost(NetClients[a].Peer^.address.host, False);
4597 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_TEMPBAN);
4598 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4599 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4600 g_Net_Slist_ServerPlayerLeaves();
4601 end;
4602 end else
4603 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4604 end
4605 else if cmd = 'ban_pid' then
4606 begin
4607 if g_Game_IsServer and g_Game_IsNet then
4608 begin
4609 if Length(P) < 2 then
4610 begin
4611 g_Console_Add('ban_pid <player ID>');
4612 Exit;
4613 end;
4614 if P[1] = '' then
4615 begin
4616 g_Console_Add('ban_pid <player ID>');
4617 Exit;
4618 end;
4620 a := StrToIntDef(P[1], 0);
4621 pl := g_Net_Client_ByPlayer(a);
4622 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4623 begin
4624 s := g_Net_ClientName_ByID(pl^.ID);
4625 g_Net_BanHost(pl^.Peer^.address.host, False);
4626 enet_peer_disconnect(pl^.Peer, NET_DISC_TEMPBAN);
4627 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4628 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4629 g_Net_Slist_ServerPlayerLeaves();
4630 end;
4631 end else
4632 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4633 end
4634 else if cmd = 'permban' then
4635 begin
4636 if g_Game_IsServer and g_Game_IsNet then
4637 begin
4638 if Length(P) < 2 then
4639 begin
4640 g_Console_Add('permban <name>');
4641 Exit;
4642 end;
4643 if P[1] = '' then
4644 begin
4645 g_Console_Add('permban <name>');
4646 Exit;
4647 end;
4649 pl := g_Net_Client_ByName(P[1]);
4650 if (pl <> nil) then
4651 begin
4652 s := g_Net_ClientName_ByID(pl^.ID);
4653 g_Net_BanHost(pl^.Peer^.address.host);
4654 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4655 g_Net_SaveBanList();
4656 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4657 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4658 g_Net_Slist_ServerPlayerLeaves();
4659 end else
4660 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
4661 end else
4662 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4663 end
4664 else if cmd = 'permban_id' then
4665 begin
4666 if g_Game_IsServer and g_Game_IsNet then
4667 begin
4668 if Length(P) < 2 then
4669 begin
4670 g_Console_Add('permban_id <client ID>');
4671 Exit;
4672 end;
4673 if P[1] = '' then
4674 begin
4675 g_Console_Add('permban_id <client ID>');
4676 Exit;
4677 end;
4679 a := StrToIntDef(P[1], 0);
4680 if (NetClients <> nil) and (a <= High(NetClients)) then
4681 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4682 begin
4683 s := g_Net_ClientName_ByID(NetClients[a].ID);
4684 g_Net_BanHost(NetClients[a].Peer^.address.host);
4685 enet_peer_disconnect(NetClients[a].Peer, NET_DISC_BAN);
4686 g_Net_SaveBanList();
4687 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4688 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4689 g_Net_Slist_ServerPlayerLeaves();
4690 end;
4691 end else
4692 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4693 end
4694 else if cmd = 'permban_pid' then
4695 begin
4696 if g_Game_IsServer and g_Game_IsNet then
4697 begin
4698 if Length(P) < 2 then
4699 begin
4700 g_Console_Add('permban_pid <player ID>');
4701 Exit;
4702 end;
4703 if P[1] = '' then
4704 begin
4705 g_Console_Add('permban_pid <player ID>');
4706 Exit;
4707 end;
4709 a := StrToIntDef(P[1], 0);
4710 pl := g_Net_Client_ByPlayer(a);
4711 if (pl <> nil) and pl^.Used and (pl^.Peer <> nil) then
4712 begin
4713 s := g_Net_ClientName_ByID(pl^.ID);
4714 g_Net_BanHost(pl^.Peer^.address.host);
4715 enet_peer_disconnect(pl^.Peer, NET_DISC_BAN);
4716 g_Net_SaveBanList();
4717 g_Console_Add(Format(_lc[I_PLAYER_BAN], [s]));
4718 MH_SEND_GameEvent(NET_EV_PLAYER_BAN, 0, s);
4719 g_Net_Slist_ServerPlayerLeaves();
4720 end;
4721 end else
4722 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4723 end
4724 else if cmd = 'permban_ip' then
4725 begin
4726 if g_Game_IsServer and g_Game_IsNet then
4727 begin
4728 if Length(P) < 2 then
4729 begin
4730 g_Console_Add('permban_ip <IP address>');
4731 Exit;
4732 end;
4733 if P[1] = '' then
4734 begin
4735 g_Console_Add('permban_ip <IP address>');
4736 Exit;
4737 end;
4739 g_Net_BanHost(P[1]);
4740 g_Net_SaveBanList();
4741 g_Console_Add(Format(_lc[I_PLAYER_BAN], [P[1]]));
4742 end else
4743 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4744 end
4745 else if cmd = 'unban' then
4746 begin
4747 if g_Game_IsServer and g_Game_IsNet then
4748 begin
4749 if Length(P) < 2 then
4750 begin
4751 g_Console_Add('unban <IP Address>');
4752 Exit;
4753 end;
4754 if P[1] = '' then
4755 begin
4756 g_Console_Add('unban <IP Address>');
4757 Exit;
4758 end;
4760 if g_Net_UnbanHost(P[1]) then
4761 begin
4762 g_Console_Add(Format(_lc[I_MSG_UNBAN_OK], [P[1]]));
4763 g_Net_SaveBanList();
4764 end else
4765 g_Console_Add(Format(_lc[I_MSG_UNBAN_FAIL], [P[1]]));
4766 end else
4767 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4768 end
4769 else if cmd = 'clientlist' then
4770 begin
4771 if g_Game_IsServer and g_Game_IsNet then
4772 begin
4773 b := 0;
4774 if NetClients <> nil then
4775 for a := Low(NetClients) to High(NetClients) do
4776 if NetClients[a].Used and (NetClients[a].Peer <> nil) then
4777 begin
4778 plr := g_Player_Get(NetClients[a].Player);
4779 if plr = nil then continue;
4780 Inc(b);
4781 g_Console_Add(Format('#%2d: %-15s | %s', [a,
4782 IpToStr(NetClients[a].Peer^.address.host), plr.Name]));
4783 end;
4784 if b = 0 then
4785 g_Console_Add(_lc[I_MSG_NOCLIENTS]);
4786 end else
4787 g_Console_Add(_lc[I_MSG_SERVERONLY]);
4788 end
4789 else if cmd = 'connect' then
4790 begin
4791 if (NetMode = NET_NONE) then
4792 begin
4793 if Length(P) < 2 then
4794 begin
4795 g_Console_Add('connect <IP> [port] [password]');
4796 Exit;
4797 end;
4798 if P[1] = '' then
4799 begin
4800 g_Console_Add('connect <IP> [port] [password]');
4801 Exit;
4802 end;
4804 if Length(P) > 2 then
4805 prt := StrToIntDef(P[2], 25666)
4806 else
4807 prt := 25666;
4809 if Length(P) > 3 then
4810 pw := P[3]
4811 else
4812 pw := '';
4814 g_Game_StartClient(P[1], prt, pw);
4815 end;
4816 end
4817 else if cmd = 'disconnect' then
4818 begin
4819 if (NetMode = NET_CLIENT) then
4820 g_Net_Disconnect();
4821 end
4822 else if cmd = 'reconnect' then
4823 begin
4824 if (NetMode = NET_SERVER) then
4825 Exit;
4827 if (NetMode = NET_CLIENT) then
4828 begin
4829 g_Net_Disconnect();
4830 gExit := EXIT_SIMPLE;
4831 EndGame;
4832 end;
4834 //TODO: Use last successful password to reconnect, instead of ''
4835 g_Game_StartClient(NetClientIP, NetClientPort, '');
4836 end
4837 else if (cmd = 'addbot') or
4838 (cmd = 'bot_add') then
4839 begin
4840 if Length(P) > 2 then
4841 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2), StrToIntDef(P[2], 100))
4842 else if Length(P) > 1 then
4843 g_Bot_Add(TEAM_NONE, StrToIntDef(P[1], 2))
4844 else
4845 g_Bot_Add(TEAM_NONE, 2);
4846 end
4847 else if cmd = 'bot_addlist' then
4848 begin
4849 if Length(P) > 1 then
4850 begin
4851 if Length(P) = 2 then
4852 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1))
4853 else if Length(P) = 3 then
4854 g_Bot_AddList(TEAM_NONE, P[1], StrToIntDef(P[1], -1), StrToIntDef(P[2], 100))
4855 else
4856 g_Bot_AddList(IfThen(P[2] = 'red', TEAM_RED, TEAM_BLUE), P[1], StrToIntDef(P[1], -1));
4857 end;
4858 end
4859 else if cmd = 'bot_removeall' then
4860 g_Bot_RemoveAll()
4861 else if cmd = 'chat' then
4862 begin
4863 if g_Game_IsNet then
4864 begin
4865 if Length(P) > 1 then
4866 begin
4867 for a := 1 to High(P) do
4868 chstr := chstr + P[a] + ' ';
4870 if Length(chstr) > 200 then SetLength(chstr, 200);
4872 if Length(chstr) < 1 then
4873 begin
4874 g_Console_Add('chat <text>');
4875 Exit;
4876 end;
4878 chstr := b_Text_Format(chstr);
4879 if g_Game_IsClient then
4880 MC_SEND_Chat(chstr, NET_CHAT_PLAYER)
4881 else
4882 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_PLAYER);
4883 end
4884 else
4885 g_Console_Add('chat <text>');
4886 end else
4887 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4888 end
4889 else if cmd = 'teamchat' then
4890 begin
4891 if g_Game_IsNet and (gGameSettings.GameMode in [GM_TDM, GM_CTF]) then
4892 begin
4893 if Length(P) > 1 then
4894 begin
4895 for a := 1 to High(P) do
4896 chstr := chstr + P[a] + ' ';
4898 if Length(chstr) > 200 then SetLength(chstr, 200);
4900 if Length(chstr) < 1 then
4901 begin
4902 g_Console_Add('teamchat <text>');
4903 Exit;
4904 end;
4906 chstr := b_Text_Format(chstr);
4907 if g_Game_IsClient then
4908 MC_SEND_Chat(chstr, NET_CHAT_TEAM)
4909 else
4910 MH_SEND_Chat(gPlayer1Settings.Name + ': ' + chstr, NET_CHAT_TEAM,
4911 gPlayer1Settings.Team);
4912 end
4913 else
4914 g_Console_Add('teamchat <text>');
4915 end else
4916 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4917 end
4918 else if cmd = 'game' then
4919 begin
4920 if gGameSettings.GameType <> GT_NONE then
4921 begin
4922 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4923 Exit;
4924 end;
4925 if Length(P) = 1 then
4926 begin
4927 g_Console_Add(cmd + ' <WAD> [MAP] [# players]');
4928 Exit;
4929 end;
4930 // game not started yet, load fist map from some wad
4931 found := false;
4932 s := addWadExtension(P[1]);
4933 found := e_FindResource(AllMapDirs, s);
4934 P[1] := s;
4935 if found then
4936 begin
4937 P[1] := ExpandFileName(P[1]);
4938 // if map not choosed then set first map
4939 if Length(P) < 3 then
4940 begin
4941 SetLength(P, 3);
4942 P[2] := g_Game_GetFirstMap(P[1]);
4943 end;
4945 s := P[1] + ':\' + UpperCase(P[2]);
4947 if g_Map_Exist(s) then
4948 begin
4949 // start game
4950 g_Game_Free();
4951 with gGameSettings do
4952 begin
4953 Options := gsGameFlags;
4954 GameMode := g_Game_TextToMode(gsGameMode);
4955 if gSwitchGameMode <> GM_NONE then
4956 GameMode := gSwitchGameMode;
4957 if GameMode = GM_NONE then GameMode := GM_DM;
4958 if GameMode = GM_SINGLE then GameMode := GM_COOP;
4959 b := 1;
4960 if Length(P) >= 4 then
4961 b := StrToIntDef(P[3], 1);
4962 g_Game_StartCustom(s, GameMode, TimeLimit,
4963 GoalLimit, MaxLives, Options, b);
4964 end;
4965 end
4966 else
4967 if P[2] = '' then
4968 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
4969 else
4970 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[2]), P[1]]));
4971 end else
4972 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]));
4973 end
4974 else if cmd = 'host' then
4975 begin
4976 if gGameSettings.GameType <> GT_NONE then
4977 begin
4978 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
4979 Exit;
4980 end;
4981 if Length(P) < 4 then
4982 begin
4983 g_Console_Add(cmd + ' <listen IP> <port> <WAD> [MAP] [# players]');
4984 Exit;
4985 end;
4986 if not StrToIp(P[1], listen) then
4987 Exit;
4988 prt := StrToIntDef(P[2], 25666);
4990 s := addWadExtension(P[3]);
4991 found := e_FindResource(AllMapDirs, s);
4992 P[3] := s;
4993 if found then
4994 begin
4995 // get first map in wad, if not specified
4996 if Length(P) < 5 then
4997 begin
4998 SetLength(P, 5);
4999 P[4] := g_Game_GetFirstMap(P[1]);
5000 end;
5001 s := P[3] + ':\' + UpperCase(P[4]);
5002 if g_Map_Exist(s) then
5003 begin
5004 // start game
5005 g_Game_Free();
5006 with gGameSettings do
5007 begin
5008 Options := gsGameFlags;
5009 GameMode := g_Game_TextToMode(gsGameMode);
5010 if gSwitchGameMode <> GM_NONE then GameMode := gSwitchGameMode;
5011 if GameMode = GM_NONE then GameMode := GM_DM;
5012 if GameMode = GM_SINGLE then GameMode := GM_COOP;
5013 b := 0;
5014 if Length(P) >= 6 then
5015 b := StrToIntDef(P[5], 0);
5016 g_Game_StartServer(s, GameMode, TimeLimit, GoalLimit, MaxLives, Options, b, listen, prt)
5017 end
5018 end
5019 else
5020 begin
5021 if P[4] = '' then
5022 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[3]]))
5023 else
5024 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [UpperCase(P[4]), P[3]]))
5025 end
5026 end
5027 else
5028 begin
5029 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[3]]))
5030 end
5031 end
5032 else if cmd = 'map' then
5033 begin
5034 if Length(P) = 1 then
5035 begin
5036 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5037 begin
5038 g_Console_Add(cmd + ' <MAP>');
5039 g_Console_Add(cmd + ' <WAD> [MAP]')
5040 end
5041 else
5042 begin
5043 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5044 end
5045 end
5046 else
5047 begin
5048 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5049 begin
5050 if Length(P) < 3 then
5051 begin
5052 // first param is map or wad
5053 s := UpperCase(P[1]);
5054 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5055 begin
5056 gExitByTrigger := False;
5057 if gGameOn then
5058 begin
5059 // already in game, finish current map
5060 gNextMap := s;
5061 gExit := EXIT_ENDLEVELCUSTOM;
5062 end
5063 else
5064 begin
5065 // intermission, so change map immediately
5066 g_Game_ChangeMap(s)
5067 end
5068 end
5069 else
5070 begin
5071 s := P[1];
5072 found := e_FindResource(AllMapDirs, s);
5073 P[1] := s;
5074 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, 'WAD ' + P[1]]));
5075 if found then
5076 begin
5077 // no such map, found wad
5078 pw := P[1];
5079 SetLength(P, 3);
5080 P[1] := ExpandFileName(pw);
5081 P[2] := g_Game_GetFirstMap(P[1]);
5082 s := P[1] + ':\' + P[2];
5083 if g_Map_Exist(s) then
5084 begin
5085 gExitByTrigger := False;
5086 if gGameOn then
5087 begin
5088 // already in game, finish current map
5089 gNextMap := s;
5090 gExit := EXIT_ENDLEVELCUSTOM
5091 end
5092 else
5093 begin
5094 // intermission, so change map immediately
5095 g_Game_ChangeMap(s)
5096 end
5097 end
5098 else
5099 begin
5100 if P[2] = '' then
5101 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5102 else
5103 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5104 end
5105 end
5106 else
5107 begin
5108 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5109 end
5110 end;
5111 end
5112 else
5113 begin
5114 s := addWadExtension(P[1]);
5115 found := e_FindResource(AllMapDirs, s);
5116 P[1] := s;
5117 if found then
5118 begin
5119 P[2] := UpperCase(P[2]);
5120 s := P[1] + ':\' + P[2];
5121 if g_Map_Exist(s) then
5122 begin
5123 gExitByTrigger := False;
5124 if gGameOn then
5125 begin
5126 gNextMap := s;
5127 gExit := EXIT_ENDLEVELCUSTOM
5128 end
5129 else
5130 begin
5131 g_Game_ChangeMap(s)
5132 end
5133 end
5134 else
5135 begin
5136 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5137 end
5138 end
5139 else
5140 begin
5141 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5142 end
5143 end
5144 end
5145 else
5146 begin
5147 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5148 end
5149 end
5150 end
5151 else if cmd = 'nextmap' then
5152 begin
5153 if not(gGameOn or (gState = STATE_INTERCUSTOM)) then
5154 begin
5155 g_Console_Add(_lc[I_MSG_NOT_GAME])
5156 end
5157 else
5158 begin
5159 nm := True;
5160 if Length(P) = 1 then
5161 begin
5162 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5163 begin
5164 g_Console_Add(cmd + ' <MAP>');
5165 g_Console_Add(cmd + ' <WAD> [MAP]');
5166 end
5167 else
5168 begin
5169 nm := False;
5170 g_Console_Add(_lc[I_MSG_GM_UNAVAIL]);
5171 end;
5172 end
5173 else
5174 begin
5175 nm := False;
5176 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5177 begin
5178 if Length(P) < 3 then
5179 begin
5180 // first param is map or wad
5181 s := UpperCase(P[1]);
5182 if g_Map_Exist(gGameSettings.WAD + ':\' + s) then
5183 begin
5184 // map founded
5185 gExitByTrigger := False;
5186 gNextMap := s;
5187 nm := True;
5188 end
5189 else
5190 begin
5191 // no such map, found wad
5192 pw := addWadExtension(P[1]);
5193 found := e_FindResource(MapDirs, pw);
5194 if not found then
5195 found := e_FindResource(WadDirs, pw);
5196 P[1] := pw;
5197 g_Console_Add(Format(_lc[I_MSG_NO_MAP_FALLBACK], [s, P[1]]));
5198 if found then
5199 begin
5200 // map not specified, select first map
5201 SetLength(P, 3);
5202 P[2] := g_Game_GetFirstMap(P[1]);
5203 s := P[1] + ':\' + P[2];
5204 if g_Map_Exist(s) then
5205 begin
5206 gExitByTrigger := False;
5207 gNextMap := s;
5208 nm := True
5209 end
5210 else
5211 begin
5212 if P[2] = '' then
5213 g_Console_Add(Format(_lc[I_MSG_NO_MAPS], [P[1]]))
5214 else
5215 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5216 end
5217 end
5218 else
5219 begin
5220 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5221 end
5222 end
5223 end
5224 else
5225 begin
5226 // specified two params wad + map
5227 pw := addWadExtension(P[1]);
5228 found := e_FindResource(MapDirs, pw);
5229 if not found then
5230 found := e_FindResource(MapDirs, pw);
5231 P[1] := pw;
5232 if found then
5233 begin
5234 P[2] := UpperCase(P[2]);
5235 s := P[1] + ':\' + P[2];
5236 if g_Map_Exist(s) then
5237 begin
5238 gExitByTrigger := False;
5239 gNextMap := s;
5240 nm := True
5241 end
5242 else
5243 begin
5244 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [P[2]]))
5245 end
5246 end
5247 else
5248 begin
5249 g_Console_Add(Format(_lc[I_MSG_NO_WAD], [P[1]]))
5250 end
5251 end
5252 end
5253 else
5254 begin
5255 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5256 end
5257 end;
5258 if nm then
5259 begin
5260 if gNextMap = '' then
5261 g_Console_Add(_lc[I_MSG_NEXTMAP_UNSET])
5262 else
5263 g_Console_Add(Format(_lc[I_MSG_NEXTMAP_SET], [gNextMap]))
5264 end
5265 end
5266 end
5267 else if (cmd = 'endmap') or (cmd = 'goodbye') then
5268 begin
5269 if not gGameOn then
5270 begin
5271 g_Console_Add(_lc[I_MSG_NOT_GAME])
5272 end
5273 else
5274 begin
5275 if g_Game_IsServer and (gGameSettings.GameType <> GT_SINGLE) then
5276 begin
5277 gExitByTrigger := False;
5278 // next map not specified, try to find trigger EXIT
5279 if (gNextMap = '') and (gTriggers <> nil) then
5280 begin
5281 for a := 0 to High(gTriggers) do
5282 begin
5283 if gTriggers[a].TriggerType = TRIGGER_EXIT then
5284 begin
5285 gExitByTrigger := True;
5286 //gNextMap := gTriggers[a].Data.MapName;
5287 gNextMap := gTriggers[a].tgcMap;
5288 Break
5289 end
5290 end
5291 end;
5292 if gNextMap = '' then
5293 gNextMap := g_Game_GetNextMap();
5294 if not isWadPath(gNextMap) then
5295 s := gGameSettings.WAD + ':\' + gNextMap
5296 else
5297 s := gNextMap;
5298 if g_Map_Exist(s) then
5299 gExit := EXIT_ENDLEVELCUSTOM
5300 else
5301 g_Console_Add(Format(_lc[I_MSG_NO_MAP], [gNextMap]))
5302 end
5303 else
5304 begin
5305 g_Console_Add(_lc[I_MSG_GM_UNAVAIL])
5306 end
5307 end
5308 end
5309 else if (cmd = 'event') then
5310 begin
5311 if (Length(P) <= 1) then
5312 begin
5313 for a := 0 to High(gEvents) do
5314 if gEvents[a].Command = '' then
5315 g_Console_Add(gEvents[a].Name + ' <none>')
5316 else
5317 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5318 Exit;
5319 end;
5320 if (Length(P) = 2) then
5321 begin
5322 for a := 0 to High(gEvents) do
5323 if gEvents[a].Name = P[1] then
5324 if gEvents[a].Command = '' then
5325 g_Console_Add(gEvents[a].Name + ' <none>')
5326 else
5327 g_Console_Add(gEvents[a].Name + ' "' + gEvents[a].Command + '"');
5328 Exit;
5329 end;
5330 for a := 0 to High(gEvents) do
5331 if gEvents[a].Name = P[1] then
5332 begin
5333 gEvents[a].Command := '';
5334 for b := 2 to High(P) do
5335 if Pos(' ', P[b]) = 0 then
5336 gEvents[a].Command := gEvents[a].Command + ' ' + P[b]
5337 else
5338 gEvents[a].Command := gEvents[a].Command + ' "' + P[b] + '"';
5339 gEvents[a].Command := Trim(gEvents[a].Command);
5340 Exit;
5341 end;
5342 end
5343 else if cmd = 'suicide' then
5344 begin
5345 if gGameOn then
5346 begin
5347 if g_Game_IsClient then
5348 MC_SEND_CheatRequest(NET_CHEAT_SUICIDE)
5349 else
5350 begin
5351 if gPlayer1 <> nil then
5352 gPlayer1.Damage(SUICIDE_DAMAGE, gPlayer1.UID, 0, 0, HIT_SELF);
5353 if gPlayer2 <> nil then
5354 gPlayer2.Damage(SUICIDE_DAMAGE, gPlayer2.UID, 0, 0, HIT_SELF);
5355 end;
5356 end;
5357 end
5358 else if cmd = 'screenshot' then
5359 begin
5360 g_TakeScreenShot()
5361 end
5362 else if cmd = 'weapon' then
5363 begin
5364 if Length(p) = 2 then
5365 begin
5366 a := WP_FIRST + StrToInt(p[1]) - 1;
5367 if (a >= WP_FIRST) and (a <= WP_LAST) then
5368 gSelectWeapon[0, a] := True
5369 end
5370 end
5371 else if (cmd = 'p1_weapon') or (cmd = 'p2_weapon') then
5372 begin
5373 if Length(p) = 2 then
5374 begin
5375 a := WP_FIRST + StrToInt(p[1]) - 1;
5376 b := ord(cmd[2]) - ord('1');
5377 if (a >= WP_FIRST) and (a <= WP_LAST) then
5378 gSelectWeapon[b, a] := True
5379 end
5380 end
5381 // Команды Своей игры:
5382 else if gGameSettings.GameType in [GT_CUSTOM, GT_SERVER, GT_CLIENT] then
5383 begin
5384 if cmd = 'bot_addred' then
5385 begin
5386 if Length(P) > 1 then
5387 g_Bot_Add(TEAM_RED, StrToIntDef(P[1], 2))
5388 else
5389 g_Bot_Add(TEAM_RED, 2);
5390 end
5391 else if cmd = 'bot_addblue' then
5392 begin
5393 if Length(P) > 1 then
5394 g_Bot_Add(TEAM_BLUE, StrToIntDef(P[1], 2))
5395 else
5396 g_Bot_Add(TEAM_BLUE, 2);
5397 end
5398 else if cmd = 'spectate' then
5399 begin
5400 if not gGameOn then
5401 Exit;
5402 g_Game_Spectate();
5403 end
5404 else if cmd = 'say' then
5405 begin
5406 if g_Game_IsServer and g_Game_IsNet then
5407 begin
5408 if Length(P) > 1 then
5409 begin
5410 chstr := '';
5411 for a := 1 to High(P) do
5412 chstr := chstr + P[a] + ' ';
5414 if Length(chstr) > 200 then SetLength(chstr, 200);
5416 if Length(chstr) < 1 then
5417 begin
5418 g_Console_Add('say <text>');
5419 Exit;
5420 end;
5422 chstr := b_Text_Format(chstr);
5423 MH_SEND_Chat(chstr, NET_CHAT_PLAYER);
5424 end
5425 else g_Console_Add('say <text>');
5426 end else
5427 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5428 end
5429 else if cmd = 'tell' then
5430 begin
5431 if g_Game_IsServer and g_Game_IsNet then
5432 begin
5433 if (Length(P) > 2) and (P[1] <> '') then
5434 begin
5435 chstr := '';
5436 for a := 2 to High(P) do
5437 chstr := chstr + P[a] + ' ';
5439 if Length(chstr) > 200 then SetLength(chstr, 200);
5441 if Length(chstr) < 1 then
5442 begin
5443 g_Console_Add('tell <playername> <text>');
5444 Exit;
5445 end;
5447 pl := g_Net_Client_ByName(P[1]);
5448 if pl <> nil then
5449 MH_SEND_Chat(b_Text_Format(chstr), NET_CHAT_PLAYER, pl^.ID)
5450 else
5451 g_Console_Add(Format(_lc[I_NET_ERR_NAME404], [P[1]]));
5452 end
5453 else g_Console_Add('tell <playername> <text>');
5454 end else
5455 g_Console_Add(_lc[I_MSG_SERVERONLY]);
5456 end
5457 else if cmd = 'centerprint' then
5458 begin
5459 if (Length(P) > 2) and (P[1] <> '') then
5460 begin
5461 chstr := '';
5462 for a := 2 to High(P) do
5463 chstr := chstr + P[a] + ' ';
5465 if Length(chstr) > 200 then SetLength(chstr, 200);
5467 if Length(chstr) < 1 then
5468 begin
5469 g_Console_Add('centerprint <timeout> <text>');
5470 Exit;
5471 end;
5473 a := StrToIntDef(P[1], 100);
5474 chstr := b_Text_Format(chstr);
5475 g_Game_Message(chstr, a);
5476 if g_Game_IsNet and g_Game_IsServer then
5477 MH_SEND_GameEvent(NET_EV_BIGTEXT, a, chstr);
5478 end
5479 else g_Console_Add('centerprint <timeout> <text>');
5480 end
5481 else if (cmd = 'overtime') and not g_Game_IsClient then
5482 begin
5483 if (Length(P) = 1) or (StrToIntDef(P[1], -1) <= 0) then
5484 Exit;
5485 // Дополнительное время:
5486 gGameSettings.TimeLimit := (gTime - gGameStartTime) div 1000 + Word(StrToIntDef(P[1], 0));
5488 g_Console_Add(Format(_lc[I_MSG_TIME_LIMIT],
5489 [gGameSettings.TimeLimit div 3600,
5490 (gGameSettings.TimeLimit div 60) mod 60,
5491 gGameSettings.TimeLimit mod 60]));
5492 if g_Game_IsNet then MH_SEND_GameSettings;
5493 end
5494 else if (cmd = 'rcon_password') and g_Game_IsClient then
5495 begin
5496 if (Length(P) <= 1) then
5497 g_Console_Add('rcon_password <password>')
5498 else
5499 MC_SEND_RCONPassword(P[1]);
5500 end
5501 else if cmd = 'rcon' then
5502 begin
5503 if g_Game_IsClient then
5504 begin
5505 if Length(P) > 1 then
5506 begin
5507 chstr := '';
5508 for a := 1 to High(P) do
5509 chstr := chstr + P[a] + ' ';
5511 if Length(chstr) > 200 then SetLength(chstr, 200);
5513 if Length(chstr) < 1 then
5514 begin
5515 g_Console_Add('rcon <command>');
5516 Exit;
5517 end;
5519 MC_SEND_RCONCommand(chstr);
5520 end
5521 else g_Console_Add('rcon <command>');
5522 end;
5523 end
5524 else if cmd = 'ready' then
5525 begin
5526 if g_Game_IsServer and (gLMSRespawn = LMS_RESPAWN_WARMUP) then
5527 gLMSRespawnTime := gTime + 100;
5528 end
5529 else if (cmd = 'callvote') and g_Game_IsNet then
5530 begin
5531 if Length(P) > 1 then
5532 begin
5533 chstr := '';
5534 for a := 1 to High(P) do begin
5535 if a > 1 then chstr := chstr + ' ';
5536 chstr := chstr + P[a];
5537 end;
5539 if Length(chstr) > 200 then SetLength(chstr, 200);
5541 if Length(chstr) < 1 then
5542 begin
5543 g_Console_Add('callvote <command>');
5544 Exit;
5545 end;
5547 if g_Game_IsClient then
5548 MC_SEND_Vote(True, chstr)
5549 else
5550 g_Game_StartVote(chstr, gPlayer1Settings.Name);
5551 g_Console_Process('vote', True);
5552 end
5553 else
5554 g_Console_Add('callvote <command>');
5555 end
5556 else if (cmd = 'vote') and g_Game_IsNet then
5557 begin
5558 if g_Game_IsClient then
5559 MC_SEND_Vote(False)
5560 else if gVoteInProgress then
5561 begin
5562 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
5563 a := Floor((NetClientCount+1)/2.0) + 1
5564 else
5565 a := Floor(NetClientCount/2.0) + 1;
5566 if gVoted then
5567 begin
5568 Dec(gVoteCount);
5569 gVoted := False;
5570 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_REVOKED], [gPlayer1Settings.Name, gVoteCount, a]), True);
5571 MH_SEND_VoteEvent(NET_VE_REVOKE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5572 end
5573 else
5574 begin
5575 Inc(gVoteCount);
5576 gVoted := True;
5577 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_VOTE], [gPlayer1Settings.Name, gVoteCount, a]), True);
5578 MH_SEND_VoteEvent(NET_VE_VOTE, gPlayer1Settings.Name, 'a', gVoteCount, a);
5579 g_Game_CheckVote;
5580 end;
5581 end;
5582 end
5583 end;
5584 end;
5586 procedure SystemCommands(P: SSArray);
5587 var
5588 cmd: string;
5589 begin
5590 cmd := LowerCase(P[0]);
5591 case cmd of
5592 'exit', 'quit':
5593 begin
5594 g_Game_Free();
5595 g_Game_Quit();
5596 end;
5597 'r_reset':
5598 begin
5599 gRC_Width := Max(1, gRC_Width);
5600 gRC_Height := Max(1, gRC_Height);
5601 gBPP := Max(1, gBPP);
5602 if sys_SetDisplayMode(gRC_Width, gRC_Height, gBPP, gRC_FullScreen, gRC_Maximized) = True then
5603 e_LogWriteln('resolution changed')
5604 else
5605 e_LogWriteln('resolution not changed');
5606 sys_EnableVSync(gVSync);
5607 end;
5608 'r_maxfps':
5609 begin
5610 if Length(p) = 2 then
5611 begin
5612 gMaxFPS := StrToIntDef(p[1], gMaxFPS);
5613 if gMaxFPS > 0 then
5614 gFrameTime := 1000 div gMaxFPS
5615 else
5616 gFrameTime := 0;
5617 end;
5618 e_LogWritefln('r_maxfps %d', [gMaxFPS]);
5619 end;
5620 'g_language':
5621 begin
5622 if Length(p) = 2 then
5623 begin
5624 gAskLanguage := true;
5625 gLanguage := LANGUAGE_ENGLISH;
5626 case LowerCase(p[1]) of
5627 'english':
5628 begin
5629 gAskLanguage := false;
5630 gLanguage := LANGUAGE_ENGLISH;
5631 end;
5632 'russian':
5633 begin
5634 gAskLanguage := false;
5635 gLanguage := LANGUAGE_RUSSIAN;
5636 end;
5637 'ask':
5638 begin
5639 gAskLanguage := true;
5640 gLanguage := LANGUAGE_ENGLISH;
5641 end;
5642 end;
5643 g_Language_Set(gLanguage);
5644 end
5645 else
5646 begin
5647 e_LogWritefln('usage: %s <English|Russian|Ask>', [cmd]);
5648 end
5649 end;
5650 end;
5651 end;
5653 procedure g_TakeScreenShot(Filename: string = '');
5654 var s: TStream; t: TDateTime; dir, date, name: String;
5655 begin
5656 if e_NoGraphics then Exit;
5657 try
5658 dir := e_GetWriteableDir(ScreenshotDirs);
5660 if Filename = '' then
5661 begin
5662 t := Now;
5663 DateTimeToString(date, 'yyyy-mm-dd-hh-nn-ss', t);
5664 Filename := 'screenshot-' + date;
5665 end;
5667 name := e_CatPath(dir, Filename + '.png');
5668 s := createDiskFile(name);
5669 try
5670 e_MakeScreenshot(s, gScreenWidth, gScreenHeight);
5671 s.Free;
5672 g_Console_Add(Format(_lc[I_CONSOLE_SCREENSHOT], [name]))
5673 except
5674 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_WRITE], [name]));
5675 s.Free;
5676 DeleteFile(name)
5677 end
5678 except
5679 g_Console_Add('oh shit, i can''t create screenshot!')
5680 end
5681 end;
5683 procedure g_Game_InGameMenu(Show: Boolean);
5684 begin
5685 if (g_ActiveWindow = nil) and Show then
5686 begin
5687 if gGameSettings.GameType = GT_SINGLE then
5688 g_GUI_ShowWindow('GameSingleMenu')
5689 else
5690 begin
5691 if g_Game_IsClient then
5692 g_GUI_ShowWindow('GameClientMenu')
5693 else
5694 if g_Game_IsNet then
5695 g_GUI_ShowWindow('GameServerMenu')
5696 else
5697 g_GUI_ShowWindow('GameCustomMenu');
5698 end;
5699 g_Sound_PlayEx('MENU_OPEN');
5701 // Пауза при меню только в одиночной игре:
5702 if (not g_Game_IsNet) then
5703 g_Game_Pause(True);
5704 end
5705 else
5706 if (g_ActiveWindow <> nil) and (not Show) then
5707 begin
5708 // Пауза при меню только в одиночной игре:
5709 if (not g_Game_IsNet) then
5710 g_Game_Pause(False);
5711 end;
5712 end;
5714 procedure g_Game_Pause (Enable: Boolean);
5715 var
5716 oldPause: Boolean;
5717 begin
5718 if not gGameOn then exit;
5720 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5722 oldPause := gPause;
5723 gPauseMain := Enable;
5725 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5726 end;
5728 procedure g_Game_HolmesPause (Enable: Boolean);
5729 var
5730 oldPause: Boolean;
5731 begin
5732 if not gGameOn then exit;
5733 if not (gGameSettings.GameType in [GT_SINGLE, GT_CUSTOM]) then exit;
5735 oldPause := gPause;
5736 gPauseHolmes := Enable;
5738 if (gPause <> oldPause) then g_Game_PauseAllSounds(gPause);
5739 end;
5741 procedure g_Game_PauseAllSounds(Enable: Boolean);
5742 var
5743 i: Integer;
5744 begin
5745 // Триггеры:
5746 if gTriggers <> nil then
5747 for i := 0 to High(gTriggers) do
5748 with gTriggers[i] do
5749 if (TriggerType = TRIGGER_SOUND) and
5750 (Sound <> nil) and
5751 Sound.IsPlaying() then
5752 begin
5753 Sound.Pause(Enable);
5754 end;
5756 // Звуки игроков:
5757 if gPlayers <> nil then
5758 for i := 0 to High(gPlayers) do
5759 if gPlayers[i] <> nil then
5760 gPlayers[i].PauseSounds(Enable);
5762 // Музыка:
5763 if gMusic <> nil then
5764 gMusic.Pause(Enable);
5765 end;
5767 procedure g_Game_StopAllSounds(all: Boolean);
5768 var
5769 i: Integer;
5770 begin
5771 if gTriggers <> nil then
5772 for i := 0 to High(gTriggers) do
5773 with gTriggers[i] do
5774 if (TriggerType = TRIGGER_SOUND) and
5775 (Sound <> nil) then
5776 Sound.Stop();
5778 if gMusic <> nil then
5779 gMusic.Stop();
5781 if all then
5782 e_StopChannels();
5783 end;
5785 procedure g_Game_UpdateTriggerSounds;
5786 var i: Integer;
5787 begin
5788 if gTriggers <> nil then
5789 for i := 0 to High(gTriggers) do
5790 with gTriggers[i] do
5791 if (TriggerType = TRIGGER_SOUND) and (Sound <> nil) and tgcLocal and Sound.IsPlaying() then
5792 Sound.SetCoordsRect(X, Y, Width, Height, tgcVolume / 255.0)
5793 end;
5795 function g_Game_IsWatchedPlayer(UID: Word): Boolean;
5796 begin
5797 Result := False;
5798 if (gPlayer1 <> nil) and (gPlayer1.UID = UID) then
5799 begin
5800 Result := True;
5801 Exit;
5802 end;
5803 if (gPlayer2 <> nil) and (gPlayer2.UID = UID) then
5804 begin
5805 Result := True;
5806 Exit;
5807 end;
5808 if gSpectMode <> SPECT_PLAYERS then
5809 Exit;
5810 if gSpectPID1 = UID then
5811 begin
5812 Result := True;
5813 Exit;
5814 end;
5815 if gSpectViewTwo and (gSpectPID2 = UID) then
5816 begin
5817 Result := True;
5818 Exit;
5819 end;
5820 end;
5822 function g_Game_IsWatchedTeam(Team: Byte): Boolean;
5823 var
5824 Pl: TPlayer;
5825 begin
5826 Result := False;
5827 if (gPlayer1 <> nil) and (gPlayer1.Team = Team) then
5828 begin
5829 Result := True;
5830 Exit;
5831 end;
5832 if (gPlayer2 <> nil) and (gPlayer2.Team = Team) then
5833 begin
5834 Result := True;
5835 Exit;
5836 end;
5837 if gSpectMode <> SPECT_PLAYERS then
5838 Exit;
5839 Pl := g_Player_Get(gSpectPID1);
5840 if (Pl <> nil) and (Pl.Team = Team) then
5841 begin
5842 Result := True;
5843 Exit;
5844 end;
5845 if gSpectViewTwo then
5846 begin
5847 Pl := g_Player_Get(gSpectPID2);
5848 if (Pl <> nil) and (Pl.Team = Team) then
5849 begin
5850 Result := True;
5851 Exit;
5852 end;
5853 end;
5854 end;
5856 procedure g_Game_Message(Msg: string; Time: Word);
5857 begin
5858 MessageLineLength := (gScreenWidth - 204) div e_CharFont_GetMaxWidth(gMenuFont);
5859 MessageText := b_Text_Wrap(b_Text_Format(Msg), MessageLineLength);
5860 MessageTime := Time;
5861 end;
5863 procedure g_Game_ChatSound(Text: String; Taunt: Boolean = True);
5864 const
5865 punct: Array[0..13] of String =
5866 ('.', ',', ':', ';', '!', '?', '(', ')', '''', '"', '/', '\', '*', '^');
5867 var
5868 i, j: Integer;
5869 ok: Boolean;
5870 fpText: String;
5872 function IsPunctuation(S: String): Boolean;
5873 var
5874 i: Integer;
5875 begin
5876 Result := False;
5877 if Length(S) <> 1 then
5878 Exit;
5879 for i := Low(punct) to High(punct) do
5880 if S = punct[i] then
5881 begin
5882 Result := True;
5883 break;
5884 end;
5885 end;
5886 function FilterPunctuation(S: String): String;
5887 var
5888 i: Integer;
5889 begin
5890 for i := Low(punct) to High(punct) do
5891 S := StringReplace(S, punct[i], ' ', [rfReplaceAll]);
5892 Result := S;
5893 end;
5894 begin
5895 ok := False;
5897 if gUseChatSounds and Taunt and (gChatSounds <> nil) and (Pos(': ', Text) > 0) then
5898 begin
5899 // remove player name
5900 Delete(Text, 1, Pos(': ', Text) + 2 - 1);
5901 // for FullWord check
5902 Text := toLowerCase1251(' ' + Text + ' ');
5903 fpText := FilterPunctuation(Text);
5905 for i := 0 to Length(gChatSounds) - 1 do
5906 begin
5907 ok := True;
5908 for j := 0 to Length(gChatSounds[i].Tags) - 1 do
5909 begin
5910 if gChatSounds[i].FullWord and (not IsPunctuation(gChatSounds[i].Tags[j])) then
5911 ok := Pos(' ' + gChatSounds[i].Tags[j] + ' ', fpText) > 0
5912 else
5913 ok := Pos(gChatSounds[i].Tags[j], Text) > 0;
5914 if not ok then
5915 break;
5916 end;
5917 if ok then
5918 begin
5919 gChatSounds[i].Sound.Play();
5920 break;
5921 end;
5922 end;
5923 end;
5924 if not ok then
5925 g_Sound_PlayEx('SOUND_GAME_RADIO');
5926 end;
5928 procedure g_Game_Announce_GoodShot(SpawnerUID: Word);
5929 var
5930 a: Integer;
5931 begin
5932 case gAnnouncer of
5933 ANNOUNCE_NONE:
5934 Exit;
5935 ANNOUNCE_ME,
5936 ANNOUNCE_MEPLUS:
5937 if not g_Game_IsWatchedPlayer(SpawnerUID) then
5938 Exit;
5939 end;
5940 for a := 0 to 3 do
5941 if goodsnd[a].IsPlaying() then
5942 Exit;
5944 goodsnd[Random(4)].Play();
5945 end;
5947 procedure g_Game_Announce_KillCombo(Param: Integer);
5948 var
5949 UID: Word;
5950 c, n: Byte;
5951 Pl: TPlayer;
5952 Name: String;
5953 begin
5954 UID := Param and $FFFF;
5955 c := Param shr 16;
5956 if c < 2 then
5957 Exit;
5959 Pl := g_Player_Get(UID);
5960 if Pl = nil then
5961 Name := '?'
5962 else
5963 Name := Pl.Name;
5965 case c of
5966 2: begin
5967 n := 0;
5968 g_Console_Add(Format(_lc[I_PLAYER_KILL_2X], [Name]), True);
5969 end;
5970 3: begin
5971 n := 1;
5972 g_Console_Add(Format(_lc[I_PLAYER_KILL_3X], [Name]), True);
5973 end;
5974 4: begin
5975 n := 2;
5976 g_Console_Add(Format(_lc[I_PLAYER_KILL_4X], [Name]), True);
5977 end;
5978 else begin
5979 n := 3;
5980 g_Console_Add(Format(_lc[I_PLAYER_KILL_MX], [Name]), True);
5981 end;
5982 end;
5984 case gAnnouncer of
5985 ANNOUNCE_NONE:
5986 Exit;
5987 ANNOUNCE_ME:
5988 if not g_Game_IsWatchedPlayer(UID) then
5989 Exit;
5990 ANNOUNCE_MEPLUS:
5991 if (not g_Game_IsWatchedPlayer(UID)) and (c < 4) then
5992 Exit;
5993 end;
5995 if killsnd[n].IsPlaying() then
5996 killsnd[n].Stop();
5997 killsnd[n].Play();
5998 end;
6000 procedure g_Game_Announce_BodyKill(SpawnerUID: Word);
6001 var
6002 a: Integer;
6003 begin
6004 case gAnnouncer of
6005 ANNOUNCE_NONE:
6006 Exit;
6007 ANNOUNCE_ME:
6008 if not g_Game_IsWatchedPlayer(SpawnerUID) then
6009 Exit;
6010 end;
6011 for a := 0 to 2 do
6012 if hahasnd[a].IsPlaying() then
6013 Exit;
6015 hahasnd[Random(3)].Play();
6016 end;
6018 procedure g_Game_StartVote(Command, Initiator: string);
6019 var
6020 Need: Integer;
6021 begin
6022 if not gVotesEnabled then Exit;
6023 if gGameSettings.GameType <> GT_SERVER then Exit;
6024 if gVoteInProgress or gVotePassed then
6025 begin
6026 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_INPROGRESS], [gVoteCommand]), True);
6027 MH_SEND_VoteEvent(NET_VE_INPROGRESS, gVoteCommand);
6028 Exit;
6029 end;
6030 gVoteInProgress := True;
6031 gVotePassed := False;
6032 gVoteTimer := gTime + gVoteTimeout * 1000;
6033 gVoteCount := 0;
6034 gVoted := False;
6035 gVoteCommand := Command;
6037 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6038 Need := Floor((NetClientCount+1)/2.0)+1
6039 else
6040 Need := Floor(NetClientCount/2.0)+1;
6041 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_STARTED], [Initiator, Command, Need]), True);
6042 MH_SEND_VoteEvent(NET_VE_STARTED, Initiator, Command, Need);
6043 end;
6045 procedure g_Game_CheckVote;
6046 var
6047 I, Need: Integer;
6048 begin
6049 if gGameSettings.GameType <> GT_SERVER then Exit;
6050 if not gVoteInProgress then Exit;
6052 if (gTime >= gVoteTimer) then
6053 begin
6054 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6055 Need := Floor((NetClientCount+1)/2.0) + 1
6056 else
6057 Need := Floor(NetClientCount/2.0) + 1;
6058 if gVoteCount >= Need then
6059 begin
6060 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6061 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6062 gVotePassed := True;
6063 gVoteCmdTimer := gTime + 5000;
6064 end
6065 else
6066 begin
6067 g_Console_Add(_lc[I_MESSAGE_VOTE_FAILED], True);
6068 MH_SEND_VoteEvent(NET_VE_FAILED);
6069 end;
6070 if NetClients <> nil then
6071 for I := Low(NetClients) to High(NetClients) do
6072 if NetClients[i].Used then
6073 NetClients[i].Voted := False;
6074 gVoteInProgress := False;
6075 gVoted := False;
6076 gVoteCount := 0;
6077 end
6078 else
6079 begin
6080 if (gPlayer1 <> nil) or (gPlayer2 <> nil) then
6081 Need := Floor((NetClientCount+1)/2.0) + 1
6082 else
6083 Need := Floor(NetClientCount/2.0) + 1;
6084 if gVoteCount >= Need then
6085 begin
6086 g_Console_Add(Format(_lc[I_MESSAGE_VOTE_PASSED], [gVoteCommand]), True);
6087 MH_SEND_VoteEvent(NET_VE_PASSED, gVoteCommand);
6088 gVoteInProgress := False;
6089 gVotePassed := True;
6090 gVoteCmdTimer := gTime + 5000;
6091 gVoted := False;
6092 gVoteCount := 0;
6093 if NetClients <> nil then
6094 for I := Low(NetClients) to High(NetClients) do
6095 if NetClients[i].Used then
6096 NetClients[i].Voted := False;
6097 end;
6098 end;
6099 end;
6101 procedure g_Game_LoadMapList(FileName: string);
6102 var
6103 ListFile: TextFile;
6104 s: string;
6105 begin
6106 MapList := nil;
6107 MapIndex := -1;
6109 if not FileExists(FileName) then Exit;
6111 AssignFile(ListFile, FileName);
6112 Reset(ListFile);
6113 while not EOF(ListFile) do
6114 begin
6115 ReadLn(ListFile, s);
6117 s := Trim(s);
6118 if s = '' then Continue;
6120 SetLength(MapList, Length(MapList)+1);
6121 MapList[High(MapList)] := s;
6122 end;
6123 CloseFile(ListFile);
6124 end;
6126 procedure g_Game_SetDebugMode();
6127 begin
6128 gDebugMode := True;
6129 // Читы (даже в своей игре):
6130 gCheats := True;
6131 end;
6133 procedure g_Game_SetLoadingText(Text: String; Max: Integer; reWrite: Boolean);
6134 var
6135 i: Word;
6136 begin
6137 if Length(LoadingStat.Msgs) = 0 then
6138 Exit;
6140 with LoadingStat do
6141 begin
6142 if not reWrite then
6143 begin // Переходим на следующую строку или скроллируем:
6144 if NextMsg = Length(Msgs) then
6145 begin // scroll
6146 for i := 0 to High(Msgs)-1 do
6147 Msgs[i] := Msgs[i+1];
6148 end
6149 else
6150 Inc(NextMsg);
6151 end else
6152 if NextMsg = 0 then
6153 Inc(NextMsg);
6155 Msgs[NextMsg-1] := Text;
6156 CurValue := 0;
6157 MaxValue := Max;
6158 ShowCount := 0;
6159 PBarWasHere := false;
6160 end;
6162 g_ActiveWindow := nil;
6164 ProcessLoading(true);
6165 end;
6167 procedure g_Game_StepLoading(Value: Integer = -1);
6168 begin
6169 with LoadingStat do
6170 begin
6171 if Value = -1 then
6172 begin
6173 Inc(CurValue);
6174 Inc(ShowCount);
6175 end
6176 else
6177 CurValue := Value;
6178 if (ShowCount > LOADING_SHOW_STEP) or (Value > -1) then
6179 begin
6180 ShowCount := 0;
6181 ProcessLoading();
6182 end;
6183 end;
6184 end;
6186 procedure g_Game_ClearLoading();
6187 var
6188 len: Word;
6189 begin
6190 with LoadingStat do
6191 begin
6192 CurValue := 0;
6193 MaxValue := 0;
6194 ShowCount := 0;
6195 len := ((gScreenHeight div 3)*2 - 50) div LOADING_INTERLINE;
6196 if len < 1 then len := 1;
6197 SetLength(Msgs, len);
6198 for len := Low(Msgs) to High(Msgs) do
6199 Msgs[len] := '';
6200 NextMsg := 0;
6201 PBarWasHere := false;
6202 end;
6203 end;
6205 procedure Parse_Params(var pars: TParamStrValues);
6206 var
6207 i: Integer;
6208 s: String;
6209 begin
6210 SetLength(pars, 0);
6211 i := 1;
6212 while i <= ParamCount do
6213 begin
6214 s := ParamStr(i);
6215 if (s[1] = '-') and (Length(s) > 1) then
6216 begin
6217 if (s[2] = '-') and (Length(s) > 2) then
6218 begin // Одиночный параметр
6219 SetLength(pars, Length(pars) + 1);
6220 with pars[High(pars)] do
6221 begin
6222 Name := LowerCase(s);
6223 Value := '+';
6224 end;
6225 end
6226 else
6227 if (i < ParamCount) then
6228 begin // Параметр со значением
6229 Inc(i);
6230 SetLength(pars, Length(pars) + 1);
6231 with pars[High(pars)] do
6232 begin
6233 Name := LowerCase(s);
6234 Value := LowerCase(ParamStr(i));
6235 end;
6236 end;
6237 end;
6239 Inc(i);
6240 end;
6241 end;
6243 function Find_Param_Value(var pars: TParamStrValues; aName: String): String;
6244 var
6245 i: Integer;
6246 begin
6247 Result := '';
6248 for i := 0 to High(pars) do
6249 if pars[i].Name = aName then
6250 begin
6251 Result := pars[i].Value;
6252 Break;
6253 end;
6254 end;
6256 procedure g_Game_Process_Params();
6257 var
6258 pars: TParamStrValues;
6259 map: String;
6260 GMode, n: Byte;
6261 LimT, LimS: Integer;
6262 Opt: LongWord;
6263 Lives: Integer;
6264 s: String;
6265 Port: Integer;
6266 ip: String;
6267 F: TextFile;
6268 begin
6269 Parse_Params(pars);
6271 // Debug mode:
6272 s := Find_Param_Value(pars, '--debug');
6273 if (s <> '') then
6274 begin
6275 g_Game_SetDebugMode();
6276 s := Find_Param_Value(pars, '--netdump');
6277 if (s <> '') then
6278 NetDump := True;
6279 end;
6281 // Connect when game loads
6282 ip := Find_Param_Value(pars, '-connect');
6284 if ip <> '' then
6285 begin
6286 s := Find_Param_Value(pars, '-port');
6287 if (s = '') or not TryStrToInt(s, Port) then
6288 Port := 25666;
6290 s := Find_Param_Value(pars, '-pw');
6292 g_Game_StartClient(ip, Port, s);
6293 Exit;
6294 end;
6296 s := LowerCase(Find_Param_Value(pars, '-dbg-mainwad'));
6297 if (s <> '') then
6298 begin
6299 gDefaultMegawadStart := s;
6300 end;
6302 if (Find_Param_Value(pars, '--dbg-mainwad-restore') <> '') or
6303 (Find_Param_Value(pars, '--dbg-mainwad-default') <> '') then
6304 begin
6305 gDefaultMegawadStart := DF_Default_Megawad_Start;
6306 end;
6308 // Start map when game loads:
6309 map := LowerCase(Find_Param_Value(pars, '-map'));
6310 if isWadPath(map) then
6311 begin
6312 // Game mode:
6313 s := Find_Param_Value(pars, '-gm');
6314 GMode := g_Game_TextToMode(s);
6315 if GMode = GM_NONE then GMode := GM_DM;
6316 if GMode = GM_SINGLE then GMode := GM_COOP;
6318 // Time limit:
6319 s := Find_Param_Value(pars, '-limt');
6320 if (s = '') or (not TryStrToInt(s, LimT)) then
6321 LimT := 0;
6322 if LimT < 0 then
6323 LimT := 0;
6325 // Goal limit:
6326 s := Find_Param_Value(pars, '-lims');
6327 if (s = '') or (not TryStrToInt(s, LimS)) then
6328 LimS := 0;
6329 if LimS < 0 then
6330 LimS := 0;
6332 // Lives limit:
6333 s := Find_Param_Value(pars, '-lives');
6334 if (s = '') or (not TryStrToInt(s, Lives)) then
6335 Lives := 0;
6336 if Lives < 0 then
6337 Lives := 0;
6339 // Options:
6340 s := Find_Param_Value(pars, '-opt');
6341 if (s = '') then
6342 Opt := gsGameFlags
6343 else
6344 Opt := StrToIntDef(s, 0);
6346 // Close after map:
6347 s := Find_Param_Value(pars, '--close');
6348 if (s <> '') then
6349 gMapOnce := True;
6351 // Override map to test:
6352 s := LowerCase(Find_Param_Value(pars, '-testmap'));
6353 if s <> '' then
6354 begin
6355 if e_IsValidResourceName(s) then
6356 e_FindResource(AllMapDirs, s);
6357 gTestMap := ExpandFileName(s);
6358 end;
6360 // Delete test map after play:
6361 s := Find_Param_Value(pars, '--testdelete');
6362 if (s <> '') then
6363 begin
6364 //gMapToDelete := MapsDir + map;
6365 e_WriteLog('"--testdelete" is deprecated, use --tempdelete.', TMsgType.Fatal);
6366 Halt(1);
6367 end;
6369 // Delete temporary WAD after play:
6370 s := Find_Param_Value(pars, '--tempdelete');
6371 if (s <> '') and (gTestMap <> '') then
6372 begin
6373 gMapToDelete := gTestMap;
6374 gTempDelete := True;
6375 end;
6377 // Number of players:
6378 s := Find_Param_Value(pars, '-pl');
6379 if (s = '') then
6380 n := DEFAULT_PLAYERS
6381 else
6382 n := StrToIntDef(s, DEFAULT_PLAYERS);
6384 // Start:
6385 s := Find_Param_Value(pars, '-port');
6386 if (s = '') or not TryStrToInt(s, Port) then
6387 g_Game_StartCustom(map, GMode, LimT, LimS, Lives, Opt, n)
6388 else
6389 g_Game_StartServer(map, GMode, LimT, LimS, Lives, Opt, n, 0, Port);
6390 end;
6392 // Execute script when game loads:
6393 s := Find_Param_Value(pars, '-exec');
6394 if s <> '' then
6395 begin
6396 // if not isWadPath(s) then
6397 // s := GameDir + '/' + s;
6399 {$I-}
6400 AssignFile(F, s);
6401 Reset(F);
6402 if IOResult <> 0 then
6403 begin
6404 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6405 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6406 CloseFile(F);
6407 Exit;
6408 end;
6409 e_WriteLog('Executing script: ' + s, TMsgType.Notify);
6410 g_Console_Add(Format(_lc[I_CONSOLE_EXEC], [s]));
6412 while not EOF(F) do
6413 begin
6414 ReadLn(F, s);
6415 if IOResult <> 0 then
6416 begin
6417 e_WriteLog(Format(_lc[I_SIMPLE_ERROR], ['Failed to read file: ' + s]), TMsgType.Warning);
6418 g_Console_Add(Format(_lc[I_CONSOLE_ERROR_READ], [s]));
6419 CloseFile(F);
6420 Exit;
6421 end;
6422 if Pos('#', s) <> 1 then // script comment
6423 g_Console_Process(s, True);
6424 end;
6426 CloseFile(F);
6427 {$I+}
6428 end;
6430 SetLength(pars, 0);
6431 end;
6433 begin
6434 conRegVar('pf_draw_frame', @g_profile_frame_draw, 'draw frame rendering profiles', 'render profiles');
6435 //conRegVar('pf_update_frame', @g_profile_frame_update, 'draw frame updating profiles', 'update profiles');
6436 conRegVar('pf_coldet', @g_profile_collision, 'draw collision detection profiles', 'coldet profiles');
6437 conRegVar('pf_los', @g_profile_los, 'draw monster LOS profiles', 'monster LOS profiles');
6439 conRegVar('r_sq_draw', @gdbg_map_use_accel_render, 'accelerated spatial queries in rendering', 'accelerated rendering');
6440 conRegVar('cd_sq_enabled', @gdbg_map_use_accel_coldet, 'accelerated spatial queries in map coldet', 'accelerated map coldet');
6441 conRegVar('mon_sq_enabled', @gmon_debug_use_sqaccel, 'accelerated spatial queries for monsters', 'accelerated monster coldet');
6442 conRegVar('wtrace_sq_enabled', @gwep_debug_fast_trace, 'accelerated spatial queries for weapon hitscan trace', 'accelerated weapon hitscan');
6444 conRegVar('pr_enabled', @gpart_dbg_enabled, 'enable/disable particles', 'particles');
6445 conRegVar('pr_phys_enabled', @gpart_dbg_phys_enabled, 'enable/disable particle physics', 'particle physics');
6447 conRegVar('los_enabled', @gmon_dbg_los_enabled, 'enable/disable monster LOS calculations', 'monster LOS', true);
6448 conRegVar('mon_think', @gmon_debug_think, 'enable/disable monster thinking', 'monster thinking', true);
6450 {$IFDEF ENABLE_HOLMES}
6451 conRegVar('dbg_holmes', @g_holmes_enabled, 'enable/disable Holmes', 'Holmes', true);
6452 {$ENDIF}
6454 conRegVar('dbg_ignore_level_bounds', @g_dbg_ignore_bounds, 'ignore level bounds', '', false);
6456 conRegVar('r_scale', @g_dbg_scale, 0.01, 100.0, 'render scale', '', false);
6457 conRegVar('r_resolution_scale', @r_pixel_scale, 0.01, 100.0, 'upscale factor', '', false);
6459 conRegVar('light_enabled', @gwin_k8_enable_light_experiments, 'enable/disable dynamic lighting', 'lighting');
6460 conRegVar('light_player_halo', @g_playerLight, 'enable/disable player halo', 'player light halo');
6462 conRegVar('r_smallmap_align_h', @r_smallmap_h, 'halign: 0: left; 1: center; 2: right', 'horizontal aligning of small maps');
6463 conRegVar('r_smallmap_align_v', @r_smallmap_v, 'valign: 0: top; 1: center; 2: bottom', 'vertial aligning of small maps');
6465 conRegVar('r_showfps', @gShowFPS, 'draw fps counter', 'draw fps counter');
6466 conRegVar('r_showtime', @gShowTime, 'show game time', 'show game time');
6467 conRegVar('r_showping', @gShowPing, 'show ping', 'show ping');
6468 conRegVar('r_showscore', @gShowGoals, 'show score', 'show score');
6469 conRegVar('r_showkillmsg', @gShowKillMsg, 'show kill log', 'show kill log');
6470 conRegVar('r_showlives', @gShowLives, 'show lives', 'show lives');
6471 conRegVar('r_showspect', @gSpectHUD, 'show spectator hud', 'show spectator hud');
6472 conRegVar('r_showstat', @gShowStat, 'show stats', 'show stats');
6473 conRegVar('r_showpids', @gShowPIDs, 'show PIDs', 'show PIDs');
6474 end.