aboutsummaryrefslogtreecommitdiff
path: root/src/server/luaentity_sao.cpp
blob: 3bcbe107b39beb7602a6175b1432bb0397d9f97f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2013-2020 Minetest core developers & community

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "luaentity_sao.h"
#include "collision.h"
#include "constants.h"
#include "player_sao.h"
#include "scripting_server.h"
#include "server.h"
#include "serverenvironment.h"

LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &data)
	: UnitSAO(env, pos)
{
	std::string name;
	std::string state;
	u16 hp = 1;
	v3f velocity;
	v3f rotation;

	while (!data.empty()) { // breakable, run for one iteration
		std::istringstream is(data, std::ios::binary);
		// 'version' does not allow to incrementally extend the parameter list thus
		// we need another variable to build on top of 'version=1'. Ugly hack but works™
		u8 version2 = 0;
		u8 version = readU8(is);

		name = deSerializeString16(is);
		state = deSerializeString32(is);

		if (version < 1)
			break;

		hp = readU16(is);
		velocity = readV3F1000(is);
		// yaw must be yaw to be backwards-compatible
		rotation.Y = readF1000(is);

		if (is.good()) // EOF for old formats
			version2 = readU8(is);

		if (version2 < 1) // PROTOCOL_VERSION < 37
			break;

		// version2 >= 1
		rotation.X = readF1000(is);
		rotation.Z = readF1000(is);

		// if (version2 < 2)
		//     break;
		// <read new values>
		break;
	}
	// create object
	infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\""
			 << state << "\")" << std::endl;

	m_init_name = name;
	m_init_state = state;
	m_hp = hp;
	m_velocity = velocity;
	m_rotation = rotation;
}

LuaEntitySAO::~LuaEntitySAO()
{
	if(m_registered){
		m_env->getScriptIface()->luaentity_Remove(m_id);
	}

	for (u32 attached_particle_spawner : m_attached_particle_spawners) {
		m_env->deleteParticleSpawner(attached_particle_spawner, false);
	}
}

void LuaEntitySAO::addedToEnvironment(u32 dtime_s)
{
	ServerActiveObject::addedToEnvironment(dtime_s);

	// Create entity from name
	m_registered = m_env->getScriptIface()->
		luaentity_Add(m_id, m_init_name.c_str());

	if(m_registered){
		// Get properties
		m_env->getScriptIface()->
			luaentity_GetProperties(m_id, this, &m_prop);
		// Initialize HP from properties
		m_hp = m_prop.hp_max;
		// Activate entity, supplying serialized state
		m_env->getScriptIface()->
			luaentity_Activate(m_id, m_init_state, dtime_s);
	} else {
		m_prop.infotext = m_init_name;
	}
}

void LuaEntitySAO::dispatchScriptDeactivate()
{
	// Ensure that this is in fact a registered entity,
	// and that it isn't already gone.
	// The latter also prevents this from ever being called twice.
	if (m_registered && !isGone())
		m_env->getScriptIface()->luaentity_Deactivate(m_id);
}

