code:
--        ______
--       |
--       |
--       |        __       ___  _   __         _  _
-- |   | |       |  | |\ |  |  |_| |  | |  |  |_ |_|
-- |___| |______ |__| | \|  |  | \ |__| |_ |_ |_ |\
-- |
-- |
--

-- Reference
-- ports = get_real_port_states(pos): gets if inputs are powered from outside
-- newport = merge_port_states(state1, state2): just does result = state1 or state2 for every port
-- set_port(pos, rule, state): activates/deactivates the mesecons according to the port states
-- set_port_states(pos, ports): Applies new port states to a Luacontroller at pos
-- run_inner(pos, code, event): runs code on the controller at pos and event
-- reset_formspec(pos, code, errmsg): installs new code and prints error messages, without resetting LCID
-- reset_meta(pos, code, errmsg): performs a software-reset, installs new code and prints error message
-- run(pos, event): a wrapper for run_inner which gets code & handles errors via reset_meta
-- resetn(pos): performs a hardware reset, turns off all ports
--
-- The Sandbox
-- The whole code of the controller runs in a sandbox,
-- a very restricted environment.
-- Actually the only way to damage the server is to
-- use too much memory from the sandbox.
-- You can add more functions to the environment
-- (see where local env is defined)
-- Something nice to play is is appending minetest.env to it.

local BASENAME = "mesecons_luacontroller:luacontroller"

local rules = {
	a = {x = -1, y = 0, z =  0, name="A"},
	b = {x =  0, y = 0, z =  1, name="B"},
	c = {x =  1, y = 0, z =  0, name="C"},
	d = {x =  0, y = 0, z = -1, name="D"},
}

------------------
-- Action stuff --
------------------
-- These helpers are required to set the port states of the luacontroller

-- Updates the real port states according to the signal change.
-- Returns whether the real port states actually changed.
local function update_real_port_states(pos, rule_name, new_state)
	local meta = minetest.get_meta(pos)
	if rule_name == nil then
		meta:set_int("real_portstates", 1)
		return true
	end
	local real_portstates = meta:get_int("real_portstates")
	local n = real_portstates - 1
	local L = {}
	for i = 1, 4 do
		L[i] = n % 2
		n = math.floor(n / 2)
	end
	--                   (0,-1) (-1,0)      (1,0) (0,1)
	local pos_to_side = {  4,     1,   nil,   3,    2 }
	if rule_name.x == nil then
		for _, rname in ipairs(rule_name) do
			local port = pos_to_side[rname.x + (2 * rname.z) + 3]
			L[port] = (new_state == "on") and 1 or 0
		end
	else
		local port = pos_to_side[rule_name.x + (2 * rule_name.z) + 3]
		L[port] = (new_state == "on") and 1 or 0
	end
	local new_portstates = 1 + 1 * L[1] + 2 * L[2] + 4 * L[3] + 8 * L[4]
	if new_portstates ~= real_portstates then
		meta:set_int("real_portstates", new_portstates)
		return true
	end
	return false
end

local port_names = {"a", "b", "c", "d"}

local function get_real_port_states(pos)
	-- Determine if ports are powered (by itself or from outside)
	local meta = minetest.get_meta(pos)
	local L = {}
	local n = meta:get_int("real_portstates") - 1
	for _, name in ipairs(port_names) do
		L[name] = ((n % 2) == 1)
		n = math.floor(n / 2)
	end
	return L
end

local function merge_port_states(ports, vports)
	return {
		a = ports.a or vports.a,
		b = ports.b or vports.b,
		c = ports.c or vports.c,
		d = ports.d or vports.d,
	}
end

local function generate_name(ports)
	local d = ports.d and 1 or 0
	local c = ports.c and 1 or 0
	local b = ports.b and 1 or 0
	local a = ports.a and 1 or 0
	return BASENAME..d..c..b..a
end

local function set_port(pos, rule, state)
	if state then
		mesecon.receptor_on(pos, {rule})
	else
		mesecon.receptor_off(pos, {rule})
	end
end

local function clean_port_states(ports)
	ports.a = ports.a and true or false
	ports.b = ports.b and true or false
	ports.c = ports.c and true or false
	ports.d = ports.d and true or false
end

local function set_port_states(pos, ports)
	local node = minetest.get_node(pos)
	local name = node.name
	clean_port_states(ports)
	local vports = minetest.registered_nodes[name].virtual_portstates
	local new_name = generate_name(ports)

	if name ~= new_name and vports then
		-- Problem:
		-- We need to place the new node first so that when turning
		-- off some port, it won't stay on because the rules indicate
		-- there is an onstate output port there.
		-- When turning the output off then, it will however cause feedback
		-- so that the luacontroller will receive an "off" event by turning
		-- its output off.
		-- Solution / Workaround:
		-- Remember which output was turned off and ignore next "off" event.
		local meta = minetest.get_meta(pos)
		local ign = minetest.deserialize(meta:get_string("ignore_offevents"), true) or {}
		if ports.a and not vports.a and not mesecon.is_powered(pos, rules.a) then ign.A = true end
		if ports.b and not vports.b and not mesecon.is_powered(pos, rules.b) then ign.B = true end
		if ports.c and not vports.c and not mesecon.is_powered(pos, rules.c) then ign.C = true end
		if ports.d and not vports.d and not mesecon.is_powered(pos, rules.d) then ign.D = true end
		meta:set_string("ignore_offevents", minetest.serialize(ign))

		minetest.swap_node(pos, {name = new_name, param2 = node.param2})

		if ports.a ~= vports.a then set_port(pos, rules.a, ports.a) end
		if ports.b ~= vports.b then set_port(pos, rules.b, ports.b) end
		if ports.c ~= vports.c then set_port(pos, rules.c, ports.c) end
		if ports.d ~= vports.d then set_port(pos, rules.d, ports.d) end
	end
end

-----------------
-- Overheating --
-----------------
local function burn_controller(pos)
	local node = minetest.get_node(pos)
	node.name = BASENAME.."_burnt"
	minetest.swap_node(pos, node)
	minetest.get_meta(pos):set_string("lc_memory", "");
	-- Wait for pending operations
	minetest.after(0.2, mesecon.receptor_off, pos, mesecon.rules.flat)
end

local function overheat(pos)
	if mesecon.do_overheat(pos) then -- If too hot
		burn_controller(pos)
		return true
	end
end

------------------------
-- Ignored off events --
------------------------

local function ignore_event(event, meta)
	if event.type ~= "off" then return false end
	local ignore_offevents = minetest.deserialize(meta:get_string("ignore_offevents"), true) or {}
	if ignore_offevents[event.pin.name] then
		ignore_offevents[event.pin.name] = nil
		meta:set_string("ignore_offevents", minetest.serialize(ignore_offevents))
		return true
	end
end

-------------------------
-- Parsing and running --
-------------------------

local function safe_print(param)
	local string_meta = getmetatable("")
	local sandbox = string_meta.__index
	string_meta.__index = string -- Leave string sandbox temporarily
	print(dump(param))
	string_meta.__index = sandbox -- Restore string sandbox
end

local function safe_date()
	return(os.date("*t",os.time()))
end

-- string.rep(str, n) with a high value for n can be used to DoS
-- the server. Therefore, limit max. length of generated string.
local function safe_string_rep(str, n)
	if #str * n > mesecon.setting("luacontroller_string_rep_max", 64000) then
		debug.sethook() -- Clear hook
		error("string.rep: string length overflow", 2)
	end

	return string.rep(str, n)
end

-- string.find with a pattern can be used to DoS the server.
-- Therefore, limit string.find to patternless matching.
local function safe_string_find(...)
	if (select(4, ...)) ~= true then
		debug.sethook() -- Clear hook
		error("string.find: 'plain' (fourth parameter) must always be true in a Luacontroller")
	end

	return string.find(...)
end

local function remove_functions(x)
	local tp = type(x)
	if tp == "function" then
		return nil
	end

	-- Make sure to not serialize the same table multiple times, otherwise
	-- writing mem.test = mem in the Luacontroller will lead to infinite recursion
	local seen = {}

	local function rfuncs(x)
		if x == nil then return end
		if seen[x] then return end
		seen[x] = true
		if type(x) ~= "table" then return end

		for key, value in pairs(x) do
			if type(key) == "function" or type(value) == "function" then
				x[key] = nil
			else
				if type(key) == "table" then
					rfuncs(key)
				end
				if type(value) == "table" then
					rfuncs(value)
				end
			end
		end
	end

	rfuncs(x)

	return x
end

local function validate_iid(iid)
	if not iid then return true end -- nil is OK

	local limit = mesecon.setting("luacontroller_interruptid_maxlen", 256)
	if type(iid) == "string" then
		if #iid <= limit then return true end -- string is OK unless too long
		return false, "An interrupt ID was too large!"
	end
	if type(iid) == "number" or type(iid) == "boolean" then return true, "Non-string interrupt IDs are deprecated" end

	local warn
	local seen = {}
	local function check(t)
		if type(t) == "function" then
			warn = "Functions cannot be used in interrupt IDs"
			return false
		end
		if type(t) ~= "table" then
			return true
		end
		if seen[t] then
			warn = "Non-tree-like tables are forbidden as interrupt IDs"
			return false
		end
		seen[t] = true
		for k, v in pairs(t) do
			if not check(k) then return false end
			if not check(v) then return false end
		end
		return true
	end
	if not check(iid) then return false, warn end

	if #minetest.serialize(iid) > limit then
		return false, "An interrupt ID was too large!"
	end

	return true, "Table interrupt IDs are deprecated and are unreliable; use strings instead"
end

-- The setting affects API so is not intended to be changeable at runtime
local get_interrupt
if mesecon.setting("luacontroller_lightweight_interrupts", false) then
	-- use node timer
	get_interrupt = function(pos, itbl, send_warning)
		return (function(time, iid)
			if type(time) ~= "number" then error("Delay must be a number") end
			if iid ~= nil then send_warning("Interrupt IDs are disabled on this server") end
			table.insert(itbl, function() minetest.get_node_timer(pos):start(time) end)
		end)
	end
else
	-- use global action queue
	-- itbl: Flat table of functions to run after sandbox cleanup, used to prevent various security hazards
	get_interrupt = function(pos, itbl, send_warning)
		-- iid = interrupt id
		return function (time, iid)
			-- NOTE: This runs within string metatable sandbox, so don't *rely* on anything of the form (""):y
			-- Hence the values get moved out. Should take less time than original, so totally compatible
			if type(time) ~= "number" then error("Delay must be a number") end
			table.insert(itbl, function ()
				-- Outside string metatable sandbox, can safely run this now
				local luac_id = minetest.get_meta(pos):get_int("luac_id")
				local ok, warn = validate_iid(iid)
				if ok then mesecon.queue:add_action(pos, "lc_interrupt", {luac_id, iid}, time, iid, 1) end
				if warn then send_warning(warn) end
			end)
		end
	end
end

-- Given a message object passed to digiline_send, clean it up into a form
-- which is safe to transmit over the network and compute its "cost" (a very
-- rough estimate of its memory usage).
--
-- The cleaning comprises the following:
-- 1. Functions (and userdata, though user scripts ought not to get hold of
--    those in the first place) are removed, because they break the model of
--    Digilines as a network that carries basic data, and they could exfiltrate
--    references to mutable objects from one Luacontroller to another, allowing
--    inappropriate high-bandwidth, no-wires communication.
-- 2. Tables are duplicated because, being mutable, they could otherwise be
--    modified after the send is complete in order to change what data arrives
--    at the recipient, perhaps in violation of the previous cleaning rule or
--    in violation of the message size limit.
--
-- The cost indication is only approximate; it’s not a perfect measurement of
-- the number of bytes of memory used by the message object.
--
-- Parameters:
-- msg -- the message to clean
-- back_references -- for internal use only; do not provide
--
-- Returns:
-- 1. The cleaned object.
-- 2. The approximate cost of the object.
local function clean_and_weigh_digiline_message(msg, back_references)
	local t = type(msg)
	if t == "string" then
		-- Strings are immutable so can be passed by reference, and cost their
		-- length plus the size of the Lua object header (24 bytes on a 64-bit
		-- platform) plus one byte for the NUL terminator.
		return msg, #msg + 25
	elseif t == "number" then
		-- Numbers are passed by value so need not be touched, and cost 8 bytes
		-- as all numbers in Lua are doubles.
		return msg, 8
	elseif t == "boolean" then
		-- Booleans are passed by value so need not be touched, and cost 1
		-- byte.
		return msg, 1
	elseif t == "table" then
		-- Tables are duplicated. Check if this table has been seen before
		-- (self-referential or shared table); if so, reuse the cleaned value
		-- of the previous occurrence, maintaining table topology and avoiding
		-- infinite recursion, and charge zero bytes for this as the object has
		-- already been counted.
		back_references = back_references or {}
		local bref = back_references[msg]
		if bref then
			return bref, 0
		end
		-- Construct a new table by cleaning all the keys and values and adding
		-- up their costs, plus 8 bytes as a rough estimate of table overhead.
		local cost = 8
		local ret = {}
		back_references[msg] = ret
		for k, v in pairs(msg) do
			local k_cost, v_cost
			k, k_cost = clean_and_weigh_digiline_message(k, back_references)
			v, v_cost = clean_and_weigh_digiline_message(v, back_references)
			if k ~= nil and v ~= nil then
				-- Only include an element if its key and value are of legal
				-- types.
				ret[k] = v
			end
			-- If we only counted the cost of a table element when we actually
			-- used it, we would be vulnerable to the following attack:
			-- 1. Construct a huge table (too large to pass the cost limit).
			-- 2. Insert it somewhere in a table, with a function as a key.
			-- 3. Insert it somewhere in another table, with a number as a key.
			-- 4. The first occurrence doesn’t pay the cost because functions
			--    are stripped and therefore the element is dropped.
			-- 5. The second occurrence doesn’t pay the cost because it’s in
			--    back_references.
			-- By counting the costs regardless of whether the objects will be
			-- included, we avoid this attack; it may overestimate the cost of
			-- some messages, but only those that won’t be delivered intact
			-- anyway because they contain illegal object types.
			cost = cost + k_cost + v_cost
		end
		return ret, cost
	else
		return nil, 0
	end
