Examples

Twenty-one complete mods, each showing a different part of the API. They are in the download's examples/mods/ folder (the repository's examples/ folder also has a gallery with a screenshot of each): copy one into your mods folder to try it, then change it. Every one of them is tested in the game, and all but four run in both games ("games": ["dinohunter", "iceage"] in their mod.json): the Hunting Lodge is for Ice Age, the Swiftclaw, Extra Dinos and Extra Guns are for Dinosaur Hunter. The script mods pick their creatures with game.id() (Ice Age: wolves, a boss mammoth, a pet wolf, its animals in the arena); the content packs (Content packs) keep what differs between the games in content/dinohunter/ and content/iceage/ (below).

Mod Keys Shows
Creature Labels the draw event, world.creatures, c:screen(), settings, a creature's mood (c.mood, API 3)
Survival Waves waves placed with world.randomPoint, packs that hunt the hunter (group.create, g:hunt), c.mood, the death event, lives, a results page (API 3)
Boss Rex B (phone: BOSS) armour (c.armor), phases from the damage event, a bite that hurts instead of killing (creature_attack), c.moveSpeed, c:roar, a darker sky (world.weather), a boss health bar (API 3)
Admin Menu F1 a mod menu tab with sub-tabs: a live table, camera, possession; the selected creature's brain, mood, tame and armor, species, weapon, weather, wind and hunter values, game.changes() (API 3)
Perk Shop P (phone: PERKS) perks that change the game's values (player.speed, player.maxHealth, weapons.get ...), a shop page in the game's style (menu.page), points and perks saved between sessions (API 3)
Pet Raptor K (phone: PET) a Lua brain (c.brain) with the game's own walking, running and idles (c:walkTo, c:runTo, c:idle), c.tame (API 3)
Guard Pet K, G (phone: PET, SIC) a Lua brain (c.brain), one creature against another (c:attack), the hunt events, player.aim() (API 3)
Dino Arena F7, F1 (phone: ARENA) a whole game mode: pairings with c:attack, pens, ring and hazards as zones, the damage / death events for handicaps, kill cam and statistics, bets, tournaments, a results page (API 3)
Clean HUD H, Esc (phone: HUD) the game's own HUD: hud.hide, hud.offset, hud.scale, player.ammo, the back event; a cell in the hunt's menu and a counter in the game's font (the gui event, API 3)
Shader Lab F8, F1 (phone: LAB) the shader API (API 4): world and screen effects, the shader groups, live GLSL (shader.setSource), the draw event for a camcorder overlay, mod.exports for other mods
Swiftclaw a dinosaur made in Blender: one glTF file with its model, skeleton, texture and animations (glTF), a content-pack species with its own model, card and menu picture (API 4)
Extra Dinos six new hunt species made in Blender, each with its own Lua brain (c.brain) built on one shared brain module: the game's senses, its walk, chase and kill (c:stockAI, c:walkTo, c:runTo, c:senses), states with time limits; their own sounds, cards and menu pictures (API 4)
Extra Guns four new weapons made in Blender, with the hunter's hands, each in the slot of one of the game's weapons, with its own stats, sounds, card and menu picture; a content pack without a script (API 4)
Hunting Lodge Ice Age: a content pack (a new animal, new equipment) and a page in the game's style: menu.page, menu.list, draw.sprite
Living Herds populations (populations.json): herds near water that flee together, a raptor pack (a wolf pack) with a territory that hunts as a group; Ice Age's mammoth herds in a wedge (API 3)
Storm Chaser F3, F4, F5 (phone: WEATHER, STRIKE, AUTO) the weather (API 4): presets that fade in and out (weather.set), lightning strikes (weather.strike), the lightning event; the map's own weather back when the mod is off
Sandbox Panel F6, F1 (phone: SANDBOX) the data layer (API 3): species, creature fields, weapons and slots, the hunter's overrides, weather and wind; all undone when the mod is off
Content packs for both games content/dinohunter/ and content/iceage/: Alpha T-Rex (a new species in each game, and a script for its armour and roar), Cheap Hunting (rules), Elephant Gun (a weapon)

Creature Labels

A name, distance and health bar over every creature near the hunter, with three settings in the mod menu. A line above the name says when a creature is alert, hunting you or fleeing (c.mood, API 3).

-- Creature Labels: a name, distance and health bar over every creature near the hunter, and what it thinks of him.
-- Shows: the draw event, world.creatures with a filter, c:screen(), draw.text / draw.bar, settings, c.mood (API 3).

mod.setting("enabled", true, { label = "Show labels" })
mod.setting("range", 6000, { label = "Range", min = 1000, max = 20000, help = "How far away creatures get a label" })
mod.setting("dead", false, { label = "Label dead bodies too" })

-- c.mood: "calm", "alert" (it knows he is there), "hunt" (it chases him), "flee" (it runs from him)
local MOODS = { alert = { "alert", "#ffd040" }, hunt = { "HUNTING YOU", "#ff5040" }, flee = { "fleeing", "#80c8ff" } }

local function healthColor(f)
  if f > 0.6 then return "#5fd35f" elseif f > 0.3 then return "#f0c040" else return "#e04a3a" end
end

on("draw", function()
  if not (game.inHunt() and mod.settings.enabled) or game.paused() or not player.alive() then return end
  for _, c in ipairs(world.creatures({ radius = mod.settings.range, all = mod.settings.dead })) do
    local sx, sy = c:screen()
    if sx and c.alive then
      local f = c.health / c.maxHealth
      draw.text(sx, sy - 26, string.format("%s  %dm", c.name, math.floor(c.distance / 128)), "white", 18, "center")
      draw.bar(sx - 40, sy - 6, 80, 7, f, healthColor(f))
      local mood = MOODS[c.mood]
      if mood then draw.text(sx, sy - 46, mood[1], mood[2], 16, "center") end
    elseif sx then
      draw.text(sx, sy - 26, c.name .. " (dead)", "gray", 18, "center")
    end
  end
end)

Survival Waves

Waves of predators that grow every round, three lives, the best wave saved. Each wave starts out of sight, 30 to 50 m away (Ice Age: 17 to 28 m), at a place the species can stand on (world.randomPoint), in packs of up to four that hunt the hunter together: they spread around him and attack in turns (group.create{kind = "pack"}, g:hunt()); one left over comes straight at him (c.mood = "hunt"). The death event counts them, whatever killed them; at the game over a page in the game's style shows the wave, the kills and the best wave. The settings choose the attackers and the pace; the attackers are each game's predators (raptors and the Allosaurus, or wolves, hyaenodons, smilodons and titanis birds in Ice Age). Switched off, the mod takes its waves with it. Needs API 3.

-- Survival Waves: every round sends more predators at the hunter; survive as long as you can.
-- Shows: waves placed with world.randomPoint (away from the hunter, where the species can stand), packs that hunt the
-- hunter together (group.create, g:hunt) or a lone hunter (c.mood = "hunt"), the death event for counting, lives with
-- player_death, saved data, a HUD and a results page in the game's style (menu.page); one mod for both games.

-- the predators of each game ("games" in mod.json lists both) and how far away a wave starts (Ice Age's smilodon
-- runs off from a hunter farther than about 36 m, so its waves start closer)
local ATTACKERS = {
  dinohunter = { "velociraptor", "utahraptor", "troodon", "allosaurus" },
  iceage = { "wolf", "hyaenodon", "smilodon", "titanis" },
}
local START = { dinohunter = { 4000, 6000 }, iceage = { 2200, 3600 } }
local attackers, start = ATTACKERS[game.id()], START[game.id()]

mod.setting("interval", 45, { label = "Seconds between waves", min = 15, max = 120 })
mod.setting("lives", 3, { label = "Lives", min = 1, max = 9 })
mod.setting("species", attackers[1], { label = "Attackers", options = attackers })

local save = mod.load() or { best = 0 }
local wave, lives, alive, kills, nextWave, running = 0, 0, 0, 0, 0, false

