-- Mobs Api+random(1)

mobs = {}
mobs.mod = "redo"
mobs.version = "20180505"


-- Intllib
local MP = minetest.get_modpath(minetest.get_current_modname())
local S, NS = dofile(MP .. "/intllib.lua")
mobs.intllib = S


local isInvisible=function(player)
	if not minetest.is_player(player) then return false end
	--return not minetest.check_player_privs(player, "interact") or mfplayers[player:get_player_name()].invisible
	return not minetest.check_player_privs(player, "interact")
end

-- creative check
local creative_mode_cache = minetest.settings:get_bool("creative_mode")
function mobs.is_creative(name)
	return creative_mode_cache or minetest.check_player_privs(name, {creative = true})
end


-- localize math functions
local Vero= {x=0, y=0, z=0}
local pi = math.pi
local square = math.sqrt
local sin = math.sin
local cos = math.cos
local abs = math.abs
local min = math.min
local max = math.max
local atann = math.atan
local random = math.random
local floor = math.floor
local atan = function(x)
	if not x or x ~= x then
		--error("atan bassed NaN")
		return 0
	else
		return atann(x)
	end
end


-- Load settings
local damage_enabled = minetest.settings:get_bool("enable_damage")
local creative = minetest.settings:get_bool("creative_mode")
local show_health = minetest.settings:get_bool("mob_show_health") == true
local mob_chance_multiplier = tonumber(minetest.settings:get("mob_chance_multiplier") or 1)

-- calculate aoc range for mob count
local aosrb = tonumber(minetest.settings:get("active_object_send_range_blocks"))
local abr = tonumber(minetest.settings:get("active_block_range"))
local aoc_range = max(aosrb, abr) * 16

-- default nodes
local node_fire = "fire:basic_flame"
mobs.fallback_node = minetest.registered_aliases["mapgen_dirt"] or "default:dirt"

mobs.tp_fx= function(pos)
	minetest.add_particlespawner
	{
		amount=25,
		time=1,
		minpos={x=pos.x-0.25, y=pos.y, z=pos.z-0.25},
		maxpos={x=pos.x+0.25, y=pos.y, z=pos.z+0.25},
		minvel={x=0,y=3,z=0},
		maxvel={x=0,y=5,z=0},
		minsize=4,
		maxsize=4,
		glow=7,
		texture="default_mineral_mese.png",
	}
end



-- play sound
local mob_sound = function(self, sound)

	if sound then
		minetest.sound_play(sound, {
			object = self.object,
			max_hear_distance = self.sounds.distance
		}, true)
	end
end


-- attack player/mob
local do_attack = function(self, player)

	--[[
	if self.state == "attack" then
		return
	end
	]]

	self.attack = player
	self.state = "attack"
	self.lifespan=300

	if random(0, 100) < 90 then
		mob_sound(self, self.sounds.war_cry)
	end
end

-- set and return valid yaw
local set_yaw = function(self, yaw)

	self.object:set_yaw(yaw)
	return yaw
end

local get_yaw = function(self)

	return (self.object:get_yaw() or 0)
end

-- global function to set mob yaw
--[[
function mobs:yaw(self, yaw)
	set_yaw(self, yaw)
end
]]

local function angle_to(self, p)
	local s = self.object:get_pos()
	if p.x==s.x then return 0 end
	local yaw = (atan((p.z-s.z)/(p.x-s.x)) + pi / 2) - self.rotate
	if p.x > s.x then yaw = yaw + pi end
	return yaw
end

-- set defined animation
local set_animation = function(self, anim)
	if not self.animation or not anim then
		return
	end

	self.animation.current = self.animation.current or ""

	if anim == self.animation.current or not self.animation[anim .. "_start"] or not self.animation[anim .. "_end"] then
		return
	end

	self.animation.current = anim

	self.object:set_animation({ x = self.animation[anim .. "_start"], y = self.animation[anim .. "_end"]},
	self.animation[anim .. "_speed"] or self.animation.speed_normal or 15,
	0, self.animation[anim .. "_loop"] ~= false)
end


-- above function exported for mount.lua
function mobs:set_animation(self, anim)
	set_animation(self, anim)
end

-- move mob in facing direction
local set_velocity = function(self, v)

	local yaw = get_yaw(self)

	local vel= self.object:get_velocity()
	if not vel then return end
	-- get_velocity can return numbers that set_velocity won't accept...
	if abs(vel.y)>10000 then vel.y=0 end
	self.object:set_velocity({
		x = sin(yaw+self.rotate) * -v,
		y = (self.fly and 0) or vel.y,
		z = cos(yaw+self.rotate) * v
	})
	if v==0 then
		set_animation(self, "stand")
	end

end

local get_distance = vector.distance

-- check line of sight (BrunoMine)

local line_of_sight=function(self, pos1, pos2)
	local ray=minetest.raycast(pos1, pos2, true, false)
	local thing=ray:next()
	while thing do
		if thing.type=="object" and thing.ref~=self.object and not thing.ref:is_player() then return false end
		if thing.type=="node" then
			local node=minetest.registered_items[minetest.get_node(thing.under).name]
			if node and node.walkable then return false end
		end
		thing=ray:next()
	end
	return true
end

local can_see=function(self, entity)
	local cb=self.collisionbox 
	local p1=self.object:get_pos()
	-- p1.y=p1.y + 0.1 + (cb[5]+cb[2])*0.5
	p1.y=p1.y + cb[5]
	local p2=entity:get_pos()
	if not p2 then return false end
	cb=entity:get_properties().collisionbox
	p2.y=p2.y + cb[5]
	local ray=minetest.raycast(p1, p2, true, false)
	local thing=ray:next()
	while thing do
		if thing.type=="node" then
			local node=minetest.registered_items[minetest.get_node(thing.under).name]
			if node and node.walkable then return false end
		elseif thing.type=="object" and thing.ref~=self.object and thing.ref~=entity then
			return false
		end
		thing=ray:next()
	end
	return true
end

-- are we flying in what we are suppose to? (taikedz)
local flight_check = function(self, pos_w)

	local nod = (pos_w and minetest.get_node(pos_w).name) or self.standing_in
	local def = minetest.registered_nodes[nod]

	if not def then return false end -- nil check

	if type(self.fly_in) == "string"
		and nod == self.fly_in then

		return true

	elseif type(self.fly_in) == "table" then

		for _,fly_in in pairs(self.fly_in) do

			if nod == fly_in then

				return true
			end
		end
	end

	-- stops mobs getting stuck inside stairs and plantlike nodes
	if def.drawtype ~= "airlike"
		and def.drawtype ~= "liquid"
		and def.drawtype ~= "flowingliquid" then
		return true
	end

	return false
end


-- custom particle effects
local effect = function(pos, amount, texture, min_size, max_size, radius, gravity, glow)

	radius = radius or 3
	min_size = min_size or 0.5
	max_size = max_size or 1
	gravity = gravity or -10
	glow = glow or 0

	minetest.add_particlespawner({
		amount = amount,
		time = 1,
		minpos = pos,
		maxpos = pos,
		minvel = {x = -radius, y = -radius, z = -radius},
		maxvel = {x = radius, y = radius, z = radius},
		minacc = {x = 0, y = gravity, z = 0},
		maxacc = {x = 0, y = gravity, z = 0},
		minexptime = 0.1,
		maxexptime = 1,
		minsize = min_size,
		maxsize = max_size,
		texture = texture,
		glow = glow,
	})
end


-- update nametag colour
local update_tag = function(self)

	local col = "#00FF00"
	local qua = self.hp_max / 4

	if self.health <= floor(qua * 3) then
		col = "#FFFF00"
	end

	if self.health <= floor(qua * 2) then
		col = "#FF6600"
	end

	if self.health <= floor(qua) then
		col = "#FF0000"
	end

	self.object:set_properties({
		nametag = self.nametag,
		nametag_color = col
	})

