<?xml version='1.0' encoding='utf-8'?>
<CheatTable CheatEngineTableVersion="45">
  <CheatEntries>
    <CheatEntry>
      <ID>1</ID>
      <Description>"[ATTACH / ALL OFF] Select and verify game"</Description>
      <Color>00A5FF</Color>
      <VariableType>Auto Assembler Script</VariableType>
      <AssemblerScript>

{ Game    : DRAGON QUEST BUILDERS 2
  GameVer : 1.7.3d
  Steam   : App 1072420 / Build 15274091
  Engine  : KTGL R2.5.6 (Koei Tecmo Game Library, DX11 x64)
  Author  : Black_wolf
  CheatVer:1.7.3d-001-181

  実行ファイル：DQB2.exe / DQB2_EU.exe / DQB2_AS.exe

　ハンマー範囲拡大はなかなか手こずった。
　一度に処理できるブロック数に上限があるので、広い範囲は何回かに分けて壊すようにした。

}

[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec, function() DQB2.attachGame() end)
{$asm}
[DISABLE]
</AssemblerScript>
    </CheatEntry>
    <CheatEntry>
      <ID>2</ID>
      <Description>"0. Settings"</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 (initial / default)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.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
DQB2.oneShot(memrec,function() DQB2.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>"DRAGON QUEST BUILDERS 2 1.7.3d / KTGL 2.5.6 (DX11 x64)"</Description>
              <GroupHeader>1</GroupHeader>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>12</ID>
          <Description>"Diagnostics"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>13</ID>
              <Description>"Lua Engine (ON = show / OFF = hide)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.userRun(function() DQB2.luaEngine(true) end)
{$asm}
[DISABLE]
{$lua}
if syntaxcheck then return end
if DQB2 then DQB2.userRun(function() DQB2.luaEngine(false) end) end
{$asm}
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>14</ID>
              <Description>"Validate requested resolvers (read only)"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.scanSelfTest() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>15</ID>
              <Description>"Environment / connection info"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.envReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>16</ID>
              <Description>"Feature / resolver status"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.statusReport() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>100</ID>
      <Description>"01. Gameplay"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>119</ID>
          <Description>"Invincibility"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'invincible',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'invincible',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>120</ID>
          <Description>"Infinite HP"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hp',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hp',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>121</ID>
          <Description>"Infinite stamina"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'stamina',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'stamina',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>122</ID>
          <Description>"Maximize hunger"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hunger',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hunger',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>126</ID>
          <Description>"Always critical hit"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'critical',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'critical',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>124</ID>
          <Description>"One-hit kill"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'oneHit',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'oneHit',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>125</ID>
          <Description>"Stealth mode"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'stealth',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'stealth',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>127</ID>
          <Description>"Stop enemy AI"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyAi',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyAi',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>130</ID>
          <Description>"Multipliers"</Description>
          <Options moManualExpandCollapse="1" />
          <GroupHeader>1</GroupHeader>
          <Color>FFFF00</Color>
          <Options />
          <CheatEntries>
            <CheatEntry>
              <ID>131</ID>
              <Description>"Enemy XP multiplier"</Description>
              <Options moManualExpandCollapse="1" />
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyXp',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyXp',false) end
{$asm}
</AssemblerScript>
              <CheatEntries>
                <CheatEntry>
                  <ID>132</ID>
                  <Description>"Multiplier"</Description>
                  <VariableType>4 Bytes</VariableType>
                  <Address>dqb2EnemyXpFactor</Address>
                </CheatEntry>
              </CheatEntries>
            </CheatEntry>
            <CheatEntry>
              <ID>133</ID>
              <Description>"Enemy item drop rate multiplier"</Description>
              <Options moManualExpandCollapse="1" />
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyDrop',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'enemyDrop',false) end
{$asm}
</AssemblerScript>
              <CheatEntries>
                <CheatEntry>
                  <ID>134</ID>
                  <Description>"Multiplier"</Description>
                  <VariableType>4 Bytes</VariableType>
                  <Address>dqb2EnemyDropFactor</Address>
                </CheatEntry>
              </CheatEntries>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>200</ID>
      <Description>"02. Player"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>211</ID>
          <Description>"Player movement speed"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'moveSpeed',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'moveSpeed',false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>212</ID>
              <Description>"Multiplier"</Description>
              <VariableType>Float</VariableType>
              <Address>dqb2MoveSpeedFactor</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>214</ID>
          <Description>"Jump multiplier"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'jumpFactor',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'jumpFactor',false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>215</ID>
              <Description>"Multiplier"</Description>
              <VariableType>Float</VariableType>
              <Address>dqb2JumpFactor</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>213</ID>
          <Description>"Rise while holding Jump"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'jumpHold',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'jumpHold',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>210</ID>
          <Description>"Player editor"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.openEditor(memrec,'player') end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck and DQB2 then DQB2.closeEditor(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>300</ID>
      <Description>"03. Members"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>311</ID>
          <Description>"Member editor"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.openEditor(memrec,'member')
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck and DQB2 then DQB2.closeEditor(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>312</ID>
          <Description>"Add resident"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
if not DQB2.userRun(function() DQB2.openResidentAdd(memrec) end) then
  DQB2.defer(function() memrec.Active=false end)
end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck and DQB2 then DQB2.closeEditor(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>400</ID>
      <Description>"04. Items / crafting"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>407</ID>
          <Description>"Instant cooking"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'instantCooking',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'instantCooking',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>408</ID>
          <Description>"Ignore crafting material requirements"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'craftRequirements',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'craftRequirements',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>409</ID>
          <Description>"Items are not consumed (use / crafting)"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'craftKeep',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'craftKeep',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>410</ID>
          <Description>"Edit item quantities"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.openInventoryQuantities(memrec) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck and DQB2 then DQB2.closeEditor(memrec) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>411</ID>
          <Description>"Add items by category"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.openItemAdd() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>412</ID>
          <Description>"Hammer range multiplier"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hammerRange',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'hammerRange',false) end
{$asm}
</AssemblerScript>
          <CheatEntries>
            <CheatEntry>
              <ID>413</ID>
              <Description>"Side to side"</Description>
              <VariableType>Float</VariableType>
              <Address>dqb2HammerWidth</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>415</ID>
              <Description>"Depth"</Description>
              <VariableType>Float</VariableType>
              <Address>dqb2HammerDepth</Address>
            </CheatEntry>
            <CheatEntry>
              <ID>414</ID>
              <Description>"Height"</Description>
              <VariableType>Float</VariableType>
              <Address>dqb2HammerHeight</Address>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
        <CheatEntry>
          <ID>420</ID>
          <Description>"Recipes and Builderpedia"</Description>
          <Options moManualExpandCollapse="1" />
          <Color>FFFF00</Color>
          <GroupHeader>1</GroupHeader>
          <CheatEntries>
            <CheatEntry>
              <ID>421</ID>
              <Description>"Obtain all Builder's tools"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.obtainAllBuilderTools() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>422</ID>
              <Description>"Unlock all recipes"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.unlockAllRecipes() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>423</ID>
              <Description>"Discover all items"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.discoverAllItems() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>424</ID>
              <Description>"Discover all monsters"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.discoverAllMonsters() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>425</ID>
              <Description>"Unlock all room recipes"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.unlockAllRoomRecipes() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
            <CheatEntry>
              <ID>426</ID>
              <Description>"Unlock all blueprints"</Description>
              <Color>00A5FF</Color>
              <VariableType>Auto Assembler Script</VariableType>
              <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.unlockAllBlueprints() end)
{$asm}
[DISABLE]
</AssemblerScript>
            </CheatEntry>
          </CheatEntries>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>500</ID>
      <Description>"05. World"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>501</ID>
          <Description>"Stop time of day"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'worldTime',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'worldTime',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>503</ID>
          <Description>"Disable fog"</Description>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'disableFog',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'disableFog',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>502</ID>
          <Description>"Reveal current island map"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.revealMap() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
    <CheatEntry>
      <ID>600</ID>
      <Description>"06. Other"</Description>
      <Options moManualExpandCollapse="1" />
      <Color>FFFF00</Color>
      <GroupHeader>1</GroupHeader>
      <CheatEntries>
        <CheatEntry>
          <ID>604</ID>
          <Description>"Unlock all Steam achievements"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.unlockSteamAchievements() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>605</ID>
          <Description>"Steam hotkey fix"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'steamHotkey',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'steamHotkey',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>606</ID>
          <Description>"Release mouse cursor"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'releaseCursor',true) end
{$asm}
[DISABLE]
{$lua}
if not syntaxcheck then DQB2.toggleRecord(memrec,'releaseCursor',false) end
{$asm}
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>602</ID>
          <Description>"Restore all"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.disableAll() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
        <CheatEntry>
          <ID>603</ID>
          <Description>"Restore and disconnect"</Description>
          <Color>00A5FF</Color>
          <VariableType>Auto Assembler Script</VariableType>
          <AssemblerScript>[ENABLE]
{$lua}
if syntaxcheck then return end
DQB2.oneShot(memrec,function() DQB2.shutdown() end)
{$asm}
[DISABLE]
</AssemblerScript>
        </CheatEntry>
      </CheatEntries>
    </CheatEntry>
  </CheatEntries>
  <LuaScript>if DQB2 then
  if type(DQB2.shutdown)~='function' then
    print('[DQB2] An older DQB2 table is still loaded. Restore and close it before loading V3. / 旧GTテーブルを解除して閉じてからV3を開いてください。')
    return
  end
  local restored,err=pcall(DQB2.shutdown)
  if not restored then
    print('[DQB2] '..tostring(err))
    return
  end
end
DQB2 = {}
DQB2.VERSION, DQB2.CHEATVER, DQB2.TAG = 'V3', '1.7.3d-001-181', 'DQB2'
DQB2.TITLE = 'DRAGON QUEST BUILDERS 2'
DQB2.GAMEVER, DQB2.ENGINE = '1.7.3d', 'KTGL 2.5.6 (DX11 x64)'
DQB2.RVA = {}

DQB2.C_GROUP, DQB2.C_SCRIPT = 0xFFFF00, 0x00A5FF

DQB2.lang = 'en'
DQB2.serial, DQB2.epoch = 0, 0
DQB2.A, DQB2.status, DQB2.hooks, DQB2.active = {}, {}, {}, {}
DQB2.sessions, DQB2.dynamic, DQB2.deferred = {}, {}, {}
DQB2.history = {}

DQB2.CONFIG = {title=DQB2.TITLE, candidates=nil, identify=nil,
  boundary=nil, tick=250, maxCandidates=64, editorAutoRefresh=false, editorUndo=false,
  scanChunkBytes=262144, resolveBudgetMs=1500,
  modules={code={main=true}}}

DQB2.SIGS = {}

DQB2.HOOKS = {}

DQB2.F, DQB2.EDITORS = {}, {}

local function need(v,en,ja) if not v then error(DQB2.T(en,ja),0) end return v end
local function hex(v) return string.format('%X',v) end
local function keyOK(v) return type(v)=='string' and v:match('^[%a_][%w_]*$') end
local function equal(a,b)
  if type(a)~='table' or type(b)~='table' or #a~=#b then return false end
  for i=1,#a do if a[i]~=b[i] then return false end end return true
end
local function bytes(a,n)
  local ok,b=pcall(readBytes,a,n,true)
  if ok and type(b)=='table' and #b==n then return b end
end
local function db(b) local t={} for i,v in ipairs(b) do t[i]=('%02X'):format(v) end return table.concat(t,' ') end
local function checkedCall(fn,...)
  local r=fn(...); need(r~=false,'Operation rejected.','処理が拒否されました。'); return r
end
DQB2.sameBytes, DQB2.readExact = equal, bytes
function DQB2.T(en,ja) return DQB2.lang=='ja' and (ja or en) or en end
function DQB2.msg(en,ja) print('['..DQB2.TAG..'] '..DQB2.T(en,ja)) end
function DQB2.err(en,ja) error(DQB2.T(en,ja),0) end
function DQB2.userRun(fn)
  local ok,e=pcall(fn)
  if not ok then DQB2.msg(tostring(e),tostring(e)) end
  return ok,e
end

local function disposeDeferred(timer)
  pcall(function() timer.Enabled=false end)
  pcall(function() timer.OnTimer=nil end)
  pcall(function() timer.destroy() end)
end

function DQB2.defer(fn)
  local epoch=DQB2.epoch
  local timer=createTimer(nil,false)
  local pending=DQB2.deferred
  pending[timer]=true
  timer.Interval=1
  timer.OnTimer=function()
    if DQB2.deferred~=pending or not pending[timer] then return end
    pending[timer]=nil
    disposeDeferred(timer)
    if DQB2.deferred==pending and DQB2.epoch==epoch then DQB2.userRun(fn) end
  end
  timer.Enabled=true
end
function DQB2.oneShot(mr,fn)
  DQB2.defer(function()
    DQB2.userRun(fn)
    if mr then pcall(function() mr.Active=false end) end
  end)
end
function DQB2.closeItemPicker()
  DQB2.itemGrantBatch=nil
  local form=DQB2.itemPicker
  DQB2.itemPicker=nil
  if form then
    form.OnClose=function() return caFree end
    form.close()
  end
end

function DQB2.cancelDeferred()
  local pending=DQB2.deferred
  DQB2.deferred={}
  for timer in pairs(pending) do disposeDeferred(timer) end
end


local function u32(a) local v=readInteger(a); if v and v&lt;0 then v=v+0x100000000 end return v end
local function s32(a) local v=u32(a); if v and v&gt;=0x80000000 then v=v-0x100000000 end return v end
local function u16(a) local b=bytes(a,2); return b and b[1]+b[2]*256 end
function DQB2.pe(m)
  local b=m.Address
  need(bytes(b,2) and u16(b)==0x5A4D,'Invalid MZ header.','MZヘッダが不正です。')
  local off=u32(b+0x3C)
  need(off and off&gt;=64 and off&lt;0x100000,'Invalid PE header.','PEヘッダが不正です。')
  local p=b+off
  need(u32(p)==0x4550,'Invalid PE signature.','PEシグネチャが不正です。')
  local n,optional=u16(p+6),u16(p+20); local magic=u16(p+24)
  need(n and n&gt;0 and n&lt;=96 and optional and optional&gt;=96 and
    (magic==0x10B or magic==0x20B),'Unsupported PE layout.','未対応のPE形式です。')
  local size=u32(p+24+56)
  need(size and size&gt;0 and (not m.Size or size&lt;=m.Size),
    'Invalid image bounds.','イメージの範囲が不正です。')
  local info={base=b,size=size,ts=u32(p+8),machine=u16(p+4),sections={}}
  for i=0,n-1 do
    local a=p+24+optional+i*40
    local va,vs,raw,ch=u32(a+12),u32(a+8),u32(a+16),u32(a+36)
    need(va and vs and raw and ch,'Unreadable section table.','セクション表を読み取れません。')
    local len=vs&gt;0 and vs or raw
    if len&gt;0 then
      need(va&lt;size and va+len&lt;=size,'Section outside image.','セクションがイメージ範囲外です。')
      info.sections[#info.sections+1]={first=b+va,last=b+va+len,execute=(ch &amp; 0x20000000)~=0}
    end
  end
  return info
end
function DQB2.module(alias)
  alias=alias or 'code'
  local spec=need(DQB2.CONFIG.modules[alias],'Unknown module alias.','未定義のモジュールです。')
  local result
  for i,m in ipairs(DQB2.modules or {}) do
    local match=spec.main and i==1 or false
    for _,name in ipairs(spec.names or {}) do if m.Name:lower()==name:lower() then match=true end end
    if spec.match and spec.match(m)==true then match=true end
    if match then need(not result,'Ambiguous module.','モジュール候補が複数あります。'); result=m end
  end
  return need(result,'Required module is not loaded.','必要なモジュールがロードされていません。')
end
local aliveCache={}
function DQB2.alive()
  if not DQB2.pid or getOpenedProcessID()~=DQB2.pid then
    aliveCache={}
    return false
  end
  local now=getTickCount()
  if DQB2.lifeHandle then
    local ok,result=pcall(executeCodeLocalEx,'kernel32.WaitForSingleObject',DQB2.lifeHandle,0)
    if not ok or result~=0x102 then
      aliveCache={}
      return false
    end
    if aliveCache.pid==DQB2.pid and aliveCache.epoch==DQB2.epoch
        and now&gt;=aliveCache.at and now-aliveCache.at&lt;1000 then return true end
  end
  aliveCache={}
  local ps=getProcesslist()
  if ps[DQB2.pid]~=DQB2.processName then return false end
  local ok,ms=pcall(enumModules,DQB2.pid)
  if not ok or not ms or not ms[1] or ms[1].Address~=DQB2.mainBase or ms[1].Name~=DQB2.mainName then return false end
  local good,pe=pcall(DQB2.pe,ms[1])
  local alive=good and pe.ts==DQB2.mainPE.ts and pe.size==DQB2.mainPE.size
  if alive then aliveCache={pid=DQB2.pid,epoch=DQB2.epoch,at=now} end
  return alive
end
function DQB2.require()
  need(not DQB2.recoveryFailed,'Previous patches could not be restored. Save, restart the game, then attach again.',
    '前回のパッチを復元できませんでした。セーブ後にゲームを再起動し、アタッチし直してください。')
  need(DQB2.alive(),'Connection changed. Run ATTACH.','接続が変わりました。アタッチを実行してください。')
end
function DQB2.captureBoundary()
  DQB2.require()
  need(type(DQB2.CONFIG.boundary)=='function','Game adapter is not configured.','ゲーム用の解析結果が設定されていません。')
  local token=DQB2.CONFIG.boundary()
  need(token~=nil and token~=false,'Game data is not ready.','ゲームデータの準備ができていません。')
  need(type(token)=='string' or (type(token)=='number' and token==token and math.abs(token)&lt;math.huge),'Boundary must be a stable scalar token.','境界識別子は安定した文字列か数値にしてください。')
  return token
end
function DQB2.featureBoundary(f)
  DQB2.require()
  if f.boundary==false then return DQB2.epoch end
  if f.boundary==nil then return DQB2.captureBoundary() end
  need(type(f.boundary)=='function','Invalid feature boundary contract.','機能の境界定義が不正です。')
  local token=f.boundary()
  need(type(token)=='string' or (type(token)=='number' and token==token and math.abs(token)&lt;math.huge),
    'Feature data is not ready.','この機能に必要なデータの準備ができていません。')
  return token
end
function DQB2.attachGame()
  need(type(DQB2.CONFIG.identify)=='function','Configure the locally analysed game adapter first.','先にローカル解析済みのゲーム設定を実装してください。')
  if DQB2.pid then
    if DQB2.alive() then DQB2.disableAll(); return end
    local exited=false
    if DQB2.lifeHandle then
      local ok,result=pcall(executeCodeLocalEx,'kernel32.WaitForSingleObject',DQB2.lifeHandle,0)
      exited=ok and result==0
    end
    need(exited or (not DQB2.lifeHandle and not getProcesslist()[DQB2.pid]),
      'Select the original process and restore it before changing targets.',
      '対象を変更する前に元のプロセスを選択し、一括解除してください。')
    DQB2.forgetProcess()
  end
  local rows={}
  for pid,name in pairs(getProcesslist()) do
    if not DQB2.CONFIG.candidates or DQB2.CONFIG.candidates(name,pid)==true then
      rows[#rows+1]={id=pid,en=name..' (PID '..pid..')',ja=name..' (PID '..pid..')',process=name}
    end
  end
  table.sort(rows,function(a,b) return a.id&lt;b.id end)
  need(#rows&gt;0,'No candidate processes.','対象候補のプロセスがありません。')
  local row=rows[1]
  if #rows&gt;1 then
    row=nil
    for _, candidate in ipairs(rows) do
      if candidate.id==getOpenedProcessID() then row=candidate;break end
    end
    need(row,'Select a candidate process in the CE process list first.',
      '候補が複数あります。CEのプロセス一覧から対象を選択してください。')
  end
  openProcess(row.id)
  need(getOpenedProcessID()==row.id,'Cannot open process.','プロセスを開けません。')
  local modules=enumModules(row.id)
  need(modules and modules[1],'No modules found.','モジュールが見つかりません。')
  local main=DQB2.pe(modules[1])
  need(DQB2.CONFIG.identify(modules,row.id,row.process,main)==true,
    'The selected binary is not the supported game.','選択されたバイナリは対象ゲームと確認できません。')
  local handle=executeCodeLocalEx('kernel32.OpenProcess',0x100000,0,row.id)
  need(handle and handle~=0,'Cannot track process lifetime.','プロセスの生存期間を確認できません。')
  DQB2.pid,DQB2.processName,DQB2.modules=row.id,row.process,modules
  DQB2.mainBase,DQB2.mainName,DQB2.mainPE=modules[1].Address,modules[1].Name,main
  DQB2.lifeHandle=handle; DQB2.epoch=DQB2.epoch+1
  DQB2.A,DQB2.status={},{}
  local recoveryFailed=false
  for _,recover in ipairs({DQB2.recoverStaleHooks,DQB2.recoverInlinePatches,DQB2.checkLegacyCombatHooks}) do
    local ok,reason=pcall(recover)
    if not ok then
      recoveryFailed=true
      DQB2.msg(tostring(reason),tostring(reason))
    end
  end
  DQB2.recoveryFailed=recoveryFailed
  if recoveryFailed then
    DQB2.msg('Attachment blocked because previous patches could not be restored.',
      '前回のパッチを復元できなかったため、機能を有効化できません。')
  else
    DQB2.startTimer()
    DQB2.msg('Attached. All features are OFF.','アタッチしました。全機能は無効です。')
  end
end


function DQB2.scanPattern(pat,first,last,cap,deadline)
  need(type(pat)=='string' and pat~='','Empty pattern.','パターンが空です。')
  local fixed,patternBytes=0,0
  for token in pat:gmatch('%S+') do
    patternBytes=patternBytes+1
    need(token:match('^%x%x$') or token=='??','Use byte tokens or ??.','バイト値または??を指定してください。')
    if token~='??' then fixed=fixed+1 end
  end
  need(fixed&gt;=4,'Pattern is too broad.','パターンの識別力が不足しています。')
  need(type(first)=='number' and type(last)=='number' and first&lt;last and type(cap)=='number' and cap&gt;=1,
    'Invalid scan range or candidate limit.','探索範囲または候補上限が不正です。')
  local chunk=DQB2.CONFIG.scanChunkBytes
  need(type(chunk)=='number' and chunk%1==0 and chunk&gt;=patternBytes and chunk&lt;=1048576,
    'Invalid scan chunk size.','探索チャンクサイズが不正です。')
  local result,pos={},first
  DQB2.serial=DQB2.serial+1; local symbol='dqb2Scan_'..DQB2.serial
  local function cleanup() pcall(unregisterSymbol,symbol) end
  local ok,err=pcall(function()
    while pos&lt;last do
      need(not deadline or getTickCount()&lt;deadline,'Resolver search budget reached.','解決器の探索時間上限に達しました。')
      cleanup()
      local finish=math.min(last,pos+chunk)
      if finish-pos&lt;patternBytes then break end
      local assembled=autoAssemble(('aobscanregion(%s,%X,%X,%s)\nregistersymbol(%s)'):format(symbol,pos,finish-1,pat,symbol))
      if not assembled then
        if finish==last then break end
        pos=finish-patternBytes+1
      else
        local a=getAddressSafe(symbol); cleanup()
        need(a and a&gt;=pos and a+patternBytes&lt;=finish,'Invalid scanner result.','スキャン結果が範囲外です。')
        result[#result+1]=a
        need(#result&lt;=cap,'Too many pattern candidates.','パターン候補が多すぎます。')
        pos=a+1
      end
    end
  end)
  cleanup(); if not ok then error(err,0) end
  return result
end
function DQB2.resolveSig(name,fresh)
  DQB2.require()
  local sg=need(DQB2.SIGS[name],'Unknown resolver: '..tostring(name),'未定義の解決器です: '..tostring(name))
  need(keyOK(name),'Invalid resolver name.','解決器名が不正です。')
  need(type(sg.validate)=='function','Semantic validation is required.','対象の意味的な検証が必要です。')
  local module,pe
  local available,why=pcall(function()
    DQB2.modules=enumModules(DQB2.pid)
    module=DQB2.module(sg.module); pe=DQB2.pe(module)
  end)
  if not available then DQB2.A[name]=nil; DQB2.status[name]=tostring(why); return nil,tostring(why) end
  local fingerprint=table.concat({DQB2.pid,module.Address,pe.ts,pe.size,pe.machine},':')
  local cached=DQB2.A[name]
  if cached and not fresh and cached.fingerprint==fingerprint then
    local okay,valid=pcall(function()
      for _,r in ipairs(cached.entries) do
        if sg.validate(r.target,r.site,module)~=true or (r.anchor and not equal(bytes(r.anchorAt,#r.anchor),r.anchor)) then return false end
      end
      return true
    end)
    if okay and valid then return cached.value end
  end
  DQB2.A[name]=nil
  local budget=sg.budgetMs or DQB2.CONFIG.resolveBudgetMs
  need(type(budget)=='number' and budget&gt;0 and budget&lt;math.huge,'Invalid resolver time budget.','探索時間上限が不正です。')
  local deadline=getTickCount()+budget
  local entries,seen={},{}
  local function accept(target,site,anchor)
    if type(target)=='number' and target&gt;0 and sg.validate(target,site,module)==true and not seen[target] then
      entries[#entries+1]={target=target,site=site,anchor=anchor}; seen[target]=true
    end
  end
  local ok,e=pcall(function()
    local known=sg.knownSite and sg.knownSite()
    if known then
      accept(known,known,nil)
    elseif sg.resolve then
      local list=sg.resolve(DQB2.modules,deadline) or {}
      need(getTickCount()&lt;deadline,'Resolver search budget reached.','解決器の探索時間上限に達しました。')
      need(type(list)=='table','Resolver must return a candidate list.','解決器は候補一覧を返してください。')
      need(#list&lt;=DQB2.CONFIG.maxCandidates,'Too many candidates.','候補が多すぎます。')
      for _,a in ipairs(list) do accept(a,a,nil) end
    else
      local patterns=sg.patterns or {sg}
      for _,p in ipairs(patterns) do
        for _,section in ipairs(pe.sections) do
          if section.execute~=(sg.executable==false) then
            for _,a in ipairs(DQB2.scanPattern(p.p,section.first,section.last,DQB2.CONFIG.maxCandidates,deadline)) do
              local site=a+(p.off or sg.off or 0); local target=site
              local kind=sg.kind or 'site'
              if kind=='call' then
                need(bytes(site,1) and readBytes(site,1)==0xE8,'Expected direct call.','直接call命令ではありません。')
                local d=need(s32(site+1),'Unreadable displacement.','変位を読み取れません。'); target=site+5+d
              elseif kind=='rip' then
                local disp,len=p.disp or sg.disp,p.length or sg.length
                need(disp and len and disp&gt;=0 and disp+4&lt;=len,'Invalid RIP contract.','RIP相対命令の定義が不正です。')
                target=site+len+need(s32(site+disp),'Unreadable displacement.','変位を読み取れません。')
              else need(kind=='site' or kind=='multi','Unknown resolver kind.','未対応の解決方式です。') end
              local count=0 for _ in p.p:gmatch('%S+') do count=count+1 end
              local anchor=need(bytes(a,count),'Cannot read anchor.','照合元を読み取れません。')
              accept(target,site,nil)
              local r=entries[#entries]
              if r and r.target==target and not r.anchor then r.anchor=anchor; r.anchorAt=a end
            end
          end
        end
      end
    end
    local expected=(sg.kind=='multi') and sg.count or 1
    need(type(expected)=='number' and expected&gt;=1 and #entries==expected,
      'Resolver missing or ambiguous: '..name,'未検出または複数候補です: '..name)
  end)
  if not ok then DQB2.status[name]=tostring(e); return nil,tostring(e) end
  local values={} for i,r in ipairs(entries) do values[i]=r.target end
  local value=sg.kind=='multi' and values or values[1]
  DQB2.A[name]={fingerprint=fingerprint,entries=entries,value=value}; DQB2.status[name]='OK'
  return value
end
function DQB2.needSig(name)
  local value,e=DQB2.resolveSig(name); return need(value,e or 'Resolver unavailable.',e or '対象を解決できません。')
end


local HOOK_MARKER='DQB2HOOK'
local HOOK_MARKER_OFFSET=0x1000
local HOOK_MARKER_TAIL=0x60

local function hookJumpTarget(site,jump)
  if jump and jump[1]==0xE9 then
    return site+5+string.unpack('&lt;i4',string.char(table.unpack(jump,2,5)))
  end
end

local function restorePreviousPatch(site,original,patched)
  pause()
  local ok,reason=pcall(function()
    need(equal(bytes(site,#patched),patched),'Patch ownership changed.','パッチの所有状態が変わりました。')
    writeBytes(site,original)
    need(equal(bytes(site,#original),original),'Previous patch restoration failed.','前回のパッチを復元できませんでした。')
  end)
  unpause()
  if not ok then error(reason,0) end
end

function DQB2.writeHookMarker(site,original,cave)
  local at=cave+HOOK_MARKER_OFFSET
  local free=need(bytes(at,HOOK_MARKER_TAIL),'Cannot read the hook recovery area.','フックの復元領域を読み取れません。')
  for _,value in ipairs(free) do
    need(value==0,'Hook recovery area is occupied.','フックの復元領域が使用されています。')
  end
  local marker={HOOK_MARKER:byte(1,-1)}
  for _,value in ipairs({string.pack('&lt;I8',site):byte(1,8)}) do marker[#marker+1]=value end
  marker[#marker+1]=#original
  for _,value in ipairs(original) do marker[#marker+1]=value end
  writeBytes(at,marker)
  need(equal(bytes(at,#marker),marker),'Cannot save the hook recovery record.','フックの復元情報を記録できません。')
end

function DQB2.recoverStaleHooks()
  local found=AOBScan('44 51 42 32 48 4F 4F 4B','+X')
  if not found then return end
  local restored={}
  local ok,reason=pcall(function()
    for i=0,found.Count-1 do
      local at=tonumber(found[i],16)
      local site=readQword(at+8)
      local count=readBytes(at+16,1)
      local executable=false
      if site and count and count&gt;=5 and count&lt;=64 then
        for _,section in ipairs(DQB2.mainPE.sections) do
          if section.execute and site&gt;=section.first and site+count&lt;=section.last then executable=true break end
        end
      end
      if executable then
        local owned=false
        for _,state in pairs(DQB2.hooks) do if state.addr==site then owned=true break end end
        local current=bytes(site,count)
        local target=hookJumpTarget(site,current)
        if not owned and target==at-HOOK_MARKER_OFFSET then
          local original=need(bytes(at+17,count),'Cannot read the saved hook bytes.','保存済みの元の命令を読み取れません。')
          restorePreviousPatch(site,original,current)
          restored[#restored+1]=hex(site)
        end
      end
    end
  end)
  found.destroy()
  if not ok then error(reason,0) end
  if #restored&gt;0 then
    DQB2.msg('Restored hooks left by a previous session: '..table.concat(restored,', '),
      '前回のセッションが残したフックを元に戻しました: '..table.concat(restored,', '))
  end
end

function DQB2.hookOn(name)
  DQB2.require()
  if DQB2.hooks[name] and DQB2.hooks[name].failedInstall then DQB2.hookOff(name) end
  if DQB2.hooks[name] then return false end
  local h=need(DQB2.HOOKS[name],'Hook is not configured.','フックが設定されていません。')
  need(h.len and h.len&gt;=5 and h.len&lt;=64 and type(h.validate)=='function' and type(h.quiesce)=='function',
    'Hook requires length, validation and quiescence contracts.','フックには長さ・検証・実行待機の定義が必要です。')
  local site=DQB2.needSig(h.sig)
  need(type(site)=='number','A hook requires one code site.','フック位置は1か所に限定してください。')
  for _,st in pairs(DQB2.hooks) do need(site+h.len&lt;=st.addr or site&gt;=st.addr+#st.orig,
    'Hook sites overlap.','フック範囲が重複しています。') end
  local original=need(bytes(site,h.len),'Cannot read original code.','元コードを読み取れません。')
  need(h.validate(site,original)==true,'Hook instruction contract failed.','フック命令の検証に失敗しました。')
  local limit=site+h.len
  local cursor=site
  while cursor&lt;limit do
    local size=getInstructionSize(cursor)
    need(type(size)=='number' and size&gt;=1 and size&lt;=15 and cursor+size&lt;=limit,
      'Hook range ends inside an instruction.','フック範囲が命令の途中で終わっています。')
    cursor=cursor+size
  end
  local assembly=type(h.aa)=='function' and h.aa() or h.aa
  need(type(assembly)=='string' and assembly:find('[ENABLE]',1,true) and assembly:find('[DISABLE]',1,true),
    'Hook AA needs ENABLE and DISABLE.','AAの有効化・解除処理が必要です。')
  local script=assembly:gsub('%$SITE',hex(site)):gsub('%$ORIG','db '..db(original)):gsub('%$NOP',h.len&gt;5 and 'nop '..(h.len-5) or '')
  script=script:gsub('%[ENABLE%]','[ENABLE]\nassert('..hex(site)..','..db(original)..')',1)
  local cave,entry
  if not h.inline then
    script=script:gsub('alloc%(([%w_]+),4096,',function(symbol)
      cave=symbol
      return 'alloc('..symbol..',$'..hex(HOOK_MARKER_OFFSET+HOOK_MARKER_TAIL)..','
    end,1)
    need(cave,'Hook cave is unavailable.','フック領域が見つかりません。')
    local start,finish=script:find('\n'..hex(site)..':\n',1,true)
    local disable=script:find('[DISABLE]',1,true)
    need(start and disable and finish&lt;disable,'Hook entry is unavailable.','フックの入口が見つかりません。')
    entry=script:sub(finish+1,disable-1)
    local resume=entry:match('\n([%w_]+):\n$')
    if resume then
      entry=entry:sub(1,#entry-#resume-2)
    end
    script=script:sub(1,start)..script:sub(disable)
    if resume then
      local replaced
      script,replaced=script:gsub('label%('..resume..'%)','define('..resume..','..hex(limit)..')',1)
      need(replaced==1,'Hook return label is unavailable.','フックの戻り先を確認できません。')
    end
    script=script:gsub('(alloc%('..cave..',[^\n]+%)\n)','%1registersymbol('..cave..')\n',1)
    script=script:gsub('%[DISABLE%]','[DISABLE]\nunregistersymbol('..cave..')',1)
  end
  local assembled,ok,info=pcall(autoAssemble,script)
  if assembled and ok and cave then
    local published,reason=pcall(function()
      local address=need(getAddressSafe(cave),'Hook allocation is unavailable.','フック領域を取得できません。')
      DQB2.writeHookMarker(site,original,address)
      local publish='assert('..hex(site)..','..db(original)..')\n'..hex(site)..':\n'..entry
      need(autoAssemble(publish),'Hook entry installation failed.','フックの入口を設置できませんでした。')
    end)
    if not published then
      local current=bytes(site,h.len)
      if equal(current,original) then
        need(autoAssemble(script,info),'Hook allocation cleanup failed.','フック領域の後始末に失敗しました。')
      elseif hookJumpTarget(site,current)==getAddressSafe(cave) then
        DQB2.hooks[name]={addr=site,orig=original,patch=current,script=script,info=info,pid=DQB2.pid}
      end
      error(reason,0)
    end
  end
  local patched=bytes(site,h.len)
  if not assembled or not ok or not patched or equal(original,patched) then
    local state={addr=site,orig=original,pid=DQB2.pid,info=assembled and info or nil,
      failedInstall=true,cleanup=h.cleanupFailedInstall,
      resourceCleanup=h.failedInstallResourceAA, allocationConfirmed=assembled and ok==true}
    DQB2.hooks[name]=state
    local cleaned,reason=pcall(DQB2.hookOff,name)
    if not cleaned then DQB2.status[name]=tostring(reason) end
    DQB2.err('Hook installation could not be verified.','フックの設置を確認できませんでした。')
  end
  DQB2.hooks[name]={addr=site,orig=original,patch=patched,script=script,info=info,pid=DQB2.pid}
  need(patched and not equal(original,patched),'Hook bytes were not changed.','フックの書き込みを確認できません。')
  DQB2.A[h.sig]=nil
  return true
end
function DQB2.hookOff(name)
  local st=DQB2.hooks[name]; if not st then return end
  DQB2.require()
  need(st.pid==DQB2.pid,'Hook belongs to another process.','別プロセスのフックです。')
  if st.failedInstall then
    if not st.resourceCleanupComplete then
      if st.cleanup then
        checkedCall(st.cleanup,st)
      else
        need(st.allocationConfirmed and type(st.info)=='table' and type(st.resourceCleanup)=='string',
          'Failed installation requires verified cleanup.','設置失敗後の復元と資源の照合が必要です。')
        need(equal(bytes(st.addr,#st.orig),st.orig),
          'Cannot release hook resources while entry bytes differ.','入口の命令が異なるためフック領域を解放できません。')
        need(autoAssemble(st.resourceCleanup,st.info),
          'Hook resource cleanup failed.','フック領域の後始末に失敗しました。')
      end
      st.resourceCleanupComplete=true
    end
    need(equal(bytes(st.addr,#st.orig),st.orig),
      'Failed installation left unverified instructions.','設置失敗後の命令を照合できません。')
    DQB2.hooks[name]=nil
    return
  end
  need(DQB2.HOOKS[name].quiesce(st)==true,'Hook execution has not drained.','フックの実行完了を確認できません。')
  local now=bytes(st.addr,#st.orig)
  need(equal(now,st.patch) or equal(now,st.orig),
    'Code ownership changed; restore was stopped.','コードの所有状態が変化したため復元を停止しました。')
  need(autoAssemble(st.script,st.info),'Hook restoration failed; state retained.','フック復元に失敗しました。状態を保持します。')
  need(equal(bytes(st.addr,#st.orig),st.orig),'Restored bytes do not match.','復元したバイトが一致しません。')
  DQB2.hooks[name]=nil
end

local function usedHook(name)
  for key in pairs(DQB2.active) do for _,h in ipairs(DQB2.F[key].hooks or {}) do if h==name then return true end end end
  return false
end
function DQB2.feature(key,on)
  DQB2.require()
  local f=need(DQB2.F[key],'Feature is not configured.','機能が設定されていません。')
  if on then
    if DQB2.active[key] then return end
    if f.available then need(f.available()==true,'Feature unavailable for this binary.','このバイナリでは利用できません。') end
    local boundary=DQB2.featureBoundary(f)
    if f.prepare then checkedCall(f.prepare) end
    local added={}; DQB2.active[key]={boundary=boundary,starting=true}
    local ok,e=pcall(function()
      for _,h in ipairs(f.hooks or {}) do
        if not DQB2.hooks[h] then added[#added+1]=h; DQB2.hookOn(h) end
      end
      need(DQB2.featureBoundary(f)==boundary,'Game data changed.','ゲームデータが変化しました。')
      if f.on then checkedCall(f.on) end
      DQB2.active[key].starting=nil
    end)
    if not ok then
      local clean,ce=pcall(function() if f.off then checkedCall(f.off) end end)
      if clean then
        DQB2.active[key]=nil
        for i=#added,1,-1 do if not usedHook(added[i]) then local restored,re=pcall(DQB2.hookOff,added[i]); if not restored then clean=false; ce=re end end end
      end
      if not clean then DQB2.active[key]={boundary=boundary,cleanup=true}; error(tostring(e)..' / '..tostring(ce),0) end
      error(e,0)
    end
  else
    if not DQB2.active[key] then return end
    DQB2.active[key].cleanup=true
    if f.off then checkedCall(f.off) end
    local previous=DQB2.active[key]; DQB2.active[key]=nil
    local ok,e=pcall(function()
      local hooks=f.hooks or {}
      for i=#hooks,1,-1 do
        local h=hooks[i]
        if not usedHook(h) then DQB2.hookOff(h) end
      end
    end)
    if not ok then previous.cleanup=true; DQB2.active[key]=previous; error(e,0) end
  end
end
function DQB2.toggleRecord(mr,key,on)
  if DQB2.disarming then return end
  if not on and not DQB2.active[key] then return end
  local ok=DQB2.userRun(function() DQB2.feature(key,on) end)
  if on and not ok then DQB2.defer(function() if mr then mr.Active=false end end) end
end
function DQB2.mirrorBase()
  DQB2.require()
  if not DQB2.uiBase then
    local address=allocateMemory(0x10000)
    need(type(address)=='number' and address&gt;0,'Cannot allocate editor mirrors.','編集用メモリを確保できません。')
    DQB2.uiBase=address
    DQB2.slots={}
  end
  return DQB2.uiBase
end
function DQB2.allocSlot()
  local b=DQB2.mirrorBase()
  for i=0,127 do if not DQB2.slots[i] then DQB2.slots[i]=true; return i,b+i*512 end end
  DQB2.err('Too many editor rows; close another editor.','編集行が多すぎます。ほかのエディタを閉じてください。')
end
function DQB2.checkContext(session)
  DQB2.require()
  need(session.epoch==DQB2.epoch and session.pid==DQB2.pid and DQB2.captureBoundary()==session.boundary,
    'Game context changed. Reopen the editor.','ゲームの状態が変わりました。エディタを開き直してください。')
  local definition=DQB2.EDITORS[session.key]
  local ctx=definition.context(session.id)
  need(ctx and ctx.identity~=nil and ctx.identity==session.identity,
    'Target identity changed. Reopen the editor.','対象の実体が変わりました。エディタを開き直してください。')
  return ctx
end
function DQB2.normalized(field,value,reading)
  if field.kind=='string' then
    value=tostring(value)
    need(not value:find('\0',1,true) and #value&lt;=(field.maxLength or 120),
      'Text is too long or contains NUL.','文字列が長すぎるか、NULを含んでいます。')
  else
    value=tonumber(value)
    need(value and value==value and math.abs(value)&lt;math.huge,
      'Enter a finite number.','有限の数値を入力してください。')
    need(math.abs(value)&lt;=9007199254740991,'Value exceeds exact numeric range.','数値の正確な表現範囲を超えています。')
    local strict=reading or field.strict or field.choices
    if field.kind=='integer' then
      if strict then need(value%1==0,'Enter an integer.','整数を入力してください。')
      else value=math.floor(value) end
    end
    if strict then
      need((not field.min or value&gt;=field.min) and (not field.max or value&lt;=field.max),
        'Value is out of range.','入力値が範囲外です。')
    else
      if field.min then value=math.max(field.min,value) end
      if field.max then value=math.min(field.max,value) end
    end
  end
  if field.choices then
    local found=false for _,r in ipairs(field.choices) do if r.value==value then found=true end end
    need(found,'Select a listed value.','一覧の値を選択してください。')
  end
  return value
end
function DQB2.paintMirror(info,value)
  DQB2.require()
  info.painting=true
  local ok,e=pcall(function()
    if info.field.kind=='string' then need(writeString(info.address,tostring(value)..'\0',true), 'Mirror write failed.','表示値を更新できません。')
    else need(writeDouble(info.address,value),'Mirror write failed.','表示値を更新できません。') end
    info.last=value
  end)
  info.painting=false; if not ok then error(e,0) end
end
function DQB2.commit(info,value,before)
  local s=info.session
  need(DQB2.sessions[s.parent.ID]==s and s.rows[info.mr.ID]==info,
    'Editor was closed.','エディタは閉じられています。')
  local ctx=DQB2.checkContext(s); value=DQB2.normalized(info.field,value)
  need(info.field.read(ctx)==before,'Value changed in the game; refresh first.','ゲーム内で値が変化しました。再取得してください。')
  need(type(info.field.write)=='function','This field is read-only.','この項目は読み取り専用です。')
  need(info.field.write(ctx,value)==true,'Game rejected the edit.','ゲーム側の変更処理に失敗しました。')
  local fresh=DQB2.checkContext(s)
  need(info.field.read(fresh)==value,'Readback differs; refresh before another edit.','変更結果が一致しません。再取得してください。')
  DQB2.history[#DQB2.history+1]={session=s,field=info.field,before=before,after=value}
  if #DQB2.history&gt;32 then table.remove(DQB2.history,1) end
  DQB2.paintMirror(info,value)
end
function DQB2.applyEdit(info,newValue)
  if info.painting then return end
  local ok,reason=pcall(DQB2.commit,info,newValue,info.last)
  if not ok then
    DQB2.msg(tostring(reason),tostring(reason))
    pcall(DQB2.paintMirror,info,info.last)
  end
end
function DQB2.undoLast()
  local h=DQB2.history[#DQB2.history]; if not h then return end
  local ctx=DQB2.checkContext(h.session)
  need(h.field.read(ctx)==h.after,'Value changed; undo cancelled.','値が変化したため元に戻せません。')
  need(h.field.write(ctx,h.before)==true,'Undo was rejected.','変更を戻せませんでした。')
  need(h.field.read(DQB2.checkContext(h.session))==h.before,'Undo readback differs.','元に戻した値が一致しません。')
  table.remove(DQB2.history)
end

function DQB2.track(m,en,ja)
  m.DontSave=true; DQB2.dynamic[m.ID]={mr=m,en=en,ja=ja}; return m
end
function DQB2.addHdr(parent,en,ja)
  local m=getAddressList().createMemoryRecord(); m.IsGroupHeader=true
  m.Description=DQB2.T(en,ja); m.Color=DQB2.C_GROUP; m.Options='[moManualExpandCollapse]'
  m.appendToEntry(parent); m.Collapsed=true; return DQB2.track(m,en,ja)
end
function DQB2.addAction(parent,en,ja,body)
  local m=getAddressList().createMemoryRecord()
  m.Description=DQB2.T(en,ja); m.Color=DQB2.C_SCRIPT; m.Type=vtAutoAssembler
  m.Script='[ENABLE]\n{$lua}\nif syntaxcheck then return end\nDQB2.oneShot(memrec,function() '..body..' end)\n{$asm}\n[DISABLE]'
  m.appendToEntry(parent); return DQB2.track(m,en,ja)
end
function DQB2.clearChildren(parent)
  while parent.Count&gt;0 do
    local m=parent.Child[0]; DQB2.clearChildren(m)
    local d=DQB2.dynamic[m.ID]
    if d and d.inventoryQuantity then m.OnValueChangedByUser=nil end
    if d and d.info then
      if DQB2.slots then DQB2.slots[d.info.slot]=nil end
      d.info.mr.OnValueChangedByUser=nil
    end
    DQB2.dynamic[m.ID]=nil; m.Active=false; m.destroy()
  end
end
function DQB2.closeEditor(parent)
  local s=DQB2.sessions[parent.ID]
  if s then
    DQB2.sessions[parent.ID]=nil
  end
  DQB2.clearChildren(parent)
  if s and s.inventoryMirror and DQB2.alive() then
    need(deAlloc(s.inventoryMirror),'Cannot free quantity editor memory.','個数編集用メモリを解放できません。')
  end
  local names=DQB2.NAMES[parent.ID]; if names then parent.Description=DQB2.T(names[1],names[2]) end
end
function DQB2.selectEditor(parent,key)
  DQB2.require()
  local d=need(DQB2.EDITORS[key],'Editor is not configured.','エディタが設定されていません。')
  local boundary=DQB2.captureBoundary()
  local rows=d.rows()
  need(type(rows)=='table' and #rows&gt;0,'No editable targets.','編集対象がありません。')
  local function select(target)
    need(DQB2.captureBoundary()==boundary,'Game data changed while choosing.','選択中にゲームデータが変化しました。')
    return DQB2.openEditorTarget(parent,key,target,target.identity)
  end
  if #rows==1 then return select(rows[1]) end
  for i=parent.Count-1,0,-1 do
    local child=parent.Child[i]
    if DQB2.dynamic[child.ID] and DQB2.dynamic[child.ID].selector then
      DQB2.clearChildren(child); DQB2.dynamic[child.ID]=nil; child.destroy()
    end
  end
  local group=DQB2.addHdr(parent,'Select target','対象を選択')
  DQB2.dynamic[group.ID].selector=true
  DQB2.choose(group,rows,false,select)
  parent.Collapsed=false
  return true
end
function DQB2.openEditorTarget(parent,key,chosen,expectedIdentity)
  DQB2.require()
  local d=DQB2.EDITORS[key]
  local boundary=DQB2.captureBoundary()
  local ctx=need(d.context(chosen.id),'Target is unavailable.','対象を取得できません。')
  need(expectedIdentity==nil or ctx.identity==expectedIdentity,
    'Target changed. Refresh the list.','対象が変わりました。一覧を更新してください。')
  need(ctx.identity~=nil,'Editor identity contract is missing.','対象の同一性確認が未実装です。')
  DQB2.closeEditor(parent)
  local session={key=key,id=chosen.id,identity=ctx.identity,boundary=boundary,
    epoch=DQB2.epoch,pid=DQB2.pid,parent=parent,rows={}}
  DQB2.sessions[parent.ID]=session
  local ok,e=pcall(function()
    session.label={chosen.en or chosen.name,chosen.ja or chosen.name}
    if d.runtimeNames then
      DQB2.addHdr(parent,session.label[1],session.label[2])
    else
      parent.Description=DQB2.T(d.en,d.ja)..' : '..DQB2.T(session.label[1],session.label[2])
    end
    DQB2.addAction(parent,'Change target...','対象を変更...',('DQB2.selectEditor(getAddressList().getMemoryRecordByID(%d),%q)'):format(parent.ID,key))
    DQB2.addAction(parent,'Refresh values','値を再取得','DQB2.refreshEditors()')
    if DQB2.CONFIG.editorUndo then DQB2.addAction(parent,'Undo last edit','直前の変更を戻す','DQB2.undoLast()') end
    for _,field in ipairs(d.fields) do
      if not field.available or field.available(ctx)==true then
        local value=DQB2.normalized(field,field.read(DQB2.checkContext(session)),true)
        local slot,address=DQB2.allocSlot()
        local m=getAddressList().createMemoryRecord()
        local info={mr=m,session=session,field=field,slot=slot,address=address}
        m.Description=DQB2.T(field.en,field.ja); m.Address=hex(address)
        if field.kind=='string' then
          need((field.maxLength or 120)&lt;=120,'Mirror text limit is 120 UTF-8 bytes.','表示文字列の上限はUTF-8で120バイトです。')
          m.Type=vtString; m.String.Size=field.maxLength or 120; m.String.Unicode=true
        else m.Type=vtDouble end
        m.appendToEntry(parent); DQB2.track(m,field.en,field.ja).DontSave=true
        DQB2.dynamic[m.ID].info=info; session.rows[m.ID]=info
        DQB2.paintMirror(info,value)
        DQB2.applyChoices(info)
        m.OnActivate=function(_,before) return not before end
        m.OnValueChangedByUser=function(_,old,new)
          DQB2.applyEdit(info,field.kind=='string' and new or readDouble(address))
        end
      end
    end
    parent.Collapsed=false
  end)
  if not ok then DQB2.closeEditor(parent); error(e,0) end
  return true
end
function DQB2.openEditor(parent,key)
  if DQB2.sessions[parent.ID] then return end
  DQB2.defer(function()
    if not parent.Active then return end
    local ok,result=DQB2.userRun(function() return DQB2.selectEditor(parent,key) end)
    if not ok or result==false then parent.Active=false end
  end)
end
function DQB2.refreshEditors(identityOnly)
  local stale={}
  for _,s in pairs(DQB2.sessions) do
    local ok,e=pcall(function()
      if s.inventoryMirror then
        need(DQB2.captureBoundary()==s.boundary,'Inventory changed. Reopen the editor.','所持品の状態が変わりました。エディタを開き直してください。')
        return
      end
      local ctx=DQB2.checkContext(s)
      for _,info in pairs(s.rows) do
        if not identityOnly then DQB2.paintMirror(info,DQB2.normalized(info.field,info.field.read(ctx),true)) end
      end
    end)
    if not ok then stale[#stale+1]={session=s,error=e} end
  end
  for _,v in ipairs(stale) do
    DQB2.closeEditor(v.session.parent); v.session.parent.Active=false
    DQB2.msg(tostring(v.error),tostring(v.error))
  end
end
function DQB2.applyChoices(info)
  if not info.field.choices then return end
  local lines={}
  for _,v in ipairs(info.field.choices) do lines[#lines+1]=tostring(v.value)..':'..DQB2.T(v.en,v.ja) end
  local m=info.mr; m.DropDownList.Text=table.concat(lines,'\n')
  m.DropDownReadOnly=true; m.DropDownDescriptionOnly=true; m.DisplayAsDropDownListItem=true
end

local function inlineAction(parent,en,ja,callback)
  local row=DQB2.addAction(parent,en,ja,'')
  row.Script=('[ENABLE]\n{$lua}\nif syntaxcheck then return end\nDQB2.oneShot(memrec,function() DQB2.runInline(%d) end)\n{$asm}\n[DISABLE]'):format(row.ID)
  DQB2.dynamic[row.ID].callback=callback
  return row
end
function DQB2.runInline(id)
  local entry=DQB2.dynamic[id]
  if entry and entry.callback then entry.callback() end
end
local function validateRows(rows,known)
  for _,row in ipairs(rows) do
    need((type(row.id)=='number' or type(row.id)=='string') and not known[row.id],
      'Selection IDs must be stable and unique.','選択IDは安定した一意の値にしてください。')
    known[row.id]=true
  end
end
function DQB2.choose(parent,rows,multiple,accept)
  validateRows(rows,{})
  DQB2.clearChildren(parent)
  local selected={}
  for _,row in ipairs(rows) do
    local en,ja=row.en or row.name,row.ja or row.name or row.en
    local entry
    entry=inlineAction(parent,en,ja,function()
      if not multiple then return accept(row) end
      selected[row.id]=not selected[row.id] or nil
      entry.Description=(selected[row.id] and '+ ' or '')..DQB2.T(en,ja)
    end)
  end
  if multiple then
    inlineAction(parent,'Apply selection','選択を確定',function()
      local result={}
      for _,row in ipairs(rows) do if selected[row.id] then result[#result+1]=row end end
      need(#result&gt;0,'Select at least one entry.','項目を1件以上選択してください。')
      accept(result)
    end)
  end
  parent.Collapsed=false
end
function DQB2.applyLang()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i); local names=DQB2.NAMES[m.ID]
    if names and not DQB2.sessions[m.ID] then m.Description=DQB2.T(names[1],names[2]) end
  end
  for _,d in pairs(DQB2.dynamic) do d.mr.Description=DQB2.T(d.en,d.ja); if d.info then DQB2.applyChoices(d.info) end end
  for _,s in pairs(DQB2.sessions) do
    local d=DQB2.EDITORS[s.key]
    if d then
      local label=DQB2.T(d.en,d.ja)
      if not d.runtimeNames then label=label..' : '..DQB2.T(s.label[1],s.label[2]) end
      s.parent.Description=label
    end
  end
end
function DQB2.setLang(lang) need(lang=='en' or lang=='ja','Invalid language.','言語設定が不正です。'); DQB2.lang=lang; DQB2.applyLang() end
function DQB2.initCollapse()
  local al=getAddressList()
  for i=0,al.Count-1 do
    local m=al.getMemoryRecord(i)
    if m.Count&gt;0 then
      local p=m; local settings=false
      while p do if p.ID==2 then settings=true break end p=p.Parent end
      m.Collapsed=not settings
    end
  end
end

function DQB2.disableAll()
  DQB2.closeItemPicker()
  DQB2.require(); DQB2.cancelDeferred()
  if DQB2.pendingGrant then DQB2.recoverGrant() end
  local errors={}; local keys={}
  for key in pairs(DQB2.active) do keys[#keys+1]=key end
  for _,key in ipairs(keys) do local ok,e=pcall(DQB2.feature,key,false); if not ok then errors[#errors+1]=tostring(e) end end
  local orphan={}
  for h in pairs(DQB2.hooks) do
    if not usedHook(h) and h~='enemyXp' and h~='moveSpeed' then orphan[#orphan+1]=h end
  end
  for _,h in ipairs({'enemyXp','moveSpeed'}) do
    if DQB2.hooks[h] and not usedHook(h) then orphan[#orphan+1]=h end
  end
  for _,h in ipairs(orphan) do
    local ok,e=pcall(DQB2.hookOff,h)
    if not ok then errors[#errors+1]=tostring(e) end
  end
  local parents={} for _,s in pairs(DQB2.sessions) do parents[#parents+1]=s.parent end
  for _,p in ipairs(parents) do DQB2.closeEditor(p) end
  need(#errors==0,table.concat(errors,'\n'),table.concat(errors,'\n'))
  DQB2.disarming=true
  local ok,e=pcall(function()
    local al=getAddressList()
    for i=al.Count-1,0,-1 do local m=al.getMemoryRecord(i); if m.ID&gt;=100 and m.Active then m.Active=false end end
  end)
  DQB2.disarming=false; if not ok then error(e,0) end
  DQB2.history={}; DQB2.msg('All features are OFF.','全機能を解除しました。')
end

function DQB2.stopTimer()
  if DQB2.timer then DQB2.timer.Enabled=false; DQB2.timer.destroy(); DQB2.timer=nil end
end
function DQB2.tick()
  if not DQB2.pid then return end
  if not DQB2.alive() then
    DQB2.closeItemPicker()
    DQB2.cancelDeferred()
    DQB2.stopTimer()
    local parents={} for _,s in pairs(DQB2.sessions) do parents[#parents+1]=s.parent end
    for _,p in ipairs(parents) do DQB2.closeEditor(p) end
    DQB2.msg('Process changed/exited. Automatic work stopped. Select the original process to restore.',
      'プロセスが変化／終了しました。自動処理を停止しました。復元時は元のプロセスを選択してください。')
    return
  end
  local keys={} for k in pairs(DQB2.active) do keys[#keys+1]=k end
  for _,key in ipairs(keys) do
    local st,f=DQB2.active[key],DQB2.F[key]
    if not st.cleanup and (f.boundary~=false or f.task) then
      local ok,e=pcall(function()
        need(DQB2.featureBoundary(f)==st.boundary,'World/save context changed.','ワールド／プレイ状態が変化しました。')
        if f.task then checkedCall(f.task) end
      end)
      if not ok then
        local clean,ce=pcall(DQB2.feature,key,false)
        if not clean and DQB2.active[key] then DQB2.active[key].cleanup=true end
        DQB2.msg(tostring(e)..(clean and '' or ' / '..tostring(ce)),tostring(e)..(clean and '' or ' / '..tostring(ce)))
      end
    end
  end
  DQB2.refreshEditors(not DQB2.CONFIG.editorAutoRefresh)
end
function DQB2.startTimer()
  DQB2.stopTimer(); local t=createTimer(nil,false); DQB2.timer=t; t.Interval=DQB2.CONFIG.tick
  t.OnTimer=function()
    if DQB2.inTick then return end
    DQB2.inTick=true; local ok,e=pcall(DQB2.tick); DQB2.inTick=false
    if not ok then DQB2.stopTimer(); DQB2.msg(tostring(e),tostring(e)) end
  end
  t.Enabled=true
end

function DQB2.forgetProcess()
  DQB2.closeItemPicker()
  local addressList=getAddressList()
  for _,id in ipairs({8001,8002}) do
    local record=addressList.getMemoryRecordByID(id)
    if record then record.Active=false;DQB2.clearChildren(record) end
  end
  DQB2.stopTimer(); DQB2.cancelDeferred()
  local parents={} for _,s in pairs(DQB2.sessions) do parents[#parents+1]=s.parent end
  for _,p in ipairs(parents) do DQB2.closeEditor(p) end
  if DQB2.lifeHandle then executeCodeLocalEx('kernel32.CloseHandle',DQB2.lifeHandle) end
  DQB2.pendingGrant=nil
  DQB2.recoveryFailed=nil
  DQB2.lifeHandle=nil; DQB2.pid=nil; DQB2.modules=nil; DQB2.uiBase=nil; DQB2.slots=nil
  DQB2.active,DQB2.hooks,DQB2.A,DQB2.status,DQB2.history={},{},{},{},{}
  DQB2.epoch=DQB2.epoch+1
end
function DQB2.shutdown()
  if DQB2.pid then
    if DQB2.alive() then
      if not DQB2.recoveryFailed then DQB2.disableAll() end
      if DQB2.uiBase then
        need(deAlloc(DQB2.uiBase),'Cannot free editor mirrors.','編集用メモリを解放できません。')
        DQB2.uiBase,DQB2.slots=nil,nil
      end
    else
      local exited=false
      if DQB2.lifeHandle then
        local ok,r=pcall(executeCodeLocalEx,'kernel32.WaitForSingleObject',DQB2.lifeHandle,0); exited=ok and r==0
      end
      need(exited,'Select the original process and restore before reloading this table.',
        'テーブル再読込前に元のプロセスを選択して解除してください。')
    end
  end
  DQB2.forgetProcess()
end

function DQB2.luaEngine(on)
  local form=getLuaEngine(); if on then form.show() else form.hide() end
end
function DQB2.envReport()
  DQB2.msg('Template '..DQB2.VERSION..' / '..DQB2.CHEATVER,'テンプレート '..DQB2.VERSION..' / '..DQB2.CHEATVER)
  DQB2.msg('PID: '..tostring(DQB2.pid)..' / opened: '..tostring(getOpenedProcessID()),
    'PID: '..tostring(DQB2.pid)..' / 接続先: '..tostring(getOpenedProcessID()))
  if DQB2.pid and DQB2.alive() then
    for _,m in ipairs(enumModules(DQB2.pid)) do
      local ok,p=pcall(DQB2.pe,m)
      if ok then print(('%s base=%X size=%X machine=%X PE-id=%X'):format(m.Name,m.Address,p.size,p.machine,p.ts)) end
    end
  end
end
function DQB2.scanSelfTest()
  DQB2.require()
  local names={} for n in pairs(DQB2.SIGS) do names[#names+1]=n end table.sort(names)
  if #names==0 then DQB2.msg('No game resolvers are configured.','ゲーム用の解決器は未設定です。'); return end
  for _,n in ipairs(names) do
    local hooked=false
    for key in pairs(DQB2.hooks) do if DQB2.HOOKS[key].sig==n then hooked=true end end
    if hooked then DQB2.msg(n..': disable owning hooks before scanning.',n..': 該当フックを解除してから確認してください。')
    else local ok,v,e=pcall(DQB2.resolveSig,n,true); print(n..': '..(ok and (v and 'OK' or tostring(e)) or tostring(v))) end
  end
end
function DQB2.statusReport()
  local n=0 for _ in pairs(DQB2.active) do n=n+1 end
  local h=0 for _ in pairs(DQB2.hooks) do h=h+1 end
  DQB2.msg(('Features: %d / Hooks: %d'):format(n,h),('有効機能: %d / フック: %d'):format(n,h))
  for name,value in pairs(DQB2.status) do print(name..': '..value) end
end

DQB2.NAMES = {
  [132] = {"Multiplier","倍率"},
  [131] = {"Enemy XP multiplier","敵XP取得倍率"},
  [133] = {"Enemy item drop rate multiplier","敵アイテムドロップ率倍率"},
  [134] = {"Multiplier","倍率"},
  [130] = {"Multipliers","倍率操作"},
  [605] = {"Steam hotkey fix","Steamホットキー修正"},
  [606] = {"Release mouse cursor","マウスカーソルの制限解除"},
  [604] = {"Unlock all Steam achievements","Steam実績全解除"},
  [408] = {"Ignore crafting material requirements","クラフト素材要件無視"},
  [409] = {"Items are not consumed (use / crafting)","アイテム減らない（使用・クラフト）"},
  [120] = {"Infinite HP","HP無限"},
  [122] = {"Maximize hunger","満腹度MAX"},
  [121] = {"Infinite stamina","スタミナ無限"},
  [1] = {"[ATTACH / ALL OFF] Select and verify game","【アタッチ／一括解除】ゲームを選択・確認"},
  [2] = {"0. Settings","0. 設定"},
  [3] = {"Language / 言語設定","言語設定 / Language"},
  [4] = {"English (initial / default)","English（初期表示・既定）"},
  [5] = {"Japanese / 日本語","日本語（切替）"},
  [6] = {"README","はじめに"},
  [7] = {"DRAGON QUEST BUILDERS 2 1.7.3d / KTGL 2.5.6 (DX11 x64)","ドラゴンクエストビルダーズ２ 1.7.3d / KTGL 2.5.6 (DX11 x64)"},
  [12] = {"Diagnostics","診断"},
  [13] = {"Lua Engine (ON = show / OFF = hide)","Lua Engine（ONで開く／OFFで閉じる）"},
  [14] = {"Validate requested resolvers (read only)","解決器を確認（読み取り）"},
  [15] = {"Environment / connection info","環境・接続情報"},
  [16] = {"Feature / resolver status","機能・解決状態"},
  [119] = {"Invincibility","無敵"},
  [126] = {"Always critical hit","必ずクリティカル"},
  [124] = {"One-hit kill","一撃必殺"},
  [125] = {"Stealth mode","ステルスモード"},
  [100] = {"01. Gameplay","01. 便利機能"},
  [211] = {"Player movement speed","プレイヤー移動速度"},
  [212] = {"Multiplier","倍率"},
  [214] = {"Jump multiplier","ジャンプ倍率"},
  [215] = {"Multiplier","倍率"},
  [127] = {"Stop enemy AI","敵AI停止"},
  [213] = {"Rise while holding Jump","ジャンプ長押しで浮上"},
  [210] = {"Player editor","プレイヤーエディタ"},
  [200] = {"02. Player","02. プレイヤー"},
  [311] = {"Member editor","メンバーエディタ"},
  [312] = {"Add resident","住人追加"},
  [300] = {"03. Members","03. メンバー"},
  [407] = {"Instant cooking","インスタント調理"},
  [410] = {"Edit item quantities","アイテム個数変更"},
  [411] = {"Add items by category","カテゴリ別アイテム追加"},
  [412] = {"Hammer range multiplier","ハンマー範囲拡大"},
  [413] = {"Side to side","左右"},
  [414] = {"Height","高さ"},
  [415] = {"Depth","奥行き"},
  [420] = {"Recipes and Builderpedia","レシピ・図鑑"},
  [421] = {"Obtain all Builder's tools","ビルダーズ道具全取得"},
  [422] = {"Unlock all recipes","レシピ全開放"},
  [424] = {"Discover all monsters","モンスター全判明"},
  [425] = {"Unlock all room recipes","部屋レシピ全開放"},
  [426] = {"Unlock all blueprints","せっけいず全開放"},
  [423] = {"Discover all items","アイテム全判明"},
  [400] = {"04. Items / crafting","04. アイテム・クラフト"},
  [502] = {"Reveal current island map","現在の島のマップ全開放"},
  [503] = {"Disable fog","霧無効"},
  [501] = {"Stop time of day","時刻停止"},
  [500] = {"05. World","05. ワールド"},
  [600] = {"06. Other","06. その他"},
  [602] = {"Restore all","一括解除"},
  [603] = {"Restore and disconnect","解除して切断"},
}
local baseline = {
  name='dqb2.exe', stamp=0x66A30246, size=0x166D000, marker=0x1111480,version=0xEEC08C,
}
local function regionalBuild(name, stamp, size, marker, version)
  return setmetatable({name=name, stamp=stamp, size=size, marker=marker, version=version}, {__index=baseline})
end
DQB2.BUILD = {
  [baseline.name] = baseline,
  ['dqb2_eu.exe'] = regionalBuild('dqb2_eu.exe', 0x66A30163, 0x169F000, 0x11408A0, 0xF1B624),
  ['dqb2_as.exe'] = regionalBuild('dqb2_as.exe', 0x66A301B6, 0x168D000, 0x112D8E0, 0xF085FC),
}
local engineMarker = '-- KTGL For DX11(x64)[' .. string.rep('\0', 6) .. '2.5.6'
DQB2.CONFIG.candidates = function(name)
  return DQB2.BUILD[name:lower()] ~= nil
end
DQB2.CONFIG.identify = function(modules, _, name, pe)
  local main = modules[1]
  local build = DQB2.BUILD[name:lower()]
  if not build or main.Name:lower() ~= build.name then return false end
  if pe.machine ~= 0x8664 or pe.size ~= build.size or pe.ts ~= build.stamp then return false end
  local actual = DQB2.readExact(pe.base + build.marker, #engineMarker)
  if not actual or string.char(table.unpack(actual))~=engineMarker then return false end
  local version=DQB2.readExact(pe.base+build.version,7)
  return version~=nil and string.char(table.unpack(version))=='1.7.3d\0'
end


local inlineRecovery={}
local baselineInlineSites={
  stamina=0x353A02,hunger=0x3538E0,hungerSet=0x33E8C0,hpSubtract=0x352712,hpFloor=0x352762,
  craftKeep=0x8FD710,craftKeepAlternate=0x7EE0DD,craftKeepAux=0x8FD650,
  craftKeepAlternateAux=0x7EE001,itemUseKeep=0x8129E8,craftCheck=0x803A1E,
  craftCheckAux=0x80381B,releaseCursor=0x15F81A,instantCooking=0x3F711E,worldTime=0x723CA6,
  heightFog=0xCD86C0,heightFogLite=0xCD8B30,heightFogFull=0xCD8FC0,
}
local function verifiedBaselineInlineSite(patch)
  local rva=baselineInlineSites[patch.key]
  if not rva then return nil end
  local site=DQB2.mainBase+rva
  local actual=bytes(site,#patch.original)
  if not equal(actual,patch.original) and not equal(actual,patch.patched) then return nil end
  local anchor=bytes(site-patch.offset,#patch.anchor)
  if not anchor then return nil end
  for i,expected in ipairs(patch.anchor) do
    if (i&lt;=patch.offset or i&gt;patch.offset+#patch.patched)
        and expected~='??' and anchor[i]~=tonumber(expected,16) then return nil end
  end
  return site
end
function DQB2.recoverInlinePatches()
  local name=DQB2.mainName:lower()
  local restored={}
  for _,patch in ipairs(inlineRecovery) do
    if DQB2.HOOKS[patch.key].inline then
      local regional=patch.regional and type(patch.regional)=='table' and patch.regional[name]
      local site=type(regional)=='number' and DQB2.mainBase+regional
      if name==baseline.name then site=verifiedBaselineInlineSite(patch) end
      if type(regional)=='table' then
        need(not equal(bytes(DQB2.mainBase+regional.site,#patch.patched),patch.patched),
          'Previous regional patch has no verified original call. Save and restart the game: '..patch.key,
          '前回の地域版パッチの元の呼び出しを確認できません。セーブしてゲームを再起動してください: '..patch.key)
      end
      if not site and (name==baseline.name or type(patch.regional)=='function') then
        local count,match=0,nil
        local deadline=getTickCount()+DQB2.CONFIG.resolveBudgetMs
        for _,section in ipairs(DQB2.mainPE.sections) do
          if section.execute then
            for _,address in ipairs(DQB2.scanPattern(patch.pattern,section.first,section.last,2,deadline)) do
              count=count+1
              match=address+patch.offset
            end
          end
        end
        need(count&lt;=1,'Previous patch is ambiguous: '..patch.key,'前回のパッチを一意に特定できません: '..patch.key)
        site=match
      end
      if site and equal(bytes(site,#patch.patched),patch.patched) then
        restorePreviousPatch(site,patch.original,patch.patched)
        restored[#restored+1]=patch.key
      end
    end
  end
  if #restored&gt;0 then
    DQB2.msg('Restored previous inline patches: '..table.concat(restored,', '),
      '前回の直接パッチを元に戻しました: '..table.concat(restored,', '))
  end
end

local legacyHooks={
  {name='invincible',site=0x2FA570,original='4c8bdc564156',padding='90',
    code='4885d20f84a1000000440fb75202664585d20f8e92000000488b05000000004885c00f8482000000488b40484885c00f8475000000450fb6da6641f7c200400f840d0000004a8b84d860110000e92d0000006641f7c200300f840d0000004a8b84d820150000e9140000006641f7c200080f84330000004a8b84d8e01800004885c00f842200000066443990b80200000f851400000049ba00000000000000004c39100f8501000000c34c8bdc564156e900000000',
    refs={{28,4,0x137E490,31,0x0},{153,8,0xE78648,0,0x0},{178,4,0x2FA576,181,0x0}}},
  {name='fallDamage',site=0x11BAC9,original='0fb7f0663be8',padding='90',
    code='0fb7f0663be89c5048b80000000000000000483903580f85060000009de9000000009de900000000',
    refs={{11,8,0xE77DC0,0,0x0},{31,4,0x11BC26,34,0x0},{37,4,0x11BACF,40,0x0}}},
  {name='critical',site=0x119EE5,original='8b5c243484c0',padding='90',
    code='415249ba00000000000000004d3914240f851500000049ba00000000000000004c39160f8502000000b001415a8b5c243484c0e900000000',
    refs={{5,8,0xE77DC0,0,0x0},{25,8,0xE78648,0,0x0},{53,4,0x119EEB,56,0x0}}},
  {name='oneHit',site=0x2F9ED0,original='488b030fb7d6',padding='90',
    code='488b030fb7d69c415285d20f8463000000807f0f000f855900000049ba00000000000000004c39d00f85460000004c8b15000000004d85d20f84360000004d8b52484d85d20f8429000000664183bac8020000000f841a00000066458b92c802000066443957020f85070000000fb7934a0e0000415a9de900000000',
    refs={{30,8,0xE78648,0,0x0},{50,4,0x137E490,53,0x0},{121,4,0x2F9ED6,124,0x0}}},
  {name='stealthSight',site=0x272800,original='4056574155',padding='',
    code='4885c90f84320000004885d20f842900000048b800000000000000004839010f851600000048b800000000000000004839020f850300000031c0c34056574155e900000000',
    refs={{21,8,0xE78648,0,0x0},{40,8,0xE77DC0,0,0x0},{66,4,0x272805,69,0x0}}},
  {name='stealthTarget',site=0x2ADC87,original='6641399dc8020000',padding='0f1f00',
    code='4584f60f851f000000415249ba00000000000000004c3916415a0f85080000004d39d2e9000000006641399dc8020000e900000000',
    refs={{14,8,0xE78648,0,0x0},{37,4,0x2ADC8F,40,0x0},{50,4,0x2ADC8F,53,0x0}}},
  {name='enemyXp',site=0x2A5D12,original='4038b0c8750600',padding='6690',
    code='528b150000000083fa010f8c0e0000000fafda0f8105000000bbffffff7f5a4038b0c8750600e900000000',
    refs={{4,4,0x2C,7,0x2A5D12},{40,4,0x2A5D19,43,0x0}}},
  {name='enemyXpDisplayReward',site=0x12D348,original='440fb77a38',padding='',
    code='440fb77a389c5248ba00000000000000008b1283fa010f8c10000000440faffa0f810600000041bfffffff7f5a9de900000000',
    refs={{10,8,0x2C,0,0x2A5D12},{48,4,0x12D34D,51,0x0}}},
  {name='enemyXpDisplayBattle',site=0x5E811E,original='440fb74238',padding='',
    code='440fb742389c5248ba00000000000000008b1283fa010f8c10000000440fafc20f810600000041b8ffffff7f5a9de900000000',
    refs={{10,8,0x2C,0,0x2A5D12},{48,4,0x5E8123,51,0x0}}},
  {name='enemyDrop',site=0x5F62DD,original='440fb77d184584f6',padding='0f1f00',
    code='440fb77d184584f666837d00010f855d00000049ba00000000000000004c395424480f854800000049ba00000000000000004c399424180100000f8530000000448b15000000004183fa010f8c1f0000004d0fafd74981fa102700000f8708000000458bfae90600000041bf102700004584f6e900000000',
    refs={{22,8,0x623266,0,0x0},{43,8,0x620794,0,0x0},{68,4,0x78,71,0x5F62DD},{117,4,0x5F62E5,120,0x0}}},
  {name='moveSpeed',site=0xB281B,original='488b5750488bc2',padding='6690',
    code='9c5048b800000000000000004839070f85220000008b050000000085c00f8e140000003d0000807f0f8309000000f3440f590500000000589d488b5750488bc2e900000000',
    refs={{5,8,0xE653E0,0,0x0},{24,4,0x48,27,0xB281B},{52,4,0x48,55,0xB281B},{66,4,0xB2822,69,0x0}}},
  {name='moveSpeedCap',site=0xB2B17,original='0f2fc87321',padding='',
    code='5048b800000000000000004839070f853500000048b800000000000000008338000f8e2200000081380000807f0f8316000000f30f5908580f2fc80f83170000000f28c1e90f000000580f2fc80f8305000000e900000000e900000000',
    refs={{4,8,0xE653E0,0,0x0},{23,8,0x48,0,0xB281B},{85,4,0xB2B1C,88,0x0},{90,4,0xB2B3D,93,0x0}}},
  {name='ladderStep',site=0x394425,original='f30f117c2424',padding='90',
    code='9c5048b800000000000000004839070f853000000080bf380b00000c0f852300000048b800000000000000008338000f8e1000000081380000807f0f8304000000f30f5938589df30f117c2424e900000000',
    refs={{5,8,0xE77DC0,0,0x0},{37,8,0x48,0,0xB281B},{79,4,0x39442B,82,0x0}}},
  {name='jumpFactor',site=0xAD980,original='4c8bdc53554881ecb8000000',padding='0f1f8000000000',
    code='9c5048b800000000000000004839010f8586000000837a14000f8f0c000000c6050000000000e970000000b00186050000000084c00f856000000048b80000000000000000488b004885c00f844a000000f680b8010000080f843d0000008b050000000085c00f8e2f0000003d0000807f0f83240000004883ec10f30f7f0424f30f104214f30f590500000000f30f114214f30f6f04244883c410589d4c8bdc53554881ecb8000000e900000000',
    refs={{5,8,0xE653E0,0,0x0},{34,4,0xB4,38,0xAD980},{48,4,0xB4,51,0xAD980},{62,8,0x13C0F20,0,0x0},{97,4,0xB0,100,0xAD980},{138,4,0xB0,141,0xAD980},{171,4,0xAD98C,174,0x0}}},
  {name='jumpHold',site=0xADF5D,original='440f28542450',padding='90',
    code='9c5048b800000000000000004839030f855a00000048b80000000000000000488b004885c00f8444000000515241504151415241534883ec20488bc8ba0300000048b80000000000000000ffd04883c42084c07410817d140000803e7d07c745140000803e415b415a415941585a59589d440f28542450e900000000',
    refs={{5,8,0xE653E0,0,0x0},{24,8,0x13C0F20,0,0x0},{68,8,0xA92500,0,0x0},{121,4,0xADF63,124,0x0}}},
}

local function legacyBytes(text)
  return (text:gsub('%x%x',function(value) return string.char(tonumber(value,16)) end))
end

function DQB2.checkLegacyCombatHooks()
  if DQB2.mainName:lower()~=baseline.name then return end
  local base=DQB2.mainBase
  local pending,targets={},{}
  for _,hook in ipairs(legacyHooks) do
    local site=base+hook.site
    local original=legacyBytes(hook.original)
    local current=need(bytes(site,#original),'Cannot read previous hook entry.','旧版フックの入口を読み取れません。')
    if string.char(table.unpack(current))~=original then
      local target=hookJumpTarget(site,current)
      need(target and (target&lt;base or target&gt;=base+baseline.size) and
          string.char(table.unpack(current,6))==legacyBytes(hook.padding),
        'Unknown code at previous hook: '..hook.name,'旧版フックの入口を確認できません: '..hook.name)
      targets[hook.site]=target
      pending[#pending+1]={hook=hook,site=site,original=original,current=current,target=target}
    end
  end
  if #pending==0 then return end
  local restored={}
  local function verify(entry)
    local hook,target=entry.hook,entry.target
    local code=legacyBytes(hook.code)
    for _,ref in ipairs(hook.refs) do
      local at,width,offset,ending,linked=table.unpack(ref)
      local owner=linked==0 and base or targets[linked]
      need(owner,'Previous hook dependency is missing: '..hook.name,'旧版フックの参照先を確認できません: '..hook.name)
      local address=owner+offset
      local data=width==8 and string.pack('&lt;I8',address) or string.pack('&lt;i4',address-target-ending)
      code=code:sub(1,at-1)..data..code:sub(at+width)
    end
    local actual=bytes(target,#code)
    need(actual and string.char(table.unpack(actual))==code,
      'Unknown previous hook code: '..hook.name,'旧版フックのコードが一致しません: '..hook.name)
    need(equal(bytes(entry.site,#entry.current),entry.current),
      'Previous hook entry changed: '..hook.name,'旧版フックの入口が変化しました: '..hook.name)
  end
  pause()
  local ok,reason=pcall(function()
    for _,entry in ipairs(pending) do verify(entry) end
    for _,entry in ipairs(pending) do
      writeBytes(entry.site,{entry.original:byte(1,-1)})
      local actual=bytes(entry.site,#entry.original)
      need(actual and string.char(table.unpack(actual))==entry.original,
        'Previous hook restoration failed: '..entry.hook.name,'旧版フックを復元できません: '..entry.hook.name)
      restored[#restored+1]=entry.hook.name
    end
  end)
  unpause()
  if not ok then error(reason,0) end
  DQB2.msg('Restored previous table hooks: '..table.concat(restored,', '),
    '旧版CTのフックを元に戻しました: '..table.concat(restored,', '))
end

local function defineConsumptionPatch(key, pattern, offset, original, replacement, regionalSites)
  local expected={}
  for value in original:gmatch('%x%x') do expected[#expected+1]=tonumber(value,16) end
  local tokens={}
  local patched={}
  for token in pattern:gmatch('%S+') do tokens[#tokens+1]=token end
  for value in replacement:gmatch('%x%x') do
    patched[#patched+1]=tonumber(value,16)
    tokens[offset+#patched]=value
  end
  inlineRecovery[#inlineRecovery+1]={key=key,pattern=table.concat(tokens,' '),offset=offset,
    original=expected,patched=patched,regional=regionalSites,anchor=tokens}
  local function matches(site)
    local name=DQB2.mainName:lower()
    local originalBytes=DQB2.readExact(site,#expected)
    if name==baseline.name then return DQB2.sameBytes(originalBytes,expected) end
    if type(regionalSites)=='function' then return regionalSites(site,originalBytes) end
    local regional=regionalSites and regionalSites[name]
    if type(regional)=='number' then
      return regional==site-DQB2.mainBase and DQB2.sameBytes(originalBytes,expected)
    end
    if not regional or regional.site~=site-DQB2.mainBase or not originalBytes or originalBytes[1]~=0xE8 then return false end
    local target=site+5+string.unpack('&lt;i4',string.char(table.unpack(originalBytes,2,5)))
    local code=DQB2.readExact(target,5)
    if code and code[1]==0xE9 then
      target=target+5+string.unpack('&lt;i4',string.char(table.unpack(code,2,5)))
    end
    return target==DQB2.mainBase+regional.target
  end
  local function knownSite()
    local name=DQB2.mainName:lower()
    local regional=type(regionalSites)=='table' and regionalSites[name]
    local rva=name==baseline.name and baselineInlineSites[key]
      or (type(regional)=='table' and regional.site or regional)
    if type(rva)~='number' then return nil end
    local site=DQB2.mainBase+rva
    if not matches(site) then return nil end
    local anchor=bytes(site-offset,#tokens)
    if not anchor then return nil end
    local i=0
    for token in pattern:gmatch('%S+') do
      i=i+1
      if token~='??' and anchor[i]~=tonumber(token,16) then return nil end
    end
    return site
  end
  DQB2.SIGS[key]={p=pattern,off=offset,validate=matches,knownSite=knownSite}
  DQB2.HOOKS[key]={
    sig=key,len=#expected,inline=true,validate=matches,quiesce=function() return true end,
    cleanupFailedInstall=function(state)
      return DQB2.sameBytes(DQB2.readExact(state.addr,#state.orig),state.orig)
    end,
    aa='[ENABLE]\n$SITE:\ndb '..replacement..'\n[DISABLE]\n$SITE:\n$ORIG',
  }
end
defineConsumptionPatch('stamina',
  '0F B7 81 D8 54 09 00 66 0F 6E C0 0F 5B C0 F3 0F 5D D8 F3 0F 11 99 D4 54 09 00 48 83 C4 38 C3',
  18,'F3 0F 11 99 D4 54 09 00','0F 1F 84 00 00 00 00 00',
  {['dqb2_eu.exe']=0x354202,['dqb2_as.exe']=0x353C82})
local function hungerStateAt(site,original)
  if not original or #original~=7 or original[1]~=0x48 or original[2]~=0x8B or original[3]~=0x05 then return nil end
  local address=site+7+string.unpack('&lt;i4',string.char(table.unpack(original,4,7)))
  for _,section in ipairs(DQB2.mainPE.sections) do
    if not section.execute and address&gt;=section.first and address+8&lt;=section.last then
      local owner=readPointer(address)
      local state=owner and owner~=0 and readPointer(owner+0x60)
      local hunger=state and state~=0 and u16(state+0x954CC)
      if hunger and hunger&lt;=10000 then return state end
      return nil
    end
  end
end
defineConsumptionPatch('hunger',
  '48 8B 05 ?? ?? ?? ?? 44 0F B7 C2 48 8B 48 60 0F B7 81 CC 54 09 00 41 3B C0 73 0A 33 C0 66 89 81 CC 54 09 00 C3 41 2B C0 3D FF FF 00 00 77 07 66 89 81 CC 54 09 00 C3',
  0,'48 8B 05 A9 AB 02 01','C3 66 0F 1F 44 00 00',
  function(site,original) return hungerStateAt(site,original)~=nil end)

defineConsumptionPatch('hungerSet',
  '81 FA FF FF 00 00 77 12 48 8B 05 ?? ?? ?? ?? 48 8B 48 60 66 89 91 CC 54 09 00 C3',
  0,'81 FA FF FF 00 00 77 12','BA 10 27 00 00 90 90 90',
  function(site,original)
    if not DQB2.sameBytes(original,{0x81,0xFA,0xFF,0xFF,0x00,0x00,0x77,0x12}) then return false end
    return hungerStateAt(site+8,bytes(site+8,7))~=nil
  end)

defineConsumptionPatch('hpSubtract',
  '44 0F B7 CA 48 8B 51 60 0F B7 82 C4 54 09 00 41 3B C1 72 0D 41 2B C1 44 8B C0 3D FF FF 00 00 77 08 66 44 89 82 C4 54 09 00 48 8B 03',
  33,'66 44 89 82 C4 54 09 00','0F 1F 84 00 00 00 00 00',
  {['dqb2_eu.exe']=0x352F12,['dqb2_as.exe']=0x352992})
defineConsumptionPatch('hpFloor',
  '48 8B 41 60 66 3B 90 C4 54 09 00 72 8F 66 89 B8 C4 54 09 00 EB AF',
  13,'66 89 B8 C4 54 09 00','0F 1F 80 00 00 00 00',
  {['dqb2_eu.exe']=0x352F62,['dqb2_as.exe']=0x3529E2})
defineConsumptionPatch('craftKeep',
  '44 8B 83 00 F8 FF FF 48 8B CD 8B 13 E8 ?? ?? ?? ?? 48 8D 5B 04 48 83 EF 01 75 E5',
  0,'44 8B 83 00 F8 FF FF','41 B8 00 00 00 00 90',
  {['dqb2_eu.exe']=0x907560,['dqb2_as.exe']=0x902E00})
defineConsumptionPatch('craftKeepAlternate',
  '8B 17 44 8B C0 49 8B CC E8 ?? ?? ?? ?? 48 8D 7F 04 48 83 ED 01 75 D4',
  8,'E8 D0 54 81 FF','0F 1F 44 00 00',
  {['dqb2_eu.exe']={site=0x7F076D,target=0xA06EB0},['dqb2_as.exe']={site=0x7EDFCD,target=0xA009E0}})
defineConsumptionPatch('craftKeepAux',
  '41 0F B7 57 12 48 8B CD 44 0F AF C0 E8 ?? ?? ?? ?? 33 F6 4D 8D 77 18',
  12,'E8 44 F7 73 FF','0F 1F 44 00 00',
  {['dqb2_eu.exe']={site=0x9074A0,target=0xA06780},['dqb2_as.exe']={site=0x902D40,target=0xA002B0}})
defineConsumptionPatch('craftKeepAlternateAux',
  '41 0F B7 57 12 44 8B C0 49 8B CC E8 ?? ?? ?? ?? 44 8B 4C 24 30 33 F6',
  11,'E8 93 ED 84 FF','0F 1F 44 00 00',
  {['dqb2_eu.exe']={site=0x7F0691,target=0xA06780},['dqb2_as.exe']={site=0x7EDEF1,target=0xA002B0}})
defineConsumptionPatch('itemUseKeep',
  'C6 44 24 28 01 41 B1 01 44 88 7C 24 20 44 0F B7 C3 41 0F B7 D4 E8 ?? ?? ?? ?? 45 84 F6 74 0E',
  21,'E8 05 38 81 FF','0F 1F 44 00 00',
  {['dqb2_eu.exe']={site=0x8159D8,target=0x353300},['dqb2_as.exe']={site=0x813118,target=0x352D80}})
DQB2.F.craftKeep={boundary=false,hooks={'craftKeep','craftKeepAlternate','craftKeepAux','craftKeepAlternateAux','itemUseKeep'}}
defineConsumptionPatch('craftCheck',
  '41 8B EE 3B EF 73 0C 45 38 77 08 0F 84 0D 02 00 00 EB 0B 80 7E 28 01',
  0,'41 8B EE 3B EF 73 0C','41 8B EE 3B EF EB 0C',
  {['dqb2_eu.exe']=0x80628E,['dqb2_as.exe']=0x803F8E})
defineConsumptionPatch('craftCheckAux',
  '44 3B DF 73 0C 45 38 77 08 0F 84 12 04 00 00 EB 02 FF 03',
  0,'44 3B DF 73 0C','44 3B DF EB 0C',
  {['dqb2_eu.exe']=0x80608B,['dqb2_as.exe']=0x803D8B})
defineConsumptionPatch('instantCooking',
  'B8 58 02 00 00 3B C8 0F 47 C8 85 C9 74 ?? 3B DF 72 0F 41 0F B7 C3 48 8B 5C 24 08 48 8B 7C 24 10 C3 8B C3 F7 F1',
  14,'3B DF 72 0F 41 0F B7 C3','3B DF 66 90 41 0F B7 C3',
  function(_, original) return DQB2.sameBytes(original,{0x3B,0xDF,0x72,0x0F,0x41,0x0F,0xB7,0xC3}) end)
DQB2.F.instantCooking={boundary=false,hooks={'instantCooking'}}


DQB2.SIGS.steamKeyboardOwner={
  p='48 89 6C 24 68 48 8B 2D ?? ?? ?? ?? 48 89 74 24 70 48 8B 35 ?? ?? ?? ?? 48 89 44 24 40 48 8B CE 49 8B 86 E0 02 00 00',
  kind='rip',off=5,disp=3,length=7,
  knownSite=function()
    if DQB2.mainName:lower()~='dqb2.exe' then return nil end
    local site=DQB2.mainBase+0x11F685
    local guard=bytes(site,12)
    if guard and equal({table.unpack(guard,1,8)},{0x48,0x89,0x6C,0x24,0x68,0x48,0x8B,0x2D}) then
      local d=s32(site+8)
      if d then return site+12+d end
    end
  end,
  validate=function(site)
    for _,section in ipairs(DQB2.mainPE.sections) do
      if not section.execute and site&gt;=section.first and site+8&lt;=section.last then return true end
    end
    return false
  end,
}
DQB2.SIGS.steamKeyboardCoop={
  p='48 8B 8F 48 0D 00 00 41 B8 05 00 00 00 48 8B D6 48 8B 01 FF 50 68 85 C0 0F 88 ?? ?? ?? ?? 48 8B 8F 48 0D 00 00',
  knownSite=function()
    if DQB2.mainName:lower()=='dqb2.exe' then
      local site=DQB2.mainBase+0xA871D7
      if DQB2.SIGS.steamKeyboardCoop.validate(site) then return site end
    end
  end,
  validate=function(site)
    return DQB2.sameBytes(DQB2.readExact(site+7,15),{0x41,0xB8,5,0,0,0,0x48,0x8B,0xD6,0x48,0x8B,1,0xFF,0x50,0x68})
  end,
}
local function steamKeyboardTarget()
  DQB2.needSig('steamKeyboardCoop')
  local global=DQB2.needSig('steamKeyboardOwner')
  local owner=readQword(global)
  local keyboard=owner and owner~=0 and readQword(owner+0x10)
  local device=keyboard and keyboard~=0 and readQword(keyboard+0xD48)
  local window=owner and owner~=0 and readQword(owner+0x48)
  need(window and window~=0 and getWindowProcessID(window)==DQB2.pid,
    'Cannot verify the game window.','ゲームのウィンドウを確認できません。')
  local vtable=device and device~=0 and readQword(device)
  need(vtable and vtable~=0,'Keyboard device is unavailable.','キーボードデバイスを取得できません。')
  local acquire,unacquire,set=readQword(vtable+0x38),readQword(vtable+0x40),readQword(vtable+0x68)
  for _,address in ipairs({acquire or 0,unacquire or 0,set or 0}) do
    local supported=false
    for _,name in ipairs({'dinput8.dll','gameoverlayrenderer64.dll'}) do
      local base=getAddressSafe(name)
      local size=base and getModuleSize(name)
      if size and address&gt;=base and address&lt;base+size then supported=true break end
    end
    need(supported,'Cannot verify the DirectInput keyboard methods.','DirectInputのキーボード処理を確認できません。')
  end
  return {device=device,window=window,acquire=acquire,unacquire=unacquire,set=set}
end
local function steamKeyboardLevel(target,level)
  executeCodeEx(0,2000,target.unacquire,target.device)
  local changed=executeCodeEx(0,2000,target.set,target.device,target.window,level)
  executeCodeEx(0,2000,target.acquire,target.device)
  need(changed==0,('SetCooperativeLevel failed: %X'):format(changed or -1),
    ('SetCooperativeLevelに失敗しました: %X'):format(changed or -1))
end
DQB2.F.steamHotkey={boundary=false,on=function()
  local target=steamKeyboardTarget()
  steamKeyboardLevel(target,6)
  DQB2.steamKeyboard=target
end,off=function()
  local previous=DQB2.steamKeyboard
  if not previous then return end
  local target=steamKeyboardTarget()
  if target.device==previous.device then steamKeyboardLevel(target,5) end
  DQB2.steamKeyboard=nil
end}

defineConsumptionPatch('releaseCursor',
  '8B 4C 24 44 03 CA 89 54 24 2C 89 4C 24 34 48 8D 4C 24 28 EB 17 33 C0 80 BC 02 C9 06 00 00 00',
  14,'48 8D 4C 24 28','B9 00 00 00 00',
  function(_, original) return equal(original,{0x48,0x8D,0x4C,0x24,0x28}) end)
DQB2.F.releaseCursor={boundary=false,hooks={'releaseCursor'},on=function()
  local released=executeCodeLocalEx('user32.ClipCursor',0)
  need(type(released)=='number' and released~=0,
    'The cursor could not be released.','カーソルの制限を解除できませんでした。')
end}

DQB2.F.hp={boundary=false,hooks={'hpSubtract','hpFloor'}}
DQB2.F.stamina={boundary=false,hooks={'stamina'}}
DQB2.F.hunger={boundary=false,hooks={'hunger','hungerSet'},on=function() DQB2.setHungerMax() end}
defineConsumptionPatch('worldTime',
  'F3 0F 58 81 C8 57 7E 00 F3 0F 11 81 C8 57 7E 00 48 8B CB F3 0F 10 53 34 F3 0F 5C D7',
  8,'F3 0F 11 81 C8 57 7E 00','0F 1F 84 00 00 00 00 00',
  {['dqb2_eu.exe']=0x725C66,['dqb2_as.exe']=0x723EA6})
DQB2.F.worldTime={boundary=false,hooks={'worldTime'}}

defineConsumptionPatch('heightFog',
  '48 89 5C 24 18 48 89 7C 24 20 55 48 8B EC 48 81 EC 80 00 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 F0 48 8B 5A 30 48 8B F9 8B 0D ?? ?? ?? ?? 4C 8B CA 41 BA 01 00 00 00 44 8B 47 28',
  0,'48 89 5C 24 18','C3 90 90 90 90',
  function(_,original) return equal(original,{0x48,0x89,0x5C,0x24,0x18}) end)
defineConsumptionPatch('heightFogLite',
  '40 55 56 57 41 54 41 55 41 56 41 57 48 8D 6C 24 D9 48 81 EC 90 00 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 17 80 79 18 00 4C 8B E9 48 8B 7A 30 74 08 48 8B CA E8 ?? ?? ?? ?? 41 8B 55 28 48 8D 05 ?? ?? ?? ?? 41 B9 02 00 00 00 48 89 44 24 20 45 33 C0 48 8B CF',
  0,'40 55 56 57 41 54','C3 90 90 90 90 90',
  function(_,original) return equal(original,{0x40,0x55,0x56,0x57,0x41,0x54}) end)
defineConsumptionPatch('heightFogFull',
  '40 55 56 57 41 54 41 55 41 56 41 57 48 8D 6C 24 D9 48 81 EC 90 00 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 17 80 79 18 00 4C 8B E9 48 8B 7A 30 74 08 48 8B CA E8 ?? ?? ?? ?? 41 8B 55 28 48 8D 05 ?? ?? ?? ?? 41 B9 03 00 00 00 48 89 44 24 20 45 33 C0 48 8B CF',
  0,'40 55 56 57 41 54','C3 90 90 90 90 90',
  function(_,original) return equal(original,{0x40,0x55,0x56,0x57,0x41,0x54}) end)
DQB2.F.disableFog={boundary=false,hooks={'heightFog','heightFogLite','heightFogFull'}}


local catalogLayouts = {
  definitions = {descriptor=0x7B0, count=4000, size=208064},
  items = {descriptor=0xF0, count=3001, fields=2, westernFields=13},
  craftCategories = {descriptor=0x120, count=65, fields=1, westernFields=3},
  itemCategories = {descriptor=0x150, count=65, fields=1, sampleKeys={5}},
  characters = {descriptor=0x1F8, count=1024, fields=1, westernFields=12},
}
local function pointed(address)
  local pointer=address and readPointer(address)
  if pointer and pointer&gt;0 then return pointer end
end
local catalogManagerSites={
  ['dqb2.exe']=0x8FD5FF,
  ['dqb2_eu.exe']=0x90744F,
  ['dqb2_as.exe']=0x902CEF,
}
local function catalogManager()
  local offset=catalogManagerSites[DQB2.mainName:lower()]
  if not offset then return nil end
  local site=DQB2.mainBase+offset
  if not equal(bytes(site,3),{0x48,0x8B,0x05}) or
      not equal(bytes(site+7,23),{0x45,0x8B,0xE8,0x44,0x8B,0xE2,0x48,0x8B,0xE9,0x4C,0x8B,0x08,
        0x4D,0x8B,0x51,0x58,0x41,0x3B,0x92,0,0x09,0,0}) then return nil end
  local displacement=s32(site+3)
  local wrapper=displacement and pointed(site+7+displacement)
  local owner=pointed(wrapper)
  return owner and pointed(owner+0x58)
end
local function catalogShape(base, layout)
  return base and base &gt; 0 and u32(base)==layout.count and u32(base+64)==0 and
    u32(base+68)==1 and u32(base+60+4*layout.count)==layout.count-1
end
local function catalogString(base, layout, key)
  if math.type(key)~='integer' or key&lt;1 or key&gt;=layout.count then return nil end
  local offsets=64+4*layout.count
  local slot=offsets+4*(layout.fields*key+(layout.displayField or 0))
  local delta=u32(base+slot)
  local start=delta and slot+delta
  if not start or start&lt;offsets+4*layout.fields*layout.count or start&gt;=layout.size then return nil end
  local value=readString(base+start, math.min(256,layout.size-start),false)
  if not value or value=='' or not utf8.len(value) then return nil end
  return (value:gsub('&lt;([^:&lt;&gt;]+):[^&lt;&gt;]+&gt;','%1'))
end
local function catalogBase(manager,layout)
  local descriptor=manager+layout.descriptor
  if u32(descriptor)~=layout.count or u32(descriptor+4)~=64 or
      u32(descriptor+8)~=64+4*layout.count or u32(descriptor+12)~=0 then return nil end
  local base=pointed(descriptor+16)
  if catalogShape(base,layout) then return base end
end
local function catalogTextLayout(base, layout)
  local stride=u32(base+64+4*layout.count)
  if stride==4*layout.count*layout.fields then
    return {descriptor=layout.descriptor,count=layout.count,fields=layout.fields}
  end
  local fields=layout.westernFields
  if fields and stride==4*layout.count*fields then
    return {descriptor=layout.descriptor,count=layout.count,fields=fields,displayField=fields-1}
  end
end
local function catalogTextSize(base,layout)
  local offset=64+4*layout.count
  local length=4*layout.count*layout.fields
  local entries=bytes(base+offset,length)
  if not entries then return nil end
  local last=offset+length
  for i=1,#entries,4 do
    local displacement=entries[i]+entries[i+1]*256+entries[i+2]*65536+entries[i+3]*16777216
    local start=offset+i-1+displacement
    if start&lt;last or start&gt;=0x200000 then return nil end
    last=start
  end
  for i=0,255 do
    local byte=readBytes(base+last+i,1)
    if byte==nil then return nil end
    if byte==0 then return last+i+1 end
  end
end
function DQB2.resolveCatalog(kinds)
  DQB2.require()
  local manager=need(catalogManager(),'Game catalog manager is unavailable.','ゲームの名前テーブルを取得できません。')
  local result={pid=DQB2.pid,epoch=DQB2.epoch,manager=manager,layouts={}}
  for _,kind in ipairs(kinds or {'definitions','items','characters'}) do
    local layout=catalogLayouts[kind]
    local base=need(catalogBase(manager,layout),'Game catalog is unavailable: '..kind,'ゲームの名前テーブルを確認できません。')
    if layout.fields then
      local sampleKeys=layout.sampleKeys or {1,2}
      layout=need(catalogTextLayout(base,layout),'Game text layout is invalid.','名前テーブルの構造が一致しません。')
      local size=need(catalogTextSize(base,layout),'Game text offsets are invalid.','名前テーブルの文字列位置を確認できません。')
      layout.size=size
      for _,key in ipairs(sampleKeys) do
        need(catalogString(base,layout,key),
          'Game text has an unexpected encoding.','名前テーブルの文字列形式を確認できません。')
      end
    end
    result[kind],result.layouts[kind]=base,layout
  end
  return result
end
local function currentCatalog(context,kind)
  if context.pid~=DQB2.pid or context.epoch~=DQB2.epoch or getOpenedProcessID()~=DQB2.pid then return nil end
  local base,layout=context[kind],context.layouts[kind]
  if catalogManager()==context.manager and pointed(context.manager+layout.descriptor+16)==base and
      catalogShape(base,layout) then return base,layout end
end
function DQB2.catalogItem(context,id)
  local base, layout=currentCatalog(context,'definitions')
  local names, nameLayout=currentCatalog(context,'items')
  if not base or not names or math.type(id)~='integer' or id&lt;1 or id&gt;=layout.count then return nil end
  if u32(base+64+4*id)~=id then return nil end
  local record=base+64+4*layout.count+48*id
  local key,category=u16(record+0x1C),u16(record+4)
  local name=key and catalogString(names,nameLayout,key)
  if name and category then return name,category,key end
end
function DQB2.catalogCharacter(context,key)
  local base,layout=currentCatalog(context,'characters')
  if base then return catalogString(base,layout,key) end
end
local originalScanSelfTest=DQB2.scanSelfTest
function DQB2.scanSelfTest()
  DQB2.require()
  if next(DQB2.SIGS) then originalScanSelfTest() end
  local context=DQB2.resolveCatalog()
  local itemCount,characterCount=0,0
  for id=1,catalogLayouts.definitions.count-1 do
    if DQB2.catalogItem(context,id) then itemCount=itemCount+1 end
  end
  for key=1,catalogLayouts.characters.count-1 do
    if DQB2.catalogCharacter(context,key) then characterCount=characterCount+1 end
  end
  DQB2.msg(('Named items: %d / character name keys: %d'):format(itemCount,characterCount),
    ('名前付きアイテム: %d件 / キャラクター名キー: %d件'):format(itemCount,characterCount))
end

local function craftCategory(context,id)
  local base,layout=currentCatalog(context,'definitions')
  if not base then return nil end
  local record=base+64+4*layout.count+48*id
  local flags,extra=u16(record+0x2C),u16(record+0x2E)
  if not flags or not extra then return nil end
  flags=(flags&gt;&gt;5) | ((extra &amp; 1)&lt;&lt;11)
  for key=1,12 do
    if (flags &amp; (1&lt;&lt;(key-1)))~=0 then return key end
  end
end
local itemCategoryLabels={
  [0]={'Uncategorized','分類なし'},
  [13]={'Decorative furniture','かざり家具'},
  [14]={'Functional furniture','機能家具'},
  [19]={'Blocks','ブロック'},
  [37]={'Crops','農作物'},
  [38]={'Special items','特殊アイテム'},
}
local function itemCategories()
  DQB2.require()
  local context=DQB2.resolveCatalog({'definitions','items'})
  local categoryNames={}
  local hasCategories,labels=pcall(DQB2.resolveCatalog,{'craftCategories'})
  if hasCategories then
    local base,layout=currentCatalog(labels,'craftCategories')
    if base then
      for key=1,12 do categoryNames[key]=catalogString(base,layout,key) end
    end
  end
  local hasItemCategories,itemLabels=pcall(DQB2.resolveCatalog,{'itemCategories'})
  if hasItemCategories then
    local base,layout=currentCatalog(itemLabels,'itemCategories')
    if base then
      for category=1,layout.count-1 do
        local name=catalogString(base,layout,category)
        if name then categoryNames[category+0x100]=name:gsub('^%[(.*)%]$','%1') end
      end
    end
  end
  local groups={}
  for id=1,catalogLayouts.definitions.count-1 do
    local name,category=DQB2.catalogItem(context,id)
    if name then
      local key=craftCategory(context,id)
      local group=key and categoryNames[key] and key or category+0x100
      local ids=groups[group] or {}
      ids[#ids+1]=id
      groups[group]=ids
    end
  end
  return context,categoryNames,groups
end
function DQB2.setHungerMax()
  DQB2.require()
  local patch=DQB2.hooks.hunger
  local state=need(patch and hungerStateAt(patch.addr,patch.orig),
    'Player state is unavailable.','プレイヤー状態を取得できません。')
  need(writeSmallInteger(state+0x954CC,10000)==true and u16(state+0x954CC)==10000,
    'Hunger write could not be verified.','満腹度の変更を確認できません。')
end

local inventoryHotbarCount=15
local inventoryBagCount=0x1A4
local function slotAddress(state,slot)
  if math.type(slot)~='integer' or slot&lt;1 or slot&gt;inventoryHotbarCount+inventoryBagCount then return nil end
  if slot&lt;=inventoryHotbarCount then return state+0xB88650+4*(slot-1) end
  return state+0xB8DF74+4*(slot-inventoryHotbarCount-1)
end
local inventorySites={
  ['dqb2.exe']={scan=0x24998F,bag=0x2BAD89},
  ['dqb2_eu.exe']={scan=0x24A0BF,bag=0x2BB549},
  ['dqb2_as.exe']={scan=0x249C0F,bag=0x2BB009},
}
local function inventoryStackTable()
  local layout=DQB2.mainName and inventorySites[DQB2.mainName:lower()]
  if not layout then return nil end
  local scan,bag=DQB2.mainBase+layout.scan,DQB2.mainBase+layout.bag
  local scanTail=bytes(scan+7,12)
  local slots=bytes(scan+0x62,20)
  local bagTail=bytes(bag+7,11)
  if not scanTail or db(scanTail)~='48 8B 9C 24 90 00 00 00 45 0F B7 D1' or
      not slots or db(slots)~='48 8D 8D 50 86 B8 00 41 8D 51 0F 0F 1F 40 00 0F B7 01 66 85' or
      not bagTail or db(bagTail)~='0F B7 C6 41 3B C7 B8 3A 16 00 00' or
      not equal(bytes(scan,3),{0x48,0x8D,0x35}) or not equal(bytes(bag,3),{0x48,0x8D,0x3D}) then return nil end
  local scanOffset,bagOffset=s32(scan+3),s32(bag+3)
  if not scanOffset or not bagOffset then return nil end
  local stack=scan+7+scanOffset
  if stack~=bag+7+bagOffset then return nil end
  for _,section in ipairs(DQB2.mainPE.sections) do
    if not section.execute and stack&gt;=section.first and stack+4000*4&lt;=section.last then return stack end
  end
end
local function isStackable(item,stack)
  stack=stack or inventoryStackTable()
  return stack and math.type(item)=='integer' and item&gt;0 and item&lt;4000 and u16(stack+4*item)==0
end
local function slotRows()
  local state=DQB2.CONFIG.boundary()
  local stack=inventoryStackTable()
  need(state and stack,'Player inventory is unavailable.','所持品を取得できません。')
  local names=DQB2.resolveCatalog({'definitions','items'})
  local rows={}
  local function appendRows(first,count)
    local batch=need(bytes(slotAddress(state,first),4*count),'Inventory read failed.','所持品を読み取れません。')
    for i=0,count-1 do
      local item=batch[4*i+1]+256*batch[4*i+2]
      local quantity=batch[4*i+3]+256*batch[4*i+4]
      if quantity&gt;0 and isStackable(item,stack) then
        local slot=first+i
        local name=DQB2.catalogItem(names,item) or ('#%d'):format(item)
        local number=slot&lt;=inventoryHotbarCount and slot or slot-inventoryHotbarCount
        local en,ja=slot&lt;=inventoryHotbarCount and 'Hotbar' or 'Bag',slot&lt;=inventoryHotbarCount and 'スロットバー' or 'ふくろ'
        rows[#rows+1]={id=slot,item=item,quantity=quantity,
          en=('%s %d  %s'):format(en,number,name),ja=('%s %d  %s'):format(ja,number,name)}
      end
    end
  end
  appendRows(1,inventoryHotbarCount)
  appendRows(inventoryHotbarCount+1,inventoryBagCount)
  return rows,state,stack
end

local function setSlotQuantity(session,row,mirror,newValue)
  local address=slotAddress(session.boundary,row.id)
  local value=tonumber(newValue)
  local ok=DQB2.userRun(function()
    need(DQB2.sessions[session.parent.ID]==session and DQB2.captureBoundary()==session.boundary
        and inventoryStackTable()==session.stack and u16(address)==row.item,
      'The slot changed. Refresh the list.','スロットの内容が変わりました。一覧を更新してください。')
    need(value and value%1==0 and value&gt;=1 and value&lt;=999,
      'Enter a quantity from 1 to 999.','個数には1から999の整数を入力してください。')
    need(writeSmallInteger(address+2,value)==true and u16(address+2)==value,
      'The quantity could not be changed.','個数を変更できませんでした。')
    row.quantity=value
  end)
  if not ok then
    local alive,boundary=pcall(DQB2.captureBoundary)
    if alive and boundary==session.boundary and u16(address)==row.item then
      row.quantity=u16(address+2) or row.quantity
    end
    writeSmallInteger(mirror,row.quantity)
  end
end

function DQB2.setHotbarQuantity(parent)
  local session=need(DQB2.sessions[parent.ID],'Refresh the list first.','先に一覧を更新してください。')
  local input=inputQuery(DQB2.T('Set hotbar quantities','指定個数一括変更'),
    DQB2.T('Quantity for all listed hotbar items (1–999)','スロットバーの一覧にある全アイテムの個数（1～999）'),'999')
  if input==nil then return end
  local value=tonumber(input)
  need(value and value%1==0 and value&gt;=1 and value&lt;=999,
    'Enter a quantity from 1 to 999.','個数には1から999の整数を入力してください。')
  need(DQB2.sessions[parent.ID]==session and DQB2.captureBoundary()==session.boundary
    and inventoryStackTable()==session.stack,'The inventory changed. Refresh the list.','所持品が変わりました。一覧を更新してください。')
  local targets={}
  for _,row in ipairs(session.rows) do
    if row.id&gt;inventoryHotbarCount then break end
    local address=slotAddress(session.boundary,row.id)
    local quantity=u16(address+2)
    need(u16(address)==row.item and quantity and quantity&gt;0,
      'The hotbar changed. Refresh the list.','スロットバーの内容が変わりました。一覧を更新してください。')
    targets[#targets+1]={address=address,quantity=quantity,row=row}
  end
  need(#targets&gt;0,'No editable hotbar items.','スロットバーに変更できるアイテムがありません。')
  local attempted=0
  local ok,reason=pcall(function()
    for i,target in ipairs(targets) do
      need(u16(target.address)==target.row.item and u16(target.address+2)==target.quantity,
        'The hotbar changed. Refresh the list.','スロットバーの内容が変わりました。一覧を更新してください。')
      attempted=i
      need(writeSmallInteger(target.address+2,value)==true and u16(target.address+2)==value,
        'The quantity could not be changed.','個数を変更できませんでした。')
    end
  end)
  if not ok then
    local restored=true
    for i=attempted,1,-1 do
      local target=targets[i]
      if u16(target.address)==target.row.item and u16(target.address+2)==value then
        if not writeSmallInteger(target.address+2,target.quantity) or u16(target.address+2)~=target.quantity then restored=false end
      elseif u16(target.address)~=target.row.item or u16(target.address+2)~=target.quantity then
        restored=false
      end
    end
    if not restored then DQB2.err('Some quantities could not be restored. Refresh the list.','一部の個数を復元できませんでした。一覧を更新してください。') end
    error(reason,0)
  end
  DQB2.buildInventoryQuantities(parent)
end

function DQB2.buildInventoryQuantities(parent)
  DQB2.require()
  local rows,state,stack=slotRows()
  DQB2.closeEditor(parent)
  local mirror=allocateMemory(math.max(2,2*#rows))
  need(type(mirror)=='number' and mirror&gt;0,
    'Cannot allocate quantity editor memory.','個数編集用メモリを確保できません。')
  local session={parent=parent,boundary=state,stack=stack,inventoryMirror=mirror,rows=rows}
  DQB2.sessions[parent.ID]=session
  local ok,reason=pcall(function()
    local initial={}
    for _,row in ipairs(rows) do
      initial[#initial+1]=row.quantity &amp; 0xFF
      initial[#initial+1]=row.quantity &gt;&gt; 8
    end
    if #initial&gt;0 then
      local written=writeBytes(mirror,initial)
      need(written==true or written==#initial,'Cannot initialize quantities.','個数を初期化できません。')
    end
    DQB2.addAction(parent,'Refresh list','一覧を更新',('DQB2.buildInventoryQuantities(getAddressList().getMemoryRecordByID(%d))'):format(parent.ID))
    local hotbar=DQB2.addHdr(parent,'Hotbar','スロットバー')
    DQB2.addAction(hotbar,'Set all quantities','指定個数一括変更',
      ('DQB2.setHotbarQuantity(getAddressList().getMemoryRecordByID(%d))'):format(parent.ID))
    local bags={}
    local pageSize=60
    for page=1,inventoryBagCount//pageSize do
      bags[page]=DQB2.addHdr(parent,('Bag %d'):format(page),('ふくろ%d'):format(page))
    end
    for i,row in ipairs(rows) do
      local address=mirror+2*(i-1)
      local m=getAddressList().createMemoryRecord()
      m.Type=vtWord
      m.Address=hex(address)
      m.appendToEntry(row.id&lt;=inventoryHotbarCount and hotbar or bags[(row.id-inventoryHotbarCount-1)//pageSize+1])
      m.Description=DQB2.T(row.en,row.ja)
      DQB2.track(m,row.en,row.ja).inventoryQuantity=true
      m.OnActivate=function(_,before) return not before end
      m.OnValueChangedByUser=function(_,_,newValue) setSlotQuantity(session,row,address,newValue) end
    end
    for _,bag in ipairs(bags) do bag.Collapsed=true end
    hotbar.Collapsed=false
    parent.Collapsed=false
  end)
  if not ok then DQB2.closeEditor(parent);error(reason,0) end
end

function DQB2.openInventoryQuantities(parent)
  DQB2.defer(function()
    if parent.Active and not DQB2.userRun(function() DQB2.buildInventoryQuantities(parent) end) then
      parent.Active=false
    end
  end)
end

local function maxHealth(state)
  local base,bonus=u16(state+0x954C6),u16(state+0x954C8)
  if base and bonus then return math.min(999,base+bonus) end
end
local function playerHealthPart(en,ja,offset,other)
  return {en=en,ja=ja,kind='integer',strict=true,min=0,max=65535,
    read=function(c) return u16(c.address+offset) end,
    write=function(c,value)
      local hp,rest=u16(c.address+0x954C4),u16(c.address+other)
      return hp and rest and hp&lt;=math.min(999,value+rest)
        and writeSmallInteger(c.address+offset,value)==true
    end}
end
local playerCombatActor
DQB2.EDITORS.player={
  en='Player editor',ja='プレイヤーエディタ',
  rows=function() return {{id=1,en='Player',ja='プレイヤー'}} end,
  context=function(id)
    local state=id==1 and DQB2.CONFIG.boundary()
    if state then
      local actor=playerCombatActor and playerCombatActor()
      return {identity=('%X:%X'):format(state,actor or 0),address=state,actor=actor}
    end
  end,
  fields={
    {en='HP',ja='HP',kind='integer',strict=true,min=1,max=999,
      read=function(c) return u16(c.address+0x954C4) end,
      write=function(c,value)
        local limit=maxHealth(c.address)
        return limit and value&lt;=limit and writeSmallInteger(c.address+0x954C4,value)==true
      end},
    {en='Maximum HP',ja='最大HP',kind='integer',strict=true,min=0,max=999,
      read=function(c) return maxHealth(c.address) end},
    playerHealthPart('Base maximum HP','基本最大HP',0x954C6,0x954C8),
    playerHealthPart('Bonus maximum HP','追加最大HP',0x954C8,0x954C6),
    {en='Hunger',ja='満腹度',kind='integer',strict=true,min=0,max=10000,
      read=function(c) return u16(c.address+0x954CC) end,
      write=function(c,value) return writeSmallInteger(c.address+0x954CC,value)==true end},
    {en='Stamina',ja='スタミナ',kind='number',strict=true,min=0,max=65535,
      read=function(c) return readFloat(c.address+0x954D4) end,
      write=function(c,value)
        local limit=u16(c.address+0x954D8)
        return limit and value%1==0 and value&lt;=limit and writeFloat(c.address+0x954D4,value)==true
      end},
    {en='Maximum stamina',ja='最大スタミナ',kind='integer',strict=true,min=0,max=65535,
      read=function(c) return u16(c.address+0x954D8) end},
    {en='Level',ja='レベル',kind='integer',strict=true,min=1,max=99,
      read=function(c) return u16(c.address+0x9560C) end},
    {en='Experience',ja='経験値',kind='integer',strict=true,min=0,max=4294967295,
      read=function(c) return u32(c.address+0x95608) end},
  },
}

local combatMethod
local memberSites={
  ['dqb2.exe']={record=0x75058A,hp=0x2A97F0,mode=0x6206A2},
  ['dqb2_eu.exe']={record=0x75254A,hp=0x2A9F30,mode=0x622222},
  ['dqb2_as.exe']={record=0x75078A,hp=0x2A9A70,mode=0x620A52},
}
local function memberRecords()
  local layout=DQB2.mainName and memberSites[DQB2.mainName:lower()]
  if not layout then return nil end
  local site=DQB2.mainBase+layout.record
  local lookup=bytes(site+7,58)
  if not equal(bytes(site,3),{0x48,0x8B,0x0D}) or not lookup or db(lookup)~=
    '48 8B 51 60 48 81 C2 A0 54 09 00 41 81 F8 60 05 00 00 73 0C 4C 69 CB 70 02 00 00 4C 03 CA EB 03 4C 8B CA 41 0F B7 91 A4 02 00 00 49 8D B1 90 01 00 00 48 8B 49 48 44 8B C3 E8' then return nil end
  local relative=s32(site+3)
  local called=s32(site+65)
  if not relative or not called then return nil end
  local root=pointed(site+7+relative)
  local target=site+69+called
  if readBytes(target,1)==0xE9 then
    local jump=s32(target+1)
    if not jump then return nil end
    target=target+5+jump
  end
  local registry=bytes(target+15,14)
  if not registry or db(registry)~='0F B7 C2 48 8B 84 C1 88 78 00 00 48 85 C0' then return nil end
  local state=DQB2.CONFIG.boundary()
  if root and state and pointed(root+0x60)==state then return state+0x95630,root,state end
end
local function memberString(context,descriptor,key)
  local count=u32(context.manager+descriptor)
  if not count or count==0 or count&gt;1024 then return nil end
  local layout={descriptor=descriptor,count=count,fields=1,westernFields=12}
  local base=catalogBase(context.manager,layout)
  local text=base and catalogTextLayout(base,layout)
  if text then
    text.size=0x10000
    return catalogString(base,text,key)
  end
end
local function customMemberName(record)
  local layout=memberSites[DQB2.mainName:lower()]
  local site=layout and DQB2.mainBase+layout.mode
  local marker=site and bytes(site+7,18)
  local relative=site and s32(site+3)
  if not relative or not equal(bytes(site,3),{0x48,0x8B,0x05}) or not marker or
      db(marker)~='41 0F B6 F0 48 8B DA 48 8B F9 80 B8 C8 75 06 00 00 74' then return nil end
  local game=pointed(site+7+relative)
  local c=game and bytes(game+0x675C8,2)
  local flags=bytes(record+0x1B2,1)
  if c and (c[1]==0 or c[2]~=0) and flags and flags[1]&gt;=128 then
    local name=readString(record+0x80,128,false)
    if name and name~='' and utf8.len(name) then return name end
  end
end
local function memberName(context,record,key)
  local custom=customMemberName(record)
  if custom then return custom end
  local desc=context.manager+0x810
  local types=pointed(desc+16)
  if not types or u32(desc)~=1024 or u32(desc+8)~=0x1040 then return nil end
  local family=bytes(types+0x1040+72*key+0x23,1)
  local flags=bytes(record+0x1B4,1)
  if not family or not flags then return nil end
  if flags[1] &amp; 1~=0 and family[1]==1 then
    local fields=bytes(record+0x187,17)
    if fields then return memberString(context,fields[1]==1 and 0x2A0 or 0x2B8,fields[17]) end
  end
  if flags[1] &amp; 1~=0 or family[1]==2 or family[1]==3 then
    local ids=bytes(record+0x194,2)
    local id=ids and ids[2]
    if not id then return nil end
    if id==0 or id&gt;=128 then id=ids[1] end
    if id&gt;0 and id&lt;128 then return memberString(context,0x228,id) end
    return nil
  end
  return DQB2.catalogCharacter(context,key)
end
function DQB2.characterRows(residentsOnly)
  DQB2.require()
  local context=DQB2.resolveCatalog({'characters'})
  local base=need(memberRecords(),'Character records are unavailable.','キャラクター記録を取得できません。')
  local rows={}
  for first=0,0x55F,16 do
    local block=bytes(base+0x270*first,0x270*16)
    for i=first,first+15 do
      local record=base+0x270*i
      local offset=(i-first)*0x270
      local key,flags
      if block then
        key=block[offset+0x115]+256*block[offset+0x116]
        flags=block[offset+0x1B3]
      else
        key=u16(record+0x114)
        if residentsOnly then flags=readBytes(record+0x1B2,1) end
      end
      if key and key&gt;0 and key&lt;1024 and
          (not residentsOnly or (flags and flags &amp; 0x10~=0)) then
        local name=memberName(context,record,key)
        if name then rows[#rows+1]={id=i,name=name,key=key} end
      end
    end
  end
  return rows,context,base
end
local function memberHealthContext(id)
  if math.type(id)~='integer' or id&lt;0 or id&gt;=0x560 then return nil end
  local base,root=memberRecords()
  local registry=root and pointed(root+0x48)
  if not base or not registry then return nil end
  local record=base+0x270*id
  local key=u16(record+0x114)
  if not key or key==0 or key&gt;=1024 then return nil end
  local node=pointed(registry+0x7888+8*key)
  for _=1,128 do
    if not node then break end
    local actor=pointed(node)
    local active=actor and u16(actor+0x2B8)
    if active and active~=0 and u16(actor+0x10D8)==id and pointed(actor+0x1190)==record then
      local vtable=pointed(actor)
      local hpGetter=vtable and combatMethod(vtable-DQB2.mainBase,0x2B0)
      local maxGetter=vtable and combatMethod(vtable-DQB2.mainBase,0x2B8)
      if hpGetter~=DQB2.mainBase+memberSites[DQB2.mainName:lower()].hp or not maxGetter then return nil end
      if not equal(bytes(hpGetter+9,7),{0x0F,0xB7,0x80,0x16,0x01,0,0}) or
          not equal(bytes(maxGetter,8),{0x0F,0xB7,0x81,0x48,0x0E,0,0,0xC3}) then return nil end
      local hp,limit=u16(record+0x116),u16(actor+0xE48)
      if hp and limit and limit&gt;0 and hp&lt;=limit then
        return {identity=('%X:%X:%X'):format(record,actor,active),address=record,actor=actor}
      end
      return nil
    end
    node=pointed(node+8)
  end
end
local function residentHealthContext(id)
  local ctx=memberHealthContext(id)
  if not ctx then return nil end
  local flags=readBytes(ctx.address+0x1B2,1)
  local kind=readBytes(ctx.actor+0x1171,1)
  if flags and flags &amp; 0x10~=0 and (kind==1 or kind==2 or kind==4) then return ctx,kind end
end
DQB2.EDITORS.member={
  en='Member editor',ja='メンバーエディタ',runtimeNames=true,
  rows=function()
    local rows={}
    for _,row in ipairs(DQB2.characterRows(true)) do
      local context=residentHealthContext(row.id)
      if context then
        rows[#rows+1]={id=row.id,name=('%d  %s'):format(row.id,row.name),identity=context.identity}
      end
    end
    return rows
  end,
  context=residentHealthContext,
  fields={
    {en='HP',ja='HP',kind='integer',strict=true,min=0,max=65535,
      read=function(c) return u16(c.address+0x116) end,
      write=function(c,value)
        local hp,limit=u16(c.address+0x116),u16(c.actor+0xE48)
        local flags=readBytes(c.address+0x1B9,1)
        return hp and hp&gt;0 and flags and flags &amp; 2==0 and value&gt;0 and limit and value&lt;=limit
          and writeSmallInteger(c.address+0x116,value)==true
      end},
    {en='Maximum HP',ja='最大HP',kind='integer',strict=true,min=1,max=65535,
      read=function(c) return u16(c.actor+0xE48) end},
  },
}

function DQB2.catalogSessionAlive(session)
  return currentCatalog(session.catalog,'definitions')~=nil and currentCatalog(session.catalog,'items')~=nil
end

local function grantBytes(address,count)
  local data=bytes(address,count)
  return data and string.char(table.unpack(data))
end
local function putGrantBytes(address,data)
  return writeBytes(address,{data:byte(1,#data)}) and grantBytes(address,#data)==data
end
local function grantThreadsClear(site,cave,buffer,siteSize)
  siteSize=siteSize or 8
  local api=executeCodeLocalEx
  local threads=getThreadlist()
  if not threads or #threads==0 then return false end
  for _,id in ipairs(threads) do
    local thread=api('kernel32.OpenThread',8,0,id)
    if not thread or thread==0 then return false end
    writeIntegerLocal(buffer+0x30,0x100001)
    local result=api('kernel32.GetThreadContext',thread,buffer)
    api('kernel32.CloseHandle',thread)
    local rip=result and result~=0 and readQwordLocal(buffer+0xF8)
    if not rip or (rip&gt;=site and rip&lt;site+siteSize) or (rip&gt;=cave and rip&lt;cave+4096) then return false end
  end
  return true
end
local function bagCapacity(state,item)
  local count=0x163A
  local slots=bytes(state+0xB8868C,count*4)
  if not slots then return 0 end
  local capacity=0
  for i=1,#slots,4 do
    local id=slots[i]+256*slots[i+1]
    local quantity=slots[i+2]+256*slots[i+3]
    if id==0 then
      capacity=capacity+999
    elseif id==item and quantity&lt;999 then
      capacity=capacity+999-quantity
    end
  end
  return capacity
end
local function grantCanRestore(installed,status)
  return not installed or status==0 or status==1 or status==3
end
function DQB2.recoverGrant()
  DQB2.require()
  local state=DQB2.pendingGrant
  if not state then return end
  need(state.pid==DQB2.pid,'Item request belongs to another process.','別のプロセスのアイテム追加処理です。')
  local api=executeCodeLocalEx
  local buffer=api('kernel32.VirtualAlloc',0,4096,0x3000,4)
  need(buffer and buffer~=0,'Context allocation failed.','検証用メモリを確保できません。')
  pause()
  local ok,reason=pcall(function()
    need(grantCanRestore(state.installed,readInteger(state.box)) and
        grantThreadsClear(state.site,state.cave,buffer),
      'Item request is still running.','アイテム追加処理をまだ解除できません。')
    local current=grantBytes(state.site,8)
    need(not state.installed or current==state.original or
        (current==state.entry and putGrantBytes(state.site,state.original)),
      'Item request entry changed.','アイテム追加の命令が変わりました。')
    need(deAlloc(state.cave),'Unable to release item request.','アイテム追加用メモリを解放できません。')
    DQB2.pendingGrant=nil
  end)
  unpause()
  api('kernel32.VirtualFree',buffer,0,0x8000)
  if not ok then error(reason,0) end
end
local grantSites={
  ['dqb2.exe']={frame=0x723C1E,entry=0x24C550,grant=0x248C40},
  ['dqb2_eu.exe']={frame=0x725BDE,entry=0x24CC80,grant=0x249370},
  ['dqb2_as.exe']={frame=0x723E1E,entry=0x24C7D0,grant=0x248EC0},
}
local function grantEntryPoints()
  local layout=DQB2.mainName and grantSites[DQB2.mainName:lower()]
  if not layout then return nil end
  local site,entry=DQB2.mainBase+layout.frame,DQB2.mainBase+layout.entry
  local frame=bytes(site-21,37)
  local prepare=bytes(entry,26)
  local finish=bytes(entry+30,5)
  if not frame or db(frame)~='48 8B 78 60 33 C0 F3 0F 5A CF 0F 28 C1 F2 0F 58 87 90 54 09 00 F2 0F 11 87 90 54 09 00 F2 0F 58 8F 70 B6 61 00' or
      not prepare or db(prepare)~='48 83 EC 48 33 C0 C7 44 24 30 0F 00 00 00 89 44 24 28 0F B7 D2 89 44 24 20 E8' or
      not equal(finish,{0x48,0x83,0xC4,0x48,0xC3}) then return nil end
  local offset=s32(entry+26)
  if not offset then return nil end
  local target=entry+30+offset
  if readBytes(target,1)==0xE9 then
    local thunk=s32(target+1)
    if not thunk then return nil end
    target=target+5+thunk
  end
  if target==DQB2.mainBase+layout.grant then return site,target end
end

local function runFrameCall(site,target,state,body,prepare,ready,result,timeout)
  need(not DQB2.pendingGrant,'An earlier game request has not settled.','前回のゲーム内処理が完了していません。')
  local original=string.char(0xF2,0x0F,0x11,0x87,0x90,0x54,0x09,0x00)
  local api=executeCodeLocalEx
  local buffer=api('kernel32.VirtualAlloc',0,4096,0x3000,4)
  need(buffer and buffer~=0,'Context allocation failed.','検証用メモリを確保できません。')
  local cave=allocateMemory(4096,site)
  if not cave or cave==0 then
    api('kernel32.VirtualFree',buffer,0,0x8000)
    DQB2.err('Game request allocation failed.','ゲーム内処理用メモリを確保できません。')
  end
  local box=cave+0x200
  local paused,installed,actual,entry
  local ok,reason=pcall(function()
    local assembly=([[
define(box,%X)
define(target,%X)
define(resume,%X)
define(expected,%X)
define(output,%X)
label(done)
label(skip)
%X:
db F2 0F 11 87 90 54 09 00
pushfq
push rax
push rcx
push rdx
push r8
push r9
push r10
push r11
mov eax,1
mov edx,2
lock cmpxchg [box],edx
jne skip
cmp rdi,[expected]
jne done
sub rsp,80
movdqu [rsp+20],xmm0
movdqu [rsp+30],xmm1
movdqu [rsp+40],xmm2
movdqu [rsp+50],xmm3
movdqu [rsp+60],xmm4
movdqu [rsp+70],xmm5
%s
movdqu xmm0,[rsp+20]
movdqu xmm1,[rsp+30]
movdqu xmm2,[rsp+40]
movdqu xmm3,[rsp+50]
movdqu xmm4,[rsp+60]
movdqu xmm5,[rsp+70]
add rsp,80
done:
mov dword ptr [box],3
skip:
pop r11
pop r10
pop r9
pop r8
pop rdx
pop rcx
pop rax
popfq
jmp resume
]]):format(box,target,site+8,box+0x10,box+0x40,cave,body)
    local compiled,err=autoAssemble(assembly)
    need(compiled,tostring(err),tostring(err))
    need(prepare(box) and writeInteger(box+0xC,-1)
        and writeQword(box+0x10,state),'Cannot prepare game request.','ゲーム内処理を準備できません。')
    entry=string.char(0xE9)..string.pack('&lt;i4',cave-site-5)..string.char(0x0F,0x1F,0)
    pause();paused=true
    need(DQB2.CONFIG.boundary()==state and ready() and
        grantThreadsClear(site,cave,buffer) and grantBytes(site,8)==original,
      'Game state changed or the action is unavailable.','ゲームの状態が変わったか、操作を実行できません。')
    installed=true
    need(putGrantBytes(site,entry) and writeInteger(box,1),'Cannot submit game request.','ゲーム内処理を開始できません。')
    unpause();paused=false
    local start=getTickCount()
    while readInteger(box)~=3 and (getTickCount()-start)&lt;(timeout or 1000) do sleep(4) end
  end)
  local restored=false
  local readResult,resultError=true,nil
  local cleaned=pcall(function()
    for _=1,30 do
      if not paused then pause();paused=true end
      local status=readInteger(box)
      if grantCanRestore(installed,status) and grantThreadsClear(site,cave,buffer) then
        local reply=status==3 and readInteger(box+0xC)
        if reply and reply~=-1 then
          readResult,actual=pcall(result,box)
          if not readResult then resultError=actual end
        end
        local live=grantBytes(site,8)
        restored=(not installed or live==original or (live==entry and putGrantBytes(site,original))) and deAlloc(cave)
        break
      end
      unpause();paused=false;sleep(5)
    end
  end)
  if paused then unpause() end
  api('kernel32.VirtualFree',buffer,0,0x8000)
  if not cleaned or not restored then
    DQB2.pendingGrant={pid=DQB2.pid,site=site,cave=cave,box=box,original=original,entry=entry,installed=installed}
    DQB2.err('Game request could not be cleaned up. Do not repeat it.',
      'ゲーム内処理を解除できませんでした。繰り返さないでください。')
  end
  if not ok then error(reason,0) end
  if not readResult then error(resultError,0) end
  need(actual~=nil,'Game request did not complete.','ゲーム内処理が完了しませんでした。')
  return actual
end

local function residentRegistration()
  local name=DQB2.mainName:lower()
  local rva=name=='dqb2.exe' and 0x2E3EB0 or name=='dqb2_eu.exe' and 0x2E46A0 or name=='dqb2_as.exe' and 0x2E4130 or nil
  if not rva then return nil end
  local base=DQB2.mainBase
  local frame=grantEntryPoints()
  local target=base+rva
  local entry=bytes(target,10)
  local registration=bytes(target+0x1F5,7)
  if not frame or not entry or not registration
      or db(entry)~='40 53 56 57 41 56 48 83 EC 58'
      or db(registration)~='80 8D B2 01 00 00 11' then return nil end
  local holder=pointed(base+(name=='dqb2_eu.exe' and 0x13F2118 or name=='dqb2_as.exe' and 0x13DFFD8 or 0x13C1048))
  local data=holder and pointed(holder)
  local definitions=data and pointed(data+0x58)
  if definitions then return frame,target,definitions end
end

local function residentTable(definitions,offset)
  local count=u32(definitions+offset)
  local displacement=u32(definitions+offset+8)
  local entries=pointed(definitions+offset+0x10)
  if count and displacement and entries then return entries+displacement,count end
end

local function residentIsland(definitions)
  local _,root,state=memberRecords()
  local stage=root and u32(root+0x10)
  local entries,count=residentTable(definitions,0xA38)
  local session=pointed(DQB2.mainBase+0x133AA10)
  if state and session and readBytes(session+0x675C8,1)==0
      and stage and stage&gt;0 and stage&lt;=31 and entries and stage&lt;count
      and readBytes(entries+stage*8+2,1)==1 then
    return root,state,stage
  end
end

local function recruitableResident(id,stage,definitions)
  local ctx=memberHealthContext(id)
  if not ctx or readBytes(ctx.address+0x164,1)~=stage then return nil end
  local flags=readBytes(ctx.address+0x1B2,1)
  local hp=u16(ctx.address+0x116)
  local wrapper=pointed(ctx.actor+0x1198)
  local template=u16(ctx.actor+0x10DA)
  local entries,count=residentTable(definitions,0x810)
  if not flags or flags &amp; 0x13~=2 or not hp or hp==0
      or not wrapper or pointed(wrapper+8)~=ctx.actor
      or not entries or not template or template&gt;=count then return nil end
  local flagAddress=entries+template*0x48+0x44
  local allowed=readBytes(flagAddress,1)
  if allowed and allowed &amp; 4~=0 then return ctx,wrapper,flagAddress end
end

function DQB2.openResidentAdd(parent)
  DQB2.require()
  local frame,target,definitions=residentRegistration()
  need(frame,'Resident registration is unavailable for this build.','このバージョンでは住人登録を確認できません。')
  local root,state,stage=residentIsland(definitions)
  need(state,'Resident registration is unavailable here.','ここでは住人を登録できません。')
  local rows={}
  for _,row in ipairs(DQB2.characterRows(false)) do
    local ctx=recruitableResident(row.id,stage,definitions)
    if ctx then rows[#rows+1]={id=row.id,name=('%d  %s'):format(row.id,row.name),identity=ctx.identity} end
  end
  need(#rows&gt;0,'No recruitable characters are present.','登録できるキャラクターがいません。')
  DQB2.choose(parent,rows,false,function(row)
    local ctx,wrapper,flagAddress=recruitableResident(row.id,stage,definitions)
    need(ctx and ctx.identity==row.identity,'Character changed. Reopen the list.','キャラクターの状態が変わりました。一覧を開き直してください。')
    local function ready()
      local f,t,g=residentRegistration()
      if f~=frame or t~=target or g~=definitions then return false end
      local r,s,i=residentIsland(g)
      if r~=root or s~=state or i~=stage then return false end
      local now,w,flag=recruitableResident(row.id,stage,g)
      return now and now.identity==ctx.identity and w==wrapper and flag==flagAddress
    end
    local added=runFrameCall(frame,target,state,[[
label(residentExit)
mov rax,[box+18]
mov ecx,[box+04]
cmp [rax+10],ecx
jne residentExit
mov rax,[box+20]
mov edx,[box+08]
cmp [rax+10D8],dx
jne residentExit
cmp word ptr [rax+2B8],0
je residentExit
mov rcx,[box+28]
cmp [rax+1198],rcx
jne residentExit
cmp [rcx+08],rax
jne residentExit
mov rdx,[box+30]
cmp [rax+1190],rdx
jne residentExit
mov eax,[box+04]
cmp [rdx+164],al
jne residentExit
cmp word ptr [rdx+116],0
je residentExit
mov al,[rdx+1B2]
and al,13
cmp al,2
jne residentExit
mov rax,[box+38]
test byte ptr [rax],4
je residentExit
xor edx,edx
xor r8d,r8d
sub rsp,40
call target
add rsp,40
movzx eax,al
mov [box+0C],eax
residentExit:
]],function(box)
      return writeInteger(box+4,stage) and writeInteger(box+8,row.id) and writeQword(box+0x18,root)
        and writeQword(box+0x20,ctx.actor) and writeQword(box+0x28,wrapper)
        and writeQword(box+0x30,ctx.address) and writeQword(box+0x38,flagAddress)
    end,ready,function(box)
      local flags=readBytes(ctx.address+0x1B2,1)
      return readInteger(box+0xC)==1 and flags and flags &amp; 0x11==0x11
        and readBytes(ctx.address+0x164,1)==stage
    end)
    need(added,'The game did not confirm the resident registration.','住人として登録されたことを確認できません。')
    DQB2.msg('Resident added.','住人を追加しました。')
  end)
end

local heartSetterGuard={
  {0,'44 8B 05 ?? ?? ?? ?? 4C 8B C9 41 3B D0 7D 10 3B 15 ?? ?? ?? ?? 0F 4E 15 ?? ?? ?? ?? 44 8B C2'},
  {31,'0F B6 81 3E 57 7E 00 44 89 81 34 57 7E 00 48 8D 0D ?? ?? ?? ?? 0F B6 14 08 83 FA 04 73 25'},
  {90,'41 89 8C 91 0C AB 5E 00 C3'},
}
local function playerHeartSetter()
  local name=DQB2.mainName:lower()
  local rva=name=='dqb2.exe' and 0x716DD0 or name=='dqb2_eu.exe' and 0x718F70 or name=='dqb2_as.exe' and 0x717200 or nil
  if not rva then return nil end
  local entry=DQB2.mainBase+rva
  for _,guard in ipairs(heartSetterGuard) do
    local tokens={}
    for token in guard[2]:gmatch('%S+') do tokens[#tokens+1]=token end
    local data=bytes(entry+guard[1],#tokens)
    if not data then return nil end
    for i,token in ipairs(tokens) do
      if token~='??' and data[i]~=tonumber(token,16) then return nil end
    end
  end
  local relative=s32(entry+3)
  local limit=relative and readInteger(entry+7+relative)
  if limit and limit&gt;0 then return entry,limit end
end
local function setPlayerHearts(c,value)
  local target,limit=playerHeartSetter()
  if not target or value&gt;limit then return false end
  local frame=grantEntryPoints()
  if not frame then return false end
  return runFrameCall(frame,target,c.address,[[
lea rcx,[rdi+10]
mov edx,[box+04]
sub rsp,40
call target
add rsp,40
mov eax,[box+04]
cmp dword ptr [rdi+7E5744],eax
sete al
movzx eax,al
mov [box+0C],eax
]],function(box) return writeInteger(box+4,value) end,
    function() return playerHeartSetter()==target end,
    function(box) return readInteger(box+0xC)==1 end)==true
end
local function playerMedalsAvailable()
  local name=DQB2.mainName:lower()
  local rva=name=='dqb2.exe' and 0x852002 or name=='dqb2_eu.exe' and 0x858B77 or name=='dqb2_as.exe' and 0x853162 or nil
  return rva~=nil and equal(bytes(DQB2.mainBase+rva,16),
      {0x48,0x8B,0x48,0x60,0x8B,0x81,0xA0,0x70,0x2E,0,0x03,0x81,0xA4,0x70,0x2E,0})
end
local function medalField(en,ja,offset)
  return {en=en,ja=ja,kind='integer',strict=true,min=0,max=0xFFFFFFFF,
    available=playerMedalsAvailable,
    read=function(c) return u32(c.address+offset) end,
    write=function(c,value)
      local other=u32(c.address+(offset==0x2E70A0 and 0x2E70A4 or 0x2E70A0))
      return playerMedalsAvailable() and other and value&lt;=0xFFFFFFFF-other
        and writeInteger(c.address+offset,value)==true
    end}
end
table.insert(DQB2.EDITORS.player.fields,{
  en='Gratitude points',ja='ビルダーハート',kind='integer',strict=true,min=0,
  available=function() return playerHeartSetter()~=nil end,
  read=function(c) return u32(c.address+0x7E5744) end,
  write=setPlayerHearts,
})
table.insert(DQB2.EDITORS.player.fields,medalField('Mini medals','小さなメダル',0x2E70A0))
table.insert(DQB2.EDITORS.player.fields,medalField('Mini medals handed in','納品済みの小さなメダル',0x2E70A4))

function DQB2.grantBagItem(item,quantity)
  DQB2.require()
  local stack=need(inventoryStackTable(),'Item stack data is unavailable.','スタック情報を取得できません。')
  need(isStackable(item,stack),
    'This item cannot be added to the bag.','このアイテムはふくろに追加できません。')
  need(math.type(quantity)=='integer' and quantity&gt;=1 and quantity&lt;=999,
    'Quantity must be 1 to 999.','個数には1から999を指定してください。')
  local context=DQB2.resolveCatalog({'definitions','items'})
  need(DQB2.catalogItem(context,item),'Item no longer resolves.','アイテムを確認できません。')
  local state=need(DQB2.CONFIG.boundary(),'Player state is unavailable.','プレイヤー状態を取得できません。')
  need(bagCapacity(state,item)&gt;=quantity,
    'There is not enough room in the bag.','ふくろに指定個数を追加できる空きがありません。')
  local site,grant=grantEntryPoints()
  need(site and grant,'Item grant instructions changed.','アイテム追加の命令が一致しません。')
  return runFrameCall(site,grant,state,[[
lea rcx,[rdi+B7F640]
mov edx,[box+04]
mov r8d,[box+08]
lea r9,[output]
sub rsp,40
mov dword ptr [rsp+20],1
mov dword ptr [rsp+28],0
mov dword ptr [rsp+30],163A
call target
add rsp,40
mov [box+0C],eax
]],function(box)
    return writeInteger(box+4,item) and writeInteger(box+8,quantity)
  end,function()
    return inventoryStackTable()==stack and isStackable(item,stack) and
      bagCapacity(state,item)&gt;=quantity
  end,function(box)
    local status=readBytes(box+0x0C,1)
    local entries=readBytes(box+0x82,1)
    if (status~=0 and status~=1) or not entries or entries&gt;16 then return nil end
    local count=0
    for i=0,entries-1 do
      local added=u16(box+0x62+2*i)
      if not added or added&lt;1 then return nil end
      count=count+added
    end
    if count&gt;quantity or (status==1 and count~=quantity) then return nil end
    return count
  end)
end

DQB2.SIGS.mapReveal={
  p='48 89 5C 24 10 48 89 6C 24 18 48 89 74 24 20 57 41 56 41 57 48 83 EC 20 48 8B F1 4C 8D 3D ?? ?? ?? ?? BD 01 00 00 00 41 BE FF 00 00 00 0F 1F 00 48 63 56 68',
  validate=function(site)
    local mapping=s32(site+0x1E)
    if not mapping or not equal(bytes(site+0x72,7),{0xC6,0x80,2,0,2,0,1}) or
      not equal(bytes(site+0xD6,7),{0xC6,0x86,0x78,0x24,0,0,1}) then return false end
    local address=site+0x22+mapping
    for _,section in ipairs(DQB2.mainPE.sections) do
      if not section.execute and address&gt;=section.first and address+0x1B&lt;=section.last then return true end
    end
    return false
  end,
}
DQB2.SIGS.mapOwner={
  p='48 8B 05 ?? ?? ?? ?? 45 33 E4 48 8B F1 48 85 C0 74 06 48 8B 48 10 EB 03 49 8B CC 48 8B 96 A8 00 00 00 48 8D AE 10 01 00 00 4C 8B B1 90 03 00 00',
  kind='rip',disp=3,length=7,
  validate=function(address)
    for _,section in ipairs(DQB2.mainPE.sections) do
      if not section.execute and address&gt;=section.first and address+8&lt;=section.last then return true end
    end
    return false
  end,
}
DQB2.SIGS.itemDiscoveryList={
  p='48 83 EC 28 48 8B 05 ?? ?? ?? ?? 48 8B 10 4C 8B 4A 58 41 3B 89 B0 07 00 00 73 29 45 8B 81 B8 07 00 00 8B C1 48 8D 14 40',
  validate=function(site)
    return equal(bytes(site+56,13),{0x41,0x0F,0xB6,0x40,0x2E,0xC0,0xE8,0x02,0x24,0x01,0x75,0x09,0xE8})
  end,
}
DQB2.SIGS.itemDiscoveryRead={
  p='0F B7 C3 3D A0 0F 00 00 0F 83 ?? ?? ?? ?? 8B D0 48 8B 05 ?? ?? ?? ?? 48 8B 48 60 F6 84 11 20 C8 2E 00 09 0F 95 C2',
  validate=function(site)
    local displacement=s32(site+19)
    local manager=displacement and pointed(site+23+displacement)
    local state=DQB2.CONFIG.boundary()
    return state~=nil and manager~=nil and pointed(manager+0x60)==state
  end,
}
function DQB2.discoverAllItems()
  DQB2.require()
  local state=DQB2.captureBoundary()
  local query=DQB2.needSig('itemDiscoveryRead')
  local displacement=need(s32(query+19),'Item list address is unavailable.','アイテム図鑑のアドレスを取得できません。')
  local owner=query+23+displacement
  local function ownsList()
    local manager=pointed(owner)
    return manager~=nil and pointed(manager+0x60)==state
  end
  local target=DQB2.needSig('itemDiscoveryList')
  local site=need(grantEntryPoints(),'Frame update is unavailable.','フレーム更新を取得できません。')
  local count=runFrameCall(site,target,state,[[
label(nextItem)
label(skipItem)
push rbx
push rsi
sub rsp,30
xor esi,esi
mov ebx,1
nextItem:
mov ecx,ebx
call target
test al,al
je skipItem
test byte ptr [rdi+rbx+2EC820],09
jne skipItem
or byte ptr [rdi+rbx+2EC820],01
inc esi
skipItem:
inc ebx
cmp ebx,FA0
jb nextItem
mov [box+0C],esi
add rsp,30
pop rsi
pop rbx
]],function() return true end,ownsList,function(box)
    local value=readInteger(box+0xC)
    if value and value&gt;=0 and value&lt;4000 then return value end
  end,3000)
  need(count~=nil,'Item discovery could not be verified.','アイテムの判明を確認できませんでした。')
  DQB2.msg(('Newly discovered items: %d.'):format(count),('新たに判明したアイテム: %d件。'):format(count))
end

DQB2.SIGS.blueprintList={
  p='83 FB 64 73 0F 42 0F B6 B4 33 68 0B 2F 00 40 80 E6 01 EB 03 40 32 F6 48 85 C9 0F 84 ?? ?? ?? ?? 44 0F B6 79 11 45 85 FF',
  validate=function(site)
    return equal(bytes(site+46,7),{0x0F,0xB6,0x41,0x13,0xC0,0xE8,0x02})
  end,
}
function DQB2.unlockAllBlueprints()
  DQB2.require()
  DQB2.needSig('blueprintList')
  local state=DQB2.captureBoundary()
  local layout={descriptor=0x750,count=100}
  local manager=need(catalogManager(),'Catalog is unavailable.','図鑑データを取得できません。')
  local base=need(catalogBase(manager,layout),'Blueprint definitions are unavailable.','せっけいずの定義を取得できません。')
  local site=need(grantEntryPoints(),'Frame update is unavailable.','フレーム更新を取得できません。')
  local records=base+64+4*layout.count
  local count=runFrameCall(site,records,state,[[
label(nextBlueprint)
label(skipBlueprint)
mov r8,target
add r8,18
mov ecx,1
xor edx,edx
nextBlueprint:
cmp byte ptr [r8+11],0
je skipBlueprint
test byte ptr [r8+13],04
jne skipBlueprint
test byte ptr [rdi+rcx+2F0B68],01
jne skipBlueprint
or byte ptr [rdi+rcx+2F0B68],01
inc edx
skipBlueprint:
add r8,18
inc ecx
cmp ecx,64
jb nextBlueprint
mov [box+0C],edx
]],function() return true end,function()
    return catalogManager()==manager and catalogBase(manager,layout)==base
  end,function(box)
    local value=readInteger(box+0xC)
    if value and value&gt;=0 and value&lt;100 then return value end
  end)
  need(count~=nil,'Blueprint unlock could not be verified.','せっけいずの開放を確認できませんでした。')
  DQB2.msg(('Blueprints unlocked: %d.'):format(count),('開放したせっけいず: %d件。'):format(count))
end

local builderpediaLists={
  recipe={
    count=1500,
    list='48 83 EC 28 48 8B 05 ?? ?? ?? ?? 48 8B 10 4C 8B 4A 58 41 3B 89 00 09 00 00 73 25 45 8B 81 08 09 00 00 8B C1 48 6B D0 6C',
    tailOffset=52,tail={0x41,0x0F,0xB6,0x40,0x67,0xC0,0xE8,0x05},
    state='81 FB DC 05 00 00 73 08 80 8C 9A B2 70 2E 00 02 41 B0 01 BA 01 00 00 00 8B CB E8 ?? ?? ?? ?? 33 D2 8B CB E8 ?? ?? ?? ?? 84 C0 74 1B 48 8B 05 ?? ?? ?? ?? 48 8B 48 60 81 FB DC 05 00 00 73 08 80 8C 99 B2 70 2E 00 04 48 8B 05 ?? ?? ?? ?? 48 89 7C 24 30',
    stateOffset=8,stateBytes={0x80,0x8C,0x9A,0xB2,0x70,0x2E,0,2},
    catalog={descriptor=0x900,count=1500},
    labels='label(recipeCategories)\nlabel(nextCategory)\nlabel(skipCategory)',
    update=[[
test byte ptr [rdi+rbx*4+2E70B2],02
jne recipeCategories
or byte ptr [rdi+rbx*4+2E70B2],02
inc esi
recipeCategories:
mov rdx,%X
imul rax,rbx,6C
add rdx,rax
mov ecx,1
nextCategory:
cmp byte ptr [rdx+rcx+35],0
je skipCategory
or byte ptr [rdi+rcx+2EEBCC],01
skipCategory:
inc ecx
cmp ecx,32
jb nextCategory
jmp skipEntry
]],
    en='Recipes unlocked: %d.',ja='開放したレシピ: %d件。',
  },
  monster={
    count=1000,
    list='48 83 EC 28 48 8B 05 ?? ?? ?? ?? 48 8B 10 4C 8B 4A 58 41 3B 89 28 08 00 00 73 25 45 8B 81 30 08 00 00 8B C1 48 6B D0 44',
    tailOffset=52,tail={0x41,0x0F,0xB6,0x40,0x3D,0xC0,0xE8,0x03},
    state='48 8B 78 60 41 81 F8 00 04 00 00 73 0B 42 0F B7 9C 87 C0 D9 2E 00 EB 03 41 8B DA',
    stateOffset=13,stateBytes={0x42,0x0F,0xB7,0x9C,0x87,0xC0,0xD9,0x2E,0},
    update=[[
cmp word ptr [rdi+rbx*4+2ED9C0],0
jne skipEntry
mov word ptr [rdi+rbx*4+2ED9C0],1
]],
    en='Monsters discovered: %d.',ja='判明したモンスター: %d件。',
  },
  room={
    count=512,
    list='48 8B 05 ?? ?? ?? ?? 8B D1 4C 8B 08 49 8B 49 58 3B 91 90 09 00 00 73 50 8B 81 98 09 00 00 4C 8D 04 D2',
    tailOffset=50,tail={0x0F,0xB6,0x40,0x21,0xC0,0xE8,0x02,0x24,0x01},
    state='81 FB 00 02 00 00 73 21 41 0F B6 82 4E 57 7E 00 48 C1 E0 09 49 03 C3 42 0F B6 84 10 20 88 2E 00 24 01',
    stateOffset=23,stateBytes={0x42,0x0F,0xB6,0x84,0x10,0x20,0x88,0x2E,0},
    update=[[
movzx ecx,byte ptr [rdi+7E574E]
cmp ecx,20
jae skipEntry
shl ecx,9
add rcx,rdi
test byte ptr [rcx+rbx+2E8820],01
jne skipEntry
or byte ptr [rcx+rbx+2E8820],01
]],
    en='Room recipes unlocked: %d.',ja='開放した部屋レシピ: %d件。',
  },
}
for key,layout in pairs(builderpediaLists) do
  DQB2.SIGS[key..'DiscoveryList']={
    p=layout.list,
    validate=function(site) return equal(bytes(site+layout.tailOffset,#layout.tail),layout.tail) end,
  }
  DQB2.SIGS[key..'DiscoveryState']={
    p=layout.state,
    validate=function(site) return equal(bytes(site+layout.stateOffset,#layout.stateBytes),layout.stateBytes) end,
  }
end
DQB2.SIGS.recipeDiscoveryCategories={
  p='41 0F B6 4C 39 35 85 C9 74 ?? 48 8B 05 ?? ?? ?? ?? 48 8B 48 60 41 83 F9 40 73 ?? 41 80 8C 09 CC EB 2E 00 01',
  validate=function(site) return equal(bytes(site+27,9),{0x41,0x80,0x8C,0x09,0xCC,0xEB,0x2E,0,1}) end,
}
local function unlockBuilderpediaList(key)
  DQB2.require()
  local layout=builderpediaLists[key]
  local state=DQB2.captureBoundary()
  DQB2.needSig(key..'DiscoveryState')
  local target=DQB2.needSig(key..'DiscoveryList')
  local manager,recipeTable
  local update=layout.update
  if layout.catalog then
    DQB2.needSig('recipeDiscoveryCategories')
    manager=need(catalogManager(),'Catalog is unavailable.','図鑑データを取得できません。')
    recipeTable=need(catalogBase(manager,layout.catalog),
      'Recipe definitions are unavailable.','レシピの定義を取得できません。')
    update=update:format(recipeTable+64+layout.count*4)
  end
  local site=need(grantEntryPoints(),'Frame update is unavailable.','フレーム更新を取得できません。')
  local count=runFrameCall(site,target,state,([[
label(nextEntry)
label(skipEntry)
%s
push rbx
push rsi
sub rsp,30
xor esi,esi
mov ebx,1
nextEntry:
mov ecx,ebx
call target
test al,al
je skipEntry
%s
inc esi
skipEntry:
inc ebx
cmp ebx,%X
jb nextEntry
mov [box+0C],esi
add rsp,30
pop rsi
pop rbx
]]):format(layout.labels or '',update,layout.count),function() return true end,function()
    if layout.catalog then
      return catalogManager()==manager and catalogBase(manager,layout.catalog)==recipeTable
    end
    if key~='room' then return true end
    local bank=readBytes(state+0x7E574E,1)
    return bank~=nil and bank&lt;32
  end,function(box)
    local value=readInteger(box+0xC)
    if value and value&gt;=0 and value&lt;layout.count then return value end
  end,3000)
  need(count~=nil,'Unlock could not be verified.','開放を確認できませんでした。')
  DQB2.msg(layout.en:format(count),layout.ja:format(count))
end
function DQB2.unlockAllRecipes() unlockBuilderpediaList('recipe') end
function DQB2.discoverAllMonsters() unlockBuilderpediaList('monster') end
function DQB2.unlockAllRoomRecipes() unlockBuilderpediaList('room') end

DQB2.SIGS.builderToolSet={
  p='48 89 5C 24 08 48 89 74 24 10 57 48 83 EC 30 8B FA 41 0F B6 D9 41 0F B7 F0 41 80 F9 10 72 12',
  validate=function(site)
    return equal(bytes(site+59,11),{0x48,0x8D,0x0C,0x81,0x48,0x81,0xC1,0xC4,0xEF,0,0})
  end,
}
local builderToolItems={316,395,1889,4,1174,2168,31,32}
local builderToolVariants={
  {id=202,slot=1},{id=316,slot=1},{id=317,slot=1},{id=318,slot=1},{id=320,slot=1},
  {id=655},{id=2401},{id=2575},
}
local function ownedBuilderToolItems(state)
  local slots=need(bytes(state+0xB88650,(15+0x163A)*4),
    'Inventory is unavailable.','所持品を取得できません。')
  local equipped=need(bytes(state+0xB8E604,16*4),
    'Equipped tools are unavailable.','装備中の道具を取得できません。')
  local owned={}
  for _,list in ipairs({slots,equipped}) do
    for i=1,#list,4 do
      if list[i+2]~=0 or list[i+3]~=0 then
        owned[list[i]+256*list[i+1]]=true
      end
    end
  end
  return owned
end
function DQB2.obtainAllBuilderTools()
  DQB2.require()
  local state=DQB2.captureBoundary()
  local target=DQB2.needSig('builderToolSet')
  local site=need(grantEntryPoints(),'Frame update is unavailable.','フレーム更新を取得できません。')
  local manager=need(catalogManager(),'Catalog is unavailable.','図鑑データを取得できません。')
  local layout={descriptor=0x450,count=65}
  local tools=need(catalogBase(manager,layout),'Builder tool definitions are unavailable.','ビルダーズ道具の定義を取得できません。')
  local definitions=need(catalogBase(manager,catalogLayouts.definitions),
    'Item definitions are unavailable.','アイテム定義を取得できません。')
  local items=definitions+64+catalogLayouts.definitions.count*4
  local records=tools+64+layout.count*4
  for slot,id in ipairs(builderToolItems) do
    local item=items+48*id
    local index=u32(item)
    need(readBytes(item+0x1F,1)==11 and index and index&gt;0 and index&lt;layout.count and
      u16(records+24*index)==slot,
      'Builder tool definitions do not match.','ビルダーズ道具の定義が一致しません。')
  end
  local stack
  local context=DQB2.resolveCatalog({'definitions','items'})
  for _,variant in ipairs(builderToolVariants) do
    local id=variant.id
    local item=items+48*id
    local index=u32(item)
    local kind=readBytes(item+0x1F,1)
    need(DQB2.catalogItem(context,id) and (variant.slot and kind==11 and index and
      index&gt;0 and index&lt;layout.count and u16(records+24*index)==variant.slot or
      not variant.slot and kind==13),
      'Builder tool variant definitions do not match.','ビルダーズ道具の種類の定義が一致しません。')
    if not stack then
      stack=need(inventoryStackTable(),'Item stack data is unavailable.','スタック情報を取得できません。')
    end
    need(isStackable(id,stack),
      'A builder tool cannot be added to the bag.','ふくろに追加できないビルダーズ道具があります。')
  end
  local count=runFrameCall(site,target,state,[[
label(nextTool)
label(grantTool)
label(writeTool)
label(skipTool)
push rbx
push rsi
sub rsp,30
mov ebx,1
xor esi,esi
nextTool:
movzx edx,word ptr [rdi+rbx*4+B8E604]
test edx,edx
je grantTool
cmp word ptr [rdi+rbx*4+B8E606],0
jne skipTool
jmp writeTool
grantTool:
mov rax,output
movzx edx,word ptr [rax+rbx*2]
writeTool:
lea rcx,[rdi+B7F640]
mov r8d,1
mov r9d,ebx
call target
cmp word ptr [rdi+rbx*4+B8E604],0
je skipTool
inc esi
skipTool:
inc ebx
cmp ebx,9
jb nextTool
mov [box+0C],esi
add rsp,30
pop rsi
pop rbx
]],function(box)
    for slot,id in ipairs(builderToolItems) do
      if not writeSmallInteger(box+0x40+slot*2,id) then return false end
    end
    return true
  end,function()
    return catalogManager()==manager and catalogBase(manager,layout)==tools and
      catalogBase(manager,catalogLayouts.definitions)==definitions
  end,function(box)
    for slot in ipairs(builderToolItems) do
      local item=u16(state+0xB8E604+4*slot)
      local quantity=u16(state+0xB8E606+4*slot)
      if not item or item==0 or not quantity or quantity==0 then return nil end
    end
    local value=readInteger(box+0xC)
    if value and value&gt;=0 and value&lt;=8 then return value end
  end)
  need(count~=nil,'Builder tool acquisition could not be verified.','ビルダーズ道具の取得を確認できませんでした。')
  local owned=ownedBuilderToolItems(state)
  local added=0
  for _,variant in ipairs(builderToolVariants) do
    local id=variant.id
    if not owned[id] then
      need(DQB2.captureBoundary()==state,'Game data changed.','ゲームデータが変化しました。')
      local granted=DQB2.grantBagItem(id,1)
      owned=ownedBuilderToolItems(state)
      need(granted==1 and owned[id],
        'Builder tool could not be added to the bag.','ビルダーズ道具をふくろに追加できませんでした。')
      added=added+1
    end
  end
  DQB2.msg(('Builder tools ready: %d equipment slots. Added or restored: %d equipped, %d in the bag.'):format(#builderToolItems,count,added),
    ('ビルダーズ道具を確認しました。装備枠 %d、装備の追加・復元 %d、ふくろへの追加 %d。'):format(#builderToolItems,count,added))
end

local function mapOwner(global)
  local ui=pointed(global)
  local scene=ui and pointed(ui+0x10)
  return scene and pointed(scene+0x390)
end
local function mapLayers(target,state,stage)
  local displacement=s32(target+0x1E)
  if displacement==nil then return nil end
  local mapping=target+0x22+displacement
  local index=readBytes(mapping+stage,1)
  if not index then return nil end
  local bank=index&gt;=0x20 and 0x895E8C or 0x30A9D0
  index=index%0x20
  if index&gt;=20 then return nil end
  local layers={state+0x10+bank+index*0x20004}
  if stage==3 or stage==0x1A then
    if index~=2 then return nil end
    for layer=20,22 do layers[#layers+1]=state+0x10+bank+layer*0x20004 end
  end
  return layers
end
local function mapFullyRevealed(layers)
  local revealed=true
  for _,address in ipairs(layers) do
    local data=bytes(address,0x20003)
    if not data then return nil end
    if data[0x20003]~=1 then
      revealed=false
    elseif revealed then
      for i=2,0x20000,2 do
        if data[i]&lt;0x80 then revealed=false; break end
      end
    end
  end
  return revealed
end
function DQB2.revealMap()
  DQB2.require()
  local target=DQB2.needSig('mapReveal')
  local global=DQB2.needSig('mapOwner')
  local owner=need(mapOwner(global),'Map is unavailable.','マップを取得できません。')
  local stage=readInteger(owner+0x68)
  local state=need(DQB2.CONFIG.boundary(),'Player state is unavailable.','プレイヤー状態を取得できません。')
  local site=need(grantEntryPoints(),'Frame update is unavailable.','フレーム更新を取得できません。')
  need(stage and stage&gt;0 and stage&lt;=0x1A,'Map is unavailable here.','ここではマップを開放できません。')
  local layers=need(mapLayers(target,state,stage),'Map data is unavailable.','マップのデータを取得できません。')
  local revealed=mapFullyRevealed(layers)
  need(revealed~=nil,'Map data is unreadable.','マップデータを読み取れません。')
  if revealed then
    DQB2.msg('The current island map is already revealed.','現在の島のマップは全開放済みです。')
    return
  end
  local result=runFrameCall(site,target,state,[[
mov rax,[box+18]
mov rax,[rax]
test rax,rax
jz done
mov rax,[rax+10]
test rax,rax
jz done
mov rcx,[rax+390]
cmp rcx,[box+20]
jne done
mov eax,[box+04]
cmp [rcx+68],eax
jne done
call target
mov dword ptr [box+0C],1
]],function(box)
    return writeInteger(box+4,stage) and writeQword(box+0x18,global) and writeQword(box+0x20,owner)
  end,function()
    return mapOwner(global)==owner and readInteger(owner+0x68)==stage
  end,function(box)
    return readInteger(box+0xC)==1
  end,3000)
  need(result and DQB2.CONFIG.boundary()==state and mapOwner(global)==owner and
    readInteger(owner+0x68)==stage and mapFullyRevealed(layers),
    'Map reveal did not complete.','マップ全開放を確認できませんでした。')
  DQB2.msg('Current island map revealed.','現在の島のマップを全開放しました。')
end

function DQB2.itemCanBeGranted(id)
  return isStackable(id)
end

do
    local Picker={}
    DQB2.Picker=Picker
    local function text(v)
      if math.type(v)=='float' then return ('%.6g'):format(v) end
      return v == nil and '' or tostring(v)
    end
    local function normalizeQuery(query)
      return text(query):match('^%s*(.-)%s*$'):lower()
    end

    local function matchesFilter(value, query, numeric)
      if numeric then
        local n = tonumber(value)
        if not n then
          return false
        end
        local number = '[+-]?%d*%.?%d+'
        local lo, hi = query:match('^(' .. number .. ')%s*%-%s*(' .. number .. ')$')
        if lo then
          return n &gt;= tonumber(lo) and n &lt;= tonumber(hi)
        end
        local op, rhs = query:match('^([&lt;&gt;!=]+)%s*(' .. number .. ')$')
        rhs = tonumber(rhs)
        if rhs then
          if op == '&gt;=' then
            return n &gt;= rhs
          elseif op == '&lt;=' then
            return n &lt;= rhs
          elseif op == '&gt;' then
            return n &gt; rhs
          elseif op == '&lt;' then
            return n &lt; rhs
          elseif op == '=' or op == '==' then
            return n == rhs
          elseif op == '!=' then
            return n ~= rhs
          end
        end
        local exact = tonumber(query)
        if exact then
          return n == exact
        end
      end
      return text(value):lower():find(query, 1, true) ~= nil
    end

    function Picker.matches(value, query, numeric)
      local normalized = normalizeQuery(query)
      return normalized == '' or matchesFilter(value, normalized, numeric)
    end

    function Picker.view(rows, columns, queries, sortIndex, ascending)
      local filters = {}
      for i, column in ipairs(columns) do
        local query = normalizeQuery(queries[i])
        if query ~= '' then
          filters[#filters + 1] = {column = column, query = query}
        end
      end

      local shown = {}
      for _, row in ipairs(rows) do
        local include = true
        for _, filter in ipairs(filters) do
          local column = filter.column
          if not matchesFilter(row[column.key], filter.query, column.numeric) then
            include = false
            break
          end
        end
        if include then
          shown[#shown + 1] = row
        end
      end
      local col = columns[sortIndex]
      local sortKey = col.sortKey or col.key
      table.sort(shown, function(a, b)
        local x, y = a[sortKey], b[sortKey]
        if x == nil or y == nil then
          if x ~= y then
            return y == nil
          end
        else
          if not (col.numeric or col.sortKey) then
            x = text(x):lower()
            y = text(y):lower()
          end
          if x ~= y then
            if ascending then
              return x &lt; y
            else
              return x &gt; y
            end
          end
        end
        return a.id &lt; b.id
      end)
      return shown
    end
    function Picker.selectedRows(state,list)
      local rows={}
      local index=-1
      while true do
        local nextIndex=tonumber(sendMessage(list.Handle,0x100c,index,2)) or -1
        if nextIndex&lt;=index or nextIndex&gt;=#state.shown then break end
        rows[#rows+1]=state.shown[nextIndex+1]
        index=nextIndex
      end
      return rows
    end
    function Picker.create(options)
      local state = {
        rows = options.rows,
        columns = options.columns,
        shown = {},
        filters = {},
        sortIndex = options.sortIndex or #options.columns,
        ascending = true,
        lastId = options.current,
        result = nil,
        updating = false,
      }
      local form = options.form
      state.form = form
      form.Name = 'DQB2_EntityPicker101'
      form.Caption = options.title
      form.Position = 'poScreenCenter'
      form.BorderStyle = 'bsSizeable'
      form.ClientWidth = options.multi and 1200 or 840
      form.ClientHeight = math.max(330, math.min(620, 180 + #options.rows * 32))
      form.Font.Name = 'Yu Gothic UI'
      form.Font.Size = 10
      form.Color = 0x252525
      form.Font.Color = 0xf0f0f0
      pcall(function()
        local columnMinimum = 48
        local fitted=false
        for _, col in ipairs(state.columns) do
          if col.fitValues then
            local widths={}
            local widest=form.Canvas.getTextWidth(col.title)
            for _,row in ipairs(options.rows) do
              local value=text(row[col.key])
              if not widths[value] then
                widths[value]=form.Canvas.getTextWidth(value)
                widest=math.max(widest,widths[value])
              end
            end
            local width=math.max(col.width,widest+12)
            fitted=fitted or width&gt;col.width
            col.width=width
          end
          columnMinimum = columnMinimum + (col.flex and 180 or (col.width or 100))
        end
        if fitted and options.multi then form.ClientWidth=math.max(form.ClientWidth,columnMinimum) end
        form.Constraints.MinWidth = options.multi
          and math.max(options.quantity and 900 or 700,columnMinimum+form.Width-form.ClientWidth) or 700
        form.Constraints.MinHeight = 380
      end)
      local list = createListView(form)
      state.list = list
      list.Name = 'DQB2_EntityTable101'
      list.ViewStyle = 'vsReport'
      list.RowSelect = true
      list.HideSelection = false
      list.ReadOnly = true
      list.MultiSelect = options.multi == true and not options.singleSelection
      list.OwnerData = true
      list.Color = 0x252525
      list.Font.Color = 0xf0f0f0
      local headers = {}
      local headerButtons = {}
      state.headerButtons = headerButtons
      list.ShowColumnHeaders = options.multi == true
      for i, col in ipairs(state.columns) do
        local h = list.Columns.add()
        h.Caption = col.title
        headers[i] = h
        local button = createButton(form)
        button.Name = 'DQB2_EntitySort101_' .. i
        button.Caption = col.title
        headerButtons[i] = button
        button.OnClick = function()
          state.sort(i)
        end
        local edit = createEdit(form)
        edit.Name = 'DQB2_EntityFilter101_' .. i
        edit.Text = ''
        edit.Color = 0x353535
        edit.Font.Color = 0xffffff
        edit.ShowHint = not options.noTooltips
        pcall(function()
          edit.TextHint = DQB2.T('Search ' .. col.title, col.title .. '検索')
        end)
        if not options.noTooltips then
          edit.Hint = col.numeric and DQB2.T('Exact value, range10-30, or &gt;=10', '数値、範囲10-30、&gt;=10で検索')
            or DQB2.T('Search this column', 'この列を検索')
        end
        state.filters[i] = edit
      end
      local count = createLabel(form)
      state.count = count
      count.Font.Color = 0xcfcfcf
      local clear = createButton(form)
      state.clear = clear
      clear.Caption = DQB2.T('Clear filters', '検索解除')
      local accept = createButton(form)
      state.accept = accept
      accept.Name = 'DQB2_EntityAccept101'
      accept.Caption = options.accept or DQB2.T('Select', '選択')
      accept.Default = true
      local cancel = createButton(form)
      state.cancel = cancel
      cancel.Name = 'DQB2_EntityCancel101'
      cancel.Caption = DQB2.T('Cancel', 'キャンセル')
      cancel.Cancel = true
      local quantityLabel, quantityEdit, quantityError
      if options.quantity then
        quantityLabel = createLabel(form)
        quantityLabel.Caption = options.batch and DQB2.T('Qty per item','品目ごとの個数') or DQB2.T('Quantity','個数')
        quantityEdit = createEdit(form)
        quantityEdit.Name = 'DQB2_EntityQuantity101'
        quantityEdit.Text = '1'
        quantityEdit.Hint = tostring(options.minimum or 1)..'–'..tostring(options.maximum or 0x7FFFFFFF)
        quantityEdit.ShowHint = true
        pcall(function() quantityLabel.FocusControl = quantityEdit end)
        quantityError = createLabel(form)
        quantityError.Caption = DQB2.T('Enter a valid quantity','有効な個数を入力してください')
        quantityError.Visible = false
        local tabOrder = 0
        for _, filter in ipairs(state.filters) do
          filter.TabOrder = tabOrder
          tabOrder = tabOrder + 1
        end
        for _, control in ipairs({list,quantityEdit,clear,cancel,accept}) do
          control.TabOrder = tabOrder
          tabOrder = tabOrder + 1
        end
      end
      local function readQuantity()
        if not quantityEdit then return end
        local text = quantityEdit.Text
        local value = text:match('^%s*%d+%s*$') and tonumber(text)
        local limit=options.maximum or 0x7FFFFFFF
        if options.selectionLimit then limit=options.selectionLimit(Picker.selectedRows(state,list)) end
        if limit==0 then
          quantityError.Caption=DQB2.T('Selected item is full','選択品目は所持上限です')
        else
          quantityError.Caption=DQB2.T('Enter a quantity from 1 to ','追加個数の範囲 1～')..limit
        end
        if value and value &gt;= (options.minimum or 1) and value &lt;= limit then return value end
      end
      function state.selectedId()
        local item = list.Selected
        local row = item and state.shown[item.Index + 1]
        return row and row.id or nil
      end
      local function updateAccept()
        local selectedCount=options.multi and #Picker.selectedRows(state,list) or 0
        if options.multi then
          count.Caption=DQB2.T('Shown ','表示 ')..#state.shown..' / '..#state.rows
            ..DQB2.T('   Selected ','   選択 ')..selectedCount
          local minimum=quantityEdit and 278 or 155
          clear.Left=math.max(minimum,count.Left+count.Width+16)
        end
        local valid = not quantityEdit or readQuantity() ~= nil
        if quantityError then quantityError.Visible = not valid end
        accept.Enabled = options.alwaysAccept or (valid and ((options.multi and (selectedCount==1 or (options.batch and selectedCount&gt;0)))
          or (not options.multi and state.selectedId()~=nil)))
      end
      if quantityEdit then quantityEdit.OnChange = updateAccept end
      list.OnData = function(sender, item)
        local row = state.shown[item.Index + 1]
        if not row then
          return
        end
        local first = state.columns[1]
        local value = row[first.key]
        item.Caption = value == nil and first.missingText or text(value)
        item.SubItems.clear()
        for i = 2, #state.columns do
          local column = state.columns[i]
          local subValue = row[column.key]
          item.SubItems.add(subValue == nil and column.missingText or text(subValue))
        end
      end
      function state.render()
        if state.updating then
          return
        end
        local selected = state.selectedId()
        if selected ~= nil then
          state.lastId = selected
        end
        local queries = {}
        for i, edit in ipairs(state.filters) do
          queries[i] = edit.Text
        end
        local selectedIds={}
        if options.multi then
          for _,row in ipairs(Picker.selectedRows(state,list)) do selectedIds[row.id]=true end
        end
        state.shown = Picker.view(
          state.rows,
          state.columns,
          queries,
          state.sortIndex,
          state.ascending
        )
        list.beginUpdate()
        state.rendering = true
        local updated, reason = pcall(function()
          list.Items.clear()
          list.Items.Count = #state.shown
          local selectedIndex = -1
          for i, row in ipairs(state.shown) do
            if row.id == state.lastId then
              selectedIndex = i - 1
              break
            end
          end
          list.ItemIndex = selectedIndex
          if options.multi then
            for i,row in ipairs(state.shown) do
              list.Items[i-1].Selected=selectedIds[row.id]==true
            end
          end
          if not options.multi and state.lastId == nil and #state.shown &gt; 0 then
            list.ItemIndex = 0
            state.lastId = state.shown[1].id
          end
        end)
        local ended, endError = pcall(list.endUpdate)
        state.rendering = false
        if not updated then error(reason, 0) end
        if not ended then error(endError, 0) end
        for i, h in ipairs(headers) do
          h.Caption = state.columns[i].title .. (i == state.sortIndex and (state.ascending and ' ↑' or ' ↓') or '')
          headerButtons[i].Caption = h.Caption
        end
        count.Caption = DQB2.T('Shown ', '表示 ') .. #state.shown .. ' / ' .. #state.rows
        updateAccept()
      end
      function state.sort(index)
        if state.sortIndex == index then
          state.ascending = not state.ascending
        else
          state.sortIndex = index
          state.ascending = true
        end
        state.render()
      end
      list.OnColumnClick = function(sender, column)
        for i, h in ipairs(headers) do
          if h == column or h.Caption == column.Caption then
            state.sort(i)
            return
          end
        end
      end
      list.OnSelectItem = function()
        if not state.rendering then updateAccept() end
      end
      local function choose()
        local id = state.selectedId()
        if options.multi then
          local selected=Picker.selectedRows(state,list)
          if options.batch and #selected&gt;0 then
            id={}
            for _,row in ipairs(selected) do id[#id+1]=row.id end
          else
            id=#selected==1 and selected[1].id or nil
          end
        end
        local quantity = readQuantity()
        if id ~= nil and (not quantityEdit or quantity) then
          state.quantity = quantity
          state.result = id
          form.close()
        end
      end
      accept.OnClick = choose
      if not options.confirmOnly then list.OnDblClick = choose end
      if options.back then
        cancel.Caption = DQB2.T('Back','戻る')
        cancel.Cancel = false
      end
      cancel.OnClick = function()
        state.result = nil
        state.back = options.back
        form.close()
      end
      for _, edit in ipairs(state.filters) do
        edit.OnKeyDown = function(sender, key)
          if key == 40 and #state.shown &gt; 0 then
            if list.ItemIndex &lt; 0 then
              list.ItemIndex = 0
            end
            list.setFocus()
            return 0
          end
          return key
        end
      end
      for _, edit in ipairs(state.filters) do
        edit.OnChange = state.render
      end
      clear.OnClick = function()
        state.updating = true
        for _, edit in ipairs(state.filters) do
          edit.Text = ''
        end
        state.updating = false
        state.render()
      end
      list.OnCustomDrawItem = function(sender, item, drawState)
        local row = state.shown[item.Index + 1]
        if not row then
          return false
        end
        local rect = item.displayRect('drBounds')
        local canvas = sender.Canvas
        canvas.Font.Color = 0xffffff
        canvas.Brush.Color = item.Selected and 0x805020 or 0x252525
        canvas.fillRect(rect.Left, rect.Top, sender.Width, rect.Bottom)
        local x = rect.Left
        for i, col in ipairs(state.columns) do
          local width = headers[i].Width
          canvas.textRect(
            { Left = x + 6, Top = rect.Top, Right = x + width - 6, Bottom = rect.Bottom },
            x + 6,
            rect.Top + 2,
            row[col.key] == nil and (col.missingText or '') or text(row[col.key])
          )
          x = x + width
        end
        return false
      end
      local function layout()
        local w, h = form.ClientWidth, form.ClientHeight
        local x = 14
        local available = w - 48
        local fixed, flex = 0, 0
        for _, col in ipairs(state.columns) do
          if col.flex then
            flex = flex + 1
          else
            fixed = fixed + (col.width or 100)
          end
        end
        for i, col in ipairs(state.columns) do
          local width = col.flex and math.max(180, math.floor((available - fixed) / math.max(1, flex)))
            or (col.width or 100)
          headers[i].Width = width
          headers[i].MinWidth = width
          headers[i].MaxWidth = width
          local edit = state.filters[i]
          edit.Left = x
          edit.Top = 54
          edit.Width = width - 6
          edit.Visible = not options.multi or x+width &lt;= w-14
          edit.Height = 28
          x = x + width
          local button = headerButtons[i]
          button.Left = edit.Left
          button.Top = 91
          button.Width = width
          button.Visible = not options.multi
          button.Height = 30
        end
        list.Left = 14
        list.Top = options.multi and 88 or 122
        list.Width = w - 28
        list.Height = h - list.Top - 64
        count.Left = 16
        count.Top = h - 43
        clear.Top = h - 49
        clear.Width = 110
        clear.Height = 33
        if quantityEdit then
          quantityLabel.Left = 16
          quantityLabel.Top = h - 43
          quantityEdit.Left = quantityLabel.Left + quantityLabel.Width + 8
          quantityEdit.Top = h - 49
          quantityEdit.Width = 64
          quantityError.Left = 16
          quantityError.Top = h - 72
          list.Height = list.Height - 12
          count.Left = quantityEdit.Left + quantityEdit.Width + 20
        end
        clear.Left = math.max(quantityEdit and 278 or 155,count.Left+count.Width+16)
        accept.Left = w - (options.back and 136 or 266)
        accept.Top = h - 49
        accept.Width = 118
        accept.Height = 33
        cancel.Left = w - (options.back and 266 or 136)
        cancel.Top = h - 49
        cancel.Width = 118
        cancel.Height = 33
      end
      form.OnResize = layout
      form.OnShow = function()
        state.render()
        layout()
        if options.noTooltips then

          sendMessage(list.Handle,0x1036,0x4400,0)
        end
      end
      return state
    end
    function Picker.show(options, complete)
      local owner=DQB2
      local generation=owner.epoch
      local form=createForm(false)
      owner.itemPicker=form
      options.form=form
      local ok, reason=pcall(function()
        local state=Picker.create(options)
        if options.configure then options.configure(state) end
        form.OnClose=function()
          if owner.itemPicker==form then owner.itemPicker=nil end
          if _G.DQB2==owner and (state.result or state.back) then
            owner.defer(function()
              if _G.DQB2==owner and owner.epoch==generation and not owner.itemPicker then
                complete(state.result,state.back,state.quantity)
              end
            end)
          end
          return caFree
        end
        form.show()
      end)
      if not ok then
        owner.itemPicker=nil
        form.destroy()
        error(reason,0)
      end
    end

end

function DQB2.openItemAdd()
  if DQB2.itemPicker or DQB2.itemGrantBatch then return end
  local context,names,groups=itemCategories()
  local session={catalog=context}
  local boundary=DQB2.captureBoundary()
  local choices={}
  for id=1,0x1FF do
    if groups[id] then
      local label=names[id]
      if not label then
        local fallback=itemCategoryLabels[id-0x100]
        label=fallback and DQB2.T(fallback[1],fallback[2]) or
          (DQB2.T('Category ','分類 ')..('%02X'):format(id-0x100))
      end
      choices[#choices+1]={id=id,label=label}
    end
  end
  local function checkContext()
    need(DQB2.catalogSessionAlive(session) and DQB2.captureBoundary()==boundary,
      'Game data changed while choosing.','選択中にゲームデータが変化しました。')
  end
  local showCategories
  local function selectCategory(category)
    if not category then return end
    checkContext()
    local rows={}
    for _,id in ipairs(groups[category]) do
      local name=DQB2.catalogItem(context,id)
      if name and DQB2.itemCanBeGranted(id) then rows[#rows+1]={id=id,label=name} end
    end
    if #rows==0 then
      DQB2.msg('No items are available.','追加できるアイテムがありません。')
      showCategories()
      return
    end
    DQB2.Picker.show({
        title=DQB2.T('Add items','アイテム追加'),rows=rows,multi=true,batch=true,back=true,
        confirmOnly=true,quantity=true,minimum=1,maximum=999,sortIndex=1,
        accept=DQB2.T('Add selected','選択品を追加'),
        columns={{key='id',title='ID',numeric=true,width=85},
          {key='label',title=DQB2.T('Item','アイテム'),flex=true}},
    },function(ids,back,quantity)
      if back then checkContext(); showCategories(); return end
      if not ids then return end
      checkContext()
      local count=math.tointeger(quantity)
      need(count and count&gt;=1 and count&lt;=999,
        'Quantity must be 1 to 999.','個数には1から999を指定してください。')
      local batch={index=1,added=0}
      DQB2.itemGrantBatch=batch
      local function nextItem()
        if DQB2.itemGrantBatch~=batch then return end
        local ok=DQB2.userRun(function()
          checkContext()
          if DQB2.pendingGrant then return end
          local success,actual=pcall(DQB2.grantBagItem,ids[batch.index],count)
          if success and actual==count then batch.added=batch.added+1
          elseif not success then print(tostring(actual)) end
          batch.index=batch.index+1
        end)
        if ok and not DQB2.pendingGrant and batch.index&lt;=#ids then
          DQB2.defer(nextItem)
        else
          DQB2.itemGrantBatch=nil
          DQB2.msg(('Items added: %d/%d.'):format(batch.added,#ids),
            ('追加できた品目: %d/%d。'):format(batch.added,#ids))
        end
      end
      DQB2.defer(nextItem)
    end)
  end
  showCategories=function()
    DQB2.Picker.show({
      title=DQB2.T('Add items','アイテム追加'),rows=choices,
      columns={{key='label',title=DQB2.T('Category','カテゴリ'),flex=true}},
    },selectCategory)
  end
  showCategories()
end

local steamAchievementExports={
  pipe={0x8BF0,'8b05b2a60300c3cc'}, user={0x8C00,'8b05a6a60300c3cc'},
  client={0x9CE0,'488b0559950300c3'}, utils={0x5250,'488b0148ff6048cc'},
  interface={0x9DB0,'4881ec2804000044'}, count={0x5360,'488b0148ff6070cc'},
  name={0x52B0,'488b0148ff6078cc'}, unlock={0x5220,'488b0148ff6038cc'},
  status={0x5230,'488b0148ff6030cc'}, store={0x52C0,'488b0148ff6050cc'},
}
function DQB2.steamAchievementContext()
  DQB2.require()
  local module
  for _,candidate in ipairs(enumModules(DQB2.pid)) do
    if candidate.Name:lower()=='steam_api64.dll' then module=candidate; break end
  end
  local pe=DQB2.pe(need(module,'Steam API is unavailable.','Steam API を取得できません。'))
  need(pe.ts==0x5C6B2CF7 and pe.size==0x4A000 and pe.machine==0x8664,
    'Steam API build is unverified.','Steam API のビルドが一致しません。')
  for _,entry in pairs(steamAchievementExports) do
    local expected=entry[2]:gsub('%x%x',function(p) return string.char(tonumber(p,16)) end)
    need(grantBytes(pe.base+entry[1],#expected)==expected,
      'Steam export bytes changed.','Steam API の命令が変わりました。')
  end
  local function call(name,...)
    DQB2.require()
    local result=executeCodeEx(0,1500,pe.base+steamAchievementExports[name][1],...)
    return need(type(result)=='number' and result,'Steam API call failed.','Steam API の呼び出しに失敗しました。')
  end
  local pipe,user,client=call('pipe'),call('user'),call('client')
  need(pipe~=0 and user~=0 and client~=0,'Steam is not ready.','Steam の準備ができていません。')
  local utils=call('utils',client,pipe,{type=3,value='SteamUtils009'})
  need(utils~=0 and (call('utils',utils) &amp; 0xffffffff)==1072420,
    'Steam App ID is not 1072420.','Steam App ID が 1072420 ではありません。')
  local stats=call('interface',user,{type=3,value='STEAMUSERSTATS_INTERFACE_VERSION011'})
  need(stats~=0,'Steam user stats are unavailable.','Steam 実績情報を取得できません。')
  local count=call('count',stats) &amp; 0xffffffff
  need(count==31,'Unexpected achievement count.','実績数が一致しません。')
  local ids,seen={},{}
  for i=0,count-1 do
    local address=call('name',stats,i)
    local id=address~=0 and readString(address,32,false)
    need(id and id:match('^TRP%d+$') and not seen[id],
      'Invalid achievement ID.','実績IDが無効か重複しています。')
    ids[#ids+1]=id
    seen[id]=true
  end
  return {stats=stats,ids=ids,call=call}
end
function DQB2.unlockSteamAchievements()
  local context=DQB2.steamAchievementContext()
  local buffer=need(allocateMemory(16),'Cannot allocate Steam status buffer.','Steam 実績ステータス用の領域を確保できません。')
  local statusInFlight=false
  local function unlocked(id)
    DQB2.require()
    statusInFlight=true
    local status=context.call('status',context.stats,{type=3,value=id},buffer)
    statusInFlight=false
    need((status &amp; 0xff)~=0,
      'Steam achievement status is unavailable.','Steam 実績の状態を取得できません。')
    local state=readBytes(buffer,1)
    need(state==0 or state==1,'Invalid Steam achievement status.','Steam 実績の状態が不正です。')
    return state==1
  end
  local ok,result=pcall(function()
    local pending={}
    for _,id in ipairs(context.ids) do
      if not unlocked(id) then pending[#pending+1]=id end
    end
    local changed=0
    for _,id in ipairs(pending) do
      if (context.call('unlock',context.stats,{type=3,value=id}) &amp; 0xff)~=0 then changed=changed+1 end
    end
    local saved=changed==0 or (context.call('store',context.stats) &amp; 0xff)~=0
    local verified=#context.ids-#pending
    for _,id in ipairs(pending) do if unlocked(id) then verified=verified+1 end end
    return {verified=verified,changed=changed,failed=#pending-changed,saved=saved}
  end)
  if not statusInFlight then deAlloc(buffer) end
  if not ok then error(result,0) end
  local en,ja='',''
  if not result.saved then en,ja=' Steam save request failed.',' Steam への保存要求に失敗しました。' end
  DQB2.msg(('Steam achievements: %d/%d unlocked, %d newly accepted, %d failed.%s'):format(result.verified,#context.ids,result.changed,result.failed,en),
    ('Steam 実績 %d/%d 件解除済み、今回の受付 %d 件、失敗 %d 件。%s'):format(result.verified,#context.ids,result.changed,result.failed,ja))
end


local xpCompare={0x40,0x38,0xB0,0xC8,0x75,0x06,0x00}
local function xpValidator(instruction,eu,asia)
  local sites={['dqb2_eu.exe']=eu,['dqb2_as.exe']=asia}
  return function(address)
    local name=DQB2.mainName:lower()
    return (name==baseline.name or sites[name]==address-DQB2.mainBase) and
      equal(bytes(address,#instruction),instruction)
  end
end
local xpSite=xpValidator(xpCompare,0x2A6452,0x2A5F92)
DQB2.SIGS.enemyXp={
  p='8B DE 48 85 FF 74 04 0F B7 5F 38 40 38 B0 C8 75 06 00 74 4E 48 8B 51 60 B8 9F 86 01 00',
  off=11,validate=xpSite,
}
local function hookCaveIdle(state,siteSize)
  if not state.patch or #state.patch&lt;5 or state.patch[1]~=0xE9 then return false end
  local displacement=string.unpack('&lt;i4',string.char(table.unpack(state.patch,2,5)))
  local cave=state.addr+5+displacement
  local api=executeCodeLocalEx
  local buffer=api('kernel32.VirtualAlloc',0,4096,0x3000,4)
  if not buffer or buffer==0 then return false end
  local ok,clear=pcall(grantThreadsClear,state.addr,cave,buffer,siteSize or #state.orig)
  api('kernel32.VirtualFree',buffer,0,0x8000)
  return ok and clear
end
DQB2.HOOKS.hunger.inline=nil
DQB2.HOOKS.hunger.quiesce=hookCaveIdle
DQB2.HOOKS.hunger.aa=function()
  local site=DQB2.needSig('hunger')
  local owner=site+7+need(s32(site+3),'Unreadable displacement.','変位を読み取れません。')
  return ([[
[ENABLE]
alloc(dqb2HungerCode,4096,$SITE)
label(dqb2HungerExit)
dqb2HungerCode:
  mov rax,@OWNER@
  mov rax,[rax]
  test rax,rax
  je dqb2HungerExit
  mov rax,[rax+60]
  test rax,rax
  je dqb2HungerExit
  mov word ptr [rax+954CC],#10000
dqb2HungerExit:
  ret
$SITE:
  jmp dqb2HungerCode
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2HungerCode)
]]):gsub('@OWNER@',hex(owner))
end

DQB2.HOOKS.enemyXp={
  sig='enemyXp',len=7,validate=xpSite,quiesce=hookCaveIdle,
  aa=[[
[ENABLE]
alloc(dqb2XpCode,4096,$SITE)
label(dqb2EnemyXpFactor)
label(dqb2XpContinue)
label(dqb2XpResume)
registersymbol(dqb2EnemyXpFactor)
dqb2XpCode:
  push rdx
  mov edx,[dqb2EnemyXpFactor]
  cmp edx,1
  jl dqb2XpContinue
  imul ebx,edx
  jno dqb2XpContinue
  mov ebx,7FFFFFFF
dqb2XpContinue:
  pop rdx
  cmp byte ptr [rax+675C8],sil
  jmp dqb2XpResume
align 4
dqb2EnemyXpFactor:
  dd 2
$SITE:
  jmp dqb2XpCode
  nop 2
dqb2XpResume:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2EnemyXpFactor)
dealloc(dqb2XpCode)
]],
}
local function xpDisplayHook(name,instruction,pattern,destination,eu,asia)
  local validate=xpValidator(instruction,eu,asia)
  DQB2.SIGS[name]={p=pattern,off=0,validate=validate}
  DQB2.HOOKS[name]={
    sig=name,len=#instruction,validate=validate,
    quiesce=function(state) return hookCaveIdle(state,#instruction) end,
    aa=([[
[ENABLE]
alloc(dqb2XpDisplayCode,4096,$SITE)
label(dqb2XpDisplayContinue)
label(dqb2XpDisplayResume)
dqb2XpDisplayCode:
  $ORIG
  pushfq
  push rdx
  mov rdx,dqb2EnemyXpFactor
  mov edx,[rdx]
  cmp edx,1
  jl dqb2XpDisplayContinue
  imul %s,edx
  jno dqb2XpDisplayContinue
  mov %s,7FFFFFFF
dqb2XpDisplayContinue:
  pop rdx
  popfq
  jmp dqb2XpDisplayResume
$SITE:
  jmp dqb2XpDisplayCode
dqb2XpDisplayResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2XpDisplayCode)
]]):format(destination,destination),
  }
end
xpDisplayHook('enemyXpDisplayReward',{0x44,0x0F,0xB7,0x7A,0x38},
  '44 0F B7 7A 38 EB 03 44 8B FF E8 ?? ?? ?? ?? 84 C0 75 55','r15d',0x12D778,0x12D538)
xpDisplayHook('enemyXpDisplayBattle',{0x44,0x0F,0xB7,0x42,0x38},
  '44 0F B7 42 38 EB 03 45 33 C0 48 8B 05 ?? ?? ?? ?? 33 D2','r8d',0x5E9C9E,0x5E84CE)
local xpHooks={'enemyXp','enemyXpDisplayReward','enemyXpDisplayBattle'}
DQB2.F.enemyXp={boundary=false,hooks=xpHooks}
local combatBuilds={
  ['dqb2.exe']={player=0xE77DC0,monster=0xE78648,critical=0x119EE5,oneHit=0x2F9ED0,stealthSight=0x272800,stealthTarget=0x2ADC87},
  ['dqb2_eu.exe']={player=0xE87E60,monster=0xE886E8,critical=0x11A315,oneHit=0x2FA6C0,stealthSight=0x272F30,stealthTarget=0x2AE3C7},
  ['dqb2_as.exe']={player=0xE81E20,monster=0xE826A8,critical=0x11A0F5,oneHit=0x2FA150,stealthSight=0x272A80,stealthTarget=0x2ADF07},
}
combatMethod=function(tableOffset,slot)
  local method=readPointer(DQB2.mainBase+tableOffset+slot)
  if not method or method&lt;DQB2.mainBase or method+5&gt;DQB2.mainBase+DQB2.mainPE.size then return nil end
  local opcode=readBytes(method,1)
  if opcode==nil then return nil end
  local body=method
  if opcode==0xE9 then
    local displacement=s32(method+1)
    if displacement==nil then return nil end
    body=method+5+displacement
  end
  for _,section in ipairs(DQB2.mainPE.sections) do
    if section.execute and body&gt;=section.first and body+19&lt;=section.last then return body end
  end
end
local function playerMethodOwner(build,slot,instruction)
  local method=combatMethod(build.player,slot)
  local tail=method and bytes(method+7,(#instruction+1)//3)
  if not tail or db(tail)~=instruction or not equal(bytes(method,3),{0x48,0x8B,0x05}) then return nil end
  local displacement=s32(method+3)
  if not displacement then return nil end
  local owner=method+7+displacement
  for _,section in ipairs(DQB2.mainPE.sections) do
    if not section.execute and owner&gt;=section.first and owner+8&lt;=section.last then return owner end
  end
end
local function playerHpOwner(build)
  return playerMethodOwner(build,0x2B0,'48 8B 48 60 0F B7 81 C4 54 09 00 C3')
end
local playerEditorGetters={
  {0x2B8,'B9 E7 03 00 00 48 8B 50 60 8B C1 44 0F B7 8A C6 54 09 00 44 0F B7 82 C8 54 09 00'},
  {0x2E8,'48 8B 48 60 0F B7 81 CC 54 09 00 C3'},
  {0x318,'48 8B 48 60 F3 0F 10 81 D4 54 09 00 C3'},
  {0x328,'48 8B 48 60 0F B7 81 D8 54 09 00 66 0F 6E C0 0F 5B C0 C3'},
}
DQB2.CONFIG.boundary=function()
  local build=DQB2.mainName and combatBuilds[DQB2.mainName:lower()]
  local owner=build and playerHpOwner(build)
  if not owner then return nil end
  for _,getter in ipairs(playerEditorGetters) do
    if playerMethodOwner(build,getter[1],getter[2])~=owner then return nil end
  end
  local root=pointed(owner)
  local state=root and pointed(root+0x60)
  local hunger=state and u16(state+0x954CC)
  if hunger and hunger&lt;=10000 then return state end
end
local function combatContext()
  local build=combatBuilds[DQB2.mainName:lower()]
  local owner=build and playerHpOwner(build)
  if not owner then return nil end
  local monsterHp=combatMethod(build.monster,0x2B0)
  if monsterHp and equal(bytes(monsterHp,8),{0x0F,0xB7,0x81,0x4A,0x0E,0,0,0xC3}) then return build,owner end
end
local function combatAssembly(script)
  return function()
    local build,owner=combatContext()
    need(build,'Combat layout does not match.','戦闘処理の構造が一致しません。')
    return (script:gsub('@PLAYER@',hex(DQB2.mainBase+build.player))
      :gsub('@MONSTER@',hex(DQB2.mainBase+build.monster)):gsub('@OWNER@',hex(owner)))
  end
end

DQB2.SIGS.motionRegistry={
  p='81 F9 F6 01 00 00 77 ?? 48 8B 05 ?? ?? ?? ?? 48 8B 4C C8 58 48 85 C9 74 ?? 48 8B 01 FF 50 10',
  off=8,kind='rip',disp=3,length=7,
  validate=function(address)
    for _,section in ipairs(DQB2.mainPE.sections) do
      if not section.execute and address&gt;=section.first and address+8&lt;=section.last then return true end
    end
    return false
  end,
}
playerCombatActor=function()
  local build=combatBuilds[DQB2.mainName:lower()]
  if not build then return nil end
  local global=DQB2.resolveSig('motionRegistry')
  local registry=global and pointed(global)
  local node=registry and pointed(registry+0x58)
  local actor=node and pointed(node+0x10)
  if actor and pointed(actor)==DQB2.mainBase+build.player then return actor,node,build end
end
local function combatField(en,ja,offset,slot,delta,expected,baseOffset)
  return {en=en,ja=ja,kind='integer',strict=true,min=0,max=9999,
    available=function(c)
      if not c.actor then return false end
      local vtable=pointed(c.actor)
      local getter=vtable and combatMethod(vtable-DQB2.mainBase,slot)
      local actual=getter and bytes(getter+delta,(#expected+1)//3)
      return actual~=nil and db(actual)==expected
    end,
    read=function(c)
      local stored=c.actor and u16(c.actor+offset)
      local base=c.actor and (not baseOffset and 0 or u16(c.actor+baseOffset))
      if stored and base then return (stored+base) &amp; 0xFFFF end
    end,
    write=function(c,value)
      local base=c.actor and (not baseOffset and 0 or u16(c.actor+baseOffset))
      return base and value&gt;=base and writeSmallInteger(c.actor+offset,value-base)==true
    end}
end
table.insert(DQB2.EDITORS.player.fields,combatField('Attack','攻撃力',0xFB0,0x1A8,0xB7,'0F B7 84 5F B0 0F 00 00'))
table.insert(DQB2.EDITORS.player.fields,combatField('Defence','守備力',0xFB6,0x1C0,0,'0F B7 81 B6 0F 00 00 C3'))

table.insert(DQB2.EDITORS.member.fields,combatField('Attack','攻撃力',0x1112,0x1A8,0,
  '48 63 C2 0F B7 84 41 12 11 00 00 66 03 81 4C 0E 00 00 C3',0xE4C))
table.insert(DQB2.EDITORS.member.fields,combatField('Defence','守備力',0x1118,0x1C0,0,
  '0F B7 81 18 11 00 00 66 03 81 50 0E 00 00 C3',0xE50))

local function playerMotionMethod(slot)
  local _,node=playerCombatActor()
  if not node then return nil end
  local motion=node+0x180
  local info=pointed(motion+8)
  local vtable=pointed(motion)
  if not info or u32(info+0x20)~=0 or not vtable then return nil end
  local jump=slot==0xD8 and DQB2.hooks.jumpFactor
  local method=jump and pointed(vtable+slot)==jump.addr and jump.addr or combatMethod(vtable-DQB2.mainBase,slot)
  for _=1,2 do
    if not method or (jump and method==jump.addr) or readBytes(method,1)~=0xE9 then break end
    local offset=s32(method+1)
    if not offset then return nil end
    method=method+5+offset
  end
  return method,vtable
end
local function playerMotionTable(site,slot,offset)
  local method,vtable=playerMotionMethod(slot)
  if method and method+offset==site then return vtable end
end
local moveSpeedBytes={0x48,0x8B,0x57,0x50,0x48,0x8B,0xC2}
local moveSpeedCapBytes={0x0F,0x2F,0xC8,0x73,0x21}
local function motionSite(address,instruction,offset)
  return equal(bytes(address,#instruction),instruction) and playerMotionTable(address,0xA0,offset)~=nil
end
local function moveSpeedSite(address)
  return motionSite(address,moveSpeedBytes,0xD2B)
end
local function moveSpeedCapSite(address)
  return motionSite(address,moveSpeedCapBytes,0x1027)
    and equal(bytes(address+0x26,5),{0xF3,0x0F,0x11,0x46,0x10})
end
DQB2.SIGS.moveSpeed={
  resolve=function()
    local method=playerMotionMethod(0xA0)
    return method and {method+0xD2B}
  end,
  validate=moveSpeedSite,
}
DQB2.SIGS.moveSpeedCap={
  resolve=function()
    local method=playerMotionMethod(0xA0)
    return method and {method+0x1027}
  end,
  validate=moveSpeedCapSite,
}
DQB2.HOOKS.moveSpeed={
  sig='moveSpeed',len=#moveSpeedBytes,validate=moveSpeedSite,quiesce=hookCaveIdle,
  aa=function()
    local vtable=need(playerMotionTable(DQB2.needSig('moveSpeed'),0xA0,0xD2B),
      'Player movement is unavailable.','プレイヤーの移動処理を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2MoveSpeedCode,4096,$SITE)
label(dqb2MoveSpeedFactor)
label(dqb2MoveSpeedNext)
label(dqb2MoveSpeedResume)
registersymbol(dqb2MoveSpeedFactor)
dqb2MoveSpeedCode:
  pushfq
  push rax
  mov rax,@MOTION@
  cmp [rdi],rax
  jne dqb2MoveSpeedNext
  mov eax,[dqb2MoveSpeedFactor]
  test eax,eax
  jle dqb2MoveSpeedNext
  cmp eax,7F800000
  jae dqb2MoveSpeedNext
  mulss xmm8,[dqb2MoveSpeedFactor]
dqb2MoveSpeedNext:
  pop rax
  popfq
  $ORIG
  jmp dqb2MoveSpeedResume
align 4
dqb2MoveSpeedFactor:
  dd (float)2
$SITE:
  jmp dqb2MoveSpeedCode
  $NOP
dqb2MoveSpeedResume:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2MoveSpeedFactor)
dealloc(dqb2MoveSpeedCode)
]]):gsub('@MOTION@',hex(vtable))
  end,
}
DQB2.HOOKS.moveSpeedCap={
  sig='moveSpeedCap',len=#moveSpeedCapBytes,validate=moveSpeedCapSite,quiesce=hookCaveIdle,
  aa=function()
    local site=DQB2.needSig('moveSpeedCap')
    local vtable=need(playerMotionTable(site,0xA0,0x1027),
      'Player movement is unavailable.','プレイヤーの移動処理を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2MoveCapCode,4096,$SITE)
label(dqb2MoveCapOriginal)
label(dqb2MoveCapStore)
label(dqb2MoveCapResume)
dqb2MoveCapCode:
  push rax
  mov rax,@MOTION@
  cmp [rdi],rax
  jne dqb2MoveCapOriginal
  mov rax,dqb2MoveSpeedFactor
  cmp dword ptr [rax],0
  jle dqb2MoveCapOriginal
  cmp dword ptr [rax],7F800000
  jae dqb2MoveCapOriginal
  mulss xmm1,[rax]
  pop rax
  comiss xmm1,xmm0
  jae dqb2MoveCapStore
  movaps xmm0,xmm1
  jmp dqb2MoveCapStore
dqb2MoveCapOriginal:
  pop rax
  comiss xmm1,xmm0
  jae dqb2MoveCapStore
  jmp dqb2MoveCapResume
dqb2MoveCapStore:
  jmp @STORE@
$SITE:
  jmp dqb2MoveCapCode
dqb2MoveCapResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2MoveCapCode)
]]):gsub('@MOTION@',hex(vtable)):gsub('@STORE@',hex(site+0x26))
  end,
}
local ladderStepBytes={0xF3,0x0F,0x11,0x7C,0x24,0x24}
local function ladderStepSite(site)
  if not equal(bytes(site,#ladderStepBytes),ladderStepBytes) or readBytes(site+34,1)~=0xE8 then return false end
  local displacement=s32(site+35)
  local target=displacement and site+39+displacement
  if target and readBytes(target,1)==0xE9 then
    local jump=s32(target+1)
    target=jump and target+5+jump
  end
  return target~=nil and equal(bytes(target,17),
    {0x48,0x8B,0xC4,0x55,0x41,0x56,0x48,0x81,0xEC,0x98,0,0,0,0x83,0x79,0x10,0x01})
end
DQB2.SIGS.ladderStep={
  p='F3 0F 11 7C 24 24 C7 44 24 20 00 00 00 00 48 C7 44 24 28 00 00 00 00 48 8B 48 50 48 81 C1 90 52 00 00 E8',
  validate=ladderStepSite,
}
DQB2.HOOKS.ladderStep={
  sig='ladderStep',len=#ladderStepBytes,validate=ladderStepSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2LadderStep,4096,$SITE)
label(dqb2LadderStepOriginal)
label(dqb2LadderStepResume)
dqb2LadderStep:
  pushfq
  push rax
  mov rax,@PLAYER@
  cmp [rdi],rax
  jne dqb2LadderStepOriginal
  cmp byte ptr [rdi+B38],0C
  jne dqb2LadderStepOriginal
  mov rax,dqb2MoveSpeedFactor
  cmp dword ptr [rax],0
  jle dqb2LadderStepOriginal
  cmp dword ptr [rax],7F800000
  jae dqb2LadderStepOriginal
  mulss xmm7,[rax]
dqb2LadderStepOriginal:
  pop rax
  popfq
  $ORIG
  jmp dqb2LadderStepResume
$SITE:
  jmp dqb2LadderStep
  $NOP
dqb2LadderStepResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2LadderStep)
]]),
}
DQB2.F.moveSpeed={boundary=false,hooks={'moveSpeed','moveSpeedCap','ladderStep'},
  prepare=function() DQB2.needSig('motionRegistry') end,
}

local function hammerExecutable(address,length)
  for _,section in ipairs(DQB2.mainPE.sections) do
    if section.execute and address&gt;=section.first and address+length&lt;=section.last then return true end
  end
  return false
end
local function hammerNativeCall(address,body)
  local entry=bytes(address,5)
  if not entry or entry[1]~=0xE8 then return false end
  local target=address+5+string.unpack('&lt;i4',string.char(table.unpack(entry,2,5)))
  if not hammerExecutable(target,5) then return false end
  local thunk=bytes(target,5)
  if thunk and thunk[1]==0xE9 then
    target=target+5+string.unpack('&lt;i4',string.char(table.unpack(thunk,2,5)))
  end
  return hammerExecutable(target,#body) and equal(bytes(target,#body),body)
end
local function hammerBatchWorkerSite(address)
  return hammerNativeCall(address,{0xF7,0x82,0xA0,0,0,0,0,0,3,0,0x4D,0x8B,0xC8,0x74,0x5D,0x0F,0xB7,0x82,0xA6,0,0,0,0xFF,0xC8})
end
DQB2.SIGS.hammerBatchWorker={p='48 8D 8E E1 7A 03 00 4C 8B C7 48 8B D3 E8 ?? ?? ?? ??',off=0xD,validate=hammerBatchWorkerSite}
local function hammerBatchMainSite(address)
  return equal(bytes(address,12),{0x48,0x8B,0x06,0x48,0x8B,0xCE,0x48,0x03,0xD7,0xFF,0x50,0x08})
end
DQB2.SIGS.hammerBatchMain={p='48 69 F8 D8 01 00 00 48 8B 06 48 8B CE 48 03 D7 FF 50 08',off=0x7,validate=hammerBatchMainSite}
local function hammerBatchExpirySite(address)
  return equal(bytes(address,8),{0xF3,0x0F,0x11,0x81,0xD4,0x83,0x00,0x00})
end
DQB2.SIGS.hammerBatchExpiry={p='F3 0F 5C C2 F3 0F 11 81 D4 83 00 00 40 38 B1 19 84 00 00',off=0x4,validate=hammerBatchExpirySite}
DQB2.SIGS.hammerBatchNative={
  p='40 53 55 56 41 55 41 56 41 57 48 83 EC 38 48 8B 05 ?? ?? ?? ?? 49 8B D8 F3 0F 10 8A 88 00 00 00',
  validate=function(address)
    return equal(bytes(address,14),{0x40,0x53,0x55,0x56,0x41,0x55,0x41,0x56,0x41,0x57,0x48,0x83,0xEC,0x38})
  end,
}
local function hammerBatchAddresses(assembly)
  local enumerator=DQB2.needSig('hammerBatchNative')
  local world=enumerator+0x15+string.unpack('&lt;i4',string.char(table.unpack(bytes(enumerator+0x11,4))))
  local call=assembly:find('@DISPATCH@',1,true) and DQB2.needSig('hammerBatchWorker')
  local dispatcher=call and (call+5+string.unpack('&lt;i4',string.char(table.unpack(bytes(call+1,4))))) or 0
  return (assembly:gsub('@WORLD@',hex(world)):gsub('@ENUM@',hex(enumerator)):gsub('@DISPATCH@',hex(dispatcher)))
end
DQB2.HOOKS.hammerBatchWorker={
  sig='hammerBatchWorker',len=5,validate=hammerBatchWorkerSite,
  quiesce=function(state)
    local busy=getAddressSafe('dqb2HammerWorkerBusy')
    return busy~=nil and readInteger(busy)==0 and hookCaveIdle(state) and readInteger(busy)==0
  end,
  aa=function()
    return hammerBatchAddresses([[
[ENABLE]
alloc(dqb2HammerBatchWorkerCode,4096,$SITE)
label(dqb2HammerWorkerBusy)
registersymbol(dqb2HammerWorkerBusy)
alloc(dqb2HammerSlots,32768)
label(dqb2HammerRouteMain)
label(dqb2HammerRouteExpiry)
label(dqb2HammerRouteWorker)
label(dqb2HammerWorkerStock)
label(dqb2HammerWorkerResume)
label(dqb2HammerWorkerEnd)
registersymbol(dqb2HammerSlots)
registersymbol(dqb2HammerRouteMain)
registersymbol(dqb2HammerRouteExpiry)
dqb2HammerBatchWorkerCode:
  lock inc dword ptr [dqb2HammerWorkerBusy]
  sub rsp,60
  mov [rsp+40],rcx
  mov [rsp+48],rdx
  mov [rsp+50],r8
  mov rax,@WORLD@
  mov rax,[rax]
  test rax,rax
  je dqb2HammerWorkerStock
  mov r10,[rax+88]
  test r10,r10
  je dqb2HammerWorkerStock
  add r10,30
  mov [rsp+20],r10
  mov r10,dqb2HammerSlots
  mov [rsp+28],r10
  mov r10,[rax+38]
  mov [rsp+30],r10
  mov r10,@ENUM@
  mov [rsp+38],r10
  mov r10,@WIDTH@
  mov [rsp+58],r10
  lea r11,[rsp+20]
  call dqb2HammerRouteWorker
  test eax,eax
  jne dqb2HammerWorkerEnd
dqb2HammerWorkerStock:
  mov rcx,[rsp+40]
  mov rdx,[rsp+48]
  mov r8,[rsp+50]
  mov rax,@DISPATCH@
  call rax
dqb2HammerWorkerEnd:
  lock dec dword ptr [dqb2HammerWorkerBusy]
  add rsp,60
  jmp dqb2HammerWorkerResume
dqb2HammerRouteMain:
  db EB 07
dqb2HammerRouteExpiry:
  db EB 63
dqb2HammerRouteWorker:
  db E9 9F 00 00 00 0F B7 41 3E 2D 31 6D 00 00 83 F8 01 77 4D 48 83 EC 48 48
  db 89 4C 24 20 48 89 54 24 28 4C 89 44 24 30 4C 89 D2 4D 89 D8 E8 7F 01 00
  db 00 48 85 C0 74 0F 48 8B 4C 24 20 8B 49 38 3B 48 2C 74 02 31 C0 48 8B 4C
  db 24 20 48 8B 54 24 28 4C 8B 44 24 30 49 89 C1 48 83 C4 48 E9 B9 0D 00 00
  db 41 FF E0 0F B7 41 3E 2D 31 6D 00 00 83 F8 01 77 30 48 83 EC 28 48 89 4C
  db 24 20 E8 31 01 00 00 48 85 C0 74 19 48 8B 4C 24 20 8B 49 38 3B 48 2C 75
  db 0C 48 89 C1 48 83 C4 28 E9 1F 0B 00 00 48 83 C4 28 31 C0 C3 0F B7 42 1E
  db 2D 31 6D 00 00 83 F8 01 0F 87 F7 00 00 00 F7 82 A0 00 00 00 00 00 03 00
  db 0F 84 E7 00 00 00 66 83 BA A6 00 00 00 01 0F 85 D9 00 00 00 53 56 57 41
  db 54 41 55 48 83 EC 30 48 89 CB 48 89 D6 4C 89 C7 4D 89 DC 48 8D 4A E0 48
  db 8D 81 F8 00 00 00 48 39 F8 0F 85 A0 00 00 00 49 8B 14 24 4D 8B 44 24 08
  db E8 A3 00 00 00 48 85 C0 0F 84 89 00 00 00 49 89 C5 48 89 F1 48 89 C2 E8
  db CC 00 00 00 85 C0 75 5F 49 8B 44 24 10 48 85 C0 74 6D 48 8B 90 30 02 34
  db 08 48 85 D2 74 61 44 0F BF 80 38 F1 B7 08 44 0F BF 88 3A F1 B7 08 0F B7
  db 82 08 20 00 00 89 44 24 20 0F B7 82 0A 20 00 00 89 44 24 28 4C 89 E9 48
  db 89 F2 4D 8B 54 24 38 E8 9B 00 00 00 8B 4E 18 41 89 4D 2C 85 C0 75 08 41
  db C7 45 28 03 00 00 00 48 89 D9 48 89 F2 49 89 F8 4D 89 E9 4D 8B 54 24 18
  db E8 C2 08 00 00 EB 02 31 C0 48 83 C4 30 41 5D 41 5C 5F 5E 5B C3 31 C0 C3
  db 48 89 C8 48 29 D0 72 20 48 3D 00 20 84 00 73 18 31 D2 41 B9 20 84 00 00
  db 49 F7 F1 48 85 D2 75 08 48 C1 E0 07 4C 01 C0 C3 31 C0 C3 B8 01 00 00 00
  db F0 0F C1 02 FF C0 89 41 18 66 C7 41 1E 31 6D C3 31 C0 0F B7 41 1E 2D 31
  db 6D 00 00 83 F8 01 77 0C 44 8B 41 18 44 3B 42 2C 0F 94 C0 C3 31 C0 C3 53
  db 56 57 48 81 EC E0 00 00 00 48 89 CB 48 89 D6 4C 89 D7 C7 43 28 00 00 00
  db 00 31 C0 81 3F 00 00 80 3F 72 0A 81 7F 04 00 00 80 3F 0F 93 C0 83 F8 01
  db 75 0A 81 7F 08 00 00 80 3F 0F 93 C0 8B 17 3B 57 08 74 03 83 C8 02 89 43
  db 64 44 89 44 24 48 44 89 4C 24 4C 8B 84 24 20 01 00 00 89 44 24 20 8B 84
  db 24 28 01 00 00 89 44 24 28 48 89 F1 48 8D 53 48 E8 A5 06 00 00 85 C0 0F
  db 84 C8 00 00 00 48 89 D9 48 89 F2 44 8B 44 24 48 44 8B 4C 24 4C F6 43 64
  db 02 74 0A 49 89 FA E8 EF 03 00 00 EB 05 E8 5B 02 00 00 48 89 F1 48 8D 94
  db 24 C8 00 00 00 49 89 F8 E8 9B 00 00 00 F6 43 64 02 75 16 48 89 F1 48 8D
  db 94 24 C8 00 00 00 E8 73 01 00 00 85 C0 74 76 EB 1A 48 89 D9 48 8D 94 24
  db C8 00 00 00 44 8B 44 24 48 44 8B 4C 24 4C E8 49 05 00 00 48 8D 4C 24 48
  db 48 8D 53 30 44 8B 44 24 48 44 8B 4C 24 4C E8 17 06 00 00 85 C0 74 3E 31
  db C9 8B 44 CB 48 3B 44 CB 30 0F 4C 44 CB 30 89 44 CB 48 8B 44 CB 4C 3B 44
  db CB 34 0F 4F 44 CB 34 89 44 CB 4C FF C1 83 F9 03 72 D7 C7 43 60 FF FF FF
  db FF C7 43 28 01 00 00 00 B8 01 00 00 00 48 81 C4 E0 00 00 00 5F 5E 5B C3
  db 41 B9 00 00 00 3F 66 41 0F 6E E1 41 B9 00 00 80 47 66 41 0F 6E E9 F3 41
  db 0F 10 18 41 8B 00 41 3B 40 08 74 10 F3 41 0F 5F 58 08 F3 0F 58 DB F3 0F
  db 58 DB EB 07 3D 00 00 80 3F 74 4F 31 C0 F3 0F 10 84 01 80 00 00 00 F3 0F
  db 10 8C 01 8C 00 00 00 0F 28 D1 F3 0F 5C D0 F3 0F 59 D3 F3 0F 5D D5 F3 0F
  db 59 D4 F3 0F 58 C1 F3 0F 59 C4 0F 28 C8 F3 0F 5C C2 F3 0F 58 CA F3 0F 11
  db 04 02 F3 0F 11 4C 02 0C 83 C0 08 83 F8 10 72 B5 EB 23 8B 81 80 00 00 00
  db 89 02 8B 81 88 00 00 00 89 42 08 8B 81 8C 00 00 00 89 42 0C 8B 81 94 00
  db 00 00 89 42 14 F3 0F 10 81 84 00 00 00 41 81 78 04 00 00 80 3F 74 1C F3
  db 0F 10 89 90 00 00 00 F3 0F 5C C8 F3 41 0F 59 48 04 F3 0F 5D CD F3 0F 58
  db C8 EB 08 F3 0F 10 89 90 00 00 00 F3 0F 11 42 04 F3 0F 11 4A 10 C3 F3 0F
  db 10 41 50 F3 0F 10 49 58 0F 28 D0 F3 0F 59 D0 0F 28 D9 F3 0F 59 D9 F3 0F
  db 58 D3 0F 57 DB 0F 2E D3 0F 86 94 00 00 00 F3 0F 51 D2 F3 0F 5E C2 F3 0F
  db 5E CA B8 00 00 00 3F 66 0F 6E E8 F3 0F 10 52 0C F3 0F 5C 12 F3 0F 5C 91
  db 8C 00 00 00 F3 0F 58 91 80 00 00 00 F3 0F 59 D5 F3 0F 59 C2 F3 0F 10 5A
  db 14 F3 0F 5C 5A 08 F3 0F 5C 99 94 00 00 00 F3 0F 58 99 88 00 00 00 F3 0F
  db 59 DD F3 0F 59 CB F3 0F 10 12 F3 0F 58 D0 F3 0F 11 12 F3 0F 10 52 0C F3
  db 0F 58 D0 F3 0F 11 52 0C F3 0F 10 52 08 F3 0F 58 D1 F3 0F 11 52 08 F3 0F
  db 10 52 14 F3 0F 58 D1 F3 0F 11 52 14 B8 01 00 00 00 C3 31 C0 C3 F3 0F 10
  db 42 50 F3 0F 10 4A 58 66 0F 76 E4 66 0F 72 D4 01 0F 28 D0 0F 28 D9 0F 54
  db D4 0F 54 DC B8 00 00 80 35 66 0F 6E E8 0F 2E D5 73 03 0F 57 C0 0F 2E DD
  db 73 03 0F 57 C9 F3 0F 11 41 68 F3 0F 11 49 6C 0F 57 DB 8B 41 48 0F 2E C3
  db 0F 42 41 4C 44 29 C0 89 41 74 F3 0F 2A D0 F3 0F 59 D0 8B 41 58 0F 2E CB
  db 0F 42 41 5C 44 29 C8 89 41 78 F3 0F 2A D8 F3 0F 59 D9 F3 0F 58 D3 F3 0F
  db 11 51 70 C3 F6 41 64 02 0F 85 80 00 00 00 44 0F B7 42 10 45 85 C0 74 75
  db 4C 8B 5A 08 4D 85 DB 74 6C F3 0F 5A 51 68 F3 0F 5A 59 6C 8B 41 74 66 0F
  db 6E E0 8B 41 78 66 0F 6E E8 45 31 C9 31 C0 43 0F B7 0C CB 66 41 0F 7E E2
  db 44 29 D1 F2 0F 2A C1 F2 0F 59 C2 43 0F B7 4C CB 04 66 41 0F 7E EA 44 29
  db D1 F2 0F 2A C9 F2 0F 59 CB F2 0F 58 C1 66 0F 57 C9 66 0F 2E C1 72 0A 4F
  db 8B 14 CB 4D 89 14 C3 FF C0 41 FF C1 45 39 C1 72 B5 66 89 42 10 C3 44 0F
  db B7 42 10 45 85 C0 74 79 4C 8B 5A 08 4D 85 DB 74 70 F3 0F 10 51 68 F3 0F
  db 10 59 6C 45 31 C9 31 C0 47 0F B7 14 CB F3 41 0F 2A E2 47 0F B7 54 CB 04
  db F3 41 0F 2A EA 0F 28 C4 F3 0F 59 C2 0F 28 CD F3 0F 59 CB F3 0F 58 C1 0F
  db 2E 41 70 72 28 0F 2E 41 74 77 22 F3 0F 59 E3 F3 0F 59 EA F3 0F 5C E5 0F
  db 2E 61 78 72 10 0F 2E 61 7C 77 0A 4F 8B 14 CB 4D 89 14 C3 FF C0 41 FF C1
  db 45 39 C1 72 A3 66 89 42 10 C3 F3 0F 10 42 50 F3 0F 10 4A 58 0F 28 D0 F3
  db 0F 59 D0 0F 28 D9 F3 0F 59 D9 F3 0F 58 D3 F3 0F 51 D2 F3 0F 5E C2 F3 0F
  db 5E CA F3 0F 11 41 68 F3 0F 11 49 6C 8B 41 48 44 29 C0 F3 0F 2A D0 8B 41
  db 4C 44 29 C0 F3 0F 2A D8 F3 0F 58 DA B8 00 00 00 3F 66 0F 6E E8 F3 0F 59
  db DD 8B 41 4C 2B 41 48 F3 0F 2A D0 F3 0F 59 D5 8B 41 58 44 29 C8 F3 0F 2A
  db E0 8B 41 5C 44 29 C8 F3 0F 2A E8 F3 0F 58 EC B8 00 00 00 3F 66 0F 6E E0
  db F3 0F 59 EC F3 0F 11 59 70 F3 0F 11 69 74 8B 41 5C 2B 41 58 F3 0F 2A D8
  db F3 0F 59 DC 66 0F 76 E4 66 0F 72 D4 01 0F 54 C4 0F 54 CC 0F 28 E2 F3 0F
  db 59 E1 0F 28 EB F3 0F 59 E8 F3 0F 58 E5 F3 41 0F 59 22 B8 00 00 00 48 66
  db 0F 6E E8 F3 0F 5D E5 F3 0F 10 69 70 F3 0F 59 69 6C F3 0F 10 41 74 F3 0F
  db 59 41 68 F3 0F 5C E8 0F 28 C5 F3 0F 5C C4 F3 0F 58 EC F3 0F 11 41 78 F3
  db 0F 11 69 7C F3 0F 10 41 68 F3 0F 10 49 6C 66 0F 76 E4 66 0F 72 D4 01 0F
  db 54 C4 0F 54 CC F3 0F 59 D0 F3 0F 59 D9 F3 0F 58 D3 F3 0F 10 61 70 F3 0F
  db 59 61 68 F3 0F 10 69 74 F3 0F 59 69 6C F3 0F 58 E5 F3 0F 5C E2 F3 0F 11
  db 61 70 F3 0F 58 D2 F3 41 0F 59 52 08 B8 00 00 00 48 66 0F 6E E8 F3 0F 5D
  db D5 F3 0F 58 D4 F3 0F 11 51 74 B8 6F 12 83 3A 66 0F 6E E8 F3 0F 10 41 70
  db F3 0F 10 49 74 F3 0F 10 51 78 F3 0F 10 59 7C F3 0F 5C C5 F3 0F 58 CD F3
  db 0F 5C D5 F3 0F 58 DD F3 0F 11 41 70 F3 0F 11 49 74 F3 0F 11 51 78 F3 0F
  db 11 59 7C C3 F3 0F 10 51 68 F3 0F 10 59 6C F3 0F 10 41 70 F3 0F 10 49 74
  db F3 0F 59 C2 F3 0F 59 CA 0F 28 E0 F3 0F 5D C1 F3 0F 5F E1 F3 0F 10 49 78
  db F3 0F 10 69 7C F3 0F 59 CB F3 0F 59 EB 0F 28 D1 F3 0F 5D CD F3 0F 5F D5
  db F3 0F 58 C1 F3 0F 58 E2 F3 41 0F 2A C8 F3 0F 58 C1 F3 0F 58 E1 B8 6F 12
  db 83 3A 66 0F 6E E8 F3 0F 5C C5 F3 0F 58 E5 F3 0F 11 02 F3 0F 11 62 0C F3
  db 0F 10 51 68 B8 00 00 00 80 66 0F 6E C8 0F 57 D1 F3 0F 10 41 70 F3 0F 10
  db 49 74 F3 0F 59 C3 F3 0F 59 CB 0F 28 E0 F3 0F 5D C1 F3 0F 5F E1 F3 0F 10
  db 49 78 F3 0F 10 59 7C F3 0F 59 CA F3 0F 59 DA 0F 28 D1 F3 0F 5D CB F3 0F
  db 5F D3 F3 0F 58 C1 F3 0F 58 E2 F3 41 0F 2A C9 F3 0F 58 C1 F3 0F 58 E1 F3
  db 0F 5C C5 F3 0F 58 E5 F3 0F 11 42 08 F3 0F 11 62 14 C3 44 8B 54 24 28 44
  db 8B 5C 24 30 45 85 D2 0F 8E 1F 01 00 00 45 85 DB 0F 8E 16 01 00 00 41 FF
  db CA 41 FF CB 48 89 5C 24 08 31 DB F3 41 0F 2A C8 F3 41 0F 2A D1 F3 0F 10
  db 81 84 00 00 00 F3 0F 2C C0 83 F8 5F 0F 8F E5 00 00 00 F3 0F 10 81 80 00
  db 00 00 F3 0F 5C C1 F3 0F 2C C0 85 C0 0F 48 C3 44 39 D0 41 0F 4F C2 44 01
  db C0 89 02 F3 0F 10 81 8C 00 00 00 F3 0F 5C C1 F3 0F 2C C0 85 C0 0F 48 C3
  db 44 39 D0 41 0F 4F C2 44 01 C0 89 42 04 F3 0F 10 81 84 00 00 00 F3 0F 2C
  db C0 85 C0 0F 48 C3 83 F8 5F 7E 05 B8 5F 00 00 00 89 42 08 F3 0F 10 81 90
  db 00 00 00 F3 0F 2C C0 85 C0 0F 48 C3 83 F8 5F 7E 05 B8 5F 00 00 00 89 42
  db 0C F3 0F 10 81 88 00 00 00 F3 0F 5C C2 F3 0F 2C C0 85 C0 0F 48 C3 44 39
  db D8 41 0F 4F C3 44 01 C8 89 42 10 F3 0F 10 81 94 00 00 00 F3 0F 5C C2 F3
  db 0F 2C C0 85 C0 0F 48 C3 44 39 D8 41 0F 4F C3 44 01 C8 89 42 14 8B 02 3B
  db 42 04 7F 1B 8B 42 08 3B 42 0C 7F 13 8B 42 10 3B 42 14 7F 0B B8 01 00 00
  db 00 48 8B 5C 24 08 C3 48 8B 5C 24 08 31 C0 C3 4D 85 C9 0F 84 C4 00 00 00
  db 53 56 57 48 83 EC 50 48 89 CB 48 89 D6 4C 89 C7 4C 89 54 24 40 4C 89 4C
  db 24 48 41 83 79 60 FF 75 4A 41 F6 41 64 01 74 43 41 8B 41 48 41 3B 41 4C
  db 7F 14 41 8B 41 50 41 3B 41 54 7F 0A 41 8B 41 58 41 3B 41 5C 7E 25 41 C7
  db 41 60 00 00 00 00 41 C7 41 14 00 00 00 00 41 C7 41 20 01 00 00 00 41 C7
  db 41 28 02 00 00 00 41 FF D2 EB 4C 4C 89 C9 48 8D 54 24 20 E8 4F 00 00 00
  db 85 C0 74 3B 48 89 D9 48 89 F2 49 89 F8 4C 8D 4C 24 20 4C 8B 54 24 40 48
  db 8B 44 24 48 83 78 60 00 75 0B F6 40 64 01 74 05 41 FF D2 EB 12 E8 65 02
  db 00 00 48 8B 4C 24 48 48 89 FA E8 6D FA FF FF B8 01 00 00 00 48 83 C4 50
  db 5F 5E 5B C3 31 C0 C3 83 79 28 01 75 76 53 56 48 83 EC 28 48 89 CB 48 89
  db D6 83 7B 60 FF 74 13 48 89 D9 48 8D 53 18 49 89 F0 E8 70 01 00 00 85 C0
  db 75 38 44 8B 43 60 41 FF C0 44 89 43 60 41 83 F8 06 77 30 48 8D 4B 30 48
  db 8D 53 48 49 89 D9 E8 54 00 00 00 85 C0 74 DB 8B 03 89 43 18 8B 43 08 89
  db 43 1C 8B 43 10 89 43 20 EB B5 C7 43 28 02 00 00 00 EB 09 C7 43 28 03 00
  db 00 00 31 C0 48 83 C4 28 5E 5B C3 31 C0 C3 83 79 28 02 75 07 C7 41 28 01
  db 00 00 00 C3 31 C0 48 85 C9 74 0B 8B 51 28 FF CA 83 FA 01 0F 96 C0 C3 41
  db 83 F8 06 0F 87 EA 00 00 00 8B 02 3B 42 04 0F 8F A0 00 00 00 8B 42 08 3B
  db 42 0C 0F 8F 94 00 00 00 8B 42 10 3B 42 14 0F 8F 88 00 00 00 45 85 C0 75
  db 1B 48 8B 02 49 89 01 48 8B 42 08 49 89 41 08 48 8B 42 10 49 89 41 10 E9
  db 84 00 00 00 41 FF C8 45 89 C2 41 D1 EA 41 FF C2 41 83 FA 03 72 03 45 31
  db D2 45 31 DB 45 39 D3 74 11 41 83 FA 01 74 11 45 85 DB 75 06 41 83 FA 02
  db 74 06 4A 8B 04 D9 EB 04 4A 8B 04 DA 4B 89 04 D9 41 FF C3 41 83 FB 03 72
  db D3 41 F7 C0 01 00 00 00 75 0D 42 8B 04 D2 FF C8 43 89 44 D1 04 EB 29 42
  db 8B 44 D2 04 FF C0 43 89 04 D1 EB 1C 41 83 F8 01 75 39 48 8B 01 49 89 01
  db 48 8B 41 08 49 89 41 08 48 8B 41 10 49 89 41 10 41 8B 01 41 3B 41 04 7F
  db 1A 41 8B 41 08 41 3B 41 0C 7F 10 41 8B 41 10 41 3B 41 14 7F 06 B8 01 00
  db 00 00 C3 31 C0 C3 8B 42 08 3B 41 14 0F 8F A2 00 00 00 44 8B 49 0C 44 2B
  db 49 08 41 FF C1 44 8B 51 14 44 2B 51 10 41 FF C2 B8 D0 07 00 00 52 31 D2
  db 41 F7 F1 5A 41 39 C2 44 0F 4F D0 45 89 CB 45 0F AF DA B8 D0 07 00 00 52
  db 31 D2 41 F7 F3 5A 41 BB 01 00 00 00 85 C0 41 0F 44 C3 44 8B 1A 45 89 18
  db 41 8D 44 03 FF 3B 41 04 0F 4F 41 04 41 89 40 04 44 8B 4A 04 45 89 48 08
  db 44 8B 49 0C 45 89 48 0C 44 8B 4A 08 45 89 48 10 47 8D 54 11 FF 44 3B 51
  db 14 44 0F 4F 51 14 45 89 50 14 3B 41 04 7C 0B 41 FF C2 44 89 52 08 8B 01
  db FF C8 FF C0 89 02 B8 01 00 00 00 C3 31 C0 C3 53 56 57 48 81 EC E0 00 00
  db 00 4C 89 94 24 D0 00 00 00 48 89 8C 24 D8 00 00 00 4C 89 C3 48 89 D6 48
  db 8D 7C 24 20 B9 16 00 00 00 F3 48 A5 48 8D 54 24 20 F3 41 0F 2A 01 F3 0F
  db 11 82 80 00 00 00 F3 41 0F 2A 41 08 F3 0F 11 82 84 00 00 00 F3 41 0F 2A
  db 41 10 F3 0F 11 82 88 00 00 00 F3 41 0F 2A 41 04 F3 0F 11 82 8C 00 00 00
  db F3 41 0F 2A 41 0C F3 0F 11 82 90 00 00 00 F3 41 0F 2A 41 14 F3 0F 11 82
  db 94 00 00 00 49 89 D8 48 8B 8C 24 D8 00 00 00 FF 94 24 D0 00 00 00 48 81
  db C4 E0 00 00 00 5F 5E 5B C3 4D 85 C9 74 28 41 83 79 28 02 75 21 53 48 83
  db EC 20 4C 89 CB 41 B9 01 00 00 00 E8 11 00 00 00 48 89 D9 E8 6E FD FF FF
  db 48 83 C4 20 5B C3 41 FF E0 41 83 F9 01 75 23 66 83 7A 10 00 74 1C 66 81
  db 7A 10 D0 07 77 14 66 81 B9 16 84 00 00 D0 07 75 09 66 C7 81 14 84 00 00
  db 00 00 41 FF E0
align 4
dqb2HammerWorkerBusy:
  dd 0
$SITE:
  jmp dqb2HammerBatchWorkerCode
  $NOP
dqb2HammerWorkerResume:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2HammerRouteExpiry)
unregistersymbol(dqb2HammerRouteMain)
unregistersymbol(dqb2HammerSlots)
dealloc(dqb2HammerSlots)
unregistersymbol(dqb2HammerWorkerBusy)
dealloc(dqb2HammerBatchWorkerCode)
]]):gsub('@WIDTH@',hex(DQB2.hammerRangeSettings.address))
  end,
}

local function hammerDetachedTickSite(address)
  return hammerNativeCall(address,{0x48,0x89,0x5C,0x24,0x10,0x48,0x89,0x74,0x24,0x18,0x48,0x89,0x7C,0x24,0x20,0x41,0x56,0x48,0x81,0xEC,0x30,2,0,0})
end
DQB2.SIGS.hammerDetachedTick={p='0F 57 C0 0F 2F F0 76 09 48 8D 4B 10 E8 ?? ?? ?? ?? 0F 28 CE 48 8B CB',off=12,validate=hammerDetachedTickSite}
DQB2.SIGS.hammerDetachedConsumer={
  p='40 55 57 41 56 48 8D AC 24 60 AD FF FF B8 A0 53 00 00 E8 ?? ?? ?? ?? 48 2B E0',
  validate=function(address)
    return equal(bytes(address+0x38,13),{0x40,0x38,0xBA,0xA4,0,0,0,0x75,0x0A,0x66,0x3B,0x7A,0x10})
      and equal(bytes(address+0x52,8),{0x41,0x0F,0xB7,0x96,0xD8,0x83,0,0})
      and equal(bytes(address+0x1923,9),{0xFF,0x50,0x10,0x44,0x0F,0xB6,0xC0,0x84,0xC0})
  end,
}
DQB2.HOOKS.hammerDetachedTick={
  sig='hammerDetachedTick',len=5,validate=hammerDetachedTickSite,
  quiesce=function(state)
    if DQB2.hooks.hammerTerrainRelease or DQB2.hooks.hammerBatchMain then return false end
    local busy=getAddressSafe('dqb2HammerDetachedBusy')
    return busy~=nil and readInteger(busy)==0 and hookCaveIdle(state) and readInteger(busy)==0
  end,
  aa=function()
    local site=DQB2.needSig('hammerDetachedTick')
    local tick=site+5+string.unpack('&lt;i4',string.char(table.unpack(bytes(site+1,4))))
    local consume=DQB2.needSig('hammerDetachedConsumer')
    local qpc=getAddressSafe('kernel32.QueryPerformanceCounter') or 0
    local budget=0
    if qpc~=0 then
      local stream=createMemoryStream()
      stream.Size=8
      local ok,result=pcall(executeCodeLocalEx,'kernel32.QueryPerformanceFrequency',stream.Memory)
      stream.Position=0
      local frequency=ok and result and result~=0 and stream.readQword() or 0
      stream.destroy()
      if frequency and frequency>0 then budget=frequency//500 end
    end
    return (hammerBatchAddresses([[
[ENABLE]
alloc(dqb2HammerDetachedCode,4096,$SITE)
alloc(dqb2HammerDetachedPool,1624064)
label(dqb2HammerDetachedBusy)
label(dqb2HammerDetachedTable)
label(dqb2HammerDetachedScheduler)
label(dqb2HammerDetachedTickRoute)
label(dqb2HammerDetachedHandoff)
label(dqb2HammerDetachedExit)
label(dqb2HammerDetachedBack)
registersymbol(dqb2HammerDetachedBusy)
registersymbol(dqb2HammerDetachedTable)
registersymbol(dqb2HammerDetachedHandoff)
dqb2HammerDetachedCode:
  lock inc dword ptr [dqb2HammerDetachedBusy]
  mov rax,@TICK_ORIGINAL@
  call rax
  mov rax,@WORLD@
  mov rax,[rax]
  test rax,rax
  je dqb2HammerDetachedExit
  mov rdx,[rax+38]
  test rdx,rdx
  je dqb2HammerDetachedExit
  mov rdx,[rdx+8340230]
  test rdx,rdx
  je dqb2HammerDetachedExit
  mov rax,[rax+48]
  test rax,rax
  je dqb2HammerDetachedExit
  movzx r11d,word ptr [rax+2C8]
  test r11d,r11d
  je dqb2HammerDetachedExit
  mov rcx,dqb2HammerDetachedScheduler
  mov r8,@CONSUMER@
  mov r9,@ENUM@
  xor r10d,r10d
  mov rax,@QPC@
  call dqb2HammerDetachedTickRoute
dqb2HammerDetachedExit:
  lock dec dword ptr [dqb2HammerDetachedBusy]
  jmp dqb2HammerDetachedBack
dqb2HammerDetachedHandoff:
  db EB 05
dqb2HammerDetachedTickRoute:
  db E9 78 02 00 00 66 81 79 3E 31 6D 75 3F 53 56 48 83 EC 28 48 89 CB 4C 89
  db CE E8 31 00 00 00 48 85 C0 74 20 8B 4B 38 3B 48 2C 75 18 48 89 D9 48 89
  db C2 4C 8B 06 44 8B 4E 08 4C 8B 56 10 E8 39 00 00 00 EB 02 31 C0 48 83 C4
  db 28 5E 5B C3 31 C0 C3 48 89 C8 48 29 D0 72 20 48 3D 00 20 84 00 73 18 31
  db D2 41 B9 20 84 00 00 49 F7 F1 48 85 D2 75 08 48 C1 E0 07 4C 01 C0 C3 31
  db C0 C3 83 7A 28 01 0F 85 88 00 00 00 66 81 B9 D8 83 00 00 00 80 75 7D 4D
  db 85 D2 74 78 49 8B 42 38 48 85 C0 74 6F 4C 8B 98 30 02 34 08 4D 85 DB 74
  db 63 49 8B 42 48 48 85 C0 74 5A 44 0F B7 90 C8 02 00 00 45 85 D2 74 4D 31
  db C0 44 39 C8 73 46 56 49 8B 34 C0 48 85 F6 74 0C 50 8B 46 28 FF C8 83 F8
  db 01 58 77 05 5E FF C0 EB E0 48 89 F0 5E 53 48 83 EC 20 48 89 D3 49 89 C8
  db 48 89 C1 4D 89 D9 E8 14 00 00 00 85 C0 74 07 C7 43 28 03 00 00 00 48 83
  db C4 20 5B C3 31 C0 C3 4D 85 C9 0F 84 EB 00 00 00 4D 85 D2 0F 84 E2 00 00
  db 00 83 7A 28 01 0F 85 D8 00 00 00 8B 41 28 FF C8 83 F8 01 0F 86 CA 00 00
  db 00 53 56 57 41 54 48 83 EC 28 48 89 CB 4D 89 C4 4C 89 8B 80 00 00 00 4C
  db 89 93 A8 00 00 00 48 8D 83 00 01 00 00 48 89 83 88 00 00 00 48 8D 83 20
  db 85 00 00 48 89 83 90 00 00 00 48 8D 83 D0 85 00 00 48 89 83 98 00 00 00
  db 48 8D 83 B0 87 00 00 48 89 83 A0 00 00 00 48 89 DF 48 89 D6 C7 43 28 00
  db 00 00 00 B9 05 00 00 00 F3 48 A5 8B 46 04 89 47 04 48 83 C7 08 48 83 C6
  db 08 B9 0A 00 00 00 F3 48 A5 48 8B BB 98 00 00 00 31 C0 B9 3B 00 00 00 F3
  db 48 AB 48 8B BB 90 00 00 00 49 8D 74 24 20 B9 16 00 00 00 F3 48 A5 48 8B
  db 8B 88 00 00 00 4C 89 E2 E8 19 00 00 00 C7 43 28 01 00 00 00 B8 01 00 00
  db 00 48 83 C4 28 41 5C 5F 5E 5B C3 31 C0 C3 48 8B 42 08 48 89 41 08 0F B7
  db 42 18 66 89 41 18 8B 82 C0 00 00 00 25 00 00 03 00 89 81 C0 00 00 00 0F
  db 10 82 D0 00 00 00 0F 11 81 D0 00 00 00 0F 10 82 E0 00 00 00 0F 11 81 E0
  db 00 00 00 0F B7 82 D8 83 00 00 66 89 81 D8 83 00 00 8B 82 10 84 00 00 89
  db 81 10 84 00 00 66 C7 81 14 84 00 00 00 00 66 C7 81 16 84 00 00 D0 07 0F
  db B6 82 1D 84 00 00 88 81 1D 84 00 00 C3 48 85 C0 0F 84 B3 00 00 00 48 83
  db 79 10 00 0F 84 A8 00 00 00 53 56 57 41 54 41 55 41 56 41 57 48 83 EC 50
  db 48 89 CB 48 89 D6 4C 89 C7 4D 89 CC 4D 89 D5 4D 89 DE 49 89 C7 48 8D 4C
  db 24 20 41 FF D7 85 C0 74 51 48 8B 44 24 20 48 03 43 10 48 89 44 24 30 C7
  db 44 24 38 0F 00 00 00 48 89 D9 48 89 F2 49 89 F8 4D 89 E1 4D 89 EA 4D 89
  db F3 E8 4B 00 00 00 85 C0 74 37 FF 4C 24 38 74 31 48 8D 4C 24 28 41 FF D7
  db 85 C0 74 25 48 8B 44 24 28 48 3B 44 24 30 72 C7 EB 17 48 89 D9 48 89 F2
  db 49 89 F8 4D 89 E1 4D 89 EA 4D 89 F3 E8 10 00 00 00 48 83 C4 50 41 5F 41
  db 5E 41 5D 41 5C 5F 5E 5B C3 48 85 D2 0F 84 B3 00 00 00 4D 85 DB 0F 84 AA
  db 00 00 00 53 56 57 41 54 41 55 41 56 41 57 48 83 EC 30 48 89 CB 48 89 D6
  db 4C 89 C7 4D 89 CC 4D 89 D5 4D 89 DE C7 44 24 20 0F 00 00 00 44 8B 7B 04
  db 45 85 FF 74 66 8B 03 3B 43 04 72 02 31 C0 8D 48 01 89 0B 48 8B 53 08 48
  db 8B 0C C2 48 85 C9 74 46 83 79 28 01 75 40 48 39 B1 80 00 00 00 75 30 4C
  db 39 B1 A8 00 00 00 75 27 48 89 F2 49 89 F8 4D 89 E1 4D 89 EA E8 37 00 00
  db 00 83 F8 01 74 1F 83 F8 02 75 13 FF 4C 24 20 74 12 44 8B 7B 04 EB A6 C7
  db 41 28 04 00 00 00 41 FF CF 75 9A 31 C0 48 83 C4 30 41 5F 41 5E 41 5D 41
  db 5C 5F 5E 5B C3 31 C0 C3 48 85 D2 0F 84 DD 00 00 00 48 39 91 80 00 00 00
  db 0F 85 D0 00 00 00 4D 85 C0 0F 84 C7 00 00 00 4D 85 C9 0F 84 BE 00 00 00
  db 53 56 57 41 54 41 55 48 83 EC 40 48 89 CB 4D 89 C4 4D 89 CD 4C 89 54 24
  db 38 48 8B B3 88 00 00 00 48 8B BB 98 00 00 00 48 8D 54 24 20 E8 1D 02 00
  db 00 85 C0 74 7D 48 8B 83 A0 00 00 00 48 89 47 08 66 C7 47 10 00 00 66 C7
  db 87 D0 01 00 00 D0 07 80 A7 D2 01 00 00 FE 48 8B 4C 24 38 48 8B 93 90 00
  db 00 00 49 89 F8 4C 8D 4C 24 20 4D 89 EA E8 24 04 00 00 48 89 D9 48 89 FA
  db E8 C3 00 00 00 66 83 7F 10 00 74 21 66 C7 86 14 84 00 00 00 00 48 89 F1
  db 48 89 FA 41 FF D4 48 89 D9 E8 2F 02 00 00 B8 01 00 00 00 EB 0D 48 89 D9
  db E8 20 02 00 00 B8 02 00 00 00 48 83 C4 40 41 5D 41 5C 5F 5E 5B C3 31 C0
  db C3 F3 0F 10 42 50 F3 0F 10 4A 58 66 0F 76 E4 66 0F 72 D4 01 0F 28 D0 0F
  db 28 D9 0F 54 D4 0F 54 DC B8 00 00 80 35 66 0F 6E E8 0F 2E D5 73 03 0F 57
  db C0 0F 2E DD 73 03 0F 57 C9 F3 0F 11 41 68 F3 0F 11 49 6C 0F 57 DB 8B 41
  db 48 0F 2E C3 0F 42 41 4C 44 29 C0 89 41 74 F3 0F 2A D0 F3 0F 59 D0 8B 41
  db 58 0F 2E CB 0F 42 41 5C 44 29 C8 89 41 78 F3 0F 2A D8 F3 0F 59 D9 F3 0F
  db 58 D3 F3 0F 11 51 70 C3 F6 41 64 02 0F 85 80 00 00 00 44 0F B7 42 10 45
  db 85 C0 74 75 4C 8B 5A 08 4D 85 DB 74 6C F3 0F 5A 51 68 F3 0F 5A 59 6C 8B
  db 41 74 66 0F 6E E0 8B 41 78 66 0F 6E E8 45 31 C9 31 C0 43 0F B7 0C CB 66
  db 41 0F 7E E2 44 29 D1 F2 0F 2A C1 F2 0F 59 C2 43 0F B7 4C CB 04 66 41 0F
  db 7E EA 44 29 D1 F2 0F 2A C9 F2 0F 59 CB F2 0F 58 C1 66 0F 57 C9 66 0F 2E
  db C1 72 0A 4F 8B 14 CB 4D 89 14 C3 FF C0 41 FF C1 45 39 C1 72 B5 66 89 42
  db 10 C3 44 0F B7 42 10 45 85 C0 74 79 4C 8B 5A 08 4D 85 DB 74 70 F3 0F 10
  db 51 68 F3 0F 10 59 6C 45 31 C9 31 C0 47 0F B7 14 CB F3 41 0F 2A E2 47 0F
  db B7 54 CB 04 F3 41 0F 2A EA 0F 28 C4 F3 0F 59 C2 0F 28 CD F3 0F 59 CB F3
  db 0F 58 C1 0F 2E 41 70 72 28 0F 2E 41 74 77 22 F3 0F 59 E3 F3 0F 59 EA F3
  db 0F 5C E5 0F 2E 61 78 72 10 0F 2E 61 7C 77 0A 4F 8B 14 CB 4D 89 14 C3 FF
  db C0 41 FF C1 45 39 C1 72 A3 66 89 42 10 C3 83 79 28 01 75 76 53 56 48 83
  db EC 28 48 89 CB 48 89 D6 83 7B 60 FF 74 13 48 89 D9 48 8D 53 18 49 89 F0
  db E8 70 01 00 00 85 C0 75 38 44 8B 43 60 41 FF C0 44 89 43 60 41 83 F8 06
  db 77 30 48 8D 4B 30 48 8D 53 48 49 89 D9 E8 54 00 00 00 85 C0 74 DB 8B 03
  db 89 43 18 8B 43 08 89 43 1C 8B 43 10 89 43 20 EB B5 C7 43 28 02 00 00 00
  db EB 09 C7 43 28 03 00 00 00 31 C0 48 83 C4 28 5E 5B C3 31 C0 C3 83 79 28
  db 02 75 07 C7 41 28 01 00 00 00 C3 31 C0 48 85 C9 74 0B 8B 51 28 FF CA 83
  db FA 01 0F 96 C0 C3 41 83 F8 06 0F 87 EA 00 00 00 8B 02 3B 42 04 0F 8F A0
  db 00 00 00 8B 42 08 3B 42 0C 0F 8F 94 00 00 00 8B 42 10 3B 42 14 0F 8F 88
  db 00 00 00 45 85 C0 75 1B 48 8B 02 49 89 01 48 8B 42 08 49 89 41 08 48 8B
  db 42 10 49 89 41 10 E9 84 00 00 00 41 FF C8 45 89 C2 41 D1 EA 41 FF C2 41
  db 83 FA 03 72 03 45 31 D2 45 31 DB 45 39 D3 74 11 41 83 FA 01 74 11 45 85
  db DB 75 06 41 83 FA 02 74 06 4A 8B 04 D9 EB 04 4A 8B 04 DA 4B 89 04 D9 41
  db FF C3 41 83 FB 03 72 D3 41 F7 C0 01 00 00 00 75 0D 42 8B 04 D2 FF C8 43
  db 89 44 D1 04 EB 29 42 8B 44 D2 04 FF C0 43 89 04 D1 EB 1C 41 83 F8 01 75
  db 39 48 8B 01 49 89 01 48 8B 41 08 49 89 41 08 48 8B 41 10 49 89 41 10 41
  db 8B 01 41 3B 41 04 7F 1A 41 8B 41 08 41 3B 41 0C 7F 10 41 8B 41 10 41 3B
  db 41 14 7F 06 B8 01 00 00 00 C3 31 C0 C3 8B 42 08 3B 41 14 0F 8F A2 00 00
  db 00 44 8B 49 0C 44 2B 49 08 41 FF C1 44 8B 51 14 44 2B 51 10 41 FF C2 B8
  db 80 00 00 00 52 31 D2 41 F7 F1 5A 41 39 C2 44 0F 4F D0 45 89 CB 45 0F AF
  db DA B8 80 00 00 00 52 31 D2 41 F7 F3 5A 41 BB 01 00 00 00 85 C0 41 0F 44
  db C3 44 8B 1A 45 89 18 41 8D 44 03 FF 3B 41 04 0F 4F 41 04 41 89 40 04 44
  db 8B 4A 04 45 89 48 08 44 8B 49 0C 45 89 48 0C 44 8B 4A 08 45 89 48 10 47
  db 8D 54 11 FF 44 3B 51 14 44 0F 4F 51 14 45 89 50 14 3B 41 04 7C 0B 41 FF
  db C2 44 89 52 08 8B 01 FF C8 FF C0 89 02 B8 01 00 00 00 C3 31 C0 C3 53 56
  db 57 48 81 EC E0 00 00 00 4C 89 94 24 D0 00 00 00 48 89 8C 24 D8 00 00 00
  db 4C 89 C3 48 89 D6 48 8D 7C 24 20 B9 16 00 00 00 F3 48 A5 48 8D 54 24 20
  db F3 41 0F 2A 01 F3 0F 11 82 80 00 00 00 F3 41 0F 2A 41 08 F3 0F 11 82 84
  db 00 00 00 F3 41 0F 2A 41 10 F3 0F 11 82 88 00 00 00 F3 41 0F 2A 41 04 F3
  db 0F 11 82 8C 00 00 00 F3 41 0F 2A 41 0C F3 0F 11 82 90 00 00 00 F3 41 0F
  db 2A 41 14 F3 0F 11 82 94 00 00 00 49 89 D8 48 8B 8C 24 D8 00 00 00 FF 94
  db 24 D0 00 00 00 48 81 C4 E0 00 00 00 5F 5E 5B C3
align 8
dqb2HammerDetachedScheduler:
  dd 0
  dd 20
  dq dqb2HammerDetachedTable
  dq @BUDGET@
dqb2HammerDetachedTable:
  dq dqb2HammerDetachedPool+0
  dq dqb2HammerDetachedPool+C640
  dq dqb2HammerDetachedPool+18C80
  dq dqb2HammerDetachedPool+252C0
  dq dqb2HammerDetachedPool+31900
  dq dqb2HammerDetachedPool+3DF40
  dq dqb2HammerDetachedPool+4A580
  dq dqb2HammerDetachedPool+56BC0
  dq dqb2HammerDetachedPool+63200
  dq dqb2HammerDetachedPool+6F840
  dq dqb2HammerDetachedPool+7BE80
  dq dqb2HammerDetachedPool+884C0
  dq dqb2HammerDetachedPool+94B00
  dq dqb2HammerDetachedPool+A1140
  dq dqb2HammerDetachedPool+AD780
  dq dqb2HammerDetachedPool+B9DC0
  dq dqb2HammerDetachedPool+C6400
  dq dqb2HammerDetachedPool+D2A40
  dq dqb2HammerDetachedPool+DF080
  dq dqb2HammerDetachedPool+EB6C0
  dq dqb2HammerDetachedPool+F7D00
  dq dqb2HammerDetachedPool+104340
  dq dqb2HammerDetachedPool+110980
  dq dqb2HammerDetachedPool+11CFC0
  dq dqb2HammerDetachedPool+129600
  dq dqb2HammerDetachedPool+135C40
  dq dqb2HammerDetachedPool+142280
  dq dqb2HammerDetachedPool+14E8C0
  dq dqb2HammerDetachedPool+15AF00
  dq dqb2HammerDetachedPool+167540
  dq dqb2HammerDetachedPool+173B80
  dq dqb2HammerDetachedPool+1801C0
align 4
dqb2HammerDetachedBusy:
  dd 0
$SITE:
  jmp dqb2HammerDetachedCode
  $NOP
dqb2HammerDetachedBack:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2HammerDetachedBusy)
unregistersymbol(dqb2HammerDetachedTable)
unregistersymbol(dqb2HammerDetachedHandoff)
dealloc(dqb2HammerDetachedPool)
dealloc(dqb2HammerDetachedCode)
]])):gsub('@TICK_ORIGINAL@',hex(tick)):gsub('@CONSUMER@',hex(consume)):gsub('@QPC@',hex(qpc)):gsub('@BUDGET@',hex(budget))
  end,
}

DQB2.HOOKS.hammerBatchMain={
  sig='hammerBatchMain',len=12,validate=hammerBatchMainSite,
  quiesce=function(state)
    local busy=getAddressSafe('dqb2HammerMainBusy')
    return busy~=nil and readInteger(busy)==0 and hookCaveIdle(state) and readInteger(busy)==0
  end,
  aa=function()
    return hammerBatchAddresses([[
[ENABLE]
alloc(dqb2HammerBatchMainCode,4096,$SITE)
label(dqb2HammerMainBusy)
registersymbol(dqb2HammerMainBusy)
label(dqb2HammerMainStock)
label(dqb2HammerMainBack)
label(dqb2HammerMainFinished)
dqb2HammerBatchMainCode:
  lock inc dword ptr [dqb2HammerMainBusy]
  mov rax,[rsi]
  mov rcx,rsi
  add rdx,rdi
  mov r8,[rax+8]
  mov r10,@WORLD@
  mov r10,[r10]
  test r10,r10
  je dqb2HammerMainStock
  mov r10,[r10+88]
  test r10,r10
  je dqb2HammerMainStock
  add r10,30
  mov r11,dqb2HammerSlots
  mov rax,dqb2HammerRouteMain
  call rax
  cmp word ptr [rsi+3E],6D31
  jne dqb2HammerMainFinished
  mov rax,@WORLD@
  mov rax,[rax]
  test rax,rax
  je dqb2HammerMainFinished
  mov rdx,[rax+88]
  test rdx,rdx
  je dqb2HammerMainFinished
  add rdx,30
  sub rsp,40
  mov rcx,dqb2HammerDetachedTable
  mov [rsp+20],rcx
  mov qword ptr [rsp+28],20
  mov [rsp+30],rax
  mov rcx,rsi
  mov r8,dqb2HammerSlots
  lea r9,[rsp+20]
  mov rax,dqb2HammerDetachedHandoff
  call rax
  add rsp,40
dqb2HammerMainFinished:
  lock dec dword ptr [dqb2HammerMainBusy]
  jmp dqb2HammerMainBack
dqb2HammerMainStock:
  call r8
  lock dec dword ptr [dqb2HammerMainBusy]
  jmp dqb2HammerMainBack
align 4
dqb2HammerMainBusy:
  dd 0
$SITE:
  jmp dqb2HammerBatchMainCode
  $NOP
dqb2HammerMainBack:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2HammerMainBusy)
dealloc(dqb2HammerBatchMainCode)
]])
  end,
}
DQB2.HOOKS.hammerBatchExpiry={
  sig='hammerBatchExpiry',len=8,validate=hammerBatchExpirySite,
  quiesce=function(state)
    local busy=getAddressSafe('dqb2HammerExpiryBusy')
    return busy~=nil and readInteger(busy)==0 and hookCaveIdle(state) and readInteger(busy)==0
  end,
  aa=function()
    local site=DQB2.needSig('hammerBatchExpiry')
    return (hammerBatchAddresses([[
[ENABLE]
alloc(dqb2HammerBatchExpiryCode,4096,$SITE)
label(dqb2HammerExpiryBusy)
registersymbol(dqb2HammerExpiryBusy)
label(dqb2HammerExpiryStock)
label(dqb2HammerExpiryBack)
dqb2HammerBatchExpiryCode:
  $ORIG
  pushfq
  lock inc dword ptr [dqb2HammerExpiryBusy]
  push rax
  push rcx
  push rdx
  push r8
  push r9
  sub rsp,20
  cmp dword ptr [rcx+83D4],0
  jg dqb2HammerExpiryStock
  mov rax,@WORLD@
  mov rax,[rax]
  test rax,rax
  je dqb2HammerExpiryStock
  mov rdx,[rax+88]
  test rdx,rdx
  je dqb2HammerExpiryStock
  add rdx,30
  mov r8,dqb2HammerSlots
  mov rax,dqb2HammerRouteExpiry
  call rax
  test eax,eax
  je dqb2HammerExpiryStock
  add rsp,20
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  mov dword ptr [rcx+83D4],(float)0.05
  lock dec dword ptr [dqb2HammerExpiryBusy]
  popfq
  jmp @EXPIRY_CONTINUE@
dqb2HammerExpiryStock:
  add rsp,20
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  lock dec dword ptr [dqb2HammerExpiryBusy]
  popfq
  jmp dqb2HammerExpiryBack
align 4
dqb2HammerExpiryBusy:
  dd 0
$SITE:
  jmp dqb2HammerBatchExpiryCode
  $NOP
dqb2HammerExpiryBack:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2HammerExpiryBusy)
dealloc(dqb2HammerBatchExpiryCode)
]])):gsub('@EXPIRY_CONTINUE@',hex(site+0x23))
  end,
}

local function hammerBatchOwnerExpirySite(address)
  return equal(bytes(address,7),{0xC6,0x83,0x1A,0x84,0,0,1})
end
DQB2.SIGS.hammerBatchOwnerExpiry={
  p='E8 ?? ?? ?? ?? 84 C0 74 0E C6 83 1A 84 00 00 01 32 C0 E9 ?? ?? ?? ??',
  off=9,validate=hammerBatchOwnerExpirySite,
}
DQB2.HOOKS.hammerBatchOwnerExpiry={
  sig='hammerBatchOwnerExpiry',len=7,validate=hammerBatchOwnerExpirySite,
  quiesce=function(state)
    local busy=getAddressSafe('dqb2HammerOwnerExpiryBusy')
    return busy~=nil and readInteger(busy)==0 and hookCaveIdle(state) and readInteger(busy)==0
  end,
  aa=function()
    local site=DQB2.needSig('hammerBatchOwnerExpiry')
    local enumerator=DQB2.needSig('hammerBatchNative')
    local offset=string.unpack('&lt;i4',string.char(table.unpack(bytes(enumerator+0x11,4))))
    local worldAddress=enumerator+0x15+offset
    local root=need(readPointer(worldAddress),'Game world is unavailable.','ゲームのワールドを取得できません。')
    local map=need(readPointer(root+0x38),'Game world is unavailable.','ゲームのワールドを取得できません。')
    return (hammerBatchAddresses([[
[ENABLE]
alloc(dqb2HammerOwnerExpiryCode,4096,$SITE)
label(dqb2HammerOwnerExpiryBusy)
label(dqb2HammerOwnerExpiryStock)
label(dqb2HammerOwnerExpiryBack)
registersymbol(dqb2HammerOwnerExpiryBusy)
dqb2HammerOwnerExpiryCode:
  pushfq
  lock inc dword ptr [dqb2HammerOwnerExpiryBusy]
  push rax
  push rcx
  push rdx
  push r8
  push r9
  sub rsp,20
  mov rax,@WORLD@
  mov rax,[rax]
  test rax,rax
  je dqb2HammerOwnerExpiryStock
  mov rdx,@MAP@
  cmp [rax+38],rdx
  jne dqb2HammerOwnerExpiryStock
  mov rdx,[rax+88]
  test rdx,rdx
  je dqb2HammerOwnerExpiryStock
  add rdx,30
  mov rcx,rbx
  mov r8,dqb2HammerSlots
  mov rax,dqb2HammerRouteExpiry
  call rax
  test eax,eax
  je dqb2HammerOwnerExpiryStock
  add rsp,20
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  lock dec dword ptr [dqb2HammerOwnerExpiryBusy]
  popfq
  jmp @CONTINUE@
dqb2HammerOwnerExpiryStock:
  add rsp,20
  pop r9
  pop r8
  pop rdx
  pop rcx
  pop rax
  lock dec dword ptr [dqb2HammerOwnerExpiryBusy]
  popfq
  $ORIG
  jmp dqb2HammerOwnerExpiryBack
align 4
dqb2HammerOwnerExpiryBusy:
  dd 0
$SITE:
  jmp dqb2HammerOwnerExpiryCode
  $NOP
dqb2HammerOwnerExpiryBack:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2HammerOwnerExpiryBusy)
dealloc(dqb2HammerOwnerExpiryCode)
]])):gsub('@CONTINUE@',hex(site+0xE)):gsub('@MAP@',hex(map))
  end,
}

local hammerRangeBytes={0xF3,0x0F,0x11,0x33,0xF3,0x0F,0x11,0x7B,0x04,0xF3,0x0F,0x11,0x4B,0x08}
local function hammerRangeSite(address)
  return equal(bytes(address,#hammerRangeBytes),hammerRangeBytes)
    and equal(bytes(address-0x15,5),{0xB8,1,0,0,0})
    and equal(bytes(address+0x10,4),{0xF3,0x0F,0x59,0x35})
end
DQB2.SIGS.hammerRange={
  p='F3 0F 10 05 ?? ?? ?? ?? B8 01 00 00 00 F3 0F 59 F0 66 89 43 1C F3 0F 59 F8 F3 0F 59 C8 F3 0F 11 33 F3 0F 11 7B 04 F3 0F 11 4B 08 EB ?? F3 0F 59 35',
  off=0x1D,validate=hammerRangeSite,
}
DQB2.HOOKS.hammerRange={
  sig='hammerRange',len=#hammerRangeBytes,validate=hammerRangeSite,quiesce=hookCaveIdle,
  aa=function()
    local settings=DQB2.hammerRangeSettings
    need(settings and settings.pid==DQB2.pid and settings.address~=0,
      'Hammer settings are unavailable.','ハンマーの設定領域を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2HammerRangeCode,4096,$SITE)
label(dqb2HammerGeneration)
label(dqb2HammerMark)
label(dqb2HammerLarge)
label(dqb2HammerCheckSize)
label(dqb2HammerRestore)
label(dqb2HammerResume)
dqb2HammerRangeCode:
  $ORIG
  pushfq
  push rax
  push rcx
  push rdx
  push r10
  // Target attack records 0xB4-0xBE and 0xC0-0xCA in the player motion data.
  cmp byte ptr [rdi+360],0
  jne dqb2HammerRestore
  cmp dword ptr [rsi],18
  jne dqb2HammerRestore
  mov eax,[rsi+4]
  and eax,FFFFFDFF
  cmp eax,80
  jne dqb2HammerRestore
  cmp dword ptr [rsi+0C],FFFF000E
  jne dqb2HammerRestore
  cmp dword ptr [rsi+10],012C0018
  jne dqb2HammerRestore
  cmp byte ptr [rsi+4E],3
  jne dqb2HammerRestore
  mov eax,[rsi+8]
  test al,1
  jne dqb2HammerRestore
  cmp eax,B4
  jb dqb2HammerRestore
  cmp eax,CA
  ja dqb2HammerRestore
  cmp eax,C0
  jae dqb2HammerLarge
  mov edx,C8
  jmp dqb2HammerCheckSize
dqb2HammerLarge:
  mov edx,190
dqb2HammerCheckSize:
  cmp [rsi+1C],dx
  jne dqb2HammerRestore
  cmp [rsi+1E],dx
  jne dqb2HammerRestore
  cmp [rsi+20],dx
  jne dqb2HammerRestore
  mov r10,@WIDTH@
  mov eax,[r10]
  mov ecx,[r10+4]
  test eax,eax
  jle dqb2HammerRestore
  test ecx,ecx
  jle dqb2HammerRestore
  cmp eax,7F800000
  jae dqb2HammerRestore
  cmp ecx,7F800000
  jae dqb2HammerRestore
  mov edx,[r10+8]
  test edx,edx
  jle dqb2HammerRestore
  cmp edx,7F800000
  jae dqb2HammerRestore
  cmp eax,3F800000
  jne dqb2HammerMark
  cmp ecx,3F800000
  jne dqb2HammerMark
  cmp edx,3F800000
  je dqb2HammerRestore
dqb2HammerMark:
  mov eax,1
  lock xadd [dqb2HammerGeneration],eax
  inc eax
  mov [rbx+18],eax
  mov word ptr [rbx+1E],6D31
dqb2HammerRestore:
  pop r10
  pop rdx
  pop rcx
  pop rax
  popfq
  jmp dqb2HammerResume
align 4
dqb2HammerGeneration:
  dd 0
$SITE:
  jmp dqb2HammerRangeCode
  $NOP
dqb2HammerResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2HammerRangeCode)
]]):gsub('@WIDTH@',hex(settings.address))
  end,
}
local function prepareHammerRangeSettings()
  local state=DQB2.hammerRangeSettings
  if not state or state.pid~=DQB2.pid then
    local address=need(allocateMemory(4096),'Cannot allocate hammer settings.','ハンマーの設定領域を確保できません。')
    need(address~=0,'Cannot allocate hammer settings.','ハンマーの設定領域を確保できません。')
    if not writeFloat(address,1) or not writeFloat(address+4,1) or not writeFloat(address+8,1) then
      deAlloc(address)
      DQB2.err('Cannot initialize hammer settings.','ハンマーの倍率を初期化できません。')
    end
    state={pid=DQB2.pid,address=address,split=true}
    DQB2.hammerRangeSettings=state
  elseif not state.split then
    local width=need(readFloat(state.address),'Cannot read existing hammer width.','既存のハンマーの広さを読み込めません。')
    need(writeFloat(state.address+8,width),'Cannot initialize hammer depth.','ハンマーの奥行きを初期化できません。')
    state.split=true
  end
  local list=getAddressList()
  for i,id in ipairs({413,414,415}) do
    local record=need(list.getMemoryRecordByID(id),'Hammer multiplier record is missing.','ハンマーの倍率項目が見つかりません。')
    record.Address=hex(state.address+(i-1)*4)
  end
end
-- Drop pending terrain edits before the game releases the terrain object.
local hammerTerrainReleaseBytes={0x48,0x89,0x5C,0x24,0x08}
local function hammerTerrainReleaseSite(address)
  return equal(bytes(address,#hammerTerrainReleaseBytes),hammerTerrainReleaseBytes)
end
DQB2.SIGS.hammerTerrainRelease={
  p='48 89 5C 24 08 48 89 6C 24 10 48 89 74 24 18 57 48 83 EC 20 48 8B F9 48 8D 99 F8 2D 34 08',
  validate=hammerTerrainReleaseSite,
}
DQB2.HOOKS.hammerTerrainRelease={
  sig='hammerTerrainRelease',len=#hammerTerrainReleaseBytes,
  validate=hammerTerrainReleaseSite,quiesce=hookCaveIdle,
  aa=function()
    local queue=need(getAddressSafe('dqb2HammerDetachedTable'),
      'Hammer queue is unavailable.','ハンマーの破壊予約を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2HammerTerrainReleaseCode,4096,$SITE)
label(dqb2HammerTerrainReleaseBack)
dqb2HammerTerrainReleaseCode:
  pushfq
  push rax
  push rcx
  push rdx
  mov rax,@QUEUE@
  mov ecx,20
  db 85 C9 74 1D 48 8B 10 48 85 D2 74 0D 83 7A 28 01 75 07 C7 42 28 04 00 00 00 48 83 C0 08 FF C9 75 E3
  pop rdx
  pop rcx
  pop rax
  popfq
  $ORIG
  jmp dqb2HammerTerrainReleaseBack
$SITE:
  jmp dqb2HammerTerrainReleaseCode
dqb2HammerTerrainReleaseBack:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2HammerTerrainReleaseCode)
]]):gsub('@QUEUE@',hex(queue))
  end,
}

DQB2.F.hammerRange={boundary=false,hooks={'hammerBatchWorker','hammerDetachedTick','hammerTerrainRelease','hammerBatchMain','hammerBatchExpiry','hammerBatchOwnerExpiry','hammerRange'},
  prepare=prepareHammerRangeSettings,
}

local jumpHoldBytes={0x44,0x0F,0x28,0x54,0x24,0x50}
DQB2.SIGS.jumpInput={
  p='48 8B 0D ?? ?? ?? ?? 41 0F 28 C8 E8 ?? ?? ?? ?? 48 8B 0D ?? ?? ?? ?? E8 ?? ?? ?? ?? 48 8B 0D',
  kind='rip',disp=3,length=7,
  validate=function(address)
    for _,section in ipairs(DQB2.mainPE.sections) do
      if not section.execute and address&gt;=section.first and address+8&lt;=section.last then
        local input=pointed(address)
        return input~=nil and u32(input+0x248)==256 and pointed(input+0x250)~=nil
      end
    end
    return false
  end,
}
DQB2.SIGS.jumpHeld={
  p='48 83 EC 08 48 8B 81 50 02 00 00 44 8B DA 4E 63 04 98 41 80 BC 08 B0 02 00 00 00 74 07 B0 01 48 83 C4 08 C3 48 89 1C 24',
  validate=function(address)
    local alternate=bytes(address+0xD3,7)
    return alternate~=nil and db(alternate)=='48 8B 81 80 02 00 00'
  end,
}
local function jumpHoldSite(address)
  return equal(bytes(address,#jumpHoldBytes),jumpHoldBytes) and playerMotionTable(address,0xD8,0x5DD)~=nil
end
DQB2.SIGS.jumpHold={
  resolve=function()
    local method=playerMotionMethod(0xD8)
    return method and {method+0x5DD}
  end,
  validate=jumpHoldSite,
}
DQB2.HOOKS.jumpHold={
  sig='jumpHold',len=#jumpHoldBytes,validate=jumpHoldSite,quiesce=hookCaveIdle,
  aa=function()
    local motion=need(playerMotionTable(DQB2.needSig('jumpHold'),0xD8,0x5DD),
      'Player movement is unavailable.','プレイヤーの移動処理を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2JumpHoldCode,4096,$SITE)
label(dqb2JumpHoldRestore)
label(dqb2JumpHoldResume)
dqb2JumpHoldCode:
  pushfq
  push rax
  mov rax,@MOTION@
  cmp [rbx],rax
  jne dqb2JumpHoldRestore
  mov rax,@INPUT@
  mov rax,[rax]
  test rax,rax
  je dqb2JumpHoldRestore
  cmp dword ptr [rax+6C5],0
  jne dqb2JumpHoldRestore
  push rcx
  push rdx
  push r8
  push r9
  push r10
  push r11
  sub rsp,20
  mov rcx,rax
  mov edx,3
  mov rax,@HELD@
  call rax
  add rsp,20
  test al,al
  je short @f
  cmp dword ptr [rbp+14],3E800000
  jge short @f
  mov dword ptr [rbp+14],3E800000
@@:
  pop r11
  pop r10
  pop r9
  pop r8
  pop rdx
  pop rcx
dqb2JumpHoldRestore:
  pop rax
  popfq
  $ORIG
  jmp dqb2JumpHoldResume
$SITE:
  jmp dqb2JumpHoldCode
  $NOP
dqb2JumpHoldResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2JumpHoldCode)
]]):gsub('@MOTION@',hex(motion)):gsub('@INPUT@',hex(DQB2.needSig('jumpInput'))):gsub('@HELD@',hex(DQB2.needSig('jumpHeld')))
  end,
}
DQB2.F.jumpHold={boundary=false,hooks={'jumpHold'},prepare=function()
  DQB2.needSig('motionRegistry')
  DQB2.needSig('jumpInput')
  DQB2.needSig('jumpHeld')
end}

local jumpFactorBytes={0x4C,0x8B,0xDC,0x53,0x55,0x48,0x81,0xEC,0xB8,0,0,0}
local function jumpFactorSite(address)
  return equal(bytes(address,#jumpFactorBytes),jumpFactorBytes) and playerMotionTable(address,0xD8,0)~=nil
end
DQB2.SIGS.jumpFactor={
  resolve=function()
    local method=playerMotionMethod(0xD8)
    return method and {method}
  end,
  validate=jumpFactorSite,
}
DQB2.HOOKS.jumpFactor={
  sig='jumpFactor',len=#jumpFactorBytes,validate=jumpFactorSite,quiesce=hookCaveIdle,
  aa=function()
    local motion=need(playerMotionTable(DQB2.needSig('jumpFactor'),0xD8,0),
      'Player movement is unavailable.','プレイヤーの移動処理を取得できません。')
    return ([[
[ENABLE]
alloc(dqb2JumpFactorCode,4096,$SITE)
label(dqb2JumpFactor)
label(dqb2JumpAscending)
label(dqb2JumpRising)
label(dqb2JumpFactorNext)
label(dqb2JumpFactorResume)
registersymbol(dqb2JumpFactor)
dqb2JumpFactorCode:
  pushfq
  push rax
  mov rax,@MOTION@
  cmp [rcx],rax
  jne dqb2JumpFactorNext
  cmp dword ptr [rdx+14],0
  jg dqb2JumpRising
  mov byte ptr [dqb2JumpAscending],0
  jmp dqb2JumpFactorNext
dqb2JumpRising:
  mov al,1
  xchg [dqb2JumpAscending],al
  test al,al
  jne dqb2JumpFactorNext
  mov rax,@INPUT@
  mov rax,[rax]
  test rax,rax
  je dqb2JumpFactorNext
  test byte ptr [rax+1B8],08
  je dqb2JumpFactorNext
  mov eax,[dqb2JumpFactor]
  test eax,eax
  jle dqb2JumpFactorNext
  cmp eax,7F800000
  jae dqb2JumpFactorNext
  sub rsp,10
  movdqu [rsp],xmm0
  movss xmm0,[rdx+14]
  mulss xmm0,[dqb2JumpFactor]
  movss [rdx+14],xmm0
  movdqu xmm0,[rsp]
  add rsp,10
dqb2JumpFactorNext:
  pop rax
  popfq
  $ORIG
  jmp dqb2JumpFactorResume
align 4
dqb2JumpFactor:
  dd (float)2
dqb2JumpAscending:
  db 1
$SITE:
  jmp dqb2JumpFactorCode
  $NOP
dqb2JumpFactorResume:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2JumpFactor)
dealloc(dqb2JumpFactorCode)
]]):gsub('@MOTION@',hex(motion)):gsub('@INPUT@',hex(DQB2.needSig('jumpInput')))
  end,
}
DQB2.F.jumpFactor={boundary=false,hooks={'jumpFactor'},prepare=function()
  DQB2.needSig('motionRegistry')
  DQB2.needSig('jumpInput')
end}

local invincibleBytes={0x4C,0x8B,0xDC,0x56,0x41,0x56}
local function invincibleSite(address)
  local build=combatContext()
  return build~=nil and combatMethod(build.player,0x78)==address and equal(bytes(address,#invincibleBytes),invincibleBytes)
end
DQB2.SIGS.invincible={
  p='4C 8B DC 56 41 56 48 81 EC 98 04 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 84 24 70 04 00 00',
  off=0,validate=invincibleSite,
}
DQB2.HOOKS.invincible={
  sig='invincible',len=#invincibleBytes,validate=invincibleSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2HitFilter,4096,$SITE)
label(dqb2HitNext)
label(dqb2HitResume)
dqb2HitFilter:
  test rcx,rcx
  je dqb2HitNext
  mov rax,@PLAYER@
  cmp [rcx],rax
  jne dqb2HitNext
  ret
dqb2HitNext:
  $ORIG
  jmp dqb2HitResume
$SITE:
  jmp dqb2HitFilter
  $NOP
dqb2HitResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2HitFilter)
]]),
}
local fallDamageBytes={0x0F,0xB7,0xF0,0x66,0x3B,0xE8}
local function fallDamageExit(site)
  if not equal(bytes(site,#fallDamageBytes),fallDamageBytes) or
      not equal(bytes(site+6,2),{0x0F,0x84}) then return nil end
  local displacement=s32(site+8)
  local exit=displacement and site+12+displacement
  if exit and equal(bytes(exit,10),{0x48,0x8B,0xB4,0x24,0xA0,0,0,0,0xB0,1}) then return exit end
end
DQB2.SIGS.fallDamage={
  p='0F B7 F0 66 3B E8 0F 84 ?? ?? ?? ?? C6 44 24 38 01 48 8D 4C 24 40 45 33 C9 C6 44 24 30 01',
  validate=function(site) return fallDamageExit(site)~=nil end,
}
DQB2.HOOKS.fallDamage={
  sig='fallDamage',len=#fallDamageBytes,validate=DQB2.SIGS.fallDamage.validate,quiesce=hookCaveIdle,
  aa=function()
    local site=DQB2.needSig('fallDamage')
    local exit=need(fallDamageExit(site),'Landing damage path changed.','落下ダメージ処理が一致しません。')
    return combatAssembly([[
[ENABLE]
alloc(dqb2FallDamage,4096,$SITE)
label(dqb2FallDamageOriginal)
label(dqb2FallDamageResume)
dqb2FallDamage:
  $ORIG
  pushfq
  push rax
  mov rax,@PLAYER@
  cmp [rbx],rax
  pop rax
  jne dqb2FallDamageOriginal
  popfq
  jmp @EXIT@
dqb2FallDamageOriginal:
  popfq
  jmp dqb2FallDamageResume
$SITE:
  jmp dqb2FallDamage
  $NOP
dqb2FallDamageResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2FallDamage)
]])():gsub('@EXIT@',hex(exit))
  end,
}
local attackDispatchBytes={0x40,0x55,0x53,0x56,0x57}
local function attackDispatchSite(site)
  return equal(bytes(site,#attackDispatchBytes),attackDispatchBytes) and
    equal(bytes(site+0x83,24),{0x4C,0x8B,0x0B,0x48,0x8B,0xD7,0x44,0x0F,0xB7,0x06,0x48,0x8B,0xCB,
      0x44,0x8B,0x7E,0x0C,0x41,0xFF,0x91,0x88,0,0,0})
end
DQB2.SIGS.invincibleAttackDispatch={
  p='40 55 53 56 57 41 54 41 55 41 56 41 57 48 8D 6C 24 F1 48 81 EC B8 00 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 45 F7 48 8B 45 7F 4D 8B E9 48 8B 75 77 49 8B D8',
  validate=attackDispatchSite,
}
DQB2.HOOKS.invincibleAttackDispatch={
  sig='invincibleAttackDispatch',len=#attackDispatchBytes,validate=attackDispatchSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2AttackDispatch,4096,$SITE)
label(dqb2AttackDispatchNext)
label(dqb2AttackDispatchResume)
dqb2AttackDispatch:
  test r8,r8
  je dqb2AttackDispatchNext
  mov rax,@PLAYER@
  cmp [r8],rax
  jne dqb2AttackDispatchNext
  ret
dqb2AttackDispatchNext:
  $ORIG
  jmp dqb2AttackDispatchResume
$SITE:
  jmp dqb2AttackDispatch
dqb2AttackDispatchResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2AttackDispatch)
]]),
}
local attackEligibilityBytes={0x0F,0xB7,0x41,0x16,0x83,0xF8,0x08}
local function attackEligibilitySite(site)
  if not equal(bytes(site,#attackEligibilityBytes),attackEligibilityBytes)
      or not equal(bytes(site+7,2),{0x0F,0x87}) then return false end
  local displacement=s32(site+9)
  return displacement~=nil and equal(bytes(site+13+displacement,3),{0x32,0xC0,0xC3})
end
DQB2.SIGS.invincibleAttackEligibility={
  p='0F B7 41 16 83 F8 08 0F 87 ?? ?? ?? ?? 4C 8D 05 ?? ?? ?? ?? 41 8B 8C 80 ?? ?? ?? ?? 49 03 C8 FF E1',
  validate=attackEligibilitySite,
}
DQB2.HOOKS.invincibleAttackEligibility={
  sig='invincibleAttackEligibility',len=#attackEligibilityBytes,validate=attackEligibilitySite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2AttackEligibility,4096,$SITE)
label(dqb2AttackEligibilityNext)
label(dqb2AttackEligibilityResume)
dqb2AttackEligibility:
  test rdx,rdx
  je dqb2AttackEligibilityNext
  mov rax,@PLAYER@
  cmp [rdx],rax
  jne dqb2AttackEligibilityNext
  xor al,al
  ret
dqb2AttackEligibilityNext:
  $ORIG
  jmp dqb2AttackEligibilityResume
$SITE:
  jmp dqb2AttackEligibility
  $NOP
dqb2AttackEligibilityResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2AttackEligibility)
]]),
}
local landingEligibilityBytes={0x48,0x89,0x5C,0x24,0x08}
local function landingEligibilitySite(site)
  return equal(bytes(site,#landingEligibilityBytes),landingEligibilityBytes)
    and equal(bytes(site+0x1B,8),{0xFF,0x50,0x40,0x0F,0x57,0xF6,0x0F,0x2F})
end
DQB2.SIGS.invincibleLandingEligibility={
  p='48 89 5C 24 08 57 48 83 EC 30 48 8B 02 48 8B F9 48 8B CA 0F 29 74 24 20 48 8B DA FF 50 40 0F 57 F6 0F 2F C6 0F 87 ?? ?? ?? ?? 48 8B 03 48 8B CB',
  validate=landingEligibilitySite,
}
DQB2.HOOKS.invincibleLandingEligibility={
  sig='invincibleLandingEligibility',len=#landingEligibilityBytes,validate=landingEligibilitySite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2LandingEligibility,4096,$SITE)
label(dqb2LandingEligibilityNext)
label(dqb2LandingEligibilityResume)
dqb2LandingEligibility:
  test rdx,rdx
  je dqb2LandingEligibilityNext
  mov rax,@PLAYER@
  cmp [rdx],rax
  jne dqb2LandingEligibilityNext
  xor al,al
  ret
dqb2LandingEligibilityNext:
  $ORIG
  jmp dqb2LandingEligibilityResume
$SITE:
  jmp dqb2LandingEligibility
dqb2LandingEligibilityResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2LandingEligibility)
]]),
}
local sleepStatusBytes={0x40,0x55,0x56,0x57,0x41,0x54}
local function sleepStatusSite(site)
  local name=DQB2.mainName:lower()
  local rva=name=='dqb2.exe' and 0x799D90 or name=='dqb2_eu.exe' and 0x79BF00 or name=='dqb2_as.exe' and 0x799F90 or nil
  return rva~=nil and site==DQB2.mainBase+rva
    and equal(bytes(site,#sleepStatusBytes),sleepStatusBytes)
    and equal(bytes(site+0x277,2),{0x32,0xC0})
end
DQB2.SIGS.invincibleSleepStatus={
  p='40 55 56 57 41 54 41 56 41 57 48 8D AC 24 68 FC FF FF 48 81 EC 98 04 00 00 48 8B 05 ?? ?? ?? ?? 48 33 C4 48 89 85 80 03 00 00',
  validate=sleepStatusSite,
}
DQB2.HOOKS.invincibleSleepStatus={
  sig='invincibleSleepStatus',len=#sleepStatusBytes,validate=sleepStatusSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2SleepStatus,4096,$SITE)
label(dqb2SleepStatusNext)
label(dqb2SleepStatusResume)
dqb2SleepStatus:
  cmp r8d,09
  jne dqb2SleepStatusNext
  test rdx,rdx
  je dqb2SleepStatusNext
  mov rax,@PLAYER@
  cmp [rdx],rax
  jne dqb2SleepStatusNext
  xor eax,eax
  ret
dqb2SleepStatusNext:
  $ORIG
  jmp dqb2SleepStatusResume
$SITE:
  jmp dqb2SleepStatus
  $NOP
dqb2SleepStatusResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2SleepStatus)
]]),
}
local function normalLandingTransition(site)
  local entry=bytes(site,53)
  local name=DQB2.mainName:lower()
  return (name=='dqb2.exe' or name=='dqb2_eu.exe' or name=='dqb2_as.exe') and playerMotionTable(site,0x258,0)~=nil
    and entry and db(entry)=='40 56 48 83 EC 30 48 8B 01 45 33 C9 0F 29 74 24 20 48 8B F1 48 89 5C 24 40 41 0F B6 D8 48 89 91 A0 00 00 00 41 B0 01 0F BF 52 08 48 89 6C 24 48 4C 89 74 24 58'
end
DQB2.SIGS.invincibleLandingMotion={
  resolve=function()
    local site=playerMotionMethod(0x258)
    return site and {site}
  end,
  validate=normalLandingTransition,
}
DQB2.HOOKS.invincibleLandingMotion={
  sig='invincibleLandingMotion',len=6,validate=normalLandingTransition,quiesce=hookCaveIdle,
  aa=function()
    local site=DQB2.needSig('invincibleLandingMotion')
    local motion=need(playerMotionTable(site,0x258,0),'Player motion table changed.','プレイヤーのモーションテーブルが変わっています。')
    return ([[
[ENABLE]
alloc(dqb2LandingMotion,4096,$SITE)
label(dqb2LandingMotionNext)
dqb2LandingMotion:
  pushfq
  push rax
  push r10
  mov rax,%X
  cmp [rcx],rax
  jne dqb2LandingMotionNext
  test rdx,rdx
  je dqb2LandingMotionNext
  cmp dword ptr [rdx+06],00480035
  jne dqb2LandingMotionNext
  cmp dword ptr [rdx+0A],000A0003
  jne dqb2LandingMotionNext
  cmp word ptr [rdx+0E],12
  jne dqb2LandingMotionNext
  mov rax,[rcx+60]
  test rax,rax
  je dqb2LandingMotionNext
  cmp dword ptr [rax],35
  jne dqb2LandingMotionNext
  movzx r10d,word ptr [rax+4A]
  cmp r10d,3B
  jne dqb2LandingMotionNext
  movzx r10d,word ptr [rax+48]
  mov rax,[rax+40]
  test rax,rax
  je dqb2LandingMotionNext
  mov rax,[rax+r10*8+1C8]
  test rax,rax
  je dqb2LandingMotionNext
  cmp dword ptr [rax+06],00470035
  jne dqb2LandingMotionNext
  cmp dword ptr [rax+0A],00000003
  jne dqb2LandingMotionNext
  mov rdx,rax
dqb2LandingMotionNext:
  pop r10
  pop rax
  popfq
  $ORIG
  jmp %X
$SITE:
  jmp dqb2LandingMotion
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2LandingMotion)
]]):format(motion,site+6)
  end,
}

local invincibleHooks={'invincibleAttackDispatch','invincible','hpSubtract','hpFloor','fallDamage'}
DQB2.F.invincible={boundary=false,hooks=invincibleHooks,prepare=function()
  local feature=DQB2.F.invincible
  local name=DQB2.mainName:lower()
  if name=='dqb2.exe' or name=='dqb2_eu.exe' or name=='dqb2_as.exe' then
    feature.hooks={'invincibleAttackEligibility','invincibleLandingEligibility','invincibleLandingMotion','invincibleSleepStatus',table.unpack(invincibleHooks)}
  else
    feature.hooks=invincibleHooks
  end
end}

local criticalBytes={0x8B,0x5C,0x24,0x34,0x84,0xC0}
local function criticalSite(address)
  local build=combatContext()
  return build~=nil and address==DQB2.mainBase+build.critical and equal(bytes(address,#criticalBytes),criticalBytes)
end
DQB2.SIGS.critical={
  p='F3 0F 59 C6 F3 48 0F 2C C0 0F B7 D0 E8 ?? ?? ?? ?? 8B 5C 24 34 84 C0 48 8B 7C 24 58 B9 01 00 00 00 0F B6 DB 0F 45 D9',
  off=17,validate=criticalSite,
}
DQB2.HOOKS.critical={
  sig='critical',len=#criticalBytes,validate=criticalSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2CriticalCode,4096,$SITE)
label(dqb2CriticalOriginal)
label(dqb2CriticalResume)
dqb2CriticalCode:
  push r10
  mov r10,@PLAYER@
  cmp [r12],r10
  jne dqb2CriticalOriginal
  mov r10,@MONSTER@
  cmp [rsi],r10
  jne dqb2CriticalOriginal
  mov al,1
dqb2CriticalOriginal:
  pop r10
  $ORIG
  jmp dqb2CriticalResume
$SITE:
  jmp dqb2CriticalCode
  $NOP
dqb2CriticalResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2CriticalCode)
]]),
}
DQB2.F.critical={boundary=false,hooks={'critical'}}

local oneHitBytes={0x48,0x8B,0x03,0x0F,0xB7,0xD6}
local function oneHitSite(address)
  local build=combatContext()
  return build~=nil and address==DQB2.mainBase+build.oneHit and equal(bytes(address,#oneHitBytes),oneHitBytes)
end
DQB2.SIGS.oneHit={
  p='8D 70 FF 48 8B 03 0F B7 D6 44 0F B7 47 02 48 8B CB FF 90 C8 02 00 00 0F B7 57 08',
  off=3,validate=oneHitSite,
}
DQB2.HOOKS.oneHit={
  sig='oneHit',len=#oneHitBytes,validate=oneHitSite,quiesce=hookCaveIdle,
  aa=combatAssembly([[
[ENABLE]
alloc(dqb2OneHitCode,4096,$SITE)
label(dqb2OneHitNext)
label(dqb2OneHitResume)
dqb2OneHitCode:
  $ORIG
  pushfq
  push r10
  test edx,edx
  jz dqb2OneHitNext
  cmp byte ptr [rdi+0F],0
  jne dqb2OneHitNext
  mov r10,@MONSTER@
  cmp rax,r10
  jne dqb2OneHitNext
  mov r10,[@OWNER@]
  test r10,r10
  jz dqb2OneHitNext
  mov r10,[r10+48]
  test r10,r10
  jz dqb2OneHitNext
  cmp word ptr [r10+2C8],0
  je dqb2OneHitNext
  mov r10w,[r10+2C8]
  cmp [rdi+02],r10w
  jne dqb2OneHitNext
  movzx edx,word ptr [rbx+E4A]
dqb2OneHitNext:
  pop r10
  popfq
  jmp dqb2OneHitResume
$SITE:
  jmp dqb2OneHitCode
  $NOP
dqb2OneHitResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2OneHitCode)
]]),
}
DQB2.F.oneHit={boundary=false,hooks={'oneHit'}}

local dropBytes={0x44,0x0F,0xB7,0x7D,0x18,0x45,0x84,0xF6}
local dropBuilds={
  ['dqb2.exe']={defeat=0x62078F,reward=0x623261,draw=0x5F62DD},
  ['dqb2_eu.exe']={defeat=0x62230F,reward=0x624DE1,draw=0x5F7E5D},
  ['dqb2_as.exe']={defeat=0x620B3F,reward=0x623611,draw=0x5F668D},
}
local function dropCallTargets(site,destination)
  local call=bytes(site,5)
  if not call or call[1]~=0xE8 then return false end
  local target=site+5+string.unpack('&lt;i4',string.char(table.unpack(call,2,5)))
  if target==destination then return true end
  local thunk=bytes(target,5)
  return thunk~=nil and thunk[1]==0xE9 and
    target+5+string.unpack('&lt;i4',string.char(table.unpack(thunk,2,5)))==destination
end
local function enemyDropSite(address)
  local build=dropBuilds[DQB2.mainName:lower()]
  if not build or address~=DQB2.mainBase+build.draw or not equal(bytes(address,#dropBytes),dropBytes) then return false end
  local defeat,reward=DQB2.mainBase+build.defeat,DQB2.mainBase+build.reward
  local rewardEntry,drawEntry=reward-0x161,address-0xDD
  return equal(bytes(rewardEntry,15),{0x48,0x89,0x4C,0x24,0x08,0x56,0x41,0x56,0x48,0x81,0xEC,0xB8,0,0,0}) and
    equal(bytes(drawEntry,10),{0x40,0x53,0x56,0x57,0x41,0x54,0x48,0x83,0xEC,0x28}) and
    dropCallTargets(defeat,rewardEntry) and dropCallTargets(reward,drawEntry)
end
DQB2.SIGS.enemyDrop={
  p='0F B7 4D 00 FF C9 83 F9 1E 77 78 44 0F B7 7D 18 45 84 F6 74 19 45 33 C0',
  off=11,validate=enemyDropSite,
}
DQB2.HOOKS.enemyDrop={
  sig='enemyDrop',len=#dropBytes,validate=enemyDropSite,quiesce=hookCaveIdle,
  aa=function()
    local build=dropBuilds[DQB2.mainName:lower()]
    return ([[
[ENABLE]
alloc(dqb2DropCode,4096,$SITE)
label(dqb2EnemyDropFactor)
label(dqb2DropNext)
label(dqb2DropGuaranteed)
label(dqb2DropResume)
registersymbol(dqb2EnemyDropFactor)
dqb2DropCode:
  $ORIG
  cmp word ptr [rbp],1
  jne dqb2DropNext
  mov r10,@REWARD@
  cmp [rsp+48],r10
  jne dqb2DropNext
  mov r10,@DEFEAT@
  cmp [rsp+118],r10
  jne dqb2DropNext
  mov r10d,[dqb2EnemyDropFactor]
  cmp r10d,1
  jl dqb2DropNext
  imul r10,r15
  cmp r10,#10000
  ja dqb2DropGuaranteed
  mov r15d,r10d
  jmp dqb2DropNext
dqb2DropGuaranteed:
  mov r15d,#10000
dqb2DropNext:
  test r14b,r14b
  jmp dqb2DropResume
align 4
dqb2EnemyDropFactor:
  dd 2
$SITE:
  jmp dqb2DropCode
  $NOP
dqb2DropResume:
[DISABLE]
$SITE:
  $ORIG
unregistersymbol(dqb2EnemyDropFactor)
dealloc(dqb2DropCode)
]]):gsub('@REWARD@',hex(DQB2.mainBase+build.reward+5)):gsub('@DEFEAT@',hex(DQB2.mainBase+build.defeat+5))
  end,
}
DQB2.F.enemyDrop={boundary=false,hooks={'enemyDrop'}}

local function defineStealthHook(name,pattern,instruction,aa)
  local function validate(address)
    local build=combatContext()
    return build~=nil and address==DQB2.mainBase+build[name] and equal(bytes(address,#instruction),instruction)
  end
  DQB2.SIGS[name]={p=pattern,off=0,validate=validate}
  DQB2.HOOKS[name]={sig=name,len=#instruction,validate=validate,quiesce=hookCaveIdle,aa=combatAssembly(aa)}
end
defineStealthHook('stealthSight',
  '40 56 57 41 55 48 81 EC C0 00 00 00 48 8B 05 ?? ?? ?? ?? 45 0F B6 E8 48 8B FA 48 8B F1',
  {0x40,0x56,0x57,0x41,0x55},[[
[ENABLE]
alloc(dqb2SightCode,4096,$SITE)
label(dqb2SightNext)
label(dqb2SightResume)
dqb2SightCode:
  test rcx,rcx
  je dqb2SightNext
  test rdx,rdx
  je dqb2SightNext
  mov rax,@MONSTER@
  cmp [rcx],rax
  jne dqb2SightNext
  mov rax,@PLAYER@
  cmp [rdx],rax
  jne dqb2SightNext
  xor eax,eax
  ret
dqb2SightNext:
  $ORIG
  jmp dqb2SightResume
$SITE:
  jmp dqb2SightCode
dqb2SightResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2SightCode)
]])
defineStealthHook('stealthTarget',
  '66 41 39 9D C8 02 00 00 0F 84 EB 00 00 00 49 8B 55 10 49 8D 4D 10 FF 92 98 01 00 00',
  {0x66,0x41,0x39,0x9D,0xC8,0x02,0,0},[[
[ENABLE]
alloc(dqb2TargetCode,4096,$SITE)
label(dqb2TargetNext)
label(dqb2TargetResume)
dqb2TargetCode:
  test r14b,r14b
  jne dqb2TargetNext
  push r10
  mov r10,@MONSTER@
  cmp [rsi],r10
  pop r10
  jne dqb2TargetNext
  cmp r10,r10
  jmp dqb2TargetResume
dqb2TargetNext:
  $ORIG
  jmp dqb2TargetResume
$SITE:
  jmp dqb2TargetCode
  $NOP
dqb2TargetResume:
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2TargetCode)
]])
DQB2.F.stealth={boundary=false,hooks={'stealthSight','stealthTarget'}}

local cookingProgressOriginal={0x41,0x3B,0xDD,0x73,0x76}
local function validateCookingProgress(site)
  local before=bytes(site-44,13)
  return equal(bytes(site,5),cookingProgressOriginal)
    and before and db(before)=='66 89 45 07 0F B7 47 60 66 89 45 09 0F'
    and equal(bytes(site+0x7B,6),{0x8B,0x97,0x8C,0,0,0})
end
DQB2.SIGS.cookingProgress={
  p='66 89 45 07 0F B7 47 60 66 89 45 09 0F B6 47 7C 24 01 88 45 0B 41 8B C7 4D 85 F6 74 05 41 0F B6 46 02 83 F8 03 0F 57 F6 0F 94 45 0C 41 3B DD 73 76 48 8B CF E8',
  off=44,validate=validateCookingProgress,
  knownSite=function()
    if DQB2.mainName:lower()=='dqb2.exe' then
      local site=DQB2.mainBase+0x5B2C6D
      if validateCookingProgress(site) then return site end
    end
  end,
}
DQB2.HOOKS.cookingProgress={
  sig='cookingProgress',len=5,validate=validateCookingProgress,quiesce=hookCaveIdle,
  aa=function()
    local site=DQB2.needSig('cookingProgress')
    return ([[
[ENABLE]
alloc(dqb2CookingProgress,4096,$SITE)
label(dqb2CookingReady)
dqb2CookingProgress:
  push rax
  mov ax,[rbp+7]
  cmp ax,[rbp+9]
  pop rax
  ja dqb2CookingReady
  cmp ebx,r13d
  jae dqb2CookingReady
  jmp %X
dqb2CookingReady:
  jmp %X
$SITE:
  jmp dqb2CookingProgress
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2CookingProgress)
]]):format(site+5,site+0x7B)
  end,
}
DQB2.F.instantCooking.hooks={'instantCooking','cookingProgress'}

local enemyActionBytes={0x48,0x63,0x43,0x1C,0x48,0x8D,0x0D}
local function enemyActionTable(site)
  local displacement=s32(site+7)
  if displacement then return site+11+displacement end
end
local enemyActionBuilds={
  ['dqb2.exe']={site=0x3647BA,transition=0x262D00,idle=0x365610,call='81 F3 CC FF'},
  ['dqb2_eu.exe']={site=0x364FBA,transition=0x263430,idle=0x365E10,call='6A E9 CC FF'},
  ['dqb2_as.exe']={site=0x364A3A,transition=0x262F80,idle=0x365890,call='73 F2 CC FF'},
}
local function enemyIdleTransition(site)
  local build=enemyActionBuilds[DQB2.mainName:lower()]
  if not build then return nil end
  local base=DQB2.mainBase
  local transition=base+build.transition
  local entry=bytes(transition,27)
  local idle=bytes(base+build.idle,15)
  local relative=s32(transition+0x32)
  if relative and transition+0x36+relative==enemyActionTable(site)
      and entry and db(entry)=='48 89 5C 24 18 48 89 74 24 20 57 48 83 EC 20 48 63 FA 48 8B D9 39 79 1C 0F 84 BA'
      and idle and db(idle)=='45 33 C9 41 8D 55 13 45 33 C0 E8 '..build.call then
    return transition
  end
end
local function validateEnemyAction(site)
  local head=bytes(site,11)
  local tail=bytes(site+11,35)
  return head and equal({table.unpack(head,1,7)},enemyActionBytes)
    and tail and db(tail)=='0F 28 D6 48 8D 93 A0 01 00 00 48 8B 0C C1 48 8B 01 FF 50 20 0F 28 CE 39 BB 68 01 00 00 74 0E 48 8D 8B 50'
    and equal(bytes(site+0x41,6),{0x89,0xBB,0xA8,1,0,0})
    and enemyIdleTransition(site)~=nil
end
DQB2.SIGS.enemyAction={
  p='48 63 43 1C 48 8D 0D ?? ?? ?? ?? 0F 28 D6 48 8D 93 A0 01 00 00 48 8B 0C C1 48 8B 01 FF 50 20 0F 28 CE 39 BB 68 01 00 00',
  validate=validateEnemyAction,
  knownSite=function()
    local build=enemyActionBuilds[DQB2.mainName:lower()]
    if build then
      local site=DQB2.mainBase+build.site
      if validateEnemyAction(site) then return site end
    end
  end,
}
DQB2.HOOKS.enemyAction={
  sig='enemyAction',len=11,validate=validateEnemyAction,quiesce=hookCaveIdle,
  aa=function()
    local site=DQB2.needSig('enemyAction')
    return ([[
[ENABLE]
alloc(dqb2EnemyActionCode,4096,$SITE)
label(dqb2EnemyActionNext)
label(dqb2EnemyActionIdle)
dqb2EnemyActionCode:
  mov rcx,[rbx+8]
  test rcx,rcx
  je dqb2EnemyActionNext
  mov rax,[rcx]
  call qword ptr [rax+288]
  test rax,rax
  je dqb2EnemyActionNext
  mov rcx,%X
  cmp [rax],rcx
  jne dqb2EnemyActionNext
  cmp byte ptr [rax+10A0],0
  jne dqb2EnemyActionNext
  cmp word ptr [rax+E4A],0
  je dqb2EnemyActionNext
  cmp dword ptr [rbx+1C],13
  je dqb2EnemyActionIdle
  mov rcx,rbx
  mov edx,13
  xor r8d,r8d
  xor r9d,r9d
  call %X
dqb2EnemyActionIdle:
  jmp %X
dqb2EnemyActionNext:
  movsxd rax,dword ptr [rbx+1C]
  mov rcx,%X
  jmp %X
$SITE:
  jmp dqb2EnemyActionCode
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(dqb2EnemyActionCode)
]]):format(DQB2.mainBase+combatBuilds[DQB2.mainName:lower()].monster,enemyIdleTransition(site),site+0x41,enemyActionTable(site),site+11)
  end,
}
DQB2.F.enemyAi={boundary=false,hooks={'enemyAction'}}

local craftMaterialBuilds={
  ['dqb2.exe']={
    checks={
      {0x7F4804,'89 6C 24 40 44 89 64 24 20 E8 58 CF 82 FF'},
      {0x7EEA5F,'97 C7 44 24 20 01 00 00 00 E8 FD 2C 83 FF'},
      {0x81F301,'8B D0 01 00 00 48 0F 45 D0 E8 2C A2 81 FF'},
    },
    callers={
      {0x40C37A,'0F B7 49 64 C6 44 24 20 00 E8 60 8C C3 FF'},
      {0x5EC9D3,'8B C6 88 5C 24 20 49 8B D7 E8 07 86 A5 FF'},
      {0x7F4914,'40 10 45 8B C2 48 0F 45 D0 E8 C6 06 85 FF'},
      {0x8C0B97,'8B C6 4C 0F 45 D2 49 8B D2 E8 43 44 78 FF'},
      {0x9ECEB0,'45 D1 0F B7 8E D0 01 00 00 E8 2A 81 65 FF'},
    },
    definitions=0x13C1048,
  },
  ['dqb2_eu.exe']={
    checks={
      {0x7F6FF4,'89 6C 24 40 44 89 64 24 20 E8 FC A4 82 FF'},
      {0x7F10EF,'97 C7 44 24 20 01 00 00 00 E8 01 04 83 FF'},
      {0x8224C6,'8B D0 01 00 00 48 0F 45 D0 E8 64 6E 81 FF'},
    },
    callers={
      {0x40CC3A,'0F B7 49 64 C6 44 24 20 00 E8 CF 81 C3 FF'},
      {0x5EE553,'8B C6 88 5C 24 20 49 8B D7 E8 B6 68 A5 FF'},
      {0x7F7104,'40 10 45 8B C2 48 0F 45 D0 E8 05 DD 84 FF'},
      {0x8CA071,'8B C6 4C 0F 45 D2 49 8B D2 E8 98 AD 77 FF'},
      {0x9FC4C2,'45 D1 0F B7 8E D0 01 00 00 E8 47 89 64 FF'},
    },
    definitions=0x13F2118,
  },
  ['dqb2_as.exe']={
    checks={
      {0x7F46F4,'89 6C 24 40 44 89 64 24 20 E8 D0 D1 82 FF'},
      {0x7EE94F,'97 C7 44 24 20 01 00 00 00 E8 75 2F 83 FF'},
      {0x81FCD1,'8B D0 01 00 00 48 0F 45 D0 E8 D3 99 81 FF'},
    },
    callers={
      {0x40C5FA,'0F B7 49 64 C6 44 24 20 00 E8 61 8B C3 FF'},
      {0x5ECD83,'8B C6 88 5C 24 20 49 8B D7 E8 D8 83 A5 FF'},
      {0x7F4804,'40 10 45 8B C2 48 0F 45 D0 E8 57 09 85 FF'},
      {0x8C3ACB,'8B C6 4C 0F 45 D2 49 8B D2 E8 90 16 78 FF'},
      {0x9F667F,'45 D1 0F B7 8E D0 01 00 00 E8 DC EA 64 FF'},
    },
    definitions=0x13DFFD8,
  },
}
local function craftMaterialCount(key,jpRva,euRva,asRva,original,register,success,successBytes)
  local function buildRva()
    local name=DQB2.mainName:lower()
    return name=='dqb2.exe' and jpRva or name=='dqb2_eu.exe' and euRva or name=='dqb2_as.exe' and asRva or nil
  end
  local function validate(site)
    local rva=buildRva()
    return rva~=nil and site==DQB2.mainBase+rva
      and equal(bytes(site,#original),original)
      and equal(bytes(site+success,#successBytes),successBytes)
  end
  DQB2.SIGS[key]={resolve=function() local rva=buildRva(); return rva and {DQB2.mainBase+rva} end,validate=validate}
  DQB2.HOOKS[key]={sig=key,len=#original,validate=validate,quiesce=hookCaveIdle,aa=function()
    local site=DQB2.needSig(key)
    local base=DQB2.mainBase
    local build=craftMaterialBuilds[DQB2.mainName:lower()]
    for _,guard in ipairs(build.checks) do
      local actual=bytes(base+guard[1],14)
      need(actual and db(actual)==guard[2],
        'Craft material check changed.','クラフトの素材判定命令が変わっています。')
    end
    local callerChecks={([[
  mov rax,%X
  cmp [rsp+10B0],rax
  jne %sCheck
  mov rax,%X
  cmp [rsp+11D0],rax
  je %sCategory
  jmp %sOriginal
%sCheck:
  mov rax,%X
  cmp [rsp+10B0],rax
  jne %sOriginal
]]):format(base+build.checks[2][1]+14,key,base+build.checks[3][1]+14,key,key,key,base+build.checks[1][1]+14,key)}
    for _,caller in ipairs(build.callers) do
      local addr,expected=table.unpack(caller)
      local actual=bytes(base+addr-9,14)
      need(actual and db(actual)==expected,'Craft caller has changed.','クラフトの呼び出し元が変わっています。')
      callerChecks[#callerChecks+1]=('  mov rax,%X\n  cmp [rsp+11E0],rax\n  je %sCategory\n'):format(base+addr+5,key)
    end
    callerChecks[#callerChecks+1]=([[
  jmp %sOriginal
%sCategory:
  push rdx
  mov edx,[rsp+58]
  test edx,edx
  je %sAllow
  mov rax,%X
  mov rax,[rax]
  test rax,rax
  je %sKeep
  mov rax,[rax]
  test rax,rax
  je %sKeep
  mov rax,[rax+58]
  test rax,rax
  je %sKeep
  cmp edx,[rax+960]
  jae %sKeep
  shl edx,2
  add edx,[rax+968]
  add rdx,[rax+970]
  je %sKeep
  cmp byte ptr [rdx+1],0
  jne %sKeep
%sAllow:
  pop rdx
  jmp %sApply
%sKeep:
  pop rdx
]]):format(key,key,key,base+build.definitions,key,key,key,key,key,key,key,key,key)
    return ([[
[ENABLE]
alloc(%s,4096,$SITE)
label(%sCheck)
label(%sCategory)
label(%sAllow)
label(%sKeep)
label(%sApply)
label(%sOriginal)
label(%sEnough)
%s:
  cmp %s,edi
  jae %sEnough
  push rax
%s%sOriginal:
  pop rax
  cmp byte ptr [r15+8],r14b
  jmp %X
%sApply:
  pop rax
  mov %s,edi
%sEnough:
  jmp %X
$SITE:
  jmp %s
  $NOP
[DISABLE]
$SITE:
  $ORIG
dealloc(%s)
]]):format(key,key,key,key,key,key,key,key,key,register,key,table.concat(callerChecks),key,
      site+#original,key,register,key,site+success,key,key)
  end}
end
craftMaterialCount('dqb2CraftMaterialCount',0x803A21,0x806291,0x803F91,
  {0x3B,0xEF,0x73,0x0C,0x45,0x38,0x77,0x08},'ebp',0x10,{0x80,0x7E,0x28,0x01,0x75})
craftMaterialCount('dqb2CraftMaterialCountAux',0x80381B,0x80608B,0x803D8B,
  {0x44,0x3B,0xDF,0x73,0x0C,0x45,0x38,0x77,0x08},'r11d',0x11,{0xFF,0x03})
DQB2.F.craftRequirements={boundary=false,hooks={'dqb2CraftMaterialCount','dqb2CraftMaterialCountAux'},
  available=function() return craftMaterialBuilds[DQB2.mainName:lower()]~=nil end}

local restoreHook=DQB2.hookOff
function DQB2.hookOff(name)
  local state=DQB2.hooks[name]
  local hook=DQB2.HOOKS[name]
  if not hook or (hook.quiesce~=hookCaveIdle and name~=xpHooks[2] and name~=xpHooks[3]) then return restoreHook(name) end
  if not state or state.failedInstall then return restoreHook(name) end
  if name==xpHooks[1] then
    need(not DQB2.hooks[xpHooks[2]] and not DQB2.hooks[xpHooks[3]],
      'XP display hooks are still installed.','XP表示のフックが残っています。')
  elseif name=='moveSpeed' then
    need(not DQB2.hooks.moveSpeedCap and not DQB2.hooks.ladderStep,
      'Movement-dependent hooks are still installed.','移動速度を参照するフックが残っています。')
  end
  pause()
  local ok,reason=pcall(restoreHook,name)
  unpause()
  if not ok then error(reason,0) end
end

DQB2.initCollapse()
DQB2.applyLang()
</LuaScript>
</CheatTable>