Sign in
mod

Rails and carts

by Potluck · version 1 · Checked for all ages

Lay rails and ride a cart along them. Rails join the rails beside them by themselves, bending around corners and sloping up a block. Powered rails beside live wire, a pulled lever or a lit inverter speed a cart up, and without power they slow it to a stop. Make rails, powered rails and carts at a workbench.

1--!strict
2-- Rails and carts. Lay Rails and they join the rails beside them by
3-- themselves: straight on, around a corner (a Rail bend) and up or down a
4-- block (a Rail slope). Put a Cart on a rail and climb in (Interact): Push
5-- off sets it rolling, away from where you climbed in from, Brake slows it
6-- to a stop, and Interact or Crouch gets you out. Bop an empty cart to take
7-- it back.
8-- A cart follows the rails with self:follow (world 0.23): no gravity, and
9-- it gathers and loses speed gently, so the ride is as calm as a balloon's.
10-- It slows going up a slope (and rolls back if it can't make it), speeds up
11-- coming down, and coasts to a stop on the flat. A Powered rail with power
12-- beside it (live wire, a pulled lever, or a lit inverter or delay facing
13-- it) sends a cart on fast, or sets a resting one off; without power it
14-- stops it. Carts are kept with the world.
15
16local world = require("@potluck/world@0.23")
17local tweak = require("@potluck/tweak")
18local input = require("@potluck/input@0.1")
19local ui = require("@potluck/ui@0.2")
20local sound = require("@potluck/sound@0.2")
21local store = require("@potluck/store")
22
23local knobs = tweak {
24 push = { 3, min = 1, max = 6, label = "How fast a push sends a cart", order = 1 },
25 fast = { 8, min = 3, max = 12, label = "How fast powered rails send it", order = 2 },
26 hills = { 3, min = 0.5, max = 6, label = "How much slopes slow it and speed it up", order = 3 },
27 coast = { 0.2, min = 0, max = 2, label = "How quickly it slows on the flat", order = 4 },
28 wood = { "#8a5a2b", label = "The cart's planks", order = 5 },
29}
30
31local RAIL, POWERED, BEND, SLOPE, CART = "Rail", "Powered rail", "Rail bend", "Rail slope", "Cart"
32local IS_RAIL = { [RAIL] = true, [POWERED] = true, [BEND] = true, [SLOPE] = true }
33
34-- The four ways, and what's behind and to the right of each.
35local D: { [string]: vector } = {
36 north = vector.create(0, 0, -1),
37 east = vector.create(1, 0, 0),
38 south = vector.create(0, 0, 1),
39 west = vector.create(-1, 0, 0),
40}
41local ORDER = { "north", "east", "south", "west" }
42local BACK = { north = "south", east = "west", south = "north", west = "east" }
43local RIGHT = { north = "east", east = "south", south = "west", west = "north" }
44local UP = vector.create(0, 1, 0)
45-- how high a cart's feet are above the block a rail is on (its wheels are
46-- drawn a little higher, on the rail)
47local LIFT = 0
48local WHEELS = 2 / 16
49-- the fastest anything goes along a path (world 0.23)
50local TOP = 12
51
52-- ---- the rails ----
53
54local function rail(c: vector): (string?, string)
55 local b = world.block(c)
56 if IS_RAIL[b] then
57 return b, world.facing(c) or "north"
58 end
59 return nil, "north"
60end
61
62-- A rail's end on side d: 0 at its own height, 1 a block up (a slope's
63-- high end), nil if it has none there. A rail runs the way it faces, a bend
64-- joins the side behind it to the side on its right, and a slope climbs
65-- the way it faces.
66local function end_up(c: vector, d: string): number?
67 local b, f = rail(c)
68 if b == nil then
69 return nil
70 elseif b == BEND then
71 return if d == BACK[f] or d == RIGHT[f] then 0 else nil
72 elseif b == SLOPE then
73 return if d == f then 1 elseif d == BACK[f] then 0 else nil
74 end
75 return if d == f or d == BACK[f] then 0 else nil
76end
77
78-- The rail joined to this one's end on side d, if there is one: level, a
79-- block up or a block down.
80local function link(c: vector, d: string): vector?
81 local up = end_up(c, d)
82 if up == nil then
83 return nil
84 end
85 for nu = 0, 1 do
86 local n = c + D[d] + vector.create(0, up - nu, 0)
87 if end_up(n, BACK[d]) == nu then
88 return n
89 end
90 end
91 return nil
92end
93
94-- A rail's other end, from one of them.
95local function other(c: vector, d: string): string?
96 for _, e in ORDER do
97 if e ~= d and end_up(c, e) ~= nil then
98 return e
99 end
100 end
101 return nil
102end
103
104-- the rail under a cart (on a slope's high edge, the slope or what's past it)
105local function under(p: vector): vector?
106 local c = vector.create(math.floor(p.x), math.floor(p.y + 0.25), math.floor(p.z))
107 if rail(c) then
108 return c
109 end
110 c -= UP
111 if rail(c) then
112 return c
113 end
114 return nil
115end
116
117-- ---- the way through them ----
118
119local function middle(c: vector): vector
120 return c + vector.create(0.5, LIFT + (if rail(c) == SLOPE then 0.5 else 0), 0.5)
121end
122
123-- the middle of a rail's side s, at its height there
124local function edge(c: vector, s: string): vector
125 return c + vector.create(0.5, LIFT + (end_up(c, s) or 0), 0.5) + D[s] * 0.5
126end
127
128-- The points a cart goes through on a rail it comes onto at side s and
129-- leaves by side out: around a bend in a quarter circle.
130local function through(c: vector, s: string, out: string?): { vector }
131 local pts = { edge(c, s) }
132 if rail(c) == BEND and out then
133 local corner = middle(c) + (D[s] + D[out]) * 0.5
134 for _, t in { 22.5, 45, 67.5 } do
135 local a = math.rad(t)
136 table.insert(pts, corner - D[out] * (0.5 * math.cos(a)) - D[s] * (0.5 * math.sin(a)))
137 end
138 else
139 table.insert(pts, middle(c))
140 end
141 return pts
142end
143
144-- what's beside a powered rail that powers it
145local function powered(c: vector): boolean
146 for _, d in ORDER do
147 local q = c + D[d]
148 local b = world.block(q)
149 if b == "Live wire" or b == "Pulled lever" then
150 return true
151 end
152 if (b == "Lit inverter" or b == "Lit delay") and world.facing(q) == BACK[d] then
153 return true
154 end
155 end
156 local b = world.block(c - UP)
157 return b == "Live wire" or b == "Pulled lever"
158end
159
160-- ---- carts ----
161
162local WHEEL = "#3b3b40"
163local IRON = "#a7adb4"
164
165local function body(): { any }
166 local wood = knobs.wood
167 local parts = {
168 { "plank floor", size = { 0.8, 0.08, 1.0 }, at = { 0, 0.2, 0 }, color = wood },
169 { "plank side", size = { 0.08, 0.42, 1.0 }, at = { -0.38, 0.45, 0 }, color = wood },
170 { "plank side", size = { 0.08, 0.42, 1.0 }, at = { 0.38, 0.45, 0 }, color = wood },
171 { "plank end", size = { 0.68, 0.42, 0.08 }, at = { 0, 0.45, -0.46 }, color = wood },
172 { "plank end", size = { 0.68, 0.42, 0.08 }, at = { 0, 0.45, 0.46 }, color = wood },
173 { "iron rim", size = { 0.86, 0.05, 0.06 }, at = { 0, 0.68, -0.47 }, color = IRON },
174 { "iron rim", size = { 0.86, 0.05, 0.06 }, at = { 0, 0.68, 0.47 }, color = IRON },
175 { "iron rim", size = { 0.06, 0.05, 1.0 }, at = { -0.4, 0.68, 0 }, color = IRON },
176 { "iron rim", size = { 0.06, 0.05, 1.0 }, at = { 0.4, 0.68, 0 }, color = IRON },
177 }
178 for _, w in { { -0.42, -0.3 }, { 0.42, -0.3 }, { -0.42, 0.3 }, { 0.42, 0.3 } } do
179 table.insert(parts, { "iron wheel", size = { 0.08, 0.22, 0.22 }, at = { w[1], 0.11, w[2] }, color = WHEEL })
180 end
181 -- all of it on the rail, which stands a little above the ground
182 for _, part in parts do
183 part.at[2] += WHEELS
184 end
185 return parts
186end
187
188local Cart = world.creature {
189 name = "Cart",
190 count = 0,
191 speed = 0,
192 home = "here",
193 rideable = true,
194 -- the rails steer it, not whoever's in it
195 steer = false,
196 seat = 0.35,
197 size = { 0.9, 0.75, 0.9 },
198 body = body(),
199}
200
201-- where every cart is, kept with the world
202local saved: { vector } = store.get("carts") or {}
203local where: { [number]: vector } = {}
204
205local function save()
206 local list = {}
207 for _, at in where do
208 table.insert(list, at)
209 end
210 store.set("carts", list)
211end
212
213local function vec(t: { number }): vector
214 return vector.create(t[1], t[2], t[3])
215end
216
217local function tab(v: vector): { number }
218 return { v.x, v.y, v.z }
219end
220
221-- How far ahead a cart knows the way: past where it could stop from the
222-- fastest it goes.
223local AHEAD = 40
224
225-- Adds the rails past the last one it knows of, while there's room.
226local function plan(self)
227 if not self.at then
228 return
229 end
230 for _ = 1, 12 do
231 local left, _, count = self:following()
232 if left >= AHEAD or count > 110 then
233 return
234 end
235 local c = vec(self.at)
236 local out = other(c, self.from)
237 local n = if out then link(c, out) else nil
238 if not n or not out then
239 -- the end of the line: it slows to a stop at its last point
240 return
241 end
242 local back = BACK[out]
243 self:follow(through(n, back, other(n, back)), nil, true)
244 self.at = tab(n)
245 self.from = back
246 end
247end
248
249-- Sets a cart off from the rail it's on, out by side d. False if no rail
250-- joins that side.
251local function start(self, c: vector, d: string): boolean
252 local n = link(c, d)
253 if not n then
254 return false
255 end
256 local back = BACK[d]
257 self:follow(through(n, back, other(n, back)), nil, false)
258 self.at = tab(n)
259 self.from = back
260 plan(self)
261 return true
262end
263
264-- Sets it off the way that's closest to `toward` (any way that goes, if
265-- nothing's said).
266local function set_off(self, c: vector, toward: vector?): boolean
267 local best, score = nil, -math.huge
268 for _, d in ORDER do
269 if end_up(c, d) ~= nil and link(c, d) then
270 local s = if toward then vector.dot(D[d], toward) else 0
271 if s > score then
272 best, score = d, s
273 end
274 end
275 end
276 return best ~= nil and start(self, c, best)
277end
278
279-- it rests on the rail it's on
280local function settle(self, c: vector)
281 self:follow({ middle(c) }, 0, false)
282 self.at = nil
283 self.want = 0
284end
285
286function Cart:spawned()
287 self.want = 0
288 local c = under(self.position) or under(self.position - UP)
289 if c then
290 settle(self, c)
291 end
292 where[self.id] = self.position
293end
294
295function Cart:ridden(player)
296 local p = self.position - player.position
297 self.away = { p.x, 0, p.z }
298 ui.show(player, "cart", "Push off to roll, Brake to slow down. Interact or Crouch to get out.", { at = "bottom" })
299 world.after(6, function()
300 ui.hide(player, "cart")
301 end)
302end
303
304function Cart:tick(dt: number)
305 local p = self.position
306 where[self.id] = p
307 local was = if self.was then vec(self.was) else p
308 self.was = tab(p)
309 local moved = p - was
310 local left, along, count = self:following()
311 local c = under(p)
312 if not c then
313 -- off the rails (they were taken up): it stops, and drops to the ground
314 if count > 0 then
315 self:follow({}, 0, false)
316 self.at = nil
317 end
318 return
319 end
320 if count == 0 then
321 -- put back on a rail
322 settle(self, c)
323 return
324 end
325 local b, f = rail(c)
326 local resting = along < 0.05 and vector.magnitude(moved) < 0.01
327 local want: number = self.want or 0
328 local r = self.rider
329 -- Push off, on the press
330 local pushing = r ~= nil and input.held("push", r)
331 if pushing and not self.pushing then
332 want = math.max(want, knobs.push)
333 if resting or left < 0.3 then
334 set_off(self, c, if self.away then vec(self.away) else nil)
335 end
336 end
337 self.pushing = pushing
338 if b == POWERED then
339 if powered(c) then
340 want = math.max(want, knobs.fast)
341 if resting and left < 0.3 then
342 set_off(self, c, if self.away then vec(self.away) else nil)
343 end
344 else
345 want = 0
346 end
347 elseif b == SLOPE then
348 if moved.y > 0.001 then
349 want -= knobs.hills * dt
350 elseif moved.y < -0.001 then
351 want += knobs.hills * dt
352 elseif resting then
353 -- stopped on a slope (or couldn't make it up): it rolls back down
354 if start(self, c, BACK[f]) then
355 want = math.max(want, 0.5)
356 end
357 end
358 else
359 want -= knobs.coast * dt
360 end
361 if r and input.held("brake", r) then
362 want = 0
363 end
364 -- put down a little off its rail: it settles onto it
365 if count == 1 and not self.at and left > 0.05 then
366 want = math.max(want, 1)
367 end
368 want = math.clamp(want, 0, TOP)
369 self.want = want
370 self:follow(nil, want, false)
371 plan(self)
372 -- the sound of it going
373 if along > 0.8 then
374 self.rumble_in = (self.rumble_in or 0) - dt
375 if self.rumble_in <= 0 then
376 self.rumble_in = 0.45
377 sound.play("rumble", { at = self, volume = math.min(along / TOP, 1) * 0.5 + 0.1 })
378 end
379 local here = math.floor(c.x) .. "," .. math.floor(c.z)
380 if here ~= self.cell then
381 self.cell = here
382 self.clacks = (self.clacks or 0) + 1
383 if self.clacks % 3 == 0 then
384 sound.play("clack", { at = self, volume = 0.35 })
385 end
386 end
387 end
388 -- now and then, where it is now
389 self.save_in = (self.save_in or 0) - dt
390 if self.save_in <= 0 then
391 self.save_in = 5
392 save()
393 end
394end
395
396-- bop an empty cart to take it back
397function Cart:hit(player)
398 if self.rider then
399 return
400 end
401 if world.pockets(player) ~= nil and world.give(player, CART, 1) == 0 then
402 ui.show(player, "full", "Make room in your hotbar to take the cart.", { at = "bottom" })
403 world.after(3, function()
404 ui.hide(player, "full")
405 end)
406 return
407 end
408 sound.play("thud", { at = self, caption = "Cart taken back" })
409 where[self.id] = nil
410 self:remove()
411 save()
412end
413
414-- ---- laying rails ----
415
416-- the rails that could join one at c: level, a block up or a block down
417local function near(c: vector, d: string): vector?
418 for _, dy in { 0, 1, -1 } do
419 local n = c + D[d] + vector.create(0, dy, 0)
420 if rail(n) then
421 return n
422 end
423 end
424 return nil
425end
426
427-- whether the rail at n has an end free toward c, or could be turned to
428-- have one (it's only joined on one side, or none)
429local function joined(n: vector): number
430 local k = 0
431 for _, e in ORDER do
432 if end_up(n, e) ~= nil and link(n, e) then
433 k += 1
434 end
435 end
436 return k
437end
438
439local function reaches(n: vector, c: vector): boolean
440 for _, e in ORDER do
441 local l = link(n, e)
442 if l and l == c then
443 return true
444 end
445 end
446 return false
447end
448
449-- Shapes the rail at c to join what's around it: the rails that already
450-- reach it count most, then those free to turn to meet it (joined on one
451-- side or none). It climbs to one a block up, runs straight if that joins
452-- as much as a bend would, and bends where two meet at a corner. A powered
453-- rail only runs straight.
454local function shape(c: vector)
455 local name = rail(c)
456 if name == nil then
457 return
458 end
459 local plain = name ~= POWERED
460 local score: { [string]: number } = {}
461 local up: string? = nil
462 for _, d in ORDER do
463 local n = near(c, d)
464 if n then
465 local r = reaches(n, c)
466 if r or joined(n) < 2 then
467 score[d] = if r then 2 else 1
468 if n.y > c.y and (up == nil or r) then
469 up = d
470 end
471 end
472 end
473 end
474 local kind, facing = if plain then RAIL else POWERED, world.facing(c) or "north"
475 if plain and up then
476 kind, facing = SLOPE, up
477 else
478 -- the shape that joins the most: straight (the way it runs now
479 -- winning a tie), or around a corner
480 local was = facing
481 local best, joins = -1, 0
482 for _, f in { "north", "east" } do
483 local sum = (score[f] or 0) + (score[BACK[f]] or 0)
484 local v = sum + (if f == was or BACK[f] == was then 0.75 else 0.5)
485 if v > best then
486 best, joins, facing = v, sum, f
487 end
488 end
489 if plain then
490 for _, f in ORDER do
491 local a, b = score[BACK[f]], score[RIGHT[f]]
492 if a and b and a + b > best then
493 best, joins, kind, facing = a + b, a + b, BEND, f
494 end
495 end
496 end
497 if joins == 0 then
498 -- nothing to join: as it was put down
499 return
500 end
501 end
502 local now = world.facing(c)
503 local same = kind == world.block(c) and (facing == now or ((kind == RAIL or kind == POWERED) and BACK[facing] == now))
504 if not same then
505 world.set_block(c, kind, facing)
506 end
507end
508
509-- Laying a rail: it shapes itself, and any rail beside it with a free end
510-- turns to meet it.
511local function laid(c: vector)
512 shape(c)
513 for _, d in ORDER do
514 local n = near(c, d)
515 if n and joined(n) < 2 then
516 shape(n)
517 end
518 end
519 -- the one laid may have changed again once they turned
520 shape(c)
521end
522
523-- the block an event is about, by its corner (events give its middle)
524local function cell(p: vector): vector
525 return vector.create(math.floor(p.x), math.floor(p.y), math.floor(p.z))
526end
527
528world.on("block_broken", function(_player, middle_of: vector, block: string)
529 local at = cell(middle_of)
530 if IS_RAIL[block] then
531 -- the rails beside it turn to meet what's left
532 for _, d in ORDER do
533 local n = near(at, d)
534 if n then
535 shape(n)
536 end
537 end
538 end
539end)
540
541world.on("block_placed", function(player, middle_of: vector, block: string)
542 local at = cell(middle_of)
543 if block == RAIL or block == POWERED then
544 laid(at)
545 elseif block == CART then
546 local c = if rail(at) then at elseif rail(at - UP) then at - UP else nil
547 if not c then
548 -- a cart goes on a rail
549 world.set_block(at, "Air")
550 world.give(player, CART, 1)
551 ui.show(player, "cart", "A cart goes on a rail.", { at = "bottom" })
552 world.after(3, function()
553 ui.hide(player, "cart")
554 end)
555 return
556 end
557 if c ~= at then
558 world.set_block(at, "Air")
559 end
560 if not pcall(world.spawn, Cart, middle(c)) then
561 world.give(player, CART, 1)
562 end
563 end
564end)
565
566-- a bend or a slope broken gives back a rail
567world.drops(BEND, { gives = RAIL })
568world.drops(SLOPE, { gives = RAIL })
569
570-- after a restart, the world's carts come back where they were
571world.after(0.1, function()
572 if #world.creatures(Cart) == 0 then
573 for _, at in saved do
574 pcall(world.spawn, Cart, at)
575 end
576 end
577end)