end


-- drop items
local item_drop = function(self)

	local obj, item, num
	local pos = self.object:get_pos()

	self.drops = self.drops or {} -- nil check

	for n = 1, #self.drops do
		if random(1, self.drops[n].chance)== 1 then

			num = random(self.drops[n].min or 1, self.drops[n].max or 1)
			item = self.drops[n].name

			-- add item if it exists
			obj = minetest.add_item(pos, ItemStack(item .. " " .. num))

			if obj and obj:get_luaentity() then

				obj:set_velocity({ x = random(-10, 10) / 9, y = 6, z = random(-10, 10) / 9, })
			elseif obj then
				obj:remove() -- item does not exist
			end
		end
	end

	self.drops = {} 
end


-- check if mob is dead or only hurt
local check_for_death = function(self, cause, cmi_cause)

	-- has health actually changed?
	if self.health == self.old_health and self.health > 0 then
		return
	end

	self.old_health = self.health

	-- still got some health? play hurt sound
	if self.health > 0 then

		mob_sound(self, self.sounds.damage)

		-- make sure health isn't higher than max
		self.health=min(self.health, self.hp_max)

		-- backup nametag so we can show health stats
		if not self.nametag2 then
			self.nametag2 = self.nametag or ""
		end

		if show_health
			and (cmi_cause and cmi_cause.type == "punch") then

			self.htimer = 2
			self.nametag = "♥ " .. self.health .. " / " .. self.hp_max

			update_tag(self)
		end

		return false
	end

	-- dropped cooked item if mob died in lava
	if cause == "lava" then
		item_drop(self, true, true)
	else
		item_drop(self, nil, cmi_cause.type~="punch" or not cmi_cause.puncher:is_player())
	end

	mob_sound(self, self.sounds.death)

	local pos = self.object:get_pos()

	-- execute custom death function
	if self.on_die then

		self.on_die(self, pos)

		--self.reqRemoval=true -- self.object:remove()
		self.object:set_rotation { x=0, y=0, z=math.pi }

		return true
	end

	-- default death function and die animation (if defined)
	if self.animation
		and self.animation.die_start
		and self.animation.die_end then

		local frames = self.animation.die_end - self.animation.die_start
		local speed = self.animation.die_speed or 15
		local length = max(frames / speed, 0)

		self.attack = nil
		self.timer = 0
		self.passive = true
		self.state = "die"
		set_velocity(self, 0)
		set_animation(self, "die")

		--[[
		minetest.after(length, function(self)
			self.reqRemoval=true -- self.object:remove()
		end, self)
		]]
	else
		--self.reqRemoval=true -- self.object:remove()
		set_animation(self, "stand")
		--self.object:set_rotation { x=0, y=0, z=math.pi }
	end

	effect(pos, 20, "default_mineral_mese.png", nil, 0.5, 2, 0, 10)

	return true
end


-- check if within physical map limits (-30911 to 30927)
local within_limits = function(pos, radius)

	-- fast check
	if vector.length(pos) < 30000 then return true end

	if  (pos.x - radius) > -30913
		and (pos.x + radius) <  30928
		and (pos.y - radius) > -30913
		and (pos.y + radius) <  30928
		and (pos.z - radius) > -30913
		and (pos.z + radius) <  30928 then
		return true -- within limits
	end

	return false -- beyond limits
end

-- get node but use fallback for nil or unknown
local node_ok = function(pos)
	return minetest.get_node_or_nil(pos) or minetest.registered_nodes["air"]
end



