Toby Chui 2 недель назад
Родитель
Сommit
812a6b5911

+ 39 - 2
src/web/Blocky/README.md

@@ -42,6 +42,27 @@ its folder.
   part inside itself.
 - Random tick changes such as grass spreading or reeds growing do not mark a
   chunk as modified (`world.quiet`), so untouched chunks never enter the save.
+- World rules (`world.rules`, saved with the world): `tickSpeed` (random
+  ticks per section per game tick, default 3) and `fireSpread`.
+- Wheat does not use random ticks: `cropTick` runs once a second over
+  `chunk.crops` and adds to a per crop progress (`world.cropProgress`, saved)
+  so a full grow is about 30 minutes on watered farmland (+-15 % per stage,
+  half speed when dry), scaled by `tickSpeed / 3`. Crops need light 9 from
+  the sky or a lamp / torch, but grow at night too.
+- Liquids share one `liquidTick` (`LIQUID` table: water renews and flows 7,
+  lava flows 3 and slower). Lava touching water becomes obsidian (source) or
+  cobblestone. Fire is a scheduled tick that burns `FLAME_BURN` blocks and
+  jumps to air beside `FLAME_CATCH` blocks unless `fireSpread` is off.
+- Doors and beds are two blocks; `world.removePartner` removes the other half
+  whenever one changes, so only the broken half drops the item. A door hangs
+  on the edge nearest the player who placed it; its window pixels are
+  transparent (alpha tested). Each bed half has a raised mattress and two legs
+  at its outer end.
+- Short plants (tall grass, flowers, mushrooms, saplings, dead bushes) are
+  `replaceable`: placing a block, torch or liquid on them replaces them and
+  drops the plant, and a hoe tills through them.
+- Saved chunks are resumed (`resumeChunk`): crops re-registered, fire and
+  moving liquids rescheduled.
 
 ## Crafting
 
@@ -66,12 +87,28 @@ T opens the chat line, / opens it with a slash. Commands other than `/help`
 and `/seed` need the world's cheats option (also switchable in the pause
 menu): `/give`, `/tp` (`~` relative, y optional), `/time`, `/weather`,
 `/gamemode`, `/difficulty`, `/setblock`, `/clear`, `/heal`, `/kill`,
-`/spawnpoint`.
+`/spawnpoint`, `/tickspeed`, `/firespread` and `/gamerule randomTickSpeed |
+doFireTick`.
+
+## Pick block
+
+Middle click a block to take it in hand (`game.pickBlock`): if it is already
+on the hotbar that slot is selected; otherwise creative fills the selected
+slot with a full stack, and survival swaps a stack in from the main
+inventory (nothing happens when the player has none).
+
+## Beds
+
+Right click a bed at night (or in a thunderstorm) to sleep: the screen fades
+for three seconds, then time jumps to the next morning, the weather clears
+and the respawn point moves to the bed. Shift or a movement key gets you up.
 
 ## Testing standalone
 
 Serve `src/web` statically (the `webroot-static` launch config) and open
-`/Blocky/index.html`; worlds then go to IndexedDB. The Browser pane cannot
+`/Blocky/index.html`; worlds then go to IndexedDB. A world starts without a
+"click to play" screen; the pointer lock is requested right away and again
+on the first click into the view if the browser refused. The Browser pane cannot
 hold a pointer lock, so scripted tests fake it with
 `Object.defineProperty(blocky.input, "locked", { get: () => true })` and push
 key codes into `blocky.input.keys` / `pressed` and buttons into

+ 85 - 7
src/web/Blocky/css/style.css

@@ -556,6 +556,41 @@ body.screen-open #crosshair {
     transition: none;
 }
 
+#burning {
+    position: absolute;
+    inset: 0;
+    background: linear-gradient(to top, rgba(255, 110, 20, 0.55), rgba(255, 60, 0, 0.12) 45%, rgba(255, 60, 0, 0) 70%);
+    opacity: 0;
+    transition: opacity 0.4s;
+}
+
+#burning.on {
+    opacity: 1;
+}
+
+#sleep {
+    position: fixed;
+    inset: 0;
+    z-index: 25;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    gap: 10px;
+    background: rgba(4, 6, 16, 0.3);
+}
+
+.sleepmsg {
+    font-size: 28px;
+    font-weight: 700;
+    text-shadow: 2px 2px 0 #000;
+}
+
+.sleephint {
+    color: var(--muted);
+    text-shadow: 1px 1px 0 #000;
+}
+
 #debug {
     position: absolute;
     left: 6px;
@@ -1018,15 +1053,55 @@ body.screen-open #crosshair {
     background: #3c5f2c;
 }
 
+/* Creative item grid: nine columns plus room for a thin scrollbar, so it
+   can never need a horizontal one */
+.scr-col.creative {
+    --cell: 44px;
+    display: flex;
+    flex-direction: column;
+    align-items: flex-start;
+}
+
 .palette {
-    display: grid;
-    grid-template-columns: repeat(9, 44px);
-    gap: 2px;
-    max-height: 190px;
+    box-sizing: content-box;
+    width: calc(9 * var(--cell) + 8 * 2px + 12px);
+    height: calc(6 * var(--cell) + 5 * 2px);
+    overflow-x: hidden;
     overflow-y: auto;
-    padding: 2px;
+    padding: 4px;
     background: rgba(0, 0, 0, 0.3);
     border: 2px solid #0b0c0e;
+    scrollbar-width: thin;
+    scrollbar-color: #5b616b rgba(0, 0, 0, 0.3);
+}
+
+.palette::-webkit-scrollbar {
+    width: 10px;
+}
+
+.palette::-webkit-scrollbar-thumb {
+    background: #5b616b;
+}
+
+.palette::-webkit-scrollbar-track {
+    background: rgba(0, 0, 0, 0.3);
+}
+
+.palgrid {
+    display: grid;
+    grid-template-columns: repeat(9, var(--cell));
+    gap: 2px;
+}
+
+.creativehot {
+    display: flex;
+    align-items: center;
+    gap: 12px;
+    margin-top: 10px;
+}
+
+.scr-col.creative .hint {
+    max-width: calc(9 * var(--cell) + 80px);
 }
 
 .pal {
@@ -1206,11 +1281,14 @@ body.screen-open #crosshair {
         transform-origin: 0 0;
     }
 
-    .slots,
-    .palette {
+    .slots {
         grid-template-columns: repeat(9, 34px);
     }
 
+    .scr-col.creative {
+        --cell: 34px;
+    }
+
     #screenPanel {
         flex-direction: column;
     }

BIN
src/web/Blocky/img/desktop_icon.png


+ 7 - 6
src/web/Blocky/index.html

@@ -26,6 +26,7 @@
     <div id="hud" class="hidden">
         <div id="underwater"></div>
         <div id="hurt"></div>
+        <div id="burning"></div>
         <div id="crosshair"></div>
         <pre id="debug" class="hidden"></pre>
         <div id="message"></div>
@@ -131,11 +132,10 @@
         </div>
     </div>
 
-    <div id="resume" class="overlay hidden">
-        <div class="box center clickable">
-            <h2>Click to play</h2>
-            <p>Move with W A S D, look with the mouse. Press Esc to pause.</p>
-        </div>
+    <div id="sleep" class="hidden">
+        <div class="sleepmsg">Sleeping...</div>
+        <div class="sleephint">Press Shift to get up</div>
+        <button class="btn" id="btnLeaveBed">Leave Bed</button>
     </div>
 
     <div id="pause" class="overlay dim hidden">
@@ -201,9 +201,10 @@
             <div class="helpgrid">
                 <div><b>W A S D</b> move, <b>Space</b> jump, <b>Shift</b> sneak, <b>Ctrl</b> or double tap <b>W</b> to sprint</div>
                 <div><b>Left mouse</b> mine a block, <b>Right mouse</b> place a block, use a workbench / furnace / chest, or eat</div>
-                <div><b>1 - 9</b> or the <b>mouse wheel</b> pick a hotbar slot</div>
+                <div><b>1 - 9</b> or the <b>mouse wheel</b> pick a hotbar slot, <b>Middle click</b> a block to take it in hand</div>
                 <div><b>E</b> inventory and 2 x 2 crafting, <b>Q</b> drop an item (Ctrl+Q the whole stack)</div>
                 <div><b>T</b> chat, <b>/</b> type a command such as <b>/give</b> or <b>/tp</b></div>
+                <div><b>Right click</b> a bed at night to sleep until morning, doors and gates to open them</div>
                 <div><b>Creative:</b> double tap <b>Space</b> to fly, Space / Shift to rise and sink</div>
                 <div><b>F3</b> debug info, <b>F1</b> hide the interface, <b>Esc</b> pause</div>
             </div>

+ 66 - 12
src/web/Blocky/js/blocks.js

@@ -18,15 +18,29 @@ export const B = {
     TALL_GRASS: 27, FLOWER_YELLOW: 28, FLOWER_RED: 29, MUSHROOM_BROWN: 30, MUSHROOM_RED: 31,
     CACTUS: 32, REEDS: 33, FARMLAND: 34, WHEAT: 35, DEAD_BUSH: 36, LADDER: 37,
     STONE_SLAB: 38, PLANK_SLAB: 39, COBBLE_SLAB: 40, SANDSTONE_SLAB: 41,
-    IRON_BLOCK: 42, GOLD_BLOCK: 43, CRYSTAL_BLOCK: 44, LAMP: 45, MOSSY_COBBLE: 46
+    IRON_BLOCK: 42, GOLD_BLOCK: 43, CRYSTAL_BLOCK: 44, LAMP: 45, MOSSY_COBBLE: 46,
+    FIRE: 47, LAVA: 48, OBSIDIAN: 49, DOOR: 50, FENCE: 51, FENCE_GATE: 52, BED: 53
 };
 
 export const I = {
     STICK: 256, COAL: 257, IRON_INGOT: 258, GOLD_INGOT: 259, CRYSTAL: 260, FLINT: 261,
     CLAY_BALL: 262, BRICK: 263, SEEDS: 264, WHEAT: 265, BREAD: 266, APPLE: 267,
-    BOWL: 268, STEW: 269, BUCKET: 270, WATER_BUCKET: 271
+    BOWL: 268, STEW: 269, BUCKET: 270, WATER_BUCKET: 271, FLINT_AND_STEEL: 272,
+    LAVA_BUCKET: 273, DOOR: 274, BED: 275
 };
 
+//Horizontal facings used by doors, gates and beds: 0 +x, 1 +z, 2 -x, 3 -z
+export const HDIR = [[1, 0], [0, 1], [-1, 0], [0, -1]];
+
+//Facing index the player looks along, from their yaw
+export function facingFromYaw(yaw) {
+    const lx = -Math.sin(yaw), lz = -Math.cos(yaw);
+    if (Math.abs(lx) > Math.abs(lz)) {
+        return lx > 0 ? 0 : 2;
+    }
+    return lz > 0 ? 1 : 3;
+}
+
 //Tool ids: 280 + material * 4 + kind (kinds: pickaxe, axe, shovel, hoe)
 export const TOOL_BASE = 280;
 export function toolId(matIndex, kindIndex) {
@@ -37,7 +51,7 @@ export const BLOCKS = [];
 export const ITEMS = [];
 
 const DEFAULTS = {
-    shape: "cube",      //cube, cross, crop, torch, slab, cactus, liquid, farmland, ladder, none
+    shape: "cube",      //cube, cross, crop, torch, slab, cactus, liquid, farmland, ladder, fire, door, fence, gate, bed, none
     solid: true,        //has collision
     opaque: true,       //full cube that hides neighbour faces
     lightOpacity: 15,
@@ -77,7 +91,7 @@ def(B.DIRT, "Dirt", { tex: "dirt", hardness: 0.5, tool: "shovel", sound: "gravel
 def(B.COBBLE, "Cobblestone", { tex: "cobblestone", hardness: 2, tool: "pickaxe", tier: 1 });
 def(B.MOSSY_COBBLE, "Mossy Cobblestone", { tex: "mossy", hardness: 2, tool: "pickaxe", tier: 1 });
 def(B.PLANKS, "Planks", { tex: "planks", hardness: 2, tool: "axe", sound: "wood" });
-def(B.SAPLING, "Sapling", Object.assign({}, NONSOLID_PLANT, { tex: "sapling" }));
+def(B.SAPLING, "Sapling", Object.assign({}, NONSOLID_PLANT, { tex: "sapling", replaceable: true }));
 def(B.BEDROCK, "Bedrock", { tex: "bedrock", hardness: -1, noItem: true });
 def(B.WATER, "Water", { tex: "water", shape: "liquid", solid: false, opaque: false, lightOpacity: 1, hardness: -1, replaceable: true, noItem: true, targetable: false, sound: "water" });
 def(B.SAND, "Sand", { tex: "sand", hardness: 0.5, tool: "shovel", sound: "sand", gravity: true });
@@ -111,10 +125,11 @@ def(B.FURNACE, "Furnace", { tex: { top: "furnace_top", bottom: "furnace_top", si
 def(B.FURNACE_LIT, "Lit Furnace", { tex: { top: "furnace_top", bottom: "furnace_top", side: "furnace_side", front: "furnace_front_lit" }, hardness: 3.5, tool: "pickaxe", tier: 1, orient: true, light: 13, noItem: true, interact: "furnace", drops: () => [[B.FURNACE, 1]] });
 def(B.CHEST, "Chest", { tex: { top: "chest_top", bottom: "chest_top", side: "chest_side", front: "chest_front" }, hardness: 2.5, tool: "axe", sound: "wood", orient: true, interact: "chest" });
 def(B.TALL_GRASS, "Tall Grass", Object.assign({}, NONSOLID_PLANT, { tex: "tall_grass", tint: "grass", replaceable: true, drops: (m, rng) => (rng() < 0.125 ? [[I.SEEDS, 1]] : []) }));
-def(B.FLOWER_YELLOW, "Yellow Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_yellow" }));
-def(B.FLOWER_RED, "Red Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_red" }));
-def(B.MUSHROOM_BROWN, "Brown Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_brown", support: "solid", light: 1 }));
-def(B.MUSHROOM_RED, "Red Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_red", support: "solid" }));
+//Short plants give way when a block is placed on them (they drop as items)
+def(B.FLOWER_YELLOW, "Yellow Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_yellow", replaceable: true }));
+def(B.FLOWER_RED, "Red Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_red", replaceable: true }));
+def(B.MUSHROOM_BROWN, "Brown Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_brown", support: "solid", light: 1, replaceable: true }));
+def(B.MUSHROOM_RED, "Red Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_red", support: "solid", replaceable: true }));
 def(B.CACTUS, "Cactus", { tex: { top: "cactus_top", bottom: "cactus_bottom", side: "cactus_side" }, shape: "cactus", opaque: false, lightOpacity: 0, hardness: 0.4, sound: "cloth", support: "cactus" });
 def(B.REEDS, "Reeds", Object.assign({}, NONSOLID_PLANT, { tex: "reeds", support: "reeds" }));
 def(B.FARMLAND, "Farmland", { tex: { top: "farmland_dry", bottom: "dirt", side: "dirt" }, shape: "farmland", opaque: false, lightOpacity: 0, hardness: 0.6, tool: "shovel", sound: "gravel", noItem: true, drops: () => [[B.DIRT, 1]] });