end

-- itbl: Flat table of functions to run after sandbox cleanup, used to prevent various security hazards
local function get_digiline_send(pos, itbl, send_warning)
	if not minetest.global_exists("digilines") then return end
	local chan_maxlen = mesecon.setting("luacontroller_digiline_channel_maxlen", 256)
	local maxlen = mesecon.setting("luacontroller_digiline_maxlen", 50000)
	return function(channel, msg)
		-- NOTE: This runs within string metatable sandbox, so don't *rely* on anything of the form (""):y
		--        or via anything that could.
		-- Make sure channel is string, number or boolean
		if type(channel) == "string" then
			if #channel > chan_maxlen then
				send_warning("Channel string too long.")
				return false
			end
		elseif (type(channel) ~= "string" and type(channel) ~= "number" and type(channel) ~= "boolean") then
			send_warning("Channel must be string, number or boolean.")
			return false
		end

		local msg_cost
		msg, msg_cost = clean_and_weigh_digiline_message(msg)
		if msg == nil or msg_cost > maxlen then
			send_warning("Message was too complex, or contained invalid data.")
			return false
		end

		table.insert(itbl, function ()
			-- Runs outside of string metatable sandbox
			local luac_id = minetest.get_meta(pos):get_int("luac_id")
			mesecon.queue:add_action(pos, "lc_digiline_relay", {channel, luac_id, msg})
		end)
		return true
	end
end

local safe_globals = {
	-- Don't add pcall/xpcall unless willing to deal with the consequences (unless very careful, incredibly likely to allow killing server indirectly)
	"assert", "error", "ipairs", "next", "pairs", "select",
	"tonumber", "tostring", "type", "unpack", "_VERSION"
}

local function create_environment(pos, mem, event, itbl, send_warning)
	-- Gather variables for the environment
	local node_def = minetest.registered_nodes[minetest.get_node(pos).name]
	if not node_def then return end

	local vports = node_def.virtual_portstates
	if not vports then return end

	local vports_copy = {}
	for k, v in pairs(vports) do vports_copy[k] = v end
	local rports = get_real_port_states(pos)

	-- Create new library tables on each call to prevent one Luacontroller
	-- from breaking a library and messing up other Luacontrollers.
	local env = {
		pin = merge_port_states(vports, rports),
		port = vports_copy,
		event = event,
		mem = mem,
		heat = mesecon.get_heat(pos),
		heat_max = mesecon.setting("overheat_max", 20),
		print = safe_print,
		interrupt = get_interrupt(pos, itbl, send_warning),
		digiline_send = get_digiline_send(pos, itbl, send_warning),
		string = {
			byte = string.byte,
			char = string.char,
			format = string.format,
			len = string.len,
			lower = string.lower,
			upper = string.upper,
			rep = safe_string_rep,
			reverse = string.reverse,
			sub = string.sub,
			find = safe_string_find,
		},
		math = {
			abs = math.abs,
			acos = math.acos,
			asin = math.asin,
			atan = math.atan,
			atan2 = math.atan2,
			ceil = math.ceil,
			cos = math.cos,
			cosh = math.cosh,
			deg = math.deg,
			exp = math.exp,
			floor = math.floor,
			fmod = math.fmod,
			frexp = math.frexp,
			huge = math.huge,
			ldexp = math.ldexp,
			log = math.log,
			log10 = math.log10,
			max = math.max,
			min = math.min,
			modf = math.modf,
			pi = math.pi,
			pow = math.pow,
			rad = math.rad,
			random = math.random,
			sin = math.sin,
			sinh = math.sinh,
			sqrt = math.sqrt,
			tan = math.tan,
			tanh = math.tanh,
		},
		table = {
			concat = table.concat,
			insert = table.insert,
			maxn = table.maxn,
			remove = table.remove,
			sort = table.sort,
		},
		os = {
			clock = os.clock,
			difftime = os.difftime,
			time = os.time,
			datetable = safe_date,
		},
	}
	env._G = env

	for _, name in pairs(safe_globals) do
		env[name] = _G[name]
	end

	return env
end

local function timeout()
	debug.sethook() -- Clear hook
	error("Code timed out!", 2)
end

local function create_sandbox(code, env)
	if code:byte(1) == 27 then
		return nil, "Binary code prohibited."
	end
	local f, msg = loadstring(code)
	if not f then return nil, msg end
	setfenv(f, env)

	-- Turn off JIT optimization for user code so that count
	-- events are generated when adding debug hooks
	if rawget(_G, "jit") then
		jit.off(f, true)
	end

	local maxevents = mesecon.setting("luacontroller_maxevents", 10000)
	return function(...)
		-- NOTE: This runs within string metatable sandbox, so the setting's been moved out for safety
		-- Use instruction counter to stop execution
		-- after luacontroller_maxevents
		debug.sethook(timeout, "", maxevents)
		local ok, ret = pcall(f, ...)
		debug.sethook()  -- Clear hook
		if not ok then error(ret, 0) end
		return ret
	end
end

local function load_memory(meta)
	return minetest.deserialize(meta:get_string("lc_memory"), true) or {}
end

