1 /*
2 script/common/c_content.cpp
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 */
5 
6 /*
7 This file is part of Freeminer.
8 
9 Freeminer is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13 
14 Freeminer  is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18 
19 You should have received a copy of the GNU General Public License
20 along with Freeminer.  If not, see <http://www.gnu.org/licenses/>.
21 */
22 #include "common/c_content.h"
23 #include "common/c_converter.h"
24 #include "common/c_types.h"
25 #include "nodedef.h"
26 #include "itemdef.h"
27 #include "object_properties.h"
28 #include "cpp_api/s_node.h"
29 #include "lua_api/l_object.h"
30 #include "lua_api/l_item.h"
31 #include "common/c_internal.h"
32 #include "server.h"
33 #include "log.h"
34 #include "tool.h"
35 #include "serverobject.h"
36 #include "porting.h"
37 #include "mg_schematic.h"
38 #include "noise.h"
39 #include "json/json.h"
40 
41 struct EnumString es_TileAnimationType[] =
42 {
43 	{TAT_NONE, "none"},
44 	{TAT_VERTICAL_FRAMES, "vertical_frames"},
45 	{0, NULL},
46 };
47 
48 /******************************************************************************/
read_item_definition(lua_State * L,int index,ItemDefinition default_def)49 ItemDefinition read_item_definition(lua_State* L,int index,
50 		ItemDefinition default_def)
51 {
52 	if(index < 0)
53 		index = lua_gettop(L) + 1 + index;
54 
55 	// Read the item definition
56 	ItemDefinition def = default_def;
57 
58 	def.type = (ItemType)getenumfield(L, index, "type",
59 			es_ItemType, ITEM_NONE);
60 	getstringfield(L, index, "name", def.name);
61 	getstringfield(L, index, "description", def.description);
62 	getstringfield(L, index, "inventory_image", def.inventory_image);
63 	getstringfield(L, index, "wield_image", def.wield_image);
64 
65 	lua_getfield(L, index, "wield_scale");
66 	if(lua_istable(L, -1)){
67 		def.wield_scale = check_v3f(L, -1);
68 	}
69 	lua_pop(L, 1);
70 
71 	def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
72 	if(def.stack_max == 0)
73 		def.stack_max = 1;
74 
75 	lua_getfield(L, index, "on_use");
76 	def.usable = lua_isfunction(L, -1);
77 	lua_pop(L, 1);
78 
79 	getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
80 
81 	warn_if_field_exists(L, index, "tool_digging_properties",
82 			"deprecated: use tool_capabilities");
83 
84 	lua_getfield(L, index, "tool_capabilities");
85 	if(lua_istable(L, -1)){
86 		def.tool_capabilities = new ToolCapabilities(
87 				read_tool_capabilities(L, -1));
88 	}
89 
90 	// If name is "" (hand), ensure there are ToolCapabilities
91 	// because it will be looked up there whenever any other item has
92 	// no ToolCapabilities
93 	if(def.name == "" && def.tool_capabilities == NULL){
94 		def.tool_capabilities = new ToolCapabilities();
95 	}
96 
97 	lua_getfield(L, index, "groups");
98 	read_groups(L, -1, def.groups);
99 	lua_pop(L, 1);
100 
101 	lua_getfield(L, index, "sounds");
102 	if(lua_istable(L, -1)){
103 		lua_getfield(L, -1, "place");
104 		read_soundspec(L, -1, def.sound_place);
105 		lua_pop(L, 1);
106 	}
107 	lua_pop(L, 1);
108 
109 	def.range = getfloatfield_default(L, index, "range", def.range);
110 
111 	// Client shall immediately place this node when player places the item.
112 	// Server will update the precise end result a moment later.
113 	// "" = no prediction
114 	getstringfield(L, index, "node_placement_prediction",
115 			def.node_placement_prediction);
116 
117 	return def;
118 }
119 
120 /******************************************************************************/
read_object_properties(lua_State * L,int index,ObjectProperties * prop)121 void read_object_properties(lua_State *L, int index,
122 		ObjectProperties *prop)
123 {
124 	if(index < 0)
125 		index = lua_gettop(L) + 1 + index;
126 	if(!lua_istable(L, index))
127 		return;
128 
129 	prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
130 
131 	getboolfield(L, -1, "physical", prop->physical);
132 	getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
133 
134 	getfloatfield(L, -1, "weight", prop->weight);
135 
136 	lua_getfield(L, -1, "collisionbox");
137 	if(lua_istable(L, -1))
138 		prop->collisionbox = read_aabb3f(L, -1, 1.0);
139 	lua_pop(L, 1);
140 
141 	getstringfield(L, -1, "visual", prop->visual);
142 
143 	getstringfield(L, -1, "mesh", prop->mesh);
144 
145 	lua_getfield(L, -1, "visual_size");
146 	if(lua_istable(L, -1))
147 		prop->visual_size = read_v2f(L, -1);
148 	lua_pop(L, 1);
149 
150 	lua_getfield(L, -1, "textures");
151 	if(lua_istable(L, -1)){
152 		prop->textures.clear();
153 		int table = lua_gettop(L);
154 		lua_pushnil(L);
155 		while(lua_next(L, table) != 0){
156 			// key at index -2 and value at index -1
157 			if(lua_isstring(L, -1))
158 				prop->textures.push_back(lua_tostring(L, -1));
159 			else
160 				prop->textures.push_back("");
161 			// removes value, keeps key for next iteration
162 			lua_pop(L, 1);
163 		}
164 	}
165 	lua_pop(L, 1);
166 
167 	lua_getfield(L, -1, "colors");
168 	if(lua_istable(L, -1)){
169 		prop->colors.clear();
170 		int table = lua_gettop(L);
171 		lua_pushnil(L);
172 		while(lua_next(L, table) != 0){
173 			// key at index -2 and value at index -1
174 			if(lua_isstring(L, -1))
175 				prop->colors.push_back(readARGB8(L, -1));
176 			else
177 				prop->colors.push_back(video::SColor(255, 255, 255, 255));
178 			// removes value, keeps key for next iteration
179 			lua_pop(L, 1);
180 		}
181 	}
182 	lua_pop(L, 1);
183 
184 	lua_getfield(L, -1, "spritediv");
185 	if(lua_istable(L, -1))
186 		prop->spritediv = read_v2s16(L, -1);
187 	lua_pop(L, 1);
188 
189 	lua_getfield(L, -1, "initial_sprite_basepos");
190 	if(lua_istable(L, -1))
191 		prop->initial_sprite_basepos = read_v2s16(L, -1);
192 	lua_pop(L, 1);
193 
194 	getboolfield(L, -1, "is_visible", prop->is_visible);
195 	getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
196 	getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
197 	getfloatfield(L, -1, "stepheight", prop->stepheight);
198 	prop->stepheight*=BS;
199 	lua_getfield(L, -1, "automatic_face_movement_dir");
200 	if (lua_isnumber(L, -1)) {
201 		prop->automatic_face_movement_dir = true;
202 		prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
203 	} else if (lua_isboolean(L, -1)) {
204 		prop->automatic_face_movement_dir = lua_toboolean(L, -1);
205 		prop->automatic_face_movement_dir_offset = 0.0;
206 	}
207 	lua_pop(L, 1);
208 }
209 
210 /******************************************************************************/
read_tiledef(lua_State * L,int index)211 TileDef read_tiledef(lua_State *L, int index)
212 {
213 	if(index < 0)
214 		index = lua_gettop(L) + 1 + index;
215 
216 	TileDef tiledef;
217 
218 	// key at index -2 and value at index
219 	if(lua_isstring(L, index)){
220 		// "default_lava.png"
221 		tiledef.name = lua_tostring(L, index);
222 	}
223 	else if(lua_istable(L, index))
224 	{
225 		// {name="default_lava.png", animation={}}
226 		tiledef.name = "";
227 		getstringfield(L, index, "name", tiledef.name);
228 		getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
229 		tiledef.backface_culling = getboolfield_default(
230 					L, index, "backface_culling", true);
231 		// animation = {}
232 		lua_getfield(L, index, "animation");
233 		if(lua_istable(L, -1)){
234 			// {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
235 			tiledef.animation.type = (TileAnimationType)
236 					getenumfield(L, -1, "type", es_TileAnimationType,
237 					TAT_NONE);
238 			tiledef.animation.aspect_w =
239 					getintfield_default(L, -1, "aspect_w", 16);
240 			tiledef.animation.aspect_h =
241 					getintfield_default(L, -1, "aspect_h", 16);
242 			tiledef.animation.length =
243 					getfloatfield_default(L, -1, "length", 1.0);
244 		}
245 		lua_pop(L, 1);
246 	}
247 
248 	return tiledef;
249 }
250 
251 /******************************************************************************/
read_content_features(lua_State * L,int index)252 ContentFeatures read_content_features(lua_State *L, int index)
253 {
254 	if(index < 0)
255 		index = lua_gettop(L) + 1 + index;
256 
257 	ContentFeatures f;
258 
259 	/* Cache existence of some callbacks */
260 	lua_getfield(L, index, "on_construct");
261 	if(!lua_isnil(L, -1)) f.has_on_construct = true;
262 	lua_pop(L, 1);
263 	lua_getfield(L, index, "on_destruct");
264 	if(!lua_isnil(L, -1)) f.has_on_destruct = true;
265 	lua_pop(L, 1);
266 	lua_getfield(L, index, "after_destruct");
267 	if(!lua_isnil(L, -1)) f.has_after_destruct = true;
268 	lua_pop(L, 1);
269 	lua_getfield(L, index, "on_activate");
270 	if(!lua_isnil(L, -1))
271 	{
272 		f.has_on_activate = true;
273 		f.is_circuit_element = true;
274 	}
275 	lua_pop(L, 1);
276 	lua_getfield(L, index, "on_deactivate");
277 	if(!lua_isnil(L, -1))
278 	{
279 		f.has_on_deactivate = true;
280 		f.is_circuit_element = true;
281 	}
282 	lua_pop(L, 1);
283 
284 	lua_getfield(L, index, "on_rightclick");
285 	f.rightclickable = lua_isfunction(L, -1);
286 	lua_pop(L, 1);
287 
288 	/* Name */
289 	getstringfield(L, index, "name", f.name);
290 
291 	/* Groups */
292 	lua_getfield(L, index, "groups");
293 	read_groups(L, -1, f.groups);
294 	lua_pop(L, 1);
295 
296 	/* Visual definition */
297 
298 	f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
299 			ScriptApiNode::es_DrawType,NDT_NORMAL);
300 	getfloatfield(L, index, "visual_scale", f.visual_scale);
301 
302 	/* Meshnode model filename */
303 	getstringfield(L, index, "mesh", f.mesh);
304 
305 	// tiles = {}
306 	lua_getfield(L, index, "tiles");
307 	// If nil, try the deprecated name "tile_images" instead
308 	if(lua_isnil(L, -1)){
309 		lua_pop(L, 1);
310 		warn_if_field_exists(L, index, "tile_images",
311 				"Deprecated; new name is \"tiles\".");
312 		lua_getfield(L, index, "tile_images");
313 	}
314 	if(lua_istable(L, -1)){
315 		int table = lua_gettop(L);
316 		lua_pushnil(L);
317 		int i = 0;
318 		while(lua_next(L, table) != 0){
319 			// Read tiledef from value
320 			f.tiledef[i] = read_tiledef(L, -1);
321 			// removes value, keeps key for next iteration
322 			lua_pop(L, 1);
323 			i++;
324 			if(i==6){
325 				lua_pop(L, 1);
326 				break;
327 			}
328 		}
329 		// Copy last value to all remaining textures
330 		if(i >= 1){
331 			TileDef lasttile = f.tiledef[i-1];
332 			while(i < 6){
333 				f.tiledef[i] = lasttile;
334 				i++;
335 			}
336 		}
337 	}
338 	lua_pop(L, 1);
339 
340 	/* Circuit options */
341 	lua_getfield(L, index, "is_wire");
342 	if(!lua_isnil(L, -1)) {
343 		f.is_wire = true;
344 	}
345 	lua_pop(L, 1);
346 
347 	lua_getfield(L, index, "is_wire_connector");
348 	if(!lua_isnil(L, -1)) {
349 		f.is_wire_connector = true;
350 	}
351 	lua_pop(L, 1);
352 
353 	lua_getfield(L, index, "wire_connections");
354 	if(!lua_isnil(L, -1) && lua_istable(L, -1)) {
355 		// Both can't be set to true
356 		f.is_wire |= !f.is_wire_connector;
357 		int table = lua_gettop(L);
358 		lua_pushnil(L);
359 		int i;
360 		unsigned char current_shift = 1;
361 		for(i = 0; (i < 6) && (lua_next(L, table) != 0); ++i) {
362 			f.wire_connections[i] = lua_tonumber(L, -1);
363 			f.wire_connections[i] |= current_shift;
364 			current_shift <<= 1;
365 			lua_pop(L, 1);
366 		}
367 		if(i < 6) {
368 			luaL_error(L, "Wire connectins array must have exactly 6 integer numbers.");
369 		}
370 
371 		// Convert to two-way wire (one-way may cause undefined behavior)
372 		for(i = 0; i < 6; ++i) {
373 			for(int j = 0; j < 6; ++j) {
374 				f.wire_connections[i] |= f.wire_connections[j] & (1 << i);
375 				f.wire_connections[j] |= f.wire_connections[i] & (1 << j);
376 			}
377 		}
378 
379 	} else if(f.is_wire || f.is_wire_connector) {
380 		// Assuming that it's a standart wire or wire connector
381 		for(int i = 0; i < 6; ++i) {
382 			f.wire_connections[i] = 0x3F;
383 		}
384 	}
385 	lua_pop(L, 1);
386 
387 	lua_getfield(L, index, "circuit_states");
388 	if(!lua_isnil(L, -1) && lua_istable(L, -1)) {
389 		f.is_circuit_element = true;
390 		int table = lua_gettop(L);
391 		lua_pushnil(L);
392 		int i;
393 		for(i = 0; (i < 64) && (lua_next(L, table) != 0); ++i) {
394 			f.circuit_element_func[i] = lua_tonumber(L, -1);
395 			lua_pop(L, 1);
396 		}
397 		if(i < 64) {
398 			luaL_error(L, "Circuit element states table must have exactly 64 integer numbers.");
399 		}
400 	}
401 	lua_pop(L, 1);
402 
403 	f.circuit_element_delay = getintfield_default(L, index, "circuit_element_delay", f.circuit_element_delay + 1) - 1;
404 	if(f.circuit_element_delay > 100) {
405 		luaL_error(L, "\"circuit_element_delay\" must be a positive integer number less than 101");
406 	}
407 
408 	// special_tiles = {}
409 	lua_getfield(L, index, "special_tiles");
410 	// If nil, try the deprecated name "special_materials" instead
411 	if(lua_isnil(L, -1)){
412 		lua_pop(L, 1);
413 		warn_if_field_exists(L, index, "special_materials",
414 				"Deprecated; new name is \"special_tiles\".");
415 		lua_getfield(L, index, "special_materials");
416 	}
417 	if(lua_istable(L, -1)){
418 		int table = lua_gettop(L);
419 		lua_pushnil(L);
420 		int i = 0;
421 		while(lua_next(L, table) != 0){
422 			// Read tiledef from value
423 			f.tiledef_special[i] = read_tiledef(L, -1);
424 			// removes value, keeps key for next iteration
425 			lua_pop(L, 1);
426 			i++;
427 			if(i==CF_SPECIAL_COUNT){
428 				lua_pop(L, 1);
429 				break;
430 			}
431 		}
432 	}
433 	lua_pop(L, 1);
434 
435 	f.alpha = getintfield_default(L, index, "alpha", 255);
436 
437 	bool usealpha = getboolfield_default(L, index,
438 			"use_texture_alpha", false);
439 	if (usealpha)
440 		f.alpha = 0;
441 
442 	/* Other stuff */
443 
444 	lua_getfield(L, index, "post_effect_color");
445 	if(!lua_isnil(L, -1))
446 		f.post_effect_color = readARGB8(L, -1);
447 	lua_pop(L, 1);
448 
449 	f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
450 			ScriptApiNode::es_ContentParamType, CPT_NONE);
451 	f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
452 			ScriptApiNode::es_ContentParamType2, CPT2_NONE);
453 
454 	// Warn about some deprecated fields
455 	warn_if_field_exists(L, index, "wall_mounted",
456 			"deprecated: use paramtype2 = 'wallmounted'");
457 	warn_if_field_exists(L, index, "light_propagates",
458 			"deprecated: determined from paramtype");
459 	warn_if_field_exists(L, index, "dug_item",
460 			"deprecated: use 'drop' field");
461 	warn_if_field_exists(L, index, "extra_dug_item",
462 			"deprecated: use 'drop' field");
463 	warn_if_field_exists(L, index, "extra_dug_item_rarity",
464 			"deprecated: use 'drop' field");
465 	warn_if_field_exists(L, index, "metadata_name",
466 			"deprecated: use on_add and metadata callbacks");
467 
468 	// True for all ground-like things like stone and mud, false for eg. trees
469 	getboolfield(L, index, "is_ground_content", f.is_ground_content);
470 	f.light_propagates = (f.param_type == CPT_LIGHT);
471 	getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
472 	// This is used for collision detection.
473 	// Also for general solidness queries.
474 	getboolfield(L, index, "walkable", f.walkable);
475 	// Player can point to these
476 	getboolfield(L, index, "pointable", f.pointable);
477 	// Player can dig these
478 	getboolfield(L, index, "diggable", f.diggable);
479 	// Player can climb these
480 	getboolfield(L, index, "climbable", f.climbable);
481 	// Player can build on these
482 	getboolfield(L, index, "buildable_to", f.buildable_to);
483 	// Whether the node is non-liquid, source liquid or flowing liquid
484 	f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
485 			ScriptApiNode::es_LiquidType, LIQUID_NONE);
486 	// If the content is liquid, this is the flowing version of the liquid.
487 	getstringfield(L, index, "liquid_alternative_flowing",
488 			f.liquid_alternative_flowing);
489 	// If the content is liquid, this is the source version of the liquid.
490 	getstringfield(L, index, "liquid_alternative_source",
491 			f.liquid_alternative_source);
492 	// Viscosity for fluid flow, ranging from 1 to 7, with
493 	// 1 giving almost instantaneous propagation and 7 being
494 	// the slowest possible
495 	f.liquid_viscosity = getintfield_default(L, index,
496 			"liquid_viscosity", f.liquid_viscosity);
497 
498 	f.leveled = getintfield_default(L, index, "leveled", f.leveled);
499 
500 	getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
501 	getstringfield(L, index, "freeze", f.freeze);
502 	getstringfield(L, index, "melt", f.melt);
503 	f.drowning = getintfield_default(L, index,
504 			"drowning", f.drowning);
505 	// Amount of light the node emits
506 	f.light_source = getintfield_default(L, index,
507 			"light_source", f.light_source);
508 	f.damage_per_second = getintfield_default(L, index,
509 			"damage_per_second", f.damage_per_second);
510 
511 	lua_getfield(L, index, "node_box");
512 	if(lua_istable(L, -1))
513 		f.node_box = read_nodebox(L, -1);
514 	lua_pop(L, 1);
515 
516 	lua_getfield(L, index, "selection_box");
517 	if(lua_istable(L, -1))
518 		f.selection_box = read_nodebox(L, -1);
519  	lua_pop(L, 1);
520 
521 	lua_getfield(L, index, "collision_box");
522 	if(lua_istable(L, -1))
523 		f.collision_box = read_nodebox(L, -1);
524 	lua_pop(L, 1);
525 
526 	f.waving = getintfield_default(L, index,
527 			"waving", f.waving);
528 
529 	// Set to true if paramtype used to be 'facedir_simple'
530 	getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
531 	// Set to true if wall_mounted used to be set to true
532 	getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
533 
534 	// Sound table
535 	lua_getfield(L, index, "sounds");
536 	if(lua_istable(L, -1)){
537 		lua_getfield(L, -1, "footstep");
538 		read_soundspec(L, -1, f.sound_footstep);
539 		lua_pop(L, 1);
540 		lua_getfield(L, -1, "dig");
541 		read_soundspec(L, -1, f.sound_dig);
542 		lua_pop(L, 1);
543 		lua_getfield(L, -1, "dug");
544 		read_soundspec(L, -1, f.sound_dug);
545 		lua_pop(L, 1);
546 	}
547 	lua_pop(L, 1);
548 
549 	return f;
550 }
551 
552 /******************************************************************************/
read_server_sound_params(lua_State * L,int index,ServerSoundParams & params)553 void read_server_sound_params(lua_State *L, int index,
554 		ServerSoundParams &params)
555 {
556 	if(index < 0)
557 		index = lua_gettop(L) + 1 + index;
558 	// Clear
559 	params = ServerSoundParams();
560 	if(lua_istable(L, index)){
561 		getfloatfield(L, index, "gain", params.gain);
562 		getstringfield(L, index, "to_player", params.to_player);
563 		lua_getfield(L, index, "pos");
564 		if(!lua_isnil(L, -1)){
565 			v3f p = read_v3f(L, -1)*BS;
566 			params.pos = p;
567 			params.type = ServerSoundParams::SSP_POSITIONAL;
568 		}
569 		lua_pop(L, 1);
570 		lua_getfield(L, index, "object");
571 		if(!lua_isnil(L, -1)){
572 			ObjectRef *ref = ObjectRef::checkobject(L, -1);
573 			ServerActiveObject *sao = ObjectRef::getobject(ref);
574 			if(sao){
575 				params.object = sao->getId();
576 				params.type = ServerSoundParams::SSP_OBJECT;
577 			}
578 		}
579 		lua_pop(L, 1);
580 		params.max_hear_distance = BS*getfloatfield_default(L, index,
581 				"max_hear_distance", params.max_hear_distance/BS);
582 		getboolfield(L, index, "loop", params.loop);
583 	}
584 }
585 
586 /******************************************************************************/
read_soundspec(lua_State * L,int index,SimpleSoundSpec & spec)587 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
588 {
589 	if(index < 0)
590 		index = lua_gettop(L) + 1 + index;
591 	if(lua_isnil(L, index)){
592 	} else if(lua_istable(L, index)){
593 		getstringfield(L, index, "name", spec.name);
594 		getfloatfield(L, index, "gain", spec.gain);
595 	} else if(lua_isstring(L, index)){
596 		spec.name = lua_tostring(L, index);
597 	}
598 }
599 
600 /******************************************************************************/
read_nodebox(lua_State * L,int index)601 NodeBox read_nodebox(lua_State *L, int index)
602 {
603 	NodeBox nodebox;
604 	if(lua_istable(L, -1)){
605 		nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
606 				ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
607 
608 		lua_getfield(L, index, "fixed");
609 		if(lua_istable(L, -1))
610 			nodebox.fixed = read_aabb3f_vector(L, -1, BS);
611 		lua_pop(L, 1);
612 
613 		lua_getfield(L, index, "wall_top");
614 		if(lua_istable(L, -1))
615 			nodebox.wall_top = read_aabb3f(L, -1, BS);
616 		lua_pop(L, 1);
617 
618 		lua_getfield(L, index, "wall_bottom");
619 		if(lua_istable(L, -1))
620 			nodebox.wall_bottom = read_aabb3f(L, -1, BS);
621 		lua_pop(L, 1);
622 
623 		lua_getfield(L, index, "wall_side");
624 		if(lua_istable(L, -1))
625 			nodebox.wall_side = read_aabb3f(L, -1, BS);
626 		lua_pop(L, 1);
627 	}
628 	return nodebox;
629 }
630 
631 /******************************************************************************/
readnode(lua_State * L,int index,INodeDefManager * ndef)632 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
633 {
634 	lua_getfield(L, index, "name");
635 	const char *name = luaL_checkstring(L, -1);
636 	lua_pop(L, 1);
637 	u8 param1;
638 	lua_getfield(L, index, "param1");
639 	if(lua_isnil(L, -1))
640 		param1 = 0;
641 	else
642 		param1 = lua_tonumber(L, -1);
643 	lua_pop(L, 1);
644 	u8 param2;
645 	lua_getfield(L, index, "param2");
646 	if(lua_isnil(L, -1))
647 		param2 = 0;
648 	else
649 		param2 = lua_tonumber(L, -1);
650 	lua_pop(L, 1);
651 	return MapNode(ndef, name, param1, param2);
652 }
653 
654 /******************************************************************************/
pushnode(lua_State * L,const MapNode & n,INodeDefManager * ndef)655 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
656 {
657 	lua_newtable(L);
658 	lua_pushstring(L, ndef->get(n).name.c_str());
659 	lua_setfield(L, -2, "name");
660 	lua_pushnumber(L, n.getParam1());
661 	lua_setfield(L, -2, "param1");
662 	lua_pushnumber(L, n.getParam2());
663 	lua_setfield(L, -2, "param2");
664 }
665 
666 /******************************************************************************/
warn_if_field_exists(lua_State * L,int table,const char * fieldname,const std::string & message)667 void warn_if_field_exists(lua_State *L, int table,
668 		const char *fieldname, const std::string &message)
669 {
670 	lua_getfield(L, table, fieldname);
671 	if(!lua_isnil(L, -1)){
672 //TODO find way to access backtrace fct from here
673 		//		infostream<<script_get_backtrace(L)<<std::endl;
674 		infostream<<"WARNING: field \""<<fieldname<<"\": "
675 				<<message<<std::endl;
676 	}
677 	lua_pop(L, 1);
678 }
679 
680 /******************************************************************************/
getenumfield(lua_State * L,int table,const char * fieldname,const EnumString * spec,int default_)681 int getenumfield(lua_State *L, int table,
682 		const char *fieldname, const EnumString *spec, int default_)
683 {
684 	int result = default_;
685 	string_to_enum(spec, result,
686 			getstringfield_default(L, table, fieldname, ""));
687 	return result;
688 }
689 
690 /******************************************************************************/
string_to_enum(const EnumString * spec,int & result,const std::string & str)691 bool string_to_enum(const EnumString *spec, int &result,
692 		const std::string &str)
693 {
694 	const EnumString *esp = spec;
695 	while(esp->str){
696 		if(str == std::string(esp->str)){
697 			result = esp->num;
698 			return true;
699 		}
700 		esp++;
701 	}
702 	return false;
703 }
704 
705 /******************************************************************************/
read_item(lua_State * L,int index,Server * srv)706 ItemStack read_item(lua_State* L, int index,Server* srv)
707 {
708 	if(index < 0)
709 		index = lua_gettop(L) + 1 + index;
710 
711 	if(lua_isnil(L, index))
712 	{
713 		return ItemStack();
714 	}
715 	else if(lua_isuserdata(L, index))
716 	{
717 		// Convert from LuaItemStack
718 		LuaItemStack *o = LuaItemStack::checkobject(L, index);
719 		return o->getItem();
720 	}
721 	else if(lua_isstring(L, index))
722 	{
723 		// Convert from itemstring
724 		std::string itemstring = lua_tostring(L, index);
725 		IItemDefManager *idef = srv->idef();
726 		try
727 		{
728 			ItemStack item;
729 			item.deSerialize(itemstring, idef);
730 			return item;
731 		}
732 		catch(SerializationError &e)
733 		{
734 			infostream<<"WARNING: unable to create item from itemstring"
735 					<<": "<<itemstring<<std::endl;
736 			return ItemStack();
737 		}
738 	}
739 	else if(lua_istable(L, index))
740 	{
741 		// Convert from table
742 		IItemDefManager *idef = srv->idef();
743 		std::string name = getstringfield_default(L, index, "name", "");
744 		int count = getintfield_default(L, index, "count", 1);
745 		int wear = getintfield_default(L, index, "wear", 0);
746 		std::string metadata = getstringfield_default(L, index, "metadata", "");
747 		return ItemStack(name, count, wear, metadata, idef);
748 	}
749 	else
750 	{
751 		throw LuaError("Expecting itemstack, itemstring, table or nil");
752 	}
753 }
754 
755 /******************************************************************************/
push_tool_capabilities(lua_State * L,const ToolCapabilities & toolcap)756 void push_tool_capabilities(lua_State *L,
757 		const ToolCapabilities &toolcap)
758 {
759 	lua_newtable(L);
760 	setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
761 		setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
762 		// Create groupcaps table
763 		lua_newtable(L);
764 		// For each groupcap
765 		for(std::map<std::string, ToolGroupCap>::const_iterator
766 				i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
767 			// Create groupcap table
768 			lua_newtable(L);
769 			const std::string &name = i->first;
770 			const ToolGroupCap &groupcap = i->second;
771 			// Create subtable "times"
772 			lua_newtable(L);
773 			for(std::map<int, float>::const_iterator
774 					i = groupcap.times.begin(); i != groupcap.times.end(); i++){
775 				int rating = i->first;
776 				float time = i->second;
777 				lua_pushinteger(L, rating);
778 				lua_pushnumber(L, time);
779 				lua_settable(L, -3);
780 			}
781 			// Set subtable "times"
782 			lua_setfield(L, -2, "times");
783 			// Set simple parameters
784 			setintfield(L, -1, "maxlevel", groupcap.maxlevel);
785 			setintfield(L, -1, "uses", groupcap.uses);
786 			// Insert groupcap table into groupcaps table
787 			lua_setfield(L, -2, name.c_str());
788 		}
789 		// Set groupcaps table
790 		lua_setfield(L, -2, "groupcaps");
791 		//Create damage_groups table
792 		lua_newtable(L);
793 		// For each damage group
794 		for(std::map<std::string, s16>::const_iterator
795 				i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
796 			// Create damage group table
797 			lua_pushinteger(L, i->second);
798 			lua_setfield(L, -2, i->first.c_str());
799 		}
800 		lua_setfield(L, -2, "damage_groups");
801 }
802 
803 /******************************************************************************/
push_inventory_list(lua_State * L,Inventory * inv,const char * name)804 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
805 {
806 	InventoryList *invlist = inv->getList(name);
807 	if(invlist == NULL){
808 		lua_pushnil(L);
809 		return;
810 	}
811 	std::vector<ItemStack> items;
812 	for(u32 i=0; i<invlist->getSize(); i++)
813 		items.push_back(invlist->getItem(i));
814 	push_items(L, items);
815 }
816 
817 /******************************************************************************/
read_inventory_list(lua_State * L,int tableindex,Inventory * inv,const char * name,Server * srv,int forcesize)818 void read_inventory_list(lua_State *L, int tableindex,
819 		Inventory *inv, const char *name, Server* srv, int forcesize)
820 {
821 	if(tableindex < 0)
822 		tableindex = lua_gettop(L) + 1 + tableindex;
823 	// If nil, delete list
824 	if(lua_isnil(L, tableindex)){
825 		inv->deleteList(name);
826 		return;
827 	}
828 	// Otherwise set list
829 	std::vector<ItemStack> items = read_items(L, tableindex,srv);
830 	int listsize = (forcesize != -1) ? forcesize : items.size();
831 	InventoryList *invlist = inv->addList(name, listsize);
832 	int index = 0;
833 	for(std::vector<ItemStack>::const_iterator
834 			i = items.begin(); i != items.end(); i++){
835 		if(forcesize != -1 && index == forcesize)
836 			break;
837 		invlist->changeItem(index, *i);
838 		index++;
839 	}
840 	while(forcesize != -1 && index < forcesize){
841 		invlist->deleteItem(index);
842 		index++;
843 	}
844 }
845 
846 /******************************************************************************/
read_tool_capabilities(lua_State * L,int table)847 ToolCapabilities read_tool_capabilities(
848 		lua_State *L, int table)
849 {
850 	ToolCapabilities toolcap;
851 	getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
852 	getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
853 	lua_getfield(L, table, "groupcaps");
854 	if(lua_istable(L, -1)){
855 		int table_groupcaps = lua_gettop(L);
856 		lua_pushnil(L);
857 		while(lua_next(L, table_groupcaps) != 0){
858 			// key at index -2 and value at index -1
859 			std::string groupname = luaL_checkstring(L, -2);
860 			if(lua_istable(L, -1)){
861 				int table_groupcap = lua_gettop(L);
862 				// This will be created
863 				ToolGroupCap groupcap;
864 				// Read simple parameters
865 				getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
866 				getintfield(L, table_groupcap, "uses", groupcap.uses);
867 				// DEPRECATED: maxwear
868 				float maxwear = 0;
869 				if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
870 					if(maxwear != 0)
871 						groupcap.uses = 1.0/maxwear;
872 					else
873 						groupcap.uses = 0;
874 					infostream<<script_get_backtrace(L)<<std::endl;
875 					infostream<<"WARNING: field \"maxwear\" is deprecated; "
876 							<<"should replace with uses=1/maxwear"<<std::endl;
877 				}
878 				// Read "times" table
879 				lua_getfield(L, table_groupcap, "times");
880 				if(lua_istable(L, -1)){
881 					int table_times = lua_gettop(L);
882 					lua_pushnil(L);
883 					while(lua_next(L, table_times) != 0){
884 						// key at index -2 and value at index -1
885 						int rating = luaL_checkinteger(L, -2);
886 						float time = luaL_checknumber(L, -1);
887 						groupcap.times[rating] = time;
888 						// removes value, keeps key for next iteration
889 						lua_pop(L, 1);
890 					}
891 				}
892 				lua_pop(L, 1);
893 				// Insert groupcap into toolcap
894 				toolcap.groupcaps[groupname] = groupcap;
895 			}
896 			// removes value, keeps key for next iteration
897 			lua_pop(L, 1);
898 		}
899 	}
900 	lua_pop(L, 1);
901 
902 	lua_getfield(L, table, "damage_groups");
903 	if(lua_istable(L, -1)){
904 		int table_damage_groups = lua_gettop(L);
905 		lua_pushnil(L);
906 		while(lua_next(L, table_damage_groups) != 0){
907 			// key at index -2 and value at index -1
908 			std::string groupname = luaL_checkstring(L, -2);
909 			u16 value = luaL_checkinteger(L, -1);
910 			toolcap.damageGroups[groupname] = value;
911 			// removes value, keeps key for next iteration
912 			lua_pop(L, 1);
913 		}
914 	}
915 	lua_pop(L, 1);
916 	return toolcap;
917 }
918 
919 /******************************************************************************/
push_dig_params(lua_State * L,const DigParams & params)920 void push_dig_params(lua_State *L,const DigParams &params)
921 {
922 	lua_newtable(L);
923 	setboolfield(L, -1, "diggable", params.diggable);
924 	setfloatfield(L, -1, "time", params.time);
925 	setintfield(L, -1, "wear", params.wear);
926 }
927 
928 /******************************************************************************/
push_hit_params(lua_State * L,const HitParams & params)929 void push_hit_params(lua_State *L,const HitParams &params)
930 {
931 	lua_newtable(L);
932 	setintfield(L, -1, "hp", params.hp);
933 	setintfield(L, -1, "wear", params.wear);
934 }
935 
936 /******************************************************************************/
937 
getflagsfield(lua_State * L,int table,const char * fieldname,FlagDesc * flagdesc,u32 * flags,u32 * flagmask)938 bool getflagsfield(lua_State *L, int table, const char *fieldname,
939 	FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
940 {
941 	lua_getfield(L, table, fieldname);
942 
943 	bool success = read_flags(L, -1, flagdesc, flags, flagmask);
944 
945 	lua_pop(L, 1);
946 
947 	return success;
948 }
949 
read_flags(lua_State * L,int index,FlagDesc * flagdesc,u32 * flags,u32 * flagmask)950 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
951 	u32 *flags, u32 *flagmask)
952 {
953 	if (lua_isstring(L, index)) {
954 		std::string flagstr = lua_tostring(L, index);
955 		*flags = readFlagString(flagstr, flagdesc, flagmask);
956 	} else if (lua_istable(L, index)) {
957 		*flags = read_flags_table(L, index, flagdesc, flagmask);
958 	} else {
959 		return false;
960 	}
961 
962 	return true;
963 }
964 
read_flags_table(lua_State * L,int table,FlagDesc * flagdesc,u32 * flagmask)965 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
966 {
967 	u32 flags = 0, mask = 0;
968 	char fnamebuf[64] = "no";
969 
970 	for (int i = 0; flagdesc[i].name; i++) {
971 		bool result;
972 
973 		if (getboolfield(L, table, flagdesc[i].name, result)) {
974 			mask |= flagdesc[i].flag;
975 			if (result)
976 				flags |= flagdesc[i].flag;
977 		}
978 
979 		strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
980 		if (getboolfield(L, table, fnamebuf, result))
981 			mask |= flagdesc[i].flag;
982 	}
983 
984 	if (flagmask)
985 		*flagmask = mask;
986 
987 	return flags;
988 }
989 
990 /******************************************************************************/
991 /* Lua Stored data!                                                           */
992 /******************************************************************************/
993 
994 /******************************************************************************/
read_groups(lua_State * L,int index,std::map<std::string,int> & result)995 void read_groups(lua_State *L, int index,
996 		std::map<std::string, int> &result)
997 {
998 	if (!lua_istable(L,index))
999 		return;
1000 	result.clear();
1001 	lua_pushnil(L);
1002 	if(index < 0)
1003 		index -= 1;
1004 	while(lua_next(L, index) != 0){
1005 		// key at index -2 and value at index -1
1006 		std::string name = luaL_checkstring(L, -2);
1007 		int rating = luaL_checkinteger(L, -1);
1008 		result[name] = rating;
1009 		// removes value, keeps key for next iteration
1010 		lua_pop(L, 1);
1011 	}
1012 }
1013 
1014 /******************************************************************************/
push_items(lua_State * L,const std::vector<ItemStack> & items)1015 void push_items(lua_State *L, const std::vector<ItemStack> &items)
1016 {
1017 	// Create and fill table
1018 	lua_createtable(L, items.size(), 0);
1019 	std::vector<ItemStack>::const_iterator iter = items.begin();
1020 	for (u32 i = 0; iter != items.end(); iter++) {
1021 		LuaItemStack::create(L, *iter);
1022 		lua_rawseti(L, -2, ++i);
1023 	}
1024 }
1025 
1026 /******************************************************************************/
read_items(lua_State * L,int index,Server * srv)1027 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
1028 {
1029 	if(index < 0)
1030 		index = lua_gettop(L) + 1 + index;
1031 
1032 	std::vector<ItemStack> items;
1033 	luaL_checktype(L, index, LUA_TTABLE);
1034 	lua_pushnil(L);
1035 	while (lua_next(L, index)) {
1036 		s32 key = luaL_checkinteger(L, -2);
1037 		if (key < 1) {
1038 			throw LuaError("Invalid inventory list index");
1039 		}
1040 		if (items.size() < (u32) key) {
1041 			items.resize(key);
1042 		}
1043 		items[key - 1] = read_item(L, -1, srv);
1044 		lua_pop(L, 1);
1045 	}
1046 	return items;
1047 }
1048 
1049 /******************************************************************************/
luaentity_get(lua_State * L,u16 id)1050 void luaentity_get(lua_State *L, u16 id)
1051 {
1052 	// Get luaentities[i]
1053 	lua_getglobal(L, "core");
1054 	lua_getfield(L, -1, "luaentities");
1055 	luaL_checktype(L, -1, LUA_TTABLE);
1056 	lua_pushnumber(L, id);
1057 	lua_gettable(L, -2);
1058 	lua_remove(L, -2); // Remove luaentities
1059 	lua_remove(L, -2); // Remove core
1060 }
1061 
1062 /******************************************************************************/
read_noiseparams(lua_State * L,int index)1063 NoiseParams *read_noiseparams(lua_State *L, int index)
1064 {
1065 	NoiseParams *np = new NoiseParams;
1066 
1067 	if (!read_noiseparams_nc(L, index, np)) {
1068 		delete np;
1069 		np = NULL;
1070 	}
1071 
1072 	return np;
1073 }
1074 
read_noiseparams_nc(lua_State * L,int index,NoiseParams * np)1075 bool read_noiseparams_nc(lua_State *L, int index, NoiseParams *np)
1076 {
1077 	if (index < 0)
1078 		index = lua_gettop(L) + 1 + index;
1079 
1080 	if (!lua_istable(L, index))
1081 		return false;
1082 
1083 	np->offset  = getfloatfield_default(L, index, "offset",  0.0);
1084 	np->scale   = getfloatfield_default(L, index, "scale",   0.0);
1085 	np->persist = getfloatfield_default(L, index, "persist", 0.0);
1086 	np->seed    = getintfield_default(L,   index, "seed",    0);
1087 	np->octaves = getintfield_default(L,   index, "octaves", 0);
1088 	np->eased   = getboolfield_default(L,  index, "eased",   false);
1089 
1090 	lua_getfield(L, index, "spread");
1091 	np->spread  = read_v3f(L, -1);
1092 	lua_pop(L, 1);
1093 
1094 	return true;
1095 }
1096 
1097 /******************************************************************************/
1098 
get_schematic(lua_State * L,int index,Schematic * schem,INodeDefManager * ndef,std::map<std::string,std::string> & replace_names)1099 bool get_schematic(lua_State *L, int index, Schematic *schem,
1100 	INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1101 {
1102 	if (index < 0)
1103 		index = lua_gettop(L) + 1 + index;
1104 
1105 	if (lua_istable(L, index)) {
1106 		return read_schematic(L, index, schem, ndef, replace_names);
1107 	} else if (lua_isstring(L, index)) {
1108 		NodeResolver *resolver = ndef->getResolver();
1109 		const char *filename = lua_tostring(L, index);
1110 		return schem->loadSchematicFromFile(filename, resolver, replace_names);
1111 	} else {
1112 		return false;
1113 	}
1114 }
1115 
read_schematic(lua_State * L,int index,Schematic * schem,INodeDefManager * ndef,std::map<std::string,std::string> & replace_names)1116 bool read_schematic(lua_State *L, int index, Schematic *schem,
1117 	INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1118 {
1119 	//// Get schematic size
1120 	lua_getfield(L, index, "size");
1121 	v3s16 size = read_v3s16(L, -1);
1122 	lua_pop(L, 1);
1123 
1124 	//// Get schematic data
1125 	lua_getfield(L, index, "data");
1126 	luaL_checktype(L, -1, LUA_TTABLE);
1127 
1128 	int numnodes = size.X * size.Y * size.Z;
1129 	MapNode *schemdata = new MapNode[numnodes];
1130 	int i = 0;
1131 
1132 	lua_pushnil(L);
1133 	while (lua_next(L, -2)) {
1134 		if (i < numnodes) {
1135 			// same as readnode, except param1 default is MTSCHEM_PROB_CONST
1136 			lua_getfield(L, -1, "name");
1137 			std::string name = luaL_checkstring(L, -1);
1138 			lua_pop(L, 1);
1139 
1140 			u8 param1;
1141 			lua_getfield(L, -1, "param1");
1142 			param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
1143 			lua_pop(L, 1);
1144 
1145 			u8 param2;
1146 			lua_getfield(L, -1, "param2");
1147 			param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
1148 			lua_pop(L, 1);
1149 
1150 			std::map<std::string, std::string>::iterator it;
1151 			it = replace_names.find(name);
1152 			if (it != replace_names.end())
1153 				name = it->second;
1154 
1155 			schemdata[i] = MapNode(ndef, name, param1, param2);
1156 		}
1157 
1158 		i++;
1159 		lua_pop(L, 1);
1160 	}
1161 
1162 	if (i != numnodes) {
1163 		errorstream << "read_schematic: incorrect number of "
1164 			"nodes provided in raw schematic data (got " << i <<
1165 			", expected " << numnodes << ")." << std::endl;
1166 		return false;
1167 	}
1168 
1169 	//// Get Y-slice probability values (if present)
1170 	u8 *slice_probs = new u8[size.Y];
1171 	for (i = 0; i != size.Y; i++)
1172 		slice_probs[i] = MTSCHEM_PROB_ALWAYS;
1173 
1174 	lua_getfield(L, index, "yslice_prob");
1175 	if (lua_istable(L, -1)) {
1176 		lua_pushnil(L);
1177 		while (lua_next(L, -2)) {
1178 			if (getintfield(L, -1, "ypos", i) && i >= 0 && i < size.Y) {
1179 				slice_probs[i] = getintfield_default(L, -1,
1180 					"prob", MTSCHEM_PROB_ALWAYS);
1181 			}
1182 			lua_pop(L, 1);
1183 		}
1184 	}
1185 
1186 	schem->flags       = 0;
1187 	schem->size        = size;
1188 	schem->schemdata   = schemdata;
1189 	schem->slice_probs = slice_probs;
1190 	return true;
1191 }
1192 
1193 /******************************************************************************/
1194 // Returns depth of json value tree
push_json_value_getdepth(const Json::Value & value)1195 static int push_json_value_getdepth(const Json::Value &value)
1196 {
1197 	if (!value.isArray() && !value.isObject())
1198 		return 1;
1199 
1200 	int maxdepth = 0;
1201 	for (Json::Value::const_iterator it = value.begin();
1202 			it != value.end(); ++it) {
1203 		int elemdepth = push_json_value_getdepth(*it);
1204 		if (elemdepth > maxdepth)
1205 			maxdepth = elemdepth;
1206 	}
1207 	return maxdepth + 1;
1208 }
1209 // Recursive function to convert JSON --> Lua table
push_json_value_helper(lua_State * L,const Json::Value & value,int nullindex)1210 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1211 		int nullindex)
1212 {
1213 	switch(value.type()) {
1214 		case Json::nullValue:
1215 		default:
1216 			lua_pushvalue(L, nullindex);
1217 			break;
1218 		case Json::intValue:
1219 			lua_pushinteger(L, value.asInt());
1220 			break;
1221 		case Json::uintValue:
1222 			lua_pushinteger(L, value.asUInt());
1223 			break;
1224 		case Json::realValue:
1225 			lua_pushnumber(L, value.asDouble());
1226 			break;
1227 		case Json::stringValue:
1228 			{
1229 				const char *str = value.asCString();
1230 				lua_pushstring(L, str ? str : "");
1231 			}
1232 			break;
1233 		case Json::booleanValue:
1234 			lua_pushboolean(L, value.asInt());
1235 			break;
1236 		case Json::arrayValue:
1237 			lua_newtable(L);
1238 			for (Json::Value::const_iterator it = value.begin();
1239 					it != value.end(); ++it) {
1240 				push_json_value_helper(L, *it, nullindex);
1241 				lua_rawseti(L, -2, it.index() + 1);
1242 			}
1243 			break;
1244 		case Json::objectValue:
1245 			lua_newtable(L);
1246 			for (Json::Value::const_iterator it = value.begin();
1247 					it != value.end(); ++it) {
1248 				const char *str = it.memberName();
1249 				lua_pushstring(L, str ? str : "");
1250 				push_json_value_helper(L, *it, nullindex);
1251 				lua_rawset(L, -3);
1252 			}
1253 			break;
1254 	}
1255 	return true;
1256 }
1257 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1258 // nullindex: Lua stack index of value to use in place of JSON null
push_json_value(lua_State * L,const Json::Value & value,int nullindex)1259 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1260 {
1261 	if(nullindex < 0)
1262 		nullindex = lua_gettop(L) + 1 + nullindex;
1263 
1264 	int depth = push_json_value_getdepth(value);
1265 
1266 	// The maximum number of Lua stack slots used at each recursion level
1267 	// of push_json_value_helper is 2, so make sure there a depth * 2 slots
1268 	if (lua_checkstack(L, depth * 2))
1269 		return push_json_value_helper(L, value, nullindex);
1270 	else
1271 		return false;
1272 }
1273 
1274 // Converts Lua table --> JSON
read_json_value(lua_State * L,Json::Value & root,int index,u8 recursion)1275 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1276 {
1277 	if (recursion > 16) {
1278 		throw SerializationError("Maximum recursion depth exceeded");
1279 	}
1280 	int type = lua_type(L, index);
1281 	if (type == LUA_TBOOLEAN) {
1282 		root = (bool) lua_toboolean(L, index);
1283 	} else if (type == LUA_TNUMBER) {
1284 		root = lua_tonumber(L, index);
1285 	} else if (type == LUA_TSTRING) {
1286 		size_t len;
1287 		const char *str = lua_tolstring(L, index, &len);
1288 		root = std::string(str, len);
1289 	} else if (type == LUA_TTABLE) {
1290 		lua_pushnil(L);
1291 		while (lua_next(L, index)) {
1292 			// Key is at -2 and value is at -1
1293 			Json::Value value;
1294 			read_json_value(L, value, lua_gettop(L), recursion + 1);
1295 
1296 			Json::ValueType roottype = root.type();
1297 			int keytype = lua_type(L, -1);
1298 			if (keytype == LUA_TNUMBER) {
1299 				lua_Number key = lua_tonumber(L, -1);
1300 				if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1301 					throw SerializationError("Can't mix array and object values in JSON");
1302 				} else if (key < 1) {
1303 					throw SerializationError("Can't use zero-based or negative indexes in JSON");
1304 				} else if (floor(key) != key) {
1305 					throw SerializationError("Can't use indexes with a fractional part in JSON");
1306 				}
1307 				root[(Json::ArrayIndex) key - 1] = value;
1308 			} else if (keytype == LUA_TSTRING) {
1309 				if (roottype != Json::nullValue && roottype != Json::objectValue) {
1310 					throw SerializationError("Can't mix array and object values in JSON");
1311 				}
1312 				root[lua_tostring(L, -1)] = value;
1313 			} else {
1314 				throw SerializationError("Lua key to convert to JSON is not a string or number");
1315 			}
1316 		}
1317 	} else if (type == LUA_TNIL) {
1318 		root = Json::nullValue;
1319 	} else {
1320 		throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1321 	}
1322 	lua_pop(L, 1); // Pop value
1323 }
1324 
1325