aboutsummaryrefslogtreecommitdiff
path: root/src/terminal_chat_console.cpp
blob: 9e3d33736190bc6ca2275d43b2ca84f37423c66a (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
/*
Minetest
Copyright (C) 2015 est31 <MTest31@outlook.com>

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 "config.h"
#if USE_CURSES
#include "version.h"
#include "terminal_chat_console.h"
#include "porting.h"
#include "settings.h"
#include "util/numeric.h"
#include "util/string.h"
#include "chat_interface.h"

TerminalChatConsole g_term_console;

// include this last to avoid any conflicts
// (likes to set macros to common names, conflicting various stuff)
#if CURSES_HAVE_NCURSESW_NCURSES_H
#include <ncursesw/ncurses.h>
#elif CURSES_HAVE_NCURSESW_CURSES_H
#include <ncursesw/curses.h>
#elif CURSES_HAVE_CURSES_H
#include <curses.h>
#elif CURSES_HAVE_NCURSES_H
#include <ncurses.h>
#elif CURSES_HAVE_NCURSES_NCURSES_H
#include <ncurses/ncurses.h>
#elif CURSES_HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#endif

// Some functions to make drawing etc position independent
static bool reformat_backend(ChatBackend *backend, int rows, int cols)
{
	if (rows < 2)
		return false;
	backend->reformat(cols, rows - 2);
	return true;
}

static void move_for_backend(int row, int col)
{
	move(row + 1, col);
}

void TerminalChatConsole::initOfCurses()
{
	initscr();
	cbreak(); //raw();
	noecho();
	keypad(stdscr, TRUE);
	nodelay(stdscr, TRUE);
	timeout(100);

	// To make esc not delay up to one second. According to the internet,
	// this is the value vim uses, too.
	set_escdelay(25);

	getmaxyx(stdscr, m_rows, m_cols);
	m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
}

void TerminalChatConsole::deInitOfCurses()
{
	endwin();
}

void *TerminalChatConsole::run()
{
	BEGIN_DEBUG_EXCEPTION_HANDLER

	std::cout << "========================" << std::endl;
	std::cout << "Begin log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	// Make the loggers to stdout/stderr shut up.
	// Go over our own loggers instead.
	LogLevelMask err_mask = g_logger.removeOutput(&stderr_output);
	LogLevelMask out_mask = g_logger.removeOutput(&stdout_output);

	g_logger.addOutput(&m_log_output);

	// Inform the server of our nick
	m_chat_interface->command_queue.push_back(
		new ChatEventNick(CET_NICK_ADD, m_nick));

	{
		// Ensures that curses is deinitialized even on an exception being thrown
		CursesInitHelper helper(this);

		while (!stopRequested()) {

			int ch = getch();
			if (stopRequested())
				break;

			step(ch);
		}
	}

	if (m_kill_requested)
		*m_kill_requested = true;

	g_logger.removeOutput(&m_log_output);
	g_logger.addOutputMasked(&stderr_output, err_mask);
	g_logger.addOutputMasked(&stdout_output, out_mask);

	std::cout << "End log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	std::cout << "========================" << std::endl;

	END_DEBUG_EXCEPTION_HANDLER

	return NULL;
}

void TerminalChatConsole::typeChatMessage(const std::wstring &msg)
{
	// Discard empty line
	if (msg.empty())
		return;

	// Send to server
	m_chat_interface->command_queue.push_back(
		new ChatEventChat(m_nick, msg));

	// Print if its a command (gets eaten by server otherwise)
	if (msg[0] == L'/') {
		m_chat_backend.addMessage(L"", (std::wstring)L"Issued command: " + msg);
	}
}

void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed)
{
	ChatPrompt &prompt = m_chat_backend.getPrompt();
	// Helpful if you want to collect key codes that aren't documented
	/*if (ch != ERR) {
		m_chat_backend.addMessage(L"",
			(std::wstring)L"Pressed key " + utf8_to_wide(
			std::string(keyname(ch)) + " (code " + itos(ch) + ")"));
		complete_redraw_needed = true;
	}//*/

	// All the key codes below are compatible to xterm
	// Only add new ones if you have tried them there,
	// to ensure compatibility with not just xterm but the wide
	// range of terminals that are compatible to xterm.

	switch (ch) {
		case ERR: // no input
			break;
		case 27: // ESC
			// Toggle ESC mode
			m_esc_mode = !m_esc_mode;
			break;
		case KEY_PPAGE:
			m_chat_backend.scrollPageUp();
			complete_redraw_needed = true;
			break;
		case KEY_NPAGE:
			m_chat_backend.scrollPageDown();
			complete_redraw_needed = true;
			break;
		case KEY_ENTER:
		case '\r':
		case '\n': {
			prompt.addToHistory(prompt.getLine());
			typeChatMessage(prompt.replace(L""));
			break;
		}
		case KEY_UP:
			prompt.historyPrev();
			break;
		case KEY_DOWN:
			prompt.historyNext();
			break;
		case KEY_LEFT:
			// Left pressed
			// move character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 545:
			// Ctrl-Left pressed
			// move word to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_RIGHT:
			// Right pressed
			// move character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 560:
			// Ctrl-Right pressed
			// move word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_HOME:
			// Home pressed
			// move to beginning of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_END:
			// End pressed
			// move to end of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_BACKSPACE:
		case '\b':
		case 127:
			// Backspace pressed
			// delete character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case KEY_DC:
			// Delete pressed
			// delete character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 519:
			// Ctrl-Delete pressed
			// delete word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case 21:
			// Ctrl-U pressed
			// kill line to left end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case 11:
			// Ctrl-K pressed
			// kill line to right end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_TAB:
			// Tab pressed
			// Nick completion
			prompt.nickCompletion(m_nicks, false);
			break;
		default:
			// Add character to the prompt,
			// assuming UTF-8.
			if (IS_UTF8_MULTB_START(ch)) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1;
			} else if (m_utf8_bytes_to_wait != 0) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait--;
				if (m_utf8_bytes_to_wait == 0) {
					std::wstring w = utf8_to_wide(m_pending_utf8_bytes);
					m_pending_utf8_bytes = "";
					// hopefully only one char in the wstring...
					for (size_t i = 0; i < w.size(); i++) {
						prompt.input(w.c_str()[i]);
					}
				}
			} else if (IS_ASCII_PRINTABLE_CHAR(ch)) {
				prompt.input(ch);
			} else {
				// Silently ignore characters we don't handle

				//warningstream << "Pressed invalid character '"
				//	<< keyname(ch) << "' (code " << itos(ch) << ")" << std::endl;
			}
			break;
	}
}