local function save_memory(pos, meta, mem)
	local memstring = minetest.serialize(remove_functions(mem))
	local memsize_max = mesecon.setting("luacontroller_memsize", 100000)

	if (#memstring <= memsize_max) then
		meta:set_string("lc_memory", memstring)
		meta:mark_as_private("lc_memory")
	else
		print("Error: Luacontroller memory overflow. "..memsize_max.." bytes available, "
				..#memstring.." required. Controller overheats.")
		burn_controller(pos)
	end
end

-- Returns success (boolean), errmsg (string)
-- run (as opposed to run_inner) is responsible for setting up meta according to this output
local function run_inner(pos, code, event)
	local meta = minetest.get_meta(pos)
	-- Note: These return success, presumably to avoid changing LC ID.
	if overheat(pos) then return true, "" end
	if ignore_event(event, meta) then return true, "" end

	-- Load mem from meta
	local mem  = load_memory(meta)

	-- 'Last warning' label.
	local warning = ""
	local function send_warning(str)
		warning = "Warning: " .. str
	end

	-- Create environment
	local itbl = {}
	local env = create_environment(pos, mem, event, itbl, send_warning)
	if not env then return false, "Env does not exist. Controller has been moved?" end

	local success, msg
	-- Create the sandbox and execute code
	local f
	f, msg = create_sandbox(code, env)
	if not f then return false, msg end
	-- Start string true sandboxing
	local onetruestring = getmetatable("")
	-- If a string sandbox is already up yet inconsistent, something is very wrong
	assert(onetruestring.__index == string)
	onetruestring.__index = env.string
	success, msg = pcall(f)
	onetruestring.__index = string
	-- End string true sandboxing
	if not success then return false, msg end
	if type(env.port) ~= "table" then
		return false, "Ports set are invalid."
	end

	-- Actually set the ports
	set_port_states(pos, env.port)

	-- Save memory. This may burn the luacontroller if a memory overflow occurs.
	save_memory(pos, meta, env.mem)

	-- Execute deferred tasks
	for _, v in ipairs(itbl) do
		local failure = v()
		if failure then
			return false, failure
		end
	end
	return true, warning
end

local function reset_formspec(meta, code, errmsg)
	meta:set_string("code", code)
	meta:mark_as_private("code")
	code = minetest.formspec_escape(code or "")
	errmsg = minetest.formspec_escape(tostring(errmsg or ""))
	meta:set_string("formspec", "size[12,10]"
		.."style_type[label,textarea;font=mono]"
		.."background[-0.2,-0.25;12.4,10.75;jeija_luac_background.png]"
		.."label[0.1,8.3;"..errmsg.."]"
		.."textarea[0.2,0.2;12.2,9.5;code;;"..code.."]"
		.."image_button[4.75,8.75;2.5,1;jeija_luac_runbutton.png;program;]"
		.."image_button_exit[11.72,-0.25;0.425,0.4;jeija_close_window.png;exit;]"
		)
end

local function reset_meta(pos, code, errmsg)
	local meta = minetest.get_meta(pos)
	reset_formspec(meta, code, errmsg)
	meta:set_int("luac_id", math.random(1, 65535))
end

-- Wraps run_inner with LC-reset-on-error
local function run(pos, event)
	local meta = minetest.get_meta(pos)
	local code = meta:get_string("code")
	local ok, errmsg = run_inner(pos, code, event)
	if not ok then
		reset_meta(pos, code, errmsg)
	else
		reset_formspec(meta, code, errmsg)
	end
	return ok, errmsg
end

local function reset(pos)
	set_port_states(pos, {a=false, b=false, c=false, d=false})
end

local function node_timer(pos)
	if minetest.registered_nodes[minetest.get_node(pos).name].is_burnt then
		return false
	end
	run(pos, {type="interrupt"})
	return false
end

-----------------------
-- A.Queue callbacks --
-----------------------

mesecon.queue:add_function("lc_interrupt", function (pos, luac_id, iid)
	-- There is no luacontroller anymore / it has been reprogrammed / replaced / burnt
	if (minetest.get_meta(pos):get_int("luac_id") ~= luac_id) then return end
	if (minetest.registered_nodes[minetest.get_node(pos).name].is_burnt) then return end
	run(pos, {type="interrupt", iid = iid})
end)

mesecon.queue:add_function("lc_digiline_relay", function (pos, channel, luac_id, msg)
	if not digiline then return end
	-- This check is only really necessary because in case of server crash, old actions can be thrown into the future
	if (minetest.get_meta(pos):get_int("luac_id") ~= luac_id) then return end
	if (minetest.registered_nodes[minetest.get_node(pos).name].is_burnt) then return end
	-- The actual work
	digiline:receptor_send(pos, digiline.rules.default, channel, msg)
end)

-----------------------
-- Node Registration --
-----------------------

local output_rules = {}
local input_rules = {}

local node_box = {
	type = "fixed",
	fixed = {
		{-8/16, -8/16, -8/16, 8/16, -7/16, 8/16}, -- Bottom slab
		{-5/16, -7/16, -5/16, 5/16, -6/16, 5/16}, -- Circuit board
		{-3/16, -6/16, -3/16, 3/16, -5/16, 3/16}, -- IC
	}
}

local selection_box = {
	type = "fixed",
	fixed = { -8/16, -8/16, -8/16, 8/16, -5/16, 8/16 },
}

local digiline = {
	receptor = {},
	effector = {
		action = function(pos, _, channel, msg)
			msg = clean_and_weigh_digiline_message(msg)
			run(pos, {type = "digiline", channel = channel, msg = msg})
		end
	}
}

local function get_program(pos)
	local meta = minetest.get_meta(pos)
	return meta:get_string("code")
end

local function set_program(pos, code)
	reset(pos)
	reset_meta(pos, code)
	return run(pos, {type="program"})
end

local function on_receive_fields(pos, _, fields, sender)
	if not fields.program then
		return
	end
	local name = sender:get_player_name()
	if minetest.is_protected(pos, name) and not minetest.check_player_privs(name, {protection_bypass=true}) then
		minetest.record_protection_violation(pos, name)
		return
	end
	local ok, err = set_program(pos, fields.code)
	if not ok then
		-- it's not an error from the server perspective
		minetest.log("action", "Lua controller programming error: " .. tostring(err))
	end
end

for a = 0, 1 do -- 0 = off  1 = on
for b = 0, 1 do
for c = 0, 1 do
for d = 0, 1 do
	local cid = tostring(d)..tostring(c)..tostring(b)..tostring(a)
	local node_name = BASENAME..cid
	local top = "jeija_luacontroller_top.png"
	if a == 1 then
		top = top.."^jeija_luacontroller_LED_A.png"
	end
	if b == 1 then
		top = top.."^jeija_luacontroller_LED_B.png"
	end
	if c == 1 then
		top = top.."^jeija_luacontroller_LED_C.png"
	end
	if d == 1 then
		top = top.."^jeija_luacontroller_LED_D.png"
	end

	local groups
	if a + b + c + d ~= 0 then
		groups = {dig_immediate=2, not_in_creative_inventory=1, overheat = 1}
	else
		groups = {dig_immediate=2, overheat = 1}
	end

	output_rules[cid] = {}
	input_rules[cid] = {}
	if a == 1 then table.insert(output_rules[cid], rules.a) end
	if b == 1 then table.insert(output_rules[cid], rules.b) end
	if c == 1 then table.insert(output_rules[cid], rules.c) end
	if d == 1 then table.insert(output_rules[cid], rules.d) end

	if a == 0 then table.insert( input_rules[cid], rules.a) end
	if b == 0 then table.insert( input_rules[cid], rules.b) end
	if c == 0 then table.insert( input_rules[cid], rules.c) end
	if d == 0 then table.insert( input_rules[cid], rules.d) end

	local mesecons = {
		effector = {
			rules = input_rules[cid],
			action_change = function (pos, _, rule_name, new_state)
				if update_real_port_states(pos, rule_name, new_state) then
					run(pos, {type=new_state, pin=rule_name})
				end
			end,
		},
		receptor = {
			state = mesecon.state.on,
			rules = output_rules[cid]
		},
		luacontroller = {
			get_program = get_program,
			set_program = set_program,
		},
	}

	minetest.register_node(node_name, {
		description = "Luacontroller",
		drawtype = "nodebox",
		tiles = {
			top,
			"jeija_microcontroller_bottom.png",
			"jeija_microcontroller_sides.png",
			"jeija_microcontroller_sides.png",
			"jeija_microcontroller_sides.png",
			"jeija_microcontroller_sides.png"
		},
		inventory_image = top,
		paramtype = "light",
		is_ground_content = false,
		groups = groups,
		drop = BASENAME.."0000",
		sunlight_propagates = true,
		selection_box = selection_box,
		node_box = node_box,
		on_construct = reset_meta,
		on_receive_fields = on_receive_fields,
		sounds = mesecon.node_sound.stone,
		mesecons = mesecons,
		digiline = digiline,
		-- Virtual portstates are the ports that
		-- the node shows as powered up (light up).
		virtual_portstates = {
			a = a == 1,
			b = b == 1,
			c = c == 1,
			d = d == 1,
		},
		after_dig_node = function (pos)
			mesecon.do_cooldown(pos)
			mesecon.receptor_off(pos, output_rules)
		end,
		is_luacontroller = true,
		on_timer = node_timer,
		on_blast = mesecon.on_blastnode,
	})
end
end
end
end

------------------------------
-- Overheated Luacontroller --
------------------------------

minetest.register_node(BASENAME .. "_burnt", {
	drawtype = "nodebox",
	tiles = {
		"jeija_luacontroller_burnt_top.png",
		"jeija_microcontroller_bottom.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png"
	},
	inventory_image = "jeija_luacontroller_burnt_top.png",
	is_burnt = true,
	paramtype = "light",
	is_ground_content = false,
	groups = {dig_immediate=2, not_in_creative_inventory=1},
	drop = BASENAME.."0000",
	sunlight_propagates = true,
	selection_box = selection_box,
	node_box = node_box,
	on_construct = reset_meta,
	on_receive_fields = on_receive_fields,
	sounds = mesecon.node_sound.stone,
	virtual_portstates = {a = false, b = false, c = false, d = false},
	mesecons = {
		effector = {
			rules = mesecon.rules.flat,
			action_change = function(pos, _, rule_name, new_state)
				update_real_port_states(pos, rule_name, new_state)
			end,
		},
	},
	on_blast = mesecon.on_blastnode,
})

------------------------
-- Craft Registration --
------------------------

minetest.register_craft({
	output = BASENAME.."0000 2",
	recipe = {
		{'mesecons_materials:silicon', 'mesecons_materials:silicon', 'group:mesecon_conductor_craftable'},
		{'mesecons_materials:silicon', 'mesecons_materials:silicon', 'group:mesecon_conductor_craftable'},
		{'group:mesecon_conductor_craftable', 'group:mesecon_conductor_craftable', ''},
	}
})


code:
name = mesecons_luacontroller
depends = mesecons, mesecons_gamecompat

repo_name: korkut/MeseCraft

license: mit


code: Craftitem: It can't be placed! Made by cooking glue in the furnace. Used for insulated mesecon crafting.


code: Craftitem: It can't be placed! Made by cooking saplings in furnace. Used for sticky pistons and sticky movestones.


code: Silicon is just a craftitem: It can't be placed. You'll need it in order to craft other items.


code:
-- Glue and fiber
minetest.register_craftitem("mesecons_materials:glue", {
	image = "mesecons_glue.png",
	on_place_on_ground = minetest.craftitem_place_item,
	description="Glue",
})

minetest.register_craftitem("mesecons_materials:fiber", {
	image = "mesecons_fiber.png",
	on_place_on_ground = minetest.craftitem_place_item,
	description="Fiber",
})

minetest.register_craft({
	output = "mesecons_materials:glue 2",
	type = "cooking",
	recipe = "group:sapling",
	cooktime = 2
})

minetest.register_craft({
	output = "mesecons_materials:fiber 6",
	type = "cooking",
	recipe = "mesecons_materials:glue",
	cooktime = 4
})

-- Silicon
minetest.register_craftitem("mesecons_materials:silicon", {
	image = "mesecons_silicon.png",
	on_place_on_ground = minetest.craftitem_place_item,
	description="Silicon",
})

minetest.register_craft({
	output = "mesecons_materials:silicon 4",
	recipe = {
		{"group:sand", "group:sand"},
		{"group:sand", "mesecons_gamecompat:steel_ingot"},
	}
})


code:
name = mesecons_materials
depends = mesecons_gamecompat


code:
local EEPROM_SIZE = 255

local microc_rules = {}
local yc = {}

for a = 0, 1 do
for b = 0, 1 do
for c = 0, 1 do
for d = 0, 1 do
local nodename = "mesecons_microcontroller:microcontroller"..tostring(d)..tostring(c)..tostring(b)..tostring(a)
local top = "jeija_microcontroller_top.png"
if tostring(a) == "1" then
	top = top.."^jeija_microcontroller_LED_A.png"
end
if tostring(b) == "1" then
	top = top.."^jeija_microcontroller_LED_B.png"
end
if tostring(c) == "1" then
	top = top.."^jeija_microcontroller_LED_C.png"
end
if tostring(d) == "1" then
	top = top.."^jeija_microcontroller_LED_D.png"
end
local groups
if tostring(d)..tostring(c)..tostring(b)..tostring(a) ~= "0000" then
	groups = {dig_immediate=2, not_in_creative_inventory=1, mesecon = 3, overheat = 1}
else
	groups = {dig_immediate=2, mesecon = 3, overheat = 1}
end
local rules={}
if (a == 1) then table.insert(rules, {x = -1, y = 0, z =  0}) end
if (b == 1) then table.insert(rules, {x =  0, y = 0, z =  1}) end
if (c == 1) then table.insert(rules, {x =  1, y = 0, z =  0}) end
if (d == 1) then table.insert(rules, {x =  0, y = 0, z = -1}) end

local input_rules={}
if (a == 0) then table.insert(input_rules, {x = -1, y = 0, z =  0, name = "A"}) end
if (b == 0) then table.insert(input_rules, {x =  0, y = 0, z =  1, name = "B"}) end
if (c == 0) then table.insert(input_rules, {x =  1, y = 0, z =  0, name = "C"}) end
if (d == 0) then table.insert(input_rules, {x =  0, y = 0, z = -1, name = "D"}) end
microc_rules[nodename] = rules

local mesecons = {effector =
{
	rules = input_rules,
	action_change = function (pos, node, rulename, newstate)
		if yc.update_real_portstates(pos, node, rulename, newstate) then
			yc.update(pos)
		end
	end
}}
if nodename ~= "mesecons_microcontroller:microcontroller0000" then
	mesecons.receptor = {
		state = mesecon.state.on,
		rules = rules
	}
end

minetest.register_node(nodename, {
	description = "Microcontroller",
	drawtype = "nodebox",
	tiles = {
		top,
		"jeija_microcontroller_bottom.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png",
		"jeija_microcontroller_sides.png"
		},

	sunlight_propagates = true,
	paramtype = "light",
	is_ground_content = false,
	walkable = true,
	groups = groups,
	drop = "mesecons_microcontroller:microcontroller0000 1",
	selection_box = {
		type = "fixed",
		fixed = { -8/16, -8/16, -8/16, 8/16, -5/16, 8/16 },
	},
	node_box = {
		type = "fixed",
		fixed = {
			{ -8/16, -8/16, -8/16, 8/16, -7/16, 8/16 }, -- bottom slab
			{ -5/16, -7/16, -5/16, 5/16, -6/16, 5/16 }, -- circuit board
			{ -3/16, -6/16, -3/16, 3/16, -5/16, 3/16 }, -- IC
		}
	},
	on_construct = function(pos)
		local meta = minetest.get_meta(pos)
		meta:set_string("code", "")
		meta:set_string("formspec", "size[9,2.5]"..
			"field[0.256,-0.2;9,2;code;Code:;]"..
			"button[0  ,0.2;1.5,3;band;AND]"..
			"button[1.5,0.2;1.5,3;bxor;XOR]"..
			"button[3  ,0.2;1.5,3;bnot;NOT]"..
			"button[4.5,0.2;1.5,3;bnand;NAND]"..
			"button[6  ,0.2;1.5,3;btflop;T-Flop]"..
			"button[7.5,0.2;1.5,3;brsflop;RS-Flop]"..
			"button_exit[3.5,1;2,3;program;Program]")
		meta:set_string("infotext", "Unprogrammed Microcontroller")
		local r = ""
		for i=1, EEPROM_SIZE+1 do r=r.."0" end --Generate a string with EEPROM_SIZE*"0"
		meta:set_string("eeprom", r)
	end,
	on_receive_fields = function(pos, _, fields, sender)
		local player_name = sender:get_player_name()
		if minetest.is_protected(pos, player_name) and
				not minetest.check_player_privs(player_name, {protection_bypass=true}) then
			minetest.record_protection_violation(pos, player_name)
			return
		end
		local meta = minetest.get_meta(pos)
		if fields.band then
			fields.code = "sbi(C, A&B) :A and B are inputs, C is output"
		elseif fields.bxor then
			fields.code = "sbi(C, A~B) :A and B are inputs, C is output"
		elseif fields.bnot then
			fields.code = "sbi(B, !A) :A is input, B is output"
		elseif fields.bnand then
			fields.code = "sbi(C, !A|!B) :A and B are inputs, C is output"
		elseif fields.btflop then
			fields.code = "if(A)sbi(1,1);if(!A&#1)sbi(B,!B)sbi(1,0); if(C)off(B,1); :A is input, B is output (Q), C is reset, toggles with falling edge"
		elseif fields.brsflop then
			fields.code = "if(A)on(C);if(B)off(C); :A is S (Set), B is R (Reset), C is output (R dominates)"
		end
		if fields.code == nil then return end

		meta:set_string("code", fields.code)
		meta:set_string("formspec", "size[9,2.5]"..
		"field[0.256,-0.2;9,2;code;Code:;"..minetest.formspec_escape(fields.code).."]"..
		"button[0  ,0.2;1.5,3;band;AND]"..
		"button[1.5,0.2;1.5,3;bxor;XOR]"..
		"button[3  ,0.2;1.5,3;bnot;NOT]"..
		"button[4.5,0.2;1.5,3;bnand;NAND]"..
		"button[6  ,0.2;1.5,3;btflop;T-Flop]"..
		"button[7.5,0.2;1.5,3;brsflop;RS-Flop]"..
		"button_exit[3.5,1;2,3;program;Program]")
		meta:set_string("infotext", "Programmed Microcontroller")
		yc.reset (pos)
		yc.update(pos)
	end,
	sounds = mesecon.node_sound.stone,
	mesecons = mesecons,
	after_dig_node = function (pos, node)
		rules = microc_rules[node.name]
		mesecon.receptor_off(pos, rules)
	end,
	on_blast = mesecon.on_blastnode,
})
end
end
end
end

if minetest.get_modpath("mesecons_luacontroller") then
	minetest.register_craft({
		type = "shapeless",
		output = "mesecons_microcontroller:microcontroller0000",
		recipe = {"mesecons_luacontroller:luacontroller0000"},
	})
	minetest.register_craft({
		type = "shapeless",
		output = "mesecons_luacontroller:luacontroller0000",
		recipe = {"mesecons_microcontroller:microcontroller0000"},
	})
else
	minetest.register_craft({
		output = 'craft "mesecons_microcontroller:microcontroller0000" 2',
		recipe = {
			{'mesecons_materials:silicon', 'mesecons_materials:silicon', 'group:mesecon_conductor_craftable'},
			{'mesecons_materials:silicon', 'mesecons_materials:silicon', 'group:mesecon_conductor_craftable'},
			{'group:mesecon_conductor_craftable', 'group:mesecon_conductor_craftable', ''},
		}
	})
end

yc.reset = function(pos)
	yc.action(pos, {a=false, b=false, c=false, d=false})
	local meta = minetest.get_meta(pos)
	meta:set_int("afterid", 0)
	local r = ""
	for i=1, EEPROM_SIZE+1 do r=r.."0" end --Generate a string with EEPROM_SIZE*"0"
	meta:set_string("eeprom", r)
end

yc.update = function(pos)
	local meta = minetest.get_meta(pos)

	if (mesecon.do_overheat(pos)) then
		minetest.remove_node(pos)
		minetest.after(0.2, function (pos)
			mesecon.receptor_off(pos, mesecon.rules.flat)
		end , pos) -- wait for pending parsings
		minetest.add_item(pos, "mesecons_microcontroller:microcontroller0000")
	end

	local code = meta:get_string("code")
	code = yc.code_remove_commentary(code)
	code = string.gsub(code, " ", "")	--Remove all spaces
	code = string.gsub(code, "	", "")	--Remove all tabs
	if yc.parsecode(code, pos) == nil then
		meta:set_string("infotext", "Code not valid!\n"..code)
	else
		meta:set_string("infotext", "Working Microcontroller\n"..code)
	end
end

--Code Parsing
yc.code_remove_commentary = function(code)
	local is_string = false
	for i = 1, #code do
		if code:sub(i, i) == '"' then
			is_string = not is_string --toggle is_string
		elseif code:sub(i, i) == ":" and not is_string then
			return code:sub(1, i-1)
		end
	end
	return code
end

yc.parsecode = function(code, pos)
	local meta = minetest.get_meta(pos)
	local endi = 1
	local Lreal = yc.get_real_portstates(pos)
	local Lvirtual = yc.get_virtual_portstates(pos)
	if Lvirtual == nil then return nil end
	local eeprom = meta:get_string("eeprom")
	while true do
		local command, params
		command, endi = yc.parse_get_command(code, endi)
		if command == nil then return nil end
		if command == true then break end --end of code
		if command == "if" then
			local r
			r, endi = yc.command_if(code, endi, yc.merge_portstates(Lreal, Lvirtual), eeprom)
			if r == nil then return nil end
			if r == true then  -- nothing
			elseif r == false then
				local endi_new = yc.skip_to_else (code, endi)
				if endi_new == nil then --else > not found
					endi = yc.skip_to_endif(code, endi)
				else
					endi = endi_new
				end
				if endi == nil then return nil end
			end
		else
			params, endi = yc.parse_get_params(code, endi)
			if not params then return nil end
		end
		if command == "on" then
			Lvirtual = yc.command_on (params, Lvirtual)
		elseif command == "off" then
			Lvirtual = yc.command_off(params, Lvirtual)
		elseif command == "print" then
			local su = yc.command_print(params, eeprom, yc.merge_portstates(Lreal, Lvirtual))
			if su ~= true then return nil end
		elseif command == "after" then
			local su = yc.command_after(params, pos)
			if su == nil then return nil end
		elseif command == "sbi" then
			local new_eeprom
			new_eeprom, Lvirtual = yc.command_sbi (params, eeprom, yc.merge_portstates(Lreal, Lvirtual), Lvirtual)
			if new_eeprom == nil then return nil
			else eeprom = new_eeprom end
		elseif command == "if" then --nothing
		else
			return nil
		end
		if Lvirtual == nil then return nil end
		if eeprom == nil then return nil else
		minetest.get_meta(pos):set_string("eeprom", eeprom) end
	end
	yc.action(pos, Lvirtual)
	return true
end

yc.parse_get_command = function(code, starti)
	local i = starti
	local s
	while s ~= "" do
		s = string.sub(code, i, i)
		if s == "(" then
			return string.sub(code, starti, i-1), i + 1 -- i: ( i+1 after (
		end
		if s == ";" and starti == i then
			starti = starti + 1
			i = starti
		elseif s == ">" then
			starti = yc.skip_to_endif(code, starti)
			if starti == nil then return nil end
			i = starti
		else
			i = i + 1
		end
	end

	if starti == i-1 then
		return true, true
	end
	return nil, nil
end

yc.parse_get_params = function(code, starti)
	local i = starti
	local s
	local params = {}
	local is_string = false
	while s ~= "" do
		s = string.sub(code, i, i)
		if code:sub(i, i) == '"' then
			is_string = (is_string==false) --toggle is_string
		end
		if s == ")" and is_string == false then
			table.insert(params, string.sub(code, starti, i-1)) -- i: ) i+1 after )
			return params, i + 1
		end
		if s == "," and is_string == false then
			table.insert(params, string.sub(code, starti, i-1)) -- i: ) i+1 after )
			starti = i + 1
		end
		i = i + 1
	end
	return nil, nil
