DEADSOFTWARE

spawners now count delay after their first spawn dies
[d2df-sdl.git] / src / game / g_triggers.pas
index 6e57873ec65f20e77deee928e1b1b7730f5e74c5..174b47e6594ca44e0a0429705ebb039b4394af67 100644 (file)
@@ -1,4 +1,4 @@
-(* Copyright (C)  DooM 2D:Forever Developers
+(* Copyright (C)  Doom 2D: Forever Developers
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -19,14 +19,16 @@ unit g_triggers;
 interface
 
 uses
+  SysUtils, Variants, Classes,
   MAPDEF, e_graphics, g_basic, g_sound,
-  BinEditor, xdynrec;
+  xdynrec, hashtable, exoma;
 
 type
   TActivator = record
     UID:     Word;
     TimeOut: Word;
   end;
+
   PTrigger = ^TTrigger;
   TTrigger = record
   public
@@ -39,7 +41,7 @@ type
     ActivateType:     Byte;
     Keys:             Byte;
     TexturePanelGUID: Integer;
-    TexturePanelType: Word;
+    //TexturePanelType: Word;
 
     TimeOut:          Word;
     ActivateUID:      Word;
@@ -53,7 +55,7 @@ type
     AutoSpawn:        Boolean;
     SpawnCooldown:    Integer;
     SpawnedCount:     Integer;
-    ShotPanelType:    Word;
+    //ShotPanelType:    Word;
     ShotPanelTime:    Integer;
     ShotSightTime:    Integer;
     ShotSightTimeout: Integer;
@@ -66,17 +68,18 @@ type
     mapIndex: Integer; // index in fields['trigger'], used in save/load
     trigPanelGUID: Integer;
 
-    //TrigData:             TTriggerData;
-    trigData: TDynRecord; // triggerdata; owned by trigger
+    trigDataRec: TDynRecord; // triggerdata; owned by trigger (cloned)
+    exoInit, exoThink, exoCheck, exoAction: TExprBase;
 
-  public
-    function trigCenter (): TDFPoint; inline;
+    userVars: THashStrVariant;
+
+    {$INCLUDE ../shared/mapdef_tgc_def.inc}
 
   public
-    property trigShotPanelGUID: Integer read trigPanelGUID write trigPanelGUID;
+    function trigCenter (): TDFPoint; inline;
   end;
 
-function g_Triggers_Create(Trigger: TTrigger; forceInternalIndex: Integer=-1): DWORD;
+function g_Triggers_Create (aTrigger: TTrigger; trec: TDynRecord; forceInternalIndex: Integer=-1): DWORD;
 procedure g_Triggers_Update();
 procedure g_Triggers_Press(ID: DWORD; ActivateType: Byte; ActivateUID: Word = 0);
 function g_Triggers_PressR(X, Y: Integer; Width, Height: Word; UID: Word;
@@ -86,8 +89,8 @@ procedure g_Triggers_PressC(CX, CY: Integer; Radius: Word; UID: Word; ActivateTy
 procedure g_Triggers_OpenAll();
 procedure g_Triggers_DecreaseSpawner(ID: DWORD);
 procedure g_Triggers_Free();
-procedure g_Triggers_SaveState(var Mem: TBinMemoryWriter);
-procedure g_Triggers_LoadState(var Mem: TBinMemoryReader);
+procedure g_Triggers_SaveState (st: TStream);
+procedure g_Triggers_LoadState (st: TStream);
 
 
 var
@@ -103,14 +106,152 @@ uses
   Math,
   g_player, g_map, g_panel, g_gfx, g_game, g_textures,
   g_console, g_monsters, g_items, g_phys, g_weapons,
-  wadreader, g_main, SysUtils, e_log, g_language,
-  g_options, g_net, g_netmsg, utils, xparser;
+  wadreader, g_main, e_log, g_language,
+  g_options, g_net, g_netmsg, utils, xparser, xstreams;
 
 const
   TRIGGER_SIGNATURE = $58475254; // 'TRGX'
   TRAP_DAMAGE = 1000;
 
+{$INCLUDE ../shared/mapdef_tgc_impl.inc}
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+type
+  TTrigScope = class(TExprScope)
+  private
+    plrprops: TPropHash;
+    monsprops: TPropHash;
+    platprops: TPropHash;
+
+  public
+    me: PTrigger;
+
+  public
+    constructor Create ();
+    destructor Destroy (); override;
+
+    function getObj (const aname: AnsiString): TObject; override;
+    function getField (obj: TObject; const afldname: AnsiString): Variant; override;
+    procedure setField (obj: TObject; const afldname: AnsiString; var aval: Variant); override;
+  end;
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+type
+  TMyConstList = class(TExprConstList)
+  public
+    function valid (const cname: AnsiString): Boolean; override;
+    function get (const cname: AnsiString; out v: Variant): Boolean; override;
+  end;
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+function TMyConstList.valid (const cname: AnsiString): Boolean;
+begin
+  //writeln('CHECK: ''', cname, '''');
+  result :=
+    (cname = 'player') or
+    (cname = 'self') or
+    false;
+end;
+
+function TMyConstList.get (const cname: AnsiString; out v: Variant): Boolean;
+var
+  eidx: Integer;
+  ebs: TDynEBS;
+begin
+  //if (cname = 'answer') then begin v := LongInt(42); result := true; exit; end;
+  result := false;
+  if (gCurrentMap = nil) then exit;
+  for eidx := 0 to gCurrentMap.mapdef.ebsTypeCount-1 do
+  begin
+    ebs := gCurrentMap.mapdef.ebsTypeAt[eidx];
+    if ebs.has[cname] then
+    begin
+      //writeln('FOUND: ''', cname, '''');
+      v := ebs[cname];
+      result := true;
+      exit;
+    end;
+  end;
+end;
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+constructor TTrigScope.Create ();
+begin
+  plrprops := TPropHash.Create(TPlayer, 'e');
+  monsprops := TPropHash.Create(TMonster, 'e');
+  platprops := TPropHash.Create(TPanel, 'e');
+  me := nil;
+end;
+
+
+destructor TTrigScope.Destroy ();
+begin
+  platprops.Free();
+  monsprops.Free();
+  plrprops.Free();
+  inherited;
+end;
+
+
+function TTrigScope.getObj (const aname: AnsiString): TObject;
+begin
+       if (aname = 'player') then result := gPlayers[0] //FIXME
+  else if (aname = 'self') or (aname = 'this') then result := TObject(Pointer(PtrUInt(1)))
+  else result := inherited getObj(aname);
+end;
+
+
+function TTrigScope.getField (obj: TObject; const afldname: AnsiString): Variant;
+begin
+  if (obj = gPlayers[0]) then
+  begin
+    if plrprops.get(obj, afldname, result) then exit;
+  end
+  else if (obj = TObject(Pointer(PtrUInt(1)))) then
+  begin
+    if (me <> nil) and (me.userVars <> nil) then
+    begin
+      if me.userVars.get(afldname, result) then exit;
+    end;
+  end;
+  result := inherited getField(obj, afldname);
+end;
+
+
+procedure TTrigScope.setField (obj: TObject; const afldname: AnsiString; var aval: Variant);
+begin
+  if (obj = gPlayers[0]) then
+  begin
+    if plrprops.put(obj, afldname, aval) then exit;
+  end
+  else if (obj = TObject(Pointer(PtrUInt(1)))) then
+  begin
+    if (me <> nil) then
+    begin
+      if (Length(afldname) > 4) and (afldname[1] = 'u') and (afldname[2] = 's') and
+         (afldname[3] = 'e') and (afldname[4] = 'r') then
+      begin
+        if (me.userVars = nil) then me.userVars := THashStrVariant.Create();
+        me.userVars.put(afldname, aval);
+        exit;
+      end;
+    end;
+  end;
+  inherited setField(obj, afldname, aval);
+end;
+
+
+// ////////////////////////////////////////////////////////////////////////// //
+var
+  tgscope: TTrigScope = nil;
+  tgclist: TMyConstList = nil;
 
+
+// ////////////////////////////////////////////////////////////////////////// //
 function TTrigger.trigCenter (): TDFPoint; inline;
 begin
   result := TDFPoint.Create(x+width div 2, y+height div 2);
@@ -119,23 +260,27 @@ end;
 
 function FindTrigger (): DWORD;
 var
-  i: Integer;
+  i, olen: Integer;
 begin
-  for i := 0 to High(gTriggers) do
+  olen := Length(gTriggers);
+
+  for i := 0 to olen-1 do
   begin
     if gTriggers[i].TriggerType = TRIGGER_NONE then begin result := i; exit; end;
   end;
 
-  if (gTriggers = nil) then
-  begin
-    SetLength(gTriggers, 8);
-    result := 0;
-  end
-  else
+  SetLength(gTriggers, olen+8);
+  result := olen;
+
+  for i := result to High(gTriggers) do
   begin
-    result := Length(gTriggers);
-    SetLength(gTriggers, result+8);
-    for i := result to High(gTriggers) do gTriggers[i].TriggerType := TRIGGER_NONE;
+    gTriggers[i].TriggerType := TRIGGER_NONE;
+    gTriggers[i].trigDataRec := nil;
+    gTriggers[i].exoInit := nil;
+    gTriggers[i].exoThink := nil;
+    gTriggers[i].exoCheck := nil;
+    gTriggers[i].exoAction := nil;
+    gTriggers[i].userVars := nil;
   end;
 end;
 
@@ -447,17 +592,17 @@ begin
   if (gLifts[PanelID].PanelType = PANEL_LIFTUP) or (gLifts[PanelID].PanelType = PANEL_LIFTDOWN) then
   begin
     case d of
-      0: t := 0;
-      1: t := 1;
-      else t := IfThen(gLifts[PanelID].LiftType = 1, 0, 1);
+      0: t := LIFTTYPE_UP;
+      1: t := LIFTTYPE_DOWN;
+      else t := IfThen(gLifts[PanelID].LiftType = LIFTTYPE_DOWN, LIFTTYPE_UP, LIFTTYPE_DOWN);
     end
   end
   else if (gLifts[PanelID].PanelType = PANEL_LIFTLEFT) or (gLifts[PanelID].PanelType = PANEL_LIFTRIGHT) then
   begin
     case d of
-      0: t := 2;
-      1: t := 3;
-      else t := IfThen(gLifts[PanelID].LiftType = 2, 3, 2);
+      0: t := LIFTTYPE_LEFT;
+      1: t := LIFTTYPE_RIGHT;
+      else t := IfThen(gLifts[PanelID].LiftType = LIFTTYPE_LEFT, LIFTTYPE_RIGHT, LIFTTYPE_LEFT);
     end;
   end;
 
@@ -661,6 +806,12 @@ begin
         snd := 'SOUND_WEAPON_EXPLODEBFG';
       end;
 
+    TRIGGER_SHOT_FLAME:
+      begin
+        g_Weapon_flame(wx, wy, dx, dy, 0, -1, True);
+        snd := 'SOUND_GAME_BURNING';
+      end;
+
     else exit;
   end;
 
@@ -687,28 +838,28 @@ procedure MakeShot (var Trigger: TTrigger; wx, wy, dx, dy: Integer; TargetUID: W
 begin
   with Trigger do
   begin
-    if (trigData.trigAmmo = 0) or ((trigData.trigAmmo > 0) and (ShotAmmoCount > 0)) then
+    if (tgcAmmo = 0) or ((tgcAmmo > 0) and (ShotAmmoCount > 0)) then
     begin
-      if (trigShotPanelGUID <> -1) and (ShotPanelTime = 0) then
+      if (trigPanelGUID <> -1) and (ShotPanelTime = 0) then
       begin
-        g_Map_SwitchTextureGUID(ShotPanelType, trigShotPanelGUID);
+        g_Map_SwitchTextureGUID({ShotPanelType,} trigPanelGUID);
         ShotPanelTime := 4; // òèêîâ íà âñïûøêó âûñòðåëà
       end;
 
-      if (trigData.trigSight > 0) then ShotSightTimeout := 180; // ~= 5 ñåêóíä
+      if (tgcSight > 0) then ShotSightTimeout := 180; // ~= 5 ñåêóíä
 
       if (ShotAmmoCount > 0) then Dec(ShotAmmoCount);
 
-      dx += Random(trigData.trigAccuracy)-Random(trigData.trigAccuracy);
-      dy += Random(trigData.trigAccuracy)-Random(trigData.trigAccuracy);
+      dx += Random(tgcAccuracy)-Random(tgcAccuracy);
+      dy += Random(tgcAccuracy)-Random(tgcAccuracy);
 
-      tr_SpawnShot(trigData.trigShotType, wx, wy, dx, dy, not trigData.trigQuiet, TargetUID);
+      tr_SpawnShot(tgcShotType, wx, wy, dx, dy, tgcShotSound, TargetUID);
     end
     else
     begin
-      if (trigData.trigReload > 0) and (ShotReloadTime = 0) then
+      if (tgcReload > 0) and (ShotReloadTime = 0) then
       begin
-        ShotReloadTime := trigData.trigReload; // òèêîâ íà ïåðåçàðÿäêó ïóøêè
+        ShotReloadTime := tgcReload; // òèêîâ íà ïåðåçàðÿäêó ïóøêè
       end;
     end;
   end;
@@ -1001,11 +1152,11 @@ begin
   with Trigger do
   begin
     if TriggerType <> TRIGGER_SHOT then Exit;
-    result := (trigData.trigAim and TRIGGER_SHOT_AIM_ALLMAP > 0)
+    result := (tgcAim and TRIGGER_SHOT_AIM_ALLMAP > 0)
               or g_Obj_Collide(X, Y, Width, Height, Obj);
-    if result and (trigData.trigAim and TRIGGER_SHOT_AIM_TRACE > 0) then
+    if result and (tgcAim and TRIGGER_SHOT_AIM_TRACE > 0) then
     begin
-      result := g_TraceVector(trigData.trigTX, trigData.trigTY,
+      result := g_TraceVector(tgcTX, tgcTY,
                               Obj^.X + Obj^.Rect.X + (Obj^.Rect.Width div 2),
                               Obj^.Y + Obj^.Rect.Y + (Obj^.Rect.Height div 2));
     end;
@@ -1066,18 +1217,53 @@ var
     end;
   end;
 
+var
+  tvval: Variant;
 begin
   result := false;
   if g_Game_IsClient then exit;
 
   if not Trigger.Enabled then exit;
   if (Trigger.TimeOut <> 0) and (actType <> ACTIVATE_CUSTOM) then exit;
-  if gLMSRespawn = LMS_RESPAWN_WARMUP then exit;
+  if (gLMSRespawn = LMS_RESPAWN_WARMUP) then exit;
+
+  if (Trigger.exoCheck <> nil) then
+  begin
+    //conwritefln('exocheck: [%s]', [Trigger.exoCheck.toString()]);
+    try
+      tgscope.me := @Trigger;
+      tvval := Trigger.exoCheck.value(tgscope);
+      tgscope.me := nil;
+      if not Boolean(tvval) then exit;
+    except on e: Exception do
+      begin
+        tgscope.me := nil;
+        conwritefln('trigger exocheck error: %s [%s]', [e.message, Trigger.exoCheck.toString()]);
+        exit;
+      end;
+    end;
+  end;
 
   animonce := False;
 
   coolDown := (actType <> 0);
 
+  if (Trigger.exoAction <> nil) then
+  begin
+    //conwritefln('exoactivate: [%s]', [Trigger.exoAction.toString()]);
+    try
+      tgscope.me := @Trigger;
+      Trigger.exoAction.value(tgscope);
+      tgscope.me := nil;
+    except on e: Exception do
+      begin
+        tgscope.me := nil;
+        conwritefln('trigger exoactivate error: %s [%s]', [e.message, Trigger.exoAction.toString()]);
+        exit;
+      end;
+    end;
+  end;
+
   with Trigger do
   begin
     case TriggerType of
@@ -1086,7 +1272,7 @@ begin
           g_Sound_PlayEx('SOUND_GAME_SWITCH0');
           if g_Game_IsNet then MH_SEND_Sound(X, Y, 'SOUND_GAME_SWITCH0');
           gExitByTrigger := True;
-          g_Game_ExitLevel(trigData.trigMap);
+          g_Game_ExitLevel(tgcMap);
           TimeOut := 18;
           Result := True;
 
@@ -1096,21 +1282,21 @@ begin
       TRIGGER_TELEPORT:
         begin
           Result := tr_Teleport(ActivateUID,
-                                trigData.trigTarget.X, trigData.trigTarget.Y,
-                                trigData.trigDirection, trigData.trigSilent,
-                                trigData.trigD2d);
+                                tgcTarget.X, tgcTarget.Y,
+                                tgcDirection, tgcSilent,
+                                tgcD2d);
           TimeOut := 0;
         end;
 
       TRIGGER_OPENDOOR:
         begin
-          Result := tr_OpenDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+          Result := tr_OpenDoor(trigPanelGUID, tgcSilent, tgcD2d);
           TimeOut := 0;
         end;
 
       TRIGGER_CLOSEDOOR:
         begin
-          Result := tr_CloseDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+          Result := tr_CloseDoor(trigPanelGUID, tgcSilent, tgcD2d);
           TimeOut := 0;
         end;
 
@@ -1121,12 +1307,12 @@ begin
           begin
             if gWalls[{trigPanelID}pan.arrIdx].Enabled then
             begin
-              result := tr_OpenDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+              result := tr_OpenDoor(trigPanelGUID, tgcSilent, tgcD2d);
               if (TriggerType = TRIGGER_DOOR5) then DoorTime := 180;
             end
             else
             begin
-              result := tr_CloseDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+              result := tr_CloseDoor(trigPanelGUID, tgcSilent, tgcD2d);
             end;
 
             if result then TimeOut := 18;
@@ -1135,7 +1321,7 @@ begin
 
       TRIGGER_CLOSETRAP, TRIGGER_TRAP:
         begin
-          tr_CloseTrap(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+          tr_CloseTrap(trigPanelGUID, tgcSilent, tgcD2d);
 
           if TriggerType = TRIGGER_TRAP then
             begin
@@ -1154,7 +1340,7 @@ begin
       TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF:
         begin
           PressCount += 1;
-          if PressTime = -1 then PressTime := trigData.trigWait;
+          if PressTime = -1 then PressTime := tgcWait;
           if coolDown then TimeOut := 18 else TimeOut := 0;
           Result := True;
         end;
@@ -1166,18 +1352,24 @@ begin
           Result := True;
           if gLMSRespawn = LMS_RESPAWN_NONE then
           begin
-            g_Player_Get(ActivateUID).GetSecret();
+            p := g_Player_Get(ActivateUID);
+            p.GetSecret();
             Inc(gCoopSecretsFound);
-            if g_Game_IsNet then MH_SEND_GameStats();
+            if g_Game_IsNet then
+            begin
+              MH_SEND_GameStats();
+              if p.FClientID >= 0 then
+                MH_SEND_GameEvent(NET_EV_SECRET, p.UID, '');
+            end;
           end;
         end;
 
       TRIGGER_LIFTUP:
         begin
-          Result := tr_SetLift(trigPanelGUID, 0, trigData.trigSilent, trigData.trigD2d);
+          Result := tr_SetLift(trigPanelGUID, 0, tgcSilent, tgcD2d);
           TimeOut := 0;
 
-          if (not trigData.trigSilent) and Result then begin
+          if (not tgcSilent) and Result then begin
             g_Sound_PlayExAt('SOUND_GAME_SWITCH0',
                              X + (Width div 2),
                              Y + (Height div 2));
@@ -1190,10 +1382,10 @@ begin
 
       TRIGGER_LIFTDOWN:
         begin
-          Result := tr_SetLift(trigPanelGUID, 1, trigData.trigSilent, trigData.trigD2d);
+          Result := tr_SetLift(trigPanelGUID, 1, tgcSilent, tgcD2d);
           TimeOut := 0;
 
-          if (not trigData.trigSilent) and Result then begin
+          if (not tgcSilent) and Result then begin
             g_Sound_PlayExAt('SOUND_GAME_SWITCH0',
                              X + (Width div 2),
                              Y + (Height div 2));
@@ -1206,13 +1398,13 @@ begin
 
       TRIGGER_LIFT:
         begin
-          Result := tr_SetLift(trigPanelGUID, 3, trigData.trigSilent, trigData.trigD2d);
+          Result := tr_SetLift(trigPanelGUID, 3, tgcSilent, tgcD2d);
 
           if Result then
           begin
             TimeOut := 18;
 
-            if (not trigData.trigSilent) and Result then begin
+            if (not tgcSilent) and Result then begin
               g_Sound_PlayExAt('SOUND_GAME_SWITCH0',
                                X + (Width div 2),
                                Y + (Height div 2));
@@ -1226,7 +1418,7 @@ begin
 
       TRIGGER_TEXTURE:
         begin
-          if trigData.trigActivateOnce then
+          if tgcActivateOnce then
             begin
               Enabled := False;
               TriggerType := TRIGGER_NONE;
@@ -1237,7 +1429,7 @@ begin
             else
               TimeOut := 0;
 
-          animonce := trigData.trigAnimateOnce;
+          animonce := tgcAnimateOnce;
           Result := True;
         end;
 
@@ -1245,17 +1437,17 @@ begin
         begin
           if Sound <> nil then
           begin
-            if trigData.trigSoundSwitch and Sound.IsPlaying() then
+            if tgcSoundSwitch and Sound.IsPlaying() then
               begin // Íóæíî âûêëþ÷èòü, åñëè èãðàë
                 Sound.Stop();
                 SoundPlayCount := 0;
                 Result := True;
               end
             else // (not Data.SoundSwitch) or (not Sound.IsPlaying())
-              if (trigData.trigPlayCount > 0) or (not Sound.IsPlaying()) then
+              if (tgcPlayCount > 0) or (not Sound.IsPlaying()) then
                 begin
-                  if trigData.trigPlayCount > 0 then
-                    SoundPlayCount := trigData.trigPlayCount
+                  if tgcPlayCount > 0 then
+                    SoundPlayCount := tgcPlayCount
                   else // 0 - èãðàåì áåñêîíå÷íî
                     SoundPlayCount := 1;
                   Result := True;
@@ -1265,10 +1457,10 @@ begin
         end;
 
       TRIGGER_SPAWNMONSTER:
-        if (trigData.trigSpawnMonsType in [MONSTER_DEMON..MONSTER_MAN]) then
+        if (tgcSpawnMonsType in [MONSTER_DEMON..MONSTER_MAN]) then
         begin
           Result := False;
-          if (trigData.trigDelay > 0) and (actType <> ACTIVATE_CUSTOM) then
+          if (tgcDelay > 0) and (actType <> ACTIVATE_CUSTOM) then
           begin
             AutoSpawn := not AutoSpawn;
             SpawnCooldown := 0;
@@ -1276,34 +1468,34 @@ begin
             Result := True;
           end;
 
-          if ((trigData.trigDelay = 0) and (actType <> ACTIVATE_CUSTOM))
-          or ((trigData.trigDelay > 0) and (actType = ACTIVATE_CUSTOM)) then
-            for k := 1 to trigData.trigMonsCount do
+          if ((tgcDelay = 0) and (actType <> ACTIVATE_CUSTOM))
+          or ((tgcDelay > 0) and (actType = ACTIVATE_CUSTOM)) then
+            for k := 1 to tgcMonsCount do
             begin
-              if (actType = ACTIVATE_CUSTOM) and (trigData.trigDelay > 0) then
-                SpawnCooldown := trigData.trigDelay;
-              if (trigData.trigMax > 0) and (SpawnedCount >= trigData.trigMax) then
+              if (actType = ACTIVATE_CUSTOM) and (tgcDelay > 0) then
+                SpawnCooldown := -1; // Çàäåðæêà âûñòàâèòñÿ ìîíñòðîì ïðè óíè÷òîæåíèè
+              if (tgcMax > 0) and (SpawnedCount >= tgcMax) then
                 Break;
 
-              mon := g_Monsters_Create(trigData.trigSpawnMonsType,
-                     trigData.trigTX, trigData.trigTY,
-                     TDirection(trigData.trigDirection), True);
+              mon := g_Monsters_Create(tgcSpawnMonsType,
+                     tgcTX, tgcTY,
+                     TDirection(tgcDirection), True);
 
               Result := True;
 
             // Çäîðîâüå:
-              if (trigData.trigHealth > 0) then
-                mon.SetHealth(trigData.trigHealth);
+              if (tgcHealth > 0) then
+                mon.SetHealth(tgcHealth);
             // Óñòàíàâëèâàåì ïîâåäåíèå:
-              mon.MonsterBehaviour := trigData.trigBehaviour;
+              mon.MonsterBehaviour := tgcBehaviour;
               mon.FNoRespawn := True;
               if g_Game_IsNet then
                 MH_SEND_MonsterSpawn(mon.UID);
             // Èäåì èñêàòü öåëü, åñëè íàäî:
-              if trigData.trigActive then
+              if tgcActive then
                 mon.WakeUp();
 
-              if trigData.trigSpawnMonsType <> MONSTER_BARREL then Inc(gTotalMonsters);
+              if tgcSpawnMonsType <> MONSTER_BARREL then Inc(gTotalMonsters);
 
               if g_Game_IsNet then
               begin
@@ -1311,18 +1503,15 @@ begin
                 gMonstersSpawned[High(gMonstersSpawned)] := mon.UID;
               end;
 
-              if trigData.trigMax > 0 then
-              begin
-                mon.SpawnTrigger := ID;
-                Inc(SpawnedCount);
-              end;
+              mon.SpawnTrigger := ID;
+              if tgcMax > 0 then Inc(SpawnedCount);
 
-              case trigData.trigEffect of
+              case tgcEffect of
                 EFFECT_TELEPORT: begin
                   if g_Frames_Get(FramesID, 'FRAMES_TELEPORT') then
                   begin
                     Anim := TAnimation.Create(FramesID, False, 3);
-                    g_Sound_PlayExAt('SOUND_GAME_TELEPORT', trigData.trigTX, trigData.trigTY);
+                    g_Sound_PlayExAt('SOUND_GAME_TELEPORT', tgcTX, tgcTY);
                     g_GFX_OnceAnim(mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2)-32,
                                    mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2)-32, Anim);
                     Anim.Free();
@@ -1336,7 +1525,7 @@ begin
                   if g_Frames_Get(FramesID, 'FRAMES_ITEM_RESPAWN') then
                   begin
                     Anim := TAnimation.Create(FramesID, False, 4);
-                    g_Sound_PlayExAt('SOUND_ITEM_RESPAWNITEM', trigData.trigTX, trigData.trigTY);
+                    g_Sound_PlayExAt('SOUND_ITEM_RESPAWNITEM', tgcTX, tgcTY);
                     g_GFX_OnceAnim(mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2)-16,
                                    mon.Obj.Y+mon.Obj.Rect.Y+(mon.Obj.Rect.Height div 2)-16, Anim);
                     Anim.Free();
@@ -1350,7 +1539,7 @@ begin
                   if g_Frames_Get(FramesID, 'FRAMES_FIRE') then
                   begin
                     Anim := TAnimation.Create(FramesID, False, 4);
-                    g_Sound_PlayExAt('SOUND_FIRE', trigData.trigTX, trigData.trigTY);
+                    g_Sound_PlayExAt('SOUND_FIRE', tgcTX, tgcTY);
                     g_GFX_OnceAnim(mon.Obj.X+mon.Obj.Rect.X+(mon.Obj.Rect.Width div 2)-32,
                                    mon.Obj.Y+mon.Obj.Rect.Y+mon.Obj.Rect.Height-128, Anim);
                     Anim.Free();
@@ -1378,10 +1567,10 @@ begin
         end;
 
       TRIGGER_SPAWNITEM:
-        if (trigData.trigSpawnItemType in [ITEM_MEDKIT_SMALL..ITEM_MAX]) then
+        if (tgcSpawnItemType in [ITEM_MEDKIT_SMALL..ITEM_MAX]) then
         begin
           Result := False;
-          if (trigData.trigDelay > 0) and (actType <> ACTIVATE_CUSTOM) then
+          if (tgcDelay > 0) and (actType <> ACTIVATE_CUSTOM) then
           begin
             AutoSpawn := not AutoSpawn;
             SpawnCooldown := 0;
@@ -1389,36 +1578,33 @@ begin
             Result := True;
           end;
 
-          if ((trigData.trigDelay = 0) and (actType <> ACTIVATE_CUSTOM))
-          or ((trigData.trigDelay > 0) and (actType = ACTIVATE_CUSTOM)) then
-            if (not trigData.trigDmonly) or
+          if ((tgcDelay = 0) and (actType <> ACTIVATE_CUSTOM))
+          or ((tgcDelay > 0) and (actType = ACTIVATE_CUSTOM)) then
+            if (not tgcDmonly) or
                (gGameSettings.GameMode in [GM_DM, GM_TDM, GM_CTF]) then
-              for k := 1 to trigData.trigItemCount do
+              for k := 1 to tgcItemCount do
               begin
-                if (actType = ACTIVATE_CUSTOM) and (trigData.trigDelay > 0) then
-                  SpawnCooldown := trigData.trigDelay;
-                if (trigData.trigMax > 0) and (SpawnedCount >= trigData.trigMax) then
+                if (actType = ACTIVATE_CUSTOM) and (tgcDelay > 0) then
+                  SpawnCooldown := -1; // Çàäåðæêà âûñòàâèòñÿ èòåìîì ïðè óíè÷òîæåíèè
+                if (tgcMax > 0) and (SpawnedCount >= tgcMax) then
                   Break;
 
-                iid := g_Items_Create(trigData.trigTX, trigData.trigTY,
-                  trigData.trigSpawnItemType, trigData.trigGravity, False, True);
+                iid := g_Items_Create(tgcTX, tgcTY,
+                  tgcSpawnItemType, tgcGravity, False, True);
 
                 Result := True;
 
-                if trigData.trigMax > 0 then
-                begin
-                  it := g_Items_ByIdx(iid);
-                  it.SpawnTrigger := ID;
-                  Inc(SpawnedCount);
-                end;
+                it := g_Items_ByIdx(iid);
+                it.SpawnTrigger := ID;
+                if tgcMax > 0 then Inc(SpawnedCount);
 
-                case trigData.trigEffect of
+                case tgcEffect of
                   EFFECT_TELEPORT: begin
                     it := g_Items_ByIdx(iid);
                     if g_Frames_Get(FramesID, 'FRAMES_TELEPORT') then
                     begin
                       Anim := TAnimation.Create(FramesID, False, 3);
-                      g_Sound_PlayExAt('SOUND_GAME_TELEPORT', trigData.trigTX, trigData.trigTY);
+                      g_Sound_PlayExAt('SOUND_GAME_TELEPORT', tgcTX, tgcTY);
                       g_GFX_OnceAnim(it.Obj.X+it.Obj.Rect.X+(it.Obj.Rect.Width div 2)-32,
                                      it.Obj.Y+it.Obj.Rect.Y+(it.Obj.Rect.Height div 2)-32, Anim);
                       Anim.Free();
@@ -1433,7 +1619,7 @@ begin
                     if g_Frames_Get(FramesID, 'FRAMES_ITEM_RESPAWN') then
                     begin
                       Anim := TAnimation.Create(FramesID, False, 4);
-                      g_Sound_PlayExAt('SOUND_ITEM_RESPAWNITEM', trigData.trigTX, trigData.trigTY);
+                      g_Sound_PlayExAt('SOUND_ITEM_RESPAWNITEM', tgcTX, tgcTY);
                       g_GFX_OnceAnim(it.Obj.X+it.Obj.Rect.X+(it.Obj.Rect.Width div 2)-16,
                                      it.Obj.Y+it.Obj.Rect.Y+(it.Obj.Rect.Height div 2)-16, Anim);
                       Anim.Free();
@@ -1448,7 +1634,7 @@ begin
                     if g_Frames_Get(FramesID, 'FRAMES_FIRE') then
                     begin
                       Anim := TAnimation.Create(FramesID, False, 4);
-                      g_Sound_PlayExAt('SOUND_FIRE', trigData.trigTX, trigData.trigTY);
+                      g_Sound_PlayExAt('SOUND_FIRE', tgcTX, tgcTY);
                       g_GFX_OnceAnim(it.Obj.X+it.Obj.Rect.X+(it.Obj.Rect.Width div 2)-32,
                                      it.Obj.Y+it.Obj.Rect.Y+it.Obj.Rect.Height-128, Anim);
                       Anim.Free();
@@ -1476,14 +1662,14 @@ begin
       TRIGGER_MUSIC:
         begin
         // Ìåíÿåì ìóçûêó, åñëè åñòü íà ÷òî:
-          if (Trigger.trigData.trigMusicName <> '') then
+          if (Trigger.tgcMusicName <> '') then
           begin
-            gMusic.SetByName(Trigger.trigData.trigMusicName);
+            gMusic.SetByName(Trigger.tgcMusicName);
             gMusic.SpecPause := True;
             gMusic.Play();
           end;
 
-          case Trigger.trigData.trigMusicAction of
+          case Trigger.tgcMusicAction of
             TRIGGER_MUSIC_ACTION_STOP: // Âûêëþ÷èòü
               gMusic.SpecPause := True; // Ïàóçà
             TRIGGER_MUSIC_ACTION_PLAY: // Âêëþ÷èòü
@@ -1503,11 +1689,11 @@ begin
 
       TRIGGER_PUSH:
         begin
-          pAngle := -DegToRad(trigData.trigAngle);
+          pAngle := -DegToRad(tgcAngle);
           Result := tr_Push(ActivateUID,
-                            Floor(Cos(pAngle)*trigData.trigForce),
-                            Floor(Sin(pAngle)*trigData.trigForce),
-                            trigData.trigResetVelocity);
+                            Floor(Cos(pAngle)*tgcForce),
+                            Floor(Sin(pAngle)*tgcForce),
+                            tgcResetVelocity);
           TimeOut := 0;
         end;
 
@@ -1515,114 +1701,114 @@ begin
         begin
           Result := False;
           // Ïðèáàâèòü èëè îòíÿòü î÷êî
-          if (trigData.trigScoreAction in [TRIGGER_SCORE_ACTION_ADD, TRIGGER_SCORE_ACTION_SUB]) and (trigData.trigScoreCount > 0) then
+          if (tgcScoreAction in [TRIGGER_SCORE_ACTION_ADD, TRIGGER_SCORE_ACTION_SUB]) and (tgcScoreCount > 0) then
           begin
             // Ñâîåé èëè ÷óæîé êîìàíäå
-            if (trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
+            if (tgcScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
             begin
               p := g_Player_Get(ActivateUID);
-              if ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED))
-              or ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
+              if ((tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED))
+              or ((tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
               begin
-                Inc(gTeamStat[TEAM_RED].Goals, trigData.trigScoreCount); // Red Scores
+                Inc(gTeamStat[TEAM_RED].Goals, tgcScoreCount); // Red Scores
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                  if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_OWN], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_OWN], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '+r');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '+r');
                   end else
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_ENEMY], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_ENEMY], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '+re');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '+re');
                   end;
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_ADD], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, TEAM_RED);
                 end;
               end;