void TerminalChatConsole::step(int ch)
{
	bool complete_redraw_needed = false;

	// empty queues
	while (!m_chat_interface->outgoing_queue.empty()) {
		ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
		switch (evt->type) {
			case CET_NICK_REMOVE:
				m_nicks.remove(((ChatEventNick *)evt)->nick);
				break;
			case CET_NICK_ADD:
				m_nicks.push_back(((ChatEventNick *)evt)->nick);
				break;
			case CET_CHAT:
				complete_redraw_needed = true;
				// This is only used for direct replies from commands
				// or for lua's print() functionality
				m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
				break;
			case CET_TIME_INFO:
				ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
				m_game_time = tevt->game_time;
				m_time_of_day = tevt->time;
		};
		delete evt;
	}
	while (!m_log_output.queue.empty()) {
		complete_redraw_needed = true;
		std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
		if (p.first > m_log_level)
			continue;

		std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first));
		if (!g_settings->getBool("disable_escape_sequences")) {
			error_message = std::wstring(L"\x1b(c@red)").append(error_message)
				.append(L"\x1b(c@white)");
		}
		m_chat_backend.addMessage(error_message, utf8_to_wide(p.second));
	}

	// handle input
	if (!m_esc_mode) {
		handleInput(ch, complete_redraw_needed);
	} else {
		switch (ch) {
			case ERR: // no input
				break;
			case 27: // ESC
				// Toggle ESC mode
				m_esc_mode = !m_esc_mode;
				break;
			case 'L':
				m_log_level--;
				m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
				break;
			case 'l':
				m_log_level++;
				m_log_level = MYMIN(m_log_level, LL_MAX - 1);
				break;
		}
	}

	// was there a resize?
	int xn, yn;
	getmaxyx(stdscr, yn, xn);
	if (xn != m_cols || yn != m_rows) {
		m_cols = xn;
		m_rows = yn;
		m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
		complete_redraw_needed = true;
	}

	// draw title
	move(0, 0);
	clrtoeol();
	addstr(PROJECT_NAME_C);
	addstr(" ");
	addstr(g_version_hash);

	u32 minutes = m_time_of_day % 1000;
	u32 hours = m_time_of_day / 1000;
	minutes = (float)minutes / 1000 * 60;

	if (m_game_time)
		printw(" | Game %d Time of day %02d:%02d ",
			m_game_time, hours, minutes);

	// draw text
	if (complete_redraw_needed && m_can_draw_text)
		draw_text();

	// draw prompt
	if (!m_esc_mode) {
		// normal prompt
		ChatPrompt& prompt = m_chat_backend.getPrompt();
		std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
		move(m_rows - 1, 0);
		clrtoeol();
		addstr(prompt_text.c_str());
		// Draw cursor
		s32 cursor_pos = prompt.getVisibleCursorPosition();
		if (cursor_pos >= 0) {
			move(m_rows - 1, cursor_pos);
		}
	} else {
		// esc prompt
		move(m_rows - 1, 0);
		clrtoeol();
		printw("[ESC] Toggle ESC mode |"
			" [CTRL+C] Shut down |"
			" (L) in-, (l) decrease loglevel %s",
			Logger::getLevelLabel((LogLevel) m_log_level).c_str());
	}

	refresh();
}

void TerminalChatConsole::draw_text()
{
	ChatBuffer& buf = m_chat_backend.getConsoleBuffer();
	for (u32 row = 0; row < buf.getRows(); row++) {
		move_for_backend(row, 0);
		clrtoeol();
		const ChatFormattedLine& line = buf.getFormattedLine(row);
		if (line.fragments.empty())
			continue;
		for (const ChatFormattedFragment &fragment : line.fragments) {
			addstr(wide_to_utf8(fragment.text.getString()).c_str());
		}
	}
}

void TerminalChatConsole::stopAndWaitforThread()
{
	clearKillStatus();
	stop();
	wait();
}

