<?xml version='1.0' encoding='utf-8'?>
<CheatTable CheatEngineTableVersion="45">
  <CheatEntries>
    <CheatEntry>
      <ID>1</ID>
      <Description>"[ATTACH / ALL OFF] Attach to Permafrost-Win64-Shipping.exe + disable everything"</Description>
      <Color>00A5FF</Color>
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>
{ Game   : Permafrost-Win64-Shipping.exe
  Author  : Black_wolf
  CheatVer:0.45.2.4855-001-006

  Memo: ゲームバージョン0.45.2.4855
        ゲームエンジンは Unreal Engine 5.4
        モジュールのビルド日時（PEタイムスタンプ）: 4D288179（SizeOfImage A5F1000）

        ゲームのデータはUEリフレクション（名前）で検出
	別ビルドでは警告を表示し、データが見つからない機能は無効

	このゲームはバグも多くクエストが進行不能になる。
	操作挙動もおかしいし、変な慣性系の動きが気持ち悪い。
}

[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.disableAll(memrec) end)
{$asm}
[DISABLE]
</AssemblerScript>
    </CheatEntry>
    <CheatEntry>
      <ID>2</ID>
      <Description>"0. Settings &amp; README"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>3</ID>
          <Description>"Language / 言語設定"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>4</ID>
              <Description>"English (default)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.setLang('en') end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>5</ID>
              <Description>"日本語 / Japanese"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.setLang('ja') end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>6</ID>
          <Description>"README"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>7</ID>
              <Description>"1) Start the game, open this table (allow its Lua script), then run [ATTACH / ALL OFF] at the top. Load a save before using the features."</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
            <CheatEntry>
              <ID>8</ID>
              <Description>"2) Made for the Permafrost 0.45.2.4855, Steam build 26560720, PE timestamp 4D288179 (UE 5.4). UE core references use validated data targets and bounded initialization retries. The supported build uses byte-checked known code locations; feature code is resolved on demand. Other builds use module-only AOB scans. Game data is located by UE reflection (names); on other builds a warning is shown and features whose data is not found are disabled."</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
            <CheatEntry>
              <ID>9</ID>
              <Description>"3) Orange = script (check to run / toggle), cyan = expandable group / list, no color = value (double-click to edit)."</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
            <CheatEntry>
              <ID>10</ID>
              <Description>"4) Status and error messages appear in the Lua Engine window of Cheat Engine."</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
            <CheatEntry>
              <ID>11</ID>
              <Description>"5) Save your game before using editor / one-shot actions. Game functions (add items, blueprints, weather, item names) run only while you are in game."</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>12</ID>
          <Description>"Diagnostics (only when the table does not work)"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>13</ID>
              <Description>"Lua Engine (check = open / uncheck = close)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.openLuaEngine()
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.closeLuaEngine() end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>14</ID>
              <Description>"AOB scan self-test (CE is busy for a while; prints to Lua Engine)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.scanSelfTest() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>15</ID>
              <Description>"Environment / connection info (CE, process, module, build)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.envReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>16</ID>
              <Description>"Status: unresolved code / active hooks / active features"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.statusReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>17</ID>
              <Description>"UE core check (GNames / GObjects / GWorld / player)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.ueReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>100</ID>
      <Description>"1. Survival (enabled = kept at MAX, never decreases)"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>101</ID>
          <Description>"Infinite health"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('infHealth', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('infHealth', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>102</ID>
          <Description>"Infinite stamina"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('infStamina', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('infStamina', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>106</ID>
          <Description>"No hunger (Hunger at max)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noHunger', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noHunger', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>103</ID>
          <Description>"No fatigue (Energy at max)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noFatigue', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noFatigue', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>104</ID>
          <Description>"No cold (body warmth at max)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noCold', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noCold', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>105</ID>
          <Description>"No drunkenness (alcohol = 0)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noDrunk', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noDrunk', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>200</ID>
      <Description>"2. Player"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>201</ID>
          <Description>"Skill experience multiplier"</Description>
          <Options moHideChildren="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('xpMul', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('xpMul', false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>202</ID>
              <Description>"Multiplier"</Description>
              <ShowAsSigned>0</ShowAsSigned>
              <VariableType>Float</VariableType>
              <Address>pfVars+28</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>203</ID>
          <Description>"Movement speed multiplier"</Description>
          <Options moHideChildren="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('speed', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('speed', false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>204</ID>
              <Description>"Speed multiplier"</Description>
              <ShowAsSigned>0</ShowAsSigned>
              <VariableType>Float</VariableType>
              <Address>pfVars+20</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>205</ID>
          <Description>"Jump height multiplier"</Description>
          <Options moHideChildren="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('jump', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('jump', false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>206</ID>
              <Description>"Jump multiplier"</Description>
              <ShowAsSigned>0</ShowAsSigned>
              <VariableType>Float</VariableType>
              <Address>pfVars+24</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry><ID>211</ID><Description>"Hold Space to float upward"</Description><Color>00A5FF</Color><VariableType>Auto Assembler Script</VariableType><AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('spaceFloat',true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('spaceFloat',false) end
{$asm}
</AssemblerScript></CheatEntry><CheatEntry>
          <ID>207</ID>
          <Description>"No fall damage (player only; works with Space float)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noFall', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noFall', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>210</ID>
          <Description>"Teleport to the map sticker you place (open the map, place a sticker at the mouse pointer)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('mapTeleport', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('mapTeleport', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry><ID>212</ID><Description>"Emergency unstick (find surface / reset movement state)"</Description><Color>00A5FF</Color><VariableType>Auto Assembler Script</VariableType><AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec,function() PF.emergencyEscape() end)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
{$asm}
</AssemblerScript></CheatEntry><CheatEntry>
          <ID>208</ID>
          <Description>"Player parameters (enable to list / edit)"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.userRun(function() PF.refreshAttrList(memrec) end)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>209</ID>
          <Description>"Blueprint points (enable to show / edit)"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.userRun(function() PF.refreshBPList(memrec) end)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>300</ID>
      <Description>"3. Items"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>301</ID>
          <Description>"No item consumption (player inventory; transfers and splitting allowed)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('invFreeze', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('invFreeze', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>302</ID>
          <Description>"No ammo consumption (player magazines, bullets and arrows)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('ammoInf', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('ammoInf', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>303</ID>
          <Description>"Infinite durability (refilled to MAX while enabled)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('durAll', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('durAll', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>304</ID>
          <Description>"Items never break (durability never goes below 10%)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('noBreak', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('noBreak', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>307</ID>
          <Description>"Infinite fuel (campfires / stoves / furnaces, generators, vehicles, lanterns)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('fuelInf', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('fuelInf', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>305</ID>
          <Description>"Add items... (category list / multi-select / quantity)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.addItemPick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>306</ID>
          <Description>"Item amounts (enable to list / edit)"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.userRun(function() PF.refreshInvList(memrec) end)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.clearChildren(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>400</ID>
      <Description>"4. Crafting"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>403</ID>
          <Description>"No materials needed (crafting: hand / workbenches / placed stations; building; repair / renovation)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('craftFree', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('craftFree', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>404</ID>
          <Description>"Instant craft (crafting / recycling time 0.1 s)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('instantCraft', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('instantCraft', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>405</ID>
          <Description>"Instant build (0.1 s base time; normal completion)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('instantBuild', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('instantBuild', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      <CheatEntry>
          <ID>401</ID>
          <Description>"Add blueprints... (from the blueprint list)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.learnPick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>402</ID>
          <Description>"Learn all blueprints"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.learnAll() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>500</ID>
      <Description>"5. World"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>501</ID>
          <Description>"Always daytime (lock at 12:00)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('todNoon', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('todNoon', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>502</ID>
          <Description>"Keep clear weather"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('wxClear', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('wxClear', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>503</ID>
          <Description>"Set time of day now (hour below)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.todSet() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>504</ID>
          <Description>"Lock time of day (hour below)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('todLock', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('todLock', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>505</ID>
          <Description>"Hour (0-23.99, e.g. 12 = noon, 0 = midnight)"</Description>
          <ShowAsSigned>0</ShowAsSigned>
          <VariableType>Float</VariableType>
          <Address>pfVars+2C</Address>
        </CheatEntry>
        <CheatEntry>
          <ID>506</ID>
          <Description>"Set weather now... (choose from the list)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.wxPick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>507</ID>
          <Description>"Lock weather (keep the weather chosen above)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.feature('wxLock', true)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if PF then PF.feature('wxLock', false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>509</ID>
          <Description>"Reveal the whole map (runs in the background; progress in Lua Engine)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.mapRevealAll() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>510</ID>
          <Description>"Spawn animals... (choose the kind and number; around you)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.spawnAnimalPick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>508</ID>
          <Description>"Spawn a snowmobile (in front of you; the class is loaded if needed)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.spawnVehicle() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>600</ID>
      <Description>"6. Quests (save first; close the menu before running)"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>601</ID>
          <Description>"Advance the current main quest by one step"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.questAdvance('Main') end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>602</ID>
          <Description>"Advance the current side quest by one step"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.questAdvance('Side') end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>603</ID>
          <Description>"Insert a quest... (choose from the list; starts it)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.questInsertPick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>700</ID>
      <Description>"7. Save data files (newest 10 backups kept)"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>701</ID>
          <Description>"Back up the current save data (save in game first)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.saveBackup() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>702</ID>
          <Description>"Restore save data... (list with timestamps; at the title screen or with the game closed)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec, function() PF.saveRestorePick() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  <CheatEntry><ID>800</ID><Description>"8. Other"</Description><Options moManualExpandCollapse="1" /><Color>FFFF00</Color><GroupHeader>1</GroupHeader><CheatEntries><CheatEntry><ID>801</ID><Description>"Unlock all Steam achievements"</Description><Color>00A5FF</Color><VariableType>Auto Assembler Script</VariableType><AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
PF.oneShot(memrec,function() PF.steamUnlockAll() end)
{$asm}
[DISABLE]
</AssemblerScript></CheatEntry></CheatEntries></CheatEntry></CheatEntries>
  <UserdefinedSymbols />
  <LuaScript>--[[ =====================================================================================
  Permafrost.CT  -  Cheat Engine table for Permafrost (Steam release build)   (namespace: PF)
  Based on GameTemplate.CT V02 (common framework)
  Target : Cheat Engine 7.5+ (64-bit)
  Engine : Unreal Engine 5.4 (++UE5+Release-5.4-CL-35576357), Gameplay Ability System attributes
  Layout : [ATTACH / ALL OFF]  -&gt;  0. Settings &amp; README  -&gt;  1. Survival  2. Movement  3. Held item
  Colors : expandable group = 0xFFFF00 (cyan, BGR) / script = 0x00A5FF (orange, BGR) / value row = none
  IDs    : 1 = ATTACH, 2 = "0." top group, 3..99 = inside "0.", category N uses N*100 .. N*100+99
  Game data is located through UE reflection (GNames / GUObjectArray / GWorld found by AOB, then
  classes and properties are looked up by NAME at run time), so most of it survives game updates.
===================================================================================== ]]
PF = PF or {}
local PF = PF

----------------------------------------------------------------- [GAME] basic settings
PF.TAG      = 'PF'                                -- log prefix: [PF] ...
PF.TITLE    = 'Permafrost'             -- game title (for messages)
PF.EXE      = 'Permafrost-Win64-Shipping.exe'     -- process name
PF.MODULE   = 'Permafrost-Win64-Shipping.exe'     -- module that holds the game code (UE: *-Win64-Shipping.exe)
PF.GAMEVER  = '0.45.2.4855 / Steam build 26560720 / PE 4D288179'
PF.BUILD    = {ts=0x4D288179, size=0xA5F1000}     -- PE timestamp + module size of that build
PF.RVA = {
  FallEffectApply=0x4F12890,
  ActorDamage=0x3344380,
  AmmoRemove=0x5522490,
  BuildCost=0x5481EA0,
  InventoryMoveCall=0x55204D8,
  InventorySplitCall=0x5521001,
  BuildDeduce=0x53EF77E,
  CraftChkAll=0x54D8770,
  CraftChkCan=0x54D8960,
  CraftChkQty=0x54D8AB0,
  CraftItemImpl=0x54D8C20,
  CraftReq=0x54DA570,
  FallDur=0x6336D37,
  FuelStation=0x54DE0CA,
  FuelSupply=0x54838AB,
  FuelVehicle=0x55985A0,
  GNames=0x11B8FDC,
  GObjects=0x124522D,
  GWorld=0x3ECCCC5,
  InvCheckFor=0x53A2C5A,
  InvQuantity=0x53A36C1,
  ItemConsume=0x5522540,
  ItemDurability=0x55226EF,
  ProcessEvent=0x13A87F0,
  RenovChk=0x5482930,
  RenovRemain=0x547F4F0,
  RenovUse=0x5482C77,
  RepairChk=0x54DFA75,
  RepairUse=0x54DFAB8,
  StickerAdd=0x53EBB09,
  MoveSpeed=0x6334E9B,
}
PF.TICK_MS  = 500                                 -- background timer interval (ms)
PF.lang     = PF.lang or 'en'                     -- default language: 'en' / 'ja'

----------------------------------------------------------------- common constants (do not change)
PF.C_GROUP  = 0xFFFF00          -- cyan   (BGR): expandable groups
PF.C_SCRIPT = 0x00A5FF          -- orange (BGR): scripts
PF.ID_ATTACH = 1   -- coexistence edition: IDs offset by 0
PF.ID_TOP0   = 2
-- shared memory page (allocated near PF.MODULE at attach, registered as CE symbols)
--   pfFlags +000..0FF : feature flag bytes (hook code reads [pfFlags+n])
--   pfVars  +100..1FF : parameters (value rows / hook code)
--   pfPtrs  +200..2FF : pointer slots, 8 bytes each (not used by this table)
--   +300..EFF : parameter buffer of game function calls (peCall)
--   +F00..FFF : crafting components changed by the craftClr hooks (dword count + 31 pointers)
PF.OFF_VARS, PF.OFF_PTRS = 0x100, 0x200

----------------------------------------------------------------- [GAME] AOB signatures
-- These three are DATA references (rip-relative operand), not hook sites. PF.ripTarget() reads the operand.
--   GObjects : mov rax,[GUObjectArray.ObjObjects.Objects] / mov rcx,[rax+rcx*8] / lea r8,[rcx+rdx*8]
--   GNames   : lea rcx,[FNamePool] / call FNamePool::FNamePool / mov byte ptr [bNamePoolInitialized],1
--   GWorld   : mov rbx,[GWorld] / test rbx,rbx / je / mov r8b,1   (UWorld::GetWorldSettings(false,true))
PF.SIGS = {
  MoveSpeed = { p='F3 0F 59 83 00 10 00 00 F3 0F 59 83 04 10 00 00 48 83 C4 20 5B C3', off=16, len=5 },
  GObjects = { p='48 8B 05 ?? ?? ?? ?? 48 8B 0C C8 4C 8D 04 D1 EB 06', off=0, len=7, disp=3,
               alt={'48 8B 05 ?? ?? ?? ?? 48 8B 0C C8 4C 8D 04 D1','48 8B 05 ?? ?? ?? ?? 48 8B 0C C8 48 8D 04 D1'} },   -- alternatives: about 50 sites, all GUObjectArray
  GNames   = { p='48 8D 0D ?? ?? ?? ?? E8 ?? ?? ?? ?? C6 05 ?? ?? ?? ?? 01 0F 10', off=0, len=7, disp=3, alt={'48 8D 0D ?? ?? ?? ?? E8 ?? ?? ?? ?? C6 05 ?? ?? ?? ?? 01','48 8D 0D ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8D'} },
  GWorld   = { p='48 8B 1D ?? ?? ?? ?? 48 85 DB 74 ?? 41 B0 01', off=0, len=7, disp=3, alt={'48 8B 05 ?? ?? ?? ?? 48 85 C0 74 ?? 41 B0 01','48 8B 35 ?? ?? ?? ?? 48 85 F6 74 ?? 41 B0 01'} },
  -- UObject::ProcessEvent (hook site: push rbp/rsi/rdi/r12 = 6 bytes, no rip-relative operand)
  -- UCraftingComponent_Base::GetRequirementsForCrafting (rows 0x30: +28 current amount, +2C required amount)
  CraftReq = { p='40 55 53 56 57 41 56 41 57 48 8D 6C 24 ?? 48 81 EC ?? ?? ?? ?? 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 ?? 49 8B D8 48 8B F2 4C 8B F9', off=0, len=9 },
  -- inventory item RemoveAmmo(AmmoCount) native body: MagazineAmmo(+B0) -= AmmoCount
  AmmoRemove = { p='48 89 5C 24 08 48 89 74 24 10 57 48 83 EC 20 8B B1 ?? ?? ?? ?? 48 8B D9 48 83 C1 ?? 2B F2 E8', off=0, len=5 },
  -- character movement falling update: FallDuration (+1008) += DeltaTime while falling fast (read by
  -- GetCurrentFallDuration); hook site = the addss, the following movss stores xmm6 back
  FallDur = { p='F3 0F 58 B3 ?? ?? 00 00 F3 0F 11 B3 ?? ?? 00 00 0F 28 74 24 20 48 83 C4 30 5B C3 F3 0F 58 B3', off=0, len=8 },
  -- execSERVER_AddWorldMapSticker (native thunk): rdx = &amp;TargetLocation right before the _Implementation call
  StickerAdd = { p='44 0F B6 44 24 50 33 C9 48 85 C0 0F 95 C1 48 03 C8 48 89 4B 20 48 8B CF 48 8B 07 FF 90 ?? ?? 00 00 48 8B 5C 24 58', off=0x15, len=6 },
  -- crafting without materials: entries of the crafting checks of UCraftingComponent_Base (rcx = component;
  -- bUseCraftingCosts = byte +329): CheckAllIngredientsFor / CheckIfCanBeCrafted / CheckIfCanCraftQuantity / craft
  CraftChkAll = { p='40 53 41 55 41 57 48 83 EC 70 80 B9 29 03 00 00 00 45 8B E8', off=0, len=6 },
  CraftChkCan = { p='48 89 5C 24 10 56 48 83 EC 30 8B 81 ?? ?? 00 00 48 8B F1 B9 01 00 00 00', off=0, len=5 },
  CraftChkQty = { p='48 89 5C 24 10 48 89 74 24 18 57 48 83 EC 30 41 8B F0 48 8B DA 48 8B F9 48 85 D2 74', off=0, len=5 },
  CraftItemImpl = { p='48 89 54 24 10 55 53 56 41 55 41 56 48 8D 6C 24 C9 48 81 EC A0 00 00 00 45 8B F0 48 8B DA 48 8B F1', off=0, len=5 },
  -- building: UBuildingSystemComponent::CheckBuildCost(TargetBuildPartConfig, bBuildPartItem) (entry)
  BuildCost   = { p='48 89 5C 24 08 48 89 74 24 10 57 48 81 EC 80 00 00 00 48 83 B9 ?? ?? 00 00 00 48 8B C2 48 8B F1', off=0, len=5 },
  -- building: execGetShouldDeduceCost (Blueprint asks whether to take the materials; the native body always
  -- returns true). Site = call + mov [rbx],al (the call target is a shared 'return true' stub)
  InventoryMoveCall = {p='2B DF 8B D7 48 8B CE E8 ?? ?? ?? ?? 49 8D 7C 24 08 EB ?? 49 8B 06',off=7,len=5,validateCall=true},
  InventorySplitCall = {p='8B D7 48 8B CB E8 ?? ?? ?? ?? B0 01 EB ?? 32 C0',off=5,len=5,validateCall=true},
  BuildDeduce = { p='40 53 48 83 EC 20 48 8B 42 20 45 33 C9 48 85 C0 49 8B D8 41 0F 95 C1 4C 03 C8 4C 89 4A 20 E8 ?? ?? ?? ?? 88 03 48 83 C4 20 5B C3', off=0x1E, len=7, validateCall=true },
  -- item repair (AUTHORITY_RepairItem body): cost rows of CalculateRepairCost; row Amount (+28) &gt; 0 -&gt;
  -- 1st loop: ResourceInventory has the items? (vtable+4B0)  2nd loop: remove them (vtable+520)
  RepairChk = { p='48 03 F3 48 3B DE 74 30 83 7B 28 00 7E 17 48 8B 07 48 8B D3 48 8B CF FF 90 B0 04 00 00', off=8, len=6 },
  RepairUse = { p='48 03 F3 48 3B DE 74 24 83 7B 28 00 7E 15 48 8B 07 41 B1 01 45 33 C0 48 8B D3 48 8B CF FF 90 20 05 00 00', off=8, len=6 },
  -- Blueprint calls of the inventory: execCheckForItem (result bool -&gt; [r14]) / execGetItemQuantity (int -&gt; [r14])
  InvCheckFor = { p='48 89 5F 20 48 8B 06 FF 90 B0 04 00 00 48 8B 4C 24 38 41 88 06 48 85 C9 74 05 E8', off=0xD, len=8 },
  InvQuantity = { p='48 89 7B 20 48 8B 06 FF 90 C0 04 00 00 48 8B 4C 24 38 41 89 06 48 85 C9 74 05 E8', off=0xD, len=8 },
  -- renovation (renovation actor GetRemainingRequiredResources body): out TArray&lt;FItemAmount&gt; (rows 0x30, Amount +28)
  RenovRemain = { p='48 89 4C 24 08 53 55 57 41 56 48 83 EC 48 33 ED 4C 8B F2 48 8B D1 89 AC 24 80 00 00 00 8B FD 49 89 2E 49 89 6E 08', off=0, len=5 },
  -- renovation (UPlayerBuildingComponent::SERVER_RenovateActor body): mesh cost rows (Amount +28) &gt; 0 -&gt;
  -- check: player inventory has them (vtable+4B0)   use: remove them (vtable+520) when the renovation starts
  RenovChk = { p='83 7B 28 00 7E 17 49 8B 8E E8 00 00 00 48 8B D3 48 8B 01 FF 90 B0 04 00 00 84 C0 74', off=0, len=6 },
  RenovUse = { p='83 7B 28 00 7E 19 49 8B 8E E8 00 00 00 41 B1 01 45 33 C0 48 8B D3 48 8B 01 FF 90 20 05 00 00', off=0, len=6 },
  -- infinite fuel (game code that burns fuel; the subtraction is skipped while flag 14 is on)
  -- fuel station (campfire / stove / furnace ...) AUTHORITY_UpdateFuel: slot remaining fuel (+14) -= burn amount
  FuelStation = { p='F3 0F 10 42 14 0F 2F C1 76 ?? F3 0F 5C C2 0F 2F C1 F3 0F 11 42 14 77 ??', off=0xA, len=7 },
  -- power supply (generator) AUHTORITY_FuelUpdate: CurrentFuel (+E4) -= consumption (+E0)
  FuelSupply  = { p='F3 0F 10 89 ?? ?? 00 00 0F 57 C0 F3 0F 5C 89 ?? ?? 00 00 0F 2F C8 F3 0F 11 89 ?? ?? 00 00', off=0xB, len=8 },
  -- vehicle (snowmobile) engine update: FuelAmount (+3D8) -= consumption
  FuelVehicle = { p='F3 0F 10 87 ?? ?? 00 00 F3 0F 59 3D ?? ?? ?? ?? F3 41 0F 59 F8 F3 0F 5C C7 0F 28 7C 24 30 0F 2F C1 F3 0F 11 87', off=0x15, len=9 },
  ProcessEvent = { p='40 55 56 57 41 54 41 55 41 56 41 57 48 81 EC ?? ?? ?? ?? 48 8D 6C 24 ?? 48 89 9D ?? ?? ?? ?? 48 8B 05 ?? ?? ?? ?? 48 33 C5 48 89 85 ?? ?? ?? ?? 4D 8B', off=0, len=6 },
}

----------------------------------------------------------------- [GAME] hooks
-- peCall: runs ONE queued UFunction call through ProcessEvent on the game thread (the next time the game calls
-- ProcessEvent). Request: [pfFlags+10]=1, object at pfVars+40, UFunction at pfVars+48, parameters at pfFlags+300.
-- [pfFlags+10] becomes 2 while running and 0 when done. lock cmpxchg so only one thread takes the request.
-- Carrier gate: the request is taken only inside a ProcessEvent whose object == [pfVars+50] (0 = any) and whose
-- UFunction == [pfVars+58] (0 = any). Calls that change game state use the player pawn's own tick event, so they
-- never run inside UI / input processing (running there crashed the game with the inventory open).
-- Every request runs on the GAME THREAD only: [pfVars+68] = id of the process main thread (UE runs the game thread
-- on the main thread), written by Lua. Worker threads (e.g. thread-safe animation updates) also call ProcessEvent,
-- even on the pawn, and must never run our calls.
PF.HOOKS = {
  moveSpeed = { sig='MoveSpeed', aa=[==[
[ENABLE]
alloc(pf_speed,$1000,$SITE)
label(pf_speed_ret)
label(pf_speed_done)
pf_speed:
  pushfq
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+15],0
  je pf_speed_done
  cmp rbx,[rax+2B0]
  jne pf_speed_done
  mulss xmm0,[rax+1A8]
pf_speed_done:
  pop rax
  popfq
  $ORIG
  jmp pf_speed_ret
$SITE:
  jmp pf_speed
  $NOP
pf_speed_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_speed)
]==] },
  -- craftReq: after GetRequirementsForCrafting returns, every row's current amount is raised to required x 99
  -- (flag 11). The UI, GetMaximumPossibleCrafts and all ingredient checks then see the materials as available;
  -- consumption itself is skipped by bUseCraftingCosts = false (set by the same feature).
  craftReq = { sig='CraftReq', aa=[==[
[ENABLE]
alloc(pf_req,$1000,$SITE)
label(pf_req_tramp)
label(pf_req_ret)
label(pf_req_loop)
label(pf_req_next)
label(pf_req_done)
pf_req:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  je pf_req_tramp
  push rbx
  push rdx
  sub rsp,28
  call pf_req_tramp
  add rsp,28
  pop rdx
  mov rbx,[rdx]
  mov ecx,[rdx+8]
  test rbx,rbx
  je pf_req_done
pf_req_loop:
  test ecx,ecx
  jle pf_req_done
  mov r8d,[rbx+2C]
  imul r8d,r8d,63
  cmp [rbx+28],r8d
  jge pf_req_next
  mov [rbx+28],r8d
pf_req_next:
  add rbx,30
  dec ecx
  jmp pf_req_loop
pf_req_done:
  pop rbx
  ret
pf_req_tramp:
  $ORIG
  jmp pf_req_ret
$SITE:
  jmp pf_req
  $NOP
pf_req_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_req)
]==] },
  -- fallDur: while flag 13 is on, the fall duration stays 0 (the landing never counts as a long fall)
  fallDur = { sig='FallDur', aa=[==[
[ENABLE]
alloc(pf_fall,$1000,$SITE)
label(pf_fall_ret)
label(pf_fall_done)
pf_fall:
  $ORIG
  pushfq
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+13],0
  je pf_fall_done
  mov rax,pfPtrs
  cmp rbx,[rax+F8]
  jne pf_fall_done
  xorps xmm6,xmm6
pf_fall_done:
  pop rax
  popfq
  jmp pf_fall_ret
$SITE:
  jmp pf_fall
  $NOP
pf_fall_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fall)
]==] },
  -- craftClr1..4: while flag 11 is on, a crafting component that runs a material check gets bUseCraftingCosts = 0
  -- (placed workbenches / stations loaded later included); the component is recorded at pfFlags+F00
  -- (count) / +F08 (up to 31 pointers) so the original value can be restored when the feature is turned off
  craftClr1 = { sig='CraftChkAll', aa=[==[
[ENABLE]
alloc(pf_cc1,$1000,$SITE)
label(pf_cc1_go)
label(pf_cc1_full)
label(pf_cc1_ret)
pf_cc1:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  je pf_cc1_go
  cmp byte ptr [rcx+329],0
  je pf_cc1_go
  mov byte ptr [rcx+329],0
  push rdx
  mov edx,[rax+F00]
  cmp edx,#31
  jae pf_cc1_full
  mov [rax+rdx*8+F08],rcx
  inc dword ptr [rax+F00]
pf_cc1_full:
  pop rdx
pf_cc1_go:
  pop rax
  $ORIG
  jmp pf_cc1_ret
$SITE:
  jmp pf_cc1
  $NOP
pf_cc1_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_cc1)
]==] },
  craftClr2 = { sig='CraftChkCan', aa=[==[
[ENABLE]
alloc(pf_cc2,$1000,$SITE)
label(pf_cc2_go)
label(pf_cc2_full)
label(pf_cc2_ret)
pf_cc2:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  je pf_cc2_go
  cmp byte ptr [rcx+329],0
  je pf_cc2_go
  mov byte ptr [rcx+329],0
  push rdx
  mov edx,[rax+F00]
  cmp edx,#31
  jae pf_cc2_full
  mov [rax+rdx*8+F08],rcx
  inc dword ptr [rax+F00]
pf_cc2_full:
  pop rdx
pf_cc2_go:
  pop rax
  $ORIG
  jmp pf_cc2_ret
$SITE:
  jmp pf_cc2
  $NOP
pf_cc2_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_cc2)
]==] },
  craftClr3 = { sig='CraftChkQty', aa=[==[
[ENABLE]
alloc(pf_cc3,$1000,$SITE)
label(pf_cc3_go)
label(pf_cc3_full)
label(pf_cc3_ret)
pf_cc3:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  je pf_cc3_go
  cmp byte ptr [rcx+329],0
  je pf_cc3_go
  mov byte ptr [rcx+329],0
  push rdx
  mov edx,[rax+F00]
  cmp edx,#31
  jae pf_cc3_full
  mov [rax+rdx*8+F08],rcx
  inc dword ptr [rax+F00]
pf_cc3_full:
  pop rdx
pf_cc3_go:
  pop rax
  $ORIG
  jmp pf_cc3_ret
$SITE:
  jmp pf_cc3
  $NOP
pf_cc3_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_cc3)
]==] },
  craftClr4 = { sig='CraftItemImpl', aa=[==[
[ENABLE]
alloc(pf_cc4,$1000,$SITE)
label(pf_cc4_go)
label(pf_cc4_full)
label(pf_cc4_ret)
pf_cc4:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  je pf_cc4_go
  cmp byte ptr [rcx+329],0
  je pf_cc4_go
  mov byte ptr [rcx+329],0
  push rdx
  mov edx,[rax+F00]
  cmp edx,#31
  jae pf_cc4_full
  mov [rax+rdx*8+F08],rcx
  inc dword ptr [rax+F00]
pf_cc4_full:
  pop rdx
pf_cc4_go:
  pop rax
  $ORIG
  jmp pf_cc4_ret
$SITE:
  jmp pf_cc4
  $NOP
pf_cc4_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_cc4)
]==] },
  -- buildCost: while flag 11 is on, CheckBuildCost returns true (building without materials)
  buildCost = { sig='BuildCost', aa=[==[
[ENABLE]
alloc(pf_bc,$1000,$SITE)
label(pf_bc_orig)
label(pf_bc_ret)
pf_bc:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  je pf_bc_orig
  mov al,1
  ret
pf_bc_orig:
  $ORIG
  jmp pf_bc_ret
$SITE:
  jmp pf_bc
  $NOP
pf_bc_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_bc)
]==] },
  -- buildDeduce: while flag 11 is on, GetShouldDeduceCost returns false (materials are not taken)
  buildDeduce = { sig='BuildDeduce', aa=[==[
[ENABLE]
alloc(pf_bd,$1000,$SITE)
label(pf_bd_one)
label(pf_bd_ret)
pf_bd:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  je pf_bd_one
  mov byte ptr [rbx],0
  jmp pf_bd_ret
pf_bd_one:
  mov al,1
  mov byte ptr [rbx],1
  jmp pf_bd_ret
$SITE:
  jmp pf_bd
  $NOP
pf_bd_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_bd)
]==] },
  -- renovRemain: while flag 11 is on, every resource still needed by a renovation gets Amount 0
  renovRemain = { sig='RenovRemain', aa=[==[
[ENABLE]
alloc(pf_rr,$1000,$SITE)
label(pf_rr_tramp)
label(pf_rr_ret)
label(pf_rr_loop)
label(pf_rr_done)
pf_rr:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  je pf_rr_tramp
  push rdx
  sub rsp,20
  call pf_rr_tramp
  add rsp,20
  pop rdx
  push rax
  mov r8,[rdx]
  mov r9d,[rdx+8]
  test r8,r8
  je pf_rr_done
pf_rr_loop:
  test r9d,r9d
  jle pf_rr_done
  mov dword ptr [r8+28],0
  add r8,30
  dec r9d
  jmp pf_rr_loop
pf_rr_done:
  pop rax
  ret
pf_rr_tramp:
  $ORIG
  jmp pf_rr_ret
$SITE:
  jmp pf_rr
  $NOP
pf_rr_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_rr)
]==] },
  -- invCheckFor / invQuantity: while flag 11 is on and the player's building tool is in a build mode
  -- (pfVars+B0 = address of BuildingSystemComponent.BuildMode, +B8 = value of EBuildMode::None), Blueprint
  -- inventory checks report the items as present (building repair with the building tool checks materials so)
  invCheckFor = { sig='InvCheckFor', aa=[==[
[ENABLE]
alloc(pf_icf,$1000,$SITE)
label(pf_icf_no)
label(pf_icf_ret)
pf_icf:
  push rdx
  mov rdx,pfFlags
  cmp byte ptr [rdx+11],0
  je pf_icf_no
  mov rdx,[rdx+1B0]
  test rdx,rdx
  je pf_icf_no
  movzx edx,byte ptr [rdx]
  push rcx
  mov rcx,pfFlags
  cmp dl,[rcx+1B8]
  pop rcx
  je pf_icf_no
  mov al,1
pf_icf_no:
  pop rdx
  $ORIG
  jmp pf_icf_ret
$SITE:
  jmp pf_icf
  $NOP
pf_icf_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_icf)
]==] },
  invQuantity = { sig='InvQuantity', aa=[==[
[ENABLE]
alloc(pf_iqt,$1000,$SITE)
label(pf_iqt_no)
label(pf_iqt_ret)
pf_iqt:
  push rdx
  mov rdx,pfFlags
  cmp byte ptr [rdx+11],0
  je pf_iqt_no
  mov rdx,[rdx+1B0]
  test rdx,rdx
  je pf_iqt_no
  movzx edx,byte ptr [rdx]
  push rcx
  mov rcx,pfFlags
  cmp dl,[rcx+1B8]
  pop rcx
  je pf_iqt_no
  cmp eax,#9999
  jge pf_iqt_no
  mov eax,#9999
pf_iqt_no:
  pop rdx
  $ORIG
  jmp pf_iqt_ret
$SITE:
  jmp pf_iqt
  $NOP
pf_iqt_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_iqt)
]==] },
  -- repairChk / repairUse: while flag 11 is on, item repair neither checks nor takes the repair materials
  repairChk = { sig='RepairChk', aa=[==[
[ENABLE]
alloc(pf_repairChk,$1000,$SITE)
label(pf_repairChk_skip)
pf_repairChk:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  jne pf_repairChk_skip
  cmp dword ptr [rbx+28],0
  jle pf_repairChk_skip
  jmp $SITE+6
pf_repairChk_skip:
  jmp $SITE+1D
$SITE:
  jmp pf_repairChk
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_repairChk)
]==] },
  -- renovChk / renovUse: while flag 11 is on, renovation neither checks nor takes the materials
  renovChk = { sig='RenovChk', aa=[==[
[ENABLE]
alloc(pf_renovChk,$1000,$SITE)
label(pf_renovChk_skip)
pf_renovChk:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  jne pf_renovChk_skip
  cmp dword ptr [rbx+28],0
  jle pf_renovChk_skip
  jmp $SITE+6
pf_renovChk_skip:
  jmp $SITE+1D
$SITE:
  jmp pf_renovChk
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_renovChk)
]==] },
  renovUse = { sig='RenovUse', aa=[==[
[ENABLE]
alloc(pf_renovUse,$1000,$SITE)
label(pf_renovUse_skip)
pf_renovUse:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  jne pf_renovUse_skip
  cmp dword ptr [rbx+28],0
  jle pf_renovUse_skip
  jmp $SITE+6
pf_renovUse_skip:
  jmp $SITE+1F
$SITE:
  jmp pf_renovUse
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_renovUse)
]==] },
  repairUse = { sig='RepairUse', aa=[==[
[ENABLE]
alloc(pf_repairUse,$1000,$SITE)
label(pf_repairUse_skip)
pf_repairUse:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+11],0
  pop rax
  jne pf_repairUse_skip
  cmp dword ptr [rbx+28],0
  jle pf_repairUse_skip
  jmp $SITE+6
pf_repairUse_skip:
  jmp $SITE+1B
$SITE:
  jmp pf_repairUse
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_repairUse)
]==] },
  -- fuelStation / fuelSupply / fuelVehicle: while flag 14 is on, the fuel subtraction is skipped
  fuelStation = { sig='FuelStation', aa=[==[
[ENABLE]
alloc(pf_fst,$1000,$SITE)
label(pf_fst_skip)
label(pf_fst_ret)
pf_fst:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+14],0
  pop rax
  jne pf_fst_skip
  subss xmm0,xmm2
pf_fst_skip:
  comiss xmm0,xmm1
  jmp pf_fst_ret
$SITE:
  jmp pf_fst
  $NOP
pf_fst_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fst)
]==] },
  fuelSupply = { sig='FuelSupply', aa=[==[
[ENABLE]
alloc(pf_fsu,$1000,$SITE)
label(pf_fsu_ret)
pf_fsu:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+14],0
  pop rax
  jne pf_fsu_ret
  $ORIG
  jmp pf_fsu_ret
$SITE:
  jmp pf_fsu
  $NOP
pf_fsu_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fsu)
]==] },
  fuelVehicle = { sig='FuelVehicle', aa=[==[
[ENABLE]
alloc(pf_fve,$1000,$SITE)
label(pf_fve_skip)
label(pf_fve_ret)
pf_fve:
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+14],0
  pop rax
  jne pf_fve_skip
  subss xmm0,xmm7
pf_fve_skip:
  movaps xmm7,[rsp+30]
  jmp pf_fve_ret
$SITE:
  jmp pf_fve
  $NOP
pf_fve_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fve)
]==] },
  -- sticker: every world-map sticker the player places is copied to pfVars+80 (FVector, 3 doubles) and the
  -- counter dword pfVars+A0 is incremented (the Lua timer teleports the player there while the feature is on)
  sticker = { sig='StickerAdd', aa=[==[
[ENABLE]
alloc(pf_stk,$1000,$SITE)
label(pf_stk_ret)
pf_stk:
  pushfq
  push rax
  push rcx
  mov rax,pfFlags
  mov rcx,[rdx]
  mov [rax+180],rcx
  mov rcx,[rdx+8]
  mov [rax+188],rcx
  mov rcx,[rdx+10]
  mov [rax+190],rcx
  lock inc dword ptr [rax+1A0]
  pop rcx
  pop rax
  popfq
  $ORIG
  jmp pf_stk_ret
$SITE:
  jmp pf_stk
  $NOP
pf_stk_ret:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_stk)
]==] },
  peCall = { sig='ProcessEvent', aa=[==[
[ENABLE]
alloc(pf_pe,$1000,$SITE)
label(pf_pe_orig)
label(pf_pe_ret)
label(pf_pe_skip)
label(pf_pe_c2)
label(pf_pe_take)
label(pf_pe_bad)
pf_pe:
  push rax
  push rcx
  push rdx
  push r8
  mov rax,pfFlags
  cmp byte ptr [rax+10],1
  jne pf_pe_skip
  // run requests on the game thread only (gs:[48] = current thread id)
  db 65 44 8B 04 25 48 00 00 00
  cmp r8d,[rax+168]
  jne pf_pe_skip
  mov r8,[rax+150]
  test r8,r8
  je pf_pe_c2
  cmp rcx,r8
  jne pf_pe_skip
pf_pe_c2:
  mov r8,[rax+158]
  test r8,r8
  je pf_pe_take
  cmp rdx,r8
  jne pf_pe_skip
pf_pe_take:
  mov rcx,rax
  mov al,1
  mov dl,2
  lock cmpxchg byte ptr [rcx+10],dl
  jne pf_pe_skip
  pop r8
  pop rdx
  pop rcx
  pop rax
  push rax
  push rcx
  push rdx
  push r8
  push r9
  sub rsp,20
  mov rax,pfFlags
  cmp qword ptr [rax+140],0
  je pf_pe_bad
  cmp qword ptr [rax+148],0
  je pf_pe_bad
  mov rcx,[rax+140]
  mov rdx,[rax+148]
  lea r8,[rax+300]
  call $SITE
pf_pe_bad:
  mov rax,pfFlags
  mov byte ptr [rax+10],0
  add rsp,20
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  jmp pf_pe_orig
pf_pe_skip:
  pop r8
  pop rdx
  pop rcx
  pop rax
pf_pe_orig:
  $ORIG
  jmp pf_pe_ret
$SITE:
  jmp pf_pe
  $NOP
pf_pe_ret:
[DISABLE]
$SITE:
  $ORIG
// Keep the call-gate allocation until process exit for in-flight calls.
]==] },
}

