require "prefabutil"
require "brains/mushasmallbrain"
local brain = require "brains/mushasmallbrain"
require "stategraphs/SGmusha_small"

local WAKE_TO_FOLLOW_DISTANCE = 5
local SLEEP_NEAR_LEADER_DISTANCE = 2
local CRY_NEAR_LEADER_DISTANCE = 15

local assets =
{
	Asset("ANIM", "anim/musha_small.zip"),
    Asset("ANIM", "anim/hat_xiang.zip"),
	--Asset("ANIM", "anim/hat_yamche_on.zip"),
	Asset("SOUND", "sound/tallbird.fsb"),
	
	Asset("IMAGE", "images/inventoryimages/hat_xiang.tex"),
}

local prefabs=
{
    "musha_small",
}


local slotpos_6 = {}

for y = 3, 0, -1 do
    for x = 0, 3 do
        table.insert(slotpos_6, Vector3(60*x-60*2+30, 60*y-60*2+30,0))
    end
end

local slotpos_5 = {}

for y = 3, 0, -1 do
    for x = 0, 2 do
        table.insert(slotpos_5, Vector3(75*x-75*2+75, 60*y-60*2+32,0))
    end
end

local slotpos_4 = {}

for y = 2, 0, -1 do
    for x = 0, 2 do
        table.insert(slotpos_4, Vector3(80*x-80*2+80, 80*y-80*2+80,0))
    end
end

local slotpos_3 = {}

for y = 2, 0, -1 do
    for x = 0, 1 do
        table.insert(slotpos_3, Vector3(80*x-80*2+78, 80*y-80*2+80,0))
    end
end

local slotpos_2 = {}

for y = 1, 0, -1 do
    for x = 0, 1 do
        table.insert(slotpos_2, Vector3(80*x-80*2+78, 80*y-80*2+80,0))
    end
end

local slotpos_1 = {}

for y = 1, 0, -1 do
        table.insert(slotpos_1, Vector3(74*y-74*2+70, 0))

end


local function ondeath(inst)
if inst:HasTag("aquatic") then
inst:RemoveTag("aquatic")
end
	if inst.components.container then
	inst.components.container:DropEverything() end
	--if inst.components.inventory and not inst.DLC2 then
	--inst.components.inventory:DropEverything() end
	
local dark2 = SpawnPrefab("statue_transition_2")
local pos = Vector3(inst.Transform:GetWorldPosition())
 if inst.ndead and not inst.ndeath then
 inst:Remove()
 end
 if inst.ndeath and inst:HasTag("level1") then
local poo = SpawnPrefab("musha_egg")
 inst:Remove()
poo.Transform:SetPosition(inst.Transform:GetWorldPosition()) --poo.Transform:SetScale(0.5, 0.5, 0.5)			
end
--if not inst:HasTag("level1") then
 dark2.Transform:SetPosition(pos:Get())
--end
end

----------------
local function die(inst)
if inst:HasTag("aquatic") then
inst:RemoveTag("aquatic")
end
if inst.components.inventory and not inst.components.poisonable then
local player = GetPlayer()
	if inst.pick1 then	
	player.working = false
	inst.drop = true
	inst.pick1 = false 
	inst.working_food = false
end
inst.components.inventory:DropEverything()
	end
		
--	if inst.components.container then
--	inst.components.container:DropEverything() end
	
inst.ndead = true
inst.ndeath = false
inst.components.health:DoDelta(-100000)
inst.fightn = false
--inst.components.health:Kill()
    --inst:Remove()
end
------------------
local function DropItem(inst, target, item)
	--inst.components.inventory:Unequip(EQUIPSLOTS.HANDS, true)
	inst.components.inventory:DropItem(item)
	if item.Physics then

		local x, y, z = item:GetPosition():Get()
		y = .3
		item.Physics:Teleport(x,y,z)

		local hp = target:GetPosition()
		local pt = inst:GetPosition()
		local vel = (hp - pt):GetNormalized()
		local speed = 3 + (math.random() * 2)
		local angle = -math.atan2(vel.z, vel.x) + (math.random() * 20 - 10) * DEGREES
		item.Physics:SetVel(math.cos(angle) * speed, 10, math.sin(angle) * speed)
		inst.components.talker:Say(GetString(inst.prefab, "宣布工具slip"))
	end
end

local function makeused2(inst)
	inst.AnimState:PlayAnimation("debris")
end

local function doresurrect2(inst, dude)
--inst.components.talker:Say("[Sacrifice]\nResurrection(ON)")
    dude.entity:AddLight()
	dude.Light:SetRadius(3)
    dude.Light:SetFalloff(10)
    dude.Light:SetIntensity(.5)
    dude.Light:SetColour(15/255,165/255,165/255)
	dude.Light:Enable(true)

	inst:AddTag("busy")	
	inst.persists = false
    -- if inst.Physics then
	--	RemovePhysicsColliders(inst)
    --end
    --dude:Hide()
    --if dude.HUD then
        --dude.HUD:Hide()
    --end
    if dude.components.playercontroller then
        dude.components.playercontroller:Enable(false)
    end

    inst:RemoveComponent("inspectable")
    dude:ClearBufferedAction()
------
    scheduler:ExecuteInTime(2, function()
        dude:Show()

inst.AnimState:PlayAnimation("debris")
-------
        dude.sg:GoToState("amulet_rebirth")
	    --dude.sg:GoToState("rebirth")	
        dude:DoTaskInTime(4, function() 

            --if dude.HUD then
                --dude.HUD:Show()
            --end

            if dude.components.health then
				dude.components.health:RecalculatePenalty()
                dude.components.health:Respawn(100)
                dude.components.health:SetInvincible(true)
            end
          if dude.components.sanity then
			    dude.components.sanity:SetPercent(.9)
            end
          if dude.components.hunger then
                dude.components.hunger:SetPercent(.9)
            end
        if dude.components.playercontroller then
                dude.components.playercontroller:Enable(true)
            end
		if dude:HasTag("DLC2") then
		if dude.components.poisonable then
			dude.components.poisonable:Cure(inst) end
			end	
            inst:RemoveTag("busy")
            dude.components.health:SetInvincible(false)
	dude.Light:Enable(false)

 end)
	inst:Show()

 end)

--	if inst.components.inventory then
--	inst.components.inventory:DropEverything()
-- 	end
	if inst.components.container then
	inst.components.container:DropEverything() 
	end
	inst.ndeath = true
	inst.ndead = false

		inst.sg:GoToState("command")
	inst.components.talker:Say("[I love Toso]")
	scheduler:ExecuteInTime(2.5, function() inst.components.talker:Say("[See you again ..]") 
	inst.components.locomotor.walkspeed = 0
	scheduler:ExecuteInTime(3, function() inst.resurrect_yamche = true end) end)

SaveGameIndex:DeregisterResurrector(inst)
inst.resurrect_finish = true

--inst.components.health:DoDelta(-100000) 
--ondeath(inst)
   -- inst:Remove()
            end
----------------
local function level_inventory(inst,data)
if inst.components.inventory then
if inst:HasTag("level1") then
inst.components.inventory.maxslots = 3
end
end
end

local function stop_working(inst)
local player = GetPlayer()

if inst.growup_auto then
player.working = false
inst.pick1 = false
inst.working_food = false
inst.drop = true
inst.yamche = true

inst.stop_working = true
inst.components.health:SetInvincible(true)
--inst.components.growable:StartGrowing()
end

if inst.grow_up_yamchae then
if inst.components.container then
inst.components.container:Close()
inst.components.container.canbeopened = false
inst.components.container:DropEverything()
inst:RemoveComponent("container")
end
if inst.components.inventory then
inst.components.inventory:DropEverything(true)
inst:RemoveComponent("inventory")
end

--inst.components.growable:StartGrowing()
inst.grow_up_yamchae = false
end