#endif
ree 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 "common/c_content.h" #include "common/c_converter.h" #include "common/c_types.h" #include "nodedef.h" #include "object_properties.h" #include "cpp_api/s_node.h" #include "lua_api/l_object.h" #include "lua_api/l_item.h" #include "common/c_internal.h" #include "server.h" #include "log.h" #include "tool.h" #include "serverobject.h" #include "porting.h" #include "mg_schematic.h" #include "noise.h" #include "util/pointedthing.h" #include "debug.h" // For FATAL_ERROR #include <json/json.h> struct EnumString es_TileAnimationType[] = { {TAT_NONE, "none"}, {TAT_VERTICAL_FRAMES, "vertical_frames"}, {TAT_SHEET_2D, "sheet_2d"}, {0, NULL}, }; /******************************************************************************/ void read_item_definition(lua_State* L, int index, const ItemDefinition &default_def, ItemDefinition &def) { if (index < 0) index = lua_gettop(L) + 1 + index; def.type = (ItemType)getenumfield(L, index, "type", es_ItemType, ITEM_NONE); getstringfield(L, index, "name", def.name); getstringfield(L, index, "description", def.description); getstringfield(L, index, "inventory_image", def.inventory_image); getstringfield(L, index, "wield_image", def.wield_image); getstringfield(L, index, "palette", def.palette_image); // Read item color. lua_getfield(L, index, "color"); read_color(L, -1, &def.color); lua_pop(L, 1); lua_getfield(L, index, "wield_scale"); if(lua_istable(L, -1)){ def.wield_scale = check_v3f(L, -1); } lua_pop(L, 1); int stack_max = getintfield_default(L, index, "stack_max", def.stack_max); def.stack_max = rangelim(stack_max, 1, U16_MAX); lua_getfield(L, index, "on_use"); def.usable = lua_isfunction(L, -1); lua_pop(L, 1); getboolfield(L, index, "liquids_pointable", def.liquids_pointable); warn_if_field_exists(L, index, "tool_digging_properties", "Deprecated; use tool_capabilities"); lua_getfield(L, index, "tool_capabilities"); if(lua_istable(L, -1)){ def.tool_capabilities = new ToolCapabilities( read_tool_capabilities(L, -1)); } // If name is "" (hand), ensure there are ToolCapabilities // because it will be looked up there whenever any other item has // no ToolCapabilities if(def.name == "" && def.tool_capabilities == NULL){ def.tool_capabilities = new ToolCapabilities(); } lua_getfield(L, index, "groups"); read_groups(L, -1, def.groups); lua_pop(L, 1); lua_getfield(L, index, "sounds"); if(lua_istable(L, -1)){ lua_getfield(L, -1, "place"); read_soundspec(L, -1, def.sound_place); lua_pop(L, 1); lua_getfield(L, -1, "place_failed"); read_soundspec(L, -1, def.sound_place_failed); lua_pop(L, 1); } lua_pop(L, 1); def.range = getfloatfield_default(L, index, "range", def.range); // Client shall immediately place this node when player places the item. // Server will update the precise end result a moment later. // "" = no prediction getstringfield(L, index, "node_placement_prediction", def.node_placement_prediction); } /******************************************************************************/ void push_item_definition(lua_State *L, const ItemDefinition &i) { lua_newtable(L); lua_pushstring(L, i.name.c_str()); lua_setfield(L, -2, "name"); lua_pushstring(L, i.description.c_str()); lua_setfield(L, -2, "description"); } void push_item_definition_full(lua_State *L, const ItemDefinition &i) { std::string type(es_ItemType[(int)i.type].str); lua_newtable(L); lua_pushstring(L, i.name.c_str()); lua_setfield(L, -2, "name"); lua_pushstring(L, i.description.c_str()); lua_setfield(L, -2, "description"); lua_pushstring(L, type.c_str()); lua_setfield(L, -2, "type"); lua_pushstring(L, i.inventory_image.c_str()); lua_setfield(L, -2, "inventory_image"); lua_pushstring(L, i.wield_image.c_str()); lua_setfield(L, -2, "wield_image"); lua_pushstring(L, i.palette_image.c_str()); lua_setfield(L, -2, "palette_image"); push_ARGB8(L, i.color); lua_setfield(L, -2, "color"); push_v3f(L, i.wield_scale); lua_setfield(L, -2, "wield_scale"); lua_pushinteger(L, i.stack_max); lua_setfield(L, -2, "stack_max"); lua_pushboolean(L, i.usable); lua_setfield(L, -2, "usable"); lua_pushboolean(L, i.liquids_pointable); lua_setfield(L, -2, "liquids_pointable"); if (i.type == ITEM_TOOL) { push_tool_capabilities(L, ToolCapabilities( i.tool_capabilities->full_punch_interval, i.tool_capabilities->max_drop_level, i.tool_capabilities->groupcaps, i.tool_capabilities->damageGroups)); lua_setfield(L, -2, "tool_capabilities"); } push_groups(L, i.groups); lua_setfield(L, -2, "groups"); push_soundspec(L, i.sound_place); lua_setfield(L, -2, "sound_place"); push_soundspec(L, i.sound_place_failed); lua_setfield(L, -2, "sound_place_failed"); lua_pushstring(L, i.node_placement_prediction.c_str()); lua_setfield(L, -2, "node_placement_prediction"); } /******************************************************************************/ void read_object_properties(lua_State *L, int index, ObjectProperties *prop, IItemDefManager *idef) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return; prop->hp_max = getintfield_default(L, -1, "hp_max", 10); getboolfield(L, -1, "physical", prop->physical); getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects); getfloatfield(L, -1, "weight", prop->weight); lua_getfield(L, -1, "collisionbox"); if(lua_istable(L, -1)) prop->collisionbox = read_aabb3f(L, -1, 1.0); lua_pop(L, 1); getstringfield(L, -1, "visual", prop->visual); getstringfield(L, -1, "mesh", prop->mesh); lua_getfield(L, -1, "visual_size"); if(lua_istable(L, -1)) prop->visual_size = read_v2f(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "textures"); if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 if(lua_isstring(L, -1)) prop->textures.push_back(lua_tostring(L, -1)); else prop->textures.push_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, -1, "colors"); if (lua_istable(L, -1)) { int table = lua_gettop(L); prop->colors.clear(); for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) { video::SColor color(255, 255, 255, 255); read_color(L, -1, &color); prop->colors.push_back(color); } } lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); getboolfield(L, -1, "is_visible", prop->is_visible); getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound); getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate); if (getfloatfield(L, -1, "stepheight", prop->stepheight)) prop->stepheight *= BS; lua_getfield(L, -1, "automatic_face_movement_dir"); if (lua_isnumber(L, -1)) { prop->automatic_face_movement_dir = true; prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1); } else if (lua_isboolean(L, -1)) { prop->automatic_face_movement_dir = lua_toboolean(L, -1); prop->automatic_face_movement_dir_offset = 0.0; } lua_pop(L, 1); getboolfield(L, -1, "backface_culling", prop->backface_culling); getstringfield(L, -1, "nametag", prop->nametag); lua_getfield(L, -1, "nametag_color"); if (!lua_isnil(L, -1)) { video::SColor color = prop->nametag_color; if (read_color(L, -1, &color)) prop->nametag_color = color; } lua_pop(L, 1); lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec"); if (lua_isnumber(L, -1)) { prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1); } lua_pop(L, 1); getstringfield(L, -1, "infotext", prop->infotext); lua_getfield(L, -1, "wield_item"); if (!lua_isnil(L, -1)) prop->wield_item = read_item(L, -1, idef).getItemString(); lua_pop(L, 1); } /******************************************************************************/ void push_object_properties(lua_State *L, ObjectProperties *prop) { lua_newtable(L); lua_pushnumber(L, prop->hp_max); lua_setfield(L, -2, "hp_max"); lua_pushboolean(L, prop->physical); lua_setfield(L, -2, "physical"); lua_pushboolean(L, prop->collideWithObjects); lua_setfield(L, -2, "collide_with_objects"); lua_pushnumber(L, prop->weight); lua_setfield(L, -2, "weight"); push_aabb3f(L, prop->collisionbox); lua_setfield(L, -2, "collisionbox"); lua_pushlstring(L, prop->visual.c_str(), prop->visual.size()); lua_setfield(L, -2, "visual"); lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size()); lua_setfield(L, -2, "mesh"); push_v2f(L, prop->visual_size); lua_setfield(L, -2, "visual_size"); lua_newtable(L); u16 i = 1; for (std::vector<std::string>::iterator it = prop->textures.begin(); it != prop->textures.end(); ++it) { lua_pushlstring(L, it->c_str(), it->size()); lua_rawseti(L, -2, i); } lua_setfield(L, -2, "textures"); lua_newtable(L); i = 1; for (std::vector<video::SColor>::iterator it = prop->colors.begin(); it != prop->colors.end(); ++it) { push_ARGB8(L, *it); lua_rawseti(L, -2, i); } lua_setfield(L, -2, "colors"); push_v2s16(L, prop->spritediv); lua_setfield(L, -2, "spritediv"); push_v2s16(L, prop->initial_sprite_basepos); lua_setfield(L, -2, "initial_sprite_basepos"); lua_pushboolean(L, prop->is_visible); lua_setfield(L, -2, "is_visible"); lua_pushboolean(L, prop->makes_footstep_sound); lua_setfield(L, -2, "makes_footstep_sound"); lua_pushnumber(L, prop->automatic_rotate); lua_setfield(L, -2, "automatic_rotate"); lua_pushnumber(L, prop->stepheight / BS); lua_setfield(L, -2, "stepheight"); if (prop->automatic_face_movement_dir) lua_pushnumber(L, prop->automatic_face_movement_dir_offset); else lua_pushboolean(L, false); lua_setfield(L, -2, "automatic_face_movement_dir"); lua_pushboolean(L, prop->backface_culling); lua_setfield(L, -2, "backface_culling"); lua_pushlstring(L, prop->nametag.c_str(), prop->nametag.size()); lua_setfield(L, -2, "nametag"); push_ARGB8(L, prop->nametag_color); lua_setfield(L, -2, "nametag_color"); lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec); lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec"); lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size()); lua_setfield(L, -2, "infotext"); lua_pushlstring(L, prop->wield_item.c_str(), prop->wield_item.size()); lua_setfield(L, -2, "wield_item"); } /******************************************************************************/ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) { if(index < 0) index = lua_gettop(L) + 1 + index; TileDef tiledef; bool default_tiling = true; bool default_culling = true; switch (drawtype) { case NDT_PLANTLIKE: case NDT_PLANTLIKE_ROOTED: case NDT_FIRELIKE: default_tiling = false; // "break" is omitted here intentionaly, as PLANTLIKE // FIRELIKE drawtype both should default to having // backface_culling to false. case NDT_MESH: case NDT_LIQUID: default_culling = false; break; default: break; } // key at index -2 and value at index if(lua_isstring(L, index)){ // "default_lava.png" tiledef.name = lua_tostring(L, index); tiledef.tileable_vertical = default_tiling; tiledef.tileable_horizontal = default_tiling; tiledef.backface_culling = default_culling; } else if(lua_istable(L, index)) { // name="default_lava.png" tiledef.name = ""; getstringfield(L, index, "name", tiledef.name); getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat. tiledef.backface_culling = getboolfield_default( L, index, "backface_culling", default_culling); tiledef.tileable_horizontal = getboolfield_default( L, index, "tileable_horizontal", default_tiling); tiledef.tileable_vertical = getboolfield_default( L, index, "tileable_vertical", default_tiling); // color = ... lua_getfield(L, index, "color"); tiledef.has_color = read_color(L, -1, &tiledef.color); lua_pop(L, 1); // animation = {} lua_getfield(L, index, "animation"); tiledef.animation = read_animation_definition(L, -1); lua_pop(L, 1); } return tiledef; } /******************************************************************************/ ContentFeatures read_content_features(lua_State *L, int index) { if(index < 0) index = lua_gettop(L) + 1 + index; ContentFeatures f; /* Cache existence of some callbacks */ lua_getfield(L, index, "on_construct"); if(!lua_isnil(L, -1)) f.has_on_construct = true; lua_pop(L, 1); lua_getfield(L, index, "on_destruct"); if(!lua_isnil(L, -1)) f.has_on_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "after_destruct"); if(!lua_isnil(L, -1)) f.has_after_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "on_rightclick"); f.rightclickable = lua_isfunction(L, -1); lua_pop(L, 1); /* Name */ getstringfield(L, index, "name", f.name); /* Groups */ lua_getfield(L, index, "groups"); read_groups(L, -1, f.groups); lua_pop(L, 1); /* Visual definition */ f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", ScriptApiNode::es_DrawType,NDT_NORMAL); getfloatfield(L, index, "visual_scale", f.visual_scale); /* Meshnode model filename */ getstringfield(L, index, "mesh", f.mesh); // tiles = {} lua_getfield(L, index, "tiles"); // If nil, try the deprecated name "tile_images" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "tile_images", "Deprecated; new name is \"tiles\"."); lua_getfield(L, index, "tile_images"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==6){ lua_pop(L, 1); break; } } // Copy last value to all remaining textures if(i >= 1){ TileDef lasttile = f.tiledef[i-1]; while(i < 6){ f.tiledef[i] = lasttile; i++; } } } lua_pop(L, 1); // overlay_tiles = {} lua_getfield(L, index, "overlay_tiles"); if (lua_istable(L, -1)) { int table = lua_gettop(L); lua_pushnil(L); int i = 0; while (lua_next(L, table) != 0) { // Read tiledef from value f.tiledef_overlay[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if (i == 6) { lua_pop(L, 1); break; } } // Copy last value to all remaining textures if (i >= 1) { TileDef lasttile = f.tiledef_overlay[i - 1]; while (i < 6) { f.tiledef_overlay[i] = lasttile; i++; } } } lua_pop(L, 1); // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "special_materials", "Deprecated; new name is \"special_tiles\"."); lua_getfield(L, index, "special_materials"); } if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; if(i==CF_SPECIAL_COUNT){ lua_pop(L, 1); break; } } } lua_pop(L, 1); f.alpha = getintfield_default(L, index, "alpha", 255); bool usealpha = getboolfield_default(L, index, "use_texture_alpha", false); if (usealpha) f.alpha = 0; // Read node color. lua_getfield(L, index, "color"); read_color(L, -1, &f.color); lua_pop(L, 1); getstringfield(L, index, "palette", f.palette_name); /* Other stuff */ lua_getfield(L, index, "post_effect_color"); read_color(L, -1, &f.post_effect_color); lua_pop(L, 1); f.param_type = (ContentParamType)getenumfield(L, index, "paramtype", ScriptApiNode::es_ContentParamType, CPT_NONE); f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2", ScriptApiNode::es_ContentParamType2, CPT2_NONE); if (f.palette_name != "" && !(f.param_type_2 == CPT2_COLOR || f.param_type_2 == CPT2_COLORED_FACEDIR || f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) warningstream << "Node " << f.name.c_str() << " has a palette, but not a suitable paramtype2." << std::endl; // Warn about some deprecated fields warn_if_field_exists(L, index, "wall_mounted", "Deprecated; use paramtype2 = 'wallmounted'"); warn_if_field_exists(L, index, "light_propagates", "Deprecated; determined from paramtype"); warn_if_field_exists(L, index, "dug_item", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "extra_dug_item_rarity", "Deprecated; use 'drop' field"); warn_if_field_exists(L, index, "metadata_name", "Deprecated; use on_add and metadata callbacks"); // True for all ground-like things like stone and mud, false for eg. trees getboolfield(L, index, "is_ground_content", f.is_ground_content); f.light_propagates = (f.param_type == CPT_LIGHT); getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates); // This is used for collision detection. // Also for general solidness queries. getboolfield(L, index, "walkable", f.walkable); // Player can point to these getboolfield(L, index, "pointable", f.pointable); // Player can dig these getboolfield(L, index, "diggable", f.diggable); // Player can climb these getboolfield(L, index, "climbable", f.climbable); // Player can build on these getboolfield(L, index, "buildable_to", f.buildable_to); // Liquids flow into and replace node getboolfield(L, index, "floodable", f.floodable); // Whether the node is non-liquid, source liquid or flowing liquid f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype", ScriptApiNode::es_LiquidType, LIQUID_NONE); // If the content is liquid, this is the flowing version of the liquid. getstringfield(L, index, "liquid_alternative_flowing", f.liquid_alternative_flowing); // If the content is liquid, this is the source version of the liquid. getstringfield(L, index, "liquid_alternative_source", f.liquid_alternative_source); // Viscosity for fluid flow, ranging from 1 to 7, with // 1 giving almost instantaneous propagation and 7 being // the slowest possible f.liquid_viscosity = getintfield_default(L, index, "liquid_viscosity", f.liquid_viscosity); f.liquid_range = getintfield_default(L, index, "liquid_range", f.liquid_range); f.leveled = getintfield_default(L, index, "leveled", f.leveled); getboolfield(L, index, "liquid_renewable", f.liquid_renewable); f.drowning = getintfield_default(L, index, "drowning", f.drowning); // Amount of light the node emits f.light_source = getintfield_default(L, index, "light_source", f.light_source); if (f.light_source > LIGHT_MAX) { warningstream << "Node " << f.name.c_str() << " had greater light_source than " << LIGHT_MAX << ", it was reduced." << std::endl; f.light_source = LIGHT_MAX; } f.damage_per_second = getintfield_default(L, index, "damage_per_second", f.damage_per_second); lua_getfield(L, index, "node_box"); if(lua_istable(L, -1)) f.node_box = read_nodebox(L, -1); lua_pop(L, 1); lua_getfield(L, index, "connects_to"); if (lua_istable(L, -1)) { int table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, table) != 0) { // Value at -1 f.connects_to.push_back(lua_tostring(L, -1)); lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "connect_sides"); if (lua_istable(L, -1)) { int table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, table) != 0) { // Value at -1 std::string side(lua_tostring(L, -1)); // Note faces are flipped to make checking easier if (side == "top") f.connect_sides |= 2; else if (side == "bottom") f.connect_sides |= 1; else if (side == "front") f.connect_sides |= 16; else if (side == "left") f.connect_sides |= 32; else if (side == "back") f.connect_sides |= 4; else if (side == "right") f.connect_sides |= 8; else warningstream << "Unknown value for \"connect_sides\": " << side << std::endl; lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "selection_box"); if(lua_istable(L, -1)) f.selection_box = read_nodebox(L, -1); lua_pop(L, 1); lua_getfield(L, index, "collision_box"); if(lua_istable(L, -1)) f.collision_box = read_nodebox(L, -1); lua_pop(L, 1); f.waving = getintfield_default(L, index, "waving", f.waving); // Set to true if paramtype used to be 'facedir_simple' getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple); // Set to true if wall_mounted used to be set to true getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted); // Sound table lua_getfield(L, index, "sounds"); if(lua_istable(L, -1)){ lua_getfield(L, -1, "footstep"); read_soundspec(L, -1, f.sound_footstep); lua_pop(L, 1); lua_getfield(L, -1, "dig"); read_soundspec(L, -1, f.sound_dig); lua_pop(L, 1); lua_getfield(L, -1, "dug"); read_soundspec(L, -1, f.sound_dug); lua_pop(L, 1); } lua_pop(L, 1); return f; } void push_content_features(lua_State *L, const ContentFeatures &c) { std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str); std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str); std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str); std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str); /* Missing "tiles" because I don't see a usecase (at least not yet). */ lua_newtable(L); lua_pushboolean(L, c.has_on_construct); lua_setfield(L, -2, "has_on_construct"); lua_pushboolean(L, c.has_on_destruct); lua_setfield(L, -2, "has_on_destruct"); lua_pushboolean(L, c.has_after_destruct); lua_setfield(L, -2, "has_after_destruct"); lua_pushstring(L, c.name.c_str()); lua_setfield(L, -2, "name"); push_groups(L, c.groups); lua_setfield(L, -2, "groups"); lua_pushstring(L, paramtype.c_str()); lua_setfield(L, -2, "paramtype"); lua_pushstring(L, paramtype2.c_str()); lua_setfield(L, -2, "paramtype2"); lua_pushstring(L, drawtype.c_str()); lua_setfield(L, -2, "drawtype"); if (!c.mesh.empty()) { lua_pushstring(L, c.mesh.c_str()); lua_setfield(L, -2, "mesh"); } #ifndef SERVER push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node, lua_setfield(L, -2, "minimap_color"); // but the people need to know! #endif lua_pushnumber(L, c.visual_scale); lua_setfield(L, -2, "visual_scale"); lua_pushnumber(L, c.alpha); lua_setfield(L, -2, "alpha"); if (!c.palette_name.empty()) { push_ARGB8(L, c.color); lua_setfield(L, -2, "color"); lua_pushstring(L, c.palette_name.c_str()); lua_setfield(L, -2, "palette_name"); push_palette(L, c.palette); lua_setfield(L, -2, "palette"); } lua_pushnumber(L, c.waving); lua_setfield(L, -2, "waving"); lua_pushnumber(L, c.connect_sides); lua_setfield(L, -2, "connect_sides"); lua_newtable(L); u16 i = 1; for (std::vector<std::string>::const_iterator it = c.connects_to.begin(); it != c.connects_to.end(); ++it) { lua_pushlstring(L, it->c_str(), it->size()); lua_rawseti(L, -2, i); } lua_setfield(L, -2, "connects_to"); push_ARGB8(L, c.post_effect_color); lua_setfield(L, -2, "post_effect_color"); lua_pushnumber(L, c.leveled); lua_setfield(L, -2, "leveled"); lua_pushboolean(L, c.sunlight_propagates); lua_setfield(L, -2, "sunlight_propagates"); lua_pushnumber(L, c.light_source); lua_setfield(L, -2, "light_source"); lua_pushboolean(L, c.is_ground_content); lua_setfield(L, -2, "is_ground_content"); lua_pushboolean(L, c.walkable); lua_setfield(L, -2, "walkable"); lua_pushboolean(L, c.pointable); lua_setfield(L, -2, "pointable"); lua_pushboolean(L, c.diggable); lua_setfield(L, -2, "diggable"); lua_pushboolean(L, c.climbable); lua_setfield(L, -2, "climbable"); lua_pushboolean(L, c.buildable_to); lua_setfield(L, -2, "buildable_to"); lua_pushboolean(L, c.rightclickable); lua_setfield(L, -2, "rightclickable"); lua_pushnumber(L, c.damage_per_second); lua_setfield(L, -2, "damage_per_second"); if (c.isLiquid()) { lua_pushstring(L, liquid_type.c_str()); lua_setfield(L, -2, "liquid_type"); lua_pushstring(L, c.liquid_alternative_flowing.c_str()); lua_setfield(L, -2, "liquid_alternative_flowing"); lua_pushstring(L, c.liquid_alternative_source.c_str()); lua_setfield(L, -2, "liquid_alternative_source"); lua_pushnumber(L, c.liquid_viscosity); lua_setfield(L, -2, "liquid_viscosity"); lua_pushboolean(L, c.liquid_renewable); lua_setfield(L, -2, "liquid_renewable"); lua_pushnumber(L, c.liquid_range); lua_setfield(L, -2, "liquid_range"); } lua_pushnumber(L, c.drowning); lua_setfield(L, -2, "drowning"); lua_pushboolean(L, c.floodable); lua_setfield(L, -2, "floodable"); push_nodebox(L, c.node_box); lua_setfield(L, -2, "node_box"); push_nodebox(L, c.selection_box); lua_setfield(L, -2, "selection_box"); push_nodebox(L, c.collision_box); lua_setfield(L, -2, "collision_box"); lua_newtable(L); push_soundspec(L, c.sound_footstep); lua_setfield(L, -2, "sound_footstep"); push_soundspec(L, c.sound_dig); lua_setfield(L, -2, "sound_dig"); push_soundspec(L, c.sound_dug); lua_setfield(L, -2, "sound_dug"); lua_setfield(L, -2, "sounds"); lua_pushboolean(L, c.legacy_facedir_simple); lua_setfield(L, -2, "legacy_facedir_simple"); lua_pushboolean(L, c.legacy_wallmounted); lua_setfield(L, -2, "legacy_wallmounted"); } /******************************************************************************/ void push_nodebox(lua_State *L, const NodeBox &box) { lua_newtable(L); switch (box.type) { case NODEBOX_REGULAR: lua_pushstring(L, "regular"); lua_setfield(L, -2, "type"); break; case NODEBOX_LEVELED: case NODEBOX_FIXED: lua_pushstring(L, "fixed"); lua_setfield(L, -2, "type"); push_box(L, box.fixed); lua_setfield(L, -2, "fixed"); break; case NODEBOX_WALLMOUNTED: lua_pushstring(L, "wallmounted"); lua_setfield(L, -2, "type"); push_aabb3f(L, box.wall_top); lua_setfield(L, -2, "wall_top"); push_aabb3f(L, box.wall_bottom); lua_setfield(L, -2, "wall_bottom"); push_aabb3f(L, box.wall_side); lua_setfield(L, -2, "wall_side"); break; case NODEBOX_CONNECTED: lua_pushstring(L, "connected"); lua_setfield(L, -2, "type"); push_box(L, box.connect_top); lua_setfield(L, -2, "connect_top"); push_box(L, box.connect_bottom); lua_setfield(L, -2, "connect_bottom"); push_box(L, box.connect_front); lua_setfield(L, -2, "connect_front"); push_box(L, box.connect_back); lua_setfield(L, -2, "connect_back"); push_box(L, box.connect_left); lua_setfield(L, -2, "connect_left"); push_box(L, box.connect_right); lua_setfield(L, -2, "connect_right"); break; default: FATAL_ERROR("Invalid box.type"); break; } } void push_box(lua_State *L, const std::vector<aabb3f> &box) { lua_newtable(L); u8 i = 1; for (std::vector<aabb3f>::const_iterator it = box.begin(); it != box.end(); ++it) { push_aabb3f(L, (*it)); lua_rawseti(L, -2, i); } } /******************************************************************************/ void push_palette(lua_State *L, const std::vector<video::SColor> *palette) { lua_createtable(L, palette->size(), 0); int newTable = lua_gettop(L); int index = 1; std::vector<video::SColor>::const_iterator iter; for (iter = palette->begin(); iter != palette->end(); ++iter) { push_ARGB8(L, (*iter)); lua_rawseti(L, newTable, index); index++; } } /******************************************************************************/ void read_server_sound_params(lua_State *L, int index, ServerSoundParams &params) { if(index < 0) index = lua_gettop(L) + 1 + index; // Clear params = ServerSoundParams(); if(lua_istable(L, index)){ getfloatfield(L, index, "gain", params.gain); getstringfield(L, index, "to_player", params.to_player); getfloatfield(L, index, "fade", params.fade); getfloatfield(L, index, "pitch", params.pitch); lua_getfield(L, index, "pos"); if(!lua_isnil(L, -1)){ v3f p = read_v3f(L, -1)*BS; params.pos = p; params.type = ServerSoundParams::SSP_POSITIONAL; } lua_pop(L, 1); lua_getfield(L, index, "object"); if(!lua_isnil(L, -1)){ ObjectRef *ref = ObjectRef::checkobject(L, -1); ServerActiveObject *sao = ObjectRef::getobject(ref); if(sao){ params.object = sao->getId(); params.type = ServerSoundParams::SSP_OBJECT; } } lua_pop(L, 1); params.max_hear_distance = BS*getfloatfield_default(L, index, "max_hear_distance", params.max_hear_distance/BS); getboolfield(L, index, "loop", params.loop); } } /******************************************************************************/ void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec) { if(index < 0) index = lua_gettop(L) + 1 + index; if(lua_isnil(L, index)){ } else if(lua_istable(L, index)){ getstringfield(L, index, "name", spec.name); getfloatfield(L, index, "gain", spec.gain); getfloatfield(L, index, "fade", spec.fade); getfloatfield(L, index, "pitch", spec.pitch); } else if(lua_isstring(L, index)){ spec.name = lua_tostring(L, index); } } void push_soundspec(lua_State *L, const SimpleSoundSpec &spec) { lua_newtable(L); lua_pushstring(L, spec.name.c_str()); lua_setfield(L, -2, "name"); lua_pushnumber(L, spec.gain); lua_setfield(L, -2, "gain"); lua_pushnumber(L, spec.fade); lua_setfield(L, -2, "fade"); lua_pushnumber(L, spec.pitch); lua_setfield(L, -2, "pitch"); } /******************************************************************************/ NodeBox read_nodebox(lua_State *L, int index) { NodeBox nodebox; if(lua_istable(L, -1)){ nodebox.type = (NodeBoxType)getenumfield(L, index, "type", ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); #define NODEBOXREAD(n, s) \ do { \ lua_getfield(L, index, (s)); \ if (lua_istable(L, -1)) \ (n) = read_aabb3f(L, -1, BS); \ lua_pop(L, 1); \ } while (0) #define NODEBOXREADVEC(n, s) \ do { \ lua_getfield(L, index, (s)); \ if (lua_istable(L, -1)) \ (n) = read_aabb3f_vector(L, -1, BS); \ lua_pop(L, 1); \ } while (0) NODEBOXREADVEC(nodebox.fixed, "fixed"); NODEBOXREAD(nodebox.wall_top, "wall_top"); NODEBOXREAD(nodebox.wall_bottom, "wall_bottom"); NODEBOXREAD(nodebox.wall_side, "wall_side"); NODEBOXREADVEC(nodebox.connect_top, "connect_top"); NODEBOXREADVEC(nodebox.connect_bottom, "connect_bottom"); NODEBOXREADVEC(nodebox.connect_front, "connect_front"); NODEBOXREADVEC(nodebox.connect_left, "connect_left"); NODEBOXREADVEC(nodebox.connect_back, "connect_back"); NODEBOXREADVEC(nodebox.connect_right, "connect_right"); } return nodebox; } /******************************************************************************/ MapNode readnode(lua_State *L, int index, INodeDefManager *ndef) { lua_getfield(L, index, "name"); if (!lua_isstring(L, -1)) throw LuaError("Node name is not set or is not a string!"); const char *name = lua_tostring(L, -1); lua_pop(L, 1); u8 param1 = 0; lua_getfield(L, index, "param1"); if (!lua_isnil(L, -1)) param1 = lua_tonumber(L, -1); lua_pop(L, 1); u8 param2 = 0; lua_getfield(L, index, "param2"); if (!lua_isnil(L, -1)) param2 = lua_tonumber(L, -1); lua_pop(L, 1); return MapNode(ndef, name, param1, param2); } /******************************************************************************/ void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef) { lua_newtable(L); lua_pushstring(L, ndef->get(n).name.c_str()); lua_setfield(L, -2, "name"); lua_pushnumber(L, n.getParam1()); lua_setfield(L, -2, "param1"); lua_pushnumber(L, n.getParam2()); lua_setfield(L, -2, "param2"); } /******************************************************************************/ void warn_if_field_exists(lua_State *L, int table, const char *name, const std::string &message) { lua_getfield(L, table, name); if (!lua_isnil(L, -1)) { warningstream << "Field \"" << name << "\": " << message << std::endl; infostream << script_get_backtrace(L) << std::endl; } lua_pop(L, 1); } /******************************************************************************/ int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, int default_) { int result = default_; string_to_enum(spec, result, getstringfield_default(L, table, fieldname, "")); return result; } /******************************************************************************/ bool string_to_enum(const EnumString *spec, int &result, const std::string &str) { const EnumString *esp = spec; while(esp->str){ if(str == std::string(esp->str)){ result = esp->num; return true; } esp++; } return false; } /******************************************************************************/ ItemStack read_item(lua_State* L, int index, IItemDefManager *idef) { if(index < 0) index = lua_gettop(L) + 1 + index; if(lua_isnil(L, index)) { return ItemStack(); } else if(lua_isuserdata(L, index)) { // Convert from LuaItemStack LuaItemStack *o = LuaItemStack::checkobject(L, index); return o->getItem(); } else if(lua_isstring(L, index)) { // Convert from itemstring std::string itemstring = lua_tostring(L, index); try { ItemStack item; item.deSerialize(itemstring, idef); return item; } catch(SerializationError &e) { warningstream<<"unable to create item from itemstring" <<": "<<itemstring<<std::endl; return ItemStack(); } } else if(lua_istable(L, index)) { // Convert from table std::string name = getstringfield_default(L, index, "name", ""); int count = getintfield_default(L, index, "count", 1); int wear = getintfield_default(L, index, "wear", 0); ItemStack istack(name, count, wear, idef); // BACKWARDS COMPATIBLITY std::string value = getstringfield_default(L, index, "metadata", ""); istack.metadata.setString("", value); // Get meta lua_getfield(L, index, "meta"); int fieldstable = lua_gettop(L); if (lua_istable(L, fieldstable)) { lua_pushnil(L); while (lua_next(L, fieldstable) != 0) { // key at index -2 and value at index -1 std::string key = lua_tostring(L, -2); size_t value_len; const char *value_cs = lua_tolstring(L, -1, &value_len); std::string value(value_cs, value_len); istack.metadata.setString(key, value); lua_pop(L, 1); // removes value, keeps key for next iteration } } return istack; } else { throw LuaError("Expecting itemstack, itemstring, table or nil"); } } /******************************************************************************/ void push_tool_capabilities(lua_State *L, const ToolCapabilities &toolcap) { lua_newtable(L); setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval); setintfield(L, -1, "max_drop_level", toolcap.max_drop_level); // Create groupcaps table lua_newtable(L); // For each groupcap for (ToolGCMap::const_iterator i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); ++i) { // Create groupcap table lua_newtable(L); const std::string &name = i->first; const ToolGroupCap &groupcap = i->second; // Create subtable "times" lua_newtable(L); for (std::unordered_map<int, float>::const_iterator i = groupcap.times.begin(); i != groupcap.times.end(); ++i) { lua_pushinteger(L, i->first); lua_pushnumber(L, i->second); lua_settable(L, -3); } // Set subtable "times" lua_setfield(L, -2, "times"); // Set simple parameters setintfield(L, -1, "maxlevel", groupcap.maxlevel); setintfield(L, -1, "uses", groupcap.uses); // Insert groupcap table into groupcaps table lua_setfield(L, -2, name.c_str()); } // Set groupcaps table lua_setfield(L, -2, "groupcaps"); //Create damage_groups table lua_newtable(L); // For each damage group for (DamageGroup::const_iterator i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); ++i) { // Create damage group table lua_pushinteger(L, i->second); lua_setfield(L, -2, i->first.c_str()); } lua_setfield(L, -2, "damage_groups"); } /******************************************************************************/ void push_inventory_list(lua_State *L, Inventory *inv, const char *name) { InventoryList *invlist = inv->getList(name); if(invlist == NULL){ lua_pushnil(L); return; } std::vector<ItemStack> items; for(u32 i=0; i<invlist->getSize(); i++) items.push_back(invlist->getItem(i)); push_items(L, items); } /******************************************************************************/ void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, Server* srv, int forcesize) { if(tableindex < 0) tableindex = lua_gettop(L) + 1 + tableindex; // If nil, delete list if(lua_isnil(L, tableindex)){ inv->deleteList(name); return; } // Otherwise set list std::vector<ItemStack> items = read_items(L, tableindex,srv); int listsize = (forcesize != -1) ? forcesize : items.size(); InventoryList *invlist = inv->addList(name, listsize); int index = 0; for(std::vector<ItemStack>::const_iterator i = items.begin(); i != items.end(); ++i){ if(forcesize != -1 && index == forcesize) break; invlist->changeItem(index, *i); index++; } while(forcesize != -1 && index < forcesize){ invlist->deleteItem(index); index++; } } /******************************************************************************/ struct TileAnimationParams read_animation_definition(lua_State *L, int index) { if(index < 0) index = lua_gettop(L) + 1 + index; struct TileAnimationParams anim; anim.type = TAT_NONE; if (!lua_istable(L, index)) return anim; anim.type = (TileAnimationType) getenumfield(L, index, "type", es_TileAnimationType, TAT_NONE); if (anim.type == TAT_VERTICAL_FRAMES) { // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0} anim.vertical_frames.aspect_w = getintfield_default(L, index, "aspect_w", 16); anim.vertical_frames.aspect_h = getintfield_default(L, index, "aspect_h", 16); anim.vertical_frames.length = getfloatfield_default(L, index, "length", 1.0); } else if (anim.type == TAT_SHEET_2D) { // {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5} getintfield(L, index, "frames_w", anim.sheet_2d.frames_w); getintfield(L, index, "frames_h", anim.sheet_2d.frames_h); getfloatfield(L, index, "frame_length", anim.sheet_2d.frame_length); } return anim; }