void LuaEntitySAO::step(float dtime, bool send_recommended)
{
	if(!m_properties_sent)
	{
		m_properties_sent = true;
		std::string str = getPropertyPacket();
		// create message and add to list
		m_messages_out.emplace(getId(), true, str);
	}

	// If attached, check that our parent is still there. If it isn't, detach.
	if (m_attachment_parent_id && !isAttached()) {
		// This is handled when objects are removed from the map
		warningstream << "LuaEntitySAO::step() id=" << m_id <<
			" is attached to nonexistent parent. This is a bug." << std::endl;
		clearParentAttachment();
		sendPosition(false, true);
	}

	m_last_sent_position_timer += dtime;

	collisionMoveResult moveresult, *moveresult_p = nullptr;

	// Each frame, parent position is copied if the object is attached, otherwise it's calculated normally
	// If the object gets detached this comes into effect automatically from the last known origin
	if (auto *parent = getParent()) {
		m_base_position = parent->getBasePosition();
		m_velocity = v3f(0,0,0);
		m_acceleration = v3f(0,0,0);
	} else {
		if(m_prop.physical){
			aabb3f box = m_prop.collisionbox;
			box.MinEdge *= BS;
			box.MaxEdge *= BS;
			f32 pos_max_d = BS*0.25; // Distance per iteration
			v3f p_pos = m_base_position;
			v3f p_velocity = m_velocity;
			v3f p_acceleration = m_acceleration;
			moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
					pos_max_d, box, m_prop.stepheight, dtime,
					&p_pos, &p_velocity, p_acceleration,
					this, m_prop.collideWithObjects);
			moveresult_p = &moveresult;

			// Apply results
			m_base_position = p_pos;
			m_velocity = p_velocity;
			m_acceleration = p_acceleration;
		} else {
			m_base_position += dtime * m_velocity + 0.5 * dtime
					* dtime * m_acceleration;
			m_velocity += dtime * m_acceleration;
		}

		if (m_prop.automatic_face_movement_dir &&
				(fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
			float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
				+ m_prop.automatic_face_movement_dir_offset;
			float max_rotation_per_sec =
					m_prop.automatic_face_movement_max_rotation_per_sec;

			if (max_rotation_per_sec > 0) {
				m_rotation.Y = wrapDegrees_0_360(m_rotation.Y);
				wrappedApproachShortest(m_rotation.Y, target_yaw,
					dtime * max_rotation_per_sec, 360.f);
			} else {
				// Negative values of max_rotation_per_sec mean disabled.
				m_rotation.Y = target_yaw;
			}
		}
	}

	if(m_registered) {
		m_env->getScriptIface()->luaentity_Step(m_id, dtime, moveresult_p);
	}

	if (!send_recommended)
		return;

	if(!isAttached())
	{
		// TODO: force send when acceleration changes enough?
		float minchange = 0.2*BS;
		if(m_last_sent_position_timer > 1.0){
			minchange = 0.01*BS;
		} else if(m_last_sent_position_timer > 0.2){
			minchange = 0.05*BS;
		}
		float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
		move_d += m_last_sent_move_precision;
		float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
		if (move_d > minchange || vel_d > minchange ||
				std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f ||
				std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f ||
				std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) {

			sendPosition(true, false);
		}
	}

	sendOutdatedData();
}

std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
{
	std::ostringstream os(std::ios::binary);

	// PROTOCOL_VERSION >= 37
	writeU8(os, 1); // version
	os << serializeString16(""); // name
	writeU8(os, 0); // is_player
	writeU16(os, getId()); //id
	writeV3F32(os, m_base_position);
	writeV3F32(os, m_rotation);
	writeU16(os, m_hp);

	std::ostringstream msg_os(std::ios::binary);
	msg_os << serializeString32(getPropertyPacket()); // message 1
	msg_os << serializeString32(generateUpdateArmorGroupsCommand()); // 2
	msg_os << serializeString32(generateUpdateAnimationCommand()); // 3
	for (const auto &bone_pos : m_bone_position) {
		msg_os << serializeString32(generateUpdateBonePositionCommand(
			bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // 3 + N
	}
	msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + m_bone_position.size

	int message_count = 4 + m_bone_position.size();

	for (const auto &id : getAttachmentChildIds()) {
		if (ServerActiveObject *obj = m_env->getActiveObject(id)) {
			message_count++;
			msg_os << serializeString32(obj->generateUpdateInfantCommand(
				id, protocol_version));
		}
	}

	msg_os << serializeString32(generateSetTextureModCommand());
	message_count++;

	writeU8(os, message_count);
	std::string serialized = msg_os.str();
	os.write(serialized.c_str(), serialized.size());

	// return result
	return os.str();
}

void LuaEntitySAO::getStaticData(std::string *result) const
{
	verbosestream<<FUNCTION_NAME<<std::endl;
	std::ostringstream os(std::ios::binary);
	// version must be 1 to keep backwards-compatibility. See version2
	writeU8(os, 1);
	// name
	os<<serializeString16(m_init_name);
	// state
	if(m_registered){
		std::string state = m_env->getScriptIface()->
			luaentity_GetStaticdata(m_id);
		os<<serializeString32(state);
	} else {
		os<<serializeString32(m_init_state);
	}
	writeU16(os, m_hp);
	writeV3F1000(os, m_velocity);
	// yaw
	writeF1000(os, m_rotation.Y);

	// version2. Increase this variable for new values
	writeU8(os, 1); // PROTOCOL_VERSION >= 37

	writeF1000(os, m_rotation.X);
	writeF1000(os, m_rotation.Z);

	// <write new values>

	*result = os.str();
}

u16 LuaEntitySAO::punch(v3f dir,
		const ToolCapabilities *toolcap,
		ServerActiveObject *puncher,
		float time_from_last_punch)
{
	if (!m_registered) {
		// Delete unknown LuaEntities when punched
		markForRemoval();
		return 0;
	}

	FATAL_ERROR_IF(!puncher, "Punch action called without SAO");

	s32 old_hp = getHP();
	ItemStack selected_item, hand_item;
	ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);

	PunchDamageResult result = getPunchDamage(
			m_armor_groups,
			toolcap,
			&tool_item,
			time_from_last_punch);

	bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
			time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);

	if (!damage_handled) {
		if (result.did_punch) {
			setHP((s32)getHP() - result.damage,
				PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));

			// create message and add to list
			sendPunchCommand();
		}
	}

	if (getHP() == 0 && !isGone()) {
		clearParentAttachment();
		clearChildAttachments();
		m_env->getScriptIface()->luaentity_on_death(m_id, puncher);
		markForRemoval();
	}

	actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
			", hp=" << puncher->getHP() << ") punched " <<
			getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
			"), damage=" << (old_hp - (s32)getHP()) <<
			(damage_handled ? " (handled by Lua)" : "") << std::endl;

	// TODO: give Lua control over wear
	return result.wear;
}