-- a place out of sight where the species can stand (the game's own test: no trees, water or steep ground close by);
-- where the ground near the hunter has none (a forest, a lake), farther out, else any dry ground
local function placeFor(species)
  for _, try in ipairs({ { start[2], species }, { start[2] * 2, species }, { start[2] } }) do
    local x, z = world.randomPoint({ minHunterDistance = start[1], maxHunterDistance = try[1], species = try[2] })
    if x then return x, z end
  end
end

-- a pack of up to four from one spot; together they surround the hunter and attack in turns
local function spawnPack(size)
  local species = mod.settings.species
  local x, z = placeFor(species)
  if not x then return end
  local pack = {}
  for i = 1, size do
    local c = world.spawn(species, x + math.random(-300, 300), z + math.random(-300, 300))
    if c then
      c.data.wave = wave
      pack[#pack + 1] = c
    end
  end
  if #pack > 1 then
    group.create({ kind = "pack", members = pack, attackers = 2 }):hunt()   -- (no target: the hunter)
  elseif pack[1] then
    pack[1].mood = "hunt"                                                    -- a lone one comes straight at him
  end
  alive = alive + #pack
end

local function spawnWave()
  wave = wave + 1
  local count = 2 + wave
  for first = 1, count, 4 do spawnPack(math.min(4, count - first + 1)) end
  game.message("Wave " .. wave .. ": " .. count .. " attackers!", 4, "orange")
  if wave > save.best then
    save.best = wave
    mod.save(save)
  end
end

-- the death event counts every wave creature that dies, whatever killed it
on("death", function(e)
  if running and e.creature.data.wave then alive, kills = alive - 1, kills + 1 end
end)
on("despawn", function(e)
  if running and e.creature.data.wave then alive = alive - 1 end
end)

on("hunt_start", function()
  wave, lives, alive, kills, running = 0, mod.settings.lives, 0, 0, true
  nextWave = timer.now() + 10
  game.message("Survival: first wave in 10 seconds", 5)
end)

on("hunt_end", function() running = false end)
on("unload", function()   -- switched off (or reloaded): the waves leave with the mod
  if not game.inHunt() then return end
  for _, c in ipairs(world.creatures()) do if c.data.wave then c:remove() end end
end)

on("frame", function()
  if not running or not game.inHunt() or game.paused() then return end
  if timer.now() >= nextWave then
    spawnWave()
    nextWave = timer.now() + mod.settings.interval
  end
end)

-- the results, a page in the game's style (shown over the hunt, which waits)
local results = menu.page("survival:results", { title = "Survival", back = "OK" })
local resultText = results:text("", { width = 340 })

on("player_death", function(e)
  if not running then return end
  lives = lives - 1
  if lives > 0 then
    e.cancelled = true
    game.message(lives .. (lives == 1 and " life" or " lives") .. " left!", 4, "red")
    if e.killer then e.killer:kill() end       -- the attacker pays for it
  else
    running = false
    resultText:setText(string.format("Game over at wave %d\n\nPredators killed: %d\nYour best wave: %d", wave, kills, save.best))
    timer.after(2, function() results:open() end)
  end
end)

on("draw", function(e)
  if not running then return end
  local left = math.max(0, math.ceil(nextWave - timer.now()))
  draw.fillRect(e.width / 2 - 170, 8, 340, 34, "#00000088", 6)
  draw.text(e.width / 2, 13, string.format("Wave %d   |   %d left   |   next in %ds   |   lives %d", wave, alive, left, lives),
            "white", 20, "center")
end)

ui.panel("Survival", function()
  ui.text("Best wave:", save.best)
  if ui.button("Reset best") then save.best = 0; mod.save(save) end
  if running and ui.button("Next wave now") then nextWave = timer.now() end
end)

Boss Rex

Press B in a hunt (on a phone: tap the BOSS button, made by keys.bind's touch option): a giant armoured T-Rex with its own health bar, and the fog closes in and the sky darkens while it lives (world.weather: its death brings the map's weather back, and the game does so by itself when the mod is switched off). It takes three quarters of every damage (c.armor), and its bite takes 50 health instead of your life (creature_attack's e.damage). Below half health (the damage event, whatever hurt it) it is enraged: bigger, 30% faster (c.moveSpeed, c.animSpeed), it roars (c:roar) and calls raptors, and now its bite kills. In Ice Age the boss is a giant mammoth that calls wolves. Switched off, the mod takes the boss away. Needs API 3.

-- Boss Rex: a giant armoured T-Rex with a boss health bar, a darker sky while it lives, and an enraged second phase.
-- In Ice Age (game.id() == "iceage") the boss is a giant mammoth with wolves at its side.
-- Shows (API 3): c.armor, the damage event for phases, c.moveSpeed / c.animSpeed and c:roar, a bite that hurts
-- instead of killing (creature_attack's e.damage), c.mood, world.weather; per-creature data (c.data), a top-of-screen
-- HUD, a touch button, cleaning up in unload, one mod for both games.

local BOSSES = {
  -- health: about six of its kind (the game's T-Rex has 1024, a mammoth 16); distance: where it appears
  dinohunter = { species = "trex", helper = "velociraptor", health = 6000, distance = 6000, name = "BOSS REX",
                 title = "the Boss Rex", Title = "The Boss Rex" },
  iceage = { species = "mammoth", helper = "wolf", health = 100, distance = 3500, name = "BOSS MAMMOTH",
             title = "the Boss Mammoth", Title = "The Boss Mammoth" },
}
local B = BOSSES[game.id()]
local boss = nil
local dark = false       -- the boss darkened the sky

local function alive(c) return c and c.valid and c.alive end

-- a darker, closer world while the boss lives: closer fog, and each light of the map times these red, green, blue
-- factors. The game puts the weather back by itself when the mod is switched off; the boss's death puts it back here
-- (world.weather:reset(): the map's own weather again)
local DARK = { skyColor = { 0.6, 0.4, 0.4 }, skyPlaneColor = { 0.45, 0.3, 0.3 }, sunColor = { 0.6, 0.55, 0.55 },
               shadowColor = { 0.6, 0.5, 0.5 } }
local function darken()
  local w = world.weather
  w.fogStart, w.fogEnd = w.fogStart * 0.3, w.fogEnd * 0.6
  for field, k in pairs(DARK) do
    local c = w[field]
    w[field] = { r = c.r * k[1], g = c.g * k[2], b = c.b * k[3], a = c.a }
  end
  dark = true
end
local function brighten()
  if dark then
    world.weather:reset()
    dark = false
  end
end

local function spawnBoss()
  if alive(boss) then
    game.message("The boss is already hunting you")
    return
  end
  boss = world.spawnNear(B.species, B.distance)
  if not boss then return end
  boss.scale = boss.scale * 1.8
  boss.health = B.health
  boss.armor = 0.75                                  -- thick skin: it takes three quarters of every damage
  boss.data.maxHealth = B.health
  boss.data.phase = 1
  boss.mood = "hunt"                                 -- straight at the hunter
  darken()
  game.message(B.Title .. " is coming...", 5, "red")
end

-- B on a PC; on a phone a BOSS button in the hunt that presses B
keys.bind("B", function()
  if game.inHunt() then spawnBoss() end
end, { touch = { label = "BOSS" } })

-- phase two below half health: bigger, faster, a roar, and helpers. The damage event comes for every damage (the
-- hunter's shots, other creatures, scripts), after the armour
local function enrage()
  boss.data.phase = 2
  boss.scale = boss.scale * 1.15
  boss.moveSpeed, boss.animSpeed = 1.3, 1.3          -- its AI moves and animates it 30% faster
  boss:roar()
  game.message(B.Title .. " is ENRAGED!", 5, "red")
  for i = 1, 3 do
    local helper = world.spawn(B.helper, boss.x + math.random(-800, 800), boss.z + math.random(-800, 800))
    if helper then helper.mood = "hunt" end
  end
end

on("damage", function(e)
  if e.creature == boss and boss.data.phase == 1 and boss.health - e.amount < boss.data.maxHealth / 2 then
    enrage()
  end
end)

-- its bite: a heavy blow while it is calm (the hunter has 128 health), the game's kill once it is enraged
on("creature_attack", function(e)
  if e.hunter and e.creature == boss and boss.data.phase == 1 then e.damage = 50 end
end)

-- dead (or taken away by a script): the sky clears
local function gone(e)
  if e.creature == boss then
    if e.byHunter then game.message("You killed " .. B.title .. "!", 8, "yellow") end
    boss = nil
    brighten()
  end
end
on("death", gone)
on("despawn", gone)

on("hunt_end", function() boss, dark = nil, false end)   -- the next map comes with its own weather

-- the mod switched off (or the scripts reloaded): its armour and speed go by themselves, the boss goes with them
on("unload", function()
  if alive(boss) then boss:remove() end
end)

on("draw", function(e)
  if not alive(boss) then return end
  local w = e.width * 0.5
  local x = (e.width - w) / 2
  local y = e.height * 0.14                           -- below the game's health bar and other mods' top lines
  local enraged = boss.data.phase == 2
  draw.text(e.width / 2, y, enraged and B.name .. "  (enraged)" or B.name, "white", 22, "center")
  draw.bar(x, y + 30, w, 16, boss.health / boss.data.maxHealth, enraged and "#ff3020" or "#d06020", "#000000aa")
  draw.text(e.width / 2, y + 50, math.floor(boss.distance / 128) .. " m away", "#dddddd", 16, "center")
end)

Admin Menu

A tab in the mod menu (F1) with sub-tabs. World: spawn any species, god mode, frozen world, creature fights. Creatures: a table of every creature (click a row, or aim at one, to select it) and tools for the selected one: its brain (its own AI, a small Lua brain that follows you, the generic brains or another species' AI), its mood, tame, armor and move speed, a roar, and buttons to watch it or drive it (Creature behaviour). Species, Weapons, Weather and Hunter: their values as sliders (Game data). Changes: game.changes(), every definition changed, its game value and the mods that changed it. Switched off, the mod leaves nothing behind: the game puts the definitions, overrides, brains and armor back by itself, and the unload handler the world switches and the camera. Needs API 3.

-- Admin Menu: a tab in the mod menu (F1) with world tools, a live creature table with tools for the selected creature,
-- the species, weapon, weather and hunter values, and the list of what is changed.
-- Shows: ui.panel with ui.tabs, combo boxes, sliders, checkboxes, tables; the world API, camera and possession; and
-- API 3: creature behaviour (c.brain, c.mood, c.tame, c.armor), species and weapon definitions, world.weather /
-- world.wind, the hunter's overrides and game.changes(). Switched off, the mod leaves nothing behind (see "unload").

-- small helpers ------------------------------------------------------------------------------------------------------

-- a slider for each {field, label, min, max [, "int" | format]} of an object (a species, a weapon, the weather ...)
local function sliders(object, fields)
  for _, f in ipairs(fields) do
    local value, changed
    if f[5] == "int" then
      value, changed = ui.sliderInt(f[2], object[f[1]], f[3], f[4])
    else
      value, changed = ui.slider(f[2], object[f[1]], f[3], f[4], f[5] or "%.2f")
    end
    if changed then object[f[1]] = value end
  end
end

local function names(list, key)
  local out = {}
  for i, item in ipairs(list) do out[i] = item[key] end
  return out
end

-- World: spawning and the world's switches ---------------------------------------------------------------------------

local speciesList = world.species()  -- {id, name ...} of every species of this game, content packs' too
local speciesNames = names(speciesList, "name")
local spawnChoice, distance, count, team = 1, 2000, 1, 0

-- the world switches this mod turned on, with the value they had (put back by the unload handler)
local switched = {}
local function switch(label, fn)
  local on, changed = ui.checkbox(label, fn())
  if changed then
    if switched[fn] == nil then switched[fn] = not on end
    fn(on)
  end
end

local function drawWorld()
  ui.heading("Spawn")
  spawnChoice = ui.combo("Species", spawnChoice, speciesNames)
  distance = ui.slider("Distance", distance, 500, 8000, "%.0f")
  count = ui.sliderInt("How many", count, 1, 20)
  team = ui.sliderInt("Team (fights)", team, 0, 4)
  if ui.button("Spawn") then
    for i = 1, count do
      local c = world.spawnNear(speciesList[spawnChoice].id, distance + (i - 1) * 300)
      if c and team > 0 then c.team = team end
    end
  end

  ui.heading("World")
  switch("God mode", world.god); ui.sameLine()
  switch("Invisible", world.invisible); ui.sameLine()
  switch("Frozen", world.frozen); ui.sameLine()
  switch("Creature fights", world.fights)
  if ui.button("Kill all") then world.killAll() end
  ui.sameLine()
  if ui.button("Remove all") then world.removeAll() end
  ui.sameLine()
  if ui.button("Clear bodies") then world.clearBodies() end
  if camera.following() or world.possessed() then
    ui.sameLine()
    if ui.button("Back to the hunter") then camera.follow(nil); world.unpossess() end
  end
end

-- Creatures: the table, and the selected creature's behaviour ---------------------------------------------------------

local selected  -- a Creature
local MOODS = { "calm", "alert", "hunt", "flee" }

-- a Lua brain (c.brain = function): follow the hunter, keep some distance, stand still near him
local function followBrain(c, dt)
  local x, _, z = player.pos()
  local d = c:distanceTo(x, z)
  if d > 2500 then c:runTo(x, z, { arrive = 800 })
  elseif d > 900 then c:walkTo(x, z, { arrive = 800 })
  else c:idle() end
end

-- the brains to choose from: its own AI, the Lua brain above, the generic brains and every species' AI (ai.brains())
local brains = { { label = "its own AI", value = nil }, { label = "follow me (a Lua brain)", value = followBrain } }
for _, b in ipairs(ai.brains()) do brains[#brains + 1] = { label = b, value = b } end
local brainLabels = names(brains, "label")

local function brainIndex(c)
  for i, b in ipairs(brains) do
    if b.value == c.brain then return i end
  end
  return 1
end

local function drawSelected(c)
  ui.heading(string.format("%s #%d", c.name, c.id))
  ui.text(string.format("health %.0f / %.0f   mood %s   %s", c.health, c.maxHealth, c.mood, c:awareOfHunter() or ""))
  if not c.alive then return end

  local i, changed = ui.combo("Brain", brainIndex(c), brainLabels)
  if changed then
    local ok, why = true, nil
    if type(brains[i].value) == "string" then ok, why = ai.compatible(c, brains[i].value) end
    if ok then c.brain = brains[i].value else ui.toast("Not this brain: " .. tostring(why)) end
  end
  for _, mood in ipairs(MOODS) do
    if ui.radio(mood, c.mood == mood) then c.mood = mood end  -- the safe way to steer its AI
    ui.sameLine()
  end
  ui.text("(mood)")
  local tame
  tame, changed = ui.checkbox("Tame (ignores the hunter)", c.tame)
  if changed then c.tame = tame end
  local v
  v, changed = ui.slider("Armor: damage taken", c.armor, 0, 1)
  if changed then c.armor = v end
  v, changed = ui.slider("Move speed", c.moveSpeed, 0, 3)
  if changed then c.moveSpeed = v end
  if ui.button("Roar") then c:roar() end
  ui.sameLine()
  if ui.button("Watch") then camera.follow(c, 1800) end
  ui.sameLine()
  if ui.button("Drive") then c:possess(); camera.follow(c) end
  ui.sameLine()
  if ui.button("Deselect") then selected = nil end
end

local function drawCreatures()
  if ui.button("Select the creature under the crosshair") then
    local _, _, _, _, c = player.aim(30000)
    if c then selected = c end
  end
  if selected and selected.valid then drawSelected(selected) end

  ui.heading(world.count() .. " alive")
  ui.table("creatures", 5, function()
    for _, c in ipairs(world.creatures({ radius = 20000 })) do
      ui.id(c.id, function()
        ui.nextRow(); if ui.selectable(c.name, c == selected) then selected = c end
        ui.nextColumn(); ui.text(math.floor(c.distance / 128) .. " m")
        ui.nextColumn(); ui.progress(c.health / c.maxHealth, tostring(math.floor(c.health)))
        ui.nextColumn(); ui.text(c.mood)
        ui.nextColumn(); ui.text(c.team)
      end)
    end
  end, { "Species (click: select)", "Distance", "Health", "Mood", "Team" })
end

-- Species and weapons: the definitions (the game puts them back when the mod is switched off) ------------------------

local SPECIES_FIELDS = {
  { "health", "Health (new ones)", 1, 5000, "%.0f" },
  { "mass", "Mass (tons)", 0.01, 50 },
  { "size", "Length (m)", 0.5, 40, "%.1f" },
  { "score", "Score", 0, 500, "%.0f" },
  { "sight", "Sight", 0.01, 5 },
  { "smell", "Smell", 0.01, 5 },
  { "scaleMin", "Smallest size", 0.2, 5 },
}
local speciesChoice = 1

local function drawSpecies()
  speciesChoice = ui.combo("Species", speciesChoice, speciesNames)
  local s = world.species(speciesList[speciesChoice].id)
  sliders(s, SPECIES_FIELDS)
  local danger, changed = ui.checkbox("Dangerous (a predator)", s.dangerous)
  if changed then s.dangerous = danger end
  if game.inHunt() and ui.button("Apply to the living ones") then
    ui.toast(s:applyToLiving() .. " creature(s) updated")
  end
  if game.inHunt() then ui.sameLine() end
  if ui.button("The game's values") then s:reset() end
end

local WEAPON_FIELDS = {
  { "power", "Power", 0.1, 50, "%.1f" },
  { "precision", "Precision", 0, 2 },
  { "pellets", "Pellets", 1, 64, "int" },
  { "rate", "Shots per second", 0.2, 20, "%.1f" },
  { "ammo", "Rounds per hunt", 0, 500, "int" },
  { "magazine", "Magazine", 1, 100, "int" },
  { "loudness", "Loudness", 0, 5 },
}
local weaponList = weapons.list()
local weaponNames = names(weaponList, "name")
local weaponChoice = 1

local function drawWeapons()
  weaponChoice = ui.combo("Weapon", weaponChoice, weaponNames)
  local w = weaponList[weaponChoice]
  sliders(w, WEAPON_FIELDS)
  if ui.button("The game's values") then w:reset() end
  ui.separator()
  local v, changed = ui.slider("Spread (all weapons)", weapons.spreadScale(), 0, 5)
  if changed then weapons.spreadScale(v) end
  v, changed = ui.slider("Recoil (all weapons)", weapons.recoilScale(), 0, 5)
  if changed then weapons.recoilScale(v) end
end

-- Weather and wind: the loaded map's (a new hunt loads its map's own) ------------------------------------------------

local WEATHER_FIELDS = {
  { "fogStart", "Fog starts at", 0, 20000, "%.0f" },
  { "fogEnd", "Fog complete at", 500, 25000, "%.0f" },
  { "viewDistance", "View distance (lower only)", 2000, 19456, "%.0f" },
  { "cloudsSpeed", "Clouds speed", 0, 10, "%.1f" },
}
local WIND_FIELDS = {
  { "yaw", "Wind towards (yaw)", 0, 360, "%.0f" },
  { "speed", "Wind speed", 0, 40, "%.1f" },
}
local TIMES = { "the menu's choice", "dawn", "day", "night" }

local function drawWeather()
  local w = world.weather
  ui.text("Time of day: " .. tostring(world.time()))
  sliders(w, WEATHER_FIELDS)
  if w.snow then sliders(w, { { "snow", "Snow", 0, 1 } }) end  -- Ice Age only
  for _, c in ipairs({ { "skyColor", "Sky and fog" }, { "sunColor", "Sunlight" }, { "shadowColor", "Shadows" } }) do
    local color, changed = ui.color(c[2], w[c[1]])
    if changed then w[c[1]] = color end
  end
  local locked, changed = ui.checkbox("Hold the wind (the game stops changing it)", world.wind.locked)
  if changed then world.wind.locked = locked end
  sliders(world.wind, WIND_FIELDS)
  local t = 1
  for i, name in ipairs(TIMES) do if world.nextTime() == name then t = i end end
  local choice
  choice, changed = ui.combo("Next hunts at", t, TIMES)
  if changed then world.nextTime(choice > 1 and TIMES[choice] or nil) end
end

-- Hunter: his overrides (each a function: f() reads, f(value) sets, f(nil) gives the game's value back) --------------

local HUNTER = {
  { player.speed, "Walking speed", 0.25, 5 },
  { player.runScale, "Running factor", 0.25, 5 },
  { player.jumpPower, "Jump", 0.25, 5 },
  { player.gravity, "Gravity", 300, 9000, "%.0f" },
  { player.eyeHeight, "Eye height (180: crouch)", 60, 400, "%.0f" },
  { player.regenRate, "Regeneration per second", 0, 100, "%.0f" },
  { player.maxHealth, "Full health", 1, 1000, "%.0f" },
}

local function drawHunter()
  for _, h in ipairs(HUNTER) do
    local v, changed = ui.slider(h[2], h[1](), h[3], h[4], h[5] or "%.2f")
    if changed then h[1](v) end
  end
  if ui.button("The game's values") then
    for _, h in ipairs(HUNTER) do h[1](nil) end
  end
end

-- Changes: every definition the scripts changed, its game value and who changed it ----------------------------------

local function show(value)
  if type(value) == "table" then
    return string.format("%.2f %.2f %.2f", value.r or value[1] or 0, value.g or value[2] or 0, value.b or value[3] or 0)
  elseif type(value) == "number" then
    return string.format("%.4g", value)
  end
  return tostring(value)
end

local function drawChanges()
  local list = game.changes()
  if #list == 0 then
    ui.textDisabled("Nothing changed: every definition has the game's value.")
    return
  end
  ui.textWrapped(#list .. " definition(s) changed. Each goes back when the mods that changed it are switched off.")
  ui.table("changes", 3, function()
    for _, c in ipairs(list) do
      ui.nextRow(); ui.text(c.what)
      ui.nextColumn(); ui.text(show(c.original))
      ui.nextColumn(); ui.text(table.concat(c.mods, ", "))
    end
  end, { "What", "The game's value", "Changed by" })
end

-- the tab ------------------------------------------------------------------------------------------------------------

local function inHunt(fn)
  return function()
    if game.inHunt() then fn() else ui.textDisabled("Start a hunt to use these.") end
  end
end

ui.panel("Admin", function()
  ui.tabs("admin", function()
    ui.tab("World", inHunt(drawWorld))
    ui.tab("Creatures", inHunt(drawCreatures))
    ui.tab("Species", drawSpecies)
    ui.tab("Weapons", drawWeapons)
    ui.tab("Weather", inHunt(drawWeather))
    ui.tab("Hunter", drawHunter)
    ui.tab("Changes", drawChanges)
  end)
end)

on("new_hunt", function() selected = nil end)

-- Switched off (or F9): definitions, overrides, brains, tame and armor go back by themselves; the world switches,
-- the camera and the possession are put back here.
on("unload", function()
  for fn, before in pairs(switched) do fn(before) end
  if game.inHunt() then
    camera.follow(nil)
    world.unpossess()
  end
end)

Perk Shop

Kills earn points: 15, a predator 40. The shop is a page in the game's style (Menus and pages): PERKS in the main menu, Perks in the hunt's menu (Esc), or P in a hunt (on a phone: the PERKS button). Its seven perks change the game's own values (Game data): the hunter's speed, jump, healing and full health (player.speed, player.jumpPower, player.regenRate, player.maxHealth), every weapon's power and rounds per hunt (weapons.get(id).power, .ammo), and a second life once a hunt (player_death). Points and perks are saved between sessions (mod.save) and applied when the mod loads; a bought perk can be switched off and on again. Switched off, the mod leaves nothing behind: the game puts its values back by itself. Needs API 3.

-- Perk Shop: kills earn points, and a shop page in the game's own style sells perks that change the game's values: the
-- hunter's speed, jump, healing and health, every weapon's power and rounds. Points and perks are saved between
-- sessions; a bought perk can be switched off and on again.
-- Shows (API 3): the hunter's overrides (player.speed, jumpPower, regenRate, maxHealth), weapon definitions
-- (weapons.get), the journal (switched off, the mod leaves the game's own values behind by itself), menu.page with a
-- list and a button, menu.button in the main menu and the hunt's menu, the gui event with the game's font, saved data
-- (mod.save), cancelling player_death, a touch button.

local data = mod.load() or {}
data.points = data.points or 0
data.perks = data.perks or {}           -- perk id -> true (bought, on) or false (bought, switched off)

-- each weapon's own values, read before a perk changes them
local base = {}
for _, w in ipairs(weapons.list()) do base[w.id] = { power = w.power, ammo = w.ammo } end
local function eachWeapon(fn)
  for id, b in pairs(base) do fn(weapons.get(id), b) end
end

-- apply(on): the perk's change, or (on = false) the game's own value again; nil gives the hunter's overrides back
local PERKS = {
  { id = "sprint", name = "Sprinter", cost = 40, text = "You walk, run and swim 30% faster.",
    apply = function(on) player.speed(on and 1.3 or nil) end },
  { id = "jump", name = "Spring legs", cost = 30, text = "You jump 60% higher.",
    apply = function(on) player.jumpPower(on and 1.6 or nil) end },
  { id = "medic", name = "Field medic", cost = 50, text = "Your wounds heal three times as fast.",
    apply = function(on) player.regenRate(on and 12 or nil) end },
  { id = "tough", name = "Thick hide", cost = 80, text = "Half again as much health.",
    apply = function(on) player.maxHealth(on and 192 or nil) end },
  { id = "heavy", name = "Heavy rounds", cost = 120, text = "Every weapon hits 50% harder.",
    apply = function(on) eachWeapon(function(w, b) w.power = on and b.power * 1.5 or b.power end) end },
  { id = "belt", name = "Ammo belt", cost = 60, text = "Half again as many rounds for every weapon, from the next hunt or resupply on.",
    apply = function(on) eachWeapon(function(w, b) w.ammo = on and math.floor(b.ammo * 1.5) or b.ammo end) end },
  { id = "life", name = "Second life", cost = 200, text = "Once a hunt, you survive an attack that would kill you.",
    apply = function() end },  -- player_death below
}
for _, p in ipairs(PERKS) do
  if data.perks[p.id] then p.apply(true) end
end

on("kill", function(e)
  if e.byHunter then
    local reward = e.creature.predator and 40 or 15
    data.points = data.points + reward
    mod.save(data)
    game.message("+" .. reward .. " points", 2, "yellow")
  end
end)

local lifeUsed = false
on("hunt_start", function() lifeUsed = false end)
on("player_death", function(e)
  if data.perks.life and not lifeUsed then
    lifeUsed = true
    e.cancelled = true
    game.message("Second life used!", 4, "orange")
  end
end)

-- the shop: a page in the game's style (positions in game units: the screen is 320 high), built when it opens
local shop, points, list, info, action
local chosen = 1

local function rowText(p)
  local owned = data.perks[p.id]
  return p.name .. "   " .. (owned == nil and p.cost .. " points" or owned and "ON" or "off")
end

local function rows()
  local t = {}
  for i, p in ipairs(PERKS) do t[i] = rowText(p) end
  return t
end

local function refresh()
  list:setRows(rows())
  local p, owned = PERKS[chosen], data.perks[PERKS[chosen].id]
  points:setText("Points: " .. data.points .. ".  A kill earns 15, a predator 40.")
  info:setText(p.name .. "\n\n" .. p.text)
  action:setText(owned == nil and "BUY" or owned and "SWITCH OFF" or "SWITCH ON")
  action:setEnabled(owned ~= nil or data.points >= p.cost)
end

local function press()
  local p = PERKS[chosen]
  if data.perks[p.id] == nil then
    if data.points < p.cost then return end
    data.points = data.points - p.cost
    data.perks[p.id] = true
  else
    data.perks[p.id] = not data.perks[p.id]
  end
  p.apply(data.perks[p.id])
  mod.save(data)
  refresh()
end

shop = menu.page("perk_shop:shop", {
  title = "Perk shop",
  onOpen = function()
    shop:clear()
    local w = menu.screen()
    points = shop:text("", { x = w / 2, y = 46, width = 400 })
    list = shop:list(rows(), function(i) chosen = i; refresh() end,
      { x = w / 2 - 105, y = 168, width = 210, rows = 7, selected = chosen })
    info = shop:text("", { x = w / 2 + 135, y = 100, width = 200 })
    action = shop:button("BUY", press, { x = w / 2 + 135, y = 250, sound = "menugo.wav" })
    refresh()
  end,
})

local function toggleShop()
  if shop:isOpen() then shop:close() else shop:open() end
end
keys.bind("P", function() if game.inHunt() then toggleShop() end end, { touch = { label = "PERKS" } })
menu.button("main", "PERKS", toggleShop, { sound = "menugo.wav" })
menu.button("game", "Perks", toggleShop)    -- the hunt's menu (Esc), beside ESCAPE / RESTART / OPTIONS

-- the points at the top of the hunt, beside its MENU tab (the corners hold the game's own HUD), in its yellow font
on("gui", function(e)
  if game.inHunt() and not e.menu then
    draw.text(e.width / 2 + 36, 6, data.points .. " points", "#ffe020", nil, "left", "ccra14")
  end
end)

Pet Raptor

Press K in a hunt (on a phone: PET): a tame Utahraptor (in Ice Age a wolf) that follows you. It runs to catch up, walks the last metres and stands beside you with its idle animations, turning to keep an eye on you. Its brain is a short Lua function (c.brain, Creature behaviour) that moves it with the game's own walking and running (c:walkTo, c:runTo: way finding, animations and sounds) and standing (c:idle, c:turnToward). Your shots do not hurt it, other predators can kill it, and K brings a lost pet back to you. Switched off, the mod takes the pet away: without its brain it would be a wild raptor next to you. (The Velociraptor has no idle animations, so the pet is a Utahraptor.) Guard Pet is the bigger version. Needs API 3.

-- Pet Raptor: a tame Utahraptor (Ice Age: a wolf) that follows the hunter and stands by him when he stops.
-- Shows: a Lua brain (c.brain) that moves a creature with the game's own walking and running (c:walkTo, c:runTo),
-- standing with its idle animations (c:idle) and turning (c:turnToward); c.tame; cancelling hit; cleaning up in
-- unload; a touch button for phones; one mod for both games. Guard Pet is the bigger version of this mod.

-- the pet of each game (the Velociraptor has no idle animations: it could not stand still in a natural way)
local PETS = {
  dinohunter = { species = "utahraptor", name = "raptor" },
  iceage = { species = "wolf", name = "wolf" },
}
local P = PETS[game.id()]
local pet = nil

local function alive(c) return c and c.valid and c.alive end

-- the brain: runs every frame in place of its species' AI; c is the pet, dt the frame time
local function follow(c, dt)
  local x, _, z = player.pos()
  local d = c:distanceTo(x, z)
  if d > 2500 then
    c.data.resting = false
    c:runTo(x, z, { arrive = 700 })                     -- far behind: run (way finding, run animation, sound)
  elseif d > 1300 or not c.data.resting then
    local _, arrived = c:walkTo(x, z, { arrive = 700 })  -- walk up to the hunter...
    c.data.resting = arrived
  else
    c:idle()                                             -- ...then stand by him, playing its idles
    c:turnToward(x, z, 60)                               -- and keep an eye on him
  end
end

local function callPet()
  if not game.inHunt() then return end
  if alive(pet) then
    local x, _, z = world.inFront(700)
    pet:teleport(x, z)                                   -- lost it? It comes back to you
    return
  end
  pet = world.spawnNear(P.species, 900)
  if not pet then return end
  pet.tame = true                                        -- it never notices, hunts or attacks the hunter
  pet.brain = follow                                     -- our function instead of its species' AI
  game.message("Your " .. P.name .. " is here. Good boy.", 4, "green")
end

keys.bind("K", callPet, { touch = { label = "PET" } })   -- K on a PC, a PET button on a phone

-- your shots do not hurt it
on("hit", function(e)
  if e.creature == pet then e.cancelled = true end
end)

-- other predators can still kill it: then it is gone (K calls a new one)
on("death", function(e)
  if e.creature == pet then
    pet = nil
    game.message("Your " .. P.name .. " has died.", 4, "red")
  end
end)

-- the mod switched off (or the scripts reloaded): without its brain and tameness the pet would be a wild predator
-- next to the hunter, so it leaves with the mod
on("unload", function()
  if alive(pet) then pet:remove() end
end)

Guard Pet

Press K in a hunt: a guard (a Utahraptor; in Ice Age a wolf) that follows you and fights the predators coming for you. When a predator notices you or starts its hunt within the guard radius (a setting), the guard roars, a warning shows and it intercepts: a leap, then its species' own chase and bite (c:attack with c:stockAI in its brain). G sends it at the creature under the crosshair (player.aim()), G at nothing calls it back. Your shots do not hurt it (the hit event, cancelled); when it dies it is gone for the hunt. Its brain is a Lua function (Creature behaviour). Needs API 3.

-- Guard Pet: a creature with a Lua brain that follows the hunter and fights the predators coming for him.
-- Shows: c.brain (a script's AI loop), c.tame, c:walkTo / c:runTo / c:idle, c:attack (one creature against another,
-- world fights off), c:stockAI (its own chase and bite), c:roar, c:jump, the creature_hunt / notice / death events,
-- player.aim(), cancelling hit, a HUD warning, touch buttons. Both games (Ice Age: a wolf).

local PETS = {
  dinohunter = { species = "utahraptor", text = "Your Utahraptor is here. It will guard you." },
  iceage = { species = "wolf", text = "Your wolf is here. It will guard you." },
}
local P = PETS[game.id()]

mod.setting("radius", 6000, { label = "Guard radius (units)", min = 2000, max = 12000 })
mod.setting("warnings", true, { label = "Show threat warnings" })

local pet = nil          -- the guard (nil before K, or once it is gone)
local lost = false       -- it died: gone for this hunt
local threat = nil       -- what it is fighting
local warning = nil      -- {text, until}
local leapt = false      -- one leap per attack

local function alive(c) return c and c.valid and c.alive end

local function warn(text, color)
  if mod.settings.warnings then warning = { text = text, color = color or "#ff5040", t = timer.now() + 3 } end
end

-- send the guard at a creature (the world's fight code drives its chase and bite through c:stockAI below)
local function sic(target, why)
  if not alive(pet) or not alive(target) or target == pet then return false end
  if pet:attack(target) then
    threat = target
    leapt = false
    pet:roar(target)
    warn(why .. ": " .. target.name, "#ffb030")
    return true
  end
  return false
end

-- the brain: runs every frame in place of its species' AI (the game still bleeds it, runs its fights and
-- creature_after_ai); `c` is the pet, `dt` the frame time
local function brain(c, dt)
  if alive(threat) and c.target == threat then
    -- a leap at it when it is close in front, then the species' own chase and bite (fights code: c:attack)
    local d = c:distanceTo(threat)
    if not leapt and d < 1400 and d > 700 then
      leapt = c:jump() or true
    end
    c:stockAI()
    return
  end
  threat = nil
  -- follow the hunter: run to catch up, walk when close, stand by him with its idles
  local x, _, z = player.pos()
  local d = c:distanceTo(x, z)
  if d > 2500 then
    c:runTo(x, z, { arrive = 600 })
  elseif d > 900 then
    c:walkTo(x, z, { arrive = 600 })
  else
    c:idle()
  end
end

local function summon()
  if not game.inHunt() then return end
  if lost then game.message("Your guard is gone for this hunt.", 3, "gray") return end
  if alive(pet) then
    local x, _, z = world.inFront(600)
    pet:teleport(x, z)  -- it comes back to you
    return
  end
  pet = world.spawnNear(P.species, 900)
  if not pet then return end
  pet.tame = true              -- it never notices, hunts or attacks the hunter
  pet.health = pet.health * 3  -- a sturdy guard
  pet.armor = 0.6
  pet.brain = brain
  pet.data.guard = true
  game.message(P.text, 4, "green")
end

-- G: attack the creature under the crosshair
local function command()
  if not alive(pet) then return end
  local kind, _, _, _, target = player.aim(30000)
  if target and target ~= pet then
    sic(target, "Attack")
  else
    pet:attack(nil)
    threat = nil
    game.message("Back to me!", 2, "white")
  end
end

keys.bind("K", summon, { touch = { label = "PET" } })
keys.bind("G", command, { touch = { label = "SIC" } })

-- predators coming for the hunter: the game's own detection (notice) and its hunt (creature_hunt)
local function guard(c, why)
  if not alive(pet) or alive(threat) or not alive(c) or c == pet or not c.predator then return end
  if c.distance and c.distance < mod.settings.radius then sic(c, why) end
end
on("creature_hunt", function(e) guard(e.creature, "Coming for you") end)
on("notice", function(e) guard(e.creature, "It noticed you") end)
-- and a look around every half second (predators already on their way when the guard arrived)
timer.every(0.5, function()
  if not alive(pet) or alive(threat) or not game.inHunt() then return end
  for _, c in ipairs(world.creatures({ radius = mod.settings.radius })) do
    if c ~= pet and c.predator and c.huntingPlayer then
      sic(c, "Coming for you")
      return
    end
  end
end)

-- the hunter's shots do not hurt it
on("hit", function(e)
  if e.creature == pet then e.cancelled = true end
end)

on("death", function(e)
  if e.creature == pet then
    lost = true
    pet = nil
    game.message("Your guard has fallen. It is gone for this hunt.", 5, "red")
  elseif e.creature == threat then
    warn("Threat down: " .. e.creature.name, "#80ff80")
  end
end)
on("despawn", function(e) if e.creature == pet then pet = nil end end)

on("hunt_start", function() pet, lost, threat, warning = nil, false, nil, nil end)
on("hunt_end", function() pet, threat = nil, nil end)

-- the HUD: the warning, a marker on the threat, the guard's health
on("draw", function(e)
  if not game.inHunt() then return end
  if warning and timer.now() < warning.t then
    draw.text(e.width / 2, e.height * 0.22, warning.text, warning.color, 28, "center")
  end
  if alive(threat) then
    local sx, sy = threat:screen()
    if sx then draw.circle(sx, sy - 10, 14, "#ff5040", 3) end
  end
  if alive(pet) then
    draw.text(20, e.height - 120, "Guard", "#c0ffc0", 18)
    draw.bar(20, e.height - 98, 140, 8, pet.health / pet.maxHealth, "#40d060")
  end
end)

Dino Arena

A complete game mode built only from the API: two teams of dinosaurs (in Ice Age: animals) in pens, a countdown, then team against team. The arena picks the fights: each fighter goes for the nearest enemy that nobody fights yet (c:attack; world fights stay off, so nothing else on the map joins in). The pens, the ring and the hazard strikes are zones: a fighter that leaves its pen before the release is put back (zone_leave), the ring shrinks by being made again under the same name (outside it creatures lose health), and a strike hits the creatures in its small zone (z:creatures). The damage event applies the handicaps and counts the damage each fighter deals, death the kills, for the kill cam, the results and the statistics. Team colours on the models (c.tint), health bars, the ring and the strikes drawn on the ground, a director camera, bets with your credits, automatic 1v1 tournaments, a results page in the game's style with REMATCH (menu.page) and a saved table of each species' wins and kills. Set it up in the mod menu's Arena tab, or press F7 in a hunt (on a phone: the ARENA button). After a match, and when the mod is switched off, everything goes back: the fighters leave, the hunter can be seen and hurt again, where he stood. Needs API 3.

-- Dino Arena: team fights between dinosaurs (Ice Age: its animals), made only with the modding API. F7 in a hunt
-- (phone: ARENA; or the Arena tab of the mod menu) starts a match. API 3: c:attack pairs the fighters, the pens, the ring
-- and the hazards are zones, the damage / death events feed handicaps, kill cam and statistics, menu.page the results.

local TEAM = { { name = "RED", color = "#ff4a3a", tint = { 1, 0.35, 0.3, 0.75 } },
               { name = "BLUE", color = "#4a8cff", tint = { 0.35, 0.55, 1, 0.75 } } }

-- per game (game.id()): the first hunt species' type (the dinosaurs 16-33, Ice Age's animals 116-130) and the
-- default match
local GAMES = {
  dinohunter = { firstType = 16, red = "velociraptor", blue = "allosaurus" },
  iceage = { firstType = 116, red = "wolf", blue = "bear" },
}
local G = GAMES[game.id()]

local speciesIds, speciesNames = {}, {}
for _, s in ipairs(world.species()) do
  if s.type >= G.firstType then speciesIds[#speciesIds + 1] = s.id; speciesNames[#speciesNames + 1] = s.name end
end
local function speciesIndex(id) for i, v in ipairs(speciesIds) do if v == id then return i end end return 1 end

local setup = { speciesIndex(G.red), speciesIndex(G.blue) }   -- red / blue species
local counts = { 4, 2 }
local handicap = { 100, 100 }                                                -- damage in percent
local options = { zone = true, hazards = true, killcam = true, director = true, tournament = false }
local bet = { team = 1, amount = 100 }

local stats = mod.load() or { species = {} }
local arena = nil  -- the running match

local function fighter(c) return arena and c and c.valid and (c.team == 1 or c.team == 2) end

local function fighters(team)
  local out = {}
  for _, c in ipairs(arena.fighters) do
    if c.valid and c.alive and (not team or c.team == team) then out[#out + 1] = c end
  end
  return out
end

-- ends the match: the fighters (living and dead) leave, and the rest goes back as it was (also at the hunt's end and
-- when the mod is switched off)
local function stop()
  if not arena then return end
  for _, c in ipairs(arena.fighters) do if c.valid then c:remove() end end
  for _, z in ipairs(arena.zones) do zone.remove(z) end  -- (false for a hazard that struck already)
  world.invisible(false); world.god(false); camera.follow(nil); game.timeScale(1)
  if game.inHunt() then player.teleport(arena.hx, arena.hz) end  -- the follow camera took him along: back he goes
  arena = nil
end

local function start(redSpecies, redCount, blueSpecies, blueCount)
  if not game.inHunt() then game.message("Start a hunt first") return end
  stop()
  world.removeAll(); world.clearBodies(); world.invisible(true); world.god(true)
  local cx, _, cz = world.inFront(5000)
  local dx, dz = player.forward()
  local hx, _, hz = player.pos()
  arena = { x = cx, z = cz, hx = hx, hz = hz, fighters = {}, phase = "setup", t = 0, radius = 7000, hazards = {},
            nextHazard = 12, species = { redSpecies, blueSpecies }, kills = { 0, 0 }, started = timer.now() }
  -- a pen per team: a zone that tracks that team's creatures (zone_leave keeps them in), and the ring
  arena.pens = { zone.circle("arena:red", cx - dz * 1800, cz + dx * 1800, 700, { hunter = false, creatures = { team = 1 } }),
                 zone.circle("arena:blue", cx + dz * 1800, cz - dx * 1800, 700, { hunter = false, creatures = { team = 2 } }) }
  arena.ring = zone.circle("arena:ring", cx, cz, arena.radius, { hunter = false })
  arena.zones = { arena.pens[1], arena.pens[2], arena.ring }
  for team = 1, 2 do
    for i = 1, team == 1 and redCount or blueCount do
      local x, z = arena.pens[team]:randomPoint({ species = arena.species[team] })  -- a place it can stand on
      local c = world.spawn(arena.species[team], x or arena.pens[team].x, z or arena.pens[team].z)
      if c then
        c.team, c.tint, c.data.dealt, c.data.kills = team, TEAM[team].tint, 0, 0
        arena.fighters[#arena.fighters + 1] = c
      end
    end
  end
  if #fighters(1) == 0 or #fighters(2) == 0 then stop(); game.message("No room for an arena here") return end
  if bet.amount > 0 and player.credits() >= bet.amount then
    player.addCredits(-bet.amount)
    arena.bet = { team = bet.team, amount = bet.amount }
  end
  camera.follow(arena.fighters[1], 3500)
  player.setPitch(-20)  -- looking down: the follow camera stays above the fight
  game.message("Arena: " .. redCount .. " x " .. redSpecies .. " vs " .. blueCount .. " x " .. blueSpecies, 5)
end

local function startFromSetup() start(speciesIds[setup[1]], counts[1], speciesIds[setup[2]], counts[2]) end
local function randomDuel() start(speciesIds[math.random(#speciesIds)], 1, speciesIds[math.random(#speciesIds)], 1) end

keys.bind("F7", startFromSetup, { touch = { label = "ARENA" } })

-- the pairings: a fighter without a target goes for the nearest enemy nobody fights yet, else the nearest one
-- (c:attack: its species' own chase and bite; world fights stay off, nothing else on the map joins in)
local function pairUp()
  local taken = {}
  for _, c in ipairs(fighters()) do
    local foe = c.target
    if not foe then
      local best = math.huge
      for _, o in ipairs(fighters(3 - c.team)) do
        local d = c:distanceTo(o) + ((taken[o] or o.chaser) and 6000 or 0)
        if d < best then foe, best = o, d end
      end
      if foe then c:attack(foe) end
    end
    if foe then taken[foe] = true end
  end
end

-- before the release nobody leaves its pen: one that crosses the edge is put back inside it
on("zone_leave", function(e)
  local c = e.creature
  local pen = fighter(c) and arena.pens[c.team]
  if pen and e.zone == pen and (arena.phase == "setup" or arena.phase == "countdown") then
    local d = c:distanceTo(pen.x, pen.z)
    c.x, c.z = pen.x + (c.x - pen.x) * 660 / d, pen.z + (c.z - pen.z) * 660 / d
  end
end)

-- handicaps and the damage statistics: every damage a fighter deals, whoever takes it
on("damage", function(e)
  if fighter(e.attacker) then
    e.amount = e.amount * handicap[e.attacker.team] / 100
    e.attacker.data.dealt = e.attacker.data.dealt + e.amount
  end
end)

local function record(id, key)  -- the saved statistics: games, wins and kills per species
  stats.species[id] = stats.species[id] or { wins = 0, games = 0, kills = 0 }
  stats.species[id][key] = (stats.species[id][key] or 0) + 1
end

on("death", function(e)  -- kills per fighter, team and species; kill cam: slow motion on the winner of a duel
  local k = e.killer
  if not (fighter(e.creature) and fighter(k)) then return end
  k.data.kills, arena.kills[k.team] = k.data.kills + 1, arena.kills[k.team] + 1
  record(k.species, "kills")
  if options.killcam and arena.phase == "fight" and k.alive then
    camera.follow(k, 2200); game.timeScale(0.3)
    arena.killcamUntil = timer.now() + 1.2
  end
end)

-- the results, a page in the game's style (the hunt waits while it is open)
local results = menu.page("arena:results", { title = "Arena", back = "CLOSE" })
local resultText = results:text("", { width = 380 })
results:button("REMATCH", function() results:close(); startFromSetup() end)
results:button("RANDOM DUEL", function() results:close(); randomDuel() end, { textScale = 0.8 })

local function finish(winner)
  arena.phase, arena.t, arena.winner, arena.time = "over", 0, winner, timer.now() - arena.started
  for team = 1, 2 do record(arena.species[team], "games") end
  if winner > 0 then record(arena.species[winner], "wins") end
  if arena.bet then
    local won = arena.bet.team == winner
    if won then player.addCredits(arena.bet.amount * 2) end
    arena.bet.text = won and ("You won the bet: +" .. arena.bet.amount * 2 .. " credits") or "You lost the bet"
    game.message(arena.bet.text, 6, won and "yellow" or "gray")
  end
end

local function summary()  -- the results page's text (a few seconds after the end: the last bites' deaths have come)
  local best = arena.fighters[1]
  for _, c in ipairs(arena.fighters) do if c.data.dealt > best.data.dealt then best = c end end
  return string.format("%s\n\n%s against %s, %d s\nKills: red %d, blue %d\nBest fighter: %s (%s), damage %d, kills %d%s",
                       arena.winner == 0 and "DRAW" or TEAM[arena.winner].name .. " WINS", arena.species[1], arena.species[2],
                       math.floor(arena.time), arena.kills[1], arena.kills[2], best.name, TEAM[best.team].name:lower(),
                       math.floor(best.data.dealt), best.data.kills, arena.bet and ("\n\n" .. arena.bet.text) or "")
end

on("frame", function(e)
  if not arena or not game.inHunt() then return end
  local dt = e.dt
  arena.t = arena.t + dt
  if arena.killcamUntil and timer.now() > arena.killcamUntil then game.timeScale(1); arena.killcamUntil = nil end

  if arena.phase == "setup" and arena.t > 3 then
    arena.phase, arena.t = "countdown", 0
  elseif arena.phase == "countdown" and arena.t > 3 then
    arena.phase, arena.t = "fight", 0
    game.message("FIGHT!", 2, "orange")
  elseif arena.phase == "fight" then
    local red, blue = #fighters(1), #fighters(2)
    if red == 0 or blue == 0 then finish(red > 0 and 1 or (blue > 0 and 2 or 0)) return end
    pairUp()
    if options.zone then  -- the ring shrinks (a zone made with its name replaces it); outside it, creatures lose health
      arena.radius = math.max(1500, arena.radius - 60 * dt)
      zone.circle("arena:ring", arena.x, arena.z, arena.radius, { hunter = false })
      for _, c in ipairs(fighters()) do
        if not arena.ring:contains(c.x, c.z) then c:hurt(c.maxHealth * 0.08 * dt, { calm = true, bleed = false }) end
      end
    end
    if options.hazards and arena.t > arena.nextHazard then  -- a strike: a small zone, marked first, hits 2 s later
      local hx, hz = math.forward(math.random() * 360)
      local r = math.random() * arena.radius * 0.7
      local h = zone.circle("arena:hazard" .. #arena.zones, arena.x + hx * r, arena.z + hz * r, 600, { hunter = false })
      arena.zones[#arena.zones + 1], arena.hazards[h] = h, arena.t + 2
      arena.nextHazard = arena.t + 8 + math.random() * 6
    end
    for h, at in pairs(arena.hazards) do
      if arena.t >= at then
        for _, c in ipairs(h:creatures()) do if fighter(c) then c:hurt(c.maxHealth * 0.4, { calm = true }) end end
        sound.playAt("dbsgun_sound_0.wav", h.x, world.ground(h.x, h.z), h.z, 1, 30000)
        h:remove(); arena.hazards[h] = nil
      end
    end
    if options.director and not arena.killcamUntil and arena.t - (arena.lastCut or -10) > 6 then  -- the director: cut to the action
      local best, bestScore = nil, -1
      for _, c in ipairs(fighters()) do
        local score = (c.attacking and 100 or 0) + c.data.dealt
        if score > bestScore then best, bestScore = c, score end
      end
      if best then camera.follow(best, 2600); arena.lastCut = arena.t end
    end
  elseif arena.phase == "over" and arena.t > 4 then
    mod.save(stats)
    if options.tournament then randomDuel() else resultText:setText(summary()); stop(); results:open() end
  end
end)

on("hunt_end", stop)
on("unload", stop)

-- a world-space circle on the screen
local function circle(x, z, radius, color, thickness)
  local px, py
  for i = 0, 48 do
    local dx, dz = math.forward(i * 7.5)
    local wx, wz = x + dx * radius, z + dz * radius
    local sx, sy = game.project(wx, world.ground(wx, wz) + 60, wz)
    if sx and px then draw.line(px, py, sx, sy, color, thickness) end
    px, py = sx, sy
  end
end

on("draw", function(e)
  if not arena or not game.inHunt() then return end
  for _, c in ipairs(fighters()) do  -- health bars in team colours
    local sx, sy = c:screen()
    if sx then
      draw.text(sx, sy - 26, c.name, TEAM[c.team].color, 17, "center")
      draw.bar(sx - 36, sy - 6, 72, 7, c.health / c.maxHealth, TEAM[c.team].color)
    end
  end
  if options.zone and arena.phase == "fight" then circle(arena.x, arena.z, arena.radius, "#ffd04099", 3) end
  for h in pairs(arena.hazards) do circle(h.x, h.z, 600, "#ff2020", 2) end
  local w = e.width
  draw.fillRect(w / 2 - 190, 10, 380, 34, "#00000099", 6)
  draw.text(w / 2, 15, string.format("RED %d   vs   %d BLUE", #fighters(1), #fighters(2)), "white", 22, "center")
  if arena.phase == "countdown" then
    draw.text(w / 2, e.height * 0.35, tostring(3 - math.floor(arena.t)), "white", 96, "center")
  elseif arena.phase == "setup" then
    draw.text(w / 2, e.height * 0.35, "Get ready", "white", 48, "center")
  elseif arena.phase == "over" then
    local text = arena.winner == 0 and "DRAW" or (TEAM[arena.winner].name .. " WINS")
    draw.text(w / 2, e.height * 0.35, text, arena.winner == 0 and "white" or TEAM[arena.winner].color, 72, "center")
  end
end)

ui.panel("Arena", function()
  if not game.inHunt() then ui.textDisabled("Start a hunt, then set up a match here (or press F7).") end
  ui.table("teams", 2, function()
    for team = 1, 2 do
      ui.nextColumn()
      ui.id(team, function()
        ui.textColored(TEAM[team].color, TEAM[team].name)
        setup[team] = ui.combo("Species", setup[team], speciesNames)
        counts[team] = ui.sliderInt("Count", counts[team], 1, 12)
        handicap[team] = ui.sliderInt("Damage %", handicap[team], 25, 300)
      end)
    end
  end)
  ui.heading("Options")
  options.zone = ui.checkbox("Shrinking zone", options.zone); ui.sameLine()
  options.hazards = ui.checkbox("Hazard strikes", options.hazards); ui.sameLine()
  options.killcam = ui.checkbox("Kill cam", options.killcam)
  options.director = ui.checkbox("Director camera", options.director); ui.sameLine()
  options.tournament = ui.checkbox("Auto tournament (random 1v1s)", options.tournament)
  ui.heading("Bet (credits: " .. player.credits() .. ")")
  if ui.radio("Red", bet.team == 1) then bet.team = 1 end; ui.sameLine()
  if ui.radio("Blue", bet.team == 2) then bet.team = 2 end; ui.sameLine()
  ui.width(160); bet.amount = ui.sliderInt("Stake", bet.amount, 0, 1000)
  if ui.button("Start match (F7)") then startFromSetup() end; ui.sameLine()
  if ui.button("Random duel") then randomDuel() end; ui.sameLine()
  if arena and ui.button("Stop") then stop() end
  if ui.collapsing("Species win rates") then
    local rows = {}
    for id, s in pairs(stats.species) do if s.games > 0 then rows[#rows + 1] = { id = id, s = s } end end
    table.sort(rows, function(a, b) return a.s.wins / a.s.games > b.s.wins / b.s.games end)
    ui.table("rates", 4, function()
      for _, r in ipairs(rows) do
        ui.nextRow(); ui.text(r.id)
        ui.nextColumn(); ui.text(r.s.wins .. " / " .. r.s.games)
        ui.nextColumn(); ui.text(r.s.kills or 0)
        ui.nextColumn(); ui.progress(r.s.wins / r.s.games)
      end
    end, { "Species", "Wins", "Kills", "Rate" })
    if ui.smallButton("Reset") then stats.species = {}; mod.save(stats) end
  end
end)

Clean HUD

Changes the game's own HUD: no MENU tab (Esc opens the menu and closes it again), an ammo counter of its own drawn in the game's yellow HUD font (the gui event draws inside the game's own GUI), the compass bigger and higher by settings, and H hides the whole HUD for screenshots (H or Esc brings it back). The hunt's menu gets a HIDE HUD cell next to ESCAPE / RESTART / OPTIONS (menu.button("game", ...)), and a phone a HUD button for the H key (keys.bind's touch option). Needs API 3.

-- Clean HUD: changes the game's own HUD. No MENU tab (Esc opens the menu, and closes it again), the ammo count replaced
-- by a counter of its own (loaded / total) in the game's HUD font, the compass bigger and higher, and H hides every part
-- of the HUD for screenshots (also HIDE HUD in the hunt's menu, and a HUD button on a phone).
-- Shows: hud.hide / hud.offset / hud.scale, player.ammo, the back event, settings that apply at once; and API 3: the gui
-- event (drawing inside the game's own GUI with its fonts), a cell in the hunt's menu (menu.button "game"),
-- hud.closeMenu, a touch button for the key.

mod.setting("menuTab", false, { label = "Show the MENU tab" })
mod.setting("ammo", true, { label = "Own ammo counter" })
mod.setting("compassSize", 1.4, { label = "Compass size", min = 0.5, max = 3 })
mod.setting("compassUp", 0, { label = "Compass higher by", min = 0, max = 400 })

local screenshot = false  -- everything hidden

local function apply()
  hud.reset()
  if screenshot then
    hud.hide("all")
    return
  end
  if not mod.settings.menuTab then hud.hide("menu") end
  if mod.settings.ammo then hud.hide("ammo") end
  hud.scale("compass", mod.settings.compassSize)
  hud.offset("compass", 0, -mod.settings.compassUp)
end
apply()

local function setScreenshot(on)
  screenshot = on
  apply()
end

on("setting", function(e)
  if e.mod == mod.id then apply() end
end)

-- H on a PC; on a phone a HUD button (it shows while nothing covers the 3D view)
keys.bind("H", function()
  if game.inHunt() then setScreenshot(not screenshot) end
end, { touch = { label = "HUD" } })

-- the same from the hunt's menu (ESCAPE / RESTART / OPTIONS): one more cell of the game's kind, which closes the menu
menu.button("game", "HIDE HUD", function()
  hud.closeMenu()
  setScreenshot(true)
end)

-- Esc while the HUD is hidden brings it back instead of opening the menu
on("back", function(e)
  if screenshot and game.inHunt() and not e.menuOpen then
    setScreenshot(false)
    e.cancelled = true
  end
end)

-- the ammo counter, drawn in the game's own GUI pass: its yellow HUD font, in game units (the screen is 320 high),
-- under the game's popups like the count it replaces
on("gui", function(e)
  if screenshot or not (mod.settings.ammo and game.inHunt()) or hud.menuOpen() then return end
  local total, loaded = player.ammo()
  if not total then return end
  local text = string.format("%d / %d", loaded, total)
  local w, h = draw.textSize(text, 16, "ccra14")
  local x, y = e.width - 14, e.height - 34
  draw.fillRect(x - w - 8, y - 4, w + 16, h + 8, { 0, 0, 0, 0.45 }, 4)
  draw.text(x, y, text, total == 0 and "#ff6040" or "#ffd040", 16, "right", "ccra14")
end)

Shader Lab

The whole shader API in one window, opened with F8 (on a phone the LAB button) and also a tab of the mod menu (F1). A preset sets a few values of shader.world and shader.screen (:set after :reset), the tabs show every value as a slider bound to its field, the Targets tab switches the shader groups, and the Editor tab loads a game shader's GLSL (shader.source), compiles your change into the game (shader.setSource) or shows why it was refused. The VHS button switches shader.screen.vhs and draws the camcorder's PLAY and date with draw.text in the draw event. Other mods can use it through mod.exports: mods.get("shader_lab").preset("CRT arcade"). Needs API 4.

-- Shader Lab: the shader API (API 4) in one window. F8 (LAB on a phone) opens it; it is also a tab of the mod menu (F1).
-- Shows: shader.world / shader.screen / shader.targets (:set, :get, :reset), shader.files, shader.source,
-- shader.setSource and shader.revert, ui.window with tabs, sliders, combo boxes, colour pickers and a text editor, and
-- the draw event for the VHS camcorder text.

local W, S, T = shader.world, shader.screen, shader.targets

-- ---- presets: each starts from the game's own picture ----
local PRESETS = {
  {"Original", {}, {}},
  {"Night vision", {vision = "night"}, {vignette = 0.9, grain = 0.35, bloom = 0.4, bloomThreshold = 0.5}},
  {"Thermal", {vision = "thermal"}, {blur = 1, grain = 0.1}},
  {"Film noir", {saturation = 0, contrast = 1.25, exposure = 0.3}, {vignette = 0.8, grain = 0.25, letterbox = 0.1}},
  {"Old photo", {sepia = 1, contrast = 0.85}, {vignette = 1, grain = 0.3, blur = 0.6}},
  {"PS1", {snap = 80, posterize = 24, dither = 1}, {pixelate = 3}},
  {"Comic book", {toon = 5, saturation = 1.5, contrast = 1.15}, {outlines = 0.9, outlineThreshold = 0.35}},
  {"CRT arcade", {}, {barrel = 0.6, scanlines = 0.7, crtMask = 0.6, chromatic = 2, vignette = 0.6, bloom = 0.3}},
  {"Drunk", {wobble = 1, wave = 0.15, waveFrequency = 3}, {ghost = 18, blur = 1, haze = 0.6}},
  {"Dreamy", {temperature = 0.4, saturation = 1.15, exposure = -0.2}, {bloom = 0.5, bloomThreshold = 0.6, blur = 1, vignette = 0.5}},
  {"Sonar", {sonarStrength = 1.2, sonarSpeed = 6000, exposure = -0.8, saturation = 0.3}, {scanlines = 0.3}},
  {"Toxic", {hue = 120, saturation = 1.8, contrast = 1.2}, {chromatic = 3, haze = 0.3}},
  {"Underwater", {fogAmount = 0.9, fog = {0.05, 0.35, 0.45}, fogStart = 500, fogEnd = 9000, tintAmount = 0.6,
                  tint = {0.3, 0.8, 1}, wave = 0.04, waveFrequency = 12}, {haze = 1}},
  {"Pixel art", {posterize = 6, dither = 1, saturation = 1.3}, {pixelate = 6}},
  {"Rainbow", {vision = "rainbow", visionMix = 0.75}, {bloom = 0.5}},
  {"Blueprint", {vision = "blueprint"}, {outlines = 0.7, outlineColor = {0.9, 0.97, 1}, outlineThreshold = 0.3, vignette = 0.4}},
  {"Matrix", {vision = "matrix"}, {scanlines = 0.4, bloom = 0.6, bloomThreshold = 0.3}},
  {"Tiny planet", {curve = 1.6, saturation = 1.3}, {vignette = 0.4}},
  {"Kaleidoscope", {saturation = 1.5, hue = 40}, {kaleidoscope = 8}},
  {"Melting", {melt = 0.6, wave = 0.05, temperature = 0.8}, {haze = 0.8}},
}
local presetNames = {}
for i, p in ipairs(PRESETS) do presetNames[i] = p[1] end
local preset = 1

local function applyPreset(i)
  local vhs = S.vhs                    -- the VHS button is its own switch: presets keep it
  W:reset() S:reset()
  W:set(PRESETS[i][2]) S:set(PRESETS[i][3])
  S.vhs = vhs and i ~= 1               -- Original: the tape too
  preset = i
end

-- ---- widgets bound to a field ----
local function slider(t, key, label, min, max, fmt)
  local v, changed = ui.slider(label, t[key], min, max, fmt or "%.2f")
  if changed then t[key] = math.max(min, math.min(max, v)) end
end
local function color(t, key, label)
  local c, changed = ui.color(label, t[key])
  if changed then t[key] = c end
end
local function check(t, key, label)
  local v, changed = ui.checkbox(label, t[key])
  if changed then t[key] = v end
end

local VISIONS = {"none", "night", "thermal", "depth", "rainbow", "blueprint", "matrix"}
local VISION_LABELS = {"None", "Night vision", "Thermal", "Depth", "Rainbow", "Blueprint", "Matrix"}

local function colourTab()
  slider(W, "exposure", "Exposure (stops)", -3, 3)
  slider(W, "brightness", "Brightness", -0.5, 0.5)
  slider(W, "contrast", "Contrast", 0, 3)
  slider(W, "saturation", "Saturation", 0, 3)
  slider(W, "gamma", "Gamma", 0.3, 3)
  slider(W, "hue", "Hue shift", -180, 180, "%.0f deg")
  slider(W, "temperature", "Temperature", -1, 1)
  slider(W, "tintAmount", "Tint", 0, 1)
  color(W, "tint", "Tint colour")
  slider(W, "pulse", "Pulse", 0, 1)
  slider(W, "pulseSpeed", "Pulse speed", 0.1, 8, "%.1f Hz")
end

local function styleTab()
  local index = 1
  for i, name in ipairs(VISIONS) do if W.vision == name then index = i end end
  local chosen, changed = ui.combo("Vision", index, VISION_LABELS)
  if changed then W.vision = VISIONS[chosen] end
  slider(W, "visionMix", "Vision mix", 0, 1)
  slider(W, "toon", "Toon bands", 0, 8, "%.0f")
  slider(W, "posterize", "Posterize", 0, 32, "%.0f levels")
  slider(W, "dither", "Dither", 0, 2)
  slider(W, "sepia", "Sepia", 0, 1)
  slider(W, "invert", "Invert", 0, 1)
  ui.heading("Fog")
  slider(W, "fogAmount", "Fog", 0, 1)
  color(W, "fog", "Fog colour")
  slider(W, "fogStart", "Fog start", 0, 40000, "%.0f")
  slider(W, "fogEnd", "Fog end", 0, 40000, "%.0f")
  ui.heading("Sonar")
  slider(W, "sonarStrength", "Sonar", 0, 3)
  color(W, "sonar", "Sonar colour")
  slider(W, "sonarSpeed", "Sonar speed", 0, 20000, "%.0f")
  slider(W, "sonarWidth", "Sonar width", 20, 3000, "%.0f")
  slider(W, "depthRange", "Depth range", 1000, 40000, "%.0f")
end

local function shapeTab()
  slider(W, "wave", "Wave", 0, 0.5)
  slider(W, "waveFrequency", "Wave frequency", 0.5, 40)
  slider(W, "waveSpeed", "Wave speed", 0, 10)
  slider(W, "curve", "World curve", -2, 2)
  slider(W, "wobble", "Wobble", 0, 3)
  slider(W, "twist", "Twist", -3, 3)
  slider(W, "melt", "Melt", 0, 1)
  slider(W, "stretchX", "Stretch X", 0.25, 2.5)
  slider(W, "stretchY", "Stretch Y", 0.25, 2.5)
  slider(W, "shake", "Shake", 0, 2)
  slider(W, "snap", "PS1 snap", 0, 240, "%.0f")
end

local function screenTab()
  slider(S, "pixelate", "Pixelate", 0, 24, "%.0f px")
  slider(S, "blur", "Blur", 0, 6, "%.1f px")
  slider(S, "sharpen", "Sharpen", 0, 3)
  slider(S, "chromatic", "Chromatic", 0, 12, "%.1f px")
  slider(S, "bloom", "Bloom", 0, 2)
  slider(S, "bloomThreshold", "Bloom threshold", 0, 1)
  slider(S, "outlines", "Outlines", 0, 1)
  color(S, "outlineColor", "Outline colour")
  slider(S, "outlineThreshold", "Outline threshold", 0.02, 1)
  slider(S, "halftone", "Halftone", 0, 16, "%.0f px")
  slider(S, "barrel", "Barrel / CRT", -1, 1.5)
  slider(S, "vignette", "Vignette", 0, 1.5)
  slider(S, "grain", "Film grain", 0, 1)
  slider(S, "scanlines", "Scanlines", 0, 1)
  slider(S, "crtMask", "CRT mask", 0, 1)
  slider(S, "jitter", "Jitter", 0, 3)
  slider(S, "haze", "Heat haze", 0, 3)
  slider(S, "ghost", "Double vision", 0, 40, "%.0f px")
  slider(S, "zoomBlur", "Zoom blur", 0, 2)
  slider(S, "kaleidoscope", "Kaleidoscope", 0, 16, "%.0f")
  slider(S, "letterbox", "Letterbox", 0, 0.3)
  check(S, "mirror", "Mirror") ui.sameLine() check(S, "flip", "Upside down")
end

local TARGETS = {{"terrain", "Terrain"}, {"water", "Water"}, {"models", "Models (dinosaurs, objects, weapons)"},
                 {"plants", "Plants and sprites"}, {"sky", "Sky"}, {"particles", "Particles"},
                 {"shadows", "Shadows"}, {"interface", "Interface (menus, HUD, compass)"}}
local function targetsTab()
  ui.textDisabled("The world effects change these shader groups:")
  local counts = {}
  for _, p in ipairs(shader.programs()) do counts[p.target] = (counts[p.target] or 0) + 1 end
  for _, t in ipairs(TARGETS) do check(T, t[1], string.format("%s (%d)", t[2], counts[t[1]] or 0)) end
  ui.separator()
  ui.textDisabled(#shader.programs() .. " programs, " .. #shader.files() .. " shader files")
end

-- ---- the editor: a game shader's GLSL, changed while the game runs ----
local files, fileIndex, text, message, failed = nil, 1, nil, nil, false
local function editorTab()
  files = files or shader.files()
  if #files == 0 then ui.textDisabled("No shaders loaded yet.") return end
  local i, changed = ui.combo("File", fileIndex, files)
  if changed or not text then fileIndex, text, message = i, shader.source(files[i]), nil end
  text = ui.inputMultiline("##glsl", text, -1, 320)
  if ui.button("Compile") then
    local ok, err = shader.setSource(files[fileIndex], text)
    failed, message = not ok, ok and "Compiled: the game draws with it now." or err
  end
  ui.sameLine()
  if ui.button("Revert to the game's") then
    shader.revert(files[fileIndex])
    text, failed, message = shader.source(files[fileIndex]), false, "The game's own shader again."
  end
  if message then
    ui.textColored(failed and "#ff7070" or "#80ff80", failed and ("Refused, the game keeps the last good one:\n" .. message) or message)
  else
    ui.textWrapped("Change the GLSL and press Compile. A shader that does not compile is refused with the error.")
  end
end

-- ---- the window ----
local function lab()
  local chosen, changed = ui.combo("Preset", preset, presetNames)
  if changed then applyPreset(chosen) end
  ui.sameLine()
  if ui.smallButton("Reset") then applyPreset(1) end
  if ui.button(S.vhs and "VHS  ON" or "VHS") then S.vhs = not S.vhs end
  if ui.hovered() then ui.tooltip("An old tape: wobble, smeared colour, tracking noise, PLAY and the date") end
  ui.tabs("lab", function()
    ui.tab("Colour", colourTab)
    ui.tab("Style", styleTab)
    ui.tab("Shape", shapeTab)
    ui.tab("Screen", screenTab)
    ui.tab("Targets", targetsTab)
    ui.tab("Editor", editorTab)
  end)
end

local open = false
local function toggle()
  open = not open
  ui.cursor(open)
end
keys.bind("F8", toggle, {touch = {label = "LAB"}})
ui.panel("Shader Lab", lab)

-- the camcorder text of an old tape
local MONTHS = {"JAN.", "FEB.", "MAR.", "APR.", "MAY", "JUN.", "JUL.", "AUG.", "SEP.", "OCT.", "NOV.", "DEC."}
local function camcorder(e)
  local size = e.height / 15
  local x, y = e.height * 0.06, e.height * 0.06
  draw.text(x, y, "PLAY", "#f0f0ea", size)
  local w = draw.textSize("PLAY ", size)
  local h = size * 0.62
  draw.fillTriangle(x + w, y + size * 0.18, x + w, y + size * 0.18 + h, x + w + h * 0.9, y + size * 0.18 + h / 2, "#f0f0ea")
  draw.text(x, y + size * 1.1, "SP", "#f0f0ea", size)
  local t = os.date("*t")
  local hour = (t.hour + 11) % 12 + 1
  draw.text(x, e.height - y - size * 2.1, string.format("%s %2d:%02d", t.hour < 12 and "AM" or "PM", hour, t.min), "#f0f0ea", size)
  draw.text(x, e.height - y - size * 1.05, string.format("%s %2d %d", MONTHS[t.month], t.day, t.year), "#f0f0ea", size)
end

on("draw", function(e)
  if S.vhs then camcorder(e) end
  if open then
    open = ui.window("Shader Lab", lab, {x = e.width - 400, y = 20, w = 380, h = 600, closable = true})
    if not open then ui.cursor(false) end
  end
end)

-- other mods (and the tests) can use the lab: mods.get("shader_lab").preset("CRT arcade")
mod.exports = {
  presets = presetNames,
  preset = function(name)
    for i, n in ipairs(presetNames) do if n == name then applyPreset(i) return true end end
    return false
  end,
  open = function(on) if on ~= open then toggle() end end,
}

Swiftclaw

A new species for Dinosaur Hunter whose model comes from Blender (Models from Blender: glTF). swiftclaw.glb holds the mesh, the skeleton, the 512 x 512 texture and eight actions; swiftclaw.blend is the source to open and change. swiftclaw.cat lists the actions in the order of the Velociraptor's animation slots (run, walk, slide, swim, jump, die, eat, sleep) with the Velociraptor's own sounds, and the content pack below makes it a hunt species: a copy of the Velociraptor with this file, its name, card, price and the menu pictures swiftclaw_icon.tga / swiftclaw_icon_locked.tga. No script. Needs API 4.

{
  // A new species: a copy of the Velociraptor (its AI, senses, sounds) with a model of its own. "file" names the
  // character file swiftclaw.cat, whose model and animations come from swiftclaw.glb (the game makes swiftclaw.3dn,
  // swiftclaw_run.ani ... and swiftclaw.tga from the glTF when it loads them).
  "id": "swiftclaw",
  "copy": "velociraptor",
  "file": "swiftclaw",
  "name": "Swiftclaw",
  "card": {
    "length": "13 ft (4 m)",
    "weight": "330 lbs (150 kg)",
    "diet": "Small animals, carrion",
    "danger": "Fast and curious.\nIt hunts the hunter\nwhen it catches his scent."
  },
  "price": 150,
  "score": 18,
  "icon": "swiftclaw_icon.tga",
  "iconLocked": "swiftclaw_icon_locked.tga"
}

Extra Dinos

Six new hunt species for Dinosaur Hunter, made the Swiftclaw's way and taken further: each has its own glTF model (<id>/<id>.glb, with its .blend), sounds, card, menu pictures and a behaviour of its own in Lua. A content pack defines them (content/species/<id>.json: the AI whose animation slots each one uses, its size, senses, price and group); the .cat lists the animations in that AI's order, then the extra ones its brain plays (a display, a sniff, a tail lash). They are on the hunt menu's second dinosaur page.

Each brain (<id>/brain.lua, Creature behaviour) runs in place of the species' AI and hands the game's AI the frames it does best: its walk with the way round trees and rocks, its chase, its kill with the death camera (c:stockAI); c:walkTo / c:runTo and the game's sight and smell test (c:senses) do the rest. All six are built on brains/common.lua, which turns the game's noticing, shots, hits, calls and deaths into handlers and keeps each creature in a state with a time limit and a watchdog. Its header documents it, and the pack's README has a small brain to start your own from. main.lua gives the brains:

-- Extra Dinos: six new hunt species. Each lives in its own folder (model, animations, sounds, menu pictures) with
-- its behaviour in <id>/brain.lua; this file gives every creature of those species its brain: when it spawns, and to
-- the creatures already in the world when the scripts are (re)loaded in a hunt (F9, the Mods screen's Apply).
--
-- A brain module returns a table:
--   brain = function(c, dt)    runs every frame in place of the species' AI (see docs: Creature behaviour and AI)
--   spawn = function(c)        optional: once when a creature of the species appears (scale, senses, data)
-- and may listen to events itself with on(...). The brains built on brains/common.lua (the pack's shared brain
-- module: senses, events, states with time limits and a watchdog) return what its B.define makes.

local DINOS = {"compsognathus", "concavenator", "diplodocus", "therizinosaurus", "baryonyx", "giganotosaurus"}

local brains = {}
for _, id in ipairs(DINOS) do
  local ok, module = pcall(require, id .. ".brain")
  if ok and type(module) == "table" then
    brains[id] = module
  else
    print("Extra Dinos: no brain for " .. id .. " (" .. tostring(module) .. "): it keeps its base AI")
  end
end

local function give(c, module)
  if module.spawn then module.spawn(c) end
  if module.brain then c.brain = module.brain end
end

-- room for big bodies: the game places a group's members 1.25-2.5 m apart (right for its own dinosaurs), so a herd of
-- 24 m Diplodocus would appear inside each other. One that spawns closer than ROOM to another of its kind moves out
-- beside that one, 1 - 1.3 x ROOM away, onto ground its kind may stand on (the game's own test); its herd brain keeps
-- them together from there. (Only at spawn: a reload leaves the living where they are.)
local ROOM = {diplodocus = 32 * 128}

local function crowding(c, x, z, room)
  for _, other in ipairs(world.creatures({species = c.species})) do
    if other ~= c and other.alive and (other.x - x) ^ 2 + (other.z - z) ^ 2 < room * room then return other end
  end
end

local function makeRoom(c, room)
  local near = crowding(c, c.x, c.z, room)
  if not near then return end
  local a0 = math.random() * 2 * math.pi
  for k = 0, 11 do
    local a, r = a0 + k * math.pi / 6, room * (1 + 0.3 * math.random())
    local x, z = near.x + math.cos(a) * r, near.z + math.sin(a) * r
    if ai.goodPlace(x, z, c.type) and not crowding(c, x, z, room) then
      c.x, c.z, c.y = x, z, world.ground(x, z)
      return
    end
  end
end

on("spawn", function(e)
  local c = e.creature
  if ROOM[c.species] then makeRoom(c, ROOM[c.species]) end
  local module = brains[c.species]
  if module then give(c, module) end
end)

-- the scripts were (re)loaded during a hunt: a reload drops every creature's brain, so the living ones get theirs
-- again (a module that does this itself has already given it: those are left alone)
if game.inHunt() then
  for id, module in pairs(brains) do
    for _, c in ipairs(world.creatures({species = id})) do
      if c.alive and c.brain == nil then give(c, module) end
    end
  end
end
{
  // Giganotosaurus: a new hunt species with the T-Rex's AI slots and rules (its kill with the death camera, its
  // reactions to shots and noise). giganotosaurus.cat lists the T-Rex's ten animations in that order, then the sniff
  // of its Lua brain, giganotosaurus/brain.lua, which main.lua gives every Giganotosaurus: it stalks the hunter from a
  // distance, sniffing the air, and charges when it sees him close or is shot. Unlike the T-Rex (health 1024: only an
  // eye shot kills it) it dies from body shots; a shot into an eye still kills at once. The model, animations and
  // texture come from giganotosaurus.glb (made by tools/gltf/make_giganotosaurus.py).
  "id": "giganotosaurus",
  "ai": "trex",
  "file": "giganotosaurus",
  "name": "Giganotosaurus",
  "card": {
    "length": {"en": "40-48 ft (12-15 m)", "de": "12-15 m", "fr": "12-15 m", "es": "12-15 m"},
    "weight": {"en": "up to 9 tons", "de": "bis zu 9 Tonnen", "fr": "jusqu'à 9 tonnes", "es": "hasta 9 toneladas"},
    "diet": {"en": "Giant plant eaters", "de": "Riesige Pflanzenfresser", "fr": "Herbivores géants",
             "es": "Herbívoros gigantes"},
    "danger": {
      "en": "Extremely dangerous.\nIt stalks the hunter by scent\nand charges when it sees him.",
      "de": "Äußerst gefährlich.\nEs folgt der Witterung des Jägers\nund greift an, wenn es ihn sieht.",
      "fr": "Extrêmement dangereux.\nIl traque le chasseur à l'odeur\net charge quand il le voit.",
      "es": "Extremadamente peligroso.\nAcecha al cazador por su olor\ny embiste cuando lo ve."
    }
  },
  "price": 1400,
  "score": 65,
  "health": 40,
  "mass": 7.6,               // x scale²: about 8 t
  "size": 13.0,              // x scale: the trophy's length
  "radius": 400,
  "sight": 0.75,
  "smell": 0.95,
  "hearing": 0.85,
  "scale": [0.80, 0.96],     // the game multiplies by 64/55: 0.93 - 1.12 in a hunt, 12 - 15 m long, 4 m at the hips
  "huntable": true,
  "dangerous": true,
  "group": [1, 1],
  "groupChance": 0,
  "skipChance": 0.5,
  "trophyPriority": 18,
  "order": 6,
  "icon": "giganotosaurus_icon.tga",
  "iconLocked": "giganotosaurus_icon_locked.tga",
  "calls": ["giganotosaurus_call_a", "giganotosaurus_call_b", "giganotosaurus_call_c"]
}

Extra Guns

Four new weapons for Dinosaur Hunter, each a glTF model of the gun with the hunter's hands and arms on one skeleton (the take, fire, put-away and reload animations), with its own sounds, stats, card and menu pictures: an Auto Shotgun, a Lever-Action Rifle, a Harpoon Gun and a .577 Express Rifle. A content pack without a script: each content/weapons/<id>.json names the game's weapon whose slot it takes (base: the shotgun, the rifle, the crossbow, the double-barrelled shotgun), so it reloads, kicks and flies like that one, and its .cat lists the animations in that weapon's order. Picked in the hunt menu (its second weapon page), a gun takes the place of the slot's own weapon; all four can go on one hunt. A weapon model is seen from the eye (glTF).

{
  // The Harpoon Gun: a heavy pneumatic launcher in the crossbow's slot (its slot and behaviour: the harpoon flies
  // like the crossbow's bolts and drops with distance; no reload animation, the fire animation loads the next
  // harpoon). One harpoon per shot: after each the hunter slides a new one into the barrel and pumps the air tank
  // up again, so it fires slowly. harpoon_gun.cat names the model and animations (harpoon_gun.glb, made by
  // tools/gltf/make_harpoon_gun.py) and the sounds (harpoon_gun/sounds/, made by tools/sfx/).
  "id": "harpoon_gun",
  "base": "xbow",
  "file": "harpoon_gun",
  "name": {"en": "Harpoon Gun", "de": "Harpunengewehr", "fr": "Fusil-harpon", "es": "Fusil arpón"},
  "info": {
    "en": "A heavy pneumatic launcher for big game. Its\n barbed harpoon hits harder than any bullet,\n and the shot is quieter than a crossbow's.\n But each harpoon must be slid into the barrel\n by hand and the air tank pumped up again.\n\nPower: ==== Precision: ===^\nLoudness: {^^^ Firing Rate: {^^^",
    "de": "Ein schwerer Druckluftwerfer für Großwild.\nSeine Widerhakenharpune trifft härter als\njede Kugel, und der Schuss ist leiser als\nder eines Kreuzbogens. Doch jede Harpune\nmuss von Hand in den Lauf geschoben und\nder Lufttank neu aufgepumpt werden.\n\nFeuerkraft: ==== Genauigkeit: ===^\nLautstärke: {^^^ Feuerrate: {^^^",
    "fr": "Un lourd lance-harpon pneumatique pour le\ngros gibier. Son harpon barbelé frappe plus\nfort que toute balle, et le tir est plus\ndiscret que celui d'une arbalète. Mais chaque\nharpon doit être glissé à la main dans le\ncanon et le réservoir d'air regonflé.\n\nPuissance: ==== Précision: ===^\nBruit: {^^^ Cadence de tir: {^^^",
    "es": "Un pesado lanzaarpones neumático para caza\nmayor. Su arpón con lengüetas golpea más\nfuerte que cualquier bala y el disparo es más\nsilencioso que el de una ballesta. Pero cada\narpón se mete a mano en el cañón y hay que\nbombear de nuevo el depósito de aire.\n\nPotencia: ==== Precisión: ===^\nRuido: {^^^ Tasa de disparo: {^^^"
  },
  "power": 12,
  "precision": 1.4,
  "loudness": 0.25,
  "rate": 0.45,
  "ammo": 10,
  "magazine": 1,
  "price": 1100,
  "ammoPrice": 45,
  "icon": "harpoon_gun_icon.tga",
  "iconLocked": "harpoon_gun_icon_locked.tga",
  "order": 3
}

Hunting Lodge

Ice Age only. Its content pack adds the Dire Wolf (the wolf's own model and AI, bigger, with its own card, price and a reddish menu cell) and a fur cloak to the hunt menu's equipment; the script puts a LODGE button in the main menu that opens a page in the game's style: every animal of the hunt menu, cheapest first, with its menu picture, price and score. See Menus and pages and Equipment.

-- The hunting lodge: a page in the game's own style (its background, fonts, buttons) opened from a LODGE button in the
-- main menu. It lists the animals of the hunt menu, the Dire Wolf of this mod's content pack among them, and shows the
-- chosen one's menu picture, price and score. Positions are game units: the screen is 320 high, y from the top.
local lodge             -- the page (below)
local animals = {}      -- the hunt menu's animals, as the content registry has them
local shown = 1         -- the one picked in the list

local function collect()
  animals = {}
  for _, s in ipairs(content.species()) do
    if s.hunt and not s.hidden then animals[#animals + 1] = s end
  end
  table.sort(animals, function(a, b) return a.price < b.price end)
end

local list, details
local function show(i)
  shown = i
  local s = animals[i]
  if not s then return end
  details:setText(string.format("%s\n\nPrice: %d credits\nScore: %d\nHealth: %d", s.name, s.price,
    math.floor(s.score + 0.5), math.floor(s.health + 0.5)))
end

local function build()
  lodge:clear()
  collect()
  local w, h = menu.screen()
  local rows = {}
  for _, s in ipairs(animals) do rows[#rows + 1] = s.name end
  lodge:text("The animals of the hunt menu, cheapest first. Pick one.", {y = 46, x = w / 2, width = 360})
  list = lodge:list(rows, function(i) show(i) end, {x = w / 2 - 110, y = 168, width = 200, rows = 7, selected = shown})
  details = lodge:text("", {x = w / 2 + 120, y = 190, align = "left", width = 150})
  show(shown)
end

lodge = menu.page("lodge", {
  title = "Hunting lodge",
  onOpen = build,
  -- the chosen animal's menu cell, drawn with the game's renderer above the details
  draw = function()
    local s = animals[shown]
    if not s or s.icon == "" then return end
    local w = menu.screen()
    draw.sprite(s.icon, w / 2 + 165, 130, {center = true, scale = 0.9, color = s.iconColor})
  end,
})

menu.button("main", "LODGE", function() lodge:open() end, {sound = "menugo.wav"})

Sandbox Panel

One window (F6, or the Sandbox tab of the mod menu) that edits the creature under the crosshair and its species, the weapon in hand, the hunter's speed, jump, gravity and eye height, the fog, sky, wind and view distance (Game data). Switched off, the mod leaves nothing behind: the game puts the definitions back by itself, and the unload handler gives the creatures it resized their size and AI back.

-- Sandbox Panel: the data layer (API 3) in one window. F6 opens it in a hunt (a phone: the SANDBOX button), and the
-- mod menu (F1) has it as the Sandbox tab. Shows: world.species(id) handles, creature fields, weapon definitions and
-- slots, the hunter's overrides, world.weather / world.wind, and that nothing outlives the mod: definitions are put
-- back by the game when the mod is switched off (game.changes() lists them), the creatures it edited by the unload
-- handler below.

local open = false
local target            -- the creature picked with the crosshair
local edited = {}       -- creature -> its values before the panel changed them (put back on unload)

local function remember(c)
  if not edited[c] then edited[c] = {scale = c.scale, ai = c.ai} end
end

-- the creature under the crosshair, else the one nearest to the view direction (within 15 degrees, 8000 units)
local function pick()
  local _, _, _, _, c = player.aim(30000)
  if not c then
    local x, _, z = player.pos()
    local best = 15
    for _, o in ipairs(world.creatures({radius = 8000})) do
      local off = math.abs(math.angleDiff(player.yaw(), math.yaw(x, z, o.x, o.z)))
      if off < best then best, c = off, o end
    end
  end
  if c then target = c end
end

local function section(title, fn)
  if ui.collapsing(title, true) then fn() end
end

local function slider(label, value, lo, hi, fmt)
  local v, changed = ui.slider(label, value, lo, hi, fmt or "%.2f")
  return changed and v or nil
end

local function drawCreature()
  if ui.button("Pick the creature under the crosshair") then pick() end
  if not (target and target.valid) then
    ui.textDisabled("Nothing picked: aim at a creature and press the button (or open the panel while aiming).")
    return
  end
  local c = target
  ui.text(string.format("%s  #%d  %s", c.name, c.index, c.alive and "" or "(dead)"))
  ui.text(string.format("health %.0f / %.0f   speed %.0f u/s   %s%s", c.health, c.maxHealth, c.velocity,
    c.visible and "visible" or "hidden", c.swimming and ", swimming" or ""))
  local v = slider("Size", c.scale, 0.2, 5)
  if v then remember(c); c.scale = v end
  v = slider("Health", c.health, 0, c.maxHealth * 2, "%.0f")
  if v and c.alive then c.health = math.max(1, v) end
  local ai, changed = ui.checkbox("AI on", c.ai)
  if changed then remember(c); c.ai = ai end
  if ui.button("Wound it (bleeds 30 s)") then c.bleeding = c.bleeding + 30; c:alert(20) end
  ui.sameLine()
  if ui.button("Calm it") then c.afraid = 0; c.state = 0 end

  ui.separator()
  local s = world.species(c.species)
  ui.text("Species " .. s.id .. " (all of them; undone when the mod is off)")
  v = slider("Mass (t)", s.mass, 0.01, 50)
  if v then s.mass = v end
  v = slider("Sight", s.sight, 0.1, 5)
  if v then s.sight = v end
  v = slider("Smell", s.smell, 0.1, 5)
  if v then s.smell = v end
  v = slider("Health of new ones", s.health, 1, 5000, "%.0f")
  if v then s.health = v end
  if ui.button("Apply to the living ones") then ui.toast(s:applyToLiving() .. " creature(s) updated") end
  ui.sameLine()
  if ui.button("Reset species") then s:reset() end
end

local function drawWeapon()
  local slot = player.slot()
  if not slot then
    ui.textDisabled("No weapon in hand.")
  else
    local w = slot.weapon
    ui.text(string.format("%s: %d rounds, %d loaded, %s", w.name, slot.ammo, slot.loaded, slot.state))
    local v = slider("Power", w.power, 0.1, math.max(50, w.power * 4), "%.1f")
    if v then w.power = v end
    v = slider("Shots per second", w.rate, 0.2, 20, "%.1f")
    if v then w.rate = v end
    local n, changed = ui.sliderInt("Rounds", slot.ammo, 0, 500)
    if changed then slot.ammo = n end
    if ui.button("Reset weapon") then w:reset() end
  end
  local v = slider("Spread", weapons.spreadScale(), 0, 5)
  if v then weapons.spreadScale(v) end
  v = slider("Recoil", weapons.recoilScale(), 0, 5)
  if v then weapons.recoilScale(v) end
end

local function drawHunter()
  local v = slider("Speed", player.speed(), 0.25, 5)
  if v then player.speed(v) end
  v = slider("Jump", player.jumpPower(), 0.25, 5)
  if v then player.jumpPower(v) end
  v = slider("Gravity", player.gravity(), 300, 9000, "%.0f")
  if v then player.gravity(v) end
  v = slider("Eye height (180 or lower: crouch)", player.eyeHeight(), 60, 400, "%.0f")
  if v then player.eyeHeight(v) end
  v = slider("Regeneration /s", player.regenRate(), 0, 100, "%.0f")
  if v then player.regenRate(v) end
  if ui.button("Hunter back to normal") then
    for _, f in ipairs({player.speed, player.jumpPower, player.gravity, player.eyeHeight, player.regenRate}) do f(nil) end
  end
end

local function drawWorld()
  local w = world.weather
  ui.text("Time of day: " .. tostring(world.time()))
  local v = slider("Fog start", w.fogStart, 0, 20000, "%.0f")
  if v then w.fogStart = v end
  v = slider("Fog end", w.fogEnd, 500, 25000, "%.0f")
  if v then w.fogEnd = v end
  local color, changed = ui.color("Sky", w.skyColor)
  if changed then w.skyColor = color end
  color, changed = ui.color("Sun light", w.sunColor)
  if changed then w.sunColor = color end
  v = slider("View distance", w.viewDistance, 2000, 19456, "%.0f")
  if v then w.viewDistance = v end
  if w.snow then
    v = slider("Snow", w.snow, 0, 1)
    if v then w.snow = v end
  end
  local wind = world.wind
  local locked
  locked, changed = ui.checkbox("Hold the wind", wind.locked)
  if changed then wind.locked = locked end
  v = slider("Wind towards (yaw)", wind.yaw, 0, 360, "%.0f")
  if v then wind.yaw = v end
  v = slider("Wind speed", wind.speed, 0, 40, "%.1f")
  if v then wind.speed = v end
  local night = world.nextTime() == "night"
  local on
  on, changed = ui.checkbox("Next hunts at night", night)
  if changed then world.nextTime(on and "night" or nil) end
end

local function drawPanel()
  if not game.inHunt() then
    ui.textDisabled("Start a hunt to use the sandbox.")
    return
  end
  section("Creature", drawCreature)
  section("Weapon", drawWeapon)
  section("Hunter", drawHunter)
  section("Weather and wind", drawWorld)
  ui.textDisabled(#game.changes() .. " change(s) to the game's definitions; switched off, the mod undoes them.")
end

ui.panel("Sandbox", drawPanel)

local function toggle()
  if not game.inHunt() then return end
  open = not open
  if open then pick() end
  ui.cursor(open)
end
keys.bind("F6", toggle, {touch = {label = "SANDBOX"}})

on("draw", function()
  if not open then return end
  if not game.inHunt() then open = false; ui.cursor(false); return end
  open = ui.window("Sandbox", drawPanel, {x = 30, y = 80, w = 430, h = 620, closable = true})
  if not open then ui.cursor(false) end
end)

on("new_hunt", function() target = nil; edited = {} end)

-- the creatures this panel edited get their size and AI back (definitions come back by themselves)
on("unload", function()
  for c, o in pairs(edited) do
    if c.valid then
      c.scale = o.scale
      c.ai = o.ai
    end
  end
end)

Content packs for both games

Three content packs (Content packs) made for both games with the per-game folders (One mod for both games): what both games share sits in content/, what differs in content/dinohunter/ and content/iceage/, which each game merges into the shared files by name. Every entry uses the running game's own files (models, sounds, menu pictures), so nothing of the games is copied into the mods.

Alpha T-Rex adds a new hunt species to each game: a bigger, tougher T-Rex in Dinosaur Hunter, an alpha sabertooth in Ice Age, each with its own name, card, price, score and a reddish menu cell. The species are each game's own, so both files sit in the game folders. A small script, the same for both games, gives the alpha what JSON cannot: armour against body shots (c.armor), a roar when a shot wounds it (c:roar) and a warning when it starts hunting you. When it gets you, the results screen names it ("YOU'VE BEEN KILLED BY ALPHA T-REX!"): an added species is named by its own name.

{
  // Dinosaur Hunter's alpha (content/dinohunter/: only this game reads it; "trex" is one of its species ids).
  // A new species starts as a copy of its "ai" species (the T-Rex), then takes these fields.
  "id": "alpha_trex",
  "ai": "trex",
  "file": "tirex",
  "name": {"en": "Alpha T-Rex", "de": "Alpha-T-Rex", "fr": "Tyrannosaure alpha", "es": "T. rex alfa"},
  "card": {
    "length": "42-52 ft (13-16 m)",
    "weight": "up to 12 tons",
    "diet": "Everything that moves",
    "danger": "The old king of the island.\nOnly a shot in the eye\nbrings him down."
  },
  "health": 2048,
  "score": 140,
  "price": 2500,
  "scale": [1.15, 1.4],
  "mass": 9,
  "size": 14,
  "radius": 520,
  "smell": 0.95,
  "sight": 0.9,
  "hearing": 0.85,
  "carryHeight": 210,
  "icon": "button_dino_active_9",
  "iconLocked": "button_dino_inactive_9",
  "iconColor": [255, 150, 120]
}
{
  // Ice Age's alpha (content/iceage/: only this game reads it). A copy of the game's own sabertooth (its smilo.cat:
  // model, animations, sounds, and its AI), bigger and tougher, with its own name, card, price and a tinted menu cell.
  // Ice Age has no licences: the hunt menu adds up the prices of what is chosen, and the credits must cover them.
  "id": "alpha_smilodon",
  "ai": "smilodon",
  "file": "smilo",
  "name": {"en": "Alpha Sabertooth", "de": "Alpha-Säbelzahnkatze", "fr": "Smilodon alpha", "es": "Dientes de sable alfa"},
  "card": {
    "length": "2.5-3 m",
    "weight": "up to 450 kg",
    "diet": "Meat",
    "danger": "The leader of the pride.\nHunts the hunters."
  },
  "health": 20,
  "score": 32,
  "price": 400,
  "scale": [1.15, 1.35],
  "mass": 2.2,
  "size": 6.5,
  "radius": 700,
  "smell": 0.95,
  "sight": 1.0,
  "hearing": 0.9,
  "carryHeight": 100,
  "icon": "button_dino_active_7",
  "iconLocked": "button_dino_inactive_7",
  "iconColor": [255, 150, 120]
}
-- Alpha T-Rex: each game's alpha predator comes from the content pack (content/dinohunter/species/alpha_trex.json,
-- content/iceage/species/alpha_smilodon.json); this script gives it what a JSON file cannot: armour against body shots,
-- a roar when a shot wounds it, and a warning when it starts hunting you. (When it gets you, the results screen shows
-- the line of its AI species, the T-Rex's or the sabertooth's, by itself.) Shows: one script for both games next to
-- per-game content, c.armor, c:roar, the damage and creature_hunt events (API 3).

local ALPHA = game.id() == "iceage" and "alpha_smilodon" or "alpha_trex"

local lastRoar = {}  -- creature -> timer.now() of its last roar
local warned = {}    -- creature -> true once the hunter was warned about it

on("spawn", function(e)
  if e.creature.species == ALPHA then
    e.creature.armor = 0.5  -- half damage from body shots; a shot into the head or heart still kills at once
  end
end)

-- a wounded alpha roars back (once every 15 seconds); its AI carries on after the roar
on("damage", function(e)
  local c = e.creature
  if c.species ~= ALPHA or e.source ~= "hunter" or e.amount >= c.health then return end
  local now = timer.now()
  if now - (lastRoar[c] or -100) > 15 then
    lastRoar[c] = now
    timer.after(0.3, function()
      if c.valid and c.alive then c:roar() end
    end)
  end
end)

on("creature_hunt", function(e)
  local c = e.creature
  if c.species == ALPHA and not warned[c] then
    warned[c] = true
    game.message(c.name .. " is hunting you!", 4, "#ff6040")
  end
end)

on("new_hunt", function() lastRoar, warned = {}, {} end)

Elephant Gun is a heavy two-shot rifle in the rifle's slot. The weapon itself is shared; its own elephant_gun.cat names the game's files (rifle.3dn, the double-barrel shotgun's blast), so each game shows its own rifle model. The game folders hold what differs: Dinosaur Hunter sells a licence and the ammunition, Ice Age (no licences) counts the price against the hunter's credits when it is chosen for a hunt.

{
  // Both games: a new weapon, a copy of its "base" weapon (the rifle's slot, behaviour and stats), then these fields.
  // elephant_gun.cat names the game's files (rifle.3dn, its animations, the double-barrel shotgun's blast), so each game
  // shows its own rifle model. The price and the card differ per game: content/dinohunter/, content/iceage/.
  "id": "elephant_gun",
  "base": "rifle",
  "file": "elephant_gun",
  "name": "Elephant Gun",
  "power": 14,
  "precision": 1.9,
  "rate": 0.8,
  "ammo": 10,
  "magazine": 2,
  "loudness": 2.6,
  "icon": "button_weapon_active_5",
  "iconLocked": "button_weapon_inactive_5",
  "iconColor": [255, 205, 140]
}
{
  // Ice Age: no licences; the price counts against the hunter's credits when it is chosen for a hunt
  "id": "elephant_gun",
  "info": "A double rifle for mammoths and worse.\nTwo heavy rounds, then a long reload.\nEvery predator of the valley hears it.\n\nPower: ==== Precision: ==={\nLoudness: ==== Firing Rate: ={^^",
  "price": 250
}

Cheap Hunting changes the rules: the shared rules.json halves the prices and gives better trophies, ten species per hunt and a third bonus species; each game's own rules.json adds what only it has (Dinosaur Hunter: a cheaper T-Rex, supplies and relocations; Ice Age: a cheaper bear and yeti), merged into the shared one.

// Both games: half-price hunting, better trophies, ten species per hunt and a third bonus species.
// What only one game has is in content/dinohunter/rules.json and content/iceage/rules.json, merged into this file.
{
  "priceScale": {"species": 0.5, "weapons": 0.5, "maps": 0.5, "ammo": 0.5},
  "maxSpecies": 10,
  "score": {"multiplier": 1.25, "unlicensed": 0.75},
  "hunt": {
    "bonus": {"count": 3, "spawns": 2}
  }
}
// Ice Age: no licences; the hunt menu adds up the prices of what is chosen, and the hunter's credits must cover them,
// so lower prices let him take more. The bear and the yeti cheaper still (these prices are halved too by the shared
// priceScale), a better start (the game gives 50 credits) and more animals per hunt.
{
  "prices": {"species": {"bear": 300, "bigfoot": 500}},
  "startCredits": 200,
  "hunt": {"dinoCount": [28, 36]}
}

Small recipes

Bigger dinosaurs everywhere

on("spawn", function(e) e.creature.scale = e.creature.scale * 1.5 end)

One-shot kills with the first weapon

on("hit", function(e) if e.weapon == 0 then e.damage = 100000 end end)

A T-Rex every two minutes

on("hunt_start", function()
  timer.every(120, function() if game.inHunt() then world.spawnNear("trex", 5000) end end)
end)

Raptor ambush: ten raptors in a ring around you, five seconds into the hunt

on("hunt_start", function()
  timer.after(5, function()
    local x, _, z = player.pos()
    for i = 1, 10 do
      local dx, dz = math.forward(i * 36)
      local r = world.spawn("velociraptor", x + dx * 4000, z + dz * 4000)
      if r then r:alert() end
    end
  end)
end)

Creature fights between two teams

keys.bind("F6", function()
  for i = 1, 4 do world.spawnNear("velociraptor", 2500 + i * 200).team = 1 end
  for i = 1, 2 do world.spawnNear("allosaurus", 4000 + i * 300).team = 2 end
  world.fights(true)
end)

Count kills per species, saved

local stats = mod.load() or {}
on("kill", function(e)
  if e.byHunter then
    stats[e.creature.species] = (stats[e.creature.species] or 0) + 1
    mod.save(stats)
  end
end)
ui.panel("My trophies", function()
  for species, n in pairs(stats) do ui.text(species, n) end
end)