-              if ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED))
-              or ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
+              if ((tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED))
+              or ((tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
               begin
-                Dec(gTeamStat[TEAM_RED].Goals, trigData.trigScoreCount); // Red Fouls
+                Dec(gTeamStat[TEAM_RED].Goals, tgcScoreCount); // Red Fouls
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                  if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_OWN], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_OWN], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '-r');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '-r');
                   end else
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_ENEMY], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_ENEMY], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '-re');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '-re');
                   end;
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_SUB], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, -TEAM_RED);
                 end;
               end;
-              if ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE))
-              or ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
+              if ((tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE))
+              or ((tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
               begin
-                Inc(gTeamStat[TEAM_BLUE].Goals, trigData.trigScoreCount); // Blue Scores
+                Inc(gTeamStat[TEAM_BLUE].Goals, tgcScoreCount); // Blue Scores
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                  if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_OWN], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_OWN], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '+b');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '+b');
                   end else
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_ENEMY], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_ENEMY], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '+be');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '+be');
                   end;
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_ADD], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, TEAM_BLUE);
                 end;
               end;
-              if ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE))
-              or ((trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
+              if ((tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE))
+              or ((tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
               begin
-                Dec(gTeamStat[TEAM_BLUE].Goals, trigData.trigScoreCount); // Blue Fouls
+                Dec(gTeamStat[TEAM_BLUE].Goals, tgcScoreCount); // Blue Fouls
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                  if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_OWN], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_OWN], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '-b');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '-b');
                   end else
                   begin