end
---------------------------
--升级
--[[
local function levelexp(inst,data)

	local max_exp = 999999999999999993000
	local exp = math.min(inst.level, max_exp)
	--local hunger_percent = inst.components.hunger:GetPercent()
	local health_percent = inst.components.health:GetPercent()

--inst.components.talker:Say("[EXP]\n".. (inst.level))

if inst:HasTag("level8") then
	--inst.components.hunger.max = math.ceil (130 + exp* 1)
	inst.components.health.maxhealth = math.ceil (800 + exp* 1)
	inst.components.talker:Say("[Max Health]\n".. (inst.level + 800))
	--inst:AddTag("cure1")
end

	if not inst:HasTag("level8") then
inst.components.talker:Say("NEXT:[Grow up]")

if inst.level >=0 and inst.level <9 and inst:HasTag("level1") and not inst:HasTag("baby") then
inst.components.talker:Say("Level 1\n[EXP]: ".. (inst.level).."/10")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
elseif inst.level >9 and inst:HasTag("level1") and not inst:HasTag("baby") then
			if inst.grow_up_yamchae then stop_working(inst) end
			if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <19 and inst:HasTag("level2") then
inst.components.talker:Say("Level 2\n[EXP]: ".. (inst.level).."/20")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
	elseif inst.level >19 and inst:HasTag("level2") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <49 and inst:HasTag("level3") then
inst.components.talker:Say("Level 3\n[EXP]: ".. (inst.level).."/50")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
	elseif inst.level >49 and inst:HasTag("level3") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <99 and inst:HasTag("level4") then
inst.components.talker:Say("Level 4\n[EXP]: ".. (inst.level).."/100")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
	elseif inst.level >99 and inst:HasTag("level4") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <299 and inst:HasTag("level5") then
inst.components.talker:Say("Level 5\n[EXP]: ".. (inst.level).."/300")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
elseif inst.level >299 and inst:HasTag("level5") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <399 and inst:HasTag("level6") then
inst.components.talker:Say("Level 6\n[EXP]: ".. (inst.level).."/400")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
elseif inst.level >399 and inst:HasTag("level6") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")
elseif inst.level >=0 and inst.level <499 and inst:HasTag("level7") then
inst.components.talker:Say("Level 7\n[EXP]: ".. (inst.level).."/500")
if inst.grow_up_yamchae then
inst.sg:GoToState("command")
inst.grow_up_yamchae = false
end
elseif inst.level >499 and inst:HasTag("level7") then
    		 if inst.grow_up_yamchae then stop_working(inst) end
			 if inst.growup_auto then stop_working(inst) end
	inst.components.talker:Say("[Grow up]\n(U key)")

	end
	--inst.components.hunger:SetPercent(hunger_percent)
	inst.components.health:SetPercent(health_percent)
	end
end


local function growup_check(inst,data)	
inst.grow_up_yamchae_ready = false
levelexp(inst)
end
]]
local smallllchance = 0.45
local normalchance = 0.75
local largechance = 1

local function onkilll(inst, data)
	local victim = data.victim
	    if not (victim:HasTag("prey") or
            victim:HasTag("veggie") or
            victim:HasTag("eyeplant") or
            victim:HasTag("insect") or			
            victim:HasTag("structure")) then
        end