void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
{
	if (!m_registered)
		return;

	m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
}

void LuaEntitySAO::setPos(const v3f &pos)
{
	if(isAttached())
		return;
	m_base_position = pos;
	sendPosition(false, true);
}

void LuaEntitySAO::moveTo(v3f pos, bool continuous)
{
	if(isAttached())
		return;
	m_base_position = pos;
	if(!continuous)
		sendPosition(true, true);
}

float LuaEntitySAO::getMinimumSavedMovement()
{
	return 0.1 * BS;
}

std::string LuaEntitySAO::getDescription()
{
	std::ostringstream oss;
	oss << "LuaEntitySAO \"" << m_init_name << "\" ";
	auto pos = floatToInt(m_base_position, BS);
	oss << "at " << PP(pos);
	return oss.str();
}

void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
{
	m_hp = rangelim(hp, 0, U16_MAX);
}

u16 LuaEntitySAO::getHP() const
{
	return m_hp;
}

void LuaEntitySAO::setVelocity(v3f velocity)
{
	m_velocity = velocity;
}

v3f LuaEntitySAO::getVelocity()
{
	return m_velocity;
}

void LuaEntitySAO::setAcceleration(v3f acceleration)
{
	m_acceleration = acceleration;
}

v3f LuaEntitySAO::getAcceleration()
{
	return m_acceleration;
}

void LuaEntitySAO::setTextureMod(const std::string &mod)
{
	m_current_texture_modifier = mod;
	// create message and add to list
	m_messages_out.emplace(getId(), true, generateSetTextureModCommand());
}

std::string LuaEntitySAO::getTextureMod() const
{
	return m_current_texture_modifier;
}


std::string LuaEntitySAO::generateSetTextureModCommand() const
{
	std::ostringstream os(std::ios::binary);
	// command
	writeU8(os, AO_CMD_SET_TEXTURE_MOD);
	// parameters
	os << serializeString16(m_current_texture_modifier);
	return os.str();
}

std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames,
	f32 framelength, bool select_horiz_by_yawpitch)
{
	std::ostringstream os(std::ios::binary);
	// command
	writeU8(os, AO_CMD_SET_SPRITE);
	// parameters
	writeV2S16(os, p);
	writeU16(os, num_frames);
	writeF32(os, framelength);
	writeU8(os, select_horiz_by_yawpitch);
	return os.str();
}

void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
		bool select_horiz_by_yawpitch)
{
	std::string str = generateSetSpriteCommand(
		p,
		num_frames,
		framelength,
		select_horiz_by_yawpitch
	);
	// create message and add to list
	m_messages_out.emplace(getId(), true, str);
}

std::string LuaEntitySAO::getName()
{
	return m_init_name;
}

std::string LuaEntitySAO::getPropertyPacket()
{
	return generateSetPropertiesCommand(m_prop);
}

void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
{
	// If the object is attached client-side, don't waste bandwidth sending its position to clients
	if(isAttached())
		return;

	// Send attachment updates instantly to the client prior updating position
	sendOutdatedData();

	m_last_sent_move_precision = m_base_position.getDistanceFrom(
			m_last_sent_position);
	m_last_sent_position_timer = 0;
	m_last_sent_position = m_base_position;
	m_last_sent_velocity = m_velocity;
	//m_last_sent_acceleration = m_acceleration;
	m_last_sent_rotation = m_rotation;

	float update_interval = m_env->getSendRecommendedInterval();

	std::string str = generateUpdatePositionCommand(
		m_base_position,
		m_velocity,
		m_acceleration,
		m_rotation,
		do_interpolate,
		is_movement_end,
		update_interval
	);
	// create message and add to list
	m_messages_out.emplace(getId(), false, str);
}

bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
{
	if (m_prop.physical)
	{
		//update collision box
		toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
		toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;

		toset->MinEdge += m_base_position;
		toset->MaxEdge += m_base_position;

		return true;
	}

	return false;
}

bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
{
	if (!m_prop.is_visible || !m_prop.pointable) {
		return false;
	}

	toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
	toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;

	return true;
}

bool LuaEntitySAO::collideWithObjects() const
{
	return m_prop.collideWithObjects;
}
and p.x and p.y and p.z then teleportee:setpos(p) return true, "Teleporting " .. teleportee_name .. " to " .. core.pos_to_string(p) end local teleportee = nil local p = nil local teleportee_name = nil local target_name = nil teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$") if teleportee_name then teleportee = core.get_player_by_name(teleportee_name) end if target_name then local target = core.get_player_by_name(target_name) if target then p = target:getpos() end end if teleportee and p then p = find_free_position_near(p) teleportee:setpos(p) return true, "Teleporting " .. teleportee_name .. " to " .. target_name .. " at " .. core.pos_to_string(p) end return false, 'Invalid parameters ("' .. param .. '") or player not found (see /help teleport)' end, }) core.register_chatcommand("set", { params = "[-n] <name> <value> | <name>", description = "set or read server configuration setting", privs = {server=true}, func = function(name, param) local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)") if arg and arg == "-n" and setname and setvalue then core.setting_set(setname, setvalue) return true, setname .. " = " .. setvalue end local setname, setvalue = string.match(param, "([^ ]+) (.+)") if setname and setvalue then if not core.setting_get(setname) then return false, "Failed. Use '/set -n <name> <value>' to create a new setting." end core.setting_set(setname, setvalue) return true, setname .. " = " .. setvalue end local setname = string.match(param, "([^ ]+)") if setname then local setvalue = core.setting_get(setname) if not setvalue then setvalue = "<not set>" end return true, setname .. " = " .. setvalue end return false, "Invalid parameters (see /help set)." end, }) core.register_chatcommand("deleteblocks", { params = "(here [radius]) | (<pos1> <pos2>)", description = "delete map blocks contained in area pos1 to pos2", privs = {server=true}, func = function(name, param) local p1 = {} local p2 = {} local args = param:split(" ") if args[1] == "here" then local player = core.get_player_by_name(name) if player == nil then core.log("error", "player is nil") return false, "Unable to get current position; player is nil" end p1 = player:getpos() p2 = p1 if #args >= 2 then local radius = tonumber(args[2]) or 0 p1 = vector.add(p1, radius) p2 = vector.subtract(p2, radius) end else local pos1, pos2 = unpack(param:split(") (")) if pos1 == nil or pos2 == nil then return false, "Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)" end p1 = core.string_to_pos(pos1 .. ")") p2 = core.string_to_pos("(" .. pos2) if p1 == nil or p2 == nil then return false, "Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)" end end if core.delete_area(p1, p2) then return true, "Successfully cleared area ranging from " .. core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1) else return false, "Failed to clear one or more blocks in area" end end, }) core.register_chatcommand("mods", { params = "", description = "List mods installed on the server", privs = {}, func = function(name, param) return true, table.concat(core.get_modnames(), ", ") end, }) local function handle_give_command(cmd, giver, receiver, stackstring) core.log("action", giver .. " invoked " .. cmd .. ', stackstring="' .. stackstring .. '"') local itemstack = ItemStack(stackstring) if itemstack:is_empty() then return false, "Cannot give an empty item" elseif not itemstack:is_known() then return false, "Cannot give an unknown item" end local receiverref = core.get_player_by_name(receiver) if receiverref == nil then return false, receiver .. " is not a known player" end local leftover = receiverref:get_inventory():add_item("main", itemstack) local partiality if leftover:is_empty() then partiality = "" elseif leftover:get_count() == itemstack:get_count() then partiality = "could not be " else partiality = "partially " end -- The actual item stack string may be different from what the "giver" -- entered (e.g. big numbers are always interpreted as 2^16-1). stackstring = itemstack:to_string() if giver == receiver then return true, ("%q %sadded to inventory.") :format(stackstring, partiality) else core.chat_send_player(receiver, ("%q %sadded to inventory.") :format(stackstring, partiality)) return true, ("%q %sadded to %s's inventory.") :format(stackstring, partiality, receiver) end end core.register_chatcommand("give", { params = "<name> <ItemString>", description = "give item to player", privs = {give=true}, func = function(name, param) local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$") if not toname or not itemstring then return false, "Name and ItemString required" end return handle_give_command("/give", name, toname, itemstring) end, }) core.register_chatcommand("giveme", { params = "<ItemString>", description = "give item to yourself", privs = {give=true}, func = function(name, param) local itemstring = string.match(param, "(.+)$") if not itemstring then return false, "ItemString required" end return handle_give_command("/giveme", name, name, itemstring) end, }) core.register_chatcommand("spawnentity", { params = "<EntityName>", description = "Spawn entity at your position", privs = {give=true, interact=true}, func = function(name, param) local entityname = string.match(param, "(.+)$") if not entityname then return false, "EntityName required" end core.log("action", ("/spawnentity invoked, entityname=%q") :format(entityname)) local player = core.get_player_by_name(name) if player == nil then core.log("error", "Unable to spawn entity, player is nil") return false, "Unable to spawn entity, player is nil" end local p = player:getpos() p.y = p.y + 1 core.add_entity(p, entityname) return true, ("%q spawned."):format(entityname) end, }) core.register_chatcommand("pulverize", { params = "", description = "Destroy item in hand", func = function(name, param) local player = core.get_player_by_name(name) if not player then core.log("error", "Unable to pulverize, no player.") return false, "Unable to pulverize, no player." end if player:get_wielded_item():is_empty() then return false, "Unable to pulverize, no item in hand." end player:set_wielded_item(nil) return true, "An item was pulverized." end, }) -- Key = player name core.rollback_punch_callbacks = {} core.register_on_punchnode(function(pos, node, puncher) local name = puncher:get_player_name() if core.rollback_punch_callbacks[name] then core.rollback_punch_callbacks[name](pos, node, puncher) core.rollback_punch_callbacks[name] = nil end end) core.register_chatcommand("rollback_check", { params = "[<range>] [<seconds>] [limit]", description = "Check who has last touched a node or near it," .. " max. <seconds> ago (default range=0," .. " seconds=86400=24h, limit=5)", privs = {rollback=true}, func = function(name, param) if not core.setting_getbool("enable_rollback_recording") then return false, "Rollback functions are disabled." end local range, seconds, limit = param:match("(%d+) *(%d*) *(%d*)") range = tonumber(range) or 0 seconds = tonumber(seconds) or 86400 limit = tonumber(limit) or 5 if limit > 100 then return false, "That limit is too high!" end core.rollback_punch_callbacks[name] = function(pos, node, puncher) local name = puncher:get_player_name() core.chat_send_player(name, "Checking " .. core.pos_to_string(pos) .. "...") local actions = core.rollback_get_node_actions(pos, range, seconds, limit) if not actions then core.chat_send_player(name, "Rollback functions are disabled") return end local num_actions = #actions if num_actions == 0 then core.chat_send_player(name, "Nobody has touched" .. " the specified location in " .. seconds .. " seconds") return end local time = os.time() for i = num_actions, 1, -1 do local action = actions[i] core.chat_send_player(name, ("%s %s %s -> %s %d seconds ago.") :format( core.pos_to_string(action.pos), action.actor, action.oldnode.name, action.newnode.name, time - action.time)) end end return true, "Punch a node (range=" .. range .. ", seconds=" .. seconds .. "s, limit=" .. limit .. ")" end, }) core.register_chatcommand("rollback", { params = "<player name> [<seconds>] | :<actor> [<seconds>]", description = "revert actions of a player; default for <seconds> is 60", privs = {rollback=true}, func = function(name, param) if not core.setting_getbool("enable_rollback_recording") then return false, "Rollback functions are disabled." end local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)") if not target_name then local player_name = nil player_name, seconds = string.match(param, "([^ ]+) *(%d*)") if not player_name then return false, "Invalid parameters. See /help rollback" .. " and /help rollback_check." end target_name = "player:"..player_name end seconds = tonumber(seconds) or 60 core.chat_send_player(name, "Reverting actions of " .. target_name .. " since " .. seconds .. " seconds.") local success, log = core.rollback_revert_actions_by( target_name, seconds) local response = ""