-                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_ENEMY], [p.Name, trigData.trigScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
+                    g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_ENEMY], [p.Name, tgcScoreCount, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                     if g_Game_IsServer and g_Game_IsNet then
-                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (trigData.trigScoreCount shl 16), '-be');
+                      MH_SEND_GameEvent(NET_EV_SCORE, p.UID or (tgcScoreCount shl 16), '-be');
                   end;
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_SUB], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
@@ -1632,74 +1818,74 @@ begin
               Result := (p.Team = TEAM_RED) or (p.Team = TEAM_BLUE);
             end;
             // Êàêîé-òî êîíêðåòíîé êîìàíäå
-            if trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_RED, TRIGGER_SCORE_TEAM_FORCE_BLUE] then
+            if tgcScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_RED, TRIGGER_SCORE_TEAM_FORCE_BLUE] then
             begin
-              if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then
+              if (tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then
               begin
-                Inc(gTeamStat[TEAM_RED].Goals, trigData.trigScoreCount); // Red Scores
+                Inc(gTeamStat[TEAM_RED].Goals, tgcScoreCount); // Red Scores
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_TEAM], [_lc[I_PLAYER_SCORE_RED], trigData.trigScoreCount]), True);
+                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_TEAM], [_lc[I_PLAYER_SCORE_RED], tgcScoreCount]), True);
                   if g_Game_IsServer and g_Game_IsNet then
-                    MH_SEND_GameEvent(NET_EV_SCORE, trigData.trigScoreCount shl 16, '+tr');
+                    MH_SEND_GameEvent(NET_EV_SCORE, tgcScoreCount shl 16, '+tr');
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_ADD], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, TEAM_RED);
                 end;
               end;
-              if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then
+              if (tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then
               begin
-                Dec(gTeamStat[TEAM_RED].Goals, trigData.trigScoreCount); // Red Fouls
+                Dec(gTeamStat[TEAM_RED].Goals, tgcScoreCount); // Red Fouls
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_TEAM], [_lc[I_PLAYER_SCORE_RED], trigData.trigScoreCount]), True);
+                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_TEAM], [_lc[I_PLAYER_SCORE_RED], tgcScoreCount]), True);
                   if g_Game_IsServer and g_Game_IsNet then
-                    MH_SEND_GameEvent(NET_EV_SCORE, trigData.trigScoreCount shl 16, '-tr');
+                    MH_SEND_GameEvent(NET_EV_SCORE, tgcScoreCount shl 16, '-tr');
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_SUB], [AnsiUpperCase(_lc[I_GAME_TEAM_RED])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, -TEAM_RED);
                 end;
               end;
-              if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_ADD) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then
+              if (tgcScoreAction = TRIGGER_SCORE_ACTION_ADD) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then
               begin
-                Inc(gTeamStat[TEAM_BLUE].Goals, trigData.trigScoreCount); // Blue Scores
+                Inc(gTeamStat[TEAM_BLUE].Goals, tgcScoreCount); // Blue Scores
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_TEAM], [_lc[I_PLAYER_SCORE_BLUE], trigData.trigScoreCount]), True);
+                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_ADD_TEAM], [_lc[I_PLAYER_SCORE_BLUE], tgcScoreCount]), True);
                   if g_Game_IsServer and g_Game_IsNet then
