]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/game/falling.lua
4a13b0776a74782843662bbfaf856cc55f62c73e
[dragonfireclient.git] / builtin / game / falling.lua
1 -- Minetest: builtin/item.lua
2
3 local builtin_shared = ...
4 local SCALE = 0.667
5
6 local facedir_to_euler = {
7         {y = 0, x = 0, z = 0},
8         {y = -math.pi/2, x = 0, z = 0},
9         {y = math.pi, x = 0, z = 0},
10         {y = math.pi/2, x = 0, z = 0},
11         {y = math.pi/2, x = -math.pi/2, z = math.pi/2},
12         {y = math.pi/2, x = math.pi, z = math.pi/2},
13         {y = math.pi/2, x = math.pi/2, z = math.pi/2},
14         {y = math.pi/2, x = 0, z = math.pi/2},
15         {y = -math.pi/2, x = math.pi/2, z = math.pi/2},
16         {y = -math.pi/2, x = 0, z = math.pi/2},
17         {y = -math.pi/2, x = -math.pi/2, z = math.pi/2},
18         {y = -math.pi/2, x = math.pi, z = math.pi/2},
19         {y = 0, x = 0, z = math.pi/2},
20         {y = 0, x = -math.pi/2, z = math.pi/2},
21         {y = 0, x = math.pi, z = math.pi/2},
22         {y = 0, x = math.pi/2, z = math.pi/2},
23         {y = math.pi, x = math.pi, z = math.pi/2},
24         {y = math.pi, x = math.pi/2, z = math.pi/2},
25         {y = math.pi, x = 0, z = math.pi/2},
26         {y = math.pi, x = -math.pi/2, z = math.pi/2},
27         {y = math.pi, x = math.pi, z = 0},
28         {y = -math.pi/2, x = math.pi, z = 0},
29         {y = 0, x = math.pi, z = 0},
30         {y = math.pi/2, x = math.pi, z = 0}
31 }
32
33 local gravity = tonumber(core.settings:get("movement_gravity")) or 9.81
34
35 --
36 -- Falling stuff
37 --
38
39 core.register_entity(":__builtin:falling_node", {
40         initial_properties = {
41                 visual = "item",
42                 visual_size = vector.new(SCALE, SCALE, SCALE),
43                 textures = {},
44                 physical = true,
45                 is_visible = false,
46                 collide_with_objects = true,
47                 collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
48         },
49
50         node = {},
51         meta = {},
52         floats = false,
53
54         set_node = function(self, node, meta)
55                 node.param2 = node.param2 or 0
56                 self.node = node
57                 meta = meta or {}
58                 if type(meta.to_table) == "function" then
59                         meta = meta:to_table()
60                 end
61                 for _, list in pairs(meta.inventory or {}) do
62                         for i, stack in pairs(list) do
63                                 if type(stack) == "userdata" then
64                                         list[i] = stack:to_string()
65                                 end
66                         end
67                 end
68                 local def = core.registered_nodes[node.name]
69                 if not def then
70                         -- Don't allow unknown nodes to fall
71                         core.log("info",
72                                 "Unknown falling node removed at "..
73                                 core.pos_to_string(self.object:get_pos()))
74                         self.object:remove()
75                         return
76                 end
77                 self.meta = meta
78
79                 -- Cache whether we're supposed to float on water
80                 self.floats = core.get_item_group(node.name, "float") ~= 0
81
82                 -- Set entity visuals
83                 if def.drawtype == "torchlike" or def.drawtype == "signlike" then
84                         local textures
85                         if def.tiles and def.tiles[1] then
86                                 local tile = def.tiles[1]
87                                 if type(tile) == "table" then
88                                         tile = tile.name
89                                 end
90                                 if def.drawtype == "torchlike" then
91                                         textures = { "("..tile..")^[transformFX", tile }
92                                 else
93                                         textures = { tile, "("..tile..")^[transformFX" }
94                                 end
95                         end
96                         local vsize
97                         if def.visual_scale then
98                                 local s = def.visual_scale
99                                 vsize = vector.new(s, s, s)
100                         end
101                         self.object:set_properties({
102                                 is_visible = true,
103                                 visual = "upright_sprite",
104                                 visual_size = vsize,
105                                 textures = textures,
106                                 glow = def.light_source,
107                         })
108                 elseif def.drawtype ~= "airlike" then
109                         local itemstring = node.name
110                         if core.is_colored_paramtype(def.paramtype2) then
111                                 itemstring = core.itemstring_with_palette(itemstring, node.param2)
112                         end
113                         -- FIXME: solution needed for paramtype2 == "leveled"
114                         local s = (def.visual_scale or 1) * SCALE
115                         if def.drawtype == "mesh" then
116                                 s = s * 0.5
117                         end
118                         self.object:set_properties({
119                                 is_visible = true,
120                                 wield_item = itemstring,
121                                 visual_size = vector.new(s, s, s),
122                                 glow = def.light_source,
123                         })
124                 end
125
126                 -- Set collision box (certain nodeboxes only for now)
127                 local nb_types = {fixed=true, leveled=true, connected=true}
128                 if def.drawtype == "nodebox" and def.node_box and
129                         nb_types[def.node_box.type] and def.node_box.fixed then
130                         local box = table.copy(def.node_box.fixed)
131                         if type(box[1]) == "table" then
132                                 box = #box == 1 and box[1] or nil -- We can only use a single box
133                         end
134                         if box then
135                                 if def.paramtype2 == "leveled" and (self.node.level or 0) > 0 then
136                                         box[5] = -0.5 + self.node.level / 64
137                                 end
138                                 self.object:set_properties({
139                                         collisionbox = box
140                                 })
141                         end
142                 end
143
144                 -- Rotate entity
145                 if def.drawtype == "torchlike" then
146                         self.object:set_yaw(math.pi*0.25)
147                 elseif ((node.param2 ~= 0 or def.drawtype == "nodebox" or def.drawtype == "mesh")
148                                 and (def.wield_image == "" or def.wield_image == nil))
149                                 or def.drawtype == "signlike"
150                                 or def.drawtype == "mesh"
151                                 or def.drawtype == "normal"
152                                 or def.drawtype == "nodebox" then
153                         if (def.paramtype2 == "facedir" or def.paramtype2 == "colorfacedir") then
154                                 local fdir = node.param2 % 32
155                                 -- Get rotation from a precalculated lookup table
156                                 local euler = facedir_to_euler[fdir + 1]
157                                 if euler then
158                                         self.object:set_rotation(euler)
159                                 end
160                         elseif (def.paramtype2 == "wallmounted" or def.paramtype2 == "colorwallmounted" or def.drawtype == "signlike") then
161                                 local rot = node.param2 % 8
162                                 if (def.drawtype == "signlike" and def.paramtype2 ~= "wallmounted" and def.paramtype2 ~= "colorwallmounted") then
163                                         -- Change rotation to "floor" by default for non-wallmounted paramtype2
164                                         rot = 1
165                                 end
166                                 local pitch, yaw, roll = 0, 0, 0
167                                 if def.drawtype == "nodebox" or def.drawtype == "mesh" then
168                                         if rot == 0 then
169                                                 pitch, yaw = math.pi/2, 0
170                                         elseif rot == 1 then
171                                                 pitch, yaw = -math.pi/2, math.pi
172                                         elseif rot == 2 then
173                                                 pitch, yaw = 0, math.pi/2
174                                         elseif rot == 3 then
175                                                 pitch, yaw = 0, -math.pi/2
176                                         elseif rot == 4 then
177                                                 pitch, yaw = 0, math.pi
178                                         end
179                                 else
180                                         if rot == 1 then
181                                                 pitch, yaw = math.pi, math.pi
182                                         elseif rot == 2 then
183                                                 pitch, yaw = math.pi/2, math.pi/2
184                                         elseif rot == 3 then
185                                                 pitch, yaw = math.pi/2, -math.pi/2
186                                         elseif rot == 4 then
187                                                 pitch, yaw = math.pi/2, math.pi
188                                         elseif rot == 5 then
189                                                 pitch, yaw = math.pi/2, 0
190                                         end
191                                 end
192                                 if def.drawtype == "signlike" then
193                                         pitch = pitch - math.pi/2
194                                         if rot == 0 then
195                                                 yaw = yaw + math.pi/2
196                                         elseif rot == 1 then
197                                                 yaw = yaw - math.pi/2
198                                         end
199                                 elseif def.drawtype == "mesh" or def.drawtype == "normal" or def.drawtype == "nodebox" then
200                                         if rot >= 0 and rot <= 1 then
201                                                 roll = roll + math.pi
202                                         else
203                                                 yaw = yaw + math.pi
204                                         end
205                                 end
206                                 self.object:set_rotation({x=pitch, y=yaw, z=roll})
207                         elseif (def.drawtype == "mesh" and def.paramtype2 == "degrotate") then
208                                 local p2 = (node.param2 - (def.place_param2 or 0)) % 240
209                                 local yaw = (p2 / 240) * (math.pi * 2)
210                                 self.object:set_yaw(yaw)
211                         elseif (def.drawtype == "mesh" and def.paramtype2 == "colordegrotate") then
212                                 local p2 = (node.param2 % 32 - (def.place_param2 or 0) % 32) % 24
213                                 local yaw = (p2 / 24) * (math.pi * 2)
214                                 self.object:set_yaw(yaw)
215                         end
216                 end
217         end,
218
219         get_staticdata = function(self)
220                 local ds = {
221                         node = self.node,
222                         meta = self.meta,
223                 }
224                 return core.serialize(ds)
225         end,
226
227         on_activate = function(self, staticdata)
228                 self.object:set_armor_groups({immortal = 1})
229                 self.object:set_acceleration(vector.new(0, -gravity, 0))
230
231                 local ds = core.deserialize(staticdata)
232                 if ds and ds.node then
233                         self:set_node(ds.node, ds.meta)
234                 elseif ds then
235                         self:set_node(ds)
236                 elseif staticdata ~= "" then
237                         self:set_node({name = staticdata})
238                 end
239         end,
240
241         try_place = function(self, bcp, bcn)
242                 local bcd = core.registered_nodes[bcn.name]
243                 -- Add levels if dropped on same leveled node
244                 if bcd and bcd.paramtype2 == "leveled" and
245                                 bcn.name == self.node.name then
246                         local addlevel = self.node.level
247                         if (addlevel or 0) <= 0 then
248                                 addlevel = bcd.leveled
249                         end
250                         if core.add_node_level(bcp, addlevel) < addlevel then
251                                 return true
252                         elseif bcd.buildable_to then
253                                 -- Node level has already reached max, don't place anything
254                                 return true
255                         end
256                 end
257
258                 -- Decide if we're replacing the node or placing on top
259                 local np = vector.new(bcp)
260                 if bcd and bcd.buildable_to and
261                                 (not self.floats or bcd.liquidtype == "none") then
262                         core.remove_node(bcp)
263                 else
264                         np.y = np.y + 1
265                 end
266
267                 -- Check what's here
268                 local n2 = core.get_node(np)
269                 local nd = core.registered_nodes[n2.name]
270                 -- If it's not air or liquid, remove node and replace it with
271                 -- it's drops
272                 if n2.name ~= "air" and (not nd or nd.liquidtype == "none") then
273                         if nd and nd.buildable_to == false then
274                                 nd.on_dig(np, n2, nil)
275                                 -- If it's still there, it might be protected
276                                 if core.get_node(np).name == n2.name then
277                                         return false
278                                 end
279                         else
280                                 core.remove_node(np)
281                         end
282                 end
283
284                 -- Create node
285                 local def = core.registered_nodes[self.node.name]
286                 if def then
287                         core.add_node(np, self.node)
288                         if self.meta then
289                                 core.get_meta(np):from_table(self.meta)
290                         end
291                         if def.sounds and def.sounds.place then
292                                 core.sound_play(def.sounds.place, {pos = np}, true)
293                         end
294                 end
295                 core.check_for_falling(np)
296                 return true
297         end,
298
299         on_step = function(self, dtime, moveresult)
300                 -- Fallback code since collision detection can't tell us
301                 -- about liquids (which do not collide)
302                 if self.floats then
303                         local pos = self.object:get_pos()
304
305                         local bcp = pos:offset(0, -0.7, 0):round()
306                         local bcn = core.get_node(bcp)
307
308                         local bcd = core.registered_nodes[bcn.name]
309                         if bcd and bcd.liquidtype ~= "none" then
310                                 if self:try_place(bcp, bcn) then
311                                         self.object:remove()
312                                         return
313                                 end
314                         end
315                 end
316
317                 assert(moveresult)
318                 if not moveresult.collides then
319                         return -- Nothing to do :)
320                 end
321
322                 local bcp, bcn
323                 local player_collision
324                 if moveresult.touching_ground then
325                         for _, info in ipairs(moveresult.collisions) do
326                                 if info.type == "object" then
327                                         if info.axis == "y" and info.object:is_player() then
328                                                 player_collision = info
329                                         end
330                                 elseif info.axis == "y" then
331                                         bcp = info.node_pos
332                                         bcn = core.get_node(bcp)
333                                         break
334                                 end
335                         end
336                 end
337
338                 if not bcp then
339                         -- We're colliding with something, but not the ground. Irrelevant to us.
340                         if player_collision then
341                                 -- Continue falling through players by moving a little into
342                                 -- their collision box
343                                 -- TODO: this hack could be avoided in the future if objects
344                                 --       could choose who to collide with
345                                 local vel = self.object:get_velocity()
346                                 self.object:set_velocity(vector.new(
347                                         vel.x,
348                                         player_collision.old_velocity.y,
349                                         vel.z
350                                 ))
351                                 self.object:set_pos(self.object:get_pos():offset(0, -0.5, 0))
352                         end
353                         return
354                 elseif bcn.name == "ignore" then
355                         -- Delete on contact with ignore at world edges
356                         self.object:remove()
357                         return
358                 end
359
360                 local failure = false
361
362                 local pos = self.object:get_pos()
363                 local distance = vector.apply(vector.subtract(pos, bcp), math.abs)
364                 if distance.x >= 1 or distance.z >= 1 then
365                         -- We're colliding with some part of a node that's sticking out
366                         -- Since we don't want to visually teleport, drop as item
367                         failure = true
368                 elseif distance.y >= 2 then
369                         -- Doors consist of a hidden top node and a bottom node that is
370                         -- the actual door. Despite the top node being solid, the moveresult
371                         -- almost always indicates collision with the bottom node.
372                         -- Compensate for this by checking the top node
373                         bcp.y = bcp.y + 1
374                         bcn = core.get_node(bcp)
375                         local def = core.registered_nodes[bcn.name]
376                         if not (def and def.walkable) then
377                                 failure = true -- This is unexpected, fail
378                         end
379                 end
380
381                 -- Try to actually place ourselves
382                 if not failure then
383                         failure = not self:try_place(bcp, bcn)
384                 end
385
386                 if failure then
387                         local drops = core.get_node_drops(self.node, "")
388                         for _, item in pairs(drops) do
389                                 core.add_item(pos, item)
390                         end
391                 end
392                 self.object:remove()
393         end
394 })
395
396 local function convert_to_falling_node(pos, node)
397         local obj = core.add_entity(pos, "__builtin:falling_node")
398         if not obj then
399                 return false
400         end
401         -- remember node level, the entities' set_node() uses this
402         node.level = core.get_node_level(pos)
403         local meta = core.get_meta(pos)
404         local metatable = meta and meta:to_table() or {}
405
406         local def = core.registered_nodes[node.name]
407         if def and def.sounds and def.sounds.fall then
408                 core.sound_play(def.sounds.fall, {pos = pos}, true)
409         end
410
411         obj:get_luaentity():set_node(node, metatable)
412         core.remove_node(pos)
413         return true, obj
414 end
415
416 function core.spawn_falling_node(pos)
417         local node = core.get_node(pos)
418         if node.name == "air" or node.name == "ignore" then
419                 return false
420         end
421         return convert_to_falling_node(pos, node)
422 end
423
424 local function drop_attached_node(p)
425         local n = core.get_node(p)
426         local drops = core.get_node_drops(n, "")
427         local def = core.registered_items[n.name]
428         if def and def.preserve_metadata then
429                 local oldmeta = core.get_meta(p):to_table().fields
430                 -- Copy pos and node because the callback can modify them.
431                 local pos_copy = vector.new(p)
432                 local node_copy = {name=n.name, param1=n.param1, param2=n.param2}
433                 local drop_stacks = {}
434                 for k, v in pairs(drops) do
435                         drop_stacks[k] = ItemStack(v)
436                 end
437                 drops = drop_stacks
438                 def.preserve_metadata(pos_copy, node_copy, oldmeta, drops)
439         end
440         if def and def.sounds and def.sounds.fall then
441                 core.sound_play(def.sounds.fall, {pos = p}, true)
442         end
443         core.remove_node(p)
444         for _, item in pairs(drops) do
445                 local pos = {
446                         x = p.x + math.random()/2 - 0.25,
447                         y = p.y + math.random()/2 - 0.25,
448                         z = p.z + math.random()/2 - 0.25,
449                 }
450                 core.add_item(pos, item)
451         end
452 end
453
454 function builtin_shared.check_attached_node(p, n)
455         local def = core.registered_nodes[n.name]
456         local d = vector.new()
457         if def.paramtype2 == "wallmounted" or
458                         def.paramtype2 == "colorwallmounted" then
459                 -- The fallback vector here is in case 'wallmounted to dir' is nil due
460                 -- to voxelmanip placing a wallmounted node without resetting a
461                 -- pre-existing param2 value that is out-of-range for wallmounted.
462                 -- The fallback vector corresponds to param2 = 0.
463                 d = core.wallmounted_to_dir(n.param2) or vector.new(0, 1, 0)
464         else
465                 d.y = -1
466         end
467         local p2 = vector.add(p, d)
468         local nn = core.get_node(p2).name
469         local def2 = core.registered_nodes[nn]
470         if def2 and not def2.walkable then
471                 return false
472         end
473         return true
474 end
475
476 --
477 -- Some common functions
478 --
479
480 function core.check_single_for_falling(p)
481         local n = core.get_node(p)
482         if core.get_item_group(n.name, "falling_node") ~= 0 then
483                 local p_bottom = vector.offset(p, 0, -1, 0)
484                 -- Only spawn falling node if node below is loaded
485                 local n_bottom = core.get_node_or_nil(p_bottom)
486                 local d_bottom = n_bottom and core.registered_nodes[n_bottom.name]
487                 if d_bottom then
488                         local same = n.name == n_bottom.name
489                         -- Let leveled nodes fall if it can merge with the bottom node
490                         if same and d_bottom.paramtype2 == "leveled" and
491                                         core.get_node_level(p_bottom) <
492                                         core.get_node_max_level(p_bottom) then
493                                 convert_to_falling_node(p, n)
494                                 return true
495                         end
496                         -- Otherwise only if the bottom node is considered "fall through"
497                         if not same and
498                                         (not d_bottom.walkable or d_bottom.buildable_to) and
499                                         (core.get_item_group(n.name, "float") == 0 or
500                                         d_bottom.liquidtype == "none") then
501                                 convert_to_falling_node(p, n)
502                                 return true
503                         end
504                 end
505         end
506
507         if core.get_item_group(n.name, "attached_node") ~= 0 then
508                 if not builtin_shared.check_attached_node(p, n) then
509                         drop_attached_node(p)
510                         return true
511                 end
512         end
513
514         return false
515 end
516
517 -- This table is specifically ordered.
518 -- We don't walk diagonals, only our direct neighbors, and self.
519 -- Down first as likely case, but always before self. The same with sides.
520 -- Up must come last, so that things above self will also fall all at once.
521 local check_for_falling_neighbors = {
522         vector.new(-1, -1,  0),
523         vector.new( 1, -1,  0),
524         vector.new( 0, -1, -1),
525         vector.new( 0, -1,  1),
526         vector.new( 0, -1,  0),
527         vector.new(-1,  0,  0),
528         vector.new( 1,  0,  0),
529         vector.new( 0,  0,  1),
530         vector.new( 0,  0, -1),
531         vector.new( 0,  0,  0),
532         vector.new( 0,  1,  0),
533 }
534
535 function core.check_for_falling(p)
536         -- Round p to prevent falling entities to get stuck.
537         p = vector.round(p)
538
539         -- We make a stack, and manually maintain size for performance.
540         -- Stored in the stack, we will maintain tables with pos, and
541         -- last neighbor visited. This way, when we get back to each
542         -- node, we know which directions we have already walked, and
543         -- which direction is the next to walk.
544         local s = {}
545         local n = 0
546         -- The neighbor order we will visit from our table.
547         local v = 1
548
549         while true do
550                 -- Push current pos onto the stack.
551                 n = n + 1
552                 s[n] = {p = p, v = v}
553                 -- Select next node from neighbor list.
554                 p = vector.add(p, check_for_falling_neighbors[v])
555                 -- Now we check out the node. If it is in need of an update,
556                 -- it will let us know in the return value (true = updated).
557                 if not core.check_single_for_falling(p) then
558                         -- If we don't need to "recurse" (walk) to it then pop
559                         -- our previous pos off the stack and continue from there,
560                         -- with the v value we were at when we last were at that
561                         -- node
562                         repeat
563                                 local pop = s[n]
564                                 p = pop.p
565                                 v = pop.v
566                                 s[n] = nil
567                                 n = n - 1
568                                 -- If there's nothing left on the stack, and no
569                                 -- more sides to walk to, we're done and can exit
570                                 if n == 0 and v == 11 then
571                                         return
572                                 end
573                         until v < 11
574                         -- The next round walk the next neighbor in list.
575                         v = v + 1
576                 else
577                         -- If we did need to walk the neighbor, then
578                         -- start walking it from the walk order start (1),
579                         -- and not the order we just pushed up the stack.
580                         v = 1
581                 end
582         end
583 end
584
585 --
586 -- Global callbacks
587 --
588
589 local function on_placenode(p, node)
590         core.check_for_falling(p)
591 end
592 core.register_on_placenode(on_placenode)
593
594 local function on_dignode(p, node)
595         core.check_for_falling(p)
596 end
597 core.register_on_dignode(on_dignode)
598
599 local function on_punchnode(p, node)
600         core.check_for_falling(p)
601 end
602 core.register_on_punchnode(on_punchnode)