DEADSOFTWARE

utils: more useless APIs
[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, e_res, 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 := e_OpenResourceRO(DataDirs, 'mapdef.txt');
349 e_LogWritefln('found local "mapdef.txt"', []);
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 extractWadName (resourceName: string): string;
904 var
905 posN: Integer;
906 begin
907 posN := Pos(':', resourceName);
908 if posN > 0 then
909 Result:= Copy(resourceName, 0, posN-1)
910 else
911 Result := '';
912 end;
915 procedure addResToExternalResList (res: AnsiString);
916 var
917 uname: AnsiString;
918 f: Integer;
919 fi: TDiskFileInfo;
920 begin
921 if g_Game_IsClient or not g_Game_IsNet then exit;
922 if (length(res) = 0) then exit; // map wad
923 //res := extractWadName(res);
924 //if (length(res) = 0) then exit; // map wad
925 uname := toLowerCase1251(res);
926 // do not add duplicates
927 for f := 0 to High(gExternalResources) do
928 begin
929 if (gExternalResources[f].userName = uname) then exit;
930 end;
931 //writeln('***(000) addResToExternalResList: res=[', res, ']');
932 // add new resource
933 fi.userName := uname;
934 if not findFileCI(res) then exit;
935 //writeln('***(001) addResToExternalResList: res=[', res, ']');
936 fi.diskName := res;
937 if (not GetDiskFileInfo(res, fi)) then
938 begin
939 fi.tag := -1;
940 end
941 else
942 begin
943 //writeln('***(002) addResToExternalResList: res=[', res, ']');
944 fi.tag := 0; // non-zero means "cannot caclucate hash"
945 try
946 fi.hash := MD5File(fi.diskName);
947 except
948 fi.tag := -1;
949 end;
950 end;
951 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
952 SetLength(gExternalResources, length(gExternalResources)+1);
953 gExternalResources[High(gExternalResources)] := fi;
954 end;
957 procedure compactExtResList ();
958 var
959 src, dest: Integer;
960 begin
961 src := 0;
962 dest := 0;
963 for src := 0 to High(gExternalResources) do
964 begin
965 if (gExternalResources[src].tag = 0) then
966 begin
967 // copy it
968 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
969 Inc(dest);
970 end;
971 end;
972 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
973 end;
976 function GetReplacementWad (WadName: AnsiString): AnsiString;
977 begin
978 result := '';
979 if WadName <> '' then
980 begin
981 result := WadName;
982 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
983 if (result = WadName) then result := e_FindWad(WadDirs, result)
984 end;
985 end;
988 procedure generateExternalResourcesList (map: TDynRecord);
989 begin
990 SetLength(gExternalResources, 0);
991 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.MusicName)));
992 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.SkyName)));
993 end;
996 function CreateTexture (RecName: AnsiString; Map: string; log: Boolean): Integer;
997 var
998 WAD: TWADFile;
999 TextureData: Pointer;
1000 WADName: String;
1001 a, ResLength: Integer;
1002 begin
1003 RecName := toLowerCase1251(RecName);
1004 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1005 if TextNameHash.get(RecName, result) then
1006 begin
1007 // i found her!
1008 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
1009 exit;
1010 end;
1012 Result := -1;
1014 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
1017 if Textures <> nil then
1018 begin
1019 for a := 0 to High(Textures) do
1020 begin
1021 if (Textures[a].TextureName = RecName) then
1022 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
1023 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
1024 Result := a;
1025 Exit;
1026 end;
1027 end;
1028 end;
1031 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
1032 if (RecName = TEXTURE_NAME_WATER) or
1033 (RecName = TEXTURE_NAME_ACID1) or
1034 (RecName = TEXTURE_NAME_ACID2) then
1035 begin
1036 SetLength(Textures, Length(Textures)+1);
1038 with Textures[High(Textures)] do
1039 begin
1040 TextureName := RecName;
1041 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
1042 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
1043 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
1045 Anim := False;
1046 end;
1048 result := High(Textures);
1049 TextNameHash.put(RecName, result);
1050 Exit;
1051 end;
1053 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
1054 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1055 if (WADName <> '') then addResToExternalResList(WADName);
1056 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1058 WAD := TWADFile.Create();
1059 WAD.ReadFile(WADName);
1061 //txname := RecName;
1063 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
1064 begin
1065 FreeMem(TextureData);
1066 RecName := 'COMMON\ALIEN';
1067 end;
1070 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
1071 begin
1072 SetLength(Textures, Length(Textures)+1);
1073 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
1074 begin
1075 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1076 SetLength(Textures, Length(Textures)-1);
1077 result := -1;
1078 Exit;
1079 end;
1080 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1081 FreeMem(TextureData);
1082 Textures[High(Textures)].TextureName := RecName;
1083 Textures[High(Textures)].Anim := False;
1085 result := High(Textures);
1086 TextNameHash.put(RecName, result);
1087 end
1088 else // Íåò òàêîãî ðåóñðñà â WAD'å
1089 begin
1090 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1091 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1092 if log and (not BadTextNameHash.get(RecName, a)) then
1093 begin
1094 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1095 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1096 end;
1097 BadTextNameHash.put(RecName, -1);
1098 end;
1100 WAD.Free();
1101 end;
1104 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1105 var
1106 WAD: TWADFile;
1107 TextureWAD: PChar = nil;
1108 TextData: Pointer = nil;
1109 TextureData: Pointer = nil;
1110 cfg: TConfig = nil;
1111 WADName: String;
1112 ResLength: Integer;
1113 TextureResource: String;
1114 _width, _height, _framecount, _speed: Integer;
1115 _backanimation: Boolean;
1116 //imgfmt: string;
1117 ia: TDynImageDataArray = nil;
1118 f, c, frdelay, frloop: Integer;
1119 begin
1120 RecName := toLowerCase1251(RecName);
1121 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1122 if TextNameHash.get(RecName, result) then
1123 begin
1124 // i found her!
1125 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1126 exit;
1127 end;
1129 result := -1;
1131 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1133 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1134 if BadTextNameHash.get(RecName, f) then
1135 begin
1136 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1137 exit;
1138 end;
1140 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1141 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1142 if (WADName <> '') then addResToExternalResList(WADName);
1143 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1145 WAD := TWADFile.Create();
1146 try
1147 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1149 WAD.ReadFile(WADName);
1151 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1152 begin
1153 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1154 if log and (not BadTextNameHash.get(RecName, f)) then
1155 begin
1156 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1157 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1158 end;
1159 BadTextNameHash.put(RecName, -1);
1160 exit;
1161 end;
1163 {TEST
1164 if WADName = Map then
1165 begin
1166 //FreeMem(TextureWAD);
1167 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1168 end;
1171 WAD.FreeWAD();
1173 if ResLength < 6 then
1174 begin
1175 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1176 BadTextNameHash.put(RecName, -1);
1177 exit;
1178 end;
1180 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1181 if isWadData(TextureWAD, ResLength) then
1182 begin
1183 // íåò, ýòî ñóïåðìåí!
1184 if not WAD.ReadMemory(TextureWAD, ResLength) then
1185 begin
1186 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1187 BadTextNameHash.put(RecName, -1);
1188 exit;
1189 end;
1191 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1192 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1193 begin
1194 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1195 BadTextNameHash.put(RecName, -1);
1196 exit;
1197 end;
1199 cfg := TConfig.CreateMem(TextData, ResLength);
1201 TextureResource := cfg.ReadStr('', 'resource', '');
1202 if TextureResource = '' then
1203 begin
1204 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1205 BadTextNameHash.put(RecName, -1);
1206 exit;
1207 end;
1209 _width := cfg.ReadInt('', 'framewidth', 0);
1210 _height := cfg.ReadInt('', 'frameheight', 0);
1211 _framecount := cfg.ReadInt('', 'framecount', 0);
1212 _speed := cfg.ReadInt('', 'waitcount', 0);
1213 _backanimation := cfg.ReadBool('', 'backanimation', False);
1215 cfg.Free();
1216 cfg := nil;
1218 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1219 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1220 begin
1221 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1222 BadTextNameHash.put(RecName, -1);
1223 exit;
1224 end;
1226 WAD.Free();
1227 WAD := nil;
1229 SetLength(Textures, Length(Textures)+1);
1230 with Textures[High(Textures)] do
1231 begin
1232 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1233 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1234 begin
1235 TextureName := RecName;
1236 Width := _width;
1237 Height := _height;
1238 Anim := True;
1239 FramesCount := _framecount;
1240 Speed := _speed;
1241 result := High(Textures);
1242 TextNameHash.put(RecName, result);
1243 end
1244 else
1245 begin
1246 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1247 if log and (not BadTextNameHash.get(RecName, f)) then
1248 begin
1249 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1250 end;
1251 BadTextNameHash.put(RecName, -1);
1252 end;
1253 end;
1254 end
1255 else
1256 begin
1257 // try animated image
1259 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1260 if length(imgfmt) = 0 then
1261 begin
1262 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1263 exit;
1264 end;
1266 GlobalMetadata.ClearMetaItems();
1267 GlobalMetadata.ClearMetaItemsForSaving();
1268 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1269 begin
1270 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1271 BadTextNameHash.put(RecName, -1);
1272 exit;
1273 end;
1274 if length(ia) = 0 then
1275 begin
1276 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1277 BadTextNameHash.put(RecName, -1);
1278 exit;
1279 end;
1281 WAD.Free();
1282 WAD := nil;
1284 _width := ia[0].width;
1285 _height := ia[0].height;
1286 _framecount := length(ia);
1287 _speed := 1;
1288 _backanimation := false;
1289 frdelay := -1;
1290 frloop := -666;
1291 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1292 begin
1293 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1294 try
1295 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1296 frdelay := f;
1297 if f < 0 then f := 0;
1298 // rounding ;-)
1299 c := f mod 28;
1300 if c < 13 then c := 0 else c := 1;
1301 f := (f div 28)+c;
1302 if f < 1 then f := 1 else if f > 255 then f := 255;
1303 _speed := f;
1304 except
1305 end;
1306 end;
1307 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1308 begin
1309 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1310 try
1311 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1312 frloop := f;
1313 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1314 except
1315 end;
1316 end;
1317 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1318 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1319 f := ord(_backanimation);
1320 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);
1322 SetLength(Textures, Length(Textures)+1);
1323 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1324 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1325 begin
1326 Textures[High(Textures)].TextureName := RecName;
1327 Textures[High(Textures)].Width := _width;
1328 Textures[High(Textures)].Height := _height;
1329 Textures[High(Textures)].Anim := True;
1330 Textures[High(Textures)].FramesCount := length(ia);
1331 Textures[High(Textures)].Speed := _speed;
1332 result := High(Textures);
1333 TextNameHash.put(RecName, result);
1334 //writeln(' CREATED!');
1335 end
1336 else
1337 begin
1338 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1339 if log and (not BadTextNameHash.get(RecName, f)) then
1340 begin
1341 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1342 end;
1343 BadTextNameHash.put(RecName, -1);
1344 end;
1345 end;
1346 finally
1347 for f := 0 to High(ia) do FreeImage(ia[f]);
1348 WAD.Free();
1349 cfg.Free();
1350 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1351 if (TextData <> nil) then FreeMem(TextData);
1352 if (TextureData <> nil) then FreeMem(TextureData);
1353 end;
1354 end;
1356 procedure CreateItem(Item: TDynRecord);
1357 begin
1358 if g_Game_IsClient then Exit;
1360 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1361 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1362 Exit;
1364 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1365 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1366 end;
1368 procedure CreateArea(Area: TDynRecord);
1369 var
1370 a: Integer;
1371 id: DWORD = 0;
1372 begin
1373 case Area.AreaType of
1374 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1375 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1376 begin
1377 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1378 with RespawnPoints[High(RespawnPoints)] do
1379 begin
1380 X := Area.X;
1381 Y := Area.Y;
1382 Direction := TDirection(Area.Direction);
1384 case Area.AreaType of
1385 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1386 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1387 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1388 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1389 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1390 end;
1391 end;
1392 end;
1394 AREA_REDFLAG, AREA_BLUEFLAG:
1395 begin
1396 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1398 if FlagPoints[a] <> nil then Exit;
1400 New(FlagPoints[a]);
1402 with FlagPoints[a]^ do
1403 begin
1404 X := Area.X-FLAGRECT.X;
1405 Y := Area.Y-FLAGRECT.Y;
1406 Direction := TDirection(Area.Direction);
1407 end;
1409 with gFlags[a] do
1410 begin
1411 case a of
1412 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1413 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1414 end;
1416 Animation := TAnimation.Create(id, True, 8);
1417 Obj.Rect := FLAGRECT;
1419 g_Map_ResetFlag(a);
1420 end;
1421 end;
1423 AREA_DOMFLAG:
1424 begin
1425 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1426 with DOMFlagPoints[High(DOMFlagPoints)] do
1427 begin
1428 X := Area.X;
1429 Y := Area.Y;
1430 Direction := TDirection(Area.Direction);
1431 end;
1433 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1434 end;
1435 end;
1436 end;
1438 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1439 var
1440 _trigger: TTrigger;
1441 tp: TPanel;
1442 begin
1443 result := -1;
1444 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1446 with _trigger do
1447 begin
1448 mapId := Trigger.id;
1449 mapIndex := amapIdx;
1450 X := Trigger.X;
1451 Y := Trigger.Y;
1452 Width := Trigger.Width;
1453 Height := Trigger.Height;
1454 Enabled := Trigger.Enabled;
1455 TexturePanelGUID := atpanid;
1456 TriggerType := Trigger.TriggerType;
1457 ActivateType := Trigger.ActivateType;
1458 Keys := Trigger.Keys;
1459 trigPanelGUID := atrigpanid;
1460 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1461 if TexturePanelGUID <> -1 then
1462 begin
1463 tp := g_Map_PanelByGUID(TexturePanelGUID);
1464 if (tp <> nil) then tp.hasTexTrigger := True;
1465 end;
1466 end;
1468 result := Integer(g_Triggers_Create(_trigger, Trigger));
1469 end;
1471 procedure CreateMonster(monster: TDynRecord);
1472 var
1473 a: Integer;
1474 mon: TMonster;
1475 begin
1476 if g_Game_IsClient then Exit;
1478 if (gGameSettings.GameType = GT_SINGLE)
1479 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1480 begin
1481 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1483 if gTriggers <> nil then
1484 begin
1485 for a := 0 to High(gTriggers) do
1486 begin
1487 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1488 begin
1489 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1490 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1491 end;
1492 end;
1493 end;
1495 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1496 end;
1497 end;
1499 procedure g_Map_ReAdd_DieTriggers();
1501 function monsDieTrig (mon: TMonster): Boolean;
1502 var
1503 a: Integer;
1504 //tw: TStrTextWriter;
1505 begin
1506 result := false; // don't stop
1507 mon.ClearTriggers();
1508 for a := 0 to High(gTriggers) do
1509 begin
1510 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1511 begin
1512 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1514 tw := TStrTextWriter.Create();
1515 try
1516 gTriggers[a].trigData.writeTo(tw);
1517 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1518 finally
1519 tw.Free();
1520 end;
1522 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1523 end;
1524 end;
1525 end;
1527 begin
1528 if g_Game_IsClient then Exit;
1530 g_Mons_ForEach(monsDieTrig);
1531 end;
1533 procedure mapCreateGrid ();
1534 var
1535 mapX0: Integer = $3fffffff;
1536 mapY0: Integer = $3fffffff;
1537 mapX1: Integer = -$3fffffff;
1538 mapY1: Integer = -$3fffffff;
1540 procedure calcBoundingBox (constref panels: TPanelArray);
1541 var
1542 idx: Integer;
1543 pan: TPanel;
1544 begin
1545 for idx := 0 to High(panels) do
1546 begin
1547 pan := panels[idx];
1548 if not pan.visvalid then continue;
1549 if (pan.Width < 1) or (pan.Height < 1) then continue;
1550 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1551 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1552 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1553 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1554 end;
1555 end;
1557 procedure addPanelsToGrid (constref panels: TPanelArray);
1558 var
1559 idx: Integer;
1560 pan: TPanel;
1561 newtag: Integer;
1562 begin
1563 //tag := panelTypeToTag(tag);
1564 for idx := 0 to High(panels) do
1565 begin
1566 pan := panels[idx];
1567 if not pan.visvalid then continue;
1568 if (pan.proxyId <> -1) then
1569 begin
1570 {$IF DEFINED(D2F_DEBUG)}
1571 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);
1572 {$ENDIF}
1573 continue;
1574 end;
1575 case pan.PanelType of
1576 PANEL_WALL: newtag := GridTagWall;
1577 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1578 PANEL_BACK: newtag := GridTagBack;
1579 PANEL_FORE: newtag := GridTagFore;
1580 PANEL_WATER: newtag := GridTagWater;
1581 PANEL_ACID1: newtag := GridTagAcid1;
1582 PANEL_ACID2: newtag := GridTagAcid2;
1583 PANEL_STEP: newtag := GridTagStep;
1584 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1585 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1586 else continue; // oops
1587 end;
1588 pan.tag := newtag;
1590 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1591 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1592 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1593 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1595 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1596 begin
1597 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1598 end;
1600 {$ENDIF}
1601 end;
1602 end;
1604 begin
1605 mapGrid.Free();
1606 mapGrid := nil;
1608 calcBoundingBox(gWalls);
1609 calcBoundingBox(gRenderBackgrounds);
1610 calcBoundingBox(gRenderForegrounds);
1611 calcBoundingBox(gWater);
1612 calcBoundingBox(gAcid1);
1613 calcBoundingBox(gAcid2);
1614 calcBoundingBox(gSteps);
1615 calcBoundingBox(gLifts);
1616 calcBoundingBox(gBlockMon);
1618 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1620 if (mapX0 > 0) then mapX0 := 0;
1621 if (mapY0 > 0) then mapY0 := 0;
1623 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1624 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1626 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1627 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1629 addPanelsToGrid(gWalls);
1630 addPanelsToGrid(gRenderBackgrounds);
1631 addPanelsToGrid(gRenderForegrounds);
1632 addPanelsToGrid(gWater);
1633 addPanelsToGrid(gAcid1);
1634 addPanelsToGrid(gAcid2);
1635 addPanelsToGrid(gSteps);
1636 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1637 addPanelsToGrid(gBlockMon);
1639 mapGrid.dumpStats();
1641 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1642 end;
1645 function g_Map_Load(Res: String): Boolean;
1646 const
1647 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1648 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1649 type
1650 PTRec = ^TTRec;
1651 TTRec = record
1652 //TexturePanel: Integer;
1653 tnum: Integer;
1654 id: Integer;
1655 trigrec: TDynRecord;
1656 // texture pane;
1657 texPanelIdx: Integer;
1658 texPanel: TDynRecord;
1659 // "action" panel
1660 actPanelIdx: Integer;
1661 actPanel: TDynRecord;
1662 end;
1663 var
1664 WAD, TestWAD: TWADFile;
1665 //mapReader: TDynRecord = nil;
1666 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1667 panels: TDynField = nil; //TPanelsRec1Array;
1668 items: TDynField = nil; //TItemsRec1Array;
1669 monsters: TDynField = nil; //TMonsterRec1Array;
1670 areas: TDynField = nil; //TAreasRec1Array;
1671 triggers: TDynField = nil; //TTriggersRec1Array;
1672 b, c, k: Integer;
1673 PanelID: DWORD;
1674 AddTextures: TAddTextureArray;
1675 TriggersTable: array of TTRec;
1676 FileName, mapResName, TexName, s: AnsiString;
1677 Data: Pointer;
1678 Len: Integer;
1679 ok, isAnim: Boolean;
1680 CurTex, ntn: Integer;
1681 rec, texrec: TDynRecord;
1682 pttit: PTRec;
1683 pannum, trignum, cnt, tgpid: Integer;
1684 stt: UInt64;
1685 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1686 //moveActive: Boolean;
1687 pan: TPanel;
1688 mapOk: Boolean = false;
1689 usedTextures: THashStrInt = nil; // key: mapTextureList
1690 begin
1691 mapGrid.Free();
1692 mapGrid := nil;
1693 TestWAD := nil;
1694 Data := nil;
1696 //gCurrentMap.Free();
1697 //gCurrentMap := nil;
1699 panByGUID := nil;
1701 Result := False;
1702 gMapInfo.Map := Res;
1703 TriggersTable := nil;
1704 //mapReader := nil;
1706 sfsGCDisable(); // temporary disable removing of temporary volumes
1707 try
1708 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1709 if (gCurrentMap = nil) then
1710 begin
1711 FileName := g_ExtractWadName(Res);
1712 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1713 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1715 WAD := TWADFile.Create();
1716 if not WAD.ReadFile(FileName) then
1717 begin
1718 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1719 WAD.Free();
1720 Exit;
1721 end;
1723 if gTestMap <> '' then
1724 begin
1725 s := g_ExtractWadName(gTestMap);
1726 TestWAD := TWADFile.Create();
1727 if not TestWAD.ReadFile(s) then
1728 begin
1729 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1730 TestWAD.Free();
1731 TestWAD := nil;
1732 end;
1733 end;
1735 if TestWAD <> nil then
1736 begin
1737 mapResName := g_ExtractFileName(gTestMap);
1738 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1739 begin
1740 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1741 Data := nil;
1742 end else
1743 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1744 TestWAD.Free();
1745 TestWAD := nil;
1746 end;
1748 if Data = nil then
1749 begin
1750 //k8: why loader ignores path here?
1751 mapResName := g_ExtractFileName(Res);
1752 if not WAD.GetMapResource(mapResName, Data, Len) then
1753 begin
1754 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1755 WAD.Free();
1756 Exit;
1757 end;
1758 end;
1760 WAD.Free();
1762 if (Len < 4) then
1763 begin
1764 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1765 FreeMem(Data);
1766 exit;
1767 end;
1769 // Çàãðóçêà êàðòû:
1770 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1771 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1773 stt := getTimeMicro();
1775 try
1776 gCurrentMap := g_Map_ParseMap(Data, Len);
1777 except
1778 gCurrentMap.Free();
1779 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1780 FreeMem(Data);
1781 gCurrentMapFileName := '';
1782 Exit;
1783 end;
1785 FreeMem(Data);
1787 if (gCurrentMap = nil) then
1788 begin
1789 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1790 gCurrentMapFileName := '';
1791 exit;
1792 end;
1793 end
1794 else
1795 begin
1796 stt := getTimeMicro();
1797 end;
1799 //gCurrentMap := mapReader;
1801 generateExternalResourcesList(gCurrentMap);
1802 mapTextureList := gCurrentMap['texture'];
1803 // get all other lists here too
1804 panels := gCurrentMap['panel'];
1805 triggers := gCurrentMap['trigger'];
1806 items := gCurrentMap['item'];
1807 areas := gCurrentMap['area'];
1808 monsters := gCurrentMap['monster'];
1810 // Çàãðóçêà îïèñàíèÿ êàðòû:
1811 e_WriteLog(' Reading map info...', TMsgType.Notify);
1812 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1814 with gMapInfo do
1815 begin
1816 Name := gCurrentMap.MapName;
1817 Description := gCurrentMap.MapDesc;
1818 Author := gCurrentMap.MapAuthor;
1819 MusicName := gCurrentMap.MusicName;
1820 SkyName := gCurrentMap.SkyName;
1821 Height := gCurrentMap.Height;
1822 Width := gCurrentMap.Width;
1823 end;
1825 // Çàãðóçêà òåêñòóð:
1826 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1827 // Äîáàâëåíèå òåêñòóð â Textures[]:
1828 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1829 begin
1830 e_WriteLog(' Loading textures:', TMsgType.Notify);
1831 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1833 // find used textures
1834 usedTextures := THashStrInt.Create();
1835 try
1836 if (panels <> nil) and (panels.count > 0) then
1837 begin
1838 for rec in panels do
1839 begin
1840 texrec := rec.TextureRec;
1841 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1842 end;
1843 end;
1845 cnt := -1;
1846 for rec in mapTextureList do
1847 begin
1848 Inc(cnt);
1849 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1850 begin
1851 rec.tagInt := -1; // just in case
1852 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1853 end
1854 else
1855 begin
1856 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1857 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1858 {$ENDIF}
1859 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1860 if rec.Anim then
1861 begin
1862 // Àíèìèðîâàííàÿ òåêñòóðà
1863 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1864 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1865 end
1866 else
1867 begin
1868 // Îáû÷íàÿ òåêñòóðà
1869 ntn := CreateTexture(rec.Resource, FileName, True);
1870 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1871 end;
1872 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1874 rec.tagInt := ntn; // remember texture number
1875 end;
1876 g_Game_StepLoading();
1877 end;
1878 finally
1879 usedTextures.Free();
1880 end;
1882 // set panel tagInt to texture index
1883 if (panels <> nil) then
1884 begin
1885 for rec in panels do
1886 begin
1887 texrec := rec.TextureRec;
1888 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1889 end;
1890 end;
1891 end;
1894 // Çàãðóçêà òðèããåðîâ
1895 gTriggerClientID := 0;
1896 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1897 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1899 // Çàãðóçêà ïàíåëåé
1900 e_WriteLog(' Loading panels...', TMsgType.Notify);
1901 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1903 // check texture numbers for panels
1904 if (panels <> nil) and (panels.count > 0) then
1905 begin
1906 for rec in panels do
1907 begin
1908 if (rec.tagInt < 0) then
1909 begin
1910 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1911 result := false;
1912 gCurrentMap.Free();
1913 gCurrentMap := nil;
1914 gCurrentMapFileName := '';
1915 exit;
1916 end;
1917 end;
1918 end;
1920 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1921 if (triggers <> nil) and (triggers.count > 0) then
1922 begin
1923 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1924 //SetLength(TriggersTable, triggers.count);
1925 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1927 SetLength(TriggersTable, triggers.count);
1928 trignum := -1;
1929 for rec in triggers do
1930 begin
1931 Inc(trignum);
1932 pttit := @TriggersTable[trignum];
1933 pttit.trigrec := rec;
1934 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1935 pttit.texPanelIdx := -1; // will be fixed later
1936 pttit.texPanel := rec.TexturePanelRec;
1937 // action panel
1938 pttit.actPanelIdx := -1;
1939 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1940 // set flag
1941 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1942 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1943 // update progress
1944 g_Game_StepLoading();
1945 end;
1946 end;
1948 // Ñîçäàåì ïàíåëè
1949 if (panels <> nil) and (panels.count > 0) then
1950 begin
1951 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1952 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1954 pannum := -1;
1955 for rec in panels do
1956 begin
1957 Inc(pannum);
1958 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1959 texrec := nil;
1960 SetLength(AddTextures, 0);
1961 CurTex := -1;
1962 ok := false;
1964 if (mapTextureList <> nil) then
1965 begin
1966 texrec := rec.TextureRec;
1967 ok := (texrec <> nil);
1968 end;
1970 if ok then
1971 begin
1972 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1973 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1974 ok := false;
1975 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1976 begin
1977 if rec.userPanelTrigRef then
1978 begin
1979 // e_LogWritefln('trigref for panel %s', [pannum]);
1980 ok := True;
1981 end;
1982 end;
1983 end;
1985 if ok then
1986 begin
1987 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1988 s := texrec.Resource;
1990 // Ñïåö-òåêñòóðû çàïðåùåíû
1991 if g_Map_IsSpecialTexture(s) then
1992 begin
1993 ok := false
1994 end
1995 else
1996 begin
1997 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
1998 ok := g_Texture_NumNameFindStart(s);
1999 end;
2001 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
2002 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
2003 if ok then
2004 begin
2005 k := NNF_NAME_BEFORE;
2006 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
2007 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
2008 begin
2009 k := g_Texture_NumNameFindNext(TexName);
2011 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2012 begin
2013 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2014 if texrec.Anim then
2015 begin
2016 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2017 isAnim := True;
2018 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2019 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2020 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2021 if not ok then
2022 begin
2023 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2024 isAnim := False;
2025 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2026 ok := CreateTexture(TexName, FileName, False) >= 0;
2027 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2028 end;
2029 end
2030 else
2031 begin
2032 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2033 isAnim := False;
2034 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2035 ok := CreateTexture(TexName, FileName, False) >= 0;
2036 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2037 if not ok then
2038 begin
2039 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2040 isAnim := True;
2041 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2042 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2043 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2044 end;
2045 end;
2047 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2048 if ok then
2049 begin
2051 for c := 0 to High(Textures) do
2052 begin
2053 if (Textures[c].TextureName = TexName) then
2054 begin
2055 SetLength(AddTextures, Length(AddTextures)+1);
2056 AddTextures[High(AddTextures)].Texture := c;
2057 AddTextures[High(AddTextures)].Anim := isAnim;
2058 break;
2059 end;
2060 end;
2062 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2063 begin
2064 SetLength(AddTextures, Length(AddTextures)+1);
2065 AddTextures[High(AddTextures)].Texture := c;
2066 AddTextures[High(AddTextures)].Anim := isAnim;
2067 end;
2068 end;
2069 end
2070 else
2071 begin
2072 if k = NNF_NAME_EQUALS then
2073 begin
2074 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2075 SetLength(AddTextures, Length(AddTextures)+1);
2076 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2077 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2078 CurTex := High(AddTextures);
2079 ok := true;
2080 end
2081 else // NNF_NO_NAME
2082 begin
2083 ok := false;
2084 end;
2085 end;
2086 end; // while ok...
2088 ok := true;
2089 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2090 end; // if ok - ññûëàþòñÿ òðèããåðû
2092 if not ok then
2093 begin
2094 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2095 SetLength(AddTextures, 1);
2096 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2097 AddTextures[0].Anim := false;
2098 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2099 CurTex := 0;
2100 end;
2102 //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);
2104 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2106 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2107 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2108 PanelID := CreatePanel(rec, AddTextures, CurTex);
2109 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2110 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2112 // setup lifts
2113 moveSpeed := rec.moveSpeed;
2114 //moveStart := rec.moveStart;
2115 //moveEnd := rec.moveEnd;
2116 //moveActive := rec['move_active'].value;
2117 if not moveSpeed.isZero then
2118 begin
2119 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2120 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2121 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2122 end;
2124 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2126 g_Game_StepLoading();
2127 end;
2128 end;
2130 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2131 for b := 0 to High(TriggersTable) do
2132 begin
2133 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2134 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2135 end;
2137 // create map grid, init other grids (for monsters, for example)
2138 e_WriteLog('Creating map grid', TMsgType.Notify);
2139 mapCreateGrid();
2141 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2142 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2143 begin
2144 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2145 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2146 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2147 trignum := -1;
2148 for rec in triggers do
2149 begin
2150 Inc(trignum);
2151 tgpid := TriggersTable[trignum].actPanelIdx;
2152 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2153 TriggersTable[trignum].tnum := trignum;
2154 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2155 end;
2156 end;
2158 //FIXME: use hashtable!
2159 for pan in panByGUID do
2160 begin
2161 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2162 begin
2163 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2164 end;
2165 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2166 begin
2167 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2168 end;
2169 end;
2171 // Çàãðóçêà ïðåäìåòîâ
2172 e_WriteLog(' Loading items...', TMsgType.Notify);
2173 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2175 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2176 if (items <> nil) and not gLoadGameMode then
2177 begin
2178 e_WriteLog(' Spawning items...', TMsgType.Notify);
2179 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2180 for rec in items do CreateItem(rec);
2181 end;
2183 // Çàãðóçêà îáëàñòåé
2184 e_WriteLog(' Loading areas...', TMsgType.Notify);
2185 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2187 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2188 if areas <> nil then
2189 begin
2190 e_WriteLog(' Creating areas...', TMsgType.Notify);
2191 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2192 for rec in areas do CreateArea(rec);
2193 end;
2195 // Çàãðóçêà ìîíñòðîâ
2196 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2197 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2199 gTotalMonsters := 0;
2201 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2202 if (monsters <> nil) and not gLoadGameMode then
2203 begin
2204 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2205 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2206 for rec in monsters do CreateMonster(rec);
2207 end;
2209 //gCurrentMap := mapReader; // this will be our current map now
2210 gCurrentMapFileName := Res;
2211 //mapReader := nil;
2213 // Çàãðóçêà íåáà
2214 if (gMapInfo.SkyName <> '') then
2215 begin
2216 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2217 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2218 if gTextureFilter then TEXTUREFILTER := GL_LINEAR else TEXTUREFILTER := GL_NEAREST;
2219 try
2220 s := e_GetResourcePath(WadDirs, gMapInfo.SkyName, g_ExtractWadName(Res));
2221 if g_Texture_CreateWAD(BackID, s) then
2222 g_Game_SetupScreenSize
2223 else
2224 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]))
2225 finally
2226 TEXTUREFILTER := GL_NEAREST;
2227 end;
2228 end;
2230 // Çàãðóçêà ìóçûêè
2231 ok := False;
2232 if gMapInfo.MusicName <> '' then
2233 begin
2234 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2235 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2237 s := e_GetResourcePath(WadDirs, gMapInfo.MusicName, g_ExtractWadName(Res));
2238 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2239 ok := True
2240 else
2241 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2242 end;
2244 // Îñòàëüíûå óñòàíâêè
2245 CreateDoorMap();
2246 CreateLiftMap();
2248 g_Items_Init();
2249 g_Weapon_Init();
2250 g_Monsters_Init();
2252 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2253 if not gLoadGameMode then g_GFX_Init();
2255 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2256 mapTextureList := nil;
2257 panels := nil;
2258 items := nil;
2259 areas := nil;
2260 triggers := nil;
2261 TriggersTable := nil;
2262 AddTextures := nil;
2264 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2265 if ok and (not gLoadGameMode) then
2266 begin
2267 gMusic.SetByName(gMapInfo.MusicName);
2268 gMusic.Play();
2269 end
2270 else
2271 begin
2272 gMusic.SetByName('');
2273 end;
2275 stt := getTimeMicro()-stt;
2276 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2277 mapOk := true;
2278 finally
2279 sfsGCEnable(); // enable releasing unused volumes
2280 //mapReader.Free();
2281 e_UnpressAllKeys; // why not?
2282 if not mapOk then
2283 begin
2284 gCurrentMap.Free();
2285 gCurrentMap := nil;
2286 gCurrentMapFileName := '';
2287 end;
2288 end;
2290 compactExtResList();
2291 e_WriteLog('Done loading map.', TMsgType.Notify);
2292 Result := True;
2293 end;
2296 function g_Map_GetMapInfo(Res: String): TMapInfo;
2297 var
2298 WAD: TWADFile;
2299 mapReader: TDynRecord;
2300 //Header: TMapHeaderRec_1;
2301 FileName: String;
2302 Data: Pointer;
2303 Len: Integer;
2304 begin
2305 FillChar(Result, SizeOf(Result), 0);
2306 FileName := g_ExtractWadName(Res);
2308 WAD := TWADFile.Create();
2309 if not WAD.ReadFile(FileName) then
2310 begin
2311 WAD.Free();
2312 Exit;
2313 end;
2315 //k8: it ignores path again
2316 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2317 begin
2318 WAD.Free();
2319 Exit;
2320 end;
2322 WAD.Free();
2324 try
2325 mapReader := g_Map_ParseMap(Data, Len);
2326 except
2327 mapReader := nil;
2328 FreeMem(Data);
2329 exit;
2330 end;
2332 FreeMem(Data);
2334 if (mapReader = nil) then exit;
2336 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2337 begin
2338 Result.Name := mapReader.MapName;
2339 Result.Description := mapReader.MapDesc;
2340 Result.Map := Res;
2341 Result.Author := mapReader.MapAuthor;
2342 Result.Height := mapReader.Height;
2343 Result.Width := mapReader.Width;
2344 end
2345 else
2346 begin
2347 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2348 //ZeroMemory(@Header, SizeOf(Header));
2349 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2350 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2351 Result.Map := Res;
2352 Result.Author := '';
2353 Result.Height := 0;
2354 Result.Width := 0;
2355 end;
2357 mapReader.Free();
2358 end;
2360 function g_Map_GetMapsList(WADName: string): SSArray;
2361 var
2362 WAD: TWADFile;
2363 a: Integer;
2364 ResList: SSArray;
2365 begin
2366 Result := nil;
2367 WAD := TWADFile.Create();
2368 if not WAD.ReadFile(WADName) then
2369 begin
2370 WAD.Free();
2371 Exit;
2372 end;
2373 ResList := WAD.GetMapResources();
2374 if ResList <> nil then
2375 begin
2376 for a := 0 to High(ResList) do
2377 begin
2378 SetLength(Result, Length(Result)+1);
2379 Result[High(Result)] := ResList[a];
2380 end;
2381 end;
2382 WAD.Free();
2383 end;
2385 function g_Map_Exist(Res: string): Boolean;
2386 var
2387 WAD: TWADFile;
2388 FileName, mnn: string;
2389 ResList: SSArray;
2390 a: Integer;
2391 begin
2392 Result := False;
2394 FileName := addWadExtension(g_ExtractWadName(Res));
2396 WAD := TWADFile.Create;
2397 if not WAD.ReadFile(FileName) then
2398 begin
2399 WAD.Free();
2400 Exit;
2401 end;
2403 ResList := WAD.GetMapResources();
2404 WAD.Free();
2406 mnn := g_ExtractFileName(Res);
2407 if ResList <> nil then
2408 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2409 begin
2410 Result := True;
2411 Exit;
2412 end;
2413 end;
2415 procedure g_Map_Free(freeTextures: Boolean=true);
2416 var
2417 a: Integer;
2419 procedure FreePanelArray(var panels: TPanelArray);
2420 var
2421 i: Integer;
2423 begin
2424 if panels <> nil then
2425 begin
2426 for i := 0 to High(panels) do
2427 panels[i].Free();
2428 panels := nil;
2429 end;
2430 end;
2432 begin
2433 g_GFX_Free();
2434 g_Weapon_Free();
2435 g_Items_Free();
2436 g_Triggers_Free();
2437 g_Monsters_Free();
2439 RespawnPoints := nil;
2440 if FlagPoints[FLAG_RED] <> nil then
2441 begin
2442 Dispose(FlagPoints[FLAG_RED]);
2443 FlagPoints[FLAG_RED] := nil;
2444 end;
2445 if FlagPoints[FLAG_BLUE] <> nil then
2446 begin
2447 Dispose(FlagPoints[FLAG_BLUE]);
2448 FlagPoints[FLAG_BLUE] := nil;
2449 end;
2450 //DOMFlagPoints := nil;
2452 //gDOMFlags := nil;
2454 if (Length(gCurrentMapFileName) <> 0) then
2455 begin
2456 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2457 end
2458 else
2459 begin
2460 e_LogWritefln('g_Map_Free: no previous map.', []);
2461 end;
2463 if freeTextures then
2464 begin
2465 e_LogWritefln('g_Map_Free: clearing textures...', []);
2466 if (Textures <> nil) then
2467 begin
2468 for a := 0 to High(Textures) do
2469 begin
2470 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2471 begin
2472 if Textures[a].Anim then
2473 begin
2474 g_Frames_DeleteByID(Textures[a].FramesID)
2475 end
2476 else
2477 begin
2478 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2479 begin
2480 e_DeleteTexture(Textures[a].TextureID);
2481 end;
2482 end;
2483 end;
2484 end;
2485 Textures := nil;
2486 end;
2487 TextNameHash.Free();
2488 TextNameHash := nil;
2489 BadTextNameHash.Free();
2490 BadTextNameHash := nil;
2491 gCurrentMapFileName := '';
2492 gCurrentMap.Free();
2493 gCurrentMap := nil;
2494 end;
2496 panByGUID := nil;
2498 FreePanelArray(gWalls);
2499 FreePanelArray(gRenderBackgrounds);
2500 FreePanelArray(gRenderForegrounds);
2501 FreePanelArray(gWater);
2502 FreePanelArray(gAcid1);
2503 FreePanelArray(gAcid2);
2504 FreePanelArray(gSteps);
2505 FreePanelArray(gLifts);
2506 FreePanelArray(gBlockMon);
2507 gMovingWallIds := nil;
2509 if BackID <> DWORD(-1) then
2510 begin
2511 gBackSize.X := 0;
2512 gBackSize.Y := 0;
2513 e_DeleteTexture(BackID);
2514 BackID := DWORD(-1);
2515 end;
2517 g_Game_StopAllSounds(False);
2518 gMusic.FreeSound();
2519 g_Sound_Delete(gMapInfo.MusicName);
2521 gMapInfo.Name := '';
2522 gMapInfo.Description := '';
2523 gMapInfo.MusicName := '';
2524 gMapInfo.Height := 0;
2525 gMapInfo.Width := 0;
2527 gDoorMap := nil;
2528 gLiftMap := nil;
2529 end;
2531 procedure g_Map_Update();
2532 var
2533 a, d, j: Integer;
2534 m: Word;
2535 s: String;
2536 b: Byte;
2538 procedure UpdatePanelArray(var panels: TPanelArray);
2539 var
2540 i: Integer;
2542 begin
2543 for i := 0 to High(panels) do panels[i].Update();
2544 end;
2546 begin
2547 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2549 UpdatePanelArray(gWalls);
2550 UpdatePanelArray(gRenderBackgrounds);
2551 UpdatePanelArray(gRenderForegrounds);
2552 UpdatePanelArray(gWater);
2553 UpdatePanelArray(gAcid1);
2554 UpdatePanelArray(gAcid2);
2555 UpdatePanelArray(gSteps);
2557 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2559 if gGameSettings.GameMode = GM_CTF then
2560 begin
2561 for a := FLAG_RED to FLAG_BLUE do
2562 begin
2563 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2564 begin
2565 with gFlags[a] do
2566 begin
2567 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2569 m := g_Obj_Move(@Obj, True, True);
2571 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2573 // Ñîïðîòèâëåíèå âîçäóõà
2574 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2576 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2577 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2578 begin
2579 g_Map_ResetFlag(a);
2580 gFlags[a].CaptureTime := 0;
2581 if a = FLAG_RED then
2582 s := _lc[I_PLAYER_FLAG_RED]
2583 else
2584 s := _lc[I_PLAYER_FLAG_BLUE];
2585 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2587 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2588 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2589 b := 0
2590 else
2591 b := 1;
2593 if not sound_ret_flag[b].IsPlaying() then
2594 sound_ret_flag[b].Play();
2596 if g_Game_IsNet then
2597 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2598 Continue;
2599 end;
2601 if Count > 0 then Count -= 1;
2603 // Èãðîê áåðåò ôëàã
2604 if gPlayers <> nil then
2605 begin
2606 j := Random(Length(gPlayers)) - 1;
2607 for d := 0 to High(gPlayers) do
2608 begin
2609 Inc(j);
2610 if j > High(gPlayers) then j := 0;
2611 if gPlayers[j] <> nil then
2612 begin
2613 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2614 begin
2615 if gPlayers[j].GetFlag(a) then Break;
2616 end;
2617 end;
2618 end;
2619 end;
2620 end;
2621 end;
2622 end;
2623 end;
2624 end;
2627 // old algo
2628 procedure g_Map_DrawPanels (PanelType: Word; hasAmbient: Boolean; constref ambColor: TDFColor);
2630 procedure DrawPanels (constref panels: TPanelArray; drawDoors: Boolean=False);
2631 var
2632 idx: Integer;
2633 begin
2634 if (panels <> nil) then
2635 begin
2636 // alas, no visible set
2637 for idx := 0 to High(panels) do
2638 begin
2639 if not (drawDoors xor panels[idx].Door) then panels[idx].Draw(hasAmbient, ambColor);
2640 end;
2641 end;
2642 end;
2644 begin
2645 case PanelType of
2646 PANEL_WALL: DrawPanels(gWalls);
2647 PANEL_CLOSEDOOR: DrawPanels(gWalls, True);
2648 PANEL_BACK: DrawPanels(gRenderBackgrounds);
2649 PANEL_FORE: DrawPanels(gRenderForegrounds);
2650 PANEL_WATER: DrawPanels(gWater);
2651 PANEL_ACID1: DrawPanels(gAcid1);
2652 PANEL_ACID2: DrawPanels(gAcid2);
2653 PANEL_STEP: DrawPanels(gSteps);
2654 end;
2655 end;
2658 // new algo
2659 procedure g_Map_CollectDrawPanels (x0, y0, wdt, hgt: Integer);
2660 var
2661 mwit: PPanel;
2662 it: TPanelGrid.Iter;
2663 begin
2664 dplClear();
2665 it := mapGrid.forEachInAABB(x0, y0, wdt, hgt, GridDrawableMask);
2666 for mwit in it do if (((mwit^.tag and GridTagDoor) <> 0) = mwit^.Door) then gDrawPanelList.insert(mwit^);
2667 it.release();
2668 // list will be rendered in `g_game.DrawPlayer()`
2669 end;
2672 procedure g_Map_DrawPanelShadowVolumes (lightX: Integer; lightY: Integer; radius: Integer);
2673 var
2674 mwit: PPanel;
2675 it: TPanelGrid.Iter;
2676 begin
2677 it := mapGrid.forEachInAABB(lightX-radius, lightY-radius, radius*2, radius*2, (GridTagWall or GridTagDoor));
2678 for mwit in it do mwit^.DrawShadowVolume(lightX, lightY, radius);
2679 it.release();
2680 end;
2683 procedure g_Map_DrawBack(dx, dy: Integer);
2684 begin
2685 if gDrawBackGround and (BackID <> DWORD(-1)) then
2686 e_DrawSize(BackID, dx, dy, 0, False, False, gBackSize.X, gBackSize.Y)
2687 else
2688 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
2689 end;
2691 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2692 PanelType: Word; b1x3: Boolean=false): Boolean;
2693 var
2694 a, h: Integer;
2695 begin
2696 Result := False;
2698 if WordBool(PanelType and PANEL_WALL) then
2699 if gWalls <> nil then
2700 begin
2701 h := High(gWalls);
2703 for a := 0 to h do
2704 if gWalls[a].Enabled and
2705 g_Collide(X, Y, Width, Height,
2706 gWalls[a].X, gWalls[a].Y,
2707 gWalls[a].Width, gWalls[a].Height) then
2708 begin
2709 Result := True;
2710 Exit;
2711 end;
2712 end;
2714 if WordBool(PanelType and PANEL_WATER) then
2715 if gWater <> nil then
2716 begin
2717 h := High(gWater);
2719 for a := 0 to h do
2720 if g_Collide(X, Y, Width, Height,
2721 gWater[a].X, gWater[a].Y,
2722 gWater[a].Width, gWater[a].Height) then
2723 begin
2724 Result := True;
2725 Exit;
2726 end;
2727 end;
2729 if WordBool(PanelType and PANEL_ACID1) then
2730 if gAcid1 <> nil then
2731 begin
2732 h := High(gAcid1);
2734 for a := 0 to h do
2735 if g_Collide(X, Y, Width, Height,
2736 gAcid1[a].X, gAcid1[a].Y,
2737 gAcid1[a].Width, gAcid1[a].Height) then
2738 begin
2739 Result := True;
2740 Exit;
2741 end;
2742 end;
2744 if WordBool(PanelType and PANEL_ACID2) then
2745 if gAcid2 <> nil then
2746 begin
2747 h := High(gAcid2);
2749 for a := 0 to h do
2750 if g_Collide(X, Y, Width, Height,
2751 gAcid2[a].X, gAcid2[a].Y,
2752 gAcid2[a].Width, gAcid2[a].Height) then
2753 begin
2754 Result := True;
2755 Exit;
2756 end;
2757 end;
2759 if WordBool(PanelType and PANEL_STEP) then
2760 if gSteps <> nil then
2761 begin
2762 h := High(gSteps);
2764 for a := 0 to h do
2765 if g_Collide(X, Y, Width, Height,
2766 gSteps[a].X, gSteps[a].Y,
2767 gSteps[a].Width, gSteps[a].Height) then
2768 begin
2769 Result := True;
2770 Exit;
2771 end;
2772 end;
2774 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2775 if gLifts <> nil then
2776 begin
2777 h := High(gLifts);
2779 for a := 0 to h do
2780 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2781 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2782 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2783 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2784 g_Collide(X, Y, Width, Height,
2785 gLifts[a].X, gLifts[a].Y,
2786 gLifts[a].Width, gLifts[a].Height) then
2787 begin
2788 Result := True;
2789 Exit;
2790 end;
2791 end;
2793 if WordBool(PanelType and PANEL_BLOCKMON) then
2794 if gBlockMon <> nil then
2795 begin
2796 h := High(gBlockMon);
2798 for a := 0 to h do
2799 if ( (not b1x3) or
2800 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2801 g_Collide(X, Y, Width, Height,
2802 gBlockMon[a].X, gBlockMon[a].Y,
2803 gBlockMon[a].Width, gBlockMon[a].Height) then
2804 begin
2805 Result := True;
2806 Exit;
2807 end;
2808 end;
2809 end;
2811 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2812 var
2813 texid: DWORD;
2815 function checkPanels (constref panels: TPanelArray): Boolean;
2816 var
2817 a: Integer;
2818 begin
2819 result := false;
2820 if panels = nil then exit;
2821 for a := 0 to High(panels) do
2822 begin
2823 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2824 begin
2825 result := true;
2826 texid := panels[a].GetTextureID();
2827 exit;
2828 end;
2829 end;
2830 end;
2832 begin
2833 texid := LongWord(TEXTURE_NONE);
2834 result := texid;
2835 if not checkPanels(gWater) then
2836 if not checkPanels(gAcid1) then
2837 if not checkPanels(gAcid2) then exit;
2838 result := texid;
2839 end;
2842 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2843 const
2844 SlowMask = GridTagLift or GridTagBlockMon;
2846 function checker (pan: TPanel; tag: Integer): Boolean;
2847 begin
2849 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2850 begin
2851 result := pan.Enabled;
2852 exit;
2853 end;
2856 if ((tag and GridTagLift) <> 0) then
2857 begin
2858 result :=
2859 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2860 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2861 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2862 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2863 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2864 exit;
2865 end;
2867 if ((tag and GridTagBlockMon) <> 0) then
2868 begin
2869 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2870 exit;
2871 end;
2873 // other shit
2874 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2875 result := true; // i found her!
2876 end;
2878 var
2879 tagmask: Integer = 0;
2880 mwit: PPanel;
2881 it: TPanelGrid.Iter;
2882 pan: TPanel;
2883 begin
2884 result := false;
2885 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2886 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2887 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2888 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2889 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2890 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2891 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2893 if (tagmask = 0) then exit; // just in case
2895 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2896 if gdbg_map_use_accel_coldet then
2897 begin
2898 if ((tagmask and SlowMask) <> 0) then
2899 begin
2900 // slow
2901 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2902 for mwit in it do
2903 begin
2904 pan := mwit^;
2905 if ((pan.tag and GridTagLift) <> 0) then
2906 begin
2907 result :=
2908 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2909 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2910 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2911 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2912 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2913 end
2914 else if ((pan.tag and GridTagBlockMon) <> 0) then
2915 begin
2916 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2917 end
2918 else
2919 begin
2920 // other shit
2921 result := true; // i found her!
2922 end;
2923 if (result) then break;
2924 end;
2925 end
2926 else
2927 begin
2928 // fast
2929 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2930 result := (it.length > 0);
2931 end;
2932 it.release();
2933 end
2934 else
2935 begin
2936 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2937 end;
2938 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2939 end;
2942 // returns `true` if we need to stop
2943 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2944 begin
2945 result := false;
2946 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2947 // check priorities
2948 case cctype of
2949 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2950 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2951 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2952 end;
2953 // collision?
2954 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2955 // yeah
2956 texid := pan.GetTextureID();
2957 // water? water has the highest priority, so stop right here
2958 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2959 // acid2?
2960 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2961 // acid1?
2962 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2963 end;
2965 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2966 var
2967 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2968 mwit: PPanel;
2969 it: TPanelGrid.Iter;
2970 begin
2971 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2972 if gdbg_map_use_accel_coldet then
2973 begin
2974 result := LongWord(TEXTURE_NONE);
2975 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2976 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2977 it.release();
2978 end
2979 else
2980 begin
2981 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
2982 end;
2983 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2984 end;
2987 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
2988 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
2989 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
2992 procedure g_Map_EnableWallGUID (pguid: Integer);
2993 var
2994 pan: TPanel;
2995 begin
2996 //pan := gWalls[ID];
2997 pan := g_Map_PanelByGUID(pguid);
2998 if (pan = nil) then exit;
2999 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
3001 pan.Enabled := True;
3002 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
3004 mapGrid.proxyEnabled[pan.proxyId] := true;
3005 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
3006 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
3008 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3009 // mark platform as interesting
3010 pan.setDirty();
3012 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3013 //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);
3014 {$ENDIF}
3015 end;
3018 procedure g_Map_DisableWallGUID (pguid: Integer);
3019 var
3020 pan: TPanel;
3021 begin
3022 //pan := gWalls[ID];
3023 pan := g_Map_PanelByGUID(pguid);
3024 if (pan = nil) then exit;
3025 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
3027 pan.Enabled := False;
3028 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
3030 mapGrid.proxyEnabled[pan.proxyId] := false;
3031 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
3033 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3034 // mark platform as interesting
3035 pan.setDirty();
3037 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
3038 //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);
3039 {$ENDIF}
3040 end;
3043 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
3044 var
3045 tp: TPanel;
3046 begin
3047 tp := g_Map_PanelByGUID(pguid);
3048 if (tp = nil) then exit;
3049 tp.NextTexture(AnimLoop);
3050 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
3051 end;
3054 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
3055 var
3056 pan: TPanel;
3057 begin
3058 //pan := gLifts[ID];
3059 pan := g_Map_PanelByGUID(pguid);
3060 if (pan = nil) then exit;
3061 if not pan.isGLift then exit;
3063 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
3065 with {gLifts[ID]} pan do
3066 begin
3067 LiftType := t;
3069 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
3070 //TODO: make separate lift tags, and change tag here
3072 case LiftType of
3073 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
3074 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
3075 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3076 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3077 end;
3079 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3080 // mark platform as interesting
3081 pan.setDirty();
3082 end;
3083 end;
3086 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3087 var
3088 a: Integer;
3089 PointsArray: Array of TRespawnPoint;
3090 begin
3091 Result := False;
3092 SetLength(PointsArray, 0);
3094 if RespawnPoints = nil then
3095 Exit;
3097 for a := 0 to High(RespawnPoints) do
3098 if RespawnPoints[a].PointType = PointType then
3099 begin
3100 SetLength(PointsArray, Length(PointsArray)+1);
3101 PointsArray[High(PointsArray)] := RespawnPoints[a];
3102 end;
3104 if PointsArray = nil then
3105 Exit;
3107 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3108 Result := True;
3109 end;
3111 function g_Map_GetPointCount(PointType: Byte): Word;
3112 var
3113 a: Integer;
3114 begin
3115 Result := 0;
3117 if RespawnPoints = nil then
3118 Exit;
3120 for a := 0 to High(RespawnPoints) do
3121 if RespawnPoints[a].PointType = PointType then
3122 Result := Result + 1;
3123 end;
3125 function g_Map_HaveFlagPoints(): Boolean;
3126 begin
3127 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3128 end;
3130 procedure g_Map_ResetFlag(Flag: Byte);
3131 begin
3132 with gFlags[Flag] do
3133 begin
3134 Obj.X := -1000;
3135 Obj.Y := -1000;
3136 Obj.Vel.X := 0;
3137 Obj.Vel.Y := 0;
3138 Direction := TDirection.D_LEFT;
3139 State := FLAG_STATE_NONE;
3140 if FlagPoints[Flag] <> nil then
3141 begin
3142 Obj.X := FlagPoints[Flag]^.X;
3143 Obj.Y := FlagPoints[Flag]^.Y;
3144 Direction := FlagPoints[Flag]^.Direction;
3145 State := FLAG_STATE_NORMAL;
3146 end;
3147 Count := -1;
3148 end;
3149 end;
3151 procedure g_Map_DrawFlags();
3152 var
3153 i, dx: Integer;
3154 Mirror: TMirrorType;
3155 begin
3156 if gGameSettings.GameMode <> GM_CTF then
3157 Exit;
3159 for i := FLAG_RED to FLAG_BLUE do
3160 with gFlags[i] do
3161 if State <> FLAG_STATE_CAPTURED then
3162 begin
3163 if State = FLAG_STATE_NONE then
3164 continue;
3166 if Direction = TDirection.D_LEFT then
3167 begin
3168 Mirror := TMirrorType.Horizontal;
3169 dx := -1;
3170 end
3171 else
3172 begin
3173 Mirror := TMirrorType.None;
3174 dx := 1;
3175 end;
3177 Animation.Draw(Obj.X+dx, Obj.Y+1, Mirror);
3179 if g_debug_Frames then
3180 begin
3181 e_DrawQuad(Obj.X+Obj.Rect.X,
3182 Obj.Y+Obj.Rect.Y,
3183 Obj.X+Obj.Rect.X+Obj.Rect.Width-1,
3184 Obj.Y+Obj.Rect.Y+Obj.Rect.Height-1,
3185 0, 255, 0);
3186 end;
3187 end;
3188 end;
3191 procedure g_Map_SaveState (st: TStream);
3192 var
3193 str: String;
3195 procedure savePanels ();
3196 var
3197 pan: TPanel;
3198 begin
3199 // Ñîõðàíÿåì ïàíåëè
3200 utils.writeInt(st, LongInt(Length(panByGUID)));
3201 for pan in panByGUID do pan.SaveState(st);
3202 end;
3204 procedure saveFlag (flag: PFlag);
3205 var
3206 b: Byte;
3207 begin
3208 utils.writeSign(st, 'FLAG');
3209 utils.writeInt(st, Byte(0)); // version
3210 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3211 utils.writeInt(st, Byte(flag^.RespawnType));
3212 // Ñîñòîÿíèå ôëàãà
3213 utils.writeInt(st, Byte(flag^.State));
3214 // Íàïðàâëåíèå ôëàãà
3215 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3216 utils.writeInt(st, Byte(b));
3217 // Îáúåêò ôëàãà
3218 Obj_SaveState(st, @flag^.Obj);
3219 end;
3221 begin
3222 savePanels();
3224 // Ñîõðàíÿåì ìóçûêó
3225 utils.writeSign(st, 'MUSI');
3226 utils.writeInt(st, Byte(0));
3227 // Íàçâàíèå ìóçûêè
3228 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3229 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3230 utils.writeStr(st, str);
3231 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3232 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3233 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3234 utils.writeBool(st, gMusic.SpecPause);
3236 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3237 utils.writeInt(st, LongInt(gTotalMonsters));
3238 ///// /////
3240 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3241 if (gGameSettings.GameMode = GM_CTF) then
3242 begin
3243 // Ôëàã Êðàñíîé êîìàíäû
3244 saveFlag(@gFlags[FLAG_RED]);
3245 // Ôëàã Ñèíåé êîìàíäû
3246 saveFlag(@gFlags[FLAG_BLUE]);
3247 end;
3248 ///// /////
3250 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3251 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3252 begin
3253 // Î÷êè Êðàñíîé êîìàíäû
3254 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Goals));
3255 // Î÷êè Ñèíåé êîìàíäû
3256 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Goals));
3257 end;
3258 ///// /////
3259 end;
3262 procedure g_Map_LoadState (st: TStream);
3263 var
3264 dw: DWORD;
3265 str: String;
3266 boo: Boolean;
3268 procedure loadPanels ();
3269 var
3270 pan: TPanel;
3271 begin
3272 // Çàãðóæàåì ïàíåëè
3273 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3274 for pan in panByGUID do
3275 begin
3276 pan.LoadState(st);
3277 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3278 end;
3279 end;
3281 procedure loadFlag (flag: PFlag);
3282 var
3283 b: Byte;
3284 begin
3285 // Ñèãíàòóðà ôëàãà
3286 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3287 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3288 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3289 flag^.RespawnType := utils.readByte(st);
3290 // Ñîñòîÿíèå ôëàãà
3291 flag^.State := utils.readByte(st);
3292 // Íàïðàâëåíèå ôëàãà
3293 b := utils.readByte(st);
3294 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3295 // Îáúåêò ôëàãà
3296 Obj_LoadState(@flag^.Obj, st);
3297 end;
3299 begin
3300 if (st = nil) then exit;
3302 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3303 loadPanels();
3304 ///// /////
3306 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3307 g_GFX_Init();
3308 //mapCreateGrid();
3310 ///// Çàãðóæàåì ìóçûêó: /////
3311 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3312 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3313 // Íàçâàíèå ìóçûêè
3314 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3315 str := utils.readStr(st);
3316 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3317 dw := utils.readLongWord(st);
3318 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3319 boo := utils.readBool(st);
3320 // Çàïóñêàåì ýòó ìóçûêó
3321 gMusic.SetByName(str);
3322 gMusic.SpecPause := boo;
3323 gMusic.Play();
3324 gMusic.Pause(true);
3325 gMusic.SetPosition(dw);
3326 ///// /////
3328 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3329 gTotalMonsters := utils.readLongInt(st);
3330 ///// /////
3332 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3333 if (gGameSettings.GameMode = GM_CTF) then
3334 begin
3335 // Ôëàã Êðàñíîé êîìàíäû
3336 loadFlag(@gFlags[FLAG_RED]);
3337 // Ôëàã Ñèíåé êîìàíäû
3338 loadFlag(@gFlags[FLAG_BLUE]);
3339 end;
3340 ///// /////
3342 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3343 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3344 begin
3345 // Î÷êè Êðàñíîé êîìàíäû
3346 gTeamStat[TEAM_RED].Goals := utils.readSmallInt(st);
3347 // Î÷êè Ñèíåé êîìàíäû
3348 gTeamStat[TEAM_BLUE].Goals := utils.readSmallInt(st);
3349 end;
3350 ///// /////
3351 end;
3354 // trace liquid, stepping by `dx` and `dy`
3355 // return last seen liquid coords, and `false` if we're started outside of the liquid
3356 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3357 const
3358 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3359 begin
3360 topx := x;
3361 topy := y;
3362 // started outside of the liquid?
3363 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3364 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3365 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3366 result := true;
3367 while true do
3368 begin
3369 Inc(x, dx);
3370 Inc(y, dy);
3371 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3372 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3373 topx := x;
3374 topy := y;
3375 end;
3376 end;
3379 begin
3380 DynWarningCB := mapWarningCB;
3381 end.