-                    MH_SEND_GameEvent(NET_EV_SCORE, trigData.trigScoreCount shl 16, '+tb');
+                    MH_SEND_GameEvent(NET_EV_SCORE, tgcScoreCount shl 16, '+tb');
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_ADD], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
                     MH_SEND_GameEvent(NET_EV_SCORE_MSG, TEAM_BLUE);
                 end;
               end;
-              if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_SUB) and (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then
+              if (tgcScoreAction = TRIGGER_SCORE_ACTION_SUB) and (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then
               begin
-                Dec(gTeamStat[TEAM_BLUE].Goals, trigData.trigScoreCount); // Blue Fouls
+                Dec(gTeamStat[TEAM_BLUE].Goals, tgcScoreCount); // Blue Fouls
 
-                if trigData.trigScoreCon then
+                if tgcScoreCon then
                 begin
-                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_TEAM], [_lc[I_PLAYER_SCORE_BLUE], trigData.trigScoreCount]), True);
+                  g_Console_Add(Format(_lc[I_PLAYER_SCORE_SUB_TEAM], [_lc[I_PLAYER_SCORE_BLUE], tgcScoreCount]), True);
                   if g_Game_IsServer and g_Game_IsNet then
-                    MH_SEND_GameEvent(NET_EV_SCORE, trigData.trigScoreCount shl 16, '-tb');
+                    MH_SEND_GameEvent(NET_EV_SCORE, tgcScoreCount shl 16, '-tb');
                 end;
 
-                if trigData.trigScoreMsg then
+                if tgcScoreMsg then
                 begin
                   g_Game_Message(Format(_lc[I_MESSAGE_SCORE_SUB], [AnsiUpperCase(_lc[I_GAME_TEAM_BLUE])]), 108);
                   if g_Game_IsServer and g_Game_IsNet then
@@ -1710,22 +1896,22 @@ begin
             end;
           end;
           // Âûèãðûø
-          if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_WIN) and (gGameSettings.GoalLimit > 0) then
+          if (tgcScoreAction = TRIGGER_SCORE_ACTION_WIN) and (gGameSettings.GoalLimit > 0) then
           begin
             // Ñâîåé èëè ÷óæîé êîìàíäû
-            if (trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
+            if (tgcScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
             begin
               p := g_Player_Get(ActivateUID);
-              if ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED)) // Red Wins
-              or ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
+              if ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED)) // Red Wins
+              or ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
               begin
                 if gTeamStat[TEAM_RED].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
                   gTeamStat[TEAM_RED].Goals := gGameSettings.GoalLimit;
 
-                  if trigData.trigScoreCon then
+                  if tgcScoreCon then
                   begin
-                    if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                    if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                     begin
                       g_Console_Add(Format(_lc[I_PLAYER_SCORE_WIN_OWN], [p.Name, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                       if g_Game_IsServer and g_Game_IsNet then
@@ -1741,16 +1927,16 @@ begin
                   Result := True;
                 end;
               end;
-              if ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE)) // Blue Wins
-              or ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
+              if ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE)) // Blue Wins
+              or ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
               begin
                 if gTeamStat[TEAM_BLUE].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
                   gTeamStat[TEAM_BLUE].Goals := gGameSettings.GoalLimit;
 
-                  if trigData.trigScoreCon then
+                  if tgcScoreCon then
                   begin
-                    if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
+                    if (tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) then
                     begin
                       g_Console_Add(Format(_lc[I_PLAYER_SCORE_WIN_OWN], [p.Name, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                       if g_Game_IsServer and g_Game_IsNet then
@@ -1768,9 +1954,9 @@ begin
               end;
             end;
             // Êàêîé-òî êîíêðåòíîé êîìàíäû
-            if trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_RED, TRIGGER_SCORE_TEAM_FORCE_BLUE] then
+            if tgcScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_RED, TRIGGER_SCORE_TEAM_FORCE_BLUE] then
             begin
-              if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then // Red Wins
+              if (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then // Red Wins
               begin
                 if gTeamStat[TEAM_RED].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
@@ -1778,7 +1964,7 @@ begin
                   Result := True;
                 end;
               end;
-              if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then // Blue Wins
+              if (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then // Blue Wins
               begin
                 if gTeamStat[TEAM_BLUE].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
@@ -1789,20 +1975,20 @@ begin
             end;
           end;
           // Ïðîèãðûø
-          if (trigData.trigScoreAction = TRIGGER_SCORE_ACTION_LOOSE) and (gGameSettings.GoalLimit > 0) then
+          if (tgcScoreAction = TRIGGER_SCORE_ACTION_LOOSE) and (gGameSettings.GoalLimit > 0) then
           begin
             // Ñâîåé èëè ÷óæîé êîìàíäû
-            if (trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
+            if (tgcScoreTeam in [TRIGGER_SCORE_TEAM_MINE_RED, TRIGGER_SCORE_TEAM_MINE_BLUE]) and (g_GetUIDType(ActivateUID) = UID_PLAYER) then
             begin
               p := g_Player_Get(ActivateUID);
-              if ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE)) // Red Wins
-              or ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
+              if ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_BLUE)) // Red Wins
+              or ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_RED)) then
                 if gTeamStat[TEAM_RED].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
                   gTeamStat[TEAM_RED].Goals := gGameSettings.GoalLimit;
 
-                  if trigData.trigScoreCon then
-                    if trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED then
+                  if tgcScoreCon then
+                    if tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED then
                     begin
                       g_Console_Add(Format(_lc[I_PLAYER_SCORE_WIN_ENEMY], [p.Name, _lc[I_PLAYER_SCORE_TO_RED]]), True);
                       if g_Game_IsServer and g_Game_IsNet then
@@ -1816,14 +2002,14 @@ begin
 
                   Result := True;
                 end;
-              if ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED)) // Blue Wins
-              or ((trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
+              if ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED) and (p.Team = TEAM_RED)) // Blue Wins
+              or ((tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_BLUE) and (p.Team = TEAM_BLUE)) then
                 if gTeamStat[TEAM_BLUE].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
                   gTeamStat[TEAM_BLUE].Goals := gGameSettings.GoalLimit;
 
-                  if trigData.trigScoreCon then
-                    if trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED then
+                  if tgcScoreCon then
+                    if tgcScoreTeam = TRIGGER_SCORE_TEAM_MINE_RED then
                     begin
                       g_Console_Add(Format(_lc[I_PLAYER_SCORE_WIN_ENEMY], [p.Name, _lc[I_PLAYER_SCORE_TO_BLUE]]), True);
                       if g_Game_IsServer and g_Game_IsNet then
@@ -1839,9 +2025,9 @@ begin
                 end;
             end;
             // Êàêîé-òî êîíêðåòíîé êîìàíäû
-            if trigData.trigScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_BLUE, TRIGGER_SCORE_TEAM_FORCE_RED] then
+            if tgcScoreTeam in [TRIGGER_SCORE_TEAM_FORCE_BLUE, TRIGGER_SCORE_TEAM_FORCE_RED] then
             begin
-              if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then // Red Wins
+              if (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_BLUE) then // Red Wins
               begin
                 if gTeamStat[TEAM_RED].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
@@ -1849,7 +2035,7 @@ begin
                   Result := True;
                 end;
               end;