end

yc.parse_get_eeprom_param = function(cond, starti)
	local i = starti
	local s
	local addr
	while s ~= "" do
		s = string.sub(cond, i, i)
		local b = s:byte()
		if s == "" or 48 > b or b > 57 then
			addr = string.sub(cond, starti, i-1) -- i: last number i+1 after last number
			return addr, i
		end
		if s == "," then return nil, nil end
		i = i + 1
	end
	return nil, nil
end

yc.skip_to_endif = function(code, starti)
	local i = starti
	local s = false
	local open_ifs = 1
	while s ~= nil and s~= "" do
		s = code:sub(i, i)
		if s == "i" and code:sub(i+1, i+1) == "f" then --if in µCScript
			open_ifs = open_ifs + 1
		end
		if s == ";" then
			open_ifs = open_ifs - 1
		end
		if open_ifs == 0 then
			return i + 1
		end
		i = i + 1
	end
	return nil
end

yc.skip_to_else = function(code, starti)
	local i = starti
	local s = false
	local open_ifs = 1
	while s ~= nil and s~= "" do
		s = code:sub(i, i)
		if s == "i" and code:sub(i+1, i+1) == "f" then --if in µCScript
			open_ifs = open_ifs + 1
		end
		if s == ";" then
			open_ifs = open_ifs - 1
		end
		if open_ifs == 1 and s == ">" then
			return i + 1
		end
		i = i + 1
	end
	return nil
end

--Commands
yc.command_on = function(params, L)
	for i, port in ipairs(params) do
		L = yc.set_portstate (port, true, L)
	end
	return L
end

yc.command_off = function(params, L)
	for i, port in ipairs(params) do
		L = yc.set_portstate (port, false, L)
	end
	return L
end