----------------------------------------------------------------- [GAME] parameter defaults (pfVars)
PF.VARDEF = {
  [0x00] = { 'float', 100.0 },  -- Health     lock value (% of MaxHealth)
  [0x04] = { 'float', 100.0 },  -- Stamina    lock value (% of MaxStamina)
  [0x08] = { 'float', 100.0 },  -- Hunger     lock value (% of MaxHunger)
  [0x0C] = { 'float', 100.0 },  -- Energy     lock value (% of MaxEnergy)
  [0x10] = { 'float', 100.0 },  -- BodyWarmth lock value (% of MaxBodyWarmth)
  [0x20] = { 'float', 2.0 },    -- movement speed multiplier
  [0x24] = { 'float', 1.5 },    -- jump height multiplier
  [0x28] = { 'float', 5.0 },    -- skill experience multiplier
  [0x2C] = { 'float', 12.0 },   -- time of day (hour 0..23.99)
}

----------------------------------------------------------------- [GAME] features
-- key = { hooks={'hookName',...}, flag=n (byte pfFlags+n), task=function() (timer, while on),
--         on=function(), off=function() }
-- (defined below, after the UE reflection helper)
PF.F = {}

----------------------------------------------------------------- [GAME] pointer slots (pfPtrs), refreshed by the timer
-- Not used: value rows of this game are created at run time (lists), because offsets come from reflection.
PF.PTRS = {}

----------------------------------------------------------------- [GAME] called once per attach (after init)
function PF.onAttach()
  PF.itemCands={} PF.itemCandidatePid=nil PF.txt={}
  PF.coreScanCache={}
  for _,name in ipairs({'GNames','GObjects','GWorld'})do PF.A[name]=nil;PF.pend[name]=nil end
  PF.UE.reset()
  PF.P=nil
  return PF.UE.init()
end

----------------------------------------------------------------- [GAME] record names (ID -&gt; {en, ja})
-- PF.NAMES is generated together with the record tree (see the end of this script).


--=====================================================================================
--  COMMON PART  (no change needed per game)
--=====================================================================================
PF.A      = PF.A or {}      -- resolved signature addresses
PF.pend   = PF.pend or {}   -- unresolved signatures
PF.hookState = PF.hookState or {}
PF.featOn = PF.featOn or {}
PF.dyn    = PF.dyn or {}    -- dynamic records {mr,en,ja}
PF.suffix = PF.suffix or {} -- record ID -&gt; text appended to its name

----------------------------------------------------------------- helpers
local function rq(a) if not a or a==0 then return nil end local v=readQword(a) if not v or v==0 then return nil end return v end
local function ri(a) if not a or a==0 then return nil end local v=readInteger(a) if v and v&gt;=0x80000000 then v=v-0x100000000 end return v end
local function rf(a) if not a or a==0 then return nil end return readFloat(a) end
PF.rq, PF.ri, PF.rf = rq, ri, rf
function PF.T(en,ja) if PF.lang=='ja' then return ja or en end return en end
function PF.msg(en,ja) print('['..PF.TAG..'] '..PF.T(en,ja)) end
function PF.err(en,ja) error(PF.T(en,ja),0) end
local function hex(n) return string.format('%X',n) end

function PF.mod(name) return getAddressSafe(name or PF.MODULE) end
function PF.modSize(name) local ok,s=pcall(getModuleSize,name or PF.MODULE) return ok and s or nil end
function PF.base()
  local pid=getOpenedProcessID()
  if PF.memPid==pid and PF.memBase and readBytes(PF.memBase,1)~=nil then return PF.memBase end
  if PF.memPid and PF.memPid~=pid then return nil end
  local a=getAddressSafe('pfFlags')
  if a and readBytes(a,1)~=nil then PF.memBase=a PF.memPid=pid return a end
  return nil
end
function PF.flag(i)
  local b=PF.base()
  if not b then PF.err('Table memory is unavailable. Run ATTACH / ALL OFF again.','CTの共有メモリが未初期化です。アタッチ／一括解除を再実行してください。') end
  return b+i
end
function PF.var(o) return PF.flag(PF.OFF_VARS+o) end


----------------------------------------------------------------- one-shot / user action
-- run fn, show errors, then uncheck the record (action rows)
function PF.userRun(fn)
  local ok,e=pcall(fn)
  if not ok then local m=tostring(e) print('['..PF.TAG..'] '..m) pcall(showMessage,m) end
  return ok
end
function PF.oneShot(mr, fn)
  PF.userRun(fn)
  local t=createTimer(nil,false) t.Interval=150
  t.OnTimer=function(tt) tt.destroy() pcall(function() mr.Active=false end) end
  t.Enabled=true
end

----------------------------------------------------------------- attach / init
function PF.attached() return PF.pid~=nil and PF.pid==getOpenedProcessID() and PF.base()~=nil end
function PF.require()
  if not PF.attached() then
    PF.err('Not attached to '..PF.EXE..'. Run [ATTACH / ALL OFF] at the top of the table first.',
           PF.EXE..'にアタッチされていません。先にテーブル先頭の【アタッチ／一括解除】を実行してください。')
  end
end
-- attach CE to the game; returns true when the opened process changed
function PF.attachGame()
  local pid=getProcessIDFromProcessName(PF.EXE)
  if not pid or pid==0 then PF.err('The game is not running: '..PF.EXE,'ゲームが起動していません: '..PF.EXE) end
  local changed=false
  if getOpenedProcessID()~=pid then
    openProcess(pid) changed=true
    PF.msg(('Attached to %s (PID %d).'):format(PF.EXE,pid),('%s（PID %d）にアタッチしました。'):format(PF.EXE,pid))
  end
  if not PF.mod() then pcall(reinitializeSymbolhandler,true) end
  if not PF.mod() then PF.err(PF.MODULE..' is not loaded yet. Wait until the title screen and try again.',
                              PF.MODULE..' がまだ読み込まれていません。タイトル画面まで待ってから再実行してください。') end
  return changed
end
-- state of an old process: drop it without touching the new one
function PF.forgetProcess()
  PF.hookState={} PF.featOn={} PF.A={} PF.pend={}
  PF.memBase=nil PF.memPid=nil PF.scanRetry={} PF.resolvePid=nil
  if PF.sl then PF.sl.col={} PF.sl.pos=0 end
  PF.pid=nil
end
function PF.checkBuild()
  if not PF.BUILD then return true end
  local m=PF.mod(); local lf=ri(m+0x3C); local ts=lf and readInteger(m+lf+8)
  local sz=PF.modSize()
  if ts~=PF.BUILD.ts or (PF.BUILD.size and sz~=PF.BUILD.size) then
    PF.msg(('WARNING: different game build (timestamp %s, size %s). Made for v%s. Features whose code is not found are disabled.'):format(hex(ts or 0),hex(sz or 0),PF.GAMEVER),
           ('警告: 対応ビルドと異なります（タイムスタンプ %s、サイズ %s）。対応バージョンは v%s です。コードが見つからない機能は無効になります。'):format(hex(ts or 0),hex(sz or 0),PF.GAMEVER))
    return false
  end
  return true
end
function PF.init()
  if PF.initializing then PF.err('Attachment is already in progress.','アタッチ処理中です。完了をお待ちください。') end
  PF.initializing=true
  local ok,result=pcall(function()
    local pid=getOpenedProcessID()
    if PF.pid==pid and PF.base() and PF.UE.ready and PF.UE.pid==pid then PF.startTimer() return true end
    if PF.memPid~=pid and PF.pid~=pid then
      PF.forgetProcess()
      for _,name in ipairs({'pfFlags','pfVars','pfPtrs','pf_mem'}) do pcall(unregisterSymbol,name) end
    end
    local mem=PF.base()
    if not mem then
      for _,name in ipairs({'pfFlags','pfVars','pfPtrs','pf_mem'}) do pcall(unregisterSymbol,name) end
      if PF.mod() and autoAssemble(('alloc(pf_mem,$1000,%X)\nregistersymbol(pf_mem)\n'):format(PF.mod())) then mem=getAddressSafe('pf_mem') end
      if not mem then local good,a=pcall(allocateMemory,0x1000) if good then mem=a end end
      if not mem or mem==0 then PF.err('Memory allocation failed.','メモリ確保に失敗しました。') end
      PF.memBase=mem PF.memPid=pid
      registerSymbol('pfFlags',mem,true) registerSymbol('pfVars',mem+PF.OFF_VARS,true) registerSymbol('pfPtrs',mem+PF.OFF_PTRS,true)
      for o,d in pairs(PF.VARDEF) do
        if d[1]=='float' then writeFloat(PF.var(o),d[2]) elseif d[1]=='qword' then writeQword(PF.var(o),d[2]) else writeInteger(PF.var(o),d[2]) end
      end
    end
    PF.checkBuild()
    local coreStart=getTickCount()
    PF.onAttach() -- Propagate a failed core initialization.
    PF.msg(('UE initialization: %d ms.'):format(getTickCount()-coreStart),('UE初期化: %d ms。'):format(getTickCount()-coreStart))
    PF.msg('Attach ready: UE core only; feature code is resolved on demand.','アタッチ準備完了: UE基幹のみ取得。各機能のコードは有効化時に取得します。')
    PF.pid=pid
    PF.startTimer()
    return true
  end)
  PF.initializing=false
  if not ok then
    PF.pid=nil
    if PF.timer then PF.timer.Enabled=false end
    error(result,0)
  end
  return result
end

----------------------------------------------------------------- AOB resolver (synchronous aobscanregion)
local function aaFind(pat, s, e)
  pcall(unregisterSymbol,'pf_tmp')
  local ok=autoAssemble(('aobscanregion(pf_tmp,%s,%s,%s)\nregistersymbol(pf_tmp)\n'):format(hex(s),hex(e),pat))
  if not ok then return nil end
  local a=getAddressSafe('pf_tmp') pcall(unregisterSymbol,'pf_tmp')
  return a
end

-- Validate the meaning of variable call operands, not their build-specific displacement.
function PF.validateCallSite(name,a,m,sz,known)
  local sg=PF.SIGS[name]
  local site=a+(sg.off or 0)
  if readBytes(site,1)~=0xE8 then return false end
  local d=readInteger(site+1)
  if not d then return false end
  if d&gt;=0x80000000 then d=d-0x100000000 end
  local target=site+5+d
  if target&lt;m or target+3&gt;m+sz then return false end
  if name~='BuildDeduce' then return target==PF.resolveSig('ItemConsume') end
  local b=readBytes(target,3,true)
  if not b or b[1]~=0xB0 or b[2]~=1 or b[3]~=0xC3 then return false end
  return true
end

function PF.findValidatedSite(name,pattern,m,sz,find)
  if name=='BuildDeduce' then
    -- Inspect a bounded native-field area in the exact reflected UFunction.
    -- Do not assume a fixed native-pointer offset or scan the whole module.
    local u=PF.UE
    if not u or not u.gobj then return nil end
    local result,seen=nil,{}
    local length=0 for _ in pattern:gmatch('%S+') do length=length+1 end
    for i=0,u.count()-1 do
      local f=u.objAt(i)
      if f and u.objName(f)=='GetShouldDeduceCost' and u.isFunc(f,'GetShouldDeduceCost') then
        local owner=u.outer(f)
        if owner and u.objName(owner)=='PlayerBuildingComponent' and u.clsName(u.cls(owner))=='Class' then
          for off=0xB8,0x100,8 do
            local a=readQword(f+off)
            if a and a&gt;=m and a+length&lt;=m+sz and not seen[a] then
              seen[a]=true
              if find(pattern,a,a+length)==a and PF.validateCallSite(name,a,m,sz,true) then
                if result then return nil end
                result=a
              end
            end
          end
        end
      end
    end
    return result
  end
  local result,count,pos=nil,0,m
  while pos&lt;m+sz do
    local a=find(pattern,pos,m+sz)
    if not a then break end
    count=count+1
    if count&gt;64 or a&lt;pos or a&gt;=m+sz then return nil end
    if PF.validateCallSite(name,a,m,sz,false) then
      if result then return nil end -- Ambiguous: never take the first candidate.
      result=a
    end
    pos=a+1
  end
  return result
end