-              if (trigData.trigScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then // Blue Wins
+              if (tgcScoreTeam = TRIGGER_SCORE_TEAM_FORCE_RED) then // Blue Wins
               begin
                 if gTeamStat[TEAM_BLUE].Goals < SmallInt(gGameSettings.GoalLimit) then
                 begin
@@ -1871,8 +2057,8 @@ begin
 
       TRIGGER_MESSAGE:
         begin
-          Result := tr_Message(trigData.trigKind, trigData.trigText,
-                               trigData.trigMsgDest, trigData.trigMsgTime,
+          Result := tr_Message(tgcKind, tgcText,
+                               tgcMsgDest, tgcMsgTime,
                                ActivateUID);
           TimeOut := 18;
         end;
@@ -1903,7 +2089,7 @@ begin
               end else
               begin // Óæå âèäåëè åãî
                 // Åñëè èíòåðâàë îòêëþ÷¸í, íî îí âñ¸ åù¸ â çîíå ïîðàæåíèÿ, äà¸ì åìó âðåìÿ
-                if (trigData.trigInterval = 0) and (Activators[k].TimeOut > 0) then
+                if (tgcInterval = 0) and (Activators[k].TimeOut > 0) then
                   Activators[k].TimeOut := 65535;
                 // Òàéìàóò ïðîø¸ë - ðàáîòàåì
                 Result := Activators[k].TimeOut = 0;
@@ -1920,12 +2106,12 @@ begin
                       Exit;
 
                     // Íàíîñèì óðîí èãðîêó
-                    if (TriggerType = TRIGGER_DAMAGE) and (trigData.trigAmount > 0) then
-                      p.Damage(trigData.trigAmount, 0, 0, 0, HIT_SOME);
+                    if (TriggerType = TRIGGER_DAMAGE) and (tgcAmount > 0) then
+                      p.Damage(tgcAmount, 0, 0, 0, HIT_SOME);
 
                     // Ëå÷èì èãðîêà
-                    if (TriggerType = TRIGGER_HEALTH) and (trigData.trigAmount > 0) then
-                      if p.Heal(trigData.trigAmount, not trigData.trigHealMax) and (not trigData.trigSilent) then
+                    if (TriggerType = TRIGGER_HEALTH) and (tgcAmount > 0) then
+                      if p.Heal(tgcAmount, not tgcHealMax) and (not tgcSilent) then
                       begin
                         g_Sound_PlayExAt('SOUND_ITEM_GETITEM', p.Obj.X, p.Obj.Y);
                         if g_Game_IsServer and g_Game_IsNet then
@@ -1940,12 +2126,12 @@ begin
                       Exit;
 
                     // Íàíîñèì óðîí ìîíñòðó
-                    if (TriggerType = TRIGGER_DAMAGE) and (trigData.trigAmount > 0) then
-                      m.Damage(trigData.trigAmount, 0, 0, 0, HIT_SOME);
+                    if (TriggerType = TRIGGER_DAMAGE) and (tgcAmount > 0) then
+                      m.Damage(tgcAmount, 0, 0, 0, HIT_SOME);
 
                     // Ëå÷èì ìîíñòðà
-                    if (TriggerType = TRIGGER_HEALTH) and (trigData.trigAmount > 0) then
-                      if m.Heal(trigData.trigAmount) and (not trigData.trigSilent) then
+                    if (TriggerType = TRIGGER_HEALTH) and (tgcAmount > 0) then
+                      if m.Heal(tgcAmount) and (not tgcSilent) then
                       begin
                         g_Sound_PlayExAt('SOUND_ITEM_GETITEM', m.Obj.X, m.Obj.Y);
                         if g_Game_IsServer and g_Game_IsNet then
@@ -1954,7 +2140,7 @@ begin
                   end;
               end;
               // Íàçíà÷àåì âðåìÿ ñëåäóþùåãî âîçäåéñòâèÿ
-              idx := trigData.trigInterval;
+              idx := tgcInterval;
               if coolDown then
                 if idx > 0 then
                   Activators[k].TimeOut := idx
@@ -1971,16 +2157,16 @@ begin
             Exit;
 
           // put this at the beginning so it doesn't trigger itself
-          TimeOut := trigData.trigWait + 1;
+          TimeOut := tgcWait + 1;
 
-          wx := trigData.trigTX;
-          wy := trigData.trigTY;
-          pAngle := -DegToRad(trigData.trigAngle);
+          wx := tgcTX;
+          wy := tgcTY;
+          pAngle := -DegToRad(tgcAngle);
           xd := wx + Round(Cos(pAngle) * 32.0);
           yd := wy + Round(Sin(pAngle) * 32.0);
           TargetUID := 0;
 
-          case trigData.trigShotTarget of
+          case tgcShotTarget of
             TRIGGER_SHOT_TARGET_MON: // monsters
               //TODO: accelerate this!
               g_Mons_ForEachAlive(monsShotTarget);
@@ -2060,25 +2246,25 @@ begin
             end;
 
             else begin
-              if (trigData.trigShotTarget <> TRIGGER_SHOT_TARGET_NONE) or
-                 (trigData.trigShotType <> TRIGGER_SHOT_REV) then
+              if (tgcShotTarget <> TRIGGER_SHOT_TARGET_NONE) or
+                 (tgcShotType <> TRIGGER_SHOT_REV) then
                 TargetUID := ActivateUID;
             end;
           end;
 
-          if (trigData.trigShotTarget = TRIGGER_SHOT_TARGET_NONE) or (TargetUID > 0) or
-            ((trigData.trigShotTarget > TRIGGER_SHOT_TARGET_NONE) and (TargetUID = 0)) then
+          if (tgcShotTarget = TRIGGER_SHOT_TARGET_NONE) or (TargetUID > 0) or
+            ((tgcShotTarget > TRIGGER_SHOT_TARGET_NONE) and (TargetUID = 0)) then
           begin
             Result := True;
-            if (trigData.trigSight = 0) or
-               (trigData.trigShotTarget = TRIGGER_SHOT_TARGET_NONE) or
+            if (tgcSight = 0) or
+               (tgcShotTarget = TRIGGER_SHOT_TARGET_NONE) or
                (TargetUID = ShotSightTarget) then
               MakeShot(Trigger, wx, wy, xd, yd, TargetUID)
             else
             begin
-              ShotSightTime := trigData.trigSight;
+              ShotSightTime := tgcSight;
               ShotSightTargetN := TargetUID;
-              if trigData.trigShotType = TRIGGER_SHOT_BFG then
+              if tgcShotType = TRIGGER_SHOT_BFG then
               begin
                 g_Sound_PlayExAt('SOUND_WEAPON_STARTFIREBFG', wx, wy);
                 if g_Game_IsNet and g_Game_IsServer then
@@ -2090,11 +2276,11 @@ begin
 
       TRIGGER_EFFECT:
         begin
-          idx := trigData.trigFXCount;
+          idx := tgcFXCount;
 
           while idx > 0 do
           begin
-            case trigData.trigFXPos of
+            case tgcFXPos of
               TRIGGER_EFFECT_POS_CENTER:
               begin
                 wx := X + Width div 2;
@@ -2110,72 +2296,69 @@ begin
                 wy := Y + Height div 2;
               end;
             end;
-            xd := trigData.trigVelX;
-            yd := trigData.trigVelY;
-            if trigData.trigSpreadL > 0 then xd -= Random(trigData.trigSpreadL+1);
-            if trigData.trigSpreadR > 0 then xd += Random(trigData.trigSpreadR+1);
-            if trigData.trigSpreadU > 0 then yd -= Random(trigData.trigSpreadU+1);
-            if trigData.trigSpreadD > 0 then yd += Random(trigData.trigSpreadD+1);
+            xd := tgcVelX;
+            yd := tgcVelY;
+            if tgcSpreadL > 0 then xd -= Random(tgcSpreadL+1);
+            if tgcSpreadR > 0 then xd += Random(tgcSpreadR+1);
+            if tgcSpreadU > 0 then yd -= Random(tgcSpreadU+1);
+            if tgcSpreadD > 0 then yd += Random(tgcSpreadD+1);
             tr_MakeEffect(wx, wy, xd, yd,
-                       trigData.trigFXType, trigData.trigFXSubType,
-                       trigData.trigFXRed, trigData.trigFXGreen, trigData.trigFXBlue, True, False);
+                       tgcFXType, tgcFXSubType,
+                       tgcFXRed, tgcFXGreen, tgcFXBlue, True, False);
             Dec(idx);
           end;
-          TimeOut := trigData.trigWait;
+          TimeOut := tgcWait;
+          result := true;
         end;
     end;
   end;
 
   if Result {and (Trigger.TexturePanel <> -1)} then
   begin
-    g_Map_SwitchTextureGUID(Trigger.TexturePanelType, Trigger.TexturePanelGUID, IfThen(animonce, 2, 1));
+    g_Map_SwitchTextureGUID({Trigger.TexturePanelType,} Trigger.TexturePanelGUID, IfThen(animonce, 2, 1));
   end;
 end;
 
 
-function g_Triggers_CreateWithMapIndex (Trigger: TTrigger; arridx, mapidx: Integer): DWORD;
+function g_Triggers_CreateWithMapIndex (aTrigger: TTrigger; arridx, mapidx: Integer): DWORD;
 var
   triggers: TDynField;
 begin
   triggers := gCurrentMap['trigger'];
   if (triggers = nil) then raise Exception.Create('LOAD: map has no triggers');
   if (mapidx < 0) or (mapidx >= triggers.count) then raise Exception.Create('LOAD: invalid map trigger index');
-  Trigger.trigData := triggers.itemAt[mapidx];
-  if (Trigger.trigData = nil) then raise Exception.Create('LOAD: internal error in trigger loader');
-  Trigger.mapId := Trigger.trigData.id;
-  Trigger.mapIndex := mapidx;
-  if (Trigger.trigData.trigRec <> nil) then
-  begin
-    Trigger.trigData := Trigger.trigData.trigRec.clone({Trigger.trigData.headerRec}nil);
-  end
-  else
-  begin
-    Trigger.trigData := nil;
-  end;
-  result := g_Triggers_Create(Trigger, arridx);
+  aTrigger.mapIndex := mapidx;
+  result := g_Triggers_Create(aTrigger, triggers.itemAt[mapidx], arridx);
 end;
 
 
-function g_Triggers_Create(Trigger: TTrigger; forceInternalIndex: Integer=-1): DWORD;
+function g_Triggers_Create (aTrigger: TTrigger; trec: TDynRecord; forceInternalIndex: Integer=-1): DWORD;
 var
   find_id: DWORD;
   fn, mapw: AnsiString;
   f, olen: Integer;
+  ptg: PTrigger;
 begin
-// Íå ñîçäàâàòü âûõîä, åñëè èãðà áåç âûõîäà:
-  if (Trigger.TriggerType = TRIGGER_EXIT) and
+  if (tgscope = nil) then tgscope := TTrigScope.Create();
+  if (tgclist = nil) then tgclist := TMyConstList.Create();
+
+  // Íå ñîçäàâàòü âûõîä, åñëè èãðà áåç âûõîäà
+  if (aTrigger.TriggerType = TRIGGER_EXIT) and
      (not LongBool(gGameSettings.Options and GAME_OPTION_ALLOWEXIT)) then
-    Trigger.TriggerType := TRIGGER_NONE;
+  begin
+    aTrigger.TriggerType := TRIGGER_NONE;
+  end;
 
-// Åñëè ìîíñòðû çàïðåùåíû, îòìåíÿåì òðèããåð:
-  if (Trigger.TriggerType = TRIGGER_SPAWNMONSTER) and
+  // Åñëè ìîíñòðû çàïðåùåíû, îòìåíÿåì òðèããåð
+  if (aTrigger.TriggerType = TRIGGER_SPAWNMONSTER) and
      (not LongBool(gGameSettings.Options and GAME_OPTION_MONSTERS)) and
      (gGameSettings.GameType <> GT_SINGLE) then
-    Trigger.TriggerType := TRIGGER_NONE;
+  begin
+    aTrigger.TriggerType := TRIGGER_NONE;
+  end;
 
-// Ñ÷èòàåì êîëè÷åñòâî ñåêðåòîâ íà êàðòå:
-  if Trigger.TriggerType = TRIGGER_SECRET then
-    gSecretsCount := gSecretsCount + 1;
+  // Ñ÷èòàåì êîëè÷åñòâî ñåêðåòîâ íà êàðòå
+  if (aTrigger.TriggerType = TRIGGER_SECRET) then gSecretsCount += 1;
 
   if (forceInternalIndex < 0) then
   begin
@@ -2187,39 +2370,62 @@ begin
     if (forceInternalIndex >= olen) then
     begin
       SetLength(gTriggers, forceInternalIndex+1);
-      for f := olen to High(gTriggers) do gTriggers[f].TriggerType := TRIGGER_NONE;
+      for f := olen to High(gTriggers) do
+      begin
+        gTriggers[f].TriggerType := TRIGGER_NONE;
+        gTriggers[f].trigDataRec := nil;
+        gTriggers[f].exoInit := nil;
+        gTriggers[f].exoThink := nil;
+        gTriggers[f].exoCheck := nil;
+        gTriggers[f].exoAction := nil;
+        gTriggers[f].userVars := nil;
+      end;
     end;
+    f := forceInternalIndex;
+    gTriggers[f].trigDataRec.Free();
+    gTriggers[f].exoInit.Free();
+    gTriggers[f].exoThink.Free();
+    gTriggers[f].exoCheck.Free();
+    gTriggers[f].exoAction.Free();
+    gTriggers[f].userVars.Free();
+    gTriggers[f].trigDataRec := nil;
+    gTriggers[f].exoInit := nil;
+    gTriggers[f].exoThink := nil;
+    gTriggers[f].exoCheck := nil;
+    gTriggers[f].exoAction := nil;
+    gTriggers[f].userVars := nil;
     find_id := DWORD(forceInternalIndex);
   end;
-  gTriggers[find_id] := Trigger;
-
-  //e_LogWritefln('created trigger with map index %s, findid=%s (%s)', [Trigger.mapIndex, find_id, Trigger.mapId]);
+  gTriggers[find_id] := aTrigger;
+  ptg := @gTriggers[find_id];
 
-  {
-  writeln('trigger #', find_id, ': pos=(', Trigger.x, ',', Trigger.y, ')-(', Trigger.width, 'x', Trigger.height, ')',
-    '; TexturePanel=', Trigger.TexturePanel,
-    '; TexturePanelType=', Trigger.TexturePanelType,
-    '; ShotPanelType=', Trigger.ShotPanelType,
-    '; TriggerType=', Trigger.TriggerType,
-    '; ActivateType=', Trigger.ActivateType,
-    '; Keys=', Trigger.Keys,
-    '; trigPanelId=', Trigger.trigPanelId,
-    '; trigShotPanelId=', Trigger.trigShotPanelId
-    );
-  }
+  ptg.mapId := trec.id;
+  // clone trigger data
+  if (trec.trigRec = nil) then
+  begin
+    ptg.trigDataRec := nil;
+    //HACK!
+    if (ptg.TriggerType <> TRIGGER_SECRET) then
+    begin
+      e_LogWritefln('trigger of type %s has no triggerdata; wtf?!', [ptg.TriggerType], TMsgType.Warning);
+    end;
+  end
+  else
+  begin
+    ptg.trigDataRec := trec.trigRec.clone(nil);
+  end;
 
-  with gTriggers[find_id] do
+  with ptg^ do
   begin
     ID := find_id;
     // if this type of trigger exists both on the client and on the server
     // use an uniform numeration
-    if Trigger.TriggerType = TRIGGER_SOUND then
+    ClientID := 0;
+    if (ptg.TriggerType = TRIGGER_SOUND) then
     begin
       Inc(gTriggerClientID);
       ClientID := gTriggerClientID;
-    end
-    else
-      ClientID := 0;
+    end;
     TimeOut := 0;
     ActivateUID := 0;
     PlayerCollide := False;
@@ -2233,32 +2439,99 @@ begin
     SpawnedCount := 0;
   end;
 
-// Çàãðóæàåì çâóê, åñëè ýòî òðèããåð "Çâóê":
-  if (Trigger.TriggerType = TRIGGER_SOUND) and
-     (Trigger.trigData.trigSoundName <> '') then
+  // update cached trigger variables
+  trigUpdateCacheData(ptg^, ptg.trigDataRec);
+
+  ptg.userVars := nil;
+
+  try
+    ptg.exoThink := TExprBase.parseStatList(tgclist, VarToStr(trec.user['exoma_think']));
+  except
+    on e: TExomaParseException do
+      begin
+        conwritefln('*** ERROR parsing exoma_think (%s,%s): %s [%s]', [e.tokLine, e.tokCol, e.message, VarToStr(trec.user['exoma_think'])]);
+        ptg.exoThink := nil;
+      end;
+    else
+      raise;
+  end;
+  try
+    ptg.exoCheck := TExprBase.parse(tgclist, VarToStr(trec.user['exoma_check']));
+  except
+    on e: TExomaParseException do
+      begin
+        conwritefln('*** ERROR parsing exoma_check (%s,%s): %s [%s]', [e.tokLine, e.tokCol, e.message, VarToStr(trec.user['exoma_check'])]);
+        ptg.exoCheck := nil;
+      end;
+    else
+      raise;
+  end;
+  try
+    ptg.exoAction := TExprBase.parseStatList(tgclist, VarToStr(trec.user['exoma_action']));
+  except
+    on e: TExomaParseException do
+      begin
+        conwritefln('*** ERROR parsing exoma_action (%s,%s): %s [%s]', [e.tokLine, e.tokCol, e.message, VarToStr(trec.user['exoma_action'])]);
+        ptg.exoAction := nil;
+      end;
+    else
+      raise;
+  end;
+  try
+    ptg.exoInit := TExprBase.parseStatList(tgclist, VarToStr(trec.user['exoma_init']));
+  except
+    on e: TExomaParseException do
+      begin
+        conwritefln('*** ERROR parsing exoma_init (%s,%s): %s [%s]', [e.tokLine, e.tokCol, e.message, VarToStr(trec.user['exoma_init'])]);
+        ptg.exoInit := nil;
+      end;
+    else
+      raise;
+  end;
+
+  if (forceInternalIndex < 0) and (ptg.exoInit <> nil) then
   begin
-  // Åùå íåò òàêîãî çâóêà:
-    if not g_Sound_Exists(Trigger.trigData.trigSoundName) then
-    begin
-      fn := g_ExtractWadName(Trigger.trigData.trigSoundName);
+    //conwritefln('executing trigger init: [%s]', [gTriggers[find_id].exoInit.toString()]);
+    try
+      tgscope.me := ptg;
+      ptg.exoInit.value(tgscope);
+      tgscope.me := nil;
+    except
+      tgscope.me := nil;
+      conwritefln('*** trigger exoactivate error: %s', [ptg.exoInit.toString()]);
+      exit;
+    end;
+  end;
 
-      if fn = '' then
-        begin // Çâóê â ôàéëå ñ êàðòîé
-          mapw := g_ExtractWadName(gMapInfo.Map);
-          fn := mapw+':'+g_ExtractFilePathName(Trigger.trigData.trigSoundName);
-        end
+  // Çàãðóæàåì çâóê, åñëè ýòî òðèããåð "Çâóê"
+  if (ptg.TriggerType = TRIGGER_SOUND) and (ptg.tgcSoundName <> '') then
+  begin
+    // Åùå íåò òàêîãî çâóêà
+    if not g_Sound_Exists(ptg.tgcSoundName) then
+    begin
+      fn := g_ExtractWadName(ptg.tgcSoundName);
+      if (fn = '') then
+      begin // Çâóê â ôàéëå ñ êàðòîé
+        mapw := g_ExtractWadName(gMapInfo.Map);
+        fn := mapw+':'+g_ExtractFilePathName(ptg.tgcSoundName);
+      end
       else // Çâóê â îòäåëüíîì ôàéëå
-        fn := GameDir + '/wads/' + Trigger.trigData.trigSoundName;
+      begin
+        fn := GameDir + '/wads/' + ptg.tgcSoundName;
+      end;
 
-      if not g_Sound_CreateWADEx(Trigger.trigData.trigSoundName, fn) then
-        g_FatalError(Format(_lc[I_GAME_ERROR_TR_SOUND], [fn, Trigger.trigData.trigSoundName]));
+      //e_LogWritefln('loading trigger sound ''%s''', [fn]);
+      if not g_Sound_CreateWADEx(ptg.tgcSoundName, fn) then
+      begin
+        g_FatalError(Format(_lc[I_GAME_ERROR_TR_SOUND], [fn, ptg.tgcSoundName]));
+      end;
     end;
 
-  // Ñîçäàåì îáúåêò çâóêà:
-    with gTriggers[find_id] do
+    // Ñîçäàåì îáúåêò çâóêà
+    with ptg^ do
     begin
       Sound := TPlayableSound.Create();
-      if not Sound.SetByName(Trigger.trigData.trigSoundName) then
+      if not Sound.SetByName(ptg.tgcSoundName) then
       begin
         Sound.Free();
         Sound := nil;
@@ -2266,40 +2539,45 @@ begin
     end;
   end;
 
-// Çàãðóæàåì ìóçûêó, åñëè ýòî òðèããåð "Ìóçûêà":
-  if (Trigger.TriggerType = TRIGGER_MUSIC) and
-     (Trigger.trigData.trigMusicName <> '') then
+  // Çàãðóæàåì ìóçûêó, åñëè ýòî òðèããåð "Ìóçûêà"
+  if (ptg.TriggerType = TRIGGER_MUSIC) and (ptg.tgcMusicName <> '') then
   begin
-  // Åùå íåò òàêîé ìóçûêè:
-    if not g_Sound_Exists(Trigger.trigData.trigMusicName) then
+    // Åùå íåò òàêîé ìóçûêè
+    if not g_Sound_Exists(ptg.tgcMusicName) then
     begin
-      fn := g_ExtractWadName(Trigger.trigData.trigMusicName);
+      fn := g_ExtractWadName(ptg.tgcMusicName);
 
       if fn = '' then
-        begin // Ìóçûêà â ôàéëå ñ êàðòîé
-          mapw := g_ExtractWadName(gMapInfo.Map);
-          fn := mapw+':'+g_ExtractFilePathName(Trigger.trigData.trigMusicName);
-        end
+      begin // Ìóçûêà â ôàéëå ñ êàðòîé
+        mapw := g_ExtractWadName(gMapInfo.Map);
+        fn := mapw+':'+g_ExtractFilePathName(ptg.tgcMusicName);
+      end
       else // Ìóçûêà â ôàéëå ñ êàðòîé
-        fn := GameDir+'/wads/'+Trigger.trigData.trigMusicName;
+      begin
+        fn := GameDir+'/wads/'+ptg.tgcMusicName;
+      end;
 
-      if not g_Sound_CreateWADEx(Trigger.trigData.trigMusicName, fn, True) then
-        g_FatalError(Format(_lc[I_GAME_ERROR_TR_SOUND], [fn, Trigger.trigData.trigMusicName]));
+      if not g_Sound_CreateWADEx(ptg.tgcMusicName, fn, True) then
+      begin
+        g_FatalError(Format(_lc[I_GAME_ERROR_TR_SOUND], [fn, ptg.tgcMusicName]));
+      end;
     end;
   end;
 
-// Çàãðóæàåì äàííûå òðèããåðà "Òóðåëü":
-  if Trigger.TriggerType = TRIGGER_SHOT then
-    with gTriggers[find_id] do
+  // Çàãðóæàåì äàííûå òðèããåðà "Òóðåëü"
+  if (ptg.TriggerType = TRIGGER_SHOT) then
+  begin
+    with ptg^ do
     begin
       ShotPanelTime := 0;
       ShotSightTime := 0;
       ShotSightTimeout := 0;
       ShotSightTarget := 0;
       ShotSightTargetN := 0;
-      ShotAmmoCount := Trigger.trigData.trigAmmo;
+      ShotAmmoCount := ptg.tgcAmmo;
       ShotReloadTime := 0;
     end;
+  end;
 
   Result := find_id;
 end;
@@ -2361,7 +2639,7 @@ begin
               continue;
             end;
             // Ñ÷èòàåì, ÷òî îáúåêò ïîêèíóë çîíó äåéñòâèÿ òðèããåðà
-            if (trigData.trigInterval = 0) and (Activators[b].TimeOut < 65530) then Activators[b].TimeOut := 0;
+            if (tgcInterval = 0) and (Activators[b].TimeOut < 65530) then Activators[b].TimeOut := 0;
           end;
         end;
 
@@ -2371,13 +2649,13 @@ begin
           if SpawnCooldown = 0 then
           begin
             // Åñëè ïðèøëî âðåìÿ, ñïàâíèì ìîíñòðà
-            if (TriggerType = TRIGGER_SPAWNMONSTER) and (trigData.trigDelay > 0)  then
+            if (TriggerType = TRIGGER_SPAWNMONSTER) and (tgcDelay > 0)  then
             begin
               ActivateUID := 0;
               ActivateTrigger(gTriggers[a], ACTIVATE_CUSTOM);
             end;
             // Åñëè ïðèøëî âðåìÿ, ñïàâíèì ïðåäìåò
-            if (TriggerType = TRIGGER_SPAWNITEM) and (trigData.trigDelay > 0) then
+            if (TriggerType = TRIGGER_SPAWNITEM) and (tgcDelay > 0) then
             begin
               ActivateUID := 0;
               ActivateTrigger(gTriggers[a], ACTIVATE_CUSTOM);
@@ -2396,7 +2674,7 @@ begin
           if ShotPanelTime > 0 then
           begin
             Dec(ShotPanelTime);
-            if ShotPanelTime = 0 then g_Map_SwitchTextureGUID(ShotPanelType, trigShotPanelGUID);
+            if ShotPanelTime = 0 then g_Map_SwitchTextureGUID({ShotPanelType,} trigPanelGUID);
           end;
           if ShotSightTime > 0 then
           begin
@@ -2411,7 +2689,7 @@ begin
           if ShotReloadTime > 0 then
           begin
             Dec(ShotReloadTime);
-            if ShotReloadTime = 0 then ShotAmmoCount := trigData.trigAmmo;
+            if ShotReloadTime = 0 then ShotAmmoCount := tgcAmmo;
           end;
         end;
 
@@ -2420,14 +2698,14 @@ begin
         begin
           if (SoundPlayCount > 0) and (not Sound.IsPlaying()) then
           begin
-            if trigData.trigPlayCount > 0 then SoundPlayCount -= 1; // Åñëè 0 - èãðàåì çâóê áåñêîíå÷íî
-            if trigData.trigLocal then
+            if tgcPlayCount > 0 then SoundPlayCount -= 1; // Åñëè 0 - èãðàåì çâóê áåñêîíå÷íî
+            if tgcLocal then
             begin
-              Sound.PlayVolumeAt(X+(Width div 2), Y+(Height div 2), trigData.trigVolume/255.0);
+              Sound.PlayVolumeAt(X+(Width div 2), Y+(Height div 2), tgcVolume/255.0);
             end
             else
             begin
-              Sound.PlayPanVolume((trigData.trigPan-127.0)/128.0, trigData.trigVolume/255.0);
+              Sound.PlayPanVolume((tgcPan-127.0)/128.0, tgcVolume/255.0);
             end;
             if Sound.IsPlaying() and g_Game_IsNet and g_Game_IsServer then MH_SEND_TriggerSound(gTriggers[a]);
           end;
@@ -2436,7 +2714,7 @@ begin
         // Òðèããåð "Ëîâóøêà" - ïîðà îòêðûâàòü
         if (TriggerType = TRIGGER_TRAP) and (DoorTime = 0) and (g_Map_PanelByGUID(trigPanelGUID) <> nil) then
         begin
-          tr_OpenDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d);
+          tr_OpenDoor(trigPanelGUID, tgcSilent, tgcD2d);
           DoorTime := -1;
         end;
 