yc.command_print = function(params, eeprom, L)
	local s = ""
	for i, param in ipairs(params) do
		if param:sub(1,1) == '"' and param:sub(#param, #param) == '"' then
			s = s..param:sub(2, #param-1)
		else
			local r = yc.command_parsecondition(param, L, eeprom)
			if r == "1" or r == "0" then
				s = s..r
			else return nil end
		end
	end
	print(s) --don't remove
	return true
end

yc.command_sbi = function(params, eeprom, L, Lv)
	if params[1]==nil or params[2]==nil or params[3] ~=nil then return nil end
	local status = yc.command_parsecondition(params[2], L, eeprom)

	if status == nil then return nil, nil end

	if #params[1]==1 then
		local b = params[1]:byte()
		if 65 <= b and b <= 68 then -- is a port
			if status == "1" then
				Lv = yc.set_portstate (params[1], true,  Lv)
			else
				Lv = yc.set_portstate (params[1], false, Lv)
			end
			return eeprom, Lv;
		end
	end

	--is an eeprom address
	local new_eeprom = "";
	for i=1, #eeprom do
		if tonumber(params[1])==i then
			new_eeprom = new_eeprom..status
		else
			new_eeprom = new_eeprom..eeprom:sub(i, i)
		end
	end
	return new_eeprom, Lv
end

-- after (delay)
yc.command_after = function(params, pos)
	if params[1] == nil or params[2] == nil or params[3] ~= nil then return nil end

	--get time (maximum time is 200)
	local time = tonumber(params[1])
	if time == nil or time > 200 then
		return nil
	end

	--get code in quotes "code"
	if string.sub(params[2], 1, 1) ~= '"' or string.sub(params[2], #params[2], #params[2]) ~= '"' then return nil end
	local code = string.sub(params[2], 2, #params[2] - 1)

	local afterid = math.random(10000)
	local meta = minetest.get_meta(pos)
	meta:set_int("afterid", afterid)
	minetest.after(time, yc.command_after_execute, {pos = pos, code = code, afterid = afterid})
	return true
end

yc.command_after_execute = function(params)
	local meta = minetest.get_meta(params.pos)
	if meta:get_int("afterid") == params.afterid then --make sure the node has not been changed
		if yc.parsecode(params.code, params.pos) == nil then
			meta:set_string("infotext", "Code in after() not valid!")
		else
			if params.code ~= nil then
				meta:set_string("infotext", "Working Microcontroller\n"..params.code)
			else
				meta:set_string("infotext", "Working Microcontroller")
			end
		end
	end
end

--If
yc.command_if = function(code, starti, L, eeprom)
	local cond, endi = yc.command_if_getcondition(code, starti)
	if cond == nil then return nil end

	cond = yc.command_parsecondition(cond, L, eeprom)

	local result
	if cond == "0" then result = false
	elseif cond == "1" then result = true end
	if not result then end
	return result, endi --endi from local cond, endi = yc.command_if_getcondition(code, starti)
end

--Condition parsing
yc.command_if_getcondition = function(code, starti)
	local i = starti
	local s
	local brackets = 1 --1 Bracket to close
	while s ~= "" do
		s = string.sub(code, i, i)

		if s == ")" then
			brackets = brackets - 1
		end

		if s == "(" then
			brackets = brackets + 1
		end

		if brackets == 0 then
			return string.sub(code, starti, i-1), i + 1 -- i: ( i+1 after (
		end

		i = i + 1
	end
	return nil, nil
end

yc.command_parsecondition = function(cond, L, eeprom)
	cond = string.gsub(cond, "A", tonumber(L.a and 1 or 0))
	cond = string.gsub(cond, "B", tonumber(L.b and 1 or 0))
	cond = string.gsub(cond, "C", tonumber(L.c and 1 or 0))
	cond = string.gsub(cond, "D", tonumber(L.d and 1 or 0))

	local i = 1
	local l = string.len(cond)
	while i<=l do
		local s = cond:sub(i,i)
		if s == "#" then
			local addr, endi = yc.parse_get_eeprom_param(cond, i+1)
			local buf = yc.eeprom_read(tonumber(addr), eeprom)
			if buf == nil then return nil end
			local call = cond:sub(i, endi-1)
			cond = string.gsub(cond, call, buf)
			i = 0
			l = string.len(cond)
		end
		i = i + 1
	end

	cond = string.gsub(cond, "!0", "1")
	cond = string.gsub(cond, "!1", "0")

	i = 2
	l = string.len(cond)
	while i<=l do
		local s = cond:sub(i,i)
		local b = tonumber(cond:sub(i-1, i-1))
		local a = tonumber(cond:sub(i+1, i+1))
		if cond:sub(i+1, i+1) == nil then break end
		if s == "=" then
			if a==nil then return nil end
			if b==nil then return nil end
			local buf = a == b and "1" or "0"
			cond = string.gsub(cond, b..s..a, buf)
			i = 1
			l = string.len(cond)
		end
		i = i + 1
	end

	i = 2
	l = string.len(cond)
	while i<=l do
		local s = cond:sub(i,i)
		local b = tonumber(cond:sub(i-1, i-1))
		local a = tonumber(cond:sub(i+1, i+1))
		if cond:sub(i+1, i+1) == nil then break end
		if s == "&" then
			if a==nil then return nil end
			if b==nil then return nil end
			local buf = ((a==1) and (b==1))
			if buf == true  then buf = "1" end
			if buf == false then buf = "0" end
			cond = string.gsub(cond, b..s..a, buf)
			i = 1
			l = string.len(cond)
		end
		if s == "|" then
			if a==nil then return nil end
			if b==nil then return nil end
			local buf = ((a == 1) or (b == 1))
			if buf == true  then buf = "1" end
			if buf == false then buf = "0" end
			cond = string.gsub(cond, b..s..a, buf)
			i = 1
			l = string.len(cond)
		end
		if s == "~" then
			if a==nil then return nil end
			if b==nil then return nil end
			local buf = (((a == 1) or (b == 1)) and not((a==1) and (b==1)))
			if buf == true  then buf = "1" end
			if buf == false then buf = "0" end
			cond = string.gsub(cond, b..s..a, buf)
			i = 1
			l = string.len(cond)
		end
		i = i + 1
	end

	return cond
end

--Virtual-Hardware functions
yc.eeprom_read = function(number, eeprom)
	if not number then return end
	return eeprom:sub(number, number)
end

--Real I/O functions
yc.action = function(pos, L) --L-->Lvirtual
	local Lv = yc.get_virtual_portstates(pos)
	local name = "mesecons_microcontroller:microcontroller"
		..tonumber(L.d and 1 or 0)
		..tonumber(L.c and 1 or 0)
		..tonumber(L.b and 1 or 0)
		..tonumber(L.a and 1 or 0)
	local node = minetest.get_node(pos)
	minetest.swap_node(pos, {name = name, param2 = node.param2})

	yc.action_setports(pos, L, Lv)
end

yc.action_setports = function(pos, L, Lv)
	local name = "mesecons_microcontroller:microcontroller"
	local rules
	if Lv.a ~= L.a then
		rules = microc_rules[name.."0001"]
		if L.a == true then mesecon.receptor_on(pos, rules)
		else mesecon.receptor_off(pos, rules) end
	end
	if Lv.b ~= L.b then
		rules = microc_rules[name.."0010"]
		if L.b == true then mesecon.receptor_on(pos, rules)
		else mesecon.receptor_off(pos, rules) end
	end
	if Lv.c ~= L.c then
		rules = microc_rules[name.."0100"]
		if L.c == true then mesecon.receptor_on(pos, rules)
		else mesecon.receptor_off(pos, rules) end
	end
	if Lv.d ~= L.d then
		rules = microc_rules[name.."1000"]
		if L.d == true then mesecon.receptor_on(pos, rules)
		else mesecon.receptor_off(pos, rules) end
	end
end

yc.set_portstate = function(port, state, L)
	if port == "A" then L.a = state
	elseif port == "B" then L.b = state
	elseif port == "C" then L.c = state
	elseif port == "D" then L.d = state
	else return nil end
	return L
end

-- Updates the real port states according to the signal change.
-- Returns whether the real port states actually changed.
yc.update_real_portstates = function(pos, _, rulename, newstate)
	local meta = minetest.get_meta(pos)
	if rulename == nil then
		meta:set_int("real_portstates", 1)
		return true
	end
	local real_portstates = meta:get_int("real_portstates")
	local n = real_portstates - 1
	local L = {}
	for i = 1, 4 do
		L[i] = n%2
		n = math.floor(n/2)
	end
	if rulename.x == nil then
		for _, rname in ipairs(rulename) do
			local port = ({4, 1, nil, 3, 2})[rname.x+2*rname.z+3]
			L[port] = (newstate == "on") and 1 or 0
		end
	else
		local port = ({4, 1, nil, 3, 2})[rulename.x+2*rulename.z+3]
		L[port] = (newstate == "on") and 1 or 0
	end
	local new_portstates = 1 + L[1] + 2*L[2] + 4*L[3] + 8*L[4]
	if new_portstates ~= real_portstates then
		meta:set_int("real_portstates", new_portstates)
		return true
	end
	return false
end

yc.get_real_portstates = function(pos) -- determine if ports are powered (by itself or from outside)
	local meta = minetest.get_meta(pos)
	local L = {}
	local n = meta:get_int("real_portstates") - 1
	for _, index in ipairs({"a", "b", "c", "d"}) do
		L[index] = ((n%2) == 1)
		n = math.floor(n/2)
	end
	return L
end

yc.get_virtual_portstates = function(pos) -- portstates according to the name
	local name = minetest.get_node(pos).name
	local _, a = string.find(name, ":microcontroller")
	if a == nil then return nil end
	a = a + 1

	local Lvirtual = {a=false, b=false, c=false, d=false}
	if name:sub(a  , a  ) == "1" then Lvirtual.d = true end
	if name:sub(a+1, a+1) == "1" then Lvirtual.c = true end
	if name:sub(a+2, a+2) == "1" then Lvirtual.b = true end
	if name:sub(a+3, a+3) == "1" then Lvirtual.a = true end
	return Lvirtual
end

yc.merge_portstates = function(Lreal, Lvirtual)
	local L = {a=false, b=false, c=false, d=false}
	if Lvirtual.a or Lreal.a then L.a = true end
	if Lvirtual.b or Lreal.b then L.b = true end
	if Lvirtual.c or Lreal.c then L.c = true end
	if Lvirtual.d or Lreal.d then L.d = true end
	return L
end


code:
name = mesecons_microcontroller
depends = mesecons, mesecons_gamecompat


code:
Movestones are effectors that push the blocks in front of them. They move along on the right side of a mesecon wire track.
A movestone trying to move into, or push other nodes into, an unloaded block doesn't move.


code:
Movestones are effectors that push the blocks in front of them. They move along on the right side of a mesecon wire track. Sticky ones also pull blocks.
A sticky movestone trying to move into, or push other nodes into, an unloaded block doesn't move.
A sticky movestone trying to pull nodes from an unloaded block moves but leaves them behind.


code:
-- MOVESTONE
-- Non-sticky:
-- Moves along mesecon lines
-- Pushes all blocks in front of it
--
-- Sticky one
-- Moves along mesecon lines
-- Pushes all block in front of it
-- Pull all blocks in its back

-- settings:
local timer_interval = 1 / mesecon.setting("movestone_speed", 3)
local max_push = mesecon.setting("movestone_max_push", 50)
local max_pull = mesecon.setting("movestone_max_pull", 50)

-- helper functions:
local function get_movestone_direction(rulename, is_vertical)
	if is_vertical then
		if rulename.z > 0 then
			return {x = 0, y = -1, z = 0}
		elseif rulename.z < 0 then
			return {x = 0, y = 1, z = 0}
		elseif rulename.x > 0 then
			return {x = 0, y = -1, z = 0}
		elseif rulename.x < 0 then
			return {x = 0, y = 1, z = 0}
		end
	else
		if rulename.z > 0 then
			return {x = -1, y = 0, z = 0}
		elseif rulename.z < 0 then
			return {x = 1, y = 0, z = 0}
		elseif rulename.x > 0 then
			return {x = 0, y = 0, z = -1}
		elseif rulename.x < 0 then
			return {x = 0, y = 0, z = 1}
		end
	end
end

-- registration functions:
function mesecon.register_movestone(name, def, is_sticky, is_vertical)
	local function movestone_move(pos, node, rulename)
		local direction = get_movestone_direction(rulename, is_vertical)
		local frontpos = vector.add(pos, direction)
		local meta = minetest.get_meta(pos)
		local owner = meta:get_string("owner")

		-- ### Step 1: Push nodes in front ###
		local success, stack, oldstack = mesecon.mvps_push(frontpos, direction, max_push, owner)
		if not success then
			if stack == "protected" then
				meta:set_string("infotext", "Can't move: protected area on the way")
				return
			end
			minetest.get_node_timer(pos):start(timer_interval)
			return
		end
		mesecon.mvps_move_objects(frontpos, direction, oldstack)

		-- ### Step 2: Move the movestone ###
		minetest.set_node(frontpos, node)
		local meta2 = minetest.get_meta(frontpos)
		meta2:set_string("owner", owner)
		minetest.remove_node(pos)
		mesecon.on_dignode(pos, node)
		mesecon.on_placenode(frontpos, node)
		minetest.get_node_timer(frontpos):start(timer_interval)
		minetest.sound_play("movestone", { pos = pos, max_hear_distance = 20, gain = 0.5 }, true)

		-- ### Step 3: If sticky, pull stack behind ###
		if is_sticky then
			local backpos = vector.subtract(pos, direction)
			local success, _, oldstack = mesecon.mvps_pull_all(backpos, direction, max_pull, owner)
			if success then
				mesecon.mvps_move_objects(backpos, vector.multiply(direction, -1), oldstack, -1)
			end
		end

		-- ### Step 4: Let things fall ###
		minetest.check_for_falling(vector.add(pos, {x=0, y=1, z=0}))
	end

	def.is_ground_content = false

	def.mesecons = {effector = {
		action_on = function(pos, node, rulename)
			if rulename and not minetest.get_node_timer(pos):is_started() then
				movestone_move(pos, node, rulename)
			end
		end,
		rules = mesecon.rules.default,
	}}

	def.after_place_node = mesecon.mvps_set_owner

	def.on_punch = function(pos, _, player)
		local player_name = player and player.get_player_name and player:get_player_name()
		if mesecon.mvps_claim(pos, player_name) then
			minetest.get_node_timer(pos):start(timer_interval)
			minetest.chat_send_player(player_name, "Reclaimed movestone")
		end
	end

	def.on_timer = function(pos)
		local sourcepos = mesecon.is_powered(pos)
		if not sourcepos then
			return
		end
		local rulename = vector.subtract(sourcepos[1], pos)
		mesecon.activate(pos, minetest.get_node(pos), rulename, 0)
	end

	def.on_blast = mesecon.on_blastnode

	minetest.register_node(name, def)
end

-- registration:
mesecon.register_movestone("mesecons_movestones:movestone", {
	tiles = {
		"jeija_movestone_side.png",
		"jeija_movestone_side.png",
		"jeija_movestone_arrows.png^[transformFX",
		"jeija_movestone_arrows.png^[transformFX",
		"jeija_movestone_arrows.png",
		"jeija_movestone_arrows.png",
	},
	groups = {cracky = 3},
    description = "Movestone",
	sounds = mesecon.node_sound.stone
}, false, false)

mesecon.register_movestone("mesecons_movestones:sticky_movestone", {
	tiles = {
		"jeija_movestone_side.png",
		"jeija_movestone_side.png",
		"jeija_sticky_movestone.png^[transformFX",
		"jeija_sticky_movestone.png^[transformFX",
		"jeija_sticky_movestone.png",
		"jeija_sticky_movestone.png",
	},
	groups = {cracky = 3},
    description = "Sticky Movestone",
	sounds = mesecon.node_sound.stone,
}, true, false)

mesecon.register_movestone("mesecons_movestones:movestone_vertical", {
	tiles = {
		"jeija_movestone_side.png",
		"jeija_movestone_side.png",
		"jeija_movestone_arrows.png^[transformFXR90",
		"jeija_movestone_arrows.png^[transformR90",
		"jeija_movestone_arrows.png^[transformFXR90",
		"jeija_movestone_arrows.png^[transformR90",
	},
	groups = {cracky = 3},
    description = "Vertical Movestone",
	sounds = mesecon.node_sound.stone
}, false, true)

mesecon.register_movestone("mesecons_movestones:sticky_movestone_vertical", {
	tiles = {
		"jeija_movestone_side.png^(mesecons_glue.png^[opacity:127)",
		"jeija_movestone_side.png^(mesecons_glue.png^[opacity:127)",
		"jeija_movestone_arrows.png^[transformFXR90",
		"jeija_movestone_arrows.png^[transformR90",
		"jeija_movestone_arrows.png^[transformFXR90",
		"jeija_movestone_arrows.png^[transformR90",
	},
	groups = {cracky = 3},
    description = "Vertical Sticky Movestone",
	sounds = mesecon.node_sound.stone,
}, true, true)

-- crafting:
-- base recipe:
minetest.register_craft({
	output = "mesecons_movestones:movestone 2",
	recipe = {
		{"mesecons_gamecompat:stone", "mesecons_gamecompat:stone", "mesecons_gamecompat:stone"},
		{"group:mesecon_conductor_craftable", "group:mesecon_conductor_craftable", "group:mesecon_conductor_craftable"},
		{"mesecons_gamecompat:stone", "mesecons_gamecompat:stone", "mesecons_gamecompat:stone"},
	}
})

-- conversation:
minetest.register_craft({
	type = "shapeless",
	output = "mesecons_movestones:movestone",
	recipe = {"mesecons_movestones:movestone_vertical"},
})

minetest.register_craft({
	type = "shapeless",
	output = "mesecons_movestones:movestone_vertical",
	recipe = {"mesecons_movestones:movestone"},
})

minetest.register_craft({
	type = "shapeless",
	output = "mesecons_movestones:sticky_movestone",
	recipe = {"mesecons_movestones:sticky_movestone_vertical"},
})

minetest.register_craft({
	type = "shapeless",
	output = "mesecons_movestones:sticky_movestone_vertical",
	recipe = {"mesecons_movestones:sticky_movestone"},
})

-- make sticky:
minetest.register_craft({
	output = "mesecons_movestones:sticky_movestone",
	recipe = {
		{"mesecons_materials:glue", "mesecons_movestones:movestone", "mesecons_materials:glue"},
	}
})

minetest.register_craft({
	output = "mesecons_movestones:sticky_movestone_vertical",
	recipe = {
		{"mesecons_materials:glue"},
		{"mesecons_movestones:movestone_vertical"},
		{"mesecons_materials:glue"},
	}
})

-- legacy code:
minetest.register_alias("mesecons_movestones:movestone_active",
		"mesecons_movestones:movestone")
minetest.register_alias("mesecons_movestones:sticky_movestone_active",
		"mesecons_movestones:sticky_movestone")


code:
name = mesecons_movestones
depends = mesecons, mesecons_gamecompat, mesecons_materials, mesecons_mvps


code:
--register stoppers for movestones/pistons

mesecon.mvps_stoppers = {}
mesecon.on_mvps_move = {}
mesecon.mvps_unmov = {}

--- Objects (entities) that cannot be moved
function mesecon.register_mvps_unmov(objectname)
	mesecon.mvps_unmov[objectname] = true;
end

function mesecon.is_mvps_unmov(objectname)
	return mesecon.mvps_unmov[objectname]
end

-- Nodes that cannot be pushed / pulled by movestones, pistons
function mesecon.is_mvps_stopper(node, pushdir, stack, stackid)
	-- unknown nodes are always stoppers
	if not minetest.registered_nodes[node.name] then
		return true
	end

	local get_stopper = mesecon.mvps_stoppers[node.name]
	if type (get_stopper) == "function" then
		get_stopper = get_stopper(node, pushdir, stack, stackid)
	end

	return get_stopper
end

function mesecon.register_mvps_stopper(nodename, get_stopper)
	if get_stopper == nil then
			get_stopper = true
	end
	mesecon.mvps_stoppers[nodename] = get_stopper
end

-- Functions to be called on mvps movement
function mesecon.register_on_mvps_move(callback)
	mesecon.on_mvps_move[#mesecon.on_mvps_move+1] = callback
end

local function on_mvps_move(moved_nodes)
	for _, callback in ipairs(mesecon.on_mvps_move) do
		callback(moved_nodes)
	end
end

function mesecon.mvps_process_stack()
	-- This function is kept for compatibility.
	-- It used to call on_placenode on moved nodes, but that is now done automatically.
end

-- tests if the node can be pushed into, e.g. air, water, grass
local function node_replaceable(name)
	if minetest.registered_nodes[name] then
		return minetest.registered_nodes[name].buildable_to or false
	end

	return false
end

function mesecon.mvps_get_stack(pos, dir, maximum, all_pull_sticky)
	-- determine the number of nodes to be pushed
	local nodes = {}
	local pos_set = {}
	local frontiers = mesecon.fifo_queue.new()
	frontiers:add(vector.new(pos))

	for np in frontiers:iter() do
		local np_hash = minetest.hash_node_position(np)
		local nn = not pos_set[np_hash] and minetest.get_node(np)
		if nn and not node_replaceable(nn.name) then
			pos_set[np_hash] = true
			table.insert(nodes, {node = nn, pos = np})
			if #nodes > maximum then return nil end

			-- add connected nodes to frontiers
			if minetest.registered_nodes[nn.name]
			and minetest.registered_nodes[nn.name].mvps_sticky then
				local connected = minetest.registered_nodes[nn.name].mvps_sticky(np, nn)
				for _, cp in ipairs(connected) do
					frontiers:add(cp)
				end
			end

			frontiers:add(vector.add(np, dir))

			-- If adjacent node is sticky block and connects add that
			-- position
			for _, r in ipairs(mesecon.rules.alldirs) do
				local adjpos = vector.add(np, r)
				local adjnode = minetest.get_node(adjpos)
				if minetest.registered_nodes[adjnode.name]
				and minetest.registered_nodes[adjnode.name].mvps_sticky then
					local sticksto = minetest.registered_nodes[adjnode.name]
						.mvps_sticky(adjpos, adjnode)

					-- connects to this position?
					for _, link in ipairs(sticksto) do
						if vector.equals(link, np) then
							frontiers:add(adjpos)
						end
					end
				end
			end

			if all_pull_sticky then
				frontiers:add(vector.subtract(np, dir))
			end
		end
	end

	return nodes
end

function mesecon.mvps_set_owner(pos, placer)
	local meta = minetest.get_meta(pos)
	local owner = placer and placer.get_player_name and placer:get_player_name()
	if owner and owner ~= "" then
		meta:set_string("owner", owner)
	else
		meta:set_string("owner", "$unknown") -- to distinguish from older pistons
	end
end

function mesecon.mvps_claim(pos, player_name)
	if not player_name or player_name == "" then return end
	local meta = minetest.get_meta(pos)
	if meta:get_string("infotext") == "" then return end
	if meta:get_string("owner") == player_name then return end -- already owned
	if minetest.is_protected(pos, player_name) then
		minetest.chat_send_player(player_name, "Can't reclaim: protected")
		return
	end
	meta:set_string("owner", player_name)
	meta:set_string("infotext", "")
	return true
end

local function add_pos(positions, pos)
	local hash = minetest.hash_node_position(pos)
	positions[hash] = pos
end

local function are_protected(positions, player_name)
	local mode = mesecon.setting("mvps_protection_mode", "compat")
	if mode == "ignore" then
		return false
	end
	local name = player_name
	if player_name == "" or not player_name then -- legacy MVPS
		if mode == "normal" then
			name = "$unknown" -- sentinel, for checking for *any* protection
		elseif mode == "compat" then
			return false
		elseif mode == "restrict" then
			return true
		else
			error("Invalid protection mode")
		end
	end
	local is_protected = minetest.is_protected
	for _, pos in pairs(positions) do
		if is_protected(pos, name) then
			return true
		end
	end
	return false
end

function mesecon.mvps_push(pos, dir, maximum, player_name)
	return mesecon.mvps_push_or_pull(pos, dir, dir, maximum, false, player_name)
end

function mesecon.mvps_pull_all(pos, dir, maximum, player_name)
	return mesecon.mvps_push_or_pull(pos, vector.multiply(dir, -1), dir, maximum, true, player_name)
end

function mesecon.mvps_pull_single(pos, dir, maximum, player_name)
	return mesecon.mvps_push_or_pull(pos, vector.multiply(dir, -1), dir, maximum, false, player_name)
end

-- pos: pos of mvps
-- stackdir: direction of building the stack
-- movedir: direction of actual movement
-- maximum: maximum nodes to be pushed
-- all_pull_sticky: All nodes are sticky in the direction that they are pulled from
-- player_name: Player responsible for the action.
--  - empty string means legacy MVPS, actual check depends on configuration
--  - "$unknown" is a sentinel for forcing the check
function mesecon.mvps_push_or_pull(pos, stackdir, movedir, maximum, all_pull_sticky, player_name)
	local nodes = mesecon.mvps_get_stack(pos, movedir, maximum, all_pull_sticky)

	if not nodes then return end

	local protection_check_set = {}
	if vector.equals(stackdir, movedir) then -- pushing
		add_pos(protection_check_set, pos)
	end
	-- determine if one of the nodes blocks the push / pull
	for id, n in ipairs(nodes) do
		if mesecon.is_mvps_stopper(n.node, movedir, nodes, id) then
			return
		end
		add_pos(protection_check_set, n.pos)
		add_pos(protection_check_set, vector.add(n.pos, movedir))
	end
	if are_protected(protection_check_set, player_name) then
		return false, "protected"
	end

	-- remove all nodes
	for _, n in ipairs(nodes) do
		n.meta = minetest.get_meta(n.pos):to_table()
		local node_timer = minetest.get_node_timer(n.pos)
		if node_timer:is_started() then
			n.node_timer = {node_timer:get_timeout(), node_timer:get_elapsed()}
		end
		minetest.remove_node(n.pos)
	end

	local oldstack = mesecon.tablecopy(nodes)

	-- update mesecons for removed nodes ( has to be done after all nodes have been removed )
	for _, n in ipairs(nodes) do
		mesecon.on_dignode(n.pos, n.node)
	end

	-- add nodes
	for _, n in ipairs(nodes) do
		local np = vector.add(n.pos, movedir)

		-- Turn off conductors in transit
		local conductor = mesecon.get_conductor(n.node.name)
		if conductor and conductor.state ~= mesecon.state.off then
			n.node.name = conductor.offstate or conductor.states[1]
		end

		minetest.set_node(np, n.node)
		minetest.get_meta(np):from_table(n.meta)
		if n.node_timer then
			minetest.get_node_timer(np):set(unpack(n.node_timer))
		end
	end

	local moved_nodes = {}
	for i in ipairs(nodes) do
		moved_nodes[i] = {}
		moved_nodes[i].oldpos = nodes[i].pos
		nodes[i].pos = vector.add(nodes[i].pos, movedir)
		moved_nodes[i].pos = nodes[i].pos
		moved_nodes[i].node = nodes[i].node
		moved_nodes[i].meta = nodes[i].meta
		moved_nodes[i].node_timer = nodes[i].node_timer
	end

	on_mvps_move(moved_nodes)

	return true, nodes, oldstack
end

function mesecon.mvps_move_objects(pos, dir, nodestack, movefactor)
	local dir_k
	local dir_l
	for k, v in pairs(dir) do
		if v ~= 0 then
			dir_k = k
			dir_l = v
			break
		end
	end
	movefactor = movefactor or 1
	dir = vector.multiply(dir, movefactor)
	for id, obj in pairs(minetest.get_objects_inside_radius(pos, #nodestack + 1)) do
		local obj_pos = obj:get_pos()
		local cbox = obj:get_properties().collisionbox
		local min_pos = vector.add(obj_pos, vector.new(cbox[1], cbox[2], cbox[3]))
		local max_pos = vector.add(obj_pos, vector.new(cbox[4], cbox[5], cbox[6]))
		local ok = true
		for k, v in pairs(pos) do
			local edge1, edge2
			if k ~= dir_k then
				edge1 = v - 0.51 -- More than 0.5 to move objects near to the stack.
				edge2 = v + 0.51
			else
				edge1 = v - 0.5 * dir_l
				edge2 = v + (#nodestack + 0.5 * movefactor) * dir_l
				-- Make sure, edge1 is bigger than edge2:
				if edge1 > edge2 then
					edge1, edge2 = edge2, edge1
				end
			end
			if min_pos[k] > edge2 or max_pos[k] < edge1 then
				ok = false
				break
			end
		end
		if ok then
			local ent = obj:get_luaentity()
			if obj:is_player() or (ent and not mesecon.is_mvps_unmov(ent.name)) then
				local np = vector.add(obj_pos, dir)
				-- Move only if destination is not solid or object is inside stack:
				local nn = minetest.get_node(np)
				local node_def = minetest.registered_nodes[nn.name]
				local obj_offset = dir_l * (obj_pos[dir_k] - pos[dir_k])
				if (node_def and not node_def.walkable) or
						(obj_offset >= 0 and
						obj_offset <= #nodestack - 0.5) then
					obj:move_to(np)
				end
			end
		end
	end
end

-- Never push into unloaded blocks. Don’t try to pull from them, either.
-- TODO: load blocks instead, as with wires.
mesecon.register_mvps_stopper("ignore")

mesecon.register_on_mvps_move(mesecon.move_hot_nodes)
mesecon.register_on_mvps_move(function(moved_nodes)
	for i = 1, #moved_nodes do
		local moved_node = moved_nodes[i]
		mesecon.on_placenode(moved_node.pos, moved_node.node)
		minetest.after(0, function()
			minetest.check_for_falling(moved_node.oldpos)
			minetest.check_for_falling(moved_node.pos)
		end)
		local node_def = minetest.registered_nodes[moved_node.node.name]
		if node_def and node_def.mesecon and node_def.mesecon.on_mvps_move then
			node_def.mesecon.on_mvps_move(moved_node.pos, moved_node.node,
					moved_node.oldpos, moved_node.meta)
		end
	end
end)


code:
name = mesecons_mvps
depends = mesecons


code:
This effector makes a sound if powered and can be used for making music. Normally it makes piano sounds. The sound frequency can be changed by punching the block (only works for piano). There are some special sounds that depend on the block below:

Block Below	Effect

Glass or Obsidian Glass	Hi-hat

Any stone	Kick

Chest or Locked Chest	Snare

Any tree	Crash

Any wooden planks	Lite Crash

Coal Block	Explosion sound

Lava Source	Fire sound

Steel Block	Piano (high pitch, one octave higher than normal)

Any other block	Piano (low pitch)


code:
minetest.register_node("mesecons_noteblock:noteblock", {
	description = "Noteblock",
	tiles = {"mesecons_noteblock.png"},
	is_ground_content = false,
	groups = {snappy=2, choppy=2, oddly_breakable_by_hand=2},
	on_punch = function(pos, node, puncher) -- change sound when punched
		if minetest.is_protected(pos, puncher and puncher:get_player_name() or "") then
			return
		end

		node.param2 = (node.param2+1)%12
		mesecon.noteblock_play(pos, node.param2)
		minetest.set_node(pos, node)
	end,
	sounds = mesecon.node_sound.wood,
	mesecons = {effector = { -- play sound when activated
		action_on = function(pos, node)
			mesecon.noteblock_play(pos, node.param2)
		end
	}},
	on_blast = mesecon.on_blastnode,
})

minetest.register_craft({
	output = "mesecons_noteblock:noteblock 1",
	recipe = {
		{"group:wood", "group:wood", "group:wood"},
		{"group:mesecon_conductor_craftable", "mesecons_gamecompat:steel_ingot", "group:mesecon_conductor_craftable"},
		{"group:wood", "group:wood", "group:wood"},
	}
})

local soundnames = {
	[0] = "mesecons_noteblock_csharp",
	"mesecons_noteblock_d",
	"mesecons_noteblock_dsharp",
	"mesecons_noteblock_e",
	"mesecons_noteblock_f",
	"mesecons_noteblock_fsharp",
	"mesecons_noteblock_g",
	"mesecons_noteblock_gsharp",

	"mesecons_noteblock_a",
	"mesecons_noteblock_asharp",
	"mesecons_noteblock_b",
	"mesecons_noteblock_c"
}

local node_sounds = {}
for alias, sound in pairs({
	["mesecons_gamecompat:lava_source"] = mesecon.sound_name.fire,
	["mesecons_gamecompat:chest"] = "mesecons_noteblock_snare",
	["mesecons_gamecompat:chest_locked"] = "mesecons_noteblock_snare",
	["mesecons_gamecompat:coalblock"] = mesecon.sound_name.explode,
	["mesecons_gamecompat:glass"] = "mesecons_noteblock_hihat",
	["mesecons_gamecompat:obsidian_glass"] = "mesecons_noteblock_hihat",
}) do
	local nodename = minetest.registered_aliases[alias]
	if nodename then
		node_sounds[nodename] = sound
	end
end

local node_sounds_group = {
	["stone"] = "mesecons_noteblock_kick",
	["tree"] = "mesecons_noteblock_crash",
	["wood"] = "mesecons_noteblock_litecrash",
}

local steelblock_nodename = minetest.registered_aliases["mesecons_gamecompat:steelblock"]
mesecon.noteblock_play = function(pos, param2)
	pos.y = pos.y-1
	local nodeunder = minetest.get_node(pos).name
	local soundname = node_sounds[nodeunder]
	if not soundname then
		for k,v in pairs(node_sounds_group) do
			local g = minetest.get_item_group(nodeunder, k)
			if g ~= 0 then
				soundname = v
				break
			end
		end
	end
	if not soundname then
		soundname = soundnames[param2]
		if not soundname then
			minetest.log("error", "[mesecons_noteblock] No soundname found, test param2")
			return
		end
		if nodeunder == steelblock_nodename then
			soundname = soundname.. 2
		end
	end
	pos.y = pos.y+1
	if soundname == "fire_fire" then
		-- Smoothly fade out fire sound
		local handle = minetest.sound_play(soundname, {pos = pos, loop = true})
		minetest.after(3.0, minetest.sound_fade, handle, -1.5, 0.0)
	else
		minetest.sound_play(soundname, {pos = pos}, true)
	end
end


code:
name = mesecons_noteblock
depends = mesecons, mesecons_gamecompat


code:
Pistons are effectors, they push up to 20 blocks in front of them. The push direction can be set by placing them from different angles.
A piston pointing into an unloaded block won't extend.
A piston retracting from an unloaded block works, but gravity-sensitive nodes above the empty space may not fall.


code:
Sticky pistons are effectors, they push up to 20 blocks in front of them. The push direction can be set by placing them from different angles. Sticky ones also pull 1 block.
A sticky piston pointing into an unloaded block won't extend.
A sticky piston retracting from within an unloaded block works and pulls a node, but if it doesn't pull anything, then gravity-sensitive nodes above the empty space may not fall.
An extended sticky piston that touches the surface of an unloaded block and loses signal retracts but doesn't pull anything.


code:
local specs = {
	normal = {
		offname = "mesecons_pistons:piston_normal_off",
		onname = "mesecons_pistons:piston_normal_on",
		pusher = "mesecons_pistons:piston_pusher_normal",
	},
	sticky = {
		offname = "mesecons_pistons:piston_sticky_off",
		onname = "mesecons_pistons:piston_sticky_on",
		pusher = "mesecons_pistons:piston_pusher_sticky",
		sticky = true,
	},
}

local function get_pistonspec_name(name, part)
	if part then
		for spec_name, spec in pairs(specs) do
			if name == spec[part] then
				return spec_name, part
			end
		end
		return
	end
	for spec_name, spec in pairs(specs) do
		for part, value in pairs(spec)  do
			if name == value then
				return spec_name, part
			end
		end
	end
end

local function get_pistonspec(name, part)
	return specs[get_pistonspec_name(name, part)]
end

local max_push = mesecon.setting("piston_max_push", 15)
local max_pull = mesecon.setting("piston_max_pull", 15)

-- Get mesecon rules of pistons
local function piston_get_rules(node)
	local dir = minetest.facedir_to_dir(node.param2)
	for k, v in pairs(dir) do
		if v ~= 0 then
			dir = {k, -v}
			break
		end
	end
	local rules = table.copy(mesecon.rules.default)
	for i, rule in ipairs(rules) do
		if rule[dir[1]] == dir[2] then
			table.remove(rules, i)
		end
	end
	return rules
end

local function piston_remove_pusher(pos, node, check_falling)
	local pistonspec = get_pistonspec(node.name, "onname")
	local dir = vector.multiply(minetest.facedir_to_dir(node.param2), -1)
	local pusherpos = vector.add(pos, dir)
	local pushername = minetest.get_node(pusherpos).name

	-- make sure there actually is a pusher (for compatibility reasons mainly)
	if pushername ~= pistonspec.pusher then
		return
	end

	minetest.remove_node(pusherpos)
	minetest.sound_play("piston_retract", { pos = pos, max_hear_distance = 20, gain = 0.3 }, true)

	if check_falling then
		minetest.check_for_falling(pusherpos)
	end
end

local function piston_after_dig(pos, node)
	piston_remove_pusher(pos, node, true)
end

local piston_on = function(pos, node)
	local pistonspec = get_pistonspec(node.name, "offname")
	local dir = vector.multiply(minetest.facedir_to_dir(node.param2), -1)
	local pusher_pos = vector.add(pos, dir)
	local meta = minetest.get_meta(pos)
	local success, stack, oldstack = mesecon.mvps_push(pusher_pos, dir, max_push, meta:get_string("owner"))
	if not success then
		if stack == "protected" then
			meta:set_string("infotext", "Can't extend: protected area on the way")
		end
		return
	end
	minetest.swap_node(pos, {param2 = node.param2, name = pistonspec.onname})
	minetest.set_node(pusher_pos, {param2 = node.param2, name = pistonspec.pusher})
	minetest.sound_play("piston_extend", { pos = pos, max_hear_distance = 20, gain = 0.3 }, true)
	mesecon.mvps_move_objects(pusher_pos, dir, oldstack)
end

local function piston_off(pos, node)
	local pistonspec = get_pistonspec(node.name, "onname")
	minetest.swap_node(pos, {param2 = node.param2, name = pistonspec.offname})
	piston_remove_pusher(pos, node, not pistonspec.sticky) -- allow that even in protected area

	if not pistonspec.sticky then
		return
	end
	local dir = minetest.facedir_to_dir(node.param2)
	local pullpos = vector.add(pos, vector.multiply(dir, -2))
	local meta = minetest.get_meta(pos)
	local success, _, oldstack = mesecon.mvps_pull_single(pullpos, dir, max_pull, meta:get_string("owner"))
	if success then
		mesecon.mvps_move_objects(pullpos, vector.multiply(dir, -1), oldstack, -1)
	end
end

local orientations = {
	[0] = { 4,  8},
	      {13, 17},
	      {10,  6},
	      {20, 15},
}

local function piston_orientate(pos, placer)
	mesecon.mvps_set_owner(pos, placer)
	if not placer then
		return
	end
	local pitch = math.deg(placer:get_look_vertical())
	local node = minetest.get_node(pos)
	if pitch > 55 then
		node.param2 = orientations[node.param2][1]
	elseif pitch < -55 then
		node.param2 = orientations[node.param2][2]
	else
		return
	end
	minetest.swap_node(pos, node)
	-- minetest.after, because on_placenode for unoriented piston must be processed first
	minetest.after(0, mesecon.on_placenode, pos, node)
end

local rotations = {
	{0, 16, 20, 12},
	{2, 14, 22, 18},
	{1,  5, 23,  9},
	{3, 11, 21,  7},
	{4, 13, 10, 19},
	{6, 15,  8, 17},
}

local function get_rotation(param2)
	for a = 1, #rotations do
		for f = 1, #rotations[a] do
			if rotations[a][f] == param2 then
				return a, f
			end
		end
	end
end

local function rotate(param2, mode)
	local axis, face = get_rotation(param2)
	if mode == screwdriver.ROTATE_FACE then
		face = face + 1
		if face > 4 then
			face = 1
		end
	elseif mode == screwdriver.ROTATE_AXIS then
		axis = axis + 1
		if axis > 6 then
			axis = 1
		end
		face = 1
	else
		return param2
	end
	return rotations[axis][face]
end

local function piston_rotate(pos, node, _, mode)
	node.param2 = rotate(node.param2, mode)
	minetest.swap_node(pos, node)
	mesecon.execute_autoconnect_hooks_now(pos, node)
	return true
end

local function piston_rotate_on(pos, node, player, mode)
	local pistonspec = get_pistonspec(node.name, "onname")
	local dir = vector.multiply(minetest.facedir_to_dir(node.param2), -1)
	local pusher_pos = vector.add(dir, pos)
	local pusher_node = minetest.get_node(pusher_pos)
	if pusher_node.name ~= pistonspec.pusher then
		return piston_rotate(pos, node, nil, mode)
	end
	if mode == screwdriver.ROTATE_FACE then
		piston_rotate(pusher_pos, pusher_node, nil, mode)
		return piston_rotate(pos, node, nil, mode)
	elseif mode ~= screwdriver.ROTATE_AXIS then
		return false
	end
	local player_name = player and player:is_player() and player:get_player_name() or ""
	local ok, dir_after, pusher_pos_after
	for i = 1, 5 do
		node.param2 = rotate(node.param2, mode)
		dir_after = vector.multiply(minetest.facedir_to_dir(node.param2), -1)
		pusher_pos_after = vector.add(dir_after, pos)
		local pusher_pos_after_node_name = minetest.get_node(pusher_pos_after).name
		local pusher_pos_after_node_def = minetest.registered_nodes[pusher_pos_after_node_name]
		if pusher_pos_after_node_def and pusher_pos_after_node_def.buildable_to and
				not minetest.is_protected(pusher_pos_after, player_name) then
			ok = true
			break
		end
	end
	if not ok then
		return false
	end
	pusher_node.param2 = node.param2
	minetest.remove_node(pusher_pos)
	minetest.set_node(pusher_pos_after, pusher_node)
	minetest.swap_node(pos, node)
	mesecon.execute_autoconnect_hooks_now(pos, node)
	return true
end

local function piston_rotate_pusher(pos, node, player, mode)
	local pistonspec = get_pistonspec(node.name, "pusher")
	local piston_pos = vector.add(pos, minetest.facedir_to_dir(node.param2))
	local piston_node = minetest.get_node(piston_pos)
	if piston_node.name ~= pistonspec.onname then
		minetest.remove_node(pos) -- Make it possible to remove alone pushers.
		return false
	end
	return piston_rotate_on(piston_pos, piston_node, player, mode)
end

local function piston_punch(pos, _, player)
	local player_name = player and player.get_player_name and player:get_player_name()
	if mesecon.mvps_claim(pos, player_name) then
		minetest.chat_send_player(player_name, "Reclaimed piston")
	end
end

-- Boxes:

local pt = 3/16 -- pusher thickness

local piston_pusher_box = {
	type = "fixed",
	fixed = {
		{-2/16, -2/16, -.5 + pt, 2/16, 2/16,  .5 + pt},
		{-.5  , -.5  , -.5     , .5  , .5  , -.5 + pt},
	},
}

local piston_on_box = {
	type = "fixed",
	fixed = {
		{-.5, -.5, -.5 + pt, .5, .5, .5}
	},
}

-- Normal (non-sticky) Pistons:
-- offstate
minetest.register_node("mesecons_pistons:piston_normal_off", {
	description = "Piston",
	tiles = {
		"mesecons_piston_top.png",
		"mesecons_piston_bottom.png",
		"mesecons_piston_left.png",
		"mesecons_piston_right.png",
		"mesecons_piston_back.png",
		"mesecons_piston_pusher_front.png"
	},
	groups = {cracky = 3},
	paramtype2 = "facedir",
	is_ground_content = false,
	after_place_node = piston_orientate,
	sounds = mesecon.node_sound.wood,
	mesecons = {effector={
		action_on = piston_on,
		rules = piston_get_rules,
	}},
	on_punch = piston_punch,
	on_rotate = piston_rotate,
	on_blast = mesecon.on_blastnode,
})

-- onstate
minetest.register_node("mesecons_pistons:piston_normal_on", {
	description = "Activated Piston Base",
	drawtype = "nodebox",
	tiles = {
		"mesecons_piston_top.png",
		"mesecons_piston_bottom.png",
		"mesecons_piston_left.png",
		"mesecons_piston_right.png",
		"mesecons_piston_back.png",
		"mesecons_piston_on_front.png"
	},
	groups = {cracky = 3, not_in_creative_inventory = 1},
	paramtype = "light",
	paramtype2 = "facedir",
	is_ground_content = false,
	drop = "mesecons_pistons:piston_normal_off",
	after_dig_node = piston_after_dig,
	node_box = piston_on_box,
	selection_box = piston_on_box,
	sounds = mesecon.node_sound.wood,
	mesecons = {effector={
		action_off = piston_off,
		rules = piston_get_rules,
	}},
	on_rotate = piston_rotate_on,
	on_blast = mesecon.on_blastnode,
})

-- pusher
minetest.register_node("mesecons_pistons:piston_pusher_normal", {
	description = "Piston Pusher",
	drawtype = "nodebox",
	tiles = {
		"mesecons_piston_pusher_top.png",
		"mesecons_piston_pusher_bottom.png",
		"mesecons_piston_pusher_left.png",
		"mesecons_piston_pusher_right.png",
		"mesecons_piston_pusher_back.png",
		"mesecons_piston_pusher_front.png"
	},
	groups = {not_in_creative_inventory = 1},
	paramtype = "light",
	paramtype2 = "facedir",
	is_ground_content = false,
	diggable = false,
	selection_box = piston_pusher_box,
	node_box = piston_pusher_box,
	on_rotate = piston_rotate_pusher,
	drop = "",
	sounds = mesecon.node_sound.wood,
})

-- Sticky ones
-- offstate
minetest.register_node("mesecons_pistons:piston_sticky_off", {
	description = "Sticky Piston",
	tiles = {
		"mesecons_piston_top.png",
		"mesecons_piston_bottom.png",
		"mesecons_piston_left.png",
		"mesecons_piston_right.png",
		"mesecons_piston_back.png",
		"mesecons_piston_pusher_front_sticky.png"
	},
	groups = {cracky = 3},
	paramtype2 = "facedir",
	is_ground_content = false,
	after_place_node = piston_orientate,
	sounds = mesecon.node_sound.wood,
	mesecons = {effector={
		action_on = piston_on,
		rules = piston_get_rules,
	}},
	on_punch = piston_punch,
	on_rotate = piston_rotate,
	on_blast = mesecon.on_blastnode,
})

-- onstate
minetest.register_node("mesecons_pistons:piston_sticky_on", {
	description = "Activated Sticky Piston Base",
	drawtype = "nodebox",
	tiles = {
		"mesecons_piston_top.png",
		"mesecons_piston_bottom.png",
		"mesecons_piston_left.png",
		"mesecons_piston_right.png",
		"mesecons_piston_back.png",
		"mesecons_piston_on_front.png"
	},
	groups = {cracky = 3, not_in_creative_inventory = 1},
	paramtype = "light",
	paramtype2 = "facedir",
	is_ground_content = false,
	drop = "mesecons_pistons:piston_sticky_off",
	after_dig_node = piston_after_dig,
	node_box = piston_on_box,
	selection_box = piston_on_box,
	sounds = mesecon.node_sound.wood,
	mesecons = {effector={
		action_off = piston_off,
		rules = piston_get_rules,
	}},
	on_rotate = piston_rotate_on,
	on_blast = mesecon.on_blastnode,
})

-- pusher
minetest.register_node("mesecons_pistons:piston_pusher_sticky", {
	description = "Sticky Piston Pusher",
	drawtype = "nodebox",
	tiles = {
		"mesecons_piston_pusher_top.png",
		"mesecons_piston_pusher_bottom.png",
		"mesecons_piston_pusher_left.png",
		"mesecons_piston_pusher_right.png",
		"mesecons_piston_pusher_back.png",
		"mesecons_piston_pusher_front_sticky.png"
	},
	groups = {not_in_creative_inventory = 1},
	paramtype = "light",
	paramtype2 = "facedir",
	is_ground_content = false,
	diggable = false,
	selection_box = piston_pusher_box,
	node_box = piston_pusher_box,
	on_rotate = piston_rotate_pusher,
	drop = "",
	sounds = mesecon.node_sound.wood,
})

-- Register pushers as stoppers if they would be seperated from the piston
local function piston_pusher_get_stopper(node, _, stack, stackid)
	if (stack[stackid + 1]
	and stack[stackid + 1].node.name   == get_pistonspec(node.name, "pusher").onname
	and stack[stackid + 1].node.param2 == node.param2)
	or (stack[stackid - 1]
	and stack[stackid - 1].node.name   == get_pistonspec(node.name, "pusher").onname
	and stack[stackid - 1].node.param2 == node.param2) then
		return false
	end
	return true
end

mesecon.register_mvps_stopper("mesecons_pistons:piston_pusher_normal", piston_pusher_get_stopper)
mesecon.register_mvps_stopper("mesecons_pistons:piston_pusher_sticky", piston_pusher_get_stopper)

-- Register pistons as stoppers if they would be seperated from the stopper
local function piston_get_stopper(node, _, stack, stackid)
	local pistonspec = get_pistonspec(node.name, "onname")
	local dir = vector.multiply(minetest.facedir_to_dir(node.param2), -1)
	local pusherpos = vector.add(stack[stackid].pos, dir)
	local pushernode = minetest.get_node(pusherpos)
	if pistonspec.pusher == pushernode.name then
		for _, s in ipairs(stack) do
			if  vector.equals(s.pos, pusherpos) -- pusher is also to be pushed
			and s.node.param2 == node.param2 then
				return false
			end
		end
	end
	return true
end

mesecon.register_mvps_stopper("mesecons_pistons:piston_normal_on", piston_get_stopper)
mesecon.register_mvps_stopper("mesecons_pistons:piston_sticky_on", piston_get_stopper)

--craft recipes
minetest.register_craft({
	output = "mesecons_pistons:piston_normal_off 2",
	recipe = {
		{"group:wood",             "group:wood",                        "group:wood"},
		{"mesecons_gamecompat:cobble", "mesecons_gamecompat:steel_ingot",       "mesecons_gamecompat:cobble"},
		{"mesecons_gamecompat:cobble", "group:mesecon_conductor_craftable", "mesecons_gamecompat:cobble"},
	}
})

minetest.register_craft({
	output = "mesecons_pistons:piston_sticky_off",
	recipe = {
		{"mesecons_materials:glue"},
		{"mesecons_pistons:piston_normal_off"},
	}
})

-- load legacy code
dofile(minetest.get_modpath("mesecons_pistons").."/legacy.lua")


code:
local ground_dir = {
	[0] = {x =  0, y = -1, z =  0},
	      {x =  0, y =  0, z = -1},
	      {x =  0, y =  0, z =  1},
	      {x = -1, y =  0, z =  0},
	      {x =  1, y =  0, z =  0},
	      {x =  0, y =  1, z =  0},
}

minetest.register_lbm({
	label = "Upgrade legacy pistons pointing up",
	name = "mesecons_pistons:replace_legacy_piston_up",
	nodenames = {
		"mesecons_pistons:piston_up_normal_off",
		"mesecons_pistons:piston_up_normal_on",
		"mesecons_pistons:piston_up_pusher_normal",
		"mesecons_pistons:piston_up_sticky_off",
		"mesecons_pistons:piston_up_sticky_on",
		"mesecons_pistons:piston_up_pusher_sticky",
	},
	run_at_every_load = false,
	action = function(pos, node)
		local dir = ground_dir[math.floor(node.param2/4)]
		node.param2 = minetest.dir_to_facedir(dir, true)
		node.name = node.name:sub(1, 24)..node.name:sub(28)
		minetest.swap_node(pos, node)
	end,
})

minetest.register_lbm({
	label = "Upgrade legacy pistons pointing down",
	name = "mesecons_pistons:replace_legacy_piston_down",
	nodenames = {
		"mesecons_pistons:piston_down_normal_off",
		"mesecons_pistons:piston_down_normal_on",
		"mesecons_pistons:piston_down_pusher_normal",
		"mesecons_pistons:piston_down_sticky_off",
		"mesecons_pistons:piston_down_sticky_on",
		"mesecons_pistons:piston_down_pusher_sticky",
	},
	run_at_every_load = false,
	action = function(pos, node)
		local dir = vector.multiply(ground_dir[math.floor(node.param2/4)], -1)
		node.param2 = minetest.dir_to_facedir(dir, true)
		node.name = node.name:sub(1, 24)..node.name:sub(30)
		minetest.swap_node(pos, node)
	end,
})


code:
name = mesecons_pistons
depends = mesecons, mesecons_gamecompat, mesecons_mvps


code:
A power plant is a receptor that is always turned on: it provides energy.
It continues to work in an unloaded block.


code:
-- The POWER_PLANT
-- Just emits power. always.

minetest.register_node("mesecons_powerplant:power_plant", {
	drawtype = "plantlike",
	visual_scale = 1,
	tiles = {"jeija_power_plant.png"},
	inventory_image = "jeija_power_plant.png",
	paramtype = "light",
	is_ground_content = false,
	walkable = false,
	groups = {dig_immediate=3, mesecon = 2},
	light_source = minetest.LIGHT_MAX-9,
	description="Power Plant",
	selection_box = {
		type = "fixed",
		fixed = {-0.3, -0.5, -0.3, 0.3, -0.5+0.7, 0.3},
	},
	sounds = mesecon.node_sound.leaves,
	mesecons = {receptor = {
		state = mesecon.state.on
	}},
	on_blast = mesecon.on_blastnode,
})

minetest.register_craft({
	output = "mesecons_powerplant:power_plant 1",
	recipe = {
		{"group:mesecon_conductor_craftable"},
		{"group:mesecon_conductor_craftable"},
		{"group:sapling"},
	}
})


code:
name = mesecons_powerplant
depends = mesecons, mesecons_gamecompat


code: This receptor turns on if there's an object above it. An object can be a player, an item, a mob...


code:
local pp_box_off = {
	type = "fixed",
	fixed = { -7/16, -8/16, -7/16, 7/16, -7/16, 7/16 },
}

local pp_box_on = {
	type = "fixed",
	fixed = { -7/16, -8/16, -7/16, 7/16, -7.5/16, 7/16 },
}

local function pp_on_timer(pos)
	local node = minetest.get_node(pos)
	local basename = minetest.registered_nodes[node.name].pressureplate_basename

	-- This is a workaround for a strange bug that occurs when the server is started
	-- For some reason the first time on_timer is called, the pos is wrong
	if not basename then return end

	local objs   = minetest.get_objects_inside_radius(pos, 1)

	if objs[1] == nil and node.name == basename .. "_on" then
		minetest.set_node(pos, {name = basename .. "_off"})
		mesecon.receptor_off(pos, mesecon.rules.pplate)
	elseif node.name == basename .. "_off" then
		for k, obj in pairs(objs) do
			local objpos = obj:get_pos()
			if objpos.y > pos.y-1 and objpos.y < pos.y then
				minetest.set_node(pos, {name = basename .. "_on"})
				mesecon.receptor_on(pos, mesecon.rules.pplate )
			end
		end
	end
	return true
end

-- Register a Pressure Plate
-- offstate:	name of the pressure plate when inactive
-- onstate:	name of the pressure plate when active
-- description:	description displayed in the player's inventory
-- tiles_off:	textures of the pressure plate when inactive
-- tiles_on:	textures of the pressure plate when active
-- image:	inventory and wield image of the pressure plate
-- recipe:	crafting recipe of the pressure plate
-- groups:	groups
-- sounds:	sound table

function mesecon.register_pressure_plate(basename, description, textures_off, textures_on, image_w, image_i, recipe, groups, sounds)
	if not groups then
		groups = {}
	end
	local groups_off = table.copy(groups)
	local groups_on = table.copy(groups)
	groups_on.not_in_creative_inventory = 1

	mesecon.register_node(basename, {
		drawtype = "nodebox",
		inventory_image = image_i,
		wield_image = image_w,
		paramtype = "light",
		is_ground_content = false,
		description = description,
		pressureplate_basename = basename,
		on_timer = pp_on_timer,
		on_construct = function(pos)
			minetest.get_node_timer(pos):start(mesecon.setting("pplate_interval", 0.1))
		end,
		sounds = sounds,
	},{
		mesecons = {receptor = { state = mesecon.state.off, rules = mesecon.rules.pplate }},
		node_box = pp_box_off,
		selection_box = pp_box_off,
		groups = groups_off,
		tiles = textures_off
	},{
		mesecons = {receptor = { state = mesecon.state.on, rules = mesecon.rules.pplate }},
		node_box = pp_box_on,
		selection_box = pp_box_on,
		groups = groups_on,
		tiles = textures_on
	})

	minetest.register_craft({
		output = basename .. "_off",
		recipe = recipe,
	})
end

mesecon.register_pressure_plate(
	"mesecons_pressureplates:pressure_plate_wood",
	"Wooden Pressure Plate",
	{"jeija_pressure_plate_wood_off.png","jeija_pressure_plate_wood_off.png","jeija_pressure_plate_wood_off_edges.png"},
	{"jeija_pressure_plate_wood_on.png","jeija_pressure_plate_wood_on.png","jeija_pressure_plate_wood_on_edges.png"},
	"jeija_pressure_plate_wood_wield.png",
	"jeija_pressure_plate_wood_inv.png",
	{{"group:wood", "group:wood"}},
	{ choppy = 3, oddly_breakable_by_hand = 3 },
	mesecon.node_sound.wood)

mesecon.register_pressure_plate(
	"mesecons_pressureplates:pressure_plate_stone",
	"Stone Pressure Plate",
	{"jeija_pressure_plate_stone_off.png","jeija_pressure_plate_stone_off.png","jeija_pressure_plate_stone_off_edges.png"},
	{"jeija_pressure_plate_stone_on.png","jeija_pressure_plate_stone_on.png","jeija_pressure_plate_stone_on_edges.png"},
	"jeija_pressure_plate_stone_wield.png",
	"jeija_pressure_plate_stone_inv.png",
	{{"mesecons_gamecompat:cobble", "mesecons_gamecompat:cobble"}},
	{ cracky = 3, oddly_breakable_by_hand = 3 },
	mesecon.node_sound.stone)


code:
name = mesecons_pressureplates
depends = mesecons, mesecons_gamecompat


code:
Ghoststones disappear when powered, just like Removestones. But in contrast to Removestones, they reappear again when not powered anymore and they are also conductive.
They work in inactive blocks.


code:
Removestones are probably the simplest effectors possible. They simply disappear when powered.
They work in inactive blocks.


code:
-- REMOVESTONE

minetest.register_node("mesecons_random:removestone", {
	tiles = {"jeija_removestone.png"},
	is_ground_content = false,
	inventory_image = minetest.inventorycube("jeija_removestone_inv.png"),
	groups = {cracky=3},
	description="Removestone",
	sounds = mesecon.node_sound.stone,
	mesecons = {effector = {
		action_on = function (pos, node)
			minetest.remove_node(pos)
			mesecon.on_dignode(pos, node)
			minetest.check_for_falling(vector.add(pos, vector.new(0, 1, 0)))
		end
	}},
	on_blast = mesecon.on_blastnode,
})

minetest.register_craft({
	output = 'mesecons_random:removestone 4',
	recipe = {
		{"", "mesecons_gamecompat:cobble", ""},
		{"mesecons_gamecompat:cobble", "group:mesecon_conductor_craftable", "mesecons_gamecompat:cobble"},
		{"", "mesecons_gamecompat:cobble", ""},
	}
})

-- GHOSTSTONE

minetest.register_node("mesecons_random:ghoststone", {
	description="Ghoststone",
	tiles = {"jeija_ghoststone.png"},
	is_ground_content = false,
	inventory_image = minetest.inventorycube("jeija_ghoststone_inv.png"),
	groups = {cracky=3},
	sounds = mesecon.node_sound.stone,
	mesecons = {conductor = {
		state = mesecon.state.off,
		rules = mesecon.rules.alldirs,
		onstate = "mesecons_random:ghoststone_active"
	}},
	on_blast = mesecon.on_blastnode,
})

minetest.register_node("mesecons_random:ghoststone_active", {
	drawtype = "airlike",
	pointable = false,
	walkable = false,
	diggable = false,
	is_ground_content = false,
	sunlight_propagates = true,
	paramtype = "light",
	drop = "mesecons_random:ghoststone",
	mesecons = {conductor = {
		state = mesecon.state.on,
		rules = mesecon.rules.alldirs,
		offstate = "mesecons_random:ghoststone"
	}},
	on_construct = function(pos)
		-- remove shadow
		local shadowpos = vector.add(pos, vector.new(0, 1, 0))
		if (minetest.get_node(shadowpos).name == "air") then
			minetest.dig_node(shadowpos)
		end
	end,
	on_blast = mesecon.on_blastnode,
})

minetest.register_craft({
	output = 'mesecons_random:ghoststone 4',
	recipe = {
		{"mesecons_gamecompat:steel_ingot", "mesecons_gamecompat:cobble", "mesecons_gamecompat:steel_ingot"},
		{"mesecons_gamecompat:cobble", "group:mesecon_conductor_craftable", "mesecons_gamecompat:cobble"},
		{"mesecons_gamecompat:steel_ingot", "mesecons_gamecompat:cobble", "mesecons_gamecompat:steel_ingot"},
	}
})


code:
name = mesecons_random
depends = mesecons, mesecons_gamecompat


code:
name = mesecons_receiver
depends = mesecons, mesecons_gamecompat


code:
Solar panels are light receptors: they turn on if there is enough light.
They only work in active blocks; in inactive blocks they keep their old state.


code:
-- Solar Panel
mesecon.register_node("mesecons_solarpanel:solar_panel", {
	description = "Solar Panel",
	drawtype = "nodebox",
	tiles = {"mesecons_solarpanel.png"},
	inventory_image = "mesecons_solarpanel.png",
	wield_image = "mesecons_solarpanel.png",
	paramtype = "light",
	paramtype2 = "wallmounted",
	walkable = false,
	is_ground_content = false,
	node_box = {
		type = "wallmounted",
		wall_bottom = {-7/16, -8/16, -7/16,  7/16, -7/16, 7/16},
		wall_top    = {-7/16,  7/16, -7/16,  7/16,  8/16, 7/16},
		wall_side   = {-8/16, -7/16, -7/16, -7/16,  7/16, 7/16},
	},
	sounds = mesecon.node_sound.glass,
	on_blast = mesecon.on_blastnode,
},{
	groups = {dig_immediate = 3},
	mesecons = {receptor = {
		state = mesecon.state.off,
		rules = mesecon.rules.wallmounted_get
	}}
},{
	groups = {dig_immediate = 3, not_in_creative_inventory = 1},
	mesecons = {receptor = {
		state = mesecon.state.on,
		rules = mesecon.rules.wallmounted_get
	}},
})

minetest.register_craft({
	output = "mesecons_solarpanel:solar_panel_off",
	recipe = {
		{"mesecons_materials:silicon", "mesecons_materials:silicon"},
		{"mesecons_materials:silicon", "mesecons_materials:silicon"},
	}
})

minetest.register_abm({
	label = "Solar Panel On/Off",
	nodenames = {
		"mesecons_solarpanel:solar_panel_off",
		"mesecons_solarpanel:solar_panel_on"
	},
	interval = 1,
	chance = 1,
	catch_up = false,
	action = function(pos, node)
		local light = minetest.get_node_light(pos)
		if light >= 12 and node.name == "mesecons_solarpanel:solar_panel_off" then
			node.name = "mesecons_solarpanel:solar_panel_on"
			minetest.swap_node(pos, node)
			mesecon.receptor_on(pos, mesecon.rules.wallmounted_get(node))
		elseif light < 12 and node.name == "mesecons_solarpanel:solar_panel_on" then
			node.name = "mesecons_solarpanel:solar_panel_off"
			minetest.swap_node(pos, node)
			mesecon.receptor_off(pos, mesecon.rules.wallmounted_get(node))
		end
	end,
})


code:
name = mesecons_solarpanel
depends = mesecons, mesecons_gamecompat, mesecons_materials