Explorar o código

Optimize game mechanism

Toby Chui hai 3 semanas
pai
achega
d8ae4186a9

+ 75 - 3
src/web/Blocky/README.md

@@ -24,6 +24,7 @@ its folder.
 | `js/power.js` | Spark circuits: power sources, wire levels, torches, lamps, pistons, rail shapes. |
 | `js/power.js` | Spark circuits: power sources, wire levels, torches, lamps, pistons, rail shapes. |
 | `js/carts.js` | Minecarts (plain, chest, furnace) following rails. |
 | `js/carts.js` | Minecarts (plain, chest, furnace) following rails. |
 | `js/boats.js` | Boats: floating, rowing, steering, riding. |
 | `js/boats.js` | Boats: floating, rowing, steering, riding. |
+| `js/machines.js` | Feeders (moving items between containers, carts and the ground) and dispensers. |
 | `js/dynlight.js` | Light from a glowing item held in hand. |
 | `js/dynlight.js` | Light from a glowing item held in hand. |
 | `js/signs.js` | The text on signs: canvas planes in front of the boards. |
 | `js/signs.js` | The text on signs: canvas planes in front of the boards. |
 | `js/blocks.js` | Block / item registry, mining rules, shaped recipes and the grid matcher, smelting. |
 | `js/blocks.js` | Block / item registry, mining rules, shaped recipes and the grid matcher, smelting. |
@@ -275,7 +276,11 @@ gets a 5 blocks/s shove. Parts react
 through scheduled ticks two game ticks later. `POWER` flags each block: 1
 through scheduled ticks two game ticks later. `POWER` flags each block: 1
 wire, 2 source, 4 reacts, 8 rail. Lever and button meta is the face they are
 wire, 2 source, 4 reacts, 8 rail. Lever and button meta is the face they are
 attached to plus bit 8 for on / pressed; a pressed button's release time is
 attached to plus bit 8 for on / pressed; a pressed button's release time is
-kept in `world.buttonDue`, so other updates cannot let it go early.
+kept in `world.buttonDue`, so other updates cannot let it go early. A
+lever on a wall always swings up and down, up when off and down when on
+(`lever` in mesher.js leans the handle along the model axis that the
+wall's turn maps to world y). A wall button is always 6 px wide and 4 px
+tall (`buttonBox` in shapes.js swaps its x and z on walls facing x).
 
 
 Pressure plates (two planks or two stone in a row) lie on a solid block,
 Pressure plates (two planks or two stone in a row) lie on a solid block,
 or on the same flat tops a torch stands on (top slab, upside down stairs,
 or on the same flat tops a torch stands on (top slab, upside down stairs,
@@ -342,7 +347,8 @@ first branch when powered and straightens again after. Meta bit 16 marks a
 switched rail, bit 32 one that was straight before; the shape stays in
 switched rail, bit 32 one that was straight before; the shape stays in
 bits 0-3, which everything else reads with `& 15`. Powered rails
 bits 0-3, which everything else reads with `& 15`. Powered rails
 (on a powered block or next to a source; power runs along up to 8 connected
 (on a powered block or next to a source; power runs along up to 8 connected
-powered rails) speed carts up. Unpowered ones are brakes. How far a cart
+powered rails, up and down slopes too: `railChainPowered` follows each
+rail's height) speed carts up. Unpowered ones are brakes. How far a cart
 rolls depends on its load (`Carts.loadOf`, `LOAD_*` in `carts.js`): reaching
 rolls depends on its load (`Carts.loadOf`, `LOAD_*` in `carts.js`): reaching
 full speed (8) it cruises for a while, then slows at a steady rate; brakes
 full speed (8) it cruises for a while, then slows at a steady rate; brakes
 are a much stronger steady deceleration that also holds it on a slope or
 are a much stronger steady deceleration that also holds it on a slope or
@@ -362,6 +368,15 @@ first slope block and rolls back, the ridden one just makes it past it
 | Chest cart, full | 40 | 0 | 1 |
 | Chest cart, full | 40 | 0 | 1 |
 
 
 A chest cart in between is interpolated by how many stacks fill its slots.
 A chest cart in between is interpolated by how many stacks fill its slots.
+
+Detector rails (`B.DETECTOR_RAIL` 101; iron, a stone plate and spark dust,
+I.I / IPI / IDI makes 6) run straight like powered rails (shape in bits
+0-2, `railShapeOf` / `isRail` in blocks.js). A cart on one calls
+`pressDetector` every step: meta bit 8 goes on and the release time is
+kept 20 ticks ahead in `world.buttonDue`, so it switches off a second
+after the last cart leaves, and a parked cart holds it on. While on it is
+a source like a pressed plate: it powers the wire, lamps, pistons and
+powered rails beside it and the block it lies on.
 `js/carts.js`:
 `js/carts.js`:
 place a cart on a rail; right click to ride (Shift gets out), a chest cart
 place a cart on a rail; right click to ride (Shift gets out), a chest cart
 to open its 27 slots, a furnace cart with fuel to drive it away from you
 to open its 27 slots, a furnace cart with fuel to drive it away from you
@@ -372,7 +387,14 @@ block (a buffer) but rolls on into open space: off the rails it keeps its
 speed through the air and falls (`c.air`), a block in its way stops it
 speed through the air and falls (`c.air`), a block in its way stops it
 sideways but not its fall, on the ground it scrapes to a stop
 sideways but not its fall, on the ground it scrapes to a stop
 (`GROUND_DRAG` and `GROUND_STOP`: 1.25 blocks from full speed), and it lands
 (`GROUND_DRAG` and `GROUND_STOP`: 1.25 blocks from full speed), and it lands
-back on any rail it comes down onto. A player walking into a cart on an
+back on any rail it comes down onto. Landing, it turns to run along that rail at
+once (`landed` in `step`), keeping its speed across the ground: the way it
+moves along it, else the way it faced, else, square across the rail,
+turned to its right. Dropped straight down it only turns. A powered rail
+starts a still cart only away from a wall at one end; otherwise the cart
+stays until something pushes it - the player or an animal walking into it
+(`HALF` + the animal's half width). A cart placed on a rail lines up with
+it, facing the way the player looks (`railYaw`). A player walking into a cart on an
 unpowered powered rail pushes it at a slow pace (`BRAKE_PUSH`, 1.5
 unpowered powered rail pushes it at a slow pace (`BRAKE_PUSH`, 1.5
 blocks/s, also up a slope); the cart holds them back to that pace, so they
 blocks/s, also up a slope); the cart holds them back to that pace, so they
 lean on it instead of walking through. The model tilts
 lean on it instead of walking through. The model tilts
@@ -380,6 +402,56 @@ with the slope it is on (`pose`, from the rail direction kept by `step`).
 Two hits break a cart (one in creative); a cart takes the click over the
 Two hits break a cart (one in creative); a cart takes the click over the
 rail under it, whose box can stick out in front of a cart sitting in a dip.
 rail under it, whose box can stick out in front of a cart sitting in a dip.
 
 
+A cart touching a cactus (its box within 0.02 of the cactus's inset box,
+`touchingBlock` in physics.js) breaks into its item: in practice a cart
+running into a cactus at the end of a track, never one passing a cactus
+beside the track (0.07 apart). `breakOnCactus` drops the item, and a chest
+cart's contents, in the middle of the block the cart was in, clear of the
+cactus, which destroys any dropped item touching it (its top included)
+like lava and fire do. Touching a cactus hurts the player half a heart a
+second.
+
+## Feeders and dispensers
+
+`js/machines.js`, ticked from `Game.tick` (20 a second); both keep their
+items in tile entities (`TE_SLOTS` in world.js: feeder 5, dispenser 9)
+that drop when the block is broken, so pistons cannot move them.
+
+Feeder (`B.FEEDER` 102; I.I / ICI / .I. with a chest): a funnel, meta the
+face its spout feeds out of (down, or the side of the block clicked when
+placing). Every 8 ticks (2.5 items a second) it moves one item out of the
+spout and one in from the block on top; dropped items in its bowl or the
+block space above go in at once. Power (`isPowered`) stops it. It reaches
+chests, dispensers and other feeders (any slot), furnaces (from above
+into the smelting slot, only things that smelt; from a side into the fuel
+slot, only fuel; from below out of the output slot) and chest carts: one
+in the block the spout points into (a feeder over a rail) or in the block
+above (a rail laid on the feeder, which counts as solid ground for rails,
+wire and the like). Carts are served while moving too, as long as they are
+in that block.
+
+Dispenser (`B.DISPENSER` 103; CCC / CBC / CDC, cobblestone, a bow, spark
+dust): faces any way (placed like a piston, front looking back at the
+player), meta bit 8 while powered. Each time power arrives (`powerTick`
+calls `world.onDispense`) it takes a random filled slot and
+- shoots an arrow (22 blocks/s; dispensed arrows hurt the player too,
+  `hitsPlayer` in mobs.js)
+- sets a cart on a rail in front (or one block lower), turned along the
+  rail away from the dispenser; at the end of a powered rail the
+  dispenser is the wall the rail launches it from
+- floats a boat on water in front, raised to the water's surface, or on
+  water just below the space in front
+- pours a water or lava bucket into the space in front, keeping the empty
+  bucket, and fills an empty bucket from a source in front
+- throws anything else out as a dropped item (5 blocks/s)
+With nothing to dispense it just clicks.
+
+A cart recycler: a track ending in a cactus, its last rail laid on a
+feeder that feeds down into a dispenser facing a track below. The cart
+breaks on the cactus, its item drops onto the last rail, the feeder takes
+it into the dispenser, and power on the dispenser sets it on the track
+again.
+
 ## Boats
 ## Boats
 
 
 Five planks in a U make a boat. Right click water (or the ground) to put
 Five planks in a U make a boat. Right click water (or the ground) to put

+ 22 - 0
src/web/Blocky/css/style.css

@@ -943,6 +943,20 @@ body.screen-open #crosshair {
     margin-top: 8px;
     margin-top: 8px;
 }
 }
 
 
+/* Dispenser (3 x 3) and feeder (a row of 5), centred over the inventory */
+.slots.machine {
+    justify-content: center;
+    margin-bottom: 14px;
+}
+
+.slots.machine.n9 {
+    grid-template-columns: repeat(3, 44px);
+}
+
+.slots.machine.n5 {
+    grid-template-columns: repeat(5, 44px);
+}
+
 .slot:hover {
 .slot:hover {
     border-color: #9aa1ab;
     border-color: #9aa1ab;
 }
 }
@@ -1403,6 +1417,14 @@ body.screen-open #crosshair {
         grid-template-columns: repeat(9, 34px);
         grid-template-columns: repeat(9, 34px);
     }
     }
 
 
+    .slots.machine.n9 {
+        grid-template-columns: repeat(3, 34px);
+    }
+
+    .slots.machine.n5 {
+        grid-template-columns: repeat(5, 34px);
+    }
+
     .scr-col.creative {
     .scr-col.creative {
         --cell: 34px;
         --cell: 34px;
     }
     }

+ 27 - 3
src/web/Blocky/js/blocks.js

@@ -26,7 +26,7 @@ export const B = {
     PISTON_HEAD: 83, RAIL: 84, POWERED_RAIL: 85, SPARK_BLOCK: 86, PLATE_WOOD: 87, PLATE_STONE: 88,
     PISTON_HEAD: 83, RAIL: 84, POWERED_RAIL: 85, SPARK_BLOCK: 86, PLATE_WOOD: 87, PLATE_STONE: 88,
     RETIMER: 89, RETIMER_ON: 90, SIGN: 91, WALL_SIGN: 92, IRON_BARS: 93,
     RETIMER: 89, RETIMER_ON: 90, SIGN: 91, WALL_SIGN: 92, IRON_BARS: 93,
     PLANK_STAIRS: 94, COBBLE_STAIRS: 95, STONE_STAIRS: 96, STONE_BRICK_STAIRS: 97, BRICK_STAIRS: 98,
     PLANK_STAIRS: 94, COBBLE_STAIRS: 95, STONE_STAIRS: 96, STONE_BRICK_STAIRS: 97, BRICK_STAIRS: 98,
-    SANDSTONE_STAIRS: 99, TRAPDOOR: 100
+    SANDSTONE_STAIRS: 99, TRAPDOOR: 100, DETECTOR_RAIL: 101, FEEDER: 102, DISPENSER: 103
 };
 };
 
 
 //Wool and dye colours: key, name, colour
 //Wool and dye colours: key, name, colour