@@ -2454,28 +2732,28 @@ begin
             else
             begin
               // Ïîêà îòêðûòà - çàêðûâàåì
-              if tr_CloseDoor(trigPanelGUID, trigData.trigSilent, trigData.trigD2d) then DoorTime := -1;
+              if tr_CloseDoor(trigPanelGUID, tgcSilent, tgcD2d) then DoorTime := -1;
             end;
           end;
         end;
 
       // Òðèããåð - ðàñøèðèòåëü èëè ïåðåêëþ÷àòåëü, è ïðîøëà çàäåðæêà, è íàæàëè íóæíîå ÷èñëî ðàç:
         if (TriggerType in [TRIGGER_PRESS, TRIGGER_ON, TRIGGER_OFF, TRIGGER_ONOFF]) and
-           (PressTime = 0) and (PressCount >= trigData.trigPressCount) then
+           (PressTime = 0) and (PressCount >= tgcPressCount) then
         begin
           // Ñáðàñûâàåì çàäåðæêó àêòèâàöèè:
           PressTime := -1;
           // Ñáðàñûâàåì ñ÷åò÷èê íàæàòèé:
-          if trigData.trigPressCount > 0 then PressCount -= trigData.trigPressCount else PressCount := 0;
+          if tgcPressCount > 0 then PressCount -= tgcPressCount else PressCount := 0;
 
           // Îïðåäåëÿåì èçìåíÿåìûå èì òðèããåðû:
           for b := 0 to High(gTriggers) do
           begin
