DEADSOFTWARE

render: use TAnimationState instead of TAnimation
[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 g_base, r_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 NeedSend: Boolean;
58 end;
60 function g_Map_Load(Res: String): Boolean;
61 function g_Map_GetMapInfo(Res: String): TMapInfo;
62 function g_Map_GetMapsList(WADName: String): SSArray;
63 function g_Map_Exist(Res: String): Boolean;
64 procedure g_Map_Free(freeTextures: Boolean=true);
65 procedure g_Map_Update();
67 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
69 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word;
70 PanelType: Word; b1x3: Boolean=false): Boolean;
71 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
73 procedure g_Map_EnableWallGUID (pguid: Integer);
74 procedure g_Map_DisableWallGUID (pguid: Integer);
75 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
77 // HACK!!!
78 procedure g_Map_EnableWall_XXX (ID: DWORD);
79 procedure g_Map_DisableWall_XXX (ID: DWORD);
80 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer);
82 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
84 procedure g_Map_ReAdd_DieTriggers();
85 function g_Map_IsSpecialTexture(Texture: String): Boolean;
87 function g_Map_GetPoint(PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
88 function g_Map_GetPointCount(PointType: Byte): Word;
89 function g_Map_GetRandomPointType(): Byte;
91 function g_Map_HaveFlagPoints(): Boolean;
93 procedure g_Map_ResetFlag(Flag: Byte);
95 procedure g_Map_SaveState (st: TStream);
96 procedure g_Map_LoadState (st: TStream);
98 // returns panel or nil
99 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
100 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
102 // returns panel or nil
103 // sets `ex` and `ey` to `x1` and `y1` when no hit was detected
104 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
106 type
107 TForEachPanelCB = function (pan: TPanel): Boolean is nested; // return `true` to stop
109 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
110 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
112 // trace liquid, stepping by `dx` and `dy`
113 // return last seen liquid coords, and `false` if we're started outside of the liquid
114 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
117 // return `true` from `cb` to stop
118 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
120 procedure g_Map_NetSendInterestingPanels (); // yay!
123 procedure g_Map_ProfilersBegin ();
124 procedure g_Map_ProfilersEnd ();
127 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
130 function g_Map_MinX (): Integer; inline;
131 function g_Map_MinY (): Integer; inline;
132 function g_Map_MaxX (): Integer; inline;
133 function g_Map_MaxY (): Integer; inline;
135 const
136 NNF_NO_NAME = 0;
137 NNF_NAME_BEFORE = 1;
138 NNF_NAME_EQUALS = 2;
139 NNF_NAME_AFTER = 3;
141 function g_Texture_NumNameFindStart(name: String): Boolean;
142 function g_Texture_NumNameFindNext(var newName: String): Byte;
144 const
145 RESPAWNPOINT_PLAYER1 = 1;
146 RESPAWNPOINT_PLAYER2 = 2;
147 RESPAWNPOINT_DM = 3;
148 RESPAWNPOINT_RED = 4;
149 RESPAWNPOINT_BLUE = 5;
151 FLAG_NONE = 0;
152 FLAG_RED = 1;
153 FLAG_BLUE = 2;
154 FLAG_DOM = 3;
156 FLAG_STATE_NONE = 0;
157 FLAG_STATE_NORMAL = 1;
158 FLAG_STATE_DROPPED = 2;
159 FLAG_STATE_CAPTURED = 3;
160 FLAG_STATE_SCORED = 4; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
161 FLAG_STATE_RETURNED = 5; // Äëÿ ýâåíòîâ ÷åðåç ñåòêó.
163 FLAG_TIME = 720; // 20 seconds
165 SKY_STRETCH: Single = 1.5;
167 const
168 GridTagInvalid = 0;
170 (* draw order:
171 PANEL_BACK
172 PANEL_STEP
173 PANEL_WALL
174 PANEL_CLOSEDOOR
175 PANEL_ACID1
176 PANEL_ACID2
177 PANEL_WATER
178 PANEL_FORE
179 *)
180 // sorted by draw priority
181 GridTagBack = 1 shl 0; // gRenderBackgrounds
182 GridTagStep = 1 shl 1; // gSteps
183 GridTagWall = 1 shl 2; // gWalls
184 GridTagDoor = 1 shl 3; // gWalls
185 GridTagAcid1 = 1 shl 4; // gAcid1
186 GridTagAcid2 = 1 shl 5; // gAcid2
187 GridTagWater = 1 shl 6; // gWater
188 GridTagFore = 1 shl 7; // gRenderForegrounds
189 // the following are invisible
190 GridTagLift = 1 shl 8; // gLifts
191 GridTagBlockMon = 1 shl 9; // gBlockMon
193 GridTagSolid = (GridTagWall or GridTagDoor);
194 GridTagObstacle = (GridTagStep or GridTagWall or GridTagDoor);
195 GridTagLiquid = (GridTagAcid1 or GridTagAcid2 or GridTagWater);
197 GridDrawableMask = (GridTagBack or GridTagStep or GridTagWall or GridTagDoor or GridTagAcid1 or GridTagAcid2 or GridTagWater or GridTagFore);
200 type
201 TBinHeapPanelDrawCmp = class
202 public
203 class function less (const a, b: TPanel): Boolean; inline;
204 end;
206 TBinHeapPanelDraw = specialize TBinaryHeapBase<TPanel, TBinHeapPanelDrawCmp>;
208 var
209 gWalls: TPanelArray;
210 gRenderBackgrounds: TPanelArray;
211 gRenderForegrounds: TPanelArray;
212 gWater, gAcid1, gAcid2: TPanelArray;
213 gSteps: TPanelArray;
214 gLifts: TPanelArray;
215 gBlockMon: TPanelArray;
216 gFlags: array [FLAG_RED..FLAG_BLUE] of TFlag;
217 //gDOMFlags: array of TFlag;
218 gMapInfo: TMapInfo;
219 gBackSize: TDFPoint;
220 gDoorMap: array of array of DWORD;
221 gLiftMap: array of array of DWORD;
222 gWADHash: TMD5Digest;
223 BackID: DWORD = DWORD(-1);
224 gExternalResources: array of TDiskFileInfo = nil;
225 gMovingWallIds: array of Integer = nil;
227 gdbg_map_use_accel_render: Boolean = true;
228 gdbg_map_use_accel_coldet: Boolean = true;
229 profMapCollision: TProfiler = nil; //WARNING: FOR DEBUGGING ONLY!
230 gDrawPanelList: TBinHeapPanelDraw = nil; // binary heap of all walls we have to render, populated by `g_Map_CollectDrawPanels()`
232 gCurrentMap: TDynRecord = nil;
233 gCurrentMapFileName: AnsiString = ''; // so we can skip texture reloading
234 gTestMap: String = '';
237 function panelTypeToTag (panelType: Word): Integer; // returns GridTagXXX
240 type
241 TPanelGrid = specialize TBodyGridBase<TPanel>;
243 var
244 mapGrid: TPanelGrid = nil; // DO NOT USE! public for debugging only!
246 var (* private state *)
247 Textures: TLevelTextureArray = nil;
249 implementation
251 uses
252 e_input, e_log, e_res, g_items, g_gfx, g_console,
253 g_weapons, g_game, g_sound, e_sound, CONFIG,
254 g_options, g_triggers, g_player, r_textures, r_animations,
255 Math, g_monsters, g_saveload, g_language, g_netmsg,
256 sfs, xstreams, hashtable, wadreader,
257 ImagingTypes, Imaging, ImagingUtility,
258 ImagingGif, ImagingNetworkGraphics,
259 g_res_downloader;
261 const
262 FLAGRECT: TRectWH = (X:15; Y:12; Width:33; Height:52);
263 MUSIC_SIGNATURE = $4953554D; // 'MUSI'
264 FLAG_SIGNATURE = $47414C46; // 'FLAG'
267 // ////////////////////////////////////////////////////////////////////////// //
268 procedure mapWarningCB (const msg: AnsiString; line, col: Integer);
269 begin
270 if (line > 0) then
271 begin
272 e_LogWritefln('parse error at (%s,%s): %s', [line, col, msg], TMsgType.Warning);
273 end
274 else
275 begin
276 e_LogWritefln('parse error: %s', [msg], TMsgType.Warning);
277 end;
278 end;
281 // ////////////////////////////////////////////////////////////////////////// //
282 var
283 panByGUID: array of TPanel = nil;
286 // ////////////////////////////////////////////////////////////////////////// //
287 function g_Map_PanelByGUID (aguid: Integer): TPanel; inline;
288 begin
289 //if (panByGUID = nil) or (not panByGUID.get(aguid, result)) then result := nil;
290 if (aguid >= 0) and (aguid < Length(panByGUID)) then result := panByGUID[aguid] else result := nil;
291 end;
294 // return `true` from `cb` to stop
295 function g_Map_ForEachPanel (cb: TForEachPanelCB): TPanel;
296 var
297 pan: TPanel;
298 begin
299 result := nil;
300 if not assigned(cb) then exit;
301 for pan in panByGUID do
302 begin
303 if cb(pan) then begin result := pan; exit; end;
304 end;
305 end;
308 procedure g_Map_NetSendInterestingPanels ();
309 var
310 pan: TPanel;
311 begin
312 if g_Game_IsServer and g_Game_IsNet then
313 begin
314 for pan in panByGUID do
315 begin
316 if pan.gncNeedSend then MH_SEND_PanelState(pan.guid);
317 end;
318 end;
319 end;
322 // ////////////////////////////////////////////////////////////////////////// //
323 function g_Map_MinX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0 else result := 0; end;
324 function g_Map_MinY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0 else result := 0; end;
325 function g_Map_MaxX (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridX0+mapGrid.gridWidth-1 else result := 0; end;
326 function g_Map_MaxY (): Integer; inline; begin if (mapGrid <> nil) then result := mapGrid.gridY0+mapGrid.gridHeight-1 else result := 0; end;
329 // ////////////////////////////////////////////////////////////////////////// //
330 var
331 dfmapdef: TDynMapDef = nil;
334 procedure loadMapDefinition ();
335 var
336 pr: TTextParser = nil;
337 st: TStream = nil;
338 WAD: TWADFile = nil;
339 begin
340 if (dfmapdef <> nil) then exit;
342 try
343 e_LogWritefln('parsing "mapdef.txt"...', []);
344 st := e_OpenResourceRO(DataDirs, 'mapdef.txt');
345 e_LogWritefln('found local "mapdef.txt"', []);
346 except
347 st := nil;
348 end;
350 if (st = nil) then
351 begin
352 WAD := TWADFile.Create();
353 if not WAD.ReadFile(GameWAD) then
354 begin
355 //raise Exception.Create('cannot load "game.wad"');
356 st := nil;
357 end
358 else
359 begin
360 st := WAD.openFileStream('mapdef.txt');
361 end;
362 end;
364 try
365 if (st = nil) then
366 begin
367 //raise Exception.Create('cannot open "mapdef.txt"');
368 e_LogWriteln('using default "mapdef.txt"...');
369 pr := TStrTextParser.Create(defaultMapDef);
370 end
371 else
372 begin
373 pr := TFileTextParser.Create(st);
374 end;
375 except on e: Exception do
376 begin
377 e_LogWritefln('something is VERY wrong here! -- ', [e.message]);
378 raise;
379 end;
380 end;
382 try
383 dfmapdef := TDynMapDef.Create(pr);
384 except
385 on e: TDynParseException do
386 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
387 on e: Exception do
388 raise Exception.CreateFmt('ERROR in "mapdef.txt" at (%s,%s): %s', [pr.tokLine, pr.tokCol, e.message]);
389 end;
391 st.Free();
392 WAD.Free();
393 end;
396 // ////////////////////////////////////////////////////////////////////////// //
397 function g_Map_ParseMap (data: Pointer; dataLen: Integer): TDynRecord;
398 var
399 wst: TSFSMemoryChunkStream = nil;
400 begin
401 result := nil;
402 if (dataLen < 4) then exit;
404 if (dfmapdef = nil) then writeln('need to load mapdef');
405 loadMapDefinition();
406 if (dfmapdef = nil) then raise Exception.Create('internal map loader error');
408 wst := TSFSMemoryChunkStream.Create(data, dataLen);
409 try
410 result := dfmapdef.parseMap(wst);
411 except
412 on e: TDynParseException do
413 begin
414 e_LogWritefln('ERROR at (%s,%s): %s', [e.tokLine, e.tokCol, e.message]);
415 wst.Free();
416 result := nil;
417 exit;
418 end;
419 on e: Exception do
420 begin
421 e_LogWritefln('ERROR: %s', [e.message]);
422 wst.Free();
423 result := nil;
424 exit;
425 end;
426 end;
428 //e_LogWriteln('map parsed.');
429 end;
432 // ////////////////////////////////////////////////////////////////////////// //
433 var
434 NNF_PureName: String; // Èìÿ òåêñòóðû áåç öèôð â êîíöå
435 NNF_PureExt: String; // extension postfix
436 NNF_FirstNum: Integer; // ×èñëî ó íà÷àëüíîé òåêñòóðû
437 NNF_CurrentNum: Integer; // Ñëåäóþùåå ÷èñëî ó òåêñòóðû
440 function g_Texture_NumNameFindStart(name: String): Boolean;
441 var
442 i, j: Integer;
444 begin
445 Result := False;
446 NNF_PureName := '';
447 NNF_PureExt := '';
448 NNF_FirstNum := -1;
449 NNF_CurrentNum := -1;
451 for i := Length(name) downto 1 do
452 if (name[i] = '_') then // "_" - ñèìâîë íà÷àëà íîìåðíîãî ïîñòôèêñà
453 begin
454 if i = Length(name) then
455 begin // Íåò öèôð â êîíöå ñòðîêè
456 Exit;
457 end
458 else
459 begin
460 j := i + 1;
461 while (j <= Length(name)) and (name[j] <> '.') do inc(j);
462 NNF_PureName := Copy(name, 1, i);
463 NNF_PureExt := Copy(name, j);
464 name := Copy(name, i + 1, j - i - 1);
465 Break;
466 end;
467 end;
469 // Íå ïåðåâåñòè â ÷èñëî:
470 if not TryStrToInt(name, NNF_FirstNum) then
471 Exit;
473 NNF_CurrentNum := 0;
475 Result := True;
476 end;
479 function g_Texture_NumNameFindNext(var newName: String): Byte;
480 begin
481 if (NNF_PureName = '') or (NNF_CurrentNum < 0) then
482 begin
483 newName := '';
484 Result := NNF_NO_NAME;
485 Exit;
486 end;
488 newName := NNF_PureName + IntToStr(NNF_CurrentNum) + NNF_PureExt;
490 if NNF_CurrentNum < NNF_FirstNum then
491 Result := NNF_NAME_BEFORE
492 else
493 if NNF_CurrentNum > NNF_FirstNum then
494 Result := NNF_NAME_AFTER
495 else
496 Result := NNF_NAME_EQUALS;
498 Inc(NNF_CurrentNum);
499 end;
502 // ////////////////////////////////////////////////////////////////////////// //
503 function panelTypeToTag (panelType: Word): Integer;
504 begin
505 case panelType of
506 PANEL_WALL: result := GridTagWall; // gWalls
507 PANEL_OPENDOOR, PANEL_CLOSEDOOR: result := GridTagDoor; // gWalls
508 PANEL_BACK: result := GridTagBack; // gRenderBackgrounds
509 PANEL_FORE: result := GridTagFore; // gRenderForegrounds
510 PANEL_WATER: result := GridTagWater; // gWater
511 PANEL_ACID1: result := GridTagAcid1; // gAcid1
512 PANEL_ACID2: result := GridTagAcid2; // gAcid2
513 PANEL_STEP: result := GridTagStep; // gSteps
514 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: result := GridTagLift; // gLifts -- this is for all lifts
515 PANEL_BLOCKMON: result := GridTagBlockMon; // gBlockMon -- this is for all blockmons
516 else result := GridTagInvalid;
517 end;
518 end;
521 class function TBinHeapPanelDrawCmp.less (const a, b: TPanel): Boolean; inline;
522 begin
523 if (a.tag < b.tag) then begin result := true; exit; end;
524 if (a.tag > b.tag) then begin result := false; exit; end;
525 result := (a.arrIdx < b.arrIdx);
526 end;
528 var
529 TextNameHash: THashStrInt = nil; // key: texture name; value: index in `Textures`
530 BadTextNameHash: THashStrInt = nil; // set; so we won't spam with non-existing texture messages
531 RespawnPoints: array of TRespawnPoint;
532 FlagPoints: array[FLAG_RED..FLAG_BLUE] of PFlagPoint;
533 //DOMFlagPoints: Array of TFlagPoint;
536 procedure g_Map_ProfilersBegin ();
537 begin
538 if (profMapCollision = nil) then profMapCollision := TProfiler.Create('COLSOLID', g_profile_history_size);
539 if (profMapCollision <> nil) then profMapCollision.mainBegin(g_profile_collision);
540 // create sections
541 if g_profile_collision and (profMapCollision <> nil) then
542 begin
543 profMapCollision.sectionBegin('*solids');
544 profMapCollision.sectionEnd();
545 profMapCollision.sectionBegin('liquids');
546 profMapCollision.sectionEnd();
547 end;
548 end;
550 procedure g_Map_ProfilersEnd ();
551 begin
552 if (profMapCollision <> nil) then profMapCollision.mainEnd();
553 end;
556 // wall index in `gWalls` or -1
557 function g_Map_traceToNearestWall (x0, y0, x1, y1: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
558 var
559 ex, ey: Integer;
560 begin
561 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, (GridTagWall or GridTagDoor));
562 if (result <> nil) then
563 begin
564 if (hitx <> nil) then hitx^ := ex;
565 if (hity <> nil) then hity^ := ey;
566 end
567 else
568 begin
569 if (hitx <> nil) then hitx^ := x1;
570 if (hity <> nil) then hity^ := y1;
571 end;
572 end;
574 // returns panel or nil
575 function g_Map_traceToNearest (x0, y0, x1, y1: Integer; tag: Integer; hitx: PInteger=nil; hity: PInteger=nil): TPanel;
576 var
577 ex, ey: Integer;
578 begin
579 result := mapGrid.traceRay(ex, ey, x0, y0, x1, y1, tag);
580 if (result <> nil) then
581 begin
582 if (hitx <> nil) then hitx^ := ex;
583 if (hity <> nil) then hity^ := ey;
584 end
585 else
586 begin
587 if (hitx <> nil) then hitx^ := x1;
588 if (hity <> nil) then hity^ := y1;
589 end;
590 end;
593 function xxPanAtPointChecker (pan: TPanel; panelType: Word): Boolean; inline;
594 begin
595 if ((pan.tag and GridTagLift) <> 0) then
596 begin
597 // stop if the lift of the right type
598 result :=
599 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
600 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
601 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
602 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT)));
603 exit;
604 end;
605 result := true; // otherwise, stop anyway, 'cause `forEachAtPoint()` is guaranteed to call this only for correct panels
606 end;
608 function g_Map_HasAnyPanelAtPoint (x, y: Integer; panelType: Word): Boolean;
609 var
610 tagmask: Integer = 0;
611 mwit: PPanel;
612 it: TPanelGrid.Iter;
613 begin
614 result := false;
616 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
617 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
618 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
619 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
620 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
621 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
622 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
624 if (tagmask = 0) then exit;// just in case
626 if ((tagmask and GridTagLift) <> 0) then
627 begin
628 // slow
629 it := mapGrid.forEachAtPoint(x, y, tagmask);
630 for mwit in it do if (xxPanAtPointChecker(mwit^, PanelType)) then begin result := true; break; end;
631 end
632 else
633 begin
634 // fast
635 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true);
636 result := (it.length <> 0); // firsthit
637 end;
638 it.release();
639 end;
642 function g_Map_PanelAtPoint (x, y: Integer; tagmask: Integer=-1): TPanel;
643 var
644 it: TPanelGrid.Iter;
645 begin
646 result := nil;
647 if (tagmask = 0) then exit;
648 it := mapGrid.forEachAtPoint(x, y, tagmask, false, true); // firsthit
649 if (it.length <> 0) then result := it.first^;
650 it.release();
651 end;
654 function g_Map_IsSpecialTexture(Texture: String): Boolean;
655 begin
656 Result := (Texture = TEXTURE_NAME_WATER) or
657 (Texture = TEXTURE_NAME_ACID1) or
658 (Texture = TEXTURE_NAME_ACID2);
659 end;
661 procedure CreateDoorMap();
662 var
663 PanelArray: Array of record
664 X, Y: Integer;
665 Width, Height: Word;
666 Active: Boolean;
667 PanelID: DWORD;
668 end;
669 a, b, c, m, i, len: Integer;
670 ok: Boolean;
671 begin
672 if gWalls = nil then
673 Exit;
675 i := 0;
676 len := 128;
677 SetLength(PanelArray, len);
679 for a := 0 to High(gWalls) do
680 if gWalls[a].Door then
681 begin
682 PanelArray[i].X := gWalls[a].X;
683 PanelArray[i].Y := gWalls[a].Y;
684 PanelArray[i].Width := gWalls[a].Width;
685 PanelArray[i].Height := gWalls[a].Height;
686 PanelArray[i].Active := True;
687 PanelArray[i].PanelID := a;
689 i := i + 1;
690 if i = len then
691 begin
692 len := len + 128;
693 SetLength(PanelArray, len);
694 end;
695 end;
697 // Íåò äâåðåé:
698 if i = 0 then
699 begin
700 PanelArray := nil;
701 Exit;
702 end;
704 SetLength(gDoorMap, 0);
706 g_Game_SetLoadingText(_lc[I_LOAD_DOOR_MAP], i-1, False);
708 for a := 0 to i-1 do
709 if PanelArray[a].Active then
710 begin
711 PanelArray[a].Active := False;
712 m := Length(gDoorMap);
713 SetLength(gDoorMap, m+1);
714 SetLength(gDoorMap[m], 1);
715 gDoorMap[m, 0] := PanelArray[a].PanelID;
716 ok := True;
718 while ok do
719 begin
720 ok := False;
722 for b := 0 to i-1 do
723 if PanelArray[b].Active then
724 for c := 0 to High(gDoorMap[m]) do
725 if {((gRenderWalls[PanelArray[b].RenderPanelID].TextureID = gRenderWalls[gDoorMap[m, c]].TextureID) or
726 gRenderWalls[PanelArray[b].RenderPanelID].Hide or gRenderWalls[gDoorMap[m, c]].Hide) and}
727 g_CollideAround(PanelArray[b].X, PanelArray[b].Y,
728 PanelArray[b].Width, PanelArray[b].Height,
729 gWalls[gDoorMap[m, c]].X,
730 gWalls[gDoorMap[m, c]].Y,
731 gWalls[gDoorMap[m, c]].Width,
732 gWalls[gDoorMap[m, c]].Height) then
733 begin
734 PanelArray[b].Active := False;
735 SetLength(gDoorMap[m],
736 Length(gDoorMap[m])+1);
737 gDoorMap[m, High(gDoorMap[m])] := PanelArray[b].PanelID;
738 ok := True;
739 Break;
740 end;
741 end;
743 g_Game_StepLoading();
744 end;
746 PanelArray := nil;
747 end;
749 procedure CreateLiftMap();
750 var
751 PanelArray: Array of record
752 X, Y: Integer;
753 Width, Height: Word;
754 Active: Boolean;
755 end;
756 a, b, c, len, i, j: Integer;
757 ok: Boolean;
758 begin
759 if gLifts = nil then
760 Exit;
762 len := Length(gLifts);
763 SetLength(PanelArray, len);
765 for a := 0 to len-1 do
766 begin
767 PanelArray[a].X := gLifts[a].X;
768 PanelArray[a].Y := gLifts[a].Y;
769 PanelArray[a].Width := gLifts[a].Width;
770 PanelArray[a].Height := gLifts[a].Height;
771 PanelArray[a].Active := True;
772 end;
774 SetLength(gLiftMap, len);
775 i := 0;
777 g_Game_SetLoadingText(_lc[I_LOAD_LIFT_MAP], len-1, False);
779 for a := 0 to len-1 do
780 if PanelArray[a].Active then
781 begin
782 PanelArray[a].Active := False;
783 SetLength(gLiftMap[i], 32);
784 j := 0;
785 gLiftMap[i, j] := a;
786 ok := True;
788 while ok do
789 begin
790 ok := False;
791 for b := 0 to len-1 do
792 if PanelArray[b].Active then
793 for c := 0 to j do
794 if g_CollideAround(PanelArray[b].X,
795 PanelArray[b].Y,
796 PanelArray[b].Width,
797 PanelArray[b].Height,
798 PanelArray[gLiftMap[i, c]].X,
799 PanelArray[gLiftMap[i, c]].Y,
800 PanelArray[gLiftMap[i, c]].Width,
801 PanelArray[gLiftMap[i, c]].Height) then
802 begin
803 PanelArray[b].Active := False;
804 j := j+1;
805 if j > High(gLiftMap[i]) then
806 SetLength(gLiftMap[i],
807 Length(gLiftMap[i])+32);
809 gLiftMap[i, j] := b;
810 ok := True;
812 Break;
813 end;
814 end;
816 SetLength(gLiftMap[i], j+1);
817 i := i+1;
819 g_Game_StepLoading();
820 end;
822 SetLength(gLiftMap, i);
824 PanelArray := nil;
825 end;
827 function CreatePanel (PanelRec: TDynRecord; AddTextures: TAddTextureArray; CurTex: Integer): Integer;
828 var
829 len: Integer;
830 panels: ^TPanelArray;
831 pan: TPanel;
832 pguid: Integer;
833 begin
834 Result := -1;
836 case PanelRec.PanelType of
837 PANEL_WALL, PANEL_OPENDOOR, PANEL_CLOSEDOOR: panels := @gWalls;
838 PANEL_BACK: panels := @gRenderBackgrounds;
839 PANEL_FORE: panels := @gRenderForegrounds;
840 PANEL_WATER: panels := @gWater;
841 PANEL_ACID1: panels := @gAcid1;
842 PANEL_ACID2: panels := @gAcid2;
843 PANEL_STEP: panels := @gSteps;
844 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: panels := @gLifts;
845 PANEL_BLOCKMON: panels := @gBlockMon;
846 else exit;
847 end;
849 len := Length(panels^);
850 SetLength(panels^, len+1);
852 pguid := Length(panByGUID);
853 SetLength(panByGUID, pguid+1); //FIXME!
854 pan := TPanel.Create(PanelRec, AddTextures, CurTex, Textures, pguid);
855 assert(pguid >= 0);
856 assert(pguid < Length(panByGUID));
857 panByGUID[pguid] := pan;
858 panels^[len] := pan;
859 pan.arrIdx := len;
860 pan.proxyId := -1;
861 pan.tag := panelTypeToTag(PanelRec.PanelType);
863 PanelRec.user['panel_guid'] := pguid;
865 //result := len;
866 result := pguid;
867 end;
870 function CreateNullTexture(RecName: String): Integer;
871 begin
872 RecName := toLowerCase1251(RecName);
873 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
874 if TextNameHash.get(RecName, result) then exit; // i found her!
876 SetLength(Textures, Length(Textures)+1);
877 result := High(Textures);
879 with Textures[High(Textures)] do
880 begin
881 TextureName := RecName;
882 Width := 1;
883 Height := 1;
884 Anim := False;
885 TextureID := LongWord(TEXTURE_NONE);
886 end;
888 TextNameHash.put(RecName, result);
889 end;
892 function extractWadName (resourceName: string): string;
893 var
894 posN: Integer;
895 begin
896 posN := Pos(':', resourceName);
897 if posN > 0 then
898 Result:= Copy(resourceName, 0, posN-1)
899 else
900 Result := '';
901 end;
904 procedure addResToExternalResList (res: AnsiString);
905 var
906 uname: AnsiString;
907 f: Integer;
908 fi: TDiskFileInfo;
909 begin
910 if g_Game_IsClient or not g_Game_IsNet then exit;
911 if (length(res) = 0) then exit; // map wad
912 //res := extractWadName(res);
913 //if (length(res) = 0) then exit; // map wad
914 uname := toLowerCase1251(res);
915 // do not add duplicates
916 for f := 0 to High(gExternalResources) do
917 begin
918 if (gExternalResources[f].userName = uname) then exit;
919 end;
920 //writeln('***(000) addResToExternalResList: res=[', res, ']');
921 // add new resource
922 fi.userName := uname;
923 if not findFileCI(res) then exit;
924 //writeln('***(001) addResToExternalResList: res=[', res, ']');
925 fi.diskName := res;
926 if (not GetDiskFileInfo(res, fi)) then
927 begin
928 fi.tag := -1;
929 end
930 else
931 begin
932 //writeln('***(002) addResToExternalResList: res=[', res, ']');
933 fi.tag := 0; // non-zero means "cannot caclucate hash"
934 try
935 fi.hash := MD5File(fi.diskName);
936 except
937 fi.tag := -1;
938 end;
939 end;
940 //e_LogWritefln('addext: res=[%s]; uname=[%s]; diskName=[%s]', [res, fi.userName, fi.diskName]);
941 SetLength(gExternalResources, length(gExternalResources)+1);
942 gExternalResources[High(gExternalResources)] := fi;
943 end;
946 procedure compactExtResList ();
947 var
948 src, dest: Integer;
949 begin
950 src := 0;
951 dest := 0;
952 for src := 0 to High(gExternalResources) do
953 begin
954 if (gExternalResources[src].tag = 0) then
955 begin
956 // copy it
957 if (dest <> src) then gExternalResources[dest] := gExternalResources[src];
958 Inc(dest);
959 end;
960 end;
961 if (dest <> length(gExternalResources)) then SetLength(gExternalResources, dest);
962 end;
965 function GetReplacementWad (WadName: AnsiString): AnsiString;
966 begin
967 result := '';
968 if WadName <> '' then
969 begin
970 result := WadName;
971 if g_Game_IsClient then result := g_Res_FindReplacementWad(WadName);
972 if (result = WadName) then result := e_FindWad(WadDirs, result)
973 end;
974 end;
977 procedure generateExternalResourcesList (map: TDynRecord);
978 begin
979 SetLength(gExternalResources, 0);
980 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.MusicName)));
981 addResToExternalResList(GetReplacementWad(g_ExtractWadName(map.SkyName)));
982 end;
985 function CreateTexture (RecName: AnsiString; Map: string; log: Boolean): Integer;
986 var
987 WAD: TWADFile;
988 TextureData: Pointer;
989 WADName: String;
990 a, ResLength: Integer;
991 begin
992 RecName := toLowerCase1251(RecName);
993 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
994 if TextNameHash.get(RecName, result) then
995 begin
996 // i found her!
997 //e_LogWritefln('texture ''%s'' already loaded (%s)', [RecName, result]);
998 exit;
999 end;
1001 Result := -1;
1003 if (BadTextNameHash <> nil) and BadTextNameHash.has(RecName) then exit; // don't do it again and again
1006 if Textures <> nil then
1007 begin
1008 for a := 0 to High(Textures) do
1009 begin
1010 if (Textures[a].TextureName = RecName) then
1011 begin // Òåêñòóðà ñ òàêèì èìåíåì óæå åñòü
1012 e_LogWritefln('texture ''%s'' already loaded', [RecName]);
1013 Result := a;
1014 Exit;
1015 end;
1016 end;
1017 end;
1020 // Òåêñòóðû ñî ñïåöèàëüíûìè èìåíàìè (âîäà, ëàâà, êèñëîòà):
1021 if (RecName = TEXTURE_NAME_WATER) or
1022 (RecName = TEXTURE_NAME_ACID1) or
1023 (RecName = TEXTURE_NAME_ACID2) then
1024 begin
1025 SetLength(Textures, Length(Textures)+1);
1027 with Textures[High(Textures)] do
1028 begin
1029 TextureName := RecName;
1030 if (TextureName = TEXTURE_NAME_WATER) then TextureID := LongWord(TEXTURE_SPECIAL_WATER)
1031 else if (TextureName = TEXTURE_NAME_ACID1) then TextureID := LongWord(TEXTURE_SPECIAL_ACID1)
1032 else if (TextureName = TEXTURE_NAME_ACID2) then TextureID := LongWord(TEXTURE_SPECIAL_ACID2);
1034 Anim := False;
1035 end;
1037 result := High(Textures);
1038 TextNameHash.put(RecName, result);
1039 Exit;
1040 end;
1042 // Çàãðóæàåì ðåñóðñ òåêñòóðû â ïàìÿòü èç WAD'à:
1043 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1044 if (WADName <> '') then addResToExternalResList(WADName);
1045 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1047 WAD := TWADFile.Create();
1048 WAD.ReadFile(WADName);
1050 //txname := RecName;
1052 if (WADName = Map) and WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength) then
1053 begin
1054 FreeMem(TextureData);
1055 RecName := 'COMMON\ALIEN';
1056 end;
1059 if WAD.GetResource(g_ExtractFilePathName(RecName), TextureData, ResLength, log) then
1060 begin
1061 SetLength(Textures, Length(Textures)+1);
1062 if not e_CreateTextureMem(TextureData, ResLength, Textures[High(Textures)].TextureID) then
1063 begin
1064 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1065 SetLength(Textures, Length(Textures)-1);
1066 result := -1;
1067 Exit;
1068 end;
1069 e_GetTextureSize(Textures[High(Textures)].TextureID, @Textures[High(Textures)].Width, @Textures[High(Textures)].Height);
1070 FreeMem(TextureData);
1071 Textures[High(Textures)].TextureName := RecName;
1072 Textures[High(Textures)].Anim := False;
1074 result := High(Textures);
1075 TextNameHash.put(RecName, result);
1076 end
1077 else // Íåò òàêîãî ðåóñðñà â WAD'å
1078 begin
1079 //e_WriteLog(Format('SHIT! Error loading texture %s : %s', [RecName, g_ExtractFilePathName(RecName)]), MSG_WARNING);
1080 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1081 if log and (not BadTextNameHash.get(RecName, a)) then
1082 begin
1083 e_WriteLog(Format('Error loading texture %s', [RecName]), TMsgType.Warning);
1084 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1085 end;
1086 BadTextNameHash.put(RecName, -1);
1087 end;
1089 WAD.Free();
1090 end;
1093 function CreateAnimTexture(RecName: String; Map: string; log: Boolean): Integer;
1094 var
1095 WAD: TWADFile;
1096 TextureWAD: PChar = nil;
1097 TextData: Pointer = nil;
1098 TextureData: Pointer = nil;
1099 cfg: TConfig = nil;
1100 WADName: String;
1101 ResLength: Integer;
1102 TextureResource: String;
1103 _width, _height, _framecount, _speed: Integer;
1104 _backanimation: Boolean;
1105 //imgfmt: string;
1106 ia: TDynImageDataArray = nil;
1107 f, c, frdelay, frloop: Integer;
1108 begin
1109 RecName := toLowerCase1251(RecName);
1110 if (TextNameHash = nil) then TextNameHash := THashStrInt.Create();
1111 if TextNameHash.get(RecName, result) then
1112 begin
1113 // i found her!
1114 //e_LogWritefln('animated texture ''%s'' already loaded (%s)', [RecName, result]);
1115 exit;
1116 end;
1118 result := -1;
1120 //e_LogWritefln('*** Loading animated texture "%s"', [RecName]);
1122 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1123 if BadTextNameHash.get(RecName, f) then
1124 begin
1125 //e_WriteLog(Format('no animation texture %s (don''t worry)', [RecName]), MSG_NOTIFY);
1126 exit;
1127 end;
1129 // ×èòàåì WAD-ðåñóðñ àíèì.òåêñòóðû èç WAD'à â ïàìÿòü:
1130 WADName := GetReplacementWad(g_ExtractWadName(RecName));
1131 if (WADName <> '') then addResToExternalResList(WADName);
1132 if WADName = '' then WADName := Map; //WADName := GameDir+'/wads/'+WADName else
1134 WAD := TWADFile.Create();
1135 try
1136 //if WADName <> '' then WADName := GameDir+'/wads/'+WADName else WADName := Map;
1138 WAD.ReadFile(WADName);
1140 if not WAD.GetResource(g_ExtractFilePathName(RecName), TextureWAD, ResLength, log) then
1141 begin
1142 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1143 if log and (not BadTextNameHash.get(RecName, f)) then
1144 begin
1145 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1146 //e_WriteLog(Format('WAD Reader error: %s', [WAD.GetLastErrorStr]), MSG_WARNING);
1147 end;
1148 BadTextNameHash.put(RecName, -1);
1149 exit;
1150 end;
1152 {TEST
1153 if WADName = Map then
1154 begin
1155 //FreeMem(TextureWAD);
1156 if not WAD.GetResource('COMMON/animation', TextureWAD, ResLength) then Halt(1);
1157 end;
1160 WAD.FreeWAD();
1162 if ResLength < 6 then
1163 begin
1164 e_WriteLog(Format('Animated texture file "%s" too short', [RecName]), TMsgType.Warning);
1165 BadTextNameHash.put(RecName, -1);
1166 exit;
1167 end;
1169 // ýòî ïòèöà? ýòî ñàìîë¸ò?
1170 if isWadData(TextureWAD, ResLength) then
1171 begin
1172 // íåò, ýòî ñóïåðìåí!
1173 if not WAD.ReadMemory(TextureWAD, ResLength) then
1174 begin
1175 e_WriteLog(Format('Animated texture WAD file "%s" is invalid', [RecName]), TMsgType.Warning);
1176 BadTextNameHash.put(RecName, -1);
1177 exit;
1178 end;
1180 // ×èòàåì INI-ðåñóðñ àíèì. òåêñòóðû è çàïîìèíàåì åãî óñòàíîâêè:
1181 if not WAD.GetResource('TEXT/ANIM', TextData, ResLength) then
1182 begin
1183 e_WriteLog(Format('Animated texture file "%s" has invalid INI', [RecName]), TMsgType.Warning);
1184 BadTextNameHash.put(RecName, -1);
1185 exit;
1186 end;
1188 cfg := TConfig.CreateMem(TextData, ResLength);
1190 TextureResource := cfg.ReadStr('', 'resource', '');
1191 if TextureResource = '' then
1192 begin
1193 e_WriteLog(Format('Animated texture WAD file "%s" has no "resource"', [RecName]), TMsgType.Warning);
1194 BadTextNameHash.put(RecName, -1);
1195 exit;
1196 end;
1198 _width := cfg.ReadInt('', 'framewidth', 0);
1199 _height := cfg.ReadInt('', 'frameheight', 0);
1200 _framecount := cfg.ReadInt('', 'framecount', 0);
1201 _speed := cfg.ReadInt('', 'waitcount', 0);
1202 _backanimation := cfg.ReadBool('', 'backanimation', False);
1204 cfg.Free();
1205 cfg := nil;
1207 // ×èòàåì ðåñóðñ òåêñòóð (êàäðîâ) àíèì. òåêñòóðû â ïàìÿòü:
1208 if not WAD.GetResource('TEXTURES/'+TextureResource, TextureData, ResLength) then
1209 begin
1210 e_WriteLog(Format('Animated texture WAD file "%s" has no texture "%s"', [RecName, 'TEXTURES/'+TextureResource]), TMsgType.Warning);
1211 BadTextNameHash.put(RecName, -1);
1212 exit;
1213 end;
1215 WAD.Free();
1216 WAD := nil;
1218 SetLength(Textures, Length(Textures)+1);
1219 with Textures[High(Textures)] do
1220 begin
1221 // Ñîçäàåì êàäðû àíèì. òåêñòóðû èç ïàìÿòè:
1222 if g_Frames_CreateMemory(@FramesID, '', TextureData, ResLength, _width, _height, _framecount, _backanimation) then
1223 begin
1224 TextureName := RecName;
1225 Width := _width;
1226 Height := _height;
1227 Anim := True;
1228 FramesCount := _framecount;
1229 Speed := _speed;
1230 result := High(Textures);
1231 TextNameHash.put(RecName, result);
1232 end
1233 else
1234 begin
1235 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1236 if log and (not BadTextNameHash.get(RecName, f)) then
1237 begin
1238 e_WriteLog(Format('Error loading animation texture %s', [RecName]), TMsgType.Warning);
1239 end;
1240 BadTextNameHash.put(RecName, -1);
1241 end;
1242 end;
1243 end
1244 else
1245 begin
1246 // try animated image
1248 imgfmt := DetermineMemoryFormat(TextureWAD, ResLength);
1249 if length(imgfmt) = 0 then
1250 begin
1251 e_WriteLog(Format('Animated texture file "%s" has unknown format', [RecName]), MSG_WARNING);
1252 exit;
1253 end;
1255 GlobalMetadata.ClearMetaItems();
1256 GlobalMetadata.ClearMetaItemsForSaving();
1257 if not LoadMultiImageFromMemory(TextureWAD, ResLength, ia) then
1258 begin
1259 e_WriteLog(Format('Animated texture file "%s" cannot be loaded', [RecName]), TMsgType.Warning);
1260 BadTextNameHash.put(RecName, -1);
1261 exit;
1262 end;
1263 if length(ia) = 0 then
1264 begin
1265 e_WriteLog(Format('Animated texture file "%s" has no frames', [RecName]), TMsgType.Warning);
1266 BadTextNameHash.put(RecName, -1);
1267 exit;
1268 end;
1270 WAD.Free();
1271 WAD := nil;
1273 _width := ia[0].width;
1274 _height := ia[0].height;
1275 _framecount := length(ia);
1276 _speed := 1;
1277 _backanimation := false;
1278 frdelay := -1;
1279 frloop := -666;
1280 if GlobalMetadata.HasMetaItem(SMetaFrameDelay) then
1281 begin
1282 //writeln(' frame delay: ', GlobalMetadata.MetaItems[SMetaFrameDelay]);
1283 try
1284 f := GlobalMetadata.MetaItems[SMetaFrameDelay];
1285 frdelay := f;
1286 if f < 0 then f := 0;
1287 // rounding ;-)
1288 c := f mod 28;
1289 if c < 13 then c := 0 else c := 1;
1290 f := (f div 28)+c;
1291 if f < 1 then f := 1 else if f > 255 then f := 255;
1292 _speed := f;
1293 except
1294 end;
1295 end;
1296 if GlobalMetadata.HasMetaItem(SMetaAnimationLoops) then
1297 begin
1298 //writeln(' frame loop : ', GlobalMetadata.MetaItems[SMetaAnimationLoops]);
1299 try
1300 f := GlobalMetadata.MetaItems[SMetaAnimationLoops];
1301 frloop := f;
1302 if f <> 0 then _backanimation := true; // non-infinite looping == forth-and-back
1303 except
1304 end;
1305 end;
1306 //writeln(' creating animated texture with ', length(ia), ' frames (delay:', _speed, '; backloop:', _backanimation, ') from "', RecName, '"...');
1307 //for f := 0 to high(ia) do writeln(' frame #', f, ': ', ia[f].width, 'x', ia[f].height);
1308 f := ord(_backanimation);
1309 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);
1311 SetLength(Textures, Length(Textures)+1);
1312 // cîçäàåì êàäðû àíèì. òåêñòóðû èç êàðòèíîê
1313 if g_CreateFramesImg(ia, @Textures[High(Textures)].FramesID, '', _backanimation) then
1314 begin
1315 Textures[High(Textures)].TextureName := RecName;
1316 Textures[High(Textures)].Width := _width;
1317 Textures[High(Textures)].Height := _height;
1318 Textures[High(Textures)].Anim := True;
1319 Textures[High(Textures)].FramesCount := length(ia);
1320 Textures[High(Textures)].Speed := _speed;
1321 result := High(Textures);
1322 TextNameHash.put(RecName, result);
1323 //writeln(' CREATED!');
1324 end
1325 else
1326 begin
1327 if (BadTextNameHash = nil) then BadTextNameHash := THashStrInt.Create();
1328 if log and (not BadTextNameHash.get(RecName, f)) then
1329 begin
1330 e_WriteLog(Format('Error loading animation texture "%s" images', [RecName]), TMsgType.Warning);
1331 end;
1332 BadTextNameHash.put(RecName, -1);
1333 end;
1334 end;
1335 finally
1336 for f := 0 to High(ia) do FreeImage(ia[f]);
1337 WAD.Free();
1338 cfg.Free();
1339 if (TextureWAD <> nil) then FreeMem(TextureWAD);
1340 if (TextData <> nil) then FreeMem(TextData);
1341 if (TextureData <> nil) then FreeMem(TextureData);
1342 end;
1343 end;
1345 procedure CreateItem(Item: TDynRecord);
1346 begin
1347 if g_Game_IsClient then Exit;
1349 if (not (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF])) and
1350 ByteBool(Item.Options and ITEM_OPTION_ONLYDM) then
1351 Exit;
1353 g_Items_Create(Item.X, Item.Y, Item.ItemType, ByteBool(Item.Options and ITEM_OPTION_FALL),
1354 gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF, GM_COOP]);
1355 end;
1357 procedure CreateArea(Area: TDynRecord);
1358 var
1359 a: Integer;
1360 id: DWORD = 0;
1361 begin
1362 case Area.AreaType of
1363 AREA_DMPOINT, AREA_PLAYERPOINT1, AREA_PLAYERPOINT2,
1364 AREA_REDTEAMPOINT, AREA_BLUETEAMPOINT:
1365 begin
1366 SetLength(RespawnPoints, Length(RespawnPoints)+1);
1367 with RespawnPoints[High(RespawnPoints)] do
1368 begin
1369 X := Area.X;
1370 Y := Area.Y;
1371 Direction := TDirection(Area.Direction);
1373 case Area.AreaType of
1374 AREA_DMPOINT: PointType := RESPAWNPOINT_DM;
1375 AREA_PLAYERPOINT1: PointType := RESPAWNPOINT_PLAYER1;
1376 AREA_PLAYERPOINT2: PointType := RESPAWNPOINT_PLAYER2;
1377 AREA_REDTEAMPOINT: PointType := RESPAWNPOINT_RED;
1378 AREA_BLUETEAMPOINT: PointType := RESPAWNPOINT_BLUE;
1379 end;
1380 end;
1381 end;
1383 AREA_REDFLAG, AREA_BLUEFLAG:
1384 begin
1385 if Area.AreaType = AREA_REDFLAG then a := FLAG_RED else a := FLAG_BLUE;
1387 if FlagPoints[a] <> nil then Exit;
1389 New(FlagPoints[a]);
1391 with FlagPoints[a]^ do
1392 begin
1393 X := Area.X-FLAGRECT.X;
1394 Y := Area.Y-FLAGRECT.Y;
1395 Direction := TDirection(Area.Direction);
1396 end;
1398 with gFlags[a] do
1399 begin
1400 case a of
1401 FLAG_RED: g_Frames_Get(id, 'FRAMES_FLAG_RED');
1402 FLAG_BLUE: g_Frames_Get(id, 'FRAMES_FLAG_BLUE');
1403 end;
1405 Animation := TAnimation.Create(id, True, 8);
1406 Obj.Rect := FLAGRECT;
1408 g_Map_ResetFlag(a);
1409 end;
1410 end;
1412 AREA_DOMFLAG:
1413 begin
1414 {SetLength(DOMFlagPoints, Length(DOMFlagPoints)+1);
1415 with DOMFlagPoints[High(DOMFlagPoints)] do
1416 begin
1417 X := Area.X;
1418 Y := Area.Y;
1419 Direction := TDirection(Area.Direction);
1420 end;
1422 g_Map_CreateFlag(DOMFlagPoints[High(DOMFlagPoints)], FLAG_DOM, FLAG_STATE_NORMAL);}
1423 end;
1424 end;
1425 end;
1427 function CreateTrigger (amapIdx: Integer; Trigger: TDynRecord; atpanid, atrigpanid: Integer): Integer;
1428 var
1429 _trigger: TTrigger;
1430 tp: TPanel;
1431 begin
1432 result := -1;
1433 if g_Game_IsClient and not (Trigger.TriggerType in [TRIGGER_SOUND, TRIGGER_MUSIC]) then Exit;
1435 with _trigger do
1436 begin
1437 mapId := Trigger.id;
1438 mapIndex := amapIdx;
1439 X := Trigger.X;
1440 Y := Trigger.Y;
1441 Width := Trigger.Width;
1442 Height := Trigger.Height;
1443 Enabled := Trigger.Enabled;
1444 TexturePanelGUID := atpanid;
1445 TriggerType := Trigger.TriggerType;
1446 ActivateType := Trigger.ActivateType;
1447 Keys := Trigger.Keys;
1448 trigPanelGUID := atrigpanid;
1449 // HACK: used in TPanel.CanChangeTexture. maybe there's a better way?
1450 if TexturePanelGUID <> -1 then
1451 begin
1452 tp := g_Map_PanelByGUID(TexturePanelGUID);
1453 if (tp <> nil) then tp.hasTexTrigger := True;
1454 end;
1455 end;
1457 result := Integer(g_Triggers_Create(_trigger, Trigger));
1458 end;
1460 procedure CreateMonster(monster: TDynRecord);
1461 var
1462 a: Integer;
1463 mon: TMonster;
1464 begin
1465 if g_Game_IsClient then Exit;
1467 if (gGameSettings.GameType = GT_SINGLE)
1468 or LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS) then
1469 begin
1470 mon := g_Monsters_Create(monster.MonsterType, monster.X, monster.Y, TDirection(monster.Direction));
1472 if gTriggers <> nil then
1473 begin
1474 for a := 0 to High(gTriggers) do
1475 begin
1476 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1477 begin
1478 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1479 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1480 end;
1481 end;
1482 end;
1484 if monster.MonsterType <> MONSTER_BARREL then Inc(gTotalMonsters);
1485 end;
1486 end;
1488 procedure g_Map_ReAdd_DieTriggers();
1490 function monsDieTrig (mon: TMonster): Boolean;
1491 var
1492 a: Integer;
1493 //tw: TStrTextWriter;
1494 begin
1495 result := false; // don't stop
1496 mon.ClearTriggers();
1497 for a := 0 to High(gTriggers) do
1498 begin
1499 if gTriggers[a].TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF] then
1500 begin
1501 //if (gTriggers[a].Data.MonsterID-1) = Integer(mon.StartID) then mon.AddTrigger(a);
1503 tw := TStrTextWriter.Create();
1504 try
1505 gTriggers[a].trigData.writeTo(tw);
1506 e_LogWritefln('=== trigger #%s ==='#10'%s'#10'---', [a, tw.str]);
1507 finally
1508 tw.Free();
1509 end;
1511 if (gTriggers[a].trigDataRec.trigMonsterId) = Integer(mon.StartID) then mon.AddTrigger(a);
1512 end;
1513 end;
1514 end;
1516 begin
1517 if g_Game_IsClient then Exit;
1519 g_Mons_ForEach(monsDieTrig);
1520 end;
1522 procedure mapCreateGrid ();
1523 var
1524 mapX0: Integer = $3fffffff;
1525 mapY0: Integer = $3fffffff;
1526 mapX1: Integer = -$3fffffff;
1527 mapY1: Integer = -$3fffffff;
1529 procedure calcBoundingBox (constref panels: TPanelArray);
1530 var
1531 idx: Integer;
1532 pan: TPanel;
1533 begin
1534 for idx := 0 to High(panels) do
1535 begin
1536 pan := panels[idx];
1537 if not pan.visvalid then continue;
1538 if (pan.Width < 1) or (pan.Height < 1) then continue;
1539 if (mapX0 > pan.x0) then mapX0 := pan.x0;
1540 if (mapY0 > pan.y0) then mapY0 := pan.y0;
1541 if (mapX1 < pan.x1) then mapX1 := pan.x1;
1542 if (mapY1 < pan.y1) then mapY1 := pan.y1;
1543 end;
1544 end;
1546 procedure addPanelsToGrid (constref panels: TPanelArray);
1547 var
1548 idx: Integer;
1549 pan: TPanel;
1550 newtag: Integer;
1551 begin
1552 //tag := panelTypeToTag(tag);
1553 for idx := 0 to High(panels) do
1554 begin
1555 pan := panels[idx];
1556 if not pan.visvalid then continue;
1557 if (pan.proxyId <> -1) then
1558 begin
1559 {$IF DEFINED(D2F_DEBUG)}
1560 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);
1561 {$ENDIF}
1562 continue;
1563 end;
1564 case pan.PanelType of
1565 PANEL_WALL: newtag := GridTagWall;
1566 PANEL_OPENDOOR, PANEL_CLOSEDOOR: newtag := GridTagDoor;
1567 PANEL_BACK: newtag := GridTagBack;
1568 PANEL_FORE: newtag := GridTagFore;
1569 PANEL_WATER: newtag := GridTagWater;
1570 PANEL_ACID1: newtag := GridTagAcid1;
1571 PANEL_ACID2: newtag := GridTagAcid2;
1572 PANEL_STEP: newtag := GridTagStep;
1573 PANEL_LIFTUP, PANEL_LIFTDOWN, PANEL_LIFTLEFT, PANEL_LIFTRIGHT: newtag := GridTagLift;
1574 PANEL_BLOCKMON: newtag := GridTagBlockMon;
1575 else continue; // oops
1576 end;
1577 pan.tag := newtag;
1579 pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, newtag);
1580 // "enabled" flag has meaning only for doors and walls (engine assumes it); but meh...
1581 mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
1582 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
1584 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
1585 begin
1586 e_WriteLog(Format('INSERTED wall #%d(%d) enabled (%d)', [Integer(idx), Integer(pan.proxyId), Integer(mapGrid.proxyEnabled[pan.proxyId])]), MSG_NOTIFY);
1587 end;
1589 {$ENDIF}
1590 end;
1591 end;
1593 begin
1594 mapGrid.Free();
1595 mapGrid := nil;
1597 calcBoundingBox(gWalls);
1598 calcBoundingBox(gRenderBackgrounds);
1599 calcBoundingBox(gRenderForegrounds);
1600 calcBoundingBox(gWater);
1601 calcBoundingBox(gAcid1);
1602 calcBoundingBox(gAcid2);
1603 calcBoundingBox(gSteps);
1604 calcBoundingBox(gLifts);
1605 calcBoundingBox(gBlockMon);
1607 e_LogWritefln('map dimensions: (%d,%d)-(%d,%d); editor size:(0,0)-(%d,%d)', [mapX0, mapY0, mapX1, mapY1, gMapInfo.Width, gMapInfo.Height]);
1609 if (mapX0 > 0) then mapX0 := 0;
1610 if (mapY0 > 0) then mapY0 := 0;
1612 if (mapX1 < gMapInfo.Width-1) then mapX1 := gMapInfo.Width-1;
1613 if (mapY1 < gMapInfo.Height-1) then mapY1 := gMapInfo.Height-1;
1615 mapGrid := TPanelGrid.Create(mapX0-128, mapY0-128, mapX1-mapX0+1+128*2, mapY1-mapY0+1+128*2);
1616 //mapGrid := TPanelGrid.Create(0, 0, gMapInfo.Width, gMapInfo.Height);
1618 addPanelsToGrid(gWalls);
1619 addPanelsToGrid(gRenderBackgrounds);
1620 addPanelsToGrid(gRenderForegrounds);
1621 addPanelsToGrid(gWater);
1622 addPanelsToGrid(gAcid1);
1623 addPanelsToGrid(gAcid2);
1624 addPanelsToGrid(gSteps);
1625 addPanelsToGrid(gLifts); // it doesn't matter which LIFT type is used here
1626 addPanelsToGrid(gBlockMon);
1628 mapGrid.dumpStats();
1630 g_Mons_InitTree(mapGrid.gridX0, mapGrid.gridY0, mapGrid.gridWidth, mapGrid.gridHeight);
1631 end;
1634 function g_Map_Load(Res: String): Boolean;
1635 const
1636 DefaultMusRes = 'Standart.wad:STDMUS\MUS1';
1637 DefaultSkyRes = 'Standart.wad:STDSKY\SKY0';
1638 type
1639 PTRec = ^TTRec;
1640 TTRec = record
1641 //TexturePanel: Integer;
1642 tnum: Integer;
1643 id: Integer;
1644 trigrec: TDynRecord;
1645 // texture pane;
1646 texPanelIdx: Integer;
1647 texPanel: TDynRecord;
1648 // "action" panel
1649 actPanelIdx: Integer;
1650 actPanel: TDynRecord;
1651 end;
1652 var
1653 WAD, TestWAD: TWADFile;
1654 //mapReader: TDynRecord = nil;
1655 mapTextureList: TDynField = nil; //TTexturesRec1Array; tagInt: texture index
1656 panels: TDynField = nil; //TPanelsRec1Array;
1657 items: TDynField = nil; //TItemsRec1Array;
1658 monsters: TDynField = nil; //TMonsterRec1Array;
1659 areas: TDynField = nil; //TAreasRec1Array;
1660 triggers: TDynField = nil; //TTriggersRec1Array;
1661 b, c, k: Integer;
1662 PanelID: DWORD;
1663 AddTextures: TAddTextureArray;
1664 TriggersTable: array of TTRec;
1665 FileName, mapResName, TexName, s: AnsiString;
1666 Data: Pointer;
1667 Len: Integer;
1668 ok, isAnim: Boolean;
1669 CurTex, ntn: Integer;
1670 rec, texrec: TDynRecord;
1671 pttit: PTRec;
1672 pannum, trignum, cnt, tgpid: Integer;
1673 stt: UInt64;
1674 moveSpeed{, moveStart, moveEnd}: TDFPoint;
1675 //moveActive: Boolean;
1676 pan: TPanel;
1677 mapOk: Boolean = false;
1678 usedTextures: THashStrInt = nil; // key: mapTextureList
1679 begin
1680 mapGrid.Free();
1681 mapGrid := nil;
1682 TestWAD := nil;
1683 Data := nil;
1685 //gCurrentMap.Free();
1686 //gCurrentMap := nil;
1688 panByGUID := nil;
1690 Result := False;
1691 gMapInfo.Map := Res;
1692 TriggersTable := nil;
1693 //mapReader := nil;
1695 sfsGCDisable(); // temporary disable removing of temporary volumes
1696 try
1697 // Çàãðóçêà WAD (åñëè ó íàñ íåò óæå çàãðóæåíîé êàðòû)
1698 if (gCurrentMap = nil) then
1699 begin
1700 FileName := g_ExtractWadName(Res);
1701 e_LogWritefln('Loading map WAD [%s] (res=[%s])', [FileName, Res], TMsgType.Notify);
1702 g_Game_SetLoadingText(_lc[I_LOAD_WAD_FILE], 0, False);
1704 WAD := TWADFile.Create();
1705 if not WAD.ReadFile(FileName) then
1706 begin
1707 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_WAD], [FileName]));
1708 WAD.Free();
1709 Exit;
1710 end;
1712 if gTestMap <> '' then
1713 begin
1714 s := g_ExtractWadName(gTestMap);
1715 TestWAD := TWADFile.Create();
1716 if not TestWAD.ReadFile(s) then
1717 begin
1718 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_WAD], [s]));
1719 TestWAD.Free();
1720 TestWAD := nil;
1721 end;
1722 end;
1724 if TestWAD <> nil then
1725 begin
1726 mapResName := g_ExtractFileName(gTestMap);
1727 if not TestWAD.GetMapResource(mapResName, Data, Len) then
1728 begin
1729 g_SimpleError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1730 Data := nil;
1731 end else
1732 e_WriteLog('Using test map: '+gTestMap, TMsgType.Notify);
1733 TestWAD.Free();
1734 TestWAD := nil;
1735 end;
1737 if Data = nil then
1738 begin
1739 //k8: why loader ignores path here?
1740 mapResName := g_ExtractFileName(Res);
1741 if not WAD.GetMapResource(mapResName, Data, Len) then
1742 begin
1743 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_RES], [mapResName]));
1744 WAD.Free();
1745 Exit;
1746 end;
1747 end;
1749 WAD.Free();
1751 if (Len < 4) then
1752 begin
1753 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1754 FreeMem(Data);
1755 exit;
1756 end;
1758 // Çàãðóçêà êàðòû:
1759 e_LogWritefln('Loading map: %s', [mapResName], TMsgType.Notify);
1760 g_Game_SetLoadingText(_lc[I_LOAD_MAP], 0, False);
1762 stt := getTimeMicro();
1764 try
1765 gCurrentMap := g_Map_ParseMap(Data, Len);
1766 except
1767 gCurrentMap.Free();
1768 g_FatalError(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]));
1769 FreeMem(Data);
1770 gCurrentMapFileName := '';
1771 Exit;
1772 end;
1774 FreeMem(Data);
1776 if (gCurrentMap = nil) then
1777 begin
1778 e_LogWritefln('invalid map file: ''%s''', [mapResName]);
1779 gCurrentMapFileName := '';
1780 exit;
1781 end;
1782 end
1783 else
1784 begin
1785 stt := getTimeMicro();
1786 end;
1788 //gCurrentMap := mapReader;
1790 generateExternalResourcesList(gCurrentMap);
1791 mapTextureList := gCurrentMap['texture'];
1792 // get all other lists here too
1793 panels := gCurrentMap['panel'];
1794 triggers := gCurrentMap['trigger'];
1795 items := gCurrentMap['item'];
1796 areas := gCurrentMap['area'];
1797 monsters := gCurrentMap['monster'];
1799 // Çàãðóçêà îïèñàíèÿ êàðòû:
1800 e_WriteLog(' Reading map info...', TMsgType.Notify);
1801 g_Game_SetLoadingText(_lc[I_LOAD_MAP_HEADER], 0, False);
1803 with gMapInfo do
1804 begin
1805 Name := gCurrentMap.MapName;
1806 Description := gCurrentMap.MapDesc;
1807 Author := gCurrentMap.MapAuthor;
1808 MusicName := gCurrentMap.MusicName;
1809 SkyName := gCurrentMap.SkyName;
1810 Height := gCurrentMap.Height;
1811 Width := gCurrentMap.Width;
1812 end;
1814 // Çàãðóçêà òåêñòóð:
1815 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], 0, False);
1816 // Äîáàâëåíèå òåêñòóð â Textures[]:
1817 if (mapTextureList <> nil) and (mapTextureList.count > 0) then
1818 begin
1819 e_WriteLog(' Loading textures:', TMsgType.Notify);
1820 g_Game_SetLoadingText(_lc[I_LOAD_TEXTURES], mapTextureList.count-1, False);
1822 // find used textures
1823 usedTextures := THashStrInt.Create();
1824 try
1825 if (panels <> nil) and (panels.count > 0) then
1826 begin
1827 for rec in panels do
1828 begin
1829 texrec := rec.TextureRec;
1830 if (texrec <> nil) then usedTextures.put(toLowerCase1251(texrec.Resource), 42);
1831 end;
1832 end;
1834 cnt := -1;
1835 for rec in mapTextureList do
1836 begin
1837 Inc(cnt);
1838 if not usedTextures.has(toLowerCase1251(rec.Resource)) then
1839 begin
1840 rec.tagInt := -1; // just in case
1841 e_LogWritefln(' Unused texture #%d: %s', [cnt, rec.Resource]);
1842 end
1843 else
1844 begin
1845 {$IF DEFINED(D2F_DEBUG_TXLOAD)}
1846 e_LogWritefln(' Loading texture #%d: %s', [cnt, rec.Resource]);
1847 {$ENDIF}
1848 //if g_Map_IsSpecialTexture(s) then e_WriteLog(' SPECIAL!', MSG_NOTIFY);
1849 if rec.Anim then
1850 begin
1851 // Àíèìèðîâàííàÿ òåêñòóðà
1852 ntn := CreateAnimTexture(rec.Resource, FileName, True);
1853 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_ANIM], [rec.Resource]));
1854 end
1855 else
1856 begin
1857 // Îáû÷íàÿ òåêñòóðà
1858 ntn := CreateTexture(rec.Resource, FileName, True);
1859 if (ntn < 0) then g_SimpleError(Format(_lc[I_GAME_ERROR_TEXTURE_SIMPLE], [rec.Resource]));
1860 end;
1861 if (ntn < 0) then ntn := CreateNullTexture(rec.Resource);
1863 rec.tagInt := ntn; // remember texture number
1864 end;
1865 g_Game_StepLoading();
1866 end;
1867 finally
1868 usedTextures.Free();
1869 end;
1871 // set panel tagInt to texture index
1872 if (panels <> nil) then
1873 begin
1874 for rec in panels do
1875 begin
1876 texrec := rec.TextureRec;
1877 if (texrec = nil) then rec.tagInt := -1 else rec.tagInt := texrec.tagInt;
1878 end;
1879 end;
1880 end;
1883 // Çàãðóçêà òðèããåðîâ
1884 gTriggerClientID := 0;
1885 e_WriteLog(' Loading triggers...', TMsgType.Notify);
1886 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS], 0, False);
1888 // Çàãðóçêà ïàíåëåé
1889 e_WriteLog(' Loading panels...', TMsgType.Notify);
1890 g_Game_SetLoadingText(_lc[I_LOAD_PANELS], 0, False);
1892 // check texture numbers for panels
1893 if (panels <> nil) and (panels.count > 0) then
1894 begin
1895 for rec in panels do
1896 begin
1897 if (rec.tagInt < 0) then
1898 begin
1899 e_WriteLog('error loading map: invalid texture index for panel', TMsgType.Fatal);
1900 result := false;
1901 gCurrentMap.Free();
1902 gCurrentMap := nil;
1903 gCurrentMapFileName := '';
1904 exit;
1905 end;
1906 end;
1907 end;
1909 // Ñîçäàíèå òàáëèöû òðèããåðîâ (ñîîòâåòñòâèå ïàíåëåé òðèããåðàì)
1910 if (triggers <> nil) and (triggers.count > 0) then
1911 begin
1912 e_WriteLog(' Setting up trigger table...', TMsgType.Notify);
1913 //SetLength(TriggersTable, triggers.count);
1914 g_Game_SetLoadingText(_lc[I_LOAD_TRIGGERS_TABLE], triggers.count-1, False);
1916 SetLength(TriggersTable, triggers.count);
1917 trignum := -1;
1918 for rec in triggers do
1919 begin
1920 Inc(trignum);
1921 pttit := @TriggersTable[trignum];
1922 pttit.trigrec := rec;
1923 // Ñìåíà òåêñòóðû (âîçìîæíî, êíîïêè)
1924 pttit.texPanelIdx := -1; // will be fixed later
1925 pttit.texPanel := rec.TexturePanelRec;
1926 // action panel
1927 pttit.actPanelIdx := -1;
1928 if (rec.trigRec <> nil) then pttit.actPanel := rec.trigRec.tgPanelRec else pttit.actPanel := nil;
1929 // set flag
1930 if (pttit.texPanel <> nil) then pttit.texPanel.userPanelTrigRef := true;
1931 if (pttit.actPanel <> nil) then pttit.actPanel.userPanelTrigRef := true;
1932 // update progress
1933 g_Game_StepLoading();
1934 end;
1935 end;
1937 // Ñîçäàåì ïàíåëè
1938 if (panels <> nil) and (panels.count > 0) then
1939 begin
1940 e_WriteLog(' Setting up trigger links...', TMsgType.Notify);
1941 g_Game_SetLoadingText(_lc[I_LOAD_LINK_TRIGGERS], panels.count-1, False);
1943 pannum := -1;
1944 for rec in panels do
1945 begin
1946 Inc(pannum);
1947 //e_LogWritefln('PANSTART: pannum=%s', [pannum]);
1948 texrec := nil;
1949 SetLength(AddTextures, 0);
1950 CurTex := -1;
1951 ok := false;
1953 if (mapTextureList <> nil) then
1954 begin
1955 texrec := rec.TextureRec;
1956 ok := (texrec <> nil);
1957 end;
1959 if ok then
1960 begin
1961 // Ñìîòðèì, ññûëàþòñÿ ëè íà ýòó ïàíåëü òðèããåðû.
1962 // Åñëè äà - òî íàäî ñîçäàòü åùå òåêñòóð
1963 ok := false;
1964 if (TriggersTable <> nil) and (mapTextureList <> nil) then
1965 begin
1966 if rec.userPanelTrigRef then
1967 begin
1968 // e_LogWritefln('trigref for panel %s', [pannum]);
1969 ok := True;
1970 end;
1971 end;
1972 end;
1974 if ok then
1975 begin
1976 // Åñòü ññûëêè òðèããåðîâ íà ýòó ïàíåëü
1977 s := texrec.Resource;
1979 // Ñïåö-òåêñòóðû çàïðåùåíû
1980 if g_Map_IsSpecialTexture(s) then
1981 begin
1982 ok := false
1983 end
1984 else
1985 begin
1986 // Îïðåäåëÿåì íàëè÷èå è ïîëîæåíèå öèôð â êîíöå ñòðîêè
1987 ok := g_Texture_NumNameFindStart(s);
1988 end;
1990 // Åñëè ok, çíà÷èò åñòü öèôðû â êîíöå.
1991 // Çàãðóæàåì òåêñòóðû ñ îñòàëüíûìè #
1992 if ok then
1993 begin
1994 k := NNF_NAME_BEFORE;
1995 // Öèêë ïî èçìåíåíèþ èìåíè òåêñòóðû
1996 while ok or (k = NNF_NAME_BEFORE) or (k = NNF_NAME_EQUALS) do
1997 begin
1998 k := g_Texture_NumNameFindNext(TexName);
2000 if (k = NNF_NAME_BEFORE) or (k = NNF_NAME_AFTER) then
2001 begin
2002 // Ïðîáóåì äîáàâèòü íîâóþ òåêñòóðó
2003 if texrec.Anim then
2004 begin
2005 // Íà÷àëüíàÿ - àíèìèðîâàííàÿ, èùåì àíèìèðîâàííóþ
2006 isAnim := True;
2007 //e_LogWritefln('000: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2008 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2009 //e_LogWritefln('001: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2010 if not ok then
2011 begin
2012 // Íåò àíèìèðîâàííîé, èùåì îáû÷íóþ
2013 isAnim := False;
2014 //e_LogWritefln('002: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2015 ok := CreateTexture(TexName, FileName, False) >= 0;
2016 //e_LogWritefln('003: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2017 end;
2018 end
2019 else
2020 begin
2021 // Íà÷àëüíàÿ - îáû÷íàÿ, èùåì îáû÷íóþ
2022 isAnim := False;
2023 //e_LogWritefln('004: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2024 ok := CreateTexture(TexName, FileName, False) >= 0;
2025 //e_LogWritefln('005: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2026 if not ok then
2027 begin
2028 // Íåò îáû÷íîé, èùåì àíèìèðîâàííóþ
2029 isAnim := True;
2030 //e_LogWritefln('006: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2031 ok := CreateAnimTexture(TexName, FileName, False) >= 0;
2032 //e_LogWritefln('007: pannum=%s; TexName=[%s]; FileName=[%s]', [pannum, TexName, FileName]);
2033 end;
2034 end;
2036 // Îíà ñóùåñòâóåò. Çàíîñèì åå ID â ñïèñîê ïàíåëè
2037 if ok then
2038 begin
2040 for c := 0 to High(Textures) do
2041 begin
2042 if (Textures[c].TextureName = TexName) then
2043 begin
2044 SetLength(AddTextures, Length(AddTextures)+1);
2045 AddTextures[High(AddTextures)].Texture := c;
2046 AddTextures[High(AddTextures)].Anim := isAnim;
2047 break;
2048 end;
2049 end;
2051 if (TextNameHash <> nil) and TextNameHash.get(toLowerCase1251(TexName), c) then
2052 begin
2053 SetLength(AddTextures, Length(AddTextures)+1);
2054 AddTextures[High(AddTextures)].Texture := c;
2055 AddTextures[High(AddTextures)].Anim := isAnim;
2056 end;
2057 end;
2058 end
2059 else
2060 begin
2061 if k = NNF_NAME_EQUALS then
2062 begin
2063 // Çàíîñèì òåêóùóþ òåêñòóðó íà ñâîå ìåñòî
2064 SetLength(AddTextures, Length(AddTextures)+1);
2065 AddTextures[High(AddTextures)].Texture := rec.tagInt; // internal texture number, not map index
2066 AddTextures[High(AddTextures)].Anim := texrec.Anim;
2067 CurTex := High(AddTextures);
2068 ok := true;
2069 end
2070 else // NNF_NO_NAME
2071 begin
2072 ok := false;
2073 end;
2074 end;
2075 end; // while ok...
2077 ok := true;
2078 end; // if ok - åñòü ñìåæíûå òåêñòóðû
2079 end; // if ok - ññûëàþòñÿ òðèããåðû
2081 if not ok then
2082 begin
2083 // Çàíîñèì òîëüêî òåêóùóþ òåêñòóðó
2084 SetLength(AddTextures, 1);
2085 AddTextures[0].Texture := rec.tagInt; // internal texture number, not map index
2086 AddTextures[0].Anim := false;
2087 if (texrec <> nil) then AddTextures[0].Anim := texrec.Anim;
2088 CurTex := 0;
2089 end;
2091 //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);
2093 //e_LogWritefln('PANADD: pannum=%s', [pannum]);
2095 // Ñîçäàåì ïàíåëü è çàïîìèíàåì åå GUID
2096 //e_LogWritefln('new panel; tcount=%s; curtex=%s', [Length(AddTextures), CurTex]);
2097 PanelID := CreatePanel(rec, AddTextures, CurTex);
2098 //e_LogWritefln('panel #%s of type %s got guid #%s', [pannum, rec.PanelType, PanelID]);
2099 rec.userPanelId := PanelID; // remember game panel id, we'll fix triggers later
2101 // setup lifts
2102 moveSpeed := rec.moveSpeed;
2103 //moveStart := rec.moveStart;
2104 //moveEnd := rec.moveEnd;
2105 //moveActive := rec['move_active'].value;
2106 if not moveSpeed.isZero then
2107 begin
2108 SetLength(gMovingWallIds, Length(gMovingWallIds)+1);
2109 gMovingWallIds[High(gMovingWallIds)] := PanelID;
2110 //e_LogWritefln('found moving panel ''%s'' (idx=%s; id=%s)', [rec.id, pannum, PanelID]);
2111 end;
2113 //e_LogWritefln('PANEND: pannum=%s', [pannum]);
2115 g_Game_StepLoading();
2116 end;
2117 end;
2119 // ×èíèì ID'û ïàíåëåé, êîòîðûå èñïîëüçóþòñÿ â òðèããåðàõ
2120 for b := 0 to High(TriggersTable) do
2121 begin
2122 if (TriggersTable[b].texPanel <> nil) then TriggersTable[b].texPanelIdx := TriggersTable[b].texPanel.userPanelId;
2123 if (TriggersTable[b].actPanel <> nil) then TriggersTable[b].actPanelIdx := TriggersTable[b].actPanel.userPanelId;
2124 end;
2126 // create map grid, init other grids (for monsters, for example)
2127 e_WriteLog('Creating map grid', TMsgType.Notify);
2128 mapCreateGrid();
2130 // Åñëè íå LoadState, òî ñîçäàåì òðèããåðû
2131 if (triggers <> nil) and (panels <> nil) and (not gLoadGameMode) then
2132 begin
2133 e_LogWritefln(' Creating triggers (%d)...', [triggers.count]);
2134 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_TRIGGERS], 0, False);
2135 // Óêàçûâàåì òèï ïàíåëè, åñëè åñòü
2136 trignum := -1;
2137 for rec in triggers do
2138 begin
2139 Inc(trignum);
2140 tgpid := TriggersTable[trignum].actPanelIdx;
2141 //e_LogWritefln('creating trigger #%s; texpantype=%s; shotpantype=%s (%d,%d)', [trignum, b, c, TriggersTable[trignum].texPanIdx, TriggersTable[trignum].ShotPanelIdx]);
2142 TriggersTable[trignum].tnum := trignum;
2143 TriggersTable[trignum].id := CreateTrigger(trignum, rec, TriggersTable[trignum].texPanelIdx, tgpid);
2144 end;
2145 end;
2147 //FIXME: use hashtable!
2148 for pan in panByGUID do
2149 begin
2150 if (pan.endPosTrigId >= 0) and (pan.endPosTrigId < Length(TriggersTable)) then
2151 begin
2152 pan.endPosTrigId := TriggersTable[pan.endPosTrigId].id;
2153 end;
2154 if (pan.endSizeTrigId >= 0) and (pan.endSizeTrigId < Length(TriggersTable)) then
2155 begin
2156 pan.endSizeTrigId := TriggersTable[pan.endSizeTrigId].id;
2157 end;
2158 end;
2160 // Çàãðóçêà ïðåäìåòîâ
2161 e_WriteLog(' Loading items...', TMsgType.Notify);
2162 g_Game_SetLoadingText(_lc[I_LOAD_ITEMS], 0, False);
2164 // Åñëè íå LoadState, òî ñîçäàåì ïðåäìåòû
2165 if (items <> nil) and not gLoadGameMode then
2166 begin
2167 e_WriteLog(' Spawning items...', TMsgType.Notify);
2168 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_ITEMS], 0, False);
2169 for rec in items do CreateItem(rec);
2170 end;
2172 // Çàãðóçêà îáëàñòåé
2173 e_WriteLog(' Loading areas...', TMsgType.Notify);
2174 g_Game_SetLoadingText(_lc[I_LOAD_AREAS], 0, False);
2176 // Åñëè íå LoadState, òî ñîçäàåì îáëàñòè
2177 if areas <> nil then
2178 begin
2179 e_WriteLog(' Creating areas...', TMsgType.Notify);
2180 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_AREAS], 0, False);
2181 for rec in areas do CreateArea(rec);
2182 end;
2184 // Çàãðóçêà ìîíñòðîâ
2185 e_WriteLog(' Loading monsters...', TMsgType.Notify);
2186 g_Game_SetLoadingText(_lc[I_LOAD_MONSTERS], 0, False);
2188 gTotalMonsters := 0;
2190 // Åñëè íå LoadState, òî ñîçäàåì ìîíñòðîâ
2191 if (monsters <> nil) and not gLoadGameMode then
2192 begin
2193 e_WriteLog(' Spawning monsters...', TMsgType.Notify);
2194 g_Game_SetLoadingText(_lc[I_LOAD_CREATE_MONSTERS], 0, False);
2195 for rec in monsters do CreateMonster(rec);
2196 end;
2198 //gCurrentMap := mapReader; // this will be our current map now
2199 gCurrentMapFileName := Res;
2200 //mapReader := nil;
2202 // Çàãðóçêà íåáà
2203 if (gMapInfo.SkyName <> '') then
2204 begin
2205 e_WriteLog(' Loading sky: ' + gMapInfo.SkyName, TMsgType.Notify);
2206 g_Game_SetLoadingText(_lc[I_LOAD_SKY], 0, False);
2207 s := e_GetResourcePath(WadDirs, gMapInfo.SkyName, g_ExtractWadName(Res));
2208 if g_Texture_CreateWAD(BackID, s, gTextureFilter) then
2209 g_Game_SetupScreenSize
2210 else
2211 g_FatalError(Format(_lc[I_GAME_ERROR_SKY], [s]))
2212 end;
2214 // Çàãðóçêà ìóçûêè
2215 ok := False;
2216 if gMapInfo.MusicName <> '' then
2217 begin
2218 e_WriteLog(' Loading music: ' + gMapInfo.MusicName, TMsgType.Notify);
2219 g_Game_SetLoadingText(_lc[I_LOAD_MUSIC], 0, False);
2221 s := e_GetResourcePath(WadDirs, gMapInfo.MusicName, g_ExtractWadName(Res));
2222 if g_Sound_CreateWADEx(gMapInfo.MusicName, s, True) then
2223 ok := True
2224 else
2225 g_FatalError(Format(_lc[I_GAME_ERROR_MUSIC], [s]));
2226 end;
2228 // Îñòàëüíûå óñòàíâêè
2229 CreateDoorMap();
2230 CreateLiftMap();
2232 g_Items_Init();
2233 g_Weapon_Init();
2234 g_Monsters_Init();
2236 // Åñëè íå LoadState, òî ñîçäàåì êàðòó ñòîëêíîâåíèé:
2237 if not gLoadGameMode then g_GFX_Init();
2239 // Ñáðîñ ëîêàëüíûõ ìàññèâîâ:
2240 mapTextureList := nil;
2241 panels := nil;
2242 items := nil;
2243 areas := nil;
2244 triggers := nil;
2245 TriggersTable := nil;
2246 AddTextures := nil;
2248 // Âêëþ÷àåì ìóçûêó, åñëè ýòî íå çàãðóçêà:
2249 if ok and (not gLoadGameMode) then
2250 begin
2251 gMusic.SetByName(gMapInfo.MusicName);
2252 gMusic.Play();
2253 end
2254 else
2255 begin
2256 gMusic.SetByName('');
2257 end;
2259 stt := getTimeMicro()-stt;
2260 e_LogWritefln('map loaded in %s.%s milliseconds', [Integer(stt div 1000), Integer(stt mod 1000)]);
2261 mapOk := true;
2262 finally
2263 sfsGCEnable(); // enable releasing unused volumes
2264 //mapReader.Free();
2265 e_UnpressAllKeys; // why not?
2266 if not mapOk then
2267 begin
2268 gCurrentMap.Free();
2269 gCurrentMap := nil;
2270 gCurrentMapFileName := '';
2271 end;
2272 end;
2274 compactExtResList();
2275 e_WriteLog('Done loading map.', TMsgType.Notify);
2276 Result := True;
2277 end;
2280 function g_Map_GetMapInfo(Res: String): TMapInfo;
2281 var
2282 WAD: TWADFile;
2283 mapReader: TDynRecord;
2284 //Header: TMapHeaderRec_1;
2285 FileName: String;
2286 Data: Pointer;
2287 Len: Integer;
2288 begin
2289 FillChar(Result, SizeOf(Result), 0);
2290 FileName := g_ExtractWadName(Res);
2292 WAD := TWADFile.Create();
2293 if not WAD.ReadFile(FileName) then
2294 begin
2295 WAD.Free();
2296 Exit;
2297 end;
2299 //k8: it ignores path again
2300 if not WAD.GetMapResource(g_ExtractFileName(Res), Data, Len) then
2301 begin
2302 WAD.Free();
2303 Exit;
2304 end;
2306 WAD.Free();
2308 try
2309 mapReader := g_Map_ParseMap(Data, Len);
2310 except
2311 mapReader := nil;
2312 FreeMem(Data);
2313 exit;
2314 end;
2316 FreeMem(Data);
2318 if (mapReader = nil) then exit;
2320 if (mapReader.Width > 0) and (mapReader.Height > 0) then
2321 begin
2322 Result.Name := mapReader.MapName;
2323 Result.Description := mapReader.MapDesc;
2324 Result.Map := Res;
2325 Result.Author := mapReader.MapAuthor;
2326 Result.Height := mapReader.Height;
2327 Result.Width := mapReader.Width;
2328 end
2329 else
2330 begin
2331 g_Console_Add(Format(_lc[I_GAME_ERROR_MAP_LOAD], [Res]), True);
2332 //ZeroMemory(@Header, SizeOf(Header));
2333 Result.Name := _lc[I_GAME_ERROR_MAP_SELECT];
2334 Result.Description := _lc[I_GAME_ERROR_MAP_SELECT];
2335 Result.Map := Res;
2336 Result.Author := '';
2337 Result.Height := 0;
2338 Result.Width := 0;
2339 end;
2341 mapReader.Free();
2342 end;
2344 function g_Map_GetMapsList(WADName: string): SSArray;
2345 var
2346 WAD: TWADFile;
2347 a: Integer;
2348 ResList: SSArray;
2349 begin
2350 Result := nil;
2351 WAD := TWADFile.Create();
2352 if not WAD.ReadFile(WADName) then
2353 begin
2354 WAD.Free();
2355 Exit;
2356 end;
2357 ResList := WAD.GetMapResources();
2358 if ResList <> nil then
2359 begin
2360 for a := 0 to High(ResList) do
2361 begin
2362 SetLength(Result, Length(Result)+1);
2363 Result[High(Result)] := ResList[a];
2364 end;
2365 end;
2366 WAD.Free();
2367 end;
2369 function g_Map_Exist(Res: string): Boolean;
2370 var
2371 WAD: TWADFile;
2372 FileName, mnn: string;
2373 ResList: SSArray;
2374 a: Integer;
2375 begin
2376 Result := False;
2378 FileName := addWadExtension(g_ExtractWadName(Res));
2380 WAD := TWADFile.Create;
2381 if not WAD.ReadFile(FileName) then
2382 begin
2383 WAD.Free();
2384 Exit;
2385 end;
2387 ResList := WAD.GetMapResources();
2388 WAD.Free();
2390 mnn := g_ExtractFileName(Res);
2391 if ResList <> nil then
2392 for a := 0 to High(ResList) do if StrEquCI1251(ResList[a], mnn) then
2393 begin
2394 Result := True;
2395 Exit;
2396 end;
2397 end;
2399 procedure g_Map_Free(freeTextures: Boolean=true);
2400 var
2401 a: Integer;
2403 procedure FreePanelArray(var panels: TPanelArray);
2404 var
2405 i: Integer;
2407 begin
2408 if panels <> nil then
2409 begin
2410 for i := 0 to High(panels) do
2411 panels[i].Free();
2412 panels := nil;
2413 end;
2414 end;
2416 begin
2417 g_GFX_Free();
2418 g_Weapon_Free();
2419 g_Items_Free();
2420 g_Triggers_Free();
2421 g_Monsters_Free();
2423 RespawnPoints := nil;
2424 if FlagPoints[FLAG_RED] <> nil then
2425 begin
2426 Dispose(FlagPoints[FLAG_RED]);
2427 FlagPoints[FLAG_RED] := nil;
2428 end;
2429 if FlagPoints[FLAG_BLUE] <> nil then
2430 begin
2431 Dispose(FlagPoints[FLAG_BLUE]);
2432 FlagPoints[FLAG_BLUE] := nil;
2433 end;
2434 //DOMFlagPoints := nil;
2436 //gDOMFlags := nil;
2438 if (Length(gCurrentMapFileName) <> 0) then
2439 begin
2440 e_LogWritefln('g_Map_Free: previous map was ''%s''...', [gCurrentMapFileName]);
2441 end
2442 else
2443 begin
2444 e_LogWritefln('g_Map_Free: no previous map.', []);
2445 end;
2447 if freeTextures then
2448 begin
2449 e_LogWritefln('g_Map_Free: clearing textures...', []);
2450 if (Textures <> nil) then
2451 begin
2452 for a := 0 to High(Textures) do
2453 begin
2454 if not g_Map_IsSpecialTexture(Textures[a].TextureName) then
2455 begin
2456 if Textures[a].Anim then
2457 begin
2458 g_Frames_DeleteByID(Textures[a].FramesID)
2459 end
2460 else
2461 begin
2462 if (Textures[a].TextureID <> LongWord(TEXTURE_NONE)) then
2463 begin
2464 e_DeleteTexture(Textures[a].TextureID);
2465 end;
2466 end;
2467 end;
2468 end;
2469 Textures := nil;
2470 end;
2471 TextNameHash.Free();
2472 TextNameHash := nil;
2473 BadTextNameHash.Free();
2474 BadTextNameHash := nil;
2475 gCurrentMapFileName := '';
2476 gCurrentMap.Free();
2477 gCurrentMap := nil;
2478 end;
2480 panByGUID := nil;
2482 FreePanelArray(gWalls);
2483 FreePanelArray(gRenderBackgrounds);
2484 FreePanelArray(gRenderForegrounds);
2485 FreePanelArray(gWater);
2486 FreePanelArray(gAcid1);
2487 FreePanelArray(gAcid2);
2488 FreePanelArray(gSteps);
2489 FreePanelArray(gLifts);
2490 FreePanelArray(gBlockMon);
2491 gMovingWallIds := nil;
2493 if BackID <> DWORD(-1) then
2494 begin
2495 gBackSize.X := 0;
2496 gBackSize.Y := 0;
2497 e_DeleteTexture(BackID);
2498 BackID := DWORD(-1);
2499 end;
2501 g_Game_StopAllSounds(False);
2502 gMusic.FreeSound();
2503 g_Sound_Delete(gMapInfo.MusicName);
2505 gMapInfo.Name := '';
2506 gMapInfo.Description := '';
2507 gMapInfo.MusicName := '';
2508 gMapInfo.Height := 0;
2509 gMapInfo.Width := 0;
2511 gDoorMap := nil;
2512 gLiftMap := nil;
2513 end;
2515 procedure g_Map_Update();
2516 var
2517 a, d, j: Integer;
2518 m: Word;
2519 s: String;
2520 b: Byte;
2522 procedure UpdatePanelArray(var panels: TPanelArray);
2523 var
2524 i: Integer;
2526 begin
2527 for i := 0 to High(panels) do panels[i].Update();
2528 end;
2530 begin
2531 if g_dbgpan_mplat_step then g_dbgpan_mplat_active := true;
2533 UpdatePanelArray(gWalls);
2534 UpdatePanelArray(gRenderBackgrounds);
2535 UpdatePanelArray(gRenderForegrounds);
2536 UpdatePanelArray(gWater);
2537 UpdatePanelArray(gAcid1);
2538 UpdatePanelArray(gAcid2);
2539 UpdatePanelArray(gSteps);
2541 if g_dbgpan_mplat_step then begin g_dbgpan_mplat_step := false; g_dbgpan_mplat_active := false; end;
2543 if gGameSettings.GameMode = GM_CTF then
2544 begin
2545 for a := FLAG_RED to FLAG_BLUE do
2546 begin
2547 if not (gFlags[a].State in [FLAG_STATE_NONE, FLAG_STATE_CAPTURED]) then
2548 begin
2549 with gFlags[a] do
2550 begin
2551 if gFlags[a].Animation <> nil then gFlags[a].Animation.Update();
2553 Obj.oldX := Obj.X;
2554 Obj.oldY := Obj.Y;
2556 m := g_Obj_Move(@Obj, True, True);
2558 NeedSend := NeedSend or (Obj.X <> Obj.oldX) or (Obj.Y <> Obj.oldY);
2560 if gTime mod (GAME_TICK*2) <> 0 then Continue;
2562 // Ñîïðîòèâëåíèå âîçäóõà
2563 Obj.Vel.X := z_dec(Obj.Vel.X, 1);
2565 // Òàéìàóò ïîòåðÿííîãî ôëàãà, ëèáî îí âûïàë çà êàðòó
2566 if ((Count = 0) or ByteBool(m and MOVE_FALLOUT)) and g_Game_IsServer then
2567 begin
2568 g_Map_ResetFlag(a);
2569 gFlags[a].CaptureTime := 0;
2570 if a = FLAG_RED then
2571 s := _lc[I_PLAYER_FLAG_RED]
2572 else
2573 s := _lc[I_PLAYER_FLAG_BLUE];
2574 g_Game_Message(Format(_lc[I_MESSAGE_FLAG_RETURN], [AnsiUpperCase(s)]), 144);
2576 if (((gPlayer1 <> nil) and (((gPlayer1.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer1.Team = TEAM_BLUE) and (a = FLAG_BLUE))))
2577 or ((gPlayer2 <> nil) and (((gPlayer2.Team = TEAM_RED) and (a = FLAG_RED)) or ((gPlayer2.Team = TEAM_BLUE) and (a = FLAG_BLUE))))) then
2578 b := 0
2579 else
2580 b := 1;
2582 if not sound_ret_flag[b].IsPlaying() then
2583 sound_ret_flag[b].Play();
2585 if g_Game_IsNet then
2586 MH_SEND_FlagEvent(FLAG_STATE_RETURNED, a, 0);
2587 Continue;
2588 end;
2590 if Count > 0 then Count -= 1;
2592 // Èãðîê áåðåò ôëàã
2593 if gPlayers <> nil then
2594 begin
2595 j := Random(Length(gPlayers)) - 1;
2596 for d := 0 to High(gPlayers) do
2597 begin
2598 Inc(j);
2599 if j > High(gPlayers) then j := 0;
2600 if gPlayers[j] <> nil then
2601 begin
2602 if gPlayers[j].alive and g_Obj_Collide(@Obj, @gPlayers[j].Obj) then
2603 begin
2604 if gPlayers[j].GetFlag(a) then Break;
2605 end;
2606 end;
2607 end;
2608 end;
2609 end;
2610 end;
2611 end;
2612 end;
2613 end;
2615 function g_Map_CollidePanelOld(X, Y: Integer; Width, Height: Word;
2616 PanelType: Word; b1x3: Boolean=false): Boolean;
2617 var
2618 a, h: Integer;
2619 begin
2620 Result := False;
2622 if WordBool(PanelType and PANEL_WALL) then
2623 if gWalls <> nil then
2624 begin
2625 h := High(gWalls);
2627 for a := 0 to h do
2628 if gWalls[a].Enabled and
2629 g_Collide(X, Y, Width, Height,
2630 gWalls[a].X, gWalls[a].Y,
2631 gWalls[a].Width, gWalls[a].Height) then
2632 begin
2633 Result := True;
2634 Exit;
2635 end;
2636 end;
2638 if WordBool(PanelType and PANEL_WATER) then
2639 if gWater <> nil then
2640 begin
2641 h := High(gWater);
2643 for a := 0 to h do
2644 if g_Collide(X, Y, Width, Height,
2645 gWater[a].X, gWater[a].Y,
2646 gWater[a].Width, gWater[a].Height) then
2647 begin
2648 Result := True;
2649 Exit;
2650 end;
2651 end;
2653 if WordBool(PanelType and PANEL_ACID1) then
2654 if gAcid1 <> nil then
2655 begin
2656 h := High(gAcid1);
2658 for a := 0 to h do
2659 if g_Collide(X, Y, Width, Height,
2660 gAcid1[a].X, gAcid1[a].Y,
2661 gAcid1[a].Width, gAcid1[a].Height) then
2662 begin
2663 Result := True;
2664 Exit;
2665 end;
2666 end;
2668 if WordBool(PanelType and PANEL_ACID2) then
2669 if gAcid2 <> nil then
2670 begin
2671 h := High(gAcid2);
2673 for a := 0 to h do
2674 if g_Collide(X, Y, Width, Height,
2675 gAcid2[a].X, gAcid2[a].Y,
2676 gAcid2[a].Width, gAcid2[a].Height) then
2677 begin
2678 Result := True;
2679 Exit;
2680 end;
2681 end;
2683 if WordBool(PanelType and PANEL_STEP) then
2684 if gSteps <> nil then
2685 begin
2686 h := High(gSteps);
2688 for a := 0 to h do
2689 if g_Collide(X, Y, Width, Height,
2690 gSteps[a].X, gSteps[a].Y,
2691 gSteps[a].Width, gSteps[a].Height) then
2692 begin
2693 Result := True;
2694 Exit;
2695 end;
2696 end;
2698 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then
2699 if gLifts <> nil then
2700 begin
2701 h := High(gLifts);
2703 for a := 0 to h do
2704 if ((WordBool(PanelType and (PANEL_LIFTUP)) and (gLifts[a].LiftType = LIFTTYPE_UP)) or
2705 (WordBool(PanelType and (PANEL_LIFTDOWN)) and (gLifts[a].LiftType = LIFTTYPE_DOWN)) or
2706 (WordBool(PanelType and (PANEL_LIFTLEFT)) and (gLifts[a].LiftType = LIFTTYPE_LEFT)) or
2707 (WordBool(PanelType and (PANEL_LIFTRIGHT)) and (gLifts[a].LiftType = LIFTTYPE_RIGHT))) and
2708 g_Collide(X, Y, Width, Height,
2709 gLifts[a].X, gLifts[a].Y,
2710 gLifts[a].Width, gLifts[a].Height) then
2711 begin
2712 Result := True;
2713 Exit;
2714 end;
2715 end;
2717 if WordBool(PanelType and PANEL_BLOCKMON) then
2718 if gBlockMon <> nil then
2719 begin
2720 h := High(gBlockMon);
2722 for a := 0 to h do
2723 if ( (not b1x3) or
2724 ((gBlockMon[a].Width + gBlockMon[a].Height) >= 64) ) and
2725 g_Collide(X, Y, Width, Height,
2726 gBlockMon[a].X, gBlockMon[a].Y,
2727 gBlockMon[a].Width, gBlockMon[a].Height) then
2728 begin
2729 Result := True;
2730 Exit;
2731 end;
2732 end;
2733 end;
2735 function g_Map_CollideLiquid_TextureOld(X, Y: Integer; Width, Height: Word): DWORD;
2736 var
2737 texid: DWORD;
2739 function checkPanels (constref panels: TPanelArray): Boolean;
2740 var
2741 a: Integer;
2742 begin
2743 result := false;
2744 if panels = nil then exit;
2745 for a := 0 to High(panels) do
2746 begin
2747 if g_Collide(X, Y, Width, Height, panels[a].X, panels[a].Y, panels[a].Width, panels[a].Height) then
2748 begin
2749 result := true;
2750 texid := panels[a].GetTextureID();
2751 exit;
2752 end;
2753 end;
2754 end;
2756 begin
2757 texid := LongWord(TEXTURE_NONE);
2758 result := texid;
2759 if not checkPanels(gWater) then
2760 if not checkPanels(gAcid1) then
2761 if not checkPanels(gAcid2) then exit;
2762 result := texid;
2763 end;
2766 function g_Map_CollidePanel(X, Y: Integer; Width, Height: Word; PanelType: Word; b1x3: Boolean): Boolean;
2767 const
2768 SlowMask = GridTagLift or GridTagBlockMon;
2770 function checker (pan: TPanel; tag: Integer): Boolean;
2771 begin
2773 if ((tag and (GridTagWall or GridTagDoor)) <> 0) then
2774 begin
2775 result := pan.Enabled;
2776 exit;
2777 end;
2780 if ((tag and GridTagLift) <> 0) then
2781 begin
2782 result :=
2783 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2784 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2785 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2786 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2787 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2788 exit;
2789 end;
2791 if ((tag and GridTagBlockMon) <> 0) then
2792 begin
2793 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2794 exit;
2795 end;
2797 // other shit
2798 //result := g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2799 result := true; // i found her!
2800 end;
2802 var
2803 tagmask: Integer = 0;
2804 mwit: PPanel;
2805 it: TPanelGrid.Iter;
2806 pan: TPanel;
2807 begin
2808 result := false;
2809 if WordBool(PanelType and (PANEL_WALL or PANEL_CLOSEDOOR or PANEL_OPENDOOR)) then tagmask := tagmask or (GridTagWall or GridTagDoor);
2810 if WordBool(PanelType and PANEL_WATER) then tagmask := tagmask or GridTagWater;
2811 if WordBool(PanelType and PANEL_ACID1) then tagmask := tagmask or GridTagAcid1;
2812 if WordBool(PanelType and PANEL_ACID2) then tagmask := tagmask or GridTagAcid2;
2813 if WordBool(PanelType and PANEL_STEP) then tagmask := tagmask or GridTagStep;
2814 if WordBool(PanelType and (PANEL_LIFTUP or PANEL_LIFTDOWN or PANEL_LIFTLEFT or PANEL_LIFTRIGHT)) then tagmask := tagmask or GridTagLift;
2815 if WordBool(PanelType and PANEL_BLOCKMON) then tagmask := tagmask or GridTagBlockMon;
2817 if (tagmask = 0) then exit; // just in case
2819 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('*solids');
2820 if gdbg_map_use_accel_coldet then
2821 begin
2822 if ((tagmask and SlowMask) <> 0) then
2823 begin
2824 // slow
2825 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask);
2826 for mwit in it do
2827 begin
2828 pan := mwit^;
2829 if ((pan.tag and GridTagLift) <> 0) then
2830 begin
2831 result :=
2832 ((WordBool(PanelType and PANEL_LIFTUP) and (pan.LiftType = LIFTTYPE_UP)) or
2833 (WordBool(PanelType and PANEL_LIFTDOWN) and (pan.LiftType = LIFTTYPE_DOWN)) or
2834 (WordBool(PanelType and PANEL_LIFTLEFT) and (pan.LiftType = LIFTTYPE_LEFT)) or
2835 (WordBool(PanelType and PANEL_LIFTRIGHT) and (pan.LiftType = LIFTTYPE_RIGHT))) {and
2836 g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height)};
2837 end
2838 else if ((pan.tag and GridTagBlockMon) <> 0) then
2839 begin
2840 result := ((not b1x3) or (pan.Width+pan.Height >= 64)); //and g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height);
2841 end
2842 else
2843 begin
2844 // other shit
2845 result := true; // i found her!
2846 end;
2847 if (result) then break;
2848 end;
2849 end
2850 else
2851 begin
2852 // fast
2853 it := mapGrid.forEachInAABB(X, Y, Width, Height, tagmask, false, true); // return first hit
2854 result := (it.length > 0);
2855 end;
2856 it.release();
2857 end
2858 else
2859 begin
2860 result := g_Map_CollidePanelOld(X, Y, Width, Height, PanelType, b1x3);
2861 end;
2862 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2863 end;
2866 // returns `true` if we need to stop
2867 function liquidChecker (pan: TPanel; var texid: DWORD; var cctype: Integer): Boolean; inline;
2868 begin
2869 result := false;
2870 //if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2)) = 0) then exit;
2871 // check priorities
2872 case cctype of
2873 0: if ((pan.tag and GridTagWater) = 0) then exit; // allowed: water
2874 1: if ((pan.tag and (GridTagWater or GridTagAcid1)) = 0) then exit; // allowed: water, acid1
2875 //2: if ((tag and (GridTagWater or GridTagAcid1 or GridTagAcid2) = 0) then exit; // allowed: water, acid1, acid2
2876 end;
2877 // collision?
2878 //if not g_Collide(X, Y, Width, Height, pan.X, pan.Y, pan.Width, pan.Height) then exit;
2879 // yeah
2880 texid := pan.GetTextureID();
2881 // water? water has the highest priority, so stop right here
2882 if ((pan.tag and GridTagWater) <> 0) then begin cctype := 0; result := true; exit; end;
2883 // acid2?
2884 if ((pan.tag and GridTagAcid2) <> 0) then cctype := 2;
2885 // acid1?
2886 if ((pan.tag and GridTagAcid1) <> 0) then cctype := 1;
2887 end;
2889 function g_Map_CollideLiquid_Texture(X, Y: Integer; Width, Height: Word): DWORD;
2890 var
2891 cctype: Integer = 3; // priority: 0: water was hit, 1: acid1 was hit, 2: acid2 was hit; 3: nothing was hit
2892 mwit: PPanel;
2893 it: TPanelGrid.Iter;
2894 begin
2895 if (profMapCollision <> nil) then profMapCollision.sectionBeginAccum('liquids');
2896 if gdbg_map_use_accel_coldet then
2897 begin
2898 result := LongWord(TEXTURE_NONE);
2899 it := mapGrid.forEachInAABB(X, Y, Width, Height, (GridTagWater or GridTagAcid1 or GridTagAcid2));
2900 for mwit in it do if (liquidChecker(mwit^, result, cctype)) then break;
2901 it.release();
2902 end
2903 else
2904 begin
2905 result := g_Map_CollideLiquid_TextureOld(X, Y, Width, Height);
2906 end;
2907 if (profMapCollision <> nil) then profMapCollision.sectionEnd();
2908 end;
2911 procedure g_Map_EnableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_EnableWallGUID(gWalls[ID].guid); end;
2912 procedure g_Map_DisableWall_XXX (ID: DWORD); begin if (ID < Length(gWalls)) then g_Map_DisableWallGUID(gWalls[ID].guid); end;
2913 procedure g_Map_SetLift_XXX (ID: DWORD; t: Integer); begin if (ID < Length(gLifts)) then g_Map_SetLiftGUID(gLifts[ID].guid, t); end;
2916 procedure g_Map_EnableWallGUID (pguid: Integer);
2917 var
2918 pan: TPanel;
2919 begin
2920 //pan := gWalls[ID];
2921 pan := g_Map_PanelByGUID(pguid);
2922 if (pan = nil) then exit;
2923 if pan.Enabled and mapGrid.proxyEnabled[pan.proxyId] then exit;
2925 pan.Enabled := True;
2926 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, true);
2928 mapGrid.proxyEnabled[pan.proxyId] := true;
2929 //if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := true
2930 //else pan.proxyId := mapGrid.insertBody(pan, pan.X, pan.Y, pan.Width, pan.Height, GridTagDoor);
2932 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2933 // mark platform as interesting
2934 pan.setDirty();
2936 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2937 //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);
2938 {$ENDIF}
2939 end;
2942 procedure g_Map_DisableWallGUID (pguid: Integer);
2943 var
2944 pan: TPanel;
2945 begin
2946 //pan := gWalls[ID];
2947 pan := g_Map_PanelByGUID(pguid);
2948 if (pan = nil) then exit;
2949 if (not pan.Enabled) and (not mapGrid.proxyEnabled[pan.proxyId]) then exit;
2951 pan.Enabled := False;
2952 g_Mark(pan.X, pan.Y, pan.Width, pan.Height, MARK_DOOR, false);
2954 mapGrid.proxyEnabled[pan.proxyId] := false;
2955 //if (pan.proxyId >= 0) then begin mapGrid.removeBody(pan.proxyId); pan.proxyId := -1; end;
2957 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
2958 // mark platform as interesting
2959 pan.setDirty();
2961 {$IFDEF MAP_DEBUG_ENABLED_FLAG}
2962 //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);
2963 {$ENDIF}
2964 end;
2967 procedure g_Map_SwitchTextureGUID (pguid: Integer; AnimLoop: Byte = 0);
2968 var
2969 tp: TPanel;
2970 begin
2971 tp := g_Map_PanelByGUID(pguid);
2972 if (tp = nil) then exit;
2973 tp.NextTexture(AnimLoop);
2974 if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelTexture(pguid, AnimLoop);
2975 end;
2978 procedure g_Map_SetLiftGUID (pguid: Integer; t: Integer);
2979 var
2980 pan: TPanel;
2981 begin
2982 //pan := gLifts[ID];
2983 pan := g_Map_PanelByGUID(pguid);
2984 if (pan = nil) then exit;
2985 if not pan.isGLift then exit;
2987 if ({gLifts[ID]}pan.LiftType = t) then exit; //!FIXME!TRIGANY!
2989 with {gLifts[ID]} pan do
2990 begin
2991 LiftType := t;
2993 g_Mark(X, Y, Width, Height, MARK_LIFT, false);
2994 //TODO: make separate lift tags, and change tag here
2996 case LiftType of
2997 LIFTTYPE_UP: g_Mark(X, Y, Width, Height, MARK_LIFTUP);
2998 LIFTTYPE_DOWN: g_Mark(X, Y, Width, Height, MARK_LIFTDOWN);
2999 LIFTTYPE_LEFT: g_Mark(X, Y, Width, Height, MARK_LIFTLEFT);
3000 LIFTTYPE_RIGHT: g_Mark(X, Y, Width, Height, MARK_LIFTRIGHT);
3001 end;
3003 //if g_Game_IsServer and g_Game_IsNet then MH_SEND_PanelState(pguid);
3004 // mark platform as interesting
3005 pan.setDirty();
3006 end;
3007 end;
3010 function g_Map_GetPoint (PointType: Byte; var RespawnPoint: TRespawnPoint): Boolean;
3011 var
3012 a: Integer;
3013 PointsArray: Array of TRespawnPoint;
3014 begin
3015 Result := False;
3016 SetLength(PointsArray, 0);
3018 if RespawnPoints = nil then
3019 Exit;
3021 for a := 0 to High(RespawnPoints) do
3022 if RespawnPoints[a].PointType = PointType then
3023 begin
3024 SetLength(PointsArray, Length(PointsArray)+1);
3025 PointsArray[High(PointsArray)] := RespawnPoints[a];
3026 end;
3028 if PointsArray = nil then
3029 Exit;
3031 RespawnPoint := PointsArray[Random(Length(PointsArray))];
3032 Result := True;
3033 end;
3035 function g_Map_GetPointCount(PointType: Byte): Word;
3036 var
3037 a: Integer;
3038 begin
3039 Result := 0;
3041 if RespawnPoints = nil then
3042 Exit;
3044 for a := 0 to High(RespawnPoints) do
3045 if RespawnPoints[a].PointType = PointType then
3046 Result := Result + 1;
3047 end;
3049 function g_Map_GetRandomPointType(): Byte;
3050 begin
3051 if RespawnPoints = nil then
3052 Result := 255
3053 else
3054 Result := RespawnPoints[Random(Length(RespawnPoints))].PointType;
3055 end;
3057 function g_Map_HaveFlagPoints(): Boolean;
3058 begin
3059 Result := (FlagPoints[FLAG_RED] <> nil) and (FlagPoints[FLAG_BLUE] <> nil);
3060 end;
3062 procedure g_Map_ResetFlag(Flag: Byte);
3063 begin
3064 with gFlags[Flag] do
3065 begin
3066 Obj.X := -1000;
3067 Obj.Y := -1000;
3068 Obj.Vel.X := 0;
3069 Obj.Vel.Y := 0;
3070 Direction := TDirection.D_LEFT;
3071 State := FLAG_STATE_NONE;
3072 if FlagPoints[Flag] <> nil then
3073 begin
3074 Obj.X := FlagPoints[Flag]^.X;
3075 Obj.Y := FlagPoints[Flag]^.Y;
3076 Direction := FlagPoints[Flag]^.Direction;
3077 State := FLAG_STATE_NORMAL;
3078 end;
3079 Obj.oldX := Obj.X;
3080 Obj.oldY := Obj.Y;
3081 NeedSend := False; // the event will take care of this
3082 Count := -1;
3083 end;
3084 end;
3086 procedure g_Map_SaveState (st: TStream);
3087 var
3088 str: String;
3090 procedure savePanels ();
3091 var
3092 pan: TPanel;
3093 begin
3094 // Ñîõðàíÿåì ïàíåëè
3095 utils.writeInt(st, LongInt(Length(panByGUID)));
3096 for pan in panByGUID do pan.SaveState(st);
3097 end;
3099 procedure saveFlag (flag: PFlag);
3100 var
3101 b: Byte;
3102 begin
3103 utils.writeSign(st, 'FLAG');
3104 utils.writeInt(st, Byte(0)); // version
3105 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3106 utils.writeInt(st, Byte(flag^.RespawnType));
3107 // Ñîñòîÿíèå ôëàãà
3108 utils.writeInt(st, Byte(flag^.State));
3109 // Íàïðàâëåíèå ôëàãà
3110 if flag^.Direction = TDirection.D_LEFT then b := 1 else b := 2; // D_RIGHT
3111 utils.writeInt(st, Byte(b));
3112 // Îáúåêò ôëàãà
3113 Obj_SaveState(st, @flag^.Obj);
3114 end;
3116 begin
3117 savePanels();
3119 // Ñîõðàíÿåì ìóçûêó
3120 utils.writeSign(st, 'MUSI');
3121 utils.writeInt(st, Byte(0));
3122 // Íàçâàíèå ìóçûêè
3123 assert(gMusic <> nil, 'g_Map_SaveState: gMusic = nil');
3124 if gMusic.NoMusic then str := '' else str := gMusic.Name;
3125 utils.writeStr(st, str);
3126 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3127 utils.writeInt(st, LongWord(gMusic.GetPosition()));
3128 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3129 utils.writeBool(st, gMusic.SpecPause);
3131 ///// Ñîõðàíÿåì êîëè÷åñòâî ìîíñòðîâ: /////
3132 utils.writeInt(st, LongInt(gTotalMonsters));
3133 ///// /////
3135 //// Ñîõðàíÿåì ôëàãè, åñëè ýòî CTF: /////
3136 if (gGameSettings.GameMode = GM_CTF) then
3137 begin
3138 // Ôëàã Êðàñíîé êîìàíäû
3139 saveFlag(@gFlags[FLAG_RED]);
3140 // Ôëàã Ñèíåé êîìàíäû
3141 saveFlag(@gFlags[FLAG_BLUE]);
3142 end;
3143 ///// /////
3145 ///// Ñîõðàíÿåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3146 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3147 begin
3148 // Î÷êè Êðàñíîé êîìàíäû
3149 utils.writeInt(st, SmallInt(gTeamStat[TEAM_RED].Score));
3150 // Î÷êè Ñèíåé êîìàíäû
3151 utils.writeInt(st, SmallInt(gTeamStat[TEAM_BLUE].Score));
3152 end;
3153 ///// /////
3154 end;
3157 procedure g_Map_LoadState (st: TStream);
3158 var
3159 dw: DWORD;
3160 str: String;
3161 boo: Boolean;
3163 procedure loadPanels ();
3164 var
3165 pan: TPanel;
3166 begin
3167 // Çàãðóæàåì ïàíåëè
3168 if (Length(panByGUID) <> utils.readLongInt(st)) then raise XStreamError.Create('invalid number of saved panels');
3169 for pan in panByGUID do
3170 begin
3171 pan.LoadState(st);
3172 if (pan.proxyId >= 0) then mapGrid.proxyEnabled[pan.proxyId] := pan.Enabled;
3173 end;
3174 end;
3176 procedure loadFlag (flag: PFlag);
3177 var
3178 b: Byte;
3179 begin
3180 // Ñèãíàòóðà ôëàãà
3181 if not utils.checkSign(st, 'FLAG') then raise XStreamError.Create('invalid flag signature');
3182 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid flag version');
3183 // Âðåìÿ ïåðåïîÿâëåíèÿ ôëàãà
3184 flag^.RespawnType := utils.readByte(st);
3185 // Ñîñòîÿíèå ôëàãà
3186 flag^.State := utils.readByte(st);
3187 // Íàïðàâëåíèå ôëàãà
3188 b := utils.readByte(st);
3189 if (b = 1) then flag^.Direction := TDirection.D_LEFT else flag^.Direction := TDirection.D_RIGHT; // b = 2
3190 // Îáúåêò ôëàãà
3191 Obj_LoadState(@flag^.Obj, st);
3192 end;
3194 begin
3195 if (st = nil) then exit;
3197 ///// Çàãðóæàåì ñïèñêè ïàíåëåé: /////
3198 loadPanels();
3199 ///// /////
3201 // Îáíîâëÿåì êàðòó ñòîëêíîâåíèé è ñåòêó
3202 g_GFX_Init();
3203 //mapCreateGrid();
3205 ///// Çàãðóæàåì ìóçûêó: /////
3206 if not utils.checkSign(st, 'MUSI') then raise XStreamError.Create('invalid music signature');
3207 if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid music version');
3208 // Íàçâàíèå ìóçûêè
3209 assert(gMusic <> nil, 'g_Map_LoadState: gMusic = nil');
3210 str := utils.readStr(st);
3211 // Ïîçèöèÿ ïðîèãðûâàíèÿ ìóçûêè
3212 dw := utils.readLongWord(st);
3213 // Ñòîèò ëè ìóçûêà íà ñïåö-ïàóçå
3214 boo := utils.readBool(st);
3215 // Çàïóñêàåì ýòó ìóçûêó
3216 gMusic.SetByName(str);
3217 gMusic.SpecPause := boo;
3218 gMusic.Play();
3219 gMusic.Pause(true);
3220 gMusic.SetPosition(dw);
3221 ///// /////
3223 ///// Çàãðóæàåì êîëè÷åñòâî ìîíñòðîâ: /////
3224 gTotalMonsters := utils.readLongInt(st);
3225 ///// /////
3227 //// Çàãðóæàåì ôëàãè, åñëè ýòî CTF: /////
3228 if (gGameSettings.GameMode = GM_CTF) then
3229 begin
3230 // Ôëàã Êðàñíîé êîìàíäû
3231 loadFlag(@gFlags[FLAG_RED]);
3232 // Ôëàã Ñèíåé êîìàíäû
3233 loadFlag(@gFlags[FLAG_BLUE]);
3234 end;
3235 ///// /////
3237 ///// Çàãðóæàåì êîëè÷åñòâî ïîáåä, åñëè ýòî TDM/CTF: /////
3238 if gGameSettings.GameMode in [GM_TDM, GM_CTF] then
3239 begin
3240 // Î÷êè Êðàñíîé êîìàíäû
3241 gTeamStat[TEAM_RED].Score := utils.readSmallInt(st);
3242 // Î÷êè Ñèíåé êîìàíäû
3243 gTeamStat[TEAM_BLUE].Score := utils.readSmallInt(st);
3244 end;
3245 ///// /////
3246 end;
3249 // trace liquid, stepping by `dx` and `dy`
3250 // return last seen liquid coords, and `false` if we're started outside of the liquid
3251 function g_Map_TraceLiquidNonPrecise (x, y, dx, dy: Integer; out topx, topy: Integer): Boolean;
3252 const
3253 MaskLiquid = GridTagWater or GridTagAcid1 or GridTagAcid2;
3254 begin
3255 topx := x;
3256 topy := y;
3257 // started outside of the liquid?
3258 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then begin result := false; exit; end;
3259 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then begin result := false; exit; end;
3260 if (dx = 0) and (dy = 0) then begin result := false; exit; end; // sanity check
3261 result := true;
3262 while true do
3263 begin
3264 Inc(x, dx);
3265 Inc(y, dy);
3266 //if (mapGrid.forEachAtPoint(x, y, nil, MaskLiquid) = nil) then exit; // out of the water, just exit
3267 if (g_Map_PanelAtPoint(x, y, MaskLiquid) = nil) then exit; // out of the water, just exit
3268 topx := x;
3269 topy := y;
3270 end;
3271 end;
3274 begin
3275 DynWarningCB := mapWarningCB;
3276 end.