@@ -132,6 +147,13 @@ def(B.IRON_BLOCK, "Block of Iron", { tex: "iron_block", hardness: 5, tool: "pick
 def(B.GOLD_BLOCK, "Block of Gold", { tex: "gold_block", hardness: 3, tool: "pickaxe", tier: 3, sound: "metal" });
 def(B.CRYSTAL_BLOCK, "Block of Crystal", { tex: "crystal_block", hardness: 5, tool: "pickaxe", tier: 3, sound: "metal" });
 def(B.LAMP, "Lamp", { tex: "lamp", hardness: 0.3, light: 15, sound: "glass" });
+def(B.FIRE, "Fire", { tex: "fire", shape: "fire", solid: false, opaque: false, lightOpacity: 0, light: 15, hardness: 0, replaceable: true, noItem: true, sound: "fire", drops: () => [] });
+def(B.LAVA, "Lava", { tex: "lava", shape: "liquid", solid: false, opaque: false, lightOpacity: 15, light: 15, hardness: -1, replaceable: true, noItem: true, targetable: false, sound: "lava" });
+def(B.OBSIDIAN, "Obsidian", { tex: "obsidian", hardness: 35, tool: "pickaxe", tier: 4 });
+def(B.DOOR, "Door", { tex: "door_lower", shape: "door", opaque: false, lightOpacity: 0, hardness: 3, tool: "axe", sound: "wood", noItem: true, interact: "door", support: "door", drops: () => [[I.DOOR, 1]] });
+def(B.FENCE, "Fence", { tex: "planks", shape: "fence", opaque: false, lightOpacity: 0, hardness: 2, tool: "axe", sound: "wood" });
+def(B.FENCE_GATE, "Fence Gate", { tex: "planks", shape: "gate", opaque: false, lightOpacity: 0, hardness: 2, tool: "axe", sound: "wood", interact: "gate" });
+def(B.BED, "Bed", { tex: { top: "bed_foot_top", bottom: "planks", side: "bed_side" }, shape: "bed", opaque: false, lightOpacity: 0, hardness: 0.2, sound: "cloth", noItem: true, interact: "bed", drops: () => [[I.BED, 1]] });
 
 //Fill the gaps so every id lookup returns something sane
 for (let i = 0; i < 256; i++) {
@@ -156,7 +178,20 @@ for (let i = 0; i < 256; i++) {
     LIGHT_OPACITY[i] = b.lightOpacity;
     LIGHT_EMIT[i] = b.light;
     SHAPE[i] = b.shape;
-    RAIN_BLOCKING[i] = (b.solid || i === B.WATER || i === B.LEAVES) ? 1 : 0;
+    RAIN_BLOCKING[i] = (b.solid || i === B.WATER || i === B.LAVA || i === B.LEAVES) ? 1 : 0;
+}
+
+//Fire: how readily a block catches (spread) and burns away
+export const FLAME_CATCH = new Uint8Array(256);
+export const FLAME_BURN = new Uint8Array(256);
+for (const [id, c, b] of [
+    [B.PLANKS, 5, 20], [B.PLANK_SLAB, 5, 20], [B.LOG, 5, 5], [B.LEAVES, 30, 60], [B.WORKBENCH, 5, 20],
+    [B.CHEST, 5, 20], [B.FENCE, 5, 20], [B.FENCE_GATE, 5, 20], [B.DOOR, 5, 20], [B.BED, 5, 20],
+    [B.LADDER, 5, 20], [B.TALL_GRASS, 60, 100], [B.FLOWER_YELLOW, 60, 100], [B.FLOWER_RED, 60, 100],
+    [B.DEAD_BUSH, 60, 100], [B.SAPLING, 60, 100], [B.WHEAT, 60, 100]
+]) {
+    FLAME_CATCH[id] = c;
+    FLAME_BURN[id] = b;
 }
 
 //A slab with meta 2 is a double slab: a full opaque cube
@@ -198,6 +233,12 @@ export function blockFaceLayer(id, face, meta) {
     if (id === B.FARMLAND && face === 2) {
         return tileLayer.get(meta > 0 ? "farmland_wet" : "farmland_dry");
     }
+    if (id === B.DOOR) {
+        return tileLayer.get(meta & 8 ? "door_upper" : "door_lower");
+    }
+    if (id === B.BED && face === 2) {
+        return tileLayer.get(meta & 4 ? "bed_head_top" : "bed_foot_top");
+    }
     if (id === B.WORKBENCH) {
         return (face === 4 || face === 5) ? fl[6] : fl[face];
     }
@@ -220,7 +261,8 @@ const FLAT_BLOCK_ICONS = {
     [B.SAPLING]: "sapling", [B.TORCH]: "torch", [B.TALL_GRASS]: "tall_grass",
     [B.FLOWER_YELLOW]: "flower_yellow", [B.FLOWER_RED]: "flower_red",
     [B.MUSHROOM_BROWN]: "mushroom_brown", [B.MUSHROOM_RED]: "mushroom_red",
-    [B.REEDS]: "reeds", [B.DEAD_BUSH]: "dead_bush", [B.LADDER]: "ladder"
+    [B.REEDS]: "reeds", [B.DEAD_BUSH]: "dead_bush", [B.LADDER]: "ladder",
+    [B.FENCE]: "fence_item", [B.FENCE_GATE]: "gate_item"
 };
 
 for (let i = 1; i < 256; i++) {
@@ -251,6 +293,10 @@ item(I.BOWL, "Bowl", { icon: { flat: "bowl" }, fuel: 100 });
 item(I.STEW, "Mushroom Stew", { icon: { flat: "stew" }, stack: 1, food: { hunger: 6, sat: 7.2, leaves: I.BOWL } });
 item(I.BUCKET, "Bucket", { icon: { flat: "bucket" }, stack: 16 });
 item(I.WATER_BUCKET, "Water Bucket", { icon: { flat: "water_bucket" }, stack: 1 });
+item(I.LAVA_BUCKET, "Lava Bucket", { icon: { flat: "lava_bucket" }, stack: 1, fuel: 20000, fuelLeaves: I.BUCKET });
+item(I.FLINT_AND_STEEL, "Flint and Steel", { icon: { flat: "flint_and_steel" }, stack: 1, tool: { kind: "igniter", tier: 0, speed: 1, durability: 64 } });
+item(I.DOOR, "Door", { icon: { flat: "door_item" }, stack: 16, fuel: 200 });
+item(I.BED, "Bed", { icon: { flat: "bed_item" }, stack: 1 });
 
 //Fuel for blocks (ticks at 20 ticks per second; one smelt takes 200 ticks)
 ITEMS[B.LOG].fuel = 300;
@@ -260,6 +306,8 @@ ITEMS[B.SAPLING].fuel = 100;
 ITEMS[B.WORKBENCH].fuel = 300;
 ITEMS[B.CHEST].fuel = 300;
 ITEMS[B.LADDER].fuel = 300;
+ITEMS[B.FENCE].fuel = 300;
+ITEMS[B.FENCE_GATE].fuel = 300;
 ITEMS[B.REEDS].block = B.REEDS;
 
 export const TOOL_STATS = [
@@ -399,6 +447,7 @@ TOOL_STATS.forEach((st, mi) => {
     });
 });
 shaped(I.BUCKET, 1, ["I.I", ".I."], { I: I.IRON_INGOT }, "Tools");
+shapeless(I.FLINT_AND_STEEL, 1, [I.IRON_INGOT, I.FLINT], "Tools");
 
 shaped(I.BOWL, 4, ["P.P", ".P."], { P: B.PLANKS }, "Food");
 shaped(I.BREAD, 1, ["WWW"], { W: I.WHEAT }, "Food");
@@ -415,6 +464,10 @@ shaped(B.PLANK_SLAB, 6, ["MMM"], { M: B.PLANKS });
 shaped(B.COBBLE_SLAB, 6, ["MMM"], { M: B.COBBLE });
 shaped(B.SANDSTONE_SLAB, 6, ["MMM"], { M: B.SANDSTONE });
 shaped(B.LAMP, 1, [".G.", "GTG", ".G."], { G: B.GLASS, T: B.TORCH });
+shaped(I.DOOR, 3, ["PP", "PP", "PP"], { P: B.PLANKS });
+shaped(B.FENCE, 3, ["PSP", "PSP"], { P: B.PLANKS, S: I.STICK });
+shaped(B.FENCE_GATE, 1, ["SPS", "SPS"], { P: B.PLANKS, S: I.STICK });
+shaped(I.BED, 1, ["WWW", "PPP"], { W: I.WHEAT, P: B.PLANKS });
 for (const [block, ingot] of [[B.IRON_BLOCK, I.IRON_INGOT], [B.GOLD_BLOCK, I.GOLD_INGOT], [B.CRYSTAL_BLOCK, I.CRYSTAL]]) {
     shaped(block, 1, ["III", "III", "III"], { I: ingot });
     shapeless(ingot, 9, [block], "Basics");
@@ -515,7 +568,8 @@ export function creativeGroups() {
     const building = [B.STONE, B.COBBLE, B.MOSSY_COBBLE, B.STONE_BRICKS, B.BRICKS, B.DIRT, B.GRASS, B.SAND, B.SANDSTONE,
         B.GRAVEL, B.CLAY, B.LOG, B.PLANKS, B.LEAVES, B.GLASS, B.LAMP, B.STONE_SLAB, B.PLANK_SLAB,
         B.COBBLE_SLAB, B.SANDSTONE_SLAB, B.IRON_BLOCK, B.GOLD_BLOCK, B.CRYSTAL_BLOCK, B.COAL_ORE, B.IRON_ORE,
-        B.GOLD_ORE, B.CRYSTAL_ORE, B.LADDER, B.TORCH, B.WORKBENCH, B.FURNACE, B.CHEST];
+        B.GOLD_ORE, B.CRYSTAL_ORE, B.OBSIDIAN, B.LADDER, B.TORCH, B.WORKBENCH, B.FURNACE, B.CHEST,
+        B.FENCE, B.FENCE_GATE, I.DOOR, I.BED];
     const nature = [B.SAPLING, B.TALL_GRASS, B.FLOWER_YELLOW, B.FLOWER_RED, B.MUSHROOM_BROWN, B.MUSHROOM_RED,
         B.CACTUS, B.REEDS, B.DEAD_BUSH, I.SEEDS];
     const tools = [];
@@ -524,7 +578,7 @@ export function creativeGroups() {
             tools.push(toolId(mi, ki));
         }
     }
-    tools.push(I.BUCKET, I.WATER_BUCKET);
+    tools.push(I.BUCKET, I.WATER_BUCKET, I.LAVA_BUCKET, I.FLINT_AND_STEEL);
     const items = [I.STICK, I.COAL, I.IRON_INGOT, I.GOLD_INGOT, I.CRYSTAL, I.FLINT, I.CLAY_BALL, I.BRICK,
         I.WHEAT, I.BOWL, I.APPLE, I.BREAD, I.STEW];
     return [

+ 65 - 1
src/web/Blocky/js/commands.js

@@ -131,6 +131,36 @@ function surfaceY(game, x, z) {
     return w.gen.column(Math.floor(x), Math.floor(z)).h + 1;
 }
 
+const RULE_NAMES = {
+    randomtickspeed: "tickSpeed", tickspeed: "tickSpeed",
+    dofiretick: "fireSpread", firespread: "fireSpread"
+};
+
+//Show a world rule, or change it when a value is given
+function setRule(game, rule, value) {
+    const rules = game.world.rules;
+    if (rule === "tickSpeed") {
+        if (value === undefined) {
+            return `Tick speed is ${rules.tickSpeed} (default 3)`;
+        }
+        const v = Number(value);
+        if (!Number.isFinite(v) || v < 0 || v > 1000) {
+            fail("Tick speed must be a number from 0 to 1000");
+        }
+        rules.tickSpeed = v;
+        return `Tick speed set to ${v}` + (v > 3 ? ` - plants grow ${Math.round(v / 3 * 10) / 10}x faster` : "");
+    }
+    if (value === undefined) {
+        return `Fire spread is ${rules.fireSpread ? "on" : "off"}`;
+    }
+    const v = String(value).toLowerCase();
+    if (!["on", "off", "true", "false", "1", "0"].includes(v)) {
+        fail("Use on or off");
+    }
+    rules.fireSpread = v === "on" || v === "true" || v === "1";
+    return `Fire spread is now ${rules.fireSpread ? "on" : "off"}`;
+}
+
 /* ---------------- commands ---------------- */
 
 export const COMMANDS = {
@@ -369,6 +399,34 @@ export const COMMANDS = {
             return [`Spawn point set to ${Math.floor(p.x)}, ${Math.floor(p.y)}, ${Math.floor(p.z)}`];
         }
     },
+    tickspeed: {
+        usage: "/tickspeed [speed]",
+        desc: "How fast plants grow and random block updates happen (default 3, up to 1000)",
+        cheat: true,
+        run(game, args) {
+            return [setRule(game, "tickSpeed", args[0])];
+        }
+    },
+    firespread: {
+        usage: "/firespread [on|off]",
+        desc: "Let fire spread and burn blocks (off: fires stay put)",
+        cheat: true,
+        run(game, args) {
+            return [setRule(game, "fireSpread", args[0])];
+        }
+    },
+    gamerule: {
+        usage: "/gamerule <randomTickSpeed|doFireTick> [value]",
+        desc: "Read or change a world rule",
+        cheat: true,
+        run(game, args) {
+            const rule = RULE_NAMES[(args[0] || "").toLowerCase()];
+            if (!rule) {
+                fail("Rules: randomTickSpeed (number), doFireTick (true / false)");
+            }
+            return [setRule(game, rule, args[1])];
+        }
+    },
     seed: {
         usage: "/seed",
         desc: "Show the world seed",
@@ -428,12 +486,18 @@ export function complete(line) {
             pool = parts.length === 2 ? ["set", "add", "query"] : Object.keys(TIMES);
         } else if (cmd === "help") {
             pool = Object.keys(COMMANDS);
+        } else if (cmd === "firespread") {
+            pool = ["on", "off"];
+        } else if (cmd === "gamerule") {
+            pool = parts.length === 2 ? ["randomTickSpeed", "doFireTick"] : ["true", "false"];
+        } else if (cmd === "tickspeed") {
+            pool = ["3", "30", "300"];
         } else {
             pool = [...names().keys()];
         }
     }
     const lower = last.toLowerCase();
-    const options = pool.filter((o) => o.startsWith(lower)).sort();
+    const options = pool.filter((o) => o.toLowerCase().startsWith(lower)).sort();
     if (!options.length) {
         return { line, options: [] };
     }

+ 2 - 1
src/web/Blocky/js/entities.js

@@ -57,7 +57,8 @@ export class Entities {
         for (let i = this.items.length - 1; i >= 0; i--) {
             const e = this.items[i];
             e.age += dt;
-            if (e.age > DESPAWN) {
+            const here = world.getBlock(Math.floor(e.x), Math.floor(e.y), Math.floor(e.z));
+            if (e.age > DESPAWN || here === B.LAVA || here === B.FIRE) {
                 r.disposeItemMesh(e.mesh);
                 this.items.splice(i, 1);
                 continue;

+ 271 - 40
src/web/Blocky/js/game.js

@@ -10,7 +10,7 @@
 */
 
 import {
-    B, BLOCKS, ITEMS, I, SHAPE, SOLID, blockDrops, breakSeconds, blockFaceLayer
+    B, BLOCKS, ITEMS, I, SHAPE, SOLID, blockDrops, breakSeconds, blockFaceLayer, isOpaqueAt, HDIR, facingFromYaw
 } from "./blocks.js";
 import { World, WORLD_H } from "./world.js";
 import { BIOME, BIOME_NAMES } from "./worldgen.js";
@@ -31,6 +31,9 @@ const DEATH_TEXT = {
     cactus: "You were pricked to death by a cactus",
     lightning: "You were struck by lightning",
     suffocate: "You suffocated in a wall",
+    lava: "You tried to swim in lava",
+    fire: "You went up in flames",
+    burn: "You burned to death",
     command: "You ended it with a command",
     void: "You fell out of the world"
 };
@@ -87,7 +90,11 @@ export class Game {
         this.world = new World(meta.seed, {
             onDrop: (x, y, z, id, n, dmg) => this.entities.spawnItem(x, y, z, id, n, dmg || 0),
             onFalling: (x, y, z, id, meta2) => this.entities.spawnFalling(x, y, z, id, meta2),
-            onBlockBroken: (x, y, z, id) => this.blockParticles(x, y, z, id, 0, 10)
+            onBlockBroken: (x, y, z, id) => this.blockParticles(x, y, z, id, 0, 10),
+            onFizz: (x, y, z) => {
+                this.sound.play("fizz");
+                this.renderer.spawnParticles(x + 0.5, y + 1, z + 0.5, [200, 200, 200], 12, 0.4, 2);
+            }
         });
         this.renderer.attachWorld(this.world);
         this.entities = new Entities(this.renderer);
@@ -229,7 +236,9 @@ export class Game {
             if (this.placeOnGround && ready) {
                 this.dropToGround();
             }
-            if (ready && !this.placeOnGround) {
+            if (this.sleeping) {
+                this.updateSleep(dt);
+            } else if (ready && !this.placeOnGround) {
                 const mv = this.movementInput();
                 let rem = Math.min(dt, 0.1);
                 while (rem > 1e-4) {
@@ -271,6 +280,7 @@ export class Game {
             thunder: this.weather.thunder,
             flash: this.weather.flash,
             underwater: p.headInWater,
+            underlava: p.headInLava,
             renderDistance: R
         });
         this.world.skyDarken = Math.round((1 - env.day) * 11 + this.weather.rain * 2);
@@ -305,18 +315,19 @@ export class Game {
             sky: this.world.getSky(ex, ey, ez) / 15,
             blk: this.world.getBlockLight(ex, ey, ez) / 15
         });
-        r.render(dt, !this.hideHud && !p.dead);
+        r.render(dt, !this.hideHud && !p.dead && !this.sleeping);
 
         this.ui.updateHud(this);
         document.getElementById("underwater").classList.toggle("on", p.headInWater);
         document.getElementById("hurt").classList.toggle("on", p.hurtTime > 0.3);
+        document.getElementById("burning").classList.toggle("on", !this.creative && (p.burnTime > 0 || p.inLava));
         this.updateDebug();
         input.endFrame();
     }
 
     movementInput() {
         const k = (c) => this.input.down(c);
-        if (this.ui.isOpen() || this.player.dead || this.paused || this.app.chat.open) {
+        if (this.ui.isOpen() || this.player.dead || this.paused || this.app.chat.open || this.sleeping) {
             return { forward: 0, strafe: 0, jump: false, sneak: false, sprint: false };
         }
         const t = this.input.touchMove;
@@ -478,7 +489,7 @@ export class Game {
         const p = this.player, input = this.input, r = this.renderer;
         this.breakCooldown = Math.max(0, this.breakCooldown - dt);
         this.useCooldown = Math.max(0, this.useCooldown - dt);
-        const active = !this.ui.isOpen() && !p.dead && !this.paused && !this.app.chat.open && (input.locked || this.touchActive);
+        const active = !this.ui.isOpen() && !p.dead && !this.paused && !this.app.chat.open && !this.sleeping && (input.locked || this.touchActive);
         if (!active) {
             this.breaking = null;
             this.eatT = 0;
@@ -489,13 +500,16 @@ export class Game {
         }
         const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
         const reach = this.creative ? 5.5 : 4.5;
-        const hit = this.world.raycast(ox, oy, oz, dx, dy, dz, reach, selectionBox);
+        const hit = this.world.raycast(ox, oy, oz, dx, dy, dz, reach, (id, m, x, y, z) => selectionBox(id, m, this.world, x, y, z));
         this.hit = hit;
         r.setSelection(this.hideHud ? null : hit);
 
         const leftDown = input.buttons.has(0) || this.touchBreak;
         const rightDown = input.buttons.has(2);
         const rightClick = input.clicked.has(2) || this.touchUse;
+        if (input.clicked.has(1) && hit) {
+            this.pickBlock(hit);
+        }
         this.touchUse = false;
 
         //Mining
@@ -580,6 +594,38 @@ export class Game {
         }
     }
 
+    //Middle click: put the targeted block in hand. Creative fills the
+    //selected slot; survival swaps it in from the inventory if owned.
+    pickBlock(hit) {
+        const PICK = {
+            [B.DOOR]: I.DOOR, [B.BED]: I.BED, [B.FURNACE_LIT]: B.FURNACE, [B.WHEAT]: I.SEEDS, [B.FARMLAND]: B.DIRT
+        };
+        const id = PICK[hit.id] ?? hit.id;
+        if (!ITEMS[id]) {
+            return;
+        }
+        const inv = this.inventory;
+        const slots = inv.slots;
+        const hot = slots.findIndex((st, i) => i < 9 && st && st.id === id);
+        if (hot >= 0) {
+            inv.selected = hot;
+            return;
+        }
+        if (this.creative) {
+            slots[inv.selected] = { id, count: ITEMS[id].stack, dmg: 0 };
+        } else {
+            const at = slots.findIndex((st, i) => i >= 9 && st && st.id === id);
+            if (at < 0) {
+                return;
+            }
+            const cur = slots[inv.selected];
+            slots[inv.selected] = slots[at];
+            slots[at] = cur;
+        }
+        this.ui.hudKey = "";
+        this.sound.play("pop");
+    }
+
     blockParticles(x, y, z, id, meta, count, point) {
         const tex = this.app.tex;
         const layer = blockFaceLayer(id, 4, meta || 0);
@@ -618,40 +664,65 @@ export class Game {
         }
     }
 
-    useItem(hit) {
+    //Tall grass and other loose plants never get in the way: aim through
+    //them at the top of the block they grow on
+    throughPlant(hit) {
+        if (!hit || SHAPE[hit.id] !== "cross" || !BLOCKS[hit.id].replaceable) {
+            return hit;
+        }
+        const w = this.world, y = hit.y - 1;
+        const id = w.getBlock(hit.x, y, hit.z);
+        if (id === B.AIR) {
+            return hit;
+        }
+        return {
+            x: hit.x, y, z: hit.z, id, meta: w.getMeta(hit.x, y, hit.z), face: 2, t: hit.t, box: hit.box,
+            point: [hit.point[0], y + 1, hit.point[2]], throughPlant: true
+        };
+    }
+
+    useItem(rawHit) {
         const p = this.player, inv = this.inventory, w = this.world;
         const held = inv.held;
         const it = held && ITEMS[held.id];
-        if (hit && BLOCKS[hit.id].interact && !p.sneaking) {
-            this.interactBlock(hit);
+        if (rawHit && BLOCKS[rawHit.id].interact && !p.sneaking) {
+            this.interactBlock(rawHit);
             return;
         }
-        //Buckets look for water too
+        //An empty bucket scoops up a water or lava source
         if (held && held.id === I.BUCKET) {
             const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
-            const wh = w.raycast(ox, oy, oz, dx, dy, dz, 4.5, (bid, m) => (bid === B.WATER && m === 0 ? [0, 0, 0, 1, 0.875, 1] : selectionBox(bid, m)));
-            if (wh && wh.id === B.WATER && wh.meta === 0) {
+            const wh = w.raycast(ox, oy, oz, dx, dy, dz, 4.5, (bid, m, bx, by, bz) =>
+                ((bid === B.WATER || bid === B.LAVA) && m === 0 ? [0, 0, 0, 1, 0.875, 1] : selectionBox(bid, m, w, bx, by, bz)));
+            if (wh && (wh.id === B.WATER || wh.id === B.LAVA) && wh.meta === 0) {
+                const full = wh.id === B.WATER ? I.WATER_BUCKET : I.LAVA_BUCKET;
                 w.setBlock(wh.x, wh.y, wh.z, B.AIR, 0);
-                this.sound.play("splash");
+                this.sound.play(wh.id === B.WATER ? "splash" : "fizz");
                 this.swing = 0;
                 if (!this.creative) {
                     inv.consumeHeld(1);
                     if (inv.held) {
-                        if (inv.add(I.WATER_BUCKET, 1)) {
-                            this.dropStack({ id: I.WATER_BUCKET, count: 1 });
+                        if (inv.add(full, 1)) {
+                            this.dropStack({ id: full, count: 1 });
                         }
                     } else {
-                        inv.slots[inv.selected] = { id: I.WATER_BUCKET, count: 1, dmg: 0 };
+                        inv.slots[inv.selected] = { id: full, count: 1, dmg: 0 };
                     }
                 }
             }
             return;
         }
-        if (!hit || !held) {
+        if (!rawHit || !held) {
             return;
         }
+        const hit = this.throughPlant(rawHit);
         if (it.tool && it.tool.kind === "hoe") {
-            if ((hit.id === B.GRASS || hit.id === B.DIRT) && hit.face !== 3 && w.getBlock(hit.x, hit.y + 1, hit.z) === B.AIR) {
+            const above = w.getBlock(hit.x, hit.y + 1, hit.z);
+            const free = above === B.AIR || (SHAPE[above] === "cross" && BLOCKS[above].replaceable);
+            if ((hit.id === B.GRASS || hit.id === B.DIRT) && hit.face !== 3 && free) {
+                if (above !== B.AIR) {
+                    w.breakNaturally(hit.x, hit.y + 1, hit.z);
+                }
                 w.setBlock(hit.x, hit.y, hit.z, B.FARMLAND, 0);
                 this.sound.block("step", "gravel");
                 this.swing = 0;
@@ -661,16 +732,28 @@ export class Game {
             }
             return;
         }
-        if (held.id === I.WATER_BUCKET) {
-            const t = this.placeTarget(hit);
-            if (t && (w.getBlock(t[0], t[1], t[2]) === B.AIR || BLOCKS[w.getBlock(t[0], t[1], t[2])].replaceable)) {
-                const cur = w.getBlock(t[0], t[1], t[2]);
-                if (cur !== B.AIR && cur !== B.WATER) {
-                    w.breakNaturally(t[0], t[1], t[2]);
+        if (it.tool && it.tool.kind === "igniter") {
+            const [x, y, z] = this.placeTarget(hit);
+            if (w.ignite(x, y, z)) {
+                this.sound.play("fizz");
+                this.swing = 0;
+                if (!this.creative && inv.damageHeld(1)) {
+                    this.sound.play("toolBreak");
+                }
+            }
+            return;
+        }
+        if (held.id === I.WATER_BUCKET || held.id === I.LAVA_BUCKET) {
+            const liquid = held.id === I.WATER_BUCKET ? B.WATER : B.LAVA;
+            const [x, y, z] = this.placeTarget(hit);
+            const cur = w.getBlock(x, y, z);
+            if (y >= 0 && y < WORLD_H && (cur === B.AIR || BLOCKS[cur].replaceable)) {
+                if (cur !== B.AIR && cur !== B.WATER && cur !== B.LAVA) {
+                    w.breakNaturally(x, y, z);
                 }
-                w.setBlock(t[0], t[1], t[2], B.WATER, 0);
-                w.schedule(t[0], t[1], t[2], 5);
-                this.sound.play("splash");
+                w.setBlock(x, y, z, liquid, 0);
+                w.schedule(x, y, z, 5);
+                this.sound.play(liquid === B.WATER ? "splash" : "fizz");
                 this.swing = 0;
                 if (!this.creative) {
                     inv.slots[inv.selected] = { id: I.BUCKET, count: 1, dmg: 0 };
@@ -689,6 +772,14 @@ export class Game {
             }
             return;
         }
+        if (held.id === I.DOOR) {
+            this.placeDoor(hit);
+            return;
+        }
+        if (held.id === I.BED) {
+            this.placeBed(hit);
+            return;
+        }
         if (it.block) {
             this.placeBlock(hit, it.block);
         }
@@ -696,15 +787,37 @@ export class Game {
 
     placeTarget(hit) {
         const def = BLOCKS[hit.id];
-        if (def.replaceable && hit.id !== B.WATER) {
+        if (def.replaceable && hit.id !== B.WATER && hit.id !== B.LAVA) {
             return [hit.x, hit.y, hit.z];
         }
         const d = FACE_DIR[hit.face];
         return [hit.x + d[0], hit.y + d[1], hit.z + d[2]];
     }
 
+    //Would this block at (x, y, z) collide with the player?
+    blocksPlayer(bid, meta, x, y, z) {
+        if (!SOLID[bid]) {
+            return false;
+        }
+        const pb = this.player.box();
+        for (const b of collisionBoxes(bid, meta, this.world, x, y, z)) {
+            if (pb[0] < x + b[3] && pb[3] > x + b[0] && pb[1] < y + b[4] && pb[4] > y + b[1] && pb[2] < z + b[5] && pb[5] > z + b[2]) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    //Clear a replaceable block (a plant) so something can go there
+    clearSpot(x, y, z) {
+        const cur = this.world.getBlock(x, y, z);
+        if (cur !== B.AIR && cur !== B.WATER && cur !== B.LAVA) {
+            this.world.breakNaturally(x, y, z);
+        }
+    }
+
     placeBlock(hit, bid) {
-        const w = this.world, p = this.player, inv = this.inventory;
+        const w = this.world, p = this.player;
         const def = BLOCKS[bid];
         const face = hit.face;
         //Completing a slab into a double slab
@@ -740,6 +853,8 @@ export class Game {
                 return;
             }
             meta = face;
+        } else if (bid === B.FENCE_GATE) {
+            meta = facingFromYaw(p.yaw);
         } else if (def.orient) {
             const lx = -Math.sin(p.yaw), lz = -Math.cos(p.yaw);
             if (Math.abs(lx) > Math.abs(lz)) {
@@ -753,20 +868,60 @@ export class Game {
         if (def.support && !w.hasSupport(x, y, z, bid, meta)) {
             return;
         }
-        if (SOLID[bid]) {
-            const pb = p.box();
-            for (const b of collisionBoxes(bid, meta)) {
-                if (pb[0] < x + b[3] && pb[3] > x + b[0] && pb[1] < y + b[4] && pb[4] > y + b[1] && pb[2] < z + b[5] && pb[5] > z + b[2]) {
-                    return;
-                }
-            }
-        }
-        if (cur !== B.AIR && cur !== B.WATER) {
-            w.breakNaturally(x, y, z);
+        if (this.blocksPlayer(bid, meta, x, y, z)) {
+            return;
         }
+        this.clearSpot(x, y, z);
         this.finishPlace(x, y, z, bid, meta);
     }
 
+    //Doors are two blocks tall and hang on the edge nearest the player
+    placeDoor(hit) {
+        const w = this.world;
+        const [x, y, z] = this.placeTarget(hit);
+        if (y < 1 || y + 1 >= WORLD_H) {
+            return;
+        }
+        if (!BLOCKS[w.getBlock(x, y, z)].replaceable || !BLOCKS[w.getBlock(x, y + 1, z)].replaceable) {
+            return;
+        }
+        if (!isOpaqueAt(w.getBlock(x, y - 1, z), w.getMeta(x, y - 1, z))) {
+            return;
+        }
+        const f = (facingFromYaw(this.player.yaw) + 2) & 3;
+        if (this.blocksPlayer(B.DOOR, f, x, y, z) || this.blocksPlayer(B.DOOR, f | 8, x, y + 1, z)) {
+            return;
+        }
+        this.clearSpot(x, y, z);
+        this.clearSpot(x, y + 1, z);
+        w.setBlock(x, y, z, B.DOOR, f, false);
+        this.finishPlace(x, y + 1, z, B.DOOR, f | 8);
+    }
+
+    //Beds take two blocks: the foot where you click, the head further on
+    placeBed(hit) {
+        const w = this.world;
+        const [x, y, z] = this.placeTarget(hit);
+        const f = facingFromYaw(this.player.yaw);
+        const hx = x + HDIR[f][0], hz = z + HDIR[f][1];
+        if (y < 1 || y >= WORLD_H) {
+            return;
+        }
+        for (const [bx, bz] of [[x, z], [hx, hz]]) {
+            if (!BLOCKS[w.getBlock(bx, y, bz)].replaceable || !isOpaqueAt(w.getBlock(bx, y - 1, bz), w.getMeta(bx, y - 1, bz))) {
+                this.ui.toast("A bed needs two free blocks on solid ground");
+                return;
+            }
+            if (this.blocksPlayer(B.BED, 0, bx, y, bz)) {
+                return;
+            }
+        }
+        this.clearSpot(x, y, z);
+        this.clearSpot(hx, y, hz);
+        w.setBlock(hx, y, hz, B.BED, f | 4, false);
+        this.finishPlace(x, y, z, B.BED, f);
+    }
+
     finishPlace(x, y, z, bid, meta) {
         const w = this.world;
         if (!w.setBlock(x, y, z, bid, meta)) {
@@ -787,8 +942,22 @@ export class Game {
     interactBlock(hit) {
         const w = this.world;
         const kind = BLOCKS[hit.id].interact;
+        this.swing = 0;
         if (kind === "workbench") {
             this.openScreen("workbench");
+        } else if (kind === "door") {
+            const lowerY = hit.meta & 8 ? hit.y - 1 : hit.y;
+            for (const y of [lowerY, lowerY + 1]) {
+                if (w.getBlock(hit.x, y, hit.z) === B.DOOR) {
+                    w.setBlock(hit.x, y, hit.z, B.DOOR, w.getMeta(hit.x, y, hit.z) ^ 4, false);
+                }
+            }
+            this.sound.block("place", "wood");
+        } else if (kind === "gate") {
+            w.setBlock(hit.x, hit.y, hit.z, B.FENCE_GATE, hit.meta ^ 4, false);
+            this.sound.block("place", "wood");
+        } else if (kind === "bed") {
+            this.trySleep(hit);
         } else {
             let te = w.getTileEntity(hit.x, hit.y, hit.z);
             if (!te) {
@@ -798,6 +967,58 @@ export class Game {
         }
     }
 
+    /* ---------------- sleeping ---------------- */
+
+    trySleep(hit) {
+        const tod = this.ticks % DAY;
+        if (!(tod >= 12500 && tod <= 23500) && this.weather.state !== "thunder") {
+            this.ui.toast("You can only sleep at night or during a thunderstorm");
+            return;
+        }
+        const f = hit.meta & 3, d = HDIR[f];
+        const head = hit.meta & 4 ? [hit.x, hit.z] : [hit.x + d[0], hit.z + d[1]];
+        const foot = hit.meta & 4 ? [hit.x - d[0], hit.z - d[1]] : [hit.x, hit.z];
+        this.spawn = { x: foot[0] + 0.5, y: hit.y + 1, z: foot[1] + 0.5 };
+        this.sleeping = { t: 0, head, foot, y: hit.y, f };
+        this.breaking = null;
+        this.ui.toast("Respawn point set");
+        this.app.showSleep(true, 0);
+    }
+
+    updateSleep(dt) {
+        const s = this.sleeping;
+        s.t += dt;
+        for (const code of ["ShiftLeft", "ShiftRight", "Space", "KeyW", "KeyA", "KeyS", "KeyD"]) {
+            if (this.input.pressed.has(code)) {
+                this.wake(false);
+                return;
+            }
+        }
+        this.app.showSleep(true, Math.min(1, s.t / 2.2));
+        if (s.t >= 3) {
+            this.wake(true);
+        }
+    }
+
+    wake(skipNight) {
+        const s = this.sleeping;
+        if (!s) {
+            return;
+        }
+        this.sleeping = null;
+        if (skipNight) {
+            this.ticks = (Math.floor(this.ticks / DAY) + 1) * DAY + 500;
+            if (this.weather.state !== "clear") {
+                this.setWeather("clear");
+                this.weather.rain = 0;
+                this.weather.thunder = 0;
+            }
+            this.ui.toast("Good morning!");
+        }
+        this.player.setPos(s.foot[0] + 0.5, s.y + 0.5625, s.foot[1] + 0.5);
+        this.app.showSleep(false);
+    }
+
     /* ---------------- items ---------------- */
 
     dropHeld(whole) {
@@ -851,7 +1072,10 @@ export class Game {
             if (e.type === "hurt") {
                 this.sound.play("hurt");
             } else if (e.type === "death") {
+                this.wake(false);
                 this.onDeath(e.cause);
+            } else if (e.type === "extinguish") {
+                this.sound.play("fizz");
             } else if (e.type === "land" && e.fall > 1.2) {
                 const id = this.world.getBlock(Math.floor(p.x), Math.floor(p.y - 0.2), Math.floor(p.z));
                 this.sound.block("step", BLOCKS[id].sound);
@@ -915,6 +1139,13 @@ export class Game {
 
     updateCamera(dt) {
         const p = this.player, cam = this.renderer.camera;
+        if (this.sleeping) {
+            //Lying on the pillow, looking along the bed toward the foot
+            const s = this.sleeping, d = HDIR[s.f];
+            cam.position.set(s.head[0] + 0.5 - d[0] * 0.2, s.y + 0.75, s.head[1] + 0.5 - d[1] * 0.2);
+            cam.rotation.set(0.45, Math.atan2(d[0], d[1]), 0);
+            return;
+        }
         let bx = 0, by = 0, roll = 0;
         if (this.settings.viewBobbing && p.onGround && !p.flying) {
             const phase = p.walkDist * Math.PI * 0.75;

+ 22 - 13
src/web/Blocky/js/main.js

@@ -467,7 +467,9 @@ class App {
         if (this.touchMode) {
             show("touch");
         } else {
-            show("resume");
+            //Straight into the game: grab the mouse now if the browser still
+            //counts the Play click, otherwise the first click on the view does
+            this.input.lock();
         }
     }
 
@@ -491,7 +493,7 @@ class App {
         this.input.unlock();
         show("hud", false);
         show("touch", false);
-        show("resume", false);
+        this.showSleep(false);
         show("loading", false);
         show("menu");
         this.ui.close();
@@ -511,7 +513,14 @@ class App {
     /* ---------------- in-game overlays ---------------- */
 
     bindOverlays() {
-        $("resume").addEventListener("click", () => this.resumePlay());
+        //Clicking the game view captures the mouse again
+        this.canvas.addEventListener("mousedown", () => {
+            const g = this.game;
+            if (this.state === "playing" && g && !this.input.locked && !g.paused && !g.player.dead && !this.ui.isOpen() && !this.chat.open && !this.touchMode) {
+                this.input.lock();
+            }
+        });
+        $("btnLeaveBed").onclick = () => this.game && this.game.wake(false);
         $("btnResume").onclick = () => this.resumePlay();
         $("btnPauseSettings").onclick = () => this.openSettings();
         $("btnSaveQuit").onclick = () => this.quitToTitle();
@@ -581,7 +590,6 @@ class App {
             return;
         }
         if (locked) {
-            show("resume", false);
             return;
         }
         const g = this.game;
@@ -595,7 +603,6 @@ class App {
         g.paused = true;
         this.pausedAt = performance.now();
         this.input.active = true;
-        show("resume", false);
         this.refreshPause();
         show("pause");
         g.save(true);
@@ -635,15 +642,17 @@ class App {
         g.paused = false;
         this.input.active = true;
         this.input.reset();
-        if (this.touchMode) {
-            show("resume", false);
-            return;
+        if (!this.touchMode) {
+            //If the browser refuses (too soon after Esc), a click on the view retries
+            await this.input.lock();
         }
-        const ok = await this.input.lock();
-        if (!ok && !this.ui.isOpen() && this.game === g) {
-            show("resume");
-        } else {
-            show("resume", false);
+    }
+
+    //Darken the screen while the player sleeps (fade 0-1)
+    showSleep(on, fade = 0) {
+        show("sleep", on);
+        if (on) {
+            $("sleep").style.background = `rgba(4, 6, 16, ${0.25 + fade * 0.7})`;
         }
     }
 

+ 113 - 8
src/web/Blocky/js/mesher.js

@@ -15,9 +15,9 @@
     colour (tint x shade x occlusion) (3).
 */
 
-import { B, OPAQUE, SHAPE, BLOCKS, blockFaceLayer, layerOfTile, ITEMS } from "./blocks.js";
+import { B, OPAQUE, SHAPE, BLOCKS, blockFaceLayer, layerOfTile, ITEMS, HDIR } from "./blocks.js";
 import { WORLD_H } from "./worldgen.js";
-import { FACE_DIR } from "./shapes.js";
+import { FACE_DIR, doorBox, gateAlongZ, fenceLinks } from "./shapes.js";
 
 const P = 18;
 const P2 = P * P;
@@ -213,7 +213,7 @@ export function meshSection(world, chunk, sy, opts) {
                 if (shape === "cube" || (shape === "slab" && meta === 2)) {
                     cubeFaces(solidBuf, p, x, y, z, id, meta, fancy, tr, tg, tb, tint);
                 } else if (shape === "liquid") {
-                    liquidFaces(waterBuf, p, x, y, z, id, meta);
+                    liquidFaces(id === B.LAVA ? solidBuf : waterBuf, p, x, y, z, id, meta);
                 } else if (shape === "cross") {
                     crossPlant(solidBuf, p, x, y, z, id, meta, tr, tg, tb);
                 } else if (shape === "crop") {
@@ -256,6 +256,19 @@ export function meshSection(world, chunk, sy, opts) {
                     });
                 } else if (shape === "farmland") {
                     boxFaces(solidBuf, p, x, y, z, id, meta, 0, 0, 0, 1, 15 / 16, 1, (f, np) => f !== 2 && pOpq[np] === 1);
+                } else if (shape === "fire") {
+                    firePlanes(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "door") {
+                    const b = doorBox(meta);
+                    boxFaces(solidBuf, p, x, y, z, id, meta, b[0], b[1], b[2], b[3], b[4], b[5], (f, np) => (f === 2 || f === 3) && pOpq[np] === 1);
+                } else if (shape === "fence") {
+                    fence(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "gate") {
+                    for (const b of gateBoxes(meta)) {
+                        boxFaces(solidBuf, p, x, y, z, id, meta, b[0], b[1], b[2], b[3], b[4], b[5], (f, np) => f === 3 && b[1] === 0 && pOpq[np] === 1);
+                    }
+                } else if (shape === "bed") {
+                    bed(solidBuf, p, x, y, z, id, meta);
                 }
             }
         }
@@ -324,8 +337,19 @@ function cubeFaces(buf, p, x, y, z, id, meta, fancy, tr, tg, tb, tint) {
     }
 }
 
-//Axis aligned box with flat light; cull(f, neighbourPadded) skips faces
-function boxFaces(buf, p, x, y, z, id, meta, x0, y0, z0, x1, y1, z1, cull) {
+//Top face texture coordinates turned to a horizontal facing (0 +x, 1 +z, 2 -x, 3 -z)
+function topUV(facing, x, z) {
+    switch (facing) {
+        case 0: return [z, x];
+        case 1: return [1 - x, z];
+        case 2: return [1 - z, 1 - x];
+        default: return [x, 1 - z];
+    }
+}
+
+//Axis aligned box with flat light; cull(f, neighbourPadded) skips faces.
+//topFacing >= 0 turns the top texture to that facing (beds).
+function boxFaces(buf, p, x, y, z, id, meta, x0, y0, z0, x1, y1, z1, cull, topFacing = -1) {
     const mins = [x0, y0, z0], maxs = [x1, y1, z1];
     for (let f = 0; f < 6; f++) {
         const np = p + FACE_OFF[f];
@@ -340,13 +364,94 @@ function boxFaces(buf, p, x, y, z, id, meta, x0, y0, z0, x1, y1, z1, cull) {
         const s = FACE_SHADE[f];
         for (const c of FACE_VERTS[f]) {
             const vx = c[0] ? x1 : x0, vy = c[1] ? y1 : y0, vz = c[2] ? z1 : z0;
-            const uv = faceUV(f, vx, vy, vz);
+            const uv = f === 2 && topFacing >= 0 ? topUV(topFacing, vx, vz) : faceUV(f, vx, vy, vz);
             buf.vert(x + vx, y + vy, z + vz, uv[0], uv[1], layer, ls, lb, s, s, s);
         }
         buf.quad(false);
     }
 }
 
+const U = 1 / 16;
+
+//Bed half: a mattress on a frame, raised on two legs at its outer end, so a
+//whole bed stands on four legs
+function bed(buf, p, x, y, z, id, meta) {
+    const f = meta & 3;
+    boxFaces(buf, p, x, y, z, id, meta, 0, 3 * U, 0, 1, 9 * U, 1, () => false, f);
+    const d = HDIR[f];
+    const s = meta & 4 ? 1 : -1;
+    const ex = d[0] * s, ez = d[1] * s;
+    const near = [0, 3 * U], far = [13 * U, 1];
+    let legs;
+    if (ex !== 0) {
+        const xr = ex > 0 ? far : near;
+        legs = [[xr, near], [xr, far]];
+    } else {
+        const zr = ez > 0 ? far : near;
+        legs = [[near, zr], [far, zr]];
+    }
+    for (const [xr, zr] of legs) {
+        boxFaces(buf, p, x, y, z, id, meta, xr[0], 0, zr[0], xr[1], 3 * U, zr[1], (fc, np) => fc === 2 || (fc === 3 && pOpq[np] === 1));
+    }
+}
+
+//Fence: a post plus two rails toward every connected neighbour
+function fence(buf, p, x, y, z, id, meta) {
+    const getId = (a, b, c) => pBlk[pi(a, b, c)];
+    const getMeta = (a, b, c) => pMeta[pi(a, b, c)];
+    const links = fenceLinks(getId, getMeta, x, y, z);
+    boxFaces(buf, p, x, y, z, id, meta, 6 * U, 0, 6 * U, 10 * U, 1, 10 * U, (f, np) => (f === 2 || f === 3) && pOpq[np] === 1);
+    const arms = [
+        [10 * U, 7 * U, 1, 9 * U, 0], [0, 7 * U, 6 * U, 9 * U, 1],
+        [7 * U, 10 * U, 9 * U, 1, 4], [7 * U, 0, 9 * U, 6 * U, 5]
+    ];
+    arms.forEach(([a0, b0, a1, b1, endFace], k) => {
+        if (!links[k]) {
+            return;
+        }
+        for (const [r0, r1] of [[6 * U, 9 * U], [12 * U, 15 * U]]) {
+            boxFaces(buf, p, x, y, z, id, meta, a0, r0, b0, a1, r1, b1, (f) => f === endFace);
+        }
+    });
+}
+
+//Gate pieces in block units; built along z and swapped for gates along x
+function gateBoxes(meta) {
+    const open = (meta & 4) !== 0;
+    const parts = [[7, 5, 0, 9, 16, 2], [7, 5, 14, 9, 16, 16]];
+    if (!open) {
+        parts.push([7, 6, 2, 9, 9, 14], [7, 12, 2, 9, 15, 14], [7, 9, 7, 9, 12, 9]);
+    } else {
+        for (const [u0, u1] of [[0, 2], [14, 16]]) {
+            parts.push([9, 6, u0, 15, 9, u1], [9, 12, u0, 15, 15, u1], [13, 9, u0, 15, 12, u1]);
+        }
+    }
+    const alongZ = gateAlongZ(meta);
+    return parts.map(([w0, y0, u0, w1, y1, u1]) => (alongZ
+        ? [w0 * U, y0 * U, u0 * U, w1 * U, y1 * U, u1 * U]
+        : [u0 * U, y0 * U, w0 * U, u1 * U, y1 * U, w1 * U]));
+}
+
+//Fire: four double sided flame sheets, always fully bright
+function firePlanes(buf, p, x, y, z, id, meta) {
+    const ls = (pLight[p] >> 4) / 15;
+    const layer = blockFaceLayer(id, 4, meta);
+    for (const k of [0.2, 0.8]) {
+        buf.vert(x + k, y, z, 0, 0, layer, ls, 1, 1, 1, 1);
+        buf.vert(x + k, y, z + 1, 1, 0, layer, ls, 1, 1, 1, 1);
+        buf.vert(x + k, y + 1, z + 1, 1, 1, layer, ls, 1, 1, 1, 1);
+        buf.vert(x + k, y + 1, z, 0, 1, layer, ls, 1, 1, 1, 1);
+        buf.quad(false);
+        buf.backQuad();
+        buf.vert(x, y, z + k, 0, 0, layer, ls, 1, 1, 1, 1);
+        buf.vert(x + 1, y, z + k, 1, 0, layer, ls, 1, 1, 1, 1);
+        buf.vert(x + 1, y + 1, z + k, 1, 1, layer, ls, 1, 1, 1, 1);
+        buf.vert(x, y + 1, z + k, 0, 1, layer, ls, 1, 1, 1, 1);
+        buf.quad(false);
+        buf.backQuad();
+    }
+}
+
 function selfLight(p) {
     return [(pLight[p] >> 4) / 15, (pLight[p] & 15) / 15];
 }
@@ -448,13 +553,13 @@ export function waterHeight(meta, waterAbove) {
 }
 
 function liquidFaces(buf, p, x, y, z, id, meta) {
-    const above = pBlk[p + P2] === B.WATER;
+    const above = pBlk[p + P2] === id;
     const h = waterHeight(meta, above);
     const layer = blockFaceLayer(id, 2, meta);
     for (let f = 0; f < 6; f++) {
         const np = p + FACE_OFF[f];
         const nid = pBlk[np];
-        if (nid === B.WATER) {
+        if (nid === id) {
             continue;
         }
         if (f !== 2 && pOpq[np]) {

+ 1 - 1
src/web/Blocky/js/physics.js

@@ -29,7 +29,7 @@ export function gatherBoxes(world, minX, minY, minZ, maxX, maxY, maxZ, out) {
                     if (id === B.AIR) {
                         continue;
                     }
-                    boxes = collisionBoxes(id, world.getMeta(x, y, z));
+                    boxes = collisionBoxes(id, world.getMeta(x, y, z), world, x, y, z);
                 }
                 for (const b of boxes) {
                     out.push(x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]);

+ 60 - 7
src/web/Blocky/js/player.js

@@ -56,6 +56,9 @@ export class Player {
         this.starveTimer = 0;
         this.drownTimer = 0;
         this.cactusTimer = 0;
+        this.fireTimer = 0;
+        this.burnTime = 0;
+        this.burnTick = 0;
         this.hurtTime = 0;
         this.dead = false;
         this.events = [];
@@ -75,20 +78,22 @@ export class Player {
         this.fallDistance = 0;
     }
 
-    //Does the voxel at (x, y, z) contain the given world point under water?
-    waterAt(px, py, pz) {
+    //Is the given world point under the surface of a liquid (water or lava)?
+    waterAt(px, py, pz, liquid = B.WATER) {
         const w = this.world;
         const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);
-        if (w.getBlock(x, y, z) !== B.WATER) {
+        if (w.getBlock(x, y, z) !== liquid) {
             return false;
         }
-        const h = waterHeight(w.getMeta(x, y, z), w.getBlock(x, y + 1, z) === B.WATER);
+        const h = waterHeight(w.getMeta(x, y, z), w.getBlock(x, y + 1, z) === liquid);
         return py - y < h + 0.02;
     }
 
     sense() {
         const w = this.world;
-        this.inWater = this.waterAt(this.x, this.y + 0.25, this.z) || this.waterAt(this.x, this.y + 0.9, this.z);
+        this.inLava = this.waterAt(this.x, this.y + 0.25, this.z, B.LAVA) || this.waterAt(this.x, this.y + 0.9, this.z, B.LAVA);
+        this.headInLava = this.waterAt(this.x, this.eyeY, this.z, B.LAVA);
+        this.inWater = !this.inLava && (this.waterAt(this.x, this.y + 0.25, this.z) || this.waterAt(this.x, this.y + 0.9, this.z));
         this.headInWater = this.waterAt(this.x, this.eyeY, this.z);
         this.onLadder = false;
         const b = this.box();
@@ -132,6 +137,8 @@ export class Player {
         let speed;
         if (this.flying) {
             speed = this.sprinting ? 21.6 : 10.9;
+        } else if (this.inLava) {
+            speed = 1.1;
         } else if (this.inWater) {
             speed = this.sprinting ? 3.2 : 2.2;
         } else if (this.sneaking) {
@@ -142,7 +149,7 @@ export class Player {
         let accel;
         if (this.flying) {
             accel = 7;
-        } else if (this.inWater) {
+        } else if (this.inWater || this.inLava) {
             accel = 6;
         } else if (this.onGround) {
             accel = 16;
@@ -157,6 +164,17 @@ export class Player {
         if (this.flying) {
             const ty = (input.jump ? 8.5 : 0) - (input.sneak ? 8.5 : 0);
             this.vy += (ty - this.vy) * (1 - Math.exp(-10 * dt));
+        } else if (this.inLava) {
+            //Thick and slow: sinks gently, swims up weakly
+            this.vy -= 6 * dt;
+            this.vy *= Math.exp(-3.5 * dt);
+            if (input.jump) {
+                this.vy = Math.min(this.vy + 14 * dt, 1.8);
+                if (this.horizontalHit) {
+                    this.vy = 3.5;
+                }
+            }
+            this.vy = Math.max(this.vy, -1.8);
         } else if (this.inWater) {
             this.vy -= 10 * dt;
             this.vy *= Math.exp(-2.2 * dt);
@@ -239,6 +257,11 @@ export class Player {
             this.vz = 0;
         }
         this.horizontalHit = hitX || hitZ;
+        //Holding sneak while flying into the ground lands you
+        if (this.flying && this.onGround && input.sneak) {
+            this.flying = false;
+            this.vy = 0;
+        }
         const oldY = this.y;
         this.x = (box[0] + box[3]) / 2;
         this.y = box[1];
@@ -258,7 +281,7 @@ export class Player {
         }
 
         //Falling
-        if (this.flying || this.inWater || this.onLadder) {
+        if (this.flying || this.inWater || this.inLava || this.onLadder) {
             this.fallDistance = 0;
         } else if (this.y < oldY) {
             this.fallDistance += oldY - this.y;
@@ -387,6 +410,35 @@ export class Player {
             this.cactusTimer = 0.5;
             this.hurt(1, "cactus");
         }
+        //Fire and lava: damage while touching, then you keep burning a while
+        this.fireTimer = Math.max(0, this.fireTimer - dt);
+        if (this.inLava) {
+            this.burnTime = 8;
+            if (this.fireTimer === 0) {
+                this.fireTimer = 0.5;
+                this.hurt(4, "lava");
+            }
+        } else if (this.touching(B.FIRE)) {
+            this.burnTime = Math.max(this.burnTime, 4);
+            if (this.fireTimer === 0) {
+                this.fireTimer = 0.5;
+                this.hurt(1, "fire");
+            }
+        }
+        if (this.burnTime > 0) {
+            const rained = this.world.raining && this.world.rainTop(Math.floor(this.x), Math.floor(this.z)) <= this.y + 0.5;
+            if (this.inWater || rained) {
+                this.burnTime = 0;
+                this.events.push({ type: "extinguish" });
+            } else {
+                this.burnTime = Math.max(0, this.burnTime - dt);
+                this.burnTick += dt;
+                if (this.burnTick >= 1 && !this.inLava) {
+                    this.burnTick = 0;
+                    this.hurt(1, "burn");
+                }
+            }
+        }
         const hx = Math.floor(this.x), hy = Math.floor(this.eyeY), hz = Math.floor(this.z);
         if (this.world.isLoaded(hx, hz) && isOpaqueAt(this.world.getBlock(hx, hy, hz), this.world.getMeta(hx, hy, hz))) {
             this.suffocateTimer = (this.suffocateTimer || 0) + dt;
@@ -433,6 +485,7 @@ export class Player {
         this.air = 15;
         this.dead = false;
         this.hurtTime = 0;
+        this.burnTime = 0;
     }
 
     serialize() {

+ 15 - 3
src/web/Blocky/js/render.js

@@ -45,6 +45,8 @@ uniform float uFogNear;
 uniform float uFogFar;
 uniform float uTime;
 uniform float uWaterLayer;
+uniform float uLavaLayer;
+uniform float uFireLayer;
 uniform float uAlphaTest;
 uniform float uOpacity;
 uniform float uGammaK;
@@ -62,6 +64,10 @@ void main() {
     vec2 uv = vUv;
     if (abs(vLayer - uWaterLayer) < 0.5) {
         uv += vec2(sin(uTime * 0.7 + vUv.y * 3.0) * 0.03, uTime * 0.05);
+    } else if (abs(vLayer - uLavaLayer) < 0.5) {
+        uv += vec2(sin(uTime * 0.35 + vUv.y * 4.0) * 0.06, uTime * 0.025);
+    } else if (abs(vLayer - uFireLayer) < 0.5) {
+        uv.x += sin(uTime * 9.0 + vUv.y * 6.0) * 0.04 * vUv.y;
     }
     vec4 tex = texture(uTex, vec3(uv.x, 1.0 - uv.y, vLayer));
     if (tex.a < uAlphaTest) {
@@ -256,6 +262,8 @@ export class Renderer {
             uFogFar: { value: 100 },
             uTime: { value: 0 },
             uWaterLayer: { value: tex.layerOf.get("water") },
+            uLavaLayer: { value: tex.layerOf.get("lava") },
+            uFireLayer: { value: tex.layerOf.get("fire") },
             uGammaK: { value: 1.2 }
         };
         this.solidMat = this.terrainMaterial({ alphaTest: 0.5 });
@@ -741,8 +749,8 @@ export class Renderer {
         g.rotation.set(-s * 0.9 + pose.eat * 0.5, -s2 * 0.4 + pose.eat * 0.6, s * 0.2);
         if (this.handMesh) {
             if (this.handMesh.userData.cube) {
-                this.handMesh.scale.setScalar(0.32);
-                this.handMesh.position.set(0.06, 0.0, -0.02);
+                this.handMesh.scale.setScalar(0.24);
+                this.handMesh.position.set(0.1, -0.02, -0.04);
                 this.handMesh.rotation.set(0.1, Math.PI / 4, 0);
             } else {
                 //A flat item held upright, turned a little toward the view
@@ -953,7 +961,11 @@ export class Renderer {
         const towardSun = Math.max(0, look.x * Math.cos(ang)) * sunset;
         fog = [lerp(fog[0], 1.0, towardSun * 0.45), lerp(fog[1], 0.55, towardSun * 0.3), lerp(fog[2], 0.3, towardSun * 0.3)];
         const far = Math.max(24, env.renderDistance * 16 - 6);
-        if (env.underwater) {
+        if (env.underlava) {
+            this.shared.uFogColor.value.setRGB(0.75, 0.2, 0.02);
+            this.shared.uFogNear.value = 0.1;
+            this.shared.uFogFar.value = 2.5;
+        } else if (env.underwater) {
             const k = Math.max(0.15, daylight);
             this.shared.uFogColor.value.setRGB(0.06 * k, 0.17 * k, 0.4 * k);
             this.shared.uFogNear.value = 1;

+ 87 - 4
src/web/Blocky/js/shapes.js

@@ -2,10 +2,11 @@
     Blocky - shapes.js
 
     Collision and selection boxes of the non-cube block shapes, in block
-    local coordinates [x0, y0, z0, x1, y1, z1].
+    local coordinates [x0, y0, z0, x1, y1, z1]. Fences look at their
+    neighbours, so the box functions take the world and the position too.
 */
 
-import { B, SHAPE, SOLID } from "./blocks.js";
+import { B, SHAPE, SOLID, isOpaqueAt } from "./blocks.js";
 
 const FULL = [0, 0, 0, 1, 1, 1];
 const NONE = [];
@@ -15,7 +16,58 @@ export const FACE_DIR = [
     [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]
 ];
 
-export function collisionBoxes(id, meta) {
+const DOOR_T = 3 / 16;
+//Closed door panel along the edge the door faces (0 +x, 1 +z, 2 -x, 3 -z)
+const DOOR_PANEL = [
+    [1 - DOOR_T, 0, 0, 1, 1, 1],
+    [0, 0, 1 - DOOR_T, 1, 1, 1],
+    [0, 0, 0, DOOR_T, 1, 1],
+    [0, 0, 0, 1, 1, DOOR_T]
+];
+
+//Door meta: bits 0-1 facing, bit 2 open, bit 3 upper half
+export function doorBox(meta) {
+    const f = meta & 3;
+    return DOOR_PANEL[meta & 4 ? (f + 1) & 3 : f];
+}
+
+//Gate meta: bits 0-1 facing, bit 2 open. A gate facing x spans the z axis.
+export function gateAlongZ(meta) {
+    return (meta & 1) === 0;
+}
+
+//Which sides (+x, -x, +z, -z) a fence at (x, y, z) connects to
+export function fenceLinks(getId, getMeta, x, y, z) {
+    const link = (nx, nz) => {
+        const id = getId(nx, y, nz);
+        return id === B.FENCE || id === B.FENCE_GATE || isOpaqueAt(id, getMeta(nx, y, nz));
+    };
+    return [link(x + 1, z), link(x - 1, z), link(x, z + 1), link(x, z - 1)];
+}
+
+function fenceBoxes(world, x, y, z, top) {
+    const lo = 0.375, hi = 0.625;
+    const out = [[lo, 0, lo, hi, top, hi]];
+    if (!world) {
+        return out;
+    }
+    const l = fenceLinks((a, b, c) => world.getBlock(a, b, c), (a, b, c) => world.getMeta(a, b, c), x, y, z);
+    if (l[0]) {
+        out.push([hi, 0, lo, 1, top, hi]);
+    }
+    if (l[1]) {
+        out.push([0, 0, lo, lo, top, hi]);
+    }
+    if (l[2]) {
+        out.push([lo, 0, hi, hi, top, 1]);
+    }
+    if (l[3]) {
+        out.push([lo, 0, 0, hi, top, lo]);
+    }
+    return out;
+}
+
+export function collisionBoxes(id, meta, world, x, y, z) {
     if (!SOLID[id]) {
         return NONE;
     }
@@ -29,18 +81,31 @@ export function collisionBoxes(id, meta) {
             return [[0.0625, 0, 0.0625, 0.9375, 1, 0.9375]];
         case "farmland":
             return [[0, 0, 0, 1, 0.9375, 1]];
+        case "door":
+            return [doorBox(meta)];
+        case "fence":
+            return fenceBoxes(world, x, y, z, 1.5);
+        case "gate":
+            if (meta & 4) {
+                return NONE;
+            }
+            return [gateAlongZ(meta) ? [0.375, 0, 0, 0.625, 1.5, 1] : [0, 0, 0.375, 1, 1.5, 0.625]];
+        case "bed":
+            return [[0, 0, 0, 1, 0.5625, 1]];
         default:
             return [FULL];
     }
 }
 
-export function selectionBox(id, meta) {
+export function selectionBox(id, meta, world, x, y, z) {
     switch (SHAPE[id]) {
         case "none":
         case "liquid":
             return null;
         case "cross":
             return [0.15, 0, 0.15, 0.85, 0.8, 0.85];
+        case "fire":
+            return [0.05, 0, 0.05, 0.95, 0.85, 0.95];
         case "crop":
             return [0, 0, 0, 1, Math.min(1, 0.2 + meta * 0.1), 1];
         case "torch": {
@@ -74,6 +139,24 @@ export function selectionBox(id, meta) {
             return [0.0625, 0, 0.0625, 0.9375, 1, 0.9375];
         case "farmland":
             return [0, 0, 0, 1, 0.9375, 1];
+        case "door":
+            return doorBox(meta);
+        case "fence": {
+            //One box around the post and its arms
+            const boxes = fenceBoxes(world, x, y, z, 1);
+            const u = [1, 0, 1, 0, 1, 0];
+            for (const b of boxes) {
+                for (let i = 0; i < 3; i++) {
+                    u[i] = Math.min(u[i], b[i]);
+                    u[i + 3] = Math.max(u[i + 3], b[i + 3]);
+                }
+            }
+            return u;
+        }
+        case "gate":
+            return gateAlongZ(meta) ? [0.375, 0, 0, 0.625, 1, 1] : [0, 0, 0.375, 1, 1, 0.625];
+        case "bed":
+            return [0, 0, 0, 1, 0.5625, 1];
         default:
             return FULL;
     }

+ 232 - 1
src/web/Blocky/js/textures.js

@@ -665,10 +665,226 @@ function paintCrystalBlock(t) {
     t.border([60, 168, 166], 3);
 }
 
+function paintFire(t) {
+    t.clear();
+    //Tongues of flame rising from the bottom, hottest at the base
+    for (let x = 0; x < 16; x++) {
+        const h = 7 + Math.round(5 * Math.abs(Math.sin(x * 1.3 + 0.5)) + t.r() * 4);
+        for (let i = 0; i < h; i++) {
+            const y = 15 - i;
+            const k = i / h;
+            const c = k < 0.3 ? [255, 236, 150] : k < 0.65 ? [255, 168, 40] : [222, 70, 20];
+            if (k > 0.8 && t.r() < 0.4) {
+                continue;
+            }
+            t.set(x, y, t.vary(c, 12), k > 0.85 ? 200 : 255);
+        }
+    }
+}
+
+function paintLava(t) {
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            const a = Math.sin((x / 16) * Math.PI * 2) + Math.cos((y / 16) * Math.PI * 4 + x * 0.4);
+            const b = Math.sin(((x + y) / 16) * Math.PI * 2 * 2);
+            const v = a * 0.6 + b * 0.4;
+            let c;
+            if (v > 0.75) {
+                c = [255, 214, 90];
+            } else if (v > 0.1) {
+                c = [246, 128, 26];
+            } else if (v > -0.7) {
+                c = [214, 76, 14];
+            } else {
+                c = [150, 36, 8];
+            }
+            t.set(x, y, t.vary(c, 8));
+        }
+    }
+}
+
+function paintObsidian(t) {
+    t.fill([22, 17, 32], 5);
+    for (let k = 0; k < 18; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([58, 40, 88], 10));
+    }
+    for (let k = 0; k < 6; k++) {
+        t.set(t.ri(16), t.ri(16), [120, 96, 160]);
+    }
+}
+
+function paintDoor(t, upper) {
+    const wood = [168, 126, 72], dark = [104, 74, 40];
+    t.fill(wood, 6);
+    for (let y = 0; y < 16; y++) {
+        for (const x of [0, 15]) {
+            t.set(x, y, t.vary(dark, 4));
+        }
+        if (y % 4 === 0) {
+            t.set(7, y, t.vary(dark, 4));
+        }
+    }
+    if (upper) {
+        for (let x = 0; x < 16; x++) {
+            t.set(x, 0, t.vary(dark, 4));
+        }
+        //Four open window panes you can look through, in a wooden frame
+        for (let y = 3; y < 12; y++) {
+            for (let x = 3; x < 13; x++) {
+                const frame = x === 3 || x === 12 || y === 3 || y === 11 || x === 7 || x === 8 || y === 7;
+                if (frame) {
+                    t.set(x, y, t.vary(dark, 4));
+                } else {
+                    t.set(x, y, [0, 0, 0], 0);
+                }
+            }
+        }
+    } else {
+        for (let x = 0; x < 16; x++) {
+            t.set(x, 15, t.vary(dark, 4));
+        }
+        for (const [y0, y1] of [[2, 6], [9, 13]]) {
+            for (let y = y0; y <= y1; y++) {
+                for (let x = 3; x < 13; x++) {
+                    if (y === y0 || y === y1 || x === 3 || x === 12) {
+                        t.set(x, y, t.vary([140, 102, 56], 4));
+                    }
+                }
+            }
+        }
+        t.set(13, 1, [70, 70, 76]);
+        t.set(13, 2, [70, 70, 76]);
+    }
+}
+
+function paintBedTop(t, head) {
+    t.fill([186, 40, 40], 8);
+    for (let y = 0; y < 16; y++) {
+        for (const x of [0, 15]) {
+            t.set(x, y, t.vary([124, 90, 50], 5));
+        }
+    }
+    if (head) {
+        //Pillow at the head end (top rows of the tile)
+        for (let y = 1; y < 6; y++) {
+            for (let x = 2; x < 14; x++) {
+                t.set(x, y, t.vary(y === 5 ? [196, 196, 204] : [236, 236, 242], 5));
+            }
+        }
+        for (let x = 0; x < 16; x++) {
+            t.set(x, 0, t.vary([124, 90, 50], 5));
+        }
+    } else {
+        for (let x = 1; x < 15; x++) {
+            t.set(x, 2, t.vary([150, 26, 26], 5));
+            t.set(x, 15, t.vary([124, 90, 50], 5));
+        }
+    }
+}
+
+function paintBedSide(t) {
+    t.clear();
+    for (let x = 0; x < 16; x++) {
+        for (let y = 7; y < 16; y++) {
+            let c;
+            if (y < 11) {
+                c = [186, 40, 40];
+            } else if (y === 11) {
+                c = [232, 232, 236];
+            } else {
+                c = [124, 90, 50];
+            }
+            t.set(x, y, t.vary(c, 6));
+        }
+    }
+}
+
 /* ------------------------------------------------------------------ */
 /* Item tiles                                                          */
 /* ------------------------------------------------------------------ */
 
+function paintDoorItem(t) {
+    t.clear();
+    for (let y = 1; y < 15; y++) {
+        for (let x = 4; x < 12; x++) {
+            let c = [168, 126, 72];
+            if (x === 4 || x === 11 || y === 1 || y === 14 || y === 8) {
+                c = [104, 74, 40];
+            } else if (y < 7 && x > 5 && x < 10) {
+                c = [176, 214, 232];
+            }
+            t.set(x, y, c);
+        }
+    }
+    t.set(10, 9, [70, 70, 76]);
+    t.outline(0.7);
+}
+
+function paintBedItem(t) {
+    t.clear();
+    for (let x = 1; x < 15; x++) {
+        t.set(x, 8, x < 5 ? [236, 236, 242] : [196, 46, 46]);
+        t.set(x, 9, x < 5 ? [210, 210, 218] : [176, 36, 36]);
+        t.set(x, 10, [124, 90, 50]);
+        t.set(x, 11, [104, 74, 40]);
+    }
+    for (const x of [1, 2, 13, 14]) {
+        t.set(x, 12, [104, 74, 40]);
+    }
+    for (let y = 5; y < 10; y++) {
+        t.set(1, y, [124, 90, 50]);
+    }
+    t.outline(0.7);
+}
+
+function paintFenceItem(t, gate) {
+    t.clear();
+    const posts = gate ? [1, 14] : [3, 11];
+    for (const x of posts) {
+        for (let y = 2; y < 15; y++) {
+            t.set(x, y, [168, 126, 72]);
+            t.set(x + 1, y, [130, 96, 54]);
+        }
+    }
+    for (const y of [5, 10]) {
+        for (let x = posts[0] + 2; x < posts[1]; x++) {
+            t.set(x, y, [178, 136, 80]);
+            t.set(x, y + 1, [130, 96, 54]);
+        }
+    }
+    if (gate) {
+        for (let y = 5; y < 12; y++) {
+            t.set(7, y, [168, 126, 72]);
+            t.set(8, y, [130, 96, 54]);
+        }
+    }
+    t.outline(0.7);
+}
+
+function paintFlintAndSteel(t) {
+    t.clear();
+    //Steel striker: a thick C shape
+    for (let a = 0; a < 40; a++) {
+        const ang = Math.PI * 0.35 + (a / 40) * Math.PI * 1.3;
+        for (const r of [3.2, 4]) {
+            t.set(5.5 + Math.cos(ang) * r, 8 + Math.sin(ang) * r, r > 3.5 ? [150, 150, 158] : [204, 204, 212]);
+        }
+    }
+    //Flint shard
+    t.shape((x, y) => x > 9 && x < 15 && y > 4 + (x - 9) * 0.6 && y < 13 - (x - 9) * 0.3, (x, y) => (x < 12 ? [96, 96, 102] : [60, 60, 66]));
+    t.outline(0.65);
+}
+
+function paintLavaBucket(t) {
+    paintBucket(t, false);
+    for (let x = 3; x < 13; x++) {
+        t.set(x, 5, [255, 170, 40]);
+    }
+    for (let x = 4; x < 12; x++) {
+        t.set(x, 6, [226, 90, 20]);
+    }
+}
+
 //Coordinates along / across a handle running from bottom-left to top-right
 function handleFrame(x, y) {
     const ox = 2.5, oy = 13.5;
@@ -1053,7 +1269,22 @@ const PAINTERS = {
     bowl: (t) => paintBowl(t, false),
     stew: (t) => paintBowl(t, true),
     bucket: (t) => paintBucket(t, false),
-    water_bucket: (t) => paintBucket(t, true)
+    water_bucket: (t) => paintBucket(t, true),
+
+    fire: paintFire,
+    lava: paintLava,
+    obsidian: paintObsidian,
+    door_lower: (t) => paintDoor(t, false),
+    door_upper: (t) => paintDoor(t, true),
+    bed_head_top: (t) => paintBedTop(t, true),
+    bed_foot_top: (t) => paintBedTop(t, false),
+    bed_side: paintBedSide,
+    door_item: paintDoorItem,
+    bed_item: paintBedItem,
+    fence_item: (t) => paintFenceItem(t, false),
+    gate_item: (t) => paintFenceItem(t, true),
+    flint_and_steel: paintFlintAndSteel,
+    lava_bucket: paintLavaBucket
 };
 
 for (let s = 0; s < 8; s++) {

+ 18 - 4
src/web/Blocky/js/ui.js

@@ -217,7 +217,7 @@ export class UI {
         panel.addEventListener("contextmenu", (e) => e.preventDefault());
         panel.addEventListener("mouseover", (e) => {
             const el = e.target.closest(".slot, .recipe, .pal");
-            this.hover = el && el.classList.contains("slot") ? el.dataset.ref : null;
+            this.hover = !el ? null : el.classList.contains("slot") ? el.dataset.ref : el.classList.contains("pal") ? "pal:" + el.dataset.id : null;
             this.showTooltip(el);
         });
         panel.addEventListener("mouseleave", () => {
@@ -310,8 +310,15 @@ export class UI {
                 const groups = creativeGroups();
                 const tabs = groups.map((g, i) => `<button class="tab ${i === this.creativeTab ? "on" : ""}" data-tab="${i}">${g.name}</button>`).join("");
                 const pal = groups[this.creativeTab].ids.map((id) => `<div class="pal" data-id="${id}"><div class="ic" style="${iconCss(this.icons, id, 36)}"></div></div>`).join("");
-                html = `<div class="scr-col wide"><div class="tabs">${tabs}</div><div class="palette">${pal}</div>
-                    ${this.invSection("Inventory")}<div class="trashrow"><span>Drop an item on the bin to delete it</span>${this.slotHtml("trash", "trash")}</div></div>`;
+                let hot = "";
+                for (let i = 0; i < 9; i++) {
+                    hot += this.slotHtml("inv:" + i);
+                }
+                //Item grid and the hotbar only: the rest of the inventory has no use in creative
+                html = `<div class="scr-col creative"><div class="tabs">${tabs}</div>
+                    <div class="palette"><div class="palgrid">${pal}</div></div>
+                    <div class="creativehot"><div class="slots grid9">${hot}</div>${this.slotHtml("trash", "trash")}</div>
+                    <p class="hint">Click an item to pick up a stack, shift click to add it to the hotbar, or press 1-9 over it. Drop items on the bin to delete them.</p></div>`;
             } else if (s.kind === "furnace") {
                 html = `<div class="scr-col"><h3>Furnace</h3><div class="furnace">
                     <div class="fcol">${this.slotHtml("te:0")}<div class="flame"><i></i></div>${this.slotHtml("te:1")}</div>
@@ -746,7 +753,8 @@ export class UI {
 
     quickMove(ref) {
         const s = this.getStack(ref);
-        if (!s) {
+        //Creative only shows the hotbar, so there is nowhere to move things to
+        if (!s || this.screen.kind === "creative") {
             return;
         }
         const range = (p, a, b) => {
@@ -794,6 +802,12 @@ export class UI {
 
     hotkey(n) {
         const h = this.hover;
+        if (h && h.startsWith("pal:")) {
+            const id = Number(h.slice(4));
+            this.game.inventory.slots[n] = { id, count: maxStack(id), dmg: 0 };
+            this.after();
+            return true;
+        }
         if (!h || !(h.startsWith("inv:") || h.startsWith("te:") || h.startsWith("craft:"))) {
             return false;
         }

+ 289 - 41
src/web/Blocky/js/world.js

@@ -19,10 +19,10 @@
 
 import {
     B, BLOCKS, LIGHT_OPACITY, LIGHT_EMIT, SHAPE, SOLID, RAIN_BLOCKING, isOpaqueAt,
-    blockDrops, SMELTING, SMELT_TICKS, fuelTicks, ITEMS
+    blockDrops, SMELTING, SMELT_TICKS, fuelTicks, ITEMS, FLAME_CATCH, FLAME_BURN, HDIR
 } from "./blocks.js";
-import { TerrainGen, WORLD_H, SEA, idx } from "./worldgen.js";
-import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32 } from "./util.js";
+import { TerrainGen, WORLD_H, SEA, idx, BIOME } from "./worldgen.js";
+import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32, hash3 } from "./util.js";
 import { FACE_DIR } from "./shapes.js";
 
 export const SECTIONS = WORLD_H / 16;
@@ -31,7 +31,7 @@ const IS_SLAB = new Uint8Array(256);
 const WASHABLE = new Uint8Array(256);
 for (let i = 0; i < 256; i++) {
     IS_SLAB[i] = SHAPE[i] === "slab" ? 1 : 0;
-    WASHABLE[i] = (SHAPE[i] === "cross" || SHAPE[i] === "crop" || SHAPE[i] === "torch") && i !== B.REEDS ? 1 : 0;
+    WASHABLE[i] = (SHAPE[i] === "cross" || SHAPE[i] === "crop" || SHAPE[i] === "torch" || SHAPE[i] === "fire") && i !== B.REEDS ? 1 : 0;
 }
 
 function opacityOf(id, meta) {
@@ -44,6 +44,17 @@ function opacityOf(id, meta) {
 
 const DIRS = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
 
+//Liquid behaviour: ticks between updates, level lost per block, last level
+const LIQUID = {
+    [B.WATER]: { delay: 5, step: 1, max: 7, renew: true },
+    [B.LAVA]: { delay: 30, step: 2, max: 6, renew: false }
+};
+
+//A wheat stage takes this long on watered farmland at tick speed 3, so a
+//full grow (7 steps over 8 stages) is about 30 minutes; dry farmland halves it
+export const CROP_STAGE_SECONDS = 1800 / 7;
+export const DEFAULT_RULES = { tickSpeed: 3, fireSpread: true };
+
 export class Chunk {
     constructor(cx, cz) {
         this.cx = cx;
@@ -60,6 +71,7 @@ export class Chunk {
         this.lit = false;
         this.modified = false;
         this.dirty = new Uint8Array(SECTIONS).fill(1);
+        this.crops = new Set();
         this.meshes = null; //owned by the renderer
     }
 }
@@ -84,6 +96,10 @@ export class World {
         this.onDrop = opts.onDrop || null;
         this.onFalling = opts.onFalling || null;
         this.onBlockBroken = opts.onBlockBroken || null;
+        this.onFizz = opts.onFizz || null;
+        this.rules = Object.assign({}, DEFAULT_RULES);
+        this.cropProgress = new Map();
+        this.quiet = false;
     }
 
     /* ---------------- chunk access ---------------- */
@@ -202,6 +218,7 @@ export class World {
             }
             c.modified = true;
             this.saved.delete(c.key);
+            this.resumeChunk(c);
         } else {
             this.gen.generate(c);
         }
@@ -209,6 +226,19 @@ export class World {
         c.generated = true;
     }
 
+    //Pick up where a saved chunk left off: crops, fire and moving liquids
+    resumeChunk(c) {
+        const bx = c.cx * 16, bz = c.cz * 16;
+        for (let i = 0; i < c.blocks.length; i++) {
+            const id = c.blocks[i];
+            if (id === B.WHEAT) {
+                c.crops.add(i);
+            } else if (id === B.FIRE || ((id === B.WATER || id === B.LAVA) && c.meta[i] !== 0)) {
+                this.schedule(bx + (i >> 11), i & 127, bz + ((i >> 7) & 15), 5 + Math.floor(this.rng() * 30));
+            }
+        }
+    }
+
     computeHeightmaps(c) {
         for (let lz = 0; lz < 16; lz++) {
             for (let lx = 0; lx < 16; lx++) {
@@ -580,6 +610,19 @@ export class World {
         }
         this.markDirtyAround(x, y, z, c);
         if (oldId !== id) {
+            if (oldId === B.WHEAT) {
+                c.crops.delete(i);
+                this.cropProgress.delete(x + "," + y + "," + z);
+            }
+            if (id === B.WHEAT) {
+                c.crops.add(i);
+            }
+            if (id === B.FIRE) {
+                this.schedule(x, y, z, 30 + Math.floor(this.rng() * 10));
+            }
+            if ((oldId === B.DOOR || oldId === B.BED) && id !== oldId) {
+                this.removePartner(x, y, z, oldId, oldMeta);
+            }
             if ((oldId === B.LOG || oldId === B.LEAVES) && id !== B.LOG) {
                 this.scheduleLeafChecks(x, y, z);
             }
@@ -595,6 +638,23 @@ export class World {
         return true;
     }
 
+    //Doors and beds are two blocks; removing one half removes the other
+    partnerOf(x, y, z, id, meta) {
+        if (id === B.DOOR) {
+            return [x, y + (meta & 8 ? -1 : 1), z];
+        }
+        const d = HDIR[meta & 3];
+        const s = meta & 4 ? -1 : 1;
+        return [x + d[0] * s, y, z + d[1] * s];
+    }
+
+    removePartner(x, y, z, id, meta) {
+        const [px, py, pz] = this.partnerOf(x, y, z, id, meta);
+        if (this.getBlock(px, py, pz) === id) {
+            this.setBlock(px, py, pz, B.AIR, 0);
+        }
+    }
+
     setMeta(x, y, z, meta) {
         return this.setBlock(x, y, z, this.getBlock(x, y, z), meta, false);
     }
@@ -643,8 +703,8 @@ export class World {
             return;
         }
         const def = BLOCKS[id];
-        if (id === B.WATER) {
-            this.schedule(x, y, z, 5);
+        if (id === B.WATER || id === B.LAVA) {
+            this.schedule(x, y, z, LIQUID[id].delay);
         } else if (def.gravity) {
             if (this.canFallInto(this.getBlock(x, y - 1, z))) {
                 this.schedule(x, y, z, 2);
@@ -660,7 +720,7 @@ export class World {
     }
 
     canFallInto(id) {
-        return id === B.AIR || id === B.WATER || WASHABLE[id] === 1;
+        return id === B.AIR || id === B.WATER || id === B.LAVA || WASHABLE[id] === 1;
     }
 
     hasSupport(x, y, z, id, meta) {
@@ -704,9 +764,14 @@ export class World {
                 if (isOpaqueAt(aid, am)) {
                     return true;
                 }
-                //Torches also stand on top slabs
-                return BLOCKS[id].support === "torch" && meta === 2 && IS_SLAB[aid] === 1 && am === 1;
+                //Torches also stand on top slabs and fence posts
+                return BLOCKS[id].support === "torch" && meta === 2 && ((IS_SLAB[aid] === 1 && am === 1) || aid === B.FENCE);
             }
+            case "door":
+                if (meta & 8) {
+                    return below === B.DOOR && (belowMeta & 8) === 0;
+                }
+                return isOpaqueAt(below, belowMeta) && this.getBlock(x, y + 1, z) === B.DOOR;
             default:
                 return true;
         }
@@ -725,7 +790,7 @@ export class World {
     breakNaturally(x, y, z) {
         const id = this.getBlock(x, y, z);
         const meta = this.getMeta(x, y, z);
-        if (id === B.AIR || id === B.WATER) {
+        if (id === B.AIR || id === B.WATER || id === B.LAVA) {
             return;
         }
         const drops = blockDrops(id, meta, this.rng, 0);
@@ -783,8 +848,10 @@ export class World {
         const id = this.getBlock(x, y, z);
         const meta = this.getMeta(x, y, z);
         const def = BLOCKS[id];
-        if (id === B.WATER) {
-            this.waterTick(x, y, z, meta);
+        if (id === B.WATER || id === B.LAVA) {
+            this.liquidTick(x, y, z, meta, id);
+        } else if (id === B.FIRE) {
+            this.fireTick(x, y, z, meta);
         } else if (def.gravity) {
             if (this.canFallInto(this.getBlock(x, y - 1, z)) && y > 0) {
                 if (this.onFalling) {
@@ -803,24 +870,49 @@ export class World {
         }
     }
 
-    /* ---------------- water ---------------- */
+    /* ---------------- liquids ---------------- */
 
-    flowInto(x, y, z, level) {
+    flowInto(x, y, z, level, liquid) {
         const id = this.getBlock(x, y, z);
         if (WASHABLE[id] === 1) {
-            this.breakNaturally(x, y, z);
+            if (liquid === B.WATER) {
+                this.breakNaturally(x, y, z);
+            } else {
+                this.setBlock(x, y, z, B.AIR, 0, false);
+            }
         }
-        this.setBlock(x, y, z, B.WATER, level);
+        this.setBlock(x, y, z, liquid, level);
     }
 
     canFlow(id) {
         return id === B.AIR || WASHABLE[id] === 1;
     }
 
-    waterTick(x, y, z, m) {
+    //Lava next to water hardens: a source into obsidian, flowing lava into cobblestone
+    lavaMeetsWater(x, y, z, m) {
+        for (let d = 0; d < 18; d += 3) {
+            if (DIRS[d + 1] === -1) {
+                continue;
+            }
+            if (this.getBlock(x + DIRS[d], y + DIRS[d + 1], z + DIRS[d + 2]) === B.WATER) {
+                this.setBlock(x, y, z, m === 0 ? B.OBSIDIAN : B.COBBLE, 0);
+                if (this.onFizz) {
+                    this.onFizz(x, y, z);
+                }
+                return true;
+            }
+        }
+        return false;
+    }
+
+    liquidTick(x, y, z, m, id) {
+        const L = LIQUID[id];
+        if (id === B.LAVA && this.lavaMeetsWater(x, y, z, m)) {
+            return;
+        }
         if (m !== 0) {
             let newM;
-            if (this.getBlock(x, y + 1, z) === B.WATER) {
+            if (this.getBlock(x, y + 1, z) === id) {
                 newM = 8;
             } else {
                 let best = 99, sources = 0;
@@ -829,22 +921,22 @@ export class World {
                         continue;
                     }
                     const nx = x + DIRS[d], nz = z + DIRS[d + 2];
-                    if (this.getBlock(nx, y, nz) === B.WATER) {
+                    if (this.getBlock(nx, y, nz) === id) {
                         const nm = this.getMeta(nx, y, nz);
                         if (nm === 0) {
                             sources++;
                         }
                         const eff = nm === 8 ? 0 : nm;
-                        if (eff + 1 < best) {
-                            best = eff + 1;
+                        if (eff + L.step < best) {
+                            best = eff + L.step;
                         }
                     }
                 }
                 const below = this.getBlock(x, y - 1, z);
-                if (sources >= 2 && (isOpaqueAt(below, this.getMeta(x, y - 1, z)) || (below === B.WATER && this.getMeta(x, y - 1, z) === 0))) {
+                if (L.renew && sources >= 2 && (isOpaqueAt(below, this.getMeta(x, y - 1, z)) || (below === id && this.getMeta(x, y - 1, z) === 0))) {
                     newM = 0;
                 } else {
-                    newM = best <= 7 ? best : -1;
+                    newM = best <= L.max ? best : -1;
                 }
             }
             if (newM === -1) {
@@ -852,20 +944,20 @@ export class World {
                 return;
             }
             if (newM !== m) {
-                this.setBlock(x, y, z, B.WATER, newM);
+                this.setBlock(x, y, z, id, newM);
                 m = newM;
             }
         }
         const below = this.getBlock(x, y - 1, z);
         if (y > 0 && this.canFlow(below)) {
-            this.flowInto(x, y - 1, z, 8);
+            this.flowInto(x, y - 1, z, 8, id);
             return;
         }
-        if (below === B.WATER) {
+        if (below === id || below === B.WATER || below === B.LAVA) {
             return;
         }
-        const next = (m === 0 || m === 8) ? 1 : m + 1;
-        if (next > 7) {
+        const next = (m === 0 || m === 8) ? L.step : m + L.step;
+        if (next > L.max) {
             return;
         }
         for (let d = 0; d < 18; d += 3) {
@@ -878,11 +970,153 @@ export class World {
             }
             const nid = this.getBlock(nx, y, nz);
             if (this.canFlow(nid)) {
-                this.flowInto(nx, y, nz, next);
-            } else if (nid === B.WATER) {
+                this.flowInto(nx, y, nz, next, id);
+            } else if (nid === id) {
                 const nm = this.getMeta(nx, y, nz);
                 if (nm !== 0 && nm !== 8 && nm > next) {
-                    this.setBlock(nx, y, nz, B.WATER, next);
+                    this.setBlock(nx, y, nz, id, next);
+                }
+            }
+        }
+    }
+
+    /* ---------------- fire ---------------- */
+
+    //Highest catch chance of the blocks around a position
+    flammableAround(x, y, z) {
+        let best = 0;
+        for (let d = 0; d < 18; d += 3) {
+            const c = FLAME_CATCH[this.getBlock(x + DIRS[d], y + DIRS[d + 1], z + DIRS[d + 2])];
+            if (c > best) {
+                best = c;
+            }
+        }
+        return best;
+    }
+
+    canFireStay(x, y, z) {
+        return isOpaqueAt(this.getBlock(x, y - 1, z), this.getMeta(x, y - 1, z)) || this.flammableAround(x, y, z) > 0;
+    }
+
+    //Light a fire if the spot is free and something can hold it
+    ignite(x, y, z) {
+        const cur = this.getBlock(x, y, z);
+        if ((cur !== B.AIR && WASHABLE[cur] !== 1) || !this.canFireStay(x, y, z)) {
+            return false;
+        }
+        this.setBlock(x, y, z, B.FIRE, 0);
+        return true;
+    }
+
+    fireTick(x, y, z, age) {
+        if (!this.rules.fireSpread) {
+            //Spreading is off: fires keep burning but touch nothing
+            this.schedule(x, y, z, 40);
+            return;
+        }
+        const rng = this.rng;
+        this.schedule(x, y, z, 30 + Math.floor(rng() * 10));
+        if (this.raining && this.rainTop(x, z) <= y + 1 && this.biomeAt(x, z) !== BIOME.DESERT && rng() < 0.6) {
+            this.setBlock(x, y, z, B.AIR, 0);
+            return;
+        }
+        const fuel = this.flammableAround(x, y, z);
+        const belowId = this.getBlock(x, y - 1, z);
+        if (!fuel && !isOpaqueAt(belowId, this.getMeta(x, y - 1, z))) {
+            this.setBlock(x, y, z, B.AIR, 0);
+            return;
+        }
+        const nextAge = Math.min(15, age + Math.floor(rng() * 3));
+        if (nextAge !== age) {
+            this.setBlock(x, y, z, B.FIRE, nextAge, false);
+        }
+        if (!fuel && nextAge > 3) {
+            this.setBlock(x, y, z, B.AIR, 0);
+            return;
+        }
+        if (nextAge >= 15 && !FLAME_BURN[belowId] && rng() < 0.25) {
+            this.setBlock(x, y, z, B.AIR, 0);
+            return;
+        }
+        //Burn the blocks it touches
+        for (let d = 0; d < 18; d += 3) {
+            const nx = x + DIRS[d], ny = y + DIRS[d + 1], nz = z + DIRS[d + 2];
+            const nid = this.getBlock(nx, ny, nz);
+            const burn = FLAME_BURN[nid];
+            if (burn && rng() * (DIRS[d + 1] === 0 ? 300 : 250) < burn) {
+                if (rng() < 0.55 && nextAge < 15) {
+                    this.setBlock(nx, ny, nz, B.FIRE, Math.min(15, nextAge + Math.floor(rng() * 5)));
+                } else {
+                    this.setBlock(nx, ny, nz, B.AIR, 0);
+                }
+            }
+        }
+        //Jump to air next to something that burns
+        for (let dx = -1; dx <= 1; dx++) {
+            for (let dz = -1; dz <= 1; dz++) {
+                for (let dy = -1; dy <= 3; dy++) {
+                    if (!dx && !dy && !dz) {
+                        continue;
+                    }
+                    const tx = x + dx, ty = y + dy, tz = z + dz;
+                    if (ty < 1 || ty >= WORLD_H || this.getBlock(tx, ty, tz) !== B.AIR) {
+                        continue;
+                    }
+                    const enc = this.flammableAround(tx, ty, tz);
+                    if (!enc) {
+                        continue;
+                    }
+                    const k = dy > 1 ? 100 + (dy - 1) * 100 : 100;
+                    if (rng() * k < enc * 0.35) {
+                        this.setBlock(tx, ty, tz, B.FIRE, Math.min(15, nextAge + Math.floor(rng() * 5)));
+                    }
+                }
+            }
+        }
+    }
+
+    /* ---------------- crops ---------------- */
+
+    //Runs once a second: wheat climbs one stage per CROP_STAGE_SECONDS
+    cropTick() {
+        const speed = this.rules.tickSpeed / 3;
+        if (speed <= 0) {
+            return;
+        }
+        for (const c of this.chunks.values()) {
+            if (!c.crops.size || !c.lit) {
+                continue;
+            }
+            for (const i of c.crops) {
+                let meta = c.meta[i];
+                if (meta >= 7) {
+                    continue;
+                }
+                const x = c.cx * 16 + (i >> 11), y = i & 127, z = c.cz * 16 + ((i >> 7) & 15);
+                //Crops grow day and night as long as they are open to the sky or lit
+                if (Math.max(c.light[i] >> 4, c.light[i] & 15) < 9) {
+                    continue;
+                }
+                const key = x + "," + y + "," + z;
+                const wet = this.getMeta(x, y - 1, z) > 0;
+                let prog = (this.cropProgress.get(key) || 0) + (wet ? 1 : 0.5) * speed;
+                let grew = false;
+                for (;;) {
+                    const need = CROP_STAGE_SECONDS * (0.85 + 0.3 * ((hash3(this.seed, x, y * 8 + meta, z) & 255) / 255));
+                    if (prog < need || meta >= 7) {
+                        break;
+                    }
+                    prog -= need;
+                    meta++;
+                    grew = true;
+                }
+                if (grew) {
+                    this.setBlock(x, y, z, B.WHEAT, meta, false);
+                }
+                if (meta >= 7) {
+                    this.cropProgress.delete(key);
+                } else {
+                    this.cropProgress.set(key, prog);
                 }
             }
         }
@@ -945,12 +1179,15 @@ export class World {
             if (!c.lit || Math.abs(c.cx - pcx) > radius || Math.abs(c.cz - pcz) > radius) {
                 continue;
             }
+            const speed = this.rules.tickSpeed;
             for (let s = 0; s < SECTIONS; s++) {
-                for (let k = 0; k < 3; k++) {
+                //Whole picks, plus one more with the fractional chance
+                const picks = Math.floor(speed) + (rng() < speed % 1 ? 1 : 0);
+                for (let k = 0; k < picks; k++) {
                     const r = (rng() * 4096) | 0;
                     const lx = r & 15, lz = (r >> 4) & 15, y = s * 16 + (r >> 8);
                     const id = c.blocks[(lx << 11) | (lz << 7) | y];
-                    if (id === B.GRASS || id === B.SAPLING || id === B.WHEAT || id === B.FARMLAND || id === B.REEDS || id === B.CACTUS) {
+                    if (id === B.GRASS || id === B.SAPLING || id === B.FARMLAND || id === B.REEDS || id === B.CACTUS || id === B.LAVA) {
                         this.randomTick(c.cx * 16 + lx, y, c.cz * 16 + lz, id);
                     }
                 }
@@ -974,11 +1211,12 @@ export class World {
             if (this.effectiveLight(x, y, z) >= 9 && rng() < 0.07) {
                 this.growTree(x, y, z);
             }
-        } else if (id === B.WHEAT) {
-            if (meta < 7 && this.effectiveLight(x, y, z) >= 9) {
-                const wet = this.getMeta(x, y - 1, z) > 0;
-                if (rng() < (wet ? 0.3 : 0.12)) {
-                    this.setBlock(x, y, z, B.WHEAT, meta + 1, false);
+        } else if (id === B.LAVA) {
+            //Lava sets nearby burnable things alight
+            if (this.rules.fireSpread && rng() < 0.3) {
+                const tx = x + Math.floor(rng() * 3) - 1, ty = y + 1 + Math.floor(rng() * 2), tz = z + Math.floor(rng() * 3) - 1;
+                if (this.getBlock(tx, ty, tz) === B.AIR && this.flammableAround(tx, ty, tz) > 0) {
+                    this.setBlock(tx, ty, tz, B.FIRE, 0);
                 }
             }
         } else if (id === B.FARMLAND) {
@@ -1121,9 +1359,10 @@ export class World {
             }
             if (te.burn === 0 && canSmelt && fuel && fuelTicks(fuel.id) > 0) {
                 te.burn = te.burnMax = fuelTicks(fuel.id);
+                const leaves = ITEMS[fuel.id].fuelLeaves;
                 fuel.count--;
                 if (fuel.count <= 0) {
-                    te.slots[1] = null;
+                    te.slots[1] = leaves ? { id: leaves, count: 1 } : null;
                 }
             }
             if (te.burn > 0 && canSmelt) {
@@ -1158,6 +1397,9 @@ export class World {
     tick(pcx, pcz) {
         this.tickCount++;
         this.runScheduled();
+        if (this.tickCount % 20 === 0) {
+            this.cropTick();
+        }
         this.randomTicks(pcx, pcz, 6);
         this.tickFurnaces();
     }
@@ -1177,7 +1419,7 @@ export class World {
         for (let guard = 0; guard < 64; guard++) {
             const id = this.getBlock(x, y, z);
             if (id !== B.AIR && y >= 0 && y < WORLD_H) {
-                const box = boxes(id, this.getMeta(x, y, z));
+                const box = boxes(id, this.getMeta(x, y, z), x, y, z);
                 if (box) {
                     const hit = rayBox(ox - x, oy - y, oz - z, dx, dy, dz, box);
                     if (hit && hit.t <= maxDist) {
@@ -1225,7 +1467,11 @@ export class World {
         for (const [k, v] of this.tileEntities) {
             tileEntities[k] = v;
         }
-        return { chunks, tileEntities };
+        const crops = {};
+        for (const [k, v] of this.cropProgress) {
+            crops[k] = Math.round(v);
+        }
+        return { chunks, tileEntities, rules: Object.assign({}, this.rules), crops };
     }
 
     load(data) {
@@ -1236,6 +1482,8 @@ export class World {
                 this.saved.set(chunkKey(cx, cz), data.chunks[name]);
             }
         }
+        this.rules = Object.assign({}, DEFAULT_RULES, (data && data.rules) || {});
+        this.cropProgress = new Map(Object.entries((data && data.crops) || {}));
         this.tileEntities.clear();
         if (data && data.tileEntities) {
             for (const k of Object.keys(data.tileEntities)) {

+ 6 - 1
src/web/Blocky/js/worldgen.js

@@ -8,6 +8,7 @@
     fall inside itself.
 
     Biomes: ocean, grassland, desert, forest (plus sandy beaches along water).
+    Caves below y = 11 are filled with lava, and some stone hides lava pockets.
 */
 
 import { Noise } from "./noise.js";
@@ -179,7 +180,8 @@ export class TerrainGen {
                                 const b = sample(caveB, lx, y, lz);
                                 const t = y < 28 ? 0.085 : 0.065;
                                 if (Math.abs(a) < t && Math.abs(b) < t * 1.4) {
-                                    id = B.AIR;
+                                    //The deepest caves are flooded with lava
+                                    id = y <= 10 ? B.LAVA : B.AIR;
                                 }
                             }
                         }
@@ -220,6 +222,9 @@ export class TerrainGen {
         vein(B.IRON_ORE, 12, 7, 5, 64, B.STONE);
         vein(B.GOLD_ORE, 2, 7, 5, 32, B.STONE);
         vein(B.CRYSTAL_ORE, 1, 5, 5, 17, B.STONE);
+        if (rng() < 0.3) {
+            vein(B.LAVA, 1, 14, 6, 40, B.STONE);
+        }
 
         this.placeTrees(chunk, cols);
         this.placePlants(chunk, cols, rng);