-            if g_Collide(trigData.trigtX, trigData.trigtY, trigData.trigtWidth, trigData.trigtHeight, gTriggers[b].X, gTriggers[b].Y,
+            if g_Collide(tgcTX, tgcTY, tgcTWidth, tgcTHeight, gTriggers[b].X, gTriggers[b].Y,
                gTriggers[b].Width, gTriggers[b].Height) and
-               ((b <> a) or (trigData.trigWait > 0)) then
+               ((b <> a) or (tgcWait > 0)) then
             begin // Can be self-activated, if there is Data.Wait
-              if (not trigData.trigExtRandom) or gTriggers[b].Enabled then
+              if (not tgcExtRandom) or gTriggers[b].Enabled then
               begin
                 SetLength(Affected, Length(Affected) + 1);
                 Affected[High(Affected)] := b;
@@ -2494,15 +2772,15 @@ begin
               TRIGGER_OFF: pan.movingActive := false;
               TRIGGER_ONOFF: pan.movingActive := not pan.movingActive;
             end;
-            if not trigData.trigSilent and (Length(trigData.trigSound) > 0) then
+            if not tgcSilent and (Length(tgcSound) > 0) then
             begin
-              g_Sound_PlayExAt(trigData.trigSound, X, Y);
-              if g_Game_IsServer and g_Game_IsNet then MH_SEND_Sound(X, Y, trigData.trigSound);
+              g_Sound_PlayExAt(tgcSound, X, Y);
+              if g_Game_IsServer and g_Game_IsNet then MH_SEND_Sound(X, Y, tgcSound);
             end;
           end;
 
           // Âûáèðàåì îäèí èç òðèããåðîâ äëÿ ðàñøèðèòåëÿ, åñëè âêëþ÷åí ðàíäîì:
-          if (TriggerType = TRIGGER_PRESS) and trigData.trigExtRandom then
+          if (TriggerType = TRIGGER_PRESS) and tgcExtRandom then
           begin
             if (Length(Affected) > 0) then
             begin
@@ -2777,7 +3055,7 @@ begin
          (TriggerType = TRIGGER_DOOR5) or
          (TriggerType = TRIGGER_DOOR) then
       begin
-        tr_OpenDoor(trigPanelGUID, True, trigData.trigD2d);
+        tr_OpenDoor(trigPanelGUID, True, tgcD2d);
         if TriggerType = TRIGGER_DOOR5 then DoorTime := 180;
         b := True;
       end;
@@ -2790,11 +3068,21 @@ end;
 procedure g_Triggers_DecreaseSpawner(ID: DWORD);
 begin
   if (gTriggers <> nil) then
-    if gTriggers[ID].SpawnedCount > 0 then
-      Dec(gTriggers[ID].SpawnedCount);
+  begin
+    if gTriggers[ID].tgcMax > 0 then
+    begin
+      if gTriggers[ID].SpawnedCount > 0 then
+        Dec(gTriggers[ID].SpawnedCount);
+    end;
+    if gTriggers[ID].tgcDelay > 0 then
+    begin
+      if gTriggers[ID].SpawnCooldown < 0 then
+        gTriggers[ID].SpawnCooldown := gTriggers[ID].tgcDelay;
+    end;
+  end;
 end;
 
-procedure g_Triggers_Free();
+procedure g_Triggers_Free ();
 var
   a: Integer;
 begin
@@ -2802,9 +3090,9 @@ begin
   begin
     if (gTriggers[a].TriggerType = TRIGGER_SOUND) then
     begin
-      if g_Sound_Exists(gTriggers[a].trigData.trigSoundName) then
+      if g_Sound_Exists(gTriggers[a].tgcSoundName) then
       begin
-        g_Sound_Delete(gTriggers[a].trigData.trigSoundName);
+        g_Sound_Delete(gTriggers[a].tgcSoundName);
       end;
       gTriggers[a].Sound.Free();
     end;
@@ -2812,7 +3100,12 @@ begin
     begin
       SetLength(gTriggers[a].Activators, 0);
     end;
-    gTriggers[a].trigData.Free();
+    gTriggers[a].trigDataRec.Free();
+
+    gTriggers[a].exoThink.Free();
+    gTriggers[a].exoCheck.Free();
+    gTriggers[a].exoAction.Free();
+    gTriggers[a].userVars.Free();
   end;
 
   gTriggers := nil;
@@ -2820,235 +3113,268 @@ begin
   SetLength(gMonstersSpawned, 0);
 end;
 
-procedure g_Triggers_SaveState(var Mem: TBinMemoryWriter);
+
+procedure g_Triggers_SaveState (st: TStream);
 var
-  count, act_count, i, j: Integer;
-  dw: DWORD;
+  count, actCount, i, j: Integer;
   sg: Single;
   b: Boolean;
+  kv: THashStrVariant.PEntry;
+  t: LongInt;
 begin
   // Ñ÷èòàåì êîëè÷åñòâî ñóùåñòâóþùèõ òðèããåðîâ
   count := Length(gTriggers);
 
-  Mem := TBinMemoryWriter.Create((count+1) * 200);
-
-  // Êîëè÷åñòâî òðèããåðîâ:
-  Mem.WriteInt(count);
-
-  //e_LogWritefln('saving %s triggers (count=%s)', [Length(gTriggers), count]);
-
-  if count = 0 then exit;
+  // Êîëè÷åñòâî òðèããåðîâ
+  utils.writeInt(st, LongInt(count));
+  if (count = 0) then exit;
 
   for i := 0 to High(gTriggers) do
   begin
-  // Ñèãíàòóðà òðèããåðà:
-    dw := TRIGGER_SIGNATURE; // 'TRGX'
-    Mem.WriteDWORD(dw);
-  // Òèï òðèããåðà:
-    Mem.WriteByte(gTriggers[i].TriggerType);
+    // Ñèãíàòóðà òðèããåðà
+    utils.writeSign(st, 'TRGX');
+    utils.writeInt(st, Byte(0));
+    // Òèï òðèããåðà
+    utils.writeInt(st, Byte(gTriggers[i].TriggerType));
     if (gTriggers[i].TriggerType = TRIGGER_NONE) then continue; // empty one
-  // Ñïåöèàëüíûå äàííûå òðèããåðà: äà â æîïó, ïîòîì èç êàðòû îïÿòü âûòàùèì; ñîõðàíèì òîëüêî èíäåêñ
-    //e_LogWritefln('=== trigger #%s saved ===', [gTriggers[i].mapIndex]);
-    Mem.WriteInt(gTriggers[i].mapIndex);
-    //p := @gTriggers[i].Data;
-    //Mem.WriteMemory(p, SizeOf(TTriggerData));
-  // Êîîðäèíàòû ëåâîãî âåðõíåãî óãëà:
-    Mem.WriteInt(gTriggers[i].X);
-    Mem.WriteInt(gTriggers[i].Y);
-  // Ðàçìåðû:
-    Mem.WriteWord(gTriggers[i].Width);
-    Mem.WriteWord(gTriggers[i].Height);
-  // Âêëþ÷åí ëè òðèããåð:
-    Mem.WriteBoolean(gTriggers[i].Enabled);
-  // Òèï àêòèâàöèè òðèããåðà:
-    Mem.WriteByte(gTriggers[i].ActivateType);
-  // Êëþ÷è, íåîáõîäèìûå äëÿ àêòèâàöèè:
-    Mem.WriteByte(gTriggers[i].Keys);
-  // ID ïàíåëè, òåêñòóðà êîòîðîé èçìåíèòñÿ:
-    Mem.WriteInt(gTriggers[i].TexturePanelGUID);
-  // Òèï ýòîé ïàíåëè:
-    Mem.WriteWord(gTriggers[i].TexturePanelType);
-  // Âíóòðåííèé íîìåð äðóãîé ïàíåëè (ïî ñ÷àñòëèâîé ñëó÷àéíîñòè îí áóäåò ñîâïàäàòü ñ òåì, ÷òî ñîçäàíî ïðè çàãðóçêå êàðòû)
-    Mem.WriteInt(gTriggers[i].trigPanelGUID);
-  // Âðåìÿ äî âîçìîæíîñòè àêòèâàöèè:
-    Mem.WriteWord(gTriggers[i].TimeOut);
-  // UID òîãî, êòî àêòèâèðîâàë ýòîò òðèããåð:
-    Mem.WriteWord(gTriggers[i].ActivateUID);
-  // Ñïèñîê UID-îâ îáúåêòîâ, êîòîðûå íàõîäèëèñü ïîä âîçäåéñòâèåì:
-    act_count := Length(gTriggers[i].Activators);
-    Mem.WriteInt(act_count);
-    for j := 0 to act_count-1 do
+    // Ñïåöèàëüíûå äàííûå òðèããåðà: ïîòîì èç êàðòû îïÿòü âûòàùèì; ñîõðàíèì òîëüêî èíäåêñ
+    utils.writeInt(st, LongInt(gTriggers[i].mapIndex));
+    // Êîîðäèíàòû ëåâîãî âåðõíåãî óãëà
+    utils.writeInt(st, LongInt(gTriggers[i].X));
+    utils.writeInt(st, LongInt(gTriggers[i].Y));
+    // Ðàçìåðû
+    utils.writeInt(st, Word(gTriggers[i].Width));
+    utils.writeInt(st, Word(gTriggers[i].Height));
+    // Âêëþ÷åí ëè òðèããåð
+    utils.writeBool(st, gTriggers[i].Enabled);
+    // Òèï àêòèâàöèè òðèããåðà
+    utils.writeInt(st, Byte(gTriggers[i].ActivateType));
+    // Êëþ÷è, íåîáõîäèìûå äëÿ àêòèâàöèè
+    utils.writeInt(st, Byte(gTriggers[i].Keys));
+    // ID ïàíåëè, òåêñòóðà êîòîðîé èçìåíèòñÿ
+    utils.writeInt(st, LongInt(gTriggers[i].TexturePanelGUID));
+    // Òèï ýòîé ïàíåëè
+    //Mem.WriteWord(gTriggers[i].TexturePanelType);
+    // Âíóòðåííèé íîìåð äðóãîé ïàíåëè (ïî ñ÷àñòëèâîé ñëó÷àéíîñòè îí áóäåò ñîâïàäàòü ñ òåì, ÷òî ñîçäàíî ïðè çàãðóçêå êàðòû)
+    utils.writeInt(st, LongInt(gTriggers[i].trigPanelGUID));
+    // Âðåìÿ äî âîçìîæíîñòè àêòèâàöèè
+    utils.writeInt(st, Word(gTriggers[i].TimeOut));
+    // UID òîãî, êòî àêòèâèðîâàë ýòîò òðèããåð
+    utils.writeInt(st, Word(gTriggers[i].ActivateUID));
+    // Ñïèñîê UID-îâ îáúåêòîâ, êîòîðûå íàõîäèëèñü ïîä âîçäåéñòâèåì
+    actCount := Length(gTriggers[i].Activators);
+    utils.writeInt(st, LongInt(actCount));
+    for j := 0 to actCount-1 do
     begin
       // UID îáúåêòà
-      Mem.WriteWord(gTriggers[i].Activators[j].UID);
+      utils.writeInt(st, Word(gTriggers[i].Activators[j].UID));
       // Âðåìÿ îæèäàíèÿ
-      Mem.WriteWord(gTriggers[i].Activators[j].TimeOut);
+      utils.writeInt(st, Word(gTriggers[i].Activators[j].TimeOut));
     end;
-  // Ñòîèò ëè èãðîê â îáëàñòè òðèããåðà:
-    Mem.WriteBoolean(gTriggers[i].PlayerCollide);
-  // Âðåìÿ äî çàêðûòèÿ äâåðè:
-    Mem.WriteInt(gTriggers[i].DoorTime);
-  // Çàäåðæêà àêòèâàöèè:
-    Mem.WriteInt(gTriggers[i].PressTime);
-  // Ñ÷åò÷èê íàæàòèé:
-    Mem.WriteInt(gTriggers[i].PressCount);
-  // Ñïàâíåð àêòèâåí:
-    Mem.WriteBoolean(gTriggers[i].AutoSpawn);
-  // Çàäåðæêà ñïàâíåðà:
-    Mem.WriteInt(gTriggers[i].SpawnCooldown);
-  // Ñ÷åò÷èê ñîçäàíèÿ îáúåêòîâ:
-    Mem.WriteInt(gTriggers[i].SpawnedCount);
-  // Ñêîëüêî ðàç ïðîèãðàí çâóê:
-    Mem.WriteInt(gTriggers[i].SoundPlayCount);
-  // Ïðîèãðûâàåòñÿ ëè çâóê?
-    if gTriggers[i].Sound <> nil then
-      b := gTriggers[i].Sound.IsPlaying()
-    else
-      b := False;
-    Mem.WriteBoolean(b);
+    // Ñòîèò ëè èãðîê â îáëàñòè òðèããåðà
+    utils.writeBool(st, gTriggers[i].PlayerCollide);
+    // Âðåìÿ äî çàêðûòèÿ äâåðè
+    utils.writeInt(st, LongInt(gTriggers[i].DoorTime));
+    // Çàäåðæêà àêòèâàöèè
+    utils.writeInt(st, LongInt(gTriggers[i].PressTime));
+    // Ñ÷åò÷èê íàæàòèé
+    utils.writeInt(st, LongInt(gTriggers[i].PressCount));
+    // Ñïàâíåð àêòèâåí
+    utils.writeBool(st, gTriggers[i].AutoSpawn);
+    // Çàäåðæêà ñïàâíåðà
+    utils.writeInt(st, LongInt(gTriggers[i].SpawnCooldown));
+    // Ñ÷åò÷èê ñîçäàíèÿ îáúåêòîâ
+    utils.writeInt(st, LongInt(gTriggers[i].SpawnedCount));
+    // Ñêîëüêî ðàç ïðîèãðàí çâóê
+    utils.writeInt(st, LongInt(gTriggers[i].SoundPlayCount));
+    // Ïðîèãðûâàåòñÿ ëè çâóê?
+    if (gTriggers[i].Sound <> nil) then b := gTriggers[i].Sound.IsPlaying() else b := false;
+    utils.writeBool(st, b);
     if b then
     begin
-    // Ïîçèöèÿ ïðîèãðûâàíèÿ çâóêà:
-      dw := gTriggers[i].Sound.GetPosition();
-      Mem.WriteDWORD(dw);
-    // Ãðîìêîñòü çâóêà:
+      // Ïîçèöèÿ ïðîèãðûâàíèÿ çâóêà
+      utils.writeInt(st, LongWord(gTriggers[i].Sound.GetPosition()));
+      // Ãðîìêîñòü çâóêà
       sg := gTriggers[i].Sound.GetVolume();
-      sg := sg / (gSoundLevel/255.0);
-      Mem.WriteSingle(sg);
-    // Ñòåðåî ñìåùåíèå çâóêà:
+      sg := sg/(gSoundLevel/255.0);
+      //Mem.WriteSingle(sg);
+      st.WriteBuffer(sg, sizeof(sg)); // sorry
+      // Ñòåðåî ñìåùåíèå çâóêà
       sg := gTriggers[i].Sound.GetPan();
-      Mem.WriteSingle(sg);
+      //Mem.WriteSingle(sg);
+      st.WriteBuffer(sg, sizeof(sg)); // sorry
+    end;
+    // uservars
+    if (gTriggers[i].userVars = nil) then
+    begin
+      utils.writeInt(st, LongInt(0));
+    end
+    else
+    begin
+      utils.writeInt(st, LongInt(gTriggers[i].userVars.count)); //FIXME: check for overflow
+      for kv in gTriggers[i].userVars.byKeyValue do
+      begin
+        //writeln('<', kv.key, '>:<', VarToStr(kv.value), '>');
+        utils.writeStr(st, kv.key);
+        t := LongInt(varType(kv.value));
+        utils.writeInt(st, LongInt(t));
+        case t of
+          varString: utils.writeStr(st, AnsiString(kv.value));
+          varBoolean: utils.writeBool(st, Boolean(kv.value));
+          varShortInt: utils.writeInt(st, LongInt(kv.value));
+          varSmallint: utils.writeInt(st, LongInt(kv.value));
+          varInteger: utils.writeInt(st, LongInt(kv.value));
+          //varInt64: Mem.WriteInt(Integer(kv.value));
+          varByte: utils.writeInt(st, LongInt(kv.value));
+          varWord: utils.writeInt(st, LongInt(kv.value));
+          varLongWord: utils.writeInt(st, LongInt(kv.value));
+          //varQWord:
+          else raise Exception.CreateFmt('cannot save uservar ''%s''', [kv.key]);
+        end;
+      end;
     end;
   end;
 end;
 
-procedure g_Triggers_LoadState(var Mem: TBinMemoryReader);
+
+procedure g_Triggers_LoadState (st: TStream);
 var
-  count, act_count, i, j, a: Integer;
+  count, actCount, i, j, a: Integer;
   dw: DWORD;
   vol, pan: Single;
   b: Boolean;
-  //p: Pointer;
   Trig: TTrigger;
   mapIndex: Integer;
-  //tw: TStrTextWriter;
+  uvcount: Integer;
+  vt: LongInt;
+  vv: Variant;
+  uvname: AnsiString = '';
+  ustr: AnsiString = '';
+  uint: LongInt;
+  ubool: Boolean;
 begin
-  if Mem = nil then
-    Exit;
+  assert(st <> nil);
 
   g_Triggers_Free();
 
-// Êîëè÷åñòâî òðèããåðîâ:
-  Mem.ReadInt(count);
-
+  // Êîëè÷åñòâî òðèããåðîâ
+  count := utils.readLongInt(st);
   if (count = 0) then exit;
+  if (count < 0) or (count > 1024*1024) then raise XStreamError.Create('invalid trigger count');
 
   for a := 0 to count-1 do
   begin
-  // Ñèãíàòóðà òðèããåðà:
-    Mem.ReadDWORD(dw);
-    if (dw <> TRIGGER_SIGNATURE) then // 'TRGX'
-    begin
-      raise EBinSizeError.Create('g_Triggers_LoadState: Wrong Trigger Signature');
-    end;
-  // Òèï òðèããåðà:
-    Mem.ReadByte(Trig.TriggerType);
-  // Ñïåöèàëüíûå äàííûå òðèããåðà: èíäåêñ â gCurrentMap.field['triggers']
+    // Ñèãíàòóðà òðèããåðà
+    if not utils.checkSign(st, 'TRGX') then raise XStreamError.Create('invalid trigger signature');
+    if (utils.readByte(st) <> 0) then raise XStreamError.Create('invalid trigger version');
+    // Òèï òðèããåðà
+    Trig.TriggerType := utils.readByte(st);
     if (Trig.TriggerType = TRIGGER_NONE) then continue; // empty one
-    Mem.ReadInt(mapIndex);
-  //!!!FIXME!!!
-    {
-    Mem.ReadMemory(p, dw);
-    if dw <> SizeOf(TTriggerData) then
-    begin
-      raise EBinSizeError.Create('g_Triggers_LoadState: Wrong TriggerData Size');
-    end;
-    Trig.Data := TTriggerData(p^);
-    }
-  // Ñîçäàåì òðèããåð:
+    // Ñïåöèàëüíûå äàííûå òðèããåðà: èíäåêñ â gCurrentMap.field['triggers']
+    mapIndex := utils.readLongInt(st);
     i := g_Triggers_CreateWithMapIndex(Trig, a, mapIndex);
-    {
-    if (gTriggers[i].trigData <> nil) then
-    begin
-      tw := TStrTextWriter.Create();
-      try
-        gTriggers[i].trigData.writeTo(tw);
-        e_LogWritefln('=== trigger #%s loaded ==='#10'%s'#10'---', [mapIndex, tw.str]);
-      finally
-        tw.Free();
-      end;
-    end;
-    }
-  // Êîîðäèíàòû ëåâîãî âåðõíåãî óãëà:
-    Mem.ReadInt(gTriggers[i].X);
-    Mem.ReadInt(gTriggers[i].Y);
-  // Ðàçìåðû:
-    Mem.ReadWord(gTriggers[i].Width);
-    Mem.ReadWord(gTriggers[i].Height);
-  // Âêëþ÷åí ëè òðèããåð:
-    Mem.ReadBoolean(gTriggers[i].Enabled);
-  // Òèï àêòèâàöèè òðèããåðà:
-    Mem.ReadByte(gTriggers[i].ActivateType);
-  // Êëþ÷è, íåîáõîäèìûå äëÿ àêòèâàöèè:
-    Mem.ReadByte(gTriggers[i].Keys);
-  // ID ïàíåëè, òåêñòóðà êîòîðîé èçìåíèòñÿ:
-    Mem.ReadInt(gTriggers[i].TexturePanelGUID);
-  // Òèï ýòîé ïàíåëè:
-    Mem.ReadWord(gTriggers[i].TexturePanelType);
-  // Âíóòðåííèé íîìåð äðóãîé ïàíåëè (ïî ñ÷àñòëèâîé ñëó÷àéíîñòè îí áóäåò ñîâïàäàòü ñ òåì, ÷òî ñîçäàíî ïðè çàãðóçêå êàðòû)
-    Mem.ReadInt(gTriggers[i].trigPanelGUID);
-  // Âðåìÿ äî âîçìîæíîñòè àêòèâàöèè:
-    Mem.ReadWord(gTriggers[i].TimeOut);
-  // UID òîãî, êòî àêòèâèðîâàë ýòîò òðèããåð:
-    Mem.ReadWord(gTriggers[i].ActivateUID);
-  // Ñïèñîê UID-îâ îáúåêòîâ, êîòîðûå íàõîäèëèñü ïîä âîçäåéñòâèåì:
-    Mem.ReadInt(act_count);
-    if act_count > 0 then
+    // Êîîðäèíàòû ëåâîãî âåðõíåãî óãëà
+    gTriggers[i].X := utils.readLongInt(st);
+    gTriggers[i].Y := utils.readLongInt(st);
+    // Ðàçìåðû
+    gTriggers[i].Width := utils.readWord(st);
+    gTriggers[i].Height := utils.readWord(st);
+    // Âêëþ÷åí ëè òðèããåð
+    gTriggers[i].Enabled := utils.readBool(st);
+    // Òèï àêòèâàöèè òðèããåðà
+    gTriggers[i].ActivateType := utils.readByte(st);
+    // Êëþ÷è, íåîáõîäèìûå äëÿ àêòèâàöèè
+    gTriggers[i].Keys := utils.readByte(st);
+    // ID ïàíåëè, òåêñòóðà êîòîðîé èçìåíèòñÿ
+    gTriggers[i].TexturePanelGUID := utils.readLongInt(st);
+    // Òèï ýòîé ïàíåëè
+    //Mem.ReadWord(gTriggers[i].TexturePanelType);
+    // Âíóòðåííèé íîìåð äðóãîé ïàíåëè (ïî ñ÷àñòëèâîé ñëó÷àéíîñòè îí áóäåò ñîâïàäàòü ñ òåì, ÷òî ñîçäàíî ïðè çàãðóçêå êàðòû)
+    gTriggers[i].trigPanelGUID := utils.readLongInt(st);
+    // Âðåìÿ äî âîçìîæíîñòè àêòèâàöèè
+    gTriggers[i].TimeOut := utils.readWord(st);
+    // UID òîãî, êòî àêòèâèðîâàë ýòîò òðèããåð
+    gTriggers[i].ActivateUID := utils.readWord(st);
+    // Ñïèñîê UID-îâ îáúåêòîâ, êîòîðûå íàõîäèëèñü ïîä âîçäåéñòâèåì
+    actCount := utils.readLongInt(st);
+    if (actCount < 0) or (actCount > 1024*1024) then raise XStreamError.Create('invalid activated object count');
+    if (actCount > 0) then
     begin
-      SetLength(gTriggers[i].Activators, act_count);
-      for j := 0 to act_count-1 do
+      SetLength(gTriggers[i].Activators, actCount);
+      for j := 0 to actCount-1 do
       begin
         // UID îáúåêòà
-        Mem.ReadWord(gTriggers[i].Activators[j].UID);
+        gTriggers[i].Activators[j].UID := utils.readWord(st);
         // Âðåìÿ îæèäàíèÿ
-        Mem.ReadWord(gTriggers[i].Activators[j].TimeOut);
+        gTriggers[i].Activators[j].TimeOut := utils.readWord(st);
       end;
     end;
-  // Ñòîèò ëè èãðîê â îáëàñòè òðèããåðà:
-    Mem.ReadBoolean(gTriggers[i].PlayerCollide);
-  // Âðåìÿ äî çàêðûòèÿ äâåðè:
-    Mem.ReadInt(gTriggers[i].DoorTime);
-  // Çàäåðæêà àêòèâàöèè:
-    Mem.ReadInt(gTriggers[i].PressTime);
-  // Ñ÷åò÷èê íàæàòèé:
-    Mem.ReadInt(gTriggers[i].PressCount);
-  // Ñïàâíåð àêòèâåí:
-    Mem.ReadBoolean(gTriggers[i].AutoSpawn);
-  // Çàäåðæêà ñïàâíåðà:
-    Mem.ReadInt(gTriggers[i].SpawnCooldown);
-  // Ñ÷åò÷èê ñîçäàíèÿ îáúåêòîâ:
-    Mem.ReadInt(gTriggers[i].SpawnedCount);
-  // Ñêîëüêî ðàç ïðîèãðàí çâóê:
-    Mem.ReadInt(gTriggers[i].SoundPlayCount);
-  // Ïðîèãðûâàåòñÿ ëè çâóê?
-    Mem.ReadBoolean(b);
+    // Ñòîèò ëè èãðîê â îáëàñòè òðèããåðà
+    gTriggers[i].PlayerCollide := utils.readBool(st);
+    // Âðåìÿ äî çàêðûòèÿ äâåðè
+    gTriggers[i].DoorTime := utils.readLongInt(st);
+    // Çàäåðæêà àêòèâàöèè
+    gTriggers[i].PressTime := utils.readLongInt(st);
+    // Ñ÷åò÷èê íàæàòèé
+    gTriggers[i].PressCount := utils.readLongInt(st);
+    // Ñïàâíåð àêòèâåí
+    gTriggers[i].AutoSpawn := utils.readBool(st);
+    // Çàäåðæêà ñïàâíåðà
+    gTriggers[i].SpawnCooldown := utils.readLongInt(st);
+    // Ñ÷åò÷èê ñîçäàíèÿ îáúåêòîâ
+    gTriggers[i].SpawnedCount := utils.readLongInt(st);
+    // Ñêîëüêî ðàç ïðîèãðàí çâóê
+    gTriggers[i].SoundPlayCount := utils.readLongInt(st);
+    // Ïðîèãðûâàåòñÿ ëè çâóê?
+    b := utils.readBool(st);
     if b then
     begin
-    // Ïîçèöèÿ ïðîèãðûâàíèÿ çâóêà:
-      Mem.ReadDWORD(dw);
-    // Ãðîìêîñòü çâóêà:
-      Mem.ReadSingle(vol);
-    // Ñòåðåî ñìåùåíèå çâóêà:
-      Mem.ReadSingle(pan);
-    // Çàïóñêàåì çâóê, åñëè åñòü:
-      if gTriggers[i].Sound <> nil then
+      // Ïîçèöèÿ ïðîèãðûâàíèÿ çâóêà
+      dw := utils.readLongWord(st);
+      // Ãðîìêîñòü çâóêà
+      //Mem.ReadSingle(vol);
+      st.ReadBuffer(vol, sizeof(vol)); // sorry
+      // Ñòåðåî ñìåùåíèå çâóêà
+      //Mem.ReadSingle(pan);
+      st.ReadBuffer(pan, sizeof(pan)); // sorry
+      // Çàïóñêàåì çâóê, åñëè åñòü
+      if (gTriggers[i].Sound <> nil) then
       begin
         gTriggers[i].Sound.PlayPanVolume(pan, vol);
         gTriggers[i].Sound.Pause(True);
         gTriggers[i].Sound.SetPosition(dw);
       end
     end;
+    // uservars
+    gTriggers[i].userVars.Free();
+    gTriggers[i].userVars := nil;
+    uvcount := utils.readLongInt(st);
+    if (uvcount < 0) or (uvcount > 1024*1024) then raise XStreamError.Create('invalid number of user vars in trigger');
+    if (uvcount > 0) then
+    begin
+      gTriggers[i].userVars := THashStrVariant.Create();
+      vv := Unassigned;
+      while (uvcount > 0) do
+      begin
+        Dec(uvcount);
+        uvname := utils.readStr(st);
+        vt := utils.readLongInt(st);
+        case vt of
+          varString: begin ustr := utils.readStr(st); vv := ustr; end;
+          varBoolean: begin ubool := utils.readBool(st); vv := ubool; end;
+          varShortInt: begin uint := utils.readLongInt(st); vv := ShortInt(uint); end;
+          varSmallint: begin uint := utils.readLongInt(st); vv := SmallInt(uint); end;
+          varInteger: begin uint := utils.readLongInt(st); vv := LongInt(uint); end;
+          varByte: begin uint := utils.readLongInt(st); vv := Byte(uint); end;
+          varWord: begin uint := utils.readLongInt(st); vv := Word(uint); end;
+          varLongWord: begin uint := utils.readLongInt(st); vv := LongWord(uint); end;
+          else raise Exception.CreateFmt('cannot load uservar ''%s''', [uvname]);
+        end;
+        gTriggers[i].userVars.put(uvname, vv);
+      end;
+    end;
   end;
 end;
 
+
 end.