-- is mob facing a cliff
local is_at_cliff = function(self)

	if self.fly or self.fear_height == 0 then -- 0 for no falling protection!
		return false
	end

	local pos = self.object:get_pos()
	if not pos then return end

	local yaw = get_yaw(self)
	-- we assume here that the colbox is X and Z centered (never seen a model which wasn't)
	local ypos = pos.y - (self.collisionbox[5] - self.collisionbox[2])-0.1

	local nothing, pos=minetest.line_of_sight(
	{x = pos.x,  y = ypos, z = pos.z },
	{x = pos.x, y = ypos - self.fear_height, z = pos.z}
	) 
	if nothing then
		return true
	end
	return false
end


-- calculate mob velocity
local hor_velocity = function(v)
	return (v.x * v.x + v.z * v.z) ^ 0.5
end

-- jump if facing a solid node (not fences or gates)
local do_jump = function(self, force)
	if not self.jump
		or self.jump_height == 0
		then
		return false
	end

	local v=self.object:get_velocity()
	if not v then return false end

	-- something stopping us while moving?
	--[[
	if self.state ~= "stand" and
		v.y ~= 0 and
		hor_velocity(v) > 0.5 then
		return false
	end
	--]]
	-- already jumping or falling
	if v.y ~= 0 then return false end

	local pos = self.object:get_pos()
	local yaw = get_yaw(self)

	-- what is mob standing on?
	pos.y = pos.y + self.collisionbox[2] - 0.2

	-- where is front
	local deviation=random(-0.8, 0.8)
	local rnd_yaw=yaw+deviation
	local dir_x = -sin(rnd_yaw-self.rotate) * 1.1
	local dir_z = cos(rnd_yaw-self.rotate) * 1.1

	-- what is in front of mob?
	local nod = node_ok({
		x = pos.x + dir_x,
		y = pos.y+0.5,
		z = pos.z + dir_z
	})

	--print ("in front:", nod.name, pos.y + 0.5)
	if self.walk_chance == 0
		or minetest.registered_items[nod.name].walkable or force then

		-- can we jump on it anyway?
		local up=node_ok{x=pos.x+dir_x, y=pos.y+1.2, z=pos.z+dir_z}
		if (minetest.registered_items[up.name].walkable==true and self.state~="attack" and self.state~="runaway") or
			self.jump_height<1 or
			(self.fly and self.state~="attack")  then
			if string.find(nod.name, "^stairs:") then return false end
			set_velocity(self, 0)
			self.state = "stand"
			--[[
			if deviation<0 then set_yaw(self, yaw + 0.1) 
			else set_yaw(self, yaw - 0.1) end
			]]
			set_yaw(self, rnd_yaw+pi)
			return true
		end
		if self.fly then return false end


		v.y = self.jump_height -- -0.5+math.random()

		set_animation(self, "jump") -- only when defined

		self.object:set_velocity(v)

		-- when in air move forward
		--[[
		minetest.after(0.4, function(self, v)
			--				self.object:set_velocity({
			self.object:set_acceleration({
				x = v.x * 2,--1.5,
				y = 0,
				z = v.z * 2,--1.5
			})
		end, self, v)
		--]]

		--[[
		if get_velocity(self) > 0 then
			mob_sound(self, self.sounds.jump)
		end
		]]
	end
end

-- environmental damage (water, lava, fire, light etc.)
local do_env_damage = function(self)

	-- feed/tame text timer (so mob 'full' messages dont spam chat)
	if self.htimer > 0 then
		self.htimer = self.htimer - 1
	end

	-- reset nametag after showing health stats
	if self.htimer < 1 and self.nametag2 then

		self.nametag = self.nametag2
		self.nametag2 = nil

		update_tag(self)
	end

	local pos = self.object:get_pos()

	-- remove mob if beyond map limits
	--[[
	if not within_limits(pos, 0) then
		self.reqRemoval=true -- self.object:remove()
		return
	end
	--]]


	-- don't fall when on ignore, just stand still
	if self.standing_in == "ignore" then
		self.object:set_velocity(Vero)
		return
	end

	local nodef = minetest.registered_nodes[self.standing_in]

	-- pos.y = pos.y + 1 -- for particle effect position

	local dmg=-self.regen
	if self.env_dmg[self.standing_in] then
		dmg=self.env_dmg[self.standing_in]
	elseif self.water_damage and nodef.groups.water then
		dmg=self.water_damage
	elseif self.air_damage and self.standing_in=="air" then
		dmg=self.air_damage
		-- lava or fire
	elseif self.lava_damage and (nodef.groups.lava or self.standing_in == node_fire) then
		dmg=self.lava_damage
	elseif nodef.damage_per_second ~= 0 then
		dmg=nodef.damage_per_second
	elseif self.type=="monster" and minetest.is_protected(pos, "") then
		dmg=1
	elseif self.light_damage and self.state=="attack" then
		dmg=self.light_damage
	end

	if dmg ~= 0 then
		self.health = min(self.hp_max, self.health - dmg)
		if dmg > 0 then
			if(dmg>1) then damage_number.spawn(pos, dmg) end
			check_for_death(self, "dps", {type="environment", pos=pos, node =self.standing_in })
			local yaw=get_yaw(self)
			if yaw and self.state ~= "attack" and dmg>=1 then
				set_yaw(self,angle_to(self, vector.round(pos))+pi)
				set_velocity(self, self.run_velocity)
				set_animation(self, "run")
				self.state = "runaway"
				self.runaway_timer = 2
				self.timer=0
			end
		end
	end
end




-- should mob follow what I'm holding ?
local follow_holding = function(self, clicker)

	--if mobs.invis[clicker:get_player_name()] then
	if isInvisible(clicker) then
		return false
	end

	local item = clicker:get_wielded_item()
	local t = type(self.follow)

	-- single item
	if t == "string"
		and item:get_name() == self.follow then
		return true

		-- multiple items
	elseif t == "table" then

		for no = 1, #self.follow do

			if self.follow[no] == item:get_name() then
				return true
			end
		end
	end

	return false
end


-- find and replace what mob is looking for (grass, wheat etc.)
local replace = function(self)

	local v=self.object:get_velocity()
	if not v then return end
	if not self.env_alt or v.y ~= 0 then
		return
	end

	--minetest.chat_send_all("Replace for "..self.standing_in)
	local pos=self.object:get_pos()
	local alt=self.env_alt[self.standing_in]
	if alt and random(1, alt[2])==1 and not minetest.is_protected(pos) then
		minetest.set_node(pos, {name = alt[1]})
	end
end


-- specific attacks
local specific_attack = function(list, what)

	-- no list so attack default (player, animals etc.)
	if list == nil then
		return true
	end

	-- found entity on list to attack?
	for no = 1, #list do

		if list[no] == what then
			return true
		end
	end

	return false
end


-- monster find someone to attack
local monster_attack = function(self)

	if self.type ~= "monster"
		or not damage_enabled
		or self.state == "attack" then
		return
	end

	if not self.suicidal and (self.health< 0.2*self.hp_max) then
		return
	end
	-- if self.health <= self.hp_max*0.2 then return end

	local s = self.object:get_pos()
	if not s then return end
	local p, sp, dist
	local player, obj, min_player
	local type, name = "", ""
	local min_dist = self.view_range
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		if objs[n]:is_player() then

			--if mobs.invis[ objs[n]:get_player_name() ] then
			if isInvisible(objs[n]) then

				type = ""
			else
				player = objs[n]
				type = "player"
				name = "player"
			end
		else
			obj = objs[n]:get_luaentity()

			if obj then
				player = obj.object
				type = obj.type
				name = obj.name or ""
			end
		end

		-- find specific mob to attack, failing that attack player/npc/animal
		if specific_attack(self.specific_attack, name) and
			(type == "player" or type == "npc" or (type == "animal" and self.attack_animals == true)) then

			p = player:get_pos()
			-- local colbox=self.collisionbox
			-- local sp = {x=s.x, y=s.y+(colbox[5]-colbox[2])*0.75, z=s.z} 

			dist = get_distance(p, s)

			-- aim higher to make looking up hills more realistic
			-- p.y = p.y + 1
			-- sp.y = sp.y + 1


			-- choose closest player to attack
			if dist < min_dist and can_see(self, player) then
				min_dist = dist
				min_player = player
			end
		end
	end

	-- attack player
	if min_player then
		do_attack(self, min_player)
	end
end


-- npc, find closest monster to attack
local npc_attack = function(self)

	if self.health <= self.hp_max*0.2 and not self.suicidal then return end

	local s = self.object:get_pos()
	if not s then return end
	local p, obj, min_player
	local min_dist = self.view_range + 1
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		obj = objs[n]:get_luaentity()

		if obj and obj.type == "monster" and obj~=self then
			p = obj.object:get_pos()
			local dist = get_distance(p, s)
			if dist < min_dist and can_see(self, obj.object) then
				min_dist = dist
				min_player = obj.object
			end
		end
	end

	if min_player then
		do_attack(self, min_player)
	end
end


-- specific runaway
local specific_runaway = function(list, what)

	-- no list so do not run
	if list == nil then
		return false
	end

	-- found entity on list to attack?
	for no = 1, #list do

		if list[no] == what then
			return true
		end
	end

	return false
end


-- find someone to runaway from
local runaway_from = function(self)

	local s = self.object:get_pos()
	if not s then return end
	local low_health= ((self.health <= self.hp_max*0.2) and not self.suicidal)
	if not self.runaway_from and not low_health then 
		return
	end

	if self.timer<(0.25+random()) then return end

	local p, sp, dist
	local player, obj, min_player
	local type, name = "", ""
	local min_dist = self.view_range + 1
	
	local objs = minetest.get_objects_inside_radius(s, self.view_range)

	for n = 1, #objs do

		if objs[n]:is_player() then

			--if mobs.invis[ objs[n]:get_player_name() ]
			if isInvisible(objs[n])
				or self.owner == objs[n]:get_player_name() then

				type = ""
			else
				player = objs[n]
				type = "player"
				name = "player"
			end
		end

		-- find specific mob to runaway from
		if name ~= "" and name ~= self.name
			and (low_health or specific_runaway(self.runaway_from, name)) then

			p = player:get_pos()
			dist = get_distance(p, s)

			-- choose closest player/mpb to runaway from
			-- if dist < min_dist and line_of_sight(self, sp, p, .1) == true then
			-- if dist < min_dist and can_see(self, player) then
			if dist < min_dist then
				min_dist = dist
				min_player = player
			end
		end
	end
	if not min_player then return end

	local lp = player:get_pos()
	local vec = vector.normalize {
		-- randomize the position of the threat seen by the fleeing mob.
		x = lp.x - s.x+4*random()-2, -- random offset in [-2.0,2.0]
		y = lp.y - s.y,
		z = lp.z - s.z+4*random()-2
	}

	local yaw = (atan(vec.z / vec.x) + 3 * pi / 2) - self.rotate

	if lp.x > s.x then
		yaw = yaw + pi
	end

	yaw = set_yaw(self, yaw)
	set_velocity(self, self.run_velocity)
	set_animation(self, "run")
	self.state = "runaway"
	self.runaway_timer = 5
	self.timer=0
	self.lifespan=300
end


local closest_player=function(self)
	local pos=self.object:get_pos()
	local players=minetest.get_connected_players()
	local nearest=0
	local player=nil

	for n=1, #players do
		if player then
			local d=get_distance(players[n]:get_pos(), pos)
			if d<nearest then
				player=players[n]
				nearest=d
			end
		else
			player=players[n]
			nearest=get_distance(player:get_pos(), pos)
		end
	end
	return player
end

		
local do_stand=function(self)
	set_velocity(self, 0)
	-- done by set_velocity -- set_animation(self, "stand")
	self.state = "stand"
end

-- execute current state (stand, walk, run, attacks)
local do_states = function(self)

	--local s = self.object:get_pos()

	local yaw = get_yaw(self)
	if not yaw then return end


	if self.state == "stand" then
		if self.timer<1 then return end
		self.timer=0

		set_velocity(self, 0)

		if random(1, 100) <= self.walk_chance then
			yaw=set_yaw(self, yaw+pi/3)
			if not is_at_cliff(self) then
				set_velocity(self, self.walk_velocity)
				self.state = "walk"
				set_animation(self, "walk")
			end

			-- fly up/down randomly for flying mobs
			if self.fly then
				local up=self.object:get_pos(); up.y=up.y+1
				local ud = random(-3, 3) / 9
				if ud<=0 or flight_check(self, up) then
					local v = self.object:get_velocity()
					if v then self.object:set_velocity({x = v.x, y = ud, z = v.z}) end
				end
			end
		end
	elseif self.state == "walk" then
		local stop=is_at_cliff(self)
		if not stop and self.timer<1 then return end
		self.timer=0

		set_velocity(self, self.walk_velocity)

		if (stop or random(1, 100) > self.walk_chance) and
			(self.name~="mob_whale:whale" or #self.object:get_children()==0) then
			do_stand(self)
		else
			set_animation(self, "walk")
		end
	elseif self.state == "runaway" then
		if self.timer >= self.runaway_timer then
			self.timer = 0
			do_stand(self)
			return
		end
	elseif self.state == "attack" then
		local s = self.object:get_pos()
		local p = self.attack and self.attack:get_pos()
		if not p then
			do_stand(self)
			return
		end
		local cb=self.collisionbox
		s.y=s.y+cb[5] -- (cb[5]+cb[2])*0.75
		cb=self.attack:get_properties().collisionbox
		p.y=p.y+cb[5] -- (cb[5]+cb[2])*0.75

		local dist = get_distance(p, s)

		-- stop attacking if player invisible or out of range
		if dist > self.view_range or not self.attack or self.attack:get_hp() <= 0
			or isInvisible(self.attack) or not can_see(self, self.attack) then
			self.state = "walk"
			self.attack = nil
			self.timer=0
			return
		end

		local vec = { x = p.x - s.x, y= p.y - s.y , z = p.z - s.z }
		yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
		if p.x > s.x then yaw = yaw + pi end
		yaw = set_yaw(self, yaw)

		if dist <= self.reach then
			set_velocity(self, 0)
			if self.timer > 1.5 then
				self.timer = 0
				set_animation(self, "punch")
				mob_sound(self, self.sounds.attack)
				local attached = self.attack:get_attach()
				if attached then self.attack=attached end
				self.attack:punch(self.object, 1.0, { full_punch_interval = 1, damage_groups = {fleshy = self.damage} }, nil)
			end
		elseif self.attack_type=="dogfight" or not self.fly then
			-- move towards enemy if beyond mob reach
			if is_at_cliff(self) or (p.y - s.y >=2) then
				do_jump(self, true)
			end
			if self.attack_type=="shoot" then
				set_velocity(self, self.walk_velocity)
				set_animation(self, "walk")
			else
				set_velocity(self, self.run_velocity)
				set_animation(self, "run")
			end
			if self.fly then
				-- dogfighting fliers have to adjust their altitude too.
				local p1 = s
				local me_y = floor(p1.y)
				local p2 = p
				local p_y = floor(p2.y + 1)
				local v = self.object:get_velocity()
				if flight_check(self, s) then
					if me_y < p_y then
						self.object:set_velocity({ x = v.x, y = 1 * self.run_velocity, z = v.z })
					elseif me_y > p_y then
						self.object:set_velocity({ x = v.x, y = -1 * self.run_velocity, z = v.z })
					end
				else
					self.object:set_velocity({ x = v.x, y = -1.01, z = v.z })
				end
			end
		else
			-- Flying shooters stay still when aiming.
			set_velocity(self, 0)
		end

		if self.attack_type=="shoot" and dist>self.reach and self.timer >= self.shoot_interval then
			self.timer = 0
			set_animation(self, "shoot")
			mob_sound(self, self.sounds.shoot_attack)

			local p = self.object:get_pos()
			p.y = p.y + (self.collisionbox[2] + self.collisionbox[5]) / 2

			if minetest.registered_entities[self.arrow] then
				set_animation(self, "punch")
				local obj = minetest.add_entity(p, self.arrow)
				local ent = obj:get_luaentity()
				local amount = (vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) ^ 0.5
				local v = ent.velocity or 1 -- or set to default

				ent.owner_id = (self.object) -- add unique owner id to arrow

				vec.x = (vec.x + random(-0.25, 0.25)) * (v / amount)
				vec.y = (vec.y + random(-0.5, 0.25)) * (v / amount)
				vec.z = (vec.z + random(-0.25, 0.25)) * (v / amount)
				obj:set_velocity(vec)
				end
			end
	else
		-- Just spawned or reactivated. Reset to standing state
		do_stand(self)
		self.timer=1
	end
end


-- falling and fall damage
local falling = function(self)

	if self.fly and flight_check(self) then
		self.object:set_acceleration(Vero)
		return
	end

	-- floating in water (or falling)
	local v = self.object:get_velocity()
	if not v then return end
	local p = self.object:get_pos()

		-- apply gravity when moving up
		self.object:set_acceleration({
			x = 0,
			y = -10,
			z = 0
		})

	-- in water then float up
	if minetest.registered_nodes[node_ok(p).name].groups.liquid and self.floats == 1 then

			self.object:set_acceleration({
				x = 0,
				y = 1, -- -self.fall_speed / (max(1, v.y) ^ 2),
				z = 0
			})
	end
end

-- deal damage and effects when mob punched
local mob_punch = function(self, hitter, tflp, tool_capabilities, dir)

	-- custom punch function
	if self.do_punch then

		-- when false skip going any further
		if self.do_punch(self, hitter, tflp, tool_capabilities, dir) == false then
			return
		end
	end

	-- error checking when mod profiling is enabled
	if not tool_capabilities then
		minetest.log("warning", "[mobs] Mod profiling enabled, damage not enabled")
		return
	end

	-- is mob protected?
	if self.protected and hitter:is_player()
		and minetest.is_protected(self.object:get_pos(), hitter:get_player_name()) then
		minetest.chat_send_player(hitter:get_player_name(), S("Mob has been protected!"))
		return
	end


	-- weapon wear
	local weapon = hitter:get_wielded_item()

	-- calculate mob damage
	local damage = 0
	local armor = self.object:get_armor_groups() or {}
	local tmp

	-- quick error check incase it ends up 0 (serialize.h check test)
	tflp=tflp or 0.2


	for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do

		tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)

		if tmp < 0 then
			tmp = 0.0
		elseif tmp > 1 then
			tmp = 1.0
		end

		damage = damage + (tool_capabilities.damage_groups[group] or 0)
		* tmp * ((armor[group] or 0) / 100.0)
	end

	-- healing
	if damage <= -1 then
		self.health = self.health - floor(damage)
		return
	end

	local punch_interval = tool_capabilities.full_punch_interval or 1.4
	if tflp<punch_interval then
		minetest.sound_play("mobs_swing", {object=hitter, max_hear_distance=4}, true)
		return
	end

	local uses=tool_capabilities.punch_attack_uses or 128	

	if weapon:get_definition()
		and weapon:get_definition().tool_capabilities then
		weapon:add_wear(65536/uses)
		hitter:set_wielded_item(weapon)
	end

	if damage >= 1 then
		minetest.sound_play("default_punch", { object = self.object, max_hear_distance = 5 })

		damage_number.spawn(self.object:get_pos(), floor(damage))


		-- do damage
		self.health = self.health - floor(damage)

		-- exit here if dead
		if check_for_death(self, "hit", {type = "punch", puncher = hitter}) then
			return
		end

		local props=self.object:get_properties()
		props.glow=14
		self.object:set_properties(props)
		minetest.after(0.3, function(o)
			if not o then return end
			local p=o:get_properties()
			if p then
				p.glow=1
				o:set_properties(p)
			end
		end, self.object)

		local tkb=tool_capabilities.damage_groups["knockback"]
		if tkb then
			-- now it's a snare
			set_velocity(self, 0)
			self.pause_timer =tkb/10
		end
	end

	-- if skittish then run away
	if (not self.suicidal and (self.health< 0.2*self.hp_max)) or not can_see(self, hitter) then

		local lp = hitter:get_pos()
		local s = self.object:get_pos()
		local vec = { x = lp.x - s.x, y = lp.y - s.y, z = lp.z - s.z }

		local yaw = (atan(vec.z / vec.x) + 3 * pi / 2) - self.rotate

		if lp.x > s.x then
			yaw = yaw + pi
		end

		yaw = set_yaw(self, yaw)
		set_velocity(self, self.run_velocity)
		set_animation(self, "run")
		self.state = "runaway"
		self.runaway_timer = 2
		return
	end


	local name = hitter:get_player_name()

	-- attack puncher and call other mobs for help
	if hitter:is_player() and self.passive == false and not isInvisible(name) then

		-- attack whoever punched mob
		do_stand(self)
		do_attack(self, hitter)

		-- alert others to the attack
		local objs = minetest.get_objects_inside_radius(hitter:get_pos(), self.view_range)
		local obj = nil

		for n = 1, #objs do
			obj = objs[n]:get_luaentity()
			if obj then
				-- only alert members of same mob
				if obj.group_attack == true
					and obj.state ~= "attack"
					and obj.owner ~= name
					and string.match(self.name, obj.name) then
					do_attack(obj, hitter)
				end
				-- have owned mobs attack player threat
				if obj.owner == name and obj.owner_loyal then
					do_attack(obj, self.object)
				end
			end
		end
	end
end


-- get entity staticdata
local mob_staticdata = function(self)

	-- self.attack = nil
	-- self.state = "stand"

	local tmp = {}

	for _,stat in pairs(self) do

		local t = type(stat)

		if  t ~= "function"
			and t ~= "nil"
			and t ~= "userdata"
			and _ ~= "_cmi_components" then
			tmp[_] = stat 
		end
	end
	tmp.attack=nil

	--print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
	return minetest.serialize(tmp)
end


-- activate mob and reload settings
local mob_activate = function(self, staticdata, def, dtime)

	-- load entity variables
	local tmp = minetest.deserialize(staticdata)

	if tmp then
		for _,stat in pairs(tmp) do
			self[_] = stat
		end
	end

	-- select random texture, set model and size
	if not self.base_texture then

		-- compatiblity with old simple mobs textures
		if type(def.textures[1]) == "string" then
			def.textures = {def.textures}
		end

		self.base_texture = def.textures[random(1, #def.textures)]
		self.base_mesh = def.mesh
		self.base_size = self.visual_size
		self.base_colbox = self.collisionbox
		self.base_selbox = self.selectionbox
	end

	-- for current mobs that dont have this set
	if not self.base_selbox then
		self.base_selbox = self.selectionbox or self.base_colbox
	end


	-- set texture, model and size
	local textures = self.base_texture
	local mesh = self.base_mesh
	local vis_size = self.base_size

	if self.health == 0 then
		self.health = self.hp_max*(1+random(0.2))
	end

	-- mob defaults
	self.object:set_armor_groups({immortal = 1, fleshy = 100})
	self.old_health = self.health
	self.sounds.distance = self.sounds.distance or 10
	self.textures = textures
	self.mesh = mesh
	self.collisionbox = self.base_colbox
	self.selectionbox = self.base_selbox
	self.visual_size = vis_size
	self.standing_in = ""

	-- check existing nametag
	if not self.nametag then
		self.nametag = def.nametag
	end
	
	self.state=""
	-- set anything changed above
	self.object:set_properties(self)
	set_yaw(self, (random(0, 360) - 180) / 180 * pi)
	update_tag(self)

	-- run on_spawn function if found
	if self.on_spawn and not self.on_spawn_run then
		if self.on_spawn(self, self.object:get_pos()) then
			self.on_spawn_run = true --  if true, set flag to run once only
		end
	end

	-- run after_activate
	if def.after_activate then
		def.after_activate(self, staticdata, def, dtime)
	end
end


-- main mob function
local mob_step = function(self, dtime, mr)

	local pos = self.object:get_pos()

	if self.health<=0 or not within_limits(pos, 0) then 
		self.object:remove()
		return
	end
	self.lifespan=(self.lifespan or 300)-dtime
	if self.lifespan<0 and self.type ~= "npc" and not self.driver then
		-- driver check is for whales.
		if self.type=="monster" and random(1,4)==1 and minetest.get_node(pos).name=="air" and not minetest.is_protected(pos) then
			minetest.swap_node(pos, {name="melding:node"})
		end
		self.object:remove()
		mobs.tp_fx(pos)
		return
	end

	--[[
	local t=minetest.get_gametime()
	if t >= (self.lastseen or t)+300 and self.type~="npc" and random(1,2)==1 then
		self.object:remove()
		return
	end
	self.lastseen=t
	]]



	-- knockback timer
	if self.pause_timer > 0 then
		self.pause_timer = self.pause_timer - dtime
		falling(self)
		return
	end
	
	-- general purpose timer
	self.timer = self.timer + dtime

	-- run custom function (defined in mob lua file)
	if self.do_custom and self.do_custom(self, dtime) == false then
		return
	end

	-- standing_in update
	--local pos = self.object:get_pos()
	--pos.y=pos.y + self.collisionbox[5]/2
	--pos.y=pos.y + self.collisionbox[2]+0.1
	self.standing_in = node_ok(pos).name

	-- environmental damage timer (every 1 second)
	self.env_damage_timer = self.env_damage_timer + dtime

	if self.env_damage_timer>=1 then
		-- self.health= min(self.hp_max, self.health + self.regen)
		do_env_damage(self)
		self.env_damage_timer=0
		if self.state~="attack" then replace(self) end
	end

	-- mob freezing ice hack
	if self.standing_in == "default:ice" then
		set_velocity(self, 0)
		return
	end


	runaway_from(self)
	falling(self)
	do_states(self)
	do_jump(self)
	monster_attack(self)
	if self.type=="npc" and self.attacks_monsters and self.state ~="attack" then
		npc_attack(self)
	end
end


-- default function when mobs are blown up with TNT
local do_tnt = function(obj, damage)

	--print ("----- Damage", damage)

	obj.object:punch(obj.object, 1.0, {
		full_punch_interval = 1.0,
		damage_groups = {fleshy = damage},
	}, nil)

	return false, true, {}
end


mobs.spawning_mobs = {}

-- register mob entity
function mobs:register_mob(name, def)

	mobs.spawning_mobs[name] = true

	minetest.register_entity(name, {
		-- damage_texture_modifier="^[brighten",
		glow=def.glow or 1,
		show_on_minimap=def.show_on_minimap,
		infotext=def.infotext,
		stepheight = def.stepheight or 0.8, -- was 0.6
		name = name,
		type = def.type,
		attack_type = def.attack_type,
		fly = def.fly,
		fly_in = def.fly_in or "air",
		owner = def.owner or "",
		on_die = def.on_die,
		do_custom = def.do_custom,
		jump_height = def.jump_height or 5, -- was 6
		rotate = math.rad(def.rotate or 0), --  0=front, 90=side, 180=back, 270=side2
		hp_max = max(1, (def.hp_max or 10)),
		physical = true,
		collisionbox = def.collisionbox or {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
		selectionbox = def.selectionbox or def.collisionbox,
		visual = def.visual,
		visual_size = def.visual_size or {x = 1, y = 1},
		mesh = def.mesh,
		makes_footstep_sound = def.makes_footstep_sound or false,
		view_range = def.view_range or 5,
		walk_velocity = def.walk_velocity or 1,
		run_velocity = def.run_velocity or 2,
		damage = max(0, (def.damage or 0)),
		regen= def.regen or 0.1, -- approx. health regen per sec.
		light_damage = def.light_damage,
		water_damage = def.water_damage,
		air_damage = def.air_damage,
		lava_damage = def.lava_damage,
		fall_speed = def.fall_speed or -10, -- must be lower than -2 (default: -10)
		drops = def.drops or {},
		on_rightclick = def.on_rightclick,
		arrow = def.arrow,
		shoot_interval = def.shoot_interval,
		sounds = def.sounds or {},
		animation = def.animation,
		-- follow = def.follow,
		jump = def.jump ~= false,
		walk_chance = def.walk_chance or 50,
		attacks_monsters = def.attacks_monsters or false,
		group_attack = def.group_attack or true,
		passive = def.passive or false,
		-- blood_amount = 10, -- def.blood_amount or 10,
		--blood_texture = --[[def.blood_texture or ]] "default_mineral_mese.png",
		shoot_offset = def.shoot_offset or 0,
		floats = def.floats or 1, -- floats in water by default
		env_alt=def.env_alt,
		env_dmg=def.env_dmg or {},
		env_damage_timer = 0, -- only used when state = "attack"
		timer = 0,
		tamed = false,
		pause_timer = 0,
		health = 0,
		reach = def.reach or 3,
		htimer = 0,
		--texture_list = def.textures,
		fear_height = def.fear_height or 0,
		suicidal = def.suicidal,
		runaway_timer = 0,
		--immune_to = def.immune_to or {},
		attack_animals = def.attack_animals or false,
		specific_attack = def.specific_attack,
		runaway_from = def.runaway_from,
		owner_loyal = def.owner_loyal,
		--reqRemoval= false,

		on_spawn = def.on_spawn,
		on_blast = def.on_blast or do_tnt,
		on_step = mob_step,
		do_punch = def.do_punch,
		on_punch = mob_punch,
		-- on_grown = def.on_grown,

		on_activate = function(self, staticdata, dtime)
			return mob_activate(self, staticdata, def, dtime)
		end,

		get_staticdata = function(self)
			return mob_staticdata(self)
		end,
		-- automatic_face_movement_dir=270+(def.rotate or 0),
		-- automatic_face_movement_max_rotation_per_sec=720,
	})

end -- END mobs:register_mob function


-- count how many mobs of one type are inside an area
-- Used by wands.
function mobs:count_mobs(pos, type)

	local num_type = 0
	local num_total = 0
	local objs = minetest.get_objects_inside_radius(pos, aoc_range)

	for n = 1, #objs do

		if not objs[n]:is_player() then

			local obj = objs[n]:get_luaentity()
			-- count mob type and add to total also
			if obj and obj.name and obj.name == type then
				num_type = num_type + 1
			end
		end
	end

	return num_type
end

function mobs:check_near(pos, radius, name)
	for _, ent in ipairs(minetest.get_objects_inside_radius(pos, radius)) do
		if ent:is_player() or ent:get_luaentity().name==name then
			return true
		end
	end
	return false
end


-- global functions

function mobs:spawn_specific(name, nodes, neighbors, min_light, max_light,
	interval, chance, aoc, min_height, max_height, day_toggle, on_spawn)

	-- aoc is not used anymore, because it failed to meet its goal.
	-- we now use a simpler "no other inside a radius" polivy, plus
	-- automatic despawn if a mob "older" than 5 minutes is reactivated.

	minetest.register_abm({

		label = name .. " spawning",
		nodenames = nodes,
		neighbors = neighbors,
		interval = interval,
		chance = max(1, (chance * mob_chance_multiplier)),
		catch_up = true,
		min_y=min_height,
		max_y=max_height,

		action = function(pos, node, active_object_count, active_object_count_wider)

			-- is mob actually registered?
			local ent = minetest.registered_entities[name]
			if not mobs.spawning_mobs[name]
				or not ent then
				--print ("--- mob doesn't exist", name)
				return
			end

			-- are we spawning within height limits?
			--[[
			if pos.y > max_height
				or pos.y < min_height then
				--print ("--- height limits not met", name, pos.y)
				return
			end
			]]


			-- if toggle set to nil then ignore day/night check
			if day_toggle ~= nil then

				local tod = (minetest.get_timeofday() or 0) * 24000

				if tod > 4500 and tod < 19500 then
					-- daylight, but mob wants night
					if day_toggle == false then
						--print ("--- mob needs night", name)
						return
					end
				else
					-- night time but mob wants day
					if day_toggle == true then
						--print ("--- mob needs day", name)
						return
					end
				end
			end
			-- decrease the chance for slabs and stairs
			if minetest.get_item_group(node, "slab")~=0 and random(1,2)~=1 then return end
			if minetest.get_item_group(node, "stair")~=0 and random(1,4)~=1 then return end


			-- Two free blocks required
			pos.y = pos.y + 1 
			local nn=node_ok(pos).name
			if minetest.registered_nodes[nn].walkable == true or (ent.env_dmg[nn] or 0) > 0 then return end
			pos.y=pos.y+1
			nn=node_ok(pos).name
			if minetest.registered_nodes[nn].walkable == true or (ent.env_dmg[nn] or 0) > 0 then return end
			pos.y=pos.y-1

			-- are light levels ok?
			local light = minetest.get_node_light(pos)
			if not light
				or light > max_light
				or light < min_light then
				--print ("--- light limits not met", name, light)
				return
			end

			if ent.type=="monster" and minetest.is_protected(pos) then return end
			if mobs:check_near(pos, 15, name) then return end 


			-- back to node above spawner, account for mods that don't have their origin on bottom
			pos.y=pos.y-ent.collisionbox[2]
			local mob = minetest.add_entity(pos, name)
			-- minetest.log("Spawning ".. name) 

			if on_spawn then
				local e = mob:get_luaentity() -- e is probably the same as ent above.
				on_spawn(e, pos)
			end
		end
	})
end


-- compatibility with older mob registration
function mobs:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, day_toggle)

	mobs:spawn_specific(name, nodes, {"air"}, min_light, max_light, 29,
	chance, active_object_count, -31000, max_height, day_toggle)
end


-- MarkBu's spawn function
function mobs:spawn(def)

	local name = def.name
	local nodes = def.nodes or {"group:soil", "group:stone"}
	local neighbors = def.neighbors or {"air"}
	local min_light = def.min_light or 0
	local max_light = def.max_light or 15
	local interval = def.interval or 17
	local chance = def.chance or 5000
	local active_object_count = def.active_object_count or 1
	local min_height = def.min_height or -31000
	local max_height = def.max_height or 31000
	local day_toggle = def.day_toggle
	local on_spawn = def.on_spawn

	mobs:spawn_specific(name, nodes, neighbors, min_light, max_light, interval,
	chance, active_object_count, min_height, max_height, day_toggle, on_spawn)
end


--[[
local inside=function(pos, box, pbox)
	-- box is a collision box
	-- pbox is the position of the entity
	return pos.y<=pbox.y+box[5] and pos.y>=pbox.y+box[2] and pos.x<=pbox.x+box[4] and pos.x>=pbox.x+box[1] and pos.z<=pbox.z+box[6] and pos.z>=pbox.z+box[3]
end
--]]

-- register arrow for shoot attack
function mobs:register_arrow(name, def)

	if not name or not def then return end -- errorcheck

	minetest.register_entity(name, {

		physical = def.physical or false,
		visual = def.visual,
		visual_size = def.visual_size,
		textures = def.textures,
		velocity = def.velocity,
		hit_player = def.hit_player,
		hit_node = def.hit_node,
		hit_mob = def.hit_mob,
		drop = def.drop or false, -- drops arrow as registered item when true
		collisionbox = {0, 0, 0, 0, 0, 0}, -- remove box around arrows
		ttl = def.ttl or 5,
		owner_id = def.owner_id,
		rotate = def.rotate,
		automatic_face_movement_dir = def.rotate and (def.rotate - (pi / 180)) or false,

		on_activate = def.on_activate,

		on_step = function(self, dtime)

			self.ttl = self.ttl - dtime

			local pos = self.object:get_pos()

			if self.ttl < 0 or not within_limits(pos, 0) then
				self.object:remove()
				return
			end
			--[[ unfinished. doesn't work as expected.
			if self.physical then
				if coll.collides==false then return end
				for _, thing in ipairs(coll.collisions) do
					if thing.type=="object" then
						minetest.chat_send_all("hit object")
						if thing.object:is_player() and self.hit_player and self.owner_id~=thing.object then
							self.hit_player(self, thing.object)
							self.object:remove()
							return
						elseif self.hit_mob and thing.object~=self.owner_id then
							self.hit_mob(self, thing.object)
							self.object:remove()
							return
						end
					end
					-- TODO node collision checks.
				end
			end
			]]

			-- does arrow have a tail (fireball)
			if def.tail and def.tail == 1 and def.tail_texture then
				minetest.add_particle({
					pos = pos,
					velocity = Vero,
					acceleration = Vero,
					expirationtime = def.expire or 0.25,
					collisiondetection = false,
					texture = def.tail_texture,
					size = def.tail_size or 5,
					glow = def.glow or 0,
				})
			end

			if self.hit_node then
				local node = minetest.get_node_or_nil(pos)
				if not node then
					self.object:remove();
					return
				end
				if not minetest.registered_nodes[node.name].walkable==false then
					if not minetest.is_protected(pos,"") then
						self.hit_node(self, pos, node.name)
						if self.drop == true then
							pos.y = pos.y + 1
							self.lastpos = (self.lastpos or pos)
							minetest.add_item(self.lastpos, self.object:get_luaentity().name)
						end
					end
					self.object:remove()
					return
				end
			end

			if self.hit_player or self.hit_mob then
				for _,player in pairs(minetest.get_objects_inside_radius(pos, 2)) do
					local colbox
					if player:is_player() then colbox={-0.3, 0, -0.3, 0.3, 2, 0.3}
					else colbox=player:get_properties().collisionbox
					end
					local vpos=player:get_pos()
					vpos.y=vpos.y+(colbox[5]+colbox[2])/2
					if get_distance(vpos, pos)<1 then
						if self.hit_player and player:is_player() and self.owner_id~= player then
							self.hit_player(self, player)
							self.object:remove()
							return
						end
						local entity = player:get_luaentity()
						if entity and self.hit_mob and player ~= self.owner_id and entity.name ~= self.object:get_luaentity().name and entity.physical ~= false then
							self.hit_mob(self, player)
							self.object:remove()
							return
						end
					end
				end
			end
			self.lastpos = pos
			if def.on_step then def.on_step(self,dtime) end
		end
	})
end


--[[
-- blast damage to entities nearby (modified from TNT mod)
local entity_physics = function(pos, radius)

	radius = radius * 2

	local objs = minetest.get_objects_inside_radius(pos, radius)
	local obj_pos, dist

	for n = 1, #objs do

		obj_pos = objs[n]:get_pos()

		dist = get_distance(pos, obj_pos)
		if dist < 1 then dist = 1 end

		local damage = floor((4 / dist) * radius)
		local ent = objs[n]:get_luaentity()

		-- punches work on entities AND players
		objs[n]:punch(objs[n], 1.0, {
			full_punch_interval = 1.0,
			damage_groups = {fleshy = damage},
		}, pos)
	end
end

-- no damage to nodes explosion
function mobs:safe_boom(self, pos, radius)

	minetest.sound_play(self.sounds and self.sounds.explode or "tnt_explode", {
		pos = pos,
		gain = 1.0,
		max_hear_distance = self.sounds and self.sounds.distance or 32
	})

	entity_physics(pos, radius)
	effect(pos, 32, "tnt_smoke.png", radius * 3, radius * 5, radius, 1, 0)
end
]]

-- compatibility function
function mobs:explosion(pos, radius)
	local self = {sounds = {}}
	self.sounds.explode = "tnt_explode"
	mobs:boom(self, pos, radius)
end

-- make explosion with protection and tnt mod check
function mobs:boom(self, pos, radius)

	if not minetest.is_protected(pos, "") then
		mf_tnt.boom(pos, {
			radius = radius,
			damage_radius = radius,
			sound = self.sounds and self.sounds.explode,
			explode_center = true,
		})
	end
end


-- Register spawn eggs

-- Note: This also introduces the “spawn_egg” group:
-- * spawn_egg=1: Spawn egg (generic mob, no metadata)
-- * spawn_egg=2: Spawn egg (captured/tamed mob, metadata)
function mobs:register_egg(mob, desc, background, addegg, no_creative)

	local grp = {spawn_egg = 1}

	-- do NOT add this egg to creative inventory (e.g. dungeon master)
	if creative and no_creative == true then
		grp.not_in_creative_inventory = 1
	end

	local invimg = background

	if addegg == 1 then
		invimg = "mobs_chicken_egg.png^(" .. invimg ..
		"^[mask:mobs_chicken_egg_overlay.png)"
	end

	-- register new spawn egg containing mob information
	minetest.register_craftitem(mob .. "_set", {

		description = S("@1", desc),
		inventory_image = invimg,
		groups = {spawn_egg = 2, not_in_creative_inventory = 1},
		stack_max = 1,

		on_place = function(itemstack, placer, pointed_thing)

			local pos = pointed_thing.above

			-- am I clicking on something with existing on_rightclick function?
			local under = minetest.get_node(pointed_thing.under)
			local def = minetest.registered_nodes[under.name]
			if def and def.on_rightclick then
				return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
			end

			if pos
				and within_limits(pos, 0)
				and not minetest.is_protected(pos, placer:get_player_name()) then

				if not minetest.registered_entities[mob] then
					return
				end

				pos.y = pos.y + 0.5

				local data = itemstack:get_metadata()
				local mob = minetest.add_entity(pos, mob, data)
				local ent = mob:get_luaentity()
				if not ent then return end

				ent.type="npc"
				-- set owner if not a monster
				-- if ent.type ~= "monster" then
				ent.owner = placer:get_player_name()
				ent.tamed = true
				-- end

				-- since mob is unique we remove egg once spawned
				itemstack:take_item()
			end

			return itemstack
		end,
	})


	-- register old stackable mob egg
	minetest.register_craftitem(mob, {

		description = desc,
		inventory_image = invimg,
		groups = grp,

		on_place = function(itemstack, placer, pointed_thing)

			local pos = pointed_thing.above

			-- am I clicking on something with existing on_rightclick function?
			local under = minetest.get_node(pointed_thing.under)
			local def = minetest.registered_nodes[under.name]
			if def and def.on_rightclick then
				return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
			end

			if pos
				and within_limits(pos, 0)
				and not minetest.is_protected(pos, placer:get_player_name()) then

				if not minetest.registered_entities[mob] then
					return
				end

				pos.y = pos.y + 0.5

				local mob = minetest.add_entity(pos, mob)
				local ent = mob:get_luaentity()

				ent.type="npc"
				-- don't set owner if monster or sneak pressed
				--if ent.type ~= "monster"
				--and not placer:get_player_control().sneak then
				ent.owner = placer:get_player_name()
				ent.tamed = true
				--end

				-- if not in creative then take item
				if not mobs.is_creative(placer:get_player_name()) then
					itemstack:take_item()
				end
			end

			return itemstack
		end,
	})

end


-- capture critter (thanks to blert2112 for idea)
function mobs:capture_mob(self, clicker, chance_hand, chance_net, chance_lasso, force_take, replacewith)

	if not clicker:is_player() or not clicker:get_inventory() then
		return false
	end

	-- get name of clicked mob
	local mobname = self.name

	-- if not nil change what will be added to inventory
	if replacewith then
		mobname = replacewith
	end

	local name = clicker:get_player_name()
	local tool = clicker:get_wielded_item()

	if tool:get_name() ~= ""
		and tool:get_name() ~= "mobs:net"
		and tool:get_name() ~= "mobs:lasso" then
		return false
	end

	-- is mob tamed?
	if self.tamed == false and force_take == false then
		minetest.chat_send_player(name, S("Not tamed!"))
		return true -- false
	end

	-- cannot pick up if not owner
	if self.owner~="" and self.owner ~= name then
		minetest.chat_send_player(name, S("@1 is owner!", self.owner))
		return true -- false
	end

	if clicker:get_inventory():room_for_item("main", mobname) then

		-- was mob clicked with hand or net?
		local chance = 0

		if tool:get_name() == "" then
			chance = chance_hand
		elseif tool:get_name() == "mobs:net" then
			chance = chance_net
			-- tool:add_wear(65536/32) -- Wear is applied by the net's on_place/on_secondary_use
			clicker:set_wielded_item(tool)

		end

		-- Minefall: We make it more difficult to catch mobs through different means like
		-- a shorter reach for the net or mobs that can juke the player, so we don't need
		-- a random factor anymore. We have to keep, though, the distinction between net and hand

		if chance > 0 then

			-- default mob egg
			local new_stack = ItemStack(mobname)

			-- add special mob egg with all mob information
			-- unless 'replacewith' contains new item to use
			if not replacewith then

				new_stack = ItemStack(mobname .. "_set")

				local tmp = {}

				for _,stat in pairs(self) do
					local t = type(stat)
					if  t ~= "function"
						and t ~= "nil"
						and t ~= "userdata" then
						tmp[_] = self[_]
					end
				end

				local data_str = minetest.serialize(tmp)

				new_stack:set_metadata(data_str)
			end

			local inv = clicker:get_inventory()

			if inv:room_for_item("main", new_stack) then
				inv:add_item("main", new_stack)
			else
				minetest.add_item(clicker:get_pos(), new_stack)
			end


			mob_sound(self, "default_place_node_hard")
			self.object:remove()
		end
	end

	return true
end


-- protect tamed mob with rune item
function mobs:protect(self, clicker)

	local name = clicker:get_player_name()
	local tool = clicker:get_wielded_item()

	if tool:get_name() ~= "mobs:protector" then
		return false
	end

	if self.tamed == false then
		minetest.chat_send_player(name, S("Not tamed!"))
		return true -- false
	end

	if self.protected == true then
		minetest.chat_send_player(name, S("Already protected!"))
		return true -- false
	end

	if not mobs.is_creative(clicker:get_player_name()) then
		tool:take_item() -- take 1 protection rune
		clicker:set_wielded_item(tool)
	end

	self.protected = true

	local pos = self.object:get_pos()
	pos.y = pos.y + self.collisionbox[2] + 0.5

	effect(self.object:get_pos(), 25, "mobs_protect_particle.png", 0.5, 4, 2, 15)

	mob_sound(self, "mobs_spell")

	return true
end


local mob_obj = {}
local mob_sta = {}

-- feeding, taming and breeding (thanks blert2112)
function mobs:feed_tame(self, clicker, feed_count, breed, tame)

	if not self.follow then
		return false
	end

	-- can eat/tame with item in hand
	if follow_holding(self, clicker) then

		-- if not in creative then take item
		if not mobs.is_creative(clicker:get_player_name()) then

			local item = clicker:get_wielded_item()

			item:take_item()

			clicker:set_wielded_item(item)
		end

		-- increase health
		self.health = self.health + 4

		if self.health > self.hp_max then
			self.health = self.hp_max
			if self.htimer < 1 then
				minetest.chat_send_player(clicker:get_player_name(),
				S("@1 at full health (@2)",
				self.name:split(":")[2], tostring(self.health)))
				self.htimer = 5
			end
		end

		self.object:set_hp(self.health)

		update_tag(self)

		-- feed and tame
		self.food = (self.food or 0) + 1
		if self.food >= feed_count then
			self.food = 0
			if tame then

				if self.tamed == false then
					minetest.chat_send_player(clicker:get_player_name(),
					S("@1 has been tamed!",
					self.name:split(":")[2]))
				end

				self.tamed = true

				if not self.owner or self.owner == "" then
					self.owner = clicker:get_player_name()
				end
			end

			-- make sound when fed so many times
			mob_sound(self, self.sounds.random)
		end

		return true
	end

	local item = clicker:get_wielded_item()

	-- if mob has been tamed you can name it with a nametag
	if item:get_name() == "mobs:nametag"
		and clicker:get_player_name() == self.owner then

		local name = clicker:get_player_name()

		-- store mob and nametag stack in external variables
		mob_obj[name] = self
		mob_sta[name] = item

		local tag = self.nametag or ""

		minetest.show_formspec(name, "mobs_nametag", "size[8,4]"
		.. default.gui_bg
		.. default.gui_bg_img
		.. "field[0.5,1;7.5,0;name;" .. minetest.formspec_escape(S("Enter name:")) .. ";" .. tag .. "]"
		.. "button_exit[2.5,3.5;3,1;mob_rename;" .. minetest.formspec_escape(S("Rename")) .. "]")
	end

	return false
end


-- inspired by blockmen's nametag mod
minetest.register_on_player_receive_fields(function(player, formname, fields)

	-- right-clicked with nametag and name entered?
	if formname == "mobs_nametag"
		and fields.name
		and fields.name ~= "" then

		local name = player:get_player_name()

		if not mob_obj[name]
			or not mob_obj[name].object then
			return
		end

		-- make sure nametag is being used to name mob
		local item = player:get_wielded_item()

		if item:get_name() ~= "mobs:nametag" then
			return
		end

		-- limit name entered to 64 characters long
		if string.len(fields.name) > 64 then
			fields.name = string.sub(fields.name, 1, 64)
		end

		-- update nametag
		mob_obj[name].nametag = fields.name

		update_tag(mob_obj[name])

		-- if not in creative then take item
		if not mobs.is_creative(name) then

			mob_sta[name]:take_item()

			player:set_wielded_item(mob_sta[name])
		end

		-- reset external variables
		mob_obj[name] = nil
		mob_sta[name] = nil
	end
end)


-- compatibility function for old entities to new modpack entities
function mobs:alias_mob(old_name, new_name)

	-- spawn egg
	minetest.register_alias(old_name, new_name)

	-- entity
	minetest.register_entity(":" .. old_name, {

		physical = false,

		on_step = function(self)

			local pos = self.object:get_pos()

			if minetest.registered_entities[new_name] then
				minetest.add_entity(pos, new_name)
			end

			self.object:remove()
		end
	})
end

function mobs.attack_monster(s) npc_attack(s:get_luaentity()) end

