DEADSOFTWARE

net: game: better hash management; calculate resource hashes only once, send all...
[d2df-sdl.git] / src / game / g_map.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 {$DEFINE MAP_DEBUG_ENABLED_FLAG}
17 unit g_map;
19 interface
21 uses
22 SysUtils, Classes, mempool,
23 e_graphics, g_basic, MAPDEF, g_textures,
24 g_phys, utils, g_panel, g_grid, md5, binheap, xprofiler, xparser, xdynrec;
26 type
27 TMapInfo = record
28 Map: String;
29 Name: String;
30 Description: String;
31 Author: String;
32 MusicName: String;
33 SkyName: String;
34 Height: Word;
35 Width: Word;
36 end;
38 PRespawnPoint = ^TRespawnPoint;
39 TRespawnPoint = record
40 X, Y: Integer;
41 Direction: TDirection;
42 PointType: Byte;
43 end;
45 PFlagPoint = ^TFlagPoint;
46 TFlagPoint = TRespawnPoint;
48 PFlag = ^TFlag;
49 TFlag = record
50 Obj: TObj;
51 RespawnType: Byte;
52 State: Byte;
53 Count: Integer;
54 CaptureTime: LongWord;
55 Animation: TAnimation;
56 Direction: TDirection;
57 end;
59 function g_Map_Load(Res: String): Boolean;
60 function g_Map_GetMapInfo(Res: String): TMapInfo;
61 function g_Map_GetMapsList(WADName: String): SSArray;
62 function g_Map_Exist(Res: String): Boolean;
63 procedure g_Map_Free(freeTextures: Boolean=true);
64 procedure g_Map_Update();
66 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
68 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor); // unaccelerated
69 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
71 procedure g_Map_DrawBack(dx, dy: Integer);
72 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
73 PanelType: Word; b1x3: Boolean=false): Boolean;
74 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
76 procedure g_Map_EnableWallGUID (pguid: Integer);
77 procedure g_Map_DisableWallGUID (pguid: Integer);
78 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
80 // HACK!!!
81 procedure g_Map_EnableWall_XXX (ID: DWORD);
82 procedure g_Map_DisableWall_XXX (ID: DWORD);
83 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
85 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
87 procedure g_Map_ReAdd_DieTriggers();
88 function g_Map_IsSpecialTexture(Texture: String): Boolean;
90 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
91 function g_Map_GetPointCount(PointType: Byte): Word;
93 function g_Map_HaveFlagPoints(): Boolean;
95 procedure g_Map_ResetFlag(Flag: Byte);
96 procedure g_Map_DrawFlags();
98 procedure g_Map_SaveState (st: TStream);
99 procedure g_Map_LoadState (st: TStream);
101 procedure g_Map_DrawPanelShadowVolumes(lightX: Integer; lightY: Integer; radius: Integer);
103 // returns panel or nil
104 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
105 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
107 // returns panel or nil
108 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
109 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
111 type
112 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
114 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
115 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
117 // trace liquid, stepping by `dx` and `dy`
118 // return last seen liquid coords, and `false` if we're started outside of the liquid
119 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
122 // return `true` from `cb` to stop
123 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
125 procedure g_Map_NetSendInterestingPanels (); // yay!
128 procedure g_Map_ProfilersBegin ();
129 procedure g_Map_ProfilersEnd ();
132 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
135 function g_Map_MinX (): Integer; inline;
136 function g_Map_MinY (): Integer; inline;
137 function g_Map_MaxX (): Integer; inline;
138 function g_Map_MaxY (): Integer; inline;
140 const
141 NNF_NO_NAME = 0;
142 NNF_NAME_BEFORE = 1;
143 NNF_NAME_EQUALS = 2;
144 NNF_NAME_AFTER = 3;
146 function g_Texture_NumNameFindStart(name: String): Boolean;
147 function g_Texture_NumNameFindNext(var newName: String): Byte;
149 const
150 RESPAWNPOINT_PLAYER1 = 1;
151 RESPAWNPOINT_PLAYER2 = 2;
152 RESPAWNPOINT_DM = 3;
153 RESPAWNPOINT_RED = 4;
154 RESPAWNPOINT_BLUE = 5;
156 FLAG_NONE = 0;
157 FLAG_RED = 1;
158 FLAG_BLUE = 2;
159 FLAG_DOM = 3;
161 FLAG_STATE_NONE = 0;
162 FLAG_STATE_NORMAL = 1;
163 FLAG_STATE_DROPPED = 2;
164 FLAG_STATE_CAPTURED = 3;
165 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
166 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
168 FLAG_TIME = 720; // 20 seconds
170 SKY_STRETCH: Single = 1.5;
172 const
173 GridTagInvalid = 0;
175 (* draw order:
176 PANEL_BACK
177 PANEL_STEP
178 PANEL_WALL
179 PANEL_CLOSEDOOR
180 PANEL_ACID1
181 PANEL_ACID2
182 PANEL_WATER
183 PANEL_FORE
184 *)
185 // sorted by draw priority
186 GridTagBack = 1 shl 0; // gRenderBackgrounds
187 GridTagStep = 1 shl 1; // gSteps
188 GridTagWall = 1 shl 2; // gWalls
189 GridTagDoor = 1 shl 3; // gWalls
190 GridTagAcid1 = 1 shl 4; // gAcid1
191 GridTagAcid2 = 1 shl 5; // gAcid2
192 GridTagWater = 1 shl 6; // gWater
193 GridTagFore = 1 shl 7; // gRenderForegrounds
194 // the following are invisible
195 GridTagLift = 1 shl 8; // gLifts
196 GridTagBlockMon = 1 shl 9; // gBlockMon
198 GridTagSolid = (GridTagWall or GridTagDoor);
199 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
200 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
202 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
205 type
206 TBinHeapPanelDrawCmp = class
207 public
208 class function less (const a, b: TPanel): Boolean; inline;
209 end;
211 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
213 var
214 gWalls: TPanelArray;
215 gRenderBackgrounds: TPanelArray;
216 gRenderForegrounds: TPanelArray;
217 gWater, gAcid1, gAcid2: TPanelArray;
218 gSteps: TPanelArray;
219 gLifts: TPanelArray;
220 gBlockMon: TPanelArray;
221 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
222 //gDOMFlags: array of TFlag;
223 gMapInfo: TMapInfo;
224 gBackSize: TDFPoint;
225 gDoorMap: array of array of DWORD;
226 gLiftMap: array of array of DWORD;
227 gWADHash: TMD5Digest;
228 BackID: DWORD = DWORD(-1);
229 gExternalResources: array of TDiskFileInfo = nil;
230 gMovingWallIds: array of Integer = nil;
232 gdbg_map_use_accel_render: Boolean = true;
233 gdbg_map_use_accel_coldet: Boolean = true;
234 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
235 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
237 gCurrentMap: TDynRecord = nil;
238 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
239 gTestMap: String = '';
242 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
245 type
246 TPanelGrid = specialize TBodyGridBase<TPanel>;
248 var
249 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
252 implementation
254 uses
255 {$INCLUDE ../nogl/noGLuses.inc}
256 e_input, g_main, e_log, e_texture, g_items, g_gfx, g_console,
257 g_weapons, g_game, g_sound, e_sound, CONFIG,
258 g_options, g_triggers, g_player,
259 Math, g_monsters, g_saveload, g_language, g_netmsg,
260 sfs, xstreams, hashtable, wadreader,
261 ImagingTypes, Imaging, ImagingUtility,
262 ImagingGif, ImagingNetworkGraphics,
263 g_res_downloader;
265 const
266 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
267 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
268 FLAG_SIGNATURE = $47414C46; // 'FLAG'
271 // ////////////////////////////////////////////////////////////////////////// //
272 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
273 begin
274 if (line > 0) then
275 begin
276 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
277 end
278 else
279 begin
280 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
281 end;
282 end;
285 // ////////////////////////////////////////////////////////////////////////// //
286 var
287 panByGUID: array of TPanel = nil;
290 // ////////////////////////////////////////////////////////////////////////// //
291 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
292 begin
293 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
294 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
295 end;
298 // return `true` from `cb` to stop
299 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
300 var
301 pan: TPanel;
302 begin
303 result := nil;
304 if not assigned(cb) then exit;
305 for pan in panByGUID do
306 begin
307 if cb(pan) then begin result := pan; exit; end;
308 end;
309 end;
312 procedure g_Map_NetSendInterestingPanels ();
313 var
314 pan: TPanel;
315 begin
316 if g_Game_IsServer and g_Game_IsNet then
317 begin
318 for pan in panByGUID do
319 begin
320 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
321 end;
322 end;
323 end;
326 // ////////////////////////////////////////////////////////////////////////// //
327 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
328 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
329 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
330 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
333 // ////////////////////////////////////////////////////////////////////////// //
334 var
335 dfmapdef: TDynMapDef = nil;
338 procedure loadMapDefinition ();
339 var
340 pr: TTextParser = nil;
341 st: TStream = nil;
342 WAD: TWADFile = nil;
343 begin
344 if (dfmapdef <> nil) then exit;
346 try
347 e_LogWritefln('parsing "mapdef.txt"...', []);
348 st := openDiskFileRO(DataDir+'mapdef.txt');
349 e_LogWritefln('found local "%smapdef.txt"', [DataDir]);
350 except
351 st := nil;
352 end;
354 if (st = nil) then
355 begin
356 WAD := TWADFile.Create();
357 if not WAD.ReadFile(GameWAD) then
358 begin
359 //raise Exception.Create('cannot load "game.wad"');
360 st := nil;
361 end
362 else
363 begin
364 st := WAD.openFileStream('mapdef.txt');
365 end;
366 end;
368 try
369 if (st = nil) then
370 begin
371 //raise Exception.Create('cannot open "mapdef.txt"');
372 e_LogWriteln('using default "mapdef.txt"...');
373 pr := TStrTextParser.Create(defaultMapDef);
374 end
375 else
376 begin
377 pr := TFileTextParser.Create(st);
378 end;
379 except on e: Exception do
380 begin
381 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
382 raise;
383 end;
384 end;
386 try
387 dfmapdef := TDynMapDef.Create(pr);
388 except
389 on e: TDynParseException do
390 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
391 on e: Exception do
392 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
393 end;
395 st.Free();
396 WAD.Free();
397 end;
400 // ////////////////////////////////////////////////////////////////////////// //
401 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
402 var
403 wst: TSFSMemoryChunkStream = nil;
404 begin
405 result := nil;
406 if (dataLen < 4) then exit;
408 if (dfmapdef = nil) then writeln('need to load mapdef');
409 loadMapDefinition();
410 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
412 wst := TSFSMemoryChunkStream.Create(data, dataLen);
413 try
414 result := dfmapdef.parseMap(wst);
415 except
416 on e: TDynParseException do
417 begin
418 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
419 wst.Free();
420 result := nil;
421 exit;
422 end;
423 on e: Exception do
424 begin
425 e_LogWritefln('ERROR: %s', [e.message]);
426 wst.Free();
427 result := nil;
428 exit;
429 end;
430 end;
432 //e_LogWriteln('map parsed.');
433 end;
436 // ////////////////////////////////////////////////////////////////////////// //
437 var
438 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
439 NNF_PureExt: String; // extension postfix
440 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
441 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
444 function g_Texture_NumNameFindStart(name: String): Boolean;
445 var
446 i, j: Integer;
448 begin
449 Result := False;
450 NNF_PureName := '';
451 NNF_PureExt := '';
452 NNF_FirstNum := -1;
453 NNF_CurrentNum := -1;
455 for i := Length(name) downto 1 do
456 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
457 begin
458 if i = Length(name) then
459 begin // Íåò öèôð â êîíöå ñòðîêè
460 Exit;
461 end
462 else
463 begin
464 j := i + 1;
465 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
466 NNF_PureName := Copy(name, 1, i);
467 NNF_PureExt := Copy(name, j);
468 name := Copy(name, i + 1, j - i - 1);
469 Break;
470 end;
471 end;
473 // Íå ïåðåâåñòè â ÷èñëî:
474 if not TryStrToInt(name, NNF_FirstNum) then
475 Exit;
477 NNF_CurrentNum := 0;
479 Result := True;
480 end;
483 function g_Texture_NumNameFindNext(var newName: String): Byte;
484 begin
485 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
486 begin
487 newName := '';
488 Result := NNF_NO_NAME;
489 Exit;
490 end;
492 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
494 if NNF_CurrentNum < NNF_FirstNum then
495 Result := NNF_NAME_BEFORE
496 else
497 if NNF_CurrentNum > NNF_FirstNum then
498 Result := NNF_NAME_AFTER
499 else
500 Result := NNF_NAME_EQUALS;
502 Inc(NNF_CurrentNum);
503 end;
506 // ////////////////////////////////////////////////////////////////////////// //
507 function panelTypeToTag (panelType: Word): Integer;
508 begin
509 case panelType of
510 PANEL_WALL: result := GridTagWall; // gWalls
511 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
512 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
513 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
514 PANEL_WATER: result := GridTagWater; // gWater
515 PANEL_ACID1: result := GridTagAcid1; // gAcid1
516 PANEL_ACID2: result := GridTagAcid2; // gAcid2
517 PANEL_STEP: result := GridTagStep; // gSteps
518 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
519 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
520 else result := GridTagInvalid;
521 end;
522 end;
525 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
526 begin
527 if (a.tag < b.tag) then begin result := true; exit; end;
528 if (a.tag > b.tag) then begin result := false; exit; end;
529 result := (a.arrIdx < b.arrIdx);
530 end;
532 procedure dplClear ();
533 begin
534 if (gDrawPanelList = nil) then gDrawPanelList := TBinHeapPanelDraw.Create() else gDrawPanelList.clear();
535 end;
538 var
539 Textures: TLevelTextureArray = nil;
540 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
541 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
542 RespawnPoints: array of TRespawnPoint;
543 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
544 //DOMFlagPoints: Array of TFlagPoint;
547 procedure g_Map_ProfilersBegin ();
548 begin
549 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
550 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
551 // create sections
552 if g_profile_collision and (profMapCollision <> nil) then
553 begin
554 profMapCollision.sectionBegin('*solids');
555 profMapCollision.sectionEnd();
556 profMapCollision.sectionBegin('liquids');
557 profMapCollision.sectionEnd();
558 end;
559 end;
561 procedure g_Map_ProfilersEnd ();
562 begin
563 if (profMapCollision <> nil) then profMapCollision.mainEnd();
564 end;
567 // wall index in `gWalls` or -1
568 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
569 var
570 ex, ey: Integer;
571 begin
572 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
573 if (result <> nil) then
574 begin
575 if (hitx <> nil) then hitx^ := ex;
576 if (hity <> nil) then hity^ := ey;
577 end
578 else
579 begin
580 if (hitx <> nil) then hitx^ := x1;
581 if (hity <> nil) then hity^ := y1;
582 end;
583 end;
585 // returns panel or nil
586 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
587 var
588 ex, ey: Integer;
589 begin
590 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
591 if (result <> nil) then
592 begin
593 if (hitx <> nil) then hitx^ := ex;
594 if (hity <> nil) then hity^ := ey;
595 end
596 else
597 begin
598 if (hitx <> nil) then hitx^ := x1;
599 if (hity <> nil) then hity^ := y1;
600 end;
601 end;
604 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
605 begin
606 if ((pan.tag and GridTagLift) <> 0) then
607 begin
608 // stop if the lift of the right type
609 result :=
610 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
611 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
612 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
613 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
614 exit;
615 end;
616 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
617 end;
619 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
620 var
621 tagmask: Integer = 0;
622 mwit: PPanel;
623 it: TPanelGrid.Iter;
624 begin
625 result := false;
627 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
628 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
629 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
630 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
631 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
632 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
633 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
635 if (tagmask = 0) then exit;// just in case
637 if ((tagmask and GridTagLift) <> 0) then
638 begin
639 // slow
640 it := mapGrid.forEachAtPoint(x, y, tagmask);
641 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
642 end
643 else
644 begin
645 // fast
646 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
647 result := (it.length <> 0); // firsthit
648 end;
649 it.release();
650 end;
653 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
654 var
655 it: TPanelGrid.Iter;
656 begin
657 result := nil;
658 if (tagmask = 0) then exit;
659 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
660 if (it.length <> 0) then result := it.first^;
661 it.release();
662 end;
665 function g_Map_IsSpecialTexture(Texture: String): Boolean;
666 begin
667 Result := (Texture = TEXTURE_NAME_WATER) or
668 (Texture = TEXTURE_NAME_ACID1) or
669 (Texture = TEXTURE_NAME_ACID2);
670 end;
672 procedure CreateDoorMap();
673 var
674 PanelArray: Array of record
675 X, Y: Integer;
676 Width, Height: Word;
677 Active: Boolean;
678 PanelID: DWORD;
679 end;
680 a, b, c, m, i, len: Integer;
681 ok: Boolean;
682 begin
683 if gWalls = nil then
684 Exit;
686 i := 0;
687 len := 128;
688 SetLength(PanelArray, len);
690 for a := 0 to High(gWalls) do
691 if gWalls[a].Door then
692 begin
693 PanelArray[i].X := gWalls[a].X;
694 PanelArray[i].Y := gWalls[a].Y;
695 PanelArray[i].Width := gWalls[a].Width;
696 PanelArray[i].Height := gWalls[a].Height;
697 PanelArray[i].Active := True;
698 PanelArray[i].PanelID := a;
700 i := i + 1;
701 if i = len then
702 begin
703 len := len + 128;
704 SetLength(PanelArray, len);
705 end;
706 end;
708 // Íåò äâåðåé:
709 if i = 0 then
710 begin
711 PanelArray := nil;
712 Exit;
713 end;
715 SetLength(gDoorMap, 0);
717 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
719 for a := 0 to i-1 do
720 if PanelArray[a].Active then
721 begin
722 PanelArray[a].Active := False;
723 m := Length(gDoorMap);
724 SetLength(gDoorMap, m+1);
725 SetLength(gDoorMap[m], 1);
726 gDoorMap[m, 0] := PanelArray[a].PanelID;
727 ok := True;
729 while ok do
730 begin
731 ok := False;
733 for b := 0 to i-1 do
734 if PanelArray[b].Active then
735 for c := 0 to High(gDoorMap[m]) do
736 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
737 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
738 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
739 PanelArray[b].Width, PanelArray[b].Height,
740 gWalls[gDoorMap[m, c]].X,
741 gWalls[gDoorMap[m, c]].Y,
742 gWalls[gDoorMap[m, c]].Width,
743 gWalls[gDoorMap[m, c]].Height) then
744 begin
745 PanelArray[b].Active := False;
746 SetLength(gDoorMap[m],
747 Length(gDoorMap[m])+1);
748 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
749 ok := True;
750 Break;
751 end;
752 end;
754 g_Game_StepLoading();
755 end;
757 PanelArray := nil;
758 end;
760 procedure CreateLiftMap();
761 var
762 PanelArray: Array of record
763 X, Y: Integer;
764 Width, Height: Word;
765 Active: Boolean;
766 end;
767 a, b, c, len, i, j: Integer;
768 ok: Boolean;
769 begin
770 if gLifts = nil then
771 Exit;
773 len := Length(gLifts);
774 SetLength(PanelArray, len);
776 for a := 0 to len-1 do
777 begin
778 PanelArray[a].X := gLifts[a].X;
779 PanelArray[a].Y := gLifts[a].Y;
780 PanelArray[a].Width := gLifts[a].Width;
781 PanelArray[a].Height := gLifts[a].Height;
782 PanelArray[a].Active := True;
783 end;
785 SetLength(gLiftMap, len);
786 i := 0;
788 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
790 for a := 0 to len-1 do
791 if PanelArray[a].Active then
792 begin
793 PanelArray[a].Active := False;
794 SetLength(gLiftMap[i], 32);
795 j := 0;
796 gLiftMap[i, j] := a;
797 ok := True;
799 while ok do
800 begin
801 ok := False;
802 for b := 0 to len-1 do
803 if PanelArray[b].Active then
804 for c := 0 to j do
805 if g_CollideAround(PanelArray[b].X,
806 PanelArray[b].Y,
807 PanelArray[b].Width,
808 PanelArray[b].Height,
809 PanelArray[gLiftMap[i, c]].X,
810 PanelArray[gLiftMap[i, c]].Y,
811 PanelArray[gLiftMap[i, c]].Width,
812 PanelArray[gLiftMap[i, c]].Height) then
813 begin
814 PanelArray[b].Active := False;
815 j := j+1;
816 if j > High(gLiftMap[i]) then
817 SetLength(gLiftMap[i],
818 Length(gLiftMap[i])+32);
820 gLiftMap[i, j] := b;
821 ok := True;
823 Break;
824 end;
825 end;
827 SetLength(gLiftMap[i], j+1);
828 i := i+1;
830 g_Game_StepLoading();
831 end;
833 SetLength(gLiftMap, i);
835 PanelArray := nil;
836 end;
838 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
839 var
840 len: Integer;
841 panels: ^TPanelArray;
842 pan: TPanel;
843 pguid: Integer;
844 begin
845 Result := -1;
847 case PanelRec.PanelType of
848 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
849 PANEL_BACK: panels := @gRenderBackgrounds;
850 PANEL_FORE: panels := @gRenderForegrounds;
851 PANEL_WATER: panels := @gWater;
852 PANEL_ACID1: panels := @gAcid1;
853 PANEL_ACID2: panels := @gAcid2;
854 PANEL_STEP: panels := @gSteps;
855 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
856 PANEL_BLOCKMON: panels := @gBlockMon;
857 else exit;
858 end;
860 len := Length(panels^);
861 SetLength(panels^, len+1);
863 pguid := Length(panByGUID);
864 SetLength(panByGUID, pguid+1); //FIXME!
865 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
866 assert(pguid >= 0);
867 assert(pguid < Length(panByGUID));
868 panByGUID[pguid] := pan;
869 panels^[len] := pan;
870 pan.arrIdx := len;
871 pan.proxyId := -1;
872 pan.tag := panelTypeToTag(PanelRec.PanelType);
874 PanelRec.user['panel_guid'] := pguid;
876 //result := len;
877 result := pguid;
878 end;
881 function CreateNullTexture(RecName: String): Integer;
882 begin
883 RecName := toLowerCase1251(RecName);
884 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
885 if TextNameHash.get(RecName, result) then exit; // i found her!
887 SetLength(Textures, Length(Textures)+1);
888 result := High(Textures);
890 with Textures[High(Textures)] do
891 begin
892 TextureName := RecName;
893 Width := 1;
894 Height := 1;
895 Anim := False;
896 TextureID := LongWord(TEXTURE_NONE);
897 end;
899 TextNameHash.put(RecName, result);
900 end;
903 function GetReplacementWad (WadName: AnsiString): AnsiString;
904 begin
905 if (length(WadName) = 0) then
906 begin
907 result := '';
908 end
909 else
910 begin
911 //e_LogWritefln('GetReplacementWad: 000: old=%s', [WadName]);
912 result := g_Res_FindReplacementWad(WadName);
913 //e_LogWritefln('GetReplacementWad: 001: old=%s; new=%s', [WadName, result]);
914 if (result = WadName) then
915 begin
916 result := GameDir+'/wads/'+result;
917 //e_LogWritefln('GetReplacementWad: 002: old=%s; new=%s', [WadName, result]);
918 end;
919 end;
920 end;
923 function CreateTexture(RecName: AnsiString; Map: string; log: Boolean): Integer;
924 var
925 WAD: TWADFile;
926 TextureData: Pointer;
927 WADName: String;
928 a, ResLength: Integer;
929 begin
930 RecName := toLowerCase1251(RecName);
931 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
932 if TextNameHash.get(RecName, result) then
933 begin
934 // i found her!
935 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
936 exit;
937 end;
939 Result := -1;
941 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
944 if Textures <> nil then
945 begin
946 for a := 0 to High(Textures) do
947 begin
948 if (Textures[a].TextureName = RecName) then
949 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
950 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
951 Result := a;
952 Exit;
953 end;
954 end;
955 end;
958 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
959 if (RecName = TEXTURE_NAME_WATER) or
960 (RecName = TEXTURE_NAME_ACID1) or
961 (RecName = TEXTURE_NAME_ACID2) then
962 begin
963 SetLength(Textures, Length(Textures)+1);
965 with Textures[High(Textures)] do
966 begin
967 TextureName := RecName;
968 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
969 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
970 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
972 Anim := False;
973 end;
975 result := High(Textures);
976 TextNameHash.put(RecName, result);
977 Exit;
978 end;
980 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
981 WADName := GetReplacementWad(g_ExtractWadName(RecName));
982 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
984 WAD := TWADFile.Create();
985 WAD.ReadFile(WADName);
987 //txname := RecName;
989 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
990 begin
991 FreeMem(TextureData);
992 RecName := 'COMMON\ALIEN';
993 end;
996 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
997 begin
998 SetLength(Textures, Length(Textures)+1);
999 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
1000 begin
1001 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1002 SetLength(Textures, Length(Textures)-1);
1003 result := -1;
1004 Exit;
1005 end;
1006 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1007 FreeMem(TextureData);
1008 Textures[High(Textures)].TextureName := RecName;
1009 Textures[High(Textures)].Anim := False;
1011 result := High(Textures);
1012 TextNameHash.put(RecName, result);
1013 end
1014 else // Íåò òàêîãî ðåóñðñà â WAD'å
1015 begin
1016 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1017 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1018 if log and (not BadTextNameHash.get(RecName, a)) then
1019 begin
1020 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1021 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1022 end;
1023 BadTextNameHash.put(RecName, -1);
1024 end;
1026 WAD.Free();
1027 end;
1030 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1031 var
1032 WAD: TWADFile;
1033 TextureWAD: PChar = nil;
1034 TextData: Pointer = nil;
1035 TextureData: Pointer = nil;
1036 cfg: TConfig = nil;
1037 WADName: String;
1038 ResLength: Integer;
1039 TextureResource: String;
1040 _width, _height, _framecount, _speed: Integer;
1041 _backanimation: Boolean;
1042 //imgfmt: string;
1043 ia: TDynImageDataArray = nil;
1044 f, c, frdelay, frloop: Integer;
1045 begin
1046 RecName := toLowerCase1251(RecName);
1047 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1048 if TextNameHash.get(RecName, result) then
1049 begin
1050 // i found her!
1051 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1052 exit;
1053 end;
1055 result := -1;
1057 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1059 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1060 if BadTextNameHash.get(RecName, f) then
1061 begin
1062 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1063 exit;
1064 end;
1066 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1067 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1068 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1070 WAD := TWADFile.Create();
1071 try
1072 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1074 WAD.ReadFile(WADName);
1076 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1077 begin
1078 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1079 if log and (not BadTextNameHash.get(RecName, f)) then
1080 begin
1081 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1082 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1083 end;
1084 BadTextNameHash.put(RecName, -1);
1085 exit;
1086 end;
1088 {TEST
1089 if WADName = Map then
1090 begin
1091 //FreeMem(TextureWAD);
1092 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1093 end;
1096 WAD.FreeWAD();
1098 if ResLength < 6 then
1099 begin
1100 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1101 BadTextNameHash.put(RecName, -1);
1102 exit;
1103 end;
1105 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1106 if isWadData(TextureWAD, ResLength) then
1107 begin
1108 // íåò, ýòî ñóïåðìåí!
1109 if not WAD.ReadMemory(TextureWAD, ResLength) then
1110 begin
1111 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1112 BadTextNameHash.put(RecName, -1);
1113 exit;
1114 end;
1116 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1117 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1118 begin
1119 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1120 BadTextNameHash.put(RecName, -1);
1121 exit;
1122 end;
1124 cfg := TConfig.CreateMem(TextData, ResLength);
1126 TextureResource := cfg.ReadStr('', 'resource', '');
1127 if TextureResource = '' then
1128 begin
1129 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1130 BadTextNameHash.put(RecName, -1);
1131 exit;
1132 end;
1134 _width := cfg.ReadInt('', 'framewidth', 0);
1135 _height := cfg.ReadInt('', 'frameheight', 0);
1136 _framecount := cfg.ReadInt('', 'framecount', 0);
1137 _speed := cfg.ReadInt('', 'waitcount', 0);
1138 _backanimation := cfg.ReadBool('', 'backanimation', False);
1140 cfg.Free();
1141 cfg := nil;
1143 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1144 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1145 begin
1146 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1147 BadTextNameHash.put(RecName, -1);
1148 exit;
1149 end;
1151 WAD.Free();
1152 WAD := nil;
1154 SetLength(Textures, Length(Textures)+1);
1155 with Textures[High(Textures)] do
1156 begin
1157 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1158 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1159 begin
1160 TextureName := RecName;
1161 Width := _width;
1162 Height := _height;
1163 Anim := True;
1164 FramesCount := _framecount;
1165 Speed := _speed;
1166 result := High(Textures);
1167 TextNameHash.put(RecName, result);
1168 end
1169 else
1170 begin
1171 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1172 if log and (not BadTextNameHash.get(RecName, f)) then
1173 begin
1174 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1175 end;
1176 BadTextNameHash.put(RecName, -1);
1177 end;
1178 end;
1179 end
1180 else
1181 begin
1182 // try animated image
1184 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1185 if length(imgfmt) = 0 then
1186 begin
1187 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1188 exit;
1189 end;
1191 GlobalMetadata.ClearMetaItems();
1192 GlobalMetadata.ClearMetaItemsForSaving();
1193 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1194 begin
1195 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1196 BadTextNameHash.put(RecName, -1);
1197 exit;
1198 end;
1199 if length(ia) = 0 then
1200 begin
1201 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1202 BadTextNameHash.put(RecName, -1);
1203 exit;
1204 end;
1206 WAD.Free();
1207 WAD := nil;
1209 _width := ia[0].width;
1210 _height := ia[0].height;
1211 _framecount := length(ia);
1212 _speed := 1;
1213 _backanimation := false;
1214 frdelay := -1;
1215 frloop := -666;
1216 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1217 begin
1218 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1219 try
1220 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1221 frdelay := f;
1222 if f < 0 then f := 0;
1223 // rounding ;-)
1224 c := f mod 28;
1225 if c < 13 then c := 0 else c := 1;
1226 f := (f div 28)+c;
1227 if f < 1 then f := 1 else if f > 255 then f := 255;
1228 _speed := f;
1229 except
1230 end;
1231 end;
1232 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1233 begin
1234 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1235 try
1236 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1237 frloop := f;
1238 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1239 except
1240 end;
1241 end;
1242 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1243 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1244 f := ord(_backanimation);
1245 e_WriteLog(Format('Animated texture file "%s": %d frames (delay:%d; back:%d; frdelay:%d; frloop:%d), %dx%d', [RecName, length(ia), _speed, f, frdelay, frloop, _width, _height]), TMsgType.Notify);
1247 SetLength(Textures, Length(Textures)+1);
1248 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1249 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1250 begin
1251 Textures[High(Textures)].TextureName := RecName;
1252 Textures[High(Textures)].Width := _width;
1253 Textures[High(Textures)].Height := _height;
1254 Textures[High(Textures)].Anim := True;
1255 Textures[High(Textures)].FramesCount := length(ia);
1256 Textures[High(Textures)].Speed := _speed;
1257 result := High(Textures);
1258 TextNameHash.put(RecName, result);
1259 //writeln(' CREATED!');
1260 end
1261 else
1262 begin
1263 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1264 if log and (not BadTextNameHash.get(RecName, f)) then
1265 begin
1266 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1267 end;
1268 BadTextNameHash.put(RecName, -1);
1269 end;
1270 end;
1271 finally
1272 for f := 0 to High(ia) do FreeImage(ia[f]);
1273 WAD.Free();
1274 cfg.Free();
1275 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1276 if (TextData <> nil) then FreeMem(TextData);
1277 if (TextureData <> nil) then FreeMem(TextureData);
1278 end;
1279 end;
1281 procedure CreateItem(Item: TDynRecord);
1282 begin
1283 if g_Game_IsClient then Exit;
1285 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1286 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1287 Exit;
1289 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1290 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1291 end;
1293 procedure CreateArea(Area: TDynRecord);
1294 var
1295 a: Integer;
1296 id: DWORD = 0;
1297 begin
1298 case Area.AreaType of
1299 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1300 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1301 begin
1302 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1303 with RespawnPoints[High(RespawnPoints)] do
1304 begin
1305 X := Area.X;
1306 Y := Area.Y;
1307 Direction := TDirection(Area.Direction);
1309 case Area.AreaType of
1310 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1311 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1312 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1313 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1314 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1315 end;
1316 end;
1317 end;
1319 AREA_REDFLAG, AREA_BLUEFLAG:
1320 begin
1321 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1323 if FlagPoints[a] <> nil then Exit;
1325 New(FlagPoints[a]);
1327 with FlagPoints[a]^ do
1328 begin
1329 X := Area.X-FLAGRECT.X;
1330 Y := Area.Y-FLAGRECT.Y;
1331 Direction := TDirection(Area.Direction);
1332 end;
1334 with gFlags[a] do
1335 begin
1336 case a of
1337 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1338 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1339 end;
1341 Animation := TAnimation.Create(id, True, 8);
1342 Obj.Rect := FLAGRECT;
1344 g_Map_ResetFlag(a);
1345 end;
1346 end;
1348 AREA_DOMFLAG:
1349 begin
1350 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1351 with DOMFlagPoints[High(DOMFlagPoints)] do
1352 begin
1353 X := Area.X;
1354 Y := Area.Y;
1355 Direction := TDirection(Area.Direction);
1356 end;
1358 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1359 end;
1360 end;
1361 end;
1363 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1364 var
1365 _trigger: TTrigger;
1366 tp: TPanel;
1367 begin
1368 result := -1;
1369 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1371 with _trigger do
1372 begin
1373 mapId := Trigger.id;
1374 mapIndex := amapIdx;
1375 X := Trigger.X;
1376 Y := Trigger.Y;
1377 Width := Trigger.Width;
1378 Height := Trigger.Height;
1379 Enabled := Trigger.Enabled;
1380 TexturePanelGUID := atpanid;
1381 TriggerType := Trigger.TriggerType;
1382 ActivateType := Trigger.ActivateType;
1383 Keys := Trigger.Keys;
1384 trigPanelGUID := atrigpanid;
1385 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1386 if TexturePanelGUID <> -1 then
1387 begin
1388 tp := g_Map_PanelByGUID(TexturePanelGUID);
1389 if (tp <> nil) then tp.hasTexTrigger := True;
1390 end;
1391 end;
1393 result := Integer(g_Triggers_Create(_trigger, Trigger));
1394 end;
1396 procedure CreateMonster(monster: TDynRecord);
1397 var
1398 a: Integer;
1399 mon: TMonster;
1400 begin
1401 if g_Game_IsClient then Exit;
1403 if (gGameSettings.GameType = GT_SINGLE)
1404 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1405 begin
1406 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1408 if gTriggers <> nil then
1409 begin
1410 for a := 0 to High(gTriggers) do
1411 begin
1412 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1413 begin
1414 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1415 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1416 end;
1417 end;
1418 end;
1420 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1421 end;
1422 end;
1424 procedure g_Map_ReAdd_DieTriggers();
1426 function monsDieTrig (mon: TMonster): Boolean;
1427 var
1428 a: Integer;
1429 //tw: TStrTextWriter;
1430 begin
1431 result := false; // don't stop
1432 mon.ClearTriggers();
1433 for a := 0 to High(gTriggers) do
1434 begin
1435 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1436 begin
1437 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1439 tw := TStrTextWriter.Create();
1440 try
1441 gTriggers[a].trigData.writeTo(tw);
1442 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1443 finally
1444 tw.Free();
1445 end;
1447 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1448 end;
1449 end;
1450 end;
1452 begin
1453 if g_Game_IsClient then Exit;
1455 g_Mons_ForEach(monsDieTrig);
1456 end;
1458 function extractWadName(resourceName: string): string;
1459 var
1460 posN: Integer;
1461 begin
1462 posN := Pos(':', resourceName);
1463 if posN > 0 then
1464 Result:= Copy(resourceName, 0, posN-1)
1465 else
1466 Result := '';
1467 end;
1470 procedure addResToExternalResList (res: AnsiString);
1471 var
1472 uname: AnsiString;
1473 f: Integer;
1474 fi: TDiskFileInfo;
1475 begin
1476 if g_Game_IsClient or not g_Game_IsNet then exit;
1477 if (length(res) = 0) then exit; // map wad
1478 res := extractWadName(res);
1479 if (length(res) = 0) then exit; // map wad
1480 uname := toLowerCase1251(res);
1481 // do not add duplicates
1482 for f := 0 to High(gExternalResources) do
1483 begin
1484 if (gExternalResources[f].userName = uname) then exit;
1485 end;
1486 // add new resource
1487 fi.userName := uname;
1488 if (not GetDiskFileInfo(GameDir+'/wads/'+res, fi)) then
1489 begin
1490 fi.tag := -1;
1491 end
1492 else
1493 begin
1494 fi.tag := 0; // non-zero means "cannot caclucate hash"
1495 try
1496 fi.hash := MD5File(fi.diskName);
1497 except
1498 fi.tag := -1;
1499 end;
1500 end;
1501 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
1502 SetLength(gExternalResources, length(gExternalResources)+1);
1503 gExternalResources[High(gExternalResources)] := fi;
1504 end;
1507 procedure compactExtResList ();
1508 var
1509 src, dest: Integer;
1510 begin
1511 src := 0;
1512 dest := 0;
1513 for src := 0 to High(gExternalResources) do
1514 begin
1515 if (gExternalResources[src].tag = 0) then
1516 begin
1517 // copy it
1518 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
1519 Inc(dest);
1520 end;
1521 end;
1522 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
1523 end;
1526 procedure generateExternalResourcesList (map: TDynRecord);
1527 begin
1528 SetLength(gExternalResources, 0);
1529 addResToExternalResList(map.MusicName);
1530 addResToExternalResList(map.SkyName);
1531 end;
1534 procedure mapCreateGrid ();
1535 var
1536 mapX0: Integer = $3fffffff;
1537 mapY0: Integer = $3fffffff;
1538 mapX1: Integer = -$3fffffff;
1539 mapY1: Integer = -$3fffffff;
1541 procedure calcBoundingBox (constref panels: TPanelArray);
1542 var
1543 idx: Integer;
1544 pan: TPanel;
1545 begin
1546 for idx := 0 to High(panels) do
1547 begin
1548 pan := panels[idx];
1549 if not pan.visvalid then continue;
1550 if (pan.Width < 1) or (pan.Height < 1) then continue;
1551 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1552 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1553 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1554 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1555 end;
1556 end;
1558 procedure addPanelsToGrid (constref panels: TPanelArray);
1559 var
1560 idx: Integer;
1561 pan: TPanel;
1562 newtag: Integer;
1563 begin
1564 //tag := panelTypeToTag(tag);
1565 for idx := 0 to High(panels) do
1566 begin
1567 pan := panels[idx];
1568 if not pan.visvalid then continue;
1569 if (pan.proxyId <> -1) then
1570 begin
1571 {$IF DEFINED(D2F_DEBUG)}
1572 e_WriteLog(Format('DUPLICATE wall #%d(%d) enabled (%d); type:%08x', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.PanelType]), TMsgType.Notify);
1573 {$ENDIF}
1574 continue;
1575 end;
1576 case pan.PanelType of
1577 PANEL_WALL: newtag := GridTagWall;
1578 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1579 PANEL_BACK: newtag := GridTagBack;
1580 PANEL_FORE: newtag := GridTagFore;
1581 PANEL_WATER: newtag := GridTagWater;
1582 PANEL_ACID1: newtag := GridTagAcid1;
1583 PANEL_ACID2: newtag := GridTagAcid2;
1584 PANEL_STEP: newtag := GridTagStep;
1585 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1586 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1587 else continue; // oops
1588 end;
1589 pan.tag := newtag;
1591 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1592 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1593 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1594 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1596 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1597 begin
1598 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1599 end;
1601 {$ENDIF}
1602 end;
1603 end;
1605 begin
1606 mapGrid.Free();
1607 mapGrid := nil;
1609 calcBoundingBox(gWalls);
1610 calcBoundingBox(gRenderBackgrounds);
1611 calcBoundingBox(gRenderForegrounds);
1612 calcBoundingBox(gWater);
1613 calcBoundingBox(gAcid1);
1614 calcBoundingBox(gAcid2);
1615 calcBoundingBox(gSteps);
1616 calcBoundingBox(gLifts);
1617 calcBoundingBox(gBlockMon);
1619 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1621 if (mapX0 > 0) then mapX0 := 0;
1622 if (mapY0 > 0) then mapY0 := 0;
1624 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1625 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1627 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1628 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1630 addPanelsToGrid(gWalls);
1631 addPanelsToGrid(gRenderBackgrounds);
1632 addPanelsToGrid(gRenderForegrounds);
1633 addPanelsToGrid(gWater);
1634 addPanelsToGrid(gAcid1);
1635 addPanelsToGrid(gAcid2);
1636 addPanelsToGrid(gSteps);
1637 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1638 addPanelsToGrid(gBlockMon);
1640 mapGrid.dumpStats();
1642 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1643 end;
1646 function g_Map_Load(Res: String): Boolean;
1647 const
1648 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1649 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1650 type
1651 PTRec = ^TTRec;
1652 TTRec = record
1653 //TexturePanel: Integer;
1654 tnum: Integer;
1655 id: Integer;
1656 trigrec: TDynRecord;
1657 // texture pane;
1658 texPanelIdx: Integer;
1659 texPanel: TDynRecord;
1660 // "action" panel
1661 actPanelIdx: Integer;
1662 actPanel: TDynRecord;
1663 end;
1664 var
1665 WAD, TestWAD: TWADFile;
1666 //mapReader: TDynRecord = nil;
1667 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1668 panels: TDynField = nil; //TPanelsRec1Array;
1669 items: TDynField = nil; //TItemsRec1Array;
1670 monsters: TDynField = nil; //TMonsterRec1Array;
1671 areas: TDynField = nil; //TAreasRec1Array;
1672 triggers: TDynField = nil; //TTriggersRec1Array;
1673 b, c, k: Integer;
1674 PanelID: DWORD;
1675 AddTextures: TAddTextureArray;
1676 TriggersTable: array of TTRec;
1677 FileName, mapResName, TexName, s: AnsiString;
1678 Data: Pointer;
1679 Len: Integer;
1680 ok, isAnim: Boolean;
1681 CurTex, ntn: Integer;
1682 rec, texrec: TDynRecord;
1683 pttit: PTRec;
1684 pannum, trignum, cnt, tgpid: Integer;
1685 stt: UInt64;
1686 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1687 //moveActive: Boolean;
1688 pan: TPanel;
1689 mapOk: Boolean = false;
1690 usedTextures: THashStrInt = nil; // key: mapTextureList
1691 begin
1692 mapGrid.Free();
1693 mapGrid := nil;
1694 TestWAD := nil;
1695 Data := nil;
1697 //gCurrentMap.Free();
1698 //gCurrentMap := nil;
1700 panByGUID := nil;
1702 Result := False;
1703 gMapInfo.Map := Res;
1704 TriggersTable := nil;
1705 //mapReader := nil;
1707 sfsGCDisable(); // temporary disable removing of temporary volumes
1708 try
1709 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1710 if (gCurrentMap = nil) then
1711 begin
1712 FileName := g_ExtractWadName(Res);
1713 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1714 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1716 WAD := TWADFile.Create();
1717 if not WAD.ReadFile(FileName) then
1718 begin
1719 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1720 WAD.Free();
1721 Exit;
1722 end;
1724 if gTestMap <> '' then
1725 begin
1726 s := g_ExtractWadName(gTestMap);
1727 TestWAD := TWADFile.Create();
1728 if not TestWAD.ReadFile(s) then
1729 begin
1730 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1731 TestWAD.Free();
1732 TestWAD := nil;
1733 end;
1734 end;
1736 if TestWAD <> nil then
1737 begin
1738 mapResName := g_ExtractFileName(gTestMap);
1739 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1740 begin
1741 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1742 Data := nil;
1743 end else
1744 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1745 TestWAD.Free();
1746 TestWAD := nil;
1747 end;
1749 if Data = nil then
1750 begin
1751 //k8: why loader ignores path here?
1752 mapResName := g_ExtractFileName(Res);
1753 if not WAD.GetMapResource(mapResName, Data, Len) then
1754 begin
1755 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1756 WAD.Free();
1757 Exit;
1758 end;
1759 end;
1761 WAD.Free();
1763 if (Len < 4) then
1764 begin
1765 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1766 FreeMem(Data);
1767 exit;
1768 end;
1770 // Çàãðóçêà êàðòû:
1771 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1772 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1774 stt := getTimeMicro();
1776 try
1777 gCurrentMap := g_Map_ParseMap(Data, Len);
1778 except
1779 gCurrentMap.Free();
1780 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1781 FreeMem(Data);
1782 gCurrentMapFileName := '';
1783 Exit;
1784 end;
1786 FreeMem(Data);
1788 if (gCurrentMap = nil) then
1789 begin
1790 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1791 gCurrentMapFileName := '';
1792 exit;
1793 end;
1794 end
1795 else
1796 begin
1797 stt := getTimeMicro();
1798 end;
1800 //gCurrentMap := mapReader;
1802 generateExternalResourcesList(gCurrentMap);
1803 mapTextureList := gCurrentMap['texture'];
1804 // get all other lists here too
1805 panels := gCurrentMap['panel'];
1806 triggers := gCurrentMap['trigger'];
1807 items := gCurrentMap['item'];
1808 areas := gCurrentMap['area'];
1809 monsters := gCurrentMap['monster'];
1811 // Çàãðóçêà îïèñàíèÿ êàðòû:
1812 e_WriteLog(' Reading map info...', TMsgType.Notify);
1813 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1815 with gMapInfo do
1816 begin
1817 Name := gCurrentMap.MapName;
1818 Description := gCurrentMap.MapDesc;
1819 Author := gCurrentMap.MapAuthor;
1820 MusicName := gCurrentMap.MusicName;
1821 SkyName := gCurrentMap.SkyName;
1822 Height := gCurrentMap.Height;
1823 Width := gCurrentMap.Width;
1824 end;
1826 // Çàãðóçêà òåêñòóð:
1827 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1828 // Äîáàâëåíèå òåêñòóð â Textures[]:
1829 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1830 begin
1831 e_WriteLog(' Loading textures:', TMsgType.Notify);
1832 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1834 // find used textures
1835 usedTextures := THashStrInt.Create();
1836 try
1837 if (panels <> nil) and (panels.count > 0) then
1838 begin
1839 for rec in panels do
1840 begin
1841 texrec := rec.TextureRec;
1842 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1843 end;
1844 end;
1846 cnt := -1;
1847 for rec in mapTextureList do
1848 begin
1849 Inc(cnt);
1850 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1851 begin
1852 rec.tagInt := -1; // just in case
1853 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1854 end
1855 else
1856 begin
1857 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1858 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1859 {$ENDIF}
1860 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1861 if rec.Anim then
1862 begin
1863 // Àíèìèðîâàííàÿ òåêñòóðà
1864 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1865 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1866 end
1867 else
1868 begin
1869 // Îáû÷íàÿ òåêñòóðà
1870 ntn := CreateTexture(rec.Resource, FileName, True);
1871 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1872 end;
1873 if (ntn < 0) then
1874 begin
1875 ntn := CreateNullTexture(rec.Resource);
1876 end
1877 else
1878 begin
1879 addResToExternalResList(rec.Resource);
1880 end;
1882 rec.tagInt := ntn; // remember texture number
1883 end;
1884 g_Game_StepLoading();
1885 end;
1886 finally
1887 usedTextures.Free();
1888 end;
1890 // set panel tagInt to texture index
1891 if (panels <> nil) then
1892 begin
1893 for rec in panels do
1894 begin
1895 texrec := rec.TextureRec;
1896 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1897 end;
1898 end;
1899 end;
1902 // Çàãðóçêà òðèããåðîâ
1903 gTriggerClientID := 0;
1904 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1905 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1907 // Çàãðóçêà ïàíåëåé
1908 e_WriteLog(' Loading panels...', TMsgType.Notify);
1909 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1911 // check texture numbers for panels
1912 if (panels <> nil) and (panels.count > 0) then
1913 begin
1914 for rec in panels do
1915 begin
1916 if (rec.tagInt < 0) then
1917 begin
1918 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1919 result := false;
1920 gCurrentMap.Free();
1921 gCurrentMap := nil;
1922 gCurrentMapFileName := '';
1923 exit;
1924 end;
1925 end;
1926 end;
1928 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1929 if (triggers <> nil) and (triggers.count > 0) then
1930 begin
1931 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1932 //SetLength(TriggersTable, triggers.count);
1933 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1935 SetLength(TriggersTable, triggers.count);
1936 trignum := -1;
1937 for rec in triggers do
1938 begin
1939 Inc(trignum);
1940 pttit := @TriggersTable[trignum];
1941 pttit.trigrec := rec;
1942 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1943 pttit.texPanelIdx := -1; // will be fixed later
1944 pttit.texPanel := rec.TexturePanelRec;
1945 // action panel
1946 pttit.actPanelIdx := -1;
1947 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1948 // set flag
1949 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1950 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1951 // update progress
1952 g_Game_StepLoading();
1953 end;
1954 end;
1956 // Ñîçäàåì ïàíåëè
1957 if (panels <> nil) and (panels.count > 0) then
1958 begin
1959 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1960 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1962 pannum := -1;
1963 for rec in panels do
1964 begin
1965 Inc(pannum);
1966 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1967 texrec := nil;
1968 SetLength(AddTextures, 0);
1969 CurTex := -1;
1970 ok := false;
1972 if (mapTextureList <> nil) then
1973 begin
1974 texrec := rec.TextureRec;
1975 ok := (texrec <> nil);
1976 end;
1978 if ok then
1979 begin
1980 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1981 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1982 ok := false;
1983 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1984 begin
1985 if rec.userPanelTrigRef then
1986 begin
1987 // e_LogWritefln('trigref for panel %s', [pannum]);
1988 ok := True;
1989 end;
1990 end;
1991 end;
1993 if ok then
1994 begin
1995 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1996 s := texrec.Resource;
1998 // Ñïåö-òåêñòóðû çàïðåùåíû
1999 if g_Map_IsSpecialTexture(s) then
2000 begin
2001 ok := false
2002 end
2003 else
2004 begin
2005 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
2006 ok := g_Texture_NumNameFindStart(s);
2007 end;
2009 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
2010 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
2011 if ok then
2012 begin
2013 k := NNF_NAME_BEFORE;
2014 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
2015 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
2016 begin
2017 k := g_Texture_NumNameFindNext(TexName);
2019 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2020 begin
2021 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2022 if texrec.Anim then
2023 begin
2024 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2025 isAnim := True;
2026 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2027 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2028 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2029 if not ok then
2030 begin
2031 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2032 isAnim := False;
2033 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2034 ok := CreateTexture(TexName, FileName, False) >= 0;
2035 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2036 end;
2037 end
2038 else
2039 begin
2040 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2041 isAnim := False;
2042 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2043 ok := CreateTexture(TexName, FileName, False) >= 0;
2044 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2045 if not ok then
2046 begin
2047 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2048 isAnim := True;
2049 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2050 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2051 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2052 end;
2053 end;
2055 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2056 if ok then
2057 begin
2059 for c := 0 to High(Textures) do
2060 begin
2061 if (Textures[c].TextureName = TexName) then
2062 begin
2063 SetLength(AddTextures, Length(AddTextures)+1);
2064 AddTextures[High(AddTextures)].Texture := c;
2065 AddTextures[High(AddTextures)].Anim := isAnim;
2066 break;
2067 end;
2068 end;
2070 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2071 begin
2072 SetLength(AddTextures, Length(AddTextures)+1);
2073 AddTextures[High(AddTextures)].Texture := c;
2074 AddTextures[High(AddTextures)].Anim := isAnim;
2075 end;
2076 end;
2077 end
2078 else
2079 begin
2080 if k = NNF_NAME_EQUALS then
2081 begin
2082 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2083 SetLength(AddTextures, Length(AddTextures)+1);
2084 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2085 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2086 CurTex := High(AddTextures);
2087 ok := true;
2088 end
2089 else // NNF_NO_NAME
2090 begin
2091 ok := false;
2092 end;
2093 end;
2094 end; // while ok...
2096 ok := true;
2097 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2098 end; // if ok - ññûëàþòñÿ òðèããåðû
2100 if not ok then
2101 begin
2102 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2103 SetLength(AddTextures, 1);
2104 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2105 AddTextures[0].Anim := false;
2106 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2107 CurTex := 0;
2108 end;
2110 //e_WriteLog(Format('panel #%d: TextureNum=%d; ht=%d; ht1=%d; atl=%d', [a, panels[a].TextureNum, High(mapTextureList), High(Textures), High(AddTextures)]), MSG_NOTIFY);
2112 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2114 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2115 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2116 PanelID := CreatePanel(rec, AddTextures, CurTex);
2117 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2118 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2120 // setup lifts
2121 moveSpeed := rec.moveSpeed;
2122 //moveStart := rec.moveStart;
2123 //moveEnd := rec.moveEnd;
2124 //moveActive := rec['move_active'].value;
2125 if not moveSpeed.isZero then
2126 begin
2127 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2128 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2129 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2130 end;
2132 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2134 g_Game_StepLoading();
2135 end;
2136 end;
2138 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2139 for b := 0 to High(TriggersTable) do
2140 begin
2141 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2142 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2143 end;
2145 // create map grid, init other grids (for monsters, for example)
2146 e_WriteLog('Creating map grid', TMsgType.Notify);
2147 mapCreateGrid();
2149 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2150 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2151 begin
2152 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2153 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2154 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2155 trignum := -1;
2156 for rec in triggers do
2157 begin
2158 Inc(trignum);
2159 tgpid := TriggersTable[trignum].actPanelIdx;
2160 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2161 TriggersTable[trignum].tnum := trignum;
2162 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2163 end;
2164 end;
2166 //FIXME: use hashtable!
2167 for pan in panByGUID do
2168 begin
2169 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2170 begin
2171 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2172 end;
2173 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2174 begin
2175 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2176 end;
2177 end;
2179 // Çàãðóçêà ïðåäìåòîâ
2180 e_WriteLog(' Loading items...', TMsgType.Notify);
2181 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2183 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2184 if (items <> nil) and not gLoadGameMode then
2185 begin
2186 e_WriteLog(' Spawning items...', TMsgType.Notify);
2187 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2188 for rec in items do CreateItem(rec);
2189 end;
2191 // Çàãðóçêà îáëàñòåé
2192 e_WriteLog(' Loading areas...', TMsgType.Notify);
2193 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2195 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2196 if areas <> nil then
2197 begin
2198 e_WriteLog(' Creating areas...', TMsgType.Notify);
2199 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2200 for rec in areas do CreateArea(rec);
2201 end;
2203 // Çàãðóçêà ìîíñòðîâ
2204 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2205 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2207 gTotalMonsters := 0;
2209 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2210 if (monsters <> nil) and not gLoadGameMode then
2211 begin
2212 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2213 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2214 for rec in monsters do CreateMonster(rec);
2215 end;
2217 //gCurrentMap := mapReader; // this will be our current map now
2218 gCurrentMapFileName := Res;
2219 //mapReader := nil;
2221 // Çàãðóçêà íåáà
2222 if (gMapInfo.SkyName <> '') then
2223 begin
2224 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2225 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2226 FileName := g_ExtractWadName(gMapInfo.SkyName);
2228 if (FileName <> '') then FileName := GameDir+'/wads/'+FileName else FileName := g_ExtractWadName(Res);
2230 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2231 try
2232 s := FileName+':'+g_ExtractFilePathName(gMapInfo.SkyName);
2233 if g_Texture_CreateWAD(BackID, s) then
2234 begin
2235 g_Game_SetupScreenSize();
2236 end
2237 else
2238 begin
2239 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]));
2240 end;
2241 finally
2242 TEXTUREFILTER := GL_NEAREST;
2243 end;
2244 end;
2246 // Çàãðóçêà ìóçûêè
2247 ok := False;
2248 if gMapInfo.MusicName <> '' then
2249 begin
2250 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2251 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2252 FileName := g_ExtractWadName(gMapInfo.MusicName);
2254 if FileName <> '' then
2255 FileName := GameDir+'/wads/'+FileName
2256 else
2257 begin
2258 FileName := g_ExtractWadName(Res);
2259 end;
2261 s := FileName+':'+g_ExtractFilePathName(gMapInfo.MusicName);
2262 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2263 ok := True
2264 else
2265 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2266 end;
2268 // Îñòàëüíûå óñòàíâêè
2269 CreateDoorMap();
2270 CreateLiftMap();
2272 g_Items_Init();
2273 g_Weapon_Init();
2274 g_Monsters_Init();
2276 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2277 if not gLoadGameMode then g_GFX_Init();
2279 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2280 mapTextureList := nil;
2281 panels := nil;
2282 items := nil;
2283 areas := nil;
2284 triggers := nil;
2285 TriggersTable := nil;
2286 AddTextures := nil;
2288 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2289 if ok and (not gLoadGameMode) then
2290 begin
2291 gMusic.SetByName(gMapInfo.MusicName);
2292 gMusic.Play();
2293 end
2294 else
2295 begin
2296 gMusic.SetByName('');
2297 end;
2299 stt := getTimeMicro()-stt;
2300 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2301 mapOk := true;
2302 finally
2303 sfsGCEnable(); // enable releasing unused volumes
2304 //mapReader.Free();
2305 e_UnpressAllKeys; // why not?
2306 if not mapOk then
2307 begin
2308 gCurrentMap.Free();
2309 gCurrentMap := nil;
2310 gCurrentMapFileName := '';
2311 end;
2312 end;
2314 compactExtResList();
2315 e_WriteLog('Done loading map.', TMsgType.Notify);
2316 Result := True;
2317 end;
2320 function g_Map_GetMapInfo(Res: String): TMapInfo;
2321 var
2322 WAD: TWADFile;
2323 mapReader: TDynRecord;
2324 //Header: TMapHeaderRec_1;
2325 FileName: String;
2326 Data: Pointer;
2327 Len: Integer;
2328 begin
2329 FillChar(Result, SizeOf(Result), 0);
2330 FileName := g_ExtractWadName(Res);
2332 WAD := TWADFile.Create();
2333 if not WAD.ReadFile(FileName) then
2334 begin
2335 WAD.Free();
2336 Exit;
2337 end;
2339 //k8: it ignores path again
2340 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2341 begin
2342 WAD.Free();
2343 Exit;
2344 end;
2346 WAD.Free();
2348 try
2349 mapReader := g_Map_ParseMap(Data, Len);
2350 except
2351 mapReader := nil;
2352 FreeMem(Data);
2353 exit;
2354 end;
2356 FreeMem(Data);
2358 if (mapReader = nil) then exit;
2360 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2361 begin
2362 Result.Name := mapReader.MapName;
2363 Result.Description := mapReader.MapDesc;
2364 Result.Map := Res;
2365 Result.Author := mapReader.MapAuthor;
2366 Result.Height := mapReader.Height;
2367 Result.Width := mapReader.Width;
2368 end
2369 else
2370 begin
2371 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2372 //ZeroMemory(@Header, SizeOf(Header));
2373 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2374 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2375 Result.Map := Res;
2376 Result.Author := '';
2377 Result.Height := 0;
2378 Result.Width := 0;
2379 end;
2381 mapReader.Free();
2382 end;
2384 function g_Map_GetMapsList(WADName: string): SSArray;
2385 var
2386 WAD: TWADFile;
2387 a: Integer;
2388 ResList: SSArray;
2389 begin
2390 Result := nil;
2391 WAD := TWADFile.Create();
2392 if not WAD.ReadFile(WADName) then
2393 begin
2394 WAD.Free();
2395 Exit;
2396 end;
2397 ResList := WAD.GetMapResources();
2398 if ResList <> nil then
2399 begin
2400 for a := 0 to High(ResList) do
2401 begin
2402 SetLength(Result, Length(Result)+1);
2403 Result[High(Result)] := ResList[a];
2404 end;
2405 end;
2406 WAD.Free();
2407 end;
2409 function g_Map_Exist(Res: string): Boolean;
2410 var
2411 WAD: TWADFile;
2412 FileName, mnn: string;
2413 ResList: SSArray;
2414 a: Integer;
2415 begin
2416 Result := False;
2418 FileName := addWadExtension(g_ExtractWadName(Res));
2420 WAD := TWADFile.Create;
2421 if not WAD.ReadFile(FileName) then
2422 begin
2423 WAD.Free();
2424 Exit;
2425 end;
2427 ResList := WAD.GetMapResources();
2428 WAD.Free();
2430 mnn := g_ExtractFileName(Res);
2431 if ResList <> nil then
2432 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2433 begin
2434 Result := True;
2435 Exit;
2436 end;
2437 end;
2439 procedure g_Map_Free(freeTextures: Boolean=true);
2440 var
2441 a: Integer;
2443 procedure FreePanelArray(var panels: TPanelArray);
2444 var
2445 i: Integer;
2447 begin
2448 if panels <> nil then
2449 begin
2450 for i := 0 to High(panels) do
2451 panels[i].Free();
2452 panels := nil;
2453 end;
2454 end;
2456 begin
2457 g_GFX_Free();
2458 g_Weapon_Free();
2459 g_Items_Free();
2460 g_Triggers_Free();
2461 g_Monsters_Free();
2463 RespawnPoints := nil;
2464 if FlagPoints[FLAG_RED] <> nil then
2465 begin
2466 Dispose(FlagPoints[FLAG_RED]);
2467 FlagPoints[FLAG_RED] := nil;
2468 end;
2469 if FlagPoints[FLAG_BLUE] <> nil then
2470 begin
2471 Dispose(FlagPoints[FLAG_BLUE]);
2472 FlagPoints[FLAG_BLUE] := nil;
2473 end;
2474 //DOMFlagPoints := nil;
2476 //gDOMFlags := nil;
2478 if (Length(gCurrentMapFileName) <> 0) then
2479 begin
2480 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2481 end
2482 else
2483 begin
2484 e_LogWritefln('g_Map_Free: no previous map.', []);
2485 end;
2487 if freeTextures then
2488 begin
2489 e_LogWritefln('g_Map_Free: clearing textures...', []);
2490 if (Textures <> nil) then
2491 begin
2492 for a := 0 to High(Textures) do
2493 begin
2494 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2495 begin
2496 if Textures[a].Anim then
2497 begin
2498 g_Frames_DeleteByID(Textures[a].FramesID)
2499 end
2500 else
2501 begin
2502 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2503 begin
2504 e_DeleteTexture(Textures[a].TextureID);
2505 end;
2506 end;
2507 end;
2508 end;
2509 Textures := nil;
2510 end;
2511 TextNameHash.Free();
2512 TextNameHash := nil;
2513 BadTextNameHash.Free();
2514 BadTextNameHash := nil;
2515 gCurrentMapFileName := '';
2516 gCurrentMap.Free();
2517 gCurrentMap := nil;
2518 end;
2520 panByGUID := nil;
2522 FreePanelArray(gWalls);
2523 FreePanelArray(gRenderBackgrounds);
2524 FreePanelArray(gRenderForegrounds);
2525 FreePanelArray(gWater);
2526 FreePanelArray(gAcid1);
2527 FreePanelArray(gAcid2);
2528 FreePanelArray(gSteps);
2529 FreePanelArray(gLifts);
2530 FreePanelArray(gBlockMon);
2531 gMovingWallIds := nil;
2533 if BackID <> DWORD(-1) then
2534 begin
2535 gBackSize.X := 0;
2536 gBackSize.Y := 0;
2537 e_DeleteTexture(BackID);
2538 BackID := DWORD(-1);
2539 end;
2541 g_Game_StopAllSounds(False);
2542 gMusic.FreeSound();
2543 g_Sound_Delete(gMapInfo.MusicName);
2545 gMapInfo.Name := '';
2546 gMapInfo.Description := '';
2547 gMapInfo.MusicName := '';
2548 gMapInfo.Height := 0;
2549 gMapInfo.Width := 0;
2551 gDoorMap := nil;
2552 gLiftMap := nil;
2553 end;
2555 procedure g_Map_Update();
2556 var
2557 a, d, j: Integer;
2558 m: Word;
2559 s: String;
2560 b: Byte;
2562 procedure UpdatePanelArray(var panels: TPanelArray);
2563 var
2564 i: Integer;
2566 begin
2567 for i := 0 to High(panels) do panels[i].Update();
2568 end;
2570 begin
2571 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2573 UpdatePanelArray(gWalls);
2574 UpdatePanelArray(gRenderBackgrounds);
2575 UpdatePanelArray(gRenderForegrounds);
2576 UpdatePanelArray(gWater);
2577 UpdatePanelArray(gAcid1);
2578 UpdatePanelArray(gAcid2);
2579 UpdatePanelArray(gSteps);
2581 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2583 if gGameSettings.GameMode = GM_CTF then
2584 begin
2585 for a := FLAG_RED to FLAG_BLUE do
2586 begin
2587 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2588 begin
2589 with gFlags[a] do
2590 begin
2591 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2593 m := g_Obj_Move(@Obj, True, True);
2595 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2597 // Ñîïðîòèâëåíèå âîçäóõà
2598 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2600 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2601 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2602 begin
2603 g_Map_ResetFlag(a);
2604 gFlags[a].CaptureTime := 0;
2605 if a = FLAG_RED then
2606 s := _lc[I_PLAYER_FLAG_RED]
2607 else
2608 s := _lc[I_PLAYER_FLAG_BLUE];
2609 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2611 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2612 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2613 b := 0
2614 else
2615 b := 1;
2617 if not sound_ret_flag[b].IsPlaying() then
2618 sound_ret_flag[b].Play();
2620 if g_Game_IsNet then
2621 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2622 Continue;
2623 end;
2625 if Count > 0 then Count -= 1;
2627 // Èãðîê áåðåò ôëàã
2628 if gPlayers <> nil then
2629 begin
2630 j := Random(Length(gPlayers)) - 1;
2631 for d := 0 to High(gPlayers) do
2632 begin
2633 Inc(j);
2634 if j > High(gPlayers) then j := 0;
2635 if gPlayers[j] <> nil then
2636 begin
2637 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2638 begin
2639 if gPlayers[j].GetFlag(a) then Break;
2640 end;
2641 end;
2642 end;
2643 end;
2644 end;
2645 end;
2646 end;
2647 end;
2648 end;
2651 // old algo
2652 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor);
2654 procedure DrawPanels (constref panels: TPanelArray; drawDoors: Boolean=False);
2655 var
2656 idx: Integer;
2657 begin
2658 if (panels <> nil) then
2659 begin
2660 // alas, no visible set
2661 for idx := 0 to High(panels) do
2662 begin
2663 if not (drawDoors xor panels[idx].Door) then panels[idx].Draw(hasAmbient, ambColor);
2664 end;
2665 end;
2666 end;
2668 begin
2669 case PanelType of
2670 PANEL_WALL: DrawPanels(gWalls);
2671 PANEL_CLOSEDOOR: DrawPanels(gWalls, True);
2672 PANEL_BACK: DrawPanels(gRenderBackgrounds);
2673 PANEL_FORE: DrawPanels(gRenderForegrounds);
2674 PANEL_WATER: DrawPanels(gWater);
2675 PANEL_ACID1: DrawPanels(gAcid1);
2676 PANEL_ACID2: DrawPanels(gAcid2);
2677 PANEL_STEP: DrawPanels(gSteps);
2678 end;
2679 end;
2682 // new algo
2683 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
2684 var
2685 mwit: PPanel;
2686 it: TPanelGrid.Iter;
2687 begin
2688 dplClear();
2689 it := mapGrid.forEachInAABB(x0, y0, wdt, hgt, GridDrawableMask);
2690 for mwit in it do if (((mwit^.tag and GridTagDoor) <> 0) = mwit^.Door) then gDrawPanelList.insert(mwit^);
2691 it.release();
2692 // list will be rendered in `g_game.DrawPlayer()`
2693 end;
2696 procedure g_Map_DrawPanelShadowVolumes (lightX: Integer; lightY: Integer; radius: Integer);
2697 var
2698 mwit: PPanel;
2699 it: TPanelGrid.Iter;
2700 begin
2701 it := mapGrid.forEachInAABB(lightX-radius, lightY-radius, radius*2, radius*2, (GridTagWall or GridTagDoor));
2702 for mwit in it do mwit^.DrawShadowVolume(lightX, lightY, radius);
2703 it.release();
2704 end;
2707 procedure g_Map_DrawBack(dx, dy: Integer);
2708 begin
2709 if gDrawBackGround and (BackID <> DWORD(-1)) then
2710 e_DrawSize(BackID, dx, dy, 0, False, False, gBackSize.X, gBackSize.Y)
2711 else
2712 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
2713 end;
2715 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2716 PanelType: Word; b1x3: Boolean=false): Boolean;
2717 var
2718 a, h: Integer;
2719 begin
2720 Result := False;
2722 if WordBool(PanelType and PANEL_WALL) then
2723 if gWalls <> nil then
2724 begin
2725 h := High(gWalls);
2727 for a := 0 to h do
2728 if gWalls[a].Enabled and
2729 g_Collide(X, Y, Width, Height,
2730 gWalls[a].X, gWalls[a].Y,
2731 gWalls[a].Width, gWalls[a].Height) then
2732 begin
2733 Result := True;
2734 Exit;
2735 end;
2736 end;
2738 if WordBool(PanelType and PANEL_WATER) then
2739 if gWater <> nil then
2740 begin
2741 h := High(gWater);
2743 for a := 0 to h do
2744 if g_Collide(X, Y, Width, Height,
2745 gWater[a].X, gWater[a].Y,
2746 gWater[a].Width, gWater[a].Height) then
2747 begin
2748 Result := True;
2749 Exit;
2750 end;
2751 end;
2753 if WordBool(PanelType and PANEL_ACID1) then
2754 if gAcid1 <> nil then
2755 begin
2756 h := High(gAcid1);
2758 for a := 0 to h do
2759 if g_Collide(X, Y, Width, Height,
2760 gAcid1[a].X, gAcid1[a].Y,
2761 gAcid1[a].Width, gAcid1[a].Height) then
2762 begin
2763 Result := True;
2764 Exit;
2765 end;
2766 end;
2768 if WordBool(PanelType and PANEL_ACID2) then
2769 if gAcid2 <> nil then
2770 begin
2771 h := High(gAcid2);
2773 for a := 0 to h do
2774 if g_Collide(X, Y, Width, Height,
2775 gAcid2[a].X, gAcid2[a].Y,
2776 gAcid2[a].Width, gAcid2[a].Height) then
2777 begin
2778 Result := True;
2779 Exit;
2780 end;
2781 end;
2783 if WordBool(PanelType and PANEL_STEP) then
2784 if gSteps <> nil then
2785 begin
2786 h := High(gSteps);
2788 for a := 0 to h do
2789 if g_Collide(X, Y, Width, Height,
2790 gSteps[a].X, gSteps[a].Y,
2791 gSteps[a].Width, gSteps[a].Height) then
2792 begin
2793 Result := True;
2794 Exit;
2795 end;
2796 end;
2798 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2799 if gLifts <> nil then
2800 begin
2801 h := High(gLifts);
2803 for a := 0 to h do
2804 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2805 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2806 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2807 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2808 g_Collide(X, Y, Width, Height,
2809 gLifts[a].X, gLifts[a].Y,
2810 gLifts[a].Width, gLifts[a].Height) then
2811 begin
2812 Result := True;
2813 Exit;
2814 end;
2815 end;
2817 if WordBool(PanelType and PANEL_BLOCKMON) then
2818 if gBlockMon <> nil then
2819 begin
2820 h := High(gBlockMon);
2822 for a := 0 to h do
2823 if ( (not b1x3) or
2824 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2825 g_Collide(X, Y, Width, Height,
2826 gBlockMon[a].X, gBlockMon[a].Y,
2827 gBlockMon[a].Width, gBlockMon[a].Height) then
2828 begin
2829 Result := True;
2830 Exit;
2831 end;
2832 end;
2833 end;
2835 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2836 var
2837 texid: DWORD;
2839 function checkPanels (constref panels: TPanelArray): Boolean;
2840 var
2841 a: Integer;
2842 begin
2843 result := false;
2844 if panels = nil then exit;
2845 for a := 0 to High(panels) do
2846 begin
2847 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2848 begin
2849 result := true;
2850 texid := panels[a].GetTextureID();
2851 exit;
2852 end;
2853 end;
2854 end;
2856 begin
2857 texid := LongWord(TEXTURE_NONE);
2858 result := texid;
2859 if not checkPanels(gWater) then
2860 if not checkPanels(gAcid1) then
2861 if not checkPanels(gAcid2) then exit;
2862 result := texid;
2863 end;
2866 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2867 const
2868 SlowMask = GridTagLift or GridTagBlockMon;
2870 function checker (pan: TPanel; tag: Integer): Boolean;
2871 begin
2873 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2874 begin
2875 result := pan.Enabled;
2876 exit;
2877 end;
2880 if ((tag and GridTagLift) <> 0) then
2881 begin
2882 result :=
2883 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2884 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2885 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2886 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2887 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2888 exit;
2889 end;
2891 if ((tag and GridTagBlockMon) <> 0) then
2892 begin
2893 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2894 exit;
2895 end;
2897 // other shit
2898 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2899 result := true; // i found her!
2900 end;
2902 var
2903 tagmask: Integer = 0;
2904 mwit: PPanel;
2905 it: TPanelGrid.Iter;
2906 pan: TPanel;
2907 begin
2908 result := false;
2909 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2910 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2911 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2912 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2913 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2914 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2915 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2917 if (tagmask = 0) then exit; // just in case
2919 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2920 if gdbg_map_use_accel_coldet then
2921 begin
2922 if ((tagmask and SlowMask) <> 0) then
2923 begin
2924 // slow
2925 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2926 for mwit in it do
2927 begin
2928 pan := mwit^;
2929 if ((pan.tag and GridTagLift) <> 0) then
2930 begin
2931 result :=
2932 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2933 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2934 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2935 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2936 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2937 end
2938 else if ((pan.tag and GridTagBlockMon) <> 0) then
2939 begin
2940 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2941 end
2942 else
2943 begin
2944 // other shit
2945 result := true; // i found her!
2946 end;
2947 if (result) then break;
2948 end;
2949 end
2950 else
2951 begin
2952 // fast
2953 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2954 result := (it.length > 0);
2955 end;
2956 it.release();
2957 end
2958 else
2959 begin
2960 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2961 end;
2962 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2963 end;
2966 // returns `true` if we need to stop
2967 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2968 begin
2969 result := false;
2970 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2971 // check priorities
2972 case cctype of
2973 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2974 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2975 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2976 end;
2977 // collision?
2978 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2979 // yeah
2980 texid := pan.GetTextureID();
2981 // water? water has the highest priority, so stop right here
2982 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2983 // acid2?
2984 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2985 // acid1?
2986 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2987 end;
2989 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2990 var
2991 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2992 mwit: PPanel;
2993 it: TPanelGrid.Iter;
2994 begin
2995 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2996 if gdbg_map_use_accel_coldet then
2997 begin
2998 result := LongWord(TEXTURE_NONE);
2999 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
3000 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
3001 it.release();
3002 end
3003 else
3004 begin
3005 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
3006 end;
3007 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
3008 end;
3011 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
3012 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
3013 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
3016 procedure g_Map_EnableWallGUID (pguid: Integer);
3017 var
3018 pan: TPanel;
3019 begin
3020 //pan := gWalls[ID];
3021 pan := g_Map_PanelByGUID(pguid);
3022 if (pan = nil) then exit;
3023 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
3025 pan.Enabled := True;
3026 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
3028 mapGrid.proxyEnabled[pan.proxyId] := true;
3029 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
3030 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
3032 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3033 // mark platform as interesting
3034 pan.setDirty();
3036 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3037 //e_WriteLog(Format('ENABLE: wall #%d(%d) enabled (%d) (%d,%d)-(%d,%d)', [Integer(ID), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.x, pan.y, pan.width, pan.height]), MSG_NOTIFY);
3038 {$ENDIF}
3039 end;
3042 procedure g_Map_DisableWallGUID (pguid: Integer);
3043 var
3044 pan: TPanel;
3045 begin
3046 //pan := gWalls[ID];
3047 pan := g_Map_PanelByGUID(pguid);
3048 if (pan = nil) then exit;
3049 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
3051 pan.Enabled := False;
3052 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
3054 mapGrid.proxyEnabled[pan.proxyId] := false;
3055 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
3057 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3058 // mark platform as interesting
3059 pan.setDirty();
3061 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3062 //e_WriteLog(Format('DISABLE: wall #%d(%d) disabled (%d) (%d,%d)-(%d,%d)', [Integer(ID), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId]), pan.x, pan.y, pan.width, pan.height]), MSG_NOTIFY);
3063 {$ENDIF}
3064 end;
3067 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
3068 var
3069 tp: TPanel;
3070 begin
3071 tp := g_Map_PanelByGUID(pguid);
3072 if (tp = nil) then exit;
3073 tp.NextTexture(AnimLoop);
3074 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
3075 end;
3078 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
3079 var
3080 pan: TPanel;
3081 begin
3082 //pan := gLifts[ID];
3083 pan := g_Map_PanelByGUID(pguid);
3084 if (pan = nil) then exit;
3085 if not pan.isGLift then exit;
3087 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
3089 with {gLifts[ID]} pan do
3090 begin
3091 LiftType := t;
3093 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
3094 //TODO: make separate lift tags, and change tag here
3096 case LiftType of
3097 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
3098 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
3099 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3100 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3101 end;
3103 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3104 // mark platform as interesting
3105 pan.setDirty();
3106 end;
3107 end;
3110 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3111 var
3112 a: Integer;
3113 PointsArray: Array of TRespawnPoint;
3114 begin
3115 Result := False;
3116 SetLength(PointsArray, 0);
3118 if RespawnPoints = nil then
3119 Exit;
3121 for a := 0 to High(RespawnPoints) do
3122 if RespawnPoints[a].PointType = PointType then
3123 begin
3124 SetLength(PointsArray, Length(PointsArray)+1);
3125 PointsArray[High(PointsArray)] := RespawnPoints[a];
3126 end;
3128 if PointsArray = nil then
3129 Exit;
3131 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3132 Result := True;
3133 end;
3135 function g_Map_GetPointCount(PointType: Byte): Word;
3136 var
3137 a: Integer;
3138 begin
3139 Result := 0;
3141 if RespawnPoints = nil then
3142 Exit;
3144 for a := 0 to High(RespawnPoints) do
3145 if RespawnPoints[a].PointType = PointType then
3146 Result := Result + 1;
3147 end;
3149 function g_Map_HaveFlagPoints(): Boolean;
3150 begin
3151 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3152 end;
3154 procedure g_Map_ResetFlag(Flag: Byte);
3155 begin
3156 with gFlags[Flag] do
3157 begin
3158 Obj.X := -1000;
3159 Obj.Y := -1000;
3160 Obj.Vel.X := 0;
3161 Obj.Vel.Y := 0;
3162 Direction := TDirection.D_LEFT;
3163 State := FLAG_STATE_NONE;
3164 if FlagPoints[Flag] <> nil then
3165 begin
3166 Obj.X := FlagPoints[Flag]^.X;
3167 Obj.Y := FlagPoints[Flag]^.Y;
3168 Direction := FlagPoints[Flag]^.Direction;
3169 State := FLAG_STATE_NORMAL;
3170 end;
3171 Count := -1;
3172 end;
3173 end;
3175 procedure g_Map_DrawFlags();
3176 var
3177 i, dx: Integer;
3178 Mirror: TMirrorType;
3179 begin
3180 if gGameSettings.GameMode <> GM_CTF then
3181 Exit;
3183 for i := FLAG_RED to FLAG_BLUE do
3184 with gFlags[i] do
3185 if State <> FLAG_STATE_CAPTURED then
3186 begin
3187 if State = FLAG_STATE_NONE then
3188 continue;
3190 if Direction = TDirection.D_LEFT then
3191 begin
3192 Mirror := TMirrorType.Horizontal;
3193 dx := -1;
3194 end
3195 else
3196 begin
3197 Mirror := TMirrorType.None;
3198 dx := 1;
3199 end;
3201 Animation.Draw(Obj.X+dx, Obj.Y+1, Mirror);
3203 if g_debug_Frames then
3204 begin
3205 e_DrawQuad(Obj.X+Obj.Rect.X,
3206 Obj.Y+Obj.Rect.Y,
3207 Obj.X+Obj.Rect.X+Obj.Rect.Width-1,
3208 Obj.Y+Obj.Rect.Y+Obj.Rect.Height-1,
3209 0, 255, 0);
3210 end;
3211 end;
3212 end;
3215 procedure g_Map_SaveState (st: TStream);
3216 var
3217 str: String;
3219 procedure savePanels ();
3220 var
3221 pan: TPanel;
3222 begin
3223 // Ñîõðàíÿåì ïàíåëè
3224 utils.writeInt(st, LongInt(Length(panByGUID)));
3225 for pan in panByGUID do pan.SaveState(st);
3226 end;
3228 procedure saveFlag (flag: PFlag);
3229 var
3230 b: Byte;
3231 begin
3232 utils.writeSign(st, 'FLAG');
3233 utils.writeInt(st, Byte(0)); // version
3234 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3235 utils.writeInt(st, Byte(flag^.RespawnType));
3236 // Ñîñòîÿíèå ôëàãà
3237 utils.writeInt(st, Byte(flag^.State));
3238 // Íàïðàâëåíèå ôëàãà
3239 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3240 utils.writeInt(st, Byte(b));
3241 // Îáúåêò ôëàãà
3242 Obj_SaveState(st, @flag^.Obj);
3243 end;
3245 begin
3246 savePanels();
3248 // Ñîõðàíÿåì ìóçûêó
3249 utils.writeSign(st, 'MUSI');
3250 utils.writeInt(st, Byte(0));
3251 // Íàçâàíèå ìóçûêè
3252 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3253 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3254 utils.writeStr(st, str);
3255 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3256 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3257 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3258 utils.writeBool(st, gMusic.SpecPause);
3260 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3261 utils.writeInt(st, LongInt(gTotalMonsters));
3262 ///// /////
3264 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3265 if (gGameSettings.GameMode = GM_CTF) then
3266 begin
3267 // Ôëàã Êðàñíîé êîìàíäû
3268 saveFlag(@gFlags[FLAG_RED]);
3269 // Ôëàã Ñèíåé êîìàíäû
3270 saveFlag(@gFlags[FLAG_BLUE]);
3271 end;
3272 ///// /////
3274 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3275 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3276 begin
3277 // Î÷êè Êðàñíîé êîìàíäû
3278 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
3279 // Î÷êè Ñèíåé êîìàíäû
3280 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
3281 end;
3282 ///// /////
3283 end;
3286 procedure g_Map_LoadState (st: TStream);
3287 var
3288 dw: DWORD;
3289 str: String;
3290 boo: Boolean;
3292 procedure loadPanels ();
3293 var
3294 pan: TPanel;
3295 begin
3296 // Çàãðóæàåì ïàíåëè
3297 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3298 for pan in panByGUID do
3299 begin
3300 pan.LoadState(st);
3301 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3302 end;
3303 end;
3305 procedure loadFlag (flag: PFlag);
3306 var
3307 b: Byte;
3308 begin
3309 // Ñèãíàòóðà ôëàãà
3310 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3311 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3312 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3313 flag^.RespawnType := utils.readByte(st);
3314 // Ñîñòîÿíèå ôëàãà
3315 flag^.State := utils.readByte(st);
3316 // Íàïðàâëåíèå ôëàãà
3317 b := utils.readByte(st);
3318 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3319 // Îáúåêò ôëàãà
3320 Obj_LoadState(@flag^.Obj, st);
3321 end;
3323 begin
3324 if (st = nil) then exit;
3326 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3327 loadPanels();
3328 ///// /////
3330 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3331 g_GFX_Init();
3332 //mapCreateGrid();
3334 ///// Çàãðóæàåì ìóçûêó: /////
3335 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3336 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3337 // Íàçâàíèå ìóçûêè
3338 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3339 str := utils.readStr(st);
3340 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3341 dw := utils.readLongWord(st);
3342 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3343 boo := utils.readBool(st);
3344 // Çàïóñêàåì ýòó ìóçûêó
3345 gMusic.SetByName(str);
3346 gMusic.SpecPause := boo;
3347 gMusic.Play();
3348 gMusic.Pause(true);
3349 gMusic.SetPosition(dw);
3350 ///// /////
3352 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3353 gTotalMonsters := utils.readLongInt(st);
3354 ///// /////
3356 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3357 if (gGameSettings.GameMode = GM_CTF) then
3358 begin
3359 // Ôëàã Êðàñíîé êîìàíäû
3360 loadFlag(@gFlags[FLAG_RED]);
3361 // Ôëàã Ñèíåé êîìàíäû
3362 loadFlag(@gFlags[FLAG_BLUE]);
3363 end;
3364 ///// /////
3366 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3367 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3368 begin
3369 // Î÷êè Êðàñíîé êîìàíäû
3370 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
3371 // Î÷êè Ñèíåé êîìàíäû
3372 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
3373 end;
3374 ///// /////
3375 end;
3378 // trace liquid, stepping by `dx` and `dy`
3379 // return last seen liquid coords, and `false` if we're started outside of the liquid
3380 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3381 const
3382 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3383 begin
3384 topx := x;
3385 topy := y;
3386 // started outside of the liquid?
3387 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3388 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3389 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3390 result := true;
3391 while true do
3392 begin
3393 Inc(x, dx);
3394 Inc(y, dy);
3395 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3396 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3397 topx := x;
3398 topy := y;
3399 end;
3400 end;
3403 begin
3404 DynWarningCB := mapWarningCB;
3405 end.