function PF.resolveSig(name)
  local pid=getOpenedProcessID()
  if PF.resolvePid and PF.resolvePid~=pid then PF.A={} PF.pend={} PF.scanRetry={} end
  PF.resolvePid=pid
  if (name=='GNames' or name=='GObjects' or name=='GWorld') and PF.UE and PF.UE.resolveCoreSig then
    local a=PF.UE.resolveCoreSig(name)
    if a then pcall(unregisterSymbol,'pfA_'..name);registerSymbol('pfA_'..name,a,true) end
    return a
  end
  if PF.A[name] then return PF.A[name] end
  local sg=PF.SIGS[name]; if not sg then PF.err('Unknown signature: '..name,'未定義のシグネチャ: '..name) end
  local started=getTickCount()
  local m=PF.mod(sg.mod); local sz=PF.modSize(sg.mod)
  local lf=m and readInteger(m+0x3C)
  local expected=lf and readInteger(m+lf+8)==PF.BUILD.ts and sz==PF.BUILD.size
  local a
  if expected then
    -- Known-build sites are validated locally, never sent to a broad fallback scan.
    local rva=PF.RVA[name]
    if rva then
      local candidate=m+rva-(sg.off or 0)
      local tokens={} for t in sg.p:gmatch('%S+') do tokens[#tokens+1]=t end
      local bytes=readBytes(candidate,#tokens,true)
      local matches=bytes and #bytes==#tokens
      if matches then
        for i,t in ipairs(tokens) do
          local wanted=tonumber(t,16)
          if wanted and bytes[i]~=wanted then matches=false break end
        end
      end
      if matches and (not sg.validateCall or PF.validateCallSite(name,candidate,m,sz,true)) then a=candidate end
    end
    if not a then
      PF.pend[name]=true
      PF.msg('Known code validation failed: '..name..'. No automatic scan was run.',
             '既知コードの検証に失敗: '..name..'。自動スキャンは実行していません。')
      return nil
    end
  elseif m and sz then
    -- Other builds: search only this module, once per distinct pattern.
    PF.scanRetry=PF.scanRetry or {}
    local last=PF.scanRetry[name]
    if last and started&gt;=last and started-last&lt;10000 then return nil end
    local seen={}
    for _,pattern in ipairs({sg.p,table.unpack(sg.alt or {})}) do
      if not seen[pattern] then
        seen[pattern]=true
        if sg.validateCall then a=PF.findValidatedSite(name,pattern,m,sz,aaFind) else a=aaFind(pattern,m,m+sz) end
        if a then break end
      end
    end
    if not a then PF.scanRetry[name]=getTickCount() end
  end
  local elapsed=getTickCount()-started
  if elapsed&gt;=100 then PF.msg(('Signature %s: %d ms.'):format(name,elapsed),('シグネチャ %s: %d ms。'):format(name,elapsed)) end
  if not a then PF.pend[name]=true return nil end
  a=a+(sg.off or 0)
  PF.A[name]=a PF.pend[name]=nil
  if PF.scanRetry then PF.scanRetry[name]=nil end
  pcall(unregisterSymbol,'pfA_'..name) registerSymbol('pfA_'..name,a,true)
  return a
end



----------------------------------------------------------------- hook manager
function PF.hookOn(name)
  if PF.hookState[name] then return end
  local h=PF.HOOKS[name] or PF.err('Unknown hook: '..name,'未定義のフック: '..name)
  local a=PF.resolveSig(h.sig)
  if not a then PF.err('Game code for this feature was not found: '..h.sig..'\n(it may not be loaded yet, or the game was updated)',
                       'この機能に必要なゲームコードが見つかりません: '..h.sig..'\n（未読み込み、またはゲーム更新で変更された可能性があります）') end
  local len=PF.SIGS[h.sig].len or 5
  local orig=readBytes(a,len,true) or PF.err('Cannot read hook site.','フック位置を読み取れません。')
  local db={} for i,b in ipairs(orig) do db[i]=string.format('%02X',b) end
  local s=h.aa:gsub('%$SITE',hex(a)):gsub('%$ORIG','db '..table.concat(db,' '))
  s=s:gsub('%$NOP', len&gt;5 and ('nop '..(len-5)) or '')
  local b=PF.base()
  if not b then PF.err('Table memory is unavailable. Run ATTACH / ALL OFF.','CTの共有メモリが未初期化です。アタッチ／一括解除を実行してください。') end
  s=s:gsub('%f[%w_]pfFlags%f[^%w_]',hex(b)):gsub('%f[%w_]pfVars%f[^%w_]',hex(b+PF.OFF_VARS)):gsub('%f[%w_]pfPtrs%f[^%w_]',hex(b+PF.OFF_PTRS))
  local ok,info=autoAssemble(s)
  if not ok then PF.err('Hook assembly failed: '..name..'\n'..tostring(info),'フックの組み立てに失敗: '..name..'\n'..tostring(info)) end
  PF.hookState[name]={script=s, info=info, addr=a, orig=orig}
end
function PF.hookOff(name)
  local st=PF.hookState[name]; if not st then return end
  if PF.attached() then
    local ok=autoAssemble(st.script, st.info)
    if not ok then writeBytes(st.addr, st.orig) end   -- fallback: restore original bytes
  end
  PF.hookState[name]=nil
end

----------------------------------------------------------------- features
function PF.feature(key, on)
  local f=PF.F[key] or PF.err('Unknown feature: '..key,'未定義の機能: '..key)
  if on then
    PF.require()
    local added={}
    local ok,err=pcall(function()
      for _,h in ipairs(f.hooks or {}) do
        local existed=PF.hookState[h]~=nil
        PF.hookOn(h)
        if not existed then added[#added+1]=h end
      end
      if f.flag then writeBytes(PF.flag(f.flag),1) end
      if f.on then f.on() end
    end)
    if not ok then
      if f.flag and PF.base() then writeBytes(PF.flag(f.flag),0) end
      if f.off then pcall(f.off) end
      for i=#added,1,-1 do pcall(PF.hookOff,added[i]) end
      PF.featOn[key]=nil
      error(err,0)
    end
    PF.featOn[key]=true
  else
    PF.featOn[key]=nil
    if not PF.attached() then return end
    if f.flag then writeBytes(PF.flag(f.flag),0) end
    if f.off then pcall(f.off) end
    for _,h in ipairs(f.hooks or {}) do
      local used=false
      for k in pairs(PF.featOn) do for _,x in ipairs(PF.F[k].hooks or {}) do if x==h then used=true end end end
      if not used then PF.hookOff(h) end
    end
  end
end

----------------------------------------------------------------- timer (pointer slots, tasks, process watch)
function PF.tick()
  if PF.initializing or not PF.pid then return end
  if getOpenedProcessID()~=PF.pid or getProcessIDFromProcessName(PF.EXE)~=PF.pid then
    PF.msg('Game process changed or exited. Run [ATTACH / ALL OFF] again.','ゲームプロセスが変わったか終了しました。【アタッチ／一括解除】を再実行してください。')
    PF.forgetProcess() return
  end
  local b=PF.base(); if not b then return end
  for slot,fn in pairs(PF.PTRS) do local ok,a=pcall(fn) writeQword(b+PF.OFF_PTRS+slot*8, (ok and a) or 0) end
  for k in pairs(PF.featOn) do
    local f=PF.F[k]
    if f.task then pcall(f.task) end
  end
  -- Failed lookups retry only when explicitly requested; never scan from the timer.
  if PF.sliceStep then pcall(PF.sliceStep) end
end
function PF.startTimer()
  if PF.timer then PF.timer.Enabled=true return end
  PF.timer=createTimer(nil,false) PF.timer.Interval=PF.TICK_MS
  PF.timer.OnTimer=function() pcall(PF.tick) end
  PF.timer.Enabled=true
end

----------------------------------------------------------------- ATTACH / ALL OFF
function PF.disableAll(self)
  local ok,changed=pcall(PF.attachGame)
  if not ok then print('['..PF.TAG..'] '..tostring(changed)) pcall(showMessage,tostring(changed)) return end
  if changed or (PF.pid and PF.pid~=getOpenedProcessID()) then PF.forgetProcess() end
  local okI,e=pcall(PF.init) if not okI then print('['..PF.TAG..'] '..tostring(e)) pcall(showMessage,tostring(e)) return end
  local al=getAddressList(); local n=0
  for i=al.Count-1,0,-1 do
    local m=al.getMemoryRecord(i)
    if m.Active and not (self and m.ID==self.ID) then pcall(function() m.Active=false end) n=n+1 end
  end
  if PF.featOn.emergencyEscape then PF.feature('emergencyEscape',false) end
  local r=0 for name in pairs(PF.hookState) do PF.hookOff(name) r=r+1 end
  for i=0,0xFF do writeBytes(PF.flag(i),0) end
  PF.featOn={}
  PF.msg(('Attach / All OFF: %d records deactivated, %d hooks restored.'):format(n,r),
         ('アタッチ／一括解除: %d件を無効化、%d件のフックを元に戻しました。'):format(n,r))
end

----------------------------------------------------------------- UI helpers
function PF.askInt(title, prompt, def, lo, hi)
  local s=inputQuery(title, prompt, tostring(def or 0)); if not s then return nil end
  local v=tonumber(s)
  if not v or v%1~=0 or (lo and v&lt;lo) or (hi and v&gt;hi) then PF.err('Invalid number: '..s,'不正な数値です: '..s) end
  return v
end
-- dynamic records (lists built at run time)
function PF.clearChildren(mr) while mr.Count&gt;0 do mr.Child[0].destroy() end end
function PF.addHdr(parent, en, ja)
  local m=getAddressList().createMemoryRecord()
  m.IsGroupHeader=true m.Description=PF.T(en,ja) m.Color=PF.C_GROUP m.appendToEntry(parent) m.DontSave=true
  PF.dyn[#PF.dyn+1]={mr=m,en=en,ja=ja} return m
end
function PF.addRec(parent, en, ja, addr, vt)
  local m=getAddressList().createMemoryRecord()
  m.Description=PF.T(en,ja) m.Type=vt or vtDword m.Address=addr m.appendToEntry(parent) m.DontSave=true
  PF.dyn[#PF.dyn+1]={mr=m,en=en,ja=ja} return m
end

----------------------------------------------------------------- language
function PF.applyLang()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i); local n=PF.NAMES[m.ID]
    if n then local d=(PF.lang=='ja') and n[2] or n[1]
      if PF.suffix[m.ID] then d=d..' : '..PF.suffix[m.ID] end
      m.Description=d end
  end
  local keep={}
  for _,e in ipairs(PF.dyn) do if pcall(function() e.mr.Description=PF.T(e.en,e.ja) end) then keep[#keep+1]=e end end
  PF.dyn=keep
end
function PF.setLang(l) PF.lang=l PF.applyLang() end

----------------------------------------------------------------- [GAME] rip-relative data reference of a signature
function PF.ripTarget(name)
  local a=PF.resolveSig(name); if not a then return nil end
  local sg=PF.SIGS[name]; local d=PF.ri(a+sg.disp); if not d then return nil end
  return a+sg.len+d
end

----------------------------------------------------------------- [GAME] Unreal Engine 5.4 reflection helper (PF.UE)
-- Object layout (UObjectBase): +0C InternalIndex, +10 ClassPrivate, +18 NamePrivate(FName), +20 OuterPrivate
-- FName = ComparisonIndex(u32) + Number(u32). FNamePool: Blocks[] at +10, stride 2, header u16 (bit0 wide, len = h&gt;&gt;6)
-- UStruct.SuperStruct / ChildProperties and FField.Next / NamePrivate offsets are detected at run time.
PF.UE = PF.UE or {}
local UE = PF.UE
local rq, ri = PF.rq, PF.ri
UE.O = { objIndex=0x0C, objClass=0x10, objName=0x18, objOuter=0x20, itemSize=0x18, chunk=0x10000, poolBlocks=0x10, fClass=0x08 }

function UE.reset()
  UE.gnames=nil UE.gobj=nil UE.gworld=nil
  UE.ready=false UE.pid=nil UE.nameCache={} UE.clsNameCache={} UE.propCache={} UE.structCache={} UE.funcCache={} UE.funcResolved={}
  UE.O.super=nil UE.O.childProps=nil UE.O.fNext=nil UE.O.fName=nil UE.O.sStruct=nil
end
UE.reset()

function UE.name(id)
  if not id then return nil end
  local c=UE.nameCache[id]; if c then return c end
  local blk=id&gt;&gt;16; local off=(id&amp;0xFFFF)*2
  local b=rq(UE.gnames+UE.O.poolBlocks+blk*8); if not b then return nil end
  local hb=readBytes(b+off,2,true); if not hb then return nil end
  local h=hb[1]+hb[2]*256; local len=h&gt;&gt;6
  if len&lt;=0 or len&gt;1023 then return nil end
  -- read exactly len characters (CE readString may return one extra character, so bytes are decoded here)
  local wide=(h&amp;1)==1
  local bt=readBytes(b+off+2, wide and len*2 or len, true); if not bt then return nil end
  local s
  if wide then
    local t={} for i=1,#bt-1,2 do local c=bt[i]+bt[i+1]*256 t[#t+1]=(c&lt;0xD800 or c&gt;0xDFFF) and utf8.char(c) or '?' end
    s=table.concat(t)
  else s=string.char(table.unpack(bt)) end
  if #s==0 then return nil end
  UE.nameCache[id]=s
  return s
end
function UE.fname(addr)
  local id=readInteger(addr); local n=readInteger(addr+4)
  local s=UE.name(id); if not s then return nil end
  if n and n&gt;0 and n&lt;0x10000 then s=s..'_'..(n-1) end
  return s
end

-- GUObjectArray
function UE.count() return (UE.gobj and ri(UE.gobj+0x14)) or 0 end
function UE.objAt(i)
  local chunks=rq(UE.gobj); if not chunks then return nil end
  local ch=rq(chunks+(i//UE.O.chunk)*8); if not ch then return nil end
  return rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
end
function UE.isObj(o)
  if not o or o&lt;0x10000 or o&gt;0x7FFFFFFFFFFF then return false end
  local i=ri(o+UE.O.objIndex); if not i or i&lt;0 or i&gt;=UE.count() then return false end
  return UE.objAt(i)==o
end
function UE.cls(o) if not o then return nil end return rq(o+UE.O.objClass) end

----------------------------------------------------------------- periodic object search, a little per timer tick
-- Full searches of GUObjectArray take ~0.7 s each (about 220,000 objects) and froze Cheat Engine when they ran
-- every 15-20 s. Periodic refreshes are now done here: one shared search for all features, a slice of about
-- 30 ms per timer tick, the next search 10 s after the previous one ends. (Enabling a feature still searches once.)
PF.sl = PF.sl or { col={}, pos=0, per=2000, passes=0 }
PF.SLICE_S = 0.020
function PF.sliceAdd(key, clsTest, objTest, done)
  PF.sl.col[key]={ clsTest=clsTest, objTest=objTest, done=done, seen={}, acc={} }
end
function PF.sliceDel(key) PF.sl.col[key]=nil end
function PF.sliceStep()
  local S=PF.sl
  if next(S.col)==nil then S.pos=0 return end
  if not UE.ready or not UE.gobj then return end
  if S.pos==0 then
    if S.wait and os.clock()&lt;S.wait then return end
    for _,c in pairs(S.col) do c.acc={} c.full=true if S.passes%10==0 then c.seen={} end end
  end
  local chunks=rq(UE.gobj); if not chunks then return end
  local n=UE.count(); local CH,IS=UE.O.chunk,UE.O.itemSize
  local t0=os.clock()
  local i=S.pos; local stop=math.min(n, i+S.per)
  local ci,ch=-1,nil
  while i&lt;stop do
    if (i&amp;255)==0 and os.clock()-t0&gt;PF.SLICE_S then break end   -- time limit inside the slice too
    local c=i//CH
    if c~=ci then ch=rq(chunks+c*8) ci=c end
    local o=ch and rq(ch+(i%CH)*IS)
    local k=o and rq(o+UE.O.objClass)
    if k then
      for _,col in pairs(S.col) do
        local h=col.seen[k]
        if h==nil then local ok,v=pcall(col.clsTest,k) h=(ok and v) and true or false col.seen[k]=h end
        if h then local ok,it=pcall(col.objTest,o,k) if ok and it then col.acc[#col.acc+1]=it end end
      end
    end
    i=i+1
  end
  local dt=os.clock()-t0
  if dt&gt;0.001 then S.per=math.max(500, math.min(20000, math.floor(S.per*PF.SLICE_S/dt))) else S.per=math.min(20000,S.per*2) end
  S.pos=i
  if i&gt;=n then
    for _,c in pairs(S.col) do if c.full then pcall(c.done, c.acc) end c.acc={} c.full=nil end   -- added mid-search: wait for a full one
    S.pos=0 S.wait=os.clock()+10 S.passes=S.passes+1
  end
end
function UE.outer(o) if not o then return nil end return rq(o+UE.O.objOuter) end
function UE.objName(o) if not o then return '?' end return UE.fname(o+UE.O.objName) or '?' end
function UE.clsName(c)
  if not c then return nil end
  local n=UE.clsNameCache[c]; if n then return n end
  n=UE.fname(c+UE.O.objName); if n then UE.clsNameCache[c]=n end
  return n
end
function UE.super(c) return rq(c+UE.O.super) end
function UE.isA(o, cname)
  local c=UE.cls(o) local n=0
  while c and n&lt;64 do if UE.clsName(c)==cname then return true end c=UE.super(c) n=n+1 end
  return false
end
function UE.fullName(o)
  local s=UE.objName(o) local p=UE.outer(o) local n=0
  while p and n&lt;8 do s=UE.objName(p)..'.'..s p=UE.outer(p) n=n+1 end
  return (UE.clsName(UE.cls(o)) or '?')..' '..s
end

-- run-time detection of UStruct / FField layouts
local function detectSuper(c)
  for _,off in ipairs({0x40,0x30,0x38,0x48}) do
    local x=c local ok=false
    for _=1,32 do
      local s=rq(x+off)
      if not s then ok=(UE.clsName(x)=='Object') break end
      if not UE.isObj(s) then break end
      x=s
    end
    if ok then return off end
  end
end
local function fieldOK(p, nxt, nm)
  local n=0
  while p and n&lt;6 do
    local s=UE.fname(p+nm); local fc=rq(p+UE.O.fClass)
    local k=fc and UE.fname(fc)
    if not s or not s:match('^[%w_]+$') or not k or not k:match('Property$') then return false end
    p=rq(p+nxt) n=n+1
  end
  return n&gt;0
end
-- UE bootstrap: validate referenced DATA, deduplicate references, never take the first AOB hit.
function UE.coreName(pool,id)
  if not pool or not id or id&lt;0 then return nil end
  local block=rq(pool+UE.O.poolBlocks+(id&gt;&gt;16)*8)
  local entry=block and block+(id&amp;0xFFFF)*2
  local h=entry and readSmallInteger(entry)
  if not h then return nil end
  h=h&amp;0xFFFF
  local n=h&gt;&gt;6
  if n&lt;1 or n&gt;1023 then return nil end
  local bytes=readBytes(entry+2,n*((h&amp;1)+1),true)
  if not bytes then return nil end
  if (h&amp;1)==0 then return string.char(table.unpack(bytes)) end
  local out={} for i=1,#bytes,2 do local c=bytes[i]+bytes[i+1]*256;if c&gt;=0xD800 and c&lt;=0xDFFF then return nil end;out[#out+1]=utf8.char(c) end
  return table.concat(out)
end
function UE.coreObject(array,index)
  local n=array and ri(array+0x14)
  if not n or index&lt;0 or index&gt;=n then return nil end
  local chunks=rq(array);local chunk=chunks and rq(chunks+(index//UE.O.chunk)*8)
  return chunk and rq(chunk+(index%UE.O.chunk)*UE.O.itemSize)
end
function UE.coreDataValid(name,target)
  if not target or target&lt;0x10000 then return false end
  if name=='GNames' then return UE.coreName(target,0)=='None' end
  if name=='GObjects' then
    local n,max=ri(target+0x14),ri(target+0x10)
    if not n or not max or n&lt;8 or n&gt;10000000 or max&lt;n or max&gt;20000000 then return false end
    local checked=0
    for i=0,7 do
      local o=UE.coreObject(target,i)
      if o then
        if ri(o+UE.O.objIndex)~=i then return false end
        local c=rq(o+UE.O.objClass);local ci=c and ri(c+UE.O.objIndex)
        if not c or not ci or UE.coreObject(target,ci)~=c then return false end
        local cn=UE.coreName(UE.gnames,ri(c+UE.O.objName))
        if not cn or not cn:match('^[%w_]+$') or cn=='None' then return false end
        checked=checked+1
      end
    end
    return checked&gt;=2
  end
  if name=='GWorld' then
    local o=rq(target);local index=o and ri(o+UE.O.objIndex)
    if not index or UE.coreObject(UE.gobj,index)~=o then return false end
    local c=rq(o+UE.O.objClass)
    return c and UE.coreName(UE.gnames,ri(c+UE.O.objName))=='World' or false
  end
  return false
end
function UE.coreMatches(a,pattern)
  local tokens={} for t in pattern:gmatch('%S+') do tokens[#tokens+1]=t end
  local bytes=readBytes(a,#tokens,true)
  if not bytes or #bytes~=#tokens then return false end
  for i,t in ipairs(tokens) do if t~='??' and tonumber(t,16)~=bytes[i] then return false end end
  return true
end
function UE.coreScan(pattern,base,size)
  local metrics=UE.bootstrapMetrics
  if metrics and getTickCount()-metrics.started&gt;1200 then error('UE core search budget exceeded; update this CT instead of running a full module scan',0) end
  if metrics then metrics.scans=metrics.scans+1;metrics.bytes=metrics.bytes+size end
  local scan=createMemScan();local found
  local ok,result=xpcall(function()
    scan.firstScan(soExactValue,vtByteArray,rtRounded,pattern,'',base,base+size-1,'+X',fsmNotAligned,'',true,false,false,false)
    scan.waitTillDone();found=createFoundList(scan);found.initialize()
    assert(found.Count&lt;=4096,'UE core signature is too broad; refusing ambiguous scan')
    local hits={}for i=0,found.Count-1 do hits[#hits+1]=tonumber(found.Address[i],16)end
    return hits
  end,debug.traceback)
  if found then found.destroy() end;scan.destroy()
  if not ok then error(result,0) end
  return result
end
function UE.resolveCoreSig(name)
  local sg=PF.SIGS[name];local base,size=PF.mod(),PF.modSize()
  if not base or not size then return nil end
  local function validate(site)
    if not site or site&lt;base or site+sg.len&gt;base+size then return nil end
    local d=ri(site+sg.disp);local target=d and site+sg.len+d
    if not target or target&lt;base or target+0x20&gt;base+size then return nil end
    return UE.coreDataValid(name,target) and target or nil
  end
  local function matching(site)
    if not site then return false end
    for _,p in ipairs({sg.p,table.unpack(sg.alt or {})})do if UE.coreMatches(site,p)then return true end end
    return false
  end
  local cached=PF.A[name]
  if matching(cached) and validate(cached) then PF.pend[name]=nil;return cached end
  PF.A[name]=nil
  -- The known location is only a hint; structural validation is always required.
  local hint=PF.RVA[name] and base+PF.RVA[name]
  if matching(hint) and validate(hint) then PF.A[name]=hint;PF.pend[name]=nil;return hint end
  -- Never scan the entire game module on attach. Search a bounded region around the hint.
  if not hint or hint&lt;base or hint&gt;=base+size then PF.pend[name]=true;return nil end
  local start=math.max(base,hint-0x20000)
  local finish=math.min(base+size,hint+0x20000)
  PF.coreScanCache=PF.coreScanCache or {}
  local byTarget={};local hits=0
  for _,pattern in ipairs({sg.p,table.unpack(sg.alt or {})})do
    local key=('%s:%X:%X:%s'):format(tostring(getOpenedProcessID()),start,finish-start,pattern)
    local sites=PF.coreScanCache[key]
    if not sites then sites=UE.coreScan(pattern,start,finish-start);PF.coreScanCache[key]=sites end
    for _,site in ipairs(sites)do
      if UE.coreMatches(site,pattern) then
        local target=validate(site)
        if target then byTarget[target]=byTarget[target] or site end
      end
    end
    -- A complete search of the strongest successful pattern is sufficient.
    if next(byTarget) then break end
  end
  local chosen
  for _,site in pairs(byTarget)do hits=hits+1;chosen=site end
  if hits~=1 then
    PF.pend[name]=true
    if hits&gt;1 then error('UE core ambiguous: '..name..' ('..hits..' distinct valid data targets)',0) end
    return nil
  end
  PF.A[name]=chosen;PF.pend[name]=nil
  PF.msg('UE core recovered by bounded local search: '..name,'UE基幹データを範囲制限付き近傍検索で再検出: '..name)
  return chosen
end

function UE.init()
  if UE.ready and UE.pid==getOpenedProcessID() then return true end
  UE.bootstrapMetrics={started=getTickCount(),scans=0,bytes=0,attempts=0}
  local failure
  for attempt=1,3 do
    UE.bootstrapMetrics.attempts=attempt
    local ok,result=pcall(UE.initAttempt)
    UE.bootstrapMetrics.elapsed=getTickCount()-UE.bootstrapMetrics.started
    if ok and result then UE.lastInitError=nil;return true end
    failure=tostring(result);UE.lastInitError=failure;UE.reset()
    for _,name in ipairs({'GNames','GObjects','GWorld'})do PF.A[name]=nil end
    if failure:find('UE core ambiguous:',1,true) then break end
    if failure:find('UE core search budget exceeded',1,true) then break end
    if attempt&lt;3 then sleep(150) end
  end
  error(failure..PF.T(' [UE initialization failed; no validated core data/layout. Retried up to 3 times.]',' [UE初期化失敗: 基幹データまたはレイアウトの検証不成立。最大3回再試行しました。]'),0)
end
function UE.initAttempt()
  UE.reset()
  UE.gnames=PF.ripTarget('GNames'); UE.gobj=PF.ripTarget('GObjects'); UE.gworld=PF.ripTarget('GWorld')
  if not UE.gnames or not UE.gobj then
    PF.err('UE core validation failed (GNames / GObjects): not ready, unsupported layout, or no valid signature target.',
           'UE基幹データ（GNames／GObjects）の検証不成立: 読み込み途中、未対応レイアウト、または有効な検索候補がありません。')
  end
  local n0=UE.name(0)
  if n0~='None' then PF.err('FNamePool check failed (name #0 is "'..tostring(n0)..'", expected "None").',
                            'FNamePoolの検査に失敗しました（名前#0が"'..tostring(n0)..'"、期待値は"None"）。') end
  if UE.count()&lt;=0 then PF.err('GUObjectArray check failed (no objects).','GUObjectArrayの検査に失敗しました（オブジェクト数0）。') end
  local w=UE.gworld and rq(UE.gworld)
  local probe=(w and UE.isObj(w)) and w or UE.objAt(1)
  local c=probe and UE.cls(probe)
  if not c then PF.err('No object to probe the layout (enter the game first).','レイアウト検査用のオブジェクトがありません（先にゲームに入ってください）。') end
  UE.O.super=detectSuper(c) or PF.err('UStruct layout not recognized (SuperStruct).','UStructのレイアウトを認識できません（SuperStruct）。')
  UE.O.childProps=UE.O.super+0x10
  -- find a class that owns properties to detect FField layout (World / Actor / Engine classes have many)
  local fc=nil local x=c
  for _=1,16 do if x and rq(x+UE.O.childProps) then fc=x break end x=x and UE.super(x) end
  if not fc then PF.err('FField layout probe failed (no properties).','FFieldのレイアウト検査に失敗しました（プロパティなし）。') end
  local p=rq(fc+UE.O.childProps)
  for _,cand in ipairs({{0x20,0x28},{0x18,0x20},{0x28,0x30}}) do
    if fieldOK(p,cand[1],cand[2]) then UE.O.fNext,UE.O.fName=cand[1],cand[2] break end
  end
  if not UE.O.fName then PF.err('FField layout not recognized.','FFieldのレイアウトを認識できません。') end
  UE.pid=getOpenedProcessID() UE.ready=true
  PF.msg(('UE ready: objects=%d, SuperStruct=+%X, FField.Next=+%X, FField.Name=+%X'):format(UE.count(),UE.O.super,UE.O.fNext,UE.O.fName),
         ('UE準備完了: オブジェクト数=%d, SuperStruct=+%X, FField.Next=+%X, FField.Name=+%X'):format(UE.count(),UE.O.super,UE.O.fNext,UE.O.fName))
  return true
end

-- properties: own properties of a UStruct (class or script struct), cached per struct
-- FProperty (relative to FField.Name = N): ArrayDim N+10, ElementSize N+14, PropertyFlags N+18, Offset_Internal N+24
function UE.ownProps(s)
  local r=UE.propCache[s]; if r then return r end
  r={}
  local p=rq(s+UE.O.childProps) local n=0
  while p and n&lt;2000 do
    local N=UE.O.fName
    local fc=rq(p+UE.O.fClass)
    local nm=UE.fname(p+N) or '?'
    r[#r+1]={ f=p, name=nm, lname=nm:lower(), kind=(fc and UE.fname(fc)) or '?',
              off=ri(p+N+0x24) or 0, size=ri(p+N+0x14) or 0 }
    p=rq(p+UE.O.fNext) n=n+1
  end
  UE.propCache[s]=r
  return r
end
function UE.findProp(s, pname)
  local n=0 pname=pname:lower()   -- FName comparison is case-insensitive
  while s and n&lt;64 do
    for _,pr in ipairs(UE.ownProps(s)) do if pr.lname==pname then return pr end end
    s=UE.super(s) n=n+1
  end
end
-- address of property pname of object o (+ property info)
function UE.prop(o, pname)
  if not o then return nil end
  local pr=UE.findProp(UE.cls(o), pname); if not pr then return nil end
  return o+pr.off, pr
end
function UE.getObj(o, pname)
  local a=UE.prop(o,pname); if not a then return nil end
  local v=rq(a); if v and UE.isObj(v) then return v end
end
-- UScriptStruct* of a StructProperty (offset detected once)
function UE.structOf(pr)
  if UE.structCache[pr.f]~=nil then return UE.structCache[pr.f] or nil end
  local res=false
  local function try(off) local s=rq(pr.f+off) if s and UE.isObj(s) and UE.clsName(UE.cls(s))=='ScriptStruct' then return s end end
  if UE.O.sStruct then res=try(UE.O.sStruct) or false
  else for off=UE.O.fName+0x40,UE.O.fName+0x60,8 do local s=try(off) if s then UE.O.sStruct=off res=s break end end end
  UE.structCache[pr.f]=res
  return res or nil
end
-- search property pname inside a struct/class s located at base; descends into StructProperty members
function UE.findIn(s, base, pname, depth)
  local pr=UE.findProp(s,pname); if pr then return base+pr.off, pr end
  if (depth or 0)&lt;=0 then return nil end
  local n=0 local x=s
  while x and n&lt;64 do
    for _,q in ipairs(UE.ownProps(x)) do
      if q.kind=='StructProperty' then
        local st=UE.structOf(q)
        if st then local a,r=UE.findIn(st, base+q.off, pname, depth-1) if a then return a,r end end
      end
    end
    x=UE.super(x) n=n+1
  end
end

-- objects whose Outer chain (up to 3 levels) reaches one of the given parents.
-- Walks GUObjectArray (no memory scan: deterministic; about 2 reads per object, CE pauses ~1-3 s).
function UE.childrenOf(parents)
  local r={}
  local chunks=rq(UE.gobj); if not chunks then return r end
  local set={} for _,p in ipairs(parents) do if p then set[p]=true end end
  local n=UE.count(); local outerOf={}; local list={}
  local ch, ci = nil, -1
  for i=0,n-1 do
    local c=i//UE.O.chunk
    if c~=ci then ch=rq(chunks+c*8) ci=c end
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if o then local ou=rq(o+UE.O.objOuter) if ou then outerOf[o]=ou list[#list+1]=o end end
  end
  for _,o in ipairs(list) do
    local p=outerOf[o] local d=0
    while p and d&lt;3 do if set[p] then r[#r+1]=o break end p=outerOf[p] d=d+1 end
  end
  return r
end
function UE.children(parent) return UE.childrenOf({parent}) end

-- fallback when the GWorld signature is not valid: walk GUObjectArray for the live UWorld (throttled, cached)
function UE.worldSlow()
  local w=UE.wc
  if w and UE.isObj(w) and UE.clsName(UE.cls(w))=='World' and UE.getObj(w,'OwningGameInstance') then return w end
  UE.wc=nil
  local now=os.clock(); if UE.wcT and now-UE.wcT&lt;10 then return nil end
  UE.wcT=now
  local isW={}
  for i=0,UE.count()-1 do
    local o=UE.objAt(i)
    if o then
      local c=UE.cls(o)
      if c then
        local k=isW[c]; if k==nil then k=(UE.clsName(c)=='World') isW[c]=k end
        if k and UE.getObj(o,'OwningGameInstance') then UE.wc=o return o end
      end
    end
  end
end

----------------------------------------------------------------- [GAME] player data
-- GWorld -&gt; OwningGameInstance -&gt; LocalPlayers[0] -&gt; PlayerController -&gt; AcknowledgedPawn / PlayerState
-- Attribute sets (UAttributeSet_*Metrics) are found among the sub-objects of the pawn / player state.
-- GAS attribute = FGameplayAttributeData (0x10): +08 BaseValue (float), +0C CurrentValue (float)
local function chain()
  if not PF.attached() then return nil end
  if not UE.ready then local ok=pcall(UE.init) if not ok then return nil end end
  local w=UE.gworld and rq(UE.gworld)
  if not (w and UE.isObj(w) and UE.clsName(UE.cls(w))=='World') then w=UE.worldSlow() end
  if not w then return nil end
  local gi=UE.getObj(w,'OwningGameInstance'); if not gi then return nil end
  local la=UE.prop(gi,'LocalPlayers'); if not la then return nil end
  local data=rq(la); local num=ri(la+8)
  if not data or not num or num&lt;1 then return nil end
  local lp=rq(data); if not lp or not UE.isObj(lp) then return nil end
  local pc=UE.getObj(lp,'PlayerController'); if not pc then return nil end
  local pawn=UE.getObj(pc,'AcknowledgedPawn') or UE.getObj(pc,'Pawn')
  if not pawn then return nil end
  return { world=w, gi=gi, lp=lp, pc=pc, pawn=pawn, ps=UE.getObj(pc,'PlayerState') }
end
local function addSet(P, o)
  if P.setSeen[o] then return end
  P.setSeen[o]=true
  local set={ obj=o, cls=UE.cls(o), name=UE.clsName(UE.cls(o)) or '?', attrs={} }
  local s=set.cls local n=0
  while s and n&lt;64 do
    for _,pr in ipairs(UE.ownProps(s)) do
      if pr.kind=='StructProperty' and pr.size==0x10 then
        set.attrs[#set.attrs+1]={ name=pr.name, addr=o+pr.off }
        if not rawget(P.attr,pr.lname) then P.attr[pr.lname]=o+pr.off end
      end
    end
    s=UE.super(s) n=n+1
  end
  P.sets[#P.sets+1]=set
end
local function addASC(P, o)
  local a=UE.prop(o,'SpawnedAttributes')
  if a then
    local d=rq(a) local n=ri(a+8) or 0
    for i=0,math.min(n,64)-1 do local s=d and rq(d+i*8) if s and UE.isObj(s) and UE.isA(s,'AttributeSet') then addSet(P,s) end end
  end
end
local function scanPlayer(c)
  -- P.attr: attribute name (case-insensitive; the game registers e.g. "health", "hunger" in lower case) -&gt; address
  local P={ pawn=c.pawn, ps=c.ps, pc=c.pc, sets={}, setSeen={}, subs={},
            attr=setmetatable({},{__index=function(t,k) return type(k)=='string' and rawget(t,k:lower()) or nil end}) }
  -- 1) object properties of pawn / player state that point to an ASC or an attribute set
  for _,owner in ipairs({c.pawn, c.ps}) do
    if owner then
      local s=UE.cls(owner) local n=0
      while s and n&lt;64 do
        for _,pr in ipairs(UE.ownProps(s)) do
          if pr.kind=='ObjectProperty' or pr.kind=='ObjectPtrProperty' then
            local v=rq(owner+pr.off)
            if v and UE.isObj(v) then
              if UE.isA(v,'AttributeSet') then addSet(P,v) elseif UE.isA(v,'AbilitySystemComponent') then addASC(P,v) end
            end
          end
        end
        s=UE.super(s) n=n+1
      end
    end
  end
  -- 2) sub-objects (Outer chain) of pawn / player state
  for _,o in ipairs(UE.childrenOf({c.pawn, c.ps})) do
    P.subs[#P.subs+1]=o
    if UE.isA(o,'AttributeSet') then addSet(P,o)
    elseif UE.isA(o,'AbilitySystemComponent') then addASC(P,o) end
  end
  P.move=UE.getObj(c.pawn,'CharacterMovement')
  local na=0 for _ in pairs(P.attr) do na=na+1 end
  PF.msg(('Player scan: %d sub-objects, %d attribute sets, %d attributes, CharacterMovement=%s'):format(#P.subs,#P.sets,na,P.move and 'found' or 'NOT FOUND'),
         ('プレイヤー検出: サブオブジェクト %d件、属性セット %d件、属性 %d件、CharacterMovement=%s'):format(#P.subs,#P.sets,na,P.move and '検出' or '未検出'))
  return P
end
-- returns the player table or nil (cheap: the sub-object scan runs only when the pawn changes)
function PF.player(force)
  local now=os.clock()
  if not force and PF.P and PF.P.t and now-PF.P.t&lt;0.2 then return PF.P end
  local c=chain()
  if not c then PF.P=nil return nil end
  if force or not PF.P or PF.P.pawn~=c.pawn or PF.P.ps~=c.ps then
    PF.P=scanPlayer(c)
  else
    for _,s in ipairs(PF.P.sets) do if UE.cls(s.obj)~=s.cls then PF.P=scanPlayer(c) break end end
  end
  PF.P.t=now
  return PF.P
end
function PF.needPlayer()
  PF.require()
  local ok,e=pcall(UE.init)
  if not ok then PF.err(tostring(e),tostring(e)) end
  local P=PF.player()
  if P and #P.sets==0 then P=PF.player(true) end
  return P or PF.err('Player not found. Load a save and wait until you can move, then try again.',
                                    'プレイヤーが見つかりません。セーブをロードして操作できる状態になってから再実行してください。')
end
function PF.needAttr(P, ...)
  for _,n in ipairs({...}) do
    if not P.attr[n] then PF.err('Attribute not found: '..n,
                                 '属性が見つかりません: '..n) end
  end
end

-- write an attribute (BaseValue and CurrentValue)
local function setAttr(a, v) if a and v then writeFloat(a+8,v) writeFloat(a+0xC,v) end end
local function curAttr(a) return a and PF.rf(a+0xC) end
-- lock attr to (pct % of maxAttr)

local function lockVal(attr, v)
  local P=PF.player(); if not P then return end
  local a=P.attr[attr]; if a and (math.abs((curAttr(a) or 0)-v)&gt;0.001 or math.abs((PF.rf(a+8) or 0)-v)&gt;0.001) then setAttr(a,v) end
end

----------------------------------------------------------------- [GAME] movement (CharacterMovementComponent)
PF.mv = PF.mv or {}
local function mvTask(key, prop, varOff)
  local P=PF.player(); if not P or not P.move then return end
  local a=UE.prop(P.move,prop); if not a then return end
  local st=PF.mv[key] or {}; PF.mv[key]=st
  local cur=PF.rf(a); if not cur then return end
  if st.addr~=a or not st.last or math.abs(cur-st.last)&gt;0.01 then st.base=cur st.addr=a end   -- game changed it: new base
  local v=st.base*(PF.rf(PF.var(varOff)) or 1)
  if math.abs(cur-v)&gt;0.01 then writeFloat(a,v) end
  st.last=v
end
local function mvOff(key)
  local st=PF.mv[key]; PF.mv[key]=nil
  if st and st.addr and st.base and st.last and PF.attached() then
    local cur=PF.rf(st.addr); if cur and math.abs(cur-st.last)&lt;0.01 then writeFloat(st.addr,st.base) end
  end
end

----------------------------------------------------------------- [GAME] bool properties (FBoolProperty)
-- FBoolProperty adds FieldSize, ByteOffset, ByteMask, FieldMask (1 byte each) right after FProperty; offset detected once.
function UE.boolInfo(pr)
  if pr.bi~=nil then return pr.bi or nil end
  pr.bi=false
  local cands=UE.O.bBool and {UE.O.bBool} or {0x50,0x48,0x58,0x40,0x60}
  for _,d in ipairs(cands) do
    local b=readBytes(pr.f+UE.O.fName+d,4,true)
    if b then
      local fs,bo,bm,fm=b[1],b[2],b[3],b[4]
      local pow=(bm==1 or bm==2 or bm==4 or bm==8 or bm==16 or bm==32 or bm==64 or bm==128)
      if fs==1 and bo&lt;8 and pow and (fm==bm or fm==0xFF) then
        UE.O.bBool=d
        pr.bi={ off=pr.off+bo, mask=(fm==0xFF) and 0xFF or bm }
        return pr.bi
      end
    end
  end
end
function UE.boolAddr(o, name)
  local pr=UE.findProp(UE.cls(o),name); if not pr or pr.kind~='BoolProperty' then return nil end
  local bi=UE.boolInfo(pr); if not bi then return nil end
  return o+bi.off, bi.mask
end
local function getBit(a,m) local b=readBytes(a,1,true) if not b then return nil end b=b[1] if m==0xFF then return b~=0 end return (b&amp;m)~=0 end
local function setBit(a,m,v)
  local b=readBytes(a,1,true); if not b then return end b=b[1]
  local nb; if m==0xFF then nb=v and 1 or 0 else nb=v and (b|m) or (b&amp;(~m&amp;0xFF)) end
  if nb~=b then writeBytes(a,nb) end
end

----------------------------------------------------------------- [GAME] crafting without materials
-- UCraftingComponent_Base (player hand crafting "SimpleCrafting", workbenches) has the reflected bool
-- "bUseCraftingCosts" (the game's own switch, toggled by its ToggleCraftingCost function).
-- All crafting components are collected from GUObjectArray, including class defaults / templates,
-- so workbenches built later start with the switch already off. Original values are restored when disabled.
PF.craft = PF.craft or { list={} }
local function craftScan()
  local r={}
  local chunks=rq(UE.gobj); if not chunks then return r end
  local isC={}
  local ch, ci = nil, -1
  for i=0,UE.count()-1 do
    local c=i//UE.O.chunk
    if c~=ci then ch=rq(chunks+c*8) ci=c end
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local k=o and UE.cls(o)
    if k then
      local yes=isC[k]
      if yes==nil then
        yes=false local x=k local n=0
        while x and n&lt;64 do local nm=UE.clsName(x) if nm=='CraftingComponent_Base' then yes=true break end x=UE.super(x) n=n+1 end
        isC[k]=yes
      end
      if yes then r[#r+1]=o end
    end
  end
  return r
end
function PF.craftOn()
  PF.needPlayer()
  PF.craftOff()
  writeInteger(PF.base()+0xF00,0)
  local n=0
  for _,o in ipairs(craftScan()) do
    local a,m=UE.boolAddr(o,'bUseCraftingCosts')
    if a then
      local v=getBit(a,m)
      if v~=nil then PF.craft.list[#PF.craft.list+1]={o=o,cls=UE.cls(o),a=a,m=m,orig=v} setBit(a,m,false) n=n+1 end
    end
  end
  -- building (optional: the feature still works for crafting if these are not found)
  local bok={}
  for _,h in ipairs({'buildCost','buildDeduce','repairChk','repairUse','costDisplay','renovRemain','renovChk','renovUse'}) do if h=='costDisplay' then bok[#bok+1]='original display' else local ok,e=pcall(PF.hookOn,h) bok[#bok+1]=ok and 'OK' or ('NG: '..tostring(e)) end end
  PF.msg(('Materials not needed: %d crafting components now; workbenches / stations loaded later are switched when used. Building: cost check %s, material use %s. Item repair: check %s, material use %s, cost %s. Renovation: list %s, check %s, material use %s.'):format(n,bok[1],bok[2],bok[3],bok[4],bok[5],bok[6],bok[7],bok[8]),
         ('素材必要なし: クラフト部品 %d件を即時に切替。後から読み込まれた作業台・設置型も使用時に切替。建築: 素材チェック %s、素材消費 %s。アイテム修理: 素材チェック %s、素材消費 %s、費用表示 %s。改修（建物の修理）: 必要素材表示 %s、素材チェック %s、素材消費 %s。'):format(n,bok[1],bok[2],bok[3],bok[4],bok[5],bok[6],bok[7],bok[8]))
end
function PF.craftOff()
  if PF.attached() then
    for _,e in ipairs(PF.craft.list) do if UE.isObj(e.o) and UE.cls(e.o)==e.cls then setBit(e.a,e.m,e.orig) end end
    -- components switched by the hooks (bUseCraftingCosts was true)
    local b=PF.base()
    local cnt=b and ri(b+0xF00) or 0
    for i=0,math.min(cnt,31)-1 do
      local o=rq(b+0xF08+i*8)
      if o and UE.isObj(o) then local a,m=UE.boolAddr(o,'bUseCraftingCosts') if a then setBit(a,m,true) end end
    end
    if b then writeInteger(b+0xF00,0) end
    pcall(PF.hookOff,'buildCost') pcall(PF.hookOff,'buildDeduce') pcall(PF.hookOff,'repairChk') pcall(PF.hookOff,'repairUse') pcall(PF.hookOff,'invCheckFor') pcall(PF.hookOff,'invQuantity') pcall(PF.hookOff,'renovRemain') pcall(PF.hookOff,'renovChk') pcall(PF.hookOff,'renovUse') writeQword(PF.var(0xB0),0)
  end
  PF.craft.list={}
end
-- address of the player's BuildingSystemComponent.BuildMode for the invCheckFor / invQuantity hooks

local function craftTask()
  for _,e in ipairs(PF.craft.list) do
    if UE.isObj(e.o) and UE.cls(e.o)==e.cls and getBit(e.a,e.m) then setBit(e.a,e.m,false) end
  end
end

----------------------------------------------------------------- [GAME] skill experience multiplier
-- UCharacterSkillsComponent ("Character Skills Component" on the pawn) has the float "SkillExperienceGainModifier"
-- (also a difficulty parameter of ADifficultyManager). Value = original x multiplier; original restored when disabled.
PF.xp = PF.xp or {}
local function xpFind(P)
  for _,o in ipairs(P.subs) do
    local a,pr=UE.prop(o,'SkillExperienceGainModifier')
    if a and pr.kind=='FloatProperty' then return a, UE.fullName(o) end
  end
  -- fallback: difficulty manager (walks the object list once)
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if o and ((ri(o+8) or 0)&amp;0x30)==0 and UE.isA(o,'DifficultyManager') then
      local a,pr=UE.findIn(UE.cls(o),o,'SkillExperienceGainModifier',2)
      if a and pr.kind=='FloatProperty' then return a, UE.fullName(o) end
    end
  end
end
function PF.xpOn()
  local P=PF.needPlayer()
  local a,who=xpFind(P)
  if not a then PF.err('SkillExperienceGainModifier not found.','SkillExperienceGainModifierが見つかりません。') end
  PF.xp={ a=a, orig=PF.rf(a) or 1 }
  PF.msg(('Skill XP modifier found: %s (original %.3f)'):format(who,PF.xp.orig),('スキル経験値倍率を検出: %s（元の値 %.3f）'):format(who,PF.xp.orig))
end
function PF.xpOff()
  local x=PF.xp; PF.xp={}
  if x.a and PF.attached() then writeFloat(x.a,x.orig) end
end
local function xpTask()
  local x=PF.xp; if not x.a then return end
  local want=x.orig*(PF.rf(PF.var(0x28)) or 1)
  local cur=PF.rf(x.a); if not cur then return end
  if math.abs(cur-want)&gt;0.0001 then
    if x.last and math.abs(cur-x.last)&gt;0.0001 then x.orig=cur want=x.orig*(PF.rf(PF.var(0x28)) or 1) end  -- the game changed it (e.g. difficulty): new original
    writeFloat(x.a,want)
  end
  x.last=want
end

----------------------------------------------------------------- [GAME] blueprint points
-- UBlueprintsTreeComponent ("BP_BlueprintsTreeComponent" on the pawn) holds "AvailableBlueprintPoints".
local VT_OF = { IntProperty='vtDword', UInt32Property='vtDword', FloatProperty='vtSingle', DoubleProperty='vtDouble',
                ByteProperty='vtByte', Int64Property='vtQword', Int16Property='vtWord', UInt16Property='vtWord' }   -- CE globals, resolved at use
function PF.refreshBPList(mr)
  PF.clearChildren(mr)
  local P=PF.needPlayer()
  local list={} for _,o in ipairs({P.pawn, P.pc}) do list[#list+1]=o end
  if P.ps then list[#list+1]=P.ps end
  for _,o in ipairs(P.subs) do list[#list+1]=o end
  for _,o in ipairs(list) do
    local a,pr=UE.prop(o,'AvailableBlueprintPoints')
    if a then
      local vt=VT_OF[pr.kind] and _G[VT_OF[pr.kind]]
      if not vt then PF.err('Unsupported type of AvailableBlueprintPoints: '..pr.kind,'AvailableBlueprintPointsの型に未対応: '..pr.kind) end
      PF.addRec(mr,'Available blueprint points','使用可能な設計図ポイント',('%X'):format(a),vt)
      PF.msg(('Blueprint points: %s +%X (%s)'):format(UE.fullName(o),pr.off,pr.kind),('設計図ポイント: %s +%X（%s）'):format(UE.fullName(o),pr.off,pr.kind))
      return
    end
  end
  PF.addHdr(mr,'(AvailableBlueprintPoints not found)','（AvailableBlueprintPointsが見つかりません）')
end

----------------------------------------------------------------- [GAME] inventory amounts (arrows / ammo / consumables)
-- Every TArray property of the player's components (InventoryComponent "ItemInventory_*", equipment, quick slots ...)
-- whose element (struct or object) contains "Amount" or "MagazineAmmo" is treated as an inventory.
-- Each stack keeps the highest amount seen while the feature is on (decreases are written back).
-- FArrayProperty: Inner FProperty* right after FProperty (offset detected once).
function UE.innerOf(pr)
  if pr.inner~=nil then return pr.inner or nil end
  pr.inner=false
  local cands=UE.O.aInner and {UE.O.aInner} or {0x50,0x48,0x58}
  for _,d in ipairs(cands) do
    local p=rq(pr.f+UE.O.fName+d)
    local fc=p and rq(p+UE.O.fClass); local k=fc and UE.fname(fc)
    if k and k:match('Property$') then
      UE.O.aInner=d
      pr.inner={ f=p, kind=k, size=ri(p+UE.O.fName+0x14) or 0 }
      return pr.inner
    end
  end
end
PF.inv = PF.inv or { lay={}, frz={} }
local ID_NAMES={'ItemData','Config','ItemConfig','ItemID','ItemId','ItemClass','ItemName','ItemRowName','ID'}   -- UInventoryItem: Config (TSoftObjectPtr&lt;item config&gt;)
-- relative layout of an element type: amount / ammo / identity offsets (cached per struct or class)
local function layoutOf(s)
  local L=PF.inv.lay[s]; if L~=nil then return L or nil end
  L={}
  local a,pr=UE.findIn(s,0,'Amount',2);       if a and (pr.kind=='IntProperty' or pr.kind=='FloatProperty') then L.amount={off=a,kind=pr.kind} end
  a,pr=UE.findIn(s,0,'MagazineAmmo',2);       if a and (pr.kind=='IntProperty' or pr.kind=='FloatProperty') then L.ammo={off=a,kind=pr.kind} end
  for _,n in ipairs(ID_NAMES) do local x,xp=UE.findIn(s,0,n,2) if x then L.id=x L.idKind=xp and xp.kind break end end
  a,pr=UE.findIn(s,0,'Durability',2);         if a and (pr.kind=='IntProperty' or pr.kind=='FloatProperty') then L.dur={off=a,kind=pr.kind} end
  a,pr=UE.findIn(s,0,'FuelPercent',2);        if a and (pr.kind=='IntProperty' or pr.kind=='FloatProperty') then L.fuel={off=a,kind=pr.kind} end
  if not L.amount and not L.ammo and not L.dur and not L.fuel then L=false end
  PF.inv.lay[s]=L
  return L or nil
end
-- list of inventory arrays: { a=TArray address, inner=..., struct=... }
-- Refresh inventory components after the game destroys/recreates its backpack.
-- Cached pointers are tied to GUObjectArray serials, not just class names.
function PF.inventoryOwners(P, force)
  local now=getTickCount()
  local st=P.inventoryOwners
  local valid=st~=nil
  if st then
    for _,v in ipairs(st.rows) do
      if rq(v.entry)~=v.o or readInteger(v.entry+0x10)~=v.serial or not UE.live(v.o) then valid=false break end
    end
  end
  if valid and not force and (st.backpack or now-st.tick&lt;1000) then return st.objects end
  local objects,rows={},{}
  local backpack=false
  -- Fresh Outer scan is required: ItemInventory is replaced without changing the pawn.
  for _,o in ipairs(UE.childrenOf({P.pawn,P.ps})) do
    if UE.live(o) and UE.isA(o,'InventoryComponent') then
      local ix=ri(o+0xC)
      if ix and ix&gt;=0 and ix&lt;UE.count() then
        local ch=rq(rq(UE.gobj)+(ix//UE.O.chunk)*8)
        local entry=ch and ch+(ix%UE.O.chunk)*UE.O.itemSize
        if entry and rq(entry)==o then
          objects[#objects+1]=o
          rows[#rows+1]={o=o,entry=entry,serial=readInteger(entry+0x10)}
          if not UE.isA(o,'EquipmentComponent') and (UE.objName(o) or ''):find('^ItemInventory') then backpack=true end
        end
      end
    end
  end
  P.invArr=nil
  P.inventoryOwners={tick=now,objects=objects,rows=rows,backpack=backpack}
  return objects
end

local function invArrays(P)
  local owners=PF.inventoryOwners(P)
  if P.invArr then return P.invArr end
  local r={}
  -- SAFETY: only the item lists of inventory components (InventoryComponent / EquipmentComponent: "Items_",
  -- "Inventory_"). Engine arrays such as Children / AttachChildren (attached weapon actors etc.) are never touched.
  local ITEM_ARRAYS={ items_=true, items=true, inventory_=true }
  for _,o in ipairs(owners) do
    local isInv=false
    do local x=UE.cls(o) local n=0
      while x and n&lt;64 do local nm=UE.clsName(x) or '' if nm=='InventoryComponent' or nm=='EquipmentComponent' then isInv=true break end x=UE.super(x) n=n+1 end
    end
    local s=isInv and UE.cls(o) or nil local n=0
    while s and n&lt;64 do
      for _,pr in ipairs(UE.ownProps(s)) do
        if pr.kind=='ArrayProperty' and ITEM_ARRAYS[pr.lname] then
          local inn=UE.innerOf(pr)
          if inn then
            local e={ a=o+pr.off, owner=o, name=pr.name, inner=inn }
            if inn.kind=='StructProperty' then
              local st=UE.structOf(inn); if st and layoutOf(st) then e.struct=st r[#r+1]=e end
            elseif inn.kind=='ObjectProperty' or inn.kind=='ObjectPtrProperty' then
              e.objects=true r[#r+1]=e     -- element class is checked per element
            end
          end
        end
      end
      s=UE.super(s) n=n+1
    end
  end
  P.invArr=r
  return r
end
local function frzVal(key, addr, kind)
  local v = (kind=='FloatProperty') and PF.rf(addr) or ri(addr)
  if not v then return end
  local k=PF.inv.frz[key]
  if not k or v&gt;k then PF.inv.frz[key]=v
  elseif v&lt;k then if kind=='FloatProperty' then writeFloat(addr,k) else writeInteger(addr,k) end end
end
local function invEach(P, fn)
  for _,e in ipairs(invArrays(P)) do
    local data=rq(e.a); local num=ri(e.a+8) or 0
    if data and num&gt;0 and num&lt;4096 then
      for i=0,num-1 do
        local base,L,ident
        if e.objects then
          local o=rq(data+i*8)
          if o and UE.isObj(o) then base=o L=layoutOf(UE.cls(o)) ident=o end
        else
          base=data+i*e.inner.size L=layoutOf(e.struct)
          ident=L and L.id and rq(base+L.id) or 0
        end
        if base and L then fn(e, i, base, L, ident) end
      end
    end
  end
end
----------------------------------------------------------------- [GAME] time of day
-- The exe drives the sky through Ultra Dynamic Sky ("sGetUDSTimeOfDay", AWeatherManager::SetTimeOfDay).
-- The sky actor (class name containing "Dynamic_Sky"/"DynamicSky") has the variable "Time of Day" (0..2400 = 00:00..24:00).
-- Fallback: an AWeatherManager with a "TimeOfDay"/"CurrentTimeOfDay" number. Scale is detected (2400 or 24).
PF.tod = PF.tod or {}
local function readNum(a,kind) if kind=='DoubleProperty' then return readDouble(a) end return PF.rf(a) end
local function writeNum(a,kind,v) if kind=='DoubleProperty' then writeDouble(a,v) else writeFloat(a,v) end end
local function todFind()
  local t=PF.tod
  if t.o and UE.isObj(t.o) and UE.cls(t.o)==t.cls then return t end
  PF.tod={}
  local chunks=rq(UE.gobj); if not chunks then return nil end
  local seen={} local best=nil
  for i=0,UE.count()-1 do
    local ch=rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local c=o and UE.cls(o)
    if c and ((ri(o+8) or 0)&amp;0x30)==0 then
      local kind=seen[c]
      if kind==nil then
        kind=false local x=c local n=0
        while x and n&lt;64 do
          local nm=(UE.clsName(x) or ''):lower()
          if nm:find('dynamic_sky',1,true) or nm:find('dynamicsky',1,true) then kind='sky' break end
          if nm=='weathermanager' then kind='wm' break end
          x=UE.super(x) n=n+1
        end
        seen[c]=kind
      end
      if kind then
        local names = (kind=='sky') and {'Time of Day','TimeOfDay'} or {'TimeOfDay','CurrentTimeOfDay'}
        for _,pn in ipairs(names) do
          local a,pr=UE.findIn(c,o,pn,1)
          if a and (pr.kind=='FloatProperty' or pr.kind=='DoubleProperty') then
            local cand={o=o,cls=c,a=a,kind=pr.kind,who=UE.fullName(o)..'.'..pr.name}
            if kind=='sky' then PF.tod=cand break end
            best=best or cand
          end
        end
        if PF.tod.o then break end
      end
    end
  end
  if not PF.tod.o and best then PF.tod=best end
  local t=PF.tod
  if not t.o then return nil end
  local v=readNum(t.a,t.kind) or 0
  t.scale=(v&gt;24.5) and 100 or ((t.who:lower():find('time of day',1,true)) and 100 or 1)
  PF.msg(('Time of day: %s = %.2f (hour x%d)'):format(t.who,v,t.scale),('時刻: %s = %.2f（時×%d）'):format(t.who,v,t.scale))
  return t
end
function PF.todSet(hour)
  PF.needPlayer()
  local t=todFind() or PF.err('Time-of-day variable not found.','時刻の変数が見つかりません。')
  local h=hour or PF.rf(PF.var(0x2C)) or 12
  if h&lt;0 or h&gt;=24 then PF.err('Hour must be 0 to 23.99.','時は0～23.99で指定してください。') end
  writeNum(t.a,t.kind,h*t.scale)
end
local function todTask(hour)
  local t=PF.tod; if not t.o or not UE.isObj(t.o) then return end
  local h=hour or PF.rf(PF.var(0x2C)) or 12
  if h&lt;0 or h&gt;=24 then return end
  local want=h*t.scale; local cur=readNum(t.a,t.kind)
  if cur and math.abs(cur-want)&gt;0.01*t.scale then writeNum(t.a,t.kind,want) end
end

----------------------------------------------------------------- [GAME] calling game functions (UFunction via ProcessEvent)
-- UFunction (UE 5.4): +B0 FunctionFlags, +B6 ParmsSize (u16). UStruct.Children (UField list) = SuperStruct+8, UField.Next +28.
-- a live UFunction object with this name (cached pointers can go stale after garbage collection / level loads)
function UE.isFunc(f, fname)
  if not f or not UE.isObj(f) then return false end
  if UE.clsName(UE.cls(f))~='Function' then return false end
  return fname==nil or (UE.objName(f) or ''):lower()==fname:lower()
end
function UE.findFunc(o, fname)
  -- resolved functions are cached per (class, name): the search and its log line run only once
  UE.funcResolved=UE.funcResolved or {}
  local ck=('%X:%s'):format(UE.cls(o) or 0, fname:lower())
  local hit=UE.funcResolved[ck]
  if UE.isFunc(hit, fname) then return hit end
  local f,cnt=UE.findFuncUncached(o, fname)
  if f then UE.funcResolved[ck]=f end
  return f,cnt
end
function UE.findFuncUncached(o, fname)
  local want=fname:lower()
  local chain={} local s=UE.cls(o) local n=0
  while s and n&lt;64 do
    chain[s]=true
    local f=rq(s+UE.O.super+8) local k=0
    while f and k&lt;4000 do
      if (UE.objName(f) or ''):lower()==want then return f end
      f=rq(f+0x28) k=k+1
    end
    s=UE.super(s) n=n+1
  end
  -- not in the class chain: the function may be declared in an interface (e.g. UWeatherManagerInterface).
  -- Search GUObjectArray for UFunction objects with that name (cached).
  UE.funcCache=UE.funcCache or {}
  local key=fname:lower()
  local list=UE.funcCache[key]
  if not list then
    list={}
    local chunks=rq(UE.gobj)
    local isF={}
    for i=0,UE.count()-1 do
      local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
      local x=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
      local c=x and UE.cls(x)
      if c then
        local k=isF[c]; if k==nil then k=(UE.clsName(c)=='Function') isF[c]=k end
        if k and (UE.objName(x) or ''):lower()==key then list[#list+1]=x end
      end
    end
    UE.funcCache[key]=list
  end
  local live={} for _,f in ipairs(list) do if UE.isFunc(f, fname) then live[#live+1]=f end end list=live UE.funcCache[key]=live
  local pick=nil
  for _,f in ipairs(list) do local ou=UE.outer(f) if ou and chain[ou] then return f end end
  for _,f in ipairs(list) do local ou=UE.outer(f) if ou and (UE.objName(ou) or ''):lower():find('interface',1,true) then pick=pick or f end end
  if not pick and #list==1 then pick=list[1] end
  if pick then PF.msg(('Function %s found in %s'):format(fname,UE.objName(UE.outer(pick))),('関数 %s を %s で検出'):format(fname,UE.objName(UE.outer(pick)))) end
  return pick, #list
end
-- call o:fname(args) on the game thread; args = { paramName=value, ... } (bool / int / float)
-- one call at a time: a timer task must never rewrite the shared parameter buffer while another call is pending
function PF.callFunc(o, fname, args, opts)
  if PF.peBusy then PF.err('Another game call is in progress: '..fname,'別のゲーム呼び出しが実行中です: '..fname) end
  PF.peBusy=true
  local ok,r=pcall(PF.callFuncInner, o, fname, args, opts)
  PF.peBusy=false
  if not ok then error(r,0) end
  return r
end
function PF.callFuncInner(o, fname, args, opts)
  PF.require()
  local f,cnt=UE.findFunc(o,fname)
  if not f then PF.err(('Game function not found: %s (class %s, %d candidates)'):format(fname,UE.clsName(UE.cls(o)) or '?',cnt or 0),
                       ('ゲームの関数が見つかりません: %s（クラス %s、候補 %d件）'):format(fname,UE.clsName(UE.cls(o)) or '?',cnt or 0)) end
  local size=(readSmallInteger and readSmallInteger(f+0xB6)) or 0
  if size&gt;0xC00 then PF.err('Parameters too large: '..fname,'引数が大きすぎます: '..fname) end   -- buffer pfFlags+300..EFF
  local buf=PF.base()+0x300
  local z={} for i=1,math.max(0x100,size) do z[i]=0 end writeBytes(buf,z)
  if type(args)=='function' then args=args(f) end   -- args may be built from the function's parameter list
  for _,pr in ipairs(UE.ownProps(f)) do
    local v=args and args[pr.name]
    if v==nil and args then for k,x in pairs(args) do if type(k)=='string' and k:lower()==pr.lname then v=x end end end
    if v==nil and args and args[1]~=nil and pr==UE.ownProps(f)[1] then v=args[1] end   -- first parameter by position
    if v~=nil then
      if pr.kind=='BoolProperty' then local bi=UE.boolInfo(pr) if bi then setBit(buf+bi.off,bi.mask,v and true or false) end
      elseif pr.kind=='FloatProperty' then writeFloat(buf+pr.off,v)
      elseif pr.kind=='DoubleProperty' then writeDouble(buf+pr.off,v)
      elseif pr.kind=='ObjectProperty' or pr.kind=='ClassProperty' or pr.kind=='ObjectPtrProperty' or pr.kind=='ClassPtrProperty'
          or pr.kind=='Int64Property' then writeQword(buf+pr.off,v)
      elseif pr.kind=='ByteProperty' or pr.kind=='EnumProperty' and pr.size==1 then writeBytes(buf+pr.off,v)
      else writeInteger(buf+pr.off,v) end
    end
  end
  if args and type(args.__raw)=='function' then args.__raw(buf) end   -- extra writes (e.g. struct parameters)
  PF.hookOn('peCall')
  return PF.peRun(o, f, fname, opts)
end
-- state of the call slot: 0 free, 1 requested, 2 running
local function peState() local st=readBytes(PF.flag(0x10),1,true) return st and st[1] or 0 end
-- wait while a previous call is still running (never write a new request over a running one)
local function peWaitFree(ms)
  local t=0
  while peState()==2 and t&lt;ms do sleep(5) t=t+5 end
  return peState()~=2
end
-- carriers for calls that change game state: the pawn's own ReceiveTick (Blueprint tick), else any pawn event
function PF.safeCarriers()
  local P=PF.player()
  local pawn=P and P.pawn
  if not pawn or not UE.isObj(pawn) then return {} end
  local list={}
  -- a Blueprint override of ReceiveTick (declared in a class other than AActor) is called every frame
  local ok,fn=pcall(UE.findFuncUncached, pawn, 'ReceiveTick')
  if ok and UE.isFunc(fn,'ReceiveTick') and UE.outer(fn) and UE.objName(UE.outer(fn))~='Actor' then list[#list+1]={pawn, fn, 'pawn tick'} end
  list[#list+1]={pawn, 0, 'pawn event'}
  return list
end
-- game thread = main thread of the process (first thread of the process in the system thread list)
function PF.gameThreadId()
  if PF.gtid and PF.gtidPid==PF.pid then return PF.gtid end
  local sl=createStringList()
  local ok=pcall(getThreadlist, sl)
  local id
  if ok and sl.Count&gt;0 then id=tonumber(sl[0],16) end
  sl.destroy()
  if id and id&gt;0 then PF.gtid=id PF.gtidPid=PF.pid PF.msg(('Game thread: %X'):format(id),('ゲームスレッド: %X'):format(id)) end
  return id
end
function PF.peRun(o, f, fname, opts)
  if not UE.isObj(o) then PF.err('Target object is no longer valid: '..fname,'呼び出し先のオブジェクトが無効になっています: '..fname) end
  if not UE.isFunc(f) or not rq(f+0xD8) then PF.err('Game function is no longer valid: '..fname,'ゲーム関数が無効になっています: '..fname) end
  if not peWaitFree(10000) then PF.err('Previous game call still running: '..fname,'前回のゲーム呼び出しがまだ実行中です: '..fname) end
  -- pawn for the game-thread check in the hook (see game_head.lua)
  local P=PF.player()
  if not P or not P.pawn or not UE.isObj(P.pawn) then PF.err('Player not found (game calls run only in game).','プレイヤーが見つかりません（ゲーム呼び出しはゲーム中のみ実行します）。') end
  local tid=PF.gameThreadId()
  if not tid then PF.err('Game thread not identified (thread list unavailable).','ゲームスレッドを特定できません（スレッド一覧を取得できません）。') end
  if (ri(PF.var(0x68)) or 0)~=tid then writeInteger(PF.var(0x68),tid) end
  local tries = (opts and opts.safe) and PF.safeCarriers() or {{0,0,'any'}}
  -- quick (periodic timer calls): one carrier, short wait, so a paused game / open menu never stalls CE
  local loops=400
  if opts and opts.quick then tries={tries[1]} loops=40 end
  if #tries==0 then PF.err('Player not found (needed to run '..fname..' safely).','プレイヤーが見つかりません（'..fname..' を安全に実行するために必要）。') end
  for _,c in ipairs(tries) do
    writeQword(PF.var(0x50),c[1]) writeQword(PF.var(0x58),c[2])
    writeQword(PF.var(0x40),o) writeQword(PF.var(0x48),f)
    writeBytes(PF.flag(0x10),1)
    for _=1,loops do
      sleep(5)
      if peState()==0 then writeQword(PF.var(0x50),0) writeQword(PF.var(0x58),0) return true end
    end
    -- cancel: first make the gate impossible, then withdraw the request only if it was not taken
    writeQword(PF.var(0x50),1) writeQword(PF.var(0x58),1)
    sleep(20)
    if peState()==1 then writeBytes(PF.flag(0x10),0)
    else
      if peWaitFree(10000) then writeQword(PF.var(0x50),0) writeQword(PF.var(0x58),0) return true end
      PF.err('Game call did not finish: '..fname,'ゲーム呼び出しが終了しません: '..fname)
    end
  end
  writeQword(PF.var(0x50),0) writeQword(PF.var(0x58),0)
  PF.err('The game did not run the call (is it paused or loading?): '..fname,'ゲームが呼び出しを実行しませんでした（一時停止中・ロード中の可能性）: '..fname)
end

----------------------------------------------------------------- [GAME] add item (list selection)
-- Uses the game's own UInventoryComponent::AddItemAmount (fallback InsertItemAmount) on the player's inventory
-- ("ItemInventory_*"), called on the game thread through ProcessEvent. The item parameter type
-- (item class or item data object) is read from the function's parameter list, and every loaded candidate of
-- that type is offered in a selection list.
-- FObjectPropertyBase::PropertyClass / FClassProperty::MetaClass follow FProperty (same place as StructProperty.Struct).
function UE.objPropClass(pr)
  local base=UE.O.fName+(UE.O.sStruct and (UE.O.sStruct-UE.O.fName) or 0x50)
  local function cls(off) local c=rq(pr.f+off) if c and UE.isObj(c) then local k=UE.clsName(UE.cls(c)) or '' if k:find('Class',1,true) then return c end end end
  if pr.kind=='ClassProperty' or pr.kind=='ClassPtrProperty' or pr.kind=='SoftClassProperty' then return cls(base+8), true end
  return cls(base), false
end
-- live = valid object not being destroyed (RF_BeginDestroyed 0x8000 / RF_FinishDestroyed 0x10000 / RF_MirroredGarbage 0x40000000)
function UE.live(o) return o and UE.isObj(o) and ((ri(o+8) or 0)&amp;0x40018000)==0 end
local function invComp(P)
  local best
  for _,o in ipairs(PF.inventoryOwners(P, true)) do
    if UE.live(o) and UE.isA(o,'InventoryComponent') and not UE.isA(o,'EquipmentComponent') then
      local nm=UE.objName(o) or ''
      if nm:find('^ItemInventory') then return o end      -- the player's own backpack inventory
      best=best or o
    end
  end
  return best
end
local function isSubclass(c, base) local n=0 while c and n&lt;64 do if c==base then return true end c=UE.super(c) n=n+1 end return false end
PF.itemCands = PF.itemCands or {}
-- FText -&gt; string with the game's own UKismetTextLibrary::Conv_TextToString (localized display string),
-- called on the game thread through ProcessEvent. The FText (size from reflection) is copied into the parameter buffer.
PF.txt = PF.txt or {}
local function textLib()
  local t=PF.txt
  if t.cdo and UE.isObj(t.cdo) then return t end
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if o and UE.objName(o)=='Default__KismetTextLibrary' then
      local f=UE.findFunc(o,'Conv_TextToString')
      if f then
        local inP,retP
        for _,pr in ipairs(UE.ownProps(f)) do if pr.kind=='TextProperty' then inP=pr elseif pr.kind=='StrProperty' then retP=pr end end
        if inP and retP then PF.txt={cdo=o,f=f,inOff=inP.off,inSize=inP.size,retOff=retP.off,retSize=retP.size} return PF.txt end
      end
    end
  end
end
function UE.textAt(addr)
  if not rq(addr) then return nil end
  local t=textLib(); if not t then return nil end
  -- copy exactly the FText size given by reflection (0x10 in this build). Copying more would overwrite
  -- ReturnValue (FString) and the game would free that garbage pointer (crash in execConv_TextToString).
  local sz=t.inSize or 0
  if sz&lt;8 or sz&gt;0x18 or (t.inOff+sz)&gt;t.retOff and t.inOff&lt;t.retOff then return nil end
  local raw=readBytes(addr,sz,true); if not raw then return nil end
  PF.callFunc(t.cdo,'Conv_TextToString',{ __raw=function(buf)
    writeBytes(buf+t.inOff,raw)
    local z={} for i=1,(t.retSize or 0x10) do z[i]=0 end writeBytes(buf+t.retOff,z)   -- empty FString
  end })
  local r=PF.base()+0x300+t.retOff
  local d=rq(r); local n=ri(r+8)
  if not d or not n or n&lt;2 or n&gt;512 then return nil end
  local bt=readBytes(d,(n-1)*2,true); if not bt then return nil end
  local out={} for k=1,#bt-1,2 do local c=bt[k]+bt[k+1]*256 out[#out+1]=(c&gt;=0xD800 and c&lt;=0xDFFF) and '?' or utf8.char(c) end
  local str=table.concat(out)
  if str=='' then return nil end
  return str
end
-- display name of an item: first TextProperty whose name contains "name" (not "description"), searched in the
-- object, its struct members and the objects it references (item data assets), up to 2 levels.
function PF.itemDisplayName(o)
  if not o then return nil end
  local function search(s, base, depth, seen)
    local n=0 local x=s local objs={}
    while x and n&lt;32 do
      for _,pr in ipairs(UE.ownProps(x)) do
        if pr.kind=='TextProperty' and pr.lname:find('name',1,true) and not pr.lname:find('desc',1,true) then
          local t=UE.textAt(base+pr.off) if t then return t end
        elseif depth&gt;0 and pr.kind=='StructProperty' then
          local st=UE.structOf(pr) if st then local t=search(st, base+pr.off, depth-1, seen) if t then return t end end
        elseif depth&gt;0 and (pr.kind=='ObjectProperty' or pr.kind=='ObjectPtrProperty') then
          objs[#objs+1]=base+pr.off
        end
      end
      x=UE.super(x) n=n+1
    end
    for _,a in ipairs(objs) do
      local v=rq(a)
      if v and not seen[v] and UE.isObj(v) then seen[v]=true local t=search(UE.cls(v), v, depth-1, seen) if t then return t end end
    end
  end
  return search(UE.cls(o), o, 2, {[o]=true})
end
-- enums: FByteProperty.Enum / FEnumProperty{UnderlyingProp, Enum} follow FProperty.
-- UEnum (UField 0x30 + FString CppType) -&gt; +40 TArray&lt;TPair&lt;FName,int64&gt;&gt; Names (0x10 per entry).
function UE.enumOfProp(pr)
  local base=UE.O.fName+(UE.O.sStruct and (UE.O.sStruct-UE.O.fName) or 0x50)
  local e = (pr.kind=='EnumProperty') and rq(pr.f+base+8) or rq(pr.f+base)
  if e and UE.isObj(e) and (UE.clsName(UE.cls(e)) or ''):find('Enum',1,true) then return e end
end
function UE.enumValueName(e, v)
  local d=rq(e+0x40); local n=ri(e+0x48) or 0
  for i=0,math.min(n,256)-1 do
    local val=readQword(d+i*0x10+8)
    if val==v then local nm=UE.fname(d+i*0x10) return nm and nm:gsub('^.*::','') end
  end
end
-- item type (EItemType: Base, BuildPart, Clothing, Consumable, Equipable, Flag, Holdable, RangeWeapon, Weapon)
function PF.itemType(o)
  if not o then return nil end
  -- Native item-config subclasses are authoritative when EItemType is absent.
  local byClass={ItemConfig_Clothing='Clothing',ItemConfig_RangeWeapon='RangeWeapon',ItemConfig_Weapon='Weapon',
    ItemConfig_Holdable='Holdable',ItemConfig_Equipable='Equipable',ItemConfig_Consumable='Consumable',
    ItemConfig_BuildPart='BuildPart',ItemConfig_Flag='Flag',ItemConfig_Base='Base'}
  local c=UE.cls(o)
  for _=1,64 do if not c then break end;local kind=byClass[UE.clsName(c)];if kind then return kind end;c=UE.super(c)end
  local function search(s, base, depth, seen)
    local n=0 local x=s local objs={}
    while x and n&lt;32 do
      for _,pr in ipairs(UE.ownProps(x)) do
        if pr.kind=='EnumProperty' or pr.kind=='ByteProperty' then
          local e=UE.enumOfProp(pr)
          if e and UE.objName(e)=='EItemType' then
            local b=readBytes(base+pr.off,1,true)
            return b and UE.enumValueName(e,b[1])
          end
        elseif depth&gt;0 and pr.kind=='StructProperty' then
          local st=UE.structOf(pr) if st then local t=search(st, base+pr.off, depth-1, seen) if t then return t end end
        elseif depth&gt;0 and (pr.kind=='ObjectProperty' or pr.kind=='ObjectPtrProperty') then objs[#objs+1]=base+pr.off end
      end
      x=UE.super(x) n=n+1
    end
    for _,a in ipairs(objs) do
      local v=rq(a)
      if v and not seen[v] and UE.isObj(v) then seen[v]=true local t=search(UE.cls(v), v, depth-1, seen) if t then return t end end
    end
  end
  return search(UE.cls(o), o, 2, {[o]=true})
end
PF.ITEM_CAT = { -- EItemType -&gt; {en, ja}
  Consumable={'Consumables','消耗品'}, Weapon={'Weapons (melee)','武器（近接）'}, RangeWeapon={'Ranged weapons','遠隔武器'},
  Holdable={'Tools / holdables','道具（手に持つ物）'}, Clothing={'Clothing','衣類'}, Equipable={'Equipment','装備品'},
  BuildPart={'Building parts','建築パーツ'}, Base={'Materials / other','素材・その他'}, Flag={'Flags','フラグ'},
}
local function itemCandidates(target, wantClasses)
  local key=('%X:%s'):format(target, tostring(wantClasses))
  if PF.itemCandidatePid~=getOpenedProcessID() then PF.itemCands={} PF.itemCandidatePid=getOpenedProcessID() end
  local cached={}for _,e in ipairs(PF.itemCands[key] or {})do cached[e.ptr]=e end
  local r={} local seen={}
  local chunks=rq(UE.gobj)
  local isClassCls={}
  local cdo={}   -- class -&gt; class default object (RF_ClassDefaultObject 0x10), used for display names
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local c=o and UE.cls(o)
    if c and ((ri(o+8) or 0)&amp;0x10)~=0 then cdo[c]=o end
    if c then
      if wantClasses then
        local k=isClassCls[c]; if k==nil then local nm=UE.clsName(c) or '' k=(nm=='Class' or nm=='BlueprintGeneratedClass') isClassCls[c]=k end
        if k and o~=target and isSubclass(o,target) then
          local nm=UE.objName(o)
          if not nm:find('^SKEL_') and not nm:find('^REINST_') and not seen[nm] then seen[nm]=true r[#r+1]={ptr=o,name=nm} end
        end
      elseif ((ri(o+8) or 0)&amp;0x10)==0 and isSubclass(c,target) then
        local nm=UE.objName(o)
        if not seen[nm] then seen[nm]=true r[#r+1]={ptr=o,name=nm} end
      end
    end
  end
  for _,e in ipairs(r) do
    local holder = wantClasses and cdo[e.ptr] or e.ptr
    local previous=cached[e.ptr]
    if previous and previous.name==e.name and UE.live(e.ptr) then e.disp=previous.disp;e.cat=previous.cat end
    if not e.disp then local ok,t=pcall(PF.itemDisplayName, holder);e.disp=ok and t or nil end
    if not e.cat then local ok,ty=pcall(PF.itemType, holder);e.cat=ok and ty or nil end
  end
  table.sort(r,function(a,b) return (a.disp or a.name):lower()&lt;(b.disp or b.name):lower() end)
  PF.itemCands[key]=r
  return r
end
local function prettyItem(n) n=n:gsub('^BP_',''):gsub('^DA_',''):gsub('_C$','') return n end
function PF.addItemPick()
  local P=PF.needPlayer()
  local inv=invComp(P) or PF.err('Player inventory (InventoryComponent) not found.','プレイヤーの所持品（InventoryComponent）が見つかりません。')
  local fname, f = nil, nil
  for _,n in ipairs({'AddItemAmount','InsertItemAmount'}) do local x=UE.findFunc(inv,n) if x then fname,f=n,x break end end
  if not f then PF.err('Add-item function not found.','アイテム追加の関数が見つかりません。') end
  -- parameters: the item is either a direct object/class parameter, or a struct (e.g. FItemAmount) holding
  -- an item reference (object / class / soft object / soft class) and an int amount.
  local REF={ObjectProperty=1,ClassProperty=1,ObjectPtrProperty=1,ClassPtrProperty=1,SoftObjectProperty=1,SoftClassProperty=1}
  local itemPr, amtPr, structPr, itemOff, amtOff
  for _,pr in ipairs(UE.ownProps(f)) do
    if not itemPr and REF[pr.kind] then itemPr=pr itemOff=pr.off end
    if not amtPr and pr.kind=='IntProperty' and pr.lname~='returnvalue' then amtPr=pr amtOff=pr.off end
    if not structPr and pr.kind=='StructProperty' then structPr=pr end
  end
  if not itemPr and structPr then
    local st=UE.structOf(structPr)
    local x=st local n=0
    while x and n&lt;16 do
      for _,q in ipairs(UE.ownProps(x)) do
        if not itemPr and REF[q.kind] then itemPr=q itemOff=structPr.off+q.off end
        if not amtPr and q.kind=='IntProperty' then amtPr=q amtOff=structPr.off+q.off end
      end
      x=UE.super(x) n=n+1
    end
  end
  if not itemPr or not amtPr then PF.err('Item-add parameters are not supported: '..fname,fname..' の引数構造に対応していません。') end
  local target, isCls = UE.objPropClass(itemPr)
  if not target then PF.err('Item type of '..fname..' not resolved.',fname..' のアイテム型を特定できません。') end
  if not PF.itemCands[('%X:%s'):format(target, tostring(isCls))] then
    PF.msg('Reading item names from the game (new entries may take a few seconds)...','ゲームからアイテム名を取得しています（新しい項目は数秒かかる場合があります）…')
  end
  local list=itemCandidates(target, isCls)
  if #list==0 then PF.err('No loaded item found ('..(UE.objName(target) or '?')..').','読み込み済みのアイテムがありません（'..(UE.objName(target) or '?')..'）。') end
  -- multi-select dialog: category filter + text search + multi-select list + quantity
  local cats,order={},{}
  for _,e in ipairs(list) do local c=e.cat or '?' if not cats[c] then cats[c]=0 order[#order+1]=c end cats[c]=cats[c]+1 end
  table.sort(order)
  local catList={{key=nil,label=PF.T('(all) ','（すべて） ')..#list}}
  for _,c in ipairs(order) do
    local m=PF.ITEM_CAT[c]
    catList[#catList+1]={key=c,label=(m and PF.T(m[1],m[2]) or (c=='?' and PF.T('(unknown type)','（種類不明）') or c))..'  ('..c..')  '..cats[c]}
  end
  local entries={}
  for k2,e in ipairs(list) do
    entries[k2]={ cat=e.cat or '?', label=(e.disp and (e.disp..'  ['..prettyItem(e.name)..']') or prettyItem(e.name)) }
  end
  local function addOne(ptr, n)
    PF.callFunc(inv, fname, function(fn)
      local a={}
      for _,pr in ipairs(UE.ownProps(fn)) do
        -- no drop actor and no notification widget: fewer side effects while the game runs our call
        if pr.kind=='BoolProperty' and (pr.lname:find('notif',1,true) or pr.lname:find('drop',1,true)) then a[pr.name]=false end
      end
      a.__raw=function(buf)
        if itemPr.kind=='SoftObjectProperty' or itemPr.kind=='SoftClassProperty' then
          -- FSoftObjectPtr: FWeakObjectPtr{ObjectIndex, SerialNumber} + FSoftObjectPath{PackageName, AssetName, SubPathString}
          local idx=ri(ptr+UE.O.objIndex) or 0
          local chunks=rq(UE.gobj); local ch=chunks and rq(chunks+(idx//UE.O.chunk)*8)
          local serial=ch and ri(ch+(idx%UE.O.chunk)*UE.O.itemSize+0x10) or 0
          writeInteger(buf+itemOff,idx) writeInteger(buf+itemOff+4,serial)
          local pkg=ptr local k3=0 while UE.outer(pkg) and k3&lt;16 do pkg=UE.outer(pkg) k3=k3+1 end
          writeQword(buf+itemOff+8, readQword(pkg+UE.O.objName))
          writeQword(buf+itemOff+0x10, readQword(ptr+UE.O.objName))
        else
          writeQword(buf+itemOff,ptr)
        end
        writeInteger(buf+amtOff,n)
      end
      return a
    end, {safe=true})
    sleep(150)   -- let the game update inventory / UI before the next item
  end
  -- item pointers were collected when the list was built; check each one again before use
  local byName=nil
  local function liveItem(e2)
    local function ok(p)
      if not p or not UE.isObj(p) or UE.objName(p)~=e2.name then return false end
      local t=UE.objPropClass(itemPr) if not t then return false end
      if isCls then return isSubclass(p,t) else return isSubclass(UE.cls(p),t) end
    end
    if ok(e2.ptr) then return e2.ptr end
    if not byName then
      byName={}
      local chunks=rq(UE.gobj)
      for i=0,UE.count()-1 do
        local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
        local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
        if o then local nm=UE.objName(o) if nm and not byName[nm] then byName[nm]={} end if nm then local t=byName[nm] t[#t+1]=o end end
      end
    end
    for _,p in ipairs(byName[e2.name] or {}) do if ok(p) then e2.ptr=p return p end end
    return nil
  end
  -- total amount of an item (by item data name) in all of the player's inventories
  local function countOf(P, name)
    local t=0
    invEach(P, function(e2,i,base,L)
      if L.amount then
        for _,s in ipairs(PF.stackNames(e2,base,L)) do
          if s==name then t=t+((L.amount.kind=='FloatProperty') and (PF.rf(base+L.amount.off) or 0) or (ri(base+L.amount.off) or 0)) break end
        end
      end
    end)
    return t
  end
  local function doAdd(sel, n)
    if not PF.attached() then PF.err('Not attached.','アタッチされていません。') end
    -- rescan the player every time: equipping a backpack etc. can replace inventory components
    local P=PF.player(true) or PF.err('Player not found.','プレイヤーが見つかりません。')
    P.invArr=nil
    inv=invComp(P) or PF.err('Player inventory (InventoryComponent) not found.','プレイヤーの所持品（InventoryComponent）が見つかりません。')
    byName=nil
    local done,fail,part={},0,{}
    for _,idx in ipairs(sel) do
      local p=liveItem(list[idx])
      local ok,e
      local before=countOf(P, list[idx].name)
      if not p then ok,e=false,PF.T('item is no longer loaded in the game','この項目はゲーム内で読み込まれていません')
      else ok,e=xpcall(addOne, debug and debug.traceback or function(m) return m end, p, n) end
      if ok then
        sleep(150) P.invArr=nil
        local got=countOf(P, list[idx].name)-before
        if got&gt;=n then done[#done+1]=entries[idx].label
        elseif got&gt;0 then part[#part+1]=entries[idx].label..' ('..got..'/'..n..')'
        else fail=fail+1 PF.msg('Amount in the inventory did not increase (inventory full, or put into another container?): '..entries[idx].label,'所持数が増えていません（所持品がいっぱい、または別の入れ物に入った可能性）: '..entries[idx].label) end
      else fail=fail+1 PF.msg('Failed: '..entries[idx].label..' : '..tostring(e),'失敗: '..entries[idx].label..' : '..tostring(e)) end
    end
    PF.msg(('Added %d item(s) x%d: %s'):format(#done,n,table.concat(done,', ')),('%d種類を各%d個追加しました: %s'):format(#done,n,table.concat(done,', ')))
    if #part&gt;0 then PF.msg('Partly added: '..table.concat(part,', '),'一部のみ追加: '..table.concat(part,', ')) end
    return PF.T(('Added %d, partly %d, not added %d (x%d each). Details: Lua Engine'):format(#done,#part,fail,n),
                ('追加 %d件・一部のみ %d件・追加なし %d件（各%d個）。詳細はLua Engine'):format(#done,#part,fail,n))
  end
  PF.itemWindow(PF.T('Add items','アイテム追加'), entries, catList, doAdd, {refresh=PF.addItemPick})
end

-- item window (not modal): stays open; [Add] adds the selected items and keeps the window and the selection
-- Dark report-list styling follows WP10_2026.CT; selection keys are model IDs, never row indexes.
function PF.itemWindow(title, entries, catList, onAdd, opts)
  opts=opts or {}
  if PF.itemWin then pcall(function()PF.itemWin.close()end);if PF.itemWin then return nil end end
  local f=createForm(false);PF.itemWin=f
  f.Caption=title;f.ClientWidth=1100;f.ClientHeight=680;f.Position='poScreenCenter';f.BorderStyle='bsSizeable'
  f.Color=0x252525;f.Font.Name='Yu Gothic UI';f.Font.Size=10;f.Font.Color=0xFFFFFF
  f.Constraints.MinWidth=860;f.Constraints.MinHeight=430
  local function panel(align,height)
    local p=createPanel(f);p.Align=align;p.Height=height;p.BevelOuter='bvNone';p.Caption='';p.Color=0x252525;p.BorderSpacing.Around=6;return p
  end
  local function button(parent,caption,align,width)
    local b=createButton(parent);b.Caption=caption;b.Align=align;b.Width=width or 110;b.BorderSpacing.Around=3;return b
  end
  local status=createLabel(f);status.Align=alBottom;status.BorderSpacing.Around=9;status.Font.Color=0xCFCFCF;status.Caption=' '
  local actions=panel(alBottom,40);local choices=panel(alBottom,38)
  local headers=panel(alTop,30)
  local rowSearch=panel(alTop,34);local rowFilter=panel(alTop,34)
  local cb=createComboBox(rowFilter);cb.Align=alClient;cb.Style='csDropDownList';cb.Color=0x353535;cb.Font.Color=0xFFFFFF
  for _,c in ipairs(catList)do cb.Items.add(c.label)end;cb.ItemIndex=0
  local clear=button(rowFilter,PF.T('Clear filters','検索解除'),alRight,130)
  local refresh=button(rowFilter,PF.T('Refresh','更新'),alRight,100);refresh.Visible=type(opts.refresh)=='function'
  local searchLabel=createLabel(rowSearch);searchLabel.Align=alLeft;searchLabel.Caption=PF.T('Search:  ','検索： ');searchLabel.Layout='tlCenter'
  local ed=createEdit(rowSearch);ed.Align=alClient;ed.Color=0x353535;ed.Font.Color=0xFFFFFF
  local hint=createLabel(choices);hint.Align=alClient;hint.Layout='tlCenter';hint.Caption=opts.single and ''or PF.T('Ctrl / Shift + click: multiple selection','Ctrl／Shift＋クリック：複数選択')
  local bNone=button(choices,PF.T('Clear selection','選択解除'),alRight,140)
  local bAll=button(choices,PF.T('Select all shown','表示中を全選択'),alRight,180)
  bNone.Visible=not opts.single;bAll.Visible=not opts.single
  local bClose=button(actions,PF.T('Close','閉じる'),alRight,110);bClose.Cancel=true
  local bAdd=button(actions,PF.T(opts.addEn or 'Add selected',opts.addJa or '選択した項目を追加'),alRight,220)
  local eq=createEdit(actions);eq.Align=alLeft;eq.Width=86;eq.Text='1';eq.Color=0x353535;eq.Font.Color=0xFFFFFF
  local lq=createLabel(actions);lq.Align=alLeft;lq.Layout='tlCenter';lq.Caption=PF.T('Quantity each (1–9999):  ','個数（各1～9999）： ')
  lq.Visible=not opts.noQty;eq.Visible=not opts.noQty
  local list=createListView(f);list.Align=alClient;list.BorderSpacing.Around=6;list.ViewStyle='vsReport';list.ReadOnly=true;list.RowSelect=true;list.HideSelection=false;list.MultiSelect=not opts.single
  list.Color=0x252525;list.Font.Color=0x000000 -- Native light column headers; row text is painted white below.
  for _,c in ipairs({{PF.T('Name','名前'),570},{PF.T('Category','カテゴリ'),180},{PF.T('ID / reference','ID／参照名'),280}})do local h=list.Columns.add();h.Caption=c[1];h.Width=c[2]end
  list.ShowColumnHeaders=false -- Native header theming differs between CE versions; use matching dark headers.
  local headerLabels={}
  for i=0,2 do local label=createLabel(headers);label.AutoSize=false;label.Font.Color=0xFFFFFF;label.Layout='tlCenter';label.Caption=list.Columns[i].Caption;local index=i;label.OnClick=function()list.OnColumnClick(list,list.Columns[index])end;headerLabels[i]=label end
  local function columnLayout()
    local width=math.max(700,list.ClientWidth-4);local widths={math.floor(width*.46),math.floor(width*.19),0};widths[3]=width-widths[1]-widths[2]
    local x=0 for i=0,2 do list.Columns[i].Width=widths[i+1];local label=headerLabels[i];label.Left=x+6;label.Top=0;label.Height=headers.Height;label.Width=widths[i+1]-12;x=x+widths[i+1]end
  end
  list.OnResize=columnLayout
  list.OnCustomDrawItem=function(sender,item)
    local r=item.displayRect('drBounds');local canvas=sender.Canvas;canvas.Font.Color=0xFFFFFF;canvas.Brush.Color=item.Selected and 0x805020 or 0x252525
    canvas.fillRect({Left=r.Left,Top=r.Top,Right=sender.ClientWidth,Bottom=r.Bottom})
    local x=r.Left;for i=0,2 do local width=sender.Columns[i].Width;local text=i==0 and item.Caption or item.SubItems[i-1];local cell={Left=x+6,Top=r.Top,Right=x+width-6,Bottom=r.Bottom};canvas.textRect(cell,x+6,r.Top+math.max(0,math.floor((r.Bottom-r.Top-canvas.getTextHeight(text))/2)),text);x=x+width end
    return false
  end
  local cats={}for _,c in ipairs(catList)do if c.key then cats[c.key]=c.label end end
  local labels={}
  for id,e in ipairs(entries)do
    local name,key=(e.label or ''):match('^(.-)%s+%[([^%]]+)%]$')
    labels[id]={name=name or e.label or '',key=key or '',cat=cats[e.cat]or e.cat or ''}
  end
  local shown,picked={},{};local busy,rendering=false,false;local column,ascending=0,true
  local function save()
    for i=0,list.Items.Count-1 do local id=shown[i+1];if id then picked[id]=list.Items[i].Selected or nil end end
  end
  local function selectionStatus()
    if rendering or busy then return end
    save();local n=0 for _ in pairs(picked)do n=n+1 end
    status.Caption=PF.T(('Shown %d / %d   Selected %d (selection is kept across filters)'):format(#shown,#entries,n),('表示 %d／%d件　選択 %d件（検索・絞り込みを変更しても保持）'):format(#shown,#entries,n))
    bAdd.Enabled=n&gt;0
  end
  local function refill()
    save();rendering=true;list.Items.beginUpdate();list.Items.clear();shown={}
    local q=(ed.Text or ''):lower();local cat=catList[(cb.ItemIndex or 0)+1];local ck=cat and cat.key
    for id,e in ipairs(entries)do if (not ck or ck==e.cat)and(q==''or(e.label or ''):lower():find(q,1,true))then shown[#shown+1]=id end end
    local field=column==1 and 'cat'or column==2 and 'key'or'name'
    table.sort(shown,function(a,b)local x,y=labels[a][field]:lower(),labels[b][field]:lower();if x==y then return a&lt;b end;if ascending then return x&lt;y else return x&gt;y end end)
    for _,id in ipairs(shown)do local item=list.Items.add();item.Caption=labels[id].name;item.SubItems.add(labels[id].cat);item.SubItems.add(labels[id].key);item.Selected=picked[id]and true or false end
    list.Items.endUpdate();rendering=false;selectionStatus()
  end
  list.OnSelectItem=function()selectionStatus()end
  list.OnColumnClick=function(_,col)if column==col.Index then ascending=not ascending else column=col.Index;ascending=true end;refill()end
  cb.OnChange=refill;ed.OnChange=refill
  clear.OnClick=function()cb.ItemIndex=0;ed.Text='';refill()end
  bAll.OnClick=function()rendering=true;for i=0,list.Items.Count-1 do list.Items[i].Selected=true end;rendering=false;selectionStatus()end
  bNone.OnClick=function()picked={};rendering=true;for i=0,list.Items.Count-1 do list.Items[i].Selected=false end;rendering=false;selectionStatus()end
  bAdd.OnClick=function()
    if busy then return end;save();local sel={}for id=1,#entries do if picked[id]then sel[#sel+1]=id end end
    if #sel==0 then return end
    local qty=opts.noQty and 1 or tonumber(eq.Text)
    if not qty or qty%1~=0 or qty&lt;1 or qty&gt;9999 then status.Caption=PF.T('Enter a whole quantity from 1 to 9999.','個数は1～9999の整数で入力してください。');return end
    busy=true;bAdd.Enabled=false;refresh.Enabled=false;cb.Enabled=false;ed.Enabled=false;list.Enabled=false;bAll.Enabled=false;bNone.Enabled=false;clear.Enabled=false;eq.Enabled=false
    status.Caption=PF.T('Working…','処理中…')
    local ok,result=pcall(onAdd,sel,qty)
    busy=false;refresh.Enabled=true;cb.Enabled=true;ed.Enabled=true;list.Enabled=true;bAll.Enabled=true;bNone.Enabled=true;clear.Enabled=true;eq.Enabled=true;bAdd.Enabled=true
    if ok and opts.single then f.ModalResult=mrOK;return end
    status.Caption=ok and(type(result)=='string'and result or PF.T('Done.','完了しました。'))or tostring(result)
    if not ok then print('['..PF.TAG..'] '..tostring(result))end
  end
  if opts.single then list.OnDblClick=function()bAdd.OnClick()end end
  refresh.OnClick=function()if not busy and opts.refresh then PF.userRun(opts.refresh)end end
  bClose.OnClick=function()f.close()end
  f.OnClose=function()
    if busy then return caNone end
    if PF.itemWin==f then PF.itemWin=nil;PF.itemUI=nil end
    return opts.modal and caHide or caFree
  end
  PF.itemUI={form=f,list=list,search=ed,category=cb,clearFilters=clear,refresh=refresh,selectAll=bAll,clearSelection=bNone,apply=bAdd,quantity=eq,status=status,close=bClose}
  f.Color=0x252525
  f.OnShow=columnLayout
  columnLayout()
  refill()
  if opts.modal then f.showModal();if PF.itemWin==f then PF.itemWin=nil;PF.itemUI=nil end;f.destroy();return nil end
  f.show();return f
end

function PF.pick(title,names)
  local entries={}for _,name in ipairs(names)do entries[#entries+1]={label=name}end
  local selected
  PF.itemWindow(title,entries,{{label=PF.T('All','すべて')}},function(ids)selected=ids[1]end,{single=true,modal=true,noQty=true,addEn='Select',addJa='選択'})
  return selected
end


----------------------------------------------------------------- [GAME] weather
-- AWeatherManager: SetWeatherRandomizationEnabled(false) stops new random conditions,
-- TerminateAllWeatherConditions() ends the active ones (back to the base weather). Repeated every 15 s while on.
PF.wx = PF.wx or {}
local function wxManager()
  local w=PF.wx
  if w.o and UE.isObj(w.o) and UE.cls(w.o)==w.cls then return w.o end
  local chunks=rq(UE.gobj); if not chunks then return nil end
  local isW={}
  for i=0,UE.count()-1 do
    local ch=rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local c=o and UE.cls(o)
    if c and ((ri(o+8) or 0)&amp;0x30)==0 then
      local k=isW[c]
      if k==nil then k=false local x=c local n=0 while x and n&lt;64 do if UE.clsName(x)=='WeatherManager' then k=true break end x=UE.super(x) n=n+1 end isW[c]=k end
      if k then PF.wx={o=o,cls=c} return o end
    end
  end
end
function PF.wxClearOn()
  PF.needPlayer()
  local o=wxManager() or PF.err('WeatherManager not found.','WeatherManagerが見つかりません。')
  PF.callFunc(o,'SetWeatherRandomizationEnabled',{false})
  PF.callFunc(o,'TerminateAllWeatherConditions',{})
  PF.wx.t=os.clock()
  PF.msg('Weather: randomization off, all weather conditions ended.','天候: ランダム変化を停止し、発生中の天候をすべて終了しました。')
end
function PF.wxClearOff()
  local o=PF.wx.o
  if o and PF.attached() and UE.isObj(o) then pcall(PF.callFunc,o,'SetWeatherRandomizationEnabled',{true}) end
  PF.wx.t=nil
end
local function wxTask()
  local w=PF.wx; if not w.o or not w.t then return end
  if os.clock()-w.t&gt;15 then w.t=os.clock() pcall(PF.callFunc,w.o,'TerminateAllWeatherConditions',{},{quick=true}) end
end

-- Scale the native result for the local movement component; GAS values remain owned by the game.
function PF.speedRefresh(required)
  local base=PF.base();if not base then return end
  local P=PF.player()
  local move=P and P.move
  if not move or not UE.live(move) or not UE.isA(move,'ALSCharacterMovementComponent') then
    writeQword(base+PF.OFF_PTRS+0xB0,0)
    if required then PF.err('Local ALS movement component not found.','プレイヤーの移動コンポーネントが見つかりません。') end
    return
  end
  local m=PF.rf(PF.var(0x20))
  if not m or m~=m or m&lt;=0 or m&gt;100 then
    writeQword(base+PF.OFF_PTRS+0xB0,0)
    if required then PF.err('Speed multiplier must be greater than 0 and at most 100.','移動速度倍率は0より大きく100以下にしてください。') end
    return
  end
  writeFloat(PF.var(0xA8),m)
  writeQword(base+PF.OFF_PTRS+0xB0,move)
end

----------------------------------------------------------------- [GAME] features
PF.F = {
  noDrunk    = { task=function() lockVal('AlcoholUnits',0) end,
                 on=function() PF.needAttr(PF.needPlayer(),'AlcoholUnits') end },
  speed      = { hooks={'moveSpeed'}, flag=0x15,
                 task=function() PF.speedRefresh(false) end,
                 on=function() PF.needPlayer();PF.speedRefresh(true) end,
                 off=function()
                   if PF.base() then writeQword(PF.base()+PF.OFF_PTRS+0xB0,0) end
                 end },
  jump       = { task=function() mvTask('jump','JumpZVelocity',0x24) end,
                 on=function() local P=PF.needPlayer() if not P.move then PF.err('CharacterMovement not found.','CharacterMovementが見つかりません。') end end,
                 off=function() mvOff('jump') end },
  xpMul      = { task=function() xpTask() end, on=function() PF.xpOn() end, off=function() PF.xpOff() end },
  todLock    = { task=function() todTask() end, on=function() PF.todSet() end },
  todNoon    = { task=function() todTask(12) end, on=function() PF.todSet(12) end },
  wxClear    = { hooks={'peCall'}, task=function() wxTask() end, on=function() PF.wxClearOn() end, off=function() PF.wxClearOff() end },
  craftFree  = { hooks={'craftReq','craftClr1','craftClr2','craftClr3','craftClr4'}, flag=0x11, task=function() craftTask() end, on=function() PF.craftOn() end, off=function() PF.craftOff() end },
}

----------------------------------------------------------------- [GAME] actions

-- list generator: every GAS attribute of the player (CurrentValue, editable)
function PF.refreshAttrList(mr)
  PF.clearChildren(mr)
  local P=PF.needPlayer()
  if #P.sets==0 then PF.addHdr(mr,'(no attribute set found)','（属性セットが見つかりません）') return end
  for _,s in ipairs(P.sets) do
    local h=PF.addHdr(mr,s.name,s.name)
    for _,at in ipairs(s.attrs) do
      local j=PF.attrJa(at.name)
      local en,ja=at.name, (j and (j..' ('..at.name..')') or at.name)
      PF.addRec(h,en,ja,('%X'):format(at.addr+0xC),vtSingle)
    end
  end
end
function PF.attrJa(n) for k,v in pairs(PF.ATTR_JA) do if k:lower()==n:lower() then return v end end end
PF.ATTR_JA = {
  Health='体力', MaxHealth='最大体力', Stamina='スタミナ', MaxStamina='最大スタミナ', Energy='エネルギー（疲労）',
  MaxEnergy='最大エネルギー', Hunger='空腹度', MaxHunger='最大空腹度', Stamina_RegenFactor='スタミナ回復係数',
  Stamina_DrainFactor='スタミナ消費係数', BodyWarmth='体温', MinBodyWarmth='最低体温', MaxBodyWarmth='最大体温',
  ThermalInsulation='断熱性', FinalTemperature='最終気温', HeatSourceTemperature='熱源温度',
  MaxHeatSourceTemperature='最大熱源温度', BodyWarmth_GainFactor='体温上昇係数', BodyWarmth_LossFactor='体温低下係数',
  BodyWarmth_BaseFactor='体温基本係数', AlcoholUnits='アルコール量', Armor='防具値', Durability='耐久度', MaxDurability='最大耐久度',
  MovementSpeedScale='移動速度倍率', Temperature='気温', ThreatScore='脅威度',
}

-- helpers shared with the release additions (game_rel.lua)
PF.invEachPublic=invEach
PF.frzValPublic=frzVal
PF.itemCandidatesPublic=itemCandidates

----------------------------------------------------------------- [GAME] release build additions
-- (appended after game_body.lua; uses its helpers)

-- survival: lock at MAX (the value never decreases)
function PF.lockMax(attr, maxAttr)
  local P=PF.player(); if not P then return end
  local a,m=P.attr[attr],P.attr[maxAttr]; if not a or not m then return end
  local mx=PF.rf(m+0xC); if not mx or mx&lt;=0 then return end
  if math.abs((PF.rf(a+0xC) or 0)-mx)&gt;0.001 or math.abs((PF.rf(a+8) or 0)-mx)&gt;0.001 then writeFloat(a+8,mx) writeFloat(a+0xC,mx) end
end

----------------------------------------------------------------- objects that declare a function
-- classes that declare UFunction fname (GObjects scan, cached by UE.findFuncUncached's list)
function UE.funcOwners(fname)
  UE.funcCache=UE.funcCache or {}
  local key=fname:lower()
  local list=UE.funcCache[key]
  if not list then
    -- build the list directly
    list={}
    local chunks=rq(UE.gobj)
    for i=0,UE.count()-1 do
      local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
      local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
      if o and (UE.objName(o) or ''):lower()==key and UE.clsName(UE.cls(o))=='Function' then list[#list+1]=o end
    end
    UE.funcCache[key]=list
  end
  local r={}
  for _,f in ipairs(list) do if UE.isFunc(f,fname) then local c=UE.outer(f) if c then r[c]=f end end end
  return r
end
local function classHas(c, owners)
  local n=0 while c and n&lt;64 do if owners[c] then return owners[c] end c=UE.super(c) n=n+1 end
end
-- a player sub-object (component) whose class chain declares fname
function PF.compWithFunc(P, fname)
  local owners=UE.funcOwners(fname)
  local list={P.pawn, P.pc} if P.ps then list[#list+1]=P.ps end
  for _,o in ipairs(P.subs) do list[#list+1]=o end
  for _,o in ipairs(list) do
    if o and UE.isObj(o) and ((ri(o+8) or 0)&amp;0x10)==0 then local f=classHas(UE.cls(o),owners) if f then return o,f end end
  end
end
-- any live (non-default) object whose class chain declares fname
PF.instCache = PF.instCache or {}
function PF.instanceWithFunc(fname)
  local c=PF.instCache[fname]
  if c and UE.isObj(c.o) and UE.cls(c.o)==c.cls then return c.o end
  local owners=UE.funcOwners(fname)
  local chunks=rq(UE.gobj); local seen={}
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local k=o and UE.cls(o)
    if k and ((ri(o+8) or 0)&amp;0x30)==0 then
      local hit=seen[k]; if hit==nil then hit=classHas(k,owners) and true or false seen[k]=hit end
      if hit then PF.instCache[fname]={o=o,cls=k} return o end
    end
  end
end

----------------------------------------------------------------- soft object pointer (TSoftObjectPtr, 0x28 bytes)
-- FWeakObjectPtr{ObjectIndex, SerialNumber} + FSoftObjectPath{PackageName FName, AssetName FName, SubPathString FString(empty)}
function PF.softOf(ptr)
  local idx=ri(ptr+UE.O.objIndex) or 0
  local chunks=rq(UE.gobj); local ch=chunks and rq(chunks+(idx//UE.O.chunk)*8)
  local serial=ch and ri(ch+(idx%UE.O.chunk)*UE.O.itemSize+0x10) or 0
  local pkg=ptr local k=0 while UE.outer(pkg) and k&lt;16 do pkg=UE.outer(pkg) k=k+1 end
  return { idx=idx, serial=serial, pkg=readQword(pkg+UE.O.objName), asset=readQword(ptr+UE.O.objName) }
end
function PF.writeSoft(addr, s)
  local z={} for i=1,0x28 do z[i]=0 end writeBytes(addr,z)
  writeInteger(addr,s.idx or 0) writeInteger(addr+4,s.serial or 0)
  writeQword(addr+8,s.pkg or 0) writeQword(addr+0x10,s.asset or 0)
end
-- FName (8 bytes) -&gt; string
local function fnameStr(q) if not q or q==0 then return nil end local a=PF.var(0xF0) writeQword(a,q) return UE.fname(a) end

----------------------------------------------------------------- no fall death
-- The character movement accumulates the fall duration while falling fast (GetCurrentFallDuration); the hook keeps it 0.
-- Typed fall damage is rejected before Actor::TakeDamage sends health/death events.
-- No health restoration is used; other damage types retain their normal behavior.
PF.fall = PF.fall or {}
PF.SIGS.ActorDamage={p='48 8B C4 48 89 58 08 48 89 70 10 48 89 78 20 55 41 54 41 55 41 56 41 57 48 8D A8 48 FC FF FF 48 81 EC 90 04 00 00',off=0,len=7}
PF.HOOKS.fallDamage={sig='ActorDamage',aa=[==[
[ENABLE]
alloc(pf_fall_damage,$1000,$SITE)
label(pf_fd_original)
label(pf_fd_return)
pf_fall_damage:
  pushfq
  push rax
  mov rax,pfFlags
  cmp byte ptr [rax+13],0
  je pf_fd_original
  mov rax,pfPtrs
  cmp qword ptr [rax+E0],0
  je pf_fd_original
  cmp rcx,[rax+E0]
  jne pf_fd_original
  test r8,r8
  je pf_fd_original
  cmp qword ptr [rax+E8],0
  je pf_fd_original
  push rdx
  mov rdx,[r8+8]
  cmp rdx,[rax+E8]
  pop rdx
  jne pf_fd_original
  lock inc qword ptr [rax+F0]
  pop rax
  popfq
  xorps xmm0,xmm0
  ret
pf_fd_original:
  pop rax
  popfq
  $ORIG
  jmp pf_fd_return
$SITE:
  jmp pf_fall_damage
  $NOP
pf_fd_return:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fall_damage)
]==]}
PF.SIGS.FallEffectApply={p='48 8B C4 4C 89 48 20 48 89 48 08 55 41 54 41 55 41 56 41 57 48 8D 68 A1 48 81 EC A0 00 00 00',off=0,len=7}
PF.HOOKS.fallEffect={sig='FallEffectApply',aa=[==[
[ENABLE]
alloc(pf_fall_effect,$1000,$SITE)
label(pf_fe_original)
label(pf_fe_return)
pf_fall_effect:
  pushfq
  push rax
  push r10
  mov rax,pfFlags
  cmp byte ptr [rax+13],0
  je pf_fe_original
  mov rax,pfPtrs
  cmp qword ptr [rax+C0],0
  je pf_fe_original
  cmp rcx,[rax+C0]
  jne pf_fe_original
  test rdx,rdx
  je pf_fe_original
  test r8,r8
  je pf_fe_original
  mov r10,[r8]
  test r10,r10
  je pf_fe_original
  cmp qword ptr [rax+C8],0
  je pf_fe_original
  mov r10,[r10+10]
  cmp r10,[rax+C8]
  jne pf_fe_original
  lock inc qword ptr [rax+D0]
  mov dword ptr [rdx],FFFFFFFF
  mov byte ptr [rdx+4],0
  pop r10
  pop rax
  popfq
  mov rax,rdx
  ret
pf_fe_original:
  pop r10
  pop rax
  popfq
  $ORIG
  jmp pf_fe_return
$SITE:
  jmp pf_fall_effect
  $NOP
pf_fe_return:
[DISABLE]
$SITE:
  $ORIG
dealloc(pf_fall_effect)
]==]}
function PF.fallGuardRefresh(required)
  local base=PF.base();if not base then return end
  local ptr=base+PF.OFF_PTRS
  local P=PF.player()
  if not P or not P.pawn or not P.move then
    writeQword(ptr+0xC0,0) writeQword(ptr+0xE0,0) writeQword(ptr+0xF8,0)
    if required then PF.err('Player movement is unavailable.','プレイヤーの移動情報を取得できません。') end
    return
  end
  local c=PF.fall.damageClass
  if not c or not UE.isObj(c) or UE.objName(c)~='DamageType_FallDamage_C' then
    c=PF.findObjByName('DamageType_FallDamage_C')
    PF.fall.damageClass=c
  end
  if not c then
    writeQword(ptr+0xC0,0) writeQword(ptr+0xE0,0) writeQword(ptr+0xF8,0) writeQword(ptr+0xE8,0)
    if required then PF.err('Fall damage type is not loaded. Enter the world and try again.','落下ダメージ種別が未読込です。ワールドに入って再実行してください。') end
    return
  end
  local asc=UE.getObj(P.pawn,'AbilityComponent')
  local effect=PF.fall.effectClass
  if not effect or not UE.isObj(effect) or UE.objName(effect)~='GE_DamageCore_Fall_C' then
    effect=PF.findObjByName('GE_DamageCore_Fall_C') PF.fall.effectClass=effect
  end
  if not asc or not effect then
    writeQword(ptr+0xC0,0) writeQword(ptr+0xE0,0) writeQword(ptr+0xF8,0)
    if required then PF.err('Fall effect or player ability component not loaded.','落下効果またはプレイヤーの能力コンポーネントが未読込です。') end
    return
  end
  writeQword(ptr+0xC8,effect) writeQword(ptr+0xC0,asc)
  writeQword(ptr+0xE8,c) writeQword(ptr+0xF8,P.move) writeQword(ptr+0xE0,P.pawn)
end


local function fallTask() PF.fallGuardRefresh(false) end

-- names that identify an inventory stack (object name, class name, referenced item data)
function PF.stackNames(e, base, L)
  local t={}
  if L.id then
    local k=L.idKind or ''
    if k:find('SoftObject',1,true) or k:find('SoftClass',1,true) then t[#t+1]=fnameStr(readQword(base+L.id+0x10))
    elseif k=='NameProperty' then t[#t+1]=fnameStr(readQword(base+L.id))
    else local o=rq(base+L.id) if o and UE.isObj(o) then t[#t+1]=UE.objName(o) end end
  end
  if e.objects then t[#t+1]=UE.objName(base) t[#t+1]=UE.clsName(UE.cls(base)) end
  return t
end
----------------------------------------------------------------- inventory amount list (editable)
function PF.refreshInvList(mr)
  PF.clearChildren(mr)
  local P=PF.needPlayer()
  local rows={}
  PF.invEachPublic(P, function(e,i,base,L,ident)
    if L.amount then rows[#rows+1]={e=e,i=i,base=base,L=L} end
  end)
  if #rows==0 then PF.addHdr(mr,'(no inventory stack found)','（所持品が見つかりません）') return end
  PF.msg('Reading item names from the game...','ゲームからアイテム名を取得しています…')
  local groups={}
  for _,r in ipairs(rows) do
    local disp
    local names=PF.stackNames(r.e,r.base,r.L)
    -- display name: the stack object itself, or the referenced item data if it is loaded
    if r.L.id then
      local k=r.L.idKind or ''
      local o
      if k:find('Soft',1,true) then o=PF.resolveSoft(r.base+r.L.id)
      else o=rq(r.base+r.L.id) if o and not UE.isObj(o) then o=nil end end
      if o then local ok,t=pcall(PF.itemDisplayName,o) if ok then disp=t end end
    end
    if not disp and r.e.objects then local ok,t=pcall(PF.itemDisplayName, r.base) if ok then disp=t end end
    local internal=nil for _,s in ipairs(names) do if s and s~='?' then internal=s break end end
    local label=(disp or internal or '?')..(disp and internal and ('  ['..internal..']') or '')
    local g=groups[r.e.owner]
    if not g then g=PF.addHdr(mr,UE.objName(r.e.owner),UE.objName(r.e.owner)) groups[r.e.owner]=g end
    local vt=(r.L.amount.kind=='FloatProperty') and vtSingle or vtDword
    PF.addRec(g, ('[%d] %s'):format(r.i,label), ('[%d] %s'):format(r.i,label), ('%X'):format(r.base+r.L.amount.off), vt)
  end
end
-- object referenced by a TSoftObjectPtr: weak pointer (index + serial) first, then by asset name
function PF.resolveSoft(addr)
  local idx=ri(addr); local serial=ri(addr+4)
  if idx and idx&gt;0 and idx&lt;UE.count() and serial and serial~=0 then
    local chunks=rq(UE.gobj); local ch=chunks and rq(chunks+(idx//UE.O.chunk)*8)
    local item=ch and ch+(idx%UE.O.chunk)*UE.O.itemSize
    local o=item and rq(item)
    if o and ri(item+0x10)==serial and UE.isObj(o) then return o end
  end
  local nm=fnameStr(readQword(addr+0x10))
  return nm and PF.findObjByName(nm)
end
PF.objByName = PF.objByName or {}
function PF.findObjByName(nm)
  local c=PF.objByName[nm]
  if c and UE.isObj(c) and UE.objName(c)==nm then return c end
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if o and ((ri(o+8) or 0)&amp;0x10)==0 and UE.objName(o)==nm then PF.objByName[nm]=o return o end
  end
end

----------------------------------------------------------------- blueprints (recipes): learn from a list / learn all
-- UPlayerKnowledgeComponent: SERVER_LearnRecipesBatch(const TArray&lt;TSoftObjectPtr&lt;Recipe&gt;&gt;&amp;, bShowNotification),
-- SERVER_LearnAllRecipes(), SERVER_LearnRecipeSet(TSoftObjectPtr&lt;RecipeSet&gt;).  Standalone game: runs locally.
local function knowledge(P)
  local o=PF.compWithFunc(P,'SERVER_LearnRecipesBatch')
  if not o then PF.err('Player knowledge component (recipes) not found.','プレイヤーの知識コンポーネント（設計図・レシピ）が見つかりません。') end
  return o
end
-- class of a soft object parameter of a function
local function softParamClass(o, fname, pname)
  local f=UE.findFunc(o,fname); if not f then return nil end
  for _,pr in ipairs(UE.ownProps(f)) do
    if pr.lname==pname:lower() then
      if pr.kind=='ArrayProperty' then local inn=UE.innerOf(pr) if inn then return UE.objPropClass({f=inn.f,kind=inn.kind}) end end
      return UE.objPropClass(pr)
    end
  end
end
-- game memory for a TArray of soft pointers (kept for the session; the game only reads it)
local function arrayMem(n)
  PF.arrMem=PF.arrMem or {}
  local need=n*0x28+0x40
  if not PF.arrMem.a or PF.arrMem.size&lt;need or PF.arrMem.pid~=PF.pid then
    local sz=math.max(need,0x10000)
    PF.arrMem={a=allocateMemory(sz), size=sz, pid=PF.pid}
  end
  return PF.arrMem.a
end
function PF.learnRecipes(know, ptrs)
  local n=#ptrs; if n==0 then return 0 end
  local mem=arrayMem(n)
  for i,p in ipairs(ptrs) do PF.writeSoft(mem+(i-1)*0x28, PF.softOf(p)) end
  PF.callFunc(know,'SERVER_LearnRecipesBatch', function(fn)
    local a={}
    for _,pr in ipairs(UE.ownProps(fn)) do if pr.kind=='BoolProperty' then a[pr.name]=true end end
    a.__raw=function(buf)
      for _,pr in ipairs(UE.ownProps(fn)) do
        if pr.kind=='ArrayProperty' then writeQword(buf+pr.off,mem) writeInteger(buf+pr.off+8,n) writeInteger(buf+pr.off+12,n) end
      end
    end
    return a
  end, {safe=true})
  return n
end
function PF.learnAll()
  local P=PF.needPlayer()
  local know=knowledge(P)
  PF.callFunc(know,'SERVER_LearnAllRecipes',{}, {safe=true})
  PF.msg('All recipes (blueprints) learned.','すべての設計図（レシピ）を入手しました。')
end
function PF.learnPick()
  local P=PF.needPlayer()
  local know=knowledge(P)
  local rc=softParamClass(know,'SERVER_LearnRecipesBatch','Recipes')
  if not rc then PF.err('Recipe class not resolved.','レシピのクラスを特定できません。') end
  PF.msg('Reading blueprint names from the game (first time only)...','ゲームから設計図名を取得しています（初回のみ）…')
  local list=PF.itemCandidatesPublic(rc,false)
  if #list==0 then PF.err('No loaded recipe found ('..UE.objName(rc)..').','読み込み済みの設計図（レシピ）がありません（'..UE.objName(rc)..'）。') end
  local cats,order={},{}
  for _,e in ipairs(list) do local c=e.cat or '?' if not cats[c] then cats[c]=0 order[#order+1]=c end cats[c]=cats[c]+1 end
  table.sort(order)
  local catList={{key=nil,label=PF.T('(all) ','（すべて） ')..#list}}
  for _,c in ipairs(order) do
    local m=PF.ITEM_CAT[c]
    catList[#catList+1]={key=c,label=(m and PF.T(m[1],m[2]) or (c=='?' and PF.T('(other)','（その他）') or c))..'  ('..c..')  '..cats[c]}
  end
  local entries={}
  for k,e in ipairs(list) do entries[k]={cat=e.cat or '?', label=(e.disp and (e.disp..'  ['..e.name..']') or e.name)} end
  PF.itemWindow(PF.T('Add blueprints (recipes)','設計図（レシピ）を追加'), entries, catList, function(sel)
    local P2=PF.needPlayer()
    local k2=knowledge(P2)
    local ptrs={}
    for _,idx in ipairs(sel) do local p=list[idx].ptr if p and UE.isObj(p) then ptrs[#ptrs+1]=p end end
    local n=PF.learnRecipes(k2, ptrs)
    PF.msg(('Learned %d blueprint(s).'):format(n),('設計図を %d 件入手しました。'):format(n))
    return PF.T(('Learned %d.'):format(n),('%d件入手しました。'):format(n))
  end, {noQty=true, addEn='  Learn  ', addJa='  入手  '})
end

----------------------------------------------------------------- weather: choose / lock
-- UWeatherSubsystem: GetAllWeatherConditions(bLoadedOnly) -&gt; TArray&lt;TSoftObjectPtr&lt;WeatherCondition&gt;&gt;,
-- ForceWeatherCondition(InCondition, Phase, bTerminateCurrent), SetWeatherProgressionPaused(bPaused).
-- AWeatherManager: SetWeatherRandomizationEnabled(bEnabled).
PF.wxs = PF.wxs or {}
local function wxSub() return PF.instanceWithFunc('ForceWeatherCondition') or PF.err('Weather subsystem not found.','天候サブシステムが見つかりません。') end
local function enumIndex(fn, pname, valueName)
  for _,pr in ipairs(UE.ownProps(fn)) do
    if pr.lname==pname:lower() then
      local e=UE.enumOfProp(pr); if not e then return nil end
      local d=rq(e+0x40); local n=ri(e+0x48) or 0
      for i=0,math.min(n,256)-1 do
        local nm=UE.fname(d+i*0x10)
        if nm and nm:gsub('^.*::','')==valueName then return readQword(d+i*0x10+8) end
      end
    end
  end
end
function PF.wxList()
  local sub=wxSub()
  local out={}
  PF.callFunc(sub,'GetAllWeatherConditions', function(fn)
    local a={} for _,pr in ipairs(UE.ownProps(fn)) do if pr.kind=='BoolProperty' then a[pr.name]=false end end
    a.__raw=function(buf) end
    return a
  end)
  local f=UE.findFunc(sub,'GetAllWeatherConditions')
  local roff
  for _,pr in ipairs(UE.ownProps(f)) do if pr.kind=='ArrayProperty' then roff=pr.off end end
  local buf=PF.base()+0x300
  local data=rq(buf+(roff or 8)); local num=ri(buf+(roff or 8)+8) or 0
  for i=0,math.min(num,256)-1 do
    local el=data+i*0x28
    local pkg,asset=readQword(el+8),readQword(el+0x10)
    local nm=fnameStr(asset)
    if nm then out[#out+1]={pkg=pkg,asset=asset,name=nm} end
  end
  return out
end
function PF.wxForce(c)
  local sub=wxSub()
  local mgr=PF.instanceWithFunc('SetWeatherRandomizationEnabled')
  if mgr then pcall(PF.callFunc,mgr,'SetWeatherRandomizationEnabled',{false}) end
  PF.callFunc(sub,'ForceWeatherCondition', function(fn)
    local a={}
    for _,pr in ipairs(UE.ownProps(fn)) do if pr.kind=='BoolProperty' then a[pr.name]=true end end
    local ph=enumIndex(fn,'Phase','EWCP_Culmination') or 0
    a.__raw=function(buf)
      for _,pr in ipairs(UE.ownProps(fn)) do
        if pr.kind=='SoftObjectProperty' then PF.writeSoft(buf+pr.off,{pkg=c.pkg,asset=c.asset})
        elseif pr.lname=='phase' then writeBytes(buf+pr.off,ph) end
      end
    end
    return a
  end, {safe=true})
end
function PF.wxPick()
  PF.needPlayer()
  local list=PF.wxList()
  if #list==0 then PF.err('No weather condition found.','天候の種類が見つかりません。') end
  local names={}
  for i,c in ipairs(list) do
    local disp
    local o=PF.findObjByName(c.name); if o then local ok,t=pcall(PF.itemDisplayName,o) if ok then disp=t end end
    names[i]=(disp and (disp..'  ['..c.name..']') or c.name)
  end
  local i=PF.pick(PF.T('Weather (set now; [Lock weather] keeps it)','天候（今すぐ設定。【天候を固定】で維持）'), names)
  if not i then return end
  PF.wxs.cur=list[i] PF.wxs.label=names[i]
  PF.wxForce(list[i])
  PF.wxs.t=os.clock()
  PF.msg('Weather set: '..names[i],'天候を設定しました: '..names[i])
end
local function wxLockOn()
  PF.needPlayer()
  if not PF.wxs.cur then PF.err('Choose a weather first ([Set weather...]).','先に【天候を選んで設定…】で天候を選んでください。') end
  local sub=wxSub()
  local mgr=PF.instanceWithFunc('SetWeatherRandomizationEnabled')
  if mgr then pcall(PF.callFunc,mgr,'SetWeatherRandomizationEnabled',{false}) end
  pcall(PF.callFunc,sub,'SetWeatherProgressionPaused',{true})
  PF.wxs.lock=true PF.wxs.t=os.clock()
  PF.msg('Weather locked: '..tostring(PF.wxs.label),'天候を固定しました: '..tostring(PF.wxs.label))
end
local function wxLockOff()
  PF.wxs.lock=false
  if not PF.attached() then return end
  local ok,sub=pcall(wxSub); if ok and sub then pcall(PF.callFunc,sub,'SetWeatherProgressionPaused',{false}) end
  local mgr=PF.instCache['SetWeatherRandomizationEnabled'] and PF.instCache['SetWeatherRandomizationEnabled'].o
  if mgr and UE.isObj(mgr) then pcall(PF.callFunc,mgr,'SetWeatherRandomizationEnabled',{true}) end
end
local function wxLockTask()
  if not PF.wxs.lock or os.clock()-(PF.wxs.t or 0)&lt;15 then return end
  PF.wxs.t=os.clock()
  local ok,sub=pcall(wxSub)
  if ok and sub then pcall(PF.callFunc,sub,'SetWeatherProgressionPaused',{true},{quick=true}) end
end

----------------------------------------------------------------- feature table (release)
PF.F.infHealth  = { task=function() PF.lockMax('Health','MaxHealth') end, on=function() PF.needAttr(PF.needPlayer(),'Health','MaxHealth') end }
PF.F.infStamina = { task=function() PF.lockMax('Stamina','MaxStamina') end, on=function() PF.needAttr(PF.needPlayer(),'Stamina','MaxStamina') end }
PF.F.noHunger   = { task=function() PF.lockMax('Hunger','MaxHunger') end, on=function() PF.needAttr(PF.needPlayer(),'Hunger','MaxHunger') end }
PF.F.noFatigue  = { task=function() PF.lockMax('Energy','MaxEnergy') end, on=function() PF.needAttr(PF.needPlayer(),'Energy','MaxEnergy') end }
PF.F.noCold     = { task=function() PF.lockMax('BodyWarmth','MaxBodyWarmth') end, on=function() PF.needAttr(PF.needPlayer(),'BodyWarmth','MaxBodyWarmth') end }
PF.F.noFall     = { hooks={'fallDur','fallDamage','fallEffect'}, flag=0x13, task=function() fallTask() end, on=function() PF.needPlayer() PF.fall={} PF.fallGuardRefresh(true) writeQword(PF.base()+PF.OFF_PTRS+0xF0,0) writeQword(PF.base()+PF.OFF_PTRS+0xD0,0) end, off=function() if PF.base() then writeQword(PF.base()+PF.OFF_PTRS+0xC0,0) writeQword(PF.base()+PF.OFF_PTRS+0xE0,0) writeQword(PF.base()+PF.OFF_PTRS+0xF8,0) end PF.fall={} end }
PF.F.wxLock     = { hooks={'peCall'}, task=function() wxLockTask() end, on=function() wxLockOn() end, off=function() wxLockOff() end }

----------------------------------------------------------------- infinite fuel
-- The game code that burns fuel is patched (flag 14, hooks in game_head.lua): fuel stations (campfire / stove /
-- furnace ...), power supplies (generators) and vehicles skip the fuel subtraction. No object search is needed.
-- Items with FuelPercent in the inventory (lanterns etc.) are kept from decreasing by the timer (inventory only).
PF.fuel = PF.fuel or { frz={} }
local FUEL_HOOKS={ {'fuelStation','fuel stations','燃料を使う設備'}, {'fuelSupply','power supplies','電源（発電機）'}, {'fuelVehicle','vehicles','乗り物'} }
local function fuelTask()
  local P=PF.player()
  if P then
    PF.invEachPublic(P, function(e,i,base,L,ident)
      if L.fuel then PF.frzValPublic(('%X:%d:%X:f'):format(e.a,i,ident or 0), base+L.fuel.off, L.fuel.kind) end
    end)
  end
end
local function fuelOn()
  PF.needPlayer()
  PF.fuel={ frz={} }
  local okN,ng={},{}
  for _,h in ipairs(FUEL_HOOKS) do
    local ok,e=pcall(PF.hookOn,h[1])
    if ok then okN[#okN+1]=PF.T(h[2],h[3]) else ng[#ng+1]=PF.T(h[2],h[3])..': '..tostring(e) end
  end
  if #okN==0 then PF.err('Fuel code not found: '..table.concat(ng,' / '),'燃料のゲームコードが見つかりません: '..table.concat(ng,' / ')) end
  PF.msg('Infinite fuel: '..table.concat(okN,', ')..' + inventory items (lanterns etc.).','燃料無限: '..table.concat(okN,'、')..'＋所持品（ランタン等）。')
  for _,x in ipairs(ng) do PF.msg('  not available: '..x,'  使用不可: '..x) end
end
local function fuelOff()
  for _,h in ipairs(FUEL_HOOKS) do pcall(PF.hookOff,h[1]) end
  PF.fuel={ frz={} }
end
PF.F.fuelInf    = { flag=0x14, task=function() fuelTask() end, on=function() fuelOn() end, off=function() fuelOff() end }

----------------------------------------------------------------- helpers: call a function and read its parameter block
local BUF=function() return PF.base()+0x300 end
local function propOff(o, fname)
  local f=UE.findFunc(o,fname); if not f then PF.err('Game function not found: '..fname,'ゲームの関数が見つかりません: '..fname) end
  local t={} for _,pr in ipairs(UE.ownProps(f)) do t[pr.lname]=pr end
  return t
end
local function writeVec(a,x,y,z) writeDouble(a,x) writeDouble(a+8,y) writeDouble(a+16,z) end
local function readVec(a) return readDouble(a), readDouble(a+8), readDouble(a+16) end
local function cdoOf(name)
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local x=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if x and UE.objName(x)==name then return x end
  end
end
PF.cdoCache = PF.cdoCache or {}
local function cdo(name)
  local c=PF.cdoCache[name]; if c and UE.isObj(c) and UE.objName(c)==name then return c end
  c=cdoOf(name); if not c then PF.err(name..' not found.',name..' が見つかりません。') end
  PF.cdoCache[name]=c return c
end
function PF.actorLocation(a)
  PF.callFunc(a,'K2_GetActorLocation',{})
  local p=propOff(a,'K2_GetActorLocation')
  return readVec(BUF()+p.returnvalue.off)
end
local function actorForward(a)
  PF.callFunc(a,'GetActorForwardVector',{})
  local p=propOff(a,'GetActorForwardVector')
  return readVec(BUF()+p.returnvalue.off)
end
-- Trace the terrain/surface below the marker, not the invisible top of a level boundary.
local function groundZ(pawn, x, y, ztop, zbot, shape, complex)
  local ksl=cdo('Default__KismetSystemLibrary')
  local fname=shape and 'CapsuleTraceSingle' or 'LineTraceSingle'
  local p=propOff(ksl,fname)
  local hitSt=UE.structOf(p.outhit)
  local locOff=hitSt and UE.findIn(hitSt,0,'Location',0)
  local compPr=hitSt and UE.findProp(hitSt,'Component')
  local normalOff=hitSt and UE.findIn(hitSt,0,'ImpactNormal',0)
  local penetration=hitSt and UE.findProp(hitSt,'bStartPenetrating')
  local rb=UE.boolInfo(p.returnvalue)
  if not locOff or not compPr or not normalOff or not rb or not p.actorstoignore then
    PF.err('Ground trace layout unavailable.','地面検索に必要な構造を取得できません。')
  end
  local ignored={pawn};local seen={[pawn]=true}
  for attempt=1,16 do
    PF.callFunc(ksl,fname,{ __raw=function(buf)
      writeQword(buf+p.worldcontextobject.off,pawn)
      writeVec(buf+p.start.off,x,y,ztop) writeVec(buf+p['end'].off,x,y,zbot)
      writeBytes(buf+p.tracechannel.off,0)
      if shape then writeFloat(buf+p.radius.off,shape.radius) writeFloat(buf+p.halfheight.off,shape.height) end
      if complex then local bi=UE.boolInfo(p.btracecomplex);if bi then writeBytes(buf+bi.off,bi.mask) end end
      local bi=UE.boolInfo(p.bignoreself)
      if bi then local v=readBytes(buf+bi.off,1,true)[1] writeBytes(buf+bi.off,v|bi.mask) end
      -- Scratch array stays inside the call buffer and beyond LineTraceSingle's parameters.
      local ar=buf+0x800
      for i,o in ipairs(ignored) do writeQword(ar+(i-1)*8,o) end
      writeQword(buf+p.actorstoignore.off,ar)
      writeInteger(buf+p.actorstoignore.off+8,#ignored)
      writeInteger(buf+p.actorstoignore.off+12,#ignored)
    end }, {safe=true,quick=true})
    local hit=(readBytes(BUF()+rb.off,1,true)[1]&amp;rb.mask)~=0
    if not hit then return nil,'unloaded' end
    local ha=BUF()+p.outhit.off
    local index=readInteger(ha+compPr.off)
    local component=index and index&gt;0 and UE.objAt(index)
    local actor=component
    for i=1,8 do
      if not actor or not UE.isObj(actor) or UE.isA(actor,'Actor') then break end
      actor=UE.outer(actor)
    end
    if not actor or not UE.isObj(actor) or not UE.isA(actor,'Actor') then return nil,'unknown surface' end
    if UE.isA(actor,'Volume') then
      if seen[actor] then return nil,'boundary' end
      seen[actor]=true ignored[#ignored+1]=actor
    else
      local bi=penetration and UE.boolInfo(penetration)
      if bi and (readBytes(ha+bi.off,1)&amp;bi.mask)~=0 then return nil,'penetrating' end
      local nz=readDouble(ha+normalOff+16)
      if not nz or nz&lt;0.5 then return nil,'steep' end
      local _,_,z=readVec(ha+locOff)
      return z,'surface'
    end
  end
  return nil,'boundary'
end

----------------------------------------------------------------- no fall death (v2): fall speed limit
-- The fall damage is not computed in native code (only the Blueprint knows it), so the falling speed is limited
-- instead: while falling, the downward velocity is kept at most PF.FALL_LIMIT cm/s (checked every 10 ms).
PF.FALL_LIMIT = 700
local function fastFall()
  local P=PF.P; if not P or not P.move or not UE.isObj(P.move) then return end
  local mm=UE.prop(P.move,'MovementMode'); if not mm then return end
  local b=readBytes(mm,1,true); if not b or b[1]~=3 then
    if PF.fall.slowUntil and os.clock()&gt;PF.fall.slowUntil then PF.fall.slowUntil=nil end
    return end   -- MOVE_Falling = 3
  if PF.fall.velMove~=P.move then PF.fall.vel=UE.prop(P.move,'Velocity') PF.fall.velMove=P.move end
  local v=PF.fall.vel; if not v then return end
  local vz=readDouble(v+16)
  if vz and vz&lt; -PF.FALL_LIMIT then writeDouble(v+16,-PF.FALL_LIMIT) end
end
local function fallTimerOn()
  if PF.fallTimer then return end
  PF.fallTimer=createTimer(nil,false) PF.fallTimer.Interval=10
  PF.fallTimer.OnTimer=function() if PF.attached() and (PF.featOn.noFall or PF.fall.slowUntil) then pcall(fastFall) end end
  PF.fallTimer.Enabled=true
end
local oldFallOn=PF.F.noFall.on
PF.F.noFall.on=function() oldFallOn() fallTimerOn() end

----------------------------------------------------------------- instant craft: recipe and item recycling durations -&gt; 0.1 s while enabled
PF.icraft = PF.icraft or { orig={}, t=0 }
local function recipeCls(c)
  if UE.findProp(c,'Time') and UE.findProp(c,'Cost') and UE.findProp(c,'Result') then return true end
  local pr=UE.findProp(c,'RecyclingConfig')
  local st=pr and pr.kind=='StructProperty' and UE.structOf(pr)
  local time=st and UE.findProp(st,'RecyclingTime')
  return time and time.kind=='FloatProperty' or false
end
local function recipeObj(o,c)
  if ((ri(o+8) or 0)&amp;0x10)~=0 then return nil end
  local cfg,pr=UE.prop(o,'RecyclingConfig')
  local st=pr and pr.kind=='StructProperty' and UE.structOf(pr)
  local time=st and UE.findProp(st,'RecyclingTime')
  if cfg and time and time.kind=='FloatProperty' then return {o=o,cls=c,a=cfg+time.off,kind='recycle'} end
  local a,p=UE.prop(o,'Time')
  if a and p.kind=='FloatProperty' then return {o=o,cls=c,a=a,kind='craft'} end
end
local function recipeScan()
  local r={}
  local chunks=rq(UE.gobj); local isR={}
  local ci,ch=-1,nil
  for i=0,UE.count()-1 do
    local cx=i//UE.O.chunk
    if cx~=ci then ch=chunks and rq(chunks+cx*8) ci=cx end
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local c=o and UE.cls(o)
    if c then
      local k=isR[c]; if k==nil then k=recipeCls(c) isR[c]=k end
      if k then local e=recipeObj(o,c) if e then r[#r+1]=e end end
    end
  end
  PF.icraft.list=r PF.icraft.t=os.clock()
  PF.sliceAdd('recipe', recipeCls, recipeObj, function(list) PF.icraft.list=list PF.icraft.t=os.clock() end)
  return r
end
local function icraftTask()
  local S=PF.icraft
  for _,e in ipairs(S.list or {}) do
    if UE.isObj(e.o) and UE.cls(e.o)==e.cls then
      local v=PF.rf(e.a)
      if v and v&gt;0.1001 then
        local old=S.orig[e.a]
        if not old or old.o~=e.o or old.cls~=e.cls then
          S.orig[e.a]={o=e.o,cls=e.cls,value=v,kind=e.kind}
        end
        writeFloat(e.a,0.1)
      end
    end
  end
end
local function icraftOn()
  PF.needPlayer()
  PF.icraft={orig={},t=0}
  local list=recipeScan();local craft,recycle=0,0
  for _,e in ipairs(list) do if e.kind=='recycle' then recycle=recycle+1 else craft=craft+1 end end
  icraftTask()
  PF.msg(('Instant craft: %d recipes / %d recycling configs (0.1 s; zero-duration entries preserved).'):format(craft,recycle),
         ('インスタントクラフト: レシピ %d件／リサイクル設定 %d件（0.1秒。元から待ち時間0の項目は維持）。'):format(craft,recycle))
end
local function icraftOff()
  PF.sliceDel('recipe')
  if PF.attached() then
    for a,entry in pairs(PF.icraft.orig or {}) do
      if type(entry)=='table' and UE.isObj(entry.o) and UE.cls(entry.o)==entry.cls then
        local current=recipeObj(entry.o,entry.cls)
        if current and current.a==a and math.abs((PF.rf(a) or 0)-0.1)&lt;0.0001 then writeFloat(a,entry.value) end
      end
    end
  end
  PF.icraft={orig={},t=0}
end

-- Shorten the configuration duration while preserving the normal construction path.
PF.ibuild = PF.ibuild or {}
local function ibuildAddr(dm)
  local a,pr=UE.findIn(UE.cls(dm),dm,'bDisableBuildTime',2)
  if not a or not pr or pr.kind~='BoolProperty' then return nil end
  local bi=UE.boolInfo(pr);if not bi then return nil end
  return (a-pr.off)+bi.off,bi.mask
end
local function ibuildConfigClass(c)
  local p=UE.findProp(c,'ConstructionTime')
  return p and p.kind=='FloatProperty' or false
end
local function ibuildConfig(o,c)
  if ((ri(o+8) or 0)&amp;0x10)~=0 then return nil end
  local a,p=UE.prop(o,'ConstructionTime')
  if a and p.kind=='FloatProperty' then return {o=o,cls=c,a=a} end
end
local function ibuildRememberBool(o,a,mask)
  local B=PF.ibuild;local bytes=readBytes(a,1,true);if not bytes then return end
  local old=B.bools[a]
  if not old or old.o~=o or old.cls~=UE.cls(o) then B.bools[a]={o=o,cls=UE.cls(o),mask=mask,value=bytes[1]&amp;mask} end
  writeBytes(a,bytes[1]&amp;(~mask&amp;0xFF))
end
local function ibuildNormalPath(required)
  local B=PF.ibuild
  if not B.dm or not UE.isObj(B.dm) or UE.cls(B.dm)~=B.dmClass then
    B.dm=PF.instanceWithFunc('SetDisableBuildTime');B.dmClass=B.dm and UE.cls(B.dm)
  end
  local a,m
  if B.dm then a,m=ibuildAddr(B.dm) end
  if not a or not m then
    if required then PF.err('Build-time setting not found.','建築時間の設定が見つかりません。') end
    return
  end
  ibuildRememberBool(B.dm,a,m)
  local P=PF.player()
  local component=P and (UE.getObj(P.pawn,'BuildingComponent') or UE.getObj(P.pc,'PlayerBuildingComp'))
  local addr,pr
  if component then addr,pr=UE.prop(component,'bDisableBuildTime') end
  local bi=pr and pr.kind=='BoolProperty' and UE.boolInfo(pr)
  if not component or not addr or not bi then
    if required then PF.err('Player building component setting not found.','プレイヤーの建築コンポーネント設定が見つかりません。') end
    return
  end
  ibuildRememberBool(component,component+bi.off,bi.mask)
end
local function ibuildTask()
  local B=PF.ibuild;if not B.times then return end
  ibuildNormalPath(false)
  for _,e in ipairs(B.list or {}) do
    if UE.isObj(e.o) and UE.cls(e.o)==e.cls then
      local value=PF.rf(e.a)
      if value and value&gt;0.1001 then
        local old=B.times[e.a]
        if not old or old.o~=e.o or old.cls~=e.cls then B.times[e.a]={o=e.o,cls=e.cls,value=value} end
        writeFloat(e.a,0.1)
      end
    end
  end
end
local function ibuildOn()
  PF.needPlayer();PF.ibuild={times={},bools={},list={}}
  ibuildNormalPath(true)
  local list={};local matches={};local chunks=rq(UE.gobj);local ci,ch=-1,nil
  for i=0,UE.count()-1 do
    local cx=i//UE.O.chunk;if cx~=ci then ch=chunks and rq(chunks+cx*8);ci=cx end
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize);local c=o and UE.cls(o)
    if c then
      if matches[c]==nil then matches[c]=ibuildConfigClass(c) end
      if matches[c] then local e=ibuildConfig(o,c);if e then list[#list+1]=e end end
    end
  end
  PF.ibuild.list=list
  PF.sliceAdd('buildTime',ibuildConfigClass,ibuildConfig,function(items) PF.ibuild.list=items end)
  ibuildTask()
  PF.msg(('Instant build: %d configs; 0.1 s base time, normal construction completion.'):format(#list),
         ('インスタント建築: 設定 %d件。基本時間0.1秒、通常の建築完了処理を使用します。'):format(#list))
end
local function ibuildOff()
  PF.sliceDel('buildTime');local B=PF.ibuild
  if PF.attached() then
    for a,e in pairs(B.times or {}) do
      if UE.isObj(e.o) and UE.cls(e.o)==e.cls and UE.prop(e.o,'ConstructionTime')==a then
        if math.abs((PF.rf(a) or 0)-0.1)&lt;0.0001 then writeFloat(a,e.value) end
      end
    end
    for a,e in pairs(B.bools or {}) do
      if UE.isObj(e.o) and UE.cls(e.o)==e.cls then
        local v=readBytes(a,1,true)
        if v and (v[1]&amp;e.mask)==0 then writeBytes(a,(v[1]&amp;(~e.mask&amp;0xFF))|e.value) end
      end
    end
  end
  PF.ibuild={}
end

----------------------------------------------------------------- teleport to any map sticker (all icon types)
PF.tp = PF.tp or {}
local function tpFinite(v) return type(v)=='number' and v==v and math.abs(v)&lt;1e9 end
local function tpMove(P,x,y,z)
  local p=propOff(P.pawn,'K2_TeleportTo')
  local rb=p.returnvalue and UE.boolInfo(p.returnvalue)
  if not p.destlocation or not p.destrotation or not rb then error('Teleport parameter layout unavailable.',0) end
  PF.callFunc(P.pawn,'K2_GetActorRotation',{}, {safe=true,quick=true})
  local r=propOff(P.pawn,'K2_GetActorRotation')
  local pitch,yaw,roll=readVec(BUF()+r.returnvalue.off)
  PF.callFunc(P.pawn,'K2_TeleportTo',{ __raw=function(buf)
    writeVec(buf+p.destlocation.off,x,y,z)
    writeVec(buf+p.destrotation.off,pitch,yaw,roll)
  end },{safe=true,quick=true})
  if (readBytes(BUF()+rb.off,1,true)[1]&amp;rb.mask)==0 then
    PF.err('The game rejected this teleport destination (collision).','ゲームが移動先を拒否しました（衝突判定）。')
  end
  local ax,ay,az=PF.actorLocation(P.pawn)
  if not tpFinite(ax) or not tpFinite(ay) or not tpFinite(az) or
      (ax-x)^2+(ay-y)^2&gt;250^2 or math.abs(az-z)&gt;500 then
    PF.err('Teleport arrival could not be verified.','移動先への到達を確認できませんでした。')
  end
  return ax,ay,az
end
-- Query the actual scaled collision capsule instead of deriving height from a single ground point.
local function tpShape(P)
  local capsule=UE.getObj(P.pawn,'CapsuleComponent') or UE.getObj(P.pawn,'RootComponent')
  if not capsule then error('Player capsule not found.',0) end
  local p=propOff(capsule,'GetScaledCapsuleSize')
  if not p.outradius or not p.outhalfheight then error('Capsule dimensions unavailable.',0) end
  PF.callFunc(capsule,'GetScaledCapsuleSize',{}, {safe=true,quick=true})
  local radius=readFloat(BUF()+p.outradius.off)
  local height=readFloat(BUF()+p.outhalfheight.off)
  if not tpFinite(radius) or not tpFinite(height) or radius&lt;=0 or height&lt;radius or height&gt;5000 then error('Invalid capsule dimensions.',0) end
  return {radius=radius+5,height=height+5}
end
local function tpSurface(P,x,y)
  local shape=tpShape(P)
  local simple,why1=groundZ(P.pawn,x,y,200000,-200000,shape,false)
  local complex,why2=groundZ(P.pawn,x,y,200000,-200000,shape,true)
  -- Both collision representations must be safe; use the higher contact centre.
  if not simple and why1~='unloaded' then return nil,why1 end
  if not complex and why2~='unloaded' then return nil,why2 end
  if simple or complex then return math.max(simple or complex,complex or simple),'surface' end
  return nil,'unloaded'
end
local function tpRelease(q)
  if q and q.slowUntil and PF.fall.slowUntil==q.slowUntil then PF.fall.slowUntil=nil end
end
-- Recovery calls must belong to the actual target class, never a same-named global fallback.
function PF.recoveryFunction(o,name)
  local f=UE.findFunc(o,name);local owner=f and UE.outer(f);local c=o and UE.cls(o)
  for i=1,64 do
    if not c then break end
    if c==owner then return f end
    c=UE.super(c)
  end
  PF.err('Recovery function unavailable: '..name,'復帰用のゲーム関数が見つかりません: '..name)
end
local function recoveryEnum(P,prop,want)
  local _,pr=UE.prop(P.pawn,prop);local en=pr and UE.enumOfProp(pr)
  if en then for v=0,32 do if UE.enumValueName(en,v)==want then return v end end end
  PF.err('Recovery state unavailable: '..prop..'.'..want,'復帰状態の定義が見つかりません: '..prop..'.'..want)
end
function PF.recoveryPlan(P)
  if not P or not P.move or not P.pc or not UE.isA(P.pawn,'ALSBaseCharacter') then
    PF.err('Load a playable character before recovery.','操作可能なキャラクターをロードしてから復帰を実行してください。')
  end
  local plan={none=recoveryEnum(P,'MovementAction','None'),grounded=recoveryEnum(P,'MovementState','Grounded'),
              air=recoveryEnum(P,'MovementState','InAir'),ragdoll=recoveryEnum(P,'MovementState','Ragdoll'),vehicle=recoveryEnum(P,'MovementState','InVehicle')}
  local state=UE.prop(P.pawn,'MovementState');plan.state=state and readBytes(state,1)
  if plan.state==plan.vehicle then PF.err('Exit the vehicle before using emergency recovery.','乗り物から降りてから緊急脱出を実行してください。') end
  local h=P.attr and P.attr.Health
  if h and (curAttr(h) or 0)&lt;=0 then PF.err('Emergency recovery requires a living character.','死亡中は緊急脱出を実行できません。') end
  for _,entry in ipairs({{P.pawn,'EndSlide'},{P.pawn,'RagdollEnd'},{P.pawn,'StopJumping'},{P.pawn,'StopAnimMontage'},
      {P.pawn,'SetMovementAction'},{P.pawn,'SetMovementState'},{P.move,'StopMovementImmediately'},{P.move,'SetMovementMode'},
      {P.pc,'ResetIgnoreMoveInput'},{P.pc,'ResetIgnoreLookInput'}}) do PF.recoveryFunction(entry[1],entry[2]) end
  return plan
end
function PF.resetLocomotion(P,grounded,unlock)
  local plan=PF.recoveryPlan(P) -- validate the full sequence before changing any state
  local function call(o,n,args) return PF.callFunc(o,n,args or {},{safe=true,quick=true}) end
  call(P.pawn,'EndSlide')
  if plan.state==plan.ragdoll then call(P.pawn,'RagdollEnd') end
  call(P.pawn,'StopJumping')
  call(P.pawn,'StopAnimMontage',{AnimMontage=0})
  call(P.move,'StopMovementImmediately')
  -- Clear a stale slide request even when native EndSlide no longer sees Custom/Sliding mode.
  local a,p=UE.prop(P.move,'bWantsToSlide');local bi=p and UE.boolInfo(p)
  if a and bi then local addr=a-p.off+bi.off;local v=readBytes(addr,1);if v then writeBytes(addr,v&amp;(~bi.mask&amp;0xFF)) end end
  call(P.pawn,'SetMovementAction',{NewAction=plan.none,bForce=true})
  call(P.move,'SetMovementMode',{NewMovementMode=grounded and 1 or 3,NewCustomMode=0})
  call(P.pawn,'SetMovementState',{NewState=grounded and plan.grounded or plan.air,bForce=true})
  if unlock then call(P.pc,'ResetIgnoreMoveInput');call(P.pc,'ResetIgnoreLookInput') end
  local mode=UE.prop(P.move,'MovementMode');local custom=UE.prop(P.move,'CustomMovementMode')
  local state=UE.prop(P.pawn,'MovementState');local action=UE.prop(P.pawn,'MovementAction')
  if not mode or not custom or not state or not action or readBytes(mode,1)~=(grounded and 1 or 3) or
      readBytes(custom,1)~=0 or readBytes(state,1)~=(grounded and plan.grounded or plan.air) or readBytes(action,1)~=plan.none then
    PF.err('Movement reset was not accepted by the game.','ゲーム側で移動状態のリセットを確認できませんでした。')
  end
end
function PF.emergencyEscape()
  PF.require()
  if PF.peBusy or (PF.tp and PF.tp.busy) then PF.err('Wait for the current game call to finish.','実行中のゲーム処理が終わってから再実行してください。') end
  local P=PF.needPlayer();PF.recoveryPlan(P)
  local x,y,z=PF.actorLocation(P.pawn)
  if not tpFinite(x) or not tpFinite(y) or not tpFinite(z) then error('Current position unavailable.',0) end
  tpRelease(PF.tp and PF.tp.pending)
  PF.tp={n=ri(PF.var(0xA0)) or 0,pending={x=x,y=y,z=z,origin={x,y,z},pawn=P.pawn,ps=P.ps,
    emergency=true,deadline=getTickCount()+30000}}
  PF.featOn.emergencyEscape=true
  PF.msg('Emergency recovery started: finding clear ground and resetting locomotion.',
         '緊急脱出を開始しました。安全な地表を探し、滑落・移動・操作制限を解除します。')
end

local function tpRollback(P,q)
  if not q.moved or not q.origin then return false end
  local x,y=PF.actorLocation(P.pawn)
  if not x or not y or (x-q.x)^2+(y-q.y)^2&gt;200^2 then return false end
  tpMove(P,table.unpack(q.origin))
  return true
end
local function tpTask()
  local T=PF.tp
  if PF.peBusy or T.busy then return end
  T.busy=true
  local ok,e=pcall(function()
    local c=ri(PF.var(0xA0));if c==nil then return end
    if T.n==nil then T.n=c return end
    if c~=T.n and not (T.pending and T.pending.emergency) then
      local x,y,z=readVec(PF.var(0x80))
      if c~=ri(PF.var(0xA0)) then return end
      T.n=c
      if not tpFinite(x) or not tpFinite(y) or not tpFinite(z) then error('Invalid sticker coordinates.',0) end
      local P=PF.needPlayer();tpRelease(T.pending)
      T.pending={x=x,y=y,z=z,pawn=P.pawn,ps=P.ps,deadline=getTickCount()+20000}
    end
    local q=T.pending
    if not q or (q.nextTry and getTickCount()&lt;q.nextTry) then return end
    local P=PF.player()
    if not P or P.pawn~=q.pawn or P.ps~=q.ps then tpRelease(q);T.pending=nil;return end
    q.nextTry=getTickCount()+1000
    if getTickCount()&gt;q.deadline then
      local returned=tpRollback(P,q);tpRelease(q);T.pending=nil
      PF.err(returned and 'Landing could not be verified; returned to the previous position.' or 'Landing verification timed out.',
             returned and '安全な着地を確認できず、移動前の位置へ戻しました。' or '着地の確認が時間切れになりました。')
    end
    if q.emergency and not q.reset then PF.resetLocomotion(P,false,true);q.reset=true end
    if not q.origin then q.origin={PF.actorLocation(P.pawn)} end
    if q.moved then
      local ax,ay=PF.actorLocation(P.pawn)
      if (ax-q.x)^2+(ay-q.y)^2&gt;200^2 then
        tpRelease(q);T.pending=nil
        PF.msg('Position changed; automatic landing correction stopped.','位置が変わったため、自動着地補正を終了しました。')
        return
      end
    end
    local z,why=tpSurface(P,q.x,q.y)
    if q.emergency and not q.moved and not z then
      local ox,oy=q.x,q.y
      for _,d in ipairs({{150,0},{-150,0},{0,150},{0,-150},{400,0},{-400,0},{0,400},{0,-400}}) do
        z,why=tpSurface(P,ox+d[1],oy+d[2])
        if z then q.x=ox+d[1];q.y=oy+d[2];break end
      end
      if not z then why='no clear recovery surface' end
    end
    if z then
      if q.phase~='verify' then
        if not q.reset then
          local _,sp=UE.prop(P.pawn,'MovementState');local sa=UE.prop(P.pawn,'MovementState')
          local en=sp and UE.enumOfProp(sp);local state=sa and readBytes(sa,1)
          if en and UE.enumValueName(en,state)=='Sliding' then PF.resetLocomotion(P,false,false);q.reset=true end
        end
        local ax,ay=tpMove(P,q.x,q.y,z+30);q.x=ax;q.y=ay;q.moved=true;q.phase='verify';q.stable=0
        PF.msg('Destination reached; checking capsule clearance after terrain loading.',
               '移動先へ到達しました。地形読み込み後の体全体の空間を確認します。')
      else
        local ax,ay,az=PF.actorLocation(P.pawn)
        if az&lt;z-15 then
          -- Raise out of newly loaded collision; never push the character down into it.
          local tx,ty=tpMove(P,q.x,q.y,z+30);q.x=tx;q.y=ty;q.stable=0
        elseif az&gt;z+150 then q.stable=0
        else q.stable=(q.stable or 0)+1 end
        if q.stable&gt;=2 then
          if q.reset then PF.resetLocomotion(P,true,q.emergency) end
          tpRelease(q);T.pending=nil;T.n=ri(PF.var(0xA0)) or T.n
          if q.emergency then PF.msg('Emergency recovery completed; movement and input state reset.','緊急脱出完了。滑落・移動状態と操作制限をリセットしました。') end
          PF.msg(('Teleported to %.0f, %.0f, %.0f (landing rechecked).'):format(ax,ay,az),
                 ('%.0f, %.0f, %.0f へ移動しました（着地点を再確認）。'):format(ax,ay,az))
        end
      end
    elseif why~='unloaded' then
      local returned=tpRollback(P,q);tpRelease(q);T.pending=nil
      PF.err(returned and 'Unsafe landing; returned to the previous position.' or 'No clear landing space. Place the sticker elsewhere.',
             returned and '着地点の空間を確保できず、移動前の位置へ戻しました。' or '体全体が入る着地点を確認できません。別の位置を選んでください。')
    elseif not q.moved then
      local ax,ay=tpMove(P,q.x,q.y,math.max(q.z,q.origin[3])+3000);q.x=ax;q.y=ay;q.moved=true;q.phase='loading'
      q.slowUntil=os.clock()+25;PF.fall.slowUntil=q.slowUntil;fallTimerOn()
      PF.msg('Waiting for terrain; landing will be checked again.','地形の読み込みを待って着地点を再確認します。')
    end
  end)
  T.busy=false
  if not ok then
    if T.lastError~=tostring(e) then T.lastError=tostring(e);PF.msg('Teleport failed: '..tostring(e),'テレポート失敗: '..tostring(e)) end
  else T.lastError=nil end
end

----------------------------------------------------------------- spawn a snowmobile (vehicle classes loaded in memory)
-- the snowmobile Blueprint class (from the game's file list: Content/Permafrost/Blueprints/Vehicles/SnowMobile/BP_SnowMobile)
PF.SNOWMOBILE_PATH = '/Game/Permafrost/Blueprints/Vehicles/SnowMobile/BP_SnowMobile.BP_SnowMobile_C'
PF.strMem = PF.strMem or {}
-- FString in game memory (kept for the session; the game only copies it)
local function makeFString(s)
  local need=(#s+1)*2+0x20
  if not PF.strMem.a or PF.strMem.pid~=PF.pid then PF.strMem={a=allocateMemory(0x1000), pid=PF.pid} end
  local a=PF.strMem.a+0x20
  local b={} for i=1,#s do local c=s:byte(i) b[#b+1]=c b[#b+1]=0 end b[#b+1]=0 b[#b+1]=0
  writeBytes(a,b)
  return a, #s+1
end
local function findClassByName(nm)
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    if o and UE.objName(o)==nm then local k=UE.clsName(UE.cls(o)) if k=='BlueprintGeneratedClass' or k=='Class' then return o end end
  end
end
-- load a Blueprint class by path: MakeSoftClassPath(path) -&gt; FSoftClassPath -&gt; LoadClassAsset_Blocking
function PF.loadClass(path)
  local ksl=cdo('Default__KismetSystemLibrary')
  local p=propOff(ksl,'MakeSoftClassPath')
  local sa,sn=makeFString(path)
  PF.callFunc(ksl,'MakeSoftClassPath',{ __raw=function(buf)
    writeQword(buf+p.pathstring.off,sa) writeInteger(buf+p.pathstring.off+8,sn) writeInteger(buf+p.pathstring.off+12,sn)
  end },{safe=true})
  local r=BUF()+p.returnvalue.off
  local pkg,asset=readQword(r),readQword(r+8)
  if not pkg or pkg==0 then PF.err('Class path not resolved: '..path,'クラスのパスを解決できません: '..path) end
  local q=propOff(ksl,'LoadClassAsset_Blocking')
  PF.callFunc(ksl,'LoadClassAsset_Blocking',{ __raw=function(buf) PF.writeSoft(buf+q.assetclass.off,{pkg=pkg,asset=asset}) end },{safe=true})
  local c=rq(BUF()+q.returnvalue.off)
  if not c or not UE.isObj(c) then PF.err('Class could not be loaded: '..path,'クラスを読み込めません: '..path) end
  return c
end
function PF.spawnVehicle()
  local P=PF.needPlayer()
  local cname=PF.SNOWMOBILE_PATH:match('%.([^%.]+)$')
  local c=findClassByName(cname)
  if not c then
    PF.msg('Loading the snowmobile class...','スノーモービルのクラスを読み込んでいます…')
    c=PF.loadClass(PF.SNOWMOBILE_PATH)
  end
  local pick={c=c,name=UE.objName(c)}
  local pawn=P.pawn
  local x,y,z=PF.actorLocation(pawn)
  local fx,fy=actorForward(pawn)
  local sx,sy,sz=x+fx*500, y+fy*500, z+150
  local gz=groundZ(pawn,sx,sy,z+2000,z-5000); if gz then sz=gz+80 end
  local gs=cdo('Default__GameplayStatics')
  local p=propOff(gs,'BeginDeferredActorSpawnFromClass')
  local function xform(a)    -- FTransform (double): Rotation quat @0, Translation @20, Scale3D @40
    writeDouble(a,0) writeDouble(a+8,0) writeDouble(a+16,0) writeDouble(a+24,1)
    writeVec(a+0x20,sx,sy,sz) writeVec(a+0x40,1,1,1)
  end
  PF.callFunc(gs,'BeginDeferredActorSpawnFromClass',{ __raw=function(buf)
    writeQword(buf+p.worldcontextobject.off,pawn) writeQword(buf+p.actorclass.off,pick.c)
    xform(buf+p.spawntransform.off)
    writeBytes(buf+p.collisionhandlingoverride.off,2)    -- AdjustIfPossibleButAlwaysSpawn
    writeBytes(buf+p.transformscalemethod.off,1)         -- MultiplyWithRoot
  end },{safe=true})
  local actor=rq(BUF()+p.returnvalue.off)
  if not actor or not UE.isObj(actor) then PF.err('Spawn failed.','スポーンに失敗しました。') end
  local q=propOff(gs,'FinishSpawningActor')
  PF.callFunc(gs,'FinishSpawningActor',{ __raw=function(buf)
    writeQword(buf+q.actor.off,actor) xform(buf+q.spawntransform.off)
    if q.transformscalemethod then writeBytes(buf+q.transformscalemethod.off,1) end
  end },{safe=true})
  PF.msg('Spawned: '..pick.name,'スポーンしました: '..pick.name)
  -- state of the spawned vehicle (APermafrostVehicle: Config +350 = vehicle data, FuelAmount, bEngineOn, DriverCharacter)
  sleep(300)
  -- get in right away (UE: AUTHORITY_EnterVehicle(TargetController) attaches the character and possesses the vehicle)
  if UE.findFunc(actor,'AUTHORITY_EnterVehicle') and P.pc then
    local e=propOff(actor,'AUTHORITY_EnterVehicle')
    PF.callFunc(actor,'AUTHORITY_EnterVehicle',{ __raw=function(buf) writeQword(buf+e.targetcontroller.off,P.pc) end },{safe=true})
    local bi=UE.boolInfo(e.returnvalue)
    local ok=bi and ((readBytes(BUF()+bi.off,1,true)[1] &amp; bi.mask)~=0)
    PF.msg('Enter vehicle: '..tostring(ok),'乗車: '..(ok and '成功' or '失敗'))
    sleep(300)
  end
end


PF.F.instantCraft = { task=function() icraftTask() end, on=function() icraftOn() end, off=function() icraftOff() end }
PF.F.instantBuild = { task=function() ibuildTask() end, on=function() ibuildOn() end, off=function() ibuildOff() end }
PF.F.emergencyEscape={task=function() tpTask();if not PF.tp.pending then PF.featOn.emergencyEscape=nil end end,off=function() tpRelease(PF.tp.pending);PF.tp={} end}
PF.F.mapTeleport  = { hooks={'sticker'}, task=function() tpTask() end, on=function() PF.needPlayer() PF.tp={} PF.tp.n=ri(PF.var(0xA0)) or 0 end, off=function() tpRelease(PF.tp.pending);PF.tp={} end }

----------------------------------------------------------------- reveal the whole world map (fog of war)
-- UFogOfWarRevealer (component of the world map manager): GridSize x GridSize voxels; DiscoveredVoxels
-- (TArray&lt;FIntVector2&gt;, saved with the game); MULTICAST_RevealVoxel(Voxel) adds one voxel and draws it on the map.
-- The missing voxels are revealed in the background (a few per game frame, on the player's own events).
PF.mapRev = PF.mapRev or {}
local function mapRevTick()
  local R=PF.mapRev
  if not R.q or not PF.attached() then return end
  if R.busy then return end
  R.busy=true
  local t0=os.clock()
  while R.i&lt;=#R.q and os.clock()-t0&lt;0.25 do
    local v=R.q[R.i]
    local ok,e=pcall(PF.callFunc,R.fog,'MULTICAST_RevealVoxel',{ __raw=function(buf) writeInteger(buf+R.off,v[1]) writeInteger(buf+R.off+4,v[2]) end },{safe=true})
    if not ok then R.err=(R.err or 0)+1 if R.err&gt;20 then PF.msg('Map reveal stopped: '..tostring(e),'マップ開放を中断しました: '..tostring(e)) R.q=nil break end
    else R.i=R.i+1 end
  end
  if R.q then
    local pct=math.floor((R.i-1)*100/#R.q)
    if pct&gt;=(R.next or 0) then PF.msg(('Map reveal: %d%%'):format(pct),('マップ開放: %d%%'):format(pct)) R.next=pct+10 end
    if R.i&gt;#R.q then PF.msg(('Map reveal finished (%d areas).'):format(#R.q),('マップ開放が完了しました（%d区画）。'):format(#R.q)) R.q=nil end
  end
  R.busy=false
  if not R.q and R.timer then R.timer.destroy() R.timer=nil end
end
function PF.mapRevealAll()
  PF.needPlayer()
  local R=PF.mapRev
  if R.q then PF.msg('Map reveal is already running.','マップ開放は実行中です。') return end
  local fog=PF.instanceWithFunc('MULTICAST_RevealVoxel') or PF.err('Map fog of war component not found (open the map once).','マップの霧のコンポーネントが見つかりません（一度マップを開いてください）。')
  local ga=UE.prop(fog,'GridSize'); local G=ga and ri(ga)
  if not G or G&lt;1 or G&gt;1024 then PF.err('Map grid size not readable.','マップの区画数を読み取れません。') end
  local arr=UE.prop(fog,'DiscoveredVoxels')
  local have={}
  local data=arr and rq(arr); local num=arr and ri(arr+8) or 0
  for k=0,math.min(num,1100000)-1 do local x=ri(data+k*8) local y=ri(data+k*8+4) if x and y then have[x*65536+y]=true end end
  local f=UE.findFunc(fog,'MULTICAST_RevealVoxel'); local off=0
  for _,pr in ipairs(UE.ownProps(f)) do off=pr.off end
  local q={}
  for x=0,G-1 do for y=0,G-1 do if not have[x*65536+y] then q[#q+1]={x,y} end end end
  PF.msg(('Map: %d x %d areas, %d already discovered, %d to reveal.'):format(G,G,num,#q),('マップ: %d×%d区画、発見済み %d、開放する区画 %d。'):format(G,G,num,#q))
  if #q==0 then return end
  PF.mapRev={ fog=fog, q=q, i=1, off=off, next=10 }
  local t=createTimer(nil,false) t.Interval=50 t.OnTimer=function() pcall(mapRevTick) end t.Enabled=true
  PF.mapRev.timer=t
end

----------------------------------------------------------------- quests (Narrative plugin + the game's narrative component)
-- UQuest: CurrentState (UQuestState*), QuestName (FText), QuestCompletion (EQuestCompletion), EnterState(NewState).
-- UQuestState: Branches (TArray&lt;UQuestBranch*&gt;), StateNodeType (Regular / Success / Failure), Description (FText).
-- UQuestBranch: QuestTasks (TArray&lt;UNarrativeTask*&gt;), DestinationState (UQuestState*).
-- UNarrativeTask: RequiredQuantity, CurrentProgress, CompleteTask().
-- Game narrative component: GetActiveQuest(EQuestType Main/Side) -&gt; UQuest*.
-- Library (static): GetAllQuestClasses(BaseClass) -&gt; TMap&lt;FString, TSubclassOf&lt;UQuest&gt;&gt;,
--                   AUTHORITY_BeginQuest(TSoftClassPtr&lt;UQuest&gt;, FName StartFromID).
local function narrComp(P)
  local o=PF.compWithFunc(P,'GetActiveQuest') or PF.instanceWithFunc('GetActiveQuest')
  if not o then PF.err('Narrative (quest) component not found.','クエスト管理コンポーネントが見つかりません。') end
  return o
end
-- the narrative component that has fname (the game's component first, then any player component / instance)
local function narrWith(P, fname)
  local ok,nc=pcall(narrComp,P)
  if ok and nc and UE.findFunc(nc,fname) then return nc end
  return PF.compWithFunc(P,fname) or PF.instanceWithFunc(fname)
end
local function arrOf(o, pname)
  local a=UE.prop(o,pname); if not a then return nil, 0 end
  local d=rq(a); local n=ri(a+8) or 0
  if not d or n&lt;0 or n&gt;4096 then return nil, 0 end
  return d, n
end
local function textProp(o, pname)
  local a=o and UE.prop(o,pname); if not a then return nil end
  local ok,t=pcall(UE.textAt,a) if ok then return t end
end
local function enumProp(o, pname)
  local a,pr=UE.prop(o,pname); if not a then return nil end
  local b=readBytes(a,1,true); if not b then return nil end
  local e=UE.enumOfProp(pr)
  return e and UE.enumValueName(e,b[1]) or tostring(b[1]), b[1]
end
local function questLabel(q)
  local n=textProp(q,'QuestName')
  local c=UE.clsName(UE.cls(q)) or UE.objName(q)
  return n and (n..'  ['..c..']') or c
end
local function stateLabel(s)
  if not s then return '-' end
  return textProp(s,'Description') or UE.objName(s)
end
-- 'Main' / 'Side'
function PF.activeQuest(kind)
  local P=PF.needPlayer()
  local nc=narrComp(P)
  local fn=UE.findFunc(nc,'GetActiveQuest')
  local v=fn and enumIndex(fn,'QuestType',kind)
  if not v then PF.err('Quest type not resolved: '..kind,'クエストの種類を特定できません: '..kind) end
  local p=propOff(nc,'GetActiveQuest')
  PF.callFunc(nc,'GetActiveQuest',{ __raw=function(buf) writeBytes(buf+p.questtype.off,v) end })
  local q=rq(BUF()+p.returnvalue.off)
  if q and UE.live(q) then return q end
end
-- branch to follow from a state: first branch whose destination is not a failure state (else the first one)
local function pickBranch(st)
  local d,n=arrOf(st,'Branches')
  local first
  for i=0,n-1 do
    local b=rq(d+i*8)
    if b and UE.isObj(b) then
      local dst=UE.getObj(b,'DestinationState')
      first=first or b
      local ty=dst and enumProp(dst,'StateNodeType')
      if dst and ty~='Failure' then return b, dst end
    end
  end
  return first, first and UE.getObj(first,'DestinationState')
end
function PF.questAdvance(kind)
  local ja = (kind=='Main') and 'メイン' or 'サイド'
  local q=PF.activeQuest(kind)
  if not q then PF.err(('No active %s quest.'):format(kind:lower()),'現在の'..ja..'クエストがありません。') end
  local name=questLabel(q)
  local cur=UE.getObj(q,'CurrentState')
  if not cur then PF.err('Current quest step not found: '..name,'クエストの現在の段階が見つかりません: '..name) end
  local br,dst=pickBranch(cur)
  if not br then PF.err('This quest has no next step (last step): '..name,'このクエストには次の段階がありません（最終段階）: '..name) end
  PF.msg(('%s quest: %s'):format(kind,name),ja..'クエスト: '..name)
  PF.msg('  now : '..stateLabel(cur),'  現在: '..stateLabel(cur))
  -- 1) complete the tasks of the branch (the game then moves the quest to the next step by itself)
  local d,n=arrOf(br,'QuestTasks')
  local done=0
  for i=0,n-1 do
    local t=rq(d+i*8)
    if t and UE.live(t) then
      local ok,e=pcall(PF.callFunc,t,'CompleteTask',{},{safe=true})
      if ok then done=done+1 else PF.msg('  task not completed: '..tostring(e),'  タスクを完了できません: '..tostring(e)) end
    end
  end
  sleep(100)
  local now=UE.getObj(q,'CurrentState')
  local how='tasks'
  -- 2) still at the same step (the game did not react): enter the destination state directly
  if now==cur and dst then
    PF.callFunc(q,'EnterState',{dst},{safe=true})
    sleep(100)
    now=UE.getObj(q,'CurrentState') how='state'
  end
  if now==cur then PF.err('The quest did not advance: '..name,'クエストが進みませんでした: '..name) end
  PF.msg(('  next: %s  (%d task(s) completed%s)'):format(stateLabel(now),done,how=='state' and ', step entered directly' or ''),
         ('  次  : %s（タスク %d件を完了%s）'):format(stateLabel(now),done,how=='state' and '、段階を直接移行' or ''))
  local c=enumProp(q,'QuestCompletion')
  if c=='QC_Succeded' then PF.msg('  The quest is completed.','  クエストが完了しました。') end
end

-- list of quest classes: the game's quest list (GetAllQuestClasses) + quest classes already loaded
local function questBase()
  for c in pairs(UE.funcOwners('EnterState')) do
    if UE.objName(c)=='Quest' then return c end
  end
  for c in pairs(UE.funcOwners('EnterState')) do if UE.findProp(c,'QuestStartState') then return c end end
end
local function staticObj(fname)
  for c in pairs(UE.funcOwners(fname)) do
    local o=cdoOf('Default__'..UE.objName(c)); if o then return o end
  end
end
function PF.questClasses()
  local base=questBase() or PF.err('Quest base class not found.','クエストの基底クラスが見つかりません。')
  local set,list={},{}
  local function add(c) if c and UE.isObj(c) and not set[c] and c~=base and isSubclass(c,base) then set[c]=true list[#list+1]=c end end
  local lib=staticObj('GetAllQuestClasses')
  if lib then
    local p=propOff(lib,'GetAllQuestClasses')
    local ok,e=pcall(PF.callFunc,lib,'GetAllQuestClasses',{ __raw=function(buf) writeQword(buf+p.baseclass.off,base) end },{safe=true})
    if ok then
      local r=BUF()+p.returnvalue.off
      local d=rq(r); local n=ri(r+8) or 0
      if d and n&gt;0 and n&lt;4096 then for i=0,n-1 do add(rq(d+i*0x20+0x10)) end end
    else PF.msg('Quest list from the game not available: '..tostring(e),'ゲームからクエスト一覧を取得できません: '..tostring(e)) end
  end
  -- loaded quest classes, their default objects and live quest instances
  local cdos,inst={},{}
  local chunks=rq(UE.gobj)
  for i=0,UE.count()-1 do
    local ch=chunks and rq(chunks+(i//UE.O.chunk)*8)
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local k=o and UE.cls(o)
    if k then
      local kn=UE.clsName(k)
      if (kn=='BlueprintGeneratedClass' or kn=='Class') and isSubclass(o,base) then add(o) end
      if set[k] or (k~=base and isSubclass(k,base)) then
        if ((ri(o+8) or 0)&amp;0x10)~=0 then cdos[k]=o elseif UE.live(o) then inst[k]=o end
      end
    end
  end
  for c in pairs(cdos) do add(c) end for c in pairs(inst) do add(c) end
  local out={}
  for _,c in ipairs(list) do
    local e={cls=c, name=UE.objName(c), inst=inst[c]}
    e.disp=cdos[c] and textProp(cdos[c],'QuestName')
    if e.inst then e.status=enumProp(e.inst,'QuestCompletion') end
    out[#out+1]=e
  end
  table.sort(out,function(a,b) return (a.disp or a.name)&lt;(b.disp or b.name) end)
  return out
end
local QSTAT={ QC_NotStarted={'not started','未開始'}, QC_Started={'in progress','進行中'}, QC_Succeded={'completed','完了'}, QC_Failed={'failed','失敗'} }
function PF.questInsertPick()
  local P=PF.needPlayer()
  PF.msg('Reading the quest list from the game...','ゲームからクエスト一覧を取得しています…')
  local list=PF.questClasses()
  if #list==0 then PF.err('No quest found.','クエストが見つかりません。') end
  local names={}
  for i,e in ipairs(list) do
    local s=QSTAT[e.status or 'QC_NotStarted'] or {e.status,e.status}
    names[i]=('[%s]  %s'):format(PF.T(s[1],s[2]), e.disp and (e.disp..'  ['..e.name..']') or e.name)
  end
  local i=PF.pick(PF.T('Insert quest (start it)','クエストを挿入（開始する）'), names)
  if not i then return end
  local e=list[i]
  if e.status=='QC_Started' then PF.msg('Already in progress: '..names[i],'すでに進行中です: '..names[i]) return end
  local nc=narrWith(P,'RestartQuest')
  if e.inst and nc then
    -- finished / failed quest: start it again from the beginning
    local p=propOff(nc,'RestartQuest')
    PF.callFunc(nc,'RestartQuest',{ __raw=function(buf) writeQword(buf+p.questclass.off,e.cls) end },{safe=true})
  else
    local lib=staticObj('AUTHORITY_BeginQuest')
    local ok=false
    if lib then
      local p=propOff(lib,'AUTHORITY_BeginQuest')
      ok=pcall(PF.callFunc,lib,'AUTHORITY_BeginQuest',{ __raw=function(buf) PF.writeSoft(buf+p.questclass.off,PF.softOf(e.cls)) end },{safe=true})
    end
    sleep(100)
    local started=false
    local bq=narrWith(P,'GetQuestInstance')
    if bq then
      local p=propOff(bq,'GetQuestInstance')
      local ok2=pcall(PF.callFunc,bq,'GetQuestInstance',{ __raw=function(buf) writeQword(buf+p.questclass.off,e.cls) end })
      started=ok2 and rq(BUF()+p.returnvalue.off) and true or false
    end
    if not started and bq and UE.findFunc(bq,'BeginQuest') then
      local p=propOff(bq,'BeginQuest')
      PF.callFunc(bq,'BeginQuest',{ __raw=function(buf) writeQword(buf+p.questclass.off,e.cls) end },{safe=true})
    elseif not ok and not started then PF.err('The quest could not be started.','クエストを開始できませんでした。') end
  end
  PF.msg('Quest inserted (started): '..names[i],'クエストを挿入（開始）しました: '..names[i])
end

----------------------------------------------------------------- save data files: backup (10 generations) / restore
-- Save files of the release build (checked on the user's PC and in the game code):
--   world      : &lt;game&gt;\Permafrost\SaveGame\&lt;world&gt;.pfs  (the game's SaveGame folder; Steam Auto-Cloud)
--   difficulty : &lt;game&gt;\Permafrost\SaveGame\DifficultySettings\&lt;world&gt;.diff
--   character  : %LOCALAPPDATA%\Permafrost\Saved\SaveGames\CharacterSlots.sav
-- A backup copies all of them into %LOCALAPPDATA%\Permafrost\CT_SaveBackup\YYYYMMDD_HHMMSS\ (robocopy, so file
-- names in any language are copied as they are). The newest 10 backups are kept.
PF.SAVE_KEEP = 10
local function sbRoot() local la=os.getenv('LOCALAPPDATA') if not la then PF.err('LOCALAPPDATA not set.','環境変数 LOCALAPPDATA がありません。') end return la..'\\Permafrost\\CT_SaveBackup' end
local function sbChar() return os.getenv('LOCALAPPDATA')..'\\Permafrost\\Saved\\SaveGames' end
local function sbRun(exe, args)
  if runCommand then
    local ok,out,code=pcall(runCommand, exe, args)
    if ok then return code or 0, out or '' end
  end
  local q={'"'..exe..'"'} for _,a in ipairs(args) do q[#q+1]=a:find('[ %(%)]') and ('"'..a..'"') or a end
  local ok,_,code=os.execute('"'..table.concat(q,' ')..'"')
  return code or (ok and 0 or 1), ''
end
local function robo(src, dst, filesOrNil)
  local args={src, dst}
  if filesOrNil then for _,f in ipairs(filesOrNil) do args[#args+1]=f end else args[#args+1]='/E' end
  for _,a in ipairs({'/COPY:DAT','/R:1','/W:1','/NP','/NJH','/NJS'}) do args[#args+1]=a end
  local code,out=sbRun('robocopy.exe', args)
  if code&gt;=8 then PF.err(('Copy failed (robocopy %d): %s -&gt; %s'):format(code,src,dst),('コピーに失敗しました（robocopy %d）: %s → %s'):format(code,src,dst)) end
  return code,out
end
local function readAll(p) local f=io.open(p,'rb') if not f then return nil end local s=f:read('*a') f:close() return s end
local function writeAll(p,s) local f=io.open(p,'wb') if not f then return false end f:write(s) f:close() return true end
-- the game's project folder (&lt;game&gt;\Permafrost): from the running game, else remembered from an earlier run
local function sbProject()
  local ok,mods=pcall(enumModules)
  if ok and mods then
    for _,m in ipairs(mods) do
      if (m.Name or ''):lower()==PF.MODULE:lower() and m.PathToFile then
        local p=m.PathToFile:gsub('[\\/][^\\/]+$',''):gsub('[\\/][^\\/]+$',''):gsub('[\\/][^\\/]+$','')   -- ..\Binaries\Win64\x.exe
        pcall(function() sbRun('cmd.exe',{'/c','mkdir',sbRoot()}) end)
        writeAll(sbRoot()..'\\project_path.txt', p)
        return p
      end
    end
  end
  local s=readAll(sbRoot()..'\\project_path.txt')
  if s and #s&gt;3 then return (s:gsub('%s+$','')) end
  PF.err('Game folder unknown: start the game and run [ATTACH / ALL OFF] once.','ゲームのフォルダがわかりません。ゲームを起動して【アタッチ／一括解除】を一度実行してください。')
end
local function sbList()
  local out={}
  local ok,dirs=pcall(getDirectoryList, sbRoot(), false)
  if ok and dirs then
    for _,d in ipairs(dirs) do
      local n=d:match('([^\\/]+)[\\/]?$')
      if n and n:match('^%d%d%d%d%d%d%d%d_%d%d%d%d%d%d$') then out[#out+1]={dir=sbRoot()..'\\'..n, id=n} end
    end
  end
  table.sort(out,function(a,b) return a.id&gt;b.id end)   -- newest first
  return out
end
local function sbStamp(id) local y,mo,d,h,mi,s=id:match('^(%d%d%d%d)(%d%d)(%d%d)_(%d%d)(%d%d)(%d%d)$') return ('%s/%s/%s %s:%s:%s'):format(y,mo,d,h,mi,s) end
local function sbWorlds(dir)
  local names={}
  local ok,files=pcall(getFileList, dir, '*.pfs', false)
  if ok and files then for _,f in ipairs(files) do names[#names+1]=(f:match('([^\\/]+)%.pfs$') or f) end end
  table.sort(names) return names
end
function PF.saveBackup(note, protect)
  local proj=sbProject()
  local src=proj..'\\SaveGame'
  local id=os.date('%Y%m%d_%H%M%S')
  local dst=sbRoot()..'\\'..id
  local worlds=sbWorlds(src)
  if #worlds==0 then PF.err('No save data found: '..src,'セーブデータが見つかりません: '..src) end
  robo(src, dst..'\\SaveGame')
  robo(sbChar(), dst..'\\SaveGames', {'CharacterSlots.sav'})
  local got=sbWorlds(dst..'\\SaveGame')
  if #got~=#worlds then PF.err(('Backup incomplete (%d of %d world files copied): %s'):format(#got,#worlds,dst),('バックアップが不完全です（ワールド %d/%d件のみコピー）: %s'):format(#got,#worlds,dst)) end
  writeAll(dst..'\\info.txt', ('time=%s\nworlds=%s\nnote=%s\nsource=%s\n'):format(sbStamp(id), table.concat(worlds,', '), note or '', src))
  -- keep the newest PF.SAVE_KEEP backups
  -- (protect = a backup that must stay, e.g. the one being restored)
  local list,n=sbList(),0
  local room=PF.SAVE_KEEP
  for _,e in ipairs(list) do if e.id==protect then room=room-1 end end
  for _,e in ipairs(list) do
    if e.id~=protect then
      n=n+1
      if n&gt;room then sbRun('cmd.exe',{'/c','rmdir','/s','/q',e.dir}) end
    end
  end
  PF.msg(('Save data backed up: %s  (worlds: %s)'):format(sbStamp(id),table.concat(worlds,', ')),
         ('セーブデータをバックアップしました: %s（ワールド: %s）'):format(sbStamp(id),table.concat(worlds,'、')))
  PF.msg('  Folder: '..dst,'  保存先: '..dst)
  return id
end
function PF.saveRestorePick()
  -- restoring while a world is loaded is overwritten by the game's next save: allow only at the title screen / game closed
  if PF.attached() then
    local ok,P=pcall(PF.player,true)
    if ok and P and P.pawn then PF.err('A world is loaded. Return to the title screen (or close the game), then restore.','ワールドをプレイ中です。タイトル画面に戻るか、ゲームを終了してから復旧してください。') end
  end
  local proj=sbProject()
  local list=sbList()
  if #list==0 then PF.err('No backup found: '..sbRoot(),'バックアップがありません: '..sbRoot()) end
  local names={}
  for i,e in ipairs(list) do
    local info=readAll(e.dir..'\\info.txt') or ''
    local w=info:match('worlds=([^\n]*)') or table.concat(sbWorlds(e.dir..'\\SaveGame'),', ')
    local note=info:match('note=([^\n]*)') or ''
    names[i]=('%d.  %s   %s%s'):format(i, sbStamp(e.id), w, note~='' and ('   ('..note..')') or '')
  end
  local i=PF.pick(PF.T('Restore save data (timestamp / worlds)','セーブデータを復旧（タイムスタンプ／ワールド）'), names)
  if not i then return end
  local e=list[i]
  local msg=PF.T('Restore the save data of '..sbStamp(e.id)..'?\nThe current save files are backed up first.',
                 sbStamp(e.id)..' のセーブデータを復旧しますか？\n復旧の前に現在のセーブデータを自動でバックアップします。')
  if messageDialog(msg, mtConfirmation, mbYes, mbNo)~=mrYes then return end
  local okb,eb=pcall(PF.saveBackup, PF.T('before restore','復旧前の自動バックアップ'), e.id)
  if not okb then PF.msg('Automatic backup before restore failed: '..tostring(eb),'復旧前の自動バックアップに失敗しました: '..tostring(eb)) end
  robo(e.dir..'\\SaveGame', proj..'\\SaveGame')
  local want=sbWorlds(e.dir..'\\SaveGame'); local have={} for _,n in ipairs(sbWorlds(proj..'\\SaveGame')) do have[n]=true end
  for _,n in ipairs(want) do if not have[n] then PF.err('Restore incomplete (world file missing): '..n,'復旧が不完全です（ワールドのファイルがありません）: '..n) end end
  local cs=e.dir..'\\SaveGames'
  local ok,files=pcall(getFileList, cs, 'CharacterSlots.sav', false)
  if ok and files and #files&gt;0 then robo(cs, sbChar(), {'CharacterSlots.sav'}) end
  PF.msg('Save data restored: '..names[i],'セーブデータを復旧しました: '..names[i])
end

----------------------------------------------------------------- spawn animals (chosen kind, chosen number)
-- The game's own animal spawner (CreateAnimal) does: deferred spawn of the animal class -&gt; SpawnPoint = spawner,
-- HidingPlaceLocation = spawner location -&gt; FinishSpawning (the animal's BeginPlay then takes the patrol points of
-- the spawner and its AI starts). The same is done here around the player, with the nearest animal spawner
-- (within 150 m) as SpawnPoint; without one the animal has no patrol points.
PF.ANIMALS = {
  {'BP_Bear','Bear','クマ'}, {'BP_BearWounded','Wounded bear','手負いのクマ'}, {'BP_BearBoss','Bear (boss)','クマ（ボス）'},
  {'BP_Wolf_M','Wolf','オオカミ'}, {'BP_Fox','Fox','キツネ'}, {'BP_Boar_M','Boar (male)','イノシシ（オス）'}, {'BP_Boar_F','Boar (female)','イノシシ（メス）'},
  {'BP_Bison','Bison','バイソン'}, {'BP_Muskox','Muskox','ジャコウウシ'}, {'BP_Moose_M','Moose (male)','ヘラジカ（オス）'}, {'BP_Moose_F','Moose (female)','ヘラジカ（メス）'},
  {'BP_RedDeer','Red deer','アカシカ'}, {'BP_Doe','Doe','シカ（メス）'}, {'BP_Rabbit','Rabbit','ウサギ'}, {'BP_RabbitDomesticated','Rabbit (domesticated)','ウサギ（飼育）'},
  {'BP_Rat','Rat','ネズミ'},
}
PF.ANIMAL_DIR = '/Game/Permafrost/Blueprints/Characters/Animals/'
local function compLoc(c) if not c then return nil end local x,y,z=readDouble(c+0x1F0),readDouble(c+0x1F8),readDouble(c+0x200) if x and y and z then return x,y,z end end
local function nearestAnimalSpawner(x,y,z, maxd)
  local owners=UE.funcOwners('SpawnAnimals')
  local best,bd=nil,maxd*maxd
  local chunks=rq(UE.gobj); local seen={}
  local ci,ch=-1,nil
  for i=0,UE.count()-1 do
    local cx=i//UE.O.chunk
    if cx~=ci then ch=chunks and rq(chunks+cx*8) ci=cx end
    local o=ch and rq(ch+(i%UE.O.chunk)*UE.O.itemSize)
    local k=o and UE.cls(o)
    if k then
      local hit=seen[k]; if hit==nil then hit=classHas(k,owners) and true or false seen[k]=hit end
      if hit and ((ri(o+8) or 0)&amp;0x30)==0 then
        local sx,sy,sz=compLoc(UE.getObj(o,'BaseMesh'))
        if sx then local d=(sx-x)^2+(sy-y)^2+(sz-z)^2 if d&lt;bd then bd=d best={o=o,x=sx,y=sy,z=sz} end end
      end
    end
  end
  return best
end
function PF.spawnAnimalPick()
  local P=PF.needPlayer()
  local names={}
  for i,a in ipairs(PF.ANIMALS) do names[i]=PF.T(a[2],a[3])..'  ['..a[1]..']' end
  local i=PF.pick(PF.T('Spawn animals: kind','動物をスポーン: 種類'), names)
  if not i then return end
  local n=PF.askInt(PF.T('Spawn animals','動物をスポーン'), PF.T('How many? (1-30)','何匹出しますか？（1～30）'), 1, 1, 30)
  if not n then return end
  local A=PF.ANIMALS[i]
  local cname=A[1]..'_C'
  local c=findClassByName(cname)
  if not c then
    PF.msg('Loading the animal class: '..A[1],'動物のクラスを読み込んでいます: '..A[1])
    c=PF.loadClass(PF.ANIMAL_DIR..A[1]..'.'..cname)
  end
  local pawn=P.pawn
  local x,y,z=PF.actorLocation(pawn)
  local fx,fy=actorForward(pawn)
  local sp=nearestAnimalSpawner(x,y,z,15000)
  local gs=cdo('Default__GameplayStatics')
  local p=propOff(gs,'BeginDeferredActorSpawnFromClass')
  local q=propOff(gs,'FinishSpawningActor')
  local base=math.atan(fy,fx)
  local ok=0
  for k=1,n do
    local ang=base+(k-1)*(2*math.pi/n)
    local r=800+((k-1)%3)*300
    local sx,sy,sz=x+math.cos(ang)*r, y+math.sin(ang)*r, z+100
    local gz=groundZ(pawn,sx,sy,z+2000,z-5000); if gz then sz=gz+100 end
    local yaw=ang+math.pi   -- facing the player
    local function xform(a)
      writeDouble(a,0) writeDouble(a+8,0) writeDouble(a+16,math.sin(yaw/2)) writeDouble(a+24,math.cos(yaw/2))
      writeVec(a+0x20,sx,sy,sz) writeVec(a+0x40,1,1,1)
    end
    local s1,e1=pcall(PF.callFunc,gs,'BeginDeferredActorSpawnFromClass',{ __raw=function(buf)
      writeQword(buf+p.worldcontextobject.off,pawn) writeQword(buf+p.actorclass.off,c)
      xform(buf+p.spawntransform.off)
      writeBytes(buf+p.collisionhandlingoverride.off,2)    -- AdjustIfPossibleButAlwaysSpawn
      writeBytes(buf+p.transformscalemethod.off,1)
    end },{safe=true})
    local actor=s1 and rq(BUF()+p.returnvalue.off)
    if actor and UE.isObj(actor) then
      -- like the game's spawner: SpawnPoint / HidingPlaceLocation before BeginPlay
      local spA=UE.prop(actor,'SpawnPoint'); if spA then writeQword(spA, sp and sp.o or 0) end
      local hA=UE.prop(actor,'HidingPlaceLocation'); if hA then if sp then writeVec(hA,sp.x,sp.y,sp.z) else writeVec(hA,x,y,z) end end
      local s2=pcall(PF.callFunc,gs,'FinishSpawningActor',{ __raw=function(buf)
        writeQword(buf+q.actor.off,actor) xform(buf+q.spawntransform.off)
        if q.transformscalemethod then writeBytes(buf+q.transformscalemethod.off,1) end
      end },{safe=true})
      if s2 then ok=ok+1 end
    else PF.msg('Spawn failed: '..tostring(e1),'スポーン失敗: '..tostring(e1)) end
  end
  PF.msg(('Spawned %d x %s around you%s.'):format(ok,PF.T(A[2],A[3]), sp and ' (patrol points: nearest animal spawner)' or ''),
         ('%s を周囲に %d匹スポーンしました%s。'):format(A[3],ok, sp and '（巡回地点: 最寄りの動物スポナー）' or ''))
end

----------------------------------------------------------------- initial layout: only "0." expanded
function PF.initCollapse()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i)
    if m.Count&gt;0 then
      local opt='' pcall(function() opt=tostring(m.Options) end)
      if not opt:find('moHideChildren') then
        local inZero=false local p=m
        while p do if p.ID==PF.ID_TOP0 then inZero=true break end p=p.Parent end
        pcall(function() m.Collapsed = not inZero end)
      end
    end
  end
end

PF.CONSUME_AA=[==[
[ENABLE]
assert($ITEM,40 53 48 83 EC 20)
assert($AMMO,48 89 5C 24 08)
assert($DUR,0F 2E B3 98 00 00 00)
alloc(pf_consume,4000,$ITEM)
label(pf_ci_original)
label(pf_ci_protect)
label(pf_ci_zero)
label(pf_cd)
label(pf_cd_restore)
label(pf_cd_apply)
label(pf_tenth)
label(pf_ca)
label(pf_ca_restore)
label(pf_ca_keep)
label(pf_owned)
label(pf_owner_loop)
label(pf_owner_next)
label(pf_slot_loop)
label(pf_yes)
label(pf_no)
label(pf_ammo_type)
label(pf_type_loop)
label(pf_consume_data)
registersymbol(pf_consume_data)
pf_consume:
  push rax
  push rcx
  push rdx
  push r8
  push r9
  push r10
  push r11
  lea rax,[pf_consume_data]
  test byte ptr [rax],3
  je pf_ci_original
  mov rax,$MOVE_RETURN
  cmp [rsp+38],rax
  je pf_ci_original
  mov rax,$SPLIT_RETURN
  cmp [rsp+38],rax
  je pf_ci_original
  call pf_owned
  test eax,eax
  je pf_ci_original
  lea rax,[pf_consume_data]
  test byte ptr [rax],1
  jne pf_ci_protect
  call pf_ammo_type
  test eax,eax
  je pf_ci_original
pf_ci_protect:
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  test edx,edx
  jle pf_ci_zero
  mov eax,[rcx+90]
  test eax,eax
  jle pf_ci_zero
  cmp eax,edx
  cmovg eax,edx
  ret
pf_ci_zero:
  xor eax,eax
  ret
pf_ci_original:
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  db 40 53 48 83 EC 20
  jmp $ITEM_RETURN
pf_ca:
  push rax
  push rcx
  push rdx
  push r8
  push r9
  push r10
  push r11
  lea rax,[pf_consume_data]
  test byte ptr [rax],3
  je pf_ca_restore
  test edx,edx
  jle pf_ca_restore
  call pf_owned
  test eax,eax
  jne pf_ca_keep
pf_ca_restore:
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  mov [rsp+8],rbx
  jmp $AMMO_RETURN
pf_ca_keep:
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  xor edx,edx
  mov [rsp+8],rbx
  jmp $AMMO_RETURN
pf_cd:
  push rax
  push rcx
  push rdx
  push r8
  push r9
  push r10
  push r11
  sub rsp,10
  movups [rsp],xmm0
  lea rax,[pf_consume_data]
  test byte ptr [rax],C
  je pf_cd_restore
  mov rcx,rbx
  call pf_owned
  test eax,eax
  je pf_cd_restore
  lea rax,[pf_consume_data]
  movss xmm0,[rdi+D4]
  test byte ptr [rax],8
  jne pf_cd_apply
  mulss xmm0,[pf_tenth]
pf_cd_apply:
  maxss xmm6,xmm0
pf_cd_restore:
  movups xmm0,[rsp]
  add rsp,10
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  ucomiss xmm6,[rbx+98]
  jmp $DUR_RETURN
pf_tenth:
  dd 3DCCCCCD
// Input RCX=item. Only scratch registers RAX/R8-R11 are used below.
pf_owned:
  lea r9,[pf_consume_data]
  mov rax,[r9+8]
  test rax,rax
  je pf_no
  mov rax,[rax]
  cmp rax,[r9+10]
  jne pf_no
  mov r8d,[r9+28]
  cmp r8d,20
  ja pf_no
  add r9,40
pf_owner_loop:
  test r8d,r8d
  je pf_no
  mov r10,[r9+8]
  test r10,r10
  je pf_owner_next
  mov rax,[r9]
  cmp [r10],rax
  jne pf_owner_next
  mov r11d,[r9+10]
  cmp [r10+10],r11d
  jne pf_owner_next
  test dword ptr [rax+8],40018000
  jne pf_owner_next
  mov r10d,[r9+14]
  add rax,r10
  mov r11d,[rax+8]
  cmp r11d,1000
  ja pf_owner_next
  mov r10,[rax]
  test r10,r10
  je pf_owner_next
pf_slot_loop:
  test r11d,r11d
  je pf_owner_next
  cmp [r10],rcx
  je pf_yes
  add r10,8
  dec r11d
  jmp pf_slot_loop
pf_owner_next:
  add r9,20
  dec r8d
  jmp pf_owner_loop
pf_no:
  xor eax,eax
  ret
pf_yes:
  mov eax,1
  ret
pf_ammo_type:
  lea r9,[pf_consume_data]
  mov r10,[r9+18]
  test r10,r10
  je pf_no
  mov eax,[rcx+68]
  cmp eax,[r10+14]
  jae pf_no
  mov r11d,eax
  shr eax,10
  mov r8,[r10]
  mov r8,[r8+rax*8]
  and r11d,FFFF
  imul r11,r11,18
  add r8,r11
  mov eax,[rcx+6C]
  cmp [r8+10],eax
  jne pf_no
  mov r8,[r8]
  test r8,r8
  je pf_no
  test dword ptr [r8+8],40018000
  jne pf_no
  mov r8,[r8+10]
  mov r10,[r9+20]
  test r10,r10
  je pf_no
  mov r11d,40
pf_type_loop:
  test r8,r8
  je pf_no
  cmp r8,r10
  je pf_yes
  mov r8,[r8+40]
  dec r11d
  jne pf_type_loop
  jmp pf_no
align 10
pf_consume_data:
  // flags, GWorld address, world, GUObjectArray, projectile class, count, owner rows
  dq 0 0 0 0 0 0 0 0
  db 00
$ITEM:
  jmp pf_consume
  nop
$AMMO:
  jmp pf_ca
$DUR:
  jmp pf_cd
  nop 2
[DISABLE]
$ITEM:
  db 40 53 48 83 EC 20
$AMMO:
  db 48 89 5C 24 08
$DUR:
  db 0F 2E B3 98 00 00 00
unregistersymbol(pf_consume_data)
// Keep allocation until process exit: an in-flight call may still use it.

]==]
-- Revision 007: preserve quantities at native consumption, not by polling old values.
PF.SIGS.ItemConsume={p='40 53 48 83 EC 20 8B DA 48 8B D1 85 DB 7F 08 33 C0 48 83 C4 20 5B C3 8B 81 90 00 00 00',off=0,len=6}
PF.SIGS.ItemDurability={p='0F 2E B3 98 00 00 00 74 14 48 8D 4B 50 F3 0F 11 B3 98 00 00 00 48 8B D3',off=0,len=7}
local function consumeRefresh()
  local st=PF.consumeState
  if not st or st.pid~=getOpenedProcessID() then return end
  local P=PF.player();local c=chain()
  if not P or not c then writeBytes(st.data,0) return end
  P.invArr=nil
  local rows={};local seen={}
  for _,e in ipairs(invArrays(P)) do
    if e.objects and not seen[e.a] and UE.live(e.owner) then
      local ix=ri(e.owner+0xC)
      if ix and ix&gt;=0 and ix&lt;UE.count() then
        local ch=rq(rq(UE.gobj)+(ix//65536)*8)
        local item=ch and ch+(ix%65536)*24
        if item and rq(item)==e.owner then
          rows[#rows+1]=string.pack('&lt;I8I8I4I4I8',e.owner,item,readInteger(item+0x10),e.a-e.owner,0)
          seen[e.a]=true
        end
      end
    end
  end
  if #rows==0 or #rows&gt;32 then writeBytes(st.data,0) error('Player inventory ownership list unavailable.',0) end
  local payload=string.pack('&lt;I8I8I8I8I8I8I8I8',0,UE.gworld,c.world,UE.gobj,st.ammoClass,#rows,0,0)..table.concat(rows)
  local bytes={payload:byte(1,#payload)}
  pause()
  local ok,err=pcall(function()
    writeBytes(st.data,0)
    assert(writeBytes(st.data,bytes)~=false,'Ownership update failed')
    writeBytes(st.data,st.mask)
  end)
  unpause()
  if not ok then error(err,0) end
end
local function consumeStop(bit)
  local st=PF.consumeState
  if not st then return end
  st.mask=st.mask&amp;(~bit)
  if st.pid~=getOpenedProcessID() then PF.consumeState=nil return end
  writeBytes(st.data,st.mask)
  if st.mask==0 then
    pause()
    local ok,result=pcall(autoAssemble,st.script,st.info)
    unpause()
    if not ok or not result then error('Could not restore inventory hooks; protection disabled.',0) end
    PF.consumeState=nil
  end
end
local function consumeStart(bit)
  PF.needPlayer()
  if not PF.checkBuild() then error('Unsupported build for native inventory protection.',0) end
  local st=PF.consumeState
  if st and st.pid~=getOpenedProcessID() then PF.consumeState=nil st=nil end
  if not st then
    local cls=findClassByName('InventoryItem')
    local ammoClass=findClassByName('Data_ProjectileProperties')
    local amount=cls and UE.findProp(cls,'Amount')
    local config=cls and UE.findProp(cls,'Config')
    assert(amount and amount.off==0x90 and config and config.off==0x68 and ammoClass,'Inventory layout changed')
    assert(UE.O.chunk==65536 and UE.O.itemSize==24 and UE.O.super==0x40,'Object layout changed')
    local item=assert(PF.resolveSig('ItemConsume'),'Item consumption code not found')
    local ammo=assert(PF.resolveSig('AmmoRemove'),'Magazine consumption code not found')
    local dur=assert(PF.resolveSig('ItemDurability'),'Item durability code not found')
    local moveCall=assert(PF.resolveSig('InventoryMoveCall'),'Inventory move call not found or ambiguous')
    local splitCall=assert(PF.resolveSig('InventorySplitCall'),'Inventory split call not found or ambiguous')
    local script=PF.CONSUME_AA:gsub('%$([A-Z_]+)',function(k)
      local vals={ITEM=item,AMMO=ammo,DUR=dur,DUR_RETURN=dur+7,ITEM_RETURN=item+6,AMMO_RETURN=ammo+5,MOVE_RETURN=moveCall+5,SPLIT_RETURN=splitCall+5}
      return ('%X'):format(assert(vals[k]))
    end)
    pause()
    local ok,result,info=pcall(autoAssemble,script)
    unpause()
    if not ok or not result then error('Native inventory hook failed: '..tostring(info or result),0) end
    st={pid=getOpenedProcessID(),data=assert(getAddressSafe('pf_consume_data')),mask=0,script=script,info=info,ammoClass=ammoClass}
    PF.consumeState=st
  end
  st.mask=st.mask|bit
  local ok,err=pcall(consumeRefresh)
  if not ok then consumeStop(bit) error(err,0) end
end
PF.F.invFreeze={on=function() consumeStart(1) end,off=function() consumeStop(1) end,task=consumeRefresh}
PF.F.ammoInf={on=function() consumeStart(2) end,off=function() consumeStop(2) end,task=consumeRefresh}
PF.F.noBreak={on=function() consumeStart(4) end,off=function() consumeStop(4) end,task=consumeRefresh}
PF.F.durAll={on=function() consumeStart(8) end,off=function() consumeStop(8) end,task=consumeRefresh}
local consumeOldDisable=PF.disableAll
function PF.disableAll(self) consumeStop(15) return consumeOldDisable(self) end
local consumeOldForget=PF.forgetProcess
function PF.forgetProcess() PF.consumeState=nil return consumeOldForget() end


-- Connection and core diagnostics retained in the public table.
local function aobAll(pat, s, e, maxn)
  local r={} local from=s
  while from&lt;e and #r&lt;maxn do local a=aaFind(pat,from,e) if not a then break end r[#r+1]=a from=a+1 end
  return r
end

function PF.pendingNames() local r={} for n in pairs(PF.pend) do r[#r+1]=n end table.sort(r) return r end

function PF.luaEngine() local ok,f=pcall(getLuaEngine) if ok then return f end end

function PF.openLuaEngine(quiet)
  local f=PF.luaEngine()
  if f then pcall(function() f.show() end) pcall(function() f.bringToFront() end) end
  if not quiet then PF.msg('Lua Engine opened. Messages of this table are printed here.','Lua Engineを開きました。このテーブルのメッセージはここに表示されます。') end
end

function PF.closeLuaEngine()
  local f=PF.luaEngine()
  if f then pcall(function() f.hide() end) end
end

function PF.envReport()
  PF.openLuaEngine(true)
  local pid=getOpenedProcessID()
  print(('[%s] CE version      : %s'):format(PF.TAG, tostring(getCEVersion and getCEVersion())))
  print(('[%s] target process  : %s (running PID %s / opened PID %s / table PID %s)'):format(PF.TAG, PF.EXE,
        tostring(getProcessIDFromProcessName(PF.EXE)), tostring(pid), tostring(PF.pid)))
  local okx,x64=pcall(targetIs64Bit) print(('[%s] target 64-bit   : %s'):format(PF.TAG, tostring(okx and x64)))
  local m=PF.mod()
  if m then
    local lf=ri(m+0x3C); local ts=lf and readInteger(m+lf+8)
    print(('[%s] module          : %s base=%X size=%X PE-timestamp=%X'):format(PF.TAG, PF.MODULE, m, PF.modSize() or 0, ts or 0))
    if PF.BUILD then print(('[%s] expected build  : timestamp=%X size=%X (v%s)'):format(PF.TAG, PF.BUILD.ts, PF.BUILD.size or 0, PF.GAMEVER)) end
  else print(('[%s] module          : %s NOT FOUND'):format(PF.TAG, PF.MODULE)) end
  print(('[%s] shared memory   : pfFlags=%s'):format(PF.TAG, PF.base() and hex(PF.base()) or 'not allocated'))
  print(('[%s] attached        : %s'):format(PF.TAG, tostring(PF.attached())))
end

function PF.scanSelfTest()
  PF.openLuaEngine(true) PF.require()
  local started=getTickCount()
  local okn,bad=0,0
  local names={} for n in pairs(PF.SIGS) do names[#names+1]=n end table.sort(names)
  for _,name in ipairs(names) do
    local sg=PF.SIGS[name]; local m=PF.mod(sg.mod); local sz=PF.modSize(sg.mod)
    local r=aobAll(sg.p, m, m+sz, 3)
    local got={} for i,a in ipairs(r) do got[i]=string.format('%s+%X',sg.mod or PF.MODULE,a-m) end
    local st=(#r==1) and 'OK' or ((#r==0) and 'NOT FOUND' or 'NOT UNIQUE')
    if #r==1 then okn=okn+1 else bad=bad+1 end
    print(('[%s]   %-16s %-10s %s'):format(PF.TAG, name, st, table.concat(got,', ')))
  end
  print(('[%s] AOB self-test elapsed: %d ms'):format(PF.TAG,getTickCount()-started))
  PF.msg(('AOB self-test done: %d OK, %d NG.'):format(okn,bad),('AOBスキャンテスト完了: 正常 %d件、異常 %d件。'):format(okn,bad))
end

function PF.statusReport()
  local b=PF.base()
  if b then
    PF.msg(('Fall protection: GAS effects blocked %d / Actor damage blocked %d.'):format(readQword(b+PF.OFF_PTRS+0xD0) or 0,readQword(b+PF.OFF_PTRS+0xF0) or 0),
           ('落下保護: GAS効果の遮断 %d回 / 通常ダメージの遮断 %d回。'):format(readQword(b+PF.OFF_PTRS+0xD0) or 0,readQword(b+PF.OFF_PTRS+0xF0) or 0))
  end
  PF.openLuaEngine(true)
  local l=PF.pendingNames()
  local deferred=0 for n in pairs(PF.SIGS) do if not PF.A[n] and not PF.pend[n] then deferred=deferred+1 end end
  print(('[%s] signatures not requested yet: %d'):format(PF.TAG,deferred))
  print(('[%s] unresolved signatures: %s'):format(PF.TAG, #l&gt;0 and table.concat(l,', ') or '-'))
  local h={} for n,st in pairs(PF.hookState) do h[#h+1]=('%s@%X'):format(n,st.addr) end table.sort(h)
  print(('[%s] active hooks        : %s'):format(PF.TAG, #h&gt;0 and table.concat(h,', ') or '-'))
  local f={} for k in pairs(PF.featOn) do f[#f+1]=k end table.sort(f)
  print(('[%s] features on         : %s'):format(PF.TAG, #f&gt;0 and table.concat(f,', ') or '-'))
  local al=getAddressList(); local a={}
  for i=0,al.Count-1 do local m=al.getMemoryRecord(i) if m.Active then a[#a+1]=('[%d] %s'):format(m.ID,m.Description) end end
  print(('[%s] active records      : %s'):format(PF.TAG, #a&gt;0 and table.concat(a,' / ') or '-'))
end

function PF.ueReport()
  PF.openLuaEngine(true) PF.require()
  UE.reset()
  local ok,e=pcall(UE.init)
  local function p(s) print('['..PF.TAG..'] '..s) end
  p(('GNames   : %s'):format(UE.gnames and ('%X'):format(UE.gnames) or 'NOT FOUND'))
  p(('GObjects : %s  (objects %d)'):format(UE.gobj and ('%X'):format(UE.gobj) or 'NOT FOUND', UE.count()))
  p(('GWorld   : %s'):format(UE.gworld and ('%X'):format(UE.gworld) or 'NOT FOUND'))
  if UE.gnames then p('name #0  : '..tostring(UE.name(0))) end
  local w=UE.gworld and rq(UE.gworld)
  if w and UE.isObj(w) then p('world    : '..UE.fullName(w)) else p('world    : (none)') end
  if not ok then p('ERROR    : '..tostring(e)) return end
  local c=chain()
  if not c then p('player   : (not found - load a save)') return end
  p('pawn     : '..UE.fullName(c.pawn))
  p('ctrl     : '..UE.fullName(c.pc))
  if c.ps then p('state    : '..UE.fullName(c.ps)) end
end

-- Hold Space after jumping to maintain a gentle upward velocity.
-- No persistent movement settings are modified; release resumes normal gravity.
function PF.spaceFloatTick()
  if not PF.featOn.spaceFloat or not PF.attached() then
    if PF.spaceFloatTimer then PF.spaceFloatTimer.Enabled=false end
    return
  end
  if not isKeyPressed(0x20) or getWindowProcessID(getForegroundWindow())~=PF.pid then return end
  local P=PF.player()
  if not P or not P.move or not UE.isObj(P.move) then return end
  local mode=UE.prop(P.move,'MovementMode')
  if not mode or readBytes(mode,1)~=3 then return end -- Only airborne walking jumps; no swimming/vehicles.
  local velocity,pr=UE.prop(P.move,'Velocity')
  local st=pr and pr.kind=='StructProperty' and UE.structOf(pr)
  local z=st and UE.findProp(st,'Z')
  if not velocity or not z or z.kind~='DoubleProperty' then return end
  local vz=readDouble(velocity+z.off)
  if vz and vz==vz and vz&lt;250 then writeDouble(velocity+z.off,250) end -- cm/s, keep stronger upward jumps.
end
PF.F.spaceFloat={
  on=function()
    local P=PF.needPlayer()
    local v,pr=UE.prop(P.move,'Velocity')
    local st=pr and pr.kind=='StructProperty' and UE.structOf(pr)
    local z=st and UE.findProp(st,'Z')
    if not P.move or not UE.prop(P.move,'MovementMode') or not v or not z or z.kind~='DoubleProperty' then
      PF.err('Character movement velocity is unavailable.','キャラクターの移動速度情報を取得できません。')
    end
    if not PF.spaceFloatTimer then
      PF.spaceFloatTimer=createTimer(nil,false)
      PF.spaceFloatTimer.Interval=16
      PF.spaceFloatTimer.OnTimer=function()
        local ok,e=pcall(PF.spaceFloatTick)
        if not ok then
          PF.spaceFloatTimer.Enabled=false
          PF.msg('Space float stopped: '..tostring(e),'スペース浮上を停止: '..tostring(e))
        end
      end
    end
    PF.spaceFloatTimer.Enabled=true
  end,
  off=function() if PF.spaceFloatTimer then PF.spaceFloatTimer.Enabled=false end end
}

PF.NAMES = {
  [211] = {'Hold Space to float upward', 'スペース長押しで浮上'},
  [17] = {'UE core check (GNames / GObjects / GWorld / player)', 'UE基幹データ確認（GNames／GObjects／GWorld／プレイヤー）'},
  [16] = {'Status: unresolved code / active hooks / active features', '状態：未検出コード／有効フック／有効機能'},
  [15] = {'Environment / connection info (CE, process, module, build)', '環境・接続情報（CE・プロセス・モジュール・ビルド）'},
  [14] = {'AOB scan self-test (CE is busy for a while; prints to Lua Engine)', 'AOBスキャンテスト（しばらくCEが応答しません。結果はLua Engineに表示）'},
  [13] = {'Lua Engine (check = open / uncheck = close)', 'Lua Engine（チェックで開く／外すと閉じる）'},
  [12] = {'Diagnostics (only when the table does not work)', '診断（動作しないときのみ）'},
  [1] = {'[ATTACH / ALL OFF] Attach to Permafrost-Win64-Shipping.exe + disable everything', '【アタッチ／一括解除】Permafrost-Win64-Shipping.exeにアタッチ＋全機能オフ'},
  [2] = {'0. Settings &amp; README', '0. 設定・説明'},
  [3] = {'Language / 言語設定', '言語設定 / Language'},
  [4] = {'English (default)', 'English（既定）'},
  [5] = {'日本語 / Japanese', '日本語 / Japanese'},
  [6] = {'README', 'はじめに'},
  [7] = {'1) Start the game, open this table (allow its Lua script), then run [ATTACH / ALL OFF] at the top. Load a save before using the features.', '1) ゲームを起動してこのテーブルを開き（Luaスクリプトの実行を許可）、先頭の【アタッチ／一括解除】を実行してください。各機能はセーブをロードしてから使用してください。'},
  [8] = {'2) Made for the Permafrost 0.45.2.4855, Steam build 26560720, PE timestamp 4D288179 (UE 5.4). UE core references use validated data targets and bounded initialization retries. The supported build uses byte-checked known code locations; feature code is resolved on demand. Other builds use module-only AOB scans. Game data is located by UE reflection (names); on other builds a warning is shown and features whose data is not found are disabled.', '2) 対応は製品版 0.45.2.4855、Steam build 26560720、PEタイムスタンプ 4D288179 です（UE 5.4）。UE基幹は参照先の内容検証と回数制限付き再試行を行います。対応ビルドは既知コード位置をバイト検証して使用し、各機能のコードは有効化時に取得します。別ビルドはモジュール内AOB検索を使用します。ゲームデータはUEリフレクション（名前）で検出します。別ビルドでは警告を表示し、データが見つからない機能は無効になります。'},
  [9] = {'3) Orange = script (check to run / toggle), cyan = expandable group / list, no color = value (double-click to edit).', '3) オレンジ＝スクリプト（チェックで実行／切替）、水色＝展開できるグループ・一覧、色なし＝値（ダブルクリックで直接入力）。'},
  [10] = {'4) Status and error messages appear in the Lua Engine window of Cheat Engine.', '4) 状態・エラーメッセージはCheat EngineのLua Engineウィンドウに表示されます。'},
  [11] = {'5) Save your game before using editor / one-shot actions. Game functions (add items, blueprints, weather, item names) run only while you are in game.', '5) 書き換え系の操作の前にセーブしてください。ゲーム関数の呼び出し（アイテム追加・設計図・天候・アイテム名の取得）はゲーム中のみ動作します。'},
  [100] = {'1. Survival (enabled = kept at MAX, never decreases)', '1. サバイバル（有効中はMAX値で固定・減少しない）'},
  [101] = {'Infinite health', '体力無限'},
  [102] = {'Infinite stamina', 'スタミナ無限'},
  [106] = {'No hunger (Hunger at max)', '空腹なし（空腹度をMAXで固定）'},
  [103] = {'No fatigue (Energy at max)', '疲労なし（エネルギーをMAXで固定）'},
  [104] = {'No cold (body warmth at max)', '寒さなし（体温をMAXで固定）'},
  [105] = {'No drunkenness (alcohol = 0)', '酔わない（アルコール量＝0）'},
  [200] = {'2. Player', '2. プレイヤー'},
  [201] = {'Skill experience multiplier', 'スキル経験値倍率'},
  [202] = {'Multiplier', '倍率'},
  [203] = {'Movement speed multiplier', '移動速度倍率'},
  [204] = {'Speed multiplier', '速度倍率'},
  [205] = {'Jump height multiplier', 'ジャンプ力倍率'},
  [206] = {'Jump multiplier', 'ジャンプ倍率'},
  [207] = {'No fall damage (player only; works with Space float)', '落下ダメージなし（プレイヤーのみ・スペース浮上対応）'},
  [212] = {'Emergency unstick (find surface / reset movement state)', '緊急脱出（地表へ復帰・滑落と移動状態をリセット）'},
  [210] = {'Teleport to the map sticker you place (open the map, place a sticker at the mouse pointer)', 'マップでステッカーを置いた位置へテレポート（マップを開き、マウスポインタの位置にステッカーを置く）'},
  [208] = {'Player parameters (enable to list / edit)', 'プレイヤーパラメータ（有効化で一覧表示・直接編集）'},
  [209] = {'Blueprint points (enable to show / edit)', '設計図ポイント（有効化で表示・直接編集）'},
  [300] = {'3. Items', '3. アイテム'},
  [301] = {'No item consumption (player inventory; transfers and splitting allowed)', 'アイテム消費なし（プレイヤー所持品・移動と分割は通常動作）'},
  [302] = {'No ammo consumption (player magazines, bullets and arrows)', '弾薬消費なし（プレイヤーの装填弾・所持弾・矢）'},
  [303] = {'Infinite durability (refilled to MAX while enabled)', '耐久度無限（有効中はMAXまで回復）'},
  [304] = {'Items never break (durability never goes below 10%)', 'アイテム壊れない（耐久度が10%未満にならない）'},
  [307] = {'Infinite fuel (campfires / stoves / furnaces, generators, vehicles, lanterns)', '燃料無限（焚き火・かまど・炉など、発電機、乗り物、ランタン類）'},
  [305] = {'Add items... (category list / multi-select / quantity)', 'アイテム追加…（カテゴリ別一覧・複数選択・個数指定）'},
  [306] = {'Item amounts (enable to list / edit)', 'アイテム個数（有効化で一覧表示・直接編集）'},
  [400] = {'4. Crafting', '4. クラフト'},
  [401] = {'Add blueprints... (from the blueprint list)', '設計図追加…（設計図一覧から）'},
  [402] = {'Learn all blueprints', '設計図すべて入手'},
  [403] = {'No materials needed (crafting: hand / workbenches / placed stations; building; repair / renovation)', '素材必要なし（クラフト：手作業・作業台・設置型すべて／建築／修理・改修）'},
  [404] = {'Instant craft (crafting / recycling time 0.1 s)', 'インスタントクラフト（作成・リサイクル時間0.1秒）'},
  [405] = {'Instant build (0.1 s base time; normal completion)', 'インスタント建築（基本時間0.1秒・通常の完成処理）'},
  [500] = {'5. World', '5. ワールド'},
  [501] = {'Always daytime (lock at 12:00)', '常に昼（12:00で固定）'},
  [502] = {'Keep clear weather', '快晴を維持'},
  [503] = {'Set time of day now (hour below)', '時刻を今すぐ設定（下の時刻）'},
  [504] = {'Lock time of day (hour below)', '時刻を固定（下の時刻）'},
  [505] = {'Hour (0-23.99, e.g. 12 = noon, 0 = midnight)', '時（0～23.99、例: 12＝昼、0＝真夜中）'},
  [506] = {'Set weather now... (choose from the list)', '天候を今すぐ設定…（一覧から選択）'},
  [507] = {'Lock weather (keep the weather chosen above)', '天候を固定（上で選んだ天候を維持）'},
  [509] = {'Reveal the whole map (runs in the background; progress in Lua Engine)', 'マップをフルオープン（裏で順に開放。進み具合はLua Engineに表示）'},
  [510] = {'Spawn animals... (choose the kind and number; around you)', '動物をスポーン…（種類と数を指定。自分の周囲に）'},
  [508] = {'Spawn a snowmobile (in front of you; the class is loaded if needed)', 'スノーモービルをスポーン（目の前に。未読み込みならクラスを読み込む）'},
  [600] = {'6. Quests (save first; close the menu before running)', '6. クエスト（実行前にセーブ。メニューを閉じてから実行）'},
  [601] = {'Advance the current main quest by one step', '現在のメインクエストを1つ進める'},
  [602] = {'Advance the current side quest by one step', '現在のサイドクエストを1つ進める'},
  [603] = {'Insert a quest... (choose from the list; starts it)', 'クエストを挿入…（一覧から選択して開始）'},
  [800] = {'8. Other', '8. その他'},
  [801] = {'Unlock all Steam achievements', 'Steam実績全解除'},
  [700] = {'7. Save data files (newest 10 backups kept)', '7. セーブデータファイル（バックアップは最新10個を保持）'},
  [701] = {'Back up the current save data (save in game first)', '現在のセーブデータをバックアップ（先にゲーム内でセーブ）'},
  [702] = {'Restore save data... (list with timestamps; at the title screen or with the game closed)', 'セーブデータを復旧…（タイムスタンプ付き一覧から。タイトル画面またはゲーム終了中に実行）'},
}

----------------------------------------------------------------- Steam achievements (current game's own Steam API)
local function steamBool(v) return type(v)=='number' and (v&amp;0xFF)~=0 end
function PF.steamAchievementExports(module)
  local base,size=PF.mod(module),PF.modSize(module)
  if not base or not size or size&lt;=0 then PF.err('Steam API is not loaded. Start the game through Steam.','Steam APIが読み込まれていません。Steamからゲームを起動してください。') end
  local function at(rva,n)
    assert(type(rva)=='number' and rva&gt;=0 and rva+(n or 4)&lt;=size,'Invalid Steam API export layout')
    return base+rva
  end
  local function uint(rva)
    local n=readInteger(at(rva,4));assert(n,'Unreadable Steam API export layout');return n&amp;0xFFFFFFFF
  end
  local nt=uint(0x3C)
  assert(readSmallInteger(base)==0x5A4D and uint(nt)==0x4550 and readSmallInteger(at(nt+0x18,2))==0x20B,'Invalid Steam API PE header')
  local dir,dirSize=uint(nt+0x88),uint(nt+0x8C)
  at(dir,40);assert(dir&gt;0 and dirSize&gt;0,'Missing Steam API export directory')
  local functions,names=uint(dir+0x14),uint(dir+0x18)
  assert(functions&gt;0 and functions&lt;=65536 and names&gt;0 and names&lt;=65536,'Invalid Steam API export count')
  local ft,ntable,ord=uint(dir+0x1C),uint(dir+0x20),uint(dir+0x24)
  at(ft,functions*4);at(ntable,names*4);at(ord,names*2)
  local exports={}
  for i=0,names-1 do
    local nameRva=uint(ntable+i*4)
    local name=readString(at(nameRva,1),math.min(256,size-nameRva),false)
    if name and name:find('SteamAPI_',1,true)==1 then
      local index=readSmallInteger(at(ord+i*2,2))
      assert(index and (index&amp;0xFFFF)&lt;functions,'Invalid Steam API export ordinal')
      local rva=uint(ft+(index&amp;0xFFFF)*4)
      if rva&gt;0 and not (rva&gt;=dir and rva&lt;dir+dirSize) then exports[name]=at(rva,1) end
    end
  end
  return exports,base,size
end

function PF.steamAchievementsApi()
  PF.require()
  local module='steam_api64.dll'
  local exports,base,size=PF.steamAchievementExports(module)
  local names={stats='SteamAPI_SteamUserStats_v012',utils='SteamAPI_SteamUtils_v010',app='SteamAPI_ISteamUtils_GetAppID',
    count='SteamAPI_ISteamUserStats_GetNumAchievements',name='SteamAPI_ISteamUserStats_GetAchievementName',
    get='SteamAPI_ISteamUserStats_GetAchievement',set='SteamAPI_ISteamUserStats_SetAchievement',store='SteamAPI_ISteamUserStats_StoreStats'}
  local api={}
  for key,name in pairs(names) do
    local a=exports[name]
    if not a or a&lt;base or a&gt;=base+size then PF.err('Steam API export unavailable: '..name,'Steam API関数を取得できません: '..name) end
    api[key]=a
  end
  function api.call(key,...)
    local result=executeCodeEx(0,5000,assert(api[key]),...)
    if type(result)~='number' then
      api.uncertain=true
      PF.err('Steam API call did not complete: '..key..'. Result is unknown; no automatic retry.','Steam API呼び出しが完了しませんでした: '..key..'。結果は不明です。自動再試行は行いません。')
    end
    return result
  end
  local utils=api.call('utils')
  if utils==0 or (api.call('app',utils)&amp;0xFFFFFFFF)~=2254990 then PF.err('Steam AppID does not match Permafrost (2254990).','Steam AppIDがPermafrost（2254990）と一致しません。') end
  api.instance=api.call('stats')
  if api.instance==0 then PF.err('Steam user stats are not ready.','Steam実績情報が準備できていません。') end
  return api
end

local function steamAchievementRead(api,items)
  local buf=assert(allocateMemory(16),'Steam achievement read buffer unavailable')
  local ok,result=xpcall(function()
    for _,item in ipairs(items) do
      writeBytes(buf,0xFE)
      local good=steamBool(api.call('get',api.instance,{type=3,value=item.name},buf))
      local value=readBytes(buf,1)
      if not good or (value~=0 and value~=1) then PF.err('Steam achievement data not ready: '..item.name,'Steam実績情報を読み取れません: '..item.name) end
      item.unlocked=(value==1)
    end
    return items
  end,debug.traceback)
  -- A timed-out call could still be using the buffer. Retain it until process exit.
  if not api.uncertain then deAlloc(buf) end
  if not ok then error(result,0) end
  return result
end

function PF.steamAchievementsPlan()
  local api=PF.steamAchievementsApi()
  local n=api.call('count',api.instance)&amp;0xFFFFFFFF
  if n==0 or n&gt;4096 then PF.err('Steam achievement list is empty or invalid. Wait for Steam to finish loading.','Steam実績一覧が空、または無効です。Steamの読み込み完了後に実行してください。') end
  local items,seen={},{}
  for i=0,n-1 do
    local ptr=api.call('name',api.instance,i)
    local name=ptr~=0 and readString(ptr,512,false)
    if not name or #name==0 or #name&gt;=512 or seen[name] then PF.err('Steam achievement list is incomplete or ambiguous.','Steam実績一覧が不完全、または重複しています。') end
    seen[name]=true;items[#items+1]={name=name}
  end
  steamAchievementRead(api,items) -- Preflight every entry before changing anything.
  return api,items
end

function PF.steamUnlockAll()
  if PF.steamAchievementBusy then PF.err('Steam achievement action is already running.','Steam実績処理はすでに実行中です。') end
  PF.steamAchievementBusy=true
  local ok,result=xpcall(function()
    local api,items=PF.steamAchievementsPlan()
    local previous,updated,failed=0,0,{}
    for _,item in ipairs(items) do
      if item.unlocked then previous=previous+1
      elseif steamBool(api.call('set',api.instance,{type=3,value=item.name})) then updated=updated+1
      else failed[#failed+1]=item.name end
    end
    -- Submit once after the batch, including a retry after a previous failed submission.
    local stored=steamBool(api.call('store',api.instance))
    steamAchievementRead(api,items)
    local verified=0 for _,item in ipairs(items) do if item.unlocked then verified=verified+1 end end
    PF.msg(('Steam achievements: local %d/%d; already unlocked %d, newly accepted %d, rejected %d.'):format(verified,#items,previous,updated,#failed),
      ('Steam実績: ローカル解除 %d/%d件、解除済み %d件、新規受付 %d件、拒否 %d件。'):format(verified,#items,previous,updated,#failed))
    if not stored then PF.err('Steam rejected the save request. Local changes may be pending; retry later.','Steamへの保存要求が拒否されました。ローカル変更は未同期の可能性があります。時間を置いて再実行してください。') end
    if #failed&gt;0 or verified~=#items then PF.err('Some achievements were not unlocked; Steam sync was requested for accepted changes.','解除できなかった実績があります。受け付けられた変更についてSteam同期を要求しました。') end
    PF.msg('Steam sync requested. Server completion has not been confirmed; check your Steam achievement list.',
      'Steam同期を要求しました。サーバーでの完了は未確認です。Steamの実績一覧で確認してください。')
  end,debug.traceback)
  PF.steamAchievementBusy=false
  if not ok then error(result,0) end
end

pcall(PF.initCollapse)
PF.applyLang()
</LuaScript>
</CheatTable>