end
--[[
local exp1x = 0.1
local exp2x = 0.12
local exp3x = 0.16
local exp4x = 0.2
local normalchance = .75
local largechance = 1
local smallllchance = 0.4
local smalllllchance = 0.2
local function onkilll(inst, data)
 --if not inst.no_growup then
 
	if data.cause == inst.prefab and not data.inst:HasTag("companion") then
	if math.random() < largechance and not data.inst:HasTag("prey") and not data.inst:HasTag("eyeplant") and not data.inst:HasTag("giant1x") and not data.inst:HasTag("giant2x") and not data.inst:HasTag("giant3x") and not data.inst:HasTag("giant4x") and not data.inst:HasTag("small_giant2x") and not data.inst:HasTag("small_giant3x") and not data.inst:HasTag("small_giant4x") then

    				inst.level = inst.level + 1
	levelexp(inst)

	elseif math.random() < smallllchance and data.inst:HasTag("eyeplant") then
    				inst.level = inst.level + 1
	levelexp(inst)

	elseif math.random() < smalllllchance and data.inst:HasTag("arm") then
    				inst.level = inst.level + 1
	levelexp(inst)

------extra
	elseif math.random() < exp1x and data.inst:HasTag("spider1x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp1x and data.inst:HasTag("hound1x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())

	elseif math.random() < exp2x and data.inst:HasTag("spider2x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp3x and data.inst:HasTag("spider3x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp4x and data.inst:HasTag("spider4x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp2x and data.inst:HasTag("hound2x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp3x and data.inst:HasTag("hound3x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	elseif math.random() < exp4x and data.inst:HasTag("hound4x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())

	elseif data.inst:HasTag("giant1x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
	local fx3 = SpawnPrefab("glowdust")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 10
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+10) \n".. (inst.level))

	elseif data.inst:HasTag("giant2x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
	local fx3 = SpawnPrefab("glowdust")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 20
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+20) \n".. (inst.level))

	elseif data.inst:HasTag("giant3x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	local fx3 = SpawnPrefab("glowdust")
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 30
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+30) \n".. (inst.level))

	elseif data.inst:HasTag("giant4x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	local fx3 = SpawnPrefab("glowdust")
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 40
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+40) \n".. (inst.level))

	elseif data.inst:HasTag("small_giant2x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	local fx3 = SpawnPrefab("glowdust")
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 5
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+4) \n".. (inst.level))

	elseif data.inst:HasTag("small_giant3x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	local fx3 = SpawnPrefab("glowdust")
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 8
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+8) \n".. (inst.level))
	elseif data.inst:HasTag("small_giant4x") then
	local fx = SpawnPrefab("statue_transition")
	local fx2 = SpawnPrefab("exp")
        		fx.Transform:SetPosition(data.inst:GetPosition():Get())
        		fx2.Transform:SetPosition(data.inst:GetPosition():Get())
	local fx3 = SpawnPrefab("glowdust")
        		fx3.Transform:SetPosition(data.inst:GetPosition():Get())
    				inst.level = inst.level + 12
	--levelexp(inst)
	inst.components.talker:Say("extra [EXP](+12) \n".. (inst.level))

    			end
		    end
		end
]]			

local function resurrect_end(inst, data)
SaveGameIndex:DeregisterResurrector(inst)
        inst.components.resurrector.active = false
         inst:RemoveComponent("resurrector")
end
local function onpreload(inst, data)
	if data then
		if data.stay then
		inst.stay = data.stay
		end
--		if data.level then
--		inst.level = data.level
--			levelexp(inst)
--		end
		if data.yamche_leader then
		inst.yamche_leader = data.yamche_leader
		end
	if data and data.resurrect_end then
	resurrect_end(inst)
	end
end
end

local function onsave(inst, data)
	data.stay = inst.stay
	--data.level = inst.level
	data.yamche_leader = inst.yamche_leader
		if inst.resurrect_finish then
        data.resurrect_end = true
    end
end

------------

local function GetStatus(inst)
    --print("smallbird - GetStatus")
    if inst.components.hunger then
        if inst.components.hunger:IsStarving(inst) then
            --print("STARVING")
            return "我饿了"
        elseif inst.components.hunger:GetPercent() < .5 then
            --print("HUNGRY")
            return "饿死了"
        end
	end
end


--------------
------------

local function tryproc(inst)
if not inst.active and inst.components.health:GetPercent() < .7  then
        --heal_proc(inst)
		   end
if not inst.shield_on and inst.components.health:GetPercent() < .2  then
            cure1_proc(inst)
elseif inst.shield_on and inst.components.health:GetPercent() < .2  and inst.components.health:GetPercent() > .1 then
 inst.components.talker:Say("[Health:below(20%)]")			
elseif inst.shield_on and inst.components.health:GetPercent() <= .1 then 
  inst.components.talker:Say("[Health:below(10%)]")			
    end end

	
	------baby----hat-----

local function OnDropped(inst,data)
inst.equip_baby = false
inst.inventory_baby = false
local player = GetPlayer()
  -- inst:AddTag("level1")
   inst:RemoveTag("baby")
   inst:RemoveTag("hat")
   inst.hat = false
 inst.fightn = false
inst.peace = false
inst.active_hunt = false
inst.defense = false

local player = GetPlayer()
local pos = Vector3(GetPlayer().Transform:GetWorldPosition())
inst.Transform:SetPosition(pos:Get())
inst.sg:GoToState("walk")
inst.components.follower:SetLeader(player)

if not GetClock():IsNight() then
	inst.Light:Enable(false)	
end

end

local function OnPutInInventory(inst)

inst.inventory_baby = true

    --inst.components.growable:StopGrowing()
	inst.hat = true
    inst:AddTag("baby")
    --inst:RemoveTag("level1")
    inst:RemoveTag("hat")
	--inst:StopBrain()
	inst.fightn = false
inst.peace = false
inst.active_hunt = false
inst.defense = false

--inst.components.staycommand:SetStaying(true)
inst.components.follower:SetLeader(nil)

--if inst.components.burnable and inst.components.burnable:IsBurning() then
--	inst.components.burnable:Extinguish() 
--	end
end

local function onyamche(inst, owner)
inst.equip_baby = true
inst.inventory_baby = false
--inst.components.staycommand:SetStaying(true)
inst.components.follower:SetLeader(nil)

--if inst.components.burnable and inst.components.burnable:IsBurning() then
--	inst.components.burnable:Extinguish() 
--	end
	
local player = GetPlayer()
	inst.fightn = false
	inst.peace = false
	inst.hat = true
	player.working = false
	inst.pick1 = false
	inst.working_food = false
	inst.drop = true
	
--if not inst.DLC2 then
if inst.components.inventory then 
--SpawnPrefab("small_puff").Transform:SetPosition(inst:GetPosition():Get())
inst.components.inventory:DropEverything(true)
	inst.item_max_full = false
	inst.item_1 = false 
	--inst:RemoveComponent("inventory") 
	--inst:DoTaskInTime( 0, function() inst:AddComponent("inventory") level_inventory(inst) end)

	end

	
--yamche hat	
    --inst.components.growable:StopGrowing()
	--inst:StopBrain()
  
    --inst:RemoveTag("level1")
    inst:AddTag("baby")
    inst:AddTag("hat")
	inst.drop = true
	inst.pick1 = false
	inst.working_food = false
	inst.peace = true
	inst.active_hunt = false
	inst.defense = true

    owner.AnimState:OverrideSymbol("swap_hat", "hat_xiang", "swap_hat")
     owner.AnimState:Show("HAT")
     -- owner.AnimState:Show("HAT_HAIR")
     owner.AnimState:Hide("HAIR_NOHAT")
     owner.AnimState:Show("HAIR")

    end

    local function offyamche(inst, owner)
	inst.equip_baby = false
	--inst.Light:Enable(false)
	
        owner.AnimState:Hide("HAT")
        owner.AnimState:Hide("HAT_HAIR")
        owner.AnimState:Show("HAIR_NOHAT")
        owner.AnimState:Show("HAIR")

    end
	
------------------ adult hat  

	
local function Dropped_cave(inst,data)
inst.house = false
inst.inventory_baby = false
if inst.components.inventoryitem then
inst:RemoveComponent("inventoryitem")
end
if inst.components.container and not inst.stop_working then
inst.components.container.canbeopened = true	
end
if GetClock():IsNight() then
	inst.Light:Enable(true)
	end
inst.picked = false
inst.icon = false

local pos = Vector3(GetPlayer().Transform:GetWorldPosition())
inst.Transform:SetPosition(pos:Get())
inst.sg:GoToState("walk")
inst.stay = false

if not inst.components.staycommand then
inst:AddComponent("staycommand") end
inst.components.staycommand:SetStaying(false)
--inst.components.staycommand:RememberStayPos("stayspot", Point(inst.Transform:GetWorldPosition()))
local player = GetPlayer()
inst.components.follower:SetLeader(player)
if player.components.leader:CountFollowers("yamche") == 1 then
inst.yamche_leader = true end

end

local function OnPutInInventory_cave(inst,data)

inst.house = true
inst.components.follower:SetLeader(nil)
if not inst.warning_monkey then
inst:RemoveTag("aquatic")
end
if inst.components.container then
inst.components.container:Close()
inst.components.container.canbeopened = false	
end
--if inst.components.container and not inst.picked then
--inst.components.container:Close()
--inst.components.container:DropEverything() 
--inst.components.container.canbeopened = false
--end
if inst.components.inventory then
	if inst.pick1 then	
	inst.pick1 = false
	inst.drop = true
	inst.working_food = false
	inst.components.inventory:DropEverything(true)
	inst.check_inv = false
	inst.item_max_full = false
	inst.item_1 = false 
	--[[if inst:HasTag("DLC2") then	
	inst.DLC2_reset = true	
	inst:RemoveComponent("inventory")
	inst:DoTaskInTime( 0, function() inst:AddComponent("inventory") level_inventory(inst) end)
	end]]
	end
end
inst.Light:Enable(false)
inst.picked = true	
end

local function onyamche_house(inst, owner)
	
if owner:HasTag("monkey") then
if owner.components.inventory then
owner.components.inventory:DropEverything(false, true)
			end
--owner.components.health:Kill()
end

if inst.components.inventory then
	inst.pick1 = false
	inst.drop = true
	inst.working_food = false
	inst.components.inventory:DropEverything(true)
	inst.check_inv = false
	inst.item_max_full = false
	inst.item_1 = false 
	--[[if inst:HasTag("DLC2") then	
	inst.DLC2_reset = true	
	inst:RemoveComponent("inventory")
	inst:DoTaskInTime( 0, function() inst:AddComponent("inventory") level_inventory(inst) end)
	end]]
end
if inst.components.container and not inst.stop_working then
inst.components.container.canbeopened = true	
end
	inst.house = true
	inst.components.follower:SetLeader(nil)

        owner.AnimState:OverrideSymbol("swap_hat", "hat_xiang", "swap_hat")
        owner.AnimState:Show("HAT")
       -- owner.AnimState:Show("HAT_HAIR")
        owner.AnimState:Hide("HAIR_NOHAT")
        owner.AnimState:Show("HAIR")
	     
	end

local function offyamche_house(inst, owner)
	--inst.house = false
        owner.AnimState:Hide("HAT")
        --owner.AnimState:Hide("HAT_HAIR")
        owner.AnimState:Show("HAIR_NOHAT")
        owner.AnimState:Show("HAIR")
end
	 
local function cave_near(inst, data)
--local leader = inst.components.follower.leader
if not inst:HasTag("level1") and not inst:HasTag("baby") and not inst.warning_eyeplant and not inst.warning_monkey then

if inst.components.inventoryitem and inst.components.equippable and not inst.icon and not inst.pick_me_up then
inst.icon = true
local inv_name = inst.prefab
	--inst.components.inventoryitem.atlasname = "images/inventoryimages/"..inv_name..".xml"
	inst.components.inventoryitem.atlasname = "images/inventoryimages/hat_xiang.xml"
 	
elseif inst.stay and not inst.components.inventoryitem and not inst.picked and not inst.warning_monkey then
if not inst.pick_me_up then
--inst.components.talker:Say("[ Pick me up ]") 
--inst.sg:GoToState("command") 
inst.pick_me_up = true
end
inst:AddComponent("inventoryitem")
--inst.components.inventoryitem.cangoincontainer = false
local inv_name = inst.prefab
	--inst.components.inventoryitem.atlasname = "images/inventoryimages/"..inv_name..".xml"
	inst.components.inventoryitem.atlasname = "images/inventoryimages/hat_xiang.xml"
	inst.components.inventoryitem:SetOnDroppedFn(Dropped_cave)
	inst.components.inventoryitem:SetOnPutInInventoryFn(OnPutInInventory_cave)
	if not inst.components.equippable then
	inst:AddComponent("equippable")
	inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
	inst.components.equippable:SetOnEquip(onyamche_house)
    inst.components.equippable:SetOnUnequip(offyamche_house)
	end
elseif not inst.stay and inst.components.inventoryitem and not inst.picked then
inst:RemoveComponent("inventoryitem")
inst:RemoveComponent("equippable")
inst.pick_me_up = false
	end
end

	-----------------------------equip--hat
if inst:HasTag("level1") and not inst.warning_eyeplant and not inst.warning_monkey then
	if not inst.components.inventoryitem then
    inst:AddComponent("inventoryitem")
	inst.components.inventoryitem.atlasname = "images/inventoryimages/hat_xiang.xml"
    inst.components.inventoryitem:SetOnDroppedFn(OnDropped)
    inst.components.inventoryitem:SetOnPutInInventoryFn(OnPutInInventory)
	end
	if not inst.components.equippable then
	inst:AddComponent("equippable")
    inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
	inst.components.equippable:SetOnEquip(onyamche)
    inst.components.equippable:SetOnUnequip(offyamche)
		if not inst.DLC2 then
		inst.components.equippable.walkspeedmult = 1.25
		elseif inst.DLC2 then
		inst.components.equippable.walkspeedmult = 0.25
		end
	end
	if not inst.components.insulator then
    inst.components.insulator.insulation = TUNING.INSULATION_MED
	end
end	
-----------------------------
end
-----------------------------


-------------









local function Peace(inst)

if not inst.hat and not inst.house then

local x,y,z = inst.Transform:GetWorldPosition()
local frog = TheSim:FindEntities(x,y,z, 3, {"frog"})
for k,v in pairs(frog) do
local random = 0.1
if not inst.warning_frog then
inst.warning_frog = true
if inst.components.container then 
inst.components.container.canbeopened = false
end
if math.random() < random and inst.stay then
inst.components.talker:Say("[ Don't touch me !]")
elseif math.random() < random and not inst.stay then
inst.components.talker:Say("[ Thief !]")
end 
end
anti_thief(inst)
end

--if not inst:HasTag("level1") then
local x,y,z = inst.Transform:GetWorldPosition()
local monkey = TheSim:FindEntities(x,y,z, 3, {"monkey"})
for k,v in pairs(monkey) do

if v and not inst:HasTag("aquatic") then
inst:AddTag("aquatic")
end 
	
local random = 0.1
if not inst.warning_monkey then
inst.warning_monkey = true
if inst:HasTag("level1") and inst.components.inventoryitem then
	inst:RemoveComponent("inventoryitem")
elseif not inst:HasTag("level1") and inst.stay and inst.components.inventoryitem then
	inst:RemoveComponent("inventoryitem")
end
--inst.sg:GoToState("command")
if inst.components.container then 
inst.components.container.canbeopened = false
end
if inst.stay then
inst.components.talker:Say("[ Don't touch me !]")
elseif not inst.stay then
inst.components.talker:Say("[ Monkey !]")
end 
end
anti_thief(inst)
end

local x,y,z = inst.Transform:GetWorldPosition()
local ents = TheSim:FindEntities(x,y,z,6, {"eyeplant"})
for k,v in pairs(ents) do
if v and not inst.warning_eyeplant then
inst.warning_eyeplant = true
if inst:HasTag("level1") and inst.components.inventoryitem then
	inst:RemoveComponent("inventoryitem")
elseif not inst:HasTag("level1") and inst.stay and inst.components.inventoryitem then
	inst:RemoveComponent("inventoryitem")
end
if inst.stay then
inst.components.talker:Say("[ Danger !]")
elseif not inst.stay then
inst.components.talker:Say("[ Eye monster !]")
end 
anti_eyes(inst)
end
end

end

local player = GetPlayer()
local leader = inst.components.follower.leader

if inst.yamche then
if math.random() < 0.5 then
inst.sg:GoToState("command")
elseif math.random() < 0.5 then
inst.sg:GoToState("cry")
elseif math.random() <= 1 then
inst.sg:GoToState("command")
end
inst.components.talker.fontsize = 24
if inst.components.inventory then
--level_inventory(inst)
end
if inst.yamche and inst.active_hunt and not inst.peace and not inst.defense then
--SpawnPrefab("dr_hot_loop").Transform:SetPosition(inst:GetPosition():Get())
elseif inst.yamche and not inst.active_hun and inst.peace and inst.defense then
--SpawnPrefab("dr_warm_loop_2").Transform:SetPosition(inst:GetPosition():Get())
elseif inst.yamche and not inst.active_hunt and not inst.peace and not inst.defense then
--SpawnPrefab("dr_warmer_loop").Transform:SetPosition(inst:GetPosition():Get())
end
if inst:HasTag("notarget") then
inst:RemoveTag("notarget")
end
inst.yamche = false
inst.armor = false
end

if not leader then
inst:AddTag("notarget")
end
if inst.components.hunger.current == 0 then
inst.components.hunger:DoDelta(5)
end 

if player:HasTag("no_sacrifice")then
        inst.no_resurrect = true
		end
	
if inst.resurrect_yamche and not inst.no_resurrect then
inst.peace = false
	inst.ndeath = true
	inst.ndead = false
inst.components.health:DoDelta(-10000)
end
if player:HasTag("DLC") or inst:HasTag("DLC") or IsDLCEnabled(REIGN_OF_GIANTS) then
         inst.DLC = true
		end
if player:HasTag("DLC2") or inst:HasTag("DLC2") or SaveGameIndex:IsModeShipwrecked() then
		inst.DLC = true
         inst.DLC2 = true
		end			
local leader = inst.components.follower.leader
if inst.components.follower.leader and inst.follow and not inst.active_hunt then
inst.components.combat:GiveUp()
end 

end



local ValidItems = {
 "goldnugget", "rocks", "cutstone", "nitre", "flint", "thulecite", "thulecite_pieces", "marble", "redgem", "purplegem", "bluegem", "yellowgem", "greengem", "orangegem",    "log", "boards", "cutgrass", "dug_grass", "rope", "twigs", "dug_sapling", "gears", "spidergland", "healingsalve", "mosquitosack", "silk", "spidereggsack", "ash", "poop", "guano", "charcoal", "beefalowool", "cutreeds", "houndstooth", "ice", "stinger", "livinglog", "lightbulb", "slurper_pelt", "honeycomb", "arrowm",
 "turf_road", "turf_rocky", "turf_forest", "turf_marsh", "turf_grass", "turf_savanna", "turf_dirt", "turf_woodfloor", "turf_carpetfloor", "turf_checkerfloor", "turf_cave", "turf_fungus", "turf_fungus_red", "turf_fungus_green", "turf_sinkhole", "turf_underrock", "turf_mud", 
  "walrus_tusk", "houndstooth", "wormlight_lesser", "wormlight", "nightmarefuel", "manrabbit_tail", "beardhair", "trinket_1", "trinket_2", "trinket_3", "trinket_4", "trinket_5", "trinket_6", "trinket_7",  "trinket_8", "trinket_9", "trinket_10", "trinket_11", "trinket_12",  "coontail", "tentaclespots", "beefalowool", "horn", "feather_robin", "feather_robin_winter", "feather_crow", "boneshard", "transistor",   "boomerang", "goose_feather", "drumstick", 
  "bearger_fur", "dragon_scales", 
  "acorn", "pinecone",
 --sw 
"coconut", "coral", "bamboo", "dug_bambootree", "vine", "dug_bush_vine", "limestone", "hail_ice", "obsidian", "palmleaf", "snake_poison", "snake_skin", "messagebottle", "messagebottleempty", "fabric", 
}
	
local function ItemIsInList(item, list)
    for k,v in pairs(list) do
        if v == item or k == item then
            return true
        end
    end
end
	
local function Take_order(inst)
local player = GetPlayer()

if inst.DLC2 or SaveGameIndex:IsModeShipwrecked() then
if inst.components.poisonable and inst:HasTag("poison") then
inst.components.poisonable:Cure(inst)
--inst:DoTaskInTime(5, function() inst.components.poisonable:Cure(inst) end)
end end

if inst.components.inventory and not inst.sg:HasStateTag("open") then 

local item_max = 40
local pack_max = 1
local itemstack_1 = inst.components.inventory:FindItem(function(item) return (ItemIsInList(item.prefab, ValidItems)) end)
local itemstack_2 = inst.components.inventory:FindItem(function(item) return inst.components.eater:CanEat(item) end)

if inst.pick1 then
inst.droping = false	
--itemstack_1.components.stackable.stacksize >= item_max then
--if (itemstack_1 or itemstack_2) and 
if inst.components.inventory:IsFull() then 
inst.item_max_full = true
--inst.components.hunger:SetRate(45/TUNING.TEENBIRD_STARVE_TIME)
if not inst.item_1 then 
inst.sg:GoToState("command")
inst.components.talker:Say("[Inventory]\n[ Full ]")
inst.item_1 = true
end end
end  

if inst.pick1 then
inst.droping = false	
if not inst.campfire then
inst.components.hunger:SetRate(30/TUNING.TEENBIRD_STARVE_TIME)
end
end
if inst.drop then
if not inst.campfire then
inst.components.hunger:SetRate(15/TUNING.TEENBIRD_STARVE_TIME)
end
--if not inst.DLC2 then
--	inst.components.inventory:DropEverything(true) end
inst.item_max_full = false
inst.item_1 = false 
if not inst.droping then
inst.sg:GoToState("command")
--inst.components.talker:Say("[Drop all collected items]")
--if not inst.DLC2 then
--SpawnPrefab("small_puff").Transform:SetPosition(inst:GetPosition():Get()) end
inst.droping = true
end	
end end 
end

local function InShadow(inst, data)
local x,y,z = inst.Transform:GetWorldPosition()	
local ents = TheSim:FindEntities(x, y, z, 8)
for k,v in pairs(ents) do
--inst.sleep_on 
if v.components.combat and v.components.combat.target == inst and not (v:HasTag("berrythief") or v:HasTag("prey") or v:HasTag("bird") or v:HasTag("butterfly")) then
		v.components.combat.target = nil		
 end
 end  end
 
local function on_close(inst)
local player = GetPlayer()
inst.follow = false
--player:AddTag("yamche") 
if player:HasTag("spiderwhisperer") then
inst:AddTag("spider") 
end
if not player:HasTag("spiderwhisperer") then
inst:AddTag("character") end
inst:AddTag("closea") 
inst:RemoveTag("fara") 

local leader = inst.components.follower.leader
if not inst.components.follower.leader and inst.components.staycommand and not inst.hat and not inst.house then
inst.stay = true
inst.components.staycommand:SetStaying(true)
inst.components.staycommand:RememberStayPos("stayspot", Point(inst.Transform:GetWorldPosition()))
inst.components.follower:SetLeader(player)
end

if not inst:HasTag("animals") then
inst.MiniMapEntity:SetIcon( "" )
end
--end
local danger = FindEntity(inst, 3, function(target) 
	return target:HasTag("monster") or (target.components.combat and target.components.combat.target == inst) end)
if not inst.campfire then
if inst.pick1 then
inst.components.locomotor.walkspeed = 8
elseif not inst.pick1 then
if danger then
inst.components.locomotor.walkspeed = 8
else
inst.components.locomotor.walkspeed = 4
end  
end
end
	inst.components.locomotor.pathcaps = { ignorecreep = false }

    if player:HasTag("houndmound") then
 inst:AddTag("houndmound") 
    elseif not player:HasTag("houndmound") then
inst:RemoveTag("houndmound") 
    elseif player:HasTag("shadows") then
inst:AddTag("notarget") 
    elseif not player:HasTag("shadows") then
inst:RemoveTag("notarget") 
end
end 

local function far(inst)
local player = GetPlayer()
inst.follow = true
inst:RemoveTag("character")
	if inst:HasTag("level1") then
inst.MiniMapEntity:SetIcon( "hat_xiang.tex" )
	end

inst:RemoveTag("closea") 
inst:AddTag("fara") 
if inst.campfire and not inst:HasTag("animals") then
--inst.components.sleeper:WakeUp()
inst.components.talker:Say("Campfire-(Off)")
inst.campfire = false
if inst.components.burnable:IsBurning() then
        inst.components.burnable:Extinguish()
end 
end
	

if inst:HasTag("level1") then
inst.components.locomotor.walkspeed = 14
end

	inst.components.locomotor.pathcaps = { ignorecreep = true }
	
if inst:HasTag("animals") or inst:HasTag("animal") then
inst.components.follower:SetLeader(nil)
end
end

-----------------------








local function ShouldWakeUp(inst)
--DefaultWakeTest(inst)
--inst.light_on
    --return not inst.sleep_on 
end
local function ShouldSleep(inst)
--DefaultSleepTest(inst)
    return (inst.campfire or inst.sleep_on or inst.sleep_f) and not inst.components.hunger:IsStarving(inst)
end
--[[
local function ShouldWakeUp(inst)
    return DefaultWakeTest(inst) or inst.components.hunger:IsStarving(inst) or not inst.components.follower:IsNearLeader(WAKE_TO_FOLLOW_DISTANCE)
end
local function ShouldSleep(inst)
    return DefaultSleepTest(inst) and not inst.components.hunger:IsStarving(inst) and inst.components.follower:IsNearLeader(SLEEP_NEAR_LEADER_DISTANCE)
end]]


local function CanEatTest(inst, item)
    --print("smallbird - CanEatTest", inst.name, item.components.edible.foodtype, item, item.prefab)
    local canEat = (item.components.edible.foodtype == "SEEDS") or (item.prefab == "berries")
    --print("   canEat?", canEat)

	if not item:HasTag("spoiled") then
			return true

   -- return canEat
end
end

local function ShouldAcceptItem(inst, item)

    --print("smallbird - ShouldAcceptItem", inst.name, item.name)
    if item.components.edible and inst.components.hunger and inst.components.eater then
        return not inst.sg:HasStateTag("open") and inst.components.eater:CanEat(item) and inst.components.hunger:GetPercent() <= 0.9
    end
end

local function OnGetItemFromPlayer(inst, giver, item)
    --print("smallbird - OnGetItemFromPlayer")


    --I eat food
    if item.components.edible then

        if inst.components.combat.target and inst.components.combat.target == giver then
            inst.components.combat:SetTarget(nil)
elseif giver.components.leader then
inst.SoundEmitter:PlaySound("dontstarve/creatures/smallbird/scratch_ground")
giver.components.leader:AddFollower(inst)
        end
        if inst.components.eater:Eat(item) then
        end
    end
end

local poopchance2 = 0.6
local poopchance = 0.4
local rebackchance = 0.2
local tynychance = 0.1
local tynyychance = 0.05
local eggchance = 1.0



local function OnRefuseItem(inst, item)
    inst.sg:GoToState("refuse")
end

local function FollowPlayer(inst)
	local player = GetPlayer()
	if player and player.components.leader then
		player.components.leader:AddFollower(inst)
	end
end

local function SetTeenAttackDefault(inst)

end

local function SetTeenAttackPeck(inst)
 
end

local function OnNewTarget(inst, data)
    --print("teenbird - OnNewTarget", data.target, inst.components.follower.leader)
    if data.target and data.target:HasTag("player") then
	return 
	elseif inst:HasTag("animal") then
	inst.components.combat:SetTarget(nil)
end
end
	
local function hunting(inst)
if inst.active_hunt then
local random = 0.1
if math.random() < random then
inst.yamche_lightning = true
end
if not inst.active_hunt then
end	
end end

local function yamche_hunt(inst)
    local dist = 20
    if inst.active_hunt then
    return FindEntity(inst, dist, function(guy)
        return inst.components.combat:CanTarget(guy)
    end,
    nil,
    {"toso","player","wall","structure","companion","yamche","beefalo","koalefant","pig","bee","rocky","bird","statue","character","abigail"})
	end

end
 	

local function leader_yamche(inst, data)
local player = GetPlayer()
if player.components.leader:IsFollower(inst) and not inst.yamche_leader then

local x,y,z = inst.Transform:GetWorldPosition()
local ents = TheSim:FindEntities(x,y,z, 20, {"yamche_leader"})
for k,v in pairs(ents) do
 if v.yamche_leader and v.active_hunt and not v.peace and not v.defense then
inst.peace = false
inst.active_hunt = true
inst.defense = false
  
 elseif v.yamche_leader and not v.active_hunt and v.peace and v.defense then
inst.peace = true
inst.active_hunt = false
inst.defense = true
 
 elseif v.yamche_leader and not v.active_hunt and not v.peace and not v.defense then
inst.peace = false
inst.active_hunt = false
inst.defense = false
 
end end end
end

local function Onhunt(inst, target)
    return inst.components.combat:CanTarget(target)
end

local function OnAttacked(inst, data)
if data.attacker:HasTag("toso") then
inst:AddTag("animals")
inst.components.combat:SetTarget(nil)
inst.components.combat:GiveUp()
inst.components.follower:SetLeader(nil)
end
if inst.resurrect_activate then
InShadow(inst)
end

    inst.components.combat:SuggestTarget(data.attacker)
    inst.components.combat:ShareTarget(data.attacker, 3, function(dude) return (dude:HasTag("ghosthound") or dude:HasTag("yamche")) and not dude.components.health:IsDead() end, 5)

end




local function flower_shield(inst, attacked, data) 
if not inst.components.health:IsDead() and not inst.DLC then
    if inst.components.health:GetPercent() >= .7 then
	--SpawnPrefab("dr_warm_loop_1").Transform:SetPosition(inst:GetPosition():Get())	
    elseif inst.components.health:GetPercent() < .7 and inst.components.health:GetPercent() >= .5 then
	--SpawnPrefab("dr_warm_loop_2").Transform:SetPosition(inst:GetPosition():Get())
    elseif inst.components.health:GetPercent() < .5 and inst.components.health:GetPercent() >= .3 then
	--SpawnPrefab("dr_warmer_loop").Transform:SetPosition(inst:GetPosition():Get())
    elseif inst.components.health:GetPercent() < .3 then
	--SpawnPrefab("dr_hot_loop").Transform:SetPosition(inst:GetPosition():Get())
	end
elseif not inst.components.health:IsDead() and inst.DLC then
    if inst.components.health:GetPercent() >= .7 then
	--SpawnPrefab("green_leaves").Transform:SetPosition(inst:GetPosition():Get())	
    elseif inst.components.health:GetPercent() < .7 and inst.components.health:GetPercent() >= .5 then
	--SpawnPrefab("yellow_leaves").Transform:SetPosition(inst:GetPosition():Get())
    elseif inst.components.health:GetPercent() < .5 and inst.components.health:GetPercent() >= .3 then
	--SpawnPrefab("orange_leaves").Transform:SetPosition(inst:GetPosition():Get())
    elseif inst.components.health:GetPercent() < .3 then
	--SpawnPrefab("red_leaves").Transform:SetPosition(inst:GetPosition():Get())
	end	end
end

local function OnHitfreeze(inst, data)
local freezechance = 0.4
local other = data.target
   local pos = other:GetPosition()
    if other and other.components.freezable and inst:HasTag("iceyamche") then
        other.components.freezable:AddColdness(0.5)
        other.components.freezable:SpawnShatterFX()
		
			local prefab = "icespikes_fx_"..math.random(1,4)
			local fx = SpawnPrefab(prefab)
			local shards = math.random(0.4,0.5)
			fx.Transform:SetScale(shards, shards, shards)
			fx.Transform:SetPosition(other:GetPosition():Get())
elseif other and other.components.freezable and inst:HasTag("iceyamche") and inst.ranger2 then
        other.components.freezable:AddColdness(3)
        other.components.freezable:SpawnShatterFX()
		local prefab = "icespikes_fx_"..math.random(1,4)
			local fx = SpawnPrefab(prefab)
			local shards = math.random(1,1.2)
			fx.Transform:SetScale(shards, shards, shards)
			fx.Transform:SetPosition(other:GetPosition():Get())
			
  	local fx2 = SpawnPrefab("groundpoundring_fx")
	 	  fx2.Transform:SetScale(0.4, 0.4, 0.4)
	  	  fx2.Transform:SetPosition(other:GetPosition():Get())
elseif other and other:HasTag("toso") then
	inst.components.combat:SetTarget(nil)
inst.components.combat:GiveUp()

    end

    if other.components.burnable and other.components.burnable:IsBurning() then
        other.components.burnable:Extinguish()
    end
end

local function OnHitvampire(inst, data)
local other = data.target
if not (other:HasTag("smashable")) then
--[[inst:HasTag("darkyamche")]]
 if other and inst.vampire_on then
        SpawnPrefab("statue_transition").Transform:SetPosition(other:GetPosition():Get())
        inst.components.health:DoDelta(10)

    end
end
end





local function resist(inst, data)

if inst.components.health:GetPercent() < 0.25 and not inst.vampire then
            inst.vampire = SpawnPrefab( "deer_charge_pst" )
			inst.vampire.Transform:SetScale(0.3, 0.3, 0.3)
            local follower = inst.vampire.entity:AddFollower()
            follower:FollowSymbol( inst.GUID, "head", 0, -130, 2 )
			inst.vampire_on = true
			inst:DoTaskInTime(30, function() if inst.vampire then
			inst.vampire_on = false
			inst.vampire:Remove() inst.vampire = nil end end)
end	
if inst.components.health:GetPercent() >= 0.9 and inst.vampire then
			inst.vampire:Remove()
			inst.vampire = nil
end

if inst.components.health:GetPercent() <= 1 and  inst.components.health:GetPercent() > 0.7 then
        inst.components.freezable.wearofftime = 1.5

elseif inst.components.health:GetPercent() <= 0.7 and  inst.components.health:GetPercent() > 0.5 then
        inst.components.freezable.wearofftime = 0.5

elseif inst.components.health:GetPercent() <= 0.5 and  inst.components.health:GetPercent() > 0.2 then
        inst.components.freezable.wearofftime = 0.25

elseif inst.components.health:GetPercent() <= 0.2 then
        inst.components.freezable.wearofftime = 0
end
end

local function updatestats(inst, data)

	if inst.components.health:GetPercent() < 0.2 then
	
if not GetClock():IsNight() then inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" ) end
    --inst:ListenForEvent("attacked", OnFire)

elseif inst.components.health:GetPercent() >= 0.2 then
   -- inst:RemoveEventCallback("attacked", OnFire)

elseif inst.components.health:GetPercent() >= 0.2 and not inst.ranger2 then


end

if inst.components.health:GetPercent() >= .3 and not inst:HasTag("iceyamche") then

			--
if not GetClock():IsNight() then inst.AnimState:SetBloomEffectHandle( "" ) end
    			
    --inst:RemoveEventCallback("attacked", Onfreeze)
	if not inst.yamche_wing then
    inst.components.combat:SetAttackPeriod(0.8)
	elseif inst.yamche_wing then
	inst.components.combat:SetAttackPeriod(3.2)
	end
		elseif inst.components.health:GetPercent() >= .3 and inst:HasTag("iceyamche") then
    			
			--
    ----inst:ListenForEvent("attacked", Onfreeze)
	if not inst.yamche_wing then
    inst.components.combat:SetAttackPeriod(0.8)
	elseif inst.yamche_wing then
	inst.components.combat:SetAttackPeriod(3.2)
	end

		elseif inst.components.health:GetPercent() < .3 and not inst:HasTag("iceyamche") then
    			

    --inst:ListenForEvent("attacked", Onfreeze)

	if not inst.yamche_wing then
    inst.components.combat:SetAttackPeriod(2.4)
	elseif inst.yamche_wing then
	inst.components.combat:SetAttackPeriod(5)
	end
	elseif inst.components.health:GetPercent() < .3 and inst:HasTag("iceyamche") then
    			

    ----inst:ListenForEvent("attacked", Onfreeze)

	if not inst.yamche_wing then
    inst.components.combat:SetAttackPeriod(2.4)
	elseif inst.yamche_wing then
	inst.components.combat:SetAttackPeriod(5)
	end
end
end






local function onspawnfn(inst, spawn)
 inst.sg:GoToState("command")
 --SpawnPrefab("sparklefx").Transform:SetPosition(inst:GetPosition():Get())
 --SpawnPrefab("sparks").Transform:SetPosition(inst:GetPosition():Get())
end
local function sleep_heal(inst)
if inst.yamche_wing then
inst.yamche_lightning = true
end
if inst.sleep_on and inst.components.health:GetPercent() < 1 then
inst.components.health:DoDelta(1)
end
end




--time
--(lv2)
local function GetTeenGrowTime(inst)
	return 1
end


local function create_common(inst)
    --print("smallbird - create_common")
	--inst = inst or CreateEntity()
	
    inst:AddTag("yamche")
    inst:AddTag("yamcheb")
    inst:AddTag("companion")
   -- inst:AddTag("character")
    inst:AddTag("musha_small")
    inst:AddTag("scarytoprey")
   -- inst:AddTag("noauradamage")
   -- inst:AddTag("fridge")
   -- inst:AddTag("nocool")
   inst:AddTag("lowcool")
inst:AddTag("amphibious")
--inst:AddTag("peck_attack")
inst:AddTag("notraptrigger")
inst:AddTag("phoenix")

    inst.entity:AddMiniMapEntity()
	inst.entity:AddMiniMapEntity():SetPriority( 5 )
	--inst.MiniMapEntity:SetIcon( "musha_small.tex" )
	inst.MiniMapEntity:SetIcon( "musha_teen.tex" )

	inst.entity:AddSoundEmitter()
	inst.entity:AddDynamicShadow()

	inst.entity:AddLight()
	inst.Light:SetColour(185/255,175/255,170/255)

local player = GetPlayer()
if player:HasTag("DLC")then
	inst.DLC = true
		end
if player:HasTag("DLC2") or inst:HasTag("DLC2") or SaveGameIndex:IsModeShipwrecked() then
	inst.DLC2 = true
		end		

if inst.DLC then
inst:AddComponent("waterproofer")
inst.components.waterproofer.effectiveness = 0
end		
if inst.DLC2 or SaveGameIndex:IsModeShipwrecked() then
MakePoisonableCharacter(inst)
	inst:AddComponent("floatable")
	inst:AddComponent("waterproofer")
    inst.components.waterproofer.effectiveness = 0
 end
 if player.no_growup then
 inst.no_growup = true
 end
 --[[]]
 if not player.components.leader:IsFollower(inst) then
 inst:AddTag("animals")
 elseif player.components.leader:IsFollower(inst) then
 inst:RemoveTag("animals")
 end
 
 		if inst.DLC2 then
		--MakeAmphibiousGhostPhysics(inst, 1, .5)
		MakeAmphibiousCharacterPhysics(inst, 1, .5)
		elseif not inst.DLC2 then
    	MakeCharacterPhysics(inst, 0.5, .25)
		end
    	
	--MakeAmphibiousCharacterPhysics(inst, 1, .5)
	--MakePoisonableCharacter(inst)
--[[	
    inst.Physics:SetCollisionGroup(COLLISION.CHARACTERS)
    inst.Physics:ClearCollisionMask()
    inst.Physics:CollidesWith(COLLISION.WORLD)
    inst.Physics:CollidesWith(COLLISION.OBSTACLES)
    inst.Physics:CollidesWith(COLLISION.CHARACTERS)
]]
    inst.Transform:SetFourFaced()
	--inst.Transform:SetSixFaced()
	
	inst:SetBrain(brain)	

    inst.userfunctions = 
    {
        FollowPlayer = FollowPlayer,
        --GetPeepChance = GetPeepChance,
        --GetCryChance = GetCryChance,
        --SpawnTeen = SpawnTeen,
        --SpawnAdult = SpawnAdult,
        --SpawnAdult2 = SpawnAdult2,
        --SpawnAdult3 = SpawnAdult3,
        --SpawnAdult4 = SpawnAdult4,
        --SpawnAdult5 = SpawnAdult5,
        --SpawnAdult6 = SpawnAdult6,

    }
    --("   order")

---name
    inst:AddComponent("named")
	--if not inst:HasTag("level1") then
    inst.components.named.possiblenames = "axiang"
    inst.components.named:PickNewName()
	--[[elseif inst:HasTag("level1") then
    inst.components.named.possiblenames = STRINGS.BABY
    inst.components.named:PickNewName()
			end]]
    --inst:AddComponent("sanityaura")
    --inst.components.sanityaura.aurafn = PhoenixSanityAura
--------------------
inst:AddComponent("inspectable")
--------------------
    inst:AddComponent("playerprox")
    inst.components.playerprox:SetDist(7, 7)
    inst.components.playerprox:SetOnPlayerNear(on_close)
    inst.components.playerprox:SetOnPlayerFar(far)

    ------------------------------------------
    inst:AddComponent("health")
	inst.components.health.fire_damage_scale = 0
	inst.components.health.canmurder = false
--inst:ListenForEvent("healthdelta", OnHealthDelta)
inst.components.health:StartRegen(1, 10)

    inst:AddComponent("hunger")
inst.components.hunger:SetRate(15/TUNING.TEENBIRD_STARVE_TIME)	   
    inst.Take_order = inst:DoPeriodicTask(0.25, Take_order)   
	--inst.yamche_wing = inst:DoPeriodicTask(0,yamche_wing)
	--inst:DoPeriodicTask(0.5, function() if inst.yamche_wing then splash_on(inst) end end)
	
    inst:AddComponent("combat")
	if inst.components.health:GetPercent() >= .3 then
    inst.components.combat:SetAttackPeriod(.8)
	elseif inst.components.health:GetPercent() < .3 then
	inst.components.combat:SetAttackPeriod(3)
	end
    inst.components.combat.playerdamagepercent = 0
	inst:ListenForEvent("attacked", OnAttacked)
    inst.Peaceful = inst:DoPeriodicTask(0.1, Peace)   
	inst.leader_yamche = inst:DoPeriodicTask(0.3, leader_yamche)   
	inst.hunt = inst:DoPeriodicTask(5, hunting)
    inst.components.combat:SetRetargetFunction(1, yamche_hunt)
    inst.components.combat:SetKeepTargetFunction(Onhunt)

        inst.procfn = function() tryproc(inst) end
        inst:ListenForEvent("attacked", inst.procfn)
		--inst.taunting = inst:DoPeriodicTask(8,taunting)
		
inst.on_shard_reflect = function(attacked, data)

if data.attacker and not data.attacker:HasTag("thorny") and not data.attacker:HasTag("shadowcreature") and data.attacker.components.health then

 if inst.components.health:GetPercent() <= .5 and not inst.components.health:IsDead() and math.random() < 0.35 then
	SpawnPrefab("shock_fx2").Transform:SetPosition(inst:GetPosition():Get())
	inst.SoundEmitter:PlaySound("dontstarve/common/lightningrod")
        inst.components.health:DoDelta(5)
		end

if not inst.iceyamche and inst.components.health:GetPercent() < .3 then
	if data.attacker and data.attacker.components.freezable then
	local prefab = "icespikes_fx_"..math.random(1,4)
    local fx = SpawnPrefab(prefab)
    local shards = math.random(0.7,0.8)
 	fx.Transform:SetScale(shards, shards, shards)
	fx.Transform:SetPosition(data.attacker:GetPosition():Get())

            data.attacker.components.freezable:AddColdness(0.4)
            data.attacker.components.freezable:SpawnShatterFX()
    end 
elseif not inst.iceyamche and inst.components.health:GetPercent() >= .3 then
	if data.attacker and data.attacker.components.burnable and not data.attacker:HasTag("thorny") and not data.attacker:HasTag("shadowcreature") and math.random() < 0.25 then
            data.attacker.components.burnable:IsBurning()
            data.attacker.components.health:DoDelta(-10)
            --data.attacker.components.burnable:Ignite(true)
    end 

elseif inst.iceyamche and inst.components.health:GetPercent() < .3 then
	if data.attacker and data.attacker.components.freezable then
	local prefab = "icespikes_fx_"..math.random(1,4)
    local fx = SpawnPrefab(prefab)
    local shards = math.random(0.7,0.8)
 	fx.Transform:SetScale(shards, shards, shards)
	fx.Transform:SetPosition(data.attacker:GetPosition():Get())

            data.attacker.components.freezable:AddColdness(0.35)
            data.attacker.components.freezable:SpawnShatterFX()
    end 
elseif inst.iceyamche and inst.components.health:GetPercent() >= .3 then
	if data.attacker and data.attacker.components.freezable then
	local prefab = "icespikes_fx_"..math.random(1,4)
    local fx = SpawnPrefab(prefab)
    local shards = math.random(0.7,0.8)
 	fx.Transform:SetScale(shards, shards, shards)
	fx.Transform:SetPosition(data.attacker:GetPosition():Get())

            data.attacker.components.freezable:AddColdness(0.5)
            data.attacker.components.freezable:SpawnShatterFX()
    end 
end	

end		
end
	
inst:ListenForEvent("attacked", inst.on_shard_reflect, inst)		
		
		
--inst:ListenForEvent("hungerdelta", Checklevel)
--inst:ListenForEvent("healthdelta", resist)
--inst:ListenForEvent("healthdelta", ranger_c)
--inst:ListenForEvent("hungerdelta", on_wakeup)

    --inst:ListenForEvent("onhitother", OnHitfire)
    --inst:ListenForEvent("onhitother", OnHitfreeze)
    --inst:ListenForEvent("onhitother", OnHitvampire)
    --inst:ListenForEvent("onhitother", OnRanger)
	--inst:ListenForEvent("hungerdelta", Power_check)
    inst:ListenForEvent("death", ondeath)
    inst:ListenForEvent("attacked", flower_shield)
	--inst.growup_check = inst:DoPeriodicTask(0, function() if inst.grow_up_yamchae_ready then growup_check(inst) end end)
	
 inst.ndeath = true
inst.ndead = false
inst.peace = false
inst.active_hunt = false
inst.defense = false

    inst.components.inspectable.getstatus = GetStatus

    inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
    inst.components.locomotor.walkspeed = 6
    inst.components.locomotor.runspeed = 9
   -- inst.components.locomotor.pathcaps = { ignorecreep = true }
  --  inst:AddTag("animal") 

    inst:AddComponent("follower")
	--inst.components.follower.canaccepttarget = true
-------
 if ACTIONS.STAYORDER~= nil then
    inst:AddComponent("staycommand")
    	end
-------
    inst:AddComponent("talker")
    inst.components.talker.fontsize = 24
	inst.components.talker.offset = Vector3(0,-800,0)
    inst.components.talker.colour = Vector3(0.75, 0.85, 1, 1)

    inst:AddComponent("eater")
    inst.components.eater:SetCanEatTestFn(CanEatTest)
    inst.components.eater:SetOmnivore()
	inst.components.eater.strongstomach = true

    --[[ 
	inst:AddComponent("machine")
    inst.components.machine.turnonfn = onuseyamche
    inst.components.machine.turnofffn = offuseyamche
    inst.components.machine.cooldowntime = 0
	]]
	
	--inst.components.eater:SetElemental()
    --inst.components.eater.foodprefs = { "MEAT", "VEGGIE", "INSECT", "SEEDS", "GENERIC", }
	
		inst:AddComponent("inventory") 
		--level_inventory(inst) 
inst.inventoryset =	function(inst,data)
if inst.components.inventory then
if inst:HasTag("level1") then
inst.components.inventory.maxslots = 3
end 
end
end
		
		inst:AddComponent("playeractionpicker")
if inst.DLC or inst.DLC2 or SaveGameIndex:IsModeShipwrecked() then
	inst.components.inventory:IsWaterproof()
end	
		
	
	if inst.DLC2 then
	--inst.components.inventory.nosteal = true
	inst.components.inventory.acceptitems = true 
	end
	inst.components.inventory.maxslots = 6
		
    --inst.components.eater:SetOnEatFn(OnEat)

    --inst:AddComponent("sleeper")
    --inst.components.sleeper:SetResistance(4)
    --inst.components.sleeper.testperiod = GetRandomWithVariance(4, 1)
    --inst.components.sleeper:SetSleepTest(ShouldSleep)
    --inst.components.sleeper:SetWakeTest(ShouldWakeUp)
    --inst:AddComponent("freezable")
    --inst.components.freezable:SetResistance(6)

    inst:AddComponent("trader")
    inst.components.trader:SetAcceptTest(ShouldAcceptItem)
    inst.components.trader.onaccept = OnGetItemFromPlayer
    inst.components.trader.onrefuse = OnRefuseItem
		 
    inst:AddComponent("periodicspawner")
    inst.components.periodicspawner:SetPrefab("poop")
	inst.components.periodicspawner:SetOnSpawnFn(onspawnfn)
    inst.components.periodicspawner:SetRandomTimes(450, 900)
  --  inst.components.periodicspawner:SetDensityInRange(20, 2)
  --  inst.components.periodicspawner:SetMinimumSpacing(3)
    inst.components.periodicspawner:Start()

--------------------------------------------------------------------------

if not inst:HasTag("level1") and not inst:HasTag("baby") then
inst:AddComponent("inventoryitem") 
inst:AddComponent("equippable")
--local inv_name = inst.prefab
--inst.components.inventoryitem.atlasname = "images/inventoryimages/"..inv_name..".xml"
	if inst.components.inventoryitem and inst.components.equippable then 
	--inst.components.inventoryitem.cangoincontainer = false
	inst.components.inventoryitem:SetOnDroppedFn(Dropped_cave)
	inst.components.inventoryitem:SetOnPutInInventoryFn(OnPutInInventory_cave)
	inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
	inst.components.equippable:SetOnEquip(onyamche_house)
    inst.components.equippable:SetOnUnequip(offyamche_house)

		
	end
end	
inst.cave_near = inst:DoPeriodicTask(0, cave_near )



--------------------------------------------------------------------------


-------------------------------------------
if not inst.no_resurrect then
inst:AddComponent("resurrector")
inst.components.resurrector.doresurrect = doresurrect2
inst.components.resurrector.active = false
end
-------------------------------------------
--inst.sleep_heal = inst:DoPeriodicTask(0.5,sleep_heal)

    --print("base- create_common END")

inst:ListenForEvent( "healthdelta", updatestats)

	inst.level = 0
    --inst:ListenForEvent("entity_death", function(wrld, data) onkilll(inst, data) end, GetWorld())
	inst:ListenForEvent("killed", onkilll)
	--inst:ListenForEvent("levelup", levelexp)
	inst.OnSave = onsave
	inst.OnPreLoad = onpreload

    return inst
end

-----------start create birds grow

local function create_smallbird()
    --print("smallbird - create_smallbird")

	local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()

    MakeInventoryPhysics(inst, 1,1)

    inst.AnimState:SetBank("smallbird")
    inst.AnimState:SetBuild("musha_small")
    inst.AnimState:PlayAnimation("idle")
-------------------------------------
	--inst:AddComponent("characterspecific")
    --inst.components.characterspecific:SetOwner("musha")
	
	inst:AddTag("green")   
    inst:AddTag("musha_small")
	--inst:AddTag("light")
	inst:AddTag("level1")

	-----------------------------equip--hat
		
    inst:AddComponent("inventoryitem")
	inst.components.inventoryitem.atlasname = "images/inventoryimages/musha_small.xml"
	
    inst.components.inventoryitem:SetOnDroppedFn(OnDropped)
    inst.components.inventoryitem:SetOnPutInInventoryFn(OnPutInInventory)

	inst:AddComponent("equippable")
    inst:AddComponent("insulator")

    inst.components.equippable.equipslot = EQUIPSLOTS.HEAD
    inst.components.insulator.insulation = TUNING.INSULATION_MED
       inst.components.equippable:SetOnEquip(onyamche)
       inst.components.equippable:SetOnUnequip(offyamche)


local player = GetPlayer()
if player:HasTag("DLC")then
	inst.DLC = true
		end
if player:HasTag("DLC2")then
	inst.DLC2 = true
		end		
		
if not inst.DLC2 then
  inst.components.equippable.walkspeedmult = 1.25
elseif inst.DLC2 then
  inst.components.equippable.walkspeedmult = 0.25
  end
  
------------------------
--[[
    inst.entity:AddLight()
	inst.Light:SetRadius(.3)
    inst.Light:SetFalloff(.55)
    inst.Light:SetIntensity(.75)
    inst.Light:SetColour(10/255,125/255,125/255)
	]]
	---
-----------------------
 
-------------------------------------

    create_common(inst)


    inst:SetStateGraph("SGmusha_small")
    inst.Transform:SetScale(0.4, 0.4, 0.4)

	inst.DynamicShadow:SetSize( 0.8, .3 )
    --
        

    
	inst.components.health:SetMaxHealth(100000)

    inst.components.hunger:SetMax(50)
    --inst.components.hunger:SetRate(TUNING.SMALLBIRD_HUNGER * 1.2 /TUNING.SMALLBIRD_STARVE_TIME)


	inst.components.combat.hiteffectsymbol = "head"
    inst.components.combat:SetRange(2, 3)
    inst.components.combat:SetDefaultDamage(10)

    --inst:AddComponent("lootdropper")({"glowdust"})

  -- inst.components.eater:SetCanEatTestFn(CanEatTest)
--inst.components.eater.foodprefs = { "MEAT", "VEGGIE", "INSECT", "SEEDS", "GENERIC", }

    --local growth_stages = {
    --    {name="small", time = GetTeenGrowTime, fn = function() end },
    --    {name="tall", fn = SetTeen}
    --}

	--inst:AddComponent("growable")
    --inst.components.growable.stages = growth_stages
    --inst.components.growable:SetStage(1)
    --inst.components.growable:StopGrowing()


    --print("smallbird - create_smallbird END")
	return inst
end

return Prefab( "musha_small", create_smallbird, assets, prefabs)