@@ -213,6 +213,14 @@ def(B.STICKY_PISTON, "Sticky Piston", { tex: { side: "piston_side", top: "piston
 def(B.PISTON_HEAD, "Piston Head", { tex: { side: "piston_side", top: "piston_top" }, shape: "pistonhead", opaque: false, lightOpacity: 0, hardness: 0.5, noItem: true, drops: () => [] });
 def(B.PISTON_HEAD, "Piston Head", { tex: { side: "piston_side", top: "piston_top" }, shape: "pistonhead", opaque: false, lightOpacity: 0, hardness: 0.5, noItem: true, drops: () => [] });
 def(B.RAIL, "Rail", { tex: "rail", shape: "rail", solid: false, opaque: false, lightOpacity: 0, hardness: 0.7, sound: "metal", support: "solid", cutout: true });
 def(B.RAIL, "Rail", { tex: "rail", shape: "rail", solid: false, opaque: false, lightOpacity: 0, hardness: 0.7, sound: "metal", support: "solid", cutout: true });
 def(B.POWERED_RAIL, "Powered Rail", { tex: "powered_rail", shape: "rail", solid: false, opaque: false, lightOpacity: 0, hardness: 0.7, sound: "metal", support: "solid", cutout: true });
 def(B.POWERED_RAIL, "Powered Rail", { tex: "powered_rail", shape: "rail", solid: false, opaque: false, lightOpacity: 0, hardness: 0.7, sound: "metal", support: "solid", cutout: true });
+//Detector rail: meta 8 while a cart is on it (and a second after), when it
+//is a spark source like a pressed plate
+def(B.DETECTOR_RAIL, "Detector Rail", { tex: "detector_rail", shape: "rail", solid: false, opaque: false, lightOpacity: 0, hardness: 0.7, sound: "metal", support: "solid", cutout: true });
+//Feeder: a funnel that moves items (5 slots, see machines.js); meta is the
+//face it feeds out of (3 down, or a side)
+def(B.FEEDER, "Feeder", { tex: { top: "feeder_top", side: "feeder_side", bottom: "feeder_side" }, shape: "feeder", opaque: false, lightOpacity: 0, hardness: 3, tool: "pickaxe", sound: "metal", interact: "feeder" });
+//Dispenser: meta 0-5 the face it shoots out of, bit 8 while powered
+def(B.DISPENSER, "Dispenser", { tex: { top: "furnace_top", bottom: "furnace_top", side: "furnace_side", front: "dispenser_front" }, hardness: 3.5, tool: "pickaxe", tier: 1, interact: "dispenser" });
 def(B.SPARK_BLOCK, "Block of Spark", { tex: "spark_block", hardness: 5, tool: "pickaxe", tier: 1, sound: "metal" });
 def(B.SPARK_BLOCK, "Block of Spark", { tex: "spark_block", hardness: 5, tool: "pickaxe", tier: 1, sound: "metal" });
 //Pressure plates: meta 1 while pressed. Anything presses a wooden one;
 //Pressure plates: meta 1 while pressed. Anything presses a wooden one;
 //only players and animals press a stone one.
 //only players and animals press a stone one.
@@ -275,6 +283,12 @@ for (const [id, c, b] of [
     FLAME_BURN[id] = b;
     FLAME_BURN[id] = b;
 }
 }
 
 
+//Rails: plain rails take 10 shapes (meta bits 0-3, curves included);
+//powered and detector rails run straight (bits 0-2) and keep bit 8 for
+//their on state
+export const isRail = (id) => id === B.RAIL || id === B.POWERED_RAIL || id === B.DETECTOR_RAIL;
+export const railShapeOf = (id, meta) => (id === B.RAIL ? Math.min(9, meta & 15) : meta & 7);
+
 //A slab with meta 2 is a double slab: a full opaque cube
 //A slab with meta 2 is a double slab: a full opaque cube
 export function isOpaqueAt(id, meta) {
 export function isOpaqueAt(id, meta) {
     return OPAQUE[id] === 1 || (SHAPE[id] === "slab" && meta === 2);
     return OPAQUE[id] === 1 || (SHAPE[id] === "slab" && meta === 2);
@@ -348,12 +362,19 @@ export function blockFaceLayer(id, face, meta) {
     if (id === B.POWERED_RAIL) {
     if (id === B.POWERED_RAIL) {
         return tileLayer.get(meta & 8 ? "powered_rail_on" : "powered_rail");
         return tileLayer.get(meta & 8 ? "powered_rail_on" : "powered_rail");
     }
     }
+    if (id === B.DETECTOR_RAIL) {
+        return tileLayer.get(meta & 8 ? "detector_rail_on" : "detector_rail");
+    }
     if (id === B.RAIL) {
     if (id === B.RAIL) {
         return tileLayer.get((meta & 15) >= 6 ? "rail_curve" : "rail");
         return tileLayer.get((meta & 15) >= 6 ? "rail_curve" : "rail");
     }
     }
     if (id === B.BED && face === 2) {
     if (id === B.BED && face === 2) {
         return tileLayer.get(meta & 4 ? "bed_head_top" : "bed_foot_top");
         return tileLayer.get(meta & 4 ? "bed_head_top" : "bed_foot_top");
     }
     }
+    if (id === B.DISPENSER) {
+        const f = meta & 7;
+        return face === f ? tileLayer.get(f === 2 || f === 3 ? "dispenser_front_v" : "dispenser_front") : fl[face];
+    }
     if (id === B.WORKBENCH) {
     if (id === B.WORKBENCH) {
         return (face === 4 || face === 5) ? fl[6] : fl[face];
         return (face === 4 || face === 5) ? fl[6] : fl[face];
     }
     }
@@ -379,7 +400,7 @@ const FLAT_BLOCK_ICONS = {
     [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", [B.BLUE_FLOWER]: "blue_flower",
     [B.FENCE]: "fence_item", [B.FENCE_GATE]: "gate_item", [B.BLUE_FLOWER]: "blue_flower",
     [B.GLASS_PANE]: "glass", [B.SPARK_TORCH]: "spark_torch_on", [B.LEVER]: "lever_item",
     [B.GLASS_PANE]: "glass", [B.SPARK_TORCH]: "spark_torch_on", [B.LEVER]: "lever_item",
-    [B.BUTTON]: "button_item", [B.RAIL]: "rail", [B.POWERED_RAIL]: "powered_rail",
+    [B.BUTTON]: "button_item", [B.RAIL]: "rail", [B.POWERED_RAIL]: "powered_rail", [B.DETECTOR_RAIL]: "detector_rail",
     [B.SIGN]: "sign_item", [B.IRON_BARS]: "iron_bars"
     [B.SIGN]: "sign_item", [B.IRON_BARS]: "iron_bars"
 };
 };
 
 
@@ -657,6 +678,9 @@ shaped(B.SPARK_BLOCK, 1, ["DDD", "DDD", "DDD"], { D: I.SPARK_DUST }, "Spark");
 shapeless(I.SPARK_DUST, 9, [B.SPARK_BLOCK], "Spark");
 shapeless(I.SPARK_DUST, 9, [B.SPARK_BLOCK], "Spark");
 shaped(B.RAIL, 16, ["I.I", "ISI", "I.I"], { I: I.IRON_INGOT, S: I.STICK }, "Spark");
 shaped(B.RAIL, 16, ["I.I", "ISI", "I.I"], { I: I.IRON_INGOT, S: I.STICK }, "Spark");
 shaped(B.POWERED_RAIL, 6, ["G.G", "GSG", "GDG"], { G: I.GOLD_INGOT, S: I.STICK, D: I.SPARK_DUST }, "Spark");
 shaped(B.POWERED_RAIL, 6, ["G.G", "GSG", "GDG"], { G: I.GOLD_INGOT, S: I.STICK, D: I.SPARK_DUST }, "Spark");
+shaped(B.DETECTOR_RAIL, 6, ["I.I", "IPI", "IDI"], { I: I.IRON_INGOT, P: B.PLATE_STONE, D: I.SPARK_DUST }, "Spark");
+shaped(B.FEEDER, 1, ["I.I", "ICI", ".I."], { I: I.IRON_INGOT, C: B.CHEST }, "Spark");
+shaped(B.DISPENSER, 1, ["CCC", "CBC", "CDC"], { C: B.COBBLE, B: I.BOW, D: I.SPARK_DUST }, "Spark");
 shaped(I.MINECART, 1, ["I.I", "III"], { I: I.IRON_INGOT }, "Spark");
 shaped(I.MINECART, 1, ["I.I", "III"], { I: I.IRON_INGOT }, "Spark");
 shapeless(I.CHEST_MINECART, 1, [I.MINECART, B.CHEST], "Spark");
 shapeless(I.CHEST_MINECART, 1, [I.MINECART, B.CHEST], "Spark");
 shapeless(I.FURNACE_MINECART, 1, [I.MINECART, B.FURNACE], "Spark");
 shapeless(I.FURNACE_MINECART, 1, [I.MINECART, B.FURNACE], "Spark");
@@ -811,7 +835,7 @@ export function creativeGroups() {
     }
     }
     tools.push(I.BOW, I.ARROW, I.BUCKET, I.WATER_BUCKET, I.LAVA_BUCKET, I.FLINT_AND_STEEL, I.BOAT, I.COMPASS);
     tools.push(I.BOW, I.ARROW, I.BUCKET, I.WATER_BUCKET, I.LAVA_BUCKET, I.FLINT_AND_STEEL, I.BOAT, I.COMPASS);
     const spark = [B.SPARK_ORE, I.SPARK_DUST, B.SPARK_BLOCK, B.SPARK_TORCH, B.LEVER, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.SPARK_LAMP,
     const spark = [B.SPARK_ORE, I.SPARK_DUST, B.SPARK_BLOCK, B.SPARK_TORCH, B.LEVER, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.SPARK_LAMP,
-        B.PISTON, B.STICKY_PISTON, B.RAIL, B.POWERED_RAIL, I.MINECART, I.CHEST_MINECART, I.FURNACE_MINECART];
+        B.PISTON, B.STICKY_PISTON, B.DISPENSER, B.FEEDER, B.RAIL, B.POWERED_RAIL, B.DETECTOR_RAIL, I.MINECART, I.CHEST_MINECART, I.FURNACE_MINECART];
     const items = [I.STICK, I.COAL, I.IRON_INGOT, I.GOLD_INGOT, I.CRYSTAL, I.FLINT, I.CLAY_BALL, I.BRICK,
     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, I.RAW_MEAT, I.COOKED_MEAT, I.RAW_MUTTON,
         I.WHEAT, I.BOWL, I.APPLE, I.BREAD, I.STEW, I.RAW_MEAT, I.COOKED_MEAT, I.RAW_MUTTON,
         I.COOKED_MUTTON, I.RAW_CHICKEN, I.COOKED_CHICKEN, I.FEATHER, I.STRING, I.BONE, I.BONE_MEAL];
         I.COOKED_MUTTON, I.RAW_CHICKEN, I.COOKED_CHICKEN, I.FEATHER, I.STRING, I.BONE, I.BONE_MEAL];

+ 71 - 8
src/web/Blocky/js/carts.js

@@ -14,8 +14,8 @@
 */
 */
 
 
 import * as THREE from "three";
 import * as THREE from "three";
-import { B, I, BLOCKS, ITEMS, isOpaqueAt, fuelTicks } from "./blocks.js";
-import { moveAxis } from "./physics.js";
+import { B, I, BLOCKS, ITEMS, isOpaqueAt, fuelTicks, isRail, railShapeOf } from "./blocks.js";
+import { moveAxis, touchingBlock } from "./physics.js";
 
 
 //Two exits of each rail shape, block local (0 NS, 1 EW, 2-5 rising +x -x +z -z, 6-9 curves SE SW NW NE)
 //Two exits of each rail shape, block local (0 NS, 1 EW, 2-5 rising +x -x +z -z, 6-9 curves SE SW NW NE)
 const RAIL_EXITS = [
 const RAIL_EXITS = [
@@ -83,9 +83,9 @@ export class Carts {
         //a little below the flat rail that follows it
         //a little below the flat rail that follows it
         for (const by of [fy, fy - 1, fy + 1]) {
         for (const by of [fy, fy - 1, fy + 1]) {
             const id = w.getBlock(bx, by, bz);
             const id = w.getBlock(bx, by, bz);
-            if (id === B.RAIL || id === B.POWERED_RAIL) {
+            if (isRail(id)) {
                 const m = w.getMeta(bx, by, bz);
                 const m = w.getMeta(bx, by, bz);
-                return { id, bx, by, bz, shape: id === B.POWERED_RAIL ? m & 7 : Math.min(9, m & 15), powered: (m & 8) !== 0 };
+                return { id, bx, by, bz, shape: railShapeOf(id, m), powered: (m & 8) !== 0 };
             }
             }
         }
         }
         return null;
         return null;
@@ -152,6 +152,19 @@ export class Carts {
         return { group, mats: [metal, dark], cargo };
         return { group, mats: [metal, dark], cargo };
     }
     }
 
 
+    //Yaw for a cart on the rail at (bx, by, bz): along the rail, the way
+    //closer to the heading (hx, hz)
+    railYaw(bx, by, bz, hx, hz) {
+        const r = this.railAt(bx + 0.5, by + 0.1, bz + 0.5);
+        if (!r) {
+            return Math.atan2(hx, hz);
+        }
+        const [a, b] = RAIL_EXITS[r.shape];
+        const dx = b[0] - a[0], dz = b[2] - a[2];
+        const dir = hx * dx + hz * dz < 0 ? -1 : 1;
+        return Math.atan2(dx * dir, dz * dir);
+    }
+
     spawn(kind, x, y, z, data = {}) {
     spawn(kind, x, y, z, data = {}) {
         const c = {
         const c = {
             kind, x, y, z, vx: data.vx || 0, vy: 0, vz: data.vz || 0, yaw: data.yaw || 0,
             kind, x, y, z, vx: data.vx || 0, vy: 0, vz: data.vz || 0, yaw: data.yaw || 0,
@@ -229,16 +242,20 @@ export class Carts {
         }
         }
     }
     }
 
 
-    breakCart(c, drop) {
+    //at: where the items drop and how they fly ({ x, y, z, vel }), else
+    //from the cart, scattered
+    breakCart(c, drop, at = null) {
         const g = this.game;
         const g = this.game;
         if (c.rider) {
         if (c.rider) {
             this.dismount();
             this.dismount();
         }
         }
         if (drop) {
         if (drop) {
-            g.entities.spawnItem(c.x, c.y + 0.5, c.z, CART_ITEM[c.kind], 1);
+            const [x, y, z] = at ? [at.x, at.y, at.z] : [c.x, c.y + 0.5, c.z];
+            const vel = () => (at ? at.vel.slice() : null);
+            g.entities.spawnItem(x, y, z, CART_ITEM[c.kind], 1, 0, vel());
             for (const s of c.slots || []) {
             for (const s of c.slots || []) {
                 if (s) {
                 if (s) {
-                    g.entities.spawnItem(c.x, c.y + 0.5, c.z, s.id, s.count, s.dmg || 0);
+                    g.entities.spawnItem(x, y, z, s.id, s.count, s.dmg || 0, vel());
                 }
                 }
             }
             }
         }
         }
@@ -247,6 +264,13 @@ export class Carts {
         this.list.splice(this.list.indexOf(c), 1);
         this.list.splice(this.list.indexOf(c), 1);
     }
     }
 
 
+    //The items drop in the middle of the block the cart was in (on the
+    //rail beside the cactus), clear of the cactus so it does not destroy
+    //them as well, and where a feeder under that rail takes them in
+    breakOnCactus(c) {
+        this.breakCart(c, true, { x: Math.floor(c.x) + 0.5, y: c.y + 0.3, z: Math.floor(c.z) + 0.5, vel: [0, 1, 0] });
+    }
+
     //Right click: ride, open the chest, or fuel the furnace
     //Right click: ride, open the chest, or fuel the furnace
     use(c) {
     use(c) {
         const g = this.game, p = g.player, inv = g.inventory;
         const g = this.game, p = g.player, inv = g.inventory;
@@ -321,6 +345,12 @@ export class Carts {
                 c.hitCd = Math.max(0, c.hitCd - h);
                 c.hitCd = Math.max(0, c.hitCd - h);
                 this.step(c, h, input);
                 this.step(c, h, input);
             }
             }
+            //A cart running into a cactus breaks into its item
+            for (const c of this.list.slice()) {
+                if (touchingBlock(g.world, this.box(c), B.CACTUS, 0.02)) {
+                    this.breakOnCactus(c);
+                }
+            }
             this.collide();
             this.collide();
         }
         }
         for (const c of this.list) {
         for (const c of this.list) {
@@ -334,6 +364,7 @@ export class Carts {
             return;
             return;
         }
         }
         let r = this.railAt(c.x, c.y, c.z);
         let r = this.railAt(c.x, c.y, c.z);
+        let landed = false;
         if (r && c.air) {
         if (r && c.air) {
             //Off the rails it only lands on a rail it has come down onto
             //Off the rails it only lands on a rail it has come down onto
             if (c.vy > 0.01 || c.y > r.by + 0.55 || c.y < r.by - 0.2) {
             if (c.vy > 0.01 || c.y > r.by + 0.55 || c.y < r.by - 0.2) {
@@ -341,6 +372,7 @@ export class Carts {
             } else {
             } else {
                 c.air = false;
                 c.air = false;
                 c.vy = 0;
                 c.vy = 0;
+                landed = true;
             }
             }
         }
         }
         if (!r) {
         if (!r) {
@@ -377,6 +409,9 @@ export class Carts {
             c.z = (box[2] + box[5]) / 2;
             c.z = (box[2] + box[5]) / 2;
             return;
             return;
         }
         }
+        if (r.id === B.DETECTOR_RAIL) {
+            w.pressDetector(r.bx, r.by, r.bz);
+        }
         const [a, b] = RAIL_EXITS[r.shape];
         const [a, b] = RAIL_EXITS[r.shape];
         const ax = r.bx + a[0], ay = r.by + a[1], az = r.bz + a[2];
         const ax = r.bx + a[0], ay = r.by + a[1], az = r.bz + a[2];
         let dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
         let dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
@@ -403,6 +438,19 @@ export class Carts {
                 s = enter * speed;
                 s = enter * speed;
             }
             }
         }
         }
+        if (landed) {
+            //Come down onto a rail, it turns to run along it at once,
+            //keeping the speed it had across the ground: the way it is
+            //moving along it, else the way it faced, else (square across
+            //the rail) turned to its right. Dropped straight down it only
+            //turns, and stays put.
+            const hx = Math.sin(c.yaw), hz = Math.cos(c.yaw);
+            const face = hx * dx + hz * dz;
+            const dir = Math.abs(s) > 0.05 ? Math.sign(s) : Math.abs(face) > 0.1 ? Math.sign(face) : Math.sign(hx * dz - hz * dx) || 1;
+            const flat = Math.hypot(c.vx, c.vz);
+            s = flat > 0.05 ? dir * flat : 0;
+            c.yaw = Math.atan2(dx * dir, dz * dir);
+        }
         //Downhill pull
         //Downhill pull
         s -= 12 * dy * h;
         s -= 12 * dy * h;
         const [coast, roll, brake, boost] = this.loadOf(c);
         const [coast, roll, brake, boost] = this.loadOf(c);
@@ -416,6 +464,7 @@ export class Carts {
                     } else if (solidAt(r.bx + b[0] + dx * 0.5, r.bz + b[2] + dz * 0.5)) {
                     } else if (solidAt(r.bx + b[0] + dx * 0.5, r.bz + b[2] + dz * 0.5)) {
                         s = -2;
                         s = -2;
                     }
                     }
+                    //(no wall: a still cart stays until something pushes it)
                 } else {
                 } else {
                     s += Math.sign(s) * boost * h;
                     s += Math.sign(s) * boost * h;
                 }
                 }
@@ -507,8 +556,22 @@ export class Carts {
         if (Math.abs(s) > 0.02) {
         if (Math.abs(s) > 0.02) {
             c.yaw = Math.atan2(dx * Math.sign(s), dz * Math.sign(s));
             c.yaw = Math.atan2(dx * Math.sign(s), dz * Math.sign(s));
         }
         }
-        //Lift the rider's step: a player walking into a cart gives it a nudge
+        //A player or an animal walking into a cart gives it a nudge
         const p = g.player;
         const p = g.player;
+        for (const m of g.mobs.list) {
+            const reach = m.def.w / 2 + HALF;
+            if (Math.abs(m.x - c.x) < reach && Math.abs(m.z - c.z) < reach && m.y < c.y + 0.7 && m.y + m.def.h > c.y) {
+                const ex = c.x - m.x, ez = c.z - m.z, l = Math.hypot(ex, ez) || 1;
+                const dot = (ex / l) * dx + (ez / l) * dz;
+                if (r.id === B.POWERED_RAIL && !r.powered) {
+                    c.shove = Math.sign(dot);
+                } else {
+                    const push = dot * 3 * h;
+                    c.vx += dx * push;
+                    c.vz += dz * push;
+                }
+            }
+        }
         if (!c.rider && !p.dead && Math.abs(p.x - c.x) < 0.8 && Math.abs(p.z - c.z) < 0.8 && p.y < c.y + 0.7 && p.y + 1.8 > c.y) {
         if (!c.rider && !p.dead && Math.abs(p.x - c.x) < 0.8 && Math.abs(p.z - c.z) < 0.8 && p.y < c.y + 0.7 && p.y + 1.8 > c.y) {
             const ex = c.x - p.x, ez = c.z - p.z, l = Math.hypot(ex, ez) || 1;
             const ex = c.x - p.x, ez = c.z - p.z, l = Math.hypot(ex, ez) || 1;
             const dot = (ex / l) * dx + (ez / l) * dz;
             const dot = (ex / l) * dx + (ez / l) * dz;

+ 3 - 3
src/web/Blocky/js/commands.js

@@ -16,7 +16,7 @@
 import { ITEMS, BLOCKS, B, itemName } from "./blocks.js";
 import { ITEMS, BLOCKS, B, itemName } from "./blocks.js";
 import { DIFFICULTY } from "./player.js";
 import { DIFFICULTY } from "./player.js";
 import { maxStack } from "./inventory.js";
 import { maxStack } from "./inventory.js";
-import { WORLD_H } from "./world.js";
+import { WORLD_H, TE_KINDS } from "./world.js";
 import { WE_COMMANDS } from "./wecommands.js";
 import { WE_COMMANDS } from "./wecommands.js";
 import { EditError, blockNames, DIRECTION_WORDS } from "./worldedit.js";
 import { EditError, blockNames, DIRECTION_WORDS } from "./worldedit.js";
 
 
@@ -350,8 +350,8 @@ export const COMMANDS = {
             if (id === B.WATER) {
             if (id === B.WATER) {
                 game.world.schedule(x, y, z, 5);
                 game.world.schedule(x, y, z, 5);
             }
             }
-            if (id === B.FURNACE || id === B.CHEST) {
-                game.world.createTileEntity(x, y, z, id === B.FURNACE ? "furnace" : "chest");
+            if (BLOCKS[id].interact && TE_KINDS.has(BLOCKS[id].interact)) {
+                game.world.createTileEntity(x, y, z, BLOCKS[id].interact);
             }
             }
             return [`Placed ${id === B.AIR ? "air" : BLOCKS[id].name} at ${x}, ${y}, ${z}`];
             return [`Placed ${id === B.AIR ? "air" : BLOCKS[id].name} at ${x}, ${y}, ${z}`];
         }
         }

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

@@ -3,11 +3,12 @@
 
 
     Dropped items (small spinning blocks or flat sprites that the player
     Dropped items (small spinning blocks or flat sprites that the player
     picks up) and falling blocks (sand and gravel that lost their support).
     picks up) and falling blocks (sand and gravel that lost their support).
-    There are no creatures in Blocky.
+    Lava, fire and cactus destroy dropped items (a cactus on touch, top
+    included).
 */
 */
 
 
 import { B, BLOCKS } from "./blocks.js";
 import { B, BLOCKS } from "./blocks.js";
-import { moveAxis } from "./physics.js";
+import { moveAxis, touchingBlock } from "./physics.js";
 
 
 export const ITEM_HALF = 0.125;
 export const ITEM_HALF = 0.125;
 const DESPAWN = 300;
 const DESPAWN = 300;
@@ -118,6 +119,11 @@ export class Entities {
                 e.x = (box[0] + box[3]) / 2;
                 e.x = (box[0] + box[3]) / 2;
                 e.y = (box[1] + box[4]) / 2;
                 e.y = (box[1] + box[4]) / 2;
                 e.z = (box[2] + box[5]) / 2;
                 e.z = (box[2] + box[5]) / 2;
+                if (touchingBlock(world, box, B.CACTUS, 0.02)) {
+                    r.disposeItemMesh(e.mesh);
+                    this.items.splice(i, 1);
+                    continue;
+                }
             }
             }
             e.spin += dt * 1.6;
             e.spin += dt * 1.6;
             const bob = Math.sin(e.age * 2.5) * 0.06 + 0.1;
             const bob = Math.sin(e.age * 2.5) * 0.06 + 0.1;

+ 21 - 11
src/web/Blocky/js/game.js

@@ -18,7 +18,8 @@ import { Carts } from "./carts.js";
 import { Boats } from "./boats.js";
 import { Boats } from "./boats.js";
 import { Signs } from "./signs.js";
 import { Signs } from "./signs.js";
 import { WorldEdit } from "./worldedit.js";
 import { WorldEdit } from "./worldedit.js";
-import { World, WORLD_H } from "./world.js";
+import { Machines } from "./machines.js";
+import { World, WORLD_H, TE_KINDS } from "./world.js";
 import { BIOME, BIOME_NAMES } from "./worldgen.js";
 import { BIOME, BIOME_NAMES } from "./worldgen.js";
 import { Player, DIFFICULTY } from "./player.js";
 import { Player, DIFFICULTY } from "./player.js";
 import { Inventory } from "./inventory.js";
 import { Inventory } from "./inventory.js";
@@ -36,6 +37,7 @@ const DEATH_TEXT = {
     drown: "You drowned",
     drown: "You drowned",
     starve: "You starved to death",
     starve: "You starved to death",
     cactus: "You were pricked to death by a cactus",
     cactus: "You were pricked to death by a cactus",
+    arrow: "You were shot by a dispenser",
     lightning: "You were struck by lightning",
     lightning: "You were struck by lightning",
     suffocate: "You suffocated in a wall",
     suffocate: "You suffocated in a wall",
     lava: "You tried to swim in lava",
     lava: "You tried to swim in lava",
@@ -112,6 +114,7 @@ export class Game {
                 }
                 }
             },
             },
             onPistonPush: (cells, d) => this.pistonPush(cells, d),
             onPistonPush: (cells, d) => this.pistonPush(cells, d),
+            onDispense: (x, y, z, face) => this.machines.dispense(x, y, z, face),
             onFizz: (x, y, z) => {
             onFizz: (x, y, z) => {
                 this.sound.play("fizz");
                 this.sound.play("fizz");
                 this.renderer.spawnParticles(x + 0.5, y + 1, z + 0.5, [200, 200, 200], 12, 0.4, 2);
                 this.renderer.spawnParticles(x + 0.5, y + 1, z + 0.5, [200, 200, 200], 12, 0.4, 2);
@@ -122,6 +125,7 @@ export class Game {
         this.mobs = new Mobs(this);
         this.mobs = new Mobs(this);
         this.carts = new Carts(this);
         this.carts = new Carts(this);
         this.boats = new Boats(this);
         this.boats = new Boats(this);
+        this.machines = new Machines(this);
         this.signs = new Signs(this);
         this.signs = new Signs(this);
         this.riding = null;
         this.riding = null;
         this.boat = null;
         this.boat = null;
@@ -521,6 +525,7 @@ export class Game {
         const p = this.player;
         const p = this.player;
         this.world.tick(Math.floor(p.x / 16), Math.floor(p.z / 16));
         this.world.tick(Math.floor(p.x / 16), Math.floor(p.z / 16));
         this.pressPlates();
         this.pressPlates();
+        this.machines.tick();
         p.tick();
         p.tick();
         const w = this.weather;
         const w = this.weather;
         w.timer--;
         w.timer--;
@@ -536,7 +541,8 @@ export class Game {
                 w.timer = 6000 + Math.floor(this.rng() * 14000);
                 w.timer = 6000 + Math.floor(this.rng() * 14000);
             }
             }
         }
         }
-        if (this.ui.isOpen() && this.ui.screen.kind === "furnace" && this.ticks % 2 === 0) {
+        //Containers change while open (furnaces burn, feeders move items)
+        if (this.ui.isOpen() && this.ui.screen.te && this.ui.screen.te.slots && this.ticks % 2 === 0) {
             this.ui.renderScreen(false);
             this.ui.renderScreen(false);
         }
         }
     }
     }
@@ -1111,9 +1117,11 @@ export class Game {
             return;
             return;
         }
         }
         if (it.cart) {
         if (it.cart) {
-            if (rawHit.id === B.RAIL || rawHit.id === B.POWERED_RAIL) {
+            if (SHAPE[rawHit.id] === "rail") {
+                //Lined up with the rail, facing the way the player looks
                 const [cx, cy, cz] = this.carts.railSeat(rawHit.x, rawHit.y, rawHit.z);
                 const [cx, cy, cz] = this.carts.railSeat(rawHit.x, rawHit.y, rawHit.z);
-                this.carts.spawn(it.cart, cx, cy, cz);
+                const yaw = this.carts.railYaw(rawHit.x, rawHit.y, rawHit.z, -Math.sin(this.player.yaw), -Math.cos(this.player.yaw));
+                this.carts.spawn(it.cart, cx, cy, cz, { yaw });
                 this.sound.block("place", "metal");
                 this.sound.block("place", "metal");
                 this.swing = 0;
                 this.swing = 0;
                 if (!this.creative) {
                 if (!this.creative) {
@@ -1313,8 +1321,12 @@ export class Game {
         }
         }
         if (bid === B.LEVER || bid === B.BUTTON) {
         if (bid === B.LEVER || bid === B.BUTTON) {
             meta = face;
             meta = face;
-        } else if (bid === B.PISTON || bid === B.STICKY_PISTON) {
-            //The pushing face looks back at the player
+        } else if (bid === B.FEEDER) {
+            //The spout feeds into the block clicked (down when clicked from
+            //above or below)
+            meta = face === 2 || face === 3 ? 3 : face ^ 1;
+        } else if (bid === B.PISTON || bid === B.STICKY_PISTON || bid === B.DISPENSER) {
+            //The pushing (or shooting) face looks back at the player
             const [, , , lx, ly, lz] = this.eyeRay();
             const [, , , lx, ly, lz] = this.eyeRay();
             const ax = Math.abs(lx), ay = Math.abs(ly), az = Math.abs(lz);
             const ax = Math.abs(lx), ay = Math.abs(ly), az = Math.abs(lz);
             if (ay >= ax && ay >= az) {
             if (ay >= ax && ay >= az) {
@@ -1339,7 +1351,7 @@ export class Game {
         } else if (bid === B.RETIMER) {
         } else if (bid === B.RETIMER) {
             //Signal runs away from the player
             //Signal runs away from the player
             meta = facingFromYaw(p.yaw);
             meta = facingFromYaw(p.yaw);
-        } else if (bid === B.RAIL || bid === B.POWERED_RAIL) {
+        } else if (SHAPE[bid] === "rail") {
             meta = Math.abs(Math.sin(p.yaw)) > Math.abs(Math.cos(p.yaw)) ? 1 : 0;
             meta = Math.abs(Math.sin(p.yaw)) > Math.abs(Math.cos(p.yaw)) ? 1 : 0;
             w.railPreferX = meta === 1;
             w.railPreferX = meta === 1;
             w.railAim = face === 2 ? [hit.point[0] - x - 0.5, hit.point[2] - z - 0.5] : null;
             w.railAim = face === 2 ? [hit.point[0] - x - 0.5, hit.point[2] - z - 0.5] : null;
@@ -1465,10 +1477,8 @@ export class Game {
         if (!w.setBlock(x, y, z, bid, meta)) {
         if (!w.setBlock(x, y, z, bid, meta)) {
             return;
             return;
         }
         }
-        if (bid === B.FURNACE) {
-            w.createTileEntity(x, y, z, "furnace");
-        } else if (bid === B.CHEST) {
-            w.createTileEntity(x, y, z, "chest");
+        if (TE_KINDS.has(BLOCKS[bid].interact)) {
+            w.createTileEntity(x, y, z, BLOCKS[bid].interact);
         } else if (bid === B.SIGN || bid === B.WALL_SIGN) {
         } else if (bid === B.SIGN || bid === B.WALL_SIGN) {
             //Write on it straight away
             //Write on it straight away
             this.openScreen("sign", Signs.create(w, x, y, z));
             this.openScreen("sign", Signs.create(w, x, y, z));

+ 3 - 3
src/web/Blocky/js/icons.js

@@ -8,7 +8,7 @@
 
 
 import { ITEMS, BLOCKS, SHAPE, blockFaceLayer } from "./blocks.js";
 import { ITEMS, BLOCKS, SHAPE, blockFaceLayer } from "./blocks.js";
 import { drawIsoIcon, drawIsoBoxes, drawFlatIcon, ICON, GRASS_TINT, FOLIAGE_TINT } from "./textures.js";
 import { drawIsoIcon, drawIsoBoxes, drawFlatIcon, ICON, GRASS_TINT, FOLIAGE_TINT } from "./textures.js";
-import { STAIR_ITEM_BOXES } from "./mesher.js";
+import { STAIR_ITEM_BOXES, FEEDER_ITEM_BOXES } from "./mesher.js";
 
 
 export function buildIcons(tex) {
 export function buildIcons(tex) {
     const ids = [];
     const ids = [];
@@ -49,8 +49,8 @@ export function buildIcons(tex) {
             opts.topTint = FOLIAGE_TINT;
             opts.topTint = FOLIAGE_TINT;
             opts.sideTint = FOLIAGE_TINT;
             opts.sideTint = FOLIAGE_TINT;
         }
         }
-        if (shape === "stairs") {
-            drawIsoBoxes(ctx, x, y, tiles, STAIR_ITEM_BOXES, opts);
+        if (shape === "stairs" || shape === "feeder") {
+            drawIsoBoxes(ctx, x, y, tiles, shape === "stairs" ? STAIR_ITEM_BOXES : FEEDER_ITEM_BOXES, opts);
         } else {
         } else {
             drawIsoIcon(ctx, x, y, tiles, opts);
             drawIsoIcon(ctx, x, y, tiles, opts);
         }
         }

+ 273 - 0
src/web/Blocky/js/machines.js

@@ -0,0 +1,273 @@
+/*
+    Blocky - machines.js
+
+    Feeders and dispensers, the two item handling blocks.
+
+    A feeder (5 slots) moves one item every FEED_TICKS game ticks: out of
+    its spout into what it points at (down or to a side), and in from what
+    sits on top of it. It also takes in dropped items lying in its bowl or
+    the block space above it, at once. Power stops it. What it can reach:
+    - chests, dispensers and other feeders: any slot
+    - furnaces: fed from above into the smelting slot (only things that
+      smelt), from a side into the fuel slot (only fuel); a feeder under a
+      furnace takes from its output slot
+    - a chest cart in the block it points into (a feeder over a rail) or in
+      the block above it (a rail laid on the feeder), moving or not
+
+    A dispenser (9 slots) fires once each time power arrives (power.js
+    calls world.onDispense): it picks a random filled slot and
+    - shoots an arrow
+    - sets a cart on a rail in front of it (or one block lower), turned
+      along the rail away from it
+    - floats a boat on water in front of it (up to the water's surface)
+    - pours a water or lava bucket into the space in front (keeping the
+      empty bucket) and fills an empty bucket from a source in front
+    - throws anything else out as a dropped item
+*/
+
+import { B, I, ITEMS, BLOCKS, SMELTING, fuelTicks, isRail } from "./blocks.js";
+import { FACE_DIR } from "./shapes.js";
+import { isPowered } from "./power.js";
+import { maxStack } from "./inventory.js";
+
+//Game ticks between two moves of a feeder: 2.5 items a second
+const FEED_TICKS = 8;
+//How fast a dispenser throws items and shoots arrows (blocks / s)
+const THROW_SPEED = 5;
+const ARROW_SPEED = 22;
+const ARROW_DAMAGE = 6;
+
+const range = (n) => Array.from({ length: n }, (_, i) => i);
+
+//Put one of `st` (id, dmg) into the first of the slots `idxs` that takes it:
+//a stack of the same item first, else an empty slot
+function insertOne(slots, idxs, st) {
+    for (const i of idxs) {
+        const t = slots[i];
+        if (t && t.id === st.id && (t.dmg || 0) === (st.dmg || 0) && t.count < maxStack(t.id)) {
+            t.count++;
+            return true;
+        }
+    }
+    for (const i of idxs) {
+        if (!slots[i]) {
+            slots[i] = { id: st.id, count: 1, dmg: st.dmg || 0 };
+            return true;
+        }
+    }
+    return false;
+}
+
+function takeOne(slots, i) {
+    const s = slots[i];
+    s.count--;
+    if (s.count <= 0) {
+        slots[i] = null;
+    }
+}
+
+export class Machines {
+    constructor(game) {
+        this.game = game;
+    }
+
+    /* ---------------- feeders ---------------- */
+
+    tick() {
+        const w = this.game.world;
+        for (const [key, te] of w.tileEntities) {
+            if (te.type !== "feeder") {
+                continue;
+            }
+            const [x, y, z] = key.split(",").map(Number);
+            if (!w.isLoaded(x, z) || w.getBlock(x, y, z) !== B.FEEDER) {
+                continue;
+            }
+            this.collect(te, x, y, z);
+            if (te.cd > 0) {
+                te.cd--;
+                continue;
+            }
+            if (isPowered(w, x, y, z)) {
+                continue;
+            }
+            const out = this.feedOut(te, x, y, z, w.getMeta(x, y, z) & 7);
+            const got = this.pullIn(te, x, y, z);
+            if (out || got) {
+                te.cd = FEED_TICKS;
+            }
+        }
+    }
+
+    //What sits at (x, y, z) to put items into or take them from: a block
+    //keeping its items in a tile entity, or a chest cart in that space
+    containerAt(x, y, z) {
+        const g = this.game, w = g.world;
+        const kind = BLOCKS[w.getBlock(x, y, z)].interact;
+        if (kind === "chest" || kind === "dispenser" || kind === "feeder" || kind === "furnace") {
+            const te = w.getTileEntity(x, y, z) || w.createTileEntity(x, y, z, kind);
+            return { kind, slots: te.slots };
+        }
+        const cart = g.carts.list.find((c) => c.kind === "chest" &&
+            Math.floor(c.x) === x && Math.floor(c.z) === z && Math.floor(c.y + 0.1) === y);
+        return cart ? { kind: "cart", slots: cart.slots } : null;
+    }
+
+    //One item out of the spout (face: 3 down, else a side)
+    feedOut(te, x, y, z, face) {
+        const d = FACE_DIR[face];
+        const to = this.containerAt(x + d[0], y + d[1], z + d[2]);
+        if (!to) {
+            return false;
+        }
+        let idxs = range(to.slots.length), fits = () => true;
+        if (to.kind === "furnace") {
+            if (face === 3) {
+                idxs = [0];
+                fits = (id) => SMELTING.has(id);
+            } else {
+                idxs = [1];
+                fits = (id) => fuelTicks(id) > 0;
+            }
+        }
+        for (let i = 0; i < te.slots.length; i++) {
+            const s = te.slots[i];
+            if (s && fits(s.id) && insertOne(to.slots, idxs, s)) {
+                takeOne(te.slots, i);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    //One item in from what sits on top (a furnace gives its output only)
+    pullIn(te, x, y, z) {
+        const from = this.containerAt(x, y + 1, z);
+        if (!from) {
+            return false;
+        }
+        const idxs = from.kind === "furnace" ? [2] : range(from.slots.length);
+        const mine = range(te.slots.length);
+        for (const i of idxs) {
+            const s = from.slots[i];
+            if (s && insertOne(te.slots, mine, s)) {
+                takeOne(from.slots, i);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    //Dropped items in the bowl or the block space above it go in whole, or
+    //as many as fit
+    collect(te, x, y, z) {
+        const g = this.game, items = g.entities.items;
+        const mine = range(te.slots.length);
+        for (let i = items.length - 1; i >= 0; i--) {
+            const e = items[i];
+            if (e.x < x || e.x >= x + 1 || e.z < z || e.z >= z + 1 || e.y < y + 10 / 16 || e.y >= y + 2) {
+                continue;
+            }
+            let n = e.count;
+            while (n > 0 && insertOne(te.slots, mine, e)) {
+                n--;
+            }
+            if (n === 0) {
+                g.renderer.disposeItemMesh(e.mesh);
+                items.splice(i, 1);
+            } else {
+                e.count = n;
+            }
+        }
+    }
+
+    /* ---------------- dispensers ---------------- */
+
+    dispense(x, y, z, face) {
+        const g = this.game, w = g.world;
+        const te = w.getTileEntity(x, y, z) || w.createTileEntity(x, y, z, "dispenser");
+        const full = te.slots.map((s, i) => (s ? i : -1)).filter((i) => i >= 0);
+        if (!full.length) {
+            g.sound.play("click");
+            return;
+        }
+        const i = full[Math.floor(Math.random() * full.length)];
+        const s = te.slots[i];
+        const d = FACE_DIR[face];
+        const fx = x + d[0], fy = y + d[1], fz = z + d[2];
+        const front = w.getBlock(fx, fy, fz);
+        //Just outside the mouth
+        const ox = x + 0.5 + d[0] * 0.7, oy = y + 0.5 + d[1] * 0.7 - (d[1] === 0 ? 0.15 : 0), oz = z + 0.5 + d[2] * 0.7;
+        const it = ITEMS[s.id];
+        if (s.id === I.ARROW) {
+            g.mobs.shootArrow(ox, oy, oz, d[0] * ARROW_SPEED, d[1] * ARROW_SPEED + (d[1] === 0 ? 1.5 : 0), d[2] * ARROW_SPEED, ARROW_DAMAGE, true);
+            takeOne(te.slots, i);
+            g.sound.play("bow");
+            return;
+        }
+        if (it && it.cart) {
+            for (const ry of [fy, fy - 1]) {
+                if (isRail(w.getBlock(fx, ry, fz))) {
+                    const [cx, cy, cz] = g.carts.railSeat(fx, ry, fz);
+                    g.carts.spawn(it.cart, cx, cy, cz, { yaw: g.carts.railYaw(fx, ry, fz, d[0], d[2]) });
+                    takeOne(te.slots, i);
+                    g.sound.block("place", "metal");
+                    return;
+                }
+            }
+        }
+        if (s.id === I.BOAT) {
+            //On water in front (floated up to its surface), or on water just
+            //below the space in front
+            let wy = -1;
+            if (front === B.WATER) {
+                wy = fy;
+                while (wy < fy + 128 && w.getBlock(fx, wy + 1, fz) === B.WATER) {
+                    wy++;
+                }
+            } else if (front === B.AIR && w.getBlock(fx, fy - 1, fz) === B.WATER) {
+                wy = fy - 1;
+            }
+            if (wy >= 0) {
+                g.boats.spawn(fx + 0.5, wy + 0.875, fz + 0.5, { yaw: Math.atan2(-d[0], -d[2]) });
+                takeOne(te.slots, i);
+                g.sound.block("place", "wood");
+                return;
+            }
+        }
+        if (s.id === I.WATER_BUCKET || s.id === I.LAVA_BUCKET) {
+            const liquid = s.id === I.WATER_BUCKET ? B.WATER : B.LAVA;
+            const isLiquid = front === B.WATER || front === B.LAVA;
+            if (front === B.AIR || (isLiquid && w.getMeta(fx, fy, fz) !== 0) || (!isLiquid && BLOCKS[front].replaceable)) {
+                if (front !== B.AIR && !isLiquid) {
+                    w.breakNaturally(fx, fy, fz);
+                }
+                w.setBlock(fx, fy, fz, liquid, 0);
+                w.schedule(fx, fy, fz, 5);
+                te.slots[i] = { id: I.BUCKET, count: 1, dmg: 0 };
+                g.sound.play(liquid === B.WATER ? "splash" : "fizz");
+                return;
+            }
+        }
+        if (s.id === I.BUCKET && (front === B.WATER || front === B.LAVA) && w.getMeta(fx, fy, fz) === 0) {
+            w.setBlock(fx, fy, fz, B.AIR, 0);
+            const filled = { id: front === B.WATER ? I.WATER_BUCKET : I.LAVA_BUCKET, count: 1, dmg: 0 };
+            if (s.count === 1) {
+                te.slots[i] = filled;
+            } else {
+                takeOne(te.slots, i);
+                if (!insertOne(te.slots, range(te.slots.length), filled)) {
+                    g.entities.spawnItem(ox, oy, oz, filled.id, 1, 0, [d[0] * THROW_SPEED, d[1] * THROW_SPEED + 1, d[2] * THROW_SPEED]);
+                }
+            }
+            g.sound.play(front === B.WATER ? "splash" : "fizz");
+            return;
+        }
+        //Anything else is thrown out, a little scattered
+        const jx = (Math.random() - 0.5) * 0.8, jz = (Math.random() - 0.5) * 0.8;
+        g.entities.spawnItem(ox, oy, oz, s.id, 1, s.dmg || 0,
+            [d[0] * THROW_SPEED + jx, d[1] * THROW_SPEED + (d[1] === 0 ? 1.2 : 0), d[2] * THROW_SPEED + jz]);
+        takeOne(te.slots, i);
+        g.sound.play("click");
+    }
+}

+ 36 - 14
src/web/Blocky/js/mesher.js

@@ -18,9 +18,9 @@
 import { B, OPAQUE, SHAPE, SOLID, BLOCKS, blockFaceLayer, layerOfTile, ITEMS, HDIR, FLAME_CATCH } from "./blocks.js";
 import { B, OPAQUE, SHAPE, SOLID, BLOCKS, blockFaceLayer, layerOfTile, ITEMS, HDIR, FLAME_CATCH } from "./blocks.js";
 import { WORLD_H } from "./worldgen.js";
 import { WORLD_H } from "./worldgen.js";
 import {
 import {
-    FACE_DIR, doorBox, trapdoorBox, gateAlongZ, fenceLinks, rotatePoint, paneLinks, LEVER_BASE, BUTTON_BOX, BUTTON_PRESSED,
+    FACE_DIR, doorBox, trapdoorBox, gateAlongZ, fenceLinks, rotatePoint, paneLinks, LEVER_BASE, buttonBox,
     signAngle, SIGN_BOARD, SIGN_POST, SIGN_WALL_BOARD,
     signAngle, SIGN_BOARD, SIGN_POST, SIGN_WALL_BOARD,
-    PISTON_BASE, HEAD_PLATE, HEAD_ROD, stairShape, stairBoxes, waterHeight
+    PISTON_BASE, HEAD_PLATE, HEAD_ROD, stairShape, stairBoxes, waterHeight, feederBoxes
 } from "./shapes.js";
 } from "./shapes.js";
 
 
 export { waterHeight };
 export { waterHeight };
@@ -305,6 +305,15 @@ export function meshSection(world, chunk, sy, opts) {
                     pistonHead(solidBuf, p, x, y, z, id, meta);
                     pistonHead(solidBuf, p, x, y, z, id, meta);
                 } else if (shape === "rail") {
                 } else if (shape === "rail") {
                     rail(solidBuf, p, x, y, z, id, meta);
                     rail(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "feeder") {
+                    //Faces flush with an opaque neighbour are hidden
+                    for (const b of feederBoxes(meta)) {
+                        boxFaces(solidBuf, p, x, y, z, id, meta, b[0], b[1], b[2], b[3], b[4], b[5], (f, np) => {
+                            const axis = FACE_AXIS[f];
+                            const flush = FACE_SIGN[f] > 0 ? b[axis + 3] >= 1 : b[axis] <= 0;
+                            return flush && pOpq[np] === 1;
+                        });
+                    }
                 }
                 }
             }
             }
         }
         }
@@ -587,16 +596,16 @@ for (let face = 0; face < 6; face++) {
 }
 }
 
 
 //A box modelled facing up, turned to `face`. layerFn(f) picks the texture
 //A box modelled facing up, turned to `face`. layerFn(f) picks the texture
-//by canonical face; lean tilts the top along z (lever handles); faces on
-//the block boundary are skipped against opaque neighbours.
-function turnedBox(buf, p, x, y, z, b, face, layerFn, lean = 0) {
+//by canonical face; lean / leanX tilt the top along z / x (lever handles);
+//faces on the block boundary are skipped against opaque neighbours.
+function turnedBox(buf, p, x, y, z, b, face, layerFn, lean = 0, leanX = 0) {
     const mins = [b[0], b[1], b[2]], maxs = [b[3], b[4], b[5]];
     const mins = [b[0], b[1], b[2]], maxs = [b[3], b[4], b[5]];
     for (let f = 0; f < 6; f++) {
     for (let f = 0; f < 6; f++) {
         const wf = TURNED_FACE[face][f];
         const wf = TURNED_FACE[face][f];
         const axis = FACE_AXIS[f];
         const axis = FACE_AXIS[f];
         const onEdge = FACE_SIGN[f] > 0 ? maxs[axis] >= 1 : mins[axis] <= 0;
         const onEdge = FACE_SIGN[f] > 0 ? maxs[axis] >= 1 : mins[axis] <= 0;
         const np = p + FACE_OFF[wf];
         const np = p + FACE_OFF[wf];
-        if (onEdge && !lean && pOpq[np]) {
+        if (onEdge && !lean && !leanX && pOpq[np]) {
             continue;
             continue;
         }
         }
         //Opaque parts (pistons) hold no light themselves: light each face
         //Opaque parts (pistons) hold no light themselves: light each face
@@ -612,7 +621,7 @@ function turnedBox(buf, p, x, y, z, b, face, layerFn, lean = 0) {
             if (lean) {
             if (lean) {
                 vz += (vy - b[1]) * lean;
                 vz += (vy - b[1]) * lean;
             }
             }
-            const q = rotatePoint(face, vx, vy, vz);
+            const q = rotatePoint(face, leanX ? vx + (vy - b[1]) * leanX : vx, vy, vz);
             buf.vert(x + q[0], y + q[1], z + q[2], uv[0], uv[1], layer, ls, lb, s, s, s);
             buf.vert(x + q[0], y + q[1], z + q[2], uv[0], uv[1], layer, ls, lb, s, s, s);
         }
         }
         buf.quad(false);
         buf.quad(false);
@@ -671,7 +680,7 @@ function ironBars(buf, p, x, y, z, id, meta, links) {
 }
 }
 
 
 const WIRE_LINKS = new Set([B.SPARK_WIRE, B.LEVER, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.RETIMER_ON, B.SPARK_TORCH, B.SPARK_TORCH_OFF, B.SPARK_LAMP,
 const WIRE_LINKS = new Set([B.SPARK_WIRE, B.LEVER, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.RETIMER_ON, B.SPARK_TORCH, B.SPARK_TORCH_OFF, B.SPARK_LAMP,
-    B.SPARK_LAMP_ON, B.PISTON, B.STICKY_PISTON, B.SPARK_BLOCK, B.POWERED_RAIL]);
+    B.SPARK_LAMP_ON, B.PISTON, B.STICKY_PISTON, B.SPARK_BLOCK, B.POWERED_RAIL, B.DETECTOR_RAIL]);
 
 
 function flatQuad(buf, x0, z0, x1, z1, yy, layer, ls, lb, r, g, b) {
 function flatQuad(buf, x0, z0, x1, z1, yy, layer, ls, lb, r, g, b) {
     buf.vert(x0, yy, z1, 0, 0, layer, ls, lb, r, g, b);
     buf.vert(x0, yy, z1, 0, 0, layer, ls, lb, r, g, b);
@@ -778,13 +787,21 @@ function sign(buf, p, x, y, z, id, meta) {
 function lever(buf, p, x, y, z, id, meta) {
 function lever(buf, p, x, y, z, id, meta) {
     const face = meta & 7;
     const face = meta & 7;
     const stone = blockFaceLayer(id, 2, meta), wood = layerOfTile("planks");
     const stone = blockFaceLayer(id, 2, meta), wood = layerOfTile("planks");
-    turnedBox(buf, p, x, y, z, LEVER_BASE, face, () => stone);
-    turnedBox(buf, p, x, y, z, [7 * U, 1 * U, 7 * U, 9 * U, 10 * U, 9 * U], face, () => wood, meta & 8 ? 0.55 : -0.55);
+    //On a wall the handle always swings up and down (on: down); the turn
+    //onto an x facing wall maps the model's z to world z, so those lean
+    //(and lay the base out) along the model's x instead
+    const tilt = meta & 8 ? 0.55 : -0.55;
+    const sideways = face === 0 || face === 1;
+    const lean = sideways ? 0 : face === 5 ? -tilt : tilt;
+    const leanX = face === 0 ? tilt : face === 1 ? -tilt : 0;
+    const base = sideways ? [LEVER_BASE[2], LEVER_BASE[1], LEVER_BASE[0], LEVER_BASE[5], LEVER_BASE[4], LEVER_BASE[3]] : LEVER_BASE;
+    turnedBox(buf, p, x, y, z, base, face, () => stone);
+    turnedBox(buf, p, x, y, z, [7 * U, 1 * U, 7 * U, 9 * U, 10 * U, 9 * U], face, () => wood, lean, leanX);
 }
 }
 
 
 function button(buf, p, x, y, z, id, meta) {
 function button(buf, p, x, y, z, id, meta) {
     const layer = blockFaceLayer(id, 2, meta);
     const layer = blockFaceLayer(id, 2, meta);
-    turnedBox(buf, p, x, y, z, meta & 8 ? BUTTON_PRESSED : BUTTON_BOX, meta & 7, () => layer);
+    turnedBox(buf, p, x, y, z, buttonBox(meta), meta & 7, () => layer);
 }
 }
 
 
 function piston(buf, p, x, y, z, id, meta) {
 function piston(buf, p, x, y, z, id, meta) {
@@ -803,7 +820,7 @@ function pistonHead(buf, p, x, y, z, id, meta) {
 //Rail shapes: 0 NS, 1 EW, 2-5 rising toward +x, -x, +z, -z, 6-9 curves SE, SW, NW, NE
 //Rail shapes: 0 NS, 1 EW, 2-5 rising toward +x, -x, +z, -z, 6-9 curves SE, SW, NW, NE
 const RAIL_UV_FACING = [3, 0, 0, 0, 3, 3, 3, 0, 1, 2];
 const RAIL_UV_FACING = [3, 0, 0, 0, 3, 3, 3, 0, 1, 2];
 function rail(buf, p, x, y, z, id, meta) {
 function rail(buf, p, x, y, z, id, meta) {
-    const shape = id === B.POWERED_RAIL ? meta & 7 : meta & 15;
+    const shape = id === B.RAIL ? meta & 15 : meta & 7;
     const layer = blockFaceLayer(id, 2, meta);
     const layer = blockFaceLayer(id, 2, meta);
     const [ls, lb] = selfLight(p);
     const [ls, lb] = selfLight(p);
     const rise = (vx, vz) => (shape === 2 ? vx : shape === 3 ? 1 - vx : shape === 4 ? vz : shape === 5 ? 1 - vz : 0);
     const rise = (vx, vz) => (shape === 2 ? vx : shape === 3 ? 1 - vx : shape === 4 ? vz : shape === 5 ? 1 - vz : 0);
@@ -990,6 +1007,11 @@ export function cardGeometry(tile) {
 //on the -x half
 //on the -x half
 export const STAIR_ITEM_BOXES = [[0, 0, 0, 1, 0.5, 1], [0, 0.5, 0, 0.5, 1, 1]];
 export const STAIR_ITEM_BOXES = [[0, 0, 0, 1, 0.5, 1], [0, 0.5, 0, 0.5, 1, 1]];
 
 
+//A feeder (feeding down) in the hand and as an icon, back to front for
+//the icon's painter: spout, body, bowl floor, far walls, near walls
+const FB = feederBoxes(3);
+export const FEEDER_ITEM_BOXES = [FB[6], FB[5], FB[0], FB[1], FB[3], FB[2], FB[4]];
+
 //Geometry for held items and dropped items, centred on the origin.
 //Geometry for held items and dropped items, centred on the origin.
 //Blocks are unit cubes (slabs half height, stairs two boxes), everything
 //Blocks are unit cubes (slabs half height, stairs two boxes), everything
 //else a flat card.
 //else a flat card.
@@ -1000,13 +1022,13 @@ export function itemGeometry(id) {
     const blockId = it && it.block;
     const blockId = it && it.block;
     const shape = blockId ? SHAPE[blockId] : null;
     const shape = blockId ? SHAPE[blockId] : null;
     const cubeLike = blockId && (shape === "cube" || shape === "slab" || shape === "stairs" || shape === "cactus" || shape === "farmland" ||
     const cubeLike = blockId && (shape === "cube" || shape === "slab" || shape === "stairs" || shape === "cactus" || shape === "farmland" ||
-        shape === "piston" || shape === "plate" || shape === "retimer" || shape === "trapdoor");
+        shape === "piston" || shape === "plate" || shape === "retimer" || shape === "trapdoor" || shape === "feeder");
     if (cubeLike) {
     if (cubeLike) {
         const def = BLOCKS[blockId];
         const def = BLOCKS[blockId];
         const meta = def.orient ? 4 : 0;
         const meta = def.orient ? 4 : 0;
         const top = shape === "slab" ? 0.5 : shape === "plate" ? 1 / 16 : shape === "retimer" ? 2 / 16 : shape === "trapdoor" ? 3 / 16 : 1;
         const top = shape === "slab" ? 0.5 : shape === "plate" ? 1 / 16 : shape === "retimer" ? 2 / 16 : shape === "trapdoor" ? 3 / 16 : 1;
         const inset = shape === "cactus" ? 1 / 16 : 0;
         const inset = shape === "cactus" ? 1 / 16 : 0;
-        const boxes = shape === "stairs" ? STAIR_ITEM_BOXES : [[inset, 0, inset, 1 - inset, top, 1 - inset]];
+        const boxes = shape === "stairs" ? STAIR_ITEM_BOXES : shape === "feeder" ? FEEDER_ITEM_BOXES : [[inset, 0, inset, 1 - inset, top, 1 - inset]];
         const tintC = def.tint === "foliage" ? [0.48, 0.86, 0.32] : def.tint === "grass" ? [0.62, 1.0, 0.43] : null;
         const tintC = def.tint === "foliage" ? [0.48, 0.86, 0.32] : def.tint === "grass" ? [0.62, 1.0, 0.43] : null;
         for (let i = 0; i < boxes.length; i++) {
         for (let i = 0; i < boxes.length; i++) {
             const bx = boxes[i];
             const bx = boxes[i];

+ 10 - 2
src/web/Blocky/js/mobs.js

@@ -652,7 +652,8 @@ export class Mobs {
 
 
     /* ---------------- arrows ---------------- */
     /* ---------------- arrows ---------------- */
 
 
-    shootArrow(x, y, z, vx, vy, vz, damage) {
+    //hitsPlayer: a dispenser's arrow, which hurts the player too
+    shootArrow(x, y, z, vx, vy, vz, damage, hitsPlayer = false) {
         const mesh = new THREE.Group();
         const mesh = new THREE.Group();
         const shaft = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.05, 0.6), new THREE.MeshBasicMaterial({ color: 0x8c6a3c }));
         const shaft = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.05, 0.6), new THREE.MeshBasicMaterial({ color: 0x8c6a3c }));
         const head = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.08, 0.1), new THREE.MeshBasicMaterial({ color: 0x5c5c64 }));
         const head = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.08, 0.1), new THREE.MeshBasicMaterial({ color: 0x5c5c64 }));
@@ -661,7 +662,7 @@ export class Mobs {
         fletch.position.z = 0.26;
         fletch.position.z = 0.26;
         mesh.add(shaft, head, fletch);
         mesh.add(shaft, head, fletch);
         this.renderer.scene.add(mesh);
         this.renderer.scene.add(mesh);
-        this.arrows.push({ x, y, z, vx, vy, vz, damage, mesh, stuck: false, life: 60 });
+        this.arrows.push({ x, y, z, vx, vy, vz, damage, mesh, stuck: false, life: 60, hitsPlayer });
     }
     }
 
 
     updateArrows(dt) {
     updateArrows(dt) {
@@ -686,6 +687,13 @@ export class Mobs {
                             break;
                             break;
                         }
                         }
                     }
                     }
+                    if (!remove && a.hitsPlayer && !p.dead) {
+                        const b = p.box();
+                        if (a.x > b[0] - 0.1 && a.x < b[3] + 0.1 && a.y > b[1] && a.y < b[4] + 0.1 && a.z > b[2] - 0.1 && a.z < b[5] + 0.1) {
+                            p.hurt(Math.max(1, Math.round(a.damage * Math.min(1, speed / 40))), "arrow");
+                            remove = true;
+                        }
+                    }
                     const id = w.getBlock(Math.floor(a.x), Math.floor(a.y), Math.floor(a.z));
                     const id = w.getBlock(Math.floor(a.x), Math.floor(a.y), Math.floor(a.z));
                     if (!remove && BLOCKS[id].solid) {
                     if (!remove && BLOCKS[id].solid) {
                         a.stuck = true;
                         a.stuck = true;

+ 21 - 0
src/web/Blocky/js/physics.js

@@ -11,6 +11,27 @@ import { collisionBoxes } from "./shapes.js";
 
 
 const FULL = [0, 0, 0, 1, 1, 1];
 const FULL = [0, 0, 0, 1, 1, 1];
 
 
+//The block [x, y, z] of kind `id` whose collision boxes come within e of
+//`box` (touching it), or null
+export function touchingBlock(world, box, id, e) {
+    for (let x = Math.floor(box[0] - e); x <= Math.floor(box[3] + e); x++) {
+        for (let z = Math.floor(box[2] - e); z <= Math.floor(box[5] + e); z++) {
+            for (let y = Math.floor(box[1] - e); y <= Math.floor(box[4] + e); y++) {
+                if (world.getBlock(x, y, z) !== id) {
+                    continue;
+                }
+                for (const b of collisionBoxes(id, world.getMeta(x, y, z), world, x, y, z)) {
+                    if (box[0] - e < x + b[3] && box[3] + e > x + b[0] && box[1] - e < y + b[4] && box[4] + e > y + b[1] &&
+                        box[2] - e < z + b[5] && box[5] + e > z + b[2]) {
+                        return [x, y, z];
+                    }
+                }
+            }
+        }
+    }
+    return null;
+}
+
 //Collect world boxes overlapping [min, max]
 //Collect world boxes overlapping [min, max]
 export function gatherBoxes(world, minX, minY, minZ, maxX, maxY, maxZ, out) {
 export function gatherBoxes(world, minX, minY, minZ, maxX, maxY, maxZ, out) {
     out.length = 0;
     out.length = 0;

+ 3 - 2
src/web/Blocky/js/player.js

@@ -444,10 +444,11 @@ export class Player {
         } else {
         } else {
             this.air = Math.min(15, this.air + dt * 5);
             this.air = Math.min(15, this.air + dt * 5);
         }
         }
-        //Cactus prickles; a block in your head (fallen sand) suffocates
+        //Cactus prickles (slowly: half a heart a second); a block in your
+        //head (fallen sand) suffocates
         this.cactusTimer = Math.max(0, this.cactusTimer - dt);
         this.cactusTimer = Math.max(0, this.cactusTimer - dt);
         if (this.cactusTimer === 0 && this.touching(B.CACTUS)) {
         if (this.cactusTimer === 0 && this.touching(B.CACTUS)) {
-            this.cactusTimer = 0.5;
+            this.cactusTimer = 1;
             this.hurt(1, "cactus");
             this.hurt(1, "cactus");
         }
         }
         //Fire and lava: damage while touching, then you keep burning a while
         //Fire and lava: damage while touching, then you keep burning a while

+ 69 - 19
src/web/Blocky/js/power.js

@@ -16,28 +16,33 @@
       so torch loops make clocks instead of hanging the game
       so torch loops make clocks instead of hanging the game
 */
 */
 
 
-import { B, BLOCKS, isOpaqueAt, HDIR } from "./blocks.js";
+import { B, BLOCKS, isOpaqueAt, HDIR, railShapeOf } from "./blocks.js";
 import { FACE_DIR } from "./shapes.js";
 import { FACE_DIR } from "./shapes.js";
 
 
 //1 wire, 2 source, 4 reacts, 8 rail
 //1 wire, 2 source, 4 reacts, 8 rail
 export const POWER = new Uint8Array(256);
 export const POWER = new Uint8Array(256);
 POWER[B.SPARK_WIRE] = 1;
 POWER[B.SPARK_WIRE] = 1;
-for (const id of [B.LEVER, B.BUTTON, B.SPARK_TORCH, B.SPARK_BLOCK, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER_ON]) {
+for (const id of [B.LEVER, B.BUTTON, B.SPARK_TORCH, B.SPARK_BLOCK, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER_ON, B.DETECTOR_RAIL]) {
     POWER[id] |= 2;
     POWER[id] |= 2;
 }
 }
 for (const id of [B.SPARK_LAMP, B.SPARK_LAMP_ON, B.PISTON, B.STICKY_PISTON, B.SPARK_TORCH, B.SPARK_TORCH_OFF, B.POWERED_RAIL, B.BUTTON,
 for (const id of [B.SPARK_LAMP, B.SPARK_LAMP_ON, B.PISTON, B.STICKY_PISTON, B.SPARK_TORCH, B.SPARK_TORCH_OFF, B.POWERED_RAIL, B.BUTTON,
-    B.PLATE_WOOD, B.PLATE_STONE, B.DOOR, B.TRAPDOOR, B.RETIMER, B.RETIMER_ON]) {
+    B.PLATE_WOOD, B.PLATE_STONE, B.DOOR, B.TRAPDOOR, B.RETIMER, B.RETIMER_ON, B.DETECTOR_RAIL, B.DISPENSER]) {
     POWER[id] |= 4;
     POWER[id] |= 4;
 }
 }
 //Plain rails react too: a junction is a switch (railSwitch)
 //Plain rails react too: a junction is a switch (railSwitch)
 POWER[B.RAIL] |= 8 | 4;
 POWER[B.RAIL] |= 8 | 4;
 POWER[B.POWERED_RAIL] |= 8;
 POWER[B.POWERED_RAIL] |= 8;
+POWER[B.DETECTOR_RAIL] |= 8;
 
 
 const SIDES = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
 const SIDES = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
 const FLAT = [[1, 0], [-1, 0], [0, 1], [0, -1]];
 const FLAT = [[1, 0], [-1, 0], [0, 1], [0, -1]];
 
 
 const same = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
 const same = (a, b) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
 const isPlate = (id) => id === B.PLATE_WOOD || id === B.PLATE_STONE;
 const isPlate = (id) => id === B.PLATE_WOOD || id === B.PLATE_STONE;
+//Rails that cannot curve
+const straightRail = (id) => id === B.POWERED_RAIL || id === B.DETECTOR_RAIL;
+//A plate or detector rail pressed now (they power the block under them)
+const pressedOn = (id, meta) => (isPlate(id) && (meta & 1) !== 0) || (id === B.DETECTOR_RAIL && (meta & 8) !== 0);
 
 
 //The block a retimer sends its signal into
 //The block a retimer sends its signal into
 function retimerFront(meta, x, y, z) {
 function retimerFront(meta, x, y, z) {
@@ -60,8 +65,8 @@ function sourceOn(id, meta) {
     if (id === B.LEVER || id === B.BUTTON) {
     if (id === B.LEVER || id === B.BUTTON) {
         return (meta & 8) !== 0;
         return (meta & 8) !== 0;
     }
     }
-    if (isPlate(id)) {
-        return (meta & 1) !== 0;
+    if (isPlate(id) || id === B.DETECTOR_RAIL) {
+        return pressedOn(id, meta);
     }
     }
     return id === B.SPARK_TORCH || id === B.SPARK_BLOCK;
     return id === B.SPARK_TORCH || id === B.SPARK_BLOCK;
 }
 }
@@ -80,8 +85,8 @@ export function blockPoweredBySource(w, x, y, z) {
             return true;
             return true;
         }
         }
     }
     }
-    //A pressed plate powers the block it lies on
-    if (isPlate(w.getBlock(x, y + 1, z)) && (w.getMeta(x, y + 1, z) & 1)) {
+    //A pressed plate or detector rail powers the block it lies on
+    if (pressedOn(w.getBlock(x, y + 1, z), w.getMeta(x, y + 1, z))) {
         return true;
         return true;
     }
     }
     return w.getBlock(x, y - 1, z) === B.SPARK_TORCH;
     return w.getBlock(x, y - 1, z) === B.SPARK_TORCH;
@@ -202,7 +207,7 @@ function scheduleParts(w, x, y, z) {
                     continue;
                     continue;
                 }
                 }
                 const id = w.getBlock(x + dx, y + dy, z + dz);
                 const id = w.getBlock(x + dx, y + dy, z + dz);
-                if ((POWER[id] & 4) && id !== B.BUTTON && !isPlate(id)) {
+                if ((POWER[id] & 4) && id !== B.BUTTON && !isPlate(id) && id !== B.DETECTOR_RAIL) {
                     w.schedule(x + dx, y + dy, z + dz, 2);
                     w.schedule(x + dx, y + dy, z + dz, 2);
                 }
                 }
             }
             }
@@ -237,7 +242,7 @@ const FRAGILE = new Set(["cross", "crop", "torch", "wire", "lever", "button", "l
 
 
 function movable(id, meta) {
 function movable(id, meta) {
     if (id === B.BEDROCK || id === B.OBSIDIAN || id === B.PISTON_HEAD || id === B.FURNACE || id === B.FURNACE_LIT ||
     if (id === B.BEDROCK || id === B.OBSIDIAN || id === B.PISTON_HEAD || id === B.FURNACE || id === B.FURNACE_LIT ||
-        id === B.CHEST || id === B.DOOR || id === B.BED || BLOCKS[id].hardness < 0) {
+        id === B.CHEST || id === B.DISPENSER || id === B.FEEDER || id === B.DOOR || id === B.BED || BLOCKS[id].hardness < 0) {
         return false;
         return false;
     }
     }
     if ((id === B.PISTON || id === B.STICKY_PISTON) && (meta & 8)) {
     if ((id === B.PISTON || id === B.STICKY_PISTON) && (meta & 8)) {
@@ -326,7 +331,7 @@ const RAIL_ENDS = [[2, 3], [0, 1], [0, 1], [0, 1], [2, 3], [2, 3], [2, 0], [2, 1
 
 
 function railEnds(w, x, y, z) {
 function railEnds(w, x, y, z) {
     const id = w.getBlock(x, y, z), m = w.getMeta(x, y, z);
     const id = w.getBlock(x, y, z), m = w.getMeta(x, y, z);
-    return RAIL_ENDS[id === B.POWERED_RAIL ? m & 7 : Math.min(9, m & 15)] || RAIL_ENDS[0];
+    return RAIL_ENDS[railShapeOf(id, m)] || RAIL_ENDS[0];
 }
 }
 
 
 //The rail beside (x, y, z) on side k (level, one up or one down)
 //The rail beside (x, y, z) on side k (level, one up or one down)
@@ -383,7 +388,7 @@ export function shapeRail(w, x, y, z, preferX, aim) {
     const id = w.getBlock(x, y, z);
     const id = w.getBlock(x, y, z);
     const cands = railCandidates(w, x, y, z);
     const cands = railCandidates(w, x, y, z);
     let links = cands.map((c) => [c.k, c.dy]);
     let links = cands.map((c) => [c.k, c.dy]);
-    if (cands.length > 2 || (cands.length === 2 && id === B.POWERED_RAIL && (cands[0].k ^ 1) !== cands[1].k)) {
+    if (cands.length > 2 || (cands.length === 2 && straightRail(id) && (cands[0].k ^ 1) !== cands[1].k)) {
         //Best pair: rails leading in count most. Then a plain rail where
         //Best pair: rails leading in count most. Then a plain rail where
         //three or four tracks meet curves (a switch, see railSwitch) toward
         //three or four tracks meet curves (a switch, see railSwitch) toward
         //the side clicked, else south-east like MC; a powered rail, which
         //the side clicked, else south-east like MC; a powered rail, which
@@ -393,7 +398,7 @@ export function shapeRail(w, x, y, z, preferX, aim) {
         for (let i = 0; i < cands.length; i++) {
         for (let i = 0; i < cands.length; i++) {
             for (let j = i + 1; j < cands.length; j++) {
             for (let j = i + 1; j < cands.length; j++) {
                 const a = cands[i], b = cands[j], straight = (a.k ^ 1) === b.k;
                 const a = cands[i], b = cands[j], straight = (a.k ^ 1) === b.k;
-                if (!straight && id === B.POWERED_RAIL) {
+                if (!straight && straightRail(id)) {
                     continue;
                     continue;
                 }
                 }
                 const toward = straight ? 0 : (FLAT[a.k][0] + FLAT[b.k][0]) * ax + (FLAT[a.k][1] + FLAT[b.k][1]) * az;
                 const toward = straight ? 0 : (FLAT[a.k][0] + FLAT[b.k][0]) * ax + (FLAT[a.k][1] + FLAT[b.k][1]) * az;
@@ -407,7 +412,7 @@ export function shapeRail(w, x, y, z, preferX, aim) {
         if (best) {
         if (best) {
             links = best.map((c) => [c.k, c.dy]);
             links = best.map((c) => [c.k, c.dy]);
         } else {
         } else {
-            //A powered rail with only bends on offer: run toward one of them
+            //A straight-only rail with only bends on offer: run toward one of them
             const c = cands.find((v) => v.back) || cands[0];
             const c = cands.find((v) => v.back) || cands[0];
             links = [[c.k, c.dy]];
             links = [[c.k, c.dy]];
         }
         }
@@ -436,8 +441,8 @@ export function shapeRail(w, x, y, z, preferX, aim) {
         return;
         return;
     }
     }
     const meta = w.getMeta(x, y, z);
     const meta = w.getMeta(x, y, z);
-    const keep = id === B.POWERED_RAIL ? meta & 8 : 0;
-    if ((id === B.POWERED_RAIL ? meta & 7 : meta) !== shape) {
+    const keep = straightRail(id) ? meta & 8 : 0;
+    if ((straightRail(id) ? meta & 7 : meta) !== shape) {
         w.setBlock(x, y, z, id, shape | keep, false);
         w.setBlock(x, y, z, id, shape | keep, false);
     }
     }
 }
 }
@@ -483,7 +488,7 @@ function openUTurn(w, x, y, z) {
 //A new rail: shape it, then let the neighbours it leads into turn toward
 //A new rail: shape it, then let the neighbours it leads into turn toward
 //it, unless they are already joined at both ends
 //it, unless they are already joined at both ends
 export function railPlaced(w, x, y, z, preferX, aim) {
 export function railPlaced(w, x, y, z, preferX, aim) {
-    if (w.getBlock(x, y, z) === B.RAIL || w.getBlock(x, y, z) === B.POWERED_RAIL) {
+    if (POWER[w.getBlock(x, y, z)] & 8) {
         openUTurn(w, x, y, z);
         openUTurn(w, x, y, z);
     }
     }
     shapeRail(w, x, y, z, preferX, aim);
     shapeRail(w, x, y, z, preferX, aim);
@@ -541,17 +546,21 @@ export function railAxis(shape) {
     return shape === 1 || shape === 2 || shape === 3 ? [1, 0] : [0, 1];
     return shape === 1 || shape === 2 || shape === 3 ? [1, 0] : [0, 1];
 }
 }
 
 
+//Follows the line both ways from the rail before, so a chain climbing a
+//slope keeps going (each rail one up or down from the last)
 function railChainPowered(w, x, y, z, shape) {
 function railChainPowered(w, x, y, z, shape) {
     const [ax, az] = railAxis(shape);
     const [ax, az] = railAxis(shape);
     for (const s of [1, -1]) {
     for (const s of [1, -1]) {
+        let cy = y;
         for (let k = 1; k <= 8; k++) {
         for (let k = 1; k <= 8; k++) {
             let found = false;
             let found = false;
             for (const dy of [0, 1, -1]) {
             for (const dy of [0, 1, -1]) {
-                const px = x + ax * k * s, py = y + dy, pz = z + az * k * s;
+                const px = x + ax * k * s, py = cy + dy, pz = z + az * k * s;
                 if (w.getBlock(px, py, pz) === B.POWERED_RAIL) {
                 if (w.getBlock(px, py, pz) === B.POWERED_RAIL) {
                     if (isPowered(w, px, py, pz)) {
                     if (isPowered(w, px, py, pz)) {
                         return true;
                         return true;
                     }
                     }
+                    cy = py;
                     found = true;
                     found = true;
                     break;
                     break;
                 }
                 }
@@ -574,6 +583,19 @@ export function pressButton(w, x, y, z, meta) {
     w.schedule(x, y, z, 20);
     w.schedule(x, y, z, 20);
 }
 }
 
 
+//A cart is on a detector rail: switch it on, and keep it on for 20 ticks
+//after the last cart has left. True when it just switched on.
+export function pressDetector(w, x, y, z) {
+    w.buttonDue.set(x + "," + y + "," + z, w.tickCount + 20);
+    const m = w.getMeta(x, y, z);
+    if (m & 8) {
+        return false;
+    }
+    w.setBlock(x, y, z, B.DETECTOR_RAIL, m | 8);
+    w.schedule(x, y, z, 20);
+    return true;
+}
+
 //Something is on a plate: press it, and keep it down for 20 ticks after
 //Something is on a plate: press it, and keep it down for 20 ticks after
 //the last time anything was on it. True when it was just pressed.
 //the last time anything was on it. True when it was just pressed.
 export function pressPlate(w, x, y, z) {
 export function pressPlate(w, x, y, z) {
@@ -724,6 +746,17 @@ export function powerTick(w, x, y, z, id, meta, sound) {
             }
             }
             break;
             break;
         }
         }
+        case B.DISPENSER: {
+            //Fires once each time power arrives (bit 8 remembers it is on)
+            const powered = isPowered(w, x, y, z);
+            if (powered !== ((meta & 8) !== 0)) {
+                w.setBlock(x, y, z, B.DISPENSER, (meta & 7) | (powered ? 8 : 0), false);
+                if (powered && w.onDispense) {
+                    w.onDispense(x, y, z, meta & 7);
+                }
+            }
+            break;
+        }
         case B.TRAPDOOR: {
         case B.TRAPDOOR: {
             //Like a door: opens when power arrives, shuts when it goes, and
             //Like a door: opens when power arrives, shuts when it goes, and
             //can still be worked by hand in between
             //can still be worked by hand in between
@@ -747,11 +780,28 @@ export function powerTick(w, x, y, z, id, meta, sound) {
             break;
             break;
         }
         }
         case B.RAIL:
         case B.RAIL:
-        case B.POWERED_RAIL: {
+        case B.POWERED_RAIL:
+        case B.DETECTOR_RAIL: {
             if (railLinks(w, x, y, z).length < 2) {
             if (railLinks(w, x, y, z).length < 2) {
                 //Keep to the axis it lies on now
                 //Keep to the axis it lies on now
                 const m = w.getMeta(x, y, z);
                 const m = w.getMeta(x, y, z);
-                shapeRail(w, x, y, z, railAxis(id === B.POWERED_RAIL ? m & 7 : m & 15)[0] === 1);
+                shapeRail(w, x, y, z, railAxis(railShapeOf(id, m))[0] === 1);
+            }
+            if (id === B.DETECTOR_RAIL) {
+                //Off once no cart has been on it for 20 ticks
+                const m = w.getMeta(x, y, z);
+                const key = x + "," + y + "," + z;
+                const due = w.buttonDue.get(key);
+                if (!(m & 8)) {
+                    break;
+                }
+                if (due > w.tickCount) {
+                    w.schedule(x, y, z, due - w.tickCount);
+                    break;
+                }
+                w.buttonDue.delete(key);
+                w.setBlock(x, y, z, B.DETECTOR_RAIL, m & 7);
+                break;
             }
             }
             if (id === B.RAIL) {
             if (id === B.RAIL) {
                 railSwitch(w, x, y, z);
                 railSwitch(w, x, y, z);

+ 31 - 1
src/web/Blocky/js/shapes.js

@@ -53,6 +53,15 @@ const U = 1 / 16;
 export const LEVER_BASE = [5 * U, 0, 4 * U, 11 * U, 3 * U, 12 * U];
 export const LEVER_BASE = [5 * U, 0, 4 * U, 11 * U, 3 * U, 12 * U];
 export const BUTTON_BOX = [5 * U, 0, 6 * U, 11 * U, 2 * U, 10 * U];
 export const BUTTON_BOX = [5 * U, 0, 6 * U, 11 * U, 2 * U, 10 * U];
 export const BUTTON_PRESSED = [5 * U, 0, 6 * U, 11 * U, 1 * U, 10 * U];
 export const BUTTON_PRESSED = [5 * U, 0, 6 * U, 11 * U, 1 * U, 10 * U];
+
+//A button in model space (facing up) for meta: on a wall it is always 6 px
+//wide and 4 px tall. The turn onto a wall facing x maps the model's x to
+//world y, so there its x and z swap.
+export function buttonBox(meta) {
+    const b = meta & 8 ? BUTTON_PRESSED : BUTTON_BOX;
+    const f = meta & 7;
+    return f === 0 || f === 1 ? [b[2], b[1], b[0], b[5], b[4], b[3]] : b;
+}
 export const PISTON_BASE = [0, 0, 0, 1, 12 * U, 1];
 export const PISTON_BASE = [0, 0, 0, 1, 12 * U, 1];
 export const HEAD_PLATE = [0, 12 * U, 0, 1, 1, 1];
 export const HEAD_PLATE = [0, 12 * U, 0, 1, 1, 1];
 export const HEAD_ROD = [6 * U, -4 * U, 6 * U, 10 * U, 12 * U, 10 * U];
 export const HEAD_ROD = [6 * U, -4 * U, 6 * U, 10 * U, 12 * U, 10 * U];
@@ -253,11 +262,32 @@ function fenceBoxes(world, x, y, z, top) {
     return out;
     return out;
 }
 }
 
 
+//Feeder: a bowl (floor and four rim walls), a narrower body and a spout
+//toward the face it feeds out of (meta 3 down, else a side)
+const FEEDER_BOWL = [
+    [0, 10 * U, 0, 1, 11 * U, 1],
+    [0, 11 * U, 0, 2 * U, 1, 1], [14 * U, 11 * U, 0, 1, 1, 1],
+    [2 * U, 11 * U, 0, 14 * U, 1, 2 * U], [2 * U, 11 * U, 14 * U, 14 * U, 1, 1],
+    [4 * U, 4 * U, 4 * U, 12 * U, 10 * U, 12 * U]
+];
+const FEEDER_SPOUT = {
+    3: [6 * U, 0, 6 * U, 10 * U, 4 * U, 10 * U],
+    0: [12 * U, 4 * U, 6 * U, 1, 8 * U, 10 * U],
+    1: [0, 4 * U, 6 * U, 4 * U, 8 * U, 10 * U],
+    4: [6 * U, 4 * U, 12 * U, 10 * U, 8 * U, 1],
+    5: [6 * U, 4 * U, 0, 10 * U, 8 * U, 4 * U]
+};
+export function feederBoxes(meta) {
+    return FEEDER_BOWL.concat([FEEDER_SPOUT[meta & 7] || FEEDER_SPOUT[3]]);
+}
+
 export function collisionBoxes(id, meta, world, x, y, z) {
 export function collisionBoxes(id, meta, world, x, y, z) {
     if (!SOLID[id]) {
     if (!SOLID[id]) {
         return NONE;
         return NONE;
     }
     }
     switch (SHAPE[id]) {
     switch (SHAPE[id]) {
+        case "feeder":
+            return feederBoxes(meta);
         case "slab":
         case "slab":
             if (meta === 2) {
             if (meta === 2) {
                 return [FULL];
                 return [FULL];
@@ -364,7 +394,7 @@ export function selectionBox(id, meta, world, x, y, z) {
         case "lever":
         case "lever":
             return rotateBox(meta & 7, [4 * U, 0, 4 * U, 12 * U, 9 * U, 12 * U]);
             return rotateBox(meta & 7, [4 * U, 0, 4 * U, 12 * U, 9 * U, 12 * U]);
         case "button":
         case "button":
-            return rotateBox(meta & 7, BUTTON_BOX);
+            return rotateBox(meta & 7, buttonBox(meta & 7));
         case "sign": {
         case "sign": {
             if (id !== B.WALL_SIGN) {
             if (id !== B.WALL_SIGN) {
                 return [0.25, 0, 0.25, 0.75, 1, 0.75];
                 return [0.25, 0, 0.25, 0.75, 1, 0.75];

+ 53 - 0
src/web/Blocky/js/textures.js

@@ -1326,6 +1326,53 @@ function paintRail(t, kind) {
             t.set(8, y, kind === "on" ? [255, 90, 70] : [106, 30, 24]);
             t.set(8, y, kind === "on" ? [255, 90, 70] : [106, 30, 24]);
         }
         }
     }
     }
+    if (kind === "detector" || kind === "detector_on") {
+        //A stone sensor plate between the rails with a spark lens in it
+        t.rect(5, 4, 6, 8, [128, 128, 132], 8);
+        t.rect(5, 4, 6, 1, [156, 156, 160]);
+        t.rect(5, 11, 6, 1, [92, 92, 96]);
+        const on = kind === "detector_on";
+        t.rect(7, 6, 2, 4, on ? [255, 52, 40] : [96, 24, 20]);
+        t.set(7, 6, on ? [255, 140, 110] : [120, 36, 30]);
+    }
+}
+
+//Feeder: dark iron plates; the top shows the rim around a darker bowl
+function paintFeeder(t, top) {
+    t.clear();
+    t.rect(0, 0, 16, 16, [70, 72, 78], 10);
+    for (let i = 0; i < 16; i++) {
+        t.set(i, 0, [96, 98, 104]);
+        t.set(0, i, [96, 98, 104]);
+        t.set(i, 15, [44, 46, 50]);
+        t.set(15, i, [44, 46, 50]);
+    }
+    if (top) {
+        t.rect(2, 2, 12, 12, [38, 40, 44], 6);
+        for (let k = 4; k < 13; k += 4) {
+            t.rect(k, 2, 1, 12, [28, 29, 32]);
+            t.rect(2, k, 12, 1, [28, 29, 32]);
+        }
+    } else {
+        for (const y of [5, 10]) {
+            t.rect(1, y, 14, 1, [54, 56, 60]);
+        }
+    }
+}
+
+//Dispenser front: the furnace's stone with a dark round mouth (the
+//vertical one, facing up or down, has a stone rim all round)
+function paintDispenserFront(t, vertical) {
+    paintFurnaceSide(t);
+    const c = 7.5, r = vertical ? 4.2 : 4.6;
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            const d = Math.hypot(x - c, y - (vertical ? c : 8.5));
+            if (d < r) {
+                t.set(x, y, d < r - 1.2 ? [22, 22, 24] : [52, 52, 56]);
+            }
+        }
+    }
 }
 }
 
 
 function paintLeverItem(t) {
 function paintLeverItem(t) {
@@ -1845,6 +1892,12 @@ Object.assign(PAINTERS, {
     rail_curve: (t) => paintRail(t, "curve"),
     rail_curve: (t) => paintRail(t, "curve"),
     powered_rail: (t) => paintRail(t, "powered"),
     powered_rail: (t) => paintRail(t, "powered"),
     powered_rail_on: (t) => paintRail(t, "on"),
     powered_rail_on: (t) => paintRail(t, "on"),
+    detector_rail: (t) => paintRail(t, "detector"),
+    detector_rail_on: (t) => paintRail(t, "detector_on"),
+    feeder_side: (t) => paintFeeder(t, false),
+    feeder_top: (t) => paintFeeder(t, true),
+    dispenser_front: (t) => paintDispenserFront(t, false),
+    dispenser_front_v: (t) => paintDispenserFront(t, true),
     lever_item: paintLeverItem,
     lever_item: paintLeverItem,
     button_item: paintButtonItem,
     button_item: paintButtonItem,
     iron_bars: paintIronBars,
     iron_bars: paintIronBars,

+ 10 - 2
src/web/Blocky/js/ui.js

@@ -374,6 +374,14 @@ export class UI {
                     cs += this.slotHtml("te:" + i);
                     cs += this.slotHtml("te:" + i);
                 }
                 }
                 html = `<div class="scr-col"><h3>Chest</h3><div class="slots grid9">${cs}</div>${this.invSection("Inventory")}</div>`;
                 html = `<div class="scr-col"><h3>Chest</h3><div class="slots grid9">${cs}</div>${this.invSection("Inventory")}</div>`;
+            } else if (s.kind === "dispenser" || s.kind === "feeder") {
+                const n = s.te.slots.length;
+                let cs = "";
+                for (let i = 0; i < n; i++) {
+                    cs += this.slotHtml("te:" + i);
+                }
+                const title = s.kind === "dispenser" ? "Dispenser" : "Feeder";
+                html = `<div class="scr-col"><h3>${title}</h3><div class="slots machine n${n}">${cs}</div>${this.invSection("Inventory")}</div>`;
             } else {
             } else {
                 const bench = s.kind === "workbench";
                 const bench = s.kind === "workbench";
                 let cells = "";
                 let cells = "";
@@ -852,8 +860,8 @@ export class UI {
         let targets;
         let targets;
         if (ref.startsWith("te:") || ref.startsWith("craft:")) {
         if (ref.startsWith("te:") || ref.startsWith("craft:")) {
             targets = range("inv:", 9, 36).concat(range("inv:", 0, 9));
             targets = range("inv:", 9, 36).concat(range("inv:", 0, 9));
-        } else if (kind === "chest") {
-            targets = range("te:", 0, 27);
+        } else if (kind === "chest" || kind === "dispenser" || kind === "feeder") {
+            targets = range("te:", 0, this.screen.te.slots.length);
         } else if (kind === "furnace" && SMELTING.has(s.id)) {
         } else if (kind === "furnace" && SMELTING.has(s.id)) {
             targets = ["te:0"];
             targets = ["te:0"];
         } else if (kind === "furnace" && fuelTicks(s.id) > 0) {
         } else if (kind === "furnace" && fuelTicks(s.id) > 0) {

+ 17 - 5
src/web/Blocky/js/world.js

@@ -24,7 +24,7 @@ import {
 import { TerrainGen, WORLD_H, SEA, idx, BIOME } from "./worldgen.js";
 import { TerrainGen, WORLD_H, SEA, idx, BIOME } from "./worldgen.js";
 import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32, hash3 } from "./util.js";
 import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32, hash3 } from "./util.js";
 import { FACE_DIR, doorHinge, waterHeight } from "./shapes.js";
 import { FACE_DIR, doorHinge, waterHeight } from "./shapes.js";
-import { POWER, powerTick, powerChanged, railPlaced, pressButton, pressPlate } from "./power.js";
+import { POWER, powerTick, powerChanged, railPlaced, pressButton, pressPlate, pressDetector } from "./power.js";
 
 
 export const SECTIONS = WORLD_H / 16;
 export const SECTIONS = WORLD_H / 16;
 
 
@@ -51,6 +51,11 @@ function flatTop(id, meta) {
 
 
 const DIRS = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
 const DIRS = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
 
 
+//Slots of the container tile entities other than the furnace's three
+export const TE_SLOTS = { chest: 27, dispenser: 9, feeder: 5 };
+//Blocks whose `interact` names one of these keep their items in a tile entity
+export const TE_KINDS = new Set(["furnace", "chest", "dispenser", "feeder"]);
+
 //Liquid behaviour: ticks between updates, level lost per block, last level
 //Liquid behaviour: ticks between updates, level lost per block, last level
 const LIQUID = {
 const LIQUID = {
     [B.WATER]: { delay: 5, step: 1, max: 7, renew: true },
     [B.WATER]: { delay: 5, step: 1, max: 7, renew: true },
@@ -106,6 +111,7 @@ export class World {
         this.onFizz = opts.onFizz || null;
         this.onFizz = opts.onFizz || null;
         this.onPowerSound = opts.onPowerSound || null;
         this.onPowerSound = opts.onPowerSound || null;
         this.onPistonPush = opts.onPistonPush || null;
         this.onPistonPush = opts.onPistonPush || null;
+        this.onDispense = opts.onDispense || null;
         this.powerBusy = false;
         this.powerBusy = false;
         this.pistonMoving = false;
         this.pistonMoving = false;
         this.buttonDue = new Map();
         this.buttonDue = new Map();
@@ -261,7 +267,8 @@ export class World {
                 this.doorAdopt.add(x + "," + y + "," + z);
                 this.doorAdopt.add(x + "," + y + "," + z);
                 this.schedule(x, y, z, 5 + Math.floor(this.rng() * 30));
                 this.schedule(x, y, z, 5 + Math.floor(this.rng() * 30));
             } else if (id === B.FIRE || ((id === B.WATER || id === B.LAVA) && c.meta[i] !== 0) || (id === B.BUTTON && (c.meta[i] & 8)) ||
             } else if (id === B.FIRE || ((id === B.WATER || id === B.LAVA) && c.meta[i] !== 0) || (id === B.BUTTON && (c.meta[i] & 8)) ||
-                ((id === B.PLATE_WOOD || id === B.PLATE_STONE) && (c.meta[i] & 1)) || id === B.RETIMER || id === B.RETIMER_ON) {
+                ((id === B.PLATE_WOOD || id === B.PLATE_STONE) && (c.meta[i] & 1)) || (id === B.DETECTOR_RAIL && (c.meta[i] & 8)) ||
+                id === B.RETIMER || id === B.RETIMER_ON) {
                 this.schedule(bx + (i >> 11), i & 127, bz + ((i >> 7) & 15), 5 + Math.floor(this.rng() * 30));
                 this.schedule(bx + (i >> 11), i & 127, bz + ((i >> 7) & 15), 5 + Math.floor(this.rng() * 30));
             }
             }
         }
         }
@@ -670,7 +677,7 @@ export class World {
             if ((oldId === B.LOG || oldId === B.LEAVES) && id !== B.LOG) {
             if ((oldId === B.LOG || oldId === B.LEAVES) && id !== B.LOG) {
                 this.scheduleLeafChecks(x, y, z);
                 this.scheduleLeafChecks(x, y, z);
             }
             }
-            if (oldId === B.FURNACE || oldId === B.FURNACE_LIT || oldId === B.CHEST) {
+            if (oldId === B.FURNACE || oldId === B.FURNACE_LIT || oldId === B.CHEST || oldId === B.FEEDER || oldId === B.DISPENSER) {
                 if (id !== B.FURNACE && id !== B.FURNACE_LIT) {
                 if (id !== B.FURNACE && id !== B.FURNACE_LIT) {
                     this.dropTileEntity(x, y, z);
                     this.dropTileEntity(x, y, z);
                 }
                 }
@@ -787,7 +794,8 @@ export class World {
             case "soil":
             case "soil":
                 return below === B.GRASS || below === B.DIRT || below === B.FARMLAND;
                 return below === B.GRASS || below === B.DIRT || below === B.FARMLAND;
             case "solid":
             case "solid":
-                return isOpaqueAt(below, belowMeta);
+                //(a feeder's flat rim holds rails, wire and the like too)
+                return isOpaqueAt(below, belowMeta) || below === B.FEEDER;
             case "plate":
             case "plate":
                 return isOpaqueAt(below, belowMeta) || flatTop(below, belowMeta);
                 return isOpaqueAt(below, belowMeta) || flatTop(below, belowMeta);
             case "sand":
             case "sand":
@@ -903,6 +911,10 @@ export class World {
         }
         }
     }
     }
 
 
+    pressDetector(x, y, z) {
+        return pressDetector(this, x, y, z);
+    }
+
     pressPlate(x, y, z) {
     pressPlate(x, y, z) {
         return pressPlate(this, x, y, z);
         return pressPlate(this, x, y, z);
     }
     }
@@ -1529,7 +1541,7 @@ export class World {
     createTileEntity(x, y, z, type) {
     createTileEntity(x, y, z, type) {
         const te = type === "furnace"
         const te = type === "furnace"
             ? { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 }
             ? { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 }
-            : { type, slots: new Array(27).fill(null) };
+            : { type, slots: new Array(TE_SLOTS[type] || 27).fill(null) };
         this.tileEntities.set(this.teKey(x, y, z), te);
         this.tileEntities.set(this.teKey(x, y, z), te);
         return te;
         return te;
     }
     }

+ 13 - 9
src/web/Blocky/js/worldedit.js

@@ -25,7 +25,7 @@
 */
 */
 
 
 import { B, I, BLOCKS, SHAPE, SOLID, HDIR, toolId, facingFromYaw } from "./blocks.js";
 import { B, I, BLOCKS, SHAPE, SOLID, HDIR, toolId, facingFromYaw } from "./blocks.js";
-import { Chunk, WORLD_H } from "./world.js";
+import { Chunk, WORLD_H, TE_SLOTS } from "./world.js";
 import { FACE_DIR, doorHinge, selectionBox } from "./shapes.js";
 import { FACE_DIR, doorHinge, selectionBox } from "./shapes.js";
 import { POWER } from "./power.js";
 import { POWER } from "./power.js";
 import { chunkKey, clamp } from "./util.js";
 import { chunkKey, clamp } from "./util.js";
@@ -58,11 +58,13 @@ export const plural = (n, word) => `${fmt(n)} ${word}${n === 1 ? "" : "s"}`;
 const TE_TYPE = new Array(256).fill(null);
 const TE_TYPE = new Array(256).fill(null);
 TE_TYPE[B.FURNACE] = TE_TYPE[B.FURNACE_LIT] = "furnace";
 TE_TYPE[B.FURNACE] = TE_TYPE[B.FURNACE_LIT] = "furnace";
 TE_TYPE[B.CHEST] = "chest";
 TE_TYPE[B.CHEST] = "chest";
+TE_TYPE[B.DISPENSER] = "dispenser";
+TE_TYPE[B.FEEDER] = "feeder";
 TE_TYPE[B.SIGN] = TE_TYPE[B.WALL_SIGN] = "sign";
 TE_TYPE[B.SIGN] = TE_TYPE[B.WALL_SIGN] = "sign";
 
 
 //Blocks whose position may be a key in the world's power maps
 //Blocks whose position may be a key in the world's power maps
 const KEYED = new Uint8Array(256);
 const KEYED = new Uint8Array(256);
-for (const id of [B.DOOR, B.TRAPDOOR, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.RETIMER_ON]) {
+for (const id of [B.DOOR, B.TRAPDOOR, B.BUTTON, B.PLATE_WOOD, B.PLATE_STONE, B.RETIMER, B.RETIMER_ON, B.DETECTOR_RAIL]) {
     KEYED[id] = 1;
     KEYED[id] = 1;
 }
 }
 
 
@@ -73,8 +75,8 @@ function defaultTE(type) {
     if (type === "furnace") {
     if (type === "furnace") {
         return { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 };
         return { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 };
     }
     }
-    if (type === "chest") {
-        return { type, slots: new Array(27).fill(null) };
+    if (TE_SLOTS[type]) {
+        return { type, slots: new Array(TE_SLOTS[type]).fill(null) };
     }
     }
     return { type, lines: ["", "", "", ""], ver: 0 };
     return { type, lines: ["", "", "", ""], ver: 0 };
 }
 }
@@ -638,9 +640,11 @@ export function flipMatrix(dir) {
 }
 }
 
 
 //Meta kinds: a face index in bits 0-2 (1: any face, 2: sides only, 3: not
 //Meta kinds: a face index in bits 0-2 (1: any face, 2: sides only, 3: not
-//hanging from a ceiling), or a horizontal facing (HDIR) in bits 0-1
+//hanging from a ceiling, 4: never up - a feeder's spout), or a horizontal
+//facing (HDIR) in bits 0-1
 const FACE_KIND = new Uint8Array(256);
 const FACE_KIND = new Uint8Array(256);
-for (const id of [B.LEVER, B.BUTTON, B.PISTON, B.STICKY_PISTON, B.PISTON_HEAD]) {
+FACE_KIND[B.FEEDER] = 4;
+for (const id of [B.LEVER, B.BUTTON, B.PISTON, B.STICKY_PISTON, B.PISTON_HEAD, B.DISPENSER]) {
     FACE_KIND[id] = 1;
     FACE_KIND[id] = 1;
 }
 }
 for (const id of [B.LADDER, B.WALL_SIGN, B.FURNACE, B.FURNACE_LIT, B.CHEST]) {
 for (const id of [B.LADDER, B.WALL_SIGN, B.FURNACE, B.FURNACE_LIT, B.CHEST]) {
@@ -675,7 +679,7 @@ export function transformMeta(id, meta, M) {
             return meta;
             return meta;
         }
         }
         const nf = faceIndex(mul(M, ...FACE_DIR[f]));
         const nf = faceIndex(mul(M, ...FACE_DIR[f]));
-        if (nf < 0 || (fk === 2 && (nf === 2 || nf === 3)) || (fk === 3 && nf === 3)) {
+        if (nf < 0 || (fk === 2 && (nf === 2 || nf === 3)) || (fk === 3 && nf === 3) || (fk === 4 && nf === 2)) {
             return meta;
             return meta;
         }
         }
         return (meta & ~7) | nf;
         return (meta & ~7) | nf;
@@ -722,11 +726,11 @@ export function transformMeta(id, meta, M) {
         const step = Math.round(Math.atan2(v[0], v[2]) / (Math.PI / 8));
         const step = Math.round(Math.atan2(v[0], v[2]) / (Math.PI / 8));
         return (meta & ~15) | (((step % 16) + 16) % 16);
         return (meta & ~15) | (((step % 16) + 16) % 16);
     }
     }
-    if (id === B.RAIL || id === B.POWERED_RAIL) {
+    if (SHAPE[id] === "rail") {
         if (!yStays) {
         if (!yStays) {
             return meta;
             return meta;
         }
         }
-        const bits = id === B.POWERED_RAIL ? 7 : 15;
+        const bits = id === B.RAIL ? 15 : 7;
         const shape = meta & bits, keep = meta & ~bits;
         const shape = meta & bits, keep = meta & ~bits;
         const turn = (k) => {
         const turn = (k) => {
             const v = mul(M, FLAT[k][0], 0, FLAT[k][1]);
             const v = mul(M, FLAT[k][0], 0, FLAT[k][1]);