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