content
stringlengths
5
1.05M
AuctionatorShoppingTabRecentsContainerMixin = {} function AuctionatorShoppingTabRecentsContainerMixin:OnLoad() self.Tabs = {self.ListTab, self.RecentsTab} self.numTabs = #self.Tabs Auctionator.EventBus:RegisterSource(self, "List Search Button") Auctionator.EventBus:Register(self, { Auctionator.ShoppingLists.Events.ListSelected, }) end function AuctionatorShoppingTabRecentsContainerMixin:ReceiveEvent(eventName) if eventName == Auctionator.ShoppingLists.Events.ListSelected then self:SetView(Auctionator.Constants.ShoppingListViews.Lists) end end function AuctionatorShoppingTabRecentsContainerMixin:SetView(viewIndex) PanelTemplates_SetTab(self, viewIndex) self:GetParent().ManualSearch:Hide() self:GetParent().AddItem:Hide() self:GetParent().SortItems:Hide() if viewIndex == Auctionator.Constants.ShoppingListViews.Recents then self:GetParent().ScrollListShoppingList:Hide() self:GetParent().ScrollListRecents:Show() elseif viewIndex == Auctionator.Constants.ShoppingListViews.Lists then self:GetParent().ScrollListRecents:Hide() self:GetParent().ScrollListShoppingList:Show() self:GetParent().ManualSearch:Show() self:GetParent().AddItem:Show() self:GetParent().SortItems:Show() end end
-- local DeskView = class("DeskView", function() -- bg = ccui.ImageView:create("DowneyTang/koprokdice/bet/koprok_dice_bet.png") -- return bg -- end) local DeskView = class("DeskView",cc.load("boyaa").mvc.BoyaaView); local BehaviorExtend = cc.load("boyaa").behavior.BehaviorExtend; BehaviorExtend(DeskView); function DeskView:addTouchSpace(spaceMap) end function DeskView:init() local bg = ccui.ImageView:create("DowneyTang/koprokdice/bet/koprok_dice_bet.png") bg:addTo(self) --牌桌下方的提示文字 local deskTips = ccui.Text:create("hello", "Arial", 40) deskTips:setString(" 單骰=1:1 雙骰=1:2 全骰=1:3 組合押注=1:5") deskTips:setTextColor(cc.c3b(128, 0, 128)) deskTips:setPosition(240, 33) deskTips:setFontSize(20) deskTips:addTo(bg) end function DeskView:ctor() self:init() end return DeskView;
FrenchRP.addPlayerGesture = FrenchRP.stub{ name = "addPlayerGesture", description = "Add a player gesture to the FrenchRP animations menu (the one that opens with the keys weapon.). Note: This function must be called BOTH serverside AND clientside!", parameters = { { name = "anim", description = "The gesture enumeration.", type = "number", optional = false }, { name = "text", description = "The textual description of the animation. This is what players see on the button in the menu.", type = "string", optional = false } }, returns = { }, metatable = FrenchRP } FrenchRP.removePlayerGesture = FrenchRP.stub{ name = "removePlayerGesture", description = "Removes a player gesture from the FrenchRP animations menu (the one that opens with the keys weapon.). Note: This function must be called BOTH serverside AND clientside!", parameters = { { name = "anim", description = "The gesture enumeration.", type = "number", optional = false } }, returns = { }, metatable = FrenchRP }
-- function init() self.energyCost = config.getParameter("energyCost", 10) self.initialEnergyCost = config.getParameter("initialEnergyCost", self.energyCost) self.drainBoost = 0 end function update(args) -- if not self.specialLast and args.moves["special"] == 1 then tryActivate() end self.specialLast = args.moves["special"] == 1 if self.active then local onHealth = false -- consume energy if self.energyDepleted or not status.overConsumeResource("energy", self.energyCost * args.dt) then self.drainBoost = math.max(self.drainBoost - args.dt, 0) local lifeDrainRate = 1.0 + self.drainBoost * 0.5 if status.resource("health") < 0.01 then -- energy overuse speeds up health drain self.drainBoost = 2.5 end -- keep draining from life status.overConsumeResource("health", self.energyCost * args.dt * lifeDrainRate) --status.modifyResource("energy", 5730) -- try force-recharge status.setResource("energy", 0.01) status.setResourceLocked("energy", false) onHealth = true self.energyDepleted = true end -- boost stats status.setPersistentEffects("hypermode", { { stat = "fallDamageMultiplier", effectiveMultiplier = 0.0 }, { stat = "protection", effectiveMultiplier = 3.0 }, --amount = 10 }, { stat = "powerMultiplier", effectiveMultiplier = 3.0 }, --{ stat = "energyRegenBlockTime", effectiveMultiplier = 0 }, { stat = "dummy", amount = 0 } -- dummy cap }) -- and movement mcontroller.controlModifiers({ speedModifier = 2.0, airJumpModifier = 1.5 }) -- and apply visuals applyFX(args.dt, onHealth) else status.clearPersistentEffects("hypermode") tech.setParentDirectives("") -- blank out self.energyDepleted = false self.drainBoost = 0 end animator.setLightActive("hyper", self.active) end function applyFX(dt, onHealth) local blinkSpeed = 1.0 local color = {0x00, 0x7f, 0xff, 0xff} -- "008fffff" if onHealth then local healthPercent = status.resourcePercentage("health") color = {0xff, 0x00, 0x00, 0xff} -- "ff0000ff" if healthPercent <= 2.0/15.0 then color = {0xff, 0xff, 0xff, 0xff} end -- "ffffffff" blinkSpeed = 1.0 - healthPercent blinkSpeed = blinkSpeed * blinkSpeed * blinkSpeed blinkSpeed = 1.0 + blinkSpeed * 5 end self.blinkTimer = self.blinkTimer + dt * blinkSpeed local blink = 0.5 + math.sin(math.pi * 2.0 * self.blinkTimer) * 0.5 animator.setLightColor("hyper", colorMult(color, 0.1 + blink * 0.4)) tech.setParentDirectives("?fade=" .. colorToString(color) .. "=" .. (blink * 0.32)) end function tryActivate() if self.active then deactivate() else activate() end end function activate() -- fail if no energy if not status.overConsumeResource("energy", self.initialEnergyCost) then return end self.active = true self.blinkTimer = 0 end function deactivate() self.active = false end function colorMult(color, mult) return { color[1] * mult, color[2] * mult, color[3] * mult, color[4] * mult } end function colorToString(color) return string.format("%x", color[1] * 16777216 + color[2] * 65536 + color[3] * 256 + color[4]) end
--@name cpuTime Example --@author INP - Radon + Sparky --@client -- This function helps us check if we can run. -- Use a mixture of quotaUsed() and quotaAverage() -- quotaUsed() returns the value of the current buffer. -- quotaAverage() gives the cpuTime average across the whole buffer. -- Your chip will throw an error if quotaAverage() > quotaMax() -- n is a parameter between 0 and 1 that represents the percent. 0.8 = 80%. local function quotaCheck(n) return math.max(quotaAverage(), quotaUsed()) < quotaMax() * n end render.createRenderTarget("Background") -- Standard render hook. hook.add("render", "", function () local maxQuota = 0.1 render.setColor(Color(255, 255, 255)) -- Print some stats to the screen render.drawText(10, 10, "Quota Used: " .. math.round(quotaUsed() * 1000000) .. "us") render.drawText(10, 30, "Quota Avg: " .. math.round(quotaAverage() * 1000000) .. "us") render.drawText(10, 50, "Quota Max: " .. math.round(quotaMax() * 1000000) .. "us") local quota = quotaAverage() / quotaMax() if quota >= maxQuota then render.setColor(Color(255, 0, 0)) end render.drawText(10, 70, "Percent: " .. math.round(quota * 100, 2) .. "%") -- Set the rendertarget to our background so that we can make a bluring effect render.selectRenderTarget("Background") render.setColor(Color(0, 0, 0, 50)) render.drawRect(0, 0, 1024, 1024) -- While our quota is less than 10%. -- This will result in higher FPS, thus more render calls. -- You'd think this would affect the rendering of the cube, it doesn't. -- If you increase this check to 99%, FPS will significantly drop, and the movement would be slower. -- Play with this value and see the effects on percentage and your FPS. while quotaCheck(maxQuota) do -- Now we can draw a funky box that oscillates back and forth in the middle of the screen. render.setColor(Color(math.random(100, 255), math.random(100, 255), math.random(100, 255))) render.drawRect(math.sin(timer.curtime() * 2) * 380 + (512 - 100), 512 / 2, 200, 400) end render.selectRenderTarget(nil) -- Draw the resulting rendertarget render.setRenderTargetTexture("Background") render.setColor(Color(255, 255, 255)) render.drawTexturedRect(0, 128, 512, 384) end)
-- a version of pairs()-like iteration over a table, -- which doesn't leak a reference to the table itself. -- this can be useful to prevent unwanted modification to the table. -- next :: Table -> Maybe Key -> Maybe (Key, Value) local nextkey = next -- pairs :: Table -> Iterator (Key, Value) local f = function() return nil, nil end local pairs = function(table) local t = type(table) if t ~= "table" then error("pairs(t): expected t to be a table, got "..t) end local ckey = nil local stop = false -- we're effectively mimicking the behaviour of normal pairs() here; -- except we closure over state variables instead of being passed them. -- this also has the benefit of being possible to pass around. return function() if stop then return f() end local k, v = next(table, ckey) if k == nil then stop = true return f() end ckey = k return k, v end end return pairs
local collisionFixtures = {} function init(b2worldProxy) end function loadMapObject(objectName, mapObject) end function getFixturesInterestedInCollisions() return collisionFixtures end function update() end function beginCollision(b2Contact) end function endCollision(b2Contact) end
--# Monster converted using Devm monster converter #-- local mType = Game.createMonsterType("Draken Elite") local monster = {} monster.description = "a draken elite" monster.experience = 4200 monster.outfit = { lookType = 362, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 672 monster.Bestiary = { class = "Dragon", race = BESTY_RACE_DRAGON, toKill = 2500, FirstUnlock = 100, SecondUnlock = 1000, CharmsPoints = 50, Stars = 4, Occurrence = 0, Locations = "Razachai, including the Crystal Column chambers in the Inner Sanctum." } monster.health = 5550 monster.maxHealth = 5550 monster.race = "blood" monster.corpse = 11653 monster.speed = 332 monster.manaCost = 0 monster.maxSummons = 0 monster.changeTarget = { interval = 5000, chance = 10 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = false, attackable = true, hostile = true, convinceable = false, pushable = false, rewardBoss = false, illusionable = true, canPushItems = true, canPushCreatures = false, staticAttackChance = 90, targetDistance = 1, runHealth = 0, healthHidden = false, isBlockable = false, canWalkOnEnergy = true, canWalkOnFire = true, canWalkOnPoison = true, pet = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "For ze emperor!", yell = false}, {text = "You will die zhouzandz deazhz!", yell = false} } monster.loot = { {id = 3028, chance = 2440, maxCount = 4}, -- small diamond {id = 3031, chance = 50000, maxCount = 100}, -- gold coin {id = 3031, chance = 47000, maxCount = 100}, -- gold coin {id = 3035, chance = 50360, maxCount = 8}, -- platinum coin {id = 3577, chance = 30175}, -- meat {id = 5904, chance = 2100}, -- magic sulphur {id = 7404, chance = 980}, -- assassin dagger {id = 238, chance = 9340, maxCount = 3}, -- great mana potion {id = 7643, chance = 9250, maxCount = 3}, -- ultimate health potion {id = 10384, chance = 490}, -- Zaoan armor {id = 10385, chance = 150}, -- Zaoan helmet {id = 10387, chance = 770}, -- Zaoan legs {id = 10390, chance = 490}, -- Zaoan sword {id = 11651, chance = 110}, -- elite draken mail {id = 11657, chance = 910}, -- twiceslicer {id = 11658, chance = 7600}, -- draken sulphur {id = 11659, chance = 14030}, -- draken wristbands {id = 11660, chance = 16930}, -- broken draken mail {id = 11661, chance = 24670}, -- broken slicer {id = 11674, chance = 10}, -- cobra crown {id = 4033, chance = 600}, -- draken boots {id = 11691, chance = 80}, -- snake god's wristguard {id = 11693, chance = 20} -- blade of corruption } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -354}, {name ="combat", interval = 2000, chance = 10, type = COMBAT_FIREDAMAGE, minDamage = -240, maxDamage = -550, length = 4, spread = 3, effect = CONST_ME_EXPLOSIONHIT, target = false}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_FIREDAMAGE, minDamage = -200, maxDamage = -300, range = 7, shootEffect = CONST_ANI_FIRE, effect = CONST_ME_FIREAREA, target = true}, {name ="combat", interval = 2000, chance = 15, type = COMBAT_EARTHDAMAGE, minDamage = -280, maxDamage = -410, radius = 4, effect = CONST_ME_POFF, target = true}, -- {name ="soulfire", interval = 2000, chance = 10, target = false}, -- poison {name ="condition", type = CONDITION_POISON, interval = 2000, chance = 10, minDamage = -250, maxDamage = -320, range = 7, shootEffect = CONST_ANI_POISON, target = true} } monster.defenses = { defense = 45, armor = 45, {name ="combat", interval = 2000, chance = 15, type = COMBAT_HEALING, minDamage = 510, maxDamage = 600, effect = CONST_ME_MAGIC_BLUE, target = false} } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 40}, {type = COMBAT_EARTHDAMAGE, percent = 100}, {type = COMBAT_FIREDAMAGE, percent = 100}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 30}, {type = COMBAT_DEATHDAMAGE , percent = 30} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = true}, {type = "bleed", condition = false} } mType:register(monster)
--[[ Author: tochonement Email: tochonement@gmail.com 12.03.2021 --]] function gfconsole.show() if IsValid(gfconsole.frame) then return end gfconsole.frame = vgui.Create("GFConsole") end function gfconsole.reload_frame() local frame = gfconsole.frame if IsValid(frame) then frame:Remove() end gfconsole.show() end concommand.Add("gfconsole_reload_frame", gfconsole.reload_frame) local function toggle(_, cmd) local enable = (cmd == "+gfconsole") gfconsole.holding = enable if enable then gfconsole.show() end gui.EnableScreenClicker(enable) end concommand.Add("+gfconsole", toggle) concommand.Add("-gfconsole", toggle)
return require('lib.oop.generated.timerdialog')
local ObjectManager = require("managers.object.object_manager") buff = ScreenPlay:new { numberOfActs = 1, questString = "buff", questdata = Object:new { activePlayerName = "initial", } } registerScreenPlay("buff", true) function buff:start() self:spawnActiveAreas() end function buff:spawnActiveAreas() local pSpawnArea = spawnSceneObject("tatooine", "object/active_area.iff", 3441, 4, -4825, 0, 0, 0, 0, 0) if (pSpawnArea ~= nil) then local activeArea = LuaActiveArea(pSpawnArea) activeArea:setCellObjectID(0) activeArea:setRadius(25) createObserver(ENTEREDAREA, "buff", "notifySpawnArea", pSpawnArea) createObserver(EXITEDAREA, "buff", "notifySpawnAreaLeave", pSpawnArea) end end function buff:notifySpawnArea(pActiveArea, pMovingObject) if (not SceneObject(pMovingObject):isCreatureObject()) then return 0 end return ObjectManager.withCreatureObject(pMovingObject, function(player) if (player:isAiAgent()) then return 0 end if (player:isInCombat() ~= true) then --player:broadcastToServer("\\#00E604" .. player:getFirstName() .. "\\#63C8F9 Has entered the buff Zone!") player:sendSystemMessage("You have entered the buff zone!") player:removeAllStructureSkillMod() player:addStructureSkillMod("private_buff_mind", 125) player:addStructureSkillMod("private_med_battle_fatigue", 15) player:addStructureSkillMod("private_med_wound_mind", 15) player:addStructureSkillMod("private_medical_rating", 125) player:addStructureSkillMod("private_med_wound_mind", 20) player:addStructureSkillMod("private_buff_mind", 125) player:addStructureSkillMod("private_med_battle_fatigue", 5) player:addStructureSkillMod("private_med_wound_health", 125) player:addStructureSkillMod("private_med_wound_action", 125) player:addStructureSkillMod("private_safe_logout", 1) else player:sendSystemMessage("You must be out of combat to enter the buff zone!") player:teleport(3469, 5, -4883, 0) end return 0 end) end function buff:notifySpawnAreaLeave(pActiveArea, pMovingObject) if (not SceneObject(pMovingObject):isCreatureObject()) then return 0 end return ObjectManager.withCreatureObject(pMovingObject, function(player) if (player:isAiAgent()) then return 0 end if (player:isImperial() or player:isRebel() or player:isNeutral()) then player:sendSystemMessage("You have left the buff zone!") player:removeAllStructureSkillMod() end return 0 end) end
//----------------------------------------------------------------------------- // Name: CC_StringToChars // Desc: Converts a string or a single character into the appropriate character // codes, can output as a list of codes or a packet for the E-Gate. //----------------------------------------------------------------------------- local function CC_StringToChars (player, command, args) local adj = 0 local out = "%s" // Output usage if (table.getn (args) == 0) then Msg ("USAGE: stringtochars [PACKET] \"string\"\n Use PACKET to output in expression gate packet form.\n") return end // Select output mode if (string.upper (args[1]) == "PACKET") then adj = 1 out = "send(%s)" end // Loop through the arguments for i = 1 + adj, table.getn (args) do local fmt = "" local chars = { string.byte (args[i], 1, string.len (args[i])) } for j = 1, table.getn (chars) do if (string.len (fmt) > 0) then fmt = fmt .. ", " end fmt = fmt .. tostring (chars[j]) end Msg (string.format ("'%s' = %s\n", args[i], string.format (out, fmt))) end end concommand.Add ('stringtochars', CC_StringToChars)
-------------------------------------------------------------------------------- -- 81-717 Moscow controller panel -------------------------------------------------------------------------------- -- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o. -- Contains proprietary code. See license.txt for additional information. -------------------------------------------------------------------------------- Metrostroi.DefineSystem("81_717_Panel") function TRAIN_SYSTEM:Initialize() -- Выключатель батареи (ВБ) self.Train:LoadSystem("VB","Relay","Switch",{bass = true}) -- Buttons on the panel --self.Train:LoadSystem("DIPon","Relay","Switch", {bass = true}) self.Train:LoadSystem("Ring","Relay","Switch", {bass = true}) self.Train:LoadSystem("VozvratRP","Relay","Switch", {bass = true}) self.Train:LoadSystem("OtklBV","Relay","Switch", {bass = true}) self.Train:LoadSystem("OtklBVK","Relay","Switch", {normally_closed=true,bass = true}) self.Train:LoadSystem("RezMK","Relay","Switch", {bass = true}) self.Train:LoadSystem("VMK","Relay","Switch", {bass = true}) self.Train:LoadSystem("VAH","Relay","Switch", {bass = true}) self.Train:LoadSystem("VAD","Relay","Switch", {bass = true}) self.Train:LoadSystem("VUS","Relay","Switch", {bass = true}) self.Train:LoadSystem("VUD1","Relay","Switch", {bass = true }) self.Train:LoadSystem("VUD2","Relay","Switch", {normally_closed=true,bass = true }) -- Doors close self.Train:LoadSystem("VDL","Relay","Switch", {bass = true}) -- Doors left open self.Train:LoadSystem("KDL","Relay","Switch", {bass = true}) self.Train:LoadSystem("KDLR","Relay","Switch", {bass = true}) self.Train:LoadSystem("KDP","Relay","Switch", {bass = true}) self.Train:LoadSystem("KRZD","Relay","Switch", {bass = true}) self.Train:LoadSystem("KSN","Relay","Switch", {bass = true}) self.Train:LoadSystem("OtklAVU","Relay","Switch", {bass = true}) self.Train:LoadSystem("OVT","Relay","Switch", {bass = true}) self.Train:LoadSystem("ARS","Relay","Switch", {bass = true}) self.Train:LoadSystem("ARSR","Relay","Switch", {bass = true}) self.Train:LoadSystem("UOS","Relay","Switch", {bass = true}) self.Train:LoadSystem("VP","Relay","Switch", {bass = true}) self.Train:LoadSystem("ALSFreq","Relay","Switch",{bass=true}) self.Train:LoadSystem("ALS","Relay","Switch", {bass = true,normally_closed=true}) self.Train:LoadSystem("KVT","Relay","Switch", {bass = true}) self.Train:LoadSystem("KVTR","Relay","Switch", {bass = true}) self.Train:LoadSystem("KRP","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_UNch","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_ZS","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_G","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Radio","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_VPR","Relay","Switch", {bass = true,normally_closed = true}) self.Train:LoadSystem("R_Program1","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Program2","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Program1H","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Program2H","Relay","Switch", {bass = true}) self.Train:LoadSystem("RC1","Relay","Switch",{ bass = true,normally_closed = true }) self.Train:LoadSystem("Radio13","Relay","Switch", {bass = true}) self.Train:LoadSystem("ARS13","Relay","Switch", {bass = true}) -- Педаль бдительности (ПБ) self.Train:LoadSystem("PB","Relay","Switch", {bass = true}) ----------------- БЗОС ---------------- self.Train:LoadSystem("SAB1","Relay","Switch",{normally_closed=true, bass=true}) --Охранная сигнализация self.Train:LoadSystem("AIS","Relay","VA21-29") -- Автоматические выключатели (АВ) self.Train:LoadSystem("A11","Relay","VA21-29") self.Train:LoadSystem("A17","Relay","VA21-29") self.Train:LoadSystem("A44","Relay","VA21-29") self.Train:LoadSystem("A26","Relay","VA21-29") self.Train:LoadSystem("AR63","Relay","VA21-29") self.Train:LoadSystem("AS1","Relay","VA21-29") self.Train:LoadSystem("A21","Relay","VA21-29") self.Train:LoadSystem("A49","Relay","VA21-29") self.Train:LoadSystem("A27","Relay","VA21-29") self.Train:LoadSystem("A10","Relay","VA21-29") self.Train:LoadSystem("A53","Relay","VA21-29") self.Train:LoadSystem("A54","Relay","VA21-29") self.Train:LoadSystem("A84","Relay","VA21-29") self.Train:LoadSystem("A76","Relay","VA21-29") self.Train:LoadSystem("A48","Relay","VA21-29") self.Train:LoadSystem("A29","Relay","VA21-29") self.Train:LoadSystem("A46","Relay","VA21-29") self.Train:LoadSystem("A47","Relay","VA21-29") self.Train:LoadSystem("A79","Relay","VA21-29") self.Train:LoadSystem("A42","Relay","VA21-29") self.Train:LoadSystem("A74","Relay","VA21-29") self.Train:LoadSystem("A73","Relay","VA21-29") self.Train:LoadSystem("A71","Relay","VA21-29") self.Train:LoadSystem("A41","Relay","VA21-29") self.Train:LoadSystem("A45","Relay","VA21-29") self.Train:LoadSystem("A75","Relay","VA21-29") self.Train:LoadSystem("A58","Relay","VA21-29") self.Train:LoadSystem("A59","Relay","VA21-29") self.Train:LoadSystem("A43","Relay","VA21-29") self.Train:LoadSystem("A31","Relay","VA21-29") self.Train:LoadSystem("A32","Relay","VA21-29") self.Train:LoadSystem("A13","Relay","VA21-29") self.Train:LoadSystem("A1","Relay","VA21-29") self.Train:LoadSystem("A20","Relay","VA21-29") self.Train:LoadSystem("A25","Relay","VA21-29") self.Train:LoadSystem("A30","Relay","VA21-29") self.Train:LoadSystem("A56","Relay","VA21-29") self.Train:LoadSystem("A65","Relay","VA21-29") self.Train:LoadSystem("A2","Relay","VA21-29") self.Train:LoadSystem("A3","Relay","VA21-29") self.Train:LoadSystem("A4","Relay","VA21-29") self.Train:LoadSystem("A5","Relay","VA21-29") self.Train:LoadSystem("A6","Relay","VA21-29") self.Train:LoadSystem("A70","Relay","VA21-29") self.Train:LoadSystem("A14","Relay","VA21-29") self.Train:LoadSystem("A39","Relay","VA21-29") self.Train:LoadSystem("A28","Relay","VA21-29") self.Train:LoadSystem("A38","Relay","VA21-29") self.Train:LoadSystem("A22","Relay","VA21-29") self.Train:LoadSystem("A8","Relay","VA21-29") self.Train:LoadSystem("A12","Relay","VA21-29") self.Train:LoadSystem("A16","Relay","VA21-29") self.Train:LoadSystem("A37","Relay","VA21-29") self.Train:LoadSystem("A51","Relay","VA21-29") self.Train:LoadSystem("A24","Relay","VA21-29") self.Train:LoadSystem("A19","Relay","VA21-29") self.Train:LoadSystem("A66","Relay","VA21-29") self.Train:LoadSystem("A18","Relay","VA21-29") self.Train:LoadSystem("A40","Relay","VA21-29") self.Train:LoadSystem("A80","Relay","VA21-29") self.Train:LoadSystem("A50","Relay","VA21-29") self.Train:LoadSystem("A52","Relay","VA21-29") self.Train:LoadSystem("AV2","Relay","VA21-29") self.Train:LoadSystem("AV3","Relay","VA21-29") self.Train:LoadSystem("AV4","Relay","VA21-29") self.Train:LoadSystem("AV5","Relay","VA21-29") self.Train:LoadSystem("AV6","Relay","VA21-29") self.Train:LoadSystem("AV1","Relay","VA21-29") self.Train:LoadSystem("A55","Relay","VA21-29") self.Train:LoadSystem("A57","Relay","VA21-29") self.Train:LoadSystem("A60","Relay","VA21-29") self.Train:LoadSystem("A81","Relay","VA21-29") self.Train:LoadSystem("A7","Relay","VA21-29") self.Train:LoadSystem("A9","Relay","VA21-29") self.Train:LoadSystem("A68","Relay","VA21-29") self.Train:LoadSystem("A72","Relay","VA21-29") --Вагонные self.Train:LoadSystem("A15","Relay","VA21-29") self.Train:LoadSystem("KDLK","Relay","Switch", { bass = true,normally_closed = true }) self.Train:LoadSystem("KDLRK","Relay","Switch", { bass = true,normally_closed = true }) self.Train:LoadSystem("KDPK","Relay","Switch", { bass = true,normally_closed = true }) self.Train:LoadSystem("KAHK","Relay","Switch", { bass = true,normally_closed = true }) -- 81-717 special self.Train:LoadSystem("BPSNon","Relay","Switch", { bass = true }) self.Train:LoadSystem("L_1","Relay","Switch",{bass = true}) self.Train:LoadSystem("L_2","Relay","Switch",{bass = true}) self.Train:LoadSystem("L_3","Relay","Switch",{bass = true}) self.Train:LoadSystem("L_4","Relay","Switch",{bass = true}) self.Train:LoadSystem("DoorSelect","Relay","Switch", { bass = true, normally_closed = false }) self.Train:LoadSystem("VZ1","Relay","Switch", {bass = true}) self.Train:LoadSystem("KAH","Relay","Switch", {bass = true}) self.Train:LoadSystem("VBD","Relay","Switch",{bass = true,normally_closed=true}) self.Train:LoadSystem("Wiper","Relay","Switch") self.Train:LoadSystem("PVK","Relay","Switch",{maxvalue=2,bass=true}) self.Train:LoadSystem("V11","Relay","Switch",{bass=true}) self.Train:LoadSystem("V12","Relay","Switch",{bass=true}) self.Train:LoadSystem("V13","Relay","Switch",{bass=true}) self.Train:LoadSystem("KV1","Relay","Switch",{bass=true}) self.Train:LoadSystem("KV2","Relay","Switch",{bass=true}) self.Train:LoadSystem("KV3","Relay","Switch",{bass=true}) self.Train:LoadSystem("R1","Relay","Switch",{bass=true,close_time=2.3}) self.V1 = 0 self.LUDS = 0 self.RedLight2 = 0 self.RedLight1 = 0 self.Headlights1 = 0 self.Headlights2 = 0 self.EqLights = 0 self.CabLights = 0 self.PanelLights = 0 self.CabinLight = 0 self.EmergencyLights = 0 self.MainLights = 0 self.DoorsLeft = 0 self.DoorsRight = 0 self.DoorsW = 0 self.GreenRP = 0 self.BrW = 0 self.AVU = 0 self.L1 = 0 self.LKVP = 0 self.RZP = 0 self.KUP = 0 self.BrT = 0 self.LSN = 0 self.Ring = 0 self.SD = 0 self.LST = 0 self.LVD = 0 self.LKVD = 0 self.LhRK = 0 self.KVC = 0 self.SD = 0 self.TW18 = 0 self.KT = 0 self.LN = 0 self.RS = 0 self.AR04 = 0 self.AR0 = 0 self.AR40 = 0 self.AR60 = 0 self.AR70 = 0 self.AR80 = 0 self.M1_3 = 0 self.M4_7 = 0 self.M8 = 0 self.AnnouncerPlaying = 0 self.AnnouncerBuzz = 0 self.VPR = 0 self.CBKIPower = 0 self.PCBKPower = 0 end function TRAIN_SYSTEM:Outputs() return { "V1","LUDS","RedLight2","RedLight1","Headlights1","Headlights2","EqLights","CabLights","EqLights","PanelLights","CabinLight","EmergencyLights","MainLights","DoorsLeft","DoorsRight","DoorsW","GreenRP","BrW","AVU","LKVP","RZP","KUP","BrT","LSN","Ring","SD","LST","LVD","LhRK","KVC","SD","TW18", "KT", "LKVD","LN","RS","AR04","AR0","AR40","AR60","AR70","AR80","L1","M1_3","M4_7","M8", "AnnouncerPlaying","AnnouncerBuzz","VPR", "CBKIPower","PCBKPower"} end TRAIN_SYSTEM.AVMap = { "A11","A17","A44","A26","AR63","A61", "A21","A49","A27","A10","A53","A54", "A84","A76","A48","AV1","A29","A46", "A47","A79","A42","A74","A73","A71", "A41","A45","A75","A58","A59","A43", "A31","A32","A13","A1","A20","A25", "A30","A56","A65","A2","A3","A4","A5", "A6","A70","A14","A39","A28","A38","A22", "A8","A12","A16","A37","A51","A24","A19", "A66","A18","A40","A80","A50","A52","AV2", "AV3","AV4","AV5","AV6","A55","A57","A60", "A81","A7","A9","A68","A72","A15", }
require 'torch' require 'image' require 'paths' require 'nn' require 'inn' require 'image' require 'xlua' require 'nn' require 'loadcaffe' local gp = require 'gpath' local nn_utils = {} nn_utils.mean = torch.Tensor({129.67, 114.43, 107.26}) nn_utils.nmean = nn_utils.mean:clone():div(255) ------------------------------------------------------------------- -- generate an image of a particular size with values scaled in [0, 1] and -- then mean substracted function nn_utils.normalize(im, width, height, nmean) nmean = nmean or nn_utils.nmean assert((#im)[1] == (#nmean)[1]) -- scale the image local normalized = image.scale(im, width, height) -- normalize it to [0, 1] if normalized:max() > 1 then normalized:div(255) end -- mean subtraction for i = 1, (#nmean)[1] do normalized[i]:csub(nmean[i]) end return normalized end -- add mean value back function nn_utils.unnormalize(im, nmean) nmean = nmean or nn_utils.nmean assert((#im)[1] == (#nmean)[1]) local unnorm = im:clone() for i = 1, (#nmean)[1] do unnorm[i]:add(nmean[i]) end return unnorm end function nn_utils.loadNormalizeIm(imName, numChn, width, height) numChn = numChn or 3 local im = image.load(imName) if im:size(1) == 1 and numChn == 3 then im = torch.repeatTensor(im, 3, 1, 1) end -- normalize image im = nn_utils.normalize(im, width, height, mean) return im end function nn_utils.toCaffeInput(input, fullScale, swapChn, width, height, mean) assert(input:dim() == 4 and input:size(2) == 3 or input:dim() == 3 and input:size(1) == 3) fullScale = fullScale or true swapChn = swapChn or true width = width or 227 height = height or 227 mean = mean or nn_utils.mean if input:dim() == 4 then local bs = input:size(1) local ch = input:size(2) local ht = input:size(3) local wd = input:size(4) input = image.scale(input:view(bs * ch, ht, wd), width, height):view(bs, ch, height, width) else local ch = input:size(1) local ht = input:size(2) local wd = input:size(3) input = image.scale(input, width, height) end local maxV = input:max() local minV = input:min() if fullScale then if math.abs(maxV) <= 1 and math.abs(minV) <= 1 then input:mul(255) end if maxV >= 0.5 and minV >= 0 then if input:dim() == 4 then for i = 1, 3 do input[{{}, i, {}, {}}]:csub(mean[i]) end else for i = 1, 3 do input[{i, {}, {}}]:csub(mean[i]) end end end else if math.abs(maxV) > 1 or math.abs(minV) > 1 then input:div(255) end if maxV >= 0.5 and minV >= 0 then if input:dim() == 4 then for i = 1, 3 do input[{{}, i, {}, {}}]:csub(mean[i]/255) end else for i = 1, 3 do input[{i, {}, {}}]:csub(mean[i]/255) end end end end if swapChn then if input:dim() == 4 then local tmp = input[{{}, 1, {}, {}}]:clone() input[{{}, 1, {}, {}}] = input[{{}, 3, {}, {}}] input[{{}, 3, {}, {}}] = tmp else local tmp = input[{1, {}, {}}]:clone() input[{1, {}, {}}] = input[{3, {}, {}}] input[{3, {}, {}}] = tmp end end return input end ----------------------------------------------------------------------------- -- function nn_utils.loadLeNet(net) net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'lenet') return loadcaffe.load(paths.concat(modelPath, 'lenet.prototxt'), paths.concat(modelPath, 'lenet_iter_10000.caffemodel'), net) end function nn_utils.loadAlexNet(net) net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'bvlc_alexnet') return loadcaffe.load(paths.concat(modelPath, 'deploy.prototxt'), paths.concat(modelPath, 'bvlc_alexnet.caffemodel'), net) end -- not working function nn_utils.loadPlacesAlexNet(net) print('Warning: loadFasterRCNNZF is not working') local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'places205_alexnet') return loadcaffe.load(paths.concat(modelPath, 'places205CNN_deploy_torch.prototxt'), paths.concat(modelPath, 'places205CNN_iter_300000.caffemodel'), net) end -- not working function nn_utils.loadHybridAlexNet(net) print('Warning: loadFasterRCNNZF is not working') local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'hybrid_alexnet') return loadcaffe.load(paths.concat(modelPath, 'hybridCNN_deploy.prototxt'), paths.concat(modelPath, 'hybridCNN_iter_700000.caffemodel'), net) end function nn_utils.loadCaffeNet(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'bvlc_reference_caffenet') return loadcaffe.load(paths.concat(modelPath, 'deploy.prototxt'), paths.concat(modelPath, 'bvlc_reference_caffenet.caffemodel'), net) end function nn_utils.loadVGG16(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'vgg_16') return loadcaffe.load(paths.concat(modelPath, 'VGG_ILSVRC_16_layers_deploy.prototxt'), paths.concat(modelPath, 'VGG_ILSVRC_16_layers.caffemodel'), net) end function nn_utils.loadVGG19(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'vgg_19') return loadcaffe.load(paths.concat(modelPath, 'VGG_ILSVRC_19_layers_deploy.prototxt'), paths.concat(modelPath, 'VGG_ILSVRC_19_layers.caffemodel'), net) end function nn_utils.loadGoogleNet(net) local modelPath = paths.concat(gp.caffe_model, 'googlenet') return torch.load(paths.concat(modelPath, 'inceptionv3.net')) end function nn_utils.loadResNet18() local modelPath = paths.concat(gp.caffe_model, 'resnet_18') return torch.load(paths.concat(modelPath, 'resnet-18.t7')) end function nn_utils.loadResNet34() local modelPath = paths.concat(gp.caffe_model, 'resnet_34') return torch.load(paths.concat(modelPath, 'resnet-34.t7')) end function nn_utils.loadResNet50() local modelPath = paths.concat(gp.caffe_model, 'resnet_50') return torch.load(paths.concat(modelPath, 'resnet-50.t7')) end function nn_utils.loadResNet101() local modelPath = paths.concat(gp.caffe_model, 'resnet_101') return torch.load(paths.concat(modelPath, 'resnet-101.t7')) end function nn_utils.loadResNet152() local modelPath = paths.concat(gp.caffe_model, 'resnet_152') return torch.load(paths.concat(modelPath, 'resnet-152.t7')) end function nn_utils.loadResNet200() local modelPath = paths.concat(gp.caffe_model, 'resnet_200') return torch.load(paths.concat(modelPath, 'resnet-200.t7')) end function nn_utils.loadRCNN(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'bvlc_reference_rcnn_ilsvrc13') return loadcaffe.load(paths.concat(modelPath, 'deploy.prototxt'), paths.concat(modelPath, 'bvlc_reference_rcnn_ilsvrc13.caffemodel'), net) end function nn_utils.loadFastRCNNCaffeNet() local modelPath = paths.concat(gp.caffe_model, 'fastrcnn') return torch.load(paths.concat(modelPath, 'caffenet_fast_rcnn_iter_40000.t7')):unpack() end function nn_utils.loadFastRCNNVGG16() local modelPath = paths.concat(gp.caffe_model, 'fastrcnn') return torch.load(paths.concat(modelPath, 'vgg16_fast_rcnn_iter_40000.t7')):unpack() end function nn_utils.loadFCN32s(net) local modelPath = paths.concat(gp.caffe_model, 'fcn_32s_pascal') return torch.load(paths.concat(modelPath, 'fcn_32s_pascal.t7')) end function nn_utils.loadFCN32sRaw(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'fcn_32s_pascal') return loadcaffe.load(paths.concat(modelPath, 'fcn-32s-pascal-deploy.prototxt'), paths.concat(modelPath, 'fcn-32s-pascal.caffemodel'), net) end function nn_utils.loadNIN(net) local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'nin') return loadcaffe.load(paths.concat(modelPath, 'train_val.prototxt'), paths.concat(modelPath, 'nin_imagenet_conv.caffemodel'), net) end -- not working function nn_utils.loadFasterRCNNZF(net) print('Warning: loadFasterRCNNZF is not working') local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'faster_rcnn_VOC0712_ZF') return loadcaffe.load(paths.concat(modelPath, 'deploy.prototxt'), paths.concat(modelPath, 'ZF_faster_rcnn_final.caffemodel'), net) end -- not working function nn_utils.loadFasterRCNNVGG(net) print('Warning: loadFasterRCNNVGG is not working') local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'faster_rcnn_VOC0712_vgg_16layers') return loadcaffe.load(paths.concat(modelPath, 'deploy.prototxt'), paths.concat(modelPath, 'VGG16_faster_rcnn_final.caffemodel'), net) end -- not working function nn_utils.loadHED(net) print('Warning: loadHED is not working') local net = net or 'nn' local modelPath = paths.concat(gp.caffe_model, 'hed') return loadcaffe.load(paths.concat(modelPath, 'hed.prototxt'), paths.concat(modelPath, 'hed_bsds.caffemodel'), net) end ------------------------------------------------------------------------ function nn_utils.sanitize(net) local list = net:listModules() for nameL, val in ipairs(list) do for name, field in pairs(val) do if torch.type(field) == 'cdata' then val[name] = nil end if name == 'homeGradBuffers' then val[name] = nil end if name == 'input_gpu' then val['input_gpu'] = {} end if name == 'gradOutput_gpu' then val['gradOutput_gpu'] = {} end if name == 'gradInput_gpu' then val['gradInput_gpu'] = {} end --if (name == 'output' or name == 'gradInput' or -- name == 'fgradInput' or name == 'finput' or -- name == 'gradWeight' or name == 'gradBias') then if (name == 'output' or name == 'gradInput' or name == 'fgradInput' or name == 'finput') then if torch.type(field) == 'table' then val[name] = {} else val[name] = field.new() end end if name == 'buffer' or name == 'buffer2' or name == 'normalized' or name == 'centered' or name == 'addBuffer' then val[name] = nil end end end return net end ------------------------------------------------------------------------- function nn_utils.tensorDimsStr (A) if torch.isTensor(A) then local tmp = A:size(1) for iDim = 2,A:nDimension() do tmp = tmp .. ' x ' .. A:size(iDim) end return tmp else local tmp = 'Length ' .. #A .. ' Table\n' for i = 1, #A do tmp = tmp .. 'Table[' .. i ..']: ' .. nn_utils.tensorDimsStr(A[i]) .. '\n' end return tmp end end -- A multi-concat function. -- Replaces the 'concat' in torch, which can't deal with cuda tensors function nn_utils.concatTensors (tensors, outputDimension) local nTensors = table.getn(tensors) local sumOutputSizes = 0 for iTensor = 1,nTensors do sumOutputSizes = sumOutputSizes + tensors[iTensor]:size(outputDimension) end local outputSize = tensors[1]:size() outputSize[outputDimension] = sumOutputSizes -- We clone and then resize to make sure it's the right kind of tensor. -- TODO is there a better way to do this? local res = tensors[1]:clone() res:resize (outputSize) local curOutputOffset = 1 for iTensor = 1,nTensors do local accessor = {} for j = 1,outputSize:size() do accessor[j] = {} end local outputDimSize = tensors[iTensor]:size(outputDimension) accessor[outputDimension] = {curOutputOffset, curOutputOffset + outputDimSize - 1} res[accessor]:copy(tensors[iTensor]) curOutputOffset = curOutputOffset + outputDimSize end return res end function nn_utils.dumpNetwork (layer, inputData, prefix) prefix = prefix or '' local prefixExtension = " " local output local strLayer = tostring(layer) if (strLayer:sub(1,13) == 'nn.Sequential') then local nLayers = layer:size() print (prefix .. 'Layer type: nn.Sequential (' .. nLayers .. ')') print (prefix .. 'Input: ' .. nn_utils.tensorDimsStr(inputData)) local layerInput = inputData for iLayer = 1,nLayers do print (prefix .. 'Sequential layer ' .. iLayer) local curLayer = layer:get(iLayer) local res = nn_utils.dumpNetwork (curLayer, layerInput, prefix .. prefixExtension) layerInput = res end output = layerInput elseif (strLayer:sub(1,16) ~= "nn.ParallelTable" and strLayer:sub(1,11) == "nn.Parallel") then local nLayers = table.getn(layer.modules) print (prefix .. 'Layer type: nn.Parallel (' .. nLayers .. ')') local inputDimension = layer.inputDimension local outputDimension = layer.outputDimension print (prefix .. 'Split on ' .. inputDimension) print (prefix .. 'Input: ' .. nn_utils.tensorDimsStr(inputData)) local layerRes = {} local sumOutputSizes = 0 for iLayer = 1,nLayers do print (prefix .. 'Parallel layer ' .. iLayer) local curLayer = layer:get(iLayer) local curInput = inputData:select(inputDimension, iLayer) local res = nn_utils.dumpNetwork (curLayer, curInput, prefix .. prefixExtension) layerRes[iLayer] = res end output = nn_utils.concatTensors (layerRes, outputDimension) else print (prefix .. 'Layer type: ' .. strLayer) print (prefix .. 'Input: ' .. nn_utils.tensorDimsStr(inputData)) output = layer:forward(inputData) end if torch.isTensor(output) and output:ne(output):sum() > 0 then print( prefix .. '!!!!!!!!!!!!!!!!!!!!!!! Found NaN in output !!!!!!!!!!!!!!!!!!!!!!!') end print (prefix .. 'Output: ' .. nn_utils.tensorDimsStr(output)) return output end local function appendToPrefix (oldPrefix, newStuff) if (oldPrefix and oldPrefix ~= '') then return oldPrefix .. '_' .. newStuff; else return newStuff; end end -- Assumes that the data matrix is set up as -- level 1, channel 1 -- level 1, channel 2 -- ... -- level 2, channel 1 -- level 2, channel 2 -- ... function nn_utils.dumpIntermediateWeights (layer, inputData, pyramidLevelSizes, channelNames, outputImagesDir, filePrefix) local output local strLayer = tostring(layer) if (strLayer:sub(1,13) == 'nn.Sequential') then local nLayers = layer:size() local layerInput = inputData for iLayer = 1,nLayers do local curLayer = layer:get(iLayer) local newPrefix = appendToPrefix (filePrefix, 'layer' .. iLayer) local res = nn_utils.dumpIntermediateWeights (curLayer, layerInput, pyramidLevelSizes, channelNames, outputImagesDir, newPrefix) layerInput = res end output = layerInput elseif (strLayer:sub(1,11) == "nn.Parallel") then local nLayers = table.getn(layer.modules) local inputDimension = layer.inputDimension local outputDimension = layer.outputDimension local combinedRes; local nPyramidLevels = table.getn (pyramidLevelSizes) local nChannels = table.getn (channelNames) local layerRes = {} assert (nLayers == nPyramidLevels * nChannels) for iLevel = 1,nPyramidLevels do for jChannel = 1,nChannels do local iLayer = (iLevel-1) * nChannels + jChannel local curLayer = layer:get(iLayer) local curInput = inputData:select(inputDimension, iLayer) local newPrefix = appendToPrefix (filePrefix, 'level' .. iLevel .. '_' .. channelNames[jChannel]) local res = nn_utils.dumpIntermediateWeights (curLayer, curInput, pyramidLevelSizes, channelNames, outputImagesDir, newPrefix) layerRes[iLayer] = res end end output = nn_utils.concatTensors (layerRes, outputDimension) elseif (strLayer == "nn.SpatialConvolution" or strLayer == "nn.SpatialConvolutionMM") then -- For convolution layers, save out the weights and stuff: local nInputPlane = layer["nInputPlane"] local nOutputPlane = layer["nOutputPlane"] local kw = layer["kW"] local kh = layer["kH"] local weightOrig = layer["weight"] local w = torch.reshape (weightOrig, torch.LongStorage{nOutputPlane,nInputPlane,kw,kh}) local nChannels = table.getn (channelNames) -- Only do this for the first layer: if (w:size(2) == nChannels) then local filename = appendToPrefix (filePrefix, '_weights.png') image.save (paths.concat(outputImagesDir, filename), image.toDisplayTensor {input=w:select(2,1), padding=3}) end -- Only show the first 10 activations: local nActivationImages = math.min (nOutputPlane, 10) output = layer:forward(inputData) for iOutputPlane = 1,nActivationImages do local filename = appendToPrefix (filePrefix, '_activations_plane' .. iOutputPlane .. '.png') image.save (paths.concat (outputImagesDir, filename), image.toDisplayTensor {input=output[{{},iOutputPlane,{},{}}], padding=3}) end elseif (strLayer == 'nn.View') then output = layer:forward(inputData) if (output:nDimension() == 4 and output:size(2) == 1) then local filename = appendToPrefix (filePrefix, '_view.png') image.save (paths.concat (outputImagesDir, filename), image.toDisplayTensor {input=output[{{},1,{},{}}], padding=0}) end else output = layer:forward(inputData) end return output end function nn_utils.customLCN(inputs, kernel, threshold, thresval) assert (inputs:dim() == 4, "Input should be of the form nSamples x nChannels x width x height") local padH = math.floor(kernel:size(1)/2) local padW = padH -- normalize the kernel kernel:div(kernel:sum()) local meanestimator = nn.Sequential() meanestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) meanestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(1), kernel:size(1), 1)) meanestimator:add(nn.SpatialConvolution(1, 1, 1, kernel:size(1), 1)) local stdestimator = nn.Sequential() stdestimator:add(nn.Square()) stdestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH)) stdestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(1), kernel:size(1), 1)) stdestimator:add(nn.SpatialConvolution(1, 1, 1, kernel:size(1))) stdestimator:add(nn.Sqrt()) for i = 1,1 do meanestimator.modules[2].weight[i]:copy(kernel) meanestimator.modules[3].weight[1][i]:copy(kernel) stdestimator.modules[3].weight[i]:copy(kernel) stdestimator.modules[4].weight[1][i]:copy(kernel) end meanestimator.modules[2].bias:zero() meanestimator.modules[3].bias:zero() stdestimator.modules[3].bias:zero() stdestimator.modules[4].bias:zero() -- Run the meanestimator on a bunch of ones to figure out the sum of the kenrel -- (This is pretty wasteful for large number of samples N of Nx1xKxK.) local coef = meanestimator:updateOutput(inputs.new():resizeAs(inputs):fill(1)) coef = coef:clone() -- Take the kernel weighted local sums local localSums = meanestimator:updateOutput(inputs) -- Divide by the response of the kernel on ones (effectively, dividing by the kernel sum) local adjustedSums = nn.CDivTable():updateOutput{localSums, coef} -- Subtract tout the kernel weigthed adjusted sums local meanSubtracted = nn.CSubTable():updateOutput{inputs, adjustedSums} -- Take the mean subtracted output and divide out the kernel weighted standard deviation local localStds = stdestimator:updateOutput(meanSubtracted) local adjustedStds = nn.CDivTable():updateOutput{localStds, coef} local thresholdedStds = nn.Threshold(threshold, thresval):updateOutput(adjustedStds) local outputs = nn.CDivTable():updateOutput{meanSubtracted, thresholdedStds} return outputs end function nn_utils.originalLCN(inputs, kernel, threshold, thresval) local normalization = nn.SpatialContrastiveNormalization(1, kernel, threshold, thresval) local outputs = inputs:clone() for i=1,inputs:size(1) do outputs[i] = normalization:forward(inputs[i]) xlua.progress(i, inputs:size(1)) end return outputs end function nn_utils.testLCN() local neighborhood = image.gaussian1D(7) local inputs = torch.randn(100, 1, 50, 50) local timer = torch.Timer() timer:reset() local originalOutputs = nn_utils.originalLCN(inputs, neighborhood, 1, 1) print('Original LCN took : ' .. timer:time().real .. ' seconds') timer:reset() local customOutputs = nn_utils.customLCN(inputs, neighborhood, 1, 1) print(' Custom LCN took : ' .. timer:time().real .. ' seconds') local norm = (customOutputs - originalOutputs):norm() print('Difference between original and custom LCN implementations : '..norm) end local function ConvInit(model, name) for k, v in pairs(model:findModules(name)) do local n = v.kW * v.kH * v.nOutputPlane v.weight:normal(0, math.sqrt(2 / n)) if nn.version >= 4000 then v.bias = nil v.gradBias = nil else v.bias:zero() end end end local function BNInit(model, name) for k, v in pairs(model:findModules(name)) do v.weight:fill(1) v.bias:zero() end end function nn_utils.init(model, opt) ConvInit(model, 'nn.SpatialConvolution') ConvInit(model, 'nn.SpatialConvolution') BNInit(model, 'fbnn.SpatialBatchNormalization') BNInit(model, 'nn.SpatialBatchNormalization') BNInit(model, 'nn.SpatialBatchNormalization') for k, v in pairs(model:findModules('nn.Linear')) do v.bias:zero() end end function nn_utils.nnize(model, opt) model:cuda() nn.convert(model, nn) if opt.nn == 'deterministic' then model:apply(function(m) if m.setMode then m:setMode(1,1,1) end end) end end return nn_utils
local exp_requirement_for_levelup={} for i=1,100 do exp_requirement_for_levelup[i]=200*i end local player=class() function player:ctor() self.class_name="player" self.name="angus" self.icon=nil self.money=2000 self.level=1 self.exp=0 self.story=0 self.ship=_ship[1].new() self.itembox={[1]={},[2]={},[3]={}} end function player:change_name(name)--改变玩家姓名 self.name=name return true end function player:get_item(item)--获得道具 if item.class_name=="weapon" then assert(table.insert(self.weapon_box,item),"weapon_box insert failed") return true elseif item.class_name=="member" then assert(table.insert(self.member_box,item),"member_box insert failed") return true elseif item.class_name=="battleship" then assert(table.insert(self.member_box,item),"battleship_box insert failed") return true end end function player:use_item(item)--使用道具 item.useon(self) end function player:get_exp(exp)--获得经验值 self.exp=self.exp+exp if self.exp>=exp_requirement_for_levelup[self.level+1] then self.exp=self.exp-exp_requirement_for_levelup[self.level+1] self.level=self.level+1 end return true end function player:get_money(money)--获得金钱 self.money=self.money+money return true end function player:save_data()--存档 end function player:load_data()--读档 end return player
local null_ls = require("null-ls") local helpers = require("null-ls.helpers") return helpers.make_builtin({ name = "sqlfluff", meta = { url = "https://github.com/sqlfluff/sqlfluff", description = "A SQL linter and auto-formatter for Humans", notes = { "SQLFluff needs a mandatory `--dialect` argument. Use `extra_args` to add yours. `extra_args` can also be a function to build more sophisticated logic.", }, usage = [[ local sources = { null_ls.builtins.diagnostics.sqlfluff.with({ extra_args = {"--dialect", "postgres"} -- change to your dialect }) }]], }, method = null_ls.methods.DIAGNOSTICS, filetypes = { "sql" }, generator_opts = { command = "sqlfluff", args = { "lint", "-f", "github-annotation", "-n", "--disable_progress_bar", "-", }, from_stderr = true, to_stdin = true, format = "json", check_exit_code = function(c) return c <= 1 end, on_output = helpers.diagnostics.from_json({ attributes = { row = "line", col = "start_column", end_col = "end_column", severity = "annotation_level", message = "message", }, severities = { helpers.diagnostics.severities["information"], helpers.diagnostics.severities["warning"], helpers.diagnostics.severities["error"], helpers.diagnostics.severities["hint"], }, }), }, factory = helpers.generator_factory, })
require "common/class" require "Entity" Camera = buildClass(Entity) function Camera:_init( ) Entity._init(self) -- auto-calculated values self.scale = 1 self.offset = {} self.offset.x = 0 self.offset.y = 0 self.width = 1 self.height = 1 self.subject = nil self.bound = {} self.bound.xmin = 0 self.bound.xmax = 0 self.bound.ymax = 0 self.bound.ymin = 0 end -- -- Adjust to window resizes -- function Camera:onWindowResize( w, h ) local room_ratio = self.width / self.height local calc_width = h * room_ratio local calc_height = w / room_ratio if calc_height > h then -- window height is smaller of the two, so scale from that self.scale = h / self.height self.offset.y = 0 self.offset.x = (w - (self.width * self.scale)) / 2 else -- window width is smaller, of the two, so scale from that self.scale = w / self.width self.offset.x = 0 self.offset.y = (h - (self.height * self.scale)) / 2 end end function Camera:registerWithSecretary(secretary) Entity.registerWithSecretary(self, secretary) -- Register for event callbacks secretary:registerEventListener(self, self.adjustCanvas, EventType.PRE_DRAW) secretary:registerEventListener(self, self.onWindowResize, EventType.WINDOW_RESIZE) secretary:registerEventListener(self, self.onStep, EventType.STEP) return self end function Camera:drawingPoint(x, y) x = x or 0 y = y or 0 return (x - self.offset.x) / self.scale, (y + self.offset.y) / self.scale end function Camera:drawingScale(w, h) w = w or 1 h = h or 1 return w * self.scale, h * self.scale end -- Adjust love's drawing offset and scale function Camera:adjustCanvas( ) love.graphics.origin() love.graphics.translate( -self.offset.x, -self.offset.y ) love.graphics.scale( self.scale, self.scale ) end function Camera:setDimensions(w, h) self.width = w or 1 self.height = h or 1 love.window.setMode(self.width, self.height, {resizable=true}) end function Camera:onStep( ) if self.subject ~= nil then local x, y, z = self.subject:getPosition() self.offset.y = y - self.height / 2 end if self.offset.y < self.bound.ymin then self.offset.y = self.bound.ymin elseif self.offset.y + self.height > self.bound.ymax then self.offset.y = self.bound.ymax - self.height elseif self.offset.x < self.bound.xmin then self.offset.x = self.bound.xmin elseif self.offset.x > self.bound.xmax - self.width then self.offset.x = self.bound.xmax - self.width end end function Camera:track(object) assertType(object, "object", PhysObject) self.subject = object end
------------------------ -- Graphics functions. -- @util graphics local graphics = {} local lg = love.graphics -- http://love2d.org/forums/viewtopic.php?f=4&t=77599 function graphics.roundRectangle(mode, x, y, w, h, rd, s) local r, g, b, a = lg.getColor() local rd = rd or math.min(w, h)/4 local s = s or 32 local l = lg.getLineWidth() local corner = 1 local function mystencil() lg.setColor(255, 255, 255, 255) if corner == 1 then lg.rectangle("fill", x-l, y-l, rd+l, rd+l) elseif corner == 2 then lg.rectangle("fill", x+w-rd+l, y-l, rd+l, rd+l) elseif corner == 3 then lg.rectangle("fill", x-l, y+h-rd+l, rd+l, rd+l) elseif corner == 4 then lg.rectangle("fill", x+w-rd+l, y+h-rd+l, rd+l, rd+l) elseif corner == 0 then lg.rectangle("fill", x+rd, y-l, w-2*rd+l, h+2*l) lg.rectangle("fill", x-l, y+rd, w+2*l, h-2*rd+l) end end lg.setStencil(mystencil) lg.setColor(r, g, b, a) lg.circle(mode, x+rd, y+rd, rd, s) lg.setStencil() corner = 2 lg.setStencil(mystencil) lg.setColor(r, g, b, a) lg.circle(mode, x+w-rd, y+rd, rd, s) lg.setStencil() corner = 3 lg.setStencil(mystencil) lg.setColor(r, g, b, a) lg.circle(mode, x+rd, y+h-rd, rd, s) lg.setStencil() corner = 4 lg.setStencil(mystencil) lg.setColor(r, g, b, a) lg.circle(mode, x+w-rd, y+h-rd, rd, s) lg.setStencil() corner = 0 lg.setStencil(mystencil) lg.setColor(r, g, b, a) lg.rectangle(mode, x, y, w, h) lg.setStencil() end function graphics.ellipse( mode, x, y, rx, ry, angle, ox, oy ) -- x & y are upper left corner -- for centering ox = rx/2 & oy = ry/2 ry = ry or rx ox = ox or 0 oy = oy or 0 angle = angle or 0 lg.push() lg.translate( x, y ) lg.rotate( angle ) local segments = ( rx + ry ) / 10 local vertices = {} for i = 0, 2 * math.pi * ( 1 - 1 / segments ), 2 * math.pi / segments do vertices[#vertices+1] = rx * (1 + math.cos(i) ) / 2 - ox vertices[#vertices+1] = ry * (1 + math.sin(i) ) / 2 - oy end lg.polygon( mode, vertices ) lg.pop() end function graphics.arrow( x1, y1, x2, y2, arrow_head_length, arrow_head_width ) local v1 = Vector(x1, y1) local v2 = Vector(x2, y2) local lv = v2 - v1 lv:trim( lv:length() - arrow_head_length ) local bv = Vector(v1.x+lv.x, v1.y+lv.y) local pv = lv:normalize():perpendicular() local t1x, t1y = (bv + (pv * (arrow_head_width / 2))):unpack() local t2x, t2y = (bv - (pv * (arrow_head_width / 2))):unpack() lg.line(v1.x, v1.y, bv.x, bv.y) lg.polygon("fill", t1x, t1y, t2x, t2y, x2, y2) end return graphics
-------------------------------------------------------------------------------- -- ZASM2 compatible syntax -------------------------------------------------------------------------------- -- Syntax lookup for vector definitions local VectorSyntax = { FLOAT = { {} }, SCALAR = { {} }, VECTOR1F = { {"x"} }, VECTOR2F = { {"x"},{"y"} }, VECTOR3F = { {"x"},{"y"},{"z"} }, VECTOR4F = { {"x"},{"y"},{"z"},{"w"} }, VEC1F = { {"x"} }, VEC2F = { {"x"},{"y"} }, VEC3F = { {"x"},{"y"},{"z"} }, VEC4F = { {"x"},{"y"},{"z"},{"w"} }, UV = { {"x","u"},{"y","v"} }, COLOR = { {"x","r"},{"y","g"},{"z","b"},{"w","a"} }, MATRIX = {}, } for i=0,15 do VectorSyntax.MATRIX[i+1] = {tostring(i)} end -------------------------------------------------------------------------------- -- Compile an opcode (called after if self:MatchToken(TOKEN.OPCODE)) function HCOMP:Opcode() local TOKEN = self.TOKEN local opcodeName = self.TokenData local opcodeNo = self.OpcodeNumber[self.TokenData] local operandCount = self.OperandCount[opcodeNo] -- Check if opcode is obsolete or old if self.OpcodeObsolete[opcodeName] then self:Warning("Instruction \""..opcodeName.."\" is obsolete") end if self.OpcodeOld[opcodeName] then self:Warning("Mnemonic \""..opcodeName.."\" is an old mnemonic for this instruction. Please use the newer mnemonic \""..self.OpcodeOld[opcodeName].."\".") end -- Create leaf local opcodeLeaf = self:NewLeaf() opcodeLeaf.Opcode = opcodeName opcodeLeaf.ExplictAssign = true -- Parse operands for i=1,operandCount do local segmentOffset,constantValue,expressionLeaf local isMemoryReference,useSpecialMemorySyntax -- Check if it's a special memory reference ([<...>]) if self:MatchToken(TOKEN.LSUBSCR) then isMemoryReference = true useSpecialMemorySyntax = true end -- Check for segment prefix (ES:<...> or ES+<...>) if ((self:PeekToken() == TOKEN.SEGMENT) or (self:PeekToken() == TOKEN.REGISTER)) and ((self:PeekToken(1) == TOKEN.DCOLON) or (useSpecialMemorySyntax and (self:PeekToken(1) == TOKEN.PLUS))) then -- next character is : or + if self:MatchToken(TOKEN.SEGMENT) then -- 1 to 8: CS .. LS segmentOffset = self.TokenData elseif self:MatchToken(TOKEN.REGISTER) then if self.TokenData >= 96 then -- 17+: extended registers segmentOffset = 17 + self.TokenData - 96 else -- 9 to 16: EAX .. EBP segmentOffset = self.TokenData + 8 end end if useSpecialMemorySyntax then if not self:MatchToken(TOKEN.DCOLON) then self:ExpectToken(TOKEN.PLUS) end else self:ExpectToken(TOKEN.DCOLON) end end -- Check if it's a memory reference (#<...>) if not useSpecialMemorySyntax then if self:MatchToken(TOKEN.HASH) then isMemoryReference = true end end -- Parse operand expression (use previous result if previous const wasnt related to seg offset) local c,v,e = self:ConstantExpression() if c then -- Constant value if v then constantValue = v -- Exact value else constantValue = e -- Expression to be recalculated later end else -- Expression expressionLeaf = self:Expression() if expressionLeaf.Opcode then self:Warning("Using complex expression as operand: might corrupt user register") end -- FIXME: warning about using extra registers? end -- Check for segment prefix again (reversed syntax <...>:ES) if self:MatchToken(TOKEN.DCOLON) then if (not segmentOffset) and ((self:PeekToken() == TOKEN.SEGMENT) or (self:PeekToken() == TOKEN.REGISTER)) then if self:MatchToken(TOKEN.SEGMENT) then -- 1 to 8: CS .. LS segmentOffset = self.TokenData elseif self:MatchToken(TOKEN.REGISTER) then if self.TokenData >= 96 then -- 17+: extended registers segmentOffset = 17 + self.TokenData - 96 else -- 9 to 16: EAX .. EBP segmentOffset = self.TokenData + 8 end end else self:Error("Invalid segment offset syntax") end end -- Trailing bracket for [...] memory syntax if useSpecialMemorySyntax then self:ExpectToken(TOKEN.RSUBSCR) end -- Create operand if isMemoryReference then if expressionLeaf then if expressionLeaf.Register then opcodeLeaf.Operands[i] = { MemoryRegister = expressionLeaf.Register, Segment = segmentOffset } else opcodeLeaf.Operands[i] = { MemoryPointer = expressionLeaf, Segment = segmentOffset } end else opcodeLeaf.Operands[i] = { MemoryPointer = constantValue, Segment = segmentOffset } end else if expressionLeaf then if expressionLeaf.Register then if (expressionLeaf.Register >= 16) and (expressionLeaf.Register <= 23) and (segmentOffset) then -- Swap EBX:ES with ES:EBX (because the former one is invalid in ZCPU) local register = expressionLeaf.Register local segment = segmentOffset -- Convert segment register index to register index if (segment >= 1) and (segment <= 8) then expressionLeaf.Register = segment + 15 end if (segment >= 9) and (segment <= 16) then expressionLeaf.Register = segment - 8 end -- Convert register index to segment register index if (register >= 1) and (register <= 8) then segmentOffset = register + 8 end if (register >= 16) and (register <= 23) then segmentOffset = register - 15 end end opcodeLeaf.Operands[i] = { Register = expressionLeaf.Register, Segment = segmentOffset } else if segmentOffset then opcodeLeaf.Operands[i] = self:NewLeaf() opcodeLeaf.Operands[i].Opcode = "add" opcodeLeaf.Operands[i].Operands[1] = { Register = segmentOffset+15 } opcodeLeaf.Operands[i].Operands[2] = expressionLeaf else opcodeLeaf.Operands[i] = expressionLeaf end end else opcodeLeaf.Operands[i] = { Constant = constantValue, Segment = segmentOffset } end end -- Attach information from expression if expressionLeaf then opcodeLeaf.Operands[i].PreviousLeaf = expressionLeaf.PreviousLeaf end -- Syntax if i < operandCount then self:ExpectToken(TOKEN.COMMA) else if self:MatchToken(TOKEN.COMMA) then self:Error("Invalid operand count") end end end -- Check if first operand is a non-preserved register if self.BusyRegisters then if opcodeLeaf.Operands[1] and opcodeLeaf.Operands[1].Register and (self.BusyRegisters[opcodeLeaf.Operands[1].Register] == false) and (self.BlockDepth > 0) then self:Warning("Warning: using an unpreserved register") end if opcodeLeaf.Operands[1] and opcodeLeaf.Operands[1].MemoryRegister and (self.BusyRegisters[opcodeLeaf.Operands[1].MemoryRegister] == false) and (self.BlockDepth > 0) then self:Warning("Warning: using an unpreserved register") end end -- Add opcode to tail self:AddLeafToTail(opcodeLeaf) self:MatchToken(TOKEN.COLON) return true end -------------------------------------------------------------------------------- -- Start a new block function HCOMP:BlockStart(blockType) if self.BlockDepth == 0 then -- Create leaf that corresponds to ENTER instruction self.HeadLeaf = self:NewLeaf() self.HeadLeaf.Opcode = "enter" self.HeadLeaf.Operands[1] = { Constant = self.Settings.MagicValue } self:AddLeafToTail(self.HeadLeaf) self.LocalLabels = {} self.StackPointer = 0 if self.GenerateInlineFunction then self.ParameterPointer = 0 -- Skip EBP else self.ParameterPointer = 1 -- Skip EBP and return address end self.StringsTable = {} self.BlockType = {} self.SpecialLeaf = {} -- Create busy registers list self.BusyRegisters = { false,false,false,false,false,false,true,true } end -- Create a leaf that corresponds to label for BREAK local breakLeaf = self:NewLeaf() breakLeaf.Opcode = "LABEL" breakLeaf.Label = self:GetTempLabel() breakLeaf.Label.Type = "Pointer" breakLeaf.Label.Leaf = breakLeaf -- Create a leaf that corresponds to label for CONTINUE local continueLeaf = self:NewLeaf() continueLeaf.Opcode = "LABEL" continueLeaf.Label = self:GetTempLabel() continueLeaf.Label.Type = "Pointer" continueLeaf.Label.Leaf = continueLeaf self:AddLeafToTail(continueLeaf) -- Only FOR loops have step code if (blockType == "WHILE") or (blockType == "DO") then self.CurrentStepLeaf = nil end self.SpecialLeaf[#self.SpecialLeaf+1] = { Break = breakLeaf, Continue = continueLeaf, JumpBack = self:NewLeaf(), Step = self.CurrentStepLeaf, } if (blockType == "FOR") or (blockType == "WHILE") or (blockType == "DO") then self.CurrentContinueLeaf = self.SpecialLeaf[#self.SpecialLeaf].Continue self.CurrentBreakLeaf = self.SpecialLeaf[#self.SpecialLeaf].Break end -- Push block type table.insert(self.BlockType,blockType or "FUNCTION") self.BlockDepth = self.BlockDepth + 1 end -------------------------------------------------------------------------------- -- End the block function HCOMP:BlockEnd() -- If required, end the previous block local endPreviousBlock = self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock -- If required, add leaf that jumps back to block start if self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode ~= "INVALID" then self.SpecialLeaf[#self.SpecialLeaf].JumpBack.CurrentPosition = self:CurrentSourcePosition() self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].JumpBack) end -- Add leaf that corresponds to break label self.SpecialLeaf[#self.SpecialLeaf].Break.CurrentPosition = self:CurrentSourcePosition() self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].Break) -- Pop current continue leaf if required if self.CurrentContinueLeaf == self.SpecialLeaf[#self.SpecialLeaf].Continue then if self.SpecialLeaf[#self.SpecialLeaf-1] then self.CurrentContinueLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Continue self.CurrentBreakLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Break self.CurrentStepLeaf = self.SpecialLeaf[#self.SpecialLeaf-1].Step else self.CurrentContinueLeaf = nil self.CurrentBreakLeaf = nil self.CurrentStepLeaf = nil end end -- Pop unused leaves self.SpecialLeaf[#self.SpecialLeaf] = nil -- Pop block type local blockType = self.BlockType[#self.BlockType] self.BlockType[#self.BlockType] = nil self.BlockDepth = self.BlockDepth - 1 if self.BlockDepth == 0 then -- Update head leaf with new stack data self.HeadLeaf.Operands[1].Constant = -self.StackPointer if (self.StackPointer == 0) and (self.ParameterPointer == 0) and (not self.Settings.AlwaysEnterLeave) then self.HeadLeaf.Opcode = "DATA" end -- Create leaf for exiting local scope local leaveLeaf = self:NewLeaf() leaveLeaf.Opcode = "leave" if (self.StackPointer ~= 0) or (self.ParameterPointer ~= 0) or (self.Settings.AlwaysEnterLeave) then self:AddLeafToTail(leaveLeaf) end -- Create leaf for returning from call if blockType == "FUNCTION" then if not self.GenerateInlineFunction then local retLeaf = self:NewLeaf() retLeaf.Opcode = "ret" self:AddLeafToTail(retLeaf) end end -- Write down strings table for string,leaf in pairs(self.StringsTable) do self:AddLeafToTail(leaf) end self.StringsTable = nil -- Add local labels to lookup list for labelName,labelData in pairs(self.LocalLabels) do self.DebugInfo.Labels["local."..labelName] = { StackOffset = labelData.StackOffset } end self.LocalLabels = nil self.StackPointer = nil self.ParameterPointer = nil self.BlockType = nil self.SpecialLeaf = nil -- Zap all registers preserved inside the function self.BusyRegisters = nil -- Disable inlining if self.GenerateInlineFunction then self.Functions[self.GenerateInlineFunction].InlineCode = self.InlineFunctionCode self.GenerateInlineFunction = nil self.InlineFunctionCode = nil end -- Disable parent label self.CurrentParentLabel = nil end -- End it, see first line of the function if endPreviousBlock then self:BlockEnd() end end -------------------------------------------------------------------------------- -- Parse ELSE clause function HCOMP:ParseElse(parentBlockExists) -- Add a jump over the else clause local jumpLeaf = self:NewLeaf() jumpLeaf.Opcode = "jmp" self:AddLeafToTail(jumpLeaf) -- Alter the conditional jump so it goes to else clause local jumpOverLabelLeaf = self:NewLeaf() local jumpOverLabel = self:GetTempLabel() jumpOverLabelLeaf.Opcode = "LABEL" jumpOverLabel.Type = "Pointer" jumpOverLabel.Leaf = jumpOverLabelLeaf jumpOverLabelLeaf.Label = jumpOverLabel self:AddLeafToTail(jumpOverLabelLeaf) if parentBlockExists and self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak then self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak) end -- Enter the ELSE block local needBlock = self:MatchToken(self.TOKEN.LBRACKET) self:BlockStart("ELSE") -- Update properly the jump leaf jumpLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label } if needBlock then -- Special marker that means that ending this block ends previous one too self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock = parentBlockExists else -- Parse next statement if dont need a block local previousBlockDepth = #self.BlockType self:Statement() -- If did not enter any new blocks, it was a plain statement. Pop ELSE block if #self.BlockType == previousBlockDepth then -- End the ELSE block self:BlockEnd() -- End the IF block, if required if parentBlockExists then self:BlockEnd() end else -- Special marker that means that ending this block ends ELSE block early too self.SpecialLeaf[#self.SpecialLeaf].EndPreviousBlock = true -- Special marker that means that ending ELSE block ends previous one too self.SpecialLeaf[#self.SpecialLeaf-1].EndPreviousBlock = parentBlockExists end end end -------------------------------------------------------------------------------- function HCOMP:DeclareRegisterVariable() if self.BlockDepth > 0 then for reg=1,6 do if not self.BusyRegisters[reg] then self.BusyRegisters[reg] = true return reg end end self:Error("Out of free registers for declaring local variables") else self:Error("Unable to declare a register variable") end end -------------------------------------------------------------------------------- -- Compile a variable/function. Returns corresponding labels function HCOMP:DefineVariable(isFunctionParam,isForwardDecl,isRegisterDecl,isStructMember) local TOKEN = self.TOKEN local varType,varSize,isStruct if self:MatchToken(TOKEN.IDENT) then -- Define structure varType = self.TokenData varSize = 0 -- Depends on pointer level isStruct = true else -- Define variable self:ExpectToken(TOKEN.TYPE) varType = self.TokenData varSize = 1 if varType == 5 then varSize = 4 end end -- Variable labels list local labelsList = {} -- Parse all variables to define while true do -- Get pointer level (0, *, **, ***, etc) local pointerLevel = 0 while self:MatchToken(TOKEN.TIMES) do pointerLevel = pointerLevel + 1 end -- Fix structure size if isStruct then if pointerLevel > 0 then varSize = 1 else varSize = self.StructSize[varType] end end -- Get variable name self:ExpectToken(TOKEN.IDENT) local varName = self.TokenData -- Try to read information about array size, stuff local arraySize while self:MatchToken(TOKEN.LSUBSCR) do -- varname[<arr size>] if self:MatchToken(TOKEN.RSUBSCR) then -- varname[] if isFunctionParam then -- just a pointer to an array pointerLevel = 1 end else local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed if c then if not arraySize then arraySize = {} end arraySize[#arraySize+1] = v else self:Error("Array size must be constant") end self:ExpectToken(TOKEN.RSUBSCR) end end -- Calculate size of array local bytesArraySize if arraySize then for k,v in pairs(arraySize) do bytesArraySize = (bytesArraySize or 0) + v*varSize end end -- Add to global list table.insert(labelsList,{ Name = varName, Type = varType, PtrLevel = pointerLevel, Size = bytesArraySize or varSize }) if not isStructMember then -- Do not define struct members if self:MatchToken(TOKEN.LPAREN) then -- Define function -- Create function entrypoint local label label = self:DefineLabel(varName) label.Type = "Pointer" label.Defined = true -- Make all further leaves parented to this label self.CurrentParentLabel = label -- Create label leaf label.Leaf = self:NewLeaf() label.Leaf.Opcode = "LABEL" label.Leaf.Label = label self:AddLeafToTail(label.Leaf) --isInlined -- Define a function local _,functionVariables = nil,{} self:BlockStart() if not self:MatchToken(TOKEN.RPAREN) then _,functionVariables = self:DefineVariable(true) self:ExpectToken(TOKEN.RPAREN) -- Add comments about function into assembly listing if self.Settings.GenerateComments then for i=1,#functionVariables do label.Leaf.Comment = (label.Leaf.Comment or "")..(functionVariables[i].Name) if i < #functionVariables then label.Leaf.Comment = label.Leaf.Comment.."," end end end end -- Forward declaration, mess up label name if isForwardDecl then local newName = label.Name.."@" for i=1,#functionVariables do newName = newName..functionVariables[i].Name..functionVariables[i].Type if i < #functionVariables then newName = newName.."_" end end self:RedefineLabel(label.Name,newName) end -- Generate comment if required if self.Settings.GenerateComments then label.Leaf.Comment = varName.."("..(label.Leaf.Comment or "")..")" end self:ExpectToken(TOKEN.LBRACKET) return true,functionVariables,varName,varType,pointerLevel else -- Define variable -- Check if there's an initializer local initializerLeaves,initializerValues if self:MatchToken(TOKEN.EQUAL) then if not self.LocalLabels then -- Check rules for global init if self:MatchToken(TOKEN.LBRACKET) then -- Array initializer if not bytesArraySize then self:Error("Cannot initialize value: not an array") end initializerValues = {} while not self:MatchToken(TOKEN.RBRACKET) do local c,v = self:ConstantExpression(true) if not c then self:Error("Cannot have expressions in global initializers") else table.insert(initializerValues,v) end self:MatchToken(TOKEN.COMMA) end else -- Single initializer if bytesArraySize then self:Error("Cannot initialize value: is an array") end local c,v = self:ConstantExpression(true) if not c then -- initializerLeaves = { self:Expression() } self:Error("Cannot have expressions in global initializers") else initializerValues = { v } end end else -- Local init always an expression if self:MatchToken(TOKEN.LBRACKET) then -- Array initializer if not bytesArraySize then self:Error("Cannot initialize value: not an array") end initializerLeaves = {} while not self:MatchToken(TOKEN.RBRACKET) do table.insert(initializerLeaves,self:Expression()) self:MatchToken(TOKEN.COMMA) end if #initializerLeaves > 256 then self:Error("Too much local variable initializers") end else if bytesArraySize then self:Error("Cannot initialize value: is an array") end initializerLeaves = { self:Expression() } end end end -- Define a variable if self.LocalLabels then -- check if var is local local label = self:DefineLabel(varName,true) if isRegisterDecl then label.Type = "Register" label.Value = self:DeclareRegisterVariable() if isStruct then self:Error("Cannot hold structure variables in registers - yet") end else label.Type = "Stack" if isStruct and (pointerLevel > 0) then label.PointerToStruct = true end end label.Defined = true if varType == 5 then label.ForceType = "vector" end if isStruct then label.Struct = varType end -- If label has associated array size, mark it as an array if bytesArraySize then label.Array = bytesArraySize end if not isRegisterDecl then if not isFunctionParam then -- Add a new local variable (stack pointer increments) self.StackPointer = self.StackPointer - (bytesArraySize or varSize) label.StackOffset = self.StackPointer else -- Add a new function variable self.ParameterPointer = self.ParameterPointer + (bytesArraySize or varSize) label.StackOffset = self.ParameterPointer end end -- Initialize local variable if isRegisterDecl then if initializerLeaves then local movLeaf = self:NewLeaf() movLeaf.Opcode = "mov" movLeaf.Operands[1] = { Register = label.Value } movLeaf.Operands[2] = initializerLeaves[1] movLeaf.ExplictAssign = true self:AddLeafToTail(movLeaf) end else if initializerLeaves then for i=1,#initializerLeaves do -- FIXME: find a nicer way to initialize local movLeaf = self:NewLeaf() movLeaf.Opcode = "mov" movLeaf.Operands[1] = { Stack = label.StackOffset+i-1 } movLeaf.Operands[2] = initializerLeaves[i] movLeaf.ExplictAssign = true self:AddLeafToTail(movLeaf) end for i=#initializerLeaves+1,bytesArraySize or 1 do local movLeaf = self:NewLeaf() movLeaf.Opcode = "mov" movLeaf.Operands[1] = { Stack = label.StackOffset+i-1 } movLeaf.Operands[2] = { Constant = 0 } movLeaf.ExplictAssign = true self:AddLeafToTail(movLeaf) end end end else -- Define a new global variable local label = self:DefineLabel(varName) if isRegisterDecl then label.Type = "Register" label.Value = self:DeclareRegisterVariable() else label.Type = "Variable" if isStruct and (pointerLevel > 0) then label.PointerToStruct = true end end label.Defined = true if varType == 5 then label.ForceType = "vector" end if isStruct then label.Struct = varType end -- If label has associated array size, mark it as an array if bytesArraySize then label.Array = bytesArraySize end -- Create initialization leaf label.Leaf = self:NewLeaf() label.Leaf.ParentLabel = self.CurrentParentLabel or label label.Leaf.Opcode = "DATA" if initializerValues then label.Leaf.Data = initializerValues label.Leaf.ZeroPadding = (bytesArraySize or varSize) - #initializerValues else label.Leaf.ZeroPadding = bytesArraySize or varSize end label.Leaf.Label = label self:AddLeafToTail(label.Leaf) end end else -- Struct member -- Do nothing right now end if not self:MatchToken(TOKEN.COMMA) then return true,labelsList else --int x, char y, float z local nextToken,structName = self:PeekToken(0,true) if (nextToken == TOKEN.IDENT) and (self.Structs[structName]) then self:MatchToken(TOKEN.IDENT) local structData = self.Structs[structName] varType = self.TokenData varSize = 0 isStruct = true elseif self:MatchToken(TOKEN.TYPE) then varType = self.TokenData varSize = 1 if varType == 5 then varSize = 4 end isStruct = false end end end end -------------------------------------------------------------------------------- -- Compile a single statement function HCOMP:Statement() local TOKEN = self.TOKEN -- Parse end of line colon if self:MatchToken(TOKEN.COLON) then return true end -- Check for EOF if self:MatchToken(TOKEN.EOF) then return false end -- Parse variable/function definition local exportSymbol = self:MatchToken(TOKEN.EXPORT) local inlineFunction = self:MatchToken(TOKEN.INLINE) local forwardFunction = self:MatchToken(TOKEN.FORWARD) local registerValue = self:MatchToken(TOKEN.LREGISTER) if self:PeekToken() == TOKEN.TYPE then if inlineFunction then self.GenerateInlineFunction = true self.InlineFunctionCode = {} end local isDefined,variableList,functionName,returnType,returnPtrLevel = self:DefineVariable(false,forwardFunction,registerValue) if isDefined then if functionName then self.Functions[functionName] = { FunctionName = functionName, Parameters = variableList, ReturnType = returnType, ReturnPtrLevel = returnPtrLevel, } if exportSymbol then self.ExportedSymbols[functionName] = self.Functions[functionName] end if inlineFunction then self.GenerateInlineFunction = functionName end else if exportSymbol then self:Error("Exporting variables not supported right now by the compiler") end end end if inlineFunction and (not functionName) then self:Error("Can only inline functions") end if forwardFunction and (not functionName) then self:Error("Can only forward-declare functions") end return isDefined end -- Peek structure definition local nextToken,structName = self:PeekToken(0,true) if (nextToken == TOKEN.IDENT) and (self.Structs[structName]) then self:DefineVariable() return true end if inlineFunction or exportSymbol or forwardFunction or registerValue then self:Error("Function definition or symbol definition expected") end -- Parse preserve/zap if self:MatchToken(TOKEN.PRESERVE) or self:MatchToken(TOKEN.ZAP) then local tokenType = self.TokenType if self.BlockDepth > 0 then while self:MatchToken(TOKEN.REGISTER) do self.BusyRegisters[self.TokenData] = tokenType == TOKEN.PRESERVE self:MatchToken(TOKEN.COMMA) end self:MatchToken(TOKEN.COLON) return true else self:Error("Can only zap/preserve registers inside functions/local blocks") end end -- Parse assembly instruction if self:MatchToken(TOKEN.OPCODE) then return self:Opcode() end -- Parse STRUCT macro if self:MatchToken(TOKEN.STRUCT) then self:ExpectToken(TOKEN.IDENT) local structName = self.TokenData -- Create structure self.Structs[structName] = {} self.StructSize[structName] = 0 -- Populate structure self:ExpectToken(TOKEN.LBRACKET) while (not self:MatchToken(TOKEN.RBRACKET)) and (not self:MatchToken(TOKEN.EOF)) do local _,variableList = self:DefineVariable(false,false,false,true) for _,variableData in ipairs(variableList) do variableData.Offset = self.StructSize[structName] self.Structs[structName][variableData.Name] = variableData self.StructSize[structName] = self.StructSize[structName] + variableData.Size end self:ExpectToken(TOKEN.COLON) end return true end -- Parse VECTOR macro if self:MatchToken(TOKEN.VECTOR) then if self.BlockDepth > 0 then self:Warning("Defining a vector inside a function block might cause issues") end -- Vector type (VEC2F, etc) local vectorType = self.TokenData -- Vector name self:ExpectToken(TOKEN.IDENT) local vectorName = self.TokenData -- Create leaf and label for vector name local vectorNameLabelLeaf = self:NewLeaf() vectorNameLabelLeaf.Opcode = "LABEL" local vectorNameLabel = self:DefineLabel(vectorName) vectorNameLabel.Type = "Pointer" vectorNameLabel.Defined = true vectorNameLabel.Leaf = vectorNameLabelLeaf vectorNameLabel.DebugAsVector = #VectorSyntax[vectorType] vectorNameLabelLeaf.Label = vectorNameLabel self:AddLeafToTail(vectorNameLabelLeaf) -- Create leaves for all vector labels and their data local vectorLeaves = {} for index,labelNames in pairs(VectorSyntax[vectorType]) do -- Create leaves for labels for labelIndex,labelName in pairs(labelNames) do local vectorLabelLeaf = self:NewLeaf() vectorLabelLeaf.Opcode = "LABEL" local vectorLabel = self:GetLabel(vectorName.."."..labelName) vectorLabel.Type = "Pointer" vectorLabel.Defined = true vectorLabel.Leaf = vectorLabelLeaf vectorLabelLeaf.Label = vectorLabel self:AddLeafToTail(vectorLabelLeaf) end -- Create leaf for data vectorLeaves[index] = self:NewLeaf() vectorLeaves[index].Opcode = "DATA" vectorLeaves[index].Data = { 0 } self:AddLeafToTail(vectorLeaves[index]) if vectorType == "COLOR" then vectorLeaves[index].Data = { 255 } end end -- Parse initialization self.MostLikelyConstantExpression = true if self:MatchToken(TOKEN.COMMA) then for index,labelNames in pairs(VectorSyntax[vectorType]) do local c,v,e = self:ConstantExpression(false) if c then vectorLeaves[index].Data[1] = v or e else self:Error("Vector initialization must be constant") end if (index == #VectorSyntax[vectorType]) and self:MatchToken(TOKEN.COMMA) then self:Error("Too much values for intialization") end if (index < #VectorSyntax[vectorType]) and (not self:MatchToken(TOKEN.COMMA)) then return true end end end self.MostLikelyConstantExpression = false return true end -- Parse DATA macro if self:MatchToken(TOKEN.DATA) then local jmpLeaf = self:NewLeaf() jmpLeaf.Opcode = "jmp" jmpLeaf.Operands[1] = { Constant = {{ Type = TOKEN.IDENT, Data = "_code", Position = self:CurrentSourcePosition() }} } self:AddLeafToTail(jmpLeaf) return true end -- Parse CODE macro if self:MatchToken(TOKEN.CODE) then local label = self:DefineLabel("_code") label.Type = "Pointer" label.Leaf = self:NewLeaf() label.Leaf.Opcode = "LABEL" label.Leaf.Label = label self:AddLeafToTail(label.Leaf) return true end -- Parse ORG macro if self:MatchToken(TOKEN.ORG) then -- org x local markerLeaf = self:NewLeaf() markerLeaf.Opcode = "MARKER" local c,v = self:ConstantExpression(true) if c then markerLeaf.SetWritePointer = v else self:Error("ORG offset must be constant") end self:AddLeafToTail(markerLeaf) return true end -- Parse OFFSET macro if self:MatchToken(TOKEN.OFFSET) then -- offset x local markerLeaf = self:NewLeaf() markerLeaf.Opcode = "MARKER" local c,v = self:ConstantExpression(true) if c then markerLeaf.SetPointerOffset = v else self:Error("OFFSET offset must be constant") end self:AddLeafToTail(markerLeaf) return true end -- Parse DB macro if self:MatchToken(TOKEN.DB) then -- db 1,... self.IgnoreStringInExpression = true self.MostLikelyConstantExpression = true local dbLeaf = self:NewLeaf() dbLeaf.Opcode = "DATA" dbLeaf.Data = {} local c,v,e = self:ConstantExpression(false) while c or (self:PeekToken() == TOKEN.STRING) do -- Insert data into leaf if self:MatchToken(TOKEN.STRING) then table.insert(dbLeaf.Data,self.TokenData) else table.insert(dbLeaf.Data,v or e) end -- Only keep parsing if next token is comma if self:MatchToken(TOKEN.COMMA) then c,v,e = self:ConstantExpression(false) else c = false end end self.IgnoreStringInExpression = false self.MostLikelyConstantExpression = false self:AddLeafToTail(dbLeaf) return true end -- Parse STRING macro if self:MatchToken(TOKEN.STRALLOC) then -- string name,1,... self:ExpectToken(TOKEN.IDENT) -- Create leaf and label for vector name local stringNameLabelLeaf = self:NewLeaf() stringNameLabelLeaf.Opcode = "LABEL" local stringNameLabel = self:DefineLabel(self.TokenData) stringNameLabel.Type = "Pointer" stringNameLabel.Defined = true stringNameLabel.Leaf = stringNameLabelLeaf stringNameLabelLeaf.Label = stringNameLabel self:AddLeafToTail(stringNameLabelLeaf) self:ExpectToken(TOKEN.COMMA) self.IgnoreStringInExpression = true self.MostLikelyConstantExpression = true local stringLeaf = self:NewLeaf() stringLeaf.Opcode = "DATA" stringLeaf.Data = {} local c,v,e = self:ConstantExpression(false) while c or (self:PeekToken() == TOKEN.STRING) do -- Insert data into leaf if self:MatchToken(TOKEN.STRING) then table.insert(stringLeaf.Data,self.TokenData) else table.insert(stringLeaf.Data,v or e) end -- Only keep parsing if next token is comma if self:MatchToken(TOKEN.COMMA) then c,v,e = self:ConstantExpression(false) else c = false end end table.insert(stringLeaf.Data,0) self.IgnoreStringInExpression = false self.MostLikelyConstantExpression = false self:AddLeafToTail(stringLeaf) return true end -- Parse DEFINE macro if self:MatchToken(TOKEN.DEFINE) then -- define label,value self:ExpectToken(TOKEN.IDENT) local defineLabel = self:DefineLabel(self.TokenData) defineLabel.Type = "Pointer" defineLabel.Defined = true self:ExpectToken(TOKEN.COMMA) self.MostLikelyConstantExpression = true local c,v,e = self:ConstantExpression(false) if c then if v then defineLabel.Value = v else defineLabel.Expression = e end else self:Error("Define value must be constant") end self.MostLikelyConstantExpression = false return true end -- Parse ALLOC macro if self:MatchToken(TOKEN.ALLOC) then -- alloc label,size,value -- alloc label,value -- alloc label -- alloc size local allocLeaf = self:NewLeaf() local allocLabel,allocSize,allocValue = nil,1,0 local expectSize = false allocLeaf.Opcode = "DATA" -- Add a label to this alloc if self:MatchToken(TOKEN.IDENT) then allocLabel = self:DefineLabel(self.TokenData) allocLabel.Type = "Pointer" allocLabel.Defined = true allocLabel.DebugAsVariable = true allocLabel.Leaf = allocLeaf allocLeaf.Label = allocLabel if self:MatchToken(TOKEN.COMMA) then expectSize = true end end -- Read size self.MostLikelyConstantExpression = true if (not allocLabel) or (expectSize) then local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed if c then allocSize = v else self:Error("Alloc size must be constant") end end if allocLabel and expectSize then if self:MatchToken(TOKEN.COMMA) then local c,v = self:ConstantExpression(true) -- need precise value here, no ptrs allowed if c then allocValue = v else self:Error("Alloc value must be constant") end else allocValue = allocSize allocSize = 1 end end self.MostLikelyConstantExpression = false -- Initialize alloc allocLeaf.ZeroPadding = allocSize self:AddLeafToTail(allocLeaf) return true end -- Parse RETURN if self:MatchToken(TOKEN.RETURN) and self.HeadLeaf then if not self:MatchToken(TOKEN.COLON) then local returnExpression = self:Expression() local returnLeaf = self:NewLeaf() returnLeaf.Opcode = "mov" returnLeaf.Operands[1] = { Register = 1 } returnLeaf.Operands[2] = returnExpression returnLeaf.ExplictAssign = true self:AddLeafToTail(returnLeaf) end self:MatchToken(TOKEN.COLON) -- Check if this is the last return in the function -- if self:MatchToken(TOKEN.RBRACKET) then -- if self.BlockDepth > 0 then -- self:BlockEnd() -- return true -- else -- self:Error("Unexpected bracket") -- end -- end if not self.GenerateInlineFunction then -- Create leaf for exiting local scope local leaveLeaf = self:NewLeaf() leaveLeaf.Opcode = "leave" if (self.StackPointer ~= 0) or (self.ParameterPointer ~= 0) or (self.Settings.AlwaysEnterLeave) then self:AddLeafToTail(leaveLeaf) end -- Create leaf for returning from call local retLeaf = self:NewLeaf() retLeaf.Opcode = "ret" self:AddLeafToTail(retLeaf) end return true end -- Parse IF syntax if self:MatchToken(TOKEN.IF) then -- Parse condition self:ExpectToken(TOKEN.LPAREN) local firstToken = self.CurrentToken self:SaveParserState() local conditionLeaf = self:Expression() local conditionText = "if ("..self:PrintTokens(self:GetSavedTokens(firstToken))..")" self:ExpectToken(TOKEN.RPAREN) -- Enter the IF block local needBlock = self:MatchToken(TOKEN.LBRACKET) self:BlockStart("IF") -- Calculate condition local cmpLeaf = self:NewLeaf() cmpLeaf.Opcode = "cmp" cmpLeaf.Operands[1] = { Constant = 0 } cmpLeaf.Operands[2] = conditionLeaf cmpLeaf.Comment = conditionText self:AddLeafToTail(cmpLeaf) -- Create label for conditional break (if condition is false) local conditionalBreakLeaf = self:NewLeaf() local conditionalBreak = self:GetTempLabel() conditionalBreakLeaf.Opcode = "LABEL" conditionalBreak.Type = "Pointer" conditionalBreak.Leaf = conditionalBreakLeaf conditionalBreakLeaf.Label = conditionalBreak self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak = conditionalBreakLeaf -- self:AddLeafToTail(conditionalBreakLeaf) -- Generate conditional jump over the block local jumpLeaf = self:NewLeaf() jumpLeaf.Opcode = "jge" jumpLeaf.Operands[1] = { PointerToLabel = conditionalBreakLeaf.Label } self:AddLeafToTail(jumpLeaf) if not needBlock then -- Parse next statement if dont need a block self:Statement() -- End the IF block early self:BlockEnd() -- Add exit label self:AddLeafToTail(conditionalBreakLeaf) -- Check for out-of-block ELSE if self:MatchToken(TOKEN.ELSE) then self:ParseElse(false) end -- else -- self:AddLeafToTail(conditionalBreak) -- self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak = jumpLeaf end return true end -- Parse WHILE syntax if self:MatchToken(TOKEN.WHILE) then local returnLabel -- Parse condition self:ExpectToken(TOKEN.LPAREN) local firstToken = self.CurrentToken self:SaveParserState() local conditionLeaf = self:Expression() local conditionText = "if ("..self:PrintTokens(self:GetSavedTokens(firstToken)) self:ExpectToken(TOKEN.RPAREN) -- Enter the WHILE block local needBlock = self:MatchToken(TOKEN.LBRACKET) if needBlock then self:BlockStart("WHILE") end if not needBlock then -- Generate return label local returnLabelLeaf = self:NewLeaf() returnLabel = self:GetTempLabel() returnLabelLeaf.Opcode = "LABEL" returnLabel.Type = "Pointer" returnLabel.Leaf = returnLabelLeaf returnLabelLeaf.Label = returnLabel self:AddLeafToTail(returnLabelLeaf) end -- Calculate condition local cmpLeaf = self:NewLeaf() cmpLeaf.Opcode = "cmp" cmpLeaf.Operands[1] = { Constant = 0 } cmpLeaf.Operands[2] = conditionLeaf cmpLeaf.Comment = conditionText self:AddLeafToTail(cmpLeaf) if not needBlock then -- Generate conditional jump over the block local jumpOverLabelLeaf = self:NewLeaf() local jumpOverLabel = self:GetTempLabel() jumpOverLabelLeaf.Opcode = "LABEL" jumpOverLabel.Type = "Pointer" jumpOverLabel.Leaf = jumpOverLabelLeaf jumpOverLabelLeaf.Label = jumpOverLabel local jumpOverLeaf = self:NewLeaf() jumpOverLeaf.Opcode = "jz" jumpOverLeaf.Operands[1] = { PointerToLabel = jumpOverLabel } self:AddLeafToTail(jumpOverLeaf) -- Parse next statement if dont need a block self:Statement() -- Generate the jump back leaf local jumpBackLeaf = self:NewLeaf() jumpBackLeaf.Opcode = "jmp" jumpBackLeaf.Operands[1] = { PointerToLabel = returnLabel } self:AddLeafToTail(jumpBackLeaf) -- Add exit label self:AddLeafToTail(jumpOverLabelLeaf) else -- Generate conditional jump over the block local jumpOverLeaf = self:NewLeaf() jumpOverLeaf.Opcode = "jz" jumpOverLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label } self:AddLeafToTail(jumpOverLeaf) -- Set the jump back leaf self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode = "jmp" self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Continue.Label } end return true end -- Parse FOR syntax if self:MatchToken(TOKEN.FOR) then local returnLabel -- Parse syntax self:ExpectToken(TOKEN.LPAREN) local initLeaf = self:Expression() initLeaf.Comment = "init loop" self:ExpectToken(TOKEN.COLON) local conditionLeaf = self:Expression() conditionLeaf.Comment = "condition" self:ExpectToken(TOKEN.COLON) local stepLeaf = self:Expression() stepLeaf.Comment = "loop step" self:ExpectToken(TOKEN.RPAREN) self:AddLeafToTail(initLeaf) -- Save stepLeaf for inlining continue self.CurrentStepLeaf = stepLeaf -- Enter the FOR block local needBlock = self:MatchToken(TOKEN.LBRACKET) if needBlock then self:BlockStart("FOR") end if not needBlock then -- Generate return label local returnLabelLeaf = self:NewLeaf() returnLabel = self:GetTempLabel() returnLabelLeaf.Opcode = "LABEL" returnLabel.Type = "Pointer" returnLabel.Leaf = returnLabelLeaf returnLabelLeaf.Label = returnLabel self:AddLeafToTail(returnLabelLeaf) end -- Calculate condition local cmpLeaf = self:NewLeaf() cmpLeaf.Opcode = "cmp" cmpLeaf.Operands[1] = { Constant = 0 } cmpLeaf.Operands[2] = conditionLeaf self:AddLeafToTail(cmpLeaf) if not needBlock then -- Generate conditional jump over the block local jumpOverLabelLeaf = self:NewLeaf() local jumpOverLabel = self:GetTempLabel() jumpOverLabelLeaf.Opcode = "LABEL" jumpOverLabel.Type = "Pointer" jumpOverLabel.Leaf = jumpOverLabelLeaf jumpOverLabelLeaf.Label = jumpOverLabel local jumpOverLeaf = self:NewLeaf() jumpOverLeaf.Opcode = "jz" jumpOverLeaf.Operands[1] = { PointerToLabel = jumpOverLabel } self:AddLeafToTail(jumpOverLeaf) -- Parse next statement if dont need a block self:Statement() -- Generate the jump back leaf local jumpBackLeaf = self:NewLeaf() jumpBackLeaf.Opcode = "jmp" jumpBackLeaf.Operands[1] = { PointerToLabel = returnLabel } self:AddLeafToTail(stepLeaf) self:AddLeafToTail(jumpBackLeaf) -- Add exit label self:AddLeafToTail(jumpOverLabelLeaf) else -- Generate conditional jump over the block local jumpOverLeaf = self:NewLeaf() jumpOverLeaf.Opcode = "jz" jumpOverLeaf.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Break.Label } self:AddLeafToTail(jumpOverLeaf) -- Set the jump back leaf self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Opcode = "jmp" self.SpecialLeaf[#self.SpecialLeaf].JumpBack.Operands[1] = { PointerToLabel = self.SpecialLeaf[#self.SpecialLeaf].Continue.Label } self.SpecialLeaf[#self.SpecialLeaf].JumpBack.PreviousLeaf = stepLeaf end return true end -- Parse CONTINUE if self:MatchToken(TOKEN.CONTINUE) then if (self.BlockDepth > 0) and (self.CurrentContinueLeaf) then local jumpBackLeaf = self:NewLeaf() jumpBackLeaf.Opcode = "jmp" jumpBackLeaf.Operands[1] = { PointerToLabel = self.CurrentContinueLeaf.Label } if (self.CurrentStepLeaf) then self:AddLeafToTail(self.CurrentStepLeaf) end self:AddLeafToTail(jumpBackLeaf) return true else self:Error("Nowhere to continue here") end end -- Parse BREAK if self:MatchToken(TOKEN.BREAK) then if (self.BlockDepth > 0) and (self.CurrentBreakLeaf) then local jumpLeaf = self:NewLeaf() jumpLeaf.Opcode = "jmp" jumpLeaf.Operands[1] = { PointerToLabel = self.CurrentBreakLeaf.Label } self:AddLeafToTail(jumpLeaf) return true else self:Error("Nowhere to break from here") end end -- Parse GOTO if self:MatchToken(TOKEN.GOTO) then local gotoExpression = self:Expression() local jumpLeaf = self:NewLeaf() jumpLeaf.Opcode = "jmp" jumpLeaf.Operands[1] = gotoExpression self:AddLeafToTail(jumpLeaf) return true end -- Parse block open bracket if self:MatchToken(TOKEN.LBRACKET) then self:BlockStart("LBLOCK") return true end -- Parse block close bracket if self:MatchToken(TOKEN.RBRACKET) then if self.BlockDepth > 0 then local blockType = self.BlockType[#self.BlockType] if (blockType == "IF") and self:MatchToken(TOKEN.ELSE) then -- Add ELSE block, IF remains in stack self:ParseElse(true) else if blockType == "IF" then -- FIXME: It kind of is redundant self:AddLeafToTail(self.SpecialLeaf[#self.SpecialLeaf].ConditionalBreak) end self:BlockEnd() end return true else self:Error("Unexpected bracket") end end -- Parse possible label definition local firstToken = self.CurrentToken self:SaveParserState() if self:MatchToken(TOKEN.IDENT) then if (self:PeekToken() == TOKEN.COMMA) or (self:PeekToken() == TOKEN.DCOLON) then -- Label definition for sure while true do local label = self:DefineLabel(self.TokenData) label.Type = "Pointer" label.Defined = true label.Leaf = self:NewLeaf() label.Leaf.Opcode = "LABEL" label.Leaf.Label = label self:AddLeafToTail(label.Leaf) self:MatchToken(TOKEN.COMMA) if not self:MatchToken(TOKEN.IDENT) then break end end self:ExpectToken(TOKEN.DCOLON) self:MatchToken(TOKEN.COLON) return true else self:RestoreParserState() end end -- If nothing else, must be some kind of an expression local expressionLeaf = self:Expression() self:AddLeafToTail(expressionLeaf) -- Add expression to leaf comment if self.Settings.GenerateComments then expressionLeaf.Comment = self:PrintTokens(self:GetSavedTokens(firstToken)) end -- Skip a colon self:MatchToken(TOKEN.COLON) return true end
ESX = nil local PlayerLoaded = false vip = false Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end PlayerLoaded = true ESX.PlayerData = ESX.GetPlayerData() end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) ESX.PlayerData = xPlayer PlayerLoaded = true end) AddEventHandler('playerSpawned', function() vip = false ESX.TriggerServerCallback('pxrp_vip:getVIPStatus', function(vip) if vip then while not PlayerLoaded do Citizen.Wait(1000) end ESX.ShowNotification("Status VIP: Activé") end end) end) function addVIPStatus() TriggerServerEvent('pxrp_vip:setVIPStatus', true) vip = true end function removeVIPStatus() TriggerServerEvent('pxrp_vip:setVIPStatus', false) vip = false end RegisterNetEvent('pxrp_vip:addVIPStatus') AddEventHandler('pxrp_vip:addVIPStatus', function() addVIPStatus() end) RegisterNetEvent('pxrp_vip:removeVIPStatus') AddEventHandler('pxrp_vip:removeVIPStatus', function() removeVIPStatus() end)
include("shared.lua") -- Define GM12 fonts for compatibility surface.CreateFont("DefaultBold", { font = "Tahoma", size = 13, weight = 1000 }) surface.CreateFont("TabLarge", { font = "Tahoma", size = 13, weight = 700, shadow = true, antialias = false }) surface.CreateFont("Trebuchet22", { font = "Trebuchet MS", size = 22, weight = 900 }) include("scoring_shd.lua") include("corpse_shd.lua") include("player_ext_shd.lua") include("weaponry_shd.lua") include("vgui/ColoredBox.lua") include("vgui/SimpleIcon.lua") include("vgui/ProgressBar.lua") include("vgui/ScrollLabel.lua") include("cl_radio.lua") include("cl_disguise.lua") include("cl_transfer.lua") include("cl_targetid.lua") include("cl_search.lua") include("cl_radar.lua") include("cl_tbuttons.lua") include("cl_scoreboard.lua") include("cl_tips.lua") include("cl_help.lua") include("cl_hud.lua") include("cl_msgstack.lua") include("cl_hudpickup.lua") include("cl_keys.lua") include("cl_wepswitch.lua") include("cl_scoring.lua") include("cl_scoring_events.lua") include("cl_popups.lua") include("cl_equip.lua") include("cl_voice.lua") CreateClientConVar("ttt_role_symbols", 0, true, false, "Shows symbols instead of letters in role icons.") CreateClientConVar("ttt_export_player_data", 0, true, false) function GM:Initialize() MsgN("TTT Client initializing...") GAMEMODE.round_state = ROUND_WAIT LANG.Init() self.BaseClass:Initialize() end function GM:InitPostEntity() MsgN("TTT Client post-init...") net.Start("TTT_Spectate") net.WriteBool(GetConVar("ttt_spectator_mode"):GetBool()) net.SendToServer() if not game.SinglePlayer() then timer.Create("idlecheck", 5, 0, CheckIdle) end -- make sure player class extensions are loaded up, and then do some -- initialization on them if IsValid(LocalPlayer()) and LocalPlayer().GetTraitor then GAMEMODE:ClearClientState() end timer.Create("cache_ents", 1, 0, GAMEMODE.DoCacheEnts) RunConsoleCommand("_ttt_request_serverlang") RunConsoleCommand("_ttt_request_rolelist") end function GM:DoCacheEnts() RADAR:CacheEnts() TBHUD:CacheEnts() end function GM:HUDClear() RADAR:Clear() TBHUD:Clear() end KARMA = {} function KARMA.IsEnabled() return GetGlobalBool("ttt_karma", false) end DRINKS = {} function DRINKS.IsEnabled() return GetGlobalBool("ttt_drinking_enabled", false) end function GetRoundState() return GAMEMODE.round_state end local function RoundStateChange(o, n) if n == ROUND_PREP then -- prep starts GAMEMODE:ClearClientState() GAMEMODE:CleanUpMap() -- show warning to spec mode players if GetConVar("ttt_spectator_mode"):GetBool() and IsValid(LocalPlayer()) then LANG.Msg("spec_mode_warning") end -- reset cached server language in case it has changed RunConsoleCommand("_ttt_request_serverlang") elseif n == ROUND_ACTIVE then -- round starts VOICE.CycleMuteState(MUTE_NONE) CLSCORE:ClearPanel() -- people may have died and been searched during prep for _, p in pairs(player.GetAll()) do p.search_result = nil end -- clear blood decals produced during prep RunConsoleCommand("r_cleardecals") GAMEMODE.StartingPlayers = #util.GetAlivePlayers() elseif n == ROUND_POST then RunConsoleCommand("ttt_cl_traitorpopup_close") end -- stricter checks when we're talking about hooks, because this function may -- be called with for example o = WAIT and n = POST, for newly connecting -- players, which hooking code may not expect if n == ROUND_PREP then -- can enter PREP from any phase due to ttt_roundrestart hook.Call("TTTPrepareRound", GAMEMODE) elseif (o == ROUND_PREP) and (n == ROUND_ACTIVE) then hook.Call("TTTBeginRound", GAMEMODE) elseif (o == ROUND_ACTIVE) and (n == ROUND_POST) then hook.Call("TTTEndRound", GAMEMODE) end -- whatever round state we get, clear out the voice flags for k, v in pairs(player.GetAll()) do v.traitor_gvoice = false end end concommand.Add("ttt_print_playercount", function() print(GAMEMODE.StartingPlayers) end) --- optional sound cues on round start and end CreateConVar("ttt_cl_soundcues", "0", FCVAR_ARCHIVE) local cues = { Sound("ttt/thump01e.mp3"), Sound("ttt/thump02e.mp3") }; local function PlaySoundCue() if GetConVar("ttt_cl_soundcues"):GetBool() then surface.PlaySound(table.Random(cues)) end end GM.TTTBeginRound = PlaySoundCue GM.TTTEndRound = PlaySoundCue local confetti = Material("confetti.png") net.Receive("TTT_Birthday", function() local ent = net.ReadEntity() ent:EmitSound("birthday.wav") local pos = ent:GetPos() + Vector(0, 0, ent:OBBMaxs().z) if ent.GetShootPos then pos = ent:GetShootPos() end local velMax = 200 local gravMax = 50 local gravity = Vector(math.random(-gravMax, gravMax), math.random(-gravMax, gravMax), math.random(-gravMax, 0)) --Handles particles local emitter = ParticleEmitter(pos, true) for I = 1, 150 do local p = emitter:Add(confetti, pos) p:SetStartSize(math.random(6, 10)) p:SetEndSize(0) p:SetAngles(Angle(math.random(0, 360), math.random(0, 360), math.random(0, 360))) p:SetAngleVelocity(Angle(math.random(5, 50), math.random(5, 50), math.random(5, 50))) p:SetVelocity(Vector(math.random(-velMax, velMax), math.random(-velMax, velMax), math.random(-velMax, velMax))) p:SetColor(255, 255, 255) p:SetDieTime(math.random(4, 7)) p:SetGravity(gravity) p:SetAirResistance(125) end end) --- usermessages local function ReceiveRole() local client = LocalPlayer() local role = net.ReadUInt(4) -- after a mapswitch, server might have sent us this before we are even done -- loading our code if not client.SetRole then return end client:SetRole(role) Msg("You are: ") if client:IsTraitor() then MsgN("TRAITOR") elseif client:IsDetective() then MsgN("DETECTIVE") elseif client:IsMercenary() then MsgN("MERCENARY") elseif client:IsHypnotist() then MsgN("HYPNOTIST") elseif client:IsGlitch() then MsgN("GLITCH") elseif client:IsJester() then MsgN("JESTER") elseif client:IsPhantom() then MsgN("PHANTOM") elseif client:IsZombie() then MsgN("ZOMBIE") elseif client:IsVampire() then MsgN("VAMPIRE") elseif client:IsSwapper() then MsgN("SWAPPER") elseif client:IsAssassin() then MsgN("ASSASSIN") elseif client:IsKiller() then MsgN("KILLER") elseif client:IsCannibal() then MsgN("CANNIBAL") elseif client:IsCrookedCop() then MsgN("CROOKED COP") else MsgN("INNOCENT") end end net.Receive("TTT_Role", ReceiveRole) local function ReceiveRoleList() local role = net.ReadUInt(4) local num_ids = net.ReadUInt(8) for i = 1, num_ids do local eidx = net.ReadUInt(7) + 1 -- we - 1 worldspawn=0 local ply = player.GetByID(eidx) if IsValid(ply) and ply.SetRole then ply:SetRole(role) if ply:IsTraitor() or ply:IsHypnotist() or ply:IsVampire() or ply:IsAssassin() or ply:IsZombie() then ply.traitor_gvoice = false -- assume traitorchat by default end end end end net.Receive("TTT_RoleList", ReceiveRoleList) -- Round state comm local function ReceiveRoundState() local o = GetRoundState() GAMEMODE.round_state = net.ReadUInt(3) if o ~= GAMEMODE.round_state then RoundStateChange(o, GAMEMODE.round_state) end MsgN("Round state: " .. GAMEMODE.round_state) end net.Receive("TTT_RoundState", ReceiveRoundState) -- Cleanup at start of new round function GM:ClearClientState() GAMEMODE:HUDClear() local client = LocalPlayer() if not client.SetRole then return end -- code not loaded yet client:SetRole(ROLE_INNOCENT) client.equipment_items = EQUIP_NONE client.equipment_credits = 0 client.bought = {} client.last_id = nil client.radio = nil client.called_corpses = {} VOICE.InitBattery() for _, p in pairs(player.GetAll()) do if IsValid(p) then p.sb_tag = nil p:SetRole(ROLE_INNOCENT) p.search_result = nil end end VOICE.CycleMuteState(MUTE_NONE) RunConsoleCommand("ttt_mute_team_check", "0") if GAMEMODE.ForcedMouse then gui.EnableScreenClicker(false) end end net.Receive("TTT_ClearClientState", GM.ClearClientState) function GM:CleanUpMap() -- Ragdolls sometimes stay around on clients. Deleting them can create issues -- so all we can do is try to hide them. for _, ent in pairs(ents.FindByClass("prop_ragdoll")) do if IsValid(ent) and CORPSE.GetPlayerNick(ent, "") ~= "" then ent:SetNoDraw(true) ent:SetSolid(SOLID_NONE) ent:SetColor(Color(0, 0, 0, 0)) -- Horrible hack to make targetid ignore this ent, because we can't -- modify the collision group clientside. ent.NoTarget = true end end -- This cleans up decals since GMod v100 game.CleanUpMap() end -- server tells us to call this when our LocalPlayer has spawned local function PlayerSpawn() local as_spec = net.ReadBit() == 1 if as_spec then TIPS.Show() else TIPS.Hide() end end net.Receive("TTT_PlayerSpawned", PlayerSpawn) local function PlayerDeath() TIPS.Show() end net.Receive("TTT_PlayerDied", PlayerDeath) function GM:ShouldDrawLocalPlayer(ply) return false end local view = { origin = vector_origin, angles = angle_zero, fov = 0 } function GM:CalcView(ply, origin, angles, fov) view.origin = origin view.angles = angles view.fov = fov -- first person ragdolling if ply:Team() == TEAM_SPEC and ply:GetObserverMode() == OBS_MODE_IN_EYE then local tgt = ply:GetObserverTarget() if IsValid(tgt) and (not tgt:IsPlayer()) then -- assume if we are in_eye and not speccing a player, we spec a ragdoll local eyes = tgt:LookupAttachment("eyes") or 0 eyes = tgt:GetAttachment(eyes) if eyes then view.origin = eyes.Pos view.angles = eyes.Ang end end end local wep = ply:GetActiveWeapon() if IsValid(wep) then local func = wep.CalcView if func then view.origin, view.angles, view.fov = func(wep, ply, origin * 1, angles * 1, fov) end end return view end function GM:AddDeathNotice() end function GM:DrawDeathNotice() end function GM:Think() for k, v in pairs(player.GetAll()) do if v:Alive() and v:GetNWBool("HauntedSmoke") then if not v.SmokeEmitter then v.SmokeEmitter = ParticleEmitter(v:GetPos()) end if not v.SmokeNextPart then v.SmokeNextPart = CurTime() end local pos = v:GetPos() + Vector(0, 0, 30) local client = LocalPlayer() if v.SmokeNextPart < CurTime() then if client:GetPos():Distance(pos) > 1000 then return end v.SmokeEmitter:SetPos(pos) v.SmokeNextPart = CurTime() + math.Rand(0.003, 0.01) local vec = Vector(math.Rand(-8, 8), math.Rand(-8, 8), math.Rand(10, 55)) local pos = v:LocalToWorld(vec) local particle = v.SmokeEmitter:Add("particle/snow.vmt", pos) particle:SetVelocity(Vector(0, 0, 4) + VectorRand() * 3) particle:SetDieTime(math.Rand(0.5, 2)) particle:SetStartAlpha(math.random(150, 220)) particle:SetEndAlpha(0) local size = math.random(4, 7) particle:SetStartSize(size) particle:SetEndSize(size + 1) particle:SetRoll(0) particle:SetRollDelta(0) particle:SetColor(0, 0, 0) end else if v.SmokeEmitter then v.SmokeEmitter:Finish() v.SmokeEmitter = nil end end end if GetConVar("ttt_export_player_data"):GetBool() then local client = LocalPlayer() local state = GetRoundState() == 3 and "1" or "0" local role = tostring(client:GetRole()) local alive = client:IsActive() and "1" or "0" local health = tostring(client:Health()) local data = state .. "," .. role .. "," .. alive .. "," .. health file.Write("playerdata/data.txt", data) end end function GM:Tick() local client = LocalPlayer() if IsValid(client) then if client:Alive() and client:Team() ~= TEAM_SPEC then WSWITCH:Think() RADIO:StoreTarget() end VOICE.Tick() end end -- Simple client-based idle checking local idle = { ang = nil, pos = nil, mx = 0, my = 0, t = 0 } function CheckIdle() local client = LocalPlayer() if not IsValid(client) then return end if not idle.ang or not idle.pos then -- init things idle.ang = client:GetAngles() idle.pos = client:GetPos() idle.mx = gui.MouseX() idle.my = gui.MouseY() idle.t = CurTime() return end if GetRoundState() == ROUND_ACTIVE and client:IsTerror() and client:Alive() then local idle_limit = GetGlobalInt("ttt_idle_limit", 300) or 300 if idle_limit <= 0 then idle_limit = 300 end -- networking sucks sometimes if client:GetAngles() ~= idle.ang then -- Normal players will move their viewing angles all the time idle.ang = client:GetAngles() idle.t = CurTime() elseif gui.MouseX() ~= idle.mx or gui.MouseY() ~= idle.my then -- Players in eg. the Help will move their mouse occasionally idle.mx = gui.MouseX() idle.my = gui.MouseY() idle.t = CurTime() elseif client:GetPos():Distance(idle.pos) > 10 then -- Even if players don't move their mouse, they might still walk idle.pos = client:GetPos() idle.t = CurTime() elseif CurTime() > (idle.t + idle_limit) then RunConsoleCommand("say", "(AUTOMATED MESSAGE) I have been moved to the Spectator team because I was idle/AFK.") timer.Simple(0.3, function() RunConsoleCommand("ttt_spectator_mode", 1) net.Start("TTT_Spectate") net.WriteBool(true) net.SendToServer() RunConsoleCommand("ttt_cl_idlepopup") end) elseif CurTime() > (idle.t + (idle_limit / 2)) then -- will repeat LANG.Msg("idle_warning") end end end function GM:OnEntityCreated(ent) -- Make ragdolls look like the player that has died if ent:IsRagdoll() then local ply = CORPSE.GetPlayer(ent) if IsValid(ply) then -- Only copy any decals if this ragdoll was recently created if ent:GetCreationTime() > CurTime() - 1 then ent:SnatchModelInstance(ply) end -- Copy the color for the PlayerColor matproxy local playerColor = ply:GetPlayerColor() ent.GetPlayerColor = function() return playerColor end end end return self.BaseClass.OnEntityCreated(self, ent) end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by heyqule. --- DateTime: 9/6/2021 1:34 AM --- local Table = require('__stdlib__/stdlib/utils/table') local ErmConfig = require('__enemyracemanager__/lib/global_config') local ErmForceHelper = require('__enemyracemanager__/lib/helper/force_helper') local AttackGroupChunkProcessor = {} AttackGroupChunkProcessor.CHUNK_SEARCH_RADIUS = 5 AttackGroupChunkProcessor.CHUNK_SIZE = 32 AttackGroupChunkProcessor.CHUNK_CENTER_POINT_RADIUS = AttackGroupChunkProcessor.CHUNK_SEARCH_RADIUS * 2 AttackGroupChunkProcessor.CHUNK_SEARCH_AREA = AttackGroupChunkProcessor.CHUNK_SEARCH_RADIUS * AttackGroupChunkProcessor.CHUNK_SIZE AttackGroupChunkProcessor.MINIMUM_SPAWNABLE = 10 AttackGroupChunkProcessor.RETRY = 4 AttackGroupChunkProcessor.AREA_NORTH = {1,2} AttackGroupChunkProcessor.AREA_SOUTH = {3,4} AttackGroupChunkProcessor.AREA_WEST = {1,4} AttackGroupChunkProcessor.AREA_EAST = {2,3} AttackGroupChunkProcessor.DIRECTION_CURSOR = {'northwest', 'northeast', 'southeast', 'southwest'} AttackGroupChunkProcessor.NORMAL_PRECISION_TARGET_TYPES = { 'mining-drill', 'rocket-silo', 'artillery-turret', } AttackGroupChunkProcessor.HARDCORE_PRECISION_TARGET_TYPES = { 'lab', 'furnace', } AttackGroupChunkProcessor.EXTREME_PRECISION_TARGET_TYPES = { 'assembling-machine', 'generator', 'solar-panel', 'accumulator', } local create_race_cursor_node = function() return { current_direction = 1, -- corresponding to DIRECTION_CURSOR rotatable_directions = {1, 2, 3, 4}, current_node_name = { northwest = nil, northeast = nil, southeast = nil, southwest = nil, } } end local get_chunk_node_list = function() return { chunks = {}, head_node_name = nil, new_node_name = nil, } end local get_spawn_area = function(position) local distance = AttackGroupChunkProcessor.CHUNK_SEARCH_AREA local area = { {position.x - distance, position.y - distance}, {position.x + distance, position.y + distance} } return area end local get_attack_area = function(position) local distance = 32 local area = { {position.x, position.y}, {position.x + distance, position.y + distance} } return area end local set_up_rotatable_direction = function(race_cursor, race_name, surface) if ErmConfig.mapgen_is_2_races_split() then if settings.startup['enemyracemanager-2way-group-enemy-orientation'].value == X_AXIS then if ErmConfig.positive_axis_race() == race_name then race_cursor.rotatable_directions = AttackGroupChunkProcessor.AREA_WEST elseif ErmConfig.negative_axis_race() == race_name then race_cursor.rotatable_directions = AttackGroupChunkProcessor.AREA_EAST else race_cursor.rotatable_directions = {} end else if ErmConfig.positive_axis_race() == race_name then race_cursor.rotatable_directions = AttackGroupChunkProcessor.AREA_SOUTH elseif ErmConfig.negative_axis_race() == race_name then race_cursor.rotatable_directions = AttackGroupChunkProcessor.AREA_NORTH else race_cursor.rotatable_directions = {} end end end end local init_spawnable_chunk = function(surface, forced_init) if global.attack_group_spawnable_chunk[surface.name] == nil or forced_init then global.attack_group_spawnable_chunk[surface.name] = { northwest = get_chunk_node_list(), northeast = get_chunk_node_list(), southeast = get_chunk_node_list(), southwest = get_chunk_node_list(), race_cursors = { }, } for _, race in pairs(ErmConfig.get_enemy_races()) do global.attack_group_spawnable_chunk[surface.name].race_cursors[race] = create_race_cursor_node() set_up_rotatable_direction(global.attack_group_spawnable_chunk[surface.name].race_cursors[race], race, surface) end end end local is_cachable_spawn_position = function(position) return position.x % AttackGroupChunkProcessor.CHUNK_CENTER_POINT_RADIUS == 0 and position.y % AttackGroupChunkProcessor.CHUNK_CENTER_POINT_RADIUS == 0 end --- Weird ass Double Linked List LOL local create_spawnable_node = function(x, y) return { x = x, y = y, next_node_name = nil, prev_node_name = nil, } end local get_location_name = function(x, y) return tostring(x)..'/'..tostring(y) end local append_chunk = function(chunk_data, x, y) local node_name = get_location_name(x,y) if chunk_data.chunks[node_name] then return end local node = create_spawnable_node(x, y) local prev_name = nil if chunk_data.head_node_name == nil then chunk_data.head_node_name = node_name else prev_name = chunk_data.new_node_name node.prev_node_name = chunk_data.new_node_name end if chunk_data.chunks[prev_name] then chunk_data.chunks[prev_name].next_node_name = node_name end chunk_data.chunks[node_name] = node chunk_data.new_node_name = node_name end local remove_chunk_from_list = function(chunk_set, node, node_name) local next_node_name = node.next_node_name local prev_node_name = node.prev_node_name if node_name == chunk_set.head_node_name then --- Reset Head and the next node to be head chunk_set.head_node_name = next_node_name if chunk_set.chunks[next_node_name] then chunk_set.chunks[next_node_name].prev_node_name = nil end elseif node.next_node_name == nil then --- Change Last node if chunk_set.chunks[prev_node_name] then chunk_set.chunks[prev_node_name].next_node_name = nil end else --- Rewire next/prev in middle node local prev_node = chunk_set.chunks[prev_node_name] local next_node = chunk_set.chunks[next_node_name] if prev_node then chunk_set.chunks[prev_node_name].next_node_name = get_location_name(next_node.x, next_node.y) end if next_node then chunk_set.chunks[next_node_name].prev_node_name = get_location_name(prev_node.x, prev_node.y) end end chunk_set.chunks[node_name] = nil local new_node_length = Table.count_keys(chunk_set.chunks) if new_node_length == 0 then chunk_set.head_node_name = nil chunk_set.new_node_name = nil end end ----- Start Spawnable Chunk Private Functions ----- --- --- Remove chunk that is no longer have spawner on it. But it preserve at least 5 blocks to track enemy expansions. --- local remove_spawnable_chunk = function(surface, direction, position) local chunk_set = global.attack_group_spawnable_chunk[surface.name][direction] local node_name = get_location_name(position.x, position.y) local node_length = Table.count_keys(chunk_set.chunks) local node = chunk_set.chunks[node_name] if node == nil and node_length < AttackGroupChunkProcessor.MINIMUM_SPAWNABLE then return end remove_chunk_from_list(chunk_set, node, node_name) end local add_spawnable_chunk_to_list = function(surface, x, y) if y < 0 then if x < 0 then append_chunk(global.attack_group_spawnable_chunk[surface.name].northwest, x, y) else append_chunk(global.attack_group_spawnable_chunk[surface.name].northeast, x, y) end else if x < 0 then append_chunk(global.attack_group_spawnable_chunk[surface.name].southwest, x, y) else append_chunk(global.attack_group_spawnable_chunk[surface.name].southeast, x, y) end end end local add_spawnable_chunk = function(surface, chunk) local position = { x = chunk.x * AttackGroupChunkProcessor.CHUNK_SIZE, y = chunk.y * AttackGroupChunkProcessor.CHUNK_SIZE } local spawner = surface.find_entities_filtered ({ area = get_spawn_area(position), type = 'unit-spawner', limit = 1 }) local total_spawner = #spawner if total_spawner > 0 then add_spawnable_chunk_to_list(surface, position.x, position.y) return true end return false end local remove_chunk_without_spawner = function(surface, position, race_name) local spawner = surface.find_entities_filtered ({ area = get_spawn_area(position), force = ErmForceHelper.get_all_enemy_forces(), type = 'unit-spawner', limit = 1 }) if #spawner == 0 then local race_cursor = global.attack_group_spawnable_chunk[surface.name].race_cursors[race_name] local current_direction = AttackGroupChunkProcessor.DIRECTION_CURSOR[ race_cursor.rotatable_directions[race_cursor.current_direction] ] remove_spawnable_chunk(surface, current_direction, position) end end local find_spawn_position = function(surface, race_name) local position = nil local position_node = nil local race_cursor = global.attack_group_spawnable_chunk[surface.name].race_cursors[race_name] local total_rotatable_directions = #race_cursor.rotatable_directions if total_rotatable_directions == 0 then return nil end --- Swap spawn direction local rotatable_direction = race_cursor.current_direction % total_rotatable_directions + 1 race_cursor.current_direction = rotatable_direction local current_direction = AttackGroupChunkProcessor.DIRECTION_CURSOR[ race_cursor.rotatable_directions[race_cursor.current_direction] ] local current_chunk_list = global.attack_group_spawnable_chunk[surface.name][current_direction] local current_race_cursor_name = race_cursor.current_node_name[current_direction] if current_race_cursor_name == nil and current_chunk_list.head_node_name ~= nil then --- Pick head node race_cursor.current_node_name[current_direction] = current_chunk_list.head_node_name position_node = current_chunk_list.chunks[current_chunk_list.head_node_name] elseif current_race_cursor_name ~= '' and current_chunk_list.head_node_name ~= nil then position_node = current_chunk_list.chunks[current_race_cursor_name] --- Pick Next node until the end, then pick head and start again if position_node and position_node.next_node_name then race_cursor.current_node_name[current_direction] = position_node.next_node_name elseif position_node then race_cursor.current_node_name[current_direction] = current_chunk_list.head_node_name end end if position_node then position = {x = position_node.x, y = position_node.y} return position end return nil end ----- End Spawnable Chunk Private Functions ----- ----- Start Attackable Chunk Private Functions ----- local init_attackable_chunk = function(surface, forced_init) if global.attack_group_attackable_chunk[surface.name] == nil or forced_init then global.attack_group_attackable_chunk[surface.name] = get_chunk_node_list() global.attack_group_attackable_chunk[surface.name].current_node_name = nil global.attack_group_attackable_chunk[surface.name].current_direction = 1 end end local is_cachable_attack_position = function(surface, area) local entities = surface.find_entities_filtered ({ area = area, type = AttackGroupChunkProcessor.NORMAL_PRECISION_TARGET_TYPES, limit = 1 }) if #entities ~= 0 then return true end return false end local add_attackable_chunk = function(surface, chunk) local position = { x = chunk.x * AttackGroupChunkProcessor.CHUNK_SIZE, y = chunk.y * AttackGroupChunkProcessor.CHUNK_SIZE } local node_name = get_location_name(position.x, position.y) if global.attack_group_attackable_chunk[surface.name].chunks[node_name] == nil then append_chunk(global.attack_group_attackable_chunk[surface.name], position.x, position.y) return true end return false end local find_attack_position = function(surface) local surface_data = global.attack_group_attackable_chunk[surface.name] if surface_data.current_node_name == nil and surface_data.head_node_name then surface_data.current_node_name = surface_data.head_node_name return surface_data.chunks[surface_data.current_node_name] end if surface_data.current_node_name ~= nil then surface_data.current_node_name = surface_data.chunks[surface_data.current_node_name].next_node_name if surface_data.current_node_name == nil then surface_data.current_node_name = surface_data.head_node_name end return surface_data.chunks[surface_data.current_node_name] end return nil end local reindex_surface = function(surface) init_spawnable_chunk(surface, true) init_attackable_chunk(surface, true) local spawn_chunk = 0 local attack_chunk = 0 for chunk in surface.get_chunks() do if is_cachable_spawn_position(chunk) then if add_spawnable_chunk(surface, chunk) then spawn_chunk = spawn_chunk + 1 end end if is_cachable_attack_position(surface, chunk.area) then if add_attackable_chunk(surface, chunk) then attack_chunk = attack_chunk + 1 end end end if spawn_chunk == 0 then global.attack_group_spawnable_chunk[surface.name] = nil spawn_chunk = 0 end if attack_chunk == 0 then global.attack_group_attackable_chunk[surface.name] = nil attack_chunk = 0 end return spawn_chunk, attack_chunk end ----- End Attackable Chunk Private Functions ----- function AttackGroupChunkProcessor.init_globals() global.attack_group_spawnable_chunk = global.attack_group_spawnable_chunk or {} global.attack_group_attackable_chunk = global.attack_group_attackable_chunk or {} end function AttackGroupChunkProcessor.init_index() game.print('[ERM] Re-indexing Attack Group Chunks...') local profiler = game.create_profiler() local spawn_chunk = 0 local attack_chunk = 0 local total_surfaces = 0 for _, surface in pairs(game.surfaces) do if surface.valid then current_spawn_chunk, current_attack_chunk = reindex_surface(surface) spawn_chunk = spawn_chunk + current_spawn_chunk attack_chunk = attack_chunk + current_attack_chunk total_surfaces = total_surfaces + 1 end end profiler.stop() game.print('[ERM] Total Processed Surfaces: '..tostring(total_surfaces)) game.print('[ERM] Total Cached Spawnable Chunks: '..tostring(spawn_chunk)) game.print('[ERM] Total Cached Attackable Chunks: '..tostring(attack_chunk)) game.print({'', '[ERM] Attack Group Chunk Re-indexed: ', profiler}) end --- on_robot_built_entity and on_built_entity --- https://lua-api.factorio.com/latest/events.html#on_built_entity --- https://lua-api.factorio.com/latest/events.html#on_robot_built_entity function AttackGroupChunkProcessor.add_attackable_chunk_by_entity(entity) local surface = entity.surface local position = entity.position position = { x = math.floor(position.x / AttackGroupChunkProcessor.CHUNK_SIZE), y = math.floor(position.y / AttackGroupChunkProcessor.CHUNK_SIZE) } init_attackable_chunk(surface) add_attackable_chunk(surface, position) end function AttackGroupChunkProcessor.add_spawnable_chunk(surface, position) if is_cachable_spawn_position(position) then init_spawnable_chunk(surface) add_spawnable_chunk(surface, position) end end function AttackGroupChunkProcessor.get_built_entity_event_filter() local filter = {} for _, type in pairs(AttackGroupChunkProcessor.NORMAL_PRECISION_TARGET_TYPES) do table.insert(filter, {filter = "type", type = type}) end return filter end function AttackGroupChunkProcessor.pick_spawn_location(surface, force) local race_name = ErmForceHelper.extract_race_name_from(force.name) local i = 0 local entities = {} repeat local position = find_spawn_position(surface, race_name) if position then entities = surface.find_entities_filtered ({ area = get_spawn_area(position), force = force, type = 'unit-spawner', limit = 10 }) end if position and next(entities) == nil then remove_chunk_without_spawner(surface, position, race_name) end i = i + 1 until i == AttackGroupChunkProcessor.RETRY or next(entities) ~= nil if next(entities) == nil then return nil end local entity = entities[math.random(1, #entities)] return entity end function AttackGroupChunkProcessor.pick_attack_location(surface, group) local position_node = nil local retry = 0 repeat local entities = nil position_node = find_attack_position(surface) if position_node then entities = surface.find_entities_filtered ({ area = get_attack_area(position_node), type = AttackGroupChunkProcessor.NORMAL_PRECISION_TARGET_TYPES, limit = 1 }) end if position_node and next(entities) == nil then local surface_data = global.attack_group_attackable_chunk[surface.name] remove_chunk_from_list(surface_data, position_node, get_location_name(position_node.x, position_node.y)) surface_data.current_node_name = nil position_node = nil end retry = retry + 1 until position_node ~= nil or retry == AttackGroupChunkProcessor.RETRY if position_node then return {x = position_node.x, y = position_node.y} else local enemy = group.surface.find_nearest_enemy { position = group.position, force = group.force, max_distance = 3200 } if enemy then return enemy.position end end return nil end AttackGroupChunkProcessor.can_attack = function(surface) if global.attack_group_spawnable_chunk[surface.name] ~= nil and global.attack_group_attackable_chunk[surface.name] ~= nil then return true end return false end AttackGroupChunkProcessor.remove_surface = function(surface_name) if global.attack_group_spawnable_chunk[surface_name] ~= nil then global.attack_group_spawnable_chunk[surface_name] = nil end if global.attack_group_attackable_chunk[surface_name] ~= nil then global.attack_group_attackable_chunk[surface_name] = nil end end return AttackGroupChunkProcessor
local image_component = { image_component = "image", load_image = function(self, name) self._image = love.graphics.newImage(name) self._image:setFilter("nearest", "nearest") end, draw_image = function(self, x, y) love.graphics.draw(self._image, x, y) end, image_width = function(self) return self._image:getWidth() end, image_height = function(self) return self._image:getHeight() end, } return image_component
-- Run this test with :source % local idx = 1 local cases = { { prompt = "Complete file: ", completion = "file", }, { prompt = "Complete cmd: ", completion = "command", }, { prompt = "Complete custom: ", completion = "custom,CustomComplete", }, { prompt = "Complete customlist: ", completion = "customlist,CustomCompleteList", }, } vim.cmd([[ function! CustomComplete(arglead, cmdline, cursorpos) return "first\nsecond\nthird" endfunction function! CustomCompleteList(arglead, cmdline, cursorpos) return ['first', 'second', 'third'] endfunction ]]) local function next() local opts = cases[idx] if opts then idx = idx + 1 vim.ui.input(opts, next) end end next()
local function doTransformCoalBasins(cbPos) local tile = Position(cbPos):getTile() if tile then local thing = tile:getItemById(1485) if thing then thing:transform(1484) end end end local config = { [0] = 50015, [1] = 50016, [2] = 50017, [3] = 50018, [4] = 50019, coalBasins = { {x = 32214, y = 31850, z = 15}, {x = 32215, y = 31850, z = 15}, {x = 32216, y = 31850, z = 15} }, effects = { [0] = { {x= 32217, y= 31845, z= 14}, {x= 32218, y= 31845, z= 14}, {x= 32219, y= 31845, z= 14}, {x= 32220, y= 31845, z= 14}, {x= 32217, y= 31843, z= 14}, {x= 32218, y= 31842, z= 14}, {x= 32219, y= 31841, z= 14} }, [1] = { {x= 32217, y= 31844, z= 14}, {x= 32218, y= 31844, z= 14}, {x= 32219, y= 31843, z= 14}, {x= 32220, y= 31845, z= 14}, {x= 32219, y= 31845, z= 14} }, [2] = { {x= 32217, y= 31842, z= 14}, {x= 32219, y= 31843, z= 14}, {x= 32219, y= 31845, z= 14}, {x= 32218, y= 31844, z= 14}, {x= 32217, y= 31844, z= 14}, {x= 32217, y= 31845, z= 14} }, [3] = { {x= 32217, y= 31845, z= 14}, {x= 32218, y= 31846, z= 14}, {x= 32218, y= 31844, z= 14}, {x= 32219, y= 31845, z= 14}, {x= 32220, y= 31846, z= 14} }, [4] = { {x= 32219, y= 31841, z= 14}, {x= 32219, y= 31842, z= 14}, {x= 32219, y= 31846, z= 14}, {x= 32217, y= 31843, z= 14}, {x= 32217, y= 31844, z= 14}, {x= 32217, y= 31845, z= 14}, {x= 32218, y= 31843, z= 14}, {x= 32218, y= 31845, z= 14} }, }, } function onUse(player, item, fromPosition, target, toPosition, isHotkey) local switchNum = Game.getStorageValue("switchNum") if switchNum == -1 then Game.setStorageValue("switchNum", 0) end local table = config[switchNum] if not table then return true end if player:getStorageValue(Storage.QueenOfBansheesQuest.ThirdSeal) < 1 then if item.uid == table then item:transform(1945) Game.setStorageValue("switchNum", math.max(1, Game.getStorageValue("switchNum") + 1)) toPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE) for i = 1, #config.effects[switchNum] do Position(config.effects[switchNum][i]):sendMagicEffect(CONST_ME_ENERGYHIT) end if Game.getStorageValue("switchNum") == 5 then for i = 1, #config.coalBasins do doTransformCoalBasins(config.coalBasins[i]) end end else toPosition:sendMagicEffect(CONST_ME_ENERGYHIT) end else return false end return true end
local LoginSelectRoleView = BaseClass() function LoginSelectRoleView:DefaultVar( ) require("Game/Login/LoginSceneBgView"):SetActive(true) return { UIConfig = { prefab_path = "Assets/AssetBundleRes/ui/login/LoginSelectRoleView.prefab", canvas_name = "Normal", components = { {UI.HideOtherView}, {UI.DelayDestroy, {delay_time=5}}, }, }, } end function LoginSelectRoleView:OnLoad( ) local names = { "item_scroll","role_con","role_tip","start:obj","item_scroll/Viewport/item_con", } UI.GetChildren(self, self.transform, names) self.transform.sizeDelta = Vector2.zero self:AddEvents() self:UpdateView() end function LoginSelectRoleView:AddEvents( ) local on_click = function ( click_btn ) if click_btn == self.start_obj then GlobalEventSystem:Fire(LoginConst.Event.SelectRoleEnterGame, self.select_role_id) CookieWrapper:GetInstance():SaveCookie(CookieLevelType.Common, CookieTimeType.TYPE_ALWAYS, CookieKey.LastSelectRoleID, self.select_role_id) end end UIHelper.BindClickEvent(self.start_obj, on_click) end function LoginSelectRoleView:UpdateView() local role_list = LoginModel:GetInstance():GetRoleList() self.data = role_list if not role_list or #role_list <= 0 then return end self.role_item_com = self.role_item_com or UIMgr:AddUIComponent(self, UI.ItemListCreator) --最少要显示3个 local min_role_num = 3 if #self.data < min_role_num then for i=1,min_role_num - #self.data do table.insert(self.data, false) end end local info = { data_list = self.data, item_con = self.item_con, prefab_path = GameResPath.GetFullUIPath("login/LoginSelectRoleItem.prefab"), item_height = 121, space_y = 15, scroll_view = self.item_scroll, child_names = { "head_bg:img:obj","name_bg:img:obj","role_lv:txt","role_name:txt","role_head:raw:obj", }, on_update_item = function(item, i, v) self:UpdateRoleHeadItems(item, i, v) end, } self.role_item_com:UpdateItems(info) local best_role_id = nil local last_role_id = CookieWrapper.Instance:GetCookie(CookieLevelType.Common, CookieKey.LastSelectRoleID) if last_role_id then for i,v in ipairs(self.data) do if v and v.role_id == last_role_id then best_role_id = v.role_id break end end end if #self.data > 0 and not best_role_id then best_role_id = self.data[1].role_id end if best_role_id then self:SetCurSelectRoleID(best_role_id) end end function LoginSelectRoleView:UpdateRoleHeadItems( item, index, v ) item.data = v if item.data then item.role_name_txt.text = item.data.name local curLv = item.data.base_info and item.data.base_info.level or 0 item.role_lv_txt.text = curLv.."级" local headRes = GameResPath.GetRoleHeadRes(item.data.career, 0) UIHelper.SetRawImage(item.role_head_raw, headRes) item.role_head_obj:SetActive(true) item.name_bg_obj:SetActive(true) else item.role_name_txt.text = "" item.role_lv_txt.text = "" item.role_head_obj:SetActive(false) UIHelper.SetImage(item.head_img, "login/login_circle_head1_1.png") item.name_bg_obj:SetActive(false) end if not item.UpdateSelect and item.data then item.UpdateSelect = function (item) local is_cur_select = self.select_role_id == item.data.role_id UIHelper.SetImage(item.name_bg_img, is_cur_select and "login/login_role_name_bg_sel.png" or "login/login_role_name_bg_nor.png", true) UIHelper.SetImage(item.head_bg_img, is_cur_select and "login/login_role_item_bg_sel.png" or "login/login_role_item_bg_nor.png", true) -- self.outline_color_sel = self.outline_color_sel or Color(143/255, 40/255, 75/255, 1) -- self.outline_color_nor = self.outline_color_nor or Color(84/255, 31/255, 49/255, 1) -- item.role_name_outline.effectColor = is_cur_select and self.outline_color_sel or self.outline_color_nor -- item.role_lv_outline.effectColor = is_cur_select and self.outline_color_sel or self.outline_color_nor end end if item.data then item:UpdateSelect() end if not item.had_bind_click then item.had_bind_click = true local on_item_click = function ( ) if item.data then self:SetCurSelectRoleID(item.data.role_id) else --显示创建角色界面 local view = require("Game/Login/LoginCreateRoleView").New() UIMgr:Show(view) end end UIHelper.BindClickEvent(item.gameObject, on_item_click) end end function LoginSelectRoleView:GetRoleInfoByID( role_id ) for k,v in pairs(self.data) do if v.role_id == role_id then return v end end return nil end function LoginSelectRoleView:SetPlayModelInfo( role_vo ) local show_data = { layer_name = self.layer_name, action_name_list = {"show"}, can_rotate = true, scale = 200, position = Vector3(0, 0, 0), need_replay_action = "show", --界面从隐藏到显示,需要重新摆pose } -- lua_resM:SetRoleModelByVo(self, self.role_con, role_vo, show_data) end function LoginSelectRoleView:SetCurSelectRoleID( role_id ) if self.select_role_id == role_id or not self.data then return end self.select_role_id = role_id self.select_role_info = self:GetRoleInfoByID(role_id) if not self.select_role_info then return end self.role_item_com:IterateItems(function(item, i) if item.UpdateSelect then item:UpdateSelect() end end) self.select_role_career = self.select_role_info.career UIHelper.SetImage(self.role_tip_img, "login/login_role_tip_"..self.select_role_career..".png", true) -- self.select_role_login_day = self.select_role_info.login_day -- self.select_role_Create_time = self.select_role_info.create_role_time self:SetPlayModelInfo(self.select_role_info) end function LoginSelectRoleView:OnClose( ) require("Game/Login/LoginSceneBgView"):SetActive(false) end return LoginSelectRoleView
function orcworg_OnCombat(pUnit, event) pUnit:RegisterEvent("orcworg_Transform",1000,0) end function orcworg_Transform(pUnit, event) if pUnit:GetHealthPct() < 45 then pUnit:RemoveEvents() pUnit:FullCastSpell(14202) pUnit:SetModel(11419) pUnit:SetScale(2) end end function orcworg_OnDied(pUnit, event) pUnit:RemoveEvents() end RegisterUnitEvent(65006, 1, "orcworg_OnCombat") RegisterUnitEvent(65006, 4, "orcworg_OnDied")
return { dice = { grims = 0, tomes = 0, bonus = 0 }, short_title = "", title_placement = "after", difficulty_levels = { "easy", "normal", "hard", "harder", "hardest", "survival_hard", "survival_harder", "survival_hardest" }, incompatible_with_all = false, compatible_with_all = false, incompatible_with = {}, compatible_with = {}, enable_before_these = {}, enable_after_these = {} }
return {'aan','aanaarden','aanaarding','aanaardploeg','aanbakken','aanbaksel','aanbedene','aanbeeld','aanbeeldsblok','aanbehoren','aanbelanden','aanbelang','aanbelangen','aanbellen','aanbenen','aanberming','aanbesteden','aanbesteder','aanbesteding','aanbestedingsbeleid','aanbestedingsprocedure','aanbestedingsregel','aanbestedingsregeling','aanbestedingsvoorwaarde','aanbetalen','aanbetaling','aanbevelen','aanbevelenswaard','aanbevelenswaardig','aanbeveling','aanbevelingsbrief','aanbevelingscomite','aanbevolen','aanbevolenen','aanbiddelijk','aanbidden','aanbidder','aanbidding','aanbidster','aanbieden','aanbieder','aanbieding','aanbiedingsbrief','aanbiedingsfolder','aanbiedingsprijs','aanbijten','aanbinden','aanblaffen','aanblazen','aanblazing','aanblijven','aanblik','aanblikken','aanbod','aanbodbeleid','aanbodcurve','aanbodeconomie','aanbodgericht','aanbodkant','aanbodoverschot','aanbodverhouding','aanbodzijde','aanboorden','aanboren','aanbotsen','aanbouw','aanbouwen','aanbouwing','aanbouwsel','aanbraden','aanbranden','aanbrassen','aanbreien','aanbreken','aanbreng','aanbrengen','aanbrenger','aanbrenging','aanbrengpremie','aanbrengst','aanbrug','aandacht','aandachtig','aandachtigheid','aandachtsaspect','aandachtsgebied','aandachtsgroep','aandachtsgroepen','aandachtspunt','aandachtspuntenlijst','aandachtsstreep','aandachtsteken','aandachtsterrein','aandachtstreep','aandachtstreepje','aandachtstreepjes','aandachtstrekker','aandachtsveld','aandachtsverlies','aandachttrekker','aandachttrekkerij','aandak','aandammen','aandamming','aandeel','aandeelbewijs','aandeelhoudend','aandeelhouder','aandeelhoudersbelang','aandeelhoudersbewijs','aandeelhouderschap','aandeelhouderscommissie','aandeelhoudersovereenkomst','aandeelhoudersstructuur','aandeelhoudersvergadering','aandeelhouderswaarde','aandeelhoudster','aandeelkoers','aandelenadvies','aandelenbelang','aandelenbelegger','aandelenbelegging','aandelenbeurs','aandelenbezit','aandelenbezitter','aandelenemissie','aandelenfonds','aandelenhandel','aandelenindex','aandeleninkoop','aandelenkapitaal','aandelenkoers','aandelenkoop','aandelenkorf','aandelenlease','aandelenmarkt','aandelenomzet','aandelenoptie','aandelenoptieplan','aandelenoptieregeling','aandelenoverdracht','aandelenpakket','aandelenplan','aandelenportefeuille','aandelenpositie','aandelenprogramma','aandelenregister','aandelenrekening','aandelenruil','aandelenselectie','aandelensplitsing','aandelensysteem','aandelentransactie','aandelenuitgifte','aandelenverhouding','aandelenverkoop','aandenken','aandienen','aandijken','aandijking','aandikken','aandoen','aandoening','aandoenlijk','aandoenlijkheid','aandraagster','aandraaien','aandragen','aandrager','aandrang','aandraven','aandrentelen','aandrift','aandrijfas','aandrijfketting','aandrijfkracht','aandrijflijn','aandrijfmechanisme','aandrijfmotor','aandrijfriem','aandrijfsysteem','aandrijfwiel','aandrijven','aandrijver','aandrijving','aandringen','aandringer','aandringers','aandrukken','aandrukkracht','aandrukrol','aanduiden','aanduiding','aandurven','aanduwen','aandweilen','aaneen','aaneenbinden','aaneenflansen','aaneengeschakeld','aaneengesloten','aaneengroeien','aaneengroeiing','aaneenhangen','aaneenhechten','aaneenkleven','aaneenklinken','aaneenknopen','aaneenkoeken','aaneenkoppelen','aaneenkoppeling','aaneenlijmen','aaneennaaien','aaneenpassen','aaneenrijgen','aaneenrijging','aaneenschakelen','aaneenschakeling','aaneenschrijven','aaneensluiten','aaneensluiting','aaneensmeden','aaneenvoegen','aaneenvoeging','aaneenzetten','aanfietsen','aanflitsen','aanfloepen','aanfluiten','aanfluiting','aanfok','aanfokken','aanfokking','aangaan','aangaande','aangapen','aangeblazen','aangeboden','aangebonden','aangeboren','aangebouwd','aangebrand','aangebreid','aangedaan','aangedanen','aangedraaid','aangeduid','aangeefster','aangegeven','aangehaald','aangehoudene','aangehuwd','aangekaart','aangeklaagde','aangekleed','aangeknipt','aangekondigden','aangekweekt','aangeladen','aangeland','aangelande','aangeleerd','aangelegd','aangelegen','aangelegenheid','aangemerkt','aangemeten','aangenaam','aangenomen','aangepast','aangerukt','aangeschakeld','aangeschoten','aangeschreven','aangeschrevene','aangeschroefd','aangeslagen','aangeslibd','aangesloten','aangeslotene','aangespen','aangesprokene','aangesteld','aangestoken','aangetast','aangetekend','aangetogen','aangetrouwd','aangevallene','aangeven','aangever','aangevoerd','aangewezen','aangewezene','aangezet','aangezicht','aangezichtsligging','aangezichtspijn','aangezien','aangeerfd','aangeerfde','aangieren','aangieten','aangifte','aangiftebehandeling','aangiftebereidheid','aangiftebiljet','aangifteformulier','aangifteplicht','aangifteverplichting','aangiftevolgnummer','aangloeien','aangluren','aangolven','aangooien','aangorden','aangraven','aangrenzen','aangrenzend','aangrijnzen','aangrijpen','aangrijpend','aangrijping','aangrijpingspunt','aangrimmen','aangroei','aangroeien','aangroeiing','aangroeipremie','aangroeisel','aangroeiwerend','aanhaken','aanhalen','aanhalerig','aanhalig','aanhaligheid','aanhaling','aanhalingsteken','aanhalingstekens','aanhang','aanhangen','aanhanger','aanhangig','aanhangmotor','aanhangsel','aanhangsels','aanhangster','aanhangwagen','aanhankelijk','aanhankelijkheid','aanhankelijkheidsbetuiging','aanharken','aanhebben','aanhechten','aanhechting','aanhechtingspunt','aanhechtsel','aanhef','aanheffen','aanhikken','aanhinken','aanhitsen','aanhitser','aanhitsing','aanhobbel','aanhobbelen','aanhollen','aanhoorder','aanhoren','aanhorig','aanhorigheden','aanhorigheid','aanhouden','aanhoudend','aanhoudendheid','aanhouder','aanhouding','aanhoudingsbevel','aanhoudingseenheid','aanhoudingsmandaat','aanhoudster','aanhuppelen','aanhuwing','aanjaagfunctie','aanjagen','aanjager','aankaarten','aankakken','aankalken','aankappen','aankijken','aanklaagster','aanklacht','aanklagen','aanklager','aanklampen','aanklamping','aankleden','aankleding','aanklemmen','aankleven','aankleving','aanklikbaar','aanklikken','aanklinken','aanklooien','aankloppen','aanklotsen','aanknippen','aanknoeien','aanknopen','aanknoping','aanknopingspunt','aankoeken','aankoersen','aankomeling','aankomen','aankomend','aankomst','aankomsthal','aankomstplaats','aankomsttijd','aankondigen','aankondiger','aankondiging','aankondigster','aankoop','aankoopakte','aankoopbedrag','aankoopbeleid','aankoopbeslissing','aankoopbewijs','aankoopbewijzen','aankoopbon','aankoopbudget','aankoopcentrale','aankoopdatum','aankoopdirecteur','aankoopfonds','aankoopfrequentie','aankoopgedrag','aankoopkoers','aankoopkosten','aankoopkracht','aankooplimiet','aankoopoptie','aankooppatroon','aankoopprijs','aankoopproces','aankoopsom','aankoopwaarde','aankopen','aankoper','aankoppelen','aankoppeling','aankorsting','aankrijgen','aankruien','aankruisen','aankunnen','aankweek','aankweken','aankweking','aanlaat','aanlachen','aanladen','aanlanden','aanlandig','aanlanding','aanlandingspunt','aanlappen','aanlassen','aanleg','aanleggen','aanlegger','aanleghaven','aanlegkosten','aanlegplaats','aanlegsteiger','aanlegster','aanlegvergunning','aanleiding','aanlengen','aanleren','aanleunen','aanleuning','aanleunwoning','aanleveren','aanlevering','aanlichten','aanliggen','aanliggend','aanlijken','aanlijmen','aanlijnen','aanlijngebod','aanloeien','aanloeren','aanloeven','aanloggen','aanlokkelijk','aanlokkelijkheid','aanlokken','aanlokking','aanloop','aanloopfase','aanloophaven','aanloophuis','aanloopkleur','aanloopkosten','aanloopperiode','aanloopprobleem','aanlooproute','aanloopspreekuur','aanlooptijd','aanlooptransformator','aanloopverlies','aanlopen','aanmaak','aanmaakblokje','aanmaakhout','aanmaakhoutje','aanmaakkosten','aanmaken','aanmanen','aanmaning','aanmaningenprocedure','aanmaningensysteem','aanmaningsbrief','aanmaningstekst','aanmarcheren','aanmatigen','aanmatigend','aanmatiging','aanmeldcentrum','aanmelden','aanmelder','aanmelding','aanmeldingsbon','aanmeldingsdatum','aanmeldingsformulier','aanmeldingsprocedure','aanmeldingspunt','aanmeldingstermijn','aanmengen','aanmenging','aanmeren','aanmerkelijk','aanmerken','aanmerking','aanmeten','aanminnig','aanminnigheid','aanmodderen','aanmoedigen','aanmoediging','aanmoedigingsbeleid','aanmoedigingspremie','aanmoedigingsprijs','aanmoedigingssubsidie','aanmoeten','aanmonding','aanmonsteren','aanmonstering','aanmunten','aanmunting','aannaaien','aanname','aannamebeleid','aanneembaar','aanneemsom','aanneemster','aannemelijk','aannemelijkheid','aannemen','aannemer','aannemerij','aannemersbedrijf','aannemerscombinatie','aannemersfirma','aannemersmaterieel','aannemerswereld','aanneming','aannemingsbedrijf','aannemingssom','aanpak','aanpakken','aanpalend','aanpappen','aanpasbaar','aanpassen','aanpassing','aanpassingsbeleid','aanpassingsfactor','aanpassingskosten','aanpassingsmoeilijkheden','aanpassingsperiode','aanpassingsprobleem','aanpassingsproces','aanpassingsprogramma','aanpassingsstoornis','aanpassingsvermogen','aanpersen','aanpezen','aanpikken','aanplakbiljet','aanplakbord','aanplakbrief','aanplakken','aanplakker','aanplakking','aanplakzuil','aanplant','aanplanten','aanplanting','aanplempen','aanplemping','aanploegen','aanporren','aanpoten','aanpraten','aanpreken','aanprijzen','aanprijzer','aanprijzing','aanprikkelen','aanprikkeling','aanprikken','aanpunten','aanpunter','aanpunting','aanraakscherm','aanraden','aanrader','aanraken','aanraking','aanrakingspunt','aanranden','aanrander','aanranding','aanrandster','aanrazen','aanrazeren','aanrecht','aanrechtbank','aanrechtblad','aanrechten','aanrechtkastje','aanrechtkeuken','aanrechttafel','aanreiken','aanreiker','aanrekenen','aanrekening','aanrennen','aanrichten','aanrijden','aanrijding','aanrijgen','aanrijpen','aanrijroute','aanrijtijd','aanroeien','aanroep','aanroepen','aanroeper','aanroeping','aanroeren','aanroken','aanrollen','aanrommelen','aanruisen','aanrukken','aanschaf','aanschafbeleid','aanschafdatum','aanschaffen','aanschaffing','aanschaffingsprijs','aanschafkosten','aanschafprijs','aanschafwaarde','aanschakelen','aanscharrelen','aanschellen','aanscherpen','aanscherping','aanschieten','aanschijn','aanschikken','aanschoffelen','aanschoppen','aanschouwelijk','aanschouwelijkheid','aanschouwen','aanschouwing','aanschouwingsonderwijs','aanschrijden','aanschrijven','aanschrijving','aanschroeven','aanschuinen','aanschuiven','aanschurken','aansjokken','aansjorren','aansjouwen','aanslaan','aanslag','aanslagbiljet','aanslagen','aanslagjaar','aanslagnummer','aanslagregelaar','aanslagtermijn','aanslagvoet','aanslenteren','aanslepen','aansleuren','aanslibben','aanslibbing','aanslibsel','aanslijking','aanslijpen','aansloffen','aansluipen','aansluitdoos','aansluiten','aansluitgroep','aansluitgroepen','aansluiting','aansluitingenregister','aansluitingskosten','aansluitingsplaats','aansluitingsprobleem','aansluitingspunt','aansluitingstreffer','aansluitkabel','aansluitkast','aansluitklem','aansluitklemmen','aansluitkosten','aansluitmogelijkheid','aansluitnet','aansluitpunt','aansluitsnoer','aansluitsnoeren','aansluitwaarde','aansmeden','aansmeren','aansmijten','aansnede','aansnee','aansnellen','aansnijden','aansnijding','aansnoeren','aansnorren','aanspannen','aanspanner','aanspanning','aanspeelbaar','aanspeelpunt','aanspelen','aanspijkeren','aanspoelen','aanspoeling','aanspoelsel','aansporen','aansporing','aanspraak','aansprakelijk','aansprakelijkheid','aansprakelijkheidsbeding','aansprakelijkheidsbedingen','aansprakelijkheidsbeperkend','aansprakelijkheidspolis','aansprakelijkheidsrecht','aansprakelijkheidsrisico','aansprakelijkheidsschade','aansprakelijkheidsschaden','aansprakelijkheidsuitsluiting','aansprakelijkheidsverzekeraar','aansprakelijkheidsverzekering','aansprakelijkstelling','aanspreekbaar','aanspreekbaarheid','aanspreekpunt','aanspreektitel','aanspreekvorm','aanspreken','aanspreker','aanspreking','aanspringen','aanstaan','aanstaand','aanstaande','aanstaat','aanstalten','aanstampen','aanstamper','aanstamping','aanstappen','aanstaren','aansteekvlam','aanstekelijk','aanstekelijkheid','aansteken','aansteker','aansteking','aanstellen','aansteller','aanstellerig','aanstellerij','aanstelleritis','aanstelling','aanstellingsbeleid','aanstellingsbrief','aanstellingsdatum','aanstellingsgesprek','aanstellingskeuring','aanstellingstermijn','aanstelster','aansterken','aansterven','aanstevenen','aanstichten','aanstichter','aanstichting','aanstichtster','aanstiefelen','aanstijven','aanstippen','aanstipping','aanstoken','aanstoker','aanstomen','aanstonds','aanstookster','aanstoot','aanstootgevend','aanstoppen','aanstormen','aanstort','aanstotelijk','aanstotelijkheid','aanstoten','aanstotend','aanstoting','aanstouwen','aanstralen','aanstrepen','aanstreping','aanstrijken','aanstromen','aanstrompelen','aanstuiven','aanstuiving','aansturen','aansturing','aanstuwen','aansukkelen','aantal','aantappen','aantasten','aantasting','aantekenaar','aantekenboek','aantekenen','aantekening','aantekenschrift','aantellen','aantijgen','aantijger','aantijging','aantikken','aantimmeren','aantocht','aantonen','aantonend','aantoning','aantoonbaar','aantoonbaarheid','aantrappen','aantreden','aantree','aantreffen','aantrekkelijk','aantrekkelijkheid','aantrekkelijkheidsfactor','aantrekkelijkheidsindex','aantrekken','aantrekker','aantrekking','aantrekkingskracht','aantrekkingspool','aantrekkingsvermogen','aantrippelen','aanturen','aanvaardbaar','aanvaardbaarheid','aanvaarden','aanvaarding','aanvaardingsplicht','aanvaardingsrede','aanvaardingstoespraak','aanval','aanvallen','aanvallend','aanvallenderwijze','aanvaller','aanvallig','aanvalligheid','aanvalsactie','aanvalscolonne','aanvalsdrang','aanvalsduo','aanvalsfront','aanvalsgolf','aanvalskoppel','aanvalskracht','aanvalskreet','aanvalsleider','aanvalslinie','aanvalslust','aanvalsoorlog','aanvalsopbouw','aanvalsopzet','aanvalsplan','aanvalspoging','aanvalsrecht','aanvalssein','aanvalsspel','aanvalsteken','aanvalster','aanvalstrio','aanvalswapen','aanvalswijze','aanvang','aanvangen','aanvanger','aanvangsdatum','aanvangsfase','aanvangsklas','aanvangsklasse','aanvangsprijs','aanvangspunt','aanvangssalaris','aanvangssnelheid','aanvangsstadium','aanvangstijd','aanvangstijdstip','aanvangstoets','aanvangsuur','aanvankelijk','aanvaren','aanvaring','aanvaringsschot','aanvatten','aanvatter','aanvatting','aanvechtbaar','aanvechten','aanvechting','aanvegen','aanverstorven','aanverwant','aanverwante','aanverwantschap','aanvetten','aanvijl','aanvijlen','aanvijzen','aanvinken','aanvlammen','aanvliegen','aanvliegroute','aanvloeien','aanvochten','aanvoegen','aanvoegend','aanvoeging','aanvoegsel','aanvoelen','aanvoeling','aanvoelingsvermogen','aanvoer','aanvoerbuis','aanvoerder','aanvoerdersband','aanvoerderschap','aanvoeren','aanvoerhaven','aanvoering','aanvoerkanaal','aanvoerlijn','aanvoerpijp','aanvoerrol','aanvoerroute','aanvoerster','aanvoerweg','aanvraag','aanvraagdatum','aanvraagformulier','aanvraagprocedure','aanvraagster','aanvraagtermijn','aanvrage','aanvragen','aanvrager','aanvreten','aanvulfrequentie','aanvullen','aanvullend','aanvulling','aanvullingsblad','aanvullingsexamen','aanvullingsregeling','aanvulsel','aanvuren','aanvuring','aanwaaien','aanwaggelen','aanwakkeren','aanwakkering','aanwandelen','aanwas','aanwassen','aanwendbaar','aanwenden','aanwending','aanwennen','aanwenning','aanwensel','aanwerken','aanwerpen','aanwerven','aanwerver','aanwerving','aanwervingsstop','aanwetten','aanwezen','aanwezend','aanwezig','aanwezige','aanwezigen','aanwezigheid','aanwezigheidsgeld','aanwezigheidslijst','aanwezigheidsperiode','aanwijsbaar','aanwijsinstrument','aanwijsstok','aanwijzen','aanwijzend','aanwijzer','aanwijzing','aanwijzingsbesluit','aanwijzingsbevoegdheid','aanwijzingsbord','aanwijzingsrecht','aanwinnen','aanwinning','aanwinst','aanwinstenbeleid','aanwippen','aanwoekeren','aanwrijven','aanwrijving','aanzagen','aanzakken','aanzeggen','aanzegger','aanzegging','aanzeilen','aanzet','aanzetriem','aanzetsel','aanzetslinger','aanzetstaal','aanzetsteen','aanzetster','aanzetstuk','aanzetten','aanzetter','aanzetting','aanzeulen','aanzicht','aanzien','aanzienlijk','aanzienlijkheid','aanzijn','aanzitten','aanzoek','aanzoeken','aanzoeker','aanzuigen','aanzuiging','aanzuigkanaal','aanzuigrooster','aanzuiveren','aanzuivering','aanzwaaien','aanzwellen','aanzwellend','aanzwemmen','aanzwengelen','aanzwepen','aanzweven','aangebodene','aannemingsmaatschappij','aangepastheid','aandelenzwendel','aandelenkoersindex','aannemerskartel','aanpassingsklas','aanvoertroepen','aandelenparticipatie','aankooporder','aanslagpleger','aanvalslustig','aanschaffingswaarde','aansluitvergunning','aanmeldformulier','aankomstlijn','aanbestedingstraject','aannemingsovereenkomst','aanbestedingsdossier','aanbestedingsplicht','aanbestedingsrecht','aanbestedingswet','aanbiedingsvorm','aanbodsturing','aanbodsysteem','aanbodtekort','aandachtsgeil','aandachtshoer','aandachtsspanne','aandachtstekort','aandachtstekortstoornis','aandachtstraining','aandachtswijk','aandeleninkoopprogramma','aandelenprijs','aandelenvermogen','aandrijftechniek','aangeefpositie','aangezichtszenuw','aangifteprogramma','aangiftesoftware','aangiftesysteem','aangiftetermijn','aanjaagteam','aankomstdag','aankomstdatum','aankomstpunt','aankomststrook','aankoopbegeleiding','aankoopdienst','aankoopfactuur','aankoopkeuring','aankoopmakelaar','aankoopnota','aankooppolitiek','aankooprecht','aankoopsysteem','aankoopverplichting','aanlegfase','aanlegvergunningenstelsel','aanmaakwater','aanmeldingsperiode','aanmeldingsplicht','aanmeldprocedure','aanmeldpunt','aanmeldscherm','aanpassingswet','aanraakbaar','aanraakgevoelig','aanrechtsubsidie','aanrijdtijd','aanschafbedrag','aanschafbelasting','aanschaffingskosten','aanslagoplegging','aanslagregeling','aansluitbaar','aansluitingscontract','aansluitnummer','aansluitschema','aansluitverordening','aansprakelijkheidsbeperking','aansprakelijkheidsregeling','aanstellingswijze','aantastbaar','aantrekkingspunt','aanvalsdoel','aanvalsdrift','aanvalsgeweld','aanvalshoek','aanvalsmachine','aanvalsmacht','aanvalsploeg','aanvalsvak','aanvalsvrij','aanvangsdosis','aanvangshuurprijs','aanvangskapitaal','aanvangsniveau','aanvangssituatie','aanvangstempo','aanvraagdossier','aanvraagperiode','aanwervingspolitiek','aanwervingsprocedure','aanwezigheidsdienst','aanwezigheidsplicht','aanwezigheidsvergunning','aanwinstenlijst','aanzuigbuis','aanzuigeffect','aanmeldingsverplichting','aansprakelijkheidsvraag','aandeelhouderskapitalisme','aangezichtsverlamming','aanvalstactiek','aanvoertemperatuur','aanbiedingsplicht','aansluitstuk','aanvangsbegeleiding','aandeelhoudersvereniging','aangeschotenheid','aanbestedingsproces','aanbiddingsleider','aangifteplichtige','aanpasbaarheid','aanrijdingsschade','aansluitleiding','aanvangsdosering','aanvangsleeftijd','aanvoerleiding','aanzuigleiding','aanbestedingsronde','aandeelhoudersregister','aankondigingsbord','aanloopschaal','aanmaakdatum','aanmaaklimonade','aanrijdingsformulier','aanvalsstrategie','aanvangsperiode','aanvalspartij','aanpassingsstage','aantekeningenboek','aanmeldtermijn','aanbodlijn','aanwijspen','aanvangskosten','aanwezigheidsdetectie','aanschafbon','aanbodgestuurd','aansprakelijkgestelde','aanzuiveringstermijn','aansprakelijkheidsverzekeringsmaatschappij','aantjes','aanraad','aandewiel','aanen','aanaard','aanaardingen','aanbad','aanbaden','aanbak','aanbaksels','aanbakt','aanbakte','aanbeden','aanbedenen','aanbeelden','aanbeen','aanbeet','aanbehoort','aanbel','aanbeland','aanbelandde','aanbelandden','aanbelande','aanbelandt','aanbelangd','aanbelangde','aanbelangt','aanbelde','aanbelden','aanbelt','aanbermen','aanbermingen','aanbestedingen','aanbestedingsprocedures','aanbestedingsvoorwaarden','aanbesteed','aanbesteedde','aanbesteedden','aanbesteedt','aanbetaal','aanbetaald','aanbetaalde','aanbetaalden','aanbetaalt','aanbetalingen','aanbeten','aanbeter','aanbeval','aanbevalen','aanbeveel','aanbeveelt','aanbevelenswaardige','aanbevelenswaardiger','aanbevelingen','aanbevelingsbrieven','aanbid','aanbiddelijke','aanbiddelijker','aanbiddelijkst','aanbiddelijkste','aanbidders','aanbiddingen','aanbidsters','aanbidt','aanbied','aanbieders','aanbiedingen','aanbiedingsbrieven','aanbiedt','aanbijt','aanbik','aanbind','aanbindt','aanblaas','aanblaast','aanblaf','aanblaft','aanblafte','aanblazingen','aanbleef','aanbleven','aanblies','aanbliezen','aanblijf','aanblijft','aanblikt','aanblikte','aanblikten','aanboden','aanbodgerichte','aanbond','aanbonden','aanbonsde','aanbonst','aanbood','aanboor','aanboorde','aanboort','aanbots','aanbotst','aanbotste','aanbotsten','aanbouwde','aanbouwden','aanbouwingen','aanbouwsels','aanbouwt','aanbraad','aanbraadt','aanbracht','aanbrachten','aanbrak','aanbraken','aanbrand','aanbrandde','aanbrandden','aanbrandt','aanbreek','aanbreekt','aanbrei','aanbreiden','aanbreit','aanbrengers','aanbrengpremies','aanbrengsten','aanbrengster','aanbrengt','aanbruggen','aandachtige','aandachtiger','aandachtigere','aandachtigst','aandachtigste','aandachtsaspecten','aandachtsgebieden','aandachtspunten','aandachtsstreepje','aandachtsstreepjes','aandachtsstrepen','aandachtstekens','aandachtstrekkers','aandachtstrepen','aandachttrekkend','aandachttrekkende','aandachttrekkers','aandaken','aandam','aandamt','aandeden','aandeed','aandeelbewijzen','aandeelhouders','aandeelhoudersbelangen','aandeelhouderskringen','aandeelkoersen','aandeeltje','aandeeltjes','aandelen','aandelenadviezen','aandelenbelangen','aandelenbeleggers','aandelenbeleggingen','aandelenbezitters','aandelenhandelaren','aandelenindexen','aandelenindices','aandelenkapitalen','aandelenkoersen','aandelenmarkten','aandelenopties','aandelenpakketten','aandelenparticipaties','aandelenprijzen','aandelenregelingen','aandelenregisters','aandelentransacties','aandelenvennootschappen','aandien','aandiende','aandienden','aandient','aandijk','aandijkingen','aandik','aandikt','aandikte','aandikten','aandoe','aandoende','aandoeningen','aandoenlijke','aandoenlijker','aandoenlijkst','aandoenlijkste','aandoet','aandraafde','aandraafden','aandraaft','aandraag','aandraagt','aandraai','aandraaide','aandraaiden','aandraait','aandragers','aandreef','aandrentelt','aandreven','aandriften','aandrijf','aandrijfassen','aandrijfkettingen','aandrijfmotoren','aandrijft','aandrijfwielen','aandrijvers','aandrijvingen','aandring','aandringt','aandroeg','aandroegen','aandrong','aandrongen','aandruk','aandrukrollen','aandrukt','aandrukte','aandrukten','aanduid','aanduidde','aanduidden','aanduidingen','aanduidt','aandurfde','aandurfden','aanduw','aanduwde','aanduwden','aanduwt','aandweilden','aandweilt','aaneenbindt','aaneenbond','aaneengebonden','aaneengebracht','aaneengeflanste','aaneengegroeid','aaneengegroeide','aaneengehecht','aaneengehechte','aaneengehouden','aaneengeketend','aaneengeketende','aaneengekleefd','aaneengekleefde','aaneengeklonken','aaneengeknoopt','aaneengeknoopte','aaneengekoekt','aaneengekoekte','aaneengekoppeld','aaneengekoppelde','aaneengelijmd','aaneengelijmde','aaneengenaaid','aaneengenaaide','aaneengepaste','aaneengeplakt','aaneengeplakte','aaneengeregen','aaneengeschakelde','aaneengeschreven','aaneengesmede','aaneengesmeed','aaneengespijkerde','aaneengevoegd','aaneengevoegde','aaneengezet','aaneengezette','aaneengroei','aaneengroeide','aaneengroeiden','aaneengroeit','aaneenhangt','aaneenhing','aaneenhoudt','aaneenkleeft','aaneenklonk','aaneenklonken','aaneenknoopt','aaneenplakken','aaneenplakt','aaneenreeg','aaneenregen','aaneenrijg','aaneenrijgt','aaneenschakel','aaneenschakelde','aaneenschakelingen','aaneenschakelt','aaneenschreef','aaneenschrijft','aaneensloot','aaneensloten','aaneensluit','aaneensluitend','aaneensluitende','aaneensmeed','aaneensmeedde','aaneensmeedden','aaneensmeedt','aaneenvoegde','aaneenvoegden','aaneenzet','aanfiets','aanfietst','aanfietste','aanfietsten','aanflitst','aanflitste','aanflitsten','aanfloept','aanfloepten','aanfluit','aanfluitingen','aanfokt','aanga','aangaand','aangaap','aangaapt','aangaapte','aangaapten','aangaat','aangaf','aangaven','aangeaard','aangeaarde','aangebakken','aangebeden','aangebeend','aangebeld','aangebermd','aangebeten','aangeblaft','aangebleven','aangeblikt','aangeboord','aangeboorde','aangebotst','aangebouwde','aangebracht','aangebrachte','aangebraden','aangebrande','aangebreide','aangebroken','aangebulderd','aangedamd','aangedamde','aangedane','aangediend','aangediende','aangedijkt','aangedijkte','aangedikt','aangedikte','aangedraafd','aangedraaide','aangedragen','aangedreven','aangedrongen','aangedrukt','aangedrukte','aangeduide','aangedurfd','aangedurfde','aangeduwd','aangeduwde','aangedweild','aangeef','aangeefsters','aangeeft','aangefietst','aangeflitst','aangefloept','aangefloten','aangefokt','aangefokte','aangefruit','aangefruite','aangegaan','aangegaapt','aangegaapte','aangegane','aangegespt','aangegespte','aangegierd','aangegloeid','aangegord','aangegoten','aangegraven','aangegrepen','aangegrijnsd','aangegroeid','aangegroeide','aangehaakt','aangehaakte','aangehaalde','aangehad','aangehangen','aangehard','aangeharde','aangeharkt','aangeharkte','aangehecht','aangehechte','aangeheven','aangehikt','aangehinkt','aangehitst','aangehitste','aangehobbeld','aangehold','aangehoord','aangehoorde','aangehouden','aangehoudenen','aangehuppeld','aangehuwde','aangejaagd','aangejaagde','aangekaarte','aangekalkt','aangekant','aangekapt','aangekapte','aangekeken','aangeklaagd','aangeklaagden','aangeklampt','aangeklampte','aangeklede','aangekleden','aangekleefd','aangekleefde','aangeklemd','aangeklemde','aangeklonken','aangeklooid','aangeklopt','aangeklost','aangeknipte','aangeknoeid','aangeknoopt','aangeknoopte','aangekocht','aangekochte','aangekoekt','aangekoekte','aangekomen','aangekomenen','aangekondigd','aangekondigde','aangekoppeld','aangekoppelde','aangekorst','aangekorste','aangekregen','aangekruid','aangekruist','aangekruiste','aangekund','aangekweekte','aangelachen','aangelanden','aangelangd','aangelapt','aangelast','aangelaste','aangeleerde','aangelegde','aangelegenheden','aangelengd','aangelengde','aangeleund','aangeleunde','aangeleverd','aangeleverde','aangelicht','aangelichte','aangelijmd','aangelijmde','aangelijnd','aangeloerd','aangelokt','aangelokte','aangelopen','aangemaakt','aangemaakte','aangemaand','aangemaande','aangemarcheerd','aangematigd','aangematigde','aangemeerd','aangemeerde','aangemeld','aangemelde','aangemengd','aangemengde','aangemerkte','aangemoedigd','aangemoedigde','aangemoeten','aangemonsterd','aangemonsterde','aangemunt','aangemunte','aangenaaid','aangenaaide','aangenaams','aangenaamst','aangenaamste','aangenageld','aangenagelde','aangename','aangenamer','aangepakt','aangepakte','aangepapt','aangepaste','aangepaster','aangeperst','aangeperste','aangepikt','aangepikte','aangeplakt','aangeplakte','aangeplant','aangeplante','aangeplempt','aangeplempte','aangeploegd','aangeploegde','aangepoot','aangepord','aangepraat','aangepreekt','aangeprezen','aangeprikkeld','aangeprikt','aangeprikte','aangepunt','aangepunte','aangeraakt','aangeraakte','aangeraasd','aangeraden','aangerand','aangerande','aangerecht','aangerechte','aangereden','aangeregen','aangereikt','aangereikte','aangerekend','aangerekende','aangerend','aangerende','aangericht','aangerichte','aangerijpt','aangerijpte','aangeroeid','aangeroepen','aangeroerd','aangeroerde','aangeroest','aangerold','aangerolde','aangerookte','aangerukte','aangeschaft','aangeschafte','aangeschakelde','aangescharreld','aangescheld','aangescherpt','aangescherpte','aangeschikte','aangeschoffeld','aangeschopt','aangeschoven','aangeschreden','aangeschrevenen','aangeschroefde','aangeschuind','aangeschuinde','aangesjokt','aangesjord','aangesjorde','aangesjouwd','aangesjouwde','aangesleept','aangesleepte','aangeslenterd','aangeslepen','aangesleurd','aangeslibde','aangeslijkte','aangesloft','aangeslopen','aangeslotenen','aangesmede','aangesmeed','aangesmeerd','aangesmeerde','aangesneden','aangesneld','aangesnelde','aangesnoerd','aangesnoerde','aangesnord','aangesp','aangespannen','aangespeeld','aangespeelde','aangespeld','aangespelde','aangespoed','aangespoeld','aangespoelde','aangesponnen','aangespoord','aangespoorde','aangesproken','aangesprokenen','aangesprongen','aangespt','aangespte','aangestaan','aangestaard','aangestaarde','aangestampt','aangestampte','aangestapt','aangestapte','aangestelde','aangesterkt','aangesterkte','aangesticht','aangestichte','aangestijfd','aangestikt','aangestikte','aangestipt','aangestipte','aangestookt','aangestookte','aangestoomd','aangestopt','aangestormd','aangestormde','aangestoten','aangestoven','aangestrand','aangestrande','aangestreept','aangestreepte','aangestreken','aangestrikt','aangestrompeld','aangestroomd','aangestroomde','aangestuurd','aangestuurde','aangestuwd','aangesukkeld','aangetapt','aangetaste','aangetekende','aangeteld','aangetikt','aangetikte','aangetimmerd','aangetimmerde','aangetoond','aangetoonde','aangetrapt','aangetrapte','aangetreden','aangetrippeld','aangetroffen','aangetrokken','aangetrouwde','aangetuurd','aangevallen','aangevangen','aangevaren','aangevat','aangeveegd','aangeveegde','aangevende','aangevers','aangevet','aangevezen','aangevijld','aangevinkt','aangevlamd','aangevlochten','aangevlogen','aangevochten','aangevoegd','aangevoegde','aangevoeld','aangevoelde','aangevoerde','aangevraagd','aangevraagde','aangevreten','aangevuld','aangevulde','aangevuurd','aangevuurde','aangewaaid','aangewaaide','aangewaggeld','aangewakkerd','aangewakkerde','aangewandeld','aangewassen','aangewend','aangewende','aangewet','aangeweven','aangewezenen','aangewipt','aangewoekerd','aangewonnen','aangeworpen','aangeworven','aangewreven','aangezakt','aangezand','aangezegd','aangezegde','aangezeild','aangezeten','aangezette','aangezeuld','aangezichten','aangezichtspijnen','aangezocht','aangezochte','aangezoet','aangezoete','aangezogen','aangezuiverd','aangezuiverde','aangezuurd','aangezuurde','aangezwaaid','aangezweefd','aangezweept','aangezwengeld','aangezwollen','aangezwommen','aangiet','aangiftebiljetten','aangifteformulieren','aangiften','aanging','aangingen','aangloeide','aangloeiden','aangolfde','aangolft','aangord','aangordde','aangordden','aangordt','aangravingen','aangreep','aangrenzende','aangrepen','aangrijnsde','aangrijnsden','aangrijnst','aangrijp','aangrijpende','aangrijpender','aangrijpendere','aangrijpendst','aangrijpendste','aangrijpingspunten','aangrijpt','aangrimt','aangroeide','aangroeiden','aangroeiingen','aangroeisels','aangroeit','aangroeiwerende','aanhaak','aanhaakt','aanhaakte','aanhaakten','aanhaal','aanhaalde','aanhaalden','aanhaalt','aanhad','aanhadden','aanhalerige','aanhalige','aanhaliger','aanhalingen','aanhangend','aanhangers','aanhangige','aanhangmotoren','aanhangselen','aanhangsters','aanhangt','aanhangwagens','aanhangwagentje','aanhangwagentjes','aanhankelijke','aanhankelijker','aanhankelijkst','aanhankelijkste','aanhardt','aanhark','aanharkt','aanharkte','aanharkten','aanhecht','aanhechtingen','aanhechtingspunten','aanhechtsels','aanhechtte','aanhechtten','aanheeft','aanheft','aanhief','aanhield','aanhielden','aanhieven','aanhikt','aanhikte','aanhikten','aanhing','aanhingen','aanhinkt','aanhitsers','aanhitsingen','aanhitst','aanhitste','aanhitsten','aanhobbelde','aanhobbelden','aanhobbelt','aanhol','aanholde','aanholden','aanholt','aanhoor','aanhoorde','aanhoorden','aanhoorders','aanhoort','aanhorige','aanhoud','aanhoudende','aanhoudender','aanhouders','aanhoudingen','aanhoudingsbevelen','aanhoudsters','aanhoudt','aanhuppel','aanhuppelde','aanhuppelden','aanhuppelt','aanjaag','aanjaagde','aanjaagden','aanjaagt','aanjagers','aanjoeg','aanjoegen','aankaart','aankaartte','aankaartten','aankant','aankantte','aankeek','aankeken','aankijk','aankijkend','aankijkt','aanklaag','aanklaagde','aanklaagden','aanklaagsters','aanklaagt','aanklachten','aanklagers','aanklamp','aanklampt','aanklampte','aanklampten','aankledingen','aankleed','aankleedde','aankleedden','aankleedt','aankleef','aankleefde','aankleefden','aankleeft','aanklem','aanklemde','aanklemt','aanklevend','aanklevende','aanklinkt','aanklonk','aanklooide','aanklooit','aanklop','aanklopt','aanklopte','aanklopten','aanklotst','aanklotste','aanklotsten','aanknip','aanknipt','aanknipte','aanknipten','aanknoeit','aanknoop','aanknoopt','aanknoopte','aanknoopten','aanknopingen','aanknopingspunten','aankocht','aankochten','aankoek','aankoekt','aankoekte','aankom','aankomelingen','aankomende','aankomsten','aankomsttijden','aankomt','aankon','aankonden','aankondig','aankondigde','aankondigden','aankondigend','aankondigende','aankondigers','aankondigingen','aankondigt','aankoopbedragen','aankoopbeslissingen','aankoopgegevens','aankooporders','aankooppatronen','aankoopprijzen','aankoopprocedures','aankoopt','aankopers','aankoppel','aankoppelde','aankoppelden','aankoppelingen','aankoppelt','aankorstingen','aankreeg','aankregen','aankrijg','aankrijgt','aankrui','aankruis','aankruist','aankruiste','aankruisten','aankunt','aankwam','aankwamen','aankweekt','aankweekte','aankweekten','aanlacht','aanlachte','aanlachten','aanlag','aanlagen','aanland','aanlandde','aanlandden','aanlandige','aanlandingen','aanlandt','aanlas','aanlast','aanleer','aanleerde','aanleerden','aanleert','aanlegde','aanlegden','aanleggers','aanlegging','aanleggingen','aanleghavens','aanlegplaatsen','aanlegsteigers','aanlegsters','aanlegt','aanleidend','aanleidende','aanleidingen','aanleng','aanlengde','aanlengden','aanlengt','aanleun','aanleunde','aanleunden','aanleuningen','aanleunt','aanlicht','aanlichtte','aanliep','aanliepen','aanliet','aanlig','aanliggende','aanligt','aanlijm','aanlijmde','aanlijn','aanlijnde','aanlijnt','aanloeit','aanloert','aanlok','aanlokkelijke','aanlokkelijker','aanlokkelijkere','aanlokkelijkheden','aanlokkelijks','aanlokkelijkst','aanlokkelijkste','aanlokkingen','aanlokselen','aanlokt','aanlokte','aanlokten','aanloophavens','aanloopje','aanloopkleuren','aanloopmoeilijkheden','aanloopproblemen','aanloopt','aanloopverliezen','aanmaakblokjes','aanmaakhoutjes','aanmaakt','aanmaakte','aanmaakten','aanmaan','aanmaande','aanmaanden','aanmaant','aanmanende','aanmaningen','aanmaningsbrieven','aanmaningsteksten','aanmat','aanmatig','aanmatigde','aanmatigden','aanmatigende','aanmatigender','aanmatigingen','aanmatigt','aanmeer','aanmeerde','aanmeerden','aanmeert','aanmeet','aanmeld','aanmeldcentra','aanmeldde','aanmeldden','aanmeldingen','aanmeldingsbonnen','aanmeldingscriteria','aanmeldingsdata','aanmeldingsformulieren','aanmeldingstermijnen','aanmeldt','aanmeng','aanmengt','aanmerk','aanmerkelijke','aanmerkelijker','aanmerkelijkste','aanmerkingen','aanmerkt','aanmerkte','aanmerkten','aanminnige','aanminniger','aanminnigst','aanminnigste','aanmoedig','aanmoedigde','aanmoedigden','aanmoedigend','aanmoedigende','aanmoedigingen','aanmoedigingspremies','aanmoedigingsprijzen','aanmoedigt','aanmoesten','aanmoet','aanmonster','aanmonsterde','aanmonsterden','aanmonsteringen','aanmonstert','aanmuntingen','aannaai','aannaaide','aannaaiden','aannaait','aannam','aannamen','aannames','aanneem','aanneembare','aanneemsommen','aanneemsters','aanneemt','aannemelijke','aannemelijker','aannemelijkere','aannemelijkst','aannemelijkste','aannemend','aannemende','aannemers','aannemingen','aannemingssommen','aanpakt','aanpakte','aanpakten','aanpalende','aanpap','aanpapt','aanpapte','aanpapten','aanpas','aanpasbare','aanpassend','aanpassende','aanpassingen','aanpassingsfactoren','aanpassingsproblemen','aanpassingswerken','aanpassingswerkzaamheden','aanpast','aanpaste','aanpasten','aanperste','aanpik','aanpikt','aanpikte','aanpikten','aanplak','aanplakbiljetten','aanplakborden','aanplakbrieven','aanplakkers','aanplakkingen','aanplakt','aanplakte','aanplakten','aanplakzuilen','aanplantingen','aanplantte','aanplantten','aanplempingen','aanpoot','aanpor','aanporde','aanporden','aanport','aanpraat','aanpraatte','aanpraatten','aanpreek','aanpreekt','aanprees','aanprezen','aanprijs','aanprijst','aanprijzend','aanprijzers','aanprijzingen','aanprik','aanprikkelt','aanprikt','aanprikte','aanpunt','aanraad','aanraadde','aanraadden','aanraadt','aanraak','aanraakt','aanraakte','aanraakten','aanraast','aanrakingen','aanrakingspunten','aanrand','aanrandde','aanrandden','aanranders','aanrandingen','aanrandt','aanrechtbladen','aanrechtkastjes','aanrechtkeukens','aanreden','aanreed','aanreeg','aanreik','aanreikt','aanreikte','aanreikten','aanreken','aanrekende','aanrekenden','aanrekent','aanren','aanrende','aanrenden','aanrent','aanricht','aanrichtte','aanrichtten','aanried','aanrieden','aanriep','aanriepen','aanrijd','aanrijdingen','aanrijdt','aanrijg','aanrijgt','aanrijtijden','aanroepend','aanroepingen','aanroept','aanroer','aanroerde','aanroerden','aanroert','aanrolde','aanrolden','aanrolt','aanrommelt','aanruiste','aanruk','aanrukt','aanrukte','aanrukten','aanschafbeslissingen','aanschaffingen','aanschafprocedures','aanschaft','aanschafte','aanschaften','aanschafwaarden','aanschakel','aanschakelde','aanschakelden','aanschakelt','aanschelde','aanschelden','aanscherp','aanscherpt','aanscherpte','aanscherpten','aanschiet','aanschoof','aanschoot','aanschop','aanschopt','aanschopte','aanschopten','aanschouw','aanschouwd','aanschouwde','aanschouwden','aanschouwelijke','aanschouwelijker','aanschouwelijkst','aanschouwelijkste','aanschouwend','aanschouwingen','aanschouwt','aanschoven','aanschreef','aanschreven','aanschrijf','aanschrijft','aanschrijvingen','aanschroef','aanschroefde','aanschroeft','aanschuif','aanschuift','aansjok','aansjokt','aansjokte','aansjokten','aansjor','aansjorde','aansjort','aansjouwde','aansjouwden','aansjouwt','aansla','aanslaander','aanslaat','aanslagbeitels','aanslagbiljetten','aanslagjaren','aanslagplegers','aansleep','aansleept','aansleepte','aansleepten','aanslentert','aansleurt','aanslib','aanslibbingen','aanslibde','aanslibsels','aanslibt','aanslijkingen','aansloeg','aansloegen','aansloft','aanslofte','aansloop','aansloot','aansloten','aansluipt','aansluit','aansluitbogen','aansluitdozen','aansluitdraden','aansluitend','aansluitende','aansluitgegevens','aansluitingen','aansluitingsproblemen','aansluitingspunten','aansluitkabels','aansluitkasten','aansluitmogelijkheden','aansluitpunten','aansmeer','aansmeerde','aansmeerden','aansmeert','aansmeet','aansmijt','aansneden','aansneed','aansnelde','aansnelden','aansnelt','aansnijd','aansnijdingen','aansnijdt','aansnoer','aansnoerde','aansnoert','aanspan','aanspande','aanspanden','aanspanners','aanspanningen','aanspant','aanspeel','aanspeelde','aanspeelden','aanspeelt','aanspijkerde','aanspoel','aanspoelde','aanspoelden','aanspoelingen','aanspoelsels','aanspoelt','aanspon','aansponnen','aanspoor','aanspoorde','aanspoorden','aanspoorder','aanspoorders','aanspoort','aansporingen','aansprak','aansprakelijke','aansprakelijkheden','aansprakelijkheidsbeperkende','aansprakelijkheidspolissen','aansprakelijkheidsrisicos','aansprakelijkheidsschades','aanspraken','aanspreek','aanspreekbare','aanspreekt','aanspreektitels','aanspreekvormen','aansprekend','aansprekende','aansprekender','aansprekers','aansprekingen','aanspringt','aansprong','aansprongen','aansta','aanstaanden','aanstaar','aanstaarde','aanstaarden','aanstaart','aanstak','aanstaken','aanstamp','aanstampers','aanstampt','aanstampte','aanstampten','aanstapte','aanstapten','aansteek','aansteekt','aanstekelijke','aanstekelijker','aanstekelijkst','aanstekelijkste','aanstekend','aanstekers','aanstel','aanstelde','aanstelden','aanstellerige','aanstelleriger','aanstellerigste','aanstellers','aanstellingen','aanstelt','aansterk','aansterkt','aansterkte','aansterkten','aanstevende','aanstevent','aansticht','aanstichters','aanstichtsters','aanstichtte','aanstichtten','aanstiet','aanstieten','aanstip','aanstippingen','aanstipt','aanstipte','aanstipten','aanstokers','aanstond','aanstonden','aanstoof','aanstook','aanstookt','aanstookten','aanstoomt','aanstootgevende','aanstoots','aanstootte','aanstootten','aanstorm','aanstormde','aanstormden','aanstormend','aanstormende','aanstormt','aanstotelijke','aanstotende','aanstotingen','aanstoven','aanstrand','aanstrandt','aanstreek','aanstreep','aanstreept','aanstreepte','aanstreepten','aanstrepingen','aanstrijk','aanstrijkt','aanstrikken','aanstrompelt','aanstroom','aanstroomt','aanstuift','aanstuur','aanstuurde','aanstuurden','aanstuurt','aanstuwt','aansukkelde','aansukkelt','aantallen','aantast','aantastend','aantastingen','aantastte','aantastten','aanteken','aantekenaars','aantekenboeken','aantekenboekje','aantekende','aantekenden','aantekeningen','aantekeningenbriefje','aantekent','aantelde','aantelt','aantijg','aantijgingen','aantijgt','aantik','aantikt','aantikte','aantikten','aantonende','aantoon','aantoonbare','aantoonde','aantoonden','aantoont','aantrad','aantraden','aantrap','aantrapt','aantrapte','aantrapten','aantrede','aantreed','aantreedt','aantref','aantreffende','aantreft','aantrek','aantrekkelijke','aantrekkelijker','aantrekkelijkere','aantrekkelijkheden','aantrekkelijkst','aantrekkelijkste','aantrekkend','aantrekkende','aantrekkers','aantrekkingskrachten','aantrekt','aantrippelt','aantrof','aantroffen','aantrok','aantrokken','aantuurde','aantuurt','aanvaard','aanvaardbaarder','aanvaardbare','aanvaardde','aanvaardden','aanvaarde','aanvaardend','aanvaardingen','aanvaardingsproblemen','aanvaardt','aanvaarpalen','aanvallende','aanvallers','aanvallige','aanvalligheden','aanvalligste','aanvalscolonnes','aanvalshelikopters','aanvalskreten','aanvalslustige','aanvalsoorlogen','aanvalspatronen','aanvalsplannen','aanvalsters','aanvalsvliegtuigen','aanvalswapenen','aanvalswapens','aanvalswijzen','aanvalt','aanvangend','aanvangende','aanvangers','aanvangsproblemen','aanvangspunten','aanvangssalarissen','aanvangssnelheden','aanvangsstadia','aanvangstijden','aanvangstijdstippen','aanvangt','aanvankelijke','aanvaringen','aanvaringsschotten','aanvat','aanvatte','aanvecht','aanvechtbaarder','aanvechtbare','aanvechtingen','aanveeg','aanveegde','aanveegden','aanveegt','aanverwanten','aanvet','aanviel','aanvielen','aanvijst','aanving','aanvingen','aanvlieg','aanvliegroutes','aanvliegt','aanvloeit','aanvlogen','aanvloog','aanvocht','aanvoeg','aanvoegende','aanvoegsels','aanvoegt','aanvoel','aanvoelde','aanvoelden','aanvoelend','aanvoelt','aanvoerbuizen','aanvoerde','aanvoerden','aanvoerders','aanvoerkanalen','aanvoerlijnen','aanvoerpijpen','aanvoerrollen','aanvoerroutes','aanvoersters','aanvoert','aanvraagbriefje','aanvraagbriefjes','aanvraagde','aanvraagden','aanvraagformulieren','aanvraagprocedures','aanvraagsters','aanvraagt','aanvragers','aanvrat','aanvraten','aanvreet','aanvroeg','aanvroegen','aanvul','aanvulde','aanvulden','aanvullende','aanvullingen','aanvullingsbladen','aanvullingstroepen','aanvult','aanvuurde','aanvuurden','aanvuurt','aanwaai','aanwaaide','aanwaaiden','aanwaait','aanwaggelt','aanwakker','aanwakkerde','aanwakkerden','aanwakkert','aanwandelde','aanwandelt','aanwast','aanwees','aanwen','aanwend','aanwendbare','aanwendde','aanwendden','aanwende','aanwendingen','aanwendt','aanwensels','aanwent','aanwentelen','aanwerf','aanwerft','aanwerp','aanwerpt','aanwervers','aanwervingen','aanwezende','aanwezigheidslijsten','aanwezigheidsperiodes','aanwierf','aanwierp','aanwierven','aanwies','aanwijs','aanwijsbare','aanwijsinstrumenten','aanwijsstokje','aanwijsstokken','aanwijst','aanwijzende','aanwijzers','aanwijzingen','aanwin','aanwinsten','aanwint','aanwip','aanwipt','aanwipte','aanwipten','aanwoei','aanwon','aanwonende','aanwonenden','aanwreef','aanwreven','aanwrijf','aanwrijft','aanzag','aanzandt','aanzat','aanzeg','aanzegde','aanzegden','aanzeggers','aanzeggingen','aanzegt','aanzei','aanzeiden','aanzeilde','aanzeilden','aanzeiling','aanzeilt','aanzetsels','aanzetstalen','aanzetstenen','aanzetstukken','aanzette','aanzetters','aanzettingen','aanzeulde','aanzichten','aanzie','aanziend','aanziende','aanzienlijke','aanzienlijken','aanzienlijker','aanzienlijkere','aanzienlijkst','aanzienlijkste','aanziet','aanzit','aanzocht','aanzoekers','aanzoekt','aanzoet','aanzogen','aanzoog','aanzuig','aanzuigroosters','aanzuigt','aanzuiverde','aanzuiverden','aanzuiveringen','aanzuivert','aanzwaai','aanzweef','aanzweeft','aanzweept','aanzweepten','aanzwel','aanzwellende','aanzwelt','aanzwem','aanzwemt','aanzwengelt','aanzwol','aanzwollen','aanzwom','aanzwommen','aanbestede','aanbestedende','aanbestedingsregels','aanbiddende','aanbiedende','aanbodcurven','aanbodcurves','aanbodverhoudingen','aandachtsvelden','aandeelhoudende','aandeelhoudersvergaderingen','aandelenbeurzen','aandelenfondsen','aandenkens','aandienende','aandoend','aandoenlijks','aandrijvende','aanduidend','aandurf','aandurft','aaneengeflanst','aangegooid','aangekakt','aangeklikt','aangekoerst','aangelijnde','aangemodderd','aangenamere','aangepeesd','aangeprate','aangerommeld','aangeschikt','aangestevend','aangestiefeld','aangestouwd','aangestraald','aangetegen','aangevend','aangewerkt','aangezwengelde','aangiftes','aangooi','aangroeiende','aanhangende','aanhankelijkheidsbetuigingen','aanheb','aanhebt','aanjagende','aankan','aanklagende','aanklik','aanklikbare','aanklikt','aankomsthallen','aankoopbudgetten','aankoopsommen','aanlegvergunningen','aanleunend','aanleunwoningen','aanleverde','aanleverden','aanleverende','aanlevert','aanlopende','aanmeldende','aanmelders','aanminnigheden','aanmoest','aannemingsbedrijven','aanraakschermen','aanraders','aanrijdend','aanrijdende','aanrollende','aanscherpingen','aanschurkt','aanslagregelaars','aanslepend','aanslepende','aanspeelbare','aansprakelijkheidsverzekeraars','aanstellingsbrieven','aanstellingskeuringen','aanstromende','aansturende','aantastende','aantekenschriften','aantel','aantredend','aantredende','aantrekkelijks','aanvalsacties','aanvalsgolven','aanvalspogingen','aanvalsseinen','aanvangsklassen','aanvinkt','aanvoelende','aanvoerende','aanvoerhavens','aanvoerwegen','aanvragende','aanwakkerende','aanwezigheden','aanwijzingsbevoegdheden','aanwijzingsborden','aanzaten','aanzettend','aanzettende','aanzuigende','aanzwengelde','aanspreekpunten','aanloopfasen','aanbeeldsblokken','aangesteven','aanvalletje','aanbevelingscomites','aanspeelpunten','aanpassingsklassen','aanvalslinies','aanloopfases','aanvliegrouten','aanvallender','aanvalletjes','aanbestedingstrajecten','aanbiedingsvormen','aandachtsgeile','aandachtspuntje','aandachtspuntjes','aandelenportefeuilles','aandrijfkrachten','aandrijfsystemen','aanhoudingseenheden','aankoopbonnen','aankoopfacturen','aanlooproutes','aannemersbedrijven','aanpassingsprogrammas','aanraakgevoelige','aansprakelijkheidsverzekeringen','aantrekkingspolen','aanvalsdoelen','aanvraagdossiers','aanwijzingsbesluiten','aandrijflijnen','aanjaagteams','aanrijdtijden','aanslagvoeten','aantekeningenboekje','aantrekkingspunten','aanwinstenlijsten','aankondigingsborden','aanbiddingsleiders','aandelenemissies','aanpassingsprocessen','aantekenboekjes','aandrijftechnieken','aankoopsystemen','aansluitnetten','aanwervingsprocedures','aandelenposities','aanbestedingsdossiers','aansluitstukken','aanmeldingsprocedures','aandeelhoudersverenigingen','aanvalsopzetten','aandelenplannen','aankoopopties','aandelenuitgiftes','aandelenoptieplannen','aanmeldformulieren','aansprakelijkheidsbeperkingen','aanlegsteigertjes','aanwijsbaars','aankoopkeuringen','aanschafprijzen','aansluitschemas','aansluitvergunningen','aanvraagdata','aandeelhoudertjes','aanlegsteigertje','aandrijfriemen','aanvalspartijen','aandachtstrainingen','aanbiedingsprijzen','aanbiedingsfolders','aandrijfmechanismen','aankoopdata','aandelenpakketje','aanloopjes','aandrukrolletjes','aanslagtermijnen','aankoopdirecteurs','aandelenuitgiften','aankomstplaatsen','aantoonbaars','aanvalstactieken','aanloopschalen','aanvraagperiodes','aansluitnummers','aantekeningenboekjes','aankomstdagen','aankomstdata','aanlooptijden','aandeelhouderscommissies','aanvalsspelletje','aanknopingspuntje','aanvangsuren','aanvraagtermijnen','aanloopprobleempjes','aanvaardbaars','aanvalsvrije','aanbestedingsprocessen','aankomstpunten','aangifteprogrammas','aandelenpakketjes','aanbevelingsbriefje','aandelenverkopen','aansluitwaarden','aanvraagperioden','aangiftetermijnen','aanvangsfasen','aanvalsdriften','aandeelhoudersregisters','aanbodgestuurde','aanwezigheidsdiensten','aandweil','aanklooi','aansprakelijkgestelden'}
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local factory = require "game.rules.character.factory" return { actions = require "game.rules.character.actions", attributes = require "game.rules.character.attributes", create = factory.newCharacter, reducer = require "game.rules.character.reducer", selectors = require "game.rules.character.selectors" }
#!/usr/bin/env texlua -- Build script for "biblatex-ext" files -- Identify the bundle and module module = "biblatex-ext" unpackfiles = { } -- Install biblatex style files and use these as the sources installfiles = {"*.cbx", "*.bbx", "*.def", "*.sty", "blxextdoiapi.lua"} sourcefiles = installfiles typesetfiles = {"biblatex-ext.tex"} textfiles = {"README.md", "CHANGES.md"} checkconfigs = {"build", "config-luatex"} checkengines = {"pdftex"} checkruns = 3 function runtest_tasks(name, run) local run = run or 1 if run == 1 or not fileexists(testdir .. "/" .. name .. ".bbl") then return "biber -q " .. name else return "" end end -- Release a TDS-style zip packtdszip = false tagfiles = {"*.bbx", "*.cbx", "*.def", "*.tex", "*.md", "*.sty", "blxextdoiapi.lua"} function update_tag(file, content, tagname, tagdate) local isodate_scheme = "%d%d%d%d%-%d%d%-%d%d" local ltxdate_scheme = string.gsub(isodate_scheme, "%-", "/") local version_scheme = "%d+%.%d+%.?%d?%w?" local tagdate_ltx = string.gsub(tagdate, "%-", "/") local tagyear = string.match(tagdate, "%d%d%d%d") local tagname_safe = string.gsub(tagname, "^v", "") if string.match(file, "^ext%-standard%.bbx$") then content = string.gsub(content, "v" .. version_scheme .. " %(" .. isodate_scheme .. "%)", "v" .. tagname_safe .. " (" .. tagdate .. ")") content = string.gsub(content, ltxdate_scheme .. " v" .. version_scheme, tagdate_ltx .. " v" .. tagname_safe) content = string.gsub(content, "Copyright 2017%-%d%d%d%d", "Copyright 2017-" .. tagyear) return content elseif string.match(file, "%.bbx$") or string.match(file, "%.cbx$") or string.match(file, "%.def$") or string.match(file, "%.sty$") then content = string.gsub(content, "\\ProvidesExplPackage {(.-)}\n {" .. ltxdate_scheme .. "} {" .. version_scheme .. "}", "\\ProvidesExplPackage {%1}\n {" .. tagdate_ltx .. "} {" .. tagname_safe .. "}") content = string.gsub(content, ltxdate_scheme .. " v" .. version_scheme, tagdate_ltx .. " v" .. tagname_safe) return content elseif string.match(file, "%.tex$") then content = string.gsub(content, "\n\\newcommand%*{\\extblxversion}{" .. version_scheme .."}\n", "\n\\newcommand*{\\extblxversion}{" .. tagname_safe .. "}\n") content = string.gsub(content, "\n\\begin{release}{<version>}{<date>}\n", "\n\\begin{release}{" .. tagname_safe .. "}{" .. tagdate .."}\n") content = string.gsub(content, "date%s*=%s*{\\DTMDate{" .. isodate_scheme .. "}}", "date = {\\DTMDate{" .. tagdate .."}}") content = string.gsub(content, "\\textcopyright 2017%-%-%d%d%d%d", "\\textcopyright 2017--" .. tagyear) return content elseif string.match(file, "%.lua$") then content = string.gsub(content, '(version%s*=%s"v)' .. version_scheme .. '"', '%1' .. tagname_safe .. '"') content = string.gsub(content, '(date%s*=%s")' .. ltxdate_scheme .. '"', '%1' .. tagdate_ltx .. '"') return content elseif string.match(file, "^README%.md$") then content = string.gsub(content, "Copyright 2017%-%d%d%d%d", "Copyright 2017-" .. tagyear) return content elseif string.match(file, "^CHANGES%.md$") then content = string.gsub(content, "## Unreleased\n", "## Version " .. tagname_safe .. " (" .. tagdate .. ")\n") if string.match(content, "https://github.com/moewew/biblatex%-ext" .. "/compare/v" .. version_scheme .. "...HEAD") then content = string.gsub(content, "...HEAD", "...v" .. tagname_safe) end return content end return content end kpse.set_program_name ("kpsewhich") if not release_date then dofile(kpse.lookup("l3build.lua")) end
-- Author : Bobby -- Create Date : 8/5/2012 4:28:09 PM BobsActionBars = BobbyCode:CreateFrame("BobsActionBarsFrame", UIParent); local UnitEventHandlers = {}; function BobsActionBars:Initialize() for eventname, _ in pairs(UnitEventHandlers) do BobsActionBars:RegisterEvent(eventname); end BobsActionBars:ClearAllPoints(); BobsActionBars:SetPoint("BOTTOM", UIParent); BobsActionBars:SetHeight(1); BobsActionBars:SetWidth(1); --BobsActionBars:ShowBackground(true); --BobsActionBars:EnableMouse(true); BobbyCode:CreateFrame("MainBar", BobsActionBars); MainBar.Buttons = {}; MultiBarRight.Buttons = {}; MultiBarBottomLeft.Buttons = {}; MultiBarBottomRight.Buttons = {}; StanceBarFrame.Buttons = {}; for i = 1, 12 do MainBar.Buttons[i] = _G["ActionButton" .. i]; --MainBar.Buttons[i]:SetParent(MainBar); MultiBarRight.Buttons[i] = _G["MultiBarRightButton" .. i]; MultiBarBottomLeft.Buttons[i] = _G["MultiBarBottomLeftButton" .. i]; MultiBarBottomRight.Buttons[i] = _G["MultiBarBottomRightButton" .. i]; end for i = 1, NUM_STANCE_SLOTS do StanceBarFrame.Buttons[i] = _G["StanceButton" .. i]; if (StanceBarFrame.Buttons[i]) then _G["StanceButton" .. i .. "NormalTexture2"]:Hide(); end end for i = 1, 12 do BobsActionBars:SetupHiddenFrameButton(MainBar, MainBar.Buttons[i], BobsToolboxSettings.ActionBars.HideMainBarOutOfCombat); BobsActionBars:SetupHiddenFrameButton(MultiBarRight, MultiBarRight.Buttons[i], BobsToolboxSettings.ActionBars.HideMultiBarRightOutOfCombat); BobsActionBars:SetupHiddenFrameButton(MultiBarBottomLeft, MultiBarBottomLeft.Buttons[i], BobsToolboxSettings.ActionBars.HideMultiBarBottomLeftOutOfCombat); BobsActionBars:SetupHiddenFrameButton(MultiBarBottomRight, MultiBarBottomRight.Buttons[i], BobsToolboxSettings.ActionBars.HideMultiBarBottomRightOutOfCombat); end BobsActionBars:SetupHiddenBar(MainBar, BobsToolboxSettings.ActionBars.HideMainBarOutOfCombat); BobsActionBars:SetupHiddenBar(MultiBarRight, BobsToolboxSettings.ActionBars.HideMultiBarRightOutOfCombat); BobsActionBars:SetupHiddenBar(MultiBarBottomLeft, BobsToolboxSettings.ActionBars.HideMultiBarBottomLeftOutOfCombat); BobsActionBars:SetupHiddenBar(MultiBarBottomRight, BobsToolboxSettings.ActionBars.HideMultiBarBottomRightOutOfCombat); BobsActionBars:ResizeFrames(); BobsToolbox:RegisterTask("BobsActionBars", BobsActionBars.Timer, 1/20); end function BobsActionBars:ApplySettings() MainBar.FadeLevel = 0; MultiBarRight.FadeLevel = 0; MultiBarBottomLeft.FadeLevel = 0; MultiBarBottomRight.FadeLevel = 0; end function BobsActionBars:ResizeFrames() local HiddenFrame = BobbyCode:CreateFrame(BobsActionBars:GetName() .. "Hidden", nil) end function BobsActionBars:ResizeWatchBar(bar) bar:SetHeight(12); if (bar.StatusBar) then bar.StatusBar:SetAllPoints(bar); bar.StatusBar.SetAllPoints = function() end; bar.StatusBar.SetPoint = function() end; bar.StatusBar.WatchBarTexture0:SetAlpha(0); bar.StatusBar.WatchBarTexture1:SetAlpha(0); bar.StatusBar.WatchBarTexture2:SetAlpha(0); bar.StatusBar.WatchBarTexture3:SetAlpha(0); bar.StatusBar.XPBarTexture0:SetAlpha(0); bar.StatusBar.XPBarTexture1:SetAlpha(0); bar.StatusBar.XPBarTexture2:SetAlpha(0); bar.StatusBar.XPBarTexture3:SetAlpha(0); end if (bar.OverlayFrame) then bar.OverlayFrame:ClearAllPoints(); bar.OverlayFrame:SetAllPoints(bar); bar.OverlayFrame.SetAllPoints = function() end; bar.OverlayFrame.SetPoint = function() end; bar.OverlayFrame:Show(); bar.OverlayFrame.Text:ClearAllPoints(); bar.OverlayFrame.Text:SetAllPoints(bar.OverlayFrame); bar.OverlayFrame.Text.SetAllPoints = function() end; bar.OverlayFrame.Text.SetPoint = function() end; bar.OverlayFrame.Text:Show(); end end function BobsActionBars:SetupHiddenBar(bar, hide) bar:HookScript("OnEnter", function(self) BobbyCode:Unfade(self); end); end function BobsActionBars:SetupHiddenFrameButton(frame, button, hide) button:HookScript("OnEnter", function(self) BobbyCode:Unfade(frame); end); end function BobsActionBars:Unfade() BobbyCode:Unfade(StanceBarFrame); BobbyCode:Unfade(MainMenuBar); BobbyCode:Unfade(MultiBarLeft); BobbyCode:Unfade(MultiBarRight); BobbyCode:Unfade(MultiBarBottomLeft); BobbyCode:Unfade(MultiBarBottomRight); end function BobsActionBars:OnEvent(event, ...) UnitEventHandlers[event](self, ...); end UnitEventHandlers.PLAYER_REGEN_DISABLED = BobsActionBars.Unfade; BobsActionBars:SetScript("OnEvent", BobsActionBars.OnEvent); function BobsActionBars:Timer() if InCombatLockdown() then return; end BobbyCode:FadeRegion(MainBar); BobbyCode:FadeRegion(MultiBarRight); BobbyCode:FadeRegion(MultiBarBottomLeft); BobbyCode:FadeRegion(MultiBarBottomRight); local f = GetMouseFocus(); if (not f) then return; end for i = 1, NUM_STANCE_SLOTS do if (_G["StanceButton" .. i]) then _G["StanceButton" .. i .. "NormalTexture2"]:Hide(); end end if (f == WorldFrame) then if (BobsToolboxSettings.ActionBars.HideMainBarOutOfCombat) then BobbyCode:StartFade(MainBar); end if (BobsToolboxSettings.ActionBars.HideMultiBarRightOutOfCombat) then BobbyCode:StartFade(MultiBarRight); end if (BobsToolboxSettings.ActionBars.HideMultiBarBottomLeftOutOfCombat) then BobbyCode:StartFade(MultiBarBottomLeft); end if (BobsToolboxSettings.ActionBars.HideMultiBarBottomRightOutOfCombat) then BobbyCode:StartFade(MultiBarBottomRight); end end end
----------------------------------------------------------------------------- -- configuration values which you can adjust according to your liking ----------------------------------------------------------------------------- -- set to false if you do not want to have any villages spawning mg_villages.ENABLE_VILLAGES = true; -- generate one random building for each mg_villages.INVERSE_HOUSE_DENSITY th mapchunk; -- set to 0 in order to disable spawning of these lone buildings outside villages mg_villages.INVERSE_HOUSE_DENSITY = 0; -- cover some villages with artificial snow; probability: 1/mg_villages.artificial_snow_probability mg_villages.artificial_snow_probability = 0; -- if set to true, soil around villaes will get special soil-snow instead of plant + snow cover mg_villages.use_soil_snow = false; -- only place roads if there are at least that many buildings in the village mg_villages.MINIMAL_BUILDUNGS_FOR_ROAD_PLACEMENT = 4; -- players without the mg_villages priv can only see villages which are less than that many blocks away -- from them when using the /vmap command mg_villages.VILLAGE_DETECT_RANGE = 400; -- if set to true, only players which have the mg_villages priv can use the "/visit <village nr>" -- command which allows teleporting to the village with the given number mg_villages.REQUIRE_PRIV_FOR_TELEPORT = true; -- if set to true, players cannot modify spawned villages without buying the house from the village first mg_villages.ENABLE_PROTECTION = true; -- the first village - the one the player spawns in - will be of this type mg_villages.FIRST_VILLAGE_TYPE = 'medieval'; -- the mapgen will disregard mapchunks where min.y > mg_villages.MAX_HEIGHT_TREATED; -- you can set this value to 64 if you have a slow machine and a mapgen which does not create extreme mountains -- (or if you don't care if extreme mountains may create burried villages occasionally) mg_villages.MAX_HEIGHT_TREATED = 300; -- choose the debug level you want mg_villages.DEBUG_LEVEL = mg_villages.DEBUG_LEVEL_NONE -- if set to true (or anything else but nil or false), highlandpools by paramat (see -- https://forum.minetest.net/viewtopic.php?t=8400) will be created mg_villages.CREATE_HIGHLANDPOOLS = true -- background image for the /vmap command -- RealTest comes with a diffrent texture if( minetest.get_modpath('grounds') and minetest.get_modpath('joiner_table')) then mg_villages.MAP_BACKGROUND_IMAGE = "default_dirt_grass.png"; elseif( minetest.registered_nodes[ 'default:dirt_with_grass'] ) then mg_villages.MAP_BACKGROUND_IMAGE = "default_grass.png"; else mg_villages.MAP_BACKGROUND_IMAGE = ""; end -- if set to true, the outer buildings in medieval villages will be fields; this is not very convincing yet -- currently not really used; does not look as good as expected mg_villages.medieval_subtype = false; -- set this to true if you want to use normal lava - but beware: charachoal villages may cause bushfires! --mg_villages.use_normal_unsafe_lava = false; ----------------------------------------------------------------------------- -- decrese these values slightly if you want MORE trees around your villages; -- increase it if you want to DECREASE the amount of trees around villages ----------------------------------------------------------------------------- -- on average, every n.th node inside a village area may be one of these trees - and it will be a relatively dense packed forrest mg_villages.sapling_probability = {}; mg_villages.sapling_probability[ minetest.get_content_id( 'default:sapling' ) ] = 25; -- suitable for a relatively dense forrest of normal trees mg_villages.sapling_probability[ minetest.get_content_id( 'default:junglesapling' ) ] = 40; -- jungletrees are a bit bigger and need more space mg_villages.sapling_probability[ minetest.get_content_id( 'default:pinesapling' ) ] = 30; if( minetest.get_modpath( 'mg' )) then mg_villages.sapling_probability[ minetest.get_content_id( 'mg:savannasapling' ) ] = 30; mg_villages.sapling_probability[ minetest.get_content_id( 'mg:pinesapling' ) ] = 35; end mg_villages.moretrees_treelist = nil; if( minetest.get_modpath( 'moretrees' )) then mg_villages.moretrees_treelist = moretrees.treelist; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:birch_sapling_ongen' ) ] = 200; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:spruce_sapling_ongen' ) ] = 200; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:fir_sapling_ongen' ) ] = 90; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:jungletree_sapling_ongen' ) ] = 200; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:beech_sapling_ongen' ) ] = 30; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:apple_sapling_ongen' ) ] = 380; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:oak_sapling_ongen' ) ] = 380; -- ca 20x20; height: 10 mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:sequoia_sapling_ongen' ) ] = 90; -- ca 10x10 mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:palm_sapling_ongen' ) ] = 90; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:pine_sapling_ongen' ) ] = 200; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:willow_sapling_ongen' ) ] = 380; mg_villages.sapling_probability[ minetest.get_content_id( 'moretrees:rubber_tree_sapling_ongen' ) ] = 380; end ----------------------------------------------------------------------------- -- no need to change this, unless you add new farming_plus fruits ----------------------------------------------------------------------------- -- the schematics for buildings of type 'farm_tiny' grow cotton; the farming_plus fruits would be far more fitting mg_villages.fruit_list = {'carrot','potatoe','orange','rhubarb','strawberry','tomato','cotton'}; -- is farming_plus available? If not, we can't use this if( not( minetest.get_modpath("farming_plus"))) then mg_villages.fruit_list = nil; end ----------------------------------------------------------------------------- -- players can buy plots in villages with houses on for this price; -- set according to your liking ----------------------------------------------------------------------------- -- how much does the player have to pay for a plot with a building? mg_villages.prices = { empty = "default:copper_ingot 1", -- plot to build on -- building types which usually have inhabitants (and thus allow the player -- who bought the building to modifiy the entire village area minus other -- buildings) tent = "default:copper_ingot 1", hut = "default:copper_ingot 1", farm_full = "default:gold_ingot 4", farm_tiny = "default:gold_ingot 2", lumberjack = "default:gold_ingot 2", house = "default:gold_ingot 2", house_large = "default:gold_ingot 4", tavern = "default:gold_ingot 12", trader = "default:gold_ingot 2", -- more or less community buildings well = "default:gold_ingot 1", village_square = "default:goldblock 1", secular = "default:goldblock 2", -- secular buildings, such as libraries ec. church = "default:goldblock 10", -- places for mobs to work at; usually without inhabitants tower = "default:copper_ingot 1", shed = "default:copper_ingot 2", pit = "default:copper_ingot 3", -- claytrader pit mill = "default:gold_ingot 10", forge = "default:gold_ingot 10", bakery = "default:gold_ingot 10", shop = "default:gold_ingot 20", sawmill = "default:gold_ingot 30", -- decoration wagon = "default:tree 10", bench = "default:tree 4", -- seperate fields pasture = "default:copper_ingot 2", field = "default:copper_ingot 2", -- chateaus are expensive chateau = "default:diamondblock 5", } ----------------------------------------------------------------------------- -- The values below seldom need adjustment; don't change them unless you -- know exactly what you are doing. ----------------------------------------------------------------------------- -- if set to false, villages will not be integrated into the terrain - which looks very bad mg_villages.ENABLE_TERRAIN_BLEND = true; -- if set to false, holes digged by cavegen and mudflow inside the village will not be repaired; houses will be destroyed mg_villages.UNDO_CAVEGEN_AND_MUDFLOW = true; -- internal variables for village generation mg_villages.VILLAGE_CHECK_RADIUS = 2 mg_villages.VILLAGE_CHECK_COUNT = 1 --mg_villages.VILLAGE_CHANCE = 28 --mg_villages.VILLAGE_MIN_SIZE = 20 --mg_villages.VILLAGE_MAX_SIZE = 40 mg_villages.VILLAGE_CHANCE = 28 -- min and max size are only used in case of them beeing not provided by the village type (see buildings.lua) mg_villages.VILLAGE_MIN_SIZE = 10 mg_villages.VILLAGE_MAX_SIZE = 15 --55 mg_villages.FIRST_ROADSIZE = 3 mg_villages.BIG_ROAD_CHANCE = 0 -- Enable that for really big villages (there are also really slow to generate) --[[mg_villages.VILLAGE_CHECK_RADIUS = 3 mg_villages.VILLAGE_CHECK_COUNT = 3 mg_villages.VILLAGE_CHANCE = 28 mg_villages.VILLAGE_MIN_SIZE = 100 mg_villages.VILLAGE_MAX_SIZE = 150 mg_villages.FIRST_ROADSIZE = 5 mg_villages.BIG_ROAD_CHANCE = 50]]
object_tangible_furniture_all_uber_desk_map_table = object_tangible_furniture_all_shared_uber_desk_map_table:new { } ObjectTemplates:addTemplate(object_tangible_furniture_all_uber_desk_map_table, "object/tangible/furniture/all/uber_desk_map_table.iff")
local Plugin = SS.Plugins:New("Block") // When player spawns function Plugin.PlayerSpawn(Player) Player:SetCollisionGroup(11) end Plugin:Create()
the_curse_of_agony_the_curse_modifier = class({}) function the_curse_of_agony_the_curse_modifier:OnCreated( kv ) self.duration = self:GetAbility():GetSpecialValueFor("duration") end function the_curse_of_agony_the_curse_modifier:GetState( kv ) self.duration = self:GetAbility():GetSpecialValueFor("duration") end function the_curse_of_agony_the_curse_modifier:CheckState() local state = { [MODIFIER_STATE_NOT_ON_MINIMAP] = true, [MODIFIER_STATE_INVULNERABLE] = true, [MODIFIER_STATE_NO_HEALTH_BAR] = true, [MODIFIER_STATE_NO_UNIT_COLLISION] = true } return state end function the_curse_of_agony_the_curse_modifier:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_TOOLTIP, } return funcs end function the_curse_of_agony_the_curse_modifier:OnTooltip( params ) return self.duration end function the_curse_of_agony_the_curse_modifier:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end function the_curse_of_agony_the_curse_modifier:IsHidden() return false end function the_curse_of_agony_the_curse_modifier:IsPurgable() return false end function the_curse_of_agony_the_curse_modifier:IsPurgeException() return false end function the_curse_of_agony_the_curse_modifier:IsStunDebuff() return false end function the_curse_of_agony_the_curse_modifier:IsDebuff() return false end
local example = {} example.title = "Slider" example.category = "Object Demonstrations" function example.func(loveframes, centerarea) local frame = loveframes.create("frame") frame:setName("Slider") frame:setSize(300, 275) frame:centerWithinArea(unpack(centerarea)) local slider1 = loveframes.create("slider", frame) slider1:setPosition(5, 30) slider1:setWidth(290) slider1:setMinMax(0, 100) local slider2 = loveframes.create("slider", frame) slider2:setPosition(5, 60) slider2:setHeight(200) slider2:setMinMax(0, 100) slider2:setButtonSize(20, 10) slider2:setSlideType("vertical") slider2.update = function(object, dt) object:centerX() end end return example
local M = {} function M.get_colors() return require("catppuccin.core.color_palette") end return M
-- Note -- the prime factorization really needs to be made -- much more efficient. This is good enough for this problem -- but it lags far behind Python (sympy.factorint). -- -- It would help if the division only used prime numbers -- instead of trying every odd value -- -- I improved it in fermat2.lua which uses prime.lua but it -- only slightly outperforms sympy.factorint -- -- Lua version of the Fermat problem solution -- -- Search for numbers that have an interesting property noted by -- Fermat. The sum of the factors of the square of a number are -- a perfect cube. The first of these numbers is 1. What is the -- next larger integer with this property? dumpfactor = function(x) for i,j in pairs(x) do print(j[1],j[2]) end end -- Calculate the prime factors and multiplicities -- for the given integer. Returns a list of lists. -- The primitive list is {prime_factor, multiplicity}. factorint = function(n) local x local m x={} m=0 while (n%2 == 0) do m=m+1 n=n/2 end if (m ~= 0) then table.insert(x,{2,m}) end for i=3,n/2,2 do m=0 while (n%i == 0) do m=m+1 n=n/i end if (m ~= 0) then table.insert(x,{i,m}) end if n==1 then break end end if (n ~= 1) then table.insert(x,{n,1}) end return(x) end sumfactors = function(x) local s local t s=1 for i,j in pairs(x) do t=1 for k=1,j[2] do t=t*j[1]+1 end s=s*t end return(s) end search_solution = function(n1,n2) local eps local x local c local n eps=1e-6 -- need this to prevent round-off error from truncating results n1=n1 or 1 n2=n2 or 100 for n=n1,n2 do x=factorint(n) for k=1,#x do x[k][2]=2*x[k][2] end target=sumfactors(x) c=math.floor(math.pow(target,1/3)+eps) if (c*c*c == target) then print("Solution = " .. n) end end end
function love.load() math.randomseed(os.time()) highscores = {} love.graphics.setDefaultFilter("linear", "nearest") require "load.rpc" require "load.graphics" require "load.fonts" require "load.sounds" require "load.bgm" require "load.save" require "load.bigint" require "load.version" loadSave() require "funcs" require "scene" require "threaded_replay_code" --config["side_next"] = false --config["reverse_rotate"] = true --config["das_last_key"] = false --config["fullscreen"] = false love.window.setMode(love.graphics.getWidth(), love.graphics.getHeight(), {resizable = true}); -- used for screenshots GLOBAL_CANVAS = love.graphics.newCanvas() -- init config initConfig() love.window.setFullscreen(config["fullscreen"]) if config.secret then playSE("welcome") end -- import custom modules initModules() generateSoundTable() loadReplayList() end function initModules() game_modes = {} mode_list = love.filesystem.getDirectoryItems("tetris/modes") for i=1,#mode_list do if(mode_list[i] ~= "gamemode.lua" and string.sub(mode_list[i], -4) == ".lua") then game_modes[#game_modes+1] = require ("tetris.modes."..string.sub(mode_list[i],1,-5)) end end rulesets = {} rule_list = love.filesystem.getDirectoryItems("tetris/rulesets") for i=1,#rule_list do if(rule_list[i] ~= "ruleset.lua" and string.sub(rule_list[i], -4) == ".lua") then rulesets[#rulesets+1] = require ("tetris.rulesets."..string.sub(rule_list[i],1,-5)) end end --sort mode/rule lists local function padnum(d) return ("%03d%s"):format(#d, d) end table.sort(game_modes, function(a,b) return tostring(a.name):gsub("%d+",padnum) < tostring(b.name):gsub("%d+",padnum) end) table.sort(rulesets, function(a,b) return tostring(a.name):gsub("%d+",padnum) < tostring(b.name):gsub("%d+",padnum) end) end --#region Tetro48's code local io_thread function loadReplayList() replays = {} replay_tree = {{name = "All"}} dict_ref = {} loaded_replays = false io_thread = love.thread.newThread( replay_load_code ) local mode_names = {} for key, value in pairs(game_modes) do table.insert(mode_names, value.name) end io_thread:start(mode_names) end function nilCheck(input, default) if input == nil then return default end return input end function popFromChannel(channel_name) local load_from = love.thread.getChannel(channel_name):pop() if load_from then return load_from end end left_clicked_before = false right_clicked_before = false prev_cur_pos_x, prev_cur_pos_y = 0, 0 is_cursor_visible = true mouse_idle = 0 TAS_mode = false frame_steps = 0 loaded_replays = false -- For when mouse controls are part of menu controls function getScaledPos(cursor_x, cursor_y) local screen_x, screen_y = love.graphics.getDimensions() local scale_factor = math.min(screen_x / 640, screen_y / 480) return (cursor_x - (screen_x - scale_factor * 640) / 2)/scale_factor, (cursor_y - (screen_y - scale_factor * 480) / 2)/scale_factor end function CursorHighlight(x,y,w,h) local mouse_x, mouse_y = getScaledPos(love.mouse.getPosition()) if mouse_idle > 2 or config.visualsettings.cursor_highlight ~= 1 then return 1 end if mouse_x > x and mouse_x < x+w and mouse_y > y and mouse_y < y+h then return 0 else return 1 end end --Interpolates in a smooth fashion. function interpolateListPos(input, from) if config.visualsettings["smooth_scroll"] == 2 then return from end if from > input then input = input + (from - input) / 4 if input > from - 0.02 then input = from end elseif from < input then input = input + (from - input) / 4 if input < from + 0.02 then input = from end end return input end function drawT48Cursor(x, y, a) if a <= 0 then return end love.graphics.setColor(1,1,1,a) love.graphics.polygon("fill", x + 5, y + 0, x + 0, y + 10, x + 5, y + 8, x + 8, y + 20, x + 12, y + 18, x + 10, y + 7, x + 15, y + 5) love.graphics.setColor(0,0,0,a) love.graphics.polygon("line", x + 5, y + 0, x + 0, y + 10, x + 5, y + 8, x + 8, y + 20, x + 12, y + 18, x + 10, y + 7, x + 15, y + 5) love.graphics.setColor(1,1,1,a) end --#endregion function love.draw() love.graphics.setCanvas(GLOBAL_CANVAS) love.graphics.clear() love.graphics.push() -- get offset matrix local width = love.graphics.getWidth() local height = love.graphics.getHeight() local scale_factor = math.min(width / 640, height / 480) love.graphics.translate( (width - scale_factor * 640) / 2, (height - scale_factor * 480) / 2 ) love.graphics.scale(scale_factor) scene:render() if TAS_mode then love.graphics.setColor(1, 1, 1, love.timer.getTime() % 2 < 1 and 1 or 0) love.graphics.setFont(font_3x5_3) love.graphics.printf( "TAS MODE ON", 240, 0, 160, "center" ) end if config.visualsettings.display_gamemode == 1 or scene.title == "Title" then love.graphics.setFont(font_3x5_2) love.graphics.setColor(1, 1, 1, 1) love.graphics.printf( string.format("%.2f", 1 / love.timer.getAverageDelta()) .. "fps - " .. version, 0, 460, 635, "right" ) end if scene.title == "Game" or scene.title == "Replay" then -- if config.visualsettings.cursor_type ~= 1 then -- is_cursor_visible = true -- else -- is_cursor_visible = love.mouse.isVisible() -- end -- config.visualsettings.cursor_type = 0 -- love.mouse.setVisible(is_cursor_visible) else love.mouse.setVisible(config.visualsettings.cursor_type == 1) if config.visualsettings.cursor_type ~= 1 then local lx, ly = getScaledPos(love.mouse.getPosition()) drawT48Cursor(lx, ly, 9 - mouse_idle * 4) end end love.graphics.pop() love.graphics.setCanvas() love.graphics.setColor(1,1,1,1) love.graphics.draw(GLOBAL_CANVAS) end function love.keypressed(key, scancode) -- global hotkeys if scancode == "f11" then config["fullscreen"] = not config["fullscreen"] saveConfig() love.window.setFullscreen(config["fullscreen"]) elseif scancode == "f1" then TAS_mode = not TAS_mode elseif scancode == "f2" and scene.title ~= "Input Config" and scene.title ~= "Game" then scene = InputConfigScene() switchBGM(nil) loadSave() elseif scancode == "f3" and TAS_mode and scene.title == "Game" then frame_steps = frame_steps + 1 -- secret sound playing :eyes: elseif scancode == "f8" and scene.title == "Title" then config.secret = not config.secret saveConfig() scene.restart_message = true if config.secret then playSE("mode_decide") else playSE("erase") end -- f12 is reserved for saving screenshots elseif scancode == "f12" then local ss_name = os.date("ss/%Y-%m-%d_%H-%M-%S.png") local info = love.filesystem.getInfo("ss", "directory") if not info then love.filesystem.remove("ss") love.filesystem.createDirectory("ss") end print("Saving screenshot as "..love.filesystem.getSaveDirectory().."/"..ss_name) GLOBAL_CANVAS:newImageData():encode("png", ss_name) -- function keys are reserved elseif string.match(scancode, "^f[1-9]$") or string.match(scancode, "^f[1-9][0-9]+$") then return -- escape is reserved for menu_back elseif scancode == "escape" then scene:onInputPress({input="menu_back", type="key", key=key, scancode=scancode}) -- pass any other key to the scene, with its configured mapping else local input_pressed = nil if config.input and config.input.keys then input_pressed = config.input.keys[scancode] end scene:onInputPress({input=input_pressed, type="key", key=key, scancode=scancode}) end end function love.keyreleased(key, scancode) -- escape is reserved for menu_back if scancode == "escape" then scene:onInputRelease({input="menu_back", type="key", key=key, scancode=scancode}) -- function keys are reserved elseif string.match(scancode, "^f[1-9]$") or string.match(scancode, "^f[1-9][0-9]+$") then return -- handle all other keys; tab is reserved, but the input config scene keeps it from getting configured as a game input, so pass tab to the scene here else local input_released = nil if config.input and config.input.keys then input_released = config.input.keys[scancode] end scene:onInputRelease({input=input_released, type="key", key=key, scancode=scancode}) end end function love.joystickpressed(joystick, button) local input_pressed = nil if config.input and config.input.joysticks and config.input.joysticks[joystick:getName()] and config.input.joysticks[joystick:getName()].buttons then input_pressed = config.input.joysticks[joystick:getName()].buttons[button] end scene:onInputPress({input=input_pressed, type="joybutton", name=joystick:getName(), button=button}) end function love.joystickreleased(joystick, button) local input_released = nil if config.input and config.input.joysticks and config.input.joysticks[joystick:getName()] and config.input.joysticks[joystick:getName()].buttons then input_released = config.input.joysticks[joystick:getName()].buttons[button] end scene:onInputRelease({input=input_released, type="joybutton", name=joystick:getName(), button=button}) end function love.joystickaxis(joystick, axis, value) local input_pressed = nil local positive_released = nil local negative_released = nil if config.input and config.input.joysticks and config.input.joysticks[joystick:getName()] and config.input.joysticks[joystick:getName()].axes and config.input.joysticks[joystick:getName()].axes[axis] then if math.abs(value) >= 1 then input_pressed = config.input.joysticks[joystick:getName()].axes[axis][value >= 1 and "positive" or "negative"] end positive_released = config.input.joysticks[joystick:getName()].axes[axis].positive negative_released = config.input.joysticks[joystick:getName()].axes[axis].negative end if math.abs(value) >= 1 then scene:onInputPress({input=input_pressed, type="joyaxis", name=joystick:getName(), axis=axis, value=value}) else scene:onInputRelease({input=positive_released, type="joyaxis", name=joystick:getName(), axis=axis, value=value}) scene:onInputRelease({input=negative_released, type="joyaxis", name=joystick:getName(), axis=axis, value=value}) end end local last_hat_direction = "" local directions = { ["u"] = "up", ["d"] = "down", ["l"] = "left", ["r"] = "right", } function love.joystickhat(joystick, hat, direction) local input_pressed = nil local has_hat = false if config.input and config.input.joysticks and config.input.joysticks[joystick:getName()] and config.input.joysticks[joystick:getName()].hats and config.input.joysticks[joystick:getName()].hats[hat] then if direction ~= "c" then input_pressed = config.input.joysticks[joystick:getName()].hats[hat][direction] end has_hat = true end if input_pressed then for i = 1, #direction do local char = direction:sub(i, i) local _, count = last_hat_direction:gsub(char, char) if count == 0 then scene:onInputPress({input=config.input.joysticks[joystick:getName()].hats[hat][char], type="joyhat", name=joystick:getName(), hat=hat, direction=char}) end end for i = 1, #last_hat_direction do local char = last_hat_direction:sub(i, i) local _, count = direction:gsub(char, char) if count == 0 then scene:onInputRelease({input=config.input.joysticks[joystick:getName()].hats[hat][char], type="joyhat", name=joystick:getName(), hat=hat, direction=char}) end end last_hat_direction = direction elseif has_hat then for i, direction in ipairs{"d", "l", "ld", "lu", "r", "rd", "ru", "u"} do scene:onInputRelease({input=config.input.joysticks[joystick:getName()].hats[hat][direction], type="joyhat", name=joystick:getName(), hat=hat, direction=direction}) end last_hat_direction = "" elseif direction ~= "c" then for i = 1, #direction do local char = direction:sub(i, i) local _, count = last_hat_direction:gsub(char, char) if count == 0 then scene:onInputPress({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char}) end end for i = 1, #last_hat_direction do local char = last_hat_direction:sub(i, i) local _, count = direction:gsub(char, char) if count == 0 then scene:onInputRelease({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char}) end end last_hat_direction = direction else for i, direction in ipairs{"d", "l", "ld", "lu", "r", "rd", "ru", "u"} do scene:onInputRelease({input=nil, type="joyhat", name=joystick:getName(), hat=hat, direction=direction}) end last_hat_direction = "" end end function love.wheelmoved(x, y) scene:onInputPress({input=nil, type="wheel", x=x, y=y}) end function love.focus(f) if f then resumeBGM(true) else pauseBGM(true) end end function love.resize(w, h) GLOBAL_CANVAS:release() GLOBAL_CANVAS = love.graphics.newCanvas(w, h) end local TARGET_FPS = 60 function love.run() if love.load then love.load(love.arg.parseGameArguments(arg), arg) end if love.timer then love.timer.step() end local dt = 0 local last_time = love.timer.getTime() local time_accumulator = 0 return function() if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then if not love.quit or not love.quit() then return a or 0 end end love.handlers[name](a,b,c,d,e,f) end end if love.timer then processBGMFadeout(love.timer.step()) end if scene and scene.update and love.timer then scene:update() local frame_duration = 1.0 / TARGET_FPS if time_accumulator < frame_duration then if love.graphics and love.graphics.isActive() and love.draw then love.graphics.origin() love.graphics.clear(love.graphics.getBackgroundColor()) love.draw() love.graphics.present() end local end_time = last_time + frame_duration local time = love.timer.getTime() while time < end_time do love.timer.sleep(0.001) time = love.timer.getTime() end time_accumulator = time_accumulator + time - last_time end time_accumulator = time_accumulator - frame_duration if love.mouse then left_clicked_before = love.mouse.isDown(1) or mouse_idle > 2 right_clicked_before = love.mouse.isDown(2) or mouse_idle > 2 if prev_cur_pos_x == love.mouse.getX() and prev_cur_pos_y == love.mouse.getY() then mouse_idle = mouse_idle + love.timer.getDelta() else mouse_idle = 0 end prev_cur_pos_x, prev_cur_pos_y = love.mouse.getPosition() end end last_time = love.timer.getTime() end end
--ナチュル・レディバグ function c19605133.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(19605133,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_GRAVE) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c19605133.spcon) e1:SetTarget(c19605133.sptg) e1:SetOperation(c19605133.spop) c:RegisterEffect(e1) --atkup local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(19605133,1)) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCost(c19605133.atcost) e2:SetTarget(c19605133.attg) e2:SetOperation(c19605133.atop) c:RegisterEffect(e2) end function c19605133.spcon(e,tp,eg,ep,ev,re,r,rp) local ec=eg:GetFirst() return ec:IsSetCard(0x2a) and ec:IsSummonType(SUMMON_TYPE_SYNCHRO) and ec:IsSummonPlayer(tp) end function c19605133.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c19605133.spop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end function c19605133.atcost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() local fe=Duel.IsPlayerAffectedByEffect(tp,101110021) local b1=fe and Duel.IsPlayerCanDiscardDeckAsCost(tp,2) local b2=c:IsReleasable() if chk==0 then return b1 or b2 end if b1 and (not b2 or Duel.SelectYesNo(tp,fe:GetDescription())) then Duel.Hint(HINT_CARD,0,101110021) fe:UseCountLimit(tp) Duel.DiscardDeck(tp,2,REASON_COST) else Duel.Release(c,REASON_COST) end end function c19605133.filter(c) return c:IsFaceup() and c:IsSetCard(0x2a) end function c19605133.attg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c19605133.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c19605133.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c19605133.filter,tp,LOCATION_MZONE,0,1,1,nil) end function c19605133.atop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(1000) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end
depends_on("Dependency/5.6")
deepboof = {} local function log10(n) if math.log10 then return math.log10(n) else return math.log(n) / math.log(10) end end -- Converts the confusion matrix into an easy to parse string function deepboof.confusionToString( confusion ) confusion:updateValids() local str = {''} local nclasses = confusion.nclasses -- Print all the classes on the first line for t = 1,nclasses do if t == nclasses then table.insert(str,confusion.classes[t] .. '\n') else table.insert(str,confusion.classes[t] .. ' ') end end -- Now print the actual table for t = 1,nclasses do for p = 1,nclasses do table.insert(str, string.format('%d', confusion.mat[t][p]) .. ' ') end table.insert(str,'\n') end return table.concat(str) end
local skynet = require "skynet" local mt19937 = require "extlib.mt19937" skynet.start(function() -- random seed mt19937.init(tostring(os.time()):reverse():sub(1, 6)) -- random integer of range [1, 1000) for i = 1, 10 do print(mt19937.randi(1, 1000)) end -- random real of range [0, 1) for j = 1, 10 do print(mt19937.randr()) end skynet.exit() end)
gl.setup(1024, 768) local interval = 5 local json = require "json" util.loaders.json = function(filename) return json.decode(resource.load_file(filename)) end util.auto_loader(_G) local stats = { function () bold:write(10, 150, "GSM", 150, 1,1,1,1) regular:write(10, 350, gsm.active_subscribers .. " subscribers", 90, 1,1,1,1) regular:write(10, 450, gsm.sms_delivered.. " SMS delivered", 90, 1,1,1,1) end; function () bold:write(10, 150, "Wlan", 150, 1,1,1,1) regular:write(10, 350, dash.clients.value[2] .. " Clients", 100, 1,1,1,1) end; function () bold:write(10, 150, "POC", 150, 1,1,1,1) regular:write(10, 350, dash.poc.value[1] .. " Phones", 100, 1,1,1,1) end; function () bold:write(10, 150, "Bandwidth", 150, 1,1,1,1) regular:write(10, 350, dash.bw.value[1] .. " Mbps down", 100, 1,1,1,1) regular:write(10, 450, dash.bw.value[2] .. " Mbps up", 100, 1,1,1,1) end; } function node.render() stats[math.floor((sys.now() / interval) % #stats)+1]() end
--- fs operations implemented with third-party tools for Windows platform abstractions. -- Download http://unxutils.sourceforge.net/ for Windows GNU utilities -- used by this module. local tools = {} local fs = require("luarocks.fs") local dir = require("luarocks.dir") local cfg = require("luarocks.core.cfg") local vars = setmetatable({}, { __index = function(_,k) return cfg.variables[k] end }) --- Adds prefix to command to make it run from a directory. -- @param directory string: Path to a directory. -- @param cmd string: A command-line string. -- @param exit_on_error bool: Exits immediately if entering the directory failed. -- @return string: The command-line with prefix. function tools.command_at(directory, cmd, exit_on_error) local drive = directory:match("^([A-Za-z]:)") local op = " & " if exit_on_error then op = " && " end local cmd = "cd " .. fs.Q(directory) .. op .. cmd if drive then cmd = drive .. " & " .. cmd end return cmd end --- Create a directory if it does not already exist. -- If any of the higher levels in the path name does not exist -- too, they are created as well. -- @param directory string: pathname of directory to create. -- @return boolean: true on success, false on failure. function tools.make_dir(directory) assert(directory) directory = dir.normalize(directory) fs.execute_quiet(fs.Q(vars.MKDIR).." -p ", directory) if not fs.is_dir(directory) then return false, "failed making directory "..directory end return true end --- Remove a directory if it is empty. -- Does not return errors (for example, if directory is not empty or -- if already does not exist) -- @param directory string: pathname of directory to remove. function tools.remove_dir_if_empty(directory) assert(directory) fs.execute_quiet(fs.Q(vars.RMDIR), directory) end --- Remove a directory if it is empty. -- Does not return errors (for example, if directory is not empty or -- if already does not exist) -- @param directory string: pathname of directory to remove. function tools.remove_dir_tree_if_empty(directory) assert(directory) fs.execute_quiet(fs.Q(vars.RMDIR), directory) end --- Copy a file. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message. function tools.copy(src, dest) assert(src and dest) if dest:match("[/\\]$") then dest = dest:sub(1, -2) end local ok = fs.execute(fs.Q(vars.CP), src, dest) if ok then return true else return false, "Failed copying "..src.." to "..dest end end --- Recursively copy the contents of a directory. -- @param src string: Pathname of source -- @param dest string: Pathname of destination -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message. function tools.copy_contents(src, dest) assert(src and dest) if not fs.is_dir(src) then return false, src .. " is not a directory" end if fs.make_dir(dest) and fs.execute_quiet(fs.Q(vars.CP), "-dR", src.."\\*.*", dest) then return true else return false, "Failed copying "..src.." to "..dest end end --- Delete a file or a directory and all its contents. -- For safety, this only accepts absolute paths. -- @param arg string: Pathname of source -- @return nil function tools.delete(arg) assert(arg) assert(arg:match("^[a-zA-Z]?:?[\\/]")) fs.execute_quiet("if exist "..fs.Q(arg.."\\*").." ( RMDIR /S /Q "..fs.Q(arg).." ) else ( DEL /Q /F "..fs.Q(arg).." )") end --- Recursively scan the contents of a directory. -- @param at string or nil: directory to scan (will be the current -- directory if none is given). -- @return table: an array of strings with the filenames representing -- the contents of a directory. Paths are returned with forward slashes. function tools.find(at) assert(type(at) == "string" or not at) if not at then at = fs.current_dir() end if not fs.is_dir(at) then return {} end local result = {} local pipe = io.popen(fs.command_at(at, fs.quiet_stderr(fs.Q(vars.FIND)), true)) for file in pipe:lines() do -- Windows find is a bit different local first_two = file:sub(1,2) if first_two == ".\\" or first_two == "./" then file=file:sub(3) end if file ~= "." then table.insert(result, (file:gsub("\\", "/"))) end end pipe:close() return result end --- Compress files in a .zip archive. -- @param zipfile string: pathname of .zip archive to be created. -- @param ... Filenames to be stored in the archive are given as -- additional arguments. -- @return boolean: true on success, nil and error message on failure. function tools.zip(zipfile, ...) if fs.execute_quiet(fs.Q(vars.SEVENZ).." -aoa a -tzip", zipfile, ...) then return true else return nil, "failed compressing " .. zipfile end end --- Uncompress files from a .zip archive. -- @param zipfile string: pathname of .zip archive to be extracted. -- @return boolean: true on success, nil and error message on failure. function tools.unzip(zipfile) assert(zipfile) if fs.execute_quiet(fs.Q(vars.SEVENZ).." -aoa x", zipfile) then return true else return nil, "failed extracting " .. zipfile end end local function sevenz(default_ext, infile, outfile) assert(type(infile) == "string") assert(outfile == nil or type(outfile) == "string") local dropext = infile:gsub("%."..default_ext.."$", "") local outdir = dir.dir_name(dropext) infile = fs.absolute_name(infile) local cmdline = fs.Q(vars.SEVENZ).." -aoa -t* -o"..fs.Q(outdir).." x "..fs.Q(infile) local ok, err = fs.execute_quiet(cmdline) if not ok then return nil, "failed extracting " .. infile end if outfile then outfile = fs.absolute_name(outfile) dropext = fs.absolute_name(dropext) ok, err = os.rename(dropext, outfile) if not ok then return nil, "failed creating new file " .. outfile end end return true end --- Uncompresses a .gz file. -- @param infile string: pathname of .gz file to be extracted. -- @param outfile string or nil: pathname of output file to be produced. -- If not given, name is derived from input file. -- @return boolean: true on success; nil and error message on failure. function tools.gunzip(infile, outfile) return sevenz("gz", infile, outfile) end --- Uncompresses a .bz2 file. -- @param infile string: pathname of .bz2 file to be extracted. -- @param outfile string or nil: pathname of output file to be produced. -- If not given, name is derived from input file. -- @return boolean: true on success; nil and error message on failure. function tools.bunzip2(infile, outfile) return sevenz("bz2", infile, outfile) end --- Test is pathname is a directory. -- @param file string: pathname to test -- @return boolean: true if it is a directory, false otherwise. function tools.is_dir(file) assert(file) return fs.execute_quiet("if not exist " .. fs.Q(file.."\\").." invalidcommandname") end --- Test is pathname is a regular file. -- @param file string: pathname to test -- @return boolean: true if it is a regular file, false otherwise. function tools.is_file(file) assert(file) return fs.execute(fs.Q(vars.TEST).." -f", file) end --- Helper function for fs.set_permissions -- @return table: an array of all system users local function get_system_users() local result = {} local fd = assert(io.popen("wmic UserAccount get name")) for user in fd:lines() do user = user:gsub("%s+$", "") if user ~= "" and user ~= "Name" and user ~= "Administrator" then table.insert(result, user) end end return result end --- Set permissions for file or directory -- @param filename string: filename whose permissions are to be modified -- @param mode string ("read" or "exec"): permission to set -- @param scope string ("user" or "all"): the user(s) to whom the permission applies -- @return boolean or (boolean, string): true on success, false on failure, -- plus an error message function tools.set_permissions(filename, mode, scope) assert(filename and mode and scope) if scope == "user" then local perms if mode == "read" then perms = "(R,W,M)" elseif mode == "exec" then perms = "(F)" end local ok -- Take ownership of the given file ok = fs.execute_quiet("takeown /f " .. fs.Q(filename)) if not ok then return false, "Could not take ownership of the given file" end -- Grant the current user the proper rights ok = fs.execute_quiet(fs.Q(vars.ICACLS) .. " " .. fs.Q(filename) .. " /inheritance:d /grant:r %USERNAME%:" .. perms) if not ok then return false, "Failed setting permission " .. mode .. " for " .. scope end -- Finally, remove all the other users from the ACL in order to deny them access to the file for _, user in pairs(get_system_users()) do local ok = fs.execute_quiet(fs.Q(vars.ICACLS) .. " " .. fs.Q(filename) .. " /remove " .. fs.Q(user)) if not ok then return false, "Failed setting permission " .. mode .. " for " .. scope end end elseif scope == "all" then local my_perms, others_perms if mode == "read" then my_perms = "(R,W,M)" others_perms = "(R)" elseif mode == "exec" then my_perms = "(F)" others_perms = "(RX)" end local ok -- Grant permissions available to all users ok = fs.execute_quiet(fs.Q(vars.ICACLS) .. " " .. fs.Q(filename) .. " /inheritance:d /grant:r *S-1-1-0:" .. others_perms) if not ok then return false, "Failed setting permission " .. mode .. " for " .. scope end -- Grant permissions available only to the current user ok = fs.execute_quiet(fs.Q(vars.ICACLS) .. " " .. fs.Q(filename) .. " /inheritance:d /grant %USERNAME%:" .. my_perms) if not ok then return false, "Failed setting permission " .. mode .. " for " .. scope end end return true end --- Test for existence of a file. -- @param file string: filename to test -- @return boolean: true if file exists, false otherwise. function tools.exists(file) assert(file) return fs.execute_quiet("if not exist " .. fs.Q(file) .. " invalidcommandname") end function tools.browser(url) return fs.execute(cfg.web_browser..' "Starting docs..." '..fs.Q(url)) end -- Set access and modification times for a file. -- @param filename File to set access and modification times for. -- @param time may be a string or number containing the format returned -- by os.time, or a table ready to be processed via os.time; if -- nil, current time is assumed. function tools.set_time(filename, time) return true -- FIXME end return tools
local function test1() local function plus(a, b) return a + b end local function varargs(a, ...) return a + plus(...) end return varargs(1, 2, 3) == 6 end local function test2() local function varargs(a, b, ...) local i, j, k, l = a, b, ... return i + j + k + l end return varargs(1, 2, 3, 4) == 10 and varargs(0, 1, 1, 2, 3, 5) == 4 end return test1() and test2()
local K, _, L = unpack(KkthnxUI) local Module = K:GetModule("AurasTable") if K.Class ~= "ROGUE" then return end local list = { ["Player Aura"] = { -- 玩家光环组 { AuraID = 1784, UnitID = "player" }, -- 潜行 { AuraID = 115191, UnitID = "player" }, -- 潜行 { AuraID = 2983, UnitID = "player" }, -- 疾跑 { AuraID = 36554, UnitID = "player" }, -- 暗影步 { AuraID = 197603, UnitID = "player" }, -- 黑暗之拥 { AuraID = 270070, UnitID = "player" }, -- 隐藏之刃 }, ["Target Aura"] = { -- 目标光环组 { AuraID = 408, UnitID = "target", Caster = "player" }, -- 肾击 { AuraID = 703, UnitID = "target", Caster = "player" }, -- 锁喉 { AuraID = 1833, UnitID = "target", Caster = "player" }, -- 偷袭 { AuraID = 6770, UnitID = "target", Caster = "player" }, -- 闷棍 { AuraID = 2094, UnitID = "target", Caster = "player" }, -- 致盲 { AuraID = 1330, UnitID = "target", Caster = "player" }, -- 锁喉 { AuraID = 1776, UnitID = "target", Caster = "player" }, -- 凿击 { AuraID = 1943, UnitID = "target", Caster = "player" }, -- 割裂 { AuraID = 79140, UnitID = "target", Caster = "player" }, -- 宿敌 { AuraID = 16511, UnitID = "target", Caster = "player" }, -- 出血 { AuraID = 192759, UnitID = "target", Caster = "player" }, -- 君王之灾 { AuraID = 192425, UnitID = "target", Caster = "player" }, -- 毒素冲动 { AuraID = 200803, UnitID = "target", Caster = "player" }, -- 苦痛毒液 { AuraID = 137619, UnitID = "target", Caster = "player" }, -- 死亡标记 { AuraID = 195452, UnitID = "target", Caster = "player" }, -- 夜刃 { AuraID = 209786, UnitID = "target", Caster = "player" }, -- 赤喉之咬 { AuraID = 196958, UnitID = "target", Caster = "player" }, -- 暗影打击 { AuraID = 196937, UnitID = "target", Caster = "player" }, -- 鬼魅攻击 { AuraID = 192925, UnitID = "target", Caster = "player" }, -- 遇刺者之血 { AuraID = 245389, UnitID = "target", Caster = "player" }, -- 淬毒之刃 { AuraID = 121411, UnitID = "target", Caster = "player" }, -- 猩红风暴 { AuraID = 255909, UnitID = "target", Caster = "player" }, -- 欺凌 { AuraID = 316220, UnitID = "target", Caster = "player" }, -- 洞悉弱点 { AuraID = 315341, UnitID = "target", Caster = "player" }, -- 正中眉心 { AuraID = 328305, UnitID = "target", Caster = "player" }, -- 败血刃伤 { AuraID = 323654, UnitID = "target", Caster = "player" }, -- Flagellation { AuraID = 324073, UnitID = "target", Caster = "player" }, -- 锯齿骨刺 }, ["Special Aura"] = { -- 玩家重要光环组 { AuraID = 1966, UnitID = "player" }, -- 佯攻 { AuraID = 5171, UnitID = "player" }, -- 切割 { AuraID = 5277, UnitID = "player" }, -- 闪避 { AuraID = 11327, UnitID = "player" }, -- 消失 { AuraID = 13750, UnitID = "player" }, -- 冲动 { AuraID = 13877, UnitID = "player" }, -- 剑刃乱舞 { AuraID = 31224, UnitID = "player" }, -- 暗影斗篷 { AuraID = 32645, UnitID = "player" }, -- 毒伤 { AuraID = 45182, UnitID = "player" }, -- 装死 { AuraID = 31665, UnitID = "player" }, -- 敏锐大师 { AuraID = 185311, UnitID = "player" }, -- 猩红之瓶 { AuraID = 193641, UnitID = "player" }, -- 深谋远虑 { AuraID = 115192, UnitID = "player" }, -- 诡诈 { AuraID = 193538, UnitID = "player" }, -- 敏锐 { AuraID = 121471, UnitID = "player" }, -- 暗影之刃 { AuraID = 185422, UnitID = "player" }, -- 影舞 { AuraID = 212283, UnitID = "player" }, -- 死亡标记 { AuraID = 202754, UnitID = "player" }, -- 隐秘刀刃 { AuraID = 193356, UnitID = "player", Text = L["Combo"] }, -- 强势连击,骰子 { AuraID = 193357, UnitID = "player", Text = L["Crit"] }, -- 暗鲨涌动,骰子 { AuraID = 193358, UnitID = "player", Text = L["AttackSpeed"] }, -- 大乱斗,骰子 { AuraID = 193359, UnitID = "player", Text = L["CD"] }, -- 双巧手,骰子 { AuraID = 199603, UnitID = "player", Text = L["Strike"] }, -- 骷髅黑帆,骰子 { AuraID = 199600, UnitID = "player", Text = L["Power"] }, -- 埋藏的宝藏,骰子 { AuraID = 202665, UnitID = "player" }, -- 恐惧之刃诅咒 { AuraID = 199754, UnitID = "player" }, -- 还击 { AuraID = 195627, UnitID = "player" }, -- 可乘之机 { AuraID = 121153, UnitID = "player" }, -- 侧袭 { AuraID = 256735, UnitID = "player", Combat = true }, -- 刺客大师 { AuraID = 271896, UnitID = "player" }, -- 刀锋冲刺 { AuraID = 51690, UnitID = "player" }, -- 影舞步 { AuraID = 277925, UnitID = "player" }, -- 袖剑旋风 { AuraID = 196980, UnitID = "player" }, -- 暗影大师 { AuraID = 315496, UnitID = "player" }, -- 切割 { AuraID = 343142, UnitID = "player" }, -- 恐惧之刃 }, ["Focus Aura"] = { -- 焦点光环组 { AuraID = 6770, UnitID = "focus", Caster = "player" }, -- 闷棍 { AuraID = 2094, UnitID = "focus", Caster = "player" }, -- 致盲 }, ["Spell Cooldown"] = { -- 冷却计时组 { SlotID = 13 }, -- 饰品1 { SlotID = 14 }, -- 饰品2 { SpellID = 13750 }, -- 冲动 { SpellID = 79140 }, -- 宿敌 { SpellID = 121471 }, -- 暗影之刃 }, } Module:AddNewAuraWatch("ROGUE", list)
local bmp_exporter = require "bmp_exporter" local CHIP_PICTURE_DEFS = {} local NUM_COLORS_PER_PALETTE = 16 function convert_gba_to_argb(gba_color) local red = bit.lshift(bit.band(gba_color, 31), 3) local green = bit.lshift(bit.band(bit.rshift(gba_color, 5), 31), 3) local blue = bit.lshift(bit.band(bit.rshift(gba_color, 10), 31), 3) local alpha = 255 return bit.bor(bit.bor(bit.bor(bit.lshift(alpha, 24), bit.lshift(red, 16)), bit.lshift(green, 8)), blue) end function get_palette_argb(palette_address) -- Just read words from the address until we got 16 words. We store them in a keyed table by their index local argb_table = {} local working_address = palette_address - 0x08000000 for i = 0, NUM_COLORS_PER_PALETTE - 1 do local palette_val = memory.read_u16_le(working_address, "ROM") working_address = working_address + 2 argb_table[i] = convert_gba_to_argb(palette_val) --print("PALETTE: ", bizstring.hex(palette_val), " = ", bizstring.hex(convert_gba_to_argb(palette_val))) end return argb_table end -- Notes: Each image is rendered as 8x8 tiles of 32 bytes, where each byte describes 2 pixels. -- The render order is row wise per tile, and rows of tiles first. -- Each tile is stored row-wise. CHIP_PICTURE_DEFS.TILES_PER_CHIP = 64 CHIP_PICTURE_DEFS.TILES_PER_DIMENSION = 8 CHIP_PICTURE_DEFS.BYTES_PER_TILE = 32 CHIP_PICTURE_DEFS.BYTES_PER_TILE_LINE = 4 CHIP_PICTURE_DEFS.PIXELS_PER_TILE_LINE = 8 CHIP_PICTURE_DEFS.WIDTH = 64 CHIP_PICTURE_DEFS.HEIGHT = 64 function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function CHIP_PICTURE_DEFS.generate_image_cache(CHIP_DATA, CHIP_ID) for key, value in pairs(CHIP_ID) do --local file_name = "Lua/mmbn3_draft_gauntlet/chip_images/" .. value .. ".bmp" local file_name = "chip_images/" .. value .. ".bmp" if not file_exists(file_name) then local chip_address = CHIP_DATA[value].CHIP_PICTURE_OFFSET local chip_palette_address = CHIP_DATA[value].CHIP_PICTURE_PALETTE_OFFSET local argb_array = CHIP_PICTURE_DEFS.get_argb_2d_array_for_image_address(chip_address, chip_palette_address) -- TODO: generate bitmap and store it in the cache. bmp_exporter.export_argb_table_to_bitmap(file_name, argb_array, 64, 56) end end end function CHIP_PICTURE_DEFS.get_argb_2d_array_for_image_address(image_address, palette_address) local argb_array = {} for i = 1, CHIP_PICTURE_DEFS.WIDTH do argb_array[i] = {} for j = 1, CHIP_PICTURE_DEFS.HEIGHT do argb_array[i][j] = 0 end end -- tile 1: local working_address = image_address local working_address = working_address - 0x08000000 local current_x_offset = 0 local current_y_offset = 1 local byte_counter_per_line = 0 local x_index = 1 local y_index = 1 local palette_table = get_palette_argb(palette_address) for tile_y = 0, CHIP_PICTURE_DEFS.TILES_PER_DIMENSION - 1 do local tile_y_offset = tile_y * CHIP_PICTURE_DEFS.PIXELS_PER_TILE_LINE for tile_x = 0, CHIP_PICTURE_DEFS.TILES_PER_DIMENSION - 1 do local tile_x_offset = (tile_x * CHIP_PICTURE_DEFS.PIXELS_PER_TILE_LINE) current_y_offset = 1 for byte_index = 1, CHIP_PICTURE_DEFS.BYTES_PER_TILE do local read_byte = memory.readbyte(working_address, "ROM") working_address = working_address + 1 -- Dissect the byte into high/low. Low byte is always the first one, high byte the second one. local color_palette_byte_1 = bit.band(read_byte, 0x0F) local color_palette_byte_2 = bit.rshift(bit.band(read_byte, 0xF0), 4) current_x_offset = current_x_offset + 1 x_index = tile_x_offset + current_x_offset y_index = tile_y_offset + current_y_offset argb_array[x_index][y_index] = palette_table[color_palette_byte_1] current_x_offset = current_x_offset + 1 x_index = tile_x_offset + current_x_offset y_index = tile_y_offset + current_y_offset argb_array[x_index][y_index] = palette_table[color_palette_byte_2] if current_x_offset >= CHIP_PICTURE_DEFS.PIXELS_PER_TILE_LINE then current_x_offset = 0 current_y_offset = current_y_offset + 1 end end end end return argb_array end return CHIP_PICTURE_DEFS
local Settings = { --Should the scoreboard draw wanted level? ["WantedStars"] = false, --Should the scoreboard draw player ID? ["PlayerID"] = true, --Should the scoreboard draw voice indicator? ["VoiceIndicator"] = true, --Display time in milliseconds ["DisplayTime"] = 5000, --Keys that will activate the scoreboard. --Change only the number value, NOT the 'true' --Multiple keys can be used, simply add another row with another number --See: https://wiki.gtanet.work/index.php?title=Game_Controls --MultiplayerInfo / Z [20] = true, --Detonate / G --[47] = true, } -- END OF SETTINGS -- local function DrawPlayerList() local players = {} for i = 0, 31 do if NetworkIsPlayerActive( i ) then table.insert( players, i ) end end --Top bar DrawRect( 0.11, 0.025, 0.2, 0.03, 0, 0, 0, 220 ) --Top bar title SetTextFont( 4 ) SetTextProportional( 0 ) SetTextScale( 0.45, 0.45 ) SetTextColour( 255, 255, 255, 255 ) SetTextDropShadow( 0, 0, 0, 0, 255 ) SetTextEdge( 1, 0, 0, 0, 255 ) SetTextEntry( "STRING" ) AddTextComponentString( "Players: " .. #players ) DrawText( 0.015, 0.007 ) for k, v in pairs( players ) do local r local g local b if k % 2 == 0 then r = 28 g = 47 b = 68 else r = 38 g = 57 b = 74 end --Row BG DrawRect( 0.11, 0.025 + ( k * 0.03 ), 0.2, 0.03, r, g, b, 220 ) --Name Label SetTextFont( 4 ) SetTextScale( 0.45, 0.45 ) SetTextColour( 255, 255, 255, 255 ) SetTextEntry( "STRING" ) if Settings["PlayerID"] then local pid = GetPlayerServerId(v) AddTextComponentString(pid .. " ".. GetPlayerName(v)) else AddTextComponentString(GetPlayerName(v)) end DrawText( 0.015, 0.007 + ( k * 0.03 ) ) --Voice Indicator if Settings["VoiceIndicator"] then local transparency = 60 if NetworkIsPlayerTalking( v ) then transparency = 255 end DrawSprite( "mplobby", "mp_charcard_stats_icons9", 0.2, 0.024 + ( k * 0.03 ), 0.015, 0.025, 0, 255, 255, 255, transparency ) end --Wanted Stars if Settings["WantedStars"] then local wantedLevel = GetPlayerWantedLevel( v ) or 0 wantedLevel = wantedLevel for i=1, 5 do local transparency = 60 if wantedLevel >= i then transparency = 255 end DrawSprite( "mpleaderboard", "leaderboard_star_icon", 0.195 - ( i * 0.010 ), 0.024 + ( k * 0.03 ), 0.0175, 0.0275, 0, 255, 255, 255, transparency ) end end end end local LastPress = 0 Citizen.CreateThread( function() RequestStreamedTextureDict( "mplobby" ) RequestStreamedTextureDict( "mpleaderboard" ) while true do Wait( 0 ) for k, v in pairs( Settings ) do if type( k ) == "number" and v == true then if IsControlPressed( 0, k ) then LastPress = GetGameTimer() end end end if GetGameTimer() < LastPress + Settings["DisplayTime"] then DrawPlayerList() end end end )
turtles = {} local modpath = minetest.get_modpath("turtle") -- Database handler (for turtles and floppies) dofile(modpath .. "/db.lua") -- Initial computer state: bootloader dofile(modpath .. "/computer_memory.lua") -- Data for the forth floppy, created from forth.fth file by f.py dofile(modpath .. "/forth_floppy.lua") -- Computer simulation code dofile(modpath .. "/cptr.lua") -- Screen handler for formspec dofile(modpath .. "/screen.lua") -- Floppy, floppy programmator, and disk dofile(modpath .. "/floppy.lua") -- Turtle code dofile(modpath .. "/t2.lua")
local row_mgmt = system_load("wm.lua")() -- 'mini-WM' system_load("cells/shared/base.lua")() -- basic interface for a cell return function(anchor, conf) local ctx = row_mgmt(anchor, conf) ctx:add_cell_type("cli", system_load("cells/cli.lua")()) ctx:add_cell_type("terminal", system_load("cells/term.lua")()) ctx:add_cell_type("image", system_load("cells/image.lua")()) ctx:add_cell_type("expression", system_load("cells/expression.lua")()) ctx:add_cell_type("capture", system_load("cells/capture.lua")()) ctx:add_cell_type("compose", system_load("cells/compose.lua")()) ctx:add_cell_type("listen", system_load("cells/listen.lua")()) ctx:add_cell_type("debug", system_load("cells/debug.lua")()) ctx:add_cell_type("target", system_load("cells/target.lua")()) ctx:add_cell_type("adopt", system_load("cells/adopt.lua")()) return ctx end
------------------------------------------------- -- Controller hints/input handler for ConsolePort ------------------------------------------------- -- This file manages support for controller input -- using ConsolePort, providing input handler and -- displaying on-screen hints. ------------------------------------------------- -- Initialization ------------------------------------------------- local NPC, API, _, L = ImmersionFrame, ImmersionAPI, ... local HANDLE, KEY do -- list of functions existing on the HANDLE local HANDLE_functions = { 'AddHint'; 'RemoveHint'; 'IsHintFocus'; 'SetHintDisabled'; 'GetHintForKey'; 'ClearHintsForFrame'; } -- list of local functions that need to exist local NPC_functions = { 'ToggleHintState'; 'SetImmersionFocus'; 'ClearImmersionFocus'; 'ParseControllerCommand'; } -- For programming convenience, set all these functions to no-op -- if ConsolePort isn't loaded, since they won't be doing anything useful. if (not ConsolePortUIHandle) then local function noop() end for _, funcID in ipairs(HANDLE_functions) do NPC[funcID] = noop end for _, funcID in ipairs(NPC_functions) do NPC[funcID] = noop end return else HANDLE, KEY = ConsolePortUIHandle, ConsolePort:GetData().KEY -- If any of the HANDLE functions are missing, bail out. for _, funcID in ipairs(HANDLE_functions) do if not HANDLE[funcID] then return end end end end ------------------------------------------------- local Inspector = NPC.Inspector local Titles = NPC.TitleButtons local controllerInterrupt ------------------------------------------------- ------------------------------------------------- -- Hint management ------------------------------------------------- function NPC:AddHint(buttonID, text) if controllerInterrupt then return HANDLE:AddHint(KEY[buttonID], text) end end function NPC:RemoveHint(buttonID) if controllerInterrupt then return HANDLE:RemoveHint(KEY[buttonID]) end end function NPC:SetHintEnabled(buttonID) if controllerInterrupt then return HANDLE:SetHintEnabled(KEY[buttonID]) end end function NPC:SetHintDisabled(buttonID) if controllerInterrupt then return HANDLE:SetHintDisabled(KEY[buttonID]) end end function NPC:ToggleHintState(buttonID, enabled) if controllerInterrupt then if enabled then return self:SetHintEnabled(buttonID) else return self:SetHintDisabled(buttonID) end end end function NPC:GetHintForKey(buttonID) return HANDLE:GetHintForKey(KEY[buttonID]) end ------------------------------------------------- -- Handle hintbar focus set/release ------------------------------------------------- function NPC:SetImmersionFocus() controllerInterrupt = true if not L('hideui') then HANDLE:ShowUI() HANDLE:HideUI(ImmersionFrame, true) end return HANDLE:SetHintFocus(ImmersionFrame) end function NPC:ClearImmersionFocus() controllerInterrupt = false if HANDLE:IsHintFocus(ImmersionFrame) then HANDLE:HideHintBar() if not L('hideui') then HANDLE:ShowUI() end end return HANDLE:ClearHintsForFrame(ImmersionFrame) end --------------------------------------------------------- local ControllerInput = { -- return true when propagating --------------------------------------------------------- [KEY.UP] = function(self) if self.TitleButtons:IsVisible() then self.TitleButtons:SetPrevious() else return true end end; [KEY.DOWN] = function(self) if self.TitleButtons:IsVisible() then self.TitleButtons:SetNext() else return true end end; [KEY.LEFT] = function(self) if self.isInspecting then self.Inspector:SetPrevious() else return true end end; [KEY.RIGHT] = function(self) if self.isInspecting then self.Inspector:SetNext() else return true end end; [KEY.SQUARE] = function(self) if self.isInspecting then local focus = self.Inspector:GetFocus() if focus and focus.ModifiedClick then focus:ModifiedClick() end else local text = self.TalkBox.TextFrame.Text if text:IsSequence() then if text:GetNumRemaining() <= 1 then text:RepeatTexts() else text:ForceNext() end end end end; [KEY.CIRCLE] = function(self) if self.isInspecting then self.Inspector:Hide() elseif self.hasItems then self:ShowItems() end end; [KEY.CROSS] = function(self) -- Gossip/multiple quest choices if self.TitleButtons:GetMaxIndex() > 0 then self.TitleButtons:ClickFocused() -- Item inspection elseif self.isInspecting then self.Inspector:ClickFocused() self.Inspector:Hide() -- Complete quest elseif self.lastEvent == 'QUEST_COMPLETE' then -- if multiple items to choose between and none chosen if self.TalkBox.Elements.itemChoice == 0 and GetNumQuestChoices() > 1 then self:ShowItems() else self.TalkBox.Elements:CompleteQuest() end -- Accept quest elseif ( self.lastEvent == 'QUEST_DETAIL' or self.lastEvent == 'QUEST_ACCEPTED' ) then self.TalkBox.Elements:AcceptQuest() -- Progress quest (why are these functions named like this?) elseif IsQuestCompletable() then CompleteQuest() end end; [KEY.TRIANGLE] = function(self) API:CloseGossip() API:CloseQuest() end; [KEY.OPTIONS] = function(self) API:CloseGossip() API:CloseQuest() end; [KEY.CENTER] = function(self) API:CloseGossip() API:CloseQuest() end; [KEY.SHARE] = function(self) API:CloseGossip() API:CloseQuest() end; ------------------------------------------------- } ----------------------------------------------- ------------------------------------------------- -- HACK: count popups for gossip edge case. local popupCounter = 0 do local function PopupFixOnShow() popupCounter = popupCounter + 1 end local function PopupFixOnHide() popupCounter = popupCounter - 1 end for i=1, 4 do _G['StaticPopup'..i]:HookScript('OnShow', PopupFixOnShow) _G['StaticPopup'..i]:HookScript('OnHide', PopupFixOnHide) end end local function GetUIControlKey(button) if ConsolePort.GetUIControlKey then return ConsolePort:GetUIControlKey(GetBindingAction(button)) elseif ConsolePortUIHandle.GetUIControlBinding then return ConsolePortUIHandle:GetUIControlBinding(button) end end function NPC:ParseControllerCommand(button) if controllerInterrupt then -- Handle edge case when CP cursor should precede Immersion input. if not ConsolePort:GetData()('disableUI') then if ( popupCounter > 0 ) or ( AzeriteEmpoweredItemUI and AzeriteEmpoweredItemUI:IsVisible() ) then return false end end -- Handle case when the inspect binding or M1 is pressed, -- in which case it should show the item inspector. if self:IsInspectModifier(button) or button:match('SHIFT') then self.Inspector:ShowFocusedTooltip(true) return true end -- Handle every other case of possible controller inputs. local keyID = GetUIControlKey(button) local func = keyID and ControllerInput[keyID] if func then return not func(self) end end end ---------------------------------- -- Button selector ---------------------------------- local Selector = {} function Selector:SetFocus(index) if index then --self:IsVisible() and index then local focus = self:GetFocus() if focus then focus:UnlockHighlight() focus:OnLeave() end local max = self:GetMaxIndex() self.index = ( index > max and max ) or ( index < 1 and 1 ) or index self:SetFocusHighlight() if max > 0 and self.HintText then NPC:AddHint('CROSS', self.HintText) else NPC:RemoveHint('CROSS') end end end function Selector:SetNext() local nextButton = self:GetNextButton(self.index, 1) self:SetFocus(nextButton and (nextButton.idx or nextButton:GetID())) end function Selector:SetPrevious() local prevButton = self:GetNextButton(self.index, -1) self:SetFocus(prevButton and (prevButton.idx or prevButton:GetID())) end function Selector:ClickFocused() local focus = self:GetFocus() if focus then focus:Click() end end function Selector:SetFocusHighlight() local focus = self:GetFocus() if focus then focus:LockHighlight() focus:OnEnter() end end function Selector:GetFocus() return self.Active[self.index] end function Selector:GetActive() return pairs(self.Active) end function Selector:GetNextButton(index, delta) if index then local modifier = delta while true do local key = index + delta if key < 1 or key > self:GetMaxIndex() then return self.Active[self.index] end if self.Active[key] then return self.Active[key] else delta = delta + modifier end end end end function Selector:GetMaxIndex() local maxIndex = 0 if self:IsShown() then for i, button in pairs(self.Active) do maxIndex = i > maxIndex and i or maxIndex end end return maxIndex end function Selector:OnHide() end L.Mixin(Inspector, Selector) L.Mixin(Titles, Selector) ---------------------------------- -- Extended script handlers ---------------------------------- -- Inspector Inspector.Buttons = {} Inspector.ignoreModifier = true Inspector:HookScript('OnShow', function(self) local parent = self.parent self.CROSS = select(2, parent:GetHintForKey('CROSS')) self.CIRCLE = select(2, parent:GetHintForKey('CIRCLE')) self.SQUARE = select(2, parent:GetHintForKey('SQUARE')) parent.isInspecting = true parent:RemoveHint('SQUARE') parent:AddHint('CIRCLE', CLOSE) if ( parent.lastEvent == 'QUEST_PROGRESS' ) then parent:RemoveHint('CROSS') else parent:AddHint('CROSS', CHOOSE) HANDLE:AddHint('M1', CURRENTLY_EQUIPPED) end end) Inspector:HookScript('OnHide', function(self) local parent = self.parent parent.isInspecting = false HANDLE:RemoveHint('M1') if self.CROSS then parent:AddHint('CROSS', self.CROSS) end if self.SQUARE then parent:AddHint('SQUARE', self.SQUARE) end if self.CIRCLE then parent:AddHint('CIRCLE', self.CIRCLE) end self.CROSS = nil self.SQUARE = nil self.CIRCLE = nil end) function Inspector:ShowFocusedTooltip(showTooltip) local button = self:GetFocus() if button then if showTooltip then button:SetFocus() else button:ClearFocus() end end end -- Handle custom modified clicks on item popups: -- Return itemLink and display text for SQUARE (modified clicks) local function GetModifiedClickInfo(item) local link = item and GetQuestItemLink(item.type, item:GetID()) if link and ImmersionAPI:IsAzeriteItem(link) then ---------------------------------------- return link, LFG_LIST_DETAILS end end function L.TooltipMixin:ModifiedClick(...) local azeriteItemLink = GetModifiedClickInfo(self.item) if azeriteItemLink then ---------------------------------------- OpenAzeriteEmpoweredItemUIFromLink(azeriteItemLink) self.inspector:Hide() end end hooksecurefunc(L.TooltipMixin, 'OnEnter', function(self) local _, hintText = GetModifiedClickInfo(self.item) if hintText then Inspector.parent:AddHint('SQUARE', hintText) end end) hooksecurefunc(L.TooltipMixin, 'OnLeave', function(self) Inspector.parent:RemoveHint('SQUARE') end) -- Titles Titles.HintText = ACCEPT
-- -- hammerspoon.lua -- hammerspoon basic keybindings -- local helpers = require("helpers") local hyper = require("modules.hyper") -- ============================================================================= -- Definitions -- ============================================================================= -- reload configs hyper:bind({ "shift" }, "r", function () hs.reload() end) -- toggle console hyper:bind({ "shift" }, "t", function () hs.console.clearConsole() hs.toggleConsole() -- focus next available window helpers.get_active_window(function (win) win:focus() end) end)
-- Helper module for 200_to_210 migration operations. -- -- Operations are versioned and specific to a migration so they remain -- fixed in time and are not modified for use in future migrations. -- -- If you want to reuse these operations in a future migration, -- copy the functions over to a new versioned module. local operations_200_210 = require "kong.db.migrations.operations.200_to_210" -------------------------------------------------------------------------------- -- Postgres operations for Workspace migration -------------------------------------------------------------------------------- local postgres = { up = [[ ]], teardown = { -- These migrations were fixed since they were originally released, -- thus those that have updated already, need to re-run it. ws_update_composite_cache_key = operations_200_210.postgres.teardown.ws_update_composite_cache_key, }, } -------------------------------------------------------------------------------- -- Cassandra operations for Workspace migration -------------------------------------------------------------------------------- local cassandra = { up = [[ ]], teardown = { -- These migrations were fixed since they were originally released, -- thus those that have updated already, need to re-run it. ws_update_composite_cache_key = operations_200_210.cassandra.teardown.ws_update_composite_cache_key, } } -------------------------------------------------------------------------------- -- Higher-level operations for Workspace migration -------------------------------------------------------------------------------- local function ws_adjust_data(ops, connector, entities) for _, entity in ipairs(entities) do if entity.cache_key and #entity.cache_key > 1 then local _, err = ops:ws_update_composite_cache_key(connector, entity.name, entity.partitioned) if err then return nil, err end end end return true end postgres.teardown.ws_adjust_data = ws_adjust_data cassandra.teardown.ws_adjust_data = ws_adjust_data -------------------------------------------------------------------------------- return { postgres = postgres, cassandra = cassandra, }
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('esx_roubarnpc:giveMoney', function(source, callback) local xPlayer = ESX.GetPlayerFromId(source) local money = math.random(Config.MinMoney, Config.MaxMoney) xPlayer.addMoney(money) callback(money) end)
local require = using("BodyEditor.Script") local CCScene = require("CCScene") local oVec2 = require("oVec2") local oContent = require("oContent") local CCScheduler = require("CCScheduler") local oWorld = require("oWorld") local CCDirector = require("CCDirector") local CCNode = require("CCNode") local CCMenu = require("CCMenu") local CCSize = require("CCSize") local oBodyDef = require("oBodyDef") local oBody = require("oBody") local oJoint = require("oJoint") local emit = require("emit") local CCSprite = require("CCSprite") local oModel = require("oModel") local tolua = require("tolua") local oCache = require("oCache") local once = require("once") local oRoutine = require("oRoutine") local oEditor = CCScene() oEditor.standAlone = true oEditor.quitable = false oEditor.isLoaded = false oEditor.isPlaying = false oEditor.origin = oVec2(60+(-120-180)*0.5,0) oEditor.currentData = nil oEditor.isFixed = true oEditor.scale = 1 oEditor.names = {} oEditor.bodyData = {} oEditor.items = {} oEditor.input = oContent.writablePath.."Body/Input/" oEditor.output = oContent.writablePath.."Body/Output/" oEditor.prefix = "" oEditor.topMost = 9999 oEditor.currentFile = nil oEditor.fixX = false oEditor.fixY = false oEditor.round = function(self,val) if type(val) == "number" then return val > 0 and math.floor(val+0.5) or math.ceil(val-0.5) else return oVec2(val.x > 0 and math.floor(val.x+0.5) or math.ceil(val.x-0.5), val.y > 0 and math.floor(val.y+0.5) or math.ceil(val.y-0.5)) end end local worldScheduler = CCScheduler() worldScheduler.timeScale = 0 oEditor.worldScheduler = worldScheduler oEditor.world = oWorld() oEditor.world.scheduler = oEditor.worldScheduler oEditor.world.showDebug = true oEditor.world:setShouldContact(0,0,true) oEditor:slot("Cleanup",function() if not oEditor.world.parent then oEditor.world:cleanup() end CCDirector.scheduler:unschedule(oEditor.worldScheduler) oEditor:clearData() end) local worldNode = CCNode() oEditor.world:addChild(worldNode) oEditor.worldNode = worldNode oEditor.touchPriorityEditMenu = CCMenu.DefaultHandlerPriority oEditor.touchPrioritySettingPanel = CCMenu.DefaultHandlerPriority+1 oEditor.touchPriorityViewPanel = CCMenu.DefaultHandlerPriority+3 oEditor.touchPriorityVRuler = CCMenu.DefaultHandlerPriority+5 oEditor.touchPriorityHRuler = CCMenu.DefaultHandlerPriority+6 oEditor.touchPriorityEditControl = CCMenu.DefaultHandlerPriority+8 oEditor.touchPriorityViewArea = CCMenu.DefaultHandlerPriority+10 local function Point(x,y) return function() return oVec2(x,y) end end local PointZero = Point(0,0) local function Size(width,height) return function() return CCSize(width,height) end end local function rename(self,oldName,newName) local change = false if self:get("BodyA") == oldName then self:set("BodyA",newName) change = true elseif self:get("BodyB") == oldName then self:set("BodyB",newName) change = true end if change then oEditor:resetItem(self) end end local resetEnable = false local function reset(self,args) if resetEnable and args.type == "Body" and (self:get("BodyA") == args.name or self:get("BodyB") == args.name) then oEditor:resetItem(self) end end local types = { Rectangle = 1, Circle = 2, Polygon = 3, Chain = 4, Loop = 5, SubRectangle = 6, SubCircle = 7, SubPolygon = 8, SubChain = 9, SubLoop = 10, Distance = 11, Friction = 12, Gear = 13, Spring = 14, Prismatic = 15, Pulley = 16, Revolute = 17, Rope = 18, Weld = 19, Wheel = 20, } local typeNames = {} for k,v in pairs(types) do typeNames[v] = k end local defaultShapeData = { Rectangle = { {"ItemType","Rectangle"}, -- 1 {"Name","rect"}, -- 2 {"Type",oBodyDef.Dynamic}, -- 3 {"Position",PointZero}, -- 4 {"Angle",0}, -- 5 {"Center",PointZero}, -- 6 {"Size",Size(100,100)}, -- 7 {"Density",1}, -- 8 {"Friction",0.4}, -- 9 {"Restitution",0.4}, -- 10 {"LinearDamping", 0}, -- 11 {"AngularDamping",0}, -- 12 {"FixedRotation",false}, -- 13 {"GravityScale",1}, -- 14 {"Bullet",false}, -- 15 {"Sensor",false}, -- 16 {"SensorTag",0}, -- 17 {"SubShapes",false}, -- 18 {"Face",""}, -- 19 {"FacePos",PointZero}, -- 20 create = function(self) local Rectangle = oEditor.Rectangle if self[Rectangle.Size].width <= 0 or self[Rectangle.Size].height <= 0 then return nil end local bodyDef = oBodyDef() if self[Rectangle.Sensor] then bodyDef:attachPolygonSensor( self[Rectangle.SensorTag], self[Rectangle.Size].width, self[Rectangle.Size].height, self[Rectangle.Center], 0) else bodyDef:attachPolygon( self[Rectangle.Center], self[Rectangle.Size].width, self[Rectangle.Size].height, 0, self[Rectangle.Density], self[Rectangle.Friction], self[Rectangle.Restitution]) end bodyDef.type = self[Rectangle.Type] bodyDef.isBullet = self[Rectangle.Bullet] bodyDef.gravityScale = self[Rectangle.GravityScale] bodyDef.fixedRotation = self[Rectangle.FixedRotation] bodyDef.linearDamping = self[Rectangle.LinearDamping] bodyDef.angularDamping = self[Rectangle.AngularDamping] local body = oBody(bodyDef,oEditor.world, self[Rectangle.Position], self[Rectangle.Angle]) if self[Rectangle.SubShapes] then for _,subShape in ipairs(self[Rectangle.SubShapes]) do subShape:create(body) end end body.scheduler = oEditor.worldScheduler oEditor.world:addChild(body) return body end, }, Circle = { {"ItemType","Circle"}, -- 1 {"Name","circle"}, -- 2 {"Type",oBodyDef.Dynamic}, -- 3 {"Position",PointZero}, -- 4 {"Angle",0}, -- 5 {"Center",PointZero}, -- 6 {"Radius",50}, -- 7 {"Density",1}, -- 8 {"Friction",0.4}, -- 9 {"Restitution",0.4}, -- 10 {"LinearDamping",0}, -- 11 {"AngularDamping",0}, -- 12 {"FixedRotation",false}, -- 13 {"GravityScale",1}, -- 14 {"Bullet",false}, -- 15 {"Sensor",false}, -- 16 {"SensorTag",0}, -- 17 {"SubShapes",false}, -- 18 {"Face",""}, -- 19 {"FacePos",PointZero}, -- 20 create = function(self) local Circle = oEditor.Circle if self[Circle.Radius] <= 0 then return nil end local bodyDef = oBodyDef() if self[Circle.Sensor] then bodyDef:attachCircleSensor( self[Circle.SensorTag], self[Circle.Center], self[Circle.Radius]) else bodyDef:attachCircle( self[Circle.Center], self[Circle.Radius], self[Circle.Density], self[Circle.Friction], self[Circle.Restitution]) end bodyDef.type = self[Circle.Type] bodyDef.isBullet = self[Circle.Bullet] bodyDef.gravityScale = self[Circle.GravityScale] bodyDef.fixedRotation = self[Circle.FixedRotation] bodyDef.linearDamping = self[Circle.LinearDamping] bodyDef.angularDamping = self[Circle.AngularDamping] local body = oBody(bodyDef,oEditor.world, self[Circle.Position], self[Circle.Angle]) if self[Circle.SubShapes] then for _,subShape in ipairs(self[Circle.SubShapes]) do subShape:create(body) end end body.scheduler = oEditor.worldScheduler oEditor.world:addChild(body) return body end, }, Polygon = { {"ItemType","Polygon"}, -- 1 {"Name","poly"}, -- 2 {"Type",oBodyDef.Dynamic}, -- 3 {"Position",PointZero}, -- 4 {"Angle",0}, -- 5 {"Vertices",false}, -- 6 {"Density",1}, -- 7 {"Friction",0.4}, -- 8 {"Restitution",0.4}, -- 9 {"LinearDamping",0}, -- 10 {"AngularDamping",0}, -- 11 {"FixedRotation",false}, -- 12 {"GravityScale",1}, -- 13 {"Bullet",false}, -- 14 {"Sensor",false}, -- 15 {"SensorTag",0}, -- 16 {"SubShapes",false}, -- 17 {"Face",""}, -- 18 {"FacePos",PointZero}, -- 19 create = function(self) local Polygon = oEditor.Polygon if not self[Polygon.Vertices] or #self[Polygon.Vertices] < 3 then return nil end local bodyDef = oBodyDef() if self[Polygon.Sensor] then bodyDef:attachPolygonSensor( self[Polygon.SensorTag], self[Polygon.Vertices]) else bodyDef:attachPolygon( self[Polygon.Vertices], self[Polygon.Density], self[Polygon.Friction], self[Polygon.Restitution]) end bodyDef.type = self[Polygon.Type] bodyDef.isBullet = self[Polygon.Bullet] bodyDef.gravityScale = self[Polygon.GravityScale] bodyDef.fixedRotation = self[Polygon.FixedRotation] bodyDef.linearDamping = self[Polygon.LinearDamping] bodyDef.angularDamping = self[Polygon.AngularDamping] local body = oBody(bodyDef,oEditor.world, self[Polygon.Position], self[Polygon.Angle]) if self[Polygon.SubShapes] then for _,subShape in ipairs(self[Polygon.SubShapes]) do subShape:create(body) end end body.scheduler = oEditor.worldScheduler oEditor.world:addChild(body) return body end, }, Chain = { {"ItemType","Chain"}, -- 1 {"Name","chain"}, -- 2 {"Type",oBodyDef.Dynamic}, -- 3 {"Position",PointZero}, -- 4 {"Angle",0}, -- 5 {"Vertices",false}, -- 6 {"Friction",0.4}, -- 7 {"Restitution",0.4}, -- 8 {"LinearDamping",0}, -- 9 {"AngularDamping",0}, -- 10 {"FixedRotation",false}, -- 11 {"GravityScale",1}, -- 12 {"Bullet",false}, -- 13 {"SubShapes",false}, -- 14 {"Face",""}, -- 15 {"FacePos",PointZero}, -- 16 create = function(self) local Chain = oEditor.Chain if not self[Chain.Vertices] or #self[Chain.Vertices] < 2 then return nil end local bodyDef = oBodyDef() bodyDef:attachChain( self[Chain.Vertices], self[Chain.Friction], self[Chain.Restitution]) bodyDef.type = self[Chain.Type] bodyDef.isBullet = self[Chain.Bullet] bodyDef.gravityScale = self[Chain.GravityScale] bodyDef.fixedRotation = self[Chain.FixedRotation] bodyDef.linearDamping = self[Chain.LinearDamping] bodyDef.angularDamping = self[Chain.AngularDamping] local body = oBody(bodyDef,oEditor.world, self[Chain.Position], self[Chain.Angle]) if self[Chain.SubShapes] then for _,subShape in ipairs(self[Chain.SubShapes]) do subShape:create(body) end end body.scheduler = oEditor.worldScheduler oEditor.world:addChild(body) return body end, }, Loop = { {"ItemType","Loop"}, -- 1 {"Name","loop"}, -- 2 {"Type",oBodyDef.Dynamic}, -- 3 {"Position",PointZero}, -- 4 {"Angle",0}, -- 5 {"Vertices",false}, -- 6 {"Friction",0.4}, -- 7 {"Restitution",0.4}, -- 8 {"LinearDamping",0}, -- 9 {"AngularDamping",0}, -- 10 {"FixedRotation",false}, -- 11 {"GravityScale",1}, -- 12 {"Bullet",false}, -- 13 {"SubShapes",false}, -- 14 {"Face",""}, -- 15 {"FacePos",PointZero}, -- 16 create = function(self) local Loop = oEditor.Loop if not self[Loop.Vertices] or #self[Loop.Vertices] < 3 then return nil end local bodyDef = oBodyDef() bodyDef:attachLoop( self[Loop.Vertices], self[Loop.Friction], self[Loop.Restitution]) bodyDef.type = self[Loop.Type] bodyDef.isBullet = self[Loop.Bullet] bodyDef.gravityScale = self[Loop.GravityScale] bodyDef.fixedRotation = self[Loop.FixedRotation] bodyDef.linearDamping = self[Loop.LinearDamping] bodyDef.angularDamping = self[Loop.AngularDamping] local body = oBody(bodyDef,oEditor.world, self[Loop.Position], self[Loop.Angle]) if self[Loop.SubShapes] then for _,subShape in ipairs(self[Loop.SubShapes]) do subShape:create(body) end end body.scheduler = oEditor.worldScheduler oEditor.world:addChild(body) return body end, }, SubRectangle = { {"ItemType","SubRectangle"}, -- 1 {"Center",PointZero}, -- 2 {"Angle",0}, -- 3 {"Size",Size(100,100)}, -- 4 {"Density",1}, -- 5 {"Friction",0.4}, -- 6 {"Restitution",0.4}, -- 7 {"Sensor",false}, -- 8 {"SensorTag",0}, -- 9 create = function(self,body) local SubRectangle = oEditor.SubRectangle if self[SubRectangle.Size].width <= 0 or self[SubRectangle.Size].height <= 0 then return end if self[SubRectangle.Sensor] then body:attachSensor( self[SubRectangle.SensorTag], oBodyDef:polygon( self[SubRectangle.Center], self[SubRectangle.Size].width, self[SubRectangle.Size].height, self[SubRectangle.Angle])) else body:attach( oBodyDef:polygon( self[SubRectangle.Center], self[SubRectangle.Size].width, self[SubRectangle.Size].height, self[SubRectangle.Angle], self[SubRectangle.Density], self[SubRectangle.Friction], self[SubRectangle.Restitution])) end end, }, SubCircle = { {"ItemType","SubCircle"}, -- 1 {"Center",PointZero}, -- 2 {"Radius",50}, -- 3 {"Density",1}, -- 4 {"Friction",0.4}, -- 5 {"Restitution",0.4}, -- 6 {"Sensor",false}, -- 7 {"SensorTag",0}, -- 8 create = function(self,body) local SubCircle = oEditor.SubCircle if self[SubCircle.Radius] <= 0 then return end if self[SubCircle.Sensor] then body:attachSensor( self[SubCircle.SensorTag], oBodyDef:circle( self[SubCircle.Center], self[SubCircle.Radius])) else body:attach( oBodyDef:circle( self[SubCircle.Center], self[SubCircle.Radius], self[SubCircle.Density], self[SubCircle.Friction], self[SubCircle.Restitution])) end end, }, SubPolygon = { {"ItemType","SubPolygon"}, -- 1 {"Vertices",false}, -- 2 {"Density",1}, -- 3 {"Friction",0.4}, -- 4 {"Restitution",0.4}, -- 5 {"Sensor",false}, -- 6 {"SensorTag",0}, -- 7 create = function(self,body) local SubPolygon = oEditor.SubPolygon if not self[SubPolygon.Vertices] or #self[SubPolygon.Vertices] < 3 then return end if self[SubPolygon.Sensor] then body:attachSensor( self[SubPolygon.SensorTag], oBodyDef:polygon( self[SubPolygon.Vertices])) else body:attach( oBodyDef:polygon( self[SubPolygon.Vertices], self[SubPolygon.Density], self[SubPolygon.Friction], self[SubPolygon.Restitution])) end end, }, SubChain = { {"ItemType","SubChain"}, -- 1 {"Vertices",false}, -- 2 {"Friction",0.4}, -- 3 {"Restitution",0.4}, -- 4 create = function(self,body) local SubChain = oEditor.SubChain if not self[SubChain.Vertices] or #self[SubChain.Vertices] < 2 then return end body:attach( oBodyDef:chain( self[SubChain.Vertices], self[SubChain.Friction], self[SubChain.Restitution])) end, }, SubLoop = { {"ItemType","SubLoop"}, -- 1 {"Vertices",false}, -- 2 {"Friction",0.4}, -- 3 {"Restitution",0.4}, -- 4 create = function(self,body) local SubLoop = oEditor.SubLoop if not self[SubLoop.Vertices] or #self[SubLoop.Vertices] < 3 then return end body:attach( oBodyDef:loop( self[SubLoop.Vertices], self[SubLoop.Friction], self[SubLoop.Restitution])) end, }, Distance = { {"ItemType","Distance"}, -- 1 {"Name","distance"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"AnchorA",PointZero}, -- 6 {"AnchorB",PointZero}, -- 7 {"Frequency",0}, -- 8 {"Damping",0}, -- 9 create = function(self) local Distance = oEditor.Distance local bodyA = oEditor:getItem(self[Distance.BodyA]) local bodyB = oEditor:getItem(self[Distance.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:distance( self[Distance.Collision], bodyA,bodyB, self[Distance.AnchorA], self[Distance.AnchorB], self[Distance.Frequency], self[Distance.Damping]) end, rename = rename, reset = reset, }, Friction = { {"ItemType","Friction"}, -- 1 {"Name","friction"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"WorldPos",PointZero}, -- 6 {"MaxForce",0}, -- 7 {"MaxTorque",0}, -- 8 create = function(self) local Friction = oEditor.Friction local bodyA = oEditor:getItem(self[Friction.BodyA]) local bodyB = oEditor:getItem(self[Friction.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:friction( self[Friction.Collision], bodyA,bodyB, self[Friction.WorldPos], self[Friction.MaxForce], self[Friction.MaxTorque]) end, rename = rename, reset = reset, }, Gear = { {"ItemType","Gear"}, -- 1 {"Name","gear"}, -- 2 {"Collision",false}, -- 3 {"JointA",""}, -- 4 {"JointB",""}, -- 5 {"Ratio",1}, -- 6 create = function(self) local Gear = oEditor.Gear local jointA = oEditor:getItem(self[Gear.JointA]) local jointB = oEditor:getItem(self[Gear.JointB]) if not jointA or not jointB or jointA == jointB then return nil end return oJoint:gear( self[Gear.Collision], jointA,jointB, self[Gear.Ratio]) end, rename = function(self,oldName,newName) local Gear = oEditor.Gear if self[Gear.JointA] == oldName then self[Gear.JointA] = newName end if self[Gear.JointB] == oldName then self[Gear.JointB] = newName end end, reset = function(self,args) if resetEnable and args.type == "Joint" and (self:get("JointA") == args.name or self:get("JointB") == args.name) then oEditor:resetItem(self) end end, }, Spring = { {"ItemType","Spring"}, -- 1 {"Name","spring"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"Offset",PointZero}, -- 6 {"AngularOffset",0}, -- 7 {"MaxForce",0}, -- 8 {"MaxTorque",0}, -- 9 {"CorrectionFactor",0.3}, -- 10 create = function(self) local Spring = oEditor.Spring local bodyA = oEditor:getItem(self[Spring.BodyA]) local bodyB = oEditor:getItem(self[Spring.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:spring( self[Spring.Collision], bodyA,bodyB, self[Spring.Offset], self[Spring.AngularOffset], self[Spring.MaxForce], self[Spring.MaxTorque], self[Spring.CorrectionFactor]) end, rename = rename, reset = reset, }, Prismatic = { {"ItemType","Prismatic"}, -- 1 {"Name","prism"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"WorldPos",PointZero}, -- 6 {"Axis",Point(1,0)}, -- 7 {"Lower",0}, -- 8 {"Upper",0}, -- 9 {"MaxMotorForce",0}, -- 10 {"MotorSpeed",0}, -- 11 create = function(self) local Prismatic = oEditor.Prismatic local bodyA = oEditor:getItem(self[Prismatic.BodyA]) local bodyB = oEditor:getItem(self[Prismatic.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:prismatic( self[Prismatic.Collision], bodyA,bodyB, self[Prismatic.WorldPos], self[Prismatic.Axis], self[Prismatic.Lower], self[Prismatic.Upper], self[Prismatic.MaxMotorForce], self[Prismatic.MotorSpeed]) end, rename = rename, reset = reset, }, Pulley = { {"ItemType","Pulley"}, -- 1 {"Name","pulley"}, -- 2 {"Collision",true}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"AnchorA",PointZero}, -- 6 {"AnchorB",PointZero}, -- 7 {"GroundA",Point(-100,100)}, -- 8 {"GroundB",Point(100,100)}, -- 9 {"Ratio",1}, -- 9 create = function(self) local Pulley = oEditor.Pulley local bodyA = oEditor:getItem(self[Pulley.BodyA]) local bodyB = oEditor:getItem(self[Pulley.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:pulley( self[Pulley.Collision], bodyA,bodyB, self[Pulley.AnchorA], self[Pulley.AnchorB], self[Pulley.GroundA], self[Pulley.GroundB], self[Pulley.Ratio]) end, rename = rename, reset = reset, }, Revolute = { {"ItemType","Revolute"}, -- 1 {"Name","revolute"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"WorldPos",PointZero}, -- 6 {"LowerAngle",0}, -- 7 {"UpperAngle",0}, -- 8 {"MaxMotorTorque",0}, -- 9 {"MotorSpeed",0}, -- 10 create = function(self) local Revolute = oEditor.Revolute local bodyA = oEditor:getItem(self[Revolute.BodyA]) local bodyB = oEditor:getItem(self[Revolute.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:revolute( self[Revolute.Collision], bodyA,bodyB, self[Revolute.WorldPos], self[Revolute.LowerAngle], self[Revolute.UpperAngle], self[Revolute.MaxMotorTorque], self[Revolute.MotorSpeed]) end, rename = rename, reset = reset, }, Rope = { {"ItemType","Rope"}, -- 1 {"Name","rope"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"AnchorA",PointZero}, -- 6 {"AnchorB",PointZero}, -- 7 {"MaxLength",100}, -- 8 create = function(self) local Rope = oEditor.Rope local bodyA = oEditor:getItem(self[Rope.BodyA]) local bodyB = oEditor:getItem(self[Rope.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:rope( self[Rope.Collision], bodyA,bodyB, self[Rope.AnchorA], self[Rope.AnchorB], self[Rope.MaxLength]) end, rename = rename, reset = reset, }, Weld = { {"ItemType","Weld"}, -- 1 {"Name","weld"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"WorldPos",PointZero}, -- 6 {"Frequency",0}, -- 7 {"Damping",0}, -- 8 create = function(self) local Weld = oEditor.Weld local bodyA = oEditor:getItem(self[Weld.BodyA]) local bodyB = oEditor:getItem(self[Weld.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:weld( self[Weld.Collision], bodyA,bodyB, self[Weld.WorldPos], self[Weld.Frequency], self[Weld.Damping]) end, rename = rename, reset = reset, }, Wheel = { {"ItemType","Wheel"}, -- 1 {"Name","wheel"}, -- 2 {"Collision",false}, -- 3 {"BodyA",""}, -- 4 {"BodyB",""}, -- 5 {"WorldPos",PointZero}, -- 6 {"Axis",Point(1,0)}, -- 7 {"MaxMotorTorque",0}, -- 8 {"MotorSpeed",0}, -- 9 {"Frequency",2}, -- 10 {"Damping",0.7}, -- 11 create = function(self) local Wheel = oEditor.Wheel local bodyA = oEditor:getItem(self[Wheel.BodyA]) local bodyB = oEditor:getItem(self[Wheel.BodyB]) if not bodyA or not bodyB or bodyA == bodyB then return nil end return oJoint:wheel( self[Wheel.Collision], bodyA,bodyB, self[Wheel.WorldPos], self[Wheel.Axis], self[Wheel.MaxMotorTorque], self[Wheel.MotorSpeed], self[Wheel.Frequency], self[Wheel.Damping]) end, rename = rename, reset = reset, }, } local function setFunc(data,name,value) data[oEditor[data[1]][name]] = value emit("Body.editor.change") end local function getFunc(data,name) return data[oEditor[data[1]][name]] end local function hasFunc(data,name) return oEditor[data[1]][name] ~= nil end for shapeName,shapeDefine in pairs(defaultShapeData) do oEditor[shapeName] = {} for index,property in ipairs(shapeDefine) do local createFunc = shapeDefine.create local renameFunc = shapeDefine.rename local resetFunc = shapeDefine.reset oEditor[shapeName][property[1]] = index oEditor[shapeName].create = createFunc oEditor[shapeName].rename = renameFunc oEditor[shapeName].reset = resetFunc oEditor["new"..shapeName] = function(self) local newData = {} for i,v in ipairs(shapeDefine) do newData[i] = type(v[2]) == "function" and v[2]() or v[2] end newData.create = createFunc newData.set = setFunc newData.get = getFunc newData.has = hasFunc if renameFunc then newData.renameListener = oEditor:gslot("Body.editor.rename",function(args) renameFunc(newData,args.oldName,args.newName) end) end if resetFunc then newData.resetListener = oEditor:gslot("Body.editor.reset",function(args) resetFunc(newData,args) end) end return newData end end end oEditor.addSubData = function(self,data,subData) local subShapes = data:get("SubShapes") if not subShapes then subShapes = {subData,} data:set("SubShapes",subShapes) else table.insert(subShapes,subData) end for _,shape in ipairs(subShapes) do shape.parent = data shape.set = setFunc shape.get = getFunc shape.has = hasFunc end oEditor:resetItem(data) emit("Body.editor.bodyData",self.bodyData) end oEditor.addData = function(self,data) local bodyData = self.bodyData if not data.resetListener then if #bodyData > 0 then local inserted = false for i = #bodyData,1,-1 do if not bodyData[i].resetListener then inserted = true table.insert(bodyData,i+1,data) break end end if not inserted then table.insert(bodyData,1,data) end else table.insert(bodyData,data) end else if #bodyData > 0 then local inserted = false for i = #bodyData,1,-1 do if bodyData[i]:get("ItemType") ~= "Gear" then inserted = true table.insert(bodyData,i+1,data) break end end if not inserted then table.insert(bodyData,1,data) end else table.insert(bodyData,data) end end oEditor:checkName(data) local subShapes = data:get("SubShapes") if subShapes then for _,shape in ipairs(subShapes) do shape.parent = data shape.set = setFunc shape.get = getFunc shape.has = hasFunc end end oEditor:resetItem(data) emit("Body.editor.bodyData",bodyData) end oEditor.getData = function(self,name) for _,data in ipairs(self.bodyData) do if data:get("Name") == name then return data end end return nil end oEditor.removeData = function(self,data) local item = data.parent or data for i,v in ipairs(self.bodyData) do if v == item then if data.parent then local subShapes = data.parent:get("SubShapes") for index,sb in ipairs(subShapes) do if sb == data then table.remove(subShapes,index) if #subShapes == 0 then data.parent:set("SubShapes",false) end break end end oEditor:resetItem(data.parent) else local name = data:get("Name") table.remove(self.bodyData,i) if data.renameListener then oEditor:gslot(data.renameListener,nil) end if data.resetListener then oEditor:gslot(data.resetListener,nil) end oEditor.names[name] = nil local item = oEditor.items[name] if item then item:destroy() oEditor.items[name] = nil end end emit("Body.editor.bodyData",self.bodyData) break end end end oEditor.clearData = function(self) for _,data in ipairs(oEditor.bodyData) do if data.renameListener then oEditor:gslot(data.renameListener,nil) end if data.resetListener then oEditor:gslot(data.resetListener,nil) end end self.bodyData = {} oEditor.names = {} oEditor:clearItems() emit("Body.editor.bodyData",self.bodyData) end oEditor.resetItem = function(self,data,resetFace) if data.parent then data = data.parent end local face = oEditor:removeItem(data) local item = data:create() if not resetFace and face then if item then item:addChild(face) else item = face item.position = data:get("Position") item.angle = data:get("Angle") oEditor.world:addChild(item) end else if data:has("Face") then local faceStr = data:get("Face") if faceStr ~= "" then faceStr = oEditor.input..faceStr if faceStr:match("|") then face = CCSprite(faceStr) elseif oContent:exist(faceStr) then local extension = string.match(faceStr,"%.([^%.\\/]*)$") if extension then extension = extension:lower() if extension == "png" then face = CCSprite(faceStr) elseif extension == "model" then face = oModel(faceStr) end end else face = nil end else face = nil end if face then face.position = data:get("FacePos") if item then item:addChild(face) else item = face item.position = data:get("Position") item.angle = data:get("Angle") oEditor.world:addChild(item) end end end end local name = data:get("Name") oEditor.items[name] = item if item then item.dataItem = data end emit("Body.editor.reset",{name=name,type=(data.resetListener and "Joint" or "Body")}) return item end oEditor.resetItems = function(self) self:clearItems() resetEnable = false for _,data in ipairs(self.bodyData) do self:resetItem(data) end resetEnable = true end oEditor.removeItem = function(self,data) if data.parent then data = data.parent end local name = data:get("Name") local item = oEditor.items[name] local face if item then if item.children then face = item.children[1] if face then item:removeChild(face) end end if item.destroy then item:destroy() else item.parent:removeChild(item) end end self.items[name] = nil return face end oEditor.rename = function(self,oldName,newName) if oldName == newName then return end local item = self.items[oldName] self.items[oldName] = nil self.items[newName] = item self.names[oldName] = nil self.names[newName] = true emit("Body.editor.rename",{oldName=oldName,newName=newName}) end oEditor.getItem = function(self,arg) -- arg: name or data if type(arg) == "string" then return self.items[arg] else if arg.parent then arg = arg.parent end return self.items[arg:get("Name")] end end oEditor.clearItems = function(self) for _,item in pairs(self.items) do item:destroy() end self.items = {} end oEditor.getUsableName = function(self,originalName) if originalName == "" then originalName = "name" end if self.names[originalName] then local counter = 1 local nawName = nil local usable = false repeat nawName = originalName..tostring(counter) usable = (self.names[nawName] == nil) counter = counter+1 until usable return nawName else return originalName end end oEditor.checkName = function(self,data) local oldName = data:get("Name") local newName = oEditor:getUsableName(oldName) oEditor.names[newName] = true if newName ~= oldName then data:set("Name",newName) end end local itemToString = nil local valueToString = nil valueToString = function(value) local str = "" local typeName = tolua.type(value) if typeName == "table" then str = str.."{" local len = #value for i,v in ipairs(value) do local typeName = tolua.type(v) if typeName == "oVec2" then str = str..string.format("v(%.2f,%.2f)",v.x,v.y) elseif typeName == "table" then str = str..itemToString(v) end if i ~= len then str = str.."," end end str = str.."}" elseif typeName == "oVec2" then str = str..string.format("v(%.2f,%.2f)",value.x,value.y) elseif typeName == "CCSize" then str = str..string.format("s(%d,%d)",value.width,value.height) elseif typeName == "string" then str = str.."\""..value.."\"" elseif typeName == "boolean" then str = str..(value and "t" or "f") else str = str..tostring(value) end return str end itemToString = function(item) local str = "" str = str.."{" local len = #item for i,v in ipairs(item) do str = str..valueToString(i == 1 and types[v] or v) if i ~= len then str = str.."," end end str = str.."}" return str end oEditor.dumpData = function(self,filename) local str = [[local v,s,t,f = require("oVec2"),require("CCSize"),true,false return {]] local len = #oEditor.bodyData for i,data in ipairs(oEditor.bodyData) do str = str..itemToString(data) if i ~= len then str = str.."," end end str = str.."}" str = str:gsub("%.00","") oContent:saveToFile(oEditor.output..filename,str) if oCache.Body then oCache.Body:unload(filename) end end oEditor.transformData = function(self,bodyData) for _,data in ipairs(bodyData) do data[1] = typeNames[data[1]] local shapeName = data[1] data.set = setFunc data.get = getFunc data.has = hasFunc local subShapes = data[oEditor[shapeName].SubShapes] if subShapes then for _,subShape in ipairs(subShapes) do subShape[1] = typeNames[subShape[1]] subShape.parent = data subShape.set = setFunc subShape.get = getFunc subShape.has = hasFunc end end end return bodyData end oEditor.loadData = function(self,filename) self:clearData() oEditor.currentData = nil if not filename then return end self.bodyData = dofile(oEditor.output..filename) if not self.bodyData then return end oEditor.names = {} for _,data in ipairs(self.bodyData) do data[1] = typeNames[data[1]] local shapeName = data[1] local createFunc = oEditor[shapeName].create local renameFunc = oEditor[shapeName].rename local resetFunc = oEditor[shapeName].reset data.create = createFunc data.set = setFunc data.get = getFunc data.has = hasFunc local subShapes = data[oEditor[shapeName].SubShapes] if subShapes then for _,subShape in ipairs(subShapes) do subShape[1] = typeNames[subShape[1]] local subShapeName = subShape[1] subShape.create = oEditor[subShapeName].create subShape.parent = data subShape.set = setFunc subShape.get = getFunc subShape.has = hasFunc end end if renameFunc then data.renameListener = oEditor:gslot("Body.editor.rename",function(args) renameFunc(data,args.oldName,args.newName) end) end if resetFunc then data.resetListener = oEditor:gslot("Body.editor.reset",function(args) resetFunc(data,args) end) end oEditor:checkName(data) end oEditor:resetItems() emit("Body.editor.bodyData",self.bodyData) -- TODO end oEditor.resetEditor = function(self) emit("Body.viewArea.create",nil) emit("Body.viewArea.toPos",oEditor.origin) emit("Body.editMenu.created") emit("Body.editMenu.reset") emit("Body.editControl.hide") emit("Body.settingPanel.toState",nil) emit("Body.settingPanel.enable",true) emit("Body.viewPanel.choose",nil) emit("Body.editor.isPlaying",false) end oEditor.edit = function(self, file) oEditor:resetEditor() oEditor.currentFile = file oEditor:loadData(file) end oEditor.new = function(self, file) oEditor:resetEditor() oEditor.currentFile = file oEditor:clearData() oEditor:dumpData(oEditor.currentFile) oEditor:emit("Edited",oEditor.currentFile) end oEditor.hideEditor = function(self,hide,instant) if instant == nil then instant = true end emit("Body.settingPanel.edit",nil) emit("Body.hideEditor",{hide,instant}) end -- bodyData[1]: ShapeName -- bodyData[2]: ItemName -- SubShapes don`t have names local controls = { "oViewArea", "oVRuler", "oHRuler", "oEditControl", "oEditMenu", "oSettingPanel", "oViewPanel", } oEditor:schedule(once(function() local require = using("BodyEditor.Script") for index,name in ipairs(controls) do local createFunc = require(name) coroutine.yield() name = name:sub(2,2):lower()..name:sub(3,-1) oEditor[name] = createFunc() -- keep lua reference for control items coroutine.yield() oEditor:addChild(oEditor[name],index) coroutine.yield() end if oEditor.standAlone then oEditor:gslot("Editor.ItemChooser",function(args) local oSpriteChooser = require("oSpriteChooser") args[#args](oSpriteChooser()) end) local resPath = "BodyEditor/Body" local writePath = oContent.writablePath.."Body" if not oContent:exist(writePath) and oContent:exist(resPath) then oContent:copyAsync(resPath,writePath) end if not oContent:exist(oEditor.input) then oContent:mkdir(oEditor.input) end if not oContent:exist(oEditor.output) then oContent:mkdir(oEditor.output) end local oFileChooser = require("oFileChooser") coroutine.yield() oEditor:addChild(oFileChooser(),oEditor.topMost) end local CCUserDefault = require("CCUserDefault") local oVec2 = require("oVec2") if CCUserDefault.G == "" then CCUserDefault.G = -10 end oEditor.world.gravity = oVec2(0,CCUserDefault.G) --dofile("BodyEditor/Script/generateLoader.lua") if not oEditor.isLoaded then oEditor.isLoaded = true end end)) oEditor:slot("Entering",function() if oEditor.isLoaded then oEditor:emit("Activated") CCDirector.scheduler:schedule(oEditor.worldScheduler) else oRoutine(once(function() repeat coroutine.yield() until oEditor.isLoaded oEditor:emit("Activated") CCDirector.scheduler:schedule(oEditor.worldScheduler) end)) end end) oEditor:slot("Exiting",function() CCDirector.scheduler:unschedule(oEditor.worldScheduler) end) return oEditor
-- Copyright (c) Jérémie N'gadi -- -- All rights reserved. -- -- Even if 'All rights reserved' is very clear : -- -- You shall not use any piece of this software in a commercial product / service -- You shall not resell this software -- You shall not provide any facility to install this particular software in a commercial product / service -- If you redistribute this software, you must link to ORIGINAL repository at https://github.com/ESX-Org/es_extended -- This copyright should appear in every part of the project code self.Frame = nil self.RegisteredElements = {} self.SetDisplay = function(opacity) self.Frame:postMessage({ action = 'setHUDDisplay', opacity = opacity }) end self.RegisterElement = function(name, index, priority, html, data) local found = false for i=1, #self.RegisteredElements, 1 do if self.RegisteredElements[i] == name then found = true break end end if found then return end table.insert(self.RegisteredElements, name) self.Frame:postMessage({ action = 'insertHUDElement', name = name, index = index, priority = priority, html = html, data = data }) self.UpdateElement(name, data) end self.RemoveElement = function(name) for i=1, #self.RegisteredElements, 1 do if self.RegisteredElements[i] == name then table.remove(self.RegisteredElements, i) break end end self.Frame:postMessage({ action = 'deleteHUDElement', name = name }) end self.UpdateElement = function(name, data) self.Frame:postMessage({ action = 'updateHUDElement', name = name, data = data }) end
--scripts/modtools/transform-unit.lua --author expwnent --based on shapechange by Putnam --[[=begin modtools/transform-unit ======================= Transforms a unit into another unit type, possibly permanently. Warning: this will crash arena mode if you view the unit on the same tick that it transforms. If you wait until later, it will be fine. =end]] local utils = require 'utils' normalRace = normalRace or {} local function transform(unit,race,caste) unit.enemy.normal_race = race unit.enemy.normal_caste = caste unit.enemy.were_race = race unit.enemy.were_caste = caste end validArgs = validArgs or utils.invert({ 'clear', 'help', 'unit', 'duration', 'setPrevRace', 'keepInventory', 'race', 'caste', 'suppressAnnouncement', 'untransform', }) local args = utils.processArgs({...}, validArgs) if args.help then print([[scripts/modtools/transform-unit.lua arguments -help print this help message -clear clear records of normal races -unit id set the target unit -duration ticks how long it should last, or "forever" -setPrevRace make a record of the previous race so that you can change it back with -untransform -keepInventory move items back into inventory after transformation -race raceName -caste casteName -suppressAnnouncement don't show the Unit has transformed into a Blah! event -untransform turn the unit back into what it was before ]]) return end if args.clear then normalRace = {} end if not args.unit then error 'Specify a unit.' end if not args.duration then args.duration = 'forever' end local raceIndex local race local caste if args.untransform then local unit = df.unit.find(tonumber(args.unit)) raceIndex = normalRace[args.unit].race race = df.creature_raw.find(raceIndex) caste = normalRace[args.unit].caste normalRace[args.unit] = nil else if not args.race or not args.caste then error 'Specficy a target form.' end --find race for i,v in ipairs(df.global.world.raws.creatures.all) do if v.creature_id == args.race then raceIndex = i race = v break end end if not race then error 'Invalid race.' end for i,v in ipairs(race.caste) do if v.caste_id == args.caste then caste = i break end end if not caste then error 'Invalid caste.' end end local unit = df.unit.find(tonumber(args.unit)) local oldRace = unit.enemy.normal_race local oldCaste = unit.enemy.normal_caste if args.setPrevRace then normalRace[args.unit] = {} normalRace[args.unit].race = oldRace normalRace[args.unit].caste = oldCaste end transform(unit,raceIndex,caste,args.setPrevRace) local inventoryItems = {} local function getInventory() local result = {} for _,item in ipairs(unit.inventory) do table.insert(result, item:new()); end return result end local function restoreInventory() dfhack.timeout(1, 'ticks', function() for _,item in ipairs(inventoryItems) do dfhack.items.moveToInventory(item.item, unit, item.mode, item.body_part_id) item:delete() end inventoryItems = {} end) end if args.keepInventory then inventoryItems = getInventory() end if args.keepInventory then restoreInventory() end if args.duration and args.duration ~= 'forever' then --when the timeout ticks down, transform them back dfhack.timeout(tonumber(args.duration), 'ticks', function() if args.keepInventory then inventoryItems = getInventory() end transform(unit,oldRace,oldCaste) if args.keepInventory then restoreInventory() end end) end
function onCreate() -- background shit makeLuaSprite('black', 'black', -600, -300); setScrollFactor('black', 0.9, 0.9); addLuaSprite('black', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
object_tangible_food_spice_spice_yarrock_01 = object_tangible_food_spice_shared_spice_yarrock_01:new { } ObjectTemplates:addTemplate(object_tangible_food_spice_spice_yarrock_01, "object/tangible/food/spice/spice_yarrock_01.iff")
--[[ Copyright (c) 2019 igor725, scaledteam released under The MIT license http://opensource.org/licenses/MIT ]] local sc = { global = true } function sc:load() registerSvPacket(0x1A, '>bbc64hhhhhhhhhh') registerSvPacket(0x1B, 'bb') end function sc:create(player, id, label, p1, p2, r, g, b, a) if not player:isSupported('SelectionCuboid')then return false end label = label or'New selection' r = r or 20 g = g or 250 b = b or 20 a = a or 100 x1, y1, z1, x2, y2, z2 = makeNormalCube(p1, p2) player:sendPacket( false, 0x1A, id, label, x1, y1, z1, x2, y2, z2, r, g, b, a ) end function sc:remove(player, id) if not player:isSupported('SelectionCuboid')then return false end player:sendPacket(false, 0x1B, id) return true end return sc
-- not sure how to approach this local m = {} m.data = { ["CVarDocumentation.lua"] = { GetCVar = {ParamType = "Arguments", Index = 1, Type = "CVar"}, GetCVarBitfield = {ParamType = "Arguments", Index = 1, Type = "CVar"}, GetCVarBool = {ParamType = "Arguments", Index = 1, Type = "CVar"}, GetCVarDefault = {ParamType = "Arguments", Index = 1, Type = "CVar"}, RegisterCVar = {ParamType = "Arguments", Index = 1, Type = "CVar"}, SetCVar = {ParamType = "Arguments", Index = 1, Type = "CVar"}, SetCVarBitfield = {ParamType = "Arguments", Index = 1, Type = "CVar"}, } } -- change the type of a documented param function m:ApplyPatch(blizzard, patch) for _, func in pairs(blizzard.Functions) do local entry = patch[func.Name] if entry then func[entry.ParamType][entry.Index].Type = entry.Type end end end return m
--[[ Copyright (c) 2014 Francisco Zamora-Martinez (pakozm@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -- DOCUMENTATION AT README.md -- https://github.com/pakozm/lua-oop-iter/blob/master/README.md class module -- section. ----------------------------- -- class module definition -- ----------------------------- local class = { _NAME = "class", _VERSION = "0.4", } -- a list of class tables declared using class function local class_tables_list = setmetatable({}, { __mode = "k" }) local function register_class_table(class_table, class_name) assert(not class_tables_list[class_name], string.format("%s class name exists", class_name)) class_tables_list[class_name] = class_table end ----------------------- -- Private functions -- ----------------------- -- Detect if APRIL-ANN is available. local type = type local aprilann_available = (aprilann ~= nil) if aprilann_available then type = luatype or type end -- Given two object meta_instance, sets the second as parent of the first. local function set_parent(child, parent) setmetatable(child.index_table, parent) end -- Checks if the type of the given object is "table" local function is_table(t) return type(t) == "table" end -- Checks if the given Lua object is a class table and returns its meta_instance -- table. local function has_metainstance(t) return is_table(t) and t.meta_instance end -- Checks if the given object is a class table and returns its -- meta_instance.index_table. local function has_class_instance_index_metamethod(t) return has_metainstance(t) and t.meta_instance.index_table end -- Checks if the given object is a class instance and returns its index_table -- metamethod. local function has_instance_index_metamethod(t) return t and getmetatable(t) and getmetatable(t).index_table end -- Converts a Lua object in an instance of the given class. local function class_instance(obj, class) setmetatable(obj, assert(has_metainstance(class), "2nd argument needs to be a class table")) obj.__instance__ = true return obj end ---------------------- -- Public functions -- ---------------------- -- Returns the class table associated with the given class_name. -- -- @param class_name - A Lua string with the class_name. -- @return class_table,methods_table - A Lua class table, and its methods table. function class.find(class_name) local cls = class_tables_list[class_name] if cls then return class_tables_list[class_name],cls.meta_instance.index_table end end -- Removes the given class name from the auxiliary class table. -- -- @param class_name - A Lua string with the class_name. function class.forget(class_name) class_tables_list[class_name] = nil end -- Predicate which returns true if a given object instance is a subclass of a -- given Lua class table. -- -- @param object_instance - A class instance object. -- @param base_class_table - A class table. -- @return boolean function class.is_a(object_instance, base_class_table) if not class.of(object_instance) then return false end assert(has_metainstance(base_class_table), "Needs a class table as 2nd parameter") local id = (base_class_table.meta_instance or {}).id local ok,result = pcall(function() return object_instance["is_" .. id] ~= nil end) return ok and result end -- Returns the super class table of a given derived class table. Throws an error -- if the given class has not a super class. -- -- @param class_table - A class table. -- @return super_class_table - The parent (super) class table. function class.super(class_table) assert(has_metainstance(class_table), "Needs a class table as 1st parameter") return assert( (getmetatable(class_table) or {}).parent, "The given class hasn't a super-class" ) end -- Returns the class table of the given object instance. -- -- @param obj - A Lua object. -- @return class_table - The class table of the given object. function class.of(obj) return (getmetatable(obj) or {}).cls end -- Returns the value associated with the given key at the given -- class_table. Throws an error if the 1st parameter is not a class table. -- -- @param class_table - A Lua class table. -- @param key - A Lua string with the name you want to consult. -- @return value - The Lua value associated to the given key name. function class.consult(class_table, key) local index = has_class_instance_index_metamethod(class_table) assert(index, "The given object is not a class") if type(index) == "function" then return index(nil,key) else return index[key] end end -- Returns the value associated with the given key at the given class_table -- meta_instance. Throws an error if the 1st parameter is not a class table. -- -- @param class_table - A Lua class table. -- @param key - A Lua string with the name you want to consult at the meta_instance. -- @return value - The Lua value associated to the given key name. function class.consult_metamethod(class_table, key) return assert(has_metainstance(class_table), "The given object is not a class")[key] end -- Calls a method in a given class_table using the given vararg arguments. It -- throws an error if the 1st parameter is not a class table or if the given -- method doesn't exist. -- -- @param class_table - A Lua class_table. -- @param method - A Lua value with the method key. -- @param ... - A vararg list which will be passed to the method call. -- @return value - The value returned by the method call. function class.call(class_table, method, ...) local method = assert(class.consult(class_table, method), "Method " .. method .. " not implemented") return method(...) end -- Extends the given class table with the addition of a new key = value pair -- into the object instance table. It throws an error if the 1st parameter is -- not a class table. -- -- @param class_table - A Lua class table. -- @param key - A Lua key used as index. -- @param value - A Lua value which will be stored at the given key. function class.extend(class_table, key, value) local index = has_class_instance_index_metamethod(class_table) assert(index, "The given 1st parameter is not a class") assert(type(index) == "table") index[key] = value end -- Extends the given class table with the addition of a new key = value pair -- into the object meta_instance table, where metamethods are stored. It throws -- an error if the 1st parameter is not a class table. Be careful, several -- metamethods (__index, __gc) are defined by default in order to implement OOP, -- overwritten them will produce unexpected errors. However, __tostring -- metamethod is also defined but it is totally safe to overwrite it. -- -- @param class_table - A Lua class table. -- @param key - A Lua key used as index. -- @param value - A Lua value which will be stored at the given key. function class.extend_metamethod(class_table, key, value) assert(key ~= "__index" and key ~= "__gc", "__index and __gc metamethods are forbidden") assert(key ~= "id" and key ~= "cls", "id and cls keys are forbidden") assert(has_metainstance(class_table), "The given 1st parameter is not a class")[key] = value end -- Returns true/false if the given instance object is an instance of a derived -- class. -- -- @param obj - A Lua class instance. -- @return boolean function class.is_derived(obj) return getmetatable((getmetatable(obj) or {}).cls or {}).parent ~= nil end -- Returns true/false if the given Lua value is a class table. -- -- @param t - A Lua value. -- @return boolean function class.is_class(t) -- not not allows to transform the returned value into boolean return not not has_class_instance_index_metamethod(t) end -- Changes the __index table by a given function, in case the function -- returns "nil", the key would be searched at the old index field function class.declare_functional_index(cls, func) assert(class.is_class(cls), "Needs a class as first argument") assert(type(func) == "function", "Needs a function as second argument") local old_index = cls.meta_instance.__index if type(old_index) ~= "function" then cls.meta_instance.__index = function(self,key) local v = func(self,key) return v~=nil and v or old_index[key] end else cls.meta_instance.__index = function(self,key) local v = func(self,key) return v~=nil and v or old_index(self,key) end end end -- TODO: reimplement this function -- -- makes a wrapper around an object, delegating the function calls to the given -- object if they are not implemented in the given wrapper table local function wrapper(obj,wrapper) local wrapper = wrapper or {} local current = obj while class.of(current) do -- and not rawequal(getmetatable(current).__index,current) do current = instance_index_metamethod(current) for i,v in pairs(current) do if wrapper[i] == nil then if type(v) == "function" then wrapper[i] = function(first, ...) if rawequal(first,wrapper) then return obj[i](obj, ...) else return obj[i](...) end end -- function elseif getmetatable(v) and getmetatable(v).__call then error("Not implemented wrapper for callable tables") else -- if type(v) == "function" wrapper[i] = v end -- if type(v) == "function" ... else end -- if wrapper[i] == nil end -- for end -- while if class.of(wrapper) then if class.is_derived(wrapper) then error("class_wrapper not works with derived or nil_safe objects") else set_parent(getmetatable(wrapper),getmetatable(obj)) end else wrapper = class_instance(wrapper, class.of(obj)) end return wrapper end -- Creates a class table with a given class_name. It receives an optional parent -- class to implement simple heritance. It returns the class table; another -- table which will contain the methods of the object. Constructor and -- destructor methods will be declared into the class table as -- class_name:constructor(...) and class_name:destructor(). Additionally, a -- third optional argument is given, which allows to give a predefined -- class_table, useful is you want to make global instead of local variables. local class_call_metamethod = function(self, class_name, parentclass, class_table) local class_table = class_table or {} assert(not class_table.constructor and not class_table.destructor and not class_table.meta_instance, "3rd argument has a constructor, destructor or meta_instance field") class_table.constructor = function() end class_table.destructor = function() end -- register_class_table(class_table, class_name) -- local class_table = get_table_from_dotted_string(class_name, true) -- if type(parentclass) == "string" then -- parentclass = get_table_from_dotted_string(parentclass) -- end assert(parentclass==nil or has_metainstance(parentclass), "The parentclass must be defined by 'class' function") -- local t = string.tokenize(class_name,".") -- local meta_instance = { id = class_name, cls = class_table, __tostring = function(self) return "instance of " .. class_name end, __index = { ["is_"..class_name] = true }, } meta_instance.index_table = meta_instance.__index meta_instance.__gc = function(self) if self.__instance__ then class_table.destructor(self) if parentclass then parentclass.meta_instance.__gc(self) end end end local class_metatable = { id = class_name .. " class", parent = parentclass, __tostring = function() return "class ".. class_name .. " class" end, __concat = function(a,b) assert(type(b) == "string", "Needs a string as second argument") return class.consult(a,b) end, __call = function(self, ...) local obj = class_instance({}, self) class_table.constructor(obj, ...) return obj end, -- __index = function(t,k) -- local aux = rawget(t,k) -- if aux then return aux else return t.meta_instance.__index[k] end -- end, } if parentclass then set_parent(meta_instance, parentclass.meta_instance) end -- class_table.meta_instance = meta_instance setmetatable(class_table, class_metatable) return class_table, class_table.meta_instance.__index end setmetatable(class, { __call = class_call_metamethod }) -- In APRIL-ANN this module is defined at global environment if aprilann_available then _G.class = class _G.class_instance = class_instance end return class
--- Secure wrapper for raw cdata buffers. -- -- Note: This is very experimental. -- -- See `RawBuffer`. -- -- @module dslib:raw_buffer -- TODO: fill, memcpy, memmove, write_and_append_buf -- TODO: string buffers (read and copy from) -- TODO: fixed-size buffer with faster, non-atomar functions local load_vars = ... local IE = load_vars.IE _G.assert(IE ~= nil, "This module needs the insecure environment.") local ffi = IE.dslib_ie.internal.require_with_IE_env("ffi") -- TODO: use IE.dslib_ie.internal.ffi, for luajit or cffi IE.assert(ffi ~= nil, "This module needs the ffi (ie. from LuaJIT).") IE.assert(ffi.istype("size_t", 1ULL), "Non 64-bit systems are currently not supported.") ffi.cdef([[ void *malloc(size_t size); void free(void *ptr); void *calloc(size_t nmemb, size_t size); void *realloc(void *ptr, size_t size); void *memmove(void *dest, const void *src, size_t n); int abs(int j); // TODO struct DSlibBuf { uint8_t *m_buffer; size_t m_capacity; size_t m_size; }; ]]) local ctype_uint8_t_ptr = ffi.typeof("uint8_t *") local ctype_uint64_t = ffi.typeof("uint64_t") local ctype_int64_t = ffi.typeof("int64_t") local int_ranges_mins = {uint8_t = 0, uint16_t = 0, uint32_t = 0, uint64_t = 0ULL, int8_t = -0x1p7, int16_t = -0x1p15, int32_t = -0x1p31, int64_t = -0x1p63+0LL} local int_ranges_maxs = {uint8_t = 0x1p8-1, uint16_t = 0x1p16-1, uint32_t = 0x1p32-1, uint64_t = 0x1p64-1ULL, int8_t = 0x1p7-1, int16_t = 0x1p15-1, int32_t = 0x1p31-1, int64_t = 0x1p63-1LL} local C = ffi.C local ffi_cast = ffi.cast local ffi_gc = ffi.gc local ffi_fill = ffi.fill local ffi_copy = ffi.copy local ffi_sizeof = ffi.sizeof local ffi_istype = ffi.istype local ffi_string = ffi.string local ffi_NULL = nil local assert = IE.assert local error = IE.error local type = IE.type local math_floor = IE.math.floor local math_huge = IE.math.huge local string_format = IE.string.format local bor = IE.bit.bor -- the module table local raw_buffer = {} raw_buffer.version = "0.1.0" local RawBuffer_methods = {} local RawBuffer_metatable = {__index = RawBuffer_methods} -- holds secret objects per buffer -- Note: hiding something in the buffer's metatable wouldn't work because mods -- have `debug.g/setmetatable`. If you have suggestions on how to do it better -- (or differently) than with a key-weak static table, please tell me. local s_RawBuffer_secrets = IE.setmetatable({}, {__mode = "k"}) -- checks that arg: -- * is a number or 64 bit cdata -- * is not NaN -- * is integral -- * is in the range [min_incl, max_incl] (TODO: remove this) -- -- Note: do not remove the type check. if arg is set to some arbitrary user-controlled -- value, most operators (ie. `<`) are compromised local function check_int(arg, min_incl, max_incl, new_type) local is_number = type(arg) == "number" if not (is_number or ffi_istype(arg, ctype_uint64_t) or ffi_istype(arg, ctype_int64_t)) then error(string_format("arg is not number, but %s", type(arg))) end if is_number then if arg ~= arg then error("arg is NaN") end if arg ~= math_floor(arg) or arg == math_huge or arg == -math_huge then error(string_format("arg is not integral (%f)", arg)) end end -- cast now to avoid wrong implicit cast at comparison (ie. min_incl to u64 at -- write_i64 with arg=1ULL) local ret_arg = ffi_cast(new_type, arg) if ret_arg < min_incl or ret_arg > max_incl then -- (use tostring because string.format with %d doesn't add the LL and ULL, -- but seems to cast to int64_t first, which can be confusing when trying -- to write a uint64_t >=0x1p63 as i64) error(string_format("arg is outside of range (%s is not in [%s, %s])", IE.tostring(arg), IE.tostring(min_incl), IE.tostring(max_incl))) end return ret_arg end --- Creates a new `RawBuffer`. -- @treturn RawBuffer The new buffer. -- @function new_RawBuffer raw_buffer.new_RawBuffer = function() local buf = IE.setmetatable({}, RawBuffer_metatable) s_RawBuffer_secrets[buf] = { -- TODO: don't name the fields with strings m_struct = ffi_gc(ffi.new("struct DSlibBuf", {ffi_NULL, 0ULL, 0ULL}), function(strct) C.free(strct.m_buffer) end), m_next_lock_owner = nil, -- see set_lock(), unset_lock() for details m_locked = false, } return buf end --- A byte-addressable secure wrapper for a cdata buffer. -- -- Maximum size is currently about `0x1p60` bytes. -- -- Integer types can be numbers or 64 bit LuaJIT cdata integers (ie. 1ULL). -- -- Note: The API is very unstable. -- -- @type RawBuffer --[[ Security notes on debug hooks and pcall: ======================================== Untrusted mods have access to debug.sethook, coroutines and pcall. This means: * Buffers can still be used after calls to error and assert (removing them from s_RawBuffer_secrets would not help because of hooks). * Any function can stopped and later continued at every function call, function return or new line. The only exception to this is if the debug hook is removed before (via `IE.debug.sethook()`), but that's a NYI. (One could try to check in the registry whether there's a hook set from lua (see luajit src), but that's even more ugly, and I'm not sure if it works with coroutines.) We must therefore ensure that: (you can actually skip this list because of the locking) * The capacity *never* decreases. Otherwise an attacker could stop execution of a writing function after capacity checks, then decrease the capacity, and then write outside of the buffer. * `m_capacity` is *always* smaller or equal to the actual buffer capacity. We therefore write the capacity *after* the realloc. * `m_size` is updated *after* the write (or other initialization) happened. * Read operations must only be able to read initialized data. Checks of old `m_size` values are ok here because the size of initialized data also never shrinks. * Allocated memory blocks must always stay valid as long as can be accessed by any function. Hence, `C.realloc()` can not be used. As we do use `C.realloc()`, we instead have to make sure, that only one function invocation is in a critical section (a code section that accesses the C buffer) at all time, we call these functions then atomar. The `set_lock()` and `unset_lock()` functions below are used to ensure this. Note: The lock is not unset if an error happens. This causes lock poisoning, which means that buffers can't be used anymore after an error happened, this is a good thing. ]] -- sets the lock on s. if not possible, raises an error and possibly poisons the -- lock. (this is just for detection of atomarity violations, not for synchronization) -- (a ffi call would be slower, when jited) local function set_lock(s) --~ C.abs(1) --~ do return end local me = {} s.m_next_lock_owner = me assert(not s.m_locked, "set_lock() failed: already locked") -- Anyone who wants to lock, must have conquered the assert above, and hence -- also set themselves as owner *before* the next line happens. s.m_locked = true -- Nobody can set themselves to m_next_lock_owner and enter this section now -- anymore. -- And anyone in this section can no longer modify m_next_lock_owner. -- Hence, only one can pass the next assert. assert(s.m_next_lock_owner == me, "set_lock() failed: someone else locked") -- Now nobody is the next owner. s.m_next_lock_owner = nil end local function unset_lock(s) s.m_locked = false end local function wrap_secret_and_atomar(func) return function(self, ...) local s = assert(s_RawBuffer_secrets[self]) set_lock(s) local ret = func(s.m_struct, ...) unset_lock(s) return ret end end --- Returns the size of a buffer. -- You can not read or write outside of this size. -- @treturn int The size. -- @function size function RawBuffer_methods:size() local s = assert(s_RawBuffer_secrets[self]).m_struct return s.m_size end --- Returns the capacity of a buffer. -- @treturn int The capacity. -- @function capacity function RawBuffer_methods:capacity() local s = assert(s_RawBuffer_secrets[self]).m_struct return s.m_capacity end --- Increases the capacity of the buffer. -- Size is not influenced. -- Capacity is never decreased. -- @tparam int new_capacity The requested minimal new capacity. -- @function reserve local function RawBuffer_methods_reserve(s, new_capacity) if s.m_capacity >= new_capacity then return end -- be more restrictive than 0x1p64 to avoid negative numbers in int64_t, even -- after we multiply by 4 new_capacity = check_int(new_capacity, 0ULL, 0x1p60-1ULL, ctype_uint64_t) -- increase capacity by factor 2 (TODO: choose better factor?) local actual_new_capacity = s.m_capacity * 2ULL -- increase more if it was not enough if new_capacity > actual_new_capacity then -- round to multiple of 0x10 (TODO: remove premature opti) -- (new_capacity - 1 >= 0 holds because of 0 <= s.m_capacity < new_capacity) actual_new_capacity = bor(new_capacity - 1, 0xfULL) + 1 end local new_buf = C.realloc(s.m_buffer, actual_new_capacity) if new_buf == ffi_NULL then -- realloc() failed. the original buffer is untouched error("realloc() failed") end s.m_buffer = ffi_cast(ctype_uint8_t_ptr, new_buf) s.m_capacity = actual_new_capacity end RawBuffer_methods.reserve = wrap_secret_and_atomar(RawBuffer_methods_reserve) --- In- or decreases the size of the buffer. -- If size is increased, new data is filled with `0`s. -- @tparam int new_size The new size. -- @function resize RawBuffer_methods.resize = wrap_secret_and_atomar(function(s, new_size) new_size = check_int(new_size, 0ULL, 0x1p60-1ULL, ctype_uint64_t) if s.m_size >= new_size then s.m_size = new_size return end -- Note: doing self:reserve(...) or RawBuffer_methods.reserve(...) would be -- insecure RawBuffer_methods_reserve(s, new_size) ffi_fill(s.m_buffer + s.m_size, new_size - s.m_size) s.m_size = new_size end) local function check_offset(s, offset, value_size) assert(s.m_size >= value_size, "calculation would overflow. Are you trying to read from / write to empty buffer?") return check_int(offset, 0ULL, s.m_size - value_size, ctype_uint64_t) end -- read methods do local function make_read_func(type_str) local type_size = ffi_sizeof(type_str) local ctype_ptr = ffi.typeof(type_str.." *") return wrap_secret_and_atomar(function(s, offset) offset = check_offset(s, offset, type_size) return ffi_cast(ctype_ptr, s.m_buffer + offset)[0] end) end for _, i in IE.ipairs({1, 2, 4, 8}) do local type_str = string_format("int%d_t", i * 8) RawBuffer_methods["read_u"..(8*i)] = make_read_func("u"..type_str) RawBuffer_methods["read_i"..(8*i)] = make_read_func(type_str) end --- Reads an unsigned 8-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `u8` value at the given offset. -- @function read_u8 --- Reads an unsigned 16-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `u16` value at the given offset. -- @function read_u16 --- Reads an unsigned 32-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `u32` value at the given offset. -- @function read_u32 --- Reads an unsigned 64-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `u64` value at the given offset. It is a `uint64_t` cdata value. -- @function read_u64 --- Reads a signed 8-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `i8` value at the given offset. -- @function read_i8 --- Reads a signed 16-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `i16` value at the given offset. -- @function read_i16 --- Reads a signed 32-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn int The `i32` value at the given offset. -- @function read_i32 --- Reads a signed 64-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @treturn int The `i64` value at the given offset. It is an `int64_t` cdata value. -- @function read_i64 --- Reads a 32-bit floating-point number (a `float`) at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn number The `f32` value at the given offset. -- @function read_f32 RawBuffer_methods.read_f32 = make_read_func("float") --- Reads a 64-bit floating-point number (a `double`) at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @treturn number The `f64` value at the given offset. -- @function read_f64 RawBuffer_methods.read_f64 = make_read_func("double") --- Reads a string of a given length at a given byte-offset. -- @tparam int offset Byte-offset in the buffer. -- @tparam int len Length of the string. Must not exceed buffer size. -- @treturn string A copy of the data as string. -- @function read_string RawBuffer_methods.read_string = wrap_secret_and_atomar(function(s, offset, len) len = check_int(len, 0ULL, int_ranges_maxs.uint64_t, ctype_uint64_t) offset = check_offset(s, offset, len) return ffi_string(s.m_buffer + offset, len) end) end -- TODO: remove append and make write to: -- * resize until offset if big -- * reserve -- * write and possibly increase size -- or not? -- write methods do local function make_write_func(type_str, value_checker) local type_size = ffi_sizeof(type_str) local ctype_ptr = ffi.typeof(type_str.." *") value_checker = value_checker or function(v) return v end return wrap_secret_and_atomar(function(s, offset, value) offset = check_offset(s, offset, type_size) value = value_checker(value) ffi_cast(ctype_ptr, s.m_buffer + offset)[0] = value end) end local function make_int_write_func(type_str) local min = assert(int_ranges_mins[type_str]) local max = assert(int_ranges_maxs[type_str]) local c_type = ffi.typeof(type_str) return make_write_func(type_str, function(value) return check_int(value, min, max, c_type) end) end for _, i in IE.ipairs({1, 2, 4, 8}) do local type_str = string_format("int%d_t", i * 8) RawBuffer_methods["write_u"..(8*i)] = make_int_write_func("u"..type_str) RawBuffer_methods["write_i"..(8*i)] = make_int_write_func(type_str) end --- Writes an unsigned 8-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `u8` value to write. -- @function write_u8 --- Writes an unsigned 16-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `u16` value to write. -- @function write_u16 --- Writes an unsigned 32-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `u32` value to write. -- @function write_u32 --- Writes an unsigned 64-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `u64` value to write. Can be a `uint64_t` cdata value. -- @function write_u64 --- Writes a signed 8-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `i8` value to write. -- @function write_i8 --- Writes a signed 16-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `i16` value to write. -- @function write_i16 --- Writes a signed 32-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `i32` value to write. -- @function write_i32 --- Writes a signed 64-bit integer at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam int value The `i64` value to write. Can be an `int64_t` cdata value. -- @function write_i64 --- Writes a 32-bit floating-point number (a `float`) at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam number value The `f32` value to write. -- @function write_f32 RawBuffer_methods.write_f32 = make_write_func("float") --- Writes a 64-bit floating-point number (a `double`) at a given byte-offset. -- @tparam int offset Byte-offset in the buffer -- @tparam number value The `f64` value to write. -- @function write_f64 RawBuffer_methods.write_f64 = make_write_func("double") --- TODO -- @function copy_from local function RawBuffer_methods_copy_from_inner(s_dst, dst_offset, s_src, src_offset, len) len = check_int(len, 0ULL, int_ranges_maxs.uint64_t, ctype_uint64_t) dst_offset = check_offset(s_dst, dst_offset, len) src_offset = check_offset(s_src, src_offset, len) if s_dst == s_src -- if they overlap, each start must be before the other's end -- if they don't overlap, one comes after the other and dst_offset < src_offset + len and src_offset < dst_offset + len then C.memmove(s_dst.m_buffer + dst_offset, s_src.m_buffer + src_offset, len) else ffi_copy(s_dst.m_buffer + dst_offset, s_src.m_buffer + src_offset, len) end end function RawBuffer_methods:copy_from(dst_offset, src_buf, src_offset, len) local s_dst = assert(s_RawBuffer_secrets[self]) local s_src = assert(s_RawBuffer_secrets[src_buf]) set_lock(s_dst) set_lock(s_src) RawBuffer_methods_copy_from_inner(s_dst.m_struct, dst_offset, s_src.m_struct, src_offset, len) unset_lock(s_src) unset_lock(s_dst) end end -- append methods do local function make_append_func(type_str, value_checker) local type_size = ffi_sizeof(type_str) local ctype_ptr = ffi.typeof(type_str.." *") value_checker = value_checker or function(v) return v end return wrap_secret_and_atomar(function(s, value) value = value_checker(value) RawBuffer_methods_reserve(s, s.m_size + type_size) ffi_cast(ctype_ptr, s.m_buffer + s.m_size)[0] = value s.m_size = s.m_size + type_size end) end local function make_int_append_func(type_str) local min = assert(int_ranges_mins[type_str]) local max = assert(int_ranges_maxs[type_str]) local c_type = ffi.typeof(type_str) return make_append_func(type_str, function(value) return check_int(value, min, max, c_type) end) end for _, i in IE.ipairs({1, 2, 4, 8}) do local type_str = string_format("int%d_t", i * 8) RawBuffer_methods["append_u"..(8*i)] = make_int_append_func("u"..type_str) RawBuffer_methods["append_i"..(8*i)] = make_int_append_func(type_str) end --- Appends an unsigned 8-bit integer to the end of the buffer. -- @tparam int value The `u8` value to write. -- @function append_u8 --- Appends an unsigned 16-bit integer to the end of the buffer. -- @tparam int value The `u16` value to write. -- @function append_u16 --- Appends an unsigned 32-bit integer to the end of the buffer. -- @tparam int value The `u32` value to write. -- @function append_u32 --- Appends an unsigned 64-bit integer to the end of the buffer. -- @tparam int value The `u64` value to write. Can be a `uint64_t` cdata value. -- @function append_u64 --- Appends a signed 8-bit integer to the end of the buffer. -- @tparam int value The `i8` value to write. -- @function append_i8 --- Appends a signed 16-bit integer to the end of the buffer. -- @tparam int value The `i16` value to write. -- @function append_i16 --- Appends a signed 32-bit integer to the end of the buffer. -- @tparam int value The `i32` value to write. -- @function append_i32 --- Appends a signed 64-bit integer to the end of the buffer. -- @tparam int value The `i64` value to write. Can be an `int64_t` cdata value. -- @function append_i64 --- Appends a 32-bit floating-point number (a `float`) to the end of the buffer. -- @tparam number value The `f32` value to write. -- @function append_f32 RawBuffer_methods.append_f32 = make_append_func("float") --- Appends a 64-bit floating-point number (a `double`) to the end of the buffer. -- @tparam number value The `f64` value to write. -- @function append_f64 RawBuffer_methods.append_f64 = make_append_func("double") end return raw_buffer
local t = ...; assert( type(t) == "table" ); return t .. { InitCommand=NOTESKIN:GetMetricA('ReceptorArrow', 'InitCommand'); MissCommand=NOTESKIN:GetMetricA('ReceptorArrow', 'MissCommand'); NoneCommand=NOTESKIN:GetMetricA('ReceptorArrow', 'NoneCommand'); HitMineCommand=NOTESKIN:GetMetricA('ReceptorArrow', 'HitMineCommand'); W5Command=NOTESKIN:GetMetricA('ReceptorArrow', 'W5Command'); W4Command=NOTESKIN:GetMetricA('ReceptorArrow', 'W4Command'); W3Command=NOTESKIN:GetMetricA('ReceptorArrow', 'W3Command'); W2Command=NOTESKIN:GetMetricA('ReceptorArrow', 'W2Command'); W1Command=NOTESKIN:GetMetricA('ReceptorArrow', 'W1Command'); };
function apply_target(keys) local caster = keys.caster local modifier = "berserker_ignite_target" local ability = keys.ability local level = (ability:GetLevel()-1) local duration_d = ability:GetLevelSpecialValueFor("duration_target", level) local target = keys.target ability:ApplyDataDrivenModifier(caster, target, modifier, {duration = duration_d}) end function area_ignite(keys) local caster = keys.caster local ability = caster:FindAbilityByName("berserker_ignite") local modifier = "berserker_fury_buff" if caster:HasModifier(modifier) then local level = (ability:GetLevel()-1) local modifier_target = "berserker_ignite_target" local duration_d = ability:GetLevelSpecialValueFor("duration_target", level) local target = keys.target ability:ApplyDataDrivenModifier(caster, target, modifier_target, {duration = duration_d}) end end
--Designed by Donrskbb-- Config = {} Config.Locale = 'en' --EN is the Dutch Translated Version. Would you like the English Version,replace the EN with EN-EN version and rename it-- Config.green = 56108 Config.grey = 8421504 Config.red = 16711680 Config.orange = 16744192 Config.blue = 2061822 Config.purple = 6965387 Config.pink = 11750815 Config.yellow = 16449301 Config.white = 16777215 Config.black = 0 Config.bluetweet = 4436965 Config.webhook = "YOUR WEBHOOK" Config.Image = "YOUR IMAGE" --Just change true for monitor and false to ignore-- settings = { LogKills = false, -- Log when a player kill an other player. LogEnterPoliceVehicle = true, -- Log when an player enter in a police vehicle. LogEnterBlackListedVehicle = true, -- Log when a player enter in a blacklisted vehicle. LogPedJacking = true, -- Log when a player is jacking a car LogChatServer = true, -- Log when a player is talking in the chat , /command works too. LogLoginServer = false, -- Log when a player is connecting/disconnecting to the server. LogItemTransfer = true, -- Log when a player is giving an item. LogItemDrop = true,-- Log when a player drop an item. LogItemPickup = true,-- Log when a player pick an item. LogWeaponTransfer = true, -- Log when a player is giving a weapon. LogWeaponDrop = true, -- Log when a player drop a weapon. LogMoneyTransfer = true, -- Log when a player is giving money LogMoneyDrop = true, -- Log when a player drop money LogMoneyPickup = true, -- Log when a player pick money LogDirtyMoneyTransfer = true, -- Log when a player is giving dirty money LogDirtyMoneyDrop = true, -- Log when a player drop dirty money LogDirtyMoneyPickup = true, -- Log when a player pick dirty money LogTweetServer = true, -- Log when a player is tweeting in the chat. LogBanhammer = true, -- Log when a player is banned. LogBankWithdraw = true, -- Log when a player is transfering account money. LogBankDeposit = true, -- Log when a player is transfering account money. } --Just add vehicles for blacklist announce-- blacklistedModels = { "APC", "BARRACKS", "BARRACKS2", "RHINO", "CRUSADER", "CARGOBOB", "SAVAGE", "TITAN", "LAZER", "VALKYRIE", "VALKYRIE2", }
--------------------------------------------------------------------------- -- DPI detection code. -- --------------------------------------------------------------------------- local capi = {screen = screen} local gtable = require("gears.table") local grect = require("gears.geometry").rectangle local gdebug = require("gears.debug") local module = {} local ascreen, data = nil, nil -- Metric to Imperial conversion constant. local mm_per_inch = 25.4 local xft_dpi, fallback_dpi local function get_fallback_dpi() -- Following Keith Packard's whitepaper on Xft, -- https://keithp.com/~keithp/talks/xtc2001/paper/xft.html#sec-editing -- the proper fallback for Xft.dpi is the vertical DPI reported by -- the X server. This will generally be 96 on Xorg, unless the user -- has configured it differently if not fallback_dpi then local _, h = root.size() local _, hmm = root.size_mm() fallback_dpi = hmm ~= 0 and h * mm_per_inch / hmm end return fallback_dpi or 96 end local function dpi_for_output(viewport, output) local dpi = nil local geo = viewport.geometry -- Ignore outputs with width/height 0 if output.mm_width ~= 0 and output.mm_height ~= 0 then local dpix = geo.width * mm_per_inch / output.mm_width local dpiy = geo.height * mm_per_inch / output.mm_height dpi = math.min(dpix, dpiy, dpi or dpix) elseif ascreen._get_xft_dpi() then dpi = ascreen._get_xft_dpi() end return dpi or get_fallback_dpi() end local function dpis_for_outputs(viewport) local max_dpi, min_dpi, max_size, min_size = 0, math.huge, 0, math.huge for _, o in pairs(viewport.outputs) do local dpi = dpi_for_output(viewport, o) o.dpi = dpi max_dpi = math.max(max_dpi, dpi) min_dpi = math.min(min_dpi, dpi) -- Compute the diagonal size. if o.mm_width and o.mm_height then o.mm_size = math.sqrt(o.mm_width^2 + o.mm_height^2) o.inch_size = o.mm_size/mm_per_inch max_size = math.max(max_size, o.mm_size) min_size = math.min(min_size, o.mm_size) end end -- When there is no output. if min_dpi == math.huge then min_dpi = get_fallback_dpi() max_dpi = min_dpi end --TODO Some output may have a lower resolution than the viewport, so their -- DPI is currently wrong. Once fixed, the preferred DPI can become -- different from the minimum one. local pref_dpi = min_dpi viewport.minimum_dpi = min_dpi viewport.maximum_dpi = max_dpi viewport.preferred_dpi = pref_dpi -- Guess the diagonal size using the DPI. if min_size == math.huge then for _, o in pairs(viewport.outputs) do local geo = o.geometry if geo then o.mm_size = math.sqrt(geo.width^2 + geo.height^2)/o.dpi max_size = math.max(max_size, o.mm_size) min_size = math.min(min_size, o.mm_size) end end -- In case there is no output information. if min_size == math.huge then local geo = viewport.geometry local size = math.sqrt(geo.width^2 + geo.height^2)/max_dpi max_size, min_size = size, size end end viewport.mm_minimum_size = min_size viewport.mm_maximum_size = max_size viewport.inch_minimum_size = min_size/mm_per_inch viewport.inch_maximum_size = max_size/mm_per_inch return max_dpi, min_dpi, pref_dpi end local function update_outputs(old_viewport, new_viewport) gtable.diff_merge( old_viewport.outputs, new_viewport.outputs, function(o) return o.name or ( (o.mm_height or -7)*9999 * (o.mm_width or 5)*123 ) end, gtable.crush ) end -- Fetch the current viewports and compare them to the caches ones. -- -- The idea is to keep whatever metadata kept within the existing ones and know -- what is added and removed. local function update_viewports(force) if #ascreen._viewports > 0 and not force then return ascreen._viewports end local new = ascreen._get_viewports() local _, add, rem = gtable.diff_merge( ascreen._viewports, new, function(a) return a.id end, update_outputs ) for _, viewport in ipairs(ascreen._viewports) do dpis_for_outputs(viewport) end assert(#ascreen._viewports > 0 or #new == 0) return ascreen._viewports, add, rem end -- Compute more useful viewport metadata frrom_sparse(add)om the list of output. -- @treturn table An viewport with more information. local function update_screen_viewport(s) local viewport = s._private.viewport if #ascreen._viewports == 0 then ascreen._viewports = update_viewports(false) end -- The maximum is equal to the screen viewport, so no need for many loops. if not viewport then local big_a, i_size = nil, 0 for _, a in ipairs(ascreen._viewports) do local int = grect.get_intersection(a.geometry, s.geometry) if int.width*int.height > i_size then big_a, i_size = a, int.width*int.height end if i_size == s.geometry.width*s.geometry.height then break end end if big_a then viewport, s._private.viewport = big_a, big_a end end if not viewport then gdebug.print_warning("Screen "..tostring(s).. " doesn't overlap a known physical monitor") end end function module.create_screen_handler(viewport) local geo = viewport.geometry local s = capi.screen.fake_add( geo.x, geo.y, geo.width, geo.height, {_managed = true} ) update_screen_viewport(s) s:emit_signal("request::desktop_decoration") s:emit_signal("request::wallpaper") -- Will call all `connect_for_each_screen`. s:emit_signal("added") end function module.remove_screen_handler(viewport) for s in capi.screen do if s._private.viewport and s._private.viewport.id == viewport.id then s:fake_remove() return end end end function module.resize_screen_handler(old_viewport, new_viewport) for s in capi.screen do if s._private.viewport and s._private.viewport.id == old_viewport.id then local ngeo = new_viewport.geometry s:fake_resize( ngeo.x, ngeo.y, ngeo.width, ngeo.height ) s._private.viewport = new_viewport return end end end -- Xft.dpi is explicit user configuration, so honor it. -- (It isn't a local function to allow the tests to replace it) function module._get_xft_dpi() if not xft_dpi then xft_dpi = tonumber(awesome.xrdb_get_value("", "Xft.dpi")) or false end return xft_dpi end -- Some of them may be present twice or a giant viewport may exist which -- encompasses everything. local function deduplicate_viewports(vps) local min_x, min_y, max_x, max_y = math.huge, math.huge, 0, 0 -- Sort the viewports by `x`. for _, vp in ipairs(vps) do local geo = vp.geometry min_x = math.min(min_x, geo.x) max_x = math.max(max_x, geo.x+geo.width) min_y = math.min(min_y, geo.y) max_y = math.max(max_y, geo.y+geo.height) end -- Remove the "encompass everything" viewport (if any). if #vps > 1 then for k, vp in ipairs(vps) do local geo = vp.geometry if geo.x == min_x and geo.y == min_y and geo.x+geo.width == max_x and geo.y+geo.height == max_y then table.remove(vps, k) break end end end --TODO when the rules are added, mark the viewports that are embedded into -- each other so the rules can decide to use the smaller or larger viewport -- when creating the screen. This happens a lot then connecting to -- projectors when doing presentations. return vps end -- Provide a way for the tests to replace `capi.screen._viewports`. function module._get_viewports() assert(type(capi.screen._viewports()) == "table") return deduplicate_viewports(capi.screen._viewports()) end local function get_dpi(s) if s._private.dpi or s._private.dpi_cache then return s._private.dpi or s._private.dpi_cache end if not s._private.viewport then update_screen_viewport(s) end -- Pick a DPI (from best to worst). local dpi = ascreen._get_xft_dpi() or (s._private.viewport and s._private.viewport.preferred_dpi or nil) or get_fallback_dpi() -- Pick the screen DPI depending on the `autodpi` settings. -- Historically, AwesomeWM size unit was the pixel. This assumption is -- present in a lot, if not most, user config and is why this cannot be -- enable by default for existing users. s._private.dpi_cache = data.autodpi and dpi or ascreen._get_xft_dpi() or get_fallback_dpi() return s._private.dpi_cache end local function set_dpi(s, dpi) s._private.dpi = dpi end screen.connect_signal("request::create", module.create_screen_handler) screen.connect_signal("request::remove", module.remove_screen_handler) screen.connect_signal("request::resize", module.resize_screen_handler) -- Create some screens when none exist. This can happen when AwesomeWM is -- started with `--screen manual` and no handler is used. capi.screen.connect_signal("scanned", function() if capi.screen.count() == 0 then -- Private API to scan for screens now. if #ascreen._get_viewports() == 0 then capi.screen._scan_quiet() end local cur_viewports = ascreen._get_viewports() if #cur_viewports > 0 then for _, viewport in ipairs(cur_viewports) do module.create_screen_handler(viewport) end else capi.screen.fake_add(0, 0, 640, 480) end assert(capi.screen.count() > 0, "Creating screens failed") end end) -- This is the (undocumented) signal sent by capi. capi.screen.connect_signal("property::_viewports", function(a) if capi.screen.automatic_factory then return end assert(#a > 0) local _, added, removed = update_viewports(true) local resized = {} -- Try to detect viewports being replaced or resized. for k2, viewport in ipairs(removed) do local candidate, best_size, best_idx = {}, 0, nil for k, viewport2 in ipairs(added) do local int = grect.get_intersection(viewport.geometry, viewport2.geometry) if (int.width*int.height) > best_size then best_size, best_idx, candidate = (int.width*int.height), k, viewport2 end end if candidate and best_size > 0 then table.insert(resized, {removed[k2], added[best_idx]}) removed[k2] = nil table.remove(added , best_idx) end end gtable.from_sparse(removed) -- Drop the cache. for s in capi.screen do s._private.dpi_cache = nil end capi.screen.emit_signal("property::viewports", ascreen._get_viewports()) -- First, ask for screens for these new viewport. for _, viewport in ipairs(added) do capi.screen.emit_signal("request::create", viewport, {context="viewports_changed"}) end -- Before removing anything, make sure to resize existing screen as it may -- affect where clients will go when the screens are removed. for _, p in ipairs(resized) do capi.screen.emit_signal("request::resize", p[1], p[2], {context="viewports_changed"}) end -- Remove the now out-of-view screens. for _, viewport in ipairs(removed) do capi.screen.emit_signal("request::remove", viewport, {context="viewports_changed"}) end end) -- Add the DPI related properties return function(screen, d) ascreen, data = screen, d -- "Lua" copy of the CAPI viewports. It has more metadata. ascreen._viewports = {} gtable.crush(ascreen, module, true) ascreen.object.set_dpi = set_dpi ascreen.object.get_dpi = get_dpi for _, prop in ipairs {"minimum_dpi" , "maximum_dpi" , "mm_maximum_width" , "mm_minimum_width" , "inch_maximum_width", "inch_minimum_width", "preferred_dpi" } do screen.object["get_"..prop] = function(s) if not s._private.viewport then update_screen_viewport(s) end local a = s._private.viewport or {} return a[prop] or nil end end end
if AkDebugLoad then print("[#Start] Loading ak.data.AkSlotNamesParser ...") end local SlotNamesParser = {} local function isModuleAvailable(name) if package.loaded[name] then return true else for _, searcher in ipairs(package.searchers) do local loader = searcher(name) if type(loader) == "function" then package.preload[name] = loader return true end end return false end end local namesToSlots = {} local slotTable local _ local SlotFuncs function SlotNamesParser.updateSlotNames() if slotTable then local function recursiveLookup(currentSlotTable, prefix, ...) for k, v in pairs(currentSlotTable) do local path = ... and {table.unpack(...)} or {} table.insert(path, k) local pathString = table.concat(path, ".") if type(v) == "table" then -- print("[#SlotNameParser]" .. pathString .. '> Lookup Table ' .. pathString) recursiveLookup(v, prefix .. "--", path) else local slotNumber = SlotFuncs.lookupSlotNr(table.unpack(path)) -- print("[#SlotNameParser]" .. pathString .. '> Found Slot: ' .. tostring(s)) namesToSlots[tostring(slotNumber)] = pathString end end end recursiveLookup(slotTable, "#", {}) end end if isModuleAvailable("SlotNames_BH2") then slotTable, _, SlotFuncs = require("SlotNames_BH2")() SlotNamesParser.updateSlotNames() end function SlotNamesParser.getSlotName(slot) if slotTable then return namesToSlots[tostring(slot)] else return nil end end return SlotNamesParser
local local0 = 0.3 local local1 = 0.3 - local0 local local2 = 0.3 - local0 local local3 = 0.3 - local0 local local4 = 0.3 - local0 local local5 = 3.4 - local0 local local6 = 0.3 - local0 local local7 = 4.2 - local0 local local8 = 0.3 - local0 local local9 = 0.3 - local0 local local10 = 0.3 - local0 local local11 = 6.6 - local0 local local12 = 0.3 - local0 local local13 = 0.3 - local0 function OnIf_303020(arg0, arg1, arg2) if arg2 == 0 then DungeonResident_Madman_TwoSickle303020_ActAfter_RealTime(arg0, arg1) end return end local0 = local11 function DungeonResident_Madman_TwoSickle303020Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetEventRequest() local local5 = arg0:GetRandam_Int(1, 100) local local6 = arg0:GetHpRate(TARGET_SELF) local local7 = 1 local local8 = 1 local local9 = 1 if arg0:IsFinishTimer(0) == false then local7 = 0 else local7 = 1 end if arg0:IsFinishTimer(1) == false then local8 = 0 else local8 = 1 end if arg0:IsFinishTimer(2) == false then local9 = 0 else local9 = 1 end arg0:AddObserveArea(0, TARGET_SELF, TARGET_ENE_0, AI_DIR_TYPE_F, 360, UPVAL0) if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 165) then local0[10] = 100 elseif 9 <= local3 then local0[1] = 10 local0[2] = 0 local0[3] = 10 local0[4] = 35 local0[5] = 25 * local9 local0[6] = 10 local0[7] = 0 * local7 local0[11] = 10 * local8 elseif 4.5 <= local3 then local0[1] = 20 local0[2] = 0 local0[3] = 0 local0[4] = 15 local0[5] = 40 * local9 local0[6] = 15 local0[7] = 10 * local7 local0[11] = 0 * local8 else local0[1] = 5 local0[2] = 25 local0[3] = 5 local0[4] = 0 local0[5] = 35 * local9 local0[6] = 15 local0[7] = 15 * local7 local0[11] = 0 * local8 end local1[1] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act01) local1[2] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act02) local1[3] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act03) local1[4] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act04) local1[5] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act05) local1[6] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act06) local1[7] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act07) local1[9] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act09) local1[10] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act10) local1[11] = REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_Act11) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, DungeonResident_Madman_TwoSickle303020_ActAfter_AdjustSpace), local2) return end local0 = 3.4 - local0 local0 = 4.1 - local0 local0 = 4.1 - local0 function DungeonResident_Madman_TwoSickle303020_Act01(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 5 local local2 = UPVAL1 + 5 local local3 = UPVAL2 + 0.5 local local4 = UPVAL0 - 1 if local4 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local4, 0, 0, 3) end if arg0:HasSpecialEffectId(TARGET_SELF, 5734) == true then if local0 <= 20 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) elseif local0 <= 40 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3010, TARGET_ENE_0, local3, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3010, TARGET_ENE_0, local2, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3011, TARGET_ENE_0, local3, 0) end elseif local0 <= 20 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) elseif local0 <= 40 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, local3, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local2, 0, 360) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, local3, 0) end GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local5 local0 = local7 function DungeonResident_Madman_TwoSickle303020_Act02(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 - 1 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0 + 5, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, UPVAL1 + 0.5, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 2.9 - local0 function DungeonResident_Madman_TwoSickle303020_Act03(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 - 1 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0, 0, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 6.3 - local0 function DungeonResident_Madman_TwoSickle303020_Act04(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 - 1 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3006, TARGET_ENE_0, UPVAL0 + 0.5, 0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local11 function DungeonResident_Madman_TwoSickle303020_Act05(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 2 local local2 = UPVAL0 - 1 if local2 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local2, 0, 0, 3) end if arg0:HasSpecialEffectId(TARGET_SELF, 5734) == true then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3016, TARGET_ENE_0, local1, 0, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3007, TARGET_ENE_0, local1, 0, 0) end arg0:SetTimer(2, 10) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 4 - local0 function DungeonResident_Madman_TwoSickle303020_Act06(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 0.5 local local2 = UPVAL0 - 2 if local2 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local2, 0, 0, 3) end if arg0:HasSpecialEffectId(TARGET_SELF, 5734) == true then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3013, TARGET_ENE_0, local1, 0, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3008, TARGET_ENE_0, local1, 0, 0) end arg0:SetTimer(0, 10) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 3.5 - local0 function DungeonResident_Madman_TwoSickle303020_Act07(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 - 1.3 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL0 + 0.5, 0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_Madman_TwoSickle303020_Act09(arg0, arg1, arg2) local local0 = arg0:GetRandam_Float(2, 6) if local0 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local0, 0, 0, 3) end local local1 = 1 for local2 = arg0:GetRandam_Int(1, 3) - local1, 3, local1 do local local3 = 0 local local4 = AI_DIR_TYPE_L if arg0:GetRandam_Int(1, 100) <= 50 then local3 = 702 local4 = AI_DIR_TYPE_L else local3 = 703 local4 = AI_DIR_TYPE_R end arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, local3, TARGET_ENE_0, 0, local4, 4) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_Madman_TwoSickle303020_Act10(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = 0 arg1:AddSubGoal(GOAL_COMMON_Turn, 1, TARGET_ENE_0, 0, 0, 0) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_Madman_TwoSickle303020_Act11(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = 0 arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Int(1.5, 3), TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(45, 60), true, true, -1) arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Int(1.5, 2), TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(45, 60), true, true, -1) arg0:SetTimer(1, 10) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_Madman_TwoSickle303020_ActStep(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = 4 local local2 = 4 local local3 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_L, local1, 5) local local4 = arg0:IsOnNearMesh(TARGET_SELF, AI_DIR_TYPE_R, local2, 5) if local3 and local4 then if arg0:GetRandam_Int(1, 100) <= 50 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, local1) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, local2) end elseif local3 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, local1) elseif local4 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, local2) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3009, TARGET_ENE_0, AttDist, 0, 0) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_Madman_TwoSickle303020_ActAfter_AdjustSpace(arg0, arg1, arg2) return end function DungeonResident_Madman_TwoSickle303020_ActAfter_RealTime(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(0, 1) local local3 = arg0:GetRandam_Float(1, 2) local local4 = arg0:GetRandam_Float(2, 4) if local0 <= 1.5 then if local1 <= 15 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 5.5) end elseif local0 <= 2.5 then if local1 <= 15 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 700, TARGET_ENE_0, 0, AI_DIR_TYPE_F, 5.5) elseif local1 <= 30 then arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 4, TARGET_ENE_0, true, -1) arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) elseif local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) end elseif local0 <= 4 then if local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, local3, TARGET_ENE_0, 6, TARGET_ENE_0, true, -1) arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) elseif local1 <= 80 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) end elseif local0 <= 6.5 then if local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) elseif local1 <= 80 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 4.5, TARGET_SELF, true, -1) end elseif local0 <= 10 then if local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local4, TARGET_ENE_0, local2, arg0:GetRandam_Int(45, 60), true, true, -1) elseif local1 <= 80 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 6.5, TARGET_SELF, true, -1) end else arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 10, TARGET_ENE_0, 8, TARGET_SELF, true, -1) end return end function DungeonResident_Madman_TwoSickle303020Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function DungeonResident_Madman_TwoSickle303020Battle_Terminate(arg0, arg1) return end local0 = local5 local0 = local7 function DungeonResident_Madman_TwoSickle303020Battle_Interupt(arg0, arg1) if arg0:IsLadderAct(TARGET_SELF) then return false end local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetHpRate(TARGET_SELF) if Damaged_Act(arg0, arg1, 3, 30) then if local0 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, UPVAL1, 0) else DungeonResident_Madman_TwoSickle303020_Act03(arg0, arg1, paramTbl) end return true elseif arg0:IsInterupt(INTERUPT_Inside_ObserveArea) and local0 <= 40 and arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 120) then if arg0:IsInsideObserve(0) then arg1:ClearSubGoal() arg0:DeleteObserve(0) DungeonResident_Madman_TwoSickle303020_Act05(arg0, arg1, paramTbl) return true end arg0:Replaning() else return false end end return
Variable = class() function Variable:GetValue() return -1; end function Variable:GetMinValue() return 0; end function Variable:GetMaxValue() return -1; end function Variable:OnActivate(variableId) --Debug.Log(variableId); --if( self.VariableRequestBusHandler == nil ) then -- self.VariableRequestBusHandler = VariableRequestBus.Connect(self,variableId) --end --unit.entityId = self.entityId; end function Variable:OnDeactivate() Debug.Log("Variable OnDeactivate()"); if( self.VariableRequestBusHandler ~= nil ) then self.VariableRequestBusHandler:Disconnect(); self.VariableRequestBusHandler=nil; end --unit.entityId = self.entityId; end function Variable:GetId() return self.entityId; end
----------------------------------- -- -- Zone: Ship bound for Selbina Pirates (227) -- ----------------------------------- local ID = require("scripts/zones/Ship_bound_for_Selbina_Pirates/IDs") require("scripts/globals/zone") ----------------------------------- function onInitialize(zone) end function onZoneIn(player,prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then local position = math.random(-2, 2) + 0.150 player:setPos(position, -2.100, 3.250, 64) end return cs end function onTransportEvent(player,transport) player:startEvent(255) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 255 then player:setPos(0, 0, 0, 0, tpz.zone.SELBINA) end end
return { joiner_marker = '■', joiner_marker_substitute = '■', feat_marker = '│', feat_marker_substitute = '│' }
local hop = Instance.new("HopperBin") script.Parent = hop for i, v in pairs(game:service("Players").LocalPlayer.Backpack:children()) do if v.className == "HopperBin" and v.Name == "Spanner" then v:remove() end end bin = Instance.new("HopperBin") bin.Name = "Spanner" bin.Parent = game:service("Players").LocalPlayer.Backpack local players = game:service("Players") local character = players.LocalPlayer.Character local char = players.LocalPlayer.Character local Torsoz = char:findFirstChild("Torso") local RA = char:findFirstChild("Right Arm") local LA = char:findFirstChild("Left Arm") local RL = char:findFirstChild("Right Leg") local LL = char:findFirstChild("Left Leg") local H = char:findFirstChild("Head") local Hum = char:findFirstChild("Humanoid") local RS = Torsoz:findFirstChild("Right Shoulder") local LS = Torsoz:findFirstChild("Left Shoulder") local RH = Torsoz:findFirstChild("Right Hip") local LH = Torsoz:findFirstChild("Left Hip") local N = Torsoz:findFirstChild("Neck") local GuiTable = {} local Spanner local Crowbar local Joint1 local TurretGui local HealthPackGui local SmokeGenGui local TypeGui local ModeGui local WorkNum = 0 local Turrets = {} local MaxTurrets = 3 local HealthPacks = {} local MaxHealthPacks = 3 local SmokeGens = {} local MaxSmokeGens = 3 local SpannerModes = {"Turret", "Health Pack", "Smoke Gen"} local CrowbarModes = {"Smack", "Destroy"} local ModeNum = 1 local Animating = false local Building = false local Mode = "Turret" local Type = "Spanner" function Stats() for i, v in pairs(char:children()) do if v.className == "Model" and v.Name == "Stats" then v:remove() end end local m = Instance.new("Model", char) m.Name = "Stats" local team = Instance.new("StringValue", m) team.Name = "Team" team.Value = "Deep blue" end Stats() function GUI(ins) if ins == "Hide" then for i, v in pairs(players.LocalPlayer.PlayerGui:children()) do if v.className == "ScreenGui" and v.Name == "StatsGui" then v:remove() end end elseif ins == "Show" then GuiTable = {} for i, v in pairs(players.LocalPlayer.PlayerGui:children()) do if v.className == "ScreenGui" and v.Name == "StatsGui" then v:remove() end end local g = Instance.new("ScreenGui", players.LocalPlayer.PlayerGui) g.Name = "StatsGui" local f = Instance.new("Frame", g) f.Position = UDim2.new(0.375,0,0,0) f.Size = UDim2.new(0.25,0,0.15,0) f.BackgroundColor3 = Color3.new(0,0,0) f.BorderColor = BrickColor.new(char.Stats.Team.Value) table.insert(GuiTable, f) for i = 0, 2 do local f2 = Instance.new("Frame", f) f2.Name = "Frame"..i+1 f2.Position = UDim2.new((1/3)*i,0,0,0) f2.Size = UDim2.new(1/3,0,0.5,0) f2.BackgroundColor3 = Color3.new(0,0,0) f2.BorderColor = BrickColor.new(char.Stats.Team.Value) table.insert(GuiTable, f2) end for i = 0, 2 do local t = Instance.new("TextLabel", f:findFirstChild("Frame"..i+1)) t.Size = UDim2.new(0.5,0,1,0) t.Position = UDim2.new(0.5,0,0,0) t.BackgroundColor3 = Color3.new(0,0,0) t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.TextColor3 = Color3.new(0.8,0.8,0.8) t.TextStrokeColor3 = BrickColor.new(char.Stats.Team.Value).Color t.TextStrokeTransparency = 0 t.Text = i t.Font = 2 t.FontSize = 6 table.insert(GuiTable, t) local f3 = Instance.new("Frame", f:findFirstChild("Frame"..i+1)) f3.Size = UDim2.new(0.5,0,1,0) f3.BackgroundColor3 = Color3.new(0,0,0) f3.BorderColor = BrickColor.new(char.Stats.Team.Value) table.insert(GuiTable, f3) local im = Instance.new("ImageLabel", f3) im.Size = UDim2.new(0.8,0,0.75,0) im.Position = UDim2.new(0.1,0,0.1,0) im.BorderSizePixel = 0 im.BackgroundColor3 = Color3.new(0,0,0) im.BorderColor = BrickColor.new(char.Stats.Team.Value) table.insert(GuiTable, im) if i == 0 then TurretGui = t im.Image = "http://www.roblox.com/asset/?id=92010919" t.Text = #Turrets.."/"..MaxTurrets elseif i == 1 then HealthPackGui = t im.Image = "http://www.roblox.com/asset/?id=92009935" --- new: 92009935 --- old: 51393782 t.Text = #HealthPacks.."/"..MaxHealthPacks elseif i == 2 then SmokeGenGui = t im.Image = "http://www.roblox.com/asset/?id=30512117" --- round smoke: 31727915 --- blue smoke: 30512117 --- red smoke: 4571186 t.Text = #SmokeGens.."/"..MaxSmokeGens end local t2 = t:Clone() t2.Parent = t.Parent t2.Text = "=" t2.Position = UDim2.new(0,0,0,0) t2.Size = UDim2.new(1,0,1,0) t2.BackgroundTransparency = 1 table.insert(GuiTable, t2) end for i = 0, 1 do local t = Instance.new("TextLabel", f) t.Size = UDim2.new(0.5,0,0.5,0) t.Position = UDim2.new(0.5*i,0,0.5,0) t.BackgroundColor3 = Color3.new(0,0,0) t.BackgroundTransparency = 1 t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.TextColor3 = Color3.new(0.8,0.8,0.8) t.TextStrokeColor3 = BrickColor.new(char.Stats.Team.Value).Color t.TextStrokeTransparency = 0 t.BorderSizePixel = 0 if i == 0 then t.Text = "Type: "..Type TypeGui = t else t.Text = "Mode: "..Mode ModeGui = t end t.Font = 2 t.FontSize = 5 table.insert(GuiTable, t) end for i = 0, 1 do local t = Instance.new("TextLabel", f) t.Size = UDim2.new(1,0,0.25,0) t.Position = UDim2.new(0,0,0.5+(0.25*i),0) t.BackgroundColor3 = Color3.new(0,0,0) t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.TextColor3 = Color3.new(0.8,0.8,0.8) t.TextStrokeColor3 = BrickColor.new(char.Stats.Team.Value).Color t.TextStrokeTransparency = 0 t.BackgroundTransparency = 1 if i == 0 then t.Text = [[/\]] else t.Text = [[\/]] end t.Font = 2 t.FontSize = 6 table.insert(GuiTable, t) end local t = Instance.new("TextLabel", f) t.Size = UDim2.new(1,0,0.25,0) t.Position = UDim2.new(0,0,1,0) t.BackgroundColor3 = Color3.new(0,0,0) t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.BackgroundTransparency = 0 t.Text = "" table.insert(GuiTable, t) local t = Instance.new("TextLabel", f) t.Size = UDim2.new(0,0,0.125,0) t.Position = UDim2.new(0,0,1+(0.125/2),0) t.BackgroundColor3 = Color3.new(0,0.75,0.1) t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.BackgroundTransparency = 0 t.Text = "" CentGui = t table.insert(GuiTable, t) local t = Instance.new("TextLabel", f) t.Size = UDim2.new(1,0,0.25,0) t.Position = UDim2.new(0,0,1,0) t.BackgroundColor3 = Color3.new(0,0,0) t.BorderColor = BrickColor.new(char.Stats.Team.Value) t.TextColor3 = Color3.new(0.8,0.8,0.8) t.TextStrokeColor3 = BrickColor.new(char.Stats.Team.Value).Color t.TextStrokeTransparency = 0 t.BackgroundTransparency = 1 t.Font = 2 t.FontSize = 5 t.Text = "" CentGuiText = t table.insert(GuiTable, t) end end function Part(parent, name, colour, anc, col, size, ptype) name = name or "Part" colour = colour or "Medium stone grey" anc = anc or false col = col or false size = size or Vector3.new(0.5,0.5,0.5) ptype = ptype or "Part" local P if ptype == "Part" then P = Instance.new("Part", parent) P.formFactor = "Custom" elseif ptype == "CornerWedgePart" then P = Instance.new("CornerWedgePart", parent) end P.Anchored = anc P.CanCollide = col P.Name = name P.Size = size P.Locked = true P.TopSurface = 0 P.BottomSurface = 0 P.BrickColor = BrickColor.new(colour) return P end function Weld(par, p0, p1, c0, c1) c0 = c0 or CFrame.new(0,0,0) c1 = c1 or CFrame.new(0,0,0) local W = Instance.new("Motor", par) W.Part0 = p0 W.Part1 = p1 W.C0 = c0 W.C1 = c1 return W end function Build(team) for i, v in pairs(char:children()) do if v.className == "Model" and v.Name == "TeamSuit" then v:remove() end end local mdl = Instance.new("Model", char) mdl.Name = "TeamSuit" team = team or "Black" local p = Part(mdl, "Belt", "Brown") local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(4.5,0.8,2.5) Weld(p, Torsoz, p, CFrame.new(0,-1,0)) local p = Part(mdl, "Strap", "Brown") local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(5.7,0.8,2.5) Weld(p, Torsoz, p, CFrame.new(0,0,0) * CFrame.Angles(0,0,math.pi/4)) local p = Part(mdl, "Strap", "Brown") local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(5.7,0.8,2.5) Weld(p, Torsoz, p, CFrame.new(0,0,0) * CFrame.Angles(0,0,-math.pi/4)) local p = Part(mdl, "TBelt", team) local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(4.2,0.35,2.55) Weld(p, Torsoz, p, CFrame.new(0,-1,0)) local p = Part(mdl, "TStrap", team) local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(5.6,0.35,2.55) Weld(p, Torsoz, p, CFrame.new(-0.03,-0.03,0) * CFrame.Angles(0,0,math.pi/4)) local p = Part(mdl, "TStrap", team) local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(5.6,0.35,2.55) Weld(p, Torsoz, p, CFrame.new(0.03,-0.03,0) * CFrame.Angles(0,0,-math.pi/4)) local p = Part(mdl, "Buckle", "Black") local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(1.75,0.85,0.58) Weld(p, Torsoz, p, CFrame.new(0,-1,-0.5)) ---------------------------------------------------------------------------------------------- ----------------------------------- LIMBS ------------------------------------------------- ---------------------------------------------------------------------------------------------- ------ Torso ------ local p = Part(mdl, "TorsoTC", team) local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(4.05,4.05,2.05) Weld(p, Torsoz, p, CFrame.new(0,0,0)) ---------------------------------------------------------------------------------------------- ----------------------------------- TOOLS ------------------------------------------------- ---------------------------------------------------------------------------------------------- local p = Part(mdl, "Spanner") local mesh = Instance.new("SpecialMesh", p) mesh.MeshId = "http://www.roblox.com/asset/?id=16884681" mesh.TextureId = "http://www.roblox.com/asset/?id=16884673" mesh.Scale = Vector3.new(0.6,0.6,0.6) Weld(p, Torsoz, p, CFrame.new(1.06,-1.15,0) * CFrame.Angles(math.pi/4,0,0)) Spanner = p local p = Part(mdl, "Crowbar") local mesh = Instance.new("SpecialMesh", p) mesh.MeshId = "http://www.roblox.com/asset/?id=21426303" mesh.TextureId = "http://www.roblox.com/asset/?id=8953043" mesh.Scale = Vector3.new(0.6,0.6,0.6) Weld(p, Torsoz, p, CFrame.new(0,-0.3,0.5) * CFrame.Angles(math.pi/2,math.pi-0.4,0)) Crowbar = p ---------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------- Torsoz.Transparency = 0 RA.Transparency = Torsoz.Transparency LA.Transparency = Torsoz.Transparency RL.Transparency = Torsoz.Transparency LL.Transparency = Torsoz.Transparency H.Transparency = Torsoz.Transparency end Build(char.Stats.Team.Value) function UpdateGui() TypeGui.Text = "Type: "..Type ModeGui.Text = "Mode: "..Mode TurretGui.Text = #Turrets.."/"..MaxTurrets HealthPackGui.Text = #HealthPacks.."/"..MaxHealthPacks SmokeGenGui.Text = #SmokeGens.."/"..MaxSmokeGens end function Stand() Joint1.DesiredAngle = 0.7 Spanner.Motor.C0 = CFrame.new(15/13,-1.5+(15/30),0) * CFrame.Angles(0,math.pi/2,0) * CFrame.Angles((math.pi/1.5)-(15/7),0,0) * CFrame.new(0,0,-0.7) Hum.PlatformStand = false Hum.WalkSpeed = 16 for i, v in pairs(Torsoz:children()) do if v.className == "Motor" and (v.Name == "RightBottom" or v.Name == "LeftBottom" or v.Name == "LeftTop") then v:remove() elseif v.Name == "CrouchBGP" and (v.className == "BodyPosition" or v.className == "BodyGyro") then v:remove() end end RH.Part0 = Torsoz RH.Part1 = RL RH.Parent = Torsoz LH.Part0 = Torsoz LH.Part1 = LL LH.Parent = Torsoz LS.Part0 = Torsoz LS.Part1 = LA LS.Parent = Torsoz Animating = false end function CrouchToBuild(mouse) Animating = true Hum.WalkSpeed = 0 Hum.PlatformStand = true RH.Part0 = nil LH.Part0 = nil LS.Part0 = nil local joint3 = Instance.new("Motor", Torsoz) joint3.Name = "RightBottom" joint3.Part0 = Torsoz joint3.Part1 = RL joint3.C0 = CFrame.new(0.5,-1.3,0.7) * CFrame.Angles((math.pi/2)+0.25,0,0) local joint4 = Instance.new("Motor", Torsoz) joint4.Name = "LeftBottom" joint4.Part0 = Torsoz joint4.Part1 = LL joint4.C0 = CFrame.new(-0.5,-0.7,-0.8) * CFrame.Angles(0.4,0,0) local joint2 = Instance.new("Motor", Torsoz) joint2.Name = "LeftTop" joint2.Part0 = Torsoz joint2.Part1 = LA joint2.C0 = CFrame.new(-1.3,0,-0.5) * CFrame.Angles(0.8,0,0.22) local bp = Instance.new("BodyPosition", Torsoz) bp.Name = "CrouchBGP" bp.maxForce = Vector3.new(1/0,1/0,1/0) bp.position = Torsoz.Position + Vector3.new(0,-1.3,0) local bg = Instance.new("BodyGyro", Torsoz) bg.maxTorque = Vector3.new(1/0,1/0,1/0) bg.Name = "CrouchBGP" bg.D = 100 bg.cframe = CFrame.new(Torsoz.Position, Vector3.new(mouse.Hit.x,Torsoz.Position.y,mouse.Hit.z)) * CFrame.Angles(-0.25,0,0) Spanner.Motor.C0 = Spanner.Motor.C0 * CFrame.new(0.3,-0.3,0.3) * CFrame.Angles(math.pi/6,0.3,0) Joint1.DesiredAngle = 0.9 end function BuildHealthPack(mouse, enz) local WNum = WorkNum CrouchToBuild(mouse) local mo = Instance.new("Model", char.Stats) mo.Name = "HealthPack" local posi = CFrame.new(Torsoz.Position, Vector3.new(mouse.Hit.x,Torsoz.Position.y,mouse.Hit.z)) local Main = Part(mo, "BlackCircleSpawnerPoint", "Really black", true) Main.CFrame = CFrame.new(Torsoz.Position.x,enz.y,Torsoz.Position.z) + posi.lookVector*4.5 local mesh = Instance.new("CylinderMesh", Main) mesh.Scale = Vector3.new(8,0.3,8) wait(0.3) local Count = 0 local p = Part(mo, "Center", "Black", true, false, Vector3.new(2,1.2,2.6)) p.CFrame = Main.CFrame p.Transparency = 1 local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(0,0,0) for i = 1, 20 do if WNum ~= WorkNum then break end mesh.Scale = mesh.Scale + Vector3.new(0.05,0.05,0.05) p.CFrame = p.CFrame + Vector3.new(0,0.1,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/80),0,0.125,0) CentGuiText.Text = math.floor((Count/80*100)) .. "%" wait(0.017) end p.Transparency = 0 local p2 = Part(mo, "Side1", char.Stats.Team.Value, true, false, Vector3.new(2.2,1.4,0.5)) p2.CFrame = p.CFrame p2.Transparency = 1 local mesh = Instance.new("SpecialMesh", p2) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(0,0.5,0) for i = 1, 20 do if WNum ~= WorkNum then break end mesh.Scale = mesh.Scale + Vector3.new(0.05,0.025,0.05) p2.CFrame = p2.CFrame + Vector3.new(0,0,0.04) p2.Transparency = p2.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/80),0,0.125,0) CentGuiText.Text = math.floor((Count/80*100)) .. "%" wait(0.017) end p2.Transparency = 0 local p2 = Part(mo, "Side2", char.Stats.Team.Value, true, false, Vector3.new(2.2,1.4,0.5)) p2.CFrame = p.CFrame p2.Transparency = 1 local mesh = Instance.new("SpecialMesh", p2) mesh.MeshType = "Brick" mesh.Scale = Vector3.new(0,0.5,0) for i = 1, 20 do if WNum ~= WorkNum then break end mesh.Scale = mesh.Scale + Vector3.new(0.05,0.025,0.05) p2.CFrame = p2.CFrame + Vector3.new(0,0,-0.04) p2.Transparency = p2.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/80),0,0.125,0) CentGuiText.Text = math.floor((Count/80*100)) .. "%" wait(0.017) end p2.Transparency = 0 local d = Instance.new("Decal", p) d.Face = "Top" d.Texture = "http://www.roblox.com/asset/?id=92009935" d.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end d.Transparency = d.Transparency - 0.04 Count = Count + 1 CentGui.Size = UDim2.new((Count/80),0,0.125,0) CentGuiText.Text = math.floor((Count/80*100)) .. "%" wait(0.017) end if Count == 80 then table.insert(HealthPacks, mo) HealthPackGui.TextStrokeColor3 = Color3.new(0,1,0) HealthPackGui.TextColor = BrickColor.new("Really black") else mo:remove() end Stand() CentGui.Size = UDim2.new(0,0,0.125,0) CentGuiText.Text = "" UpdateGui() Main:remove() end function UpdateHealthBox(box) local center = box:findFirstChild("Center") local side1 = box:findFirstChild("Side1") local side2 = box:findFirstChild("Side2") center.CFrame = center.CFrame * CFrame.Angles(0,(math.pi*2)/90,0) side1.CFrame = center.CFrame * CFrame.new(0,0,0.04*20) side2.CFrame = center.CFrame * CFrame.new(0,0,-0.04*20) end function BuildSmokeGen(mouse, enz) local WNum = WorkNum CrouchToBuild(mouse) local mo = Instance.new("Model", char.Stats) mo.Name = "SmokeGen" local posi = CFrame.new(Torsoz.Position, Vector3.new(mouse.Hit.x,Torsoz.Position.y,mouse.Hit.z)) local Main = Part(mo, "BlackCircleSpawnerPoint", "Really black", true) Main.CFrame = CFrame.new(Torsoz.Position.x,enz.y,Torsoz.Position.z) + posi.lookVector*5.75 local mesh = Instance.new("CylinderMesh", Main) mesh.Scale = Vector3.new(13.2,0.3,13.2) wait(0.3) local Count = 0 local p = Part(mo, "Center", "Black", true, false, Vector3.new(2.2,2.2,2.2)) p.CFrame = Main.CFrame p.Shape = "Ball" p.Transparency = 1 local mesh = Instance.new("SpecialMesh", p) mesh.MeshType = "Sphere" mesh.Scale = Vector3.new(0,0,0) local s = Instance.new("Smoke", p) s.Enabled = false s.Color = BrickColor.new(char.Stats.Team.Value).Color s.Size = 13 for i = 1, 20 do if WNum ~= WorkNum then break end mesh.Scale = mesh.Scale + Vector3.new(0.05,0.05,0.05) p.CFrame = p.CFrame + Vector3.new(0,0.21,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 p.CFrame = Main.CFrame + Vector3.new(0,5.45,0) local p = Part(mo, "Corner1", "Black", true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(-0.05,0.4,0.05) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner2", char.Stats.Team.Value, true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(0,0.4,0.075) p.CFrame = p.CFrame * CFrame.Angles(0,(math.pi/4)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner3", "Black", true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(0.05,0.4,0.05) p.CFrame = p.CFrame * CFrame.Angles(0,(math.pi/2)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner4", char.Stats.Team.Value, true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(0.075,0.4,0) p.CFrame = p.CFrame * CFrame.Angles(0,(math.pi*0.75)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner5", "Black", true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(0.05,0.4,-0.05) p.CFrame = p.CFrame * CFrame.Angles(0,math.pi/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner6", char.Stats.Team.Value, true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(0,0.4,-0.075) p.CFrame = p.CFrame * CFrame.Angles(0,(math.pi*1.25)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner7", "Black", true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(-0.05,0.4,-0.05) p.CFrame = p.CFrame * CFrame.Angles(0,-(math.pi/2)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 local p = Part(mo, "Corner8", char.Stats.Team.Value, true, false, Vector3.new(2,8,2), "CornerWedgePart") p.CFrame = Main.CFrame + Vector3.new(0,-4,0) p.Transparency = 1 for i = 1, 20 do if WNum ~= WorkNum then break end p.CFrame = p.CFrame + Vector3.new(-0.075,0.4,0) p.CFrame = p.CFrame * CFrame.Angles(0,(-math.pi/4)/20,0) p.Transparency = p.Transparency - 0.05 Count = Count + 1 CentGui.Size = UDim2.new((Count/180),0,0.125,0) CentGuiText.Text = math.floor((Count/180*100)) .. "%" wait(0.012) end p.Transparency = 0 s.Enabled = true if Count == 180 then table.insert(SmokeGens, mo) SmokeGenGui.TextStrokeColor3 = Color3.new(0,1,0) SmokeGenGui.TextColor = BrickColor.new("Really black") else mo:remove() end Stand() CentGui.Size = UDim2.new(0,0,0.125,0) CentGuiText.Text = "" UpdateGui() Main:remove() end function onButton1Down(mouse) if Building == false and Animating == false then if Type == "Spanner" then WorkNum = math.random() local ray = Ray.new(Torsoz.Position, CFrame.new(Torsoz.Position, Torsoz.Position+Vector3.new(0,-1,0)).lookVector*4) local hitz, enz = workspace:FindPartOnRay(ray, char) if hitz ~= nil then if Mode == "Turret" then --BuildTurret() elseif Mode == "Health Pack" then if #HealthPacks < MaxHealthPacks then BuildHealthPack(mouse, enz) end elseif Mode == "Smoke Gen" then if #SmokeGens < MaxSmokeGens then BuildSmokeGen(mouse, enz) end end end elseif Type == "Crowbar" then if Mode == "Smack" then --CrowbarSmack() elseif Mode == "Destroy" then end end end end function onButton1Up() WorkNum = math.random() end function onKeyDown(key, mouse) if key ~= nil then key:lower() if key == "e" then if Animating == false then Unequip() if Type == "Spanner" then Type = "Crowbar" ModeNum = 1 Mode = CrowbarModes[ModeNum] else Type = "Spanner" ModeNum = 1 Mode = SpannerModes[ModeNum] end TypeGui.TextStrokeColor3 = Color3.new(0,1,0) TypeGui.TextColor = BrickColor.new("Really black") ModeGui.TextStrokeColor3 = Color3.new(0,1,0) ModeGui.TextColor = BrickColor.new("Really black") UpdateGui() Equip() end elseif key == "q" then if Animating == false then ModeNum = ModeNum + 1 if Type == "Spanner" then if ModeNum > #SpannerModes then ModeNum = 1 end Mode = SpannerModes[ModeNum] elseif Type == "Crowbar" then if ModeNum > #CrowbarModes then ModeNum = 1 end Mode = CrowbarModes[ModeNum] end ModeGui.TextStrokeColor3 = Color3.new(0,1,0) ModeGui.TextColor = BrickColor.new("Really black") UpdateGui() end elseif key == "z" then UpdateGui() end end end function Equip() Animating = true if Type == "Spanner" then RS.Part0 = nil local joint = Instance.new("Motor", Torsoz) joint.Name = "RightTop" joint.Part0 = Torsoz joint.Part1 = RA joint.C1 = CFrame.new(0,0.5,0) Joint1 = joint Spanner.Motor.Part0 = RA Spanner.Motor.C0 = CFrame.new(0,-1.6,0) * CFrame.Angles(0,math.pi/2,0) * CFrame.Angles(math.pi/3,0,0) joint.C0 = CFrame.new(1.5,0.5,0) * CFrame.Angles(0,math.pi/2,0) joint.MaxVelocity = 0.08 joint.DesiredAngle = -0.3 wait(0.15) Spanner.Motor.C0 = CFrame.new(0,-1.6,0) * CFrame.Angles(0,math.pi/2,0) * CFrame.Angles(math.pi/1.5,0,0) joint.DesiredAngle = 0.7 wait(0.3) for i = 1, 15 do Spanner.Motor.C0 = CFrame.new((i/13),-1.5+(i/30),0) * CFrame.Angles(0,math.pi/2,0) * CFrame.Angles((math.pi/1.5)-(i/7),0,0) wait(0.012) end for i = 1, 7 do Spanner.Motor.C0 = Spanner.Motor.C0 * CFrame.new(0,0,-0.1) wait(0.015) end elseif Type == "Crowbar" then RS.Part0 = nil local joint = Instance.new("Motor", Torsoz) joint.Name = "RightTop" joint.Part0 = Torsoz joint.Part1 = RA joint.C1 = CFrame.new(0,0.5,0) joint.C0 = CFrame.new(1.5,0.5,0) * CFrame.Angles(0,math.pi/2,0) Joint1 = joint joint.MaxVelocity = 0.3 joint.DesiredAngle = math.pi+0.2 wait(0.38) Crowbar.Motor.Part0 = RA Crowbar.Motor.C0 = CFrame.new(0,-1,0) joint.MaxVelocity = 0.14 joint.DesiredAngle = 0.9 for i = 1, 20 do Crowbar.Motor.C0 = CFrame.new(0,-1,0) * CFrame.Angles(0,-((math.pi*4.5)/20)*i,0) wait(0.017) end Crowbar.Motor.C0 = CFrame.new(0,-1.14,0) * CFrame.Angles(math.pi/2,0,0) * CFrame.Angles(0,(math.pi/1.75),0) end Animating = false end function Unequip() Animating = true if Type == "Spanner" then for i = 1, 7 do Spanner.Motor.C0 = Spanner.Motor.C0 * CFrame.new(0,0,0.1) wait(0.015) end Joint1.MaxVelocity = 0.08 Joint1.DesiredAngle = -0.3 for i = 1, 15 do Spanner.Motor.C0 = CFrame.new((15/13)-(i/13), -1 -(i/30),0) * CFrame.Angles(0,math.pi/2,0) * CFrame.Angles(((math.pi/1.5)-(15/7))+(i/7),0,0) wait(0.012) end Spanner.Motor.Part0 = Torsoz Spanner.Motor.C0 = CFrame.new(1.06,-1.15,0) * CFrame.Angles(math.pi/4,0,0) elseif Type == "Crowbar" then Joint1.MaxVelocity = 0.14 Joint1.DesiredAngle = math.pi+0.2 for i = 1, 20 do Crowbar.Motor.C0 = CFrame.new(0,-1,0) * CFrame.Angles(0,((math.pi*4.5)/20)*i,0) wait(0.017) end Crowbar.Motor.Part0 = Torsoz Crowbar.Motor.C0 = CFrame.new(0,-0.3,0.5) * CFrame.Angles(math.pi/2,math.pi-0.4,0) Joint1.MaxVelocity = 0.28 Joint1.DesiredAngle = 0 wait(0.4) end for i, v in pairs(Torsoz:children()) do if v.className == "Motor" and v.Name == "RightTop" then v:remove() end end RS.Part0 = Torsoz RS.Part1 = RA RS.Parent = Torsoz Animating = false end bin.Selected:connect(function(mouse) mouse.Icon = "rbxasset://textures\\GunCursor.png" mouse.Button1Down:connect(function() onButton1Down(mouse) end) mouse.Button1Up:connect(function() onButton1Up() end) mouse.KeyDown:connect(function(key) onKeyDown(key, mouse) end) GUI("Show") if Animating == true then while Animating == true do wait() end end Equip() if players.LocalPlayer.PlayerGui:findFirstChild("StatsGui") == nil then GUI("Show") end end) bin.Deselected:connect(function() if Animating == true then while Animating == true do wait() end end Unequip() Stand() Build(char.Stats.Team.Value) GUI("Hide") end) local NUUUM = 0 while true do for i, v in pairs(HealthPacks) do if v.className == "Model" then UpdateHealthBox(v) if v:findFirstChild("Center") ~= nil then for _, vv in pairs(workspace:children()) do if vv:findFirstChild("Stats") ~= nil and vv:findFirstChild("Humanoid") ~= nil and vv:findFirstChild("Torso") ~= nil then if (v:findFirstChild("Center").Position - vv:findFirstChild("Torso").Position).magnitude < 2.3 then if vv:findFirstChild("Stats").Team.Value == char:findFirstChild("Stats").Team.Value then v:remove() table.remove(HealthPacks, i) vv:findFirstChild("Humanoid").Health = vv:findFirstChild("Humanoid").Health + 28 break end end end end UpdateGui() end end end if NUUUM%12 == 0 then for i, v in pairs(GuiTable) do if v.className == "TextLabel" or v.className == "TextButton" then v.TextStrokeColor3 = BrickColor.new(char.Stats.Team.Value).Color v.TextColor = BrickColor.new("White") end end end NUUUM = NUUUM + 1 wait(0.03) end --mediafire gtfo password
--[[----------------------------------------------------------------------- * | Copyright (C) Shaobo Wan (Tinywan) * |------------------------------------------------------------------------ * | Author: Tinywan * | Date Time : 2019/5/28 16:25 * | Email: Overcome.wan@Gmail.com * |------------------------------------------------------------------------ --]] -- redis config local redis = require "resty.redis" local red = redis:new() -- 容器内部 -- local ok, err = red:connect("172.19.0.2", 6379) local ok, err = red:connect("dnmp-redis-v2", 6379) -- 通过宿主机链接 -- local ok, err = red:connect("172.19.0.1", 6379) -- local ok, err = red:connect("dnmp-redis-v1", 6379) if not ok then ngx.say("failed to connect1: ", err) return end ok, err = red:set("dog", "an animal1") if not ok then ngx.say("failed to set dog: ", err) return end ngx.say("set result: ", ok) local res, err = red:get("dog") if not res then ngx.say("failed to get dog: ", err) return end if res == ngx.null then ngx.say("dog not found.") return end ngx.say("dog: ", res)
return { id = "FUYINGYINGHUA3", mode = 2, once = true, fadeType = 1, fadein = 1.5, scripts = { { expression = 4, side = 2, actor = 306070, nameColor = "#a9f548", dir = 1, say = "诸位,请留步。", bgm = "story-4", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, nameColor = "#a9f548", dir = 1, say = "哦?迎接的人是{namecode:179}么?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 5, nameColor = "#a9f548", side = 2, actor = 306070, dir = 1, say = "好久不见,{namecode:91}大人,{namecode:92}大人。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307020, side = 2, nameColor = "#a9f548", dir = 1, say = "天宇启户祭的规矩我们都明白。寒暄一会再说,按流程开始演武吧,代主祭。", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307010, side = 2, nameColor = "#a9f548", dir = 1, say = "呵呵,一上来就是主菜吗?{namecode:179}可比看起来难对付很多,大家不要轻敌哦~", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 4, nameColor = "#a9f548", side = 2, actor = 306070, dir = 1, say = "…向神明展现勇武,向神明纳奉才智,向神明给予信仰!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { expression = 4, nameColor = "#a9f548", side = 2, actor = 306070, dir = 1, say = "{namecode:179}号航空母舰,参上!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } } } }
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' description 'ESX Borrmaskin' server_scripts { 'server/main.lua' } client_scripts { 'client/main.lua' }
VIRUS.Name = "Malaria" VIRUS.Chance = 60 VIRUS.Infectious = true VIRUS.Nausea = true VIRUS.Vomiting = true VIRUS.Diarrhea = true VIRUS.Weakness = true VIRUS.Cold = true
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/blues_pharm/book.mdl") self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local physics = self:GetPhysicsObject() if (physics:IsValid()) then physics:Wake() end self:SetUseType(SIMPLE_USE) --Stores the next CurTime that they can reset angles to prevent spam self.angleResetCooldown = 0 --Allow destuction self:SetHealth(25) end function ENT:Use(act, caller) --Shift + E = Upright if caller:KeyDown(IN_SPEED) and self.angleResetCooldown < CurTime() then self:SetAngles(Angle(0,caller:GetAngles().y + 180,0)) self.angleResetCooldown = CurTime() + 1 self:GetPhysicsObject():Wake() else net.Start("BLUES_PHARMA_OPEN_BOOK") net.Send(caller) end end
local map = vim.api.nvim_set_keymap map('n', '<Space>cf', '<cmd>Clap files<cr>', { noremap = true, silent = true }) map('n', '<Space>cg', '<cmd>Clap grep<cr>', { noremap = true, silent = true }) map('n', '<Space>cd', '<cmd>Clap grep ++query=<cword><cr>', { noremap = true, silent = true }) map('n', '<Space>cb', '<cmd>Clap buffers<cr>', { noremap = true, silent = true })
-- -- Copyright (c) 2005 Pandemic Studios, LLC. All rights reserved. -- -- Code, data for a expandable (horizontally) titlebar -- -- Broken off from interface_util.lua for better encapsulation -- fnSetSize for a TitleBar's Skin. Pulled out so its -- implementation could be properly shared (refcounted) among all -- instances. Bugs: 32x32 is the smallest size possible function TitleBarSkin_fnSetSize(this,w,h) -- Massive duplication. Sorry. :( local x1 = (w * -0.5) local x2 = x1 + 64 local x3 = (w * 0.5) - 32 local x4 = x3 + 32 IFImage_fnSetTexturePos(this.ChunkL ,x1 ,-16,x2+1,16) IFImage_fnSetTexturePos(this.ChunkC ,x2-1,-16,x3,16) -- slightly overlap to avoid gap IFImage_fnSetTexturePos(this.ChunkR ,x3 ,-16,x4,16) end -- fnSelect for a TitleBar's Skin. Pulled out so its -- implementation could be properly shared (refcounted) among all -- instances function TitleBarSkin_fnSelect(this,NewTexture,NewAlpha) IFImage_fnSetTexture(this.ChunkL,NewTexture,NewAlpha) IFImage_fnSetTexture(this.ChunkC,NewTexture,NewAlpha) IFImage_fnSetTexture(this.ChunkR,NewTexture,NewAlpha) end -- fnSetSize for a TitleBar's Label. Pulled out so its -- implementation could be properly shared (refcounted) among all -- instances function TitleBarLabel_fnSetSize(this,w,h) this.label.x = w * -0.5 this.label.y = h * -0.5 this.label.textw = w this.label.texth = h end function TitleBarLabel_fnSetString(this,str) IFText_fnSetString(this.labels.label,str) end function TitleBarLabel_fnSetUString(this,str) IFText_fnSetUString(this.labels.label,str) end function TitleBarLabel_fnHilight(this,on,fDt,w,h) if(on) then -- gButton_CurSizeAdd = gButton_CurSizeAdd + fDt * gButton_CurDir -- if(gButton_CurSizeAdd > 1) then -- gButton_CurSizeAdd = 1 -- gButton_CurDir = -math.abs(gButton_CurDir) -- elseif (gButton_CurSizeAdd < 0.3) then -- gButton_CurSizeAdd = 0.3 -- gButton_CurDir = math.abs(gButton_CurDir) -- end -- Shell has label2 background text. Game doesn't. Blink one of them IFObj_fnSetAlpha(this.label,gButton_CurSizeAdd) end end function TitleBarSkin_fnHilight(this,on,fDt,w,h) TitleBarSkin_fnSetSize(this,w,h) -- Off? Revert to standard size. end function NewIFTitleBar(Template) local temp = Template temp.skin = NewIFContainer { ZPos = 140, -- Text will be at 128 by default, be a bit behind it -- 8 chunks for the pieces of the texture. Note: no texture is specified, -- as that's done in fnSelect ChunkL = NewIFImage { texture = "titlebar_l", uvs_l = 0.0, uvs_r = 1.0, uvs_t = 0.00, uvs_b = 1.00, inert_all = 1, ZPos = 190}, ChunkC = NewIFImage { texture = "titlebar_r", uvs_l = 0.0, uvs_r = 0.5, uvs_t = 0.00, uvs_b = 1.00, inert_all = 1, ZPos = 190}, ChunkR = NewIFImage { texture = "titlebar_r", uvs_l = 0.5, uvs_r = 1.0, uvs_t = 0.00, uvs_b = 1.00, inert_all = 1, ZPos = 190}, } -- end of skin if(Template.yFlip) then temp.skin.ChunkL.uvs_t,temp.skin.ChunkL.uvs_b = temp.skin.ChunkL.uvs_b,temp.skin.ChunkL.uvs_t temp.skin.ChunkR.uvs_t,temp.skin.ChunkR.uvs_b = temp.skin.ChunkR.uvs_b,temp.skin.ChunkR.uvs_t Template.yFlip = nil end temp.labels = NewIFContainer { y = -2, label = NewIFText { valign = "vcenter", inert_all = 1, font = Template.font, -- ColorR = 255, ColorG = 255, ColorB = 255, }, -- end of label } local Width = Template.width or 200 TitleBarSkin_fnSetSize(temp.skin,Width,32) TitleBarLabel_fnSetSize(temp.labels,Width,32) if(Template.string) then TitleBarLabel_fnSetString(temp,Template.string) Template.string = nil end if(Template.ustring) then TitleBarLabel_fnSetUString(temp,Template.ustring) Template.ustring = nil end -- Make a button from this expanded template return NewIFContainer(temp) end
-------------------------------- -- @module EventKeyboard -- @extend Event -- @parent_module cc -------------------------------- -- Constructor.<br> -- param keyCode A given keycode.<br> -- param isPressed True if the key is pressed.<br> -- js ctor -- @function [parent=#EventKeyboard] EventKeyboard -- @param self -- @param #int keyCode -- @param #bool isPressed -- @return EventKeyboard#EventKeyboard self (return value: cc.EventKeyboard) return nil
local filter = EasyDestroyFilterCriteria:New("Ignore BOE Items By Quality", "boequality", 65) function filter:GetItemInfo(itemLink, bag, slot) local itemLoc = ItemLocation:CreateFromBagAndSlot(bag, slot) local isBound = C_Item.IsBound(itemLoc) return isBound end -- There's no reason a filter should show up more than once -- So we can treat it as a singleton and just use this to -- get any previous creations of the filter frame, or -- create it if it's not yet been made function filter:Initialize() -- We create the frame here, we'll leave the details on size/anchors to the Filters window. self.frame = self.frame or CreateFrame("Frame", "EDFilterSoulbound", self.parent, "EasyDestroyRarityFilter") self.frame.label:SetText( self.name ) self.frame.common:SetLabel("|c11ffffff" .. "Common" .. "|r") self.frame.rare:SetLabel("|c110070dd" .. "Rare" .. "|r") self.frame.uncommon:SetLabel("|c111eff00" .. "Uncommon" .. "|r") self.frame.epic:SetLabel("|c11a335ee" .. "Epic" .. "|r") self.frame:Hide() self.scripts.OnClick = { self.frame.common, self.frame.uncommon, self.frame.rare, self.frame.epic } end -- check input vs item values function filter:Check(inputquality, item) if filter.frame then local itemquality = item.quality local itembound = item.boequality local bindtype = item.bindtype if bindtype == LE_ITEM_BIND_ON_EQUIP then if tContains(inputquality, itemquality) and not(itembound) then return false end end end return true end function filter:Blacklist(inputquality, item) if filter.frame then local itemquality = item.quality local itembound = item.boequality local bindtype = item.bindtype if bindtype == LE_ITEM_BIND_ON_EQUIP then if tContains(inputquality, itemquality) and not(itembound) then return true end end end return false end function filter:GetRarityChecked(rarityType) rarityType = string.lower(rarityType) if self.frame then if self.frame[rarityType] then if self.frame[rarityType]:GetChecked() then return true end end return false end return nil end function filter:GetValues() if self.frame then local quality = {} for key, value in pairs(Enum.ItemQuality) do if self:GetRarityChecked(key) then tinsert(quality, value) end end if next(quality) == nil then return nil else return quality end end return nil end function filter:SetValues(values) if self.frame and values ~= nil then for iqname, iqvalue in pairs(Enum.ItemQuality) do if tContains(values, iqvalue) then local quality = string.lower(iqname) if self.frame[quality] then self.frame[quality]:SetChecked(true) end end end end end function filter:Clear() if self.frame then for iqname, iqvalue in pairs(Enum.ItemQuality) do local quality = string.lower(iqname) if self.frame[quality] then self.frame[quality]:SetChecked(false) end end end end EasyDestroy.Filters.RegisterCriteria(filter)
-- -- Created by IntelliJ IDEA. -- User: kavraham -- Date: 2/9/2016 -- Time: 9:56 AM -- To change this template use File | Settings | File Templates. -- local windowsOS = {} local _helper = require('pluginHelper') local apacheProperties = {} local apache_exe_path = nil local apache_root_directory = nil local serverVersion = nil local serverArchitecture = nil local serverConfigFile = nil local serverConfigFilePath = nil local fileLocation = "http://vw-tlv-ad-qa18/Apache/" local downloadFileDestination = "C:/tmp/Apache/" local installFileDestination = "C:/tmp/Apache/" local fileNameApache22_64bit = "Apache22Win64bit.zip" local fileNameApache24_64bit = "Apache24Win64bit.zip" local fileNameApache22_32bit = "Apache22Win32bit.zip" local fileNameApache24_32bit = "Apache24Win32bit.zip" local confFileNameApache22 = "bmc-aeuem-apache22.conf" local confFileNameApache24 = "bmc-aeuem-apache24.conf" local function execute() if (_helper.isSupportedWinOSVersion() and _helper.is64BitWinOSVersion()) then apache_exe_path = _helper.get_win_binary_path() apache_root_directory = _helper.get_win_apache_root_directory(apache_exe_path) apacheProperties = _helper.get_win_apache_properties(apache_exe_path) serverVersion = apacheProperties["serverVersion"] serverArchitecture = apacheProperties["serverArchitecture"] serverConfigFile = apacheProperties["serverConfigFile"] serverConfigFilePath = apache_root_directory..serverConfigFile local downloadFileName = nil local confFileName = nil if(string.find(serverVersion, "2.4.")) then confFileName = confFileNameApache24 if(serverArchitecture == "64") then downloadFileName = fileNameApache24_64bit else downloadFileName = fileNameApache24_32bit end elseif (string.find(serverVersion, "2.2.")) then confFileName = confFileNameApache22 if(serverArchitecture == "64") then downloadFileName = fileNameApache22_64bit else downloadFileName = fileNameApache22_32bit end end _helper.downloadFile(fileLocation, downloadFileDestination, downloadFileName) _helper.Extract(downloadFileDestination, downloadFileName, installFileDestination) _helper.updateModuleConfFile(confFileName, installFileDestination) _helper.createBackupHttpdConfFile(serverConfigFilePath) _helper.updateHttpdConfFile(serverConfigFilePath, installFileDestination..confFileName) print(_helper.winApacheRestart(apache_root_directory)) end end windowsOS.execute = execute return windowsOS
Network:Subscribe( 'DamageObject', function( WNO, sender ) if not sender or not IsValid( sender ) then return end if not WNO or not IsValid( WNO ) then return end local obj = IM.items_id[WNO:GetId()] if not obj then return end -- if you tracked player ammo server side, you would do -- an ammo check here to verify the player has ammo -- to cause damage to the object. obj:Damage( sender ) end ) -- if you wanted to track player accuracy -- Network:Subscribe( 'BulletMissed', BulletMissed )
-- -- MobDebug -- Lua remote debugger -- Copyright 2011-15 Paul Kulchenko -- Based on RemDebug 1.0 Copyright Kepler Project 2005 -- -- use loaded modules or load explicitly on those systems that require that local require = require local io = io or require "io" local table = table or require "table" local string = string or require "string" local coroutine = coroutine or require "coroutine" local debug = require "debug" -- protect require "os" as it may fail on embedded systems without os module local os = os or (function(module) local ok, res = pcall(require, module) return ok and res or nil end)("os") local mobdebug = { _NAME = "mobdebug", _VERSION = "0.64", _COPYRIGHT = "Paul Kulchenko", _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", port = os and os.getenv and tonumber((os.getenv("MOBDEBUG_PORT"))) or 8172, checkcount = 200, yieldtimeout = 0.02, -- yield timeout (s) connecttimeout = 2, -- connect timeout (s) } local HOOKMASK = "lcr" local error = error local getfenv = getfenv local setfenv = setfenv local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 local pairs = pairs local setmetatable = setmetatable local tonumber = tonumber local unpack = table.unpack or unpack local rawget = rawget local gsub, sub, find = string.gsub, string.sub, string.find -- if strict.lua is used, then need to avoid referencing some global -- variables, as they can be undefined; -- use rawget to avoid complaints from strict.lua at run-time. -- it's safe to do the initialization here as all these variables -- should get defined values (if any) before the debugging starts. -- there is also global 'wx' variable, which is checked as part of -- the debug loop as 'wx' can be loaded at any time during debugging. local genv = _G or _ENV local jit = rawget(genv, "jit") local MOAICoroutine = rawget(genv, "MOAICoroutine") -- ngx_lua debugging requires a special handling as its coroutine.* -- methods use a different mechanism that doesn't allow resume calls -- from debug hook handlers. -- Instead, the "original" coroutine.* methods are used. -- `rawget` needs to be used to protect against `strict` checks, but -- ngx_lua hides those in a metatable, so need to use that. local metagindex = getmetatable(genv) and getmetatable(genv).__index local ngx = type(metagindex) == "table" and metagindex.rawget and metagindex:rawget("ngx") or nil local corocreate = ngx and coroutine._create or coroutine.create local cororesume = ngx and coroutine._resume or coroutine.resume local coroyield = ngx and coroutine._yield or coroutine.yield local corostatus = ngx and coroutine._status or coroutine.status local corowrap = coroutine.wrap if not setfenv then -- Lua 5.2+ -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html -- this assumes f is a function local function findenv(f) local level = 1 repeat local name, value = debug.getupvalue(f, level) if name == '_ENV' then return level, value end level = level + 1 until name == nil return nil end getfenv = function (f) return(select(2, findenv(f)) or _G) end setfenv = function (f, t) local level = findenv(f) if level then debug.setupvalue(f, level, t) end return f end end -- check for OS and convert file names to lower case on windows -- (its file system is case insensitive, but case preserving), as setting a -- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. -- OSX and Windows behave the same way (case insensitive, but case preserving). -- OSX can be configured to be case-sensitive, so check for that. This doesn't -- handle the case of different partitions having different case-sensitivity. local win = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')) and true or false local mac = not win and (os and os.getenv and os.getenv('DYLD_LIBRARY_PATH') or not io.open("/proc")) and true or false local iscasepreserving = win or (mac and io.open('/library') ~= nil) -- turn jit off based on Mike Pall's comment in this discussion: -- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 -- "You need to turn it off at the start if you plan to receive -- reliable hook calls at any later point in time." if jit and jit.off then jit.off() end local socket = require "socket" local coro_debugger local coro_debugee local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } local breakpoints = {} local watches = {} local lastsource local lastfile local watchescnt = 0 local abort -- default value is nil; this is used in start/loop distinction local seen_hook = false local checkcount = 0 local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local server local buf local outputs = {} local iobase = {print = print} local basedir = "" local deferror = "execution aborted at default debugee" local debugee = function () local a = 1 for _ = 1, 10 do a = a + 1 end error(deferror) end local function q(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end local serpent = (function() ---- include Serpent module for serialization local n, v = "serpent", 0.285 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local getmetatable = debug and debug.getmetatable or getmetatable local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(type(G[g]) == 'table' and G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local numformat = opts.numformat or "%.17g" local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or numformat:format(s)) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..select(2, pcall(tostring, s))..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end -- protect from those cases where __tostring may fail if type(mt) == 'table' and pcall(function() return mt.__tostring and mt.__tostring(t) end) and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.keyignore and opts.keyignore[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } end)() ---- end of Serpent module mobdebug.line = serpent.line mobdebug.dump = serpent.dump mobdebug.linemap = nil mobdebug.loadstring = loadstring local function removebasedir(path, basedir) if iscasepreserving then -- check if the lowercased path matches the basedir -- if so, return substring of the original path (to not lowercase it) return path:lower():find('^'..q(basedir:lower())) and path:sub(#basedir+1) or path else return string.gsub(path, '^'..q(basedir), '') end end local function stack(start) local function vars(f) local func = debug.getinfo(f, "f").func local i = 1 local locals = {} -- get locals while true do local name, value = debug.getlocal(f, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end i = i + 1 end -- get varargs (these use negative indices) i = 1 while true do local name, value = debug.getlocal(f, -i) -- `not name` should be enough, but LuaJIT 2.0.0 incorrectly reports `(*temporary)` names here if not name or name ~= "(*vararg)" then break end locals[name:gsub("%)$"," "..i..")")] = {value, tostring(value)} i = i + 1 end -- get upvalues i = 1 local ups = {} while func do -- check for func as it may be nil for tail calls local name, value = debug.getupvalue(func, i) if not name then break end ups[name] = {value, tostring(value)} i = i + 1 end return locals, ups end local stack = {} local linemap = mobdebug.linemap for i = (start or 0), 100 do local source = debug.getinfo(i, "Snl") if not source then break end local src = source.source if src:find("@") == 1 then src = src:sub(2):gsub("\\", "/") if src:find("%./") == 1 then src = src:sub(3) end end table.insert(stack, { -- remove basedir from source {source.name, removebasedir(src, basedir), linemap and linemap(source.linedefined, source.source) or source.linedefined, linemap and linemap(source.currentline, source.source) or source.currentline, source.what, source.namewhat, source.short_src}, vars(i+1)}) if source.what == 'main' then break end end return stack end local function set_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif iscasepreserving then file = string.lower(file) end if not breakpoints[line] then breakpoints[line] = {} end breakpoints[line][file] = true end local function remove_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif file == '*' and line == 0 then breakpoints = {} elseif iscasepreserving then file = string.lower(file) end if breakpoints[line] then breakpoints[line][file] = nil end end local function has_breakpoint(file, line) return breakpoints[line] and breakpoints[line][iscasepreserving and string.lower(file) or file] end local function restore_vars(vars) if type(vars) ~= 'table' then return end -- locals need to be processed in the reverse order, starting from -- the inner block out, to make sure that the localized variables -- are correctly updated with only the closest variable with -- the same name being changed -- first loop find how many local variables there is, while -- the second loop processes them from i to 1 local i = 1 while true do local name = debug.getlocal(3, i) if not name then break end i = i + 1 end i = i - 1 local written_vars = {} while i > 0 do local name = debug.getlocal(3, i) if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, rawget(vars, name)) end written_vars[name] = true end i = i - 1 end i = 1 local func = debug.getinfo(3, "f").func while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setupvalue(func, i, rawget(vars, name)) end written_vars[name] = true end i = i + 1 end end local function capture_vars(level) local vars = {} local func = debug.getinfo(level or 3, "f").func local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end i = 1 while true do local name, value = debug.getlocal(level or 3, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end -- returned 'vars' table plays a dual role: (1) it captures local values -- and upvalues to be restored later (in case they are modified in "eval"), -- and (2) it provides an environment for evaluated chunks. -- getfenv(func) is needed to provide proper environment for functions, -- including access to globals, but this causes vars[name] to fail in -- restore_vars on local variables or upvalues with `nil` values when -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function stack_depth(start_depth) for i = start_depth, 0, -1 do if debug.getinfo(i, "l") then return i+1 end end return start_depth end local function is_safe(stack_level) -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function if stack_level == 3 then return true end for i = 3, stack_level do -- return if it is not safe to abort local info = debug.getinfo(i, "S") if not info then return true end if info.what == "C" then return false end end return true end local function in_debugger() local this = debug.getinfo(1, "S").source -- only need to check few frames as mobdebug frames should be close for i = 3, 7 do local info = debug.getinfo(i, "S") if not info then return false end if info.source == this then return true end end return false end local function is_pending(peer) -- if there is something already in the buffer, skip check if not buf and checkcount >= mobdebug.checkcount then peer:settimeout(0) -- non-blocking buf = peer:receive(1) peer:settimeout() -- back to blocking checkcount = 0 end return buf end local function readnext(peer, num) peer:settimeout(0) -- non-blocking local res, err, partial = peer:receive(num) peer:settimeout() -- back to blocking return res or partial or '', err end local function handle_breakpoint(peer) -- check if the buffer has the beginning of SETB/DELB command; -- this is to avoid reading the entire line for commands that -- don't need to be handled here. if not buf or not (buf:sub(1,1) == 'S' or buf:sub(1,1) == 'D') then return end -- check second character to avoid reading STEP or other S* and D* commands if #buf == 1 then buf = buf .. readnext(peer, 1) end if buf:sub(2,2) ~= 'E' then return end -- need to read few more characters buf = buf .. readnext(peer, 5-#buf) if buf ~= 'SETB ' and buf ~= 'DELB ' then return end local res, _, partial = peer:receive() -- get the rest of the line; blocking if not res then if partial then buf = buf .. partial end return end local _, _, cmd, file, line = (buf..res):find("^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if cmd == 'SETB' then set_breakpoint(file, tonumber(line)) elseif cmd == 'DELB' then remove_breakpoint(file, tonumber(line)) else -- this looks like a breakpoint command, but something went wrong; -- return here to let the "normal" processing to handle, -- although this is likely to not go well. return end buf = nil end local function normalize_path(file) local n repeat file, n = file:gsub("/+%.?/+","/") -- remove all `//` and `/./` references until n == 0 -- collapse all up-dir references: this will clobber UNC prefix (\\?\) -- and disk on Windows when there are too many up-dir references: `D:\foo\..\..\bar`; -- handle the case of multiple up-dir references: `foo/bar/baz/../../../more`; -- only remove one at a time as otherwise `../../` could be removed; repeat file, n = file:gsub("[^/]+/%.%./", "", 1) until n == 0 -- there may still be a leading up-dir reference left (as `/../` or `../`); remove it return (file:gsub("%.%./", "", 1)) end local function debug_hook(event, line) -- (1) LuaJIT needs special treatment. Because debug_hook is set for -- *all* coroutines, and not just the one being debugged as in regular Lua -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), -- need to avoid debugging mobdebug's own code as LuaJIT doesn't -- always correctly generate call/return hook events (there are more -- calls than returns, which breaks stack depth calculation and -- 'step' and 'step over' commands stop working; possibly because -- 'tail return' events are not generated by LuaJIT). -- the next line checks if the debugger is run under LuaJIT and if -- one of debugger methods is present in the stack, it simply returns. if jit then -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, -- coroutine.running() returns non-nil for the main thread. local coro, main = coroutine.running() if not coro or main then coro = 'main' end local disabled = coroutines[coro] == false or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) then return end end -- (2) check if abort has been requested and it's safe to abort if abort and is_safe(stack_level) then error(abort) end -- (3) also check if this debug hook has not been visited for any reason. -- this check is needed to avoid stepping in too early -- (for example, when coroutine.resume() is executed inside start()). if not seen_hook and in_debugger() then return end if event == "call" then stack_level = stack_level + 1 elseif event == "return" or event == "tail return" then stack_level = stack_level - 1 elseif event == "line" then if mobdebug.linemap then local ok, mappedline = pcall(mobdebug.linemap, line, debug.getinfo(2, "S").source) if ok then line = mappedline end if not line then return end end -- may need to fall through because of the following: -- (1) step_into -- (2) step_over and stack_level <= step_level (need stack_level) -- (3) breakpoint; check for line first as it's known; then for file -- (4) socket call (only do every Xth check) -- (5) at least one watch is registered if not ( step_into or step_over or breakpoints[line] or watchescnt > 0 or is_pending(server) ) then checkcount = checkcount + 1; return end checkcount = mobdebug.checkcount -- force check on the next command -- this is needed to check if the stack got shorter or longer. -- unfortunately counting call/return calls is not reliable. -- the discrepancy may happen when "pcall(load, '')" call is made -- or when "error()" is called in a function. -- in either case there are more "call" than "return" events reported. -- this validation is done for every "line" event, but should be "cheap" -- as it checks for the stack to get shorter (or longer by one call). -- start from one level higher just in case we need to grow the stack. -- this may happen after coroutine.resume call to a function that doesn't -- have any other instructions to execute. it triggers three returns: -- "return, tail return, return", which needs to be accounted for. stack_level = stack_depth(stack_level+1) local caller = debug.getinfo(2, "S") -- grab the filename and fix it if needed local file = lastfile if (lastsource ~= caller.source) then file, lastsource = caller.source, caller.source -- technically, users can supply names that may not use '@', -- for example when they call loadstring('...', 'filename.lua'). -- Unfortunately, there is no reliable/quick way to figure out -- what is the filename and what is the source code. -- If the name doesn't start with `@`, assume it's a file name if it's all on one line. if find(file, "^@") or not find(file, "[\r\n]") then file = gsub(gsub(file, "^@", ""), "\\", "/") -- normalize paths that may include up-dir or same-dir references -- if the path starts from the up-dir or reference, -- prepend `basedir` to generate absolute path to keep breakpoints working. -- ignore qualified relative path (`D:../`) and UNC paths (`\\?\`) if find(file, "^%.%./") then file = basedir..file end if find(file, "/%.%.?/") then file = normalize_path(file) end -- need this conversion to be applied to relative and absolute -- file names as you may write "require 'Foo'" to -- load "foo.lua" (on a case insensitive file system) and breakpoints -- set on foo.lua will not work if not converted to the same case. if iscasepreserving then file = string.lower(file) end if find(file, "^%./") then file = sub(file, 3) else file = gsub(file, "^"..q(basedir), "") end -- some file systems allow newlines in file names; remove these. file = gsub(file, "\n", ' ') else file = mobdebug.line(file) end -- set to true if we got here; this only needs to be done once per -- session, so do it here to at least avoid setting it for every line. seen_hook = true lastfile = file end if is_pending(server) then handle_breakpoint(server) end local vars, status, res if (watchescnt > 0) then vars = capture_vars() for index, value in pairs(watches) do setfenv(value, vars) local ok, fired = pcall(value) if ok and fired then status, res = cororesume(coro_debugger, events.WATCH, vars, file, line, index) break -- any one watch is enough; don't check multiple times end end end -- need to get into the "regular" debug handler, but only if there was -- no watch that was fired. If there was a watch, handle its result. local getin = (status == nil) and (step_into -- when coroutine.running() return `nil` (main thread in Lua 5.1), -- step_over will equal 'main', so need to check for that explicitly. or (step_over and step_over == (coroutine.running() or 'main') and stack_level <= step_level) or has_breakpoint(file, line) or is_pending(server)) if getin then vars = vars or capture_vars() step_into = false step_over = false status, res = cororesume(coro_debugger, events.BREAK, vars, file, line) end -- handle 'stack' command that provides stack() information to the debugger if status and res == 'stack' then while status and res == 'stack' do -- resume with the stack trace and variables if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values -- this may fail if __tostring method fails at run-time local ok, snapshot = pcall(stack, ngx and 5 or 4) status, res = cororesume(coro_debugger, ok and events.STACK or events.BREAK, snapshot, file, line) end end -- need to recheck once more as resume after 'stack' command may -- return something else (for example, 'exit'), which needs to be handled if status and res and res ~= 'stack' then if not abort and res == "exit" then mobdebug.onexit(1, true); return end if not abort and res == "done" then mobdebug.done(); return end abort = res -- only abort if safe; if not, there is another (earlier) check inside -- debug_hook, which will abort execution at the first safe opportunity if is_safe(stack_level) then error(abort) end elseif not status and res then error(res, 2) -- report any other (internal) errors back to the application end if vars then restore_vars(vars) end -- last command requested Step Over/Out; store the current thread if step_over == true then step_over = coroutine.running() or 'main' end end end local function stringify_results(status, ...) if not status then return status, ... end -- on error report as it local t = {...} for i,v in pairs(t) do -- stringify each of the returned values local ok, res = pcall(mobdebug.line, v, {nocode = true, comment = 1}) t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") end -- stringify table with all returned values -- this is done to allow each returned value to be used (serialized or not) -- intependently and to preserve "original" comments return pcall(mobdebug.dump, t, {sparse = false}) end local function isrunning() return coro_debugger and (corostatus(coro_debugger) == 'suspended' or corostatus(coro_debugger) == 'running') end -- this is a function that removes all hooks and closes the socket to -- report back to the controller that the debugging is done. -- the script that called `done` can still continue. local function done() if not (isrunning() and server) then return end if not jit then for co, debugged in pairs(coroutines) do if debugged then debug.sethook(co) end end end debug.sethook() server:close() coro_debugger = nil -- to make sure isrunning() returns `false` seen_hook = nil -- to make sure that the next start() call works abort = nil -- to make sure that callback calls use proper "abort" value end local function debugger_loop(sev, svars, sfile, sline) local command local app, osname local eval_env = svars or {} local function emptyWatch () return false end local loaded = {} for k in pairs(package.loaded) do loaded[k] = true end while true do local line, err local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end while true do line, err = server:receive() if not line and err == "timeout" then -- yield for wx GUI applications if possible to avoid "busyness" app = app or (wx and wx.wxGetApp and wx.wxGetApp()) if app then local win = app:GetTopWindow() local inloop = app:IsMainLoopRunning() osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName() if win and not inloop then -- process messages in a regular way -- and exit as soon as the event loop is idle if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end local exitLoop = function() win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE) win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER) app:ExitMainLoop() end win:Connect(wx.wxEVT_IDLE, exitLoop) win:Connect(wx.wxEVT_TIMER, exitLoop) app:MainLoop() end elseif mobdebug.yield then mobdebug.yield() end elseif not line and err == "closed" then error("Debugger connection closed", 0) else -- if there is something in the pending buffer, prepend it to the line if buf then line = buf .. line; buf = nil end break end end if server.settimeout then server:settimeout() end -- back to blocking command = string.sub(line, string.find(line, "^[A-Z]+")) if command == "SETB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then set_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "DELB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then remove_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXEC" then local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func, res = mobdebug.loadstring(chunk) local status if func then setfenv(func, eval_env) status, res = stringify_results(pcall(func)) end if status then if mobdebug.onscratch then mobdebug.onscratch(res) end server:send("200 OK " .. tostring(#res) .. "\n") server:send(res) else -- fix error if not set (for example, when loadstring is not present) if not res then res = "Unknown error" end server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "LOAD" then local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") size = tonumber(size) if abort == nil then -- no LOAD/RELOAD allowed inside start() if size > 0 then server:receive(size) end if sfile and sline then server:send("201 Started " .. sfile .. " " .. tostring(sline) .. "\n") else server:send("200 OK 0\n") end else -- reset environment to allow required modules to load again -- remove those packages that weren't loaded when debugger started for k in pairs(package.loaded) do if not loaded[k] then package.loaded[k] = nil end end if size == 0 and name == '-' then -- RELOAD the current script being debugged server:send("200 OK 0\n") coroyield("load") else -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading local chunk = size == 0 and "" or server:receive(size) if chunk then -- LOAD a new script for debugging local func, res = mobdebug.loadstring(chunk, "@"..name) if func then server:send("200 OK 0\n") debugee = func coroyield("load") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end end end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") if exp then local func, res = mobdebug.loadstring("return(" .. exp .. ")") if func then watchescnt = watchescnt + 1 local newidx = #watches + 1 watches[newidx] = func server:send("200 OK " .. tostring(newidx) .. "\n") else server:send("401 Error in Expression " .. tostring(#res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") index = tonumber(index) if index > 0 and index <= #watches then watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) watches[index] = emptyWatch server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "RUN" then server:send("200 OK\n") local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "STEP" then server:send("200 OK\n") step_into = true local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "OVER" or command == "OUT" then server:send("200 OK\n") step_over = true -- OVER and OUT are very similar except for -- the stack level value at which to stop if command == "OUT" then step_level = stack_level - 1 else step_level = stack_level end local ev, vars, file, line, idx_watch = coroyield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. tostring(#file) .. "\n") server:send(file) end elseif command == "BASEDIR" then local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") if dir then basedir = iscasepreserving and string.lower(dir) or dir -- reset cached source as it may change with basedir lastsource = nil server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "SUSPEND" then -- do nothing; it already fulfilled its role elseif command == "DONE" then coroyield("done") return -- done with all the debugging elseif command == "STACK" then -- first check if we can execute the stack command -- as it requires yielding back to debug_hook it cannot be executed -- if we have not seen the hook yet as happens after start(). -- in this case we simply return an empty result local vars, ev = {} if seen_hook then ev, vars = coroyield("stack") end if ev and ev ~= events.STACK then server:send("401 Error in Execution " .. tostring(#vars) .. "\n") server:send(vars) else local ok, res = pcall(mobdebug.dump, vars, {nocode = true, sparse = false}) if ok then server:send("200 OK " .. tostring(res) .. "\n") else server:send("401 Error in Execution " .. tostring(#res) .. "\n") server:send(res) end end elseif command == "OUTPUT" then local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode and stream == "stdout" then -- assign "print" in the global environment local default = mode == 'd' genv.print = default and iobase.print or corowrap(function() -- wrapping into coroutine.wrap protects this function from -- being stepped through in the debugger. -- don't use vararg (...) as it adds a reference for its values, -- which may affect how they are garbage collected while true do local tbl = {coroutine.yield()} if mode == 'c' then iobase.print(unpack(tbl)) end for n = 1, #tbl do tbl[n] = select(2, pcall(mobdebug.line, tbl[n], {nocode = true, comment = false})) end local file = table.concat(tbl, "\t").."\n" server:send("204 Output " .. stream .. " " .. tostring(#file) .. "\n" .. file) end end) if not default then genv.print() end -- "fake" print to start printing loop server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXIT" then server:send("200 OK\n") coroyield("exit") else server:send("400 Bad Request\n") end end end local function output(stream, data) if server then return server:send("204 Output "..stream.." "..tostring(#data).."\n"..data) end end local function connect(controller_host, controller_port) local sock, err = socket.tcp() if not sock then return nil, err end if sock.settimeout then sock:settimeout(mobdebug.connecttimeout) end local res, err = sock:connect(controller_host, tostring(controller_port)) if sock.settimeout then sock:settimeout() end if not res then return nil, err end return sock end local lasthost, lastport -- Starts a debug session by connecting to a controller local function start(controller_host, controller_port) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local err server, err = mobdebug.connect(controller_host, controller_port) if server then -- correct stack depth which already has some calls on it -- so it doesn't go into negative when those calls return -- as this breaks subsequence checks in stack_depth(). -- start from 16th frame, which is sufficiently large for this check. stack_level = stack_depth(16) -- provide our own traceback function to report the error remotely do local dtraceback = debug.traceback debug.traceback = function (...) if select('#', ...) >= 1 then local err, lvl = ... if err and type(err) ~= 'thread' then local trace = dtraceback(err, (lvl or 2)+1) if genv.print == iobase.print then -- no remote redirect return trace else genv.print(trace) -- report the error remotely return -- don't report locally to avoid double reporting end end end -- direct call to debug.traceback: return the original. -- debug.traceback(nil, level) doesn't work in Lua 5.1 -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so -- simply remove first frame from the stack trace return (dtraceback(...):gsub("(stack traceback:\n)[^\n]*\n", "%1")) end end coro_debugger = corocreate(debugger_loop) debug.sethook(debug_hook, HOOKMASK) seen_hook = nil -- reset in case the last start() call was refused step_into = true -- start with step command return true else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) end end local function controller(controller_host, controller_port, scratchpad) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local exitonerror = not scratchpad local err server, err = mobdebug.connect(controller_host, controller_port) if server then local function report(trace, err) local msg = err .. "\n" .. trace server:send("401 Error in Execution " .. tostring(#msg) .. "\n") server:send(msg) return err end seen_hook = true -- allow to accept all commands coro_debugger = corocreate(debugger_loop) while true do step_into = true -- start with step command abort = false -- reset abort flag from the previous loop if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away coro_debugee = corocreate(debugee) debug.sethook(coro_debugee, debug_hook, HOOKMASK) local status, err = cororesume(coro_debugee, unpack(arg or {})) -- was there an error or is the script done? -- 'abort' state is allowed here; ignore it if abort then if tostring(abort) == 'exit' then break end else if status then -- normal execution is done break elseif err and not string.find(tostring(err), deferror) then -- report the error back -- err is not necessarily a string, so convert to string to report report(debug.traceback(coro_debugee), tostring(err)) if exitonerror then break end -- check if the debugging is done (coro_debugger is nil) if not coro_debugger then break end -- resume once more to clear the response the debugger wants to send -- need to use capture_vars(2) as three would be the level of -- the caller for controller(), but because of the tail call, -- the caller may not exist; -- This is not entirely safe as the user may see the local -- variable from console, but they will be reset anyway. -- This functionality is used when scratchpad is paused to -- gain access to remote console to modify global variables. local status, err = cororesume(coro_debugger, events.RESTART, capture_vars(2)) if not status or status and err == "exit" then break end end end end else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) return false end return true end local function scratchpad(controller_host, controller_port) return controller(controller_host, controller_port, true) end local function loop(controller_host, controller_port) return controller(controller_host, controller_port, false) end local function on() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end if co then coroutines[co] = true debug.sethook(co, debug_hook, HOOKMASK) else if jit then coroutines.main = true end debug.sethook(debug_hook, HOOKMASK) end end local function off() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end -- don't remove coroutine hook under LuaJIT as there is only one (global) hook if co then coroutines[co] = false if not jit then debug.sethook(co) end else if jit then coroutines.main = false end if not jit then debug.sethook() end end -- check if there is any thread that is still being debugged under LuaJIT; -- if not, turn the debugging off if jit then local remove = true for _, debugged in pairs(coroutines) do if debugged then remove = false; break end end if remove then debug.sethook() end end end -- Handles server debugging commands local function handle(params, client, options) -- when `options.verbose` is not provided, use normal `print`; verbose output can be -- disabled (`options.verbose == false`) or redirected (`options.verbose == function()...end`) local verbose = not options or options.verbose ~= nil and options.verbose local print = verbose and (type(verbose) == "function" and verbose or print) or function() end local file, line, watch_idx local _, _, command = string.find(params, "^([a-z]+)") if command == "run" or command == "step" or command == "out" or command == "over" or command == "exit" then client:send(string.upper(command) .. "\n") client:receive() -- this should consume the first '200 OK' response while true do local done = true local breakpoint = client:receive() if not breakpoint then print("Program finished") return nil, nil, false end local _, _, status = string.find(breakpoint, "^(%d+)") if status == "200" then -- don't need to do anything elseif status == "202" then _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file .. " line " .. line) end elseif status == "203" then _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") if file and line and watch_idx then print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") end elseif status == "204" then local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then local msg = client:receive(tonumber(size)) print("Error in remote application: " .. msg) return nil, nil, msg end else print("Unknown error") return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" end if done then break end end elseif command == "done" then client:send(string.upper(command) .. "\n") -- no response is expected elseif command == "setb" or command == "asetb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("SETB " .. file .. " " .. line .. "\n") if command == "asetb" or client:receive() == "200 OK" then set_breakpoint(file, line) else print("Error: breakpoint not inserted") end else print("Invalid command") end elseif command == "setw" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp then client:send("SETW " .. exp .. "\n") local answer = client:receive() local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") if watch_idx then watches[watch_idx] = exp print("Inserted watch exp no. " .. watch_idx) else local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") if size then local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") print("Error: watch expression not set: " .. err) else print("Error: watch expression not set") end end else print("Invalid command") end elseif command == "delb" or command == "adelb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("DELB " .. file .. " " .. line .. "\n") if command == "adelb" or client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: breakpoint not removed") end else print("Invalid command") end elseif command == "delallb" then local file, line = "*", 0 client:send("DELB " .. file .. " " .. tostring(line) .. "\n") if client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: all breakpoints not removed") end elseif command == "delw" then local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") if index then client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression not removed") end else print("Invalid command") end elseif command == "delallw" then for index, exp in pairs(watches) do client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") end end elseif command == "eval" or command == "exec" or command == "load" or command == "loadstring" or command == "reload" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp or (command == "reload") then if command == "eval" or command == "exec" then exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments :gsub("%-%-.-\n", " ") -- remove line comments :gsub("\n", " ")) -- convert new lines if command == "eval" then exp = "return " .. exp end client:send("EXEC " .. exp .. "\n") elseif command == "reload" then client:send("LOAD 0 -\n") elseif command == "loadstring" then local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s+(.+)") if not file then _, _, file, lines = string.find(exp, "^(%S+)%s+(.+)") end client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") client:send(lines) else local file = io.open(exp, "r") if not file and pcall(require, "winapi") then -- if file is not open and winapi is there, try with a short path; -- this may be needed for unicode paths on windows winapi.set_encoding(winapi.CP_UTF8) local shortp = winapi.short_path(exp) file = shortp and io.open(shortp, "r") end if not file then return nil, nil, "Cannot open file " .. exp end -- read the file and remove the shebang line as it causes a compilation error local lines = file:read("*all"):gsub("^#!.-\n", "\n") file:close() local file = string.gsub(exp, "\\", "/") -- convert slash file = removebasedir(file, basedir) client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") if #lines > 0 then client:send(lines) end end while true do local params, err = client:receive() if not params then return nil, nil, "Debugger connection " .. (err or "error") end local done = true local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") if status == "200" then len = tonumber(len) if len > 0 then local status, res local str = client:receive(len) -- handle serialized table with results local func, err = loadstring(str) if func then status, res = pcall(func) if not status then err = res elseif type(res) ~= "table" then err = "received "..type(res).." instead of expected 'table'" end end if err then print("Error in processing results: " .. err) return nil, nil, "Error in processing results: " .. err end print(unpack(res)) return res[1], res end elseif status == "201" then _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") elseif status == "202" or params == "200 OK" then -- do nothing; this only happens when RE/LOAD command gets the response -- that was for the original command that was aborted elseif status == "204" then local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") if stream and size then local size = tonumber(size) local msg = size > 0 and client:receive(size) or "" print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" end if done then break end end else print("Invalid command") end elseif command == "listb" then for l, v in pairs(breakpoints) do for f in pairs(v) do print(f .. ": " .. l) end end elseif command == "listw" then for i, v in pairs(watches) do print("Watch exp. " .. i .. ": " .. v) end elseif command == "suspend" then client:send("SUSPEND\n") elseif command == "stack" then client:send("STACK\n") local resp = client:receive() local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") if status == "200" then local func, err = loadstring(res) if func == nil then print("Error in stack information: " .. err) return nil, nil, err end local ok, stack = pcall(func) if not ok then print("Error in stack information: " .. stack) return nil, nil, stack end for _,frame in ipairs(stack) do print(mobdebug.line(frame[1], {comment = false})) end return stack elseif status == "401" then local _, _, len = string.find(resp, "%s+(%d+)%s*$") len = tonumber(len) local res = len > 0 and client:receive(len) or "Invalid stack information." print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after STACK" end elseif command == "output" then local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode then client:send("OUTPUT "..stream.." "..mode.."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("Stream "..stream.." redirected") outputs[stream] = type(options) == 'table' and options.handler or nil -- the client knows when she is doing, so install the handler elseif type(options) == 'table' and options.handler then outputs[stream] = options.handler else print("Unknown error") return nil, nil, "Debugger error: can't redirect "..stream end else print("Invalid command") end elseif command == "basedir" then local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") if dir then dir = string.gsub(dir, "\\", "/") -- convert slash if not string.find(dir, "/$") then dir = dir .. "/" end local remdir = dir:match("\t(.+)") if remdir then dir = dir:gsub("/?\t.+", "/") end basedir = dir client:send("BASEDIR "..(remdir or dir).."\n") local resp, err = client:receive() if not resp then print("Unknown error: "..err) return nil, nil, "Debugger connection error: "..err end local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("New base directory is " .. basedir) else print("Unknown error") return nil, nil, "Debugger error: unexpected response after BASEDIR" end else print(basedir) end elseif command == "help" then print("setb <file> <line> -- sets a breakpoint") print("delb <file> <line> -- removes a breakpoint") print("delallb -- removes all breakpoints") print("setw <exp> -- adds a new watch expression") print("delw <index> -- removes the watch expression at index") print("delallw -- removes all watch expressions") print("run -- runs until next breakpoint") print("step -- runs until next line, stepping into function calls") print("over -- runs until next line, stepping over function calls") print("out -- runs until line after returning from current function") print("listb -- lists breakpoints") print("listw -- lists watch expressions") print("eval <exp> -- evaluates expression on the current context and returns its value") print("exec <stmt> -- executes statement on the current context") print("load <file> -- loads a local file for debugging") print("reload -- restarts the current debugging session") print("stack -- reports stack trace") print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)") print("basedir [<path>] -- sets the base path of the remote application, or shows the current one") print("done -- stops the debugger and continues application execution") print("exit -- exits debugger and the application") else local _, _, spaces = string.find(params, "^(%s*)$") if spaces then return nil, nil, "Empty command" else print("Invalid command") return nil, nil, "Invalid command" end end return file, line end -- Starts debugging server local function listen(host, port) host = host or "*" port = port or mobdebug.port local socket = require "socket" print("Lua Remote Debugger") print("Run the program you wish to debug") local server = socket.bind(host, port) local client = server:accept() client:send("STEP\n") client:receive() local breakpoint = client:receive() local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file ) print("Type 'help' for commands") else local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") if size then print("Error in remote application: ") print(client:receive(size)) end end while true do io.write("> ") local file, line, err = handle(io.read("*line"), client) if not file and err == false then break end -- completed debugging end client:close() end local cocreate local function coro() if cocreate then return end -- only set once cocreate = cocreate or coroutine.create coroutine.create = function(f, ...) return cocreate(function(...) mobdebug.on() return f(...) end, ...) end end local moconew local function moai() if moconew then return end -- only set once moconew = moconew or (MOAICoroutine and MOAICoroutine.new) if not moconew then return end MOAICoroutine.new = function(...) local thread = moconew(...) -- need to support both thread.run and getmetatable(thread).run, which -- was used in earlier MOAI versions local mt = thread.run and thread or getmetatable(thread) local patched = mt.run mt.run = function(self, f, ...) return patched(self, function(...) mobdebug.on() return f(...) end, ...) end return thread end end -- make public functions available mobdebug.setbreakpoint = set_breakpoint mobdebug.removebreakpoint = remove_breakpoint mobdebug.listen = listen mobdebug.loop = loop mobdebug.scratchpad = scratchpad mobdebug.handle = handle mobdebug.connect = connect mobdebug.start = start mobdebug.on = on mobdebug.off = off mobdebug.moai = moai mobdebug.coro = coro mobdebug.done = done mobdebug.pause = function() step_into = true end mobdebug.yield = nil -- callback mobdebug.output = output mobdebug.onexit = os and os.exit or done mobdebug.onscratch = nil -- callback mobdebug.basedir = function(b) if b then basedir = b end return basedir end return mobdebug
local class = require 'class' local greedy = class('GreedyPolicy') function greedy:__init(params) self.net = params.net self.actionDim = params.actionDim end function greedy:evaluate() self.net:evaluate() end function greedy:training() self.net:training() end function greedy:action(obs) local q = self.net:forward(obs:cuda()):float() local _, maxIdT = torch.max(q,1) return maxIdT[1] end function greedy:actions(batch) local _, maxIdT = torch.max(self.net:forward(batch):float(), 2) return maxIdT:select(2,1) end function greedy:probs(batch) if batch:dim() > 1 then local nBatch = batch:size(1) local probs = torch.Tensor(nBatch, self.actionDim):zero() local actions = self:actions(batch) for i=1,nBatch do probs[i][actions[i]] = 1 end return probs else local probs = torch.Tensor(self.actionDim):zero() probs[self:action(batch)] = 1 return probs end end function greedy:setExploration(explo) error("Greedy policy does not have an exploration term") end local epsgreedy = class('EpsGreedyPolicy') function epsgreedy:__init(params) self.net = params.net self.epsilon = params.epsilon self.actionDim = params.actionDim end function epsgreedy:evaluate() self.net:evaluate() end function epsgreedy:training() self.net:training() end local function sampleEpsGreedy(q, eps, actionDim) if torch.FloatTensor.torch.uniform() < eps then return torch.FloatTensor.torch.random(actionDim) else local _, maxIdT = torch.max(q,1) return maxIdT[1] end end function epsgreedy:action(obs) if torch.FloatTensor.torch.uniform() < self.epsilon then return torch.FloatTensor.torch.random(self.actionDim) else local q = self.net:forward(obs):float() local _, maxIdT = torch.max(q,1) return maxIdT[1] end end function epsgreedy:actions(batch) local q = self.net:forward(batch):float() local nBatch = batch:size(1) local actions = torch.LongTensor(nBatch) for i=1,nBatch do actions[i] = sampleEpsGreedy(q[i], self.epsilon, self.actionDim) end return actions end function epsgreedy:probs(batch) if batch:dim() > 1 then local q = self.net:forward(batch:cuda()):float() local nBatch = batch:size(1) local nonGreedy = self.epsilon/self.actionDim local greedy = 1-self.epsilon + nonGreedy local probs = torch.Tensor(nBatch, self.actionDim):fill(nonGreedy) local _, maxIdT = torch.max(q, 2) for i=1,nBatch do probs[i][maxIdT[i][1]] = greedy end return probs else local probs = torch.Tensor(self.actionDim):fill(self.epsilon/self.actionDim) local q = self.net:forward(batch:cuda()):float() local _, maxIdT = torch.max(q,1) probs[maxIdT[1]] = probs[maxIdT[1]] + 1 - self.epsilon return probs end end function epsgreedy:setExploration(explo) self.epsilon = explo end local light_epsgreedy = class('LightEpsGreedyPolicy') function light_epsgreedy:__init(params) self.batch_net = params.net -- network that runs forward batches for multiple policies self.policy_no = params.policy_no -- no of this policy, to pick correct row of output self.epsilon = params.epsilon self.actionDim = params.actionDim end function light_epsgreedy:light_clone(policy_no) return light_epsgreedy{net = self.batch_net, policy_no = policy_no, epsilon = self.epsilon, actionDim = self.actionDim} end function light_epsgreedy:action() if torch.FloatTensor.torch.uniform() < self.epsilon then return torch.FloatTensor.torch.random(self.actionDim) else local _, maxIdT = self.batch_net.output[self.policy_no]:max(1) return maxIdT[1] end end function light_epsgreedy:probs() self._probs = self.batch_net.output[self.policy_no] -- inplace, replacing Q values as probs local _, maxIdT = self._probs:max(1) self._probs:fill(self.epsilon/self.actionDim) self._probs[maxIdT[1]] = 1-self.epsilon + self.epsilon/self.actionDim return self._probs end function light_epsgreedy:setExploration(explo) self.epsilon = explo end local light_greedy = class('LightGreedyPolicy') function light_greedy:__init(params) self.batch_net = params.net -- network that runs forward batches for multiple policies self.policy_no = params.policy_no -- no of this policy, to pick correct row of output end function light_greedy:light_clone(policy_no) return light_greedy{net = self.batch_net, policy_no = policy_no} end function light_greedy:action() local _, maxIdT = self.batch_net.output[self.policy_no]:max(1) return maxIdT[1] end function light_greedy:setExploration(explo) end return {Greedy = greedy, EpsGreedy = epsgreedy, LightEpsGreedy = light_epsgreedy, LightGreedy = light_greedy}
local options = { backup = false, clipboard = "unnamedplus", cmdheight = 2, completeopt = { "menu", "menuone", "noselect", "noinsert" }, conceallevel = 0, fileencoding = "utf-8", hlsearch = true, ignorecase = true, mouse = "a", pumheight = 10, showmode = false, showtabline = 2, smartcase = true, smartindent = true, splitbelow = true, splitright = true, swapfile = false, termguicolors = true, timeoutlen = 1000, undofile = true, updatetime = 300, writebackup = false, expandtab = true, shiftwidth = 2, tabstop = 2, cursorline = true, number = true, relativenumber = true, numberwidth = 2, signcolumn = "yes", wrap = true, scrolloff = 8, guifont = "monospace:h17", } for option, value in pairs(options) do vim.opt[option] = value end -- wrap lines movement (move back/forward oneline using h/l) vim.opt.whichwrap:append "<>[]hl" -- remember folding vim.opt.viewoptions:remove "options" vim.api.nvim_exec([[ augroup remember_folds autocmd! autocmd BufWinLeave *.* if &ft !=# 'help' | mkview | endif autocmd BufWinEnter *.* if &ft !=# 'help' | silent! loadview | endif augroup END ]], false) vim.opt.shortmess:append "c" -- vim.opt.listchars = { lead = "·" } -- don't auto comment new line --[=[ vim.api.nvim_exec([[ augroup no_auto_comment autocmd! au BufNewFile,BufRead * setlocal formatoptions-=c formatoptions-=r formatoptions-=o augroup END ]], false) --]=] vim.opt.formatoptions:append { c = false, r = false, o = false } -- highlight when yanking vim.api.nvim_exec([[ augroup highlight_yank autocmd! au TextYankPost * silent! lua vim.highlight.on_yank { higroup='IncSearch', timeout=200 } augroup END ]], false) -- -- add node provider -- --[=[ -- vim.api.nvim_exec([[ -- let g:node_host_prog = expand("~/.config/nvim/provider_nodejs/bin/node") -- ]], false) -- --]=] -- for option, value in pairs(options) do -- vim.opt[option] = value -- end -- -- from nvchad -- local disabled_built_ins = { -- "netrw", -- "netrwPlugin", -- "netrwSettings", -- "netrwFileHandlers", -- "gzip", -- "zip", -- "zipPlugin", -- "tar", -- "tarPlugin", -- "getscript", -- "getscriptPlugin", -- "vimball", -- "vimballPlugin", -- "2html_plugin", -- "logipat", -- "rrhelper", -- "spellfile_plugin", -- "matchit" -- } -- for _, plugin in pairs(disabled_built_ins) do -- vim.g["loaded_" .. plugin] = 1 -- end -- -- others
local Suite=CreateTestSuite("wow/api/Frame"); function Suite:TestCreateFrame() assert(CreateFrame("Frame"), "CreateFrame must return a value for valid frame types"); Assert.Exception("CreateFrame must throw on zero-args", CreateFrame); Assert.Exception("CreateFrame must throw on unknown type", CreateFrame, "unknown"); Assert.Succeeds("CreateFrame's type is case-insensitive", CreateFrame, "FrAMe"); end;
--- @module DragUI 枪械模块:拖动UI --- @copyright Lilith Games, Avatar Team --- @author RopzTao local DragUI, this = {}, nil ---屏幕参数 local VPX, VPY, X_2000, Y_1000, PixelX, PixelY = nil, nil, nil, nil, nil, nil ---UIanchors的x和y值 local function AnchorsXY(_tarUI) return Vector2(_tarUI.AnchorsX.x, _tarUI.AnchorsY.y) end ---UI拖放初始化 function DragUI:Init() self.root = world:CreateInstance('TestScr', 'TestScr', localPlayer.Local) self.MouseIn = false self.root:SetActive(false) invoke( function() ---创建拖动UI local testBtn = world:CreateInstance('TestBtn', 'TestBtn', self.root) local DragUIEntity = DragUI:New(testBtn) testBtn:ToTop() testBtn:SetActive(false) ---DragUIEntity:Inititial() end, 5 ) end ---Update函数 function DragUI:Update(_deltaTime) end function DragUI:New(_obj) ---初始化底板参数 VPX = self.root.Size.x VPY = self.root.Size.y local tDragUI = {} setmetatable(tDragUI, self) self.__index = self ---目标显示ui tDragUI.Base = _obj ---手指识别范围 tDragUI.BtnIdentify = _obj.BtnIdentify return tDragUI end ---析构解绑函数 function DragUI:Destructor() self.BtnIdentify.OnTouched:Clear() ---鼠标滑动逻辑,测试用,上线请注释掉 self.BtnIdentify.OnEnter:Clear() self.BtnIdentify.OnLeave:Clear() end ---拖动UI的初始化函数 function DragUI:Inititial() ---1.判断鼠标和手指是否在指定UI范围内..手指 self.BtnIdentify.OnTouched:Connect( function(_touchInfo) self:GetFingerPos(_touchInfo) end ) ---识别区域逻辑 self.BtnIdentify.OnDown:Connect( function() self.BtnIdentify.Size = Vector2(700, 700) if world:GetDevicePlatform() == Enum.Platform.Windows then self.MouseIn = true end self:OnDragBegin() end ) self.BtnIdentify.OnUp:Connect( function() self.BtnIdentify.Size = Vector2(200, 200) if world:GetDevicePlatform() == Enum.Platform.Windows then self.MouseIn = false end self:OnDragEnd() ---松手判断是否要媳妇 self:DragBox(self.Base, self.root.TarBox) end ) ---无法释放,保留在外部Connect便于析构 world.OnRenderStepped:Connect( function() if self.MouseIn then self:GetMousePos() end end ) end ---2.获取鼠标和手指的位置(屏幕坐标)..手指 function DragUI:GetFingerPos(_touchInfo) local fingerPos, tarPos for k, v in pairs(_touchInfo) do ---触摸信息 fingerPos = v.Position end tarPos = Vector2(fingerPos.x / VPX, fingerPos.y / VPY) self:DisplayUIAtTarPos(tarPos) end ---2.获取鼠标和手指的位置(屏幕坐标)..鼠标 function DragUI:GetMousePos() local mousePos, tarPos mousePos = Input.GetMouseScreenPos() tarPos = Vector2(mousePos.x / VPX, mousePos.y / VPY) self:DisplayUIAtTarPos(tarPos) end ---3.让UI显示在鼠标和手指的位置..手指 function DragUI:DisplayUIAtTarPos(_tarPos) self.Base.AnchorsX = Vector2(_tarPos.x, _tarPos.x) self.Base.AnchorsY = Vector2(_tarPos.y, _tarPos.y) end ---4.按下,松开执行函数 function DragUI:OnDragBegin() end function DragUI:OnDragEnd() end ---5.防止出屏幕,设定可拖拽范围 function DragUI:DragRange() end ---6.拖选框,吸附功能 ---@param _tarBox UiObject 目标框 function DragUI:DragBox(_tarUI, _tarBox) if (AnchorsXY(_tarUI) - AnchorsXY(_tarBox)).Magnitude < 0.12 then _tarUI.AnchorsX = _tarBox.AnchorsX _tarUI.AnchorsY = _tarBox.AnchorsY end end ---UI拖动至有内容的框内,内容互换 function DragUI:ContentExchange() end --TODO ---按住一个UI,移动鼠标(手指)时拖拽它(可能新一个新的图标), ---松开时候根据鼠标(手指)的位置做不同的处理,如果在鼠标(手指)在目标槽范围内,则替换目标位置的UI ---注意: ---1.如按住不直接出icon,而是按住后鼠标出了当前按住的技能icon范围后再显示 return DragUI
-- -- main.lua -- Main entry-point for the file. -- -- ======================== -- -- GLOBAL LIBRARIES/CLASSES -- -- ======================== Class = require('vendor/nomoon/class') Set = require('vendor/nomoon/set') JSON = require('vendor/dkjson') SLAXML = require('vendor/slaxml/slaxdom') Sfxr = require('vendor/sfxr') LPegLJ = require('vendor/lpeglj/lpeglj') -- Kikito's best libraries kikito = { anim8 = require('vendor/kikito/anim8'), bump = require('vendor/kikito/bump'), inspect = require('vendor/kikito/inspect'), loader = require('vendor/kikito/love-loader'), md5 = require('vendor/kikito/md5'), sha1 = require('vendor/kikito/sha1'), tween = require('vendor/kikito/tween') } -- Parts of the HUMP library hump = { Camera = require('vendor/hump/camera'), GS = require('vendor/hump/gamestate'), Signal = require('vendor/hump/signal'), Timer = require('vendor/hump/timer'), Vector = require('vendor/hump/vector') } -- Helper methods serialize = require('vendor/ser') inspect = kikito.inspect math.round = require('vendor/nomoon/round') --[[ .... ]] require('vendor/deepcopy') -- table.deepcopy table.copy = table.deepcopy -- ======================== -- -- LÖVE2D ENGINE/GAME STUFF -- -- ======================== -- This table can store important "global" objects for the game -- (and keep the global namespace cleaner) game = { states = {}, objects = {}, graphics = {} -- Just some ideas... } -- conf.lua -- Initial configuration (already loaded) -- Exports: -- love.conf(t) - ran already -- conf (table of love configuration settings) -- debug.lua -- Debug flags/output for Love2d -- Exports: -- love.debug, etc. (see file) require('love/debug') love.debug.setFlag('all') -- Comment this out to stop seeing everything. -- load.lua -- Loaded on game start -- Exports: -- love.load() require('love/load') -- update.lua -- Update method -- Exports: -- love.update(dt) require('love/update') -- draw.lua -- Draw method -- Exports: -- love.viewport -- Viewport singleton -- love.draw() require('love/draw') -- input.lua -- Input callbacks -- Exports: -- love.inputman -- InputMan singleton -- love.inputpressed(state, value) -- love.inputreleased(state, value) -- love.joystickadded(k) -- love.joystickremoved(j) require('love/input') -- sound.lua -- Sound methods -- Exports: -- love.soundman -- SoundMan singleton require('love/sound') -- events.lua -- Love2d Event processing -- Exports: -- love.processevents() require('love/events') -- misc.lua -- Miscellaneous Love2d events -- Exports: -- love.threaderror(thread, errorstr) require('love/misc') -- run.lua -- Main loop -- Exports: -- love.run() require('love/run')
XYZParty.Core.Parties = XYZParty.Core.Parties or {} XYZParty.Core.Passwords = XYZParty.Core.Passwords or {} hook.Add("PlayerSay", "xyz_party_chat_command", function(ply, msg) if string.lower(msg) == "!party" then if not table.HasValue(XYZShit.Jobs.Government.Police, ply:Team()) then net.Start("xyz_party_open") net.WriteTable(XYZParty.Core.Parties) net.Send(ply) else XYZShit.Msg("Party", Color(100, 160, 40), "Use the government assigned partner system if you want to team up.", ply) end end end) local function getUsersParty(ply) for k, v in pairs(XYZParty.Core.Parties) do if v.leader == ply then return k, true end for n, m in pairs(v.members) do if m == ply then return k, false end end end return false end -- So we can use it in the quest system XYZParty.Core.GetParty = getUsersParty local function addtoParty(ply, key) local targetParty = XYZParty.Core.Parties[key] if not targetParty then return end XYZShit.Msg("Party", Color(100, 160, 40), ply:Name().." has joined the party.", targetParty.members) hook.Call("XYZPartyJoin", nil, ply, targetParty.name) table.insert(XYZParty.Core.Parties[key].members, ply) net.Start("xyz_party_data") net.WriteTable(XYZParty.Core.Parties[key]) net.Send(targetParty.members) end local function removeFromParty(ply, key) local targetParty = XYZParty.Core.Parties[key] if not targetParty then return end for k, v in pairs(XYZParty.Core.Parties[key].members) do if v == ply then table.remove(XYZParty.Core.Parties[key].members, k) break end end XYZShit.Msg("Party", Color(100, 160, 40), ply:Name().." has left the party. (or was kicked)", targetParty.members) hook.Call("XYZPartyLeave", nil, ply, targetParty.name) net.Start("xyz_party_data") net.WriteTable(XYZParty.Core.Parties[key]) net.Send(targetParty.members) net.Start("xyz_party_data_wipe") net.Send(ply) end local function endParty(key) local targetParty = XYZParty.Core.Parties[key] if not targetParty then return end XYZShit.Msg("Party", Color(100, 160, 40), "Your party has been disbanded.", targetParty.members) hook.Call("XYZPartyDisband", nil, targetParty.name) XYZParty.Core.Parties[key] = nil XYZParty.Core.Passwords[key] = nil net.Start("xyz_party_data_wipe") net.Send(targetParty.members) end local function startParty(ply, data) data.name = data.name or "My party" data.password = data.password or false data.color = data.color or Color(100, 255, 100) data.leader = ply data.members = {ply} if data.orgOnly then data.orgOnly = XYZ_ORGS.Core.Members[ply:SteamID64()] data.password = false data.name = XYZ_ORGS.Core.Orgs[XYZ_ORGS.Core.Members[ply:SteamID64()]].name end local key = table.insert(XYZParty.Core.Parties, data) XYZParty.Core.Passwords[key] = data.password if data.password then XYZParty.Core.Parties[key].password = true else XYZParty.Core.Parties[key].password = false end XYZShit.Msg("Party", Color(100, 160, 40), ply:Name().." has started a party called '"..data.name.."'.") hook.Call("XYZPartyStart", nil, ply, data.name) net.Start("xyz_party_data") net.WriteTable(XYZParty.Core.Parties[key]) net.Send(ply) end local function editParty(partyKey, data) data.name = data.name or "My party" data.password = data.password or false data.color = data.color or Color(100, 255, 100) local targetParty = XYZParty.Core.Parties[partyKey] if not targetParty then return end targetParty.name = data.name targetParty.password = data.password targetParty.color = data.color if data.password then XYZParty.Core.Parties[partyKey].password = true XYZParty.Core.Passwords[partyKey] = data.password end net.Start("xyz_party_edit_share") net.WriteTable(data) net.Send(targetParty.members) end net.Receive("xyz_party_request", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_request", 1, ply) then return end local partyKey = net.ReadInt(32) local party = XYZParty.Core.Parties[partyKey] if table.HasValue(XYZShit.Jobs.Government.Police, ply:Team()) then return end if not party then XYZShit.Msg("Party", Color(100, 160, 40), "Seems the party you're requesting doesn't exist anymore...", ply) return end if party.password then local recPassword = net.ReadString() or "" if not (recPassword == XYZParty.Core.Passwords[partyKey]) then XYZShit.Msg("Party", Color(100, 160, 40), "Seems the password you gave is wrong. Remember, it's case sensitive", ply) return end end if party.orgOnly then if not XYZ_ORGS.Core.Members[ply:SteamID64()] then XYZShit.Msg("Party", Color(100, 160, 40), "This is an org-only party. You are not in an organization.", ply) return else if party.orgOnly ~= XYZ_ORGS.Core.Members[ply:SteamID64()] then XYZShit.Msg("Party", Color(100, 160, 40), "This is an org-only party. You are not in the correct organization.", ply) return end end end local curParty, curPartyLeader = getUsersParty(ply) if curParty then XYZShit.Msg("Party", Color(100, 160, 40), "Leave your current party before you try to join a new one...", ply) return end addtoParty(ply, partyKey) XYZShit.Msg("Party", Color(100, 160, 40), "You have joined the party '"..party.name.."'", ply) end) net.Receive("xyz_party_leave", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_leave", 1, ply) then return end local plysParty, plyLeader = getUsersParty(ply) if plyLeader then endParty(plysParty) elseif plysParty then removeFromParty(ply, plysParty) XYZShit.Msg("Party", Color(100, 160, 40), "You have left the party.", ply) end end) net.Receive("xyz_party_create", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_create", 1, ply) then return end local data = net.ReadTable() data.name = string.sub(data.name, 0, 20) or "My party" if not data.password or (data.password == "") then data.password = false end data.color = data.color or Color(100, 255, 100) if table.HasValue(XYZShit.Jobs.Government.Police, ply:Team()) then return end local curParty, curPartyLeader = getUsersParty(ply) if curParty then XYZShit.Msg("Party", Color(100, 160, 40), "Leave your current party before you try to start a new one...", ply) return end startParty(ply, data) end) net.Receive("xyz_party_kick", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_kick", 1, ply) then return end local target = net.ReadEntity() if target == ply then return end local plysParty, plyLeader = getUsersParty(ply) if not plyLeader then return end local kickable = false for k, v in pairs(XYZParty.Core.Parties[plysParty].members) do if v == target then kickable = true break end end if not kickable then return end XYZShit.Msg("Party", Color(100, 160, 40), "You have been kicked from the party.", target) removeFromParty(target, plysParty) end) hook.Add("OnPlayerChangedTeam", "xyz_party_team_change", function(ply, old, new) if table.HasValue(XYZShit.Jobs.Government.Police, new) then local plysParty, plyLeader = getUsersParty(ply) if plyLeader then XYZShit.Msg("Party", Color(100, 160, 40), "You have joined a job that does not support parties. Your party has been ended.", ply) endParty(plysParty) elseif plysParty then XYZShit.Msg("Party", Color(100, 160, 40), "You have joined a job that does not support parties. You have been removed from the party.", ply) removeFromParty(ply, plysParty) end end end) hook.Add("PlayerShouldTakeDamage", "xyz_party_no_team_damange", function(victim, attacker) if not attacker then return end if not IsValid(attacker) then return end if not attacker:IsPlayer() then return end if not IsValid(attacker:GetActiveWeapon()) then return end if attacker:GetActiveWeapon():GetClass() == "xyz_suicide_vest" then return end local plysParty, plyLeader = getUsersParty(attacker) local party = XYZParty.Core.Parties[plysParty] if party then if table.HasValue(party.members, victim) then return false end end end) hook.Add("PlayerDisconnected", "xyz_party_team_change", function(ply) local plysParty, plyLeader = getUsersParty(ply) if plyLeader then endParty(plysParty) elseif plysParty then removeFromParty(ply, plysParty) end end) hook.Add("PlayerSay", "xyz_party_chat", function(ply, msg) if string.sub(string.lower(msg), 1, 3) == "!p " then local plysParty, plyLeader = getUsersParty(ply) if not plysParty then return end net.Start("xyz_party_chat") net.WriteEntity(ply) net.WriteString(string.sub(msg, 4)) net.Send(XYZParty.Core.Parties[plysParty].members) return "" end end) net.Receive("xyz_party_ping_send", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_ping_send", 1, ply) then return end if ply:GetActiveWeapon() and (ply:GetActiveWeapon():GetClass() == "weapon_ziptied") then return end local curParty, curPartyLeader = getUsersParty(ply) if not curParty then return end local targetParty = XYZParty.Core.Parties[curParty] if not targetParty then return end local pingPos = net.ReadVector() if not pingPos then return end net.Start("xyz_party_ping_broadcast") net.WriteEntity(ply) net.WriteVector(pingPos) net.Send(targetParty.members) end) net.Receive("xyz_party_edit", function(_, ply) if XYZShit.CoolDown.Check("xyz_party_edit", 1, ply) then return end local plysParty, plyLeader = getUsersParty(ply) if not plyLeader then return end local data = net.ReadTable() data.name = string.sub(data.name, 0, 20) or "My party" if not data.password or (data.password == "") then data.password = false end data.color = data.color or Color(100, 255, 100) editParty(plysParty, data) end)
local class = require "utils.class" local M = class(); function M:_init_(duration) self.duration = duration or 0; self.timeout_tick = nil; self.last_timeout_tick = nil; end function M:Serialize() return {self.timeout_tick} end function M:DeSerialize(data) self.timeout_tick = data[1] end function M:SerializeChange() if self.last_timeout_tick ~= self.timeout_tick then self.last_timeout_tick = self.timeout_tick; return {self.timeout_tick} end end function M:ApplyChange(changes) self.timeout_tick = changes[1]; end return M;
return function(player) return Def.ActorFrame { LoadFont("Common Normal") .. { InitCommand=cmd(x,-35;y,5;horizalign,left); ComboCommand=function(self, param) local oldMaxCombo = tonumber(string.match( self:GetText(),"%d+")) or 0 local newMaxCombo = param.Combo or 0 if newMaxCombo > oldMaxCombo then self:stopeffect():finishtweening():diffusealpha(1):rotationz(-2):skewx(-0.125):addx(7):addy(2):decelerate(0.05*2.5):rotationz(0):addx(-7):skewx(0):addy(-2) :sleep(2):decelerate(0.1):diffusealpha(0):rotationz(10) self:settextf("MC : %d", newMaxCombo) end end; }; }; end
function fact(x) if x <= 1 then return 1 else return x * fact(x - 1) end end print(fact(5))
--[[ Boss - Priestess Delrissa Adds AI.lua This script was written and is protected by the GPL v2. This script was released by BrantX of the Blua Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation commUnity. ~~End of License Agreement -- Azolex, August 29, 2008. ]] --Fizzle-Warlocks Pet-Imp function Fizzle_OnCombat(Unit, Event) Unit:RegisterEvent("Fizzle_Fireball", 5000, 0) end function Fizzle_Fireball(pUnit, Event) pUnit:FullCastSpellOnTarget(44164, pUnit:GetRandomPlayer(0)) end function Fizzle_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function Fizzle_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24656, 1, "Fizzle_OnCombat") RegisterUnitEvent(24656, 2, "Fizzle_LeaveCombat") RegisterUnitEvent(24656, 4, "Fizzle_Died") --Ellrys Duskhallow-warlock function warlockadd_OnCombat(Unit, Event) Unit:RegisterEvent("warlockadd_Fear", 7500, 0) Unit:RegisterEvent("warlockadd_ShadowBolt", 4500, 0) Unit:RegisterEvent("warlockadd_Curse", 10000, 0) end function warlockadd_Fear(pUnit, Event) pUnit:FullCastSpellOnTarget(38595, pUnit:GetRandomPlayer(0)) end function warlockadd_ShadowBolt(pUnit, Event) pUnit:FullCastSpellOnTarget(15232, pUnit:GetRandomPlayer(0)) end function warlockadd_Curse(pUnit, Event) pUnit:FullCastSpellOnTarget(46190, pUnit:GetRandomPlayer(0)) end function warlockadd_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function warlockadd_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24558, 1, "warlockadd_OnCombat") RegisterUnitEvent(24558, 2, "warlockadd_LeaveCombat") RegisterUnitEvent(24558, 4, "warlockadd_Died") --Yazzai-Mage function MageAdd_OnCombat(Unit, Event) Unit:RegisterEvent("MageAdd_Polymorph", 10000, 0) Unit:RegisterEvent("MageAdd_FrostBolt", 4500, 0) Unit:RegisterEvent("MageAdd_ConeOfCold", 10000, 0) end function MageAdd_Polymorph(pUnit, Event) pUnit:FullCastSpellOnTarget(13323, pUnit:GetRandomPlayer(0)) end function MageAdd_FrostBolt(pUnit, Event) pUnit:FullCastSpellOnTarget(15043, pUnit:GetRandomPlayer(0)) end function MageAdd_ConeOfCold(pUnit, Event) pUnit:FullCastSpell(38384) end function MageAdd_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function MageAdd_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24561, 1, "MageAdd_OnCombat") RegisterUnitEvent(24561, 2, "MageAdd_LeaveCombat") RegisterUnitEvent(24561, 4, "MageAdd_Died") --Warlord Salaris-Warrior function WarriorAdd_OnCombat(Unit, Event) Unit:RegisterEvent("WarriorAdd_MortalStrike", 10000, 0) Unit:RegisterEvent("WarriorAdd_Hamstring", 5000, 0) Unit:RegisterEvent("WarriorAdd_Daze", 21000, 0) Unit:RegisterEvent("WarriorAdd_FrighteningShout", 1, 0) end function WarriorAdd_MortalStrike(pUnit, Event) pUnit:FullCastSpellOnTarget(44268, pUnit:GetMainTank()) end function WarriorAdd_Hamstring(pUnit, Event) pUnit:FullCastSpellOnTarget(27584, pUnit:GetRandomPlayer(0)) end function WarriorAdd_Daze(pUnit, Event) pUnit:FullCastSpell(23600) end function WarriorAdd_FrighteningShout(pUnit, Event) if(pUnit:GetHealthPct() == 20) then pUnit:FullCastSpell(19134) end end function WarriorAdd_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function WarriorAdd_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24559, 1, "WarriorAdd_OnCombat") RegisterUnitEvent(24559, 2, "WarriorAdd_LeaveCombat") RegisterUnitEvent(24559, 4, "WarriorAdd_Died") --Garaxxas-Hunter function HunterAdd_OnCombat(Unit, Event) Unit:RegisterEvent("HunterAdd_AutoShoot", 2200, 0) Unit:RegisterEvent("HunterAdd_MultiShoot", 8000, 0) Unit:RegisterEvent("HunterAdd_Trap", 18000, 0) Unit:RegisterEvent("HunterAdd_AimedShoot", 1, 0) Unit:RegisterEvent("HunterAdd_Clip", 14000, 0) end function HunterAdd_AutoShoot(pUnit, Event) pUnit:FullCastSpellOnTarget(15620, pUnit:GetRandomPlayer(0)) end function HunterAdd_MultiShoot(pUnit, Event) pUnit:FullCastSpellOnTarget(44285, pUnit:GetRandomPlayer(0)) end function HunterAdd_Trap(pUnit, Event) pUnit:FullCastSpell(44136) end function HunterAdd_AimedShoot(pUnit, Event) if(pUnit:GetHealthPct() == 32) then pUnit:FullCastSpellOnTarget(44271, pUnit:GetRandomPlayer(0)) end end function WarriorAdd_Clip(pUnit, Event) pUnit:FullCastSpellOnTarget(44286, pUnit:GetMainTank()) end function HunterAdd_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function HunterAdd_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24555, 1, "HunterAdd_OnCombat") RegisterUnitEvent(24555, 2, "HunterAdd_LeaveCombat") RegisterUnitEvent(24555, 4, "HunterAdd_Died") --Eramas Brightblaze-Monk function Monkadd_OnCombat(Unit, Event) Unit:RegisterEvent("Monkadd_Stun", 9500, 0) Unit:RegisterEvent("Monkadd_Kick", 7200, 0) end function Monkadd_Stun(pUnit, Event) pUnit:FullCastSpellOnTarget(46183, pUnit:GetRandomPlayer(1)) end function Monkadd_Kick(pUnit, Event) pUnit:FullCastSpellOnTarget(46182, pUnit:GetRandomPlayer(1)) end function Monkadd_LeaveCombat(Unit, Event) Unit:RemoveEvents() end function Monkadd_Died(Unit, Event) Unit:RemoveEvents() end RegisterUnitEvent(24554, 1, "Monkadd_OnCombat") RegisterUnitEvent(24554, 2, "Monkadd_LeaveCombat") RegisterUnitEvent(24554, 4, "Monkadd_Died")
-- cutitout: automatically cut silence from videos -- Copyright (C) 2020 Wolf Clement -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <https://www.gnu.org/licenses/>. local enabled = false local skips = {} -- Whenever time updates, we check if we should skip mp.observe_property("time-pos", "native", function (_, pos) if pos == nil then return end if not enabled then return end for _, t in pairs(skips) do -- t[1] == start time of the skip -- t[2] == end time of the skip if t[1] <= pos and t[2] > pos then mp.set_property("time-pos", t[2]) return end end end) function reload_skips() if not enabled then return end local utils = require("mp.utils") local scripts_dir = mp.find_config_file("scripts") local cutitoutpy = utils.join_path(scripts_dir, "cutitout_shared/cutitout.py") -- Reset global skips table skips = {} local video_path = mp.get_property("path") mp.command_native_async({ name = "subprocess", capture_stdout = true, playback_only = false, args = { "python3", cutitoutpy, video_path } }, function(res, val, err) -- The string sets the "skips" table skips = loadstring(val.stdout)() print(tostring(#skips) .. " skips loaded") local time_saved = 0.0 for _, t in pairs(skips) do time_saved = time_saved + (t[2] - t[1]) end print("Time saved: " .. tostring(time_saved) .. " seconds") mp.osd_message("Silence skipping enabled.") end) end -- F12 toggles silence skipping (off by default) mp.add_key_binding("F12", "toggle_silence_skip", function () enabled = not enabled if enabled then if next(skips) == nil then mp.osd_message("Enabling silence skipping...") reload_skips() else mp.osd_message("Silence skipping enabled.") end else mp.osd_message("Silence skipping disabled.") end end) -- Whenever we load another file, we reload skips mp.register_event("file-loaded", reload_skips)
-- arcify -- test script -- -- go to the PARAMS page to assign -- params to your Arc engine.name = "TestSine" -- create Arcify class and arcify object Amotion = include("lib/amotion") function init () params:add_number("demo_param", "Demo Param", 0, 100, 50) local amotion = Amotion.new() end
local mod = RegisterMod("StageAPI", 1) --[[ FUNCTIONALITY Basic Features: Commands: cstage or customstage <StageName> -- Warps to new stage. nstage or nextstage -- Warps to next stage. extraroom <ExtraRoomName> -- Warps to extra room extraroomexit -- Cleanly exits extra room to previous room. creseed -- Akin to reseed, but guaranteed to work for and only work for custom stages. Classes: StageAPI.Class("Name", AllowMultipleInit) -- Returns a Class object, actually is one itself. Classes can be constructed simply by calling them with (), i.e, local myClass = StageAPI.Class("MyClass") local myClassInst = myClass() Classes can have a couple of functions, Init, PostInit, and InheritInit. When called like in the example above, Init and PostInit are called, passing in whatever args. However, you can keep going deeper, i.e, local myClassInstCopy = myClassInst() Which will generate another copy that inherits from myClassInst that inherits from myClass which inherits from StageAPI.Class. In that case, InheritInit will be called instead of Init and PostInit, unless AllowMultipleInit was passed in to the initial myClass definition. Classes are used for a majority of StageAPI objects. Callbacks: StageAPI.AddCallback(modID, id, priority, function, params...) -- Stores a function and its params in a table indexed by ID and sorted by priority, where low priority is at the start. StageAPI.GetCallbacks(id) -- Gets a list of callbacks from the table by the ID, sorted by priority. StageAPI.UnregisterCallbacks(modID) -- Unregisters all mod callbacks, should be used when a mod loads, useful for luamod. Individual callbacks tables are arranged like so { Priority = integer, Function = function, Params = {params...}, ModID = modID } StageAPI.CallCallbacks(id, breakOnFirstReturn, params...) -- Calls all callbacks with ID, passing in additional params. If breakOnFirstReturn is defined, breaks and returns the first non-nil return value. StageAPI callbacks all use string IDs, i.e, AddCallback("POST_CHECK_VALID_ROOM", 1, function, params) Callback List: - POST_CHECK_VALID_ROOM(layout, roomList, seed, shape, rtype, requireRoomType) -- Return false to invalidate a room layout, return integer to specify new weight. - PRE_SELECT_GRIDENTITY_LIST(GridDataList, spawnIndex) -- Takes 1 return value. If false, cancels selecting the list. If GridData, selects it to spawn. -- With no value, picks at random. - PRE_SELECT_ENTITY_LIST(entityList, spawnIndex, addEntities) -- Takes 4 return values, AddEntities, EntityList, StillAddRandom, and NoBreak. If the first value is false, cancels selecting the list. -- AddEntities and EntityList are lists of EntityData tables, described below. -- Usually StageAPI will pick one entity from the EntityList to add to the AddEntities table at random, but that can be changed with this callback. -- If StillAddRandom is true, StageAPI will still add a random entity from the entitylist to addentities, alongside ones you returned. - PRE_SPAWN_ENTITY_LIST(entityList, spawnIndex, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions) -- Takes 1 return value. If false, cancels spawning the entity list. If a table, uses it as the entity list. Any return value breaks out of future callbacks. -- Every entity in the final entity list is spawned. -- Note that this entity list contains EntityInfo tables rather than EntityData, which contain persistent room-specific data. Both detailed below. - PRE_SPAWN_ENTITY(entityInfo, entityList, index, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions, shouldSpawnEntity) -- Takes 1 return value. If false, cancels spawning the entity info. If a table, uses it as the entity info. Any return value breaks out of future callbacks. - PRE_SPAWN_GRID(gridData, gridInformation, entities, gridSpawnRNG) -- Takes 1 return value. If false, cancels spawning the grid. If a table, uses it as the grid data. Any return value breaks out of future callbacks. - PRE_ROOM_LAYOUT_CHOOSE(currentRoom, roomsList) -- Takes 1 return value. If a table, uses it as the current room layout. Otherwise, chooses from the roomslist with seeded RNG. Breaks on first return. -- Called both on initial room load and when continuing game, before INIT. - POST_ROOM_INIT(currentRoom, fromSaveData, saveData) -- Called when a room initializes. Can occur at two times, when a room is initially entered or when a room is loaded from save data. Takes no return values. - POST_ROOM_LOAD(currentRoom, isFirstLoad, isExtraRoom) -- Called when a room is loaded. Takes no return value. - POST_SPAWN_CUSTOM_GRID(spawnIndex, force, reSpawning, grid, persistentData, CustomGrid) -- Takes CustomGridTypeName as first callback parameter, and will only run if parameter not supplied or matches current grid. - POST_CUSTOM_GRID_UPDATE(grid, spawnIndex, persistData, CustomGrid, customGridTypeName) -- Takes CustomGridTypeName as first callback parameter, and will only run if parameter not supplied or matches current grid. - POST_CUSTOM_GRID_REMOVE(spawnIndex, persistData, CustomGrid, customGridTypeName) -- Takes CustomGridTypeName as first callback parameter, and will only run if parameter not supplied or matches current grid. - PRE_TRANSITION_RENDER() -- Called before the custom room transition would render, for effects that should render before it. - POST_SPAWN_CUSTOM_DOOR(door, data, sprite, CustomDoor, persistData, index, force, respawning, grid, CustomGrid) -- Takes CustomDoorName as first callback parameter, and will only run if parameter not supplied or matches current door. - POST_CUSTOM_DOOR_UPDATE(door, data, sprite, CustomDoor, persistData) -- Takes CustomDoorName as first callback parameter, and will only run if parameter not supplied or matches current door. - PRE_SELECT_BOSS(bosses, allowHorseman, rng) -- If a boss is returned, uses it instead. - POST_OVERRIDDEN_GRID_BREAK(grindex, grid, justBrokenGridSpawns) -- Called when an overridden grid reaches its break state and is considered broken. justBrokenGridSpawns contains all deleted spawns from the grid. Breaks on first non-nil return. - POST_GRID_UPDATE() -- Calls when the number of grids changes or grids are reprocessed. This is when room grid graphics are changed. - PRE_UPDATE_GRID_GFX() -- Allows returning gridgfx to use in place of the stage's. - PRE_CHANGE_ROOM_GFX(currentRoom) -- Allows returning roomgfx to use in place of the stage's. - POST_CHANGE_ROOM_GFX() - PRE_STAGEAPI_NEW_ROOM() -- runs before most but not all stageapi room functionality. guaranteed to run before any room loads. - POST_STAGEAPI_NEW_ROOM_GENERATION(justGenerated, currentRoom) -- allows returning justGenerated and currentRoom. run after normal room generation but before reloading old rooms. - POST_STAGEAPI_NEW_ROOM() -- all loading and processing of new room generation and old room loading is done, but the gfx hasn't changed yet - PRE_SELECT_NEXT_STAGE(currentstage) -- return a stage to go to instead of currentstage.NextStage or none. - PRE_SHADING_RENDER(shadingEntity) - POST_SHADING_RENDER(shadingEntity) -- StageAPI Structures: EntityData { Type = integer, Variant = integer, SubType = integer, GridX = integer, GridY = integer, Index = integer } GridData { Type = integer, Variant = integer, GridX = integer, GridY = integer, Index = integer } EntityInfo { Data = EntityData, PersistentIndex = integer, Persistent = boolean, PersistenceData = PersistenceData } PersistenceData { Type = etype, Variant = variant, SubType = subtype, AutoPersists = autoPersists, RemoveOnRemove = removeOnRemove, RemoveOnDeath = removeOnDeath, UpdatePosition = updatePosition, StoreCheck = storeCheck } PersistenceFunction(EntityData) return PersistenceData end Backdrop { NFloors = {filenames}, LFloors = {filenames}, Corners = {filenames}, Walls = {filenames} } BossData { Name = string, NameTwo = string, Portrait = string, PortraitTwo = string, Weight = integer, Horseman = boolean, Rooms = RoomsList, Shapes = {RoomShapes} } Bosses { BossDataID, ... } DoorInfo { RequireCurrent = {RoomTypes}, RequireTarget = {RoomTypes}, RequireEither = {RoomTypes}, NotCurrent = {RoomTypes}, NotTarget = {RoomTypes}, NotEither = {RoomTypes} } VanillaStage { NormalStage = true, Stage = LevelStage, StageType = StageType } CustomGridIndexData { Name = CustomGridName, PersistData = persistData, Data = CustomGrid, Index = gridIndex } GridContainer { Grid = GridEntity, Type = GridEntityType, Desc = GridEntityDesc, Index = gridIndex } StageOverrideStage { OverrideStage = LevelStage.STAGE2_1, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = CustomStage } Shading = shadingPrefix .. "_RoomShape" .. shadingName StageAPI Variables: StageOverride { CatacombsOne = StageOverrideStage, CatacombsTwo = StageOverrideStage } DefaultDoorSpawn = DoorInfo -- where default doors should spawn SecretDoorSpawn = DoorInfo -- where secret room doors should spawn StageAPI Objects: - GridGfx() -- SetGrid(filename, GridEntityType, variant) -- SetRocks(filename) -- SetPits(filename, altpitsfilename, hasExtraFrames) -- Alt Pits are used where water pits would be. HasExtraFrames controls for situations where the base game would not normally tile pits specially -- OR, with lists of { File, HasExtraFrames } -- SetPits(filenames, altpitsfilenames) (see utero override) -- SetBridges(filename) -- SetDecorations(filename) -- AddDoors(filename, DoorInfo) -- SetPayToPlayDoor(filename) - RoomGfx(Backdrop, GridGfx, shadingName, shadingPrefix) - RoomsList(name, roomfiles...) -- NAME IS NOT OPTIONAL. USED FOR SAVING / LOADING ROOMS. -- AddRooms(roomfiles...) -- automatically called on init. - LevelRoom(layoutName, roomsList, seed, shape, roomType, isExtraRoom, saveData, requireRoomType) -- PostGetLayout(seed) -- second part of init that is called both when loaded from save and normally, after most other things are initialized. gets spawn ents and grids -- RemovePersistentIndex(persistentIndex) -- RemovePersistentEntity(entity) -- Load(isExtraRoom) -- SaveGridInformation() -- Save functions only called for extra rooms, usually. -- SavePersistentEntities() -- Save() -- GetSaveData() -- LoadSaveData(saveData) -- SetTypeOverride(override) - CustomStage(name, StageOverrideStage, noSetReplaces) -- replaces defaults to catacombs one if noSetReplaces is not set. -- NAME IS NOT OPTIONAL. USED TO IDENTIFY STAGE AND FOR SAVING CURRENT STAGE. -- InheritInit(name, noSetAlias) -- automatically aliases the new stage to the old one, if noSetAlias is not set, meaning that IsStage calls on either will return true if either is active. STILL NEEDS A UNIQUE NAME. -- SetName(name) -- SetDisplayName(name) -- SetReplace(StageOverrideStage) -- SetNextStage(CustomStage) -- SetRoomGfx(RoomGfx) -- SetRooms(RoomsList) -- SetMusic(musicID, RoomType) -- SetBossMusic(musicID, clearedMusicID) -- SetSpots(bossSpot, playerSpot) -- SetBosses(Bosses) -- GetPlayingMusic() -- OverrideRockAltEffects() -- SetTransitionIcon(icon) -- IsStage(noAlias) - CustomGrid(name, GridEntityType, baseVariant, anm2, animation, frame, variantFrames, offset, overrideGridSpawns, overrideGridSpawnAtState, forceSpawning) -- NAME IS NOT OPTIONAL. USED FOR IDENTIFICATION AFTER SAVING. -- Spawn(grindex, force, reSpawning, initialPersistData) -- only sets persistData if not already defined. - CustomDoor(name, anm2, openAnim, closeAnim, openedAnim, closedAnim, noAutoHandling, alwaysOpen) -- NAME IS NOT OPTIONAL. USED FOR IDENTIFICATION AFTER SAVING. - Overlay(anm2, velocity, offset, size) -- SetAlpha(alpha, noCancelFade) -- Fade(total, time, step) -- Fades from time to total incrementing by step. Use a step of -1 and a time equal to total to fade out. -- Render(noCenterCorrect) Various useful tools: Random(min, max, rng) WeightedRNG(table, rng, weightKey, preCalculatedWeight) GotoCustomStage(CustomStage, playTransition) -- also accepts VanillaStage SpawnCustomTrapdoor(position, goesTo<CustomStage>, anm2, size, alreadyEntering) AddBossData(id, BossData) -- ID is needed for save / resume. GetBossData(id) IsDoorSlotAllowed(slot) -- needed in custom rooms SetExtraRoom(name, room) GetExtraRoom(name) InOrTransitioningToExtraRoom() TransitioningToOrFromExtraRoom() TransitionToExtraRoom(name, exitSlot) TransitionFromExtraRoom(toNormalRoomIndex, exitSlot) SpawnCustomDoor(slot, leadsToExtraRoomName, leadsToNormalRoomIndex, CustomDoorName, data(at persistData.Data), exitSlot) SetDoorOpen(open, door) GetCustomGridIndicesByName(name) GetCustomGridsByName(name) -- returns list of CustomGridIndexData GetCustomGrids() -- returns list of CustomGridIndexData GetCustomDoors(doorDataName) -- returns list of CustomGridIndexData IsCustomGrid(index, name) -- if name not specified just returns if there is a custom grid at index InOverriddenStage() -- true if in new stage or in override stage InOverrideStage() -- true if in override stage InNewStage() -- true only if inoverriddenstage and not inoverridestage. GetCurrentStage() GetCurrentStageDisplayName() -- used for streaks GetCurrentListIndex() GetCurrentRoomID() -- returns list index or extra room name SetCurrentRoom(LevelRoom) GetCurrentRoom() GetCurrentRoomType() -- returns TypeOverride, or RoomType, or room:GetType() GetRooms() AddEntityPersistenceData(PersistenceData) AddPersistenceCheck(PersistenceFunction) CheckPersistence(id, variant, subtype) -- returns PersistenceData SetRoomFromList(roomsList, roomType, requireRoomType, isExtraRoom, load, seed, shape, fromSaveData) -- full room generation package. Initializes it, sets it, loads it, and returns it. RemovePersistentEntity(entity) -- mapped directly to LevelRoom function of the same name ChangeRock(GridContainer) ChangeDecoration(GridContainer, filename) ChangePit(GridContainer, filename, bridgefilename, altfilename) CheckBridge(GridEntity, gridIndex, bridgefilename) ChangeDoor(GridContainer, DoorInfo, payToPlayFilename) DoesDoorMatch(GridEntityDoor, DoorSpawn) ChangeGrid(GridContainer, filename) ChangeSingleGrid(GridEntity, GridGfx, gridIndex) ChangeGrids(GridGfx) ChangeBackdrop(Backdrop) ChangeShading(name, prefix) ChangeRoomGfx(RoomGfx) PlayTextStreak(params) -- returns params, use as a reference to update Hold, etc -- text values cannot be changed after init params = { Text = Main text, supports newlines (\n) TextOffset = positional offset for main text BaseFontScale = scale for main text, vector Font = Font used for main text, defaults to upheaval LineSpacing = spacing between newlines, defaults to 1 ExtraText = additional text usually used for item descriptions, unused by stageapi ExtraOffset = positional offset for extra text ExtraFontScale = scale for extra text, vector SmallFont = Font used for extra text, defaults to pftempestasevencondensed (item description font) Spritesheet = sprite for the streak bg, defaults to vanilla item streak SpriteOffset = positional offset for the streak bg Color = text color, used for all text RenderPos = Position the streak will be rendered at, defaults to item/new floor streak position Hold = set to true to hold streak indefinitely once it reaches default position, set to false when ready to continue HoldFrames = number of frames to hold the streak, defaults to 52 } IsIn(table, value, iterator) -- iterator defaults to ipairs GetPlayingAnimation(sprite, animationList) VectorToGrid(x, y, width) GridToVector(index, width) GetScreenCenterPosition() GetScreenBottomRight() Lerp(first, second, percent) ReverseIterate() -- in place of ipairs / pairs. ]] Isaac.DebugString("[StageAPI] Loading Core Definitions") do -- Core Definitions if not StageAPI then StageAPI = {} end function StageAPI.Log(str) str = '[StageAPI] ' .. str Isaac.ConsoleOutput(str .. '\n') Isaac.DebugString(str) end StageAPI.RockTypes = { [GridEntityType.GRID_ROCK] = true, [GridEntityType.GRID_ROCKB] = true, [GridEntityType.GRID_ROCKT] = true, [GridEntityType.GRID_ROCK_BOMB] = true, [GridEntityType.GRID_ROCK_ALT] = true, [GridEntityType.GRID_ROCK_SS] = true, [GridEntityType.GRID_PILLAR] = true, [GridEntityType.GRID_ROCK_SPIKED] = true, [GridEntityType.GRID_ROCK_ALT2] = true, [GridEntityType.GRID_ROCK_GOLD] = true, } StageAPI.PoopVariant = { Normal = 0, Red = 1, Eternal = 2, Golden = 3, Rainbow = 4, Black = 5, White = 6, Charming = 11 } StageAPI.CorrectedGridTypes = { [1000]=GridEntityType.GRID_ROCK, [1001]=GridEntityType.GRID_ROCK_BOMB, [1002]=GridEntityType.GRID_ROCK_ALT, [1008]=GridEntityType.GRID_ROCK_ALT2, [1010]=GridEntityType.GRID_ROCK_SPIKED, [1011]=GridEntityType.GRID_ROCK_GOLD, [1300]=GridEntityType.GRID_TNT, [1499]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Normal}, -- giant, does not work [1498]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.White}, [1497]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Black}, [1496]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Golden}, [1495]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Eternal}, [1494]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Rainbow}, [1490]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Red}, [1500]=GridEntityType.GRID_POOP, [1501]={Type = GridEntityType.GRID_POOP, Variant = StageAPI.PoopVariant.Charming}, [1900]=GridEntityType.GRID_ROCKB, [1901]=GridEntityType.GRID_PILLAR, [1930]=GridEntityType.GRID_SPIKES, [1931]=GridEntityType.GRID_SPIKES_ONOFF, [1940]=GridEntityType.GRID_SPIDERWEB, [1999]=GridEntityType.GRID_WALL, [3000]=GridEntityType.GRID_PIT, [4000]=GridEntityType.GRID_LOCK, [4500]=GridEntityType.GRID_PRESSURE_PLATE, [5000]=GridEntityType.GRID_STATUE, [5001]={Type = GridEntityType.GRID_STATUE, Variant = 1}, [9000]=GridEntityType.GRID_TRAPDOOR, [9100]=GridEntityType.GRID_STAIRS, [10000]=GridEntityType.GRID_GRAVITY } StageAPI.E = { MetaEntity = "StageAPIMetaEntity", Backdrop = "StageAPIBackdrop", Shading = "StageAPIShading", StageShadow = "StageAPIStageShadow", GenericEffect = "StageAPIGenericEffect", FloorEffect = "StageAPIFloorEffect", Trapdoor = "StageAPITrapdoor", Door = "StageAPIDoor", DeleteMeEffect = "StageAPIDeleteMeEffect", DeleteMeNPC = "StageAPIDeleteMeNPC", DeleteMeProjectile = "StageAPIDeleteMeProjectile", DeleteMePickup = "StageAPIDeleteMePickup", RandomRune = "StageAPIRandomRune" } StageAPI.S = { BossIntro = Isaac.GetSoundIdByName("StageAPI Boss Intro") } StageAPI.Game = Game() StageAPI.Players = {} function StageAPI.TryLoadModData(continued) if Isaac.HasModData(mod) and continued then local data = Isaac.LoadModData(mod) StageAPI.LoadSaveString(data) else StageAPI.CurrentStage = nil StageAPI.LevelRooms = {} StageAPI.RoomGrids = {} StageAPI.CustomGrids = {} StageAPI.CurrentExtraRoom = nil StageAPI.CurrentExtraRoomName = nil end end function StageAPI.SaveModData() Isaac.SaveModData(mod, StageAPI.GetSaveString()) end if Isaac.GetPlayer(0) then StageAPI.Room = StageAPI.Game:GetRoom() StageAPI.Level = StageAPI.Game:GetLevel() local numPlayers = StageAPI.Game:GetNumPlayers() if numPlayers > 0 then for i = 1, numPlayers do StageAPI.Players[i] = Isaac.GetPlayer(i - 1) end end end StageAPI.ZeroVector = Vector(0, 0) mod:AddCallback(ModCallbacks.MC_POST_PLAYER_INIT, function() StageAPI.Level = StageAPI.Game:GetLevel() StageAPI.Room = StageAPI.Game:GetRoom() local highestPlayerFrame for i = 1, StageAPI.Game:GetNumPlayers() do StageAPI.Players[i] = Isaac.GetPlayer(i - 1) local frame = StageAPI.Players[i].FrameCount if not highestPlayerFrame or frame > highestPlayerFrame then highestPlayerFrame = frame end end if highestPlayerFrame < 3 then StageAPI.TryLoadModData(StageAPI.Game:GetFrameCount() > 2) end end) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() local numPlayers = StageAPI.Game:GetNumPlayers() if numPlayers ~= #StageAPI.Players then StageAPI.Players = {} for i = 1, numPlayers do StageAPI.Players[i] = Isaac.GetPlayer(i - 1) end end end) mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.Level = StageAPI.Game:GetLevel() StageAPI.Room = StageAPI.Game:GetRoom() end) end -- local, so needs to be outside of do/end local localToStageAPIMap = { game = "Game", room = "Room", level = "Level", players = "Players", zeroVector = "ZeroVector" } local sfx = SFXManager() local oldENV = _ENV local _ENV = {} oldENV.setmetatable(_ENV, { __index = function(tbl, k) if localToStageAPIMap[k] then return StageAPI[localToStageAPIMap[k]] elseif oldENV[k] then return oldENV[k] end end }) --local game, room, level, players, zeroVector = StageAPI.Game, StageAPI.Room, StageAPI.Level, StageAPI.Players, StageAPI.ZeroVector Isaac.DebugString("[StageAPI] Loading Core Functions") do -- Core Functions mod:AddCallback(ModCallbacks.MC_PRE_GAME_EXIT, function(_, shouldSave) StageAPI.Players = {} players = StageAPI.Players if shouldSave then StageAPI.SaveModData() end end) mod:AddCallback(ModCallbacks.MC_POST_NEW_LEVEL, function() StageAPI.SaveModData() end) StageAPI.RandomRNG = RNG() StageAPI.RandomRNG:SetSeed(Random(), 0) function StageAPI.Random(a, b, rng) rng = rng or StageAPI.RandomRNG if a and b then -- TODO remove after Rev update if b - a < 0 then StageAPI.Log('Bad Random Range! ' .. a .. ', ' .. b) return b - a end return rng:Next() % (b - a + 1) + a elseif a then -- TODO remove after Rev update if a < 0 then StageAPI.Log('Bad Random Max! ' .. a) return a end return rng:Next() % (a + 1) end return rng:Next() end function StageAPI.WeightedRNG(args, rng, key, preCalculatedWeight) -- takes tables {{obj, weight}, {"pie", 3}, {555, 0}} local weight_value = preCalculatedWeight or 0 local iterated_weight = 1 if not preCalculatedWeight then for _, potentialObject in ipairs(args) do if key then weight_value = weight_value + potentialObject[key] else weight_value = weight_value + potentialObject[2] end end end rng = rng or StageAPI.RandomRNG local random_chance = StageAPI.Random(1, weight_value, rng) for i, potentialObject in ipairs(args) do if key then iterated_weight = iterated_weight + potentialObject[key] else iterated_weight = iterated_weight + potentialObject[2] end if iterated_weight > random_chance then local ret = potentialObject if key then return ret, i else return ret[1], i end end end end StageAPI.Class = {} function StageAPI.ClassInit(tbl, ...) local inst = {} setmetatable(inst, tbl) tbl.__index = tbl tbl.__call = StageAPI.ClassInit if inst.AllowMultipleInit or not inst.Initialized then inst.Initialized = true if inst.Init then inst:Init(...) end if inst.PostInit then inst:PostInit(...) end else if inst.InheritInit then inst:InheritInit(...) end end return inst end function StageAPI.Class:Init(Type, AllowMultipleInit) self.Type = Type self.AllowMultipleInit = AllowMultipleInit self.Initialized = false end setmetatable(StageAPI.Class, { __call = StageAPI.ClassInit }) StageAPI.Callbacks = {} local function Reverse_Iterator(t,i) i=i-1 local v=t[i] if v==nil then return v end return i,v end function StageAPI.ReverseIterate(t) return Reverse_Iterator, t, #t+1 end function StageAPI.AddCallback(modID, id, priority, fn, ...) if not StageAPI.Callbacks[id] then StageAPI.Callbacks[id] = {} end local index = 1 for i, callback in StageAPI.ReverseIterate(StageAPI.Callbacks[id]) do if priority > callback.Priority then index = i + 1 break end end table.insert(StageAPI.Callbacks[id], index, { Priority = priority, Function = fn, ModID = modID, Params = {...} }) end function StageAPI.UnregisterCallbacks(modID) for id, callbacks in pairs(StageAPI.Callbacks) do for i, callback in StageAPI.ReverseIterate(callbacks) do if callback.ModID == modID then table.remove(callbacks, i) end end end end StageAPI.UnregisterCallbacks("StageAPI") function StageAPI.GetCallbacks(id) return StageAPI.Callbacks[id] or {} end function StageAPI.CallCallbacks(id, breakOnFirstReturn, ...) for _, callback in ipairs(StageAPI.GetCallbacks(id)) do local ret = callback.Function(...) if breakOnFirstReturn and ret ~= nil then return ret end end end function StageAPI.IsIn(tbl, v, fn) fn = fn or ipairs for k, v2 in fn(tbl) do if v2 == v then return k or true end end end function StageAPI.Copy(tbl) local t = {} for k, v in pairs(tbl) do t[k] = v end return t end function StageAPI.GetPlayingAnimation(sprite, animations) for _, anim in ipairs(animations) do if sprite:IsPlaying(anim) then return anim end end end function StageAPI.VectorToGrid(x, y, width) width = width or room:GetGridWidth() return width + 1 + (x + width * y) end function StageAPI.GridToVector(index, width) width = width or room:GetGridWidth() return (index % width) - 1, (math.floor(index / width)) - 1 end function StageAPI.GetScreenBottomRight() return room:GetRenderSurfaceTopLeft() * 2 + Vector(442,286) end function StageAPI.GetScreenCenterPosition() return StageAPI.GetScreenBottomRight() / 2 end StageAPI.DefaultScreenSize = Vector(480, 270) function StageAPI.GetScreenScale(vec) local bottomRight = StageAPI.GetScreenBottomRight() if vec then return Vector(bottomRight.X / StageAPI.DefaultScreenSize.X, bottomRight.Y / StageAPI.DefaultScreenSize.Y) else return bottomRight.X / StageAPI.DefaultScreenSize.X, bottomRight.Y / StageAPI.DefaultScreenSize.Y end end function StageAPI.Lerp(first, second, percent) return first * (1 - percent) + second * percent end local TextStreakScales = { [0] = Vector(3,0.2), [1] = Vector(2.6,0.36), [2] = Vector(2.2,0.52), [3] = Vector(1.8,0.68), [4] = Vector(1.4,0.84), [5] = Vector(0.95,1.05), [6] = Vector(0.97,1.03), [7] = Vector(0.98,1.02), -- frame 8 is the hold frame [9] = Vector(0.99,1.03), [10] = Vector(0.98,1.05), [11] = Vector(0.96,1.08), [12] = Vector(0.95,1.1), [13] = Vector(1.36,0.92), [14] = Vector(1.77,0.74), [15] = Vector(2.18,0.56), [16] = Vector(2.59,0.38), [17] = Vector(3,0.2) } local TextStreakPositions = { [0] = -800, [1] = -639, [2] = -450, [3] = -250, [4] = -70, [5] = 10, [6] = 6, [7] = 3, [9] = -5, [10] = -10, [11] = -15, [12] = -20, [13] = 144, [14] = 308, [15] = 472, [16] = 636, [17] =800 } local StreakSprites = {} local Streaks = {} local streakFont = Font() streakFont:Load("font/upheaval.fnt") local streakSmallFont = Font() streakSmallFont:Load("font/pftempestasevencondensed.fnt") local streakDefaultHoldFrames = 52 local streakDefaultSpritesheet = "stageapi/streak.png" local streakDefaultColor = KColor(1,1,1,1,0,0,0) local streakDefaultPos = Vector(240, 48) local oneVector = Vector(1, 1) function StageAPI.PlayTextStreak(text, extratext, extratextOffset, extratextScaleMulti, replaceSpritesheet, spriteOffset, font, smallFont, color) local streak if type(text) == "table" then streak = text else streak = { Text = text, ExtraText = extratext, Color = color, Font = font, SpriteOffset = spriteOffset, SmallFont = smallFont, ExtraFontScale = extratextScaleMulti, ExtraOffset = extratextOffset, Spritesheet = replaceSpritesheet } end local splitLines = {} streak.Text:gsub("([^\n]+)", function(c) table.insert(splitLines, { Text = c }) end) streak.Text = splitLines streak.Color = streak.Color or streakDefaultColor streak.Font = streak.Font or streakFont streak.SmallFont = streak.SmallFont or streakSmallFont streak.RenderPos = streak.RenderPos or streakDefaultPos --streak.BaseFontScale = streak.BaseFontScale or oneVector streak.ExtraFontScale = streak.ExtraFontScale or oneVector streak.SpriteOffset = streak.SpriteOffset or zeroVector streak.TextOffset = streak.TextOffset or zeroVector streak.ExtraOffset = streak.ExtraOffset or zeroVector streak.Spritesheet = streak.Spritesheet or streakDefaultSpritesheet streak.LineSpacing = streak.LineSpacing or 1 streak.Hold = streak.Hold or false streak.HoldFrames = streak.HoldFrames or streakDefaultHoldFrames streak.Frame = 0 for _, line in pairs(streak.Text) do line.Width = streak.Font:GetStringWidth(line.Text) / 2 end streak.ExtraWidth = streak.SmallFont:GetStringWidth(streak.ExtraText or "") / 2 local index = #Streaks + 1 streak.SpriteIndex = index local streakSprite = StreakSprites[index] if not streakSprite then -- this system loads as many sprites as it has to play at once StreakSprites[index] = {} streakSprite = StreakSprites[index] streakSprite.Sprite = Sprite() streakSprite.Sprite:Load("stageapi/streak.anm2", true) streakSprite.Spritesheet = streakDefaultSpritesheet end if streak.Spritesheet ~= streakSprite.Spritesheet then streakSprite.Spritesheet = streak.Spritesheet streakSprite.Sprite:ReplaceSpritesheet(0, streak.Spritesheet) streakSprite.Sprite:LoadGraphics() end streakSprite.Sprite.Offset = streak.SpriteOffset streakSprite.Sprite:Play("Text", true) Streaks[index] = streak return streak end function StageAPI.UpdateTextStreak() for index, streakPlaying in StageAPI.ReverseIterate(Streaks) do local sprite = StreakSprites[streakPlaying.SpriteIndex].Sprite if streakPlaying.Frame == 8 then if streakPlaying.Hold then sprite.PlaybackSpeed = 0 elseif streakPlaying.HoldFrames > 0 then sprite.PlaybackSpeed = 0 streakPlaying.HoldFrames = streakPlaying.HoldFrames - 1 else sprite.PlaybackSpeed = 1 end end sprite:Update() streakPlaying.Frame = sprite:GetFrame() if streakPlaying.Frame >= 17 then sprite:Stop() table.remove(Streaks, index) streakPlaying.Finished = true end streakPlaying.FontScale = (TextStreakScales[streakPlaying.Frame] or oneVector) if streakPlaying.BaseFontScale then streakPlaying.FontScale = Vector(streakPlaying.FontScale.X * streakPlaying.BaseFontScale.X, streakPlaying.FontScale.X * streakPlaying.BaseFontScale.Y) end local screenX = StageAPI.GetScreenCenterPosition().X streakPlaying.RenderPos.X = screenX for _, line in ipairs(streakPlaying.Text) do line.PositionX = (TextStreakPositions[streakPlaying.Frame] or 0) - line.Width * streakPlaying.FontScale.X + screenX + 0.25 end streakPlaying.ExtraPositionX = (TextStreakPositions[streakPlaying.Frame] or 0) - (streakPlaying.ExtraWidth / 2) * streakPlaying.FontScale.X + screenX + 0.25 streakPlaying.Updated = true end end function StageAPI.RenderTextStreak() for index, streakPlaying in StageAPI.ReverseIterate(Streaks) do if streakPlaying.Updated then local sprite = StreakSprites[streakPlaying.SpriteIndex].Sprite sprite:Render(streakPlaying.RenderPos, zeroVector, zeroVector) local height = streakPlaying.Font:GetLineHeight() * streakPlaying.LineSpacing * streakPlaying.FontScale.Y for i, line in ipairs(streakPlaying.Text) do streakPlaying.Font:DrawStringScaled(line.Text, line.PositionX + streakPlaying.TextOffset.X, streakPlaying.RenderPos.Y - 9 + (i - 1) * height + streakPlaying.TextOffset.Y, streakPlaying.FontScale.X, streakPlaying.FontScale.Y, streakPlaying.Color, 0, true) end if streakPlaying.ExtraText then streakPlaying.SmallFont:DrawStringScaled(streakPlaying.ExtraText, streakPlaying.ExtraPositionX + streakPlaying.ExtraOffset.X, (streakPlaying.RenderPos.Y - 9) + streakPlaying.ExtraOffset.Y, streakPlaying.FontScale.X * streakPlaying.ExtraFontScale.X, 1 * streakPlaying.ExtraFontScale.Y, streakPlaying.Color, 0, true) end end end end mod:AddCallback(ModCallbacks.MC_POST_UPDATE, StageAPI.UpdateTextStreak) mod:AddCallback(ModCallbacks.MC_POST_RENDER, StageAPI.RenderTextStreak) for k, v in pairs(StageAPI.E) do StageAPI.E[k] = { T = Isaac.GetEntityTypeByName(v), V = Isaac.GetEntityVariantByName(v), S = 0 } end StageAPI.E.FloorEffectCreep = { T = EntityType.ENTITY_EFFECT, V = EffectVariant.CREEP_RED, S = 12545 } function StageAPI.SpawnFloorEffect(pos, velocity, spawner, anm2, loadGraphics, variant) local eff = Isaac.Spawn(StageAPI.E.FloorEffectCreep.T, StageAPI.E.FloorEffectCreep.V, StageAPI.E.FloorEffectCreep.S, pos or zeroVector, velocity or zeroVector, spawner) eff.Variant = variant or StageAPI.E.FloorEffect.V if anm2 then eff:GetSprite():Load(anm2, loadGraphics) end return eff end end Isaac.DebugString("[StageAPI] Loading Overlay System") do -- Overlays StageAPI.DebugTiling = false function StageAPI.RenderSpriteTiled(sprite, position, size, centerCorrect) local screenBottomRight = StageAPI.GetScreenBottomRight() local screenFitX = screenBottomRight.X / size.X local screenFitY = screenBottomRight.Y / size.Y local timesRendered = 0 for x = -1, math.ceil(screenFitX) do for y = -1, math.ceil(screenFitY) do local pos = position + Vector(size.X * x, size.Y * y):Rotated(sprite.Rotation) if centerCorrect then pos = pos + Vector( size.X * x, size.Y * y ):Rotated(sprite.Rotation) end sprite:Render(pos, zeroVector, zeroVector) if StageAPI.DebugTiling then timesRendered = timesRendered + 1 Isaac.RenderText("RenderPoint (" .. tostring(timesRendered) .. "): " .. tostring(x) .. ", " .. tostring(y), pos.X, pos.Y, 255, 0, 0, 1) end end end end StageAPI.OverlayDefaultSize = Vector(512, 512) StageAPI.Overlay = StageAPI.Class("Overlay") function StageAPI.Overlay:Init(file, velocity, offset, size, alpha) self.Sprite = Sprite() self.Sprite:Load(file, true) self.Sprite:Play("Idle", true) self.Position = zeroVector self.Velocity = velocity or zeroVector self.Offset = offset or zeroVector self.Size = size or StageAPI.OverlayDefaultSize if alpha then self:SetAlpha(alpha, true) end end function StageAPI.Overlay:SetAlpha(alpha, noCancelFade) local sprite = self.Sprite self.Alpha = alpha sprite.Color = Color(sprite.Color.R, sprite.Color.G, sprite.Color.B, alpha, sprite.Color.RO, sprite.Color.GO, sprite.Color.BO) if not noCancelFade then self.Fading = false self.FadingFinished = nil self.FadeTime = nil self.FadeTotal = nil self.FadeStep = nil end end function StageAPI.Overlay:Fade(total, time, step) -- use a step of -1 to fade out step = step or 1 self.FadeTotal = total self.FadeTime = time self.FadeStep = step self.Fading = true self.FadingFinished = false end function StageAPI.Overlay:Update() if self.Velocity then self.Position = self.Position + self.Velocity self.Position = self.Position:Rotated(-self.Sprite.Rotation) if self.Position.X >= self.Size.X then self.Position = Vector(self.Position.X - self.Size.X, self.Position.Y) end if self.Position.Y >= self.Size.Y then self.Position = Vector(self.Position.X, self.Position.Y - self.Size.Y) end if self.Position.X < 0 then self.Position = Vector(self.Position.X + self.Size.X, self.Position.Y) end if self.Position.Y < 0 then self.Position = Vector(self.Position.X, self.Position.Y + self.Size.Y) end self.Position = self.Position:Rotated(self.Sprite.Rotation) end end function StageAPI.Overlay:Render(noCenterCorrect, additionalOffset, noUpdate) local centerCorrect = not noCenterCorrect if self.Fading and self.FadeTime and self.FadeTotal and self.FadeStep then self.FadeTime = self.FadeTime + self.FadeStep if self.FadeTime < 0 then self.FadeTime = 0 self.Fading = false self.FadingFinished = true end if self.FadeTime > self.FadeTotal then self.FadeTime = self.FadeTotal self.Fading = false self.FadingFinished = true end self:SetAlpha(self.FadeTime / self.FadeTotal, true) end if not noUpdate then self:Update() end StageAPI.RenderSpriteTiled(self.Sprite, self.Position + (self.Offset or zeroVector) + (additionalOffset or zeroVector), self.Size, centerCorrect) if StageAPI.DebugTiling then Isaac.RenderText("OriginPoint: " .. tostring(self.Position.X) .. ", " .. tostring(self.Position.Y), self.Position.X, self.Position.Y, 0, 255, 0, 1) end end end Isaac.DebugString("[StageAPI] Loading Room Handler") do -- RoomsList StageAPI.RemappedEntities = {} function StageAPI.RemapEntity(t1, v1, s1, t2, v2, s2) v1 = v1 or "Default" s1 = s1 or "Default" if not StageAPI.RemappedEntities[t1] then StageAPI.RemappedEntities[t1] = {} end if v1 and not StageAPI.RemappedEntities[t1][v1] then StageAPI.RemappedEntities[t1][v1] = {} end StageAPI.RemappedEntities[t1][v1][s1] = { Type = t2, Variant = v2, SubType = s2 } end StageAPI.RoomShapeToWidthHeight = { [RoomShape.ROOMSHAPE_1x1] = { Width = 15, Height = 9, Slots = {DoorSlot.UP0, DoorSlot.LEFT0, DoorSlot.RIGHT0, DoorSlot.DOWN0} }, [RoomShape.ROOMSHAPE_IV] = { Width = 15, Height = 9, Slots = {DoorSlot.UP0, DoorSlot.DOWN0} }, [RoomShape.ROOMSHAPE_IH] = { Width = 15, Height = 9, Slots = {DoorSlot.LEFT0, DoorSlot.RIGHT0} }, [RoomShape.ROOMSHAPE_2x2] = { Width = 28, Height = 16, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_2x1] = { Width = 28, Height = 9, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.RIGHT0, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_1x2] = { Width = 15, Height = 16, Slots = {DoorSlot.UP0, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0} }, [RoomShape.ROOMSHAPE_IIV] = { Width = 15, Height = 16, Slots = {DoorSlot.UP0, DoorSlot.DOWN0} }, [RoomShape.ROOMSHAPE_LTL] = { Width = 28, Height = 16, LWidthEnd = 14, LHeightEnd = 8, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_LBL] = { Width = 28, Height = 16, LWidthEnd = 14, LHeightStart = 8, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_LBR] = { Width = 28, Height = 16, LWidthStart = 14, LHeightStart = 8, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_LTR] = { Width = 28, Height = 16, LWidthStart = 14, LHeightEnd = 8, Slots = {DoorSlot.UP0, DoorSlot.UP1, DoorSlot.LEFT0, DoorSlot.LEFT1, DoorSlot.RIGHT0, DoorSlot.RIGHT1, DoorSlot.DOWN0, DoorSlot.DOWN1} }, [RoomShape.ROOMSHAPE_IIH] = { Width = 28, Height = 9, Slots = {DoorSlot.LEFT0, DoorSlot.RIGHT0} } } function StageAPI.AddObjectToRoomLayout(layout, index, objtype, variant, subtype, gridX, gridY) if gridX and gridY and not index then index = StageAPI.VectorToGrid(gridX, gridY, layout.Width) end if StageAPI.CorrectedGridTypes[objtype] then local t, v = StageAPI.CorrectedGridTypes[objtype], variant if type(t) == "table" then v = t.Variant t = t.Type end local gridData = { Type = t, Variant = v, GridX = gridX, GridY = gridY, Index = index } layout.GridEntities[#layout.GridEntities + 1] = gridData if not layout.GridEntitiesByIndex[gridData.Index] then layout.GridEntitiesByIndex[gridData.Index] = {} end layout.GridEntitiesByIndex[gridData.Index][#layout.GridEntitiesByIndex[gridData.Index] + 1] = gridData elseif objtype ~= 0 then local entData = { Type = objtype, Variant = variant, SubType = subtype, GridX = gridX, GridY = gridY, Index = index } if entData.Type == 1400 or entData.Type == 1410 then entData.Type = EntityType.ENTITY_FIREPLACE if entData.Type == 1410 then entData.Variant = 1 else entData.Variant = 0 end end if entData.Type == 999 then entData.Type = 1000 end if StageAPI.RemappedEntities[entData.Type] then local remapTo if entData.Variant and StageAPI.RemappedEntities[entData.Type][entData.Variant] then if entData.SubType and StageAPI.RemappedEntities[entData.Type][entData.Variant][entData.SubType] then remapTo = StageAPI.RemappedEntities[entData.Type][entData.Variant][entData.SubType] elseif StageAPI.RemappedEntities[entData.Type][entData.Variant]["Default"] then remapTo = StageAPI.RemappedEntities[entData.Type][entData.Variant]["Default"] end elseif StageAPI.RemappedEntities[entData.Type]["Default"] then remapTo = StageAPI.RemappedEntities[entData.Type]["Default"]["Default"] end if remapTo then entData.Type = remapTo.Type if remapTo.Variant then entData.Variant = remapTo.Variant end if remapTo.SubType then entData.SubType = remapTo.SubType end end end if not layout.EntitiesByIndex[entData.Index] then layout.EntitiesByIndex[entData.Index] = {} end layout.EntitiesByIndex[entData.Index][#layout.EntitiesByIndex[entData.Index] + 1] = entData layout.Entities[#layout.Entities + 1] = entData end end StageAPI.LastRoomID = 0 function StageAPI.SimplifyRoomLayout(layout) local outLayout = { GridEntities = {}, GridEntitiesByIndex = {}, Entities = {}, EntitiesByIndex = {}, Doors = {}, Shape = layout.SHAPE, Weight = layout.WEIGHT, Difficulty = layout.DIFFICULTY, Name = layout.NAME, Width = layout.WIDTH + 2, Height = layout.HEIGHT + 2, Type = layout.TYPE, Variant = layout.VARIANT, SubType = layout.SUBTYPE, StageAPIID = StageAPI.LastRoomID + 1, PreSimplified = true } StageAPI.LastRoomID = outLayout.StageAPIID local widthHeight = StageAPI.RoomShapeToWidthHeight[outLayout.Shape] if widthHeight then outLayout.LWidthStart = widthHeight.LWidthStart outLayout.LWidthEnd = widthHeight.LWidthEnd outLayout.LHeightStart = widthHeight.LHeightStart outLayout.LHeightEnd = widthHeight.LHeightEnd end for _, object in ipairs(layout) do if not object.ISDOOR then local index = StageAPI.VectorToGrid(object.GRIDX, object.GRIDY, outLayout.Width) for _, entityData in ipairs(object) do StageAPI.AddObjectToRoomLayout(outLayout, index, entityData.TYPE, entityData.VARIANT, entityData.SUBTYPE, object.GRIDX, object.GRIDY) end else outLayout.Doors[#outLayout.Doors + 1] = { Slot = object.SLOT, Exists = object.EXISTS } end end return outLayout end function StageAPI.CreateEmptyRoomLayout(shape) shape = shape or RoomShape.ROOMSHAPE_1x1 local widthHeight = StageAPI.RoomShapeToWidthHeight[shape] local width, height, lWidthStart, lWidthEnd, lHeightStart, lHeightEnd, slots if not widthHeight then width, height, slots = StageAPI.RoomShapeToWidthHeight[RoomShape.ROOMSHAPE_1x1].Width, StageAPI.RoomShapeToWidthHeight[RoomShape.ROOMSHAPE_1x1].Height, StageAPI.RoomShapeToWidthHeight[RoomShape.ROOMSHAPE_1x1].Slots else width, height, lWidthStart, lWidthEnd, lHeightStart, lHeightEnd, slots = widthHeight.Width, widthHeight.Height, widthHeight.LWidthStart, widthHeight.LWidthEnd, widthHeight.LHeightStart, widthHeight.LHeightEnd, widthHeight.Slots end local newRoom = { Name = "Empty", RoomFilename = "Special", Type = 1, Variant = 0, SubType = 0, Shape = shape, Difficulty = 1, Width = width, Height = height, LWidthStart = lWidthStart, LWidthEnd = lWidthEnd, LHeightStart = lHeightStart, LHeightEnd = lHeightEnd, Weight = 1, GridEntities = {}, GridEntitiesByIndex = {}, Entities = {}, EntitiesByIndex = {}, Doors = {}, StageAPIID = StageAPI.LastRoomID + 1, PreSimplified = true } StageAPI.LastRoomID = newRoom.StageAPIID for _, slot in ipairs(slots) do newRoom.Doors[#newRoom.Doors + 1] = { Slot = slot, Exists = true } end return newRoom end StageAPI.DoorsBitwise = { [DoorSlot.LEFT0] = 1, [DoorSlot.UP0] = 1 << 1, [DoorSlot.RIGHT0] = 1 << 2, [DoorSlot.DOWN0] = 1 << 3, [DoorSlot.LEFT1] = 1 << 4, [DoorSlot.UP1] = 1 << 5, [DoorSlot.RIGHT1] = 1 << 6, [DoorSlot.DOWN1] = 1 << 7, } function StageAPI.GenerateRoomLayoutFromData(data) -- converts RoomDescriptor.Data to a StageAPI layout local layout = StageAPI.CreateEmptyRoomLayout(data.Shape) layout.Name = data.Name layout.RoomFilename = "Special" layout.Type = data.Type layout.Variant = data.Variant layout.SubType = data.Subtype layout.Difficulty = data.Difficulty layout.Weight = data.InitialWeight for _, door in ipairs(layout.Doors) do door.Exists = data.Doors & StageAPI.DoorsBitwise[door.Slot] ~= 0 end local spawns = data.Spawns for i = 0, spawns.Size do local spawn = spawns:Get(i) if spawn then local sumWeight = spawn.SumWeights local weight = 0 for i = 1, spawn.EntryCount do local entry = spawn:PickEntry(weight) weight = weight + entry.Weight / sumWeight StageAPI.AddObjectToRoomLayout(layout, index, entry.Type, entry.Variant, entry.Subtype, spawn.X, spawn.Y) end end end return layout end StageAPI.Layouts = {} function StageAPI.RegisterLayout(name, layout) StageAPI.Layouts[name] = layout end StageAPI.RoomsLists = {} StageAPI.RoomsList = StageAPI.Class("RoomsList") function StageAPI.RoomsList:Init(name, ...) self.Name = name StageAPI.RoomsLists[name] = self self.All = {} self.ByShape = {} self.Shapes = {} self.NotSimplifiedFiles = {} self:AddRooms(...) end function StageAPI.RoomsList:AddRooms(...) local roomfiles = {...} for _, rooms in ipairs(roomfiles) do local roomfile, waitToSimplify = "N/A", false if type(rooms) == "table" and rooms.Rooms then roomfile = rooms.Name waitToSimplify = rooms.WaitToSimplify rooms = rooms.Rooms end if waitToSimplify then self.NotSimplifiedFiles[#self.NotSimplifiedFiles + 1] = rooms else for _, room in ipairs(rooms) do local simplified if not room.PreSimplified then simplified = StageAPI.SimplifyRoomLayout(room) else simplified = room end simplified.RoomFilename = not waitToSimplify and room.RoomFilename or roomfile self.All[#self.All + 1] = simplified if not self.ByShape[simplified.Shape] then self.Shapes[#self.Shapes + 1] = simplified.Shape self.ByShape[simplified.Shape] = {} end self.ByShape[simplified.Shape][#self.ByShape[simplified.Shape] + 1] = simplified end end end end function StageAPI.RoomsList:CopyRooms(roomsList) self:AddRooms(roomsList.All) end function StageAPI.CreateSingleEntityLayout(t, v, s, name, rtype, shape) local layout = StageAPI.CreateEmptyRoomLayout(shape) layout.Type = rtype or RoomType.ROOM_DEFAULT layout.Name = name or "N/A" local centerX, centerY = math.floor((layout.Width - 2) / 2), math.floor((layout.Height - 2) / 2) local centerIndex = StageAPI.VectorToGrid(centerX, centerY, layout.Width) layout.EntitiesByIndex[centerIndex] = { { Type = t or EntityType.ENTITY_MONSTRO, Variant = v or 0, SubType = s or 0, GridX = centerX, GridY = centerY, Index = centerIndex } } return layout end function StageAPI.CreateSingleEntityRoomList(t, v, s, name, rtype, individualRoomName) local layouts = {} for name, shape in pairs(RoomShape) do local layout = StageAPI.CreateSingleEntityLayout(t, v, s, individualRoomName, rtype, shape) layouts[#layouts + 1] = layout end return StageAPI.RoomsList(name, layouts) end --[[ Entity Splitting Data { Type = , Variant = , SubType = , ListName = } ]] function StageAPI.SplitRoomsOnEntities(rooms, entities, roomEntityPairs) local singleMode = false if #entities == 0 then singleMode = true entities = {entities} end roomEntityPairs = roomEntityPairs or {} for _, room in ipairs(rooms) do local hasEntities = {} for _, object in ipairs(room) do for _, entData in ipairs(object) do for i, entity in ipairs(entities) do local useEnt = entity.Entity or entity if entData.TYPE == useEnt.Type and (not useEnt.Variant or entData.VARIANT == useEnt.Variant) and (not useEnt.SubType or entData.SUBTYPE == useEnt.SubType) then if not hasEntities[i] then hasEntities[i] = 0 end hasEntities[i] = hasEntities[i] + 1 break end end end end for ind, count in pairs(hasEntities) do local entity = entities[ind] local listName = entity.ListName if entity.MultipleListName and count > 1 then listName = entity.MultipleListName end if not roomEntityPairs[listName] then roomEntityPairs[listName] = {} end roomEntityPairs[listName][#roomEntityPairs[listName] + 1] = room end end return roomEntityPairs end --[[ Type Splitting Data { Type = RoomType, ListName = } ]] function StageAPI.SplitRoomsOnTypes(rooms, types, roomTypePairs) roomTypePairs = roomTypePairs or {} for _, room in ipairs(rooms) do for _, rtype in ipairs(types) do if room.TYPE == rtype then if not roomTypePairs[rtype.ListName] then roomTypePairs[rtype.ListName] = {} end roomTypePairs[rtype.ListName][#roomTypePairs[rtype.ListName] + 1] = room end end end return roomTypePairs end --[[ Splitting List Data { ListName = , SplitBy = Entity Splitting Data or Type Splitting Data } ]] function StageAPI.SplitRoomsIntoLists(roomsList, splitBy, splitByType, createEntityPlaceholders, listNamePrefix) listNamePrefix = listNamePrefix or "" local roomPairs if roomsList[1] and roomsList[1].TYPE then roomsList = {roomsList} end if splitByType then for _, rooms in ipairs(roomsList) do roomPairs = StageAPI.SplitRoomsOnTypes(rooms, splitBy, roomPairs) end else for _, rooms in ipairs(roomsList) do roomPairs = StageAPI.SplitRoomsOnEntities(rooms, splitBy, roomPairs) end end if roomPairs then for listName, rooms in pairs(roomPairs) do if StageAPI.RoomsLists[listNamePrefix .. listName] then StageAPI.RoomsLists[listNamePrefix .. listName]:AddRooms(rooms) else StageAPI.RoomsList(listNamePrefix .. listName, rooms) end end end if not splitByType and createEntityPlaceholders then for _, splitData in ipairs(splitBy) do if not StageAPI.RoomsLists[listNamePrefix .. splitData.ListName] then local entity = splitData.Entity or splitData StageAPI.CreateSingleEntityRoomList(entity.Type, entity.Variant, entity.SubType, listNamePrefix .. splitData.ListName, splitData.RoomType or entity.RoomType, splitData.RoomName or entity.RoomName) end end end end StageAPI.SinsSplitData = { { Type = EntityType.ENTITY_GLUTTONY, Variant = 0, ListName = "Gluttony", MultipleListName = "SuperGluttony" }, { Type = EntityType.ENTITY_ENVY, Variant = 0, ListName = "Envy", MultipleListName = "SuperEnvy" }, { Type = EntityType.ENTITY_GREED, Variant = 0, ListName = "Greed", MultipleListName = "SuperGreed" }, { Type = EntityType.ENTITY_WRATH, Variant = 0, ListName = "Wrath", MultipleListName = "SuperWrath" }, { Type = EntityType.ENTITY_PRIDE, Variant = 0, ListName = "Pride", MultipleListName = "SuperPride" }, { Type = EntityType.ENTITY_LUST, Variant = 0, ListName = "Lust", MultipleListName = "SuperLust" }, { Type = EntityType.ENTITY_SLOTH, Variant = 0, ListName = "Sloth", MultipleListName = "SuperSloth" }, { Type = EntityType.ENTITY_GLUTTONY, Variant = 1, ListName = "SuperGluttony" }, { Type = EntityType.ENTITY_ENVY, Variant = 1, ListName = "SuperEnvy" }, { Type = EntityType.ENTITY_GREED, Variant = 1, ListName = "SuperGreed" }, { Type = EntityType.ENTITY_WRATH, Variant = 1, ListName = "SuperWrath" }, { Type = EntityType.ENTITY_PRIDE, Variant = 1, ListName = "SuperPride" }, { Type = EntityType.ENTITY_LUST, Variant = 1, ListName = "SuperLust" }, { Type = EntityType.ENTITY_SLOTH, Variant = 1, ListName = "SuperSloth" }, { Type = EntityType.ENTITY_SLOTH, Variant = 2, ListName = "UltraPride" } } --[[ BossData { { Bosses = { { Type = , Variant = , SubType = , Count = } }, Name, Weight, Horseman, Portrait, Bossname, NameTwo, PortraitTwo, RoomListName } } ]] function StageAPI.SeparateRoomListToBossData(roomlist, bossdata) if roomlist.Name and StageAPI.RoomsLists[roomlist.Name] then StageAPI.RoomsLists[roomlist.Name] = nil end local retBossData = {} for _, boss in ipairs(bossdata) do for _, bossEntData in ipairs(boss.Bosses) do if not bossEntData.Count then bossEntData.Count = 1 end end local matchingLayouts = {} for _, layout in ipairs(roomlist.All) do local countsFound = {} for i, bossEntData in ipairs(boss.Bosses) do countsFound[i] = 0 end for index, entities in pairs(layout.EntitiesByIndex) do for _, entityData in ipairs(entities) do for i, bossEntData in ipairs(boss.Bosses) do if not bossEntData.Type or entityData.Type == bossEntData.Type and not bossEntData.Variant or entityData.Variant == bossEntData.Variant and not bossEntData.SubType or entityData.SubType == bossEntData.SubType then countsFound[i] = countsFound[i] + 1 end end end end local matches = true for i, bossEntData in ipairs(boss.Bosses) do if bossEntData.Count ~= countsFound[i] then matches = false end end if matches then matchingLayouts[#matchingLayouts + 1] = layout end end if #matchingLayouts > 0 then local list = StageAPI.RoomsList(boss.RoomListName or (boss.Name .. (boss.NameTwo or "")), matchingLayouts) retBossData[#retBossData + 1] = { Name = boss.Name, Weight = boss.Weight, Horseman = boss.Horseman, Portrait = boss.Portrait, Bossname = boss.Bossname, NameTwo = boss.NameTwo, PortraitTwo = boss.PortraitTwo, Rooms = list } end end return retBossData end function StageAPI.IsIndexInLayout(layout, x, y) if not y then x, y = StageAPI.GridToVector(x, layout.Width) end if x < 0 or x > layout.Width - 3 or y < 0 or y > layout.Height - 3 then return false elseif layout.LWidthStart or layout.LWidthEnd or layout.LHeightStart or layout.lHeightEnd then local inHole = true if layout.LWidthEnd and x > layout.LWidthEnd - 2 then inHole = false elseif layout.LWidthStart and x < layout.LWidthStart - 1 then inHole = false elseif layout.LHeightEnd and y > layout.LHeightEnd - 2 then inHole = false elseif layout.LHeightStart and y < layout.LHeightStart - 1 then inHole = false end return not inHole end return true end function StageAPI.DoesEntityDataMatchParameters(param, data) return (not param.Type or param.Type == data.Type) and (not param.Variant or param.Variant == data.Variant) and (not param.SubType or param.SubType == data.SubType) end function StageAPI.CountLayoutEntities(layout, entities, notIncluding) local count = 0 for _, ent in ipairs(layout.Entities) do for _, entity in ipairs(entities) do if StageAPI.DoesEntityDataMatchParameters(entity, ent) then local dontCount if notIncluding then for _, noInclude in ipairs(notIncluding) do if StageAPI.DoesEntityDataMatchParameters(noInclude, ent) then dontCount = true break end end end if not dontCount then count = count + 1 break end end end end return count end function StageAPI.DoesLayoutContainEntities(layout, mustIncludeAny, mustExclude, mustIncludeAll, notIncluding) local includesAny = not mustIncludeAny local mustIncludeAllCopy = {} if mustIncludeAll then for _, include in ipairs(mustIncludeAll) do mustIncludeAllCopy[#mustIncludeAllCopy + 1] = include end end for _, ent in ipairs(layout.Entities) do if not includesAny then for _, include in ipairs(mustIncludeAny) do if StageAPI.DoesEntityDataMatchParameters(include, ent) then local dontCount if notIncluding then for _, noInclude in ipairs(notIncluding) do if StageAPI.DoesEntityDataMatchParameters(noInclude, ent) then dontCount = true break end end end if not dontCount then includesAny = true break end end end end if mustExclude then for _, exclude in ipairs(mustExclude) do if StageAPI.DoesEntityDataMatchParameters(exclude, ent) then return false end end end if #mustIncludeAllCopy > 0 then for i, include in StageAPI.ReverseIterate(mustIncludeAllCopy) do if StageAPI.DoesEntityDataMatchParameters(include, ent) then local dontCount if notIncluding then for _, noInclude in ipairs(notIncluding) do if StageAPI.DoesEntityDataMatchParameters(noInclude, ent) then dontCount = true break end end end if not dontCount then table.remove(mustIncludeAllCopy, i) break end end end end end return includesAny and #mustIncludeAllCopy == 0 end local excludeTypesFromClearing = { [EntityType.ENTITY_FAMILIAR] = true, [EntityType.ENTITY_PLAYER] = true, [EntityType.ENTITY_KNIFE] = true, [EntityType.ENTITY_DARK_ESAU] = true, [EntityType.ENTITY_MOTHERS_SHADOW] = true } function StageAPI.ClearRoomLayout(keepDecoration, doGrids, doEnts, doPersistentEnts, onlyRemoveTheseDecorations, doWalls, doDoors) if doEnts or doPersistentEnts then for _, ent in ipairs(Isaac.GetRoomEntities()) do local etype = ent.Type if not excludeTypesFromClearing[etype] and not (etype == StageAPI.E.Shading.T and ent.Variant == StageAPI.E.Shading.V) then local persistentData = StageAPI.CheckPersistence(ent.Type, ent.Variant, ent.SubType) if (doPersistentEnts or (ent:ToNPC() and (not persistentData or not persistentData.AutoPersists))) and not (ent:HasEntityFlags(EntityFlag.FLAG_CHARM) or ent:HasEntityFlags(EntityFlag.FLAG_FRIENDLY) or ent:HasEntityFlags(EntityFlag.FLAG_PERSISTENT)) then ent:Remove() end end end end if doGrids then local lindex = StageAPI.GetCurrentRoomID() StageAPI.CustomGrids[lindex] = {} StageAPI.RoomGrids[lindex] = {} for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid then local gtype = grid.Desc.Type if (doWalls or gtype ~= GridEntityType.GRID_WALL or room:IsPositionInRoom(grid.Position, 0)) -- this allows custom wall grids to exist and (doDoors or gtype ~= GridEntityType.GRID_DOOR) and (not onlyRemoveTheseDecorations or gtype ~= GridEntityType.GRID_DECORATION or onlyRemoveTheseDecorations[i]) then StageAPI.Room:RemoveGridEntity(i, 0, keepDecoration) end end end end StageAPI.CalledRoomUpdate = true room:Update() StageAPI.CalledRoomUpdate = false end function StageAPI.DoLayoutDoorsMatch(layout, doors) local numNonExistingDoors = 0 local doesLayoutMatch = true for _, door in ipairs(layout.Doors) do if door.Slot and not door.Exists then if ((not doors and room:GetDoor(door.Slot)) or (doors and doors[door.Slot])) then doesLayoutMatch = false end numNonExistingDoors = numNonExistingDoors + 1 end end return doesLayoutMatch, numNonExistingDoors end -- returns list of rooms, error message if no rooms valid function StageAPI.GetValidRoomsForLayout(args) local roomList = args.RoomList local shape = args.Shape or room:GetRoomShape() local callbacks = StageAPI.GetCallbacks("POST_CHECK_VALID_ROOM") local validRooms = {} local possibleRooms if shape == -1 then possibleRooms = roomList.All else possibleRooms = roomList.ByShape[shape] end if not possibleRooms then return {}, "No rooms for shape!" end local requireRoomType = args.RequireRoomType local rtype if requireRoomType then rtype = args.RoomType or room:GetType() end local ignoreDoors = args.IgnoreDoors local doors = args.Doors if not doors then doors = StageAPI.GetDoorsForRoom() end local seed = args.Seed or room:GetSpawnSeed() local disallowIDs = args.DisallowIDs for _, layout in ipairs(possibleRooms) do shape = layout.Shape local isValid = true local numNonExistingDoors = 0 if requireRoomType and layout.Type ~= rtype then isValid = false elseif not ignoreDoors then isValid, numNonExistingDoors = StageAPI.DoLayoutDoorsMatch(layout, doors) end if isValid and disallowIDs then for _, id in ipairs(disallowIDs) do if layout.StageAPIID == id then isValid = false break end end end local weight = layout.Weight if isValid then for _, callback in ipairs(callbacks) do local ret = callback.Function(layout, roomList, seed, shape, rtype, requireRoomType) if ret == false then isValid = false break elseif type(ret) == "number" then weight = ret end end end if isValid then if StageAPI.CurrentlyInitializing and not StageAPI.CurrentlyInitializing.IsExtraRoom and rtype == RoomType.ROOM_DEFAULT then local originalWeight = weight weight = weight * 2 ^ numNonExistingDoors if shape == RoomShape.ROOMSHAPE_1x1 and numNonExistingDoors > 0 then weight = weight + math.min(originalWeight * 4, 4) end end end if isValid then validRooms[#validRooms + 1] = {layout, weight} end end return validRooms, nil end StageAPI.RoomChooseRNG = RNG() function StageAPI.ChooseRoomLayout(roomList, seed, shape, rtype, requireRoomType, ignoreDoors, doors, disallowIDs) local validRooms, err = StageAPI.GetValidRoomsForLayout({ RoomList = roomList, Seed = seed, Shape = shape, RoomType = rtype, RequireRoomType = requireRoomType, IgnoreDoors = ignoreDoors, Doors = doors, DisallowIDs = disallowIDs }) if err then StageAPI.Log(err) end local totalWeight = 0 for _, layout in ipairs(validRooms) do local weight = layout[2] totalWeight = totalWeight + weight end if #validRooms > 0 then StageAPI.RoomChooseRNG:SetSeed(seed, 0) return StageAPI.WeightedRNG(validRooms, StageAPI.RoomChooseRNG, nil, totalWeight) else StageAPI.Log("No rooms with correct shape and doors!") end end --[[ options { Type = etype, Variant = variant, SubType = subtype, AutoPersists = autoPersists, RemoveOnRemove = removeOnRemove, RemoveOnDeath = removeOnDeath, UpdatePosition = updatePosition, StoreCheck = storeCheck } ]] StageAPI.PersistentEntities = {} function StageAPI.AddEntityPersistenceData(persistenceData) StageAPI.PersistentEntities[#StageAPI.PersistentEntities + 1] = persistenceData end StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_STONEHEAD}) StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_CONSTANT_STONE_SHOOTER}) StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_STONE_EYE}) StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_BRIMSTONE_HEAD}) StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_WALL_HUGGER}) StageAPI.AddEntityPersistenceData({Type = EntityType.ENTITY_POKY, Variant = 1}) StageAPI.PersistenceChecks = {} function StageAPI.AddPersistenceCheck(fn) StageAPI.PersistenceChecks[#StageAPI.PersistenceChecks + 1] = fn end StageAPI.DynamicPersistentTypes = { EntityType.ENTITY_BOMBDROP, EntityType.ENTITY_PICKUP, EntityType.ENTITY_SLOT, EntityType.ENTITY_MOVABLE_TNT, EntityType.ENTITY_SHOPKEEPER, EntityType.ENTITY_PITFALL, EntityType.ENTITY_FIREPLACE, EntityType.ENTITY_ETERNALFLY, } StageAPI.AddPersistenceCheck(function(entData) local isDynamicPersistent = false for _, type in ipairs(StageAPI.DynamicPersistentTypes) do isDynamicPersistent = entData.Type == type if isDynamicPersistent then break end end if isDynamicPersistent then return { AutoPersists = true, UpdatePosition = true, RemoveOnRemove = true, StoreCheck = function(entity) if entity.Type == EntityType.ENTITY_PICKUP then local variant = entity.Variant if variant == PickupVariant.PICKUP_COLLECTIBLE then return entity.SubType == 0 else local sprite = entity:GetSprite() if sprite:IsPlaying("Open") or sprite:IsPlaying("Opened") or sprite:IsPlaying("Collect") or sprite:IsFinished("Open") or sprite:IsFinished("Opened") or sprite:IsFinished("Collect") then return true end if entity:IsDead() then return true end end elseif entity.Type == EntityType.ENTITY_FIREPLACE then return entity.HitPoints <= 2 elseif entity.Type == EntityType.ENTITY_SLOT then return entity:GetSprite():IsPlaying("Death") or entity:GetSprite():IsPlaying("Broken") or entity:GetSprite():IsFinished("Death") or entity:GetSprite():IsFinished("Broken") end end } end end) function StageAPI.CheckPersistence(id, variant, subtype) local persistentData for _, persistData in ipairs(StageAPI.PersistentEntities) do if (not persistData.Type or id == persistData.Type) and (not persistData.Variant or variant == persistData.Variant) and (not persistData.SubType or subtype == persistData.SubType) then persistentData = persistData end end if not persistentData then for _, check in ipairs(StageAPI.PersistenceChecks) do local persistData = check({Type = id, Variant = variant, SubType = subtype}) if persistData then persistentData = persistData break end end end return persistentData end StageAPI.RoomLoadRNG = RNG() StageAPI.MetadataEntities = { [199] = { [0] = { Name = "Group 0", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [1] = { Name = "Group 1", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [2] = { Name = "Group 2", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [3] = { Name = "Group 3", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [4] = { Name = "Group 4", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [5] = { Name = "Group 5", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [6] = { Name = "Group 6", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [7] = { Name = "Group 7", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [8] = { Name = "Group 8", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [9] = { Name = "Group 9", Group = "Groups", Conflicts = true, StoreAsGroup = true, OnlyConflictWith = "RandomizeGroup" }, [10] = { Name = "RandomizeGroup" }, [11] = { Name = "Left", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [12] = { Name = "Right", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [13] = { Name = "Up", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [14] = { Name = "Down", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [15] = { Name = "UpLeft", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [16] = { Name = "UpRight", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [17] = { Name = "DownLeft", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [18] = { Name = "DownRight", Group = "Direction", Conflicts = true, PreventConflictWith = "PreventDirectionConflict" }, [19] = { Name = "PreventDirectionConflict" }, [20] = { Name = "Swapper" }, [21] = { Name = "Detonator" }, [22] = { Name = "RoomClearTrigger", Trigger = true }, [23] = { Name = "Spawner", BlockEntities = true }, [24] = { Name = "PreventRandomization" }, [25] = { Name = "BridgeFailsafe" }, [26] = { Name = "DetonatorTrigger", Trigger = true }, [27] = { Name = "DoorLocker" }, [28] = { Name = "GridDestroyer" } } } mod:AddCallback(ModCallbacks.MC_NPC_UPDATE, function(_, npc) if npc.Variant ~= StageAPI.E.DeleteMeNPC.Variant then print("Something is wrong! A StageAPI metadata entity has spawned when it should have been removed.") end end, StageAPI.E.MetaEntity.T) StageAPI.MetadataEntitiesByName = {} StageAPI.UnblockableEntities = {} for id, variants in pairs(StageAPI.MetadataEntities) do for variant, metadata in pairs(variants) do metadata.Variant = variant metadata.Type = id StageAPI.MetadataEntitiesByName[metadata.Name] = metadata end end function StageAPI.AddMetadataEntities(tbl) if type(next(tbl)) == "table" and next(tbl).Name then for variant, data in pairs(tbl) do data.Type = 199 data.Variant = variant StageAPI.MetadataEntities[199][variant] = data StageAPI.MetadataEntitiesByName[data.Name] = data end else for id, variantTable in pairs(tbl) do if StageAPI.MetadataEntities[id] then for variant, data in pairs(variantTable) do data.Variant = variant data.Type = id StageAPI.MetadataEntities[id][variant] = data StageAPI.MetadataEntitiesByName[data.Name] = data end else StageAPI.MetadataEntities[id] = {} for variant, data in pairs(variantTable) do data.Variant = variant data.Type = id StageAPI.MetadataEntities[id][variant] = data StageAPI.MetadataEntitiesByName[data.Name] = data end end end end end function StageAPI.IsMetadataEntity(etype, variant) if type(etype) == "table" then variant = etype.Variant etype = etype.Type end return StageAPI.MetadataEntities[etype] and StageAPI.MetadataEntities[etype][variant] end function StageAPI.RoomDataHasMetadataEntity(data) local spawns = data.Spawns for i = 0, spawns.Size do local spawn = spawns:Get(i) if spawn then local sumWeight = spawn.SumWeights local weight = 0 for i = 1, spawn.EntryCount do local entry = spawn:PickEntry(weight) weight = weight + entry.Weight / sumWeight if StageAPI.IsMetadataEntity(entry.Type, entry.Variant) then return true end end end end return false end function StageAPI.AddUnblockableEntities(etype, variant, subtype) -- an entity that will not be blocked by the Spawner or other BlockEntities triggers if type(etype) == "table" then for _, ent in ipairs(etype) do StageAPI.AddUnblockableEntities(ent[1], ent[2], ent[3]) end else if not StageAPI.UnblockableEntities[etype] then if variant then StageAPI.UnblockableEntities[etype] = {} if subtype then StageAPI.UnblockableEntities[etype][variant] = {} StageAPI.UnblockableEntities[etype][variant][subtype] = true else StageAPI.UnblockableEntities[etype][variant] = true end else StageAPI.UnblockableEntities[etype] = true end end end end function StageAPI.SeparateEntityMetadata(entities, grids, seed) StageAPI.RoomLoadRNG:SetSeed(seed or room:GetSpawnSeed(), 1) local outEntities, entityMeta = {}, {} for index, entityList in pairs(entities) do local outList = {} for _, entity in ipairs(entityList) do if StageAPI.MetadataEntities[entity.Type] and entity.Variant and StageAPI.MetadataEntities[entity.Type][entity.Variant] and (not entity.SubType or entity.SubType == 0) then local metadata = StageAPI.MetadataEntities[entity.Type][entity.Variant] if not entityMeta[index] then entityMeta[index] = {} end if not entityMeta[index][metadata.Name] then entityMeta[index][metadata.Name] = 0 end entityMeta[index][metadata.Name] = entityMeta[index][metadata.Name] + 1 else outList[#outList + 1] = entity end end outEntities[index] = outList end local swapIndexToGroups = {} local swapGroupToIndices = {} local blockedEntities = {} for index, metadataSet in pairs(entityMeta) do local setsOfConflicting = {} for name, count in pairs(metadataSet) do local metadata = StageAPI.MetadataEntitiesByName[name] if metadata.BlockEntities and outEntities[index] then blockedEntities[index] = {} for i, entity in StageAPI.ReverseIterate(outEntities[index]) do if not (StageAPI.UnblockableEntities[entity.Type] and (StageAPI.UnblockableEntities[entity.Type] == true or (StageAPI.UnblockableEntities[entity.Type][entity.Variant] and (StageAPI.UnblockableEntities[entity.Type][entity.Variant] == true or StageAPI.UnblockableEntities[entity.Type][entity.Variant][entity.SubType] == true)))) then blockedEntities[index][#blockedEntities[index] + 1] = entity table.remove(outEntities[index], i) end end if #blockedEntities[index] == 0 then blockedEntities[index] = nil end if #outEntities[index] == 0 then outEntities[index] = nil end end if metadata.Group then if metadata.Conflicts and not setsOfConflicting[metadata.Group] then local shouldConflict = true if metadata.PreventConflictWith or metadata.OnlyConflictWith then if metadata.PreventConflictWith then local noConflictWith = metadata.PreventConflictWith if type(noConflictWith) ~= "table" then noConflictWith = {noConflictWith} end for _, preventName in ipairs(noConflictWith) do if metadataSet[preventName] then shouldConflict = false end end elseif metadata.OnlyConflictWith then shouldConflict = false local needsToConflict = metadata.OnlyConflictWith if type(needsToConflict) ~= "table" then needsToConflict = {needsToConflict} end for _, needsName in ipairs(needsToConflict) do if metadataSet[needsName] then shouldConflict = true end end end end if shouldConflict then setsOfConflicting[metadata.Group] = {} for name2, count2 in pairs(metadataSet) do local metadata2 = StageAPI.MetadataEntitiesByName[name2] if metadata2.Conflicts and metadata2.Group == metadata.Group then setsOfConflicting[metadata.Group][#setsOfConflicting[metadata.Group] + 1] = name2 end end end end end end for group, conflicts in pairs(setsOfConflicting) do local use = conflicts[StageAPI.Random(1, #conflicts, StageAPI.RoomLoadRNG)] for _, conflictName in ipairs(conflicts) do if conflictName ~= use then metadataSet[conflictName] = nil end end end for name, count in pairs(metadataSet) do local metadata = StageAPI.MetadataEntitiesByName[name] if metadata and metadata.Group then if metadata.StoreAsGroup then if not metadataSet[metadata.Group] then metadataSet[metadata.Group] = {} end if not metadataSet[metadata.Group][name] then metadataSet[metadata.Group][name] = 0 end metadataSet[metadata.Group][name] = metadataSet[metadata.Group][name] + 1 elseif type(metadataSet[metadata.Group]) ~= "table" then if not metadataSet[metadata.Group] then metadataSet[metadata.Group] = 0 end metadataSet[metadata.Group] = metadataSet[metadata.Group] + 1 end end end if metadataSet["Swapper"] then if metadataSet["Groups"] then local groupList = {} for group, count in pairs(metadataSet["Groups"]) do groupList[#groupList + 1] = group if not swapGroupToIndices[group] then swapGroupToIndices[group] = {} end swapGroupToIndices[group][#swapGroupToIndices[group] + 1] = index end swapIndexToGroups[index] = groupList else if not swapGroupToIndices["None"] then swapGroupToIndices["None"] = {} end swapGroupToIndices["None"][#swapGroupToIndices["None"] + 1] = index swapIndexToGroups[index] = {"None"} end end end local outGrids = {} for index, gridList in pairs(grids) do outGrids[index] = gridList end for index, groups in pairs(swapIndexToGroups) do local canSwapWith = {} for _, group in ipairs(groups) do local indices = swapGroupToIndices[group] for _, index2 in ipairs(indices) do canSwapWith[#canSwapWith + 1] = index2 end end if #canSwapWith > 0 then local swapWith = canSwapWith[StageAPI.Random(1, #canSwapWith)] local swappingEntityList = outEntities[swapWith] outEntities[swapWith] = outEntities[index] outEntities[index] = swappingEntityList local swappingEntityMeta = entityMeta[swapWith] entityMeta[swapWith] = entityMeta[index] entityMeta[index] = swappingEntityMeta local swappingGrid = outGrids[swapWith] outGrids[swapWith] = outGrids[index] outGrids[index] = swappingGrid end end entityMeta.BlockedEntities = blockedEntities entityMeta.Triggers = {} entityMeta.RecentTriggers = {} return outEntities, outGrids, entityMeta end function StageAPI.AddEntityToSpawnList(tbl, entData, persistentIndex, index) local currentRoom = StageAPI.CurrentlyInitializing or StageAPI.GetCurrentRoom() if persistentIndex == nil and currentRoom then persistentIndex = currentRoom.LastPersistentIndex if currentRoom.LastPersistentIndex then currentRoom.LastPersistentIndex = currentRoom.LastPersistentIndex + 1 end end if index and (tbl[index] and type(tbl[index]) == "table") then tbl = tbl[index] end entData = StageAPI.Copy(entData) entData.Type = entData.Type or 10 entData.Variant = entData.Variant or 0 entData.SubType = entData.SubType or 0 entData.Index = entData.Index or index or 0 if not entData.GridX or not entData.GridY then local width if currentRoom and currentRoom.Layout and currentRoom.Layout.Width then width = currentRoom.Layout.Width else width = room:GetGridWidth() end entData.GridX, entData.GridY = StageAPI.GridToVector(index, width) end persistentIndex = persistentIndex + 1 local persistentData = StageAPI.CheckPersistence(entData.Type, entData.Variant, entData.SubType) tbl[#tbl + 1] = { Data = entData, PersistentIndex = persistentIndex, Persistent = not not persistentData, PersistenceData = persistentData } return persistentIndex end function StageAPI.SelectSpawnEntities(entities, seed, entityMeta) StageAPI.RoomLoadRNG:SetSeed(seed or room:GetSpawnSeed(), 1) local entitiesToSpawn = {} local callbacks = StageAPI.GetCallbacks("PRE_SELECT_ENTITY_LIST") local persistentIndex = 0 for index, entityList in pairs(entities) do if #entityList > 0 then local addEntities = {} local overridden, stillAddRandom = false, nil for _, callback in ipairs(callbacks) do local retAdd, retList, retRandom = callback.Function(entityList, index, entityMeta) if retRandom ~= nil and stillAddRandom == nil then stillAddRandom = retRandom end if retAdd == false then overridden = true else if retAdd and type(retAdd) == "table" then addEntities = retAdd overridden = true end if retList and type(retList) == "table" then entityList = retList overridden = true end end if overridden then break end end if not overridden or (stillAddRandom and #entityList > 0) then addEntities[#addEntities + 1] = entityList[StageAPI.Random(1, #entityList, StageAPI.RoomLoadRNG)] end if #addEntities > 0 then if not entitiesToSpawn[index] then entitiesToSpawn[index] = {} end for _, entData in ipairs(addEntities) do persistentIndex = StageAPI.AddEntityToSpawnList(entitiesToSpawn[index], entData, persistentIndex) --[[ persistentIndex = persistentIndex + 1 local persistentData = StageAPI.CheckPersistence(entData.Type, entData.Variant, entData.SubType) entitiesToSpawn[index][#entitiesToSpawn[index] + 1] = { Data = entData, PersistentIndex = persistentIndex, Persistent = not not persistentData, PersistenceData = persistentData }]] end end end end return entitiesToSpawn, persistentIndex end function StageAPI.SelectSpawnGrids(gridsByIndex, seed) StageAPI.RoomLoadRNG:SetSeed(seed or room:GetSpawnSeed(), 1) local spawnGrids = {} local callbacks = StageAPI.GetCallbacks("PRE_SELECT_GRIDENTITY_LIST") for index, grids in pairs(gridsByIndex) do if #grids > 0 then local spawnGrid, noSpawnGrid for _, callback in ipairs(callbacks) do local ret = callback.Function(grids, index) if ret == false then noSpawnGrid = true break elseif type(ret) == "table" then if ret.Index then spawnGrid = ret else grids = ret end break end end if not noSpawnGrid then if not spawnGrid then spawnGrid = grids[StageAPI.Random(1, #grids, StageAPI.RoomLoadRNG)] end if spawnGrid then spawnGrids[index] = spawnGrid end end end end return spawnGrids end function StageAPI.ObtainSpawnObjects(layout, seed) local entitiesByIndex, gridsByIndex, entityMeta = StageAPI.SeparateEntityMetadata(layout.EntitiesByIndex, layout.GridEntitiesByIndex, seed) local spawnEntities, lastPersistentIndex = StageAPI.SelectSpawnEntities(entitiesByIndex, seed, entityMeta) local spawnGrids = StageAPI.SelectSpawnGrids(gridsByIndex, seed) local gridTakenIndices = {} local entityTakenIndices = {} for index, entity in pairs(spawnEntities) do entityTakenIndices[index] = true end for index, gridData in pairs(spawnGrids) do gridTakenIndices[index] = true end return spawnEntities, spawnGrids, entityTakenIndices, gridTakenIndices, lastPersistentIndex, entityMeta end StageAPI.ActiveEntityPersistenceData = {} mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.ActiveEntityPersistenceData = {} end) function StageAPI.GetEntityPersistenceData(entity) return StageAPI.ActiveEntityPersistenceData[GetPtrHash(entity)] end function StageAPI.SetEntityPersistenceData(entity, persistentIndex, persistentData) StageAPI.ActiveEntityPersistenceData[GetPtrHash(entity)] = { PersistentIndex = persistentIndex, PersistenceData = persistentData } end function StageAPI.LoadEntitiesFromEntitySets(entitysets, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions, loadingWave) local ents_spawned = {} local listCallbacks = StageAPI.GetCallbacks("PRE_SPAWN_ENTITY_LIST") local entCallbacks = StageAPI.GetCallbacks("PRE_SPAWN_ENTITY") if type(entitysets) ~= "table" then entitysets = {entitysets} end for _, entities in ipairs(entitysets) do for index, entityList in pairs(entities) do if #entityList > 0 then local shouldSpawn = true for _, callback in ipairs(listCallbacks) do local ret = callback.Function(entityList, index, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions) if ret == false then shouldSpawn = false break elseif ret and type(ret) == "table" then entityList = ret break end end if shouldSpawn and #entityList > 0 then local roomType = room:GetType() for _, entityInfo in ipairs(entityList) do local shouldSpawnEntity = true if shouldSpawnEntity and avoidSpawning and avoidSpawning[entityInfo.PersistentIndex] then shouldSpawnEntity = false end if shouldSpawnEntity and doPersistentOnly and not entityInfo.PersistenceData then shouldSpawnEntity = false end if shouldSpawnEntity and entityInfo.Persistent and entityInfo.PersistenceData.AutoPersists and not doAutoPersistent then shouldSpawnEntity = false end if entityInfo.PersistentIndex and persistentPositions and persistentPositions[entityInfo.PersistentIndex] then entityInfo.Position = Vector(persistentPositions[entityInfo.PersistentIndex].X, persistentPositions[entityInfo.PersistentIndex].Y) end if not entityInfo.Position then entityInfo.Position = room:GetGridPosition(index) end for _, callback in ipairs(entCallbacks) do if not callback.Params[1] or (entityInfo.Data.Type and callback.Params[1] == entityInfo.Data.Type) and not callback.Params[2] or (entityInfo.Data.Variant and callback.Params[2] == entityInfo.Data.Variant) and not callback.Params[3] or (entityInfo.Data.SubType and callback.Params[3] == entityInfo.Data.SubType) then local ret = callback.Function(entityInfo, entityList, index, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions, shouldSpawnEntity) if ret == false or ret == true then shouldSpawnEntity = ret break elseif ret and type(ret) == "table" then if ret.Data then entityInfo = ret else entityInfo.Data.Type = ret[1] == 999 and 1000 or ret[1] entityInfo.Data.Variant = ret[2] entityInfo.Data.SubType = ret[3] end break end end end if shouldSpawnEntity then local entityData = entityInfo.Data if doGrids or (entityData.Type > 9 and entityData.Type ~= EntityType.ENTITY_FIREPLACE) then local ent = Isaac.Spawn( entityData.Type or 20, entityData.Variant or 0, entityData.SubType or 0, entityInfo.Position or StageAPI.ZeroVector, StageAPI.ZeroVector, nil ) local currentRoom = StageAPI.GetCurrentRoom() if currentRoom and not currentRoom.IgnoreRoomRules then if entityData.Type == EntityType.ENTITY_PICKUP and entityData.Variant == PickupVariant.PICKUP_COLLECTIBLE then if currentRoom.RoomType == RoomType.ROOM_TREASURE and (currentRoom.Layout.Variant > 0 or string.find(string.lower(currentRoom.Layout.Name), "choice") or string.find(string.lower(currentRoom.Layout.Name), "choose")) then ent:ToPickup().OptionsPickupIndex = 1 end end end ent:GetData().StageAPISpawnedPosition = entityInfo.Position or StageAPI.ZeroVector ent:GetData().StageAPIEntityListIndex = index if entityInfo.Persistent then StageAPI.SetEntityPersistenceData(ent, entityInfo.PersistentIndex, entityInfo.PersistenceData) end if not loadingWave and ent:CanShutDoors() then StageAPI.Room:SetClear(false) end StageAPI.CallCallbacks("POST_SPAWN_ENTITY", false, ent, entityInfo, entityList, index, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions, shouldSpawnEntity) ents_spawned[#ents_spawned + 1] = ent end end end end end end end return ents_spawned end function StageAPI.CallGridPostInit() for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid then grid:PostInit() if StageAPI.RockTypes[grid.Desc.Type] then grid:ToRock():UpdateAnimFrame() end end end end StageAPI.GridSpawnRNG = RNG() function StageAPI.LoadGridsFromDataList(grids, gridInformation, entities) local grids_spawned = {} StageAPI.GridSpawnRNG:SetSeed(room:GetSpawnSeed(), 0) local callbacks = StageAPI.GetCallbacks("PRE_SPAWN_GRID") for index, gridData in pairs(grids) do local shouldSpawn = true for _, callback in ipairs(callbacks) do local ret = callback.Function(gridData, gridInformation, entities, StageAPI.GridSpawnRNG) if ret == false then shouldSpawn = false break elseif type(ret) == "table" then gridData = ret end end if shouldSpawn and StageAPI.Room:IsPositionInRoom(StageAPI.Room:GetGridPosition(index), 0) then room:RemoveGridEntity(index, 0, false) local grid = Isaac.GridSpawn(gridData.Type, gridData.Variant, StageAPI.Room:GetGridPosition(index), true) if grid then if gridInformation and gridInformation[index] then local grinformation = gridInformation[index] if grinformation.State ~= nil then grid.State = grinformation.State if grinformation.State == 4 and gridData.Type == GridEntityType.GRID_TNT then grid:ToTNT().FrameCnt = -1 end end if grinformation.VarData ~= nil then grid.VarData = grinformation.VarData end end grids_spawned[#grids_spawned + 1] = grid end if gridData.Type == GridEntityType.GRID_PRESSURE_PLATE and gridData.Variant == 0 then StageAPI.Room:SetClear(false) end end end return grids_spawned end function StageAPI.GetGridInformation() local gridInformation = {} for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid then gridInformation[i] = { State = grid.State, VarData = grid.VarData } end end return gridInformation end function StageAPI.LoadRoomLayout(grids, entities, doGrids, doEntities, doPersistentOnly, doAutoPersistent, gridData, avoidSpawning, persistentPositions, loadingWave) local grids_spawned = {} local ents_spawned = {} if grids and doGrids then grids_spawned = StageAPI.LoadGridsFromDataList(grids, gridData, entities) end if entities and doEntities then ents_spawned = StageAPI.LoadEntitiesFromEntitySets(entities, doGrids, doPersistentOnly, doAutoPersistent, avoidSpawning, persistentPositions, loadingWave) end StageAPI.CallGridPostInit() return ents_spawned, grids_spawned end function StageAPI.GetCurrentRoomID() if StageAPI.InExtraRoom then return StageAPI.CurrentExtraRoomName else return StageAPI.GetCurrentListIndex() end end StageAPI.LevelRooms = {} function StageAPI.SetCurrentRoom(room) StageAPI.ActiveEntityPersistenceData = {} StageAPI.LevelRooms[StageAPI.GetCurrentRoomID()] = room end function StageAPI.GetCurrentRoom() return StageAPI.LevelRooms[StageAPI.GetCurrentRoomID()] end function StageAPI.GetCurrentRoomType() local currentRoom = StageAPI.GetCurrentRoom() if currentRoom then return currentRoom.TypeOverride or currentRoom.RoomType or room:GetType() else return room:GetType() end end function StageAPI.GetRooms() return StageAPI.LevelRooms end function StageAPI.CloseDoors() for i = 0, 7 do local door = room:GetDoor(i) if door then door:Close() end end end function StageAPI.GetDoorsForRoom() doors = {} for i = 0, 7 do doors[i] = not not room:GetDoor(i) end return doors end StageAPI.LevelRoom = StageAPI.Class("LevelRoom") StageAPI.NextUniqueRoomIdentifier = 0 function StageAPI.LevelRoom:Init(layoutName, roomsList, seed, shape, roomType, isExtraRoom, fromSaveData, requireRoomType, ignoreDoors, doors, levelIndex, ignoreRoomRules) Isaac.DebugString("[StageAPI] Initializing room") StageAPI.CurrentlyInitializing = self self.UniqueRoomIdentifier = StageAPI.NextUniqueRoomIdentifier StageAPI.NextUniqueRoomIdentifier = StageAPI.NextUniqueRoomIdentifier + 1 if fromSaveData then Isaac.DebugString("[StageAPI] Loading from save data") self.LevelIndex = levelIndex self:LoadSaveData(fromSaveData) else Isaac.DebugString("[StageAPI] Generating room") roomType = roomType or room:GetType() shape = shape or room:GetRoomShape() seed = seed or room:GetSpawnSeed() if not doors then doors = StageAPI.GetDoorsForRoom() end self.Data = {} self.PersistentData = {} self.IsExtraRoom = isExtraRoom self.LevelIndex = levelIndex self.Doors = doors self.Shape = shape self.RoomType = roomType self.Seed = seed self.LayoutName = layoutName self.AvoidSpawning = {} self.ExtraSpawn = {} self.PersistentPositions = {} self.FirstLoad = true self.RequireRoomType = requireRoomType self.IgnoreRoomRules = ignoreRoomRules local replaceLayoutName = StageAPI.CallCallbacks("PRE_ROOM_LAYOUT_CHOOSE", true, self) if replaceLayoutName then Isaac.DebugString("[StageAPI] Layout replaced") self.LayoutName = replaceLayoutName end local layout if self.LayoutName then layout = StageAPI.Layouts[self.LayoutName] end if not layout then roomsList = StageAPI.CallCallbacks("PRE_ROOMS_LIST_USE", true, self) or roomsList self.RoomsListName = roomsList.Name layout = StageAPI.ChooseRoomLayout(roomsList, seed, shape, roomType, requireRoomType, ignoreDoors, self.Doors) end self.Layout = layout self:PostGetLayout(seed) end StageAPI.CallCallbacks("POST_ROOM_INIT", false, self, not not fromSaveData, fromSaveData) StageAPI.CurrentlyInitializing = nil end function StageAPI.LevelRoom:PostGetLayout(seed) if not self.Layout then if self.Shape == -1 then self.Shape = RoomShape.ROOMSHAPE_1x1 end self.Layout = StageAPI.CreateEmptyRoomLayout(self.Shape) StageAPI.Log("No layout!") end Isaac.DebugString("[StageAPI] Initialized room " .. self.Layout.Name .. "." .. tostring(self.Layout.Variant) .. " from file " .. tostring(self.Layout.RoomFilename) .. (roomsList and (' from list ' .. roomsList.Name) or '')) if self.Shape == -1 then self.Shape = self.Layout.Shape end self.SpawnEntities, self.SpawnGrids, self.EntityTakenIndices, self.GridTakenIndices, self.LastPersistentIndex, self.EntityMetadata = StageAPI.ObtainSpawnObjects(self.Layout, seed) --[[ self.SpawnEntities, self.LastPersistentIndex = StageAPI.SelectSpawnEntities(self.Layout.EntitiesByIndex, seed) self.SpawnGrids = StageAPI.SelectSpawnGrids(self.Layout.GridEntitiesByIndex, seed) self.GridTakenIndices = {} self.EntityTakenIndices = {} for index, entity in pairs(self.SpawnEntities) do self.EntityTakenIndices[index] = true end for _, grid in ipairs(self.SpawnGrids) do self.GridTakenIndices[grid.Index] = true end]] end function StageAPI.LevelRoom:SetEntityMetadata(index, name, value) if not self.EntityMetadata[index] then self.EntityMetadata[index] = {} end if not value and not self.EntityMetadata[index][name] then self.EntityMetadata[index][name] = 0 end if not value then self.EntityMetadata[index][name] = self.EntityMetadata[index][name] + 1 else self.EntityMetadata[index][name] = value end end function StageAPI.LevelRoom:HasEntityMetadata(index, name) return self.EntityMetadata[index] and (not name or self.EntityMetadata[index][name]) end function StageAPI.LevelRoom:GetEntityMetadata(index, name) if not name then return self.EntityMetadata[index] elseif not index then local indicesWithMetadata = {} for index, metadataSet in pairs(self.EntityMetadata) do if metadataSet[name] then indicesWithMetadata[index] = metadataSet[name] end end return indicesWithMetadata elseif self.EntityMetadata[index] and self.EntityMetadata[index][name] then return self.EntityMetadata[index][name] end end function StageAPI.LevelRoom:GetEntityMetadataOfType(metatype, index) if index then local includedMetadata = {} if self.EntityMetadata[index] then for name, val in pairs(self.EntityMetadata[index]) do if type(val) == "table" and name == metatype then for _, v in ipairs(val) do includedMetadata[#includedMetadata + 1] = v end elseif type(val) ~= "table" then if StageAPI.MetadataEntitiesByName[name] and StageAPI.MetadataEntitiesByName[name].Group == metatype then includedMetadata[#includedMetadata + 1] = name end end end end return includedMetadata else local includedMetadataByIndex = {} for index, metadataSet in pairs(self.EntityMetadata) do local includedMetadata = self:GetEntityMetadataOfType(metatype, index) if #includedMetadata > 0 then includedMetadataByIndex[index] = includedMetadata end end return includedMetadataByIndex end end function StageAPI.LevelRoom:GetEntityMetadataGroups(index) local groups = {} if index then local groupTbl = self:GetEntityMetadata(index, "Groups") if groupTbl then for group, count in pairs(groupTbl) do groups[#groups + 1] = group end end else for index, metadataSet in pairs(self.EntityMetadata) do if metadataSet["Groups"] then for group, count in pairs(metadataSet["Groups"]) do if not StageAPI.IsIn(groups, group) then groups[#groups + 1] = group end end end end end return groups end function StageAPI.LevelRoom:IndicesShareGroup(index, index2, specificGroup) if specificGroup then return self:HasEntityMetadata(index, specificGroup) and self:HasEntityMetadata(index2, specificGroup) else local groups = self:GetEntityMetadataGroups(index) for _, group in ipairs(groups) do if self:HasEntityMetadata(index2, group) then return true end end end return false end function StageAPI.LevelRoom:GetIndicesInGroup(group) local indices = {} for index, metadataSet in pairs(self.EntityMetadata) do if metadataSet[group] then indices[#indices + 1] = index end end return indices end function StageAPI.LevelRoom:GroupHasMetadata(group, name) for index, metadataSet in pairs(self.EntityMetadata) do if metadataSet[group] and metadataSet[name] then return true end end return false end function StageAPI.LevelRoom:IndexSharesGroupWithMetadata(index, name) local groups = self:GetEntityMetadataGroups(index) for _, group in ipairs(groups) do if self:GroupHasMetadata(group, name) then return true end end return false end function StageAPI.LevelRoom:IndexIsAssociatedWithMetadata(index, name) return self:HasEntityMetadata(index, name) or self:IndexSharesGroupWithMetadata(index, name) end function StageAPI.LevelRoom:SetMetadataTrigger(name, index, groups, value) if not groups then groups = {index} elseif index then groups[#groups + 1] = index end for _, group in ipairs(groups) do if not self.EntityMetadata.Triggers[group] then self.EntityMetadata.Triggers[group] = {} self.EntityMetadata.RecentTriggers[group] = {} end if value then self.EntityMetadata.Triggers[group][name] = value self.EntityMetadata.RecentTriggers[group][name] = 0 else self.EntityMetadata.Triggers[group][name] = nil self.EntityMetadata.RecentTriggers[group][name] = nil end end end function StageAPI.LevelRoom:WasMetadataTriggered(name, frames, index, groups, exactFrame) frames = frames or 0 if not groups then groups = {index} elseif index then groups[#groups + 1] = index end for group, names in pairs(self.EntityMetadata.RecentTriggers) do if not groups or StageAPI.IsIn(groups, group) then for name2, timeSince in pairs(names) do if (not name or name2 == name) and (timeSince == exactFrame or timeSince <= frames) then return true end end end end end function StageAPI.LevelRoom:TriggerIndexMetadata(index, name, value) if value == nil then value = true end local groups = self:GetEntityMetadataGroups(index) self:SetMetadataTrigger(name, index, groups, value) end function StageAPI.LevelRoom:WasIndexTriggered(index, frames, exactFrame) return self:WasMetadataTriggered(nil, frames, index, self:GetEntityMetadataGroups(index), exactFrame) end function StageAPI.LevelRoom:IsGridIndexFree(index, ignoreEntities, ignoreGrids) return (ignoreEntities or not self.EntityTakenIndices[index]) and (ignoreGrids or not self.GridTakenIndices[index]) end function StageAPI.LevelRoom:SaveGridInformation() self.GridInformation = StageAPI.GetGridInformation() end function StageAPI.LevelRoom:SavePersistentEntities() for index, spawns in pairs(self.ExtraSpawn) do for _, spawn in ipairs(spawns) do if spawn.PersistenceData.RemoveOnRemove then local hasMatch = false local matching = Isaac.FindByType(spawn.Data.Type, spawn.Data.Variant, spawn.Data.SubType, false, false) for _, match in ipairs(matching) do if not spawn.PersistenceData.StoreCheck or not spawn.PersistenceData.StoreCheck(match, match:GetData()) then hasMatch = true end end if not hasMatch then self.AvoidSpawning[spawn.PersistentIndex] = true end end end end for index, spawns in pairs(self.SpawnEntities) do for _, spawn in ipairs(spawns) do if spawn.PersistenceData and spawn.PersistenceData.RemoveOnRemove then local hasMatch = false local matching = Isaac.FindByType(spawn.Data.Type, spawn.Data.Variant, spawn.Data.SubType, false, false) for _, match in ipairs(matching) do if not spawn.PersistenceData.StoreCheck or not spawn.PersistenceData.StoreCheck(match, match:GetData()) then hasMatch = true end end if not hasMatch then self.AvoidSpawning[spawn.PersistentIndex] = true end end end end for _, entity in ipairs(Isaac.GetRoomEntities()) do local data = entity:GetData() local entityPersistData = StageAPI.GetEntityPersistenceData(entity) if entityPersistData then if entityPersistData.PersistenceData.UpdatePosition then self.PersistentPositions[entityPersistData.PersistentIndex] = {X = entity.Position.X, Y = entity.Position.Y} end if entityPersistData.PersistenceData.StoreCheck and entityPersistData.PersistenceData.StoreCheck(entity, data) then self.AvoidSpawning[entityPersistData.PersistentIndex] = true end else local persistentData = StageAPI.CheckPersistence(entity.Type, entity.Variant, entity.SubType) if persistentData then if not persistentData.StoreCheck or not persistentData.StoreCheck(entity, data) then local index = self.LastPersistentIndex + 1 self.LastPersistentIndex = index local grindex = room:GetGridIndex(entity.Position) if not self.ExtraSpawn[grindex] then self.ExtraSpawn[grindex] = {} end self.ExtraSpawn[grindex][#self.ExtraSpawn[grindex] + 1] = { Data = { Type = entity.Type, Variant = entity.Variant, SubType = entity.SubType, Index = grindex }, Persistent = true, PersistentIndex = index, PersistenceData = persistentData } if persistentData.UpdatePosition then self.PersistentPositions[index] = {X = entity.Position.X, Y = entity.Position.Y} end StageAPI.SetEntityPersistenceData(entity, index, persistentData) end end end end end function StageAPI.LevelRoom:RemovePersistentIndex(persistentIndex) self.AvoidSpawning[persistentIndex] = true end function StageAPI.LevelRoom:RemovePersistentEntity(entity) local data = StageAPI.GetEntityPersistenceData(entity) if data and data.PersistenceData then self:RemovePersistentIndex(data.PersistentIndex) end end function StageAPI.LevelRoom:Load(isExtraRoom) Isaac.DebugString("[StageAPI] Loading room " .. self.Layout.Name .. "." .. tostring(self.Layout.Variant) .. " from file " .. tostring(self.Layout.RoomFilename)) if isExtraRoom == nil then isExtraRoom = self.IsExtraRoom end room:SetClear(true) local wasFirstLoad = self.FirstLoad StageAPI.ClearRoomLayout(false, self.FirstLoad or isExtraRoom, true, self.FirstLoad or isExtraRoom, self.GridTakenIndices) if self.FirstLoad then StageAPI.LoadRoomLayout(self.SpawnGrids, {self.SpawnEntities, self.ExtraSpawn}, true, true, false, true, self.GridInformation, self.AvoidSpawning, self.PersistentPositions) self.WasClearAtStart = room:IsClear() self.IsClear = self.WasClearAtStart self.FirstLoad = false self.HasEnemies = room:GetAliveEnemiesCount() > 0 else StageAPI.LoadRoomLayout(self.SpawnGrids, {self.SpawnEntities, self.ExtraSpawn}, isExtraRoom, true, self.IsClear, isExtraRoom, self.GridInformation, self.AvoidSpawning, self.PersistentPositions) self.IsClear = room:IsClear() end StageAPI.CalledRoomUpdate = true room:Update() StageAPI.CalledRoomUpdate = false if not self.IsClear then StageAPI.CloseDoors() end StageAPI.CallCallbacks("POST_ROOM_LOAD", false, self, wasFirstLoad, isExtraRoom) StageAPI.StoreRoomGrids() end function StageAPI.LevelRoom:Save() self:SavePersistentEntities() self:SaveGridInformation() end function StageAPI.LevelRoom:GetSaveData(isExtraRoom) if isExtraRoom == nil then isExtraRoom = self.IsExtraRoom end local saveData = {} saveData.IsClear = self.IsClear saveData.WasClearAtStart = self.WasClearAtStart saveData.RoomsListName = self.RoomsListName saveData.LayoutName = self.LayoutName saveData.Seed = self.Seed saveData.FirstLoad = self.FirstLoad saveData.Shape = self.Shape saveData.RoomType = self.RoomType saveData.TypeOverride = self.TypeOverride saveData.PersistentData = self.PersistentData saveData.IsExtraRoom = isExtraRoom saveData.LastPersistentIndex = self.LastPersistentIndex saveData.RequireRoomType = self.RequireRoomType saveData.IgnoreRoomRules = self.IgnoreRoomRules if self.GridInformation then for index, gridInfo in pairs(self.GridInformation) do if not saveData.GridInformation then saveData.GridInformation = {} end saveData.GridInformation[tostring(index)] = gridInfo end end for index, avoid in pairs(self.AvoidSpawning) do if avoid then if not saveData.AvoidSpawning then saveData.AvoidSpawning = {} end saveData.AvoidSpawning[#saveData.AvoidSpawning + 1] = index end end for pindex, position in pairs(self.PersistentPositions) do if not saveData.PersistentPositions then saveData.PersistentPositions = {} end saveData.PersistentPositions[tostring(pindex)] = position end for index, entities in pairs(self.ExtraSpawn) do if not saveData.ExtraSpawn then saveData.ExtraSpawn = {} end saveData.ExtraSpawn[tostring(index)] = entities end return saveData end function StageAPI.LevelRoom:LoadSaveData(saveData) self.Data = {} self.PersistentData = saveData.PersistentData or {} self.AvoidSpawning = {} self.PersistentPositions = {} self.ExtraSpawn = {} self.RoomsListName = saveData.RoomsListName self.LayoutName = saveData.LayoutName self.Seed = saveData.Seed self.Shape = saveData.Shape self.RoomType = saveData.RoomType self.RequireRoomType = saveData.RequireRoomType self.TypeOverride = saveData.TypeOverride self.IgnoreRoomRules = saveData.IgnoreRoomRules if saveData.Doors then self.Doors = {} for _, door in ipairs(saveData.Doors) do self.Doors[door] = true end end local layout if self.LayoutName then layout = StageAPI.Layouts[layoutName] end if self.RoomsListName and not layout then local roomsList = StageAPI.RoomsLists[self.RoomsListName] if roomsList then local retLayout = StageAPI.CallCallbacks("PRE_ROOM_LAYOUT_CHOOSE", true, self, roomsList) if retLayout then layout = retLayout else layout = StageAPI.ChooseRoomLayout(roomsList, self.Seed, self.Shape, self.RoomType, self.RequireRoomType, false, self.Doors) end end end self.Layout = layout self:PostGetLayout(self.Seed) self.LastPersistentIndex = saveData.LastPersistentIndex or self.LastPersistentIndex self.IsClear = saveData.IsClear self.WasClearAtStart = saveData.WasClearAtStart self.FirstLoad = saveData.FirstLoad self.IsExtraRoom = saveData.IsExtraRoom if saveData.GridInformation then for strindex, gridInfo in pairs(saveData.GridInformation) do if not self.GridInformation then self.GridInformation = {} end self.GridInformation[tonumber(strindex)] = gridInfo end end if saveData.AvoidSpawning then for _, index in ipairs(saveData.AvoidSpawning) do self.AvoidSpawning[index] = true end end if saveData.PersistentPositions then for strindex, position in pairs(saveData.PersistentPositions) do self.PersistentPositions[tonumber(strindex)] = position end end if saveData.ExtraSpawn then for strindex, entities in pairs(saveData.ExtraSpawn) do self.ExtraSpawn[tonumber(strindex)] = entities end end end function StageAPI.LevelRoom:SetTypeOverride(override) self.TypeOverride = override end function StageAPI.LevelRoom:GetType() return self.TypeOverride or self.RoomType end function StageAPI.RemovePersistentEntity(entity) local currentRoom = StageAPI.GetCurrentRoom() if currentRoom then currentRoom:RemovePersistentEntity(entity) end end mod:AddCallback(ModCallbacks.MC_POST_ENTITY_REMOVE, function(_, ent) local data = StageAPI.GetEntityPersistenceData(ent) -- Entities are removed whenever you exit the room, in this time the game is paused, which we can use to stop removing persistent entities on room exit. if data and data.PersistenceData and data.PersistenceData.RemoveOnRemove and not game:IsPaused() then StageAPI.RemovePersistentEntity(ent) end end) mod:AddCallback(ModCallbacks.MC_POST_ENTITY_KILL, function(_, ent) local data = StageAPI.GetEntityPersistenceData(ent) if data and data.PersistenceData and data.PersistenceData.RemoveOnDeath then StageAPI.RemovePersistentEntity(ent) end end) function StageAPI.IsDoorSlotAllowed(slot) local currentRoom = StageAPI.GetCurrentRoom() if currentRoom and currentRoom.Layout and currentRoom.Layout.Doors then for _, door in ipairs(currentRoom.Layout.Doors) do if door.Slot == slot and door.Exists then return true end end else return room:IsDoorSlotAllowed(slot) end end function StageAPI.SetRoomFromList(roomsList, roomType, requireRoomType, isExtraRoom, load, seed, shape, fromSaveData) local levelIndex = StageAPI.GetCurrentRoomID() local newRoom = StageAPI.LevelRoom(nil, roomsList, seed, shape, roomType, isExtraRoom, fromSaveData, requireRoomType, nil, nil, levelIndex) StageAPI.SetCurrentRoom(newRoom) if load then newRoom:Load(isExtraRoom) end return newRoom end end Isaac.DebugString("[StageAPI] Loading Custom Grid System") do -- Custom Grid Entities StageAPI.CustomGridTypes = {} StageAPI.CustomGrid = StageAPI.Class("CustomGrid") function StageAPI.CustomGrid:Init(name, baseType, baseVariant, anm2, animation, frame, variantFrames, offset, overrideGridSpawns, overrideGridSpawnAtState, forceSpawning, noOverrideGridSprite) self.Name = name self.BaseType = baseType self.BaseVariant = baseVariant self.Anm2 = anm2 self.Animation = animation self.Frame = frame self.VariantFrames = variantFrames self.OverrideGridSpawns = overrideGridSpawns self.OverrideGridSpawnState = overrideGridSpawnAtState self.NoOverrideGridSprite = noOverrideGridSprite self.ForceSpawning = forceSpawning self.Offset = offset StageAPI.CustomGridTypes[name] = self end StageAPI.DefaultBrokenGridStateByType = { [GridEntityType.GRID_ROCK] = 2, [GridEntityType.GRID_ROCKB] = 2, [GridEntityType.GRID_ROCKT] = 2, [GridEntityType.GRID_ROCK_SS] = 2, [GridEntityType.GRID_ROCK_BOMB] = 2, [GridEntityType.GRID_ROCK_ALT] = 2, [GridEntityType.GRID_SPIDERWEB] = 1, [GridEntityType.GRID_LOCK] = 1, [GridEntityType.GRID_TNT] = 4, [GridEntityType.GRID_FIREPLACE] = 4, [GridEntityType.GRID_POOP] = 1000, } StageAPI.CustomGrids = {} StageAPI.CustomGridIndices = {} function StageAPI.CustomGrid:Spawn(grindex, force, reSpawning, startPersistData) local grid if self.BaseType then if not reSpawning then force = force or self.ForceSpawning grid = Isaac.GridSpawn(self.BaseType, self.BaseVariant or 0, room:GetGridPosition(grindex), force) else grid = room:GetGridEntity(grindex) end if self.OverrideGridSpawns and grid then local overrideState = self.OverrideGridSpawnState or StageAPI.DefaultBrokenGridStateByType[grid.Desc.Type] or 2 if grid.State ~= overrideState then StageAPI.SpawnOverriddenGrids[grindex] = self.OverrideGridSpawnState or overrideState end end if self.Anm2 and grid then local sprite = grid:GetSprite() sprite:Load(self.Anm2, true) if self.VariantFrames or self.Frame then local animation = self.Animation or sprite:GetDefaultAnimation() if self.VariantFrames then sprite:SetFrame(animation, StageAPI.Random(0, self.VariantFrames)) else sprite:SetFrame(animation, self.Frame) end elseif self.Animation then sprite:Play(self.Animation, true) end if self.Offset then sprite.Offset = self.Offset end end end local lindex = StageAPI.GetCurrentRoomID() if not StageAPI.CustomGrids[lindex] then StageAPI.CustomGrids[lindex] = {} end if not StageAPI.CustomGrids[lindex][self.Name] then StageAPI.CustomGrids[lindex][self.Name] = {} end if not StageAPI.CustomGrids[lindex][self.Name][grindex] then StageAPI.CustomGrids[lindex][self.Name][grindex] = startPersistData or {} end StageAPI.CustomGridIndices[grindex] = true for _, callback in ipairs(StageAPI.GetCallbacks("POST_SPAWN_CUSTOM_GRID")) do if not callback.Params[1] or callback.Params[1] == self.Name then callback.Function(grindex, force, reSpawning, grid, StageAPI.CustomGrids[lindex][self.Name][grindex], self) end end return grid end function StageAPI.GetCustomGridIndicesByName(name) local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] and StageAPI.CustomGrids[lindex][name] then local ret = {} for grindex, exists in pairs(StageAPI.CustomGrids[lindex][name]) do ret[#ret + 1] = grindex end return ret end return {} end function StageAPI.GetCustomGridsByName(name) local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] and StageAPI.CustomGrids[lindex][name] then local ret = {} for grindex, persistData in pairs(StageAPI.CustomGrids[lindex][name]) do ret[#ret + 1] = { Name = name, PersistData = persistData, Data = StageAPI.CustomGridTypes[name], Index = grindex } end return ret end return {} end function StageAPI.GetCustomGrids() local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] then local ret = {} for name, grindices in pairs(StageAPI.CustomGrids[lindex]) do for grindex, persistData in pairs(grindices) do ret[#ret + 1] = { Name = name, PersistData = persistData, Data = StageAPI.CustomGridTypes[name], Index = grindex } end end return ret end return {} end function StageAPI.GetCustomGrid(index, name) local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] and StageAPI.CustomGrids[lindex][name] and StageAPI.CustomGrids[lindex][name][index] then return { Name = name, PersistData = StageAPI.CustomGrids[lindex][name][index], Data = StageAPI.CustomGridTypes[name], Index = index } end end function StageAPI.GetCustomGridsAtIndex(index) local lindex = StageAPI.GetCurrentRoomID() local grids = {} if StageAPI.CustomGrids[lindex] then for k, v in pairs(StageAPI.CustomGrids[lindex]) do if v[index] then grids[#grids + 1] = { Name = k, PersistData = v[index], Data = StageAPI.CustomGridTypes[k], Index = index } end end end return grids end function StageAPI.RemoveCustomGrid(index, name, keepVanillaGrid) local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] and StageAPI.CustomGrids[lindex][name] and StageAPI.CustomGrids[lindex][name][index] then local persistData = StageAPI.CustomGrids[lindex][name][index] StageAPI.CustomGrids[lindex][name][index] = nil StageAPI.CustomGridIndices[index] = nil if not keepVanillaGrid then room:RemoveGridEntity(index, 0, false) end local callbacks = StageAPI.GetCallbacks("POST_CUSTOM_GRID_REMOVE") for _, callback in ipairs(callbacks) do if not callback.Params[1] or callback.Params[1] == name then callback.Function(grindex, persistData, StageAPI.CustomGridTypes[name], name) end end end end function StageAPI.IsCustomGrid(index, name) if not name then return StageAPI.CustomGridIndices[index] else local lindex = StageAPI.GetCurrentRoomID() return StageAPI.CustomGrids[lindex] and StageAPI.CustomGrids[lindex][name] and not not StageAPI.CustomGrids[lindex][name][index] end end mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() local lindex = StageAPI.GetCurrentRoomID() if StageAPI.CustomGrids[lindex] then for name, grindices in pairs(StageAPI.CustomGrids[lindex]) do local customGridType = StageAPI.CustomGridTypes[name] for grindex, persistData in pairs(grindices) do local grid = room:GetGridEntity(grindex) if not grid and customGridType.BaseType then StageAPI.RemoveCustomGrid(grindex, name, true) else local callbacks = StageAPI.GetCallbacks("POST_CUSTOM_GRID_UPDATE") for _, callback in ipairs(callbacks) do if not callback.Params[1] or callback.Params[1] == name then callback.Function(grid, grindex, persistData, StageAPI.CustomGridTypes[name], name) end end end end end end end) end do -- Extra Rooms StageAPI.InExtraRoom = false StageAPI.LoadedExtraRoom = false StageAPI.CurrentExtraRoom = nil StageAPI.CurrentExtraRoomName = nil function StageAPI.SetExtraRoom(name, room) StageAPI.LevelRooms[name] = room end function StageAPI.GetExtraRoom(name) return StageAPI.LevelRooms[name] end function StageAPI.InOrTransitioningToExtraRoom() return StageAPI.TransitionTimer or StageAPI.InExtraRoom end function StageAPI.TransitioningToOrFromExtraRoom() return not not StageAPI.TransitionTimer end function StageAPI.TransitioningToExtraRoom() return StageAPI.TransitioningToOrFromExtraRoom() and StageAPI.TransitionToExtra end function StageAPI.TransitioningFromExtraRoom() return StageAPI.TransitioningToOrFromExtraRoom() and not StageAPI.TransitionToExtra end StageAPI.RoomTransitionOverlay = Sprite() StageAPI.RoomTransitionOverlay:Load("stageapi/overlay_black.anm2", false) StageAPI.RoomTransitionOverlay:ReplaceSpritesheet(0, "stageapi/overlay_black.png") StageAPI.RoomTransitionOverlay:LoadGraphics() StageAPI.RoomTransitionOverlay:Play("Idle", true) function StageAPI.RenderBlackScreen(alpha) alpha = alpha or 1 StageAPI.RoomTransitionOverlay.Scale = StageAPI.GetScreenScale(true) * 8 StageAPI.RoomTransitionOverlay.Color = Color(1, 1, 1, alpha, 0, 0, 0) StageAPI.RoomTransitionOverlay:Render(StageAPI.GetScreenCenterPosition(), zeroVector, zeroVector) end StageAPI.TransitionFadeTime = 30 StageAPI.TransitionTimer = nil StageAPI.TransitioningTo = nil StageAPI.TransitioningFromTo = nil StageAPI.TransitionExitSlot = nil StageAPI.TransitionToExtra = nil StageAPI.SkipExtraRoomTransition = nil StageAPI.ExtraRoomBaseType = "Barren" function StageAPI.TransitionToExtraRoom(name, exitSlot, skipTransition, extraRoomBaseType) StageAPI.TransitionTimer = 0 StageAPI.TransitioningTo = name StageAPI.TransitionExitSlot = exitSlot StageAPI.TransitionToExtra = true StageAPI.SkipExtraRoomTransition = skipTransition StageAPI.ExtraRoomBaseType = extraRoomBaseType or "Barren" end function StageAPI.TransitionFromExtraRoom(toIndex, exitSlot) StageAPI.TransitionTimer = 0 StageAPI.TransitioningFromTo = toIndex StageAPI.TransitionExitSlot = exitSlot StageAPI.TransitionToExtra = false end StageAPI.RoomShapeToGotoID = { [RoomShape.ROOMSHAPE_1x1] = { Barren = "4550", Boss = "1010", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2, LevelStage.STAGE5, LevelStage.STAGE6, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "0" } } }, [RoomShape.ROOMSHAPE_IH] = { Barren = "4551", Boss = "1077", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "569" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "616" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "254" } } }, [RoomShape.ROOMSHAPE_IV] = { Barren = "4552", Boss = "1078", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "578" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "638" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "270" } } }, [RoomShape.ROOMSHAPE_1x2] = { Barren = "4553", Boss = "3702", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "780" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "863" }, { Stages = {LevelStage.STAGE3_1, LevelStage.STAGE3_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "775" }, { Stages = {LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "797" }, { Stages = {LevelStage.STAGE5}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "346" }, { Stages = {LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "318" } } }, [RoomShape.ROOMSHAPE_IIV] = { Barren = "4554", Boss = "4554", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "700" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "654" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "306" } } }, [RoomShape.ROOMSHAPE_2x1] = { Barren = "4555", Boss = "3700", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "785" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "729" }, { Stages = {LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "733" }, { Stages = {LevelStage.STAGE5}, StageTypes = {StageType.STAGETYPE_ORIGINAL}, ID = "180" }, { Stages = {LevelStage.STAGE5}, StageTypes = {StageType.STAGETYPE_WOTL}, ID = "145" }, { Stages = {LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "58" } } }, [RoomShape.ROOMSHAPE_IIH] = { Barren = "4556", Boss = "4556", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "712" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "669" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "310" } } }, [RoomShape.ROOMSHAPE_2x2] = { Barren = "4557", Boss = "3414", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "774" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "730" }, { Stages = {LevelStage.STAGE5}, StageTypes = {StageType.STAGETYPE_ORIGINAL}, ID = "223" }, { Stages = {LevelStage.STAGE5}, StageTypes = {StageType.STAGETYPE_WOTL}, ID = "172" }, { Stages = {LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "77" } } }, [RoomShape.ROOMSHAPE_LTL] = { Barren = "4558", Boss = "4558", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "814" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "751" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL}, ID = "295" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_WOTL}, ID = "296" } } }, [RoomShape.ROOMSHAPE_LTR] = { Barren = "4559", Boss = "4559", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "820" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "757" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL}, ID = "299" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_WOTL}, ID = "297" } } }, [RoomShape.ROOMSHAPE_LBL] = { Barren = "4560", Boss = "4560", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "828" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "763" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "300" } } }, [RoomShape.ROOMSHAPE_LBR] = { Barren = "4561", Boss = "4561", Stage = { { Stages = {LevelStage.STAGE1_1, LevelStage.STAGE1_2, LevelStage.STAGE7}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "830" }, { Stages = {LevelStage.STAGE2_1, LevelStage.STAGE2_2, LevelStage.STAGE3_1, LevelStage.STAGE3_2, LevelStage.STAGE4_1, LevelStage.STAGE4_2}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "769" }, { Stages = {LevelStage.STAGE5, LevelStage.STAGE6}, StageTypes = {StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH}, ID = "303" } } } } function StageAPI.GetGotoIDForStage(shape, stage, stagetype) local stagesets = StageAPI.RoomShapeToGotoID[shape].Stage for _, stageset in ipairs(stagesets) do local isIn for _, lvlstage in ipairs(stageset.Stages) do if stage == lvlstage then isIn = true break end end if isIn then for _, stgtype in ipairs(stageset.StageTypes) do if stagetype == stgtype then return stageset.ID end end end end end local shadowSprite = Sprite() shadowSprite:Load("stageapi/stage_shadow.anm2", false) shadowSprite:Play("1x1", true) local lastUsedShadowSpritesheet StageAPI.StoredExtraRoomThisPause = false mod:AddCallback(ModCallbacks.MC_POST_RENDER, function() if not game:IsPaused() then StageAPI.StoredExtraRoomThisPause = false if StageAPI.TransitioningTo or StageAPI.TransitioningFromTo then StageAPI.TransitionTimer = StageAPI.TransitionTimer + 1 if StageAPI.TransitionTimer == StageAPI.TransitionFadeTime or StageAPI.SkipExtraRoomTransition then if StageAPI.CurrentExtraRoom then StageAPI.CurrentExtraRoom:SaveGridInformation() StageAPI.CurrentExtraRoom:SavePersistentEntities() end if StageAPI.TransitioningTo then if not StageAPI.InExtraRoom then StageAPI.LastNonExtraRoom = level:GetCurrentRoomIndex() end local extraRoom = StageAPI.GetExtraRoom(StageAPI.TransitioningTo) StageAPI.InExtraRoom = true StageAPI.CurrentExtraRoom = extraRoom StageAPI.CurrentExtraRoomName = StageAPI.TransitioningTo StageAPI.TransitioningTo = nil if StageAPI.ExtraRoomBaseType == "Barren" then local id = StageAPI.RoomShapeToGotoID[extraRoom.Shape].Barren Isaac.ExecuteCommand("goto s.barren." .. id) elseif StageAPI.ExtraRoomBaseType == "Stage" then local id = StageAPI.GetGotoIDForStage(extraRoom.Shape, level:GetStage(), level:GetStageType()) Isaac.ExecuteCommand("goto d." .. id) elseif StageAPI.ExtraRoomBaseType == "Boss" then local id = StageAPI.RoomShapeToGotoID[extraRoom.Shape].Boss Isaac.ExecuteCommand("goto s.boss." .. id) end elseif StageAPI.TransitioningFromTo then StageAPI.InExtraRoom = nil StageAPI.CurrentExtraRoom = nil StageAPI.CurrentExtraRoomName = nil game:StartRoomTransition(StageAPI.TransitioningFromTo, Direction.NO_DIRECTION, 0) StageAPI.TransitioningFromTo = nil end StageAPI.LoadedExtraRoom = false end elseif StageAPI.TransitionTimer then StageAPI.TransitionTimer = StageAPI.TransitionTimer - 1 if StageAPI.TransitionTimer <= 0 or StageAPI.SkipExtraRoomTransition then StageAPI.TransitionTimer = nil StageAPI.TransitionToExtra = nil StageAPI.SkipExtraRoomTransition = nil end end elseif StageAPI.LoadedExtraRoom and not StageAPI.StoredExtraRoomThisPause then StageAPI.StoredExtraRoomThisPause = true StageAPI.CurrentExtraRoom:SaveGridInformation() StageAPI.CurrentExtraRoom:SavePersistentEntities() end if not StageAPI.IsHUDAnimationPlaying() then if not StageAPI.InNewStage() then local btype, stage, stype = room:GetBackdropType(), level:GetStage(), level:GetStageType() if (btype == 7 or btype == 8 or btype == 16) and (stage == LevelStage.STAGE3_1 or stage == LevelStage.STAGE3_2 or stage == LevelStage.STAGE6) then for _, overlay in ipairs(StageAPI.NecropolisOverlays) do if not game:IsPaused() then overlay:Update() end overlay:Render(nil, nil, true) end end end local shadows = Isaac.FindByType(StageAPI.E.StageShadow.T, StageAPI.E.StageShadow.V, -1, false, false) local shadow = shadows[1] if shadow then local shadowSheet, shadowAnim = shadow:GetData().Sheet, shadow:GetData().Animation if shadowSheet and shadowSheet ~= lastUsedShadowSpritesheet then shadowSprite:ReplaceSpritesheet(0, shadowSheet) shadowSprite:LoadGraphics() lastUsedShadowSpritesheet = shadowSheet end if shadowAnim and not (shadowSprite:IsPlaying(shadowAnim) or shadowSprite:IsFinished(shadowAnim)) then shadowSprite:Play(shadowAnim, true) end shadowSprite:Render(Isaac.WorldToRenderPosition(shadow.Position) + room:GetRenderScrollOffset(), zeroVector, zeroVector) end end StageAPI.CallCallbacks("PRE_TRANSITION_RENDER") if StageAPI.TransitionTimer then for _, player in ipairs(players) do player.ControlsCooldown = 2 end StageAPI.RenderBlackScreen(StageAPI.TransitionTimer / StageAPI.TransitionFadeTime) end end) StageAPI.DoorToDirection = { [DoorSlot.DOWN0] = Direction.DOWN, [DoorSlot.DOWN1] = Direction.DOWN, [DoorSlot.LEFT0] = Direction.LEFT, [DoorSlot.LEFT1] = Direction.LEFT, [DoorSlot.RIGHT0] = Direction.RIGHT, [DoorSlot.RIGHT1] = Direction.RIGHT, [DoorSlot.UP0] = Direction.UP, [DoorSlot.UP1] = Direction.UP } StageAPI.DoorOffsetsByDirection = { [Direction.DOWN] = Vector(0, -15), [Direction.UP] = Vector(0, 15), [Direction.LEFT] = Vector(15, 0), [Direction.RIGHT] = Vector(-15, 0) } function StageAPI.DirectionToDegrees(dir) return dir * 90 - 90 end StageAPI.CustomDoorGrid = StageAPI.CustomGrid("CustomDoor") StageAPI.DoorTypes = {} StageAPI.CustomDoor = StageAPI.Class("CustomDoor") function StageAPI.CustomDoor:Init(name, anm2, openAnim, closeAnim, openedAnim, closedAnim, noAutoHandling, alwaysOpen) self.NoAutoHandling = noAutoHandling self.AlwaysOpen = alwaysOpen self.Anm2 = anm2 or "gfx/grid/door_01_normaldoor.anm2" self.OpenAnim = openAnim or "Open" self.CloseAnim = closeAnim or "Close" self.OpenedAnim = openedAnim or "Opened" self.ClosedAnim = closedAnim or "Closed" self.Name = name StageAPI.DoorTypes[name] = self end StageAPI.DefaultDoor = StageAPI.CustomDoor("DefaultDoor") function StageAPI.SpawnCustomDoor(slot, leadsToExtra, leadsToNormal, doorDataName, data, exitSlot) local index = room:GetGridIndex(room:GetDoorSlotPosition(slot)) StageAPI.CustomDoorGrid:Spawn(index, nil, false, { Slot = slot, ExitSlot = exitSlot or (slot + 2) % 4, LeadsToExtra = leadsToExtra, LeadsToNormal = leadsToNormal, DoorDataName = doorDataName, Data = data }) end function StageAPI.GetCustomDoors(doorDataName) local ret = {} local doors = StageAPI.GetCustomGridsByName("CustomDoor") for _, door in ipairs(doors) do if not doorDataName or door.PersistData.DoorDataName == doorDataName then ret[#ret + 1] = door end end return ret end StageAPI.AddCallback("StageAPI", "POST_SPAWN_CUSTOM_GRID", 0, function(index, force, respawning, grid, persistData, customGrid) local doorData if persistData.DoorDataName and StageAPI.DoorTypes[persistData.DoorDataName] then doorData = StageAPI.DoorTypes[persistData.DoorDataName] else doorData = StageAPI.DefaultDoor end local door = Isaac.Spawn(StageAPI.E.Door.T, StageAPI.E.Door.V, 0, room:GetGridPosition(index), zeroVector, nil) door.Visible = false local data, sprite = door:GetData(), door:GetSprite() sprite:Load(doorData.Anm2, true) door.RenderZOffset = -10000 sprite.Rotation = persistData.Slot * 90 - 90 sprite.Offset = StageAPI.DoorOffsetsByDirection[StageAPI.DoorToDirection[persistData.Slot]] if not doorData.NoAutoHandling then if doorData.AlwaysOpen then sprite:Play(doorData.OpenedAnim, true) elseif doorData.AlwaysOpen == false then sprite:Play(doorData.ClosedAnim, true) else if room:IsClear() then sprite:Play(doorData.OpenedAnim, true) else sprite:Play(doorData.ClosedAnim, true) end end end local opened = sprite:IsPlaying(doorData.OpenedAnim) or sprite:IsFinished(doorData.OpenedAnim) local grid = room:GetGridEntity(index) if opened then grid.CollisionClass = GridCollisionClass.COLLISION_WALL_EXCEPT_PLAYER else grid.CollisionClass = GridCollisionClass.COLLISION_WALL end data.DoorGridData = persistData data.DoorData = doorData data.Opened = opened local callbacks = StageAPI.GetCallbacks("POST_SPAWN_CUSTOM_DOOR") for _, callback in ipairs(callbacks) do if not callback.Params[1] or callback.Params[1] == persistData.DoorDataName then callback.Function(door, data, sprite, doorData, persistData, index, force, respawning, grid, customGrid) end end end, "CustomDoor") StageAPI.AddCallback("StageAPI", "PRE_SHADING_RENDER", 0, function(shading) for _, door in ipairs(Isaac.FindByType(StageAPI.E.Door.T, StageAPI.E.Door.V, -1, false, false)) do door:GetSprite():Render(Isaac.WorldToRenderPosition(door.Position) + room:GetRenderScrollOffset(), zeroVector, zeroVector) end end) function StageAPI.SetDoorOpen(open, door) local grid = room:GetGridEntityFromPos(door.Position) if open then grid.CollisionClass = GridCollisionClass.COLLISION_WALL_EXCEPT_PLAYER else grid.CollisionClass = GridCollisionClass.COLLISION_WALL end end local framesWithoutDoorData = 0 local hadFrameWithoutDoorData = false mod:AddCallback(ModCallbacks.MC_POST_EFFECT_UPDATE, function(_, door) local data, sprite = door:GetData(), door:GetSprite() local doorData = data.DoorData if StageAPI.TransitioningToOrFromExtraRoom() then return end if not doorData then framesWithoutDoorData = framesWithoutDoorData + 1 hadFrameWithoutDoorData = true return end if not doorData.NoAutoHandling and doorData.AlwaysOpen == nil then if sprite:IsFinished(doorData.OpenAnim) then StageAPI.SetDoorOpen(true, door) sprite:Play(doorData.OpenedAnim, true) elseif sprite:IsFinished(doorData.CloseAnim) then StageAPI.SetDoorOpen(false, door) sprite:Play(doorData.ClosedAnim, true) end if room:IsClear() and not data.Opened then data.Opened = true sprite:Play(doorData.OpenAnim, true) elseif not room:IsClear() and data.Opened then data.Opened = false sprite:Play(doorData.CloseAnim, true) end end local transitionStarted for _, player in ipairs(players) do local size = 32 + player.Size if not room:IsPositionInRoom(player.Position, -16) and player.Position:DistanceSquared(door.Position) < size * size then if data.DoorGridData.LeadsToExtra then transitionStarted = true StageAPI.TransitionToExtraRoom(data.DoorGridData.LeadsToExtra, data.DoorGridData.ExitSlot) elseif data.DoorGridData.LeadsToNormal then transitionStarted = true StageAPI.TransitionFromExtraRoom(data.DoorGridData.LeadsToNormal, data.DoorGridData.ExitSlot) end end end if transitionStarted then for _, player in ipairs(players) do player.Velocity = zeroVector end end local callbacks = StageAPI.GetCallbacks("POST_CUSTOM_DOOR_UPDATE") for _, callback in ipairs(callbacks) do if not callback.Params[1] or callback.Params[1] == data.DoorGridData.DoorDataName then callback.Function(door, data, sprite, doorData, data.DoorGridData) end end end, StageAPI.E.Door.V) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() if hadFrameWithoutDoorData then hadFrameWithoutDoorData = false elseif framesWithoutDoorData > 0 then StageAPI.Log("Had no door data for " .. tostring(framesWithoutDoorData) .. " frames") framesWithoutDoorData = 0 end end) end Isaac.DebugString("[StageAPI] Loading GridGfx Handler") do -- GridGfx StageAPI.GridGfx = StageAPI.Class("GridGfx") function StageAPI.GridGfx:Init() self.Grids = false self.Doors = false end function StageAPI.GridGfx:SetRocks(filename, noBridge) self.Rocks = filename if not self.Bridges and not noBridge then self.Bridges = filename end end function StageAPI.GridGfx:SetGrid(filename, t, v) if not self.Grids then self.Grids = {} self.GridsByVariant = {} end if v then if not self.GridsByVariant[t] then self.GridsByVariant[t] = {} end self.GridsByVariant[t][v] = filename else self.Grids[t] = filename end end function StageAPI.GridGfx:SetPits(filenames, alts, hasExtraFrames) if type(filenames) == 'string' then filenames = { { File = filenames, HasExtraFrames = hasExtraFrames } } end if type(alts) == 'string' then alts = { { File = alts, HasExtraFrames = hasExtraFrames } } end self.PitFiles = filenames self.AltPitFiles = alts end function StageAPI.GridGfx:SetBridges(filename) self.Bridges = filename end function StageAPI.GridGfx:SetDecorations(filename, anm2, propCount, prefix, suffix) self.Decorations = { Png = filename, Anm2 = anm2 or "gfx/grid/props_03_caves.anm2", PropCount = propCount or 42, Prefix = prefix or "Prop", Suffix = suffix or "" } end -- No SetPoop, do GridGfx:SetGrid(filename, GridEntityType.GRID_POOP, StageAPI.PoopVariant.Normal) StageAPI.DefaultDoorSpawn = { RequireCurrent = {RoomType.ROOM_DEFAULT, RoomType.ROOM_MINIBOSS, RoomType.ROOM_SACRIFICE, RoomType.ROOM_SHOP, RoomType.ROOM_LIBRARY, RoomType.ROOM_BARREN, RoomType.ROOM_ISAACS, RoomType.ROOM_DICE, RoomType.ROOM_CHEST}, RequireTarget = {RoomType.ROOM_DEFAULT, RoomType.ROOM_MINIBOSS, RoomType.ROOM_SACRIFICE, RoomType.ROOM_SHOP, RoomType.ROOM_LIBRARY, RoomType.ROOM_BARREN, RoomType.ROOM_ISAACS, RoomType.ROOM_DICE, RoomType.ROOM_CHEST} } StageAPI.SecretDoorSpawn = { RequireTarget = {RoomType.ROOM_SECRET, RoomType.ROOM_SUPERSECRET}, NotCurrent = {RoomType.ROOM_SECRET, RoomType.ROOM_SUPERSECRET} } --[[ DoorInfo { RequireCurrent = {}, RequireTarget = {}, RequireEither = {}, NotCurrent = {}, NotTarget = {}, NotEither = {} } ]] function StageAPI.GridGfx:AddDoors(filename, doorInfo) if not self.Doors then self.Doors = {} end if doorInfo.IsBossAmbush then self.HasBossAmbushDoor = true end self.Doors[#self.Doors + 1] = { File = filename, RequireCurrent = doorInfo.RequireCurrent, RequireTarget = doorInfo.RequireTarget, RequireEither = doorInfo.RequireEither, NotCurrent = doorInfo.NotCurrent, NotTarget = doorInfo.NotTarget, NotEither = doorInfo.NotEither, IsBossAmbush = doorInfo.IsBossAmbush } end function StageAPI.GridGfx:SetPayToPlayDoor(filename) self.PayToPlayDoor = filename end StageAPI.GridGfxRNG = RNG() function StageAPI.ChangeRock(rock, filename) local grid = rock.Grid local gsprite = grid:GetSprite() for i = 0, 4 do gsprite:ReplaceSpritesheet(i, filename) end gsprite:LoadGraphics() grid:ToRock():UpdateAnimFrame() end StageAPI.BridgedPits = {} mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.BridgedPits = {} end) function StageAPI.CheckBridge(grid, index, bridgefilename) if grid.State == 1 and bridgefilename and not StageAPI.BridgedPits[index] then local sprite = grid:GetSprite() sprite:ReplaceSpritesheet(1, bridgefilename) sprite:LoadGraphics() StageAPI.BridgedPits[index] = true end end function StageAPI.ChangePit(pit, pitFile, bridgefilename, alt) local grid = pit.Grid local gsprite = grid:GetSprite() if gsprite:GetFilename() ~= "stageapi/pit.anm2" then gsprite:Load("stageapi/pit.anm2", true) end if alt and room:HasWaterPits() then gsprite:ReplaceSpritesheet(0, alt.File) else gsprite:ReplaceSpritesheet(0, pitFile.File) end if bridgefilename then gsprite:ReplaceSpritesheet(1, bridgefilename) end gsprite:LoadGraphics() end StageAPI.DecorationSprites = {} function StageAPI.ChangeDecoration(decoration, decorations) local grid = decoration.Grid local gsprite = grid:GetSprite() gsprite:Load(decorations.Anm2, false) gsprite:ReplaceSpritesheet(0, decorations.Png) gsprite:LoadGraphics() local prop = StageAPI.Random(1, decorations.PropCount, StageAPI.GridGfxRNG) if prop < 10 then prop = "0" .. tostring(prop) end gsprite:Play(decorations.Prefix .. tostring(prop) .. decorations.Suffix, true) end StageAPI.DoorAnimationMap = { "Opened", "Closed", "Open", "Close", "Break", "KeyOpen", "KeyClose", "BrokenOpen", "KeyClosed", "Hidden", "GoldenKeyOpen", "KeyOpenNoKey", "GoldKeyOpen", "ArcadeSign" } function StageAPI.DoesDoorMatch(door, doorSpawn, current, target, hasBossAmbushDoor) current = current or door.CurrentRoomType target = target or door.TargetRoomType local valid = true local isChallengeRequired = false if doorSpawn.RequireCurrent then local has = false for _, roomType in ipairs(doorSpawn.RequireCurrent) do if current == roomType then if roomType == RoomType.ROOM_CHALLENGE then isChallengeRequired = true end has = true end end if not has then valid = false end end if doorSpawn.RequireTarget then local has = false for _, roomType in ipairs(doorSpawn.RequireTarget) do if target == roomType then if roomType == RoomType.ROOM_CHALLENGE then isChallengeRequired = true end has = true end end if not has then valid = false end end if doorSpawn.RequireEither then local has = false for _, roomType in ipairs(doorSpawn.RequireEither) do if current == roomType or target == roomType then if roomType == RoomType.ROOM_CHALLENGE then isChallengeRequired = true end has = true end end if not has then valid = false end end if doorSpawn.NotCurrent then local has = false for _, roomType in ipairs(doorSpawn.NotCurrent) do if current == roomType then has = true end end if has then valid = false end end if doorSpawn.NotTarget then local has = false for _, roomType in ipairs(doorSpawn.NotTarget) do if target == roomType then has = true end end if has then valid = false end end if doorSpawn.NotEither then local has = false for _, roomType in ipairs(doorSpawn.NotEither) do if current == roomType or target == roomType then has = true end end if has then valid = false end end if isChallengeRequired and (current == RoomType.ROOM_CHALLENGE or target == RoomType.ROOM_CHALLENGE) and ((doorSpawn.IsBossAmbush and not level:HasBossChallenge()) or (not doorSpawn.IsBossAmbush and hasBossAmbushDoor and level:HasBossChallenge())) then valid = false end return valid end StageAPI.DoorSprite = Sprite() function StageAPI.ChangeDoor(door, doors, payToPlay, hasBossAmbushDoor) local grid = door.Grid:ToDoor() local gsprite = grid:GetSprite() local current = grid.CurrentRoomType local target = grid.TargetRoomType local isPayToPlay = grid:IsTargetRoomArcade() and target ~= RoomType.ROOM_ARCADE if isPayToPlay then if payToPlay then for i = 0, 5 do gsprite:ReplaceSpritesheet(i, payToPlay) end gsprite:LoadGraphics() end return end for _, doorOption in ipairs(doors) do if StageAPI.DoesDoorMatch(grid, doorOption, current, target, hasBossAmbushDoor) then for i = 0, 5 do gsprite:ReplaceSpritesheet(i, doorOption.File) end gsprite:LoadGraphics() break end end end function StageAPI.ChangeGrid(sent, filename) local grid = sent.Grid local sprite = grid:GetSprite() if type(filename) == "table" then filename = filename[StageAPI.Random(1, #filename, StageAPI.GridGfxRNG)] end sprite:ReplaceSpritesheet(0, filename) sprite:LoadGraphics() end function StageAPI.ChangeSingleGrid(grid, grids, i) local desc = grid.Desc local gtype = desc.Type local send = {Grid = grid, Index = i, Type = gtype, Desc = desc} if gtype == GridEntityType.GRID_DOOR and grids.Doors then StageAPI.ChangeDoor(send, grids.Doors, grids.PayToPlayDoor, grids.HasBossAmbushDoor) elseif StageAPI.RockTypes[gtype] and grids.Rocks then StageAPI.ChangeRock(send, grids.Rocks) elseif gtype == GridEntityType.GRID_PIT and grids.Pits then StageAPI.ChangePit(send, grids.Pits, grids.Bridges, grids.AltPits) elseif gtype == GridEntityType.GRID_DECORATION and grids.Decorations then StageAPI.ChangeDecoration(send, grids.Decorations) elseif grids.Grids or grids.GridsByVariant then local variant = send.Desc.Variant if grids.GridsByVariant and grids.GridsByVariant[send.Type] and grids.GridsByVariant[send.Type][variant] then StageAPI.ChangeGrid(send, grids.GridsByVariant[send.Type][variant]) elseif grids.Grids and grids.Grids[send.Type] then StageAPI.ChangeGrid(send, grids.Grids[send.Type]) end end end function StageAPI.ChangeDoors(doors) if doors then local payToPlay if doors.Type == "GridGfx" then doors = doors.Doors payToPlay = doors.PayToPlayDoor elseif doors.Type == "CustomStage" and doors.RoomGfx then local roomgfx = doors.RoomGfx[room:GetType()] if roomgfx and roomgfx.Grids then doors = roomgfx.Grids.Doors payToPlay = roomgfx.Grids.PayToPlayDoor end elseif doors.Type == "RoomGfx" and doors.Grids then payToPlay = doors.Grids.PayToPlayDoor doors = doors.Grids.Doors end if doors then for i = 0, 7 do local door = room:GetDoor(i) if door then StageAPI.ChangeDoor({Grid = door}, doors, payToPlay) end end end end end function StageAPI.ChangeGrids(grids) StageAPI.GridGfxRNG:SetSeed(room:GetDecorationSeed(), 0) if grids.PitFiles then grids.Pits = grids.PitFiles[StageAPI.Random(1, #grids.PitFiles, StageAPI.GridGfxRNG)] end if grids.AltPitFiles then grids.AltPits = grids.AltPitFiles[StageAPI.Random(1, #grids.AltPitFiles, StageAPI.GridGfxRNG)] end local pitsToUse = room:HasWaterPits() and grids.AltPits or grids.Pits local hasExtraPitFrames = pitsToUse and pitsToUse.HasExtraFrames local gridCount = 0 local pits = {} for i = 0, room:GetGridSize() do local customGrids = StageAPI.GetCustomGridsAtIndex(i) local customGridBlocking = false for _, cgrid in ipairs(customGrids) do if not cgrid.Data.NoOverrideGridSprite then customGridBlocking = true end end if not customGridBlocking then local grid = room:GetGridEntity(i) if grid then if hasExtraPitFrames and grid.Desc.Type == GridEntityType.GRID_PIT then pits[i] = grid else StageAPI.ChangeSingleGrid(grid, grids, i) end end end end StageAPI.CallGridPostInit() if hasExtraPitFrames and next(pits) then local width = room:GetGridWidth() for index, pit in pairs(pits) do StageAPI.ChangePit({Grid = pit, Index = index}, grids.Pits, grids.Bridges, grids.AltPits) local sprite = pit:GetSprite() local adj = {index - 1, index + 1, index - width, index + width, index - width - 1, index + width - 1, index - width + 1, index + width + 1} local adjPits = {} for _, ind in ipairs(adj) do local grid = room:GetGridEntity(ind) adjPits[#adjPits + 1] = not not (grid and grid.Desc.Type == GridEntityType.GRID_PIT) end adjPits[#adjPits + 1] = true sprite:SetFrame("pit", StageAPI.GetPitFrame(table.unpack(adjPits))) end end end end Isaac.DebugString("[StageAPI] Loading Backdrop & RoomGfx Handling") do -- Backdrop & RoomGfx StageAPI.BackdropRNG = RNG() local backdropDefaultOffset = Vector(260,0) local backdropIvOffset = Vector(113,0) local lRooms = { RoomShape.ROOMSHAPE_LTL, RoomShape.ROOMSHAPE_LTR, RoomShape.ROOMSHAPE_LBL, RoomShape.ROOMSHAPE_LBR } for _, roomsh in ipairs(lRooms) do lRooms[roomsh] = true end StageAPI.ShapeToWallAnm2Layers = { ["1x2"] = 58, ["2x2"] = 63, ["2x2X"] = 21, ["IIH"] = 62, ["LTR"] = 63, ["LTRX"] = 19, ["2x1"] = 63, ["2x1X"] = 7, ["1x1"] = 44, ["LTL"] = 63, ["LTLX"] = 19, ["LBR"] = 63, ["LBRX"] = 19, ["LBL"] = 63, ["LBLX"] = 19, ["IIV"] = 42, ["IH"] = 36, ["IV"] = 28 } StageAPI.ShapeToName = { [RoomShape.ROOMSHAPE_IV] = "IV", [RoomShape.ROOMSHAPE_1x2] = "1x2", [RoomShape.ROOMSHAPE_2x2] = "2x2", [RoomShape.ROOMSHAPE_IH] = "IH", [RoomShape.ROOMSHAPE_LTR] = "LTR", [RoomShape.ROOMSHAPE_LTL] = "LTL", [RoomShape.ROOMSHAPE_2x1] = "2x1", [RoomShape.ROOMSHAPE_1x1] = "1x1", [RoomShape.ROOMSHAPE_LBL] = "LBL", [RoomShape.ROOMSHAPE_LBR] = "LBR", [RoomShape.ROOMSHAPE_IIH] = "IIH", [RoomShape.ROOMSHAPE_IIV] = "IIV" } function StageAPI.LoadBackdropSprite(sprite, backdrop, mode) -- modes are 1 (walls A), 2 (floors), 3 (walls B) sprite = sprite or Sprite() local needsExtra local roomShape = room:GetRoomShape() local shapeName = StageAPI.ShapeToName[roomShape] if StageAPI.ShapeToWallAnm2Layers[shapeName .. "X"] then needsExtra = true end if mode == 3 then shapeName = shapeName .. "X" end if mode == 1 or mode == 3 then sprite:Load("stageapi/WallBackdrop.anm2", false) if backdrop.Walls then for num = 1, StageAPI.ShapeToWallAnm2Layers[shapeName] do local wall_to_use = backdrop.Walls[StageAPI.Random(1, #backdrop.Walls, backdropRNG)] sprite:ReplaceSpritesheet(num, wall_to_use) end end if backdrop.Corners and string.sub(shapeName, 1, 1) == "L" then local corner_to_use = backdrop.Corners[StageAPI.Random(1, #backdrop.Corners, backdropRNG)] sprite:ReplaceSpritesheet(0, corner_to_use) end else sprite:Load("stageapi/FloorBackdrop.anm2", false) local floors if backdrop.FloorVariants then floors = backdrop.FloorVariants[StageAPI.Random(1, #backdrop.FloorVariants, backdropRNG)] else floors = backdrop.Floors or backdrop.Walls end if floors then local numWalls if roomShape == RoomShape.ROOMSHAPE_1x1 then numWalls = 4 elseif roomShape == RoomShape.ROOMSHAPE_1x2 or roomShape == RoomShape.ROOMSHAPE_2x1 then numWalls = 8 elseif roomShape == RoomShape.ROOMSHAPE_2x2 then numWalls = 16 end if numWalls then for i = 0, numWalls - 1 do sprite:ReplaceSpritesheet(i, floors[StageAPI.Random(1, #floors, backdropRNG)]) end end end if backdrop.NFloors and string.sub(shapeName, 1, 1) == "I" then for num = 18, 19 do sprite:ReplaceSpritesheet(num, backdrop.NFloors[StageAPI.Random(1, #backdrop.NFloors, backdropRNG)]) end end if backdrop.LFloors and string.sub(shapeName, 1, 1) == "L" then for num = 16, 17 do sprite:ReplaceSpritesheet(num, backdrop.LFloors[StageAPI.Random(1, #backdrop.LFloors, backdropRNG)]) end end end sprite:LoadGraphics() local renderPos = room:GetTopLeftPos() if mode ~= 2 then renderPos = renderPos - Vector(80, 80) end sprite:Play(shapeName, true) return renderPos, needsExtra end function StageAPI.ChangeBackdrop(backdrop, justWalls, storeBackdropEnts) StageAPI.BackdropRNG:SetSeed(room:GetDecorationSeed(), 1) local needsExtra, backdropEnts if storeBackdropEnts then backdropEnts = {} end for i = 1, 3 do if justWalls and i == 2 then i = 3 end if i == 3 and not needsExtra then break end local backdropEntity = Isaac.Spawn(StageAPI.E.Backdrop.T, StageAPI.E.Backdrop.V, 0, zeroVector, zeroVector, nil) local sprite = backdropEntity:GetSprite() local renderPos renderPos, needsExtra = StageAPI.LoadBackdropSprite(sprite, backdrop, i) backdropEntity.Position = renderPos if i == 1 or i == 3 then backdropEntity:AddEntityFlags(EntityFlag.FLAG_RENDER_WALL) else backdropEntity:AddEntityFlags(EntityFlag.FLAG_RENDER_FLOOR) end if storeBackdropEnts then backdropEnts[#backdropEnts + 1] = backdropEntity end end return backdropEnts end StageAPI.StageShadowRNG = RNG() function StageAPI.ChangeStageShadow(prefix, count) prefix = prefix or "stageapi/floors/catacombs/overlays/" count = count or 5 local shadows = Isaac.FindByType(StageAPI.E.StageShadow.T, StageAPI.E.StageShadow.V, -1, false, false) for _, e in ipairs(shadows) do e:Remove() end local roomShape = room:GetRoomShape() local anim if roomShape == RoomShape.ROOMSHAPE_1x1 or roomShape == RoomShape.ROOMSHAPE_IH or roomShape == RoomShape.ROOMSHAPE_IV then anim = "1x1" elseif roomShape == RoomShape.ROOMSHAPE_1x2 or roomShape == RoomShape.ROOMSHAPE_IIV then anim = "1x2" elseif roomShape == RoomShape.ROOMSHAPE_2x1 or roomShape == RoomShape.ROOMSHAPE_IIH then anim = "2x1" elseif roomShape == RoomShape.ROOMSHAPE_2x2 or roomShape == RoomShape.ROOMSHAPE_LBL or roomShape == RoomShape.ROOMSHAPE_LBR or roomShape == RoomShape.ROOMSHAPE_LTL or roomShape == RoomShape.ROOMSHAPE_LTR then anim = "2x2" end if anim then StageAPI.StageShadowRNG:SetSeed(room:GetDecorationSeed(), 0) local usingShadow = StageAPI.Random(1, count, StageAPI.StageShadowRNG) local sheet = prefix .. anim .. "_overlay_" .. tostring(usingShadow) .. ".png" local shadowEntity = Isaac.Spawn(StageAPI.E.StageShadow.T, StageAPI.E.StageShadow.V, 0, zeroVector, zeroVector, nil) shadowEntity:GetData().Sheet = sheet shadowEntity:GetData().Animation = anim shadowEntity.Position = StageAPI.Lerp(room:GetTopLeftPos(), room:GetBottomRightPos(), 0.5) shadowEntity:AddEntityFlags(EntityFlag.FLAG_DONT_OVERWRITE) end end local shadingDefaultOffset = Vector(-80,-80) local shadingIhOffset = Vector(-80,-160) local shadingIvOffset = Vector(-240,-80) function StageAPI.ChangeShading(name, prefix) prefix = prefix or "stageapi/shading/shading" local shading = Isaac.FindByType(StageAPI.E.Shading.T, StageAPI.E.Shading.V, -1, false, false) for _, e in ipairs(shading) do e:Remove() end local shadingEntity = Isaac.Spawn(StageAPI.E.Shading.T, StageAPI.E.Shading.V, 0, zeroVector, zeroVector, nil) local roomShape = room:GetRoomShape() local topLeft = room:GetTopLeftPos() local renderPos = topLeft + shadingDefaultOffset local sheet if roomShape == RoomShape.ROOMSHAPE_1x1 then sheet = "" elseif roomShape == RoomShape.ROOMSHAPE_1x2 then sheet = "_1x2" elseif roomShape == RoomShape.ROOMSHAPE_2x1 then sheet = "_2x1" elseif roomShape == RoomShape.ROOMSHAPE_2x2 then sheet = "_2x2" elseif roomShape == RoomShape.ROOMSHAPE_IH then sheet = "_ih" renderPos = topLeft + shadingIhOffset elseif roomShape == RoomShape.ROOMSHAPE_IIH then sheet = "_iih" renderPos = topLeft + shadingIhOffset elseif roomShape == RoomShape.ROOMSHAPE_IV then sheet = "_iv" renderPos = topLeft + shadingIvOffset elseif roomShape == RoomShape.ROOMSHAPE_IIV then sheet = "_iiv" renderPos = topLeft + shadingIvOffset elseif roomShape == RoomShape.ROOMSHAPE_LBL then sheet = "_lbl" elseif roomShape == RoomShape.ROOMSHAPE_LBR then sheet = "_lbr" elseif roomShape == RoomShape.ROOMSHAPE_LTL then sheet = "_ltl" elseif roomShape == RoomShape.ROOMSHAPE_LTR then sheet = "_ltr" end sheet = prefix .. sheet .. name .. ".png" --[[ local sprite = shadingEntity:GetSprite() sprite:Load("stageapi/Shading.anm2", false) sprite:ReplaceSpritesheet(0, sheet) sprite:LoadGraphics() sprite:Play("Default", true)]] shadingEntity:GetData().Sheet = sheet shadingEntity.Position = renderPos shadingEntity:AddEntityFlags(EntityFlag.FLAG_DONT_OVERWRITE) end local shadingSprite = Sprite() shadingSprite:Load("stageapi/Shading.anm2", false) shadingSprite:Play("Default", true) local lastUsedShadingSpritesheet mod:AddCallback(ModCallbacks.MC_POST_EFFECT_RENDER, function(_, eff) StageAPI.CallCallbacks("PRE_SHADING_RENDER", false, eff) local sheet = eff:GetData().Sheet if sheet and sheet ~= lastUsedShadingSpritesheet then shadingSprite:ReplaceSpritesheet(0, sheet) shadingSprite:LoadGraphics() lastUsedShadingSpritesheet = sheet end shadingSprite:Render(Isaac.WorldToRenderPosition(eff.Position) + room:GetRenderScrollOffset(), zeroVector, zeroVector) StageAPI.CallCallbacks("POST_SHADING_RENDER", false, eff) end, StageAPI.E.Shading.V) function StageAPI.ChangeRoomGfx(roomgfx) StageAPI.BackdropRNG:SetSeed(room:GetDecorationSeed(), 0) if roomgfx.Backdrops then if #roomgfx.Backdrops > 0 then local backdrop = StageAPI.Random(1, #roomgfx.Backdrops, StageAPI.BackdropRNG) StageAPI.ChangeBackdrop(roomgfx.Backdrops[backdrop]) else StageAPI.ChangeBackdrop(roomgfx.Backdrops) end end if roomgfx.Grids then StageAPI.ChangeGrids(roomgfx.Grids) end if roomgfx.Shading and roomgfx.Shading.Name then StageAPI.ChangeShading(roomgfx.Shading.Name, roomgfx.Shading.Prefix) end end StageAPI.RoomGfx = StageAPI.Class("RoomGfx") function StageAPI.RoomGfx:Init(backdrops, grids, shading, shadingPrefix) self.Backdrops = backdrops self.Grids = grids self.Shading = { Name = shading, Prefix = shadingPrefix } end StageAPI.AddCallback("StageAPI", "POST_STAGEAPI_NEW_ROOM", 0, function() if not game:IsGreedMode() and StageAPI.ShouldRenderStartingRoomControls() and level:GetCurrentRoomIndex() == level:GetStartingRoomIndex() then local p1 = players[1] if not p1 then return end local gfxData = StageAPI.TryGetPlayerGraphicsInfo(p1) local controls = gfxData.Controls or 'stageapi/controls.png' local controlsFrame = gfxData.ControlsFrame or 0 local controlsOffset = gfxData.ControlsOffset or StageAPI.ZeroVector local eff = StageAPI.SpawnFloorEffect(room:GetCenterPos() + controlsOffset, StageAPI.ZeroVector, nil, 'stageapi/controls.anm2', true) local sprite = eff:GetSprite() sprite:ReplaceSpritesheet(0, controls) sprite:LoadGraphics() sprite:Play("Controls") sprite:SetLayerFrame(0, controlsFrame) sprite:Stop() local color = StageAPI.GetStageFloorTextColor() if color then sprite.Color = color end end end) end Isaac.DebugString("[StageAPI] Loading CustomStage Handler") do -- Custom Stage StageAPI.CustomStages = {} StageAPI.CustomStage = StageAPI.Class("CustomStage") function StageAPI.CustomStage:Init(name, replaces, noSetReplaces) self.Name = name self.Alias = name if not noSetReplaces then self.Replaces = replaces or StageAPI.StageOverride.CatacombsOne end if name then StageAPI.CustomStages[name] = self end end function StageAPI.CustomStage:InheritInit(name, noSetAlias) if not noSetAlias then self.Alias = self.Name end self.Name = name if name then StageAPI.CustomStages[name] = self end end function StageAPI.CustomStage:SetName(name) self.Name = name or self.Name if self.Name then StageAPI.CustomStages[self.Name] = self end end function StageAPI.CustomStage:GetDisplayName() return self.DisplayName or self.Name end function StageAPI.CustomStage:SetDisplayName(name) self.DisplayName = name or self.DisplayName or self.Name end function StageAPI.CustomStage:SetReplace(replaces) self.Replaces = replaces end function StageAPI.CustomStage:SetNextStage(stage) self.NextStage = stage end function StageAPI.CustomStage:SetXLStage(stage) self.XLStage = stage end function StageAPI.CustomStage:SetStageNumber(num) self.StageNumber = num end function StageAPI.CustomStage:SetIsSecondStage(isSecondStage) self.IsSecondStage = isSecondStage end function StageAPI.CustomStage:SetRoomGfx(gfx, rtype) if not self.RoomGfx then self.RoomGfx = {} end if type(rtype) == "table" then for _, roomtype in ipairs(rtype) do self.RoomGfx[roomtype] = gfx end else self.RoomGfx[rtype] = gfx end end function StageAPI.CustomStage:SetRooms(rooms, rtype) if not self.Rooms then self.Rooms = {} end if type(rooms) == "table" and rooms.Type ~= "RoomsList" then for rtype, rooms in pairs(rooms) do self.Rooms[rtype] = rooms end else rtype = rtype or RoomType.ROOM_DEFAULT self.Rooms[rtype] = rooms end end function StageAPI.CustomStage:SetChallengeWaves(rooms, bossChallengeRooms) self.ChallengeWaves = { Normal = rooms, Boss = bossChallengeRooms } end function StageAPI.CustomStage:SetMusic(music, rtype) if not self.Music then self.Music = {} end if type(rtype) == "table" then for _, roomtype in ipairs(rtype) do self.Music[roomtype] = music end else self.Music[rtype] = music end end function StageAPI.CustomStage:SetStageMusic(music) self:SetMusic(music, {RoomType.ROOM_DEFAULT, RoomType.ROOM_TREASURE}) end function StageAPI.CustomStage:SetTransitionMusic(music) self.TransitionMusic = music StageAPI.StopOverridingMusic(music) end function StageAPI.CustomStage:SetBossMusic(music, clearedMusic, intro, outro) self.BossMusic = { Fight = music, Cleared = clearedMusic, Intro = intro, Outro = outro } end function StageAPI.CustomStage:SetRenderStartingRoomControls(doRender) self.RenderStartingRoomControls = doRender end function StageAPI.CustomStage:SetFloorTextColor(color) self.FloorTextColor = color end function StageAPI.CustomStage:SetSpots(bossSpot, playerSpot) self.BossSpot = bossSpot self.PlayerSpot = playerSpot end function StageAPI.CustomStage:SetTrueCoopSpots(twoPlayersSpot, fourPlayersSpot, threePlayersSpot) -- if a three player spot is not defined, uses four instead. self.CoopSpot2P = twoPlayersSpot self.CoopSpot3P = threePlayersSpot self.CoopSpot4P = fourPlayersSpot end function StageAPI.CustomStage:SetBosses(bosses) for _, bossID in ipairs(bosses) do local boss = StageAPI.GetBossData(bossID) if boss.Horseman then bosses.HasHorseman = true end end self.Bosses = bosses end function StageAPI.CustomStage:SetSinRooms(sins) if type(sins) == "string" then -- allows passing in a prefix to a room list name, which all sins can be grabbed from self.SinRooms = {} for _, sin in ipairs(StageAPI.SinsSplitData) do self.SinRooms[sin.ListName] = StageAPI.RoomsLists[sins .. sin.ListName] end else self.SinRooms = sins end end function StageAPI.CustomStage:GetPlayingMusic() local roomType = room:GetType() local id = StageAPI.Music:GetCurrentMusicID() if roomType == RoomType.ROOM_BOSS then if self.BossMusic then local music = self.BossMusic local musicID, queue, disregardNonOverride if (music.Outro and (id == Music.MUSIC_JINGLE_BOSS_OVER or id == Music.MUSIC_JINGLE_BOSS_OVER2 or id == music.Outro or (type(music.Outro) == "table" and StageAPI.IsIn(music.Outro, id)))) or (music.Intro and (id == Music.MUSIC_JINGLE_BOSS or id == music.Intro or (type(music.Intro) == "table" and StageAPI.IsIn(music.Intro, id)))) then if id == Music.MUSIC_JINGLE_BOSS or id == music.Intro or (type(music.Intro) == "table" and StageAPI.IsIn(music.Intro, id)) then musicID, queue = music.Intro, music.Fight else musicID, queue = music.Outro, music.Cleared end disregardNonOverride = true else local isCleared = room:GetAliveBossesCount() < 1 or room:IsClear() if isCleared then musicID = music.Cleared else musicID = music.Fight end end if type(musicID) == "table" then StageAPI.MusicRNG:SetSeed(room:GetDecorationSeed(), 0) musicID = musicID[StageAPI.Random(1, #musicID, StageAPI.MusicRNG)] end local newMusicID = StageAPI.CallCallbacks("POST_SELECT_BOSS_MUSIC", true, self, musicID, isCleared, StageAPI.MusicRNG) if newMusicID then musicID = newMusicID end if musicID then return musicID, not room:IsClear(), queue, disregardNonOverride end end else local music = self.Music if music then local musicID = music[roomType] local newMusicID = StageAPI.CallCallbacks("POST_SELECT_STAGE_MUSIC", true, self, musicID, roomType, StageAPI.MusicRNG) if newMusicID then musicID = newMusicID end if musicID then return musicID, not room:IsClear() end end end end function StageAPI.CustomStage:OverrideRockAltEffects(rooms) self.OverridingRockAltEffects = rooms or true end function StageAPI.CustomStage:OverrideTrapdoors() self.OverridingTrapdoors = true end function StageAPI.CustomStage:SetTransitionIcon(icon) self.TransitionIcon = icon end function StageAPI.IsSameStage(base, comp, noAlias) if not base then return false end return base.Name == comp.Name or (not noAlias and base.Alias == comp.Alias) end function StageAPI.CustomStage:IsStage(noAlias) return StageAPI.IsSameStage(StageAPI.CurrentStage, self, noAlias) end function StageAPI.CustomStage:IsNextStage(noAlias) return StageAPI.IsSameStage(StageAPI.NextStage, self, noAlias) end function StageAPI.CustomStage:SetRequireRoomTypeMatching() self.RequireRoomTypeMatching = true end function StageAPI.CustomStage:SetRequireRoomTypeBoss() self.RequireRoomTypeBoss = true end function StageAPI.CustomStage:SetRequireRoomTypeSin() self.RequireRoomTypeSin = true end function StageAPI.ShouldPlayStageMusic() return room:GetType() == RoomType.ROOM_DEFAULT or room:GetType() == RoomType.ROOM_TREASURE, not room:IsClear() end end Isaac.DebugString("[StageAPI] Loading Stage Override Definitions") do -- Definitions function StageAPI.BackdropHelper(backdrop, prefix, suffix) if #backdrop < 1 then backdrop = {backdrop} end for i, backdropVariant in ipairs(backdrop) do for k, backdropFiles in pairs(backdropVariant) do for i2, file in ipairs(backdropFiles) do if type(file) == "table" then for i3, file2 in ipairs(file) do backdrop[i][k][i2][i3] = prefix .. file2 .. suffix end else backdrop[i][k][i2] = prefix .. file .. suffix end end end end return backdrop end StageAPI.CatacombsGridGfx = StageAPI.GridGfx() StageAPI.CatacombsGridGfx:SetRocks("gfx/grid/rocks_catacombs.png") StageAPI.CatacombsGridGfx:SetPits("gfx/grid/grid_pit_catacombs.png", "gfx/grid/grid_pit_water_catacombs.png") StageAPI.CatacombsGridGfx:SetDecorations("gfx/grid/props_03_caves.png") StageAPI.CatacombsFloors = { {"Catacombs1_1", "Catacombs1_2"}, {"Catacombs2_1", "Catacombs2_2"}, {"CatacombsExtraFloor_1", "CatacombsExtraFloor_2"} } StageAPI.CatacombsBackdrop = { { Walls = {"Catacombs1_1", "Catacombs1_2"}, FloorVariants = StageAPI.CatacombsFloors, NFloors = {"Catacombs_nfloor"}, LFloors = {"Catacombs_lfloor"}, Corners = {"Catacombs1_corner"} }, { Walls = {"Catacombs2_1", "Catacombs2_2"}, FloorVariants = StageAPI.CatacombsFloors, NFloors = {"Catacombs_nfloor"}, LFloors = {"Catacombs_lfloor"}, Corners = {"Catacombs2_corner"} } } StageAPI.CatacombsBackdrop = StageAPI.BackdropHelper(StageAPI.CatacombsBackdrop, "stageapi/floors/catacombs/", ".png") StageAPI.CatacombsRoomGfx = StageAPI.RoomGfx(--[[StageAPI.CatacombsBackdrop]] nil, StageAPI.CatacombsGridGfx, "_default") StageAPI.Catacombs = StageAPI.CustomStage("Catacombs", nil, true) StageAPI.Catacombs:SetStageMusic(Music.MUSIC_CATACOMBS) StageAPI.Catacombs:SetBossMusic({Music.MUSIC_BOSS, Music.MUSIC_BOSS2}, Music.MUSIC_BOSS_OVER) StageAPI.Catacombs:SetRoomGfx(StageAPI.CatacombsRoomGfx, {RoomType.ROOM_DEFAULT, RoomType.ROOM_TREASURE, RoomType.ROOM_MINIBOSS, RoomType.ROOM_BOSS}) StageAPI.Catacombs.DisplayName = "Catacombs I" StageAPI.CatacombsTwo = StageAPI.Catacombs("Catacombs 2") StageAPI.CatacombsTwo.DisplayName = "Catacombs II" StageAPI.CatacombsXL = StageAPI.Catacombs("Catacombs XL") StageAPI.CatacombsXL.DisplayName = "Catacombs XL" StageAPI.Catacombs:SetXLStage(StageAPI.CatacombsXL) StageAPI.CatacombsGreed = StageAPI.Catacombs("Catacombs Greed") StageAPI.CatacombsGreed.DisplayName = "Catacombs" StageAPI.NecropolisGridGfx = StageAPI.GridGfx() StageAPI.NecropolisGridGfx:SetRocks("gfx/grid/rocks_depths.png") StageAPI.NecropolisGridGfx:SetPits("gfx/grid/grid_pit_necropolis.png") StageAPI.NecropolisGridGfx:SetDecorations("gfx/grid/props_05_depths.png", "gfx/grid/props_05_depths.anm2", 43) StageAPI.NecropolisBackdrop = { { Walls = {"necropolis1_1"}, NFloors = {"necropolis_nfloor1", "necropolis_nfloor2"}, LFloors = {"necropolis_lfloor"}, Corners = {"necropolis1_corner"} } } StageAPI.NecropolisOverlays = { StageAPI.Overlay("stageapi/floors/necropolis/overlay.anm2", Vector(0.33, -0.15), nil, nil, 0.5), StageAPI.Overlay("stageapi/floors/necropolis/overlay.anm2", Vector(-0.33, -0.15), Vector(128, 128), nil, 0.5), StageAPI.Overlay("stageapi/floors/necropolis/overlay.anm2", Vector(0.33, 0.1), nil, nil, 0.5), } StageAPI.NecropolisBackdrop = StageAPI.BackdropHelper(StageAPI.NecropolisBackdrop, "stageapi/floors/necropolis/", ".png") StageAPI.NecropolisRoomGfx = StageAPI.RoomGfx(--[[StageAPI.NecropolisBackdrop]] nil, StageAPI.NecropolisGridGfx, "_default") StageAPI.Necropolis = StageAPI.CustomStage("Necropolis", nil, true) StageAPI.Necropolis:SetStageMusic(Music.MUSIC_NECROPOLIS) StageAPI.Necropolis:SetBossMusic({Music.MUSIC_BOSS, Music.MUSIC_BOSS2}, Music.MUSIC_BOSS_OVER) StageAPI.Necropolis:SetRoomGfx(StageAPI.NecropolisRoomGfx, {RoomType.ROOM_DEFAULT, RoomType.ROOM_TREASURE, RoomType.ROOM_MINIBOSS, RoomType.ROOM_BOSS}) StageAPI.Necropolis.DisplayName = "Necropolis I" StageAPI.NecropolisTwo = StageAPI.Necropolis("Necropolis 2") StageAPI.NecropolisTwo.DisplayName = "Necropolis II" StageAPI.NecropolisXL = StageAPI.Necropolis("Necropolis XL") StageAPI.NecropolisXL.DisplayName = "Necropolis XL" StageAPI.Necropolis:SetXLStage(StageAPI.NecropolisXL) StageAPI.NecropolisGreed = StageAPI.Necropolis("Necropolis Greed") StageAPI.NecropolisGreed.DisplayName = "Necropolis" StageAPI.UteroGridGfx = StageAPI.GridGfx() StageAPI.UteroGridGfx:SetRocks("gfx/grid/rocks_utero.png") StageAPI.UteroGridGfx:SetPits("gfx/grid/grid_pit_utero.png") StageAPI.UteroGridGfx:SetDecorations("gfx/grid/props_07_utero.png", "gfx/grid/props_07_utero.anm2", 43) StageAPI.UteroBackdrop = { { Walls = {"utero1_1", "utero1_2", "utero1_3", "utero1_4"}, NFloors = {"utero_nfloor"}, LFloors = {"utero_lfloor"}, Corners = {"utero1_corner"} } } StageAPI.UteroBackdrop = StageAPI.BackdropHelper(StageAPI.UteroBackdrop, "stageapi/floors/utero/", ".png") StageAPI.UteroRoomGfx = StageAPI.RoomGfx(--[[StageAPI.UteroBackdrop]] nil, StageAPI.UteroGridGfx, "_default") StageAPI.Utero = StageAPI.CustomStage("Utero", nil, true) StageAPI.Utero:SetStageMusic(Music.MUSIC_UTERO) StageAPI.Utero:SetBossMusic({Music.MUSIC_BOSS, Music.MUSIC_BOSS2}, Music.MUSIC_BOSS_OVER) StageAPI.Utero:SetRoomGfx(StageAPI.UteroRoomGfx, {RoomType.ROOM_DEFAULT, RoomType.ROOM_TREASURE, RoomType.ROOM_MINIBOSS, RoomType.ROOM_BOSS}) StageAPI.Utero.DisplayName = "Utero I" StageAPI.UteroTwo = StageAPI.Utero("Utero 2") StageAPI.UteroTwo.DisplayName = "Utero II" StageAPI.UteroXL = StageAPI.Utero("Utero XL") StageAPI.UteroXL.DisplayName = "Utero XL" StageAPI.Utero:SetXLStage(StageAPI.UteroXL) StageAPI.UteroGreed = StageAPI.Utero("Utero Greed") StageAPI.UteroGreed.DisplayName = "Utero" StageAPI.StageOverride = { CatacombsOne = { OverrideStage = LevelStage.STAGE2_1, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.Catacombs }, CatacombsTwo = { OverrideStage = LevelStage.STAGE2_2, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.CatacombsTwo }, CatacombsGreed = { OverrideStage = LevelStage.STAGE2_GREED, OverrideStageType = StageType.STAGETYPE_WOTL, GreedMode = true, ReplaceWith = StageAPI.CatacombsGreed }, NecropolisOne = { OverrideStage = LevelStage.STAGE3_1, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.Necropolis }, NecropolisTwo = { OverrideStage = LevelStage.STAGE3_2, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.NecropolisTwo }, NecropolisGreed = { OverrideStage = LevelStage.STAGE3_GREED, OverrideStageType = StageType.STAGETYPE_WOTL, GreedMode = true, ReplaceWith = StageAPI.NecropolisGreed }, UteroOne = { OverrideStage = LevelStage.STAGE4_1, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.Utero }, UteroTwo = { OverrideStage = LevelStage.STAGE4_2, OverrideStageType = StageType.STAGETYPE_WOTL, ReplaceWith = StageAPI.UteroTwo }, UteroGreed = { OverrideStage = LevelStage.STAGE4_GREED, OverrideStageType = StageType.STAGETYPE_WOTL, GreedMode = true, ReplaceWith = StageAPI.UteroGreed } } StageAPI.Catacombs:SetReplace(StageAPI.StageOverride.CatacombsOne) StageAPI.CatacombsTwo:SetReplace(StageAPI.StageOverride.CatacombsTwo) StageAPI.CatacombsGreed:SetReplace(StageAPI.StageOverride.CatacombsGreed) StageAPI.Necropolis:SetReplace(StageAPI.StageOverride.NecropolisOne) StageAPI.NecropolisTwo:SetReplace(StageAPI.StageOverride.NecropolisTwo) StageAPI.NecropolisGreed:SetReplace(StageAPI.StageOverride.NecropolisGreed) StageAPI.Utero:SetReplace(StageAPI.StageOverride.UteroOne) StageAPI.UteroTwo:SetReplace(StageAPI.StageOverride.UteroTwo) StageAPI.UteroGreed:SetReplace(StageAPI.StageOverride.UteroGreed) function StageAPI.InOverriddenStage() for name, override in pairs(StageAPI.StageOverride) do if (not not override.GreedMode) == game:IsGreedMode() then local isStage = level:GetStage() == override.OverrideStage and level:GetStageType() == override.OverrideStageType if isStage then return true, override, name end end end end function StageAPI.InOverrideStage() for name, override in pairs(StageAPI.StageOverride) do if override.ReplaceWith:IsStage() then return true end end end StageAPI.NextStage = nil StageAPI.CurrentStage = nil function StageAPI.InNewStage() return StageAPI.CurrentStage and not StageAPI.InOverrideStage() end function StageAPI.GetCurrentStage() return StageAPI.CurrentStage end function StageAPI.GetNextStage() return StageAPI.NextStage end function StageAPI.GetCurrentStageDisplayName() if StageAPI.CurrentStage then return StageAPI.CurrentStage:GetDisplayName() end end function StageAPI.GetCurrentListIndex() return level:GetCurrentRoomDesc().SafeGridIndex end end Isaac.DebugString("[StageAPI] Loading Boss Handler") do -- Bosses StageAPI.FloorInfo = { [LevelStage.STAGE1_1] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "01_basement", }, [StageType.STAGETYPE_WOTL] = { Prefix = "02_cellar", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "13_burning_basement", FloorTextColor = Color(0.5,0.5,0.5,1,0,0,0), }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "01_basement", }, [StageType.STAGETYPE_REPENTANCE] = { Prefix = "01x_downpour", }, [StageType.STAGETYPE_REPENTANCE_B] = { Prefix = "02x_dross", }, }, [LevelStage.STAGE2_1] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "03_caves", }, [StageType.STAGETYPE_WOTL] = { Prefix = "04_catacombs", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "14_drowned_caves", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "03_caves", }, [StageType.STAGETYPE_REPENTANCE] = { Prefix = "03x_mines", }, [StageType.STAGETYPE_REPENTANCE_B] = { Prefix = "04x_ashpit", }, }, [LevelStage.STAGE3_1] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "05_depths", }, [StageType.STAGETYPE_WOTL] = { Prefix = "06_necropolis", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "15_dank_depths", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "05_depths", }, [StageType.STAGETYPE_REPENTANCE] = { Prefix = "05x_mausoleum", }, [StageType.STAGETYPE_REPENTANCE_B] = { Prefix = "06x_gehenna", }, }, [LevelStage.STAGE4_1] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "07_womb", }, [StageType.STAGETYPE_WOTL] = { Prefix = "07_womb", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "16_scarred_womb", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "07_womb", }, [StageType.STAGETYPE_REPENTANCE] = { Prefix = "07x_corpse", }, [StageType.STAGETYPE_REPENTANCE_B] = { Prefix = "07x_corpse", }, }, [LevelStage.STAGE4_3] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "17_blue_womb", }, [StageType.STAGETYPE_WOTL] = { Prefix = "17_blue_womb", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "17_blue_womb", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "17_blue_womb", }, }, [LevelStage.STAGE5] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "09_sheol", }, [StageType.STAGETYPE_WOTL] = { Prefix = "10_cathedral", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "09_sheol", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "09_sheol", }, }, [LevelStage.STAGE6] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "11_darkroom", }, [StageType.STAGETYPE_WOTL] = { Prefix = "12_chest", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "11_darkroom", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "18_shop", }, }, [LevelStage.STAGE7] = { [StageType.STAGETYPE_ORIGINAL] = { Prefix = "19_void", }, [StageType.STAGETYPE_WOTL] = { Prefix = "19_void", }, [StageType.STAGETYPE_AFTERBIRTH] = { Prefix = "19_void", }, [StageType.STAGETYPE_GREEDMODE] = { Prefix = "18_shop", }, } } StageAPI.FloorInfo[LevelStage.STAGE1_2] = StageAPI.FloorInfo[LevelStage.STAGE1_1] StageAPI.FloorInfo[LevelStage.STAGE2_2] = StageAPI.FloorInfo[LevelStage.STAGE2_1] StageAPI.FloorInfo[LevelStage.STAGE3_2] = StageAPI.FloorInfo[LevelStage.STAGE3_1] StageAPI.FloorInfo[LevelStage.STAGE4_2] = StageAPI.FloorInfo[LevelStage.STAGE4_1] StageAPI.PlayerBossInfo = { isaac = "01", magdalene = "02", cain = "03", judas = "04", eve = "05", ["???"] = "06", samson = "07", azazel = "08", eden = "09", thelost = "12", lilith = "13", keeper = "14", apollyon = "15", theforgotten = "16", thesoul = "16", bethany = "18", jacob = "19", esau = "19" } for k, v in pairs(StageAPI.PlayerBossInfo) do local use = k if k == "???" then use = "bluebaby" end if k == "thesoul" then use = "theforgotten" end local portraitbig if k == "lilith" or k == "keeper" then portraitbig = "gfx/ui/stage/playerportraitbig_" .. use .. ".png" else portraitbig = "gfx/ui/stage/playerportraitbig_" .. v .. "_" .. use .. ".png" end local name if k == "keeper" then name = "gfx/ui/boss/playername_" .. v .. "_the" .. use .. ".png" else name = "gfx/ui/boss/playername_" .. v .. "_" .. use .. ".png" end StageAPI.PlayerBossInfo[k] = { Portrait = "gfx/ui/boss/playerportrait_" .. v .. "_" .. use .. ".png", Name = name, PortraitBig = portraitbig } end StageAPI.PlayerBossInfo["???"].NoShake = true StageAPI.PlayerBossInfo.keeper.NoShake = true StageAPI.PlayerBossInfo.theforgotten.NoShake = true StageAPI.PlayerBossInfo.thesoul.NoShake = true StageAPI.PlayerBossInfo.theforgotten.ControlsFrame = 1 StageAPI.PlayerBossInfo.thesoul.ControlsFrame = 1 StageAPI.PlayerBossInfo.jacob.ControlsFrame = 2 StageAPI.PlayerBossInfo.esau.ControlsFrame = 2 StageAPI.PlayerBossInfo.thelost.NoShake = true function StageAPI.AddPlayerGraphicsInfo(name, portrait, namefile, portraitbig, noshake) local args = portrait if type(args) ~= "table" then args = { Portrait = portrait, Name = namefile, PortraitBig = portraitbig, NoShake = noshake, Controls = nil, ControlsFrame = 0, ControlsOffset = nil, } end StageAPI.PlayerBossInfo[string.gsub(string.lower(name), "%s+", "")] = args end StageAPI.AddPlayerGraphicsInfo("Black Judas", "gfx/ui/boss/playerportrait_blackjudas.png", "gfx/ui/boss/playername_04_judas.png", "gfx/ui/stage/playerportraitbig_blackjudas.png") StageAPI.AddPlayerGraphicsInfo("Lazarus", "gfx/ui/boss/playerportrait_09_lazarus.png", "gfx/ui/boss/playername_10_lazarus.png", "gfx/ui/stage/playerportraitbig_09_lazarus.png") StageAPI.AddPlayerGraphicsInfo("Lazarus II", "gfx/ui/boss/playerportrait_10_lazarus2.png", "gfx/ui/boss/playername_10_lazarus.png", "gfx/ui/stage/playerportraitbig_10_lazarus2.png") function StageAPI.GetStageSpot() if StageAPI.InNewStage() then return StageAPI.CurrentStage.BossSpot or "gfx/ui/boss/bossspot.png", StageAPI.CurrentStage.PlayerSpot or "gfx/ui/boss/playerspot.png" else local stage, stype = level:GetStage(), level:GetStageType() local spot = StageAPI.FloorInfo[stage][stype].Prefix return "gfx/ui/boss/bossspot_" .. spot .. ".png", "gfx/ui/boss/playerspot_" .. spot .. ".png" end end function StageAPI.ShouldRenderStartingRoomControls() if StageAPI.InNewStage() then return StageAPI.CurrentStage.RenderStartingRoomControls else return level:GetStage() == 1 and level:GetStageType() < StageType.STAGETYPE_REPENTANCE end end -- returns nil if no special color function StageAPI.GetStageFloorTextColor() if StageAPI.InNewStage() then return StageAPI.CurrentStage.FloorTextColor else local stage, stype = level:GetStage(), level:GetStageType() return StageAPI.FloorInfo[stage][stype].FloorTextColor end end function StageAPI.TryGetPlayerGraphicsInfo(player) local playerName if type(player) == "string" then playerName = player else playerName = player:GetName() end playerName = string.gsub(string.lower(playerName), "%s+", "") if StageAPI.PlayerBossInfo[playerName] then return StageAPI.PlayerBossInfo[playerName] else -- worth a shot, most common naming convention return { Portrait = "gfx/ui/boss/playerportrait_" .. playerName .. ".png", Name = "gfx/ui/boss/playername_" .. playerName .. ".png", PortraitBig = "gfx/ui/stage/playerportraitbig_" .. playerName .. ".png" } end end StageAPI.BossSprite = Sprite() StageAPI.BossSprite:Load("gfx/ui/boss/versusscreen.anm2", false) StageAPI.BossSprite:ReplaceSpritesheet(0, "gfx/ui/boss/bgblack.png") StageAPI.PlayingBossSprite = nil StageAPI.UnskippableBossAnim = nil StageAPI.BossOffset = nil function StageAPI.PlayBossAnimationManual(portrait, name, spot, playerPortrait, playerName, playerSpot, portraitTwo, unskippable) local paramTable = portrait if type(paramTable) ~= "table" then paramTable = { BossPortrait = portrait, BossPortraitTwo = portraitTwo, BossName = name, BossSpot = spot, PlayerPortrait = playerPortrait, PlayerName = playerName, PlayerSpot = playerSpot, Unskippable = unskippable } end if paramTable.Sprite then -- if you need to use a different sprite (ex for a special boss animation) this could help StageAPI.PlayingBossSprite = paramTable.Sprite else StageAPI.PlayingBossSprite = StageAPI.BossSprite end if not paramTable.NoLoadGraphics then StageAPI.PlayingBossSprite:ReplaceSpritesheet(2, paramTable.BossSpot or "gfx/ui/boss/bossspot.png") StageAPI.PlayingBossSprite:ReplaceSpritesheet(3, paramTable.PlayerSpot or "gfx/ui/boss/bossspot.png") StageAPI.PlayingBossSprite:ReplaceSpritesheet(4, paramTable.BossPortrait or "gfx/ui/boss/portrait_20.0_monstro.png") StageAPI.PlayingBossSprite:ReplaceSpritesheet(5, paramTable.PlayerPortrait or "gfx/ui/boss/portrait_20.0_monstro.png") StageAPI.PlayingBossSprite:ReplaceSpritesheet(6, paramTable.PlayerName or "gfx/ui/boss/bossname_20.0_monstro.png") StageAPI.PlayingBossSprite:ReplaceSpritesheet(7, paramTable.BossName or "gfx/ui/boss/bossname_20.0_monstro.png") if paramTable.BossPortraitTwo then StageAPI.PlayingBossSprite:ReplaceSpritesheet(9, paramTable.BossPortraitTwo) paramTable.Animation = paramTable.Animation or "DoubleTrouble" end StageAPI.PlayingBossSprite:Play(paramTable.Animation or "Scene", true) StageAPI.PlayingBossSprite:LoadGraphics() end if paramTable.BossOffset then StageAPI.BossOffset = paramTable.BossOffset else StageAPI.BossOffset = nil end StageAPI.UnskippableBossAnim = unskippable end StageAPI.IsOddRenderFrame = nil local menuConfirmTriggered mod:AddCallback(ModCallbacks.MC_POST_RENDER, function() StageAPI.IsOddRenderFrame = not StageAPI.IsOddRenderFrame local isPlaying = StageAPI.PlayingBossSprite if isPlaying and ((game:IsPaused() and not menuConfirmTriggered) or StageAPI.UnskippableBossAnim) then if StageAPI.IsOddRenderFrame then StageAPI.PlayingBossSprite:Update() end local centerPos = StageAPI.GetScreenCenterPosition() local layerRenderOrder = {0,1,2,3,14,9,13,4,12,6,7,8,10} for _, layer in ipairs(layerRenderOrder) do local pos = centerPos if StageAPI.BossOffset then local isDoubleTrouble = StageAPI.BossOffset.One or StageAPI.BossOffset.Two if isDoubleTrouble then -- Double trouble, table {One = Vector, Two = Vector} if layer == 4 then pos = pos + StageAPI.BossOffset.One or zeroVector elseif layer == 9 then pos = pos + StageAPI.BossOffset.Two or zeroVector end elseif layer == 4 then pos = pos + StageAPI.BossOffset end end StageAPI.PlayingBossSprite:RenderLayer(layer, pos) end elseif isPlaying then StageAPI.PlayingBossSprite:Stop() StageAPI.PlayingBossSprite = nil end if not isPlaying then StageAPI.UnskippableBossAnim = nil StageAPI.BossOffset = nil end menuConfirmTriggered = nil for _, player in ipairs(players) do if Input.IsActionTriggered(ButtonAction.ACTION_MENUCONFIRM, player.ControllerIndex) then menuConfirmTriggered = true break end end end) StageAPI.Bosses = {} function StageAPI.AddBossData(id, bossData) StageAPI.Bosses[id] = bossData if not bossData.Shapes then bossData.Shapes = {} for shape, rooms in pairs(bossData.Rooms.ByShape) do bossData.Shapes[#bossData.Shapes + 1] = shape end end if not bossData.Weight then bossData.Weight = 1 end return id end function StageAPI.GetBossData(id) return StageAPI.Bosses[id] end StageAPI.DummyBoss = {} function StageAPI.PlayBossAnimation(boss, unskippable) local bSpot, pSpot = StageAPI.GetStageSpot() local gfxData = StageAPI.TryGetPlayerGraphicsInfo(StageAPI.Players[1]) StageAPI.PlayBossAnimationManual({ BossPortrait = boss.Portrait, BossPortraitTwo = boss.PortraitTwo, BossName = boss.BossName or boss.Bossname, BossSpot = boss.Spot or bSpot, PlayerPortrait = gfxData.Portrait, PlayerName = gfxData.Name, PlayerSpot = pSpot, Unskippable = unskippable, BossOffset = boss.Offset }) end local horsemanTypes = { EntityType.ENTITY_WAR, EntityType.ENTITY_FAMINE, EntityType.ENTITY_DEATH, EntityType.ENTITY_HEADLESS_HORSEMAN, EntityType.ENTITY_PESTILENCE } StageAPI.EncounteredBosses = {} function StageAPI.SetBossEncountered(name, encountered) if encountered == nil then encountered = true end StageAPI.EncounteredBosses[name] = encountered end function StageAPI.GetBossEncountered(name) return StageAPI.EncounteredBosses[name] end mod:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, function(_, continued) if not continued then StageAPI.EncounteredBosses = {} end end) StageAPI.BossSelectRNG = RNG() function StageAPI.SelectBoss(bosses, allowHorseman, rng) local bossID = StageAPI.CallCallbacks("PRE_BOSS_SELECT", true, bosses, allowHorseman, rng) if not bossID then local forceHorseman = false if allowHorseman then for _, t in ipairs(horsemanTypes) do if #Isaac.FindByType(t, -1, -1, false, false) > 0 then forceHorseman = true end end end local totalUnencounteredWeight = 0 local totalValidWeight = 0 local unencounteredBosses = {} local validBosses = {} for _, potentialBossID in ipairs(bosses) do local potentialBoss = StageAPI.GetBossData(potentialBossID) if StageAPI.IsIn(potentialBoss.Shapes, room:GetRoomShape()) then local encountered = StageAPI.GetBossEncountered(potentialBoss.Name) if not encountered and potentialBoss.NameTwo then encountered = StageAPI.GetBossEncountered(potentialBoss.NameTwo) end local weight = potentialBoss.Weight or 1 if forceHorseman and potentialBoss.Horseman then weight = weight + 100 end if not encountered then totalUnencounteredWeight = totalUnencounteredWeight + weight unencounteredBosses[#unencounteredBosses + 1] = {potentialBossID, weight} end totalValidWeight = totalValidWeight + weight validBosses[#validBosses + 1] = {potentialBossID, weight} end end if not rng then rng = StageAPI.BossSelectRNG rng:SetSeed(room:GetSpawnSeed(), 0) end if #unencounteredBosses > 0 then bossID = StageAPI.WeightedRNG(unencounteredBosses, rng, nil, totalUnencounteredWeight) elseif #validBosses > 0 then bossID = StageAPI.WeightedRNG(validBosses, rng, nil, totalValidWeight) else Isaac.ConsoleOutput("[StageAPI] Trying to select boss, but none are valid!!\n") for _, potentialBossID in ipairs(bosses) do Isaac.ConsoleOutput(potentialBossID .. "\n") end Isaac.ConsoleOutput("Were the options\n") end end return bossID end end Isaac.DebugString("[StageAPI] Loading Transition Handler") do -- Transition StageAPI.StageTypeToString = { [StageType.STAGETYPE_ORIGINAL] = "", [StageType.STAGETYPE_WOTL] = "a", [StageType.STAGETYPE_AFTERBIRTH] = "b" } StageAPI.StageTypes = { StageType.STAGETYPE_ORIGINAL, StageType.STAGETYPE_WOTL, StageType.STAGETYPE_AFTERBIRTH } StageAPI.TransitionAnimation = Sprite() StageAPI.TransitionAnimation:Load("stageapi/transition/customnightmare.anm2", true) StageAPI.RemovedHUD = false StageAPI.TransitionIsPlaying = false StageAPI.Seeds = game:GetSeeds() mod:AddCallback(ModCallbacks.MC_POST_RENDER, function() if StageAPI.TransitionAnimation:IsPlaying("Scene") or StageAPI.TransitionAnimation:IsPlaying("SceneNoShake") then if StageAPI.IsOddRenderFrame then StageAPI.TransitionAnimation:Update() end local stop for _, player in ipairs(players) do player.ControlsCooldown = 80 if Input.IsActionTriggered(ButtonAction.ACTION_MENUCONFIRM, player.ControllerIndex) or Input.IsActionTriggered(ButtonAction.ACTION_MENUBACK, player.ControllerIndex) then stop = true end end if stop or StageAPI.TransitionAnimation:IsEventTriggered("LastFrame") then for _, player in ipairs(players) do player.Position = room:GetCenterPos() player:AnimateAppear() end StageAPI.TransitionAnimation:Stop() end StageAPI.TransitionIsPlaying = true StageAPI.RenderBlackScreen() StageAPI.TransitionAnimation:Render(StageAPI.GetScreenCenterPosition(), zeroVector, zeroVector) elseif StageAPI.TransitionIsPlaying then -- Finished transition StageAPI.TransitionIsPlaying = false if StageAPI.CurrentStage then local name = StageAPI.CurrentStage:GetDisplayName() StageAPI.PlayTextStreak(name) end end if StageAPI.IsHUDAnimationPlaying() then if not StageAPI.Seeds:HasSeedEffect(SeedEffect.SEED_NO_HUD) then StageAPI.Seeds:AddSeedEffect(SeedEffect.SEED_NO_HUD) StageAPI.RemovedHUD = true end elseif StageAPI.Seeds:HasSeedEffect(SeedEffect.SEED_NO_HUD) and StageAPI.RemovedHUD then StageAPI.Seeds:RemoveSeedEffect(SeedEffect.SEED_NO_HUD) StageAPI.RemovedHUD = false end end) function StageAPI.IsHUDAnimationPlaying(spriteOnly) return StageAPI.TransitionAnimation:IsPlaying("Scene") or StageAPI.TransitionAnimation:IsPlaying("SceneNoShake") or StageAPI.BossSprite:IsPlaying("Scene") or StageAPI.BossSprite:IsPlaying("DoubleTrouble") or (room:GetType() == RoomType.ROOM_BOSS and room:GetFrameCount() <= 0 and game:IsPaused() and not spriteOnly) end mod:AddCallback(ModCallbacks.MC_PRE_USE_ITEM, function() if StageAPI.IsHUDAnimationPlaying() then return true end end) mod:AddCallback(ModCallbacks.MC_ENTITY_TAKE_DMG, function(_, e) if StageAPI.IsHUDAnimationPlaying() then return false end end, EntityType.ENTITY_PLAYER) mod:AddCallback(ModCallbacks.MC_POST_EFFECT_INIT, function(_, eff) if StageAPI.IsHUDAnimationPlaying() then eff:Remove() end end, EffectVariant.MOM_FOOT_STOMP) function StageAPI.GetLevelTransitionIcon(stage, stype) local base = StageAPI.FloorInfo[stage][stype].Prefix if base == "07_womb" and stype == StageType.STAGETYPE_WOTL then base = "utero" end return "stageapi/transition/levelicons/" .. base .. ".png" end function StageAPI.PlayTransitionAnimationManual(portraitbig, icon, transitionmusic, queue, noshake) portraitbig = portraitbig or "gfx/ui/stage/playerportraitbig_01_isaac.png" icon = icon or "stageapi/transition/levelicons/unknown.png" transitionmusic = transitionmusic or Music.MUSIC_JINGLE_NIGHTMARE if queue ~= false then queue = queue or StageAPI.Music:GetCurrentMusicID() end StageAPI.TransitionAnimation:ReplaceSpritesheet(1, portraitbig) StageAPI.TransitionAnimation:ReplaceSpritesheet(2, icon) StageAPI.TransitionAnimation:LoadGraphics() if noshake then StageAPI.TransitionAnimation:Play("SceneNoShake", true) else StageAPI.TransitionAnimation:Play("Scene", true) end StageAPI.Music:Play(transitionmusic, 0) StageAPI.Music:UpdateVolume() if queue ~= false then StageAPI.Music:Queue(queue) end end function StageAPI.PlayTransitionAnimation(stage) local gfxData = StageAPI.TryGetPlayerGraphicsInfo(players[1]) StageAPI.PlayTransitionAnimationManual(gfxData.PortraitBig, stage.TransitionIcon, stage.TransitionMusic, stage.Music[RoomType.ROOM_DEFAULT], gfxData.NoShake) end StageAPI.StageRNG = RNG() function StageAPI.GotoCustomStage(stage, playTransition, noForgetSeed) if not noForgetSeed then local realstage if stage.NormalStage then realstage = stage.Stage else realstage = stage.Replaces.OverrideStage end StageAPI.Seeds:ForgetStageSeed(realstage) end if stage.NormalStage then StageAPI.PreReseed = true local stageType = stage.StageType if not stageType then StageAPI.StageRNG:SetSeed(StageAPI.Seeds:GetStageSeed(stage.Stage), 0) stageType = StageAPI.StageTypes[StageAPI.Random(1, #StageAPI.StageTypes, StageAPI.StageRNG)] end if playTransition then local gfxData = StageAPI.TryGetPlayerGraphicsInfo(players[1]) StageAPI.PlayTransitionAnimationManual(gfxData.PortraitBig, StageAPI.GetLevelTransitionIcon(stage.Stage, stageType), nil, nil, gfxData.NoShake) end Isaac.ExecuteCommand("stage " .. tostring(stage.Stage) .. StageAPI.StageTypeToString[stageType]) else local replace = stage.Replaces local absolute = replace.OverrideStage StageAPI.NextStage = stage if playTransition then StageAPI.PlayTransitionAnimation(stage) end Isaac.ExecuteCommand("stage " .. tostring(absolute) .. StageAPI.StageTypeToString[replace.OverrideStageType]) end end function StageAPI.SpawnCustomTrapdoor(position, goesTo, anm2, size, alreadyEntering) anm2 = anm2 or "gfx/grid/door_11_trapdoor.anm2" size = size or 24 local trapdoor = Isaac.Spawn(StageAPI.E.FloorEffectCreep.T, StageAPI.E.FloorEffectCreep.V, StageAPI.E.FloorEffectCreep.S, position, zeroVector, nil) trapdoor.Variant = StageAPI.E.Trapdoor.V trapdoor.SubType = StageAPI.E.Trapdoor.S trapdoor.Size = size local sprite, data = trapdoor:GetSprite(), trapdoor:GetData() sprite:Load(anm2, true) if alreadyEntering then sprite:Play("Opened", true) data.BeingEntered = true for _, player in ipairs(players) do player:AnimateTrapdoor() end else sprite:Play("Closed", true) end data.GoesTo = goesTo return trapdoor end mod:AddCallback(ModCallbacks.MC_POST_EFFECT_UPDATE, function(_, eff) local sprite, data = eff:GetSprite(), eff:GetData() if sprite:IsFinished("Open Animation") then sprite:Play("Opened", true) elseif (sprite:IsPlaying("Closed") or sprite:IsFinished("Closed")) and room:IsClear() then local playerTooClose for _, player in ipairs(players) do local size = (eff.Size + player.Size) if player.Position:DistanceSquared(eff.Position) < size * size then playerTooClose = true end end if not playerTooClose then sprite:Play("Open Animation", true) end elseif sprite:IsPlaying("Opened") or sprite:IsFinished("Opened") then if not data.BeingEntered then local touchingTrapdoor for _, player in ipairs(players) do local size = (eff.Size + player.Size) if player.Position:DistanceSquared(eff.Position) < size * size then touchingTrapdoor = true end end if touchingTrapdoor then data.BeingEntered = true for _, player in ipairs(players) do player:AnimateTrapdoor() end end else local animationOver for _, player in ipairs(players) do player.ControlsCooldown = 5 player.Velocity = (StageAPI.Lerp(player.Position, eff.Position, 0.5) - player.Position) / 2 if player:IsExtraAnimationFinished() then animationOver = true end end if animationOver then StageAPI.GotoCustomStage(data.GoesTo, true) end end end end, StageAPI.E.Trapdoor.V) end Isaac.DebugString("[StageAPI] Loading Rock Alt Breaking Override") do -- Rock Alt Override StageAPI.SpawnOverriddenGrids = {} StageAPI.JustBrokenGridSpawns = {} StageAPI.RecentFarts = {} StageAPI.LastRockAltCheckedRoom = nil mod:AddCallback(ModCallbacks.MC_PRE_ENTITY_SPAWN, function(_, id, variant, subtype, position, velocity, spawner, seed) if StageAPI.LastRockAltCheckedRoom ~= level:GetCurrentRoomIndex() then StageAPI.LastRockAltCheckedRoom = level:GetCurrentRoomIndex() StageAPI.SpawnOverriddenGrids = {} end local lindex = StageAPI.GetCurrentRoomID() local grindex = room:GetGridIndex(position) if StageAPI.SpawnOverriddenGrids[grindex] then local grid = room:GetGridEntity(grindex) local stateCheck if type(StageAPI.SpawnOverriddenGrids[grindex]) == "number" then stateCheck = StageAPI.SpawnOverriddenGrids[grindex] elseif grid then stateCheck = StageAPI.DefaultBrokenGridStateByType[grid.Type] or 2 end if not grid or grid.State == stateCheck then if (id == EntityType.ENTITY_PICKUP and (variant == PickupVariant.PICKUP_COLLECTIBLE or variant == PickupVariant.PICKUP_TAROTCARD or variant == PickupVariant.PICKUP_HEART or variant == PickupVariant.PICKUP_COIN or variant == PickupVariant.PICKUP_TRINKET or variant == PickupVariant.PICKUP_PILL)) or id == EntityType.ENTITY_SPIDER or (id == EntityType.ENTITY_EFFECT and (variant == EffectVariant.FART or variant == EffectVariant.POOF01 or variant == EffectVariant.CREEP_RED)) or id == EntityType.ENTITY_PROJECTILE or id == EntityType.ENTITY_HOST or id == EntityType.ENTITY_MUSHROOM then if id == EntityType.ENTITY_EFFECT and variant == EffectVariant.FART then StageAPI.RecentFarts[grindex] = 2 sfx:Stop(SoundEffect.SOUND_FART) end if not StageAPI.JustBrokenGridSpawns[grindex] then StageAPI.JustBrokenGridSpawns[grindex] = {} end StageAPI.JustBrokenGridSpawns[grindex][#StageAPI.JustBrokenGridSpawns[grindex] + 1] = { Type = id, Variant = variant, SubType = subtype, Position = position, Velocity = velocity, Spawner = spawner, Seed = seed } if id == EntityType.ENTITY_EFFECT then return { StageAPI.E.DeleteMeEffect.T, StageAPI.E.DeleteMeEffect.V, 0, seed } elseif id == EntityType.ENTITY_PICKUP then return { StageAPI.E.DeleteMePickup.T, StageAPI.E.DeleteMePickup.V, 0, seed } elseif id == EntityType.ENTITY_PROJECTILE then return { StageAPI.E.DeleteMeProjectile.T, StageAPI.E.DeleteMeProjectile.V, 0, seed } else return { StageAPI.E.DeleteMeNPC.T, StageAPI.E.DeleteMeNPC.V, 0, seed } end end end end end) mod:AddCallback(ModCallbacks.MC_ENTITY_TAKE_DMG, function(_, e, amount, flag, source) if flag == 0 and source and source.Type == 0 and not e:GetData().TrueFart then local hasFarts = next(StageAPI.RecentFarts) ~= nil if hasFarts then e:GetData().Farted = {amount, source} return false end end end) mod:AddCallback(ModCallbacks.MC_POST_PLAYER_RENDER, function(_, npc) local data = npc:GetData() if data.Farted then local stoppedFart for fart, timer in pairs(StageAPI.RecentFarts) do if room:GetGridPosition(fart):Distance(npc.Position) < 150 + npc.Size then stoppedFart = true break end end if not stoppedFart then data.TrueFart = true npc:TakeDamage(data.Farted[1], 0, EntityRef(npc), 0) data.TrueFart = nil end data.Farted = nil end end) mod:AddCallback(ModCallbacks.MC_POST_NPC_RENDER, function(_, npc) local data = npc:GetData() if data.Farted then local stoppedFart for fart, timer in pairs(StageAPI.RecentFarts) do if room:GetGridPosition(fart):Distance(npc.Position) < 150 + npc.Size then stoppedFart = true break end end if not stoppedFart then data.TrueFart = true npc:TakeDamage(data.Farted[1], 0, EntityRef(npc), 0) data.TrueFart = nil end data.Farted = nil end for fart, timer in pairs(StageAPI.RecentFarts) do if npc:HasEntityFlags(EntityFlag.FLAG_POISON) and room:GetGridPosition(fart):Distance(npc.Position) < 150 + npc.Size then npc:RemoveStatusEffects() break end end end) function StageAPI.DeleteEntity(entA, entB) local ent if entA.Remove then ent = entA else ent = entB end ent:ClearEntityFlags(EntityFlag.FLAG_APPEAR) ent:Remove() end mod:AddCallback(ModCallbacks.MC_POST_NPC_INIT, function(_, npc) if npc.Variant == StageAPI.E.DeleteMeNPC.V then StageAPI.DeleteEntity(npc) end end, StageAPI.E.DeleteMeNPC.T) mod:AddCallback(ModCallbacks.MC_POST_EFFECT_INIT, StageAPI.DeleteEntity, StageAPI.E.DeleteMeEffect.V) mod:AddCallback(ModCallbacks.MC_POST_PROJECTILE_INIT, StageAPI.DeleteEntity, StageAPI.E.DeleteMeProjectile.V) mod:AddCallback(ModCallbacks.MC_POST_PICKUP_INIT, StageAPI.DeleteEntity, StageAPI.E.DeleteMePickup.V) StageAPI.PickupChooseRNG = RNG() mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.PickupChooseRNG:SetSeed(room:GetSpawnSeed(), 0) end) mod:AddCallback(ModCallbacks.MC_POST_PICKUP_UPDATE, function(_, pickup) if not pickup:Exists() then return end local card = game:GetItemPool():GetCard(StageAPI.PickupChooseRNG:Next(), false, true, true) local spawned = Isaac.Spawn(EntityType.ENTITY_PICKUP, PickupVariant.PICKUP_TAROTCARD, card, pickup.Position, zeroVector, nil) spawned:Update() -- get the spawned pickup up to speed with the original StageAPI.DeleteEntity(pickup) end, StageAPI.E.RandomRune.V) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() for fart, timer in pairs(StageAPI.RecentFarts) do StageAPI.RecentFarts[fart] = timer - 1 if timer <= 1 then StageAPI.RecentFarts[fart] = nil end end for grindex, exists in pairs(StageAPI.SpawnOverriddenGrids) do local grid = room:GetGridEntity(grindex) local stateCheck = 2 if type(exists) == "number" then stateCheck = exists end if not grid or grid.State == stateCheck then StageAPI.SpawnOverriddenGrids[grindex] = nil StageAPI.CallCallbacks("POST_OVERRIDDEN_GRID_BREAK", true, grindex, grid, StageAPI.JustBrokenGridSpawns[grindex]) end end StageAPI.JustBrokenGridSpawns = {} end) function StageAPI.AreRockAltEffectsOverridden() if (StageAPI.CurrentStage and StageAPI.CurrentStage.OverridingRockAltEffects) or StageAPI.TemporaryOverrideRockAltEffects then local isOverridden = true if not StageAPI.TemporaryOverrideRockAltEffects then if type(StageAPI.CurrentStage.OverridingRockAltEffects) == "table" then isOverridden = StageAPI.IsIn(StageAPI.CurrentStage.OverridingRockAltEffects, StageAPI.GetCurrentRoomType()) end end return isOverridden end end function StageAPI.TemporarilyOverrideRockAltEffects() StageAPI.TemporaryOverrideRockAltEffects = true end mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.TemporaryOverrideRockAltEffects = nil StageAPI.RecentFarts = {} StageAPI.SpawnOverriddenGrids = {} StageAPI.JustBrokenGridSpawns = {} end) StageAPI.AddCallback("StageAPI", "POST_GRID_UPDATE", 0, function() if StageAPI.AreRockAltEffectsOverridden() then for i = room:GetGridWidth(), room:GetGridSize() do local grid = room:GetGridEntity(i) if not StageAPI.SpawnOverriddenGrids[i] and grid and (grid.Desc.Type == GridEntityType.GRID_ROCK_ALT and grid.State ~= 2) then StageAPI.SpawnOverriddenGrids[i] = true end end end end) end Isaac.DebugString("[StageAPI] Loading Core Callbacks") do -- Callbacks StageAPI.NonOverrideMusic = { {Music.MUSIC_GAME_OVER, false, true}, Music.MUSIC_JINGLE_GAME_OVER, Music.MUSIC_JINGLE_SECRETROOM_FIND, {Music.MUSIC_JINGLE_NIGHTMARE, true}, Music.MUSIC_JINGLE_GAME_START, Music.MUSIC_JINGLE_BOSS, Music.MUSIC_JINGLE_BOSS_OVER, Music.MUSIC_JINGLE_BOSS_OVER2, Music.MUSIC_JINGLE_DEVILROOM_FIND, Music.MUSIC_JINGLE_HOLYROOM_FIND, Music.MUSIC_JINGLE_TREASUREROOM_ENTRY_0, Music.MUSIC_JINGLE_TREASUREROOM_ENTRY_1, Music.MUSIC_JINGLE_TREASUREROOM_ENTRY_2, Music.MUSIC_JINGLE_TREASUREROOM_ENTRY_3, -- Rep Music.MUSIC_JINGLE_BOSS_RUSH_OUTRO, Music.MUSIC_JINGLE_BOSS_OVER3, Music.MUSIC_JINGLE_MOTHER_OVER, Music.MUSIC_JINGLE_DOGMA_OVER, Music.MUSIC_JINGLE_BEAST_OVER, Music.MUSIC_JINGLE_CHALLENGE_ENTRY, Music.MUSIC_JINGLE_CHALLENGE_OUTRO } function StageAPI.StopOverridingMusic(music, allowOverrideQueue, neverOverrideQueue) if allowOverrideQueue ~= nil or neverOverrideQueue ~= nil then StageAPI.NonOverrideMusic[#StageAPI.NonOverrideMusic + 1] = {music, allowOverrideQueue, neverOverrideQueue} else StageAPI.NonOverrideMusic[#StageAPI.NonOverrideMusic + 1] = music end end function StageAPI.CanOverrideMusic(music) for _, id in ipairs(StageAPI.NonOverrideMusic) do if type(id) == "number" then if music == id then return false end else if music == id[1] then return false, id[2], id[3] end end end return true end mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() local currentRoom = StageAPI.GetCurrentRoom() if currentRoom then local isClear = currentRoom.IsClear currentRoom.IsClear = room:IsClear() currentRoom.JustCleared = nil if not isClear and currentRoom.IsClear then StageAPI.CallCallbacks("POST_ROOM_CLEAR", false) currentRoom.JustCleared = true end end end) StageAPI.RoomGrids = {} function StageAPI.PreventRoomGridRegrowth() StageAPI.RoomGrids[StageAPI.GetCurrentRoomID()] = {} end function StageAPI.StoreRoomGrids() local roomIndex = StageAPI.GetCurrentRoomID() local grids = {} for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid and grid.Desc.Type ~= GridEntityType.GRID_WALL and grid.Desc.Type ~= GridEntityType.GRID_DOOR then grids[i] = true end end StageAPI.RoomGrids[roomIndex] = grids end function StageAPI.RemoveExtraGrids(grids) for i = 0, room:GetGridSize() do if not grids[i] then local grid = room:GetGridEntity(i) if grid and grid.Desc.Type ~= GridEntityType.GRID_WALL and grid.Desc.Type ~= GridEntityType.GRID_DOOR then room:RemoveGridEntity(i, 0, false) end end end StageAPI.CalledRoomUpdate = true room:Update() StageAPI.CalledRoomUpdate = false end mod:AddCallback(ModCallbacks.MC_PRE_USE_ITEM, function() if StageAPI.CalledRoomUpdate then return true end end) mod:AddCallback(ModCallbacks.MC_POST_NEW_LEVEL, function() StageAPI.RoomGrids = {} end) StageAPI.RoomNamesEnabled = false StageAPI.PreviousGridCount = nil function StageAPI.ReprocessRoomGrids() StageAPI.PreviousGridCount = nil end mod:AddCallback(ModCallbacks.MC_PRE_USE_ITEM, StageAPI.ReprocessRoomGrids, CollectibleType.COLLECTIBLE_D12) function StageAPI.UseD7() local currentRoom = StageAPI.GetCurrentRoom() if currentRoom then if room:GetType() == RoomType.ROOM_BOSS then game:MoveToRandomRoom(false, room:GetSpawnSeed()) else StageAPI.JustUsedD7 = true end for _, player in ipairs(players) do if player:HasCollectible(CollectibleType.COLLECTIBLE_D7) and Input.IsActionTriggered(ButtonAction.ACTION_ITEM, player.ControllerIndex) then player:AnimateCollectible(CollectibleType.COLLECTIBLE_D7, "UseItem", "PlayerPickup") end end return true end end mod:AddCallback(ModCallbacks.MC_PRE_USE_ITEM, StageAPI.UseD7, CollectibleType.COLLECTIBLE_D7) mod:AddCallback(ModCallbacks.MC_PRE_USE_ITEM, function() if StageAPI.InNewStage() then for _, player in ipairs(players) do if player:HasCollectible(CollectibleType.COLLECTIBLE_FORGET_ME_NOW) and Input.IsActionTriggered(ButtonAction.ACTION_ITEM, player.ControllerIndex) then player:RemoveCollectible(CollectibleType.COLLECTIBLE_FORGET_ME_NOW) end end StageAPI.GotoCustomStage(StageAPI.CurrentStage, true) return true end end, CollectibleType.COLLECTIBLE_FORGET_ME_NOW) mod:AddCallback(ModCallbacks.MC_POST_EFFECT_INIT, function(_, eff) if StageAPI.InNewStage() and not eff:GetData().StageAPIDoNotDelete then eff:Remove() end end, EffectVariant.WATER_DROPLET) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() if StageAPI.JustUsedD7 then StageAPI.JustUsedD7 = nil local currentRoom = StageAPI.GetCurrentRoom() if currentRoom then currentRoom.IsClear = currentRoom.WasClearAtStart currentRoom:Load() end end end) function StageAPI.ShouldOverrideRoom(inStartingRoom, currentRoom) if inStartingRoom == nil then inStartingRoom = level:GetCurrentRoomIndex() == level:GetStartingRoomIndex() end if currentRoom == nil then currentRoom = StageAPI.GetCurrentRoom() end if currentRoom or StageAPI.InExtraRoom or (not inStartingRoom and StageAPI.InNewStage() and ((StageAPI.CurrentStage.Rooms and StageAPI.CurrentStage.Rooms[room:GetType()]) or (StageAPI.CurrentStage.Bosses and room:GetType() == RoomType.ROOM_BOSS))) then return true end end StageAPI.AddCallback("StageAPI", "POST_SELECT_BOSS_MUSIC", 0, function(stage, usingMusic, isCleared) if not isCleared then if stage.Name == "Necropolis" or stage.Alias == "Necropolis" then if room:IsCurrentRoomLastBoss() and (level:GetCurses() & LevelCurse.CURSE_OF_LABYRINTH ~= 0 or level:GetStage() == LevelStage.STAGE3_2) then return Music.MUSIC_MOM_BOSS end elseif stage.Name == "Utero" or stage.Alias == "Utero" then if room:IsCurrentRoomLastBoss() and (level:GetCurses() & LevelCurse.CURSE_OF_LABYRINTH ~= 0 or level:GetStage() == LevelStage.STAGE4_2) then return Music.MUSIC_MOMS_HEART_BOSS end end end end) StageAPI.NonOverrideTrapdoors = { ["gfx/grid/trapdoor_downpour.anm2"] = true, ["gfx/grid/trapdoor_mines.anm2"] = true, ["gfx/grid/trapdoor_mausoleum.anm2"] = true, } function StageAPI.CheckStageTrapdoor(grid, index) if not (grid.Desc.Type == GridEntityType.GRID_TRAPDOOR and grid.State == 1) or StageAPI.NonOverrideTrapdoors[grid:GetSprite():GetFilename()] then return end local entering = false for _, player in ipairs(players) do local dist = player.Position:DistanceSquared(grid.Position) local size = player.Size + 32 if dist < size * size then entering = true break end end if not entering then return end local currStage = StageAPI.CurrentStage or {} local nextStage = StageAPI.CallCallbacks("PRE_SELECT_NEXT_STAGE", true, StageAPI.CurrentStage) or currStage.NextStage if nextStage and not currStage.OverridingTrapdoors then StageAPI.SpawnCustomTrapdoor(room:GetGridPosition(index), nextStage, grid:GetSprite():GetFilename(), 32, true) room:RemoveGridEntity(index, 0, false) end end StageAPI.Music = MusicManager() StageAPI.MusicRNG = RNG() mod:AddCallback(ModCallbacks.MC_POST_RENDER, function() if game:GetFrameCount() <= 0 then return end local currentListIndex = StageAPI.GetCurrentRoomID() local stage = level:GetStage() local stype = level:GetStageType() local updatedGrids local gridCount = 0 local pits = {} for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid then if grid.Desc.Type == GridEntityType.GRID_PIT then pits[#pits + 1] = {grid, i} end StageAPI.CheckStageTrapdoor(grid, i) gridCount = gridCount + 1 end end if gridCount ~= StageAPI.PreviousGridCount then local gridCallbacks = StageAPI.CallCallbacks("POST_GRID_UPDATE") updatedGrids = true if StageAPI.RoomGrids[currentListIndex] then StageAPI.StoreRoomGrids() end StageAPI.PreviousGridCount = gridCount end if sfx:IsPlaying(SoundEffect.SOUND_CASTLEPORTCULLIS) and not (StageAPI.CurrentStage and StageAPI.CurrentStage.BossMusic and StageAPI.CurrentStage.BossMusic.Intro) then sfx:Stop(SoundEffect.SOUND_CASTLEPORTCULLIS) sfx:Play(StageAPI.S.BossIntro, 1, 0, false, 1) end if StageAPI.InOverriddenStage() and StageAPI.CurrentStage then local roomType = room:GetType() local rtype = StageAPI.GetCurrentRoomType() local grids local gridsOverride = StageAPI.CallCallbacks("PRE_UPDATE_GRID_GFX", false) local currentRoom = StageAPI.GetCurrentRoom() if gridsOverride then grids = gridsOverride elseif currentRoom and currentRoom.Data.RoomGfx then grids = currentRoom.Data.RoomGfx.Grids elseif StageAPI.CurrentStage.RoomGfx and StageAPI.CurrentStage.RoomGfx[rtype] and StageAPI.CurrentStage.RoomGfx[rtype].Grids then grids = StageAPI.CurrentStage.RoomGfx[rtype].Grids end if grids then if grids.Bridges then for _, grid in ipairs(pits) do StageAPI.CheckBridge(grid[1], grid[2], grids.Bridges) end end if not StageAPI.RoomRendered and updatedGrids then StageAPI.ChangeGrids(grids) end end local id = StageAPI.Music:GetCurrentMusicID() local musicID, shouldLayer, shouldQueue, disregardNonOverride = StageAPI.CurrentStage:GetPlayingMusic() if musicID then if not shouldQueue then shouldQueue = musicID end local queuedID = StageAPI.Music:GetQueuedMusicID() local canOverride, canOverrideQueue, neverOverrideQueue = StageAPI.CanOverrideMusic(queuedID) local shouldOverrideQueue = shouldQueue and (canOverride or canOverrideQueue or disregardNonOverride) if not neverOverrideQueue and shouldQueue then shouldOverrideQueue = shouldOverrideQueue or (id == queuedID) end if queuedID ~= shouldQueue and shouldOverrideQueue then StageAPI.Music:Queue(shouldQueue) end local canOverride = StageAPI.CanOverrideMusic(id) if id ~= musicID and (canOverride or disregardNonOverride) then StageAPI.Music:Play(musicID, 0) end StageAPI.Music:UpdateVolume() if shouldLayer and not StageAPI.Music:IsLayerEnabled() then StageAPI.Music:EnableLayer() elseif not shouldLayer and StageAPI.Music:IsLayerEnabled() then StageAPI.Music:DisableLayer() end end StageAPI.RoomRendered = true end if StageAPI.RoomNamesEnabled then local currentRoom = StageAPI.LevelRooms[currentListIndex] local roomDescriptorData = level:GetCurrentRoomDesc().Data local scale = 0.5 local base, custom if StageAPI.RoomNamesEnabled == 2 then base = tostring(roomDescriptorData.StageID) .. "." .. tostring(roomDescriptorData.Variant) .. "." .. tostring(roomDescriptorData.Subtype) .. " " .. roomDescriptorData.Name else base = "Base Room Stage ID: " .. tostring(roomDescriptorData.StageID) .. ", Name: " .. roomDescriptorData.Name .. ", ID: " .. tostring(roomDescriptorData.Variant) .. ", Difficulty: " .. tostring(roomDescriptorData.Difficulty) .. ", Subtype: " .. tostring(roomDescriptorData.Subtype) end if currentRoom and currentRoom.Layout.RoomFilename and currentRoom.Layout.Name and currentRoom.Layout.Variant then if StageAPI.RoomNamesEnabled == 2 then custom = "Room File: " .. currentRoom.Layout.RoomFilename .. ", Name: " .. currentRoom.Layout.Name .. ", ID: " .. tostring(currentRoom.Layout.Variant) else custom = "Room File: " .. currentRoom.Layout.RoomFilename .. ", Name: " .. currentRoom.Layout.Name .. ", ID: " .. tostring(currentRoom.Layout.Variant) .. ", Difficulty: " .. tostring(currentRoom.Layout.Difficulty) .. ", Subtype: " .. tostring(currentRoom.Layout.SubType) end else custom = "Room names enabled, custom room N/A" end Isaac.RenderScaledText(custom, 60, 35, scale, scale, 255, 255, 255, 0.75) Isaac.RenderScaledText(base, 60, 45, scale, scale, 255, 255, 255, 0.75) end end) function StageAPI.SetCurrentBossRoomInPlace(bossID, room) local boss = StageAPI.GetBossData(bossID) if not boss then StageAPI.Log("Trying to set boss with invalid ID: " .. tostring(bossID)) return end room.PersistentData.BossID = bossID StageAPI.CallCallbacks("POST_BOSS_ROOM_INIT", false, room, boss, bossID) end function StageAPI.GenerateBossRoom(bossID, checkEncountered, bosses, hasHorseman, requireRoomTypeBoss, noPlayBossAnim, unskippableBossAnim, isExtraRoom, shape, ignoreDoors) if not bossID then bossID = StageAPI.SelectBoss(bosses, hasHorseman) elseif checkEncountered then if StageAPI.GetBossEncountered(bossID) then StageAPI.Log("Trying to generate boss room for encountered boss: " .. tostring(bossID)) return end end local boss = StageAPI.GetBossData(bossID) if not boss then StageAPI.Log("Trying to set boss with invalid ID: " .. tostring(bossID)) return end StageAPI.SetBossEncountered(boss.Name) if boss.NameTwo then StageAPI.SetBossEncountered(boss.NameTwo) end local levelIndex = StageAPI.GetCurrentRoomID() local newRoom = StageAPI.LevelRoom(nil, boss.Rooms, nil, shape, nil, isExtraRoom, nil, requireRoomTypeBoss, ignoreDoors, nil, levelIndex) newRoom.PersistentData.BossID = bossID StageAPI.CallCallbacks("POST_BOSS_ROOM_INIT", false, newRoom, boss, bossID) if noPlayBossAnim == nil then noPlayBossAnim = boss.IsMiniboss end if not noPlayBossAnim then StageAPI.PlayBossAnimation(boss, unskippableBossAnim) elseif noPlayBossAnim ~= 2 then StageAPI.PlayTextStreak(players[1]:GetName() .. " VS " .. boss.Name) end return newRoom, boss end function StageAPI.SetCurrentBossRoom(bossID, checkEncountered, bosses, hasHorseman, requireRoomTypeBoss, noPlayBossAnim) local newRoom, boss = StageAPI.GenerateBossRoom(bossID, checkEncountered, bosses, hasHorseman, requireRoomTypeBoss, noPlayBossAnim) if not newRoom then StageAPI.Log('Could not generate room for boss: ID: ' .. bossID .. ' List Length: ' .. tostring(bosses and #bosses or 0)) return nil, nil end StageAPI.SetCurrentRoom(newRoom) newRoom:Load() return newRoom, boss end mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() StageAPI.CallCallbacks("PRE_STAGEAPI_NEW_ROOM", false) local isNewStage, override = StageAPI.InOverriddenStage() local inStartingRoom = level:GetCurrentRoomIndex() == level:GetStartingRoomIndex() StageAPI.CustomGridIndices = {} if inStartingRoom and room:IsFirstVisit() then StageAPI.CustomGrids = {} StageAPI.LevelRooms = {} StageAPI.CurrentStage = nil if isNewStage then if not StageAPI.NextStage then StageAPI.CurrentStage = override.ReplaceWith else StageAPI.CurrentStage = StageAPI.NextStage end if level:GetCurses() & LevelCurse.CURSE_OF_LABYRINTH ~= 0 and StageAPI.CurrentStage.XLStage then StageAPI.CurrentStage = StageAPI.CurrentStage.XLStage end end StageAPI.NextStage = nil if StageAPI.CurrentStage and StageAPI.CurrentStage.GetPlayingMusic then local musicID = StageAPI.CurrentStage:GetPlayingMusic() if musicID then StageAPI.Music:Queue(musicID) end end end local enteringExtraRoomFromOffGridRoom if StageAPI.PreviousExtraRoom and level:GetCurrentRoomIndex() == -3 then StageAPI.CurrentExtraRoom = StageAPI.PreviousExtraRoom StageAPI.CurrentExtraRoomName = StageAPI.PreviousExtraRoomName StageAPI.InExtraRoom = true StageAPI.TransitionExitSlot = level.LeaveDoor StageAPI.PreviousExtraRoom = nil StageAPI.PreviousExtraRoomName = nil enteringExtraRoomFromOffGridRoom = true end if not StageAPI.TransitioningToExtraRoom() and not enteringExtraRoomFromOffGridRoom and not StageAPI.LoadingExtraRoomFromSave then if StageAPI.InExtraRoom and level:GetCurrentRoomIndex() < 0 then StageAPI.PreviousExtraRoom = StageAPI.CurrentExtraRoom StageAPI.PreviousExtraRoomName = StageAPI.CurrentExtraRoomName else StageAPI.PreviousExtraRoom = nil StageAPI.PreviousExtraRoomName = nil end StageAPI.CurrentExtraRoom = nil StageAPI.CurrentExtraRoomName = nil StageAPI.InExtraRoom = false StageAPI.LoadedExtraRoom = false end StageAPI.LoadingExtraRoomFromSave = nil if StageAPI.TransitionExitSlot then local pos = room:GetDoorSlotPosition(StageAPI.TransitionExitSlot) + (StageAPI.DoorOffsetsByDirection[StageAPI.DoorToDirection[StageAPI.TransitionExitSlot]] * 3) for _, player in ipairs(players) do player.Position = pos end StageAPI.TransitionExitSlot = nil end if StageAPI.CurrentExtraRoom then for i = 0, 7 do if room:GetDoor(i) then room:RemoveDoor(i) end end StageAPI.CurrentExtraRoom:Load(true) StageAPI.LoadedExtraRoom = true StageAPI.PreviousExtraRoom = nil StageAPI.PreviousExtraRoomName = nil justGenerated = true else StageAPI.LoadedExtraRoom = false end local currentListIndex = StageAPI.GetCurrentRoomID() local currentRoom, justGenerated, boss = StageAPI.GetCurrentRoom(), nil, nil local retCurrentRoom, retJustGenerated, retBoss = StageAPI.CallCallbacks("PRE_STAGEAPI_NEW_ROOM_GENERATION", true, currentRoom, justGenerated, currentListIndex) local prevRoom = currentRoom currentRoom, justGenerated, boss = retCurrentRoom or currentRoom, retJustGenerated or justGenerated, retBoss or boss if prevRoom ~= currentRoom then StageAPI.SetCurrentRoom(currentRoom) end if not StageAPI.InExtraRoom and StageAPI.InNewStage() then local rtype = room:GetType() if not currentRoom and StageAPI.CurrentStage.SinRooms and (rtype == RoomType.ROOM_MINIBOSS or rtype == RoomType.ROOM_SECRET or rtype == RoomType.ROOM_SHOP) then local usingRoomsList local includedSins = {} for _, entity in ipairs(Isaac.GetRoomEntities()) do for i, sin in ipairs(StageAPI.SinsSplitData) do if entity.Type == sin.Type and (sin.Variant and entity.Variant == sin.Variant) and ((sin.ListName and StageAPI.CurrentStage.SinRooms[sin.ListName]) or (sin.MultipleListName and StageAPI.CurrentStage.SinRooms[sin.MultipleListName])) then if not includedSins[i] then includedSins[i] = 0 end includedSins[i] = includedSins[i] + 1 break end end end for ind, count in pairs(includedSins) do local sin = StageAPI.SinsSplitData[ind] local listName = sin.ListName if count > 1 and sin.MultipleListName then listName = sin.MultipleListName end usingRoomsList = StageAPI.CurrentStage.SinRooms[listName] end if usingRoomsList then local shape = room:GetRoomShape() if #usingRoomsList.ByShape[shape] > 0 then local levelIndex = StageAPI.GetCurrentRoomID() local newRoom = StageAPI.LevelRoom(nil, usingRoomsList, nil, nil, nil, nil, nil, StageAPI.CurrentStage.RequireRoomTypeSin, nil, nil, levelIndex) StageAPI.SetCurrentRoom(newRoom) newRoom:Load() currentRoom = newRoom justGenerated = true end end end if not inStartingRoom and not currentRoom and StageAPI.CurrentStage.Rooms and StageAPI.CurrentStage.Rooms[rtype] then local levelIndex = StageAPI.GetCurrentRoomID() local newRoom = StageAPI.LevelRoom(nil, StageAPI.CurrentStage.Rooms[rtype], nil, nil, nil, nil, nil, StageAPI.CurrentStage.RequireRoomTypeMatching, nil, nil, levelIndex) StageAPI.SetCurrentRoom(newRoom) newRoom:Load() currentRoom = newRoom justGenerated = true end if not currentRoom and StageAPI.CurrentStage.Bosses and rtype == RoomType.ROOM_BOSS then local newRoom newRoom, boss = StageAPI.SetCurrentBossRoom(nil, true, StageAPI.CurrentStage.Bosses, StageAPI.CurrentStage.Bosses.HasHorseman, StageAPI.CurrentStage.RequireRoomTypeBoss) currentRoom = newRoom justGenerated = true end end retCurrentRoom, retJustGenerated, retBoss = StageAPI.CallCallbacks("POST_STAGEAPI_NEW_ROOM_GENERATION", true, currentRoom, justGenerated, currentListIndex, boss) prevRoom = currentRoom currentRoom, justGenerated, boss = retCurrentRoom or currentRoom, retJustGenerated or justGenerated, retBoss or boss if prevRoom ~= currentRoom then StageAPI.SetCurrentRoom(currentRoom) end if not boss and currentRoom and currentRoom.PersistentData.BossID then boss = StageAPI.GetBossData(currentRoom.PersistentData.BossID) end --[[ if StageAPI.RoomGrids[currentListIndex] and not justGenerated then StageAPI.RemoveExtraGrids(StageAPI.RoomGrids[currentListIndex]) end]] if currentRoom and not StageAPI.InExtraRoom and not justGenerated then currentRoom:Load() if not room:IsClear() and boss then if not boss.IsMiniboss then StageAPI.PlayBossAnimation(boss) else StageAPI.PlayTextStreak(players[1]:GetName() .. " VS " .. boss.Name) end end end if not justGenerated then if StageAPI.CustomGrids[currentListIndex] then for name, grindices in pairs(StageAPI.CustomGrids[currentListIndex]) do for grindex, exists in pairs(grindices) do StageAPI.CustomGridTypes[name]:Spawn(grindex, nil, true) StageAPI.CustomGridIndices[grindex] = true end end end end if currentRoom then local invalidEntrance local validDoors = {} for _, door in ipairs(currentRoom.Layout.Doors) do if door.Slot then if not door.Exists and level.EnterDoor == door.Slot then invalidEntrance = true elseif door.Exists then validDoors[#validDoors + 1] = door.Slot end end end if invalidEntrance and #validDoors > 0 and not currentRoom.Data.PreventDoorFix then local changeEntrance = validDoors[StageAPI.Random(1, #validDoors)] for _, player in ipairs(players) do player.Position = room:GetDoorSlotPosition(changeEntrance) end end end StageAPI.CallCallbacks("POST_STAGEAPI_NEW_ROOM", false, justGenerated) if not StageAPI.InNewStage() then local stage = level:GetStage() if stage == LevelStage.STAGE2_1 or stage == LevelStage.STAGE2_2 then StageAPI.ChangeStageShadow("stageapi/floors/catacombs/overlays/", 5) elseif stage == LevelStage.STAGE3_1 or stage == LevelStage.STAGE3_2 then StageAPI.ChangeStageShadow("stageapi/floors/necropolis/overlays/", 5) elseif stage == LevelStage.STAGE4_1 or stage == LevelStage.STAGE4_2 then StageAPI.ChangeStageShadow("stageapi/floors/utero/overlays/", 5) end end local usingGfx if currentRoom and currentRoom.Data.RoomGfx then usingGfx = currentRoom.Data.RoomGfx elseif isNewStage then local rtype = StageAPI.GetCurrentRoomType() usingGfx = StageAPI.CurrentStage.RoomGfx[rtype] end if usingGfx then local callbacks = StageAPI.GetCallbacks("PRE_CHANGE_ROOM_GFX") for _, callback in ipairs(callbacks) do local ret = callback.Function(currentRoom, usingGfx) if ret ~= nil then usingGfx = ret end end if usingGfx then StageAPI.ChangeRoomGfx(usingGfx) if currentRoom then currentRoom.Data.RoomGfx = usingGfx end end local callbacks = StageAPI.GetCallbacks("POST_CHANGE_ROOM_GFX") for _, callback in ipairs(callbacks) do callback.Function() end else if room:GetType() ~= RoomType.ROOM_DUNGEON and room:GetBackdropType() ~= 16 then StageAPI.ChangeShading("_default") end end StageAPI.RoomRendered = false end) function StageAPI.GetGridPosition(index, width) local x, y = StageAPI.GridToVector(i, width) y = y + 4 x = x + 2 return x * 40, y * 40 end mod:AddCallback(ModCallbacks.MC_EXECUTE_CMD, function(_, cmd, params) if (cmd == "cstage" or cmd == "customstage") and StageAPI.CustomStages[params] then if StageAPI.CustomStages[params] then StageAPI.GotoCustomStage(StageAPI.CustomStages[params]) else Isaac.ConsoleOutput("No CustomStage " .. params) end elseif (cmd == "nstage" or cmd == "nextstage") and StageAPI.CurrentStage and StageAPI.CurrentStage.NextStage then StageAPI.GotoCustomStage(StageAPI.CurrentStage.NextStage) elseif cmd == "reload" then StageAPI.LoadSaveString(StageAPI.GetSaveString()) elseif cmd == "printsave" then Isaac.DebugString(StageAPI.GetSaveString()) elseif cmd == "extraroom" then if StageAPI.GetExtraRoom(params) then StageAPI.TransitionToExtraRoom(params) end elseif cmd == "extraroomexit" then StageAPI.TransitionFromExtraRoom(StageAPI.LastNonExtraRoom) elseif cmd == "croom" then local paramTable = {} for word in params:gmatch("%S+") do paramTable[#paramTable + 1] = word end local name = tonumber(paramTable[1]) or paramTable[1] local listName = paramTable[2] if name then local list if listName then listName = string.gsub(listName, "_", " ") if StageAPI.RoomsLists[listName] then list = StageAPI.RoomsLists[listName] else Isaac.ConsoleOutput("Room List name invalid.") return end elseif StageAPI.CurrentStage and StageAPI.CurrentStage.Rooms and StageAPI.CurrentStage.Rooms[RoomType.ROOM_DEFAULT] then list = StageAPI.CurrentStage.Rooms[RoomType.ROOM_DEFAULT] else Isaac.ConsoleOutput("Must supply Room List name or be in a custom stage with rooms.") return end if type(name) == "string" then name = string.gsub(name, "_", " ") end local selectedLayout for _, room in ipairs(list.All) do if room.Name == name or room.Variant == name then selectedLayout = room break end end if selectedLayout then StageAPI.RegisterLayout("StageAPITest", selectedLayout) local testRoom = StageAPI.LevelRoom("StageAPITest", nil, room:GetSpawnSeed(), selectedLayout.Shape, selectedLayout.Variant) testRoom.RoomType = selectedLayout.Type StageAPI.SetExtraRoom("StageAPITest", testRoom) local doors = {} for _, door in ipairs(selectedLayout.Doors) do if door.Exists then doors[#doors + 1] = door.Slot end end StageAPI.TransitionToExtraRoom("StageAPITest", doors[StageAPI.Random(1, #doors)]) else Isaac.ConsoleOutput("Room with ID or name " .. tostring(name) .. " does not exist.") end else Isaac.ConsoleOutput("A room ID or name is required.") end elseif cmd == "creseed" then if StageAPI.CurrentStage then StageAPI.GotoCustomStage(StageAPI.CurrentStage) end elseif cmd == "roomnames" then if StageAPI.RoomNamesEnabled then StageAPI.RoomNamesEnabled = false else StageAPI.RoomNamesEnabled = 1 end elseif cmd == "trimroomnames" then if StageAPI.RoomNamesEnabled then StageAPI.RoomNamesEnabled = false else StageAPI.RoomNamesEnabled = 2 end elseif cmd == "modversion" then for name, modData in pairs(StageAPI.LoadedMods) do if modData.Version then Isaac.ConsoleOutput(name .. " " .. modData.Prefix .. modData.Version .. "\n") end end elseif cmd == "roomtest" then local roomsList = level:GetRooms() for i = 0, roomsList.Size do local roomDesc = roomsList:Get(i) if roomDesc and roomDesc.Data.Type == RoomType.ROOM_DEFAULT then game:ChangeRoom(roomDesc.SafeGridIndex) end end elseif cmd == "clearroom" then StageAPI.ClearRoomLayout(false, true, true, true) elseif cmd == "superclearroom" then StageAPI.ClearRoomLayout(false, true, true, true, nil, true, true) elseif cmd == "crashit" then game:ShowHallucination(0, 0) elseif cmd == "testgotorooms" then StageAPI.TestGotoRoomShapes = {} for _, shape in pairs(RoomShape) do if StageAPI.RoomShapeToGotoID[shape] then StageAPI.TestGotoRoomShapes[#StageAPI.TestGotoRoomShapes + 1] = shape end end end end) local gridBlacklist = { [EntityType.ENTITY_STONEHEAD] = true, [EntityType.ENTITY_CONSTANT_STONE_SHOOTER] = true, [EntityType.ENTITY_STONE_EYE] = true, [EntityType.ENTITY_BRIMSTONE_HEAD] = true, [EntityType.ENTITY_GAPING_MAW] = true, [EntityType.ENTITY_BROKEN_GAPING_MAW] = true } mod:AddCallback(ModCallbacks.MC_PRE_ROOM_ENTITY_SPAWN, function(_, t, v, s, index, seed) if StageAPI.ShouldOverrideRoom() and (t >= 1000 or gridBlacklist[t]) and not StageAPI.InExtraRoom then local shouldReturn if room:IsFirstVisit() then shouldReturn = true else local currentListIndex = StageAPI.GetCurrentRoomID() if StageAPI.RoomGrids[currentListIndex] and not StageAPI.RoomGrids[currentListIndex][index] then shouldReturn = true end end if shouldReturn then return { 999, StageAPI.E.DeleteMeEffect.V, 0 } end end end) StageAPI.LoadedMods = {} StageAPI.RunWhenLoaded = {} function StageAPI.MarkLoaded(name, version, prntVersionOnNewGame, prntVersion, prefix) StageAPI.LoadedMods[name] = {Name = name, Version = version, PrintVersion = prntVersionOnNewGame, Prefix = prefix or "v"} if StageAPI.RunWhenLoaded[name] then for _, fn in ipairs(StageAPI.RunWhenLoaded[name]) do fn() end end if prntVersion then prefix = prefix or "v" StageAPI.Log(name .. " Loaded " .. prefix .. version) end end local versionPrintTimer = 0 mod:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, function() versionPrintTimer = 60 end) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() if versionPrintTimer > 0 then versionPrintTimer = versionPrintTimer - 1 end end) mod:AddCallback(ModCallbacks.MC_POST_RENDER, function() if versionPrintTimer > 0 then local bottomRight = StageAPI.GetScreenBottomRight() local renderY = bottomRight.Y - 12 local renderX = 12 local isFirst = true for name, modData in pairs(StageAPI.LoadedMods) do if modData.PrintVersion then local text = name .. " " .. modData.Prefix .. modData.Version if isFirst then isFirst = false else text = ", " .. text end Isaac.RenderScaledText(text, renderX, renderY, 0.5, 0.5, 1, 1, 1, (versionPrintTimer / 60) * 0.5) renderX = renderX + Isaac.GetTextWidth(text) * 0.5 end end end if StageAPI.TestGotoRoomShapes then if Input.IsButtonTriggered(Keyboard.KEY_N, players[1].ControllerIndex) then local shape = StageAPI.TestGotoRoomShapes[#StageAPI.TestGotoRoomShapes] local layout = StageAPI.CreateEmptyRoomLayout(shape) StageAPI.RegisterLayout("StageAPITest", layout) local testRoom = StageAPI.LevelRoom("StageAPITest", nil, room:GetSpawnSeed(), shape, RoomType.ROOM_DEFAULT) StageAPI.SetExtraRoom("StageAPITest", testRoom) StageAPI.TransitionToExtraRoom("StageAPITest", layout.Doors[StageAPI.Random(1, #layout.Doors)].Slot, true, "Stage") StageAPI.TestGotoRoomShapes[#StageAPI.TestGotoRoomShapes] = nil if #StageAPI.TestGotoRoomShapes == 0 then StageAPI.TestGotoRoomShapes = nil end end end end) function StageAPI.RunWhenMarkedLoaded(name, fn) if StageAPI.LoadedMods[name] then fn() else if not StageAPI.RunWhenLoaded[name] then StageAPI.RunWhenLoaded[name] = {} end StageAPI.RunWhenLoaded[name][#StageAPI.RunWhenLoaded[name] + 1] = fn end end end Isaac.DebugString("[StageAPI] Loading Save System") do StageAPI.json = require("json") function StageAPI.GetSaveString() local levelSaveData = {} for index, roomGrids in pairs(StageAPI.RoomGrids) do local strindex = tostring(index) if not levelSaveData[strindex] then levelSaveData[strindex] = {} end for grindex, exists in pairs(roomGrids) do if exists then if not levelSaveData[strindex].Grids then levelSaveData[strindex].Grids = {} end levelSaveData[strindex].Grids[#levelSaveData[strindex].Grids + 1] = grindex end end end for lindex, customGrids in pairs(StageAPI.CustomGrids) do local strindex = tostring(lindex) if not levelSaveData[strindex] then levelSaveData[strindex] = {} end for name, indices in pairs(customGrids) do for index, value in pairs(indices) do if not levelSaveData[strindex].CustomGrids then levelSaveData[strindex].CustomGrids = {} end if not levelSaveData[strindex].CustomGrids[name] then levelSaveData[strindex].CustomGrids[name] = {} end if value == true then levelSaveData[strindex].CustomGrids[name][#levelSaveData[strindex].CustomGrids[name] + 1] = index else levelSaveData[strindex].CustomGrids[name][#levelSaveData[strindex].CustomGrids[name] + 1] = {index, value} end end end end for index, customRoom in pairs(StageAPI.LevelRooms) do local strindex = tostring(index) if not levelSaveData[strindex] then levelSaveData[strindex] = {} end levelSaveData[strindex].Room = customRoom:GetSaveData() end local stage = StageAPI.CurrentStage if stage then stage = stage.Name end local encounteredBosses = {} for boss, encountered in pairs(StageAPI.EncounteredBosses) do if encountered then encounteredBosses[#encounteredBosses + 1] = boss end end return StageAPI.json.encode({ LevelInfo = levelSaveData, Stage = stage, ExtraRoomName = StageAPI.CurrentExtraRoomName, EncounteredBosses = encounteredBosses }) end function StageAPI.LoadSaveString(str) StageAPI.CallCallbacks("PRE_STAGEAPI_LOAD_SAVE", false) local retLevelRooms = {} local retRoomGrids = {} local retCustomGrids = {} local retEncounteredBosses = {} local decoded = StageAPI.json.decode(str) StageAPI.CurrentStage = nil StageAPI.CurrentExtraRoom = nil StageAPI.CurrentExtraRoomName = decoded.ExtraRoomName if decoded.Stage then StageAPI.CurrentStage = StageAPI.CustomStages[decoded.Stage] else local inOverriddenStage, override = StageAPI.InOverriddenStage() if inOverriddenStage then StageAPI.CurrentStage = override end end StageAPI.EncounteredBosses = {} if decoded.EncounteredBosses then for _, boss in ipairs(decoded.EncounteredBosses) do StageAPI.EncounteredBosses[boss] = true end end for strindex, roomSaveData in pairs(decoded.LevelInfo) do local lindex = tonumber(strindex) or strindex if roomSaveData.Grids then retRoomGrids[lindex] = {} for _, grindex in ipairs(roomSaveData.Grids) do retRoomGrids[lindex][grindex] = true end end if roomSaveData.CustomGrids then retCustomGrids[lindex] = {} for name, indices in pairs(roomSaveData.CustomGrids) do for _, index in ipairs(indices) do if not retCustomGrids[lindex][name] then retCustomGrids[lindex][name] = {} end if type(index) == "table" then retCustomGrids[lindex][name][index[1]] = index[2] else retCustomGrids[lindex][name][index] = true end end end end if roomSaveData.Room then local customRoom = StageAPI.LevelRoom(nil, nil, nil, nil, nil, nil, roomSaveData.Room, nil, nil, nil, lindex) retLevelRooms[lindex] = customRoom end end if StageAPI.CurrentExtraRoomName then StageAPI.CurrentExtraRoom = retLevelRooms[StageAPI.CurrentExtraRoomName] StageAPI.InExtraRoom = true StageAPI.LoadingExtraRoomFromSave = true end StageAPI.RoomGrids = retRoomGrids StageAPI.LevelRooms = retLevelRooms StageAPI.CustomGrids = retCustomGrids StageAPI.CallCallbacks("POST_STAGEAPI_LOAD_SAVE", false) end end Isaac.DebugString("[StageAPI] Loading Miscellaneous Functions") do -- Misc helpful functions -- Takes whether or not there is a pit in each adjacent space, returns frame to set pit sprite to. function StageAPI.GetPitFrame(L, R, U, D, UL, DL, UR, DR, hasExtraFrames) -- Words were shortened to make writing code simpler. local F = 0 -- Sprite frame to set -- First bitwise frames (works for all combinations of just left up right and down) if L then F = F | 1 end if U then F = F | 2 end if R then F = F | 4 end if D then F = F | 8 end -- Then a bunch of other combinations if U and L and not UL and not R and not D then F = 17 end if U and R and not UR and not L and not D then F = 18 end if L and D and not DL and not U and not R then F = 19 end if R and D and not DR and not L and not U then F = 20 end if L and U and R and D and not UL then F = 21 end if L and U and R and D and not UR then F = 22 end if U and R and D and not L and not UR then F = 25 end if L and U and D and not R and not UL then F = 26 end if hasExtraFrames then if U and L and D and UL and not DL then F = 35 end if U and R and D and UR and not DR then F = 36 end end if L and U and R and D and not DL and not DR then F = 24 end if L and U and R and D and not UR and not UL then F = 23 end if L and U and R and UL and not UR and not D then F = 27 end if L and U and R and UR and not UL and not D then F = 28 end if L and U and R and not D and not UR and not UL then F = 29 end if L and R and D and DL and not U and not DR then F = 30 end if L and R and D and DR and not U and not DL then F = 31 end if L and R and D and not U and not DL and not DR then F = 32 end if hasExtraFrames then if U and R and D and not L and not UR and not DR then F = 33 end if U and L and D and not R and not UL and not DL then F = 34 end if U and R and D and L and UL and UR and DL and not DR then F = 37 end if U and R and D and L and UL and UR and DR and not DL then F = 38 end if U and R and D and L and not UL and not UR and not DR and not DL then F = 39 end if U and R and D and L and DL and DR and not UL and not UR then F = 40 end if U and R and D and L and DL and UR and not UL and not DR then F = 41 end if U and R and D and L and UL and DR and not DL and not UR then F = 42 end if U and R and D and L and UL and not DL and not UR and not DR then F = 43 end if U and R and D and L and UR and not UL and not DL and not DR then F = 44 end if U and R and D and L and DL and not UL and not UR and not DR then F = 45 end if U and R and D and L and DR and not UL and not UR and not DL then F = 46 end if U and R and D and L and DL and DR and not UL and not UR then F = 47 end if U and R and D and L and DL and UL and not UR and not DR then F = 48 end if U and R and D and L and DR and UR and not UL and not DL then F = 49 end end return F end local AdjacentAdjustments = { {X = -1, Y = 0}, {X = 1, Y = 0}, {X = 0, Y = -1}, {X = 0, Y = 1}, {X = -1, Y = -1}, {X = -1, Y = 1}, {X = 1, Y = -1}, {X = 1, Y = 1} } function StageAPI.GetPitFramesFromIndices(indices, width, height, hasExtraFrames) local frames = {} for index, _ in pairs(indices) do local x, y = StageAPI.GridToVector(index, width) local adjIndices = {} for _, adjust in ipairs(AdjacentAdjustments) do local nX, nY = x + adjust.X, y + adjust.Y if (nX >= 0 and nX <= width) and (nY >= 0 and nY <= height) then local backToGrid = StageAPI.VectorToGrid(nX, nY, width) if indices[backToGrid] then adjIndices[#adjIndices + 1] = true else adjIndices[#adjIndices + 1] = false end else adjIndices[#adjIndices + 1] = false end end adjIndices[#adjIndices + 1] = hasExtraFrames frames[tostring(index)] = StageAPI.GetPitFrame(table.unpack(adjIndices)) end return frames end function StageAPI.GetIndicesWithEntity(t, v, s, entities) local indicesWithEntity = {} for index, entityList in pairs(entities) do for _, entityInfo in ipairs(entityList) do local entityData = entityInfo.Data if not t or entityData.Type == t and not v or entityData.Variant == v and not s or entityData.SubType == s then indicesWithEntity[index] = true end end end return indicesWithEntity end function StageAPI.GetPitFramesForLayoutEntities(t, v, s, entities, width, height, hasExtraFrames) width = width or room:GetGridWidth() height = height or room:GetGridHeight() local indicesWithEntity = StageAPI.GetIndicesWithEntity(t, v, s, entities) return StageAPI.GetPitFramesFromIndices(indicesWithEntity, width, height, hasExtraFrames) end end Isaac.DebugString("[StageAPI] Loading Editor Features") do local recentlyDetonated = {} local d12Used = false mod:AddCallback(ModCallbacks.MC_USE_ITEM, function() d12Used = true end, CollectibleType.COLLECTIBLE_D12) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() local currentRoom = StageAPI.GetCurrentRoom() if not currentRoom then return end for index, timer in pairs(recentlyDetonated) do recentlyDetonated[index] = timer - 1 if recentlyDetonated[index] <= 0 then recentlyDetonated[index] = nil end end for group, names in pairs(currentRoom.EntityMetadata.RecentTriggers) do for name, timer in pairs(names) do names[name] = timer + 1 end end local width = room:GetGridWidth() for index, metadataSet in pairs(currentRoom.EntityMetadata) do if type(index) == "number" then if metadataSet["RoomClearTrigger"] and currentRoom.JustCleared then currentRoom:TriggerIndexMetadata(index, "RoomClearTrigger") end if metadataSet["BridgeFailsafe"] then if room:GetGridCollision(index) ~= 0 then if d12Used then local grid = room:GetGridEntity(index) grid:ToPit():MakeBridge(grid) else local adjacent = {index - 1, index + 1, index - width, index + width} for _, index2 in ipairs(adjacent) do local grid = room:GetGridEntity(index2) if grid and room:GetGridCollision(index2) == 0 and (StageAPI.RockTypes[grid.Desc.Type] or grid.Desc.Type == GridEntityType.GRID_POOP) then local pit = room:GetGridEntity(index) pit:ToPit():MakeBridge(pit) break end end end end end if metadataSet["GridDestroyer"] then if currentRoom:WasIndexTriggered(index, 100) then local grid = room:GetGridEntity(index) if grid and room:GetGridCollision(index) ~= 0 then if StageAPI.RockTypes[grid.Desc.Type] then grid:Destroy() elseif grid.Desc.Type == GridEntityType.GRID_PIT then grid:ToPit():MakeBridge(grid) end end end end if metadataSet["Detonator"] then if room:GetGridCollision(index) ~= 0 then local checking = room:GetGridEntity(index) local shouldDetonate = currentRoom:WasIndexTriggered(index, 100) if not shouldDetonate then local adjacent = {index - 1, index + 1, index - width, index + width} for _, index2 in ipairs(adjacent) do if not recentlyDetonated[index2] and currentRoom.EntityMetadata[index2] and currentRoom.EntityMetadata[index2]["Detonator"] then if room:GetGridCollision(index2) == 0 then local grid = room:GetGridEntity(index2) if grid then if StageAPI.RockTypes[checking.Desc.Type] and StageAPI.RockTypes[grid.Desc.Type] then checking:Destroy() elseif checking.Desc.Type == GridEntityType.GRID_PIT and grid.Desc.Type == GridEntityType.GRID_PIT then checking:ToPit():MakeBridge(checking) end Isaac.Spawn(EntityType.ENTITY_EFFECT, EffectVariant.POOF01, 0, room:GetGridPosition(index), zeroVector, nil) recentlyDetonated[index] = 5 if metadataSet["DetonatorTrigger"] then currentRoom:TriggerIndexMetadata(index, "DetonatorTrigger") end end end end end end if shouldDetonate then if StageAPI.RockTypes[checking.Desc.Type] then checking:Destroy() elseif checking.Desc.Type == GridEntityType.GRID_PIT then checking:ToPit():MakeBridge(checking) end Isaac.Spawn(EntityType.ENTITY_EFFECT, EffectVariant.POOF01, 0, room:GetGridPosition(index), zeroVector, nil) recentlyDetonated[index] = 5 if metadataSet["DetonatorTrigger"] then currentRoom:TriggerIndexMetadata(index, "DetonatorTrigger") end end end end if metadataSet["Spawner"] then if currentRoom:WasIndexTriggered(index, nil, 1) then local blockedEntities = currentRoom.EntityMetadata.BlockedEntities[index] if blockedEntities then if #blockedEntities > 0 then local spawn = blockedEntities[StageAPI.Random(1, #blockedEntities)] Isaac.Spawn(spawn.Type or 20, spawn.Variant or 0, spawn.SubType or 0, room:GetGridPosition(index), zeroVector, nil) end end end end --[[ if metadataSet["DoorLocker"] then if room:IsClear() then local isClear = true for _, entity in ipairs(Isaac.GetRoomEntities()) do if entity:CanShutDoors() then isClear = false break end end if isClear then for i = 0, room:GetGridSize() do local grid = room:GetGridEntity(i) if grid and grid:ToPressurePlate() and grid:GetVariant() == 0 and grid.State ~= 3 then isClear = false break end end end if not isClear then room:SetClear(false) StageAPI.CloseDoors() end end end]] end end end) end do -- Challenge Rooms --[[ Custom Challenge Waves CustomStage:SetChallengeWaves(RoomsList, BossChallengeRoomsList) Challenge waves must be rooms with only entities, and no metadata entities, to properly merge into the existing room. If the challenge room has a non-zero SubType, only challenge waves with a SubType that matches or is zero will be selected. This allows the editor to design waves that fit each room layout, or some with SubType 0 that fit all. If a challenge room layout can fit any one set of waves, just use SubType 0. ]] StageAPI.Challenge = { WaveChanged = false, WaveSpawnFrame = nil, WaveSubtype = nil } mod:AddCallback(ModCallbacks.MC_POST_NPC_INIT, function(_, npc) if room:GetType() == RoomType.ROOM_CHALLENGE and not StageAPI.Challenge.WaveSpawnFrame and room:IsAmbushActive() and not room:IsAmbushDone() then if npc.CanShutDoors and not (npc:HasEntityFlags(EntityFlag.FLAG_FRIENDLY) or npc:HasEntityFlags(EntityFlag.FLAG_PERSISTENT) or npc:HasEntityFlags(EntityFlag.FLAG_NO_TARGET)) then local preventCounting for _, entity in ipairs(Isaac.FindInRadius(StageAPI.ZeroVector, 9999, EntityPartition.ENEMY)) do if entity:ToNPC() and entity:CanShutDoors() and not (entity:HasEntityFlags(EntityFlag.FLAG_FRIENDLY) or entity:HasEntityFlags(EntityFlag.FLAG_PERSISTENT) or entity:HasEntityFlags(EntityFlag.FLAG_NO_TARGET)) and entity.FrameCount ~= npc.FrameCount then preventCounting = true break end end if not preventCounting then StageAPI.Challenge.WaveChanged = true end if StageAPI.Challenge.WaveChanged and StageAPI.CurrentStage and StageAPI.CurrentStage.ChallengeWaves then npc:ClearEntityFlags(EntityFlag.FLAG_APPEAR) npc.Visible = false for _, effect in ipairs(Isaac.FindByType(EntityType.ENTITY_EFFECT, EffectVariant.POOF01, -1, false, false)) do if effect.Position.X == npc.Position.X and effect.Position.Y == npc.Position.Y then effect:Remove() end end npc:Remove() end end end end) StageAPI.ChallengeWaveRNG = RNG() mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, function() for k, v in pairs(StageAPI.Challenge) do StageAPI.Challenge[k] = nil end StageAPI.ChallengeWaveRNG:SetSeed(room:GetSpawnSeed(), 0) local currentRoom = StageAPI.GetCurrentRoom() if currentRoom and currentRoom.Data.ChallengeWaveIDs then currentRoom.Data.ChallengeWaveIDs = nil end end) -- prevent waves of the wrong subtype from appearing StageAPI.AddCallback("StageAPI", "POST_CHECK_VALID_ROOM", 0, function(layout) if StageAPI.Challenge.WaveSubtype then if not (layout.SubType == 0 or layout.SubType == StageAPI.Challenge.WaveSubtype) then return 0 end end end) mod:AddCallback(ModCallbacks.MC_POST_UPDATE, function() if StageAPI.Challenge.WaveSpawnFrame and game:GetFrameCount() > StageAPI.Challenge.WaveSpawnFrame then StageAPI.Challenge.WaveSpawnFrame = nil end if StageAPI.Challenge.WaveChanged then if room:GetType() ~= RoomType.ROOM_CHALLENGE then StageAPI.Challenge.WaveChanged = false StageAPI.Challenge.WaveSubtype = nil return end if StageAPI.CurrentStage and StageAPI.CurrentStage.ChallengeWaves then StageAPI.Challenge.WaveSpawnFrame = game:GetFrameCount() local currentRoom = StageAPI.GetCurrentRoom() local challengeWaveIDs if currentRoom then if not StageAPI.Challenge.WaveSubtype and currentRoom.Layout.SubType ~= 0 then StageAPI.Challenge.WaveSubtype = currentRoom.Layout.SubType end if not currentRoom.Data.ChallengeWaveIDs then currentRoom.Data.ChallengeWaveIDs = {} end challengeWaveIDs = currentRoom.Data.ChallengeWaveIDs end local seed = StageAPI.ChallengeWaveRNG:Next() local useWaves = StageAPI.CurrentStage.ChallengeWaves.Normal if level:HasBossChallenge() then useWaves = StageAPI.CurrentStage.ChallengeWaves.Boss end local wave = StageAPI.ChooseRoomLayout(useWaves, seed, room:GetRoomShape(), room:GetType(), false, false, nil, challengeWaveIDs) if currentRoom then table.insert(currentRoom.Data.ChallengeWaveIDs, wave.StageAPIID) if not StageAPI.Challenge.WaveSubtype and currentRoom.Layout.SubType == 0 and wave.SubType ~= 0 then StageAPI.Challenge.WaveSubtype = wave.SubType end end local spawnEntities = StageAPI.ObtainSpawnObjects(wave, seed) StageAPI.SpawningChallengeEnemies = true StageAPI.LoadRoomLayout(nil, {spawnEntities}, false, true, false, true, nil, nil, nil, true) StageAPI.SpawningChallengeEnemies = false end StageAPI.CallCallbacks("CHALLENGE_WAVE_CHANGED") StageAPI.Challenge.WaveChanged = false end end) end Isaac.DebugString("[StageAPI] Loading BR Compatibility") do -- BR Compatibility StageAPI.InTestMode = false StageAPI.OverrideTestRoom = false -- toggle this value in console to force enable stageapi override local status, brTestRooms = pcall(require, 'basementrenovator.roomTest') if not status then StageAPI.Log("Could not load BR compatibility file; (basementrenovator/roomTest.lua) this will disable testing StageAPI rooms. No other features will be affected. Check log.txt for full error. To suppress this message, delete the compat file and replace it with a renamed copy of blankRoomTest.lua.") Isaac.DebugString('Error loading BR compatibility file: ' .. tostring(brTestRooms)) elseif brTestRooms then local testList = StageAPI.RoomsList("BRTest", brTestRooms) for i, testLayout in ipairs(testList.All) do StageAPI.RegisterLayout("BRTest-" .. i, testLayout) end BasementRenovator = BasementRenovator or { subscribers = {} } BasementRenovator.subscribers['StageAPI'] = { PostTestInit = function(testData) local test = testData.Rooms and testData.Rooms[1] or testData local testLayout = brTestRooms[1] if test.Type ~= testLayout.TYPE or test.Variant ~= testLayout.VARIANT or test.Subtype ~= testLayout.SUBTYPE or test.Name ~= testLayout.NAME or (testData.Rooms and #testData.Rooms ~= #brTestRooms) then StageAPI.Log("basementrenovator/roomTest.lua did not have values matching the BR test! Make sure your hooks are set up properly") StageAPI.BadTestFile = true return end StageAPI.InTestMode = true StageAPI.InTestRoom = function() return BasementRenovator.InTestRoom() end StageAPI.Log("Basement Renovator test mode") end, TestStage = function(test) if StageAPI.BadTestFile or not BasementRenovator.TestRoomData then return end -- TestStage fires in post_curse_eval, -- before StageAPI's normal stage handling code if test.IsModStage then StageAPI.NextStage = StageAPI.CustomStages[test.StageName] StageAPI.OverrideTestRoom = true -- must be turned on for custom stages end end, TestRoomEntitySpawn = function() if StageAPI.BadTestFile then return end if not StageAPI.OverrideTestRoom then return end -- makes sure placeholder/meta entities can't spawn return { 999, StageAPI.E.DeleteMeEffect.V, 0 } end } local function GetBRRoom(foo) if StageAPI.BadTestFile or not BasementRenovator.TestRoomData then return end if not StageAPI.OverrideTestRoom then return end if BasementRenovator.InTestStage() and room:IsFirstVisit() then local brRoom = BasementRenovator.InTestRoom() if brRoom then return brRoom end end end StageAPI.AddCallback("StageAPI", "PRE_STAGEAPI_NEW_ROOM_GENERATION", 0, function() local brRoom = GetBRRoom() if brRoom then local testRoom = StageAPI.LevelRoom("BRTest-" .. (brRoom.Index or 1), nil, room:GetSpawnSeed(), brRoom.Shape, brRoom.Type, nil, nil, nil, nil, nil, StageAPI.GetCurrentRoomID()) return testRoom end end) StageAPI.AddCallback("StageAPI", "POST_STAGEAPI_NEW_ROOM", 0, function() if GetBRRoom() then if BasementRenovator.RenderDoorSlots then BasementRenovator.RenderDoorSlots() end end end) end end do -- Mod Compatibility local latestChangelog local function TryAddChangelog(ver, log) if not latestChangelog then latestChangelog = ver end if DeadSeaScrollsMenu and DeadSeaScrollsMenu.AddChangelog then log = string.gsub(log, "%*%*", "{FSIZE2}") if latestChangelog == ver then Isaac.DebugString(log) end DeadSeaScrollsMenu.AddChangelog("StageAPI", ver, log, false, latestChangelog == ver, false) elseif REVEL and REVEL.AddChangelog then REVEL.AddChangelog("StageAPI " .. ver, log) end end mod:AddCallback(ModCallbacks.MC_POST_GAME_STARTED, function() if (DeadSeaScrollsMenu and DeadSeaScrollsMenu.AddChangelog) or (REVEL and REVEL.AddChangelog and not REVEL.AddedStageAPIChangelogs) then if not (DeadSeaScrollsMenu and DeadSeaScrollsMenu.AddChangelog) then REVEL.AddedStageAPIChangelogs = true end TryAddChangelog("v1.92", [[- Fixed bridges not functioning in Catacombs, Necropolis, and Utero - Fixed Downpour, Mines, and Mausoleum trapdoors being overridden in custom stages - Updated StageAPI Utero backdrop to match new version in Repentance - StageAPI now enables sprite suffix replacements for all base game floors - StageAPI now loads before most or all other mods ]]) TryAddChangelog("v1.89 - 91", [[- Updated StageAPI to function with Repentance. Note that it is still a work in progress, and may have some bugs. Please report any issues at StageAPI's github page, linked in the steam description. - StageAPI no longer overrides the D7 - StageAPI now supports Dead Sea Scrolls changelogs - Custom grids can now disable the usual grid sprite replacement that custom stages do, via a new argument to CustomGrid() - Fixed an issue with overridden RoomGfx not using the correct GridGfx on custom stages - Fixed the base game's black market crawlspace leading to an error room - StageAPI no longer overrides music.xml, which should allow for considerably more compatibility with music replacing mods ]]) TryAddChangelog("v1.86 - 88", [[- Added functions AddObjectToRoomLayout, GenerateRoomLayoutFromData, IsMetadataEntity, RoomDataHasMetadataEntity for interaction with RoomDescriptor.Data - Add compatibility with Classy Vs Screen and fix double trouble rendering bug - Add Starting Room Controls rendering API per character ]]) TryAddChangelog("v1.85", [[- Add convenience function GetIndicesWithEntity - Improve womb overlay visuals in curse of darkness ]]) TryAddChangelog("v1.84", [[- Fix issue with room test file that was causing startup crashes - Add POST_CUSTOM_GRID_REMOVE callback - StageAPI is now off by default when testing rooms outside custom floors - Add StageAPI.OverrideTestRoom switch as an explicit override for that - Enhance PRE_SPAWN_ENTITY compat with PRE_ROOM_ENTITY_SPAWN so effects are automatically converted to type 1000 - Only prevent clearing wall grids "outside" the room. this allows custom grids based on GRID_WALL - Improved the accuracy of Depths and Womb overlays - Add RemoveCustomGrid function - CurrentRoom.Data.RoomGfx is set to whatever RoomGfx was applied to the room after callbacks - Fix a bug that crashed the game when a coop player exited - Fix save and continue so rooms are loaded in the correct positions - Remove all vanilla closet boss rooms - Add detonator meta entity that when triggered destroys its grid or creates a bridge, and detonated trigger that triggers when detonated in that way - Add default broken states for alt grids with overridden spawns ]]) TryAddChangelog("v1.83", [[- Fix a bug with PRE_SPAWN_ENTITY that caused replacements to persist between runs - Make compatible with multi-room Basement Renovator tests - Add GetValidRoomsForLayout and GetDoorsForRoom - Fix bug where missing door weights were unused ]]) TryAddChangelog("v1.80 - 82", [[- Extra rooms can now use default or boss room types from the current floor as a base for their backdrop and music - Upgraded streak system to allow larger base sprites, and holding in place for as long as needed - Boss rooms can be set in place for boss testing with basement renovator - Movable TNT and shopkeepers are now properly persistent - Added a triggerable grid destroyer metadata entity that can create bridges and destroy rocks - Fixed bosses marked as horsemen not taking the place of horsemen in their floors - Various changes to room layout picking including a setting to pick from all shapes, doors now more easily associated with empty room layouts, and boss room initialization without loading - Added GetDisplayName, IsNextStage, and IsSameStage functions - Fixed custom doors and shading moving incorrectly during screenshake **v1.81 - Pitfalls and eternal flies are now persistent - Separated room type requiring for sin rooms and special rooms, so that you do not need secret / shop sin rooms - Added DoLayoutDoorsMatch for convenience **v1.82 - Update BR scripts for Basement Renovator xml format and add setup script - Improve accuracy of floor anm2 to match with the base game - Add hook for custom boss portrait sprite and portrait offset - Fixed animation for trapdoors overridden with PRE_SELECT_NEXT_STAGE - Add setter functions for IsSecondStage and StageNumber ]]) TryAddChangelog("v1.78 - 79", [[-Fixed an issue where "fart damage" was cancelled even with none in the room, which broke Sharp Plug. - StageAPI's PRE_SPAWN_ENTITY is compatible with the return value of PRE_ROOM_ENTITY_SPAWN - Allow multiple pit spritesheets - Improve RNG (?) ]]) TryAddChangelog("v1.75 - 78", [[-Fixed an issue with nightmare jingle not being overridden -Relocated test room lua, fixing harmless error on game start -"roomnames" command now displays base rooms as well as difficulty and stage id. a new command "trimroomnames" has been added which cuts out everything other than name and id -Overridden d7 no longer force-plays active use animation -Added several new entity metadata features -- AddUnblockableEntities allows setting unblockable entities, like custom grids -- GetEntityMetadata allows specifying name but not index, to get all metadata entities with a particular name -- GetEntityMetadataOfType allows getting all metadata entities within a certain group, like directions -GotoCustomStage now allows not forgetting the stage seed, in case mods want to do special stage RNG -Included XML to Lua script is now much faster - Enhanced Basement Renovator compatibility: layout will now load directly so roomlist callbacks can't interfere, set up stage support -Fixed extra rooms not being loaded on save and continue ]]) TryAddChangelog("v1.72 - 74", [[-Basement renovator integration -Added stb converter to mod folder, contained within scripts zip -StageAPI now saved on new level, fixing some issues with lingering custom stages after a crash -Added room splitting by type or entities functionality, used for sins -Custom stages can now set sin rooms to take the place of base minibosses -Fixed The Soul not counting as The Forgotten in transitions -An additional offset can now be added to custom overlays -Custom stages can now override StageAPI's default trapdoor replacement system ]]) TryAddChangelog("v1.69 - 71", [[-Fixed transitions out of special rooms not properly resetting the music -Allowed following base game room rules such as multiple choice treasure rooms when filling a special room layout -Added support for all special rooms to be easily overriden by a custom stage like default rooms -Extra rooms now properly save when moving from one extra room to another -Added support for custom challenge waves (details can be found in main.lua) -Added support for tying RoomGfx to a specific room, which takes priority over stage -Text for "roomnames" command is now rendered at 50% scale and includes room subtype -Fixed first transition from extra room to normal room improperly acting like a transition from an extra room to an off-grid room -Added support for custom boss intro and outro music for custom stages -Added support for custom level transition stingers for custom stages -Added a miniboss flag for bosses that plays a text streak rather than a boss animation -Added functions -- IsIndexInLayout -- GetCustomGrid -- AddEntityToSpawnList -Fixed teleportation cards and items potentially sending the player to invalid door slots -Fixed rooms only being accepted as a table rather than alone ]]) TryAddChangelog("v1.68", [[-Fixed some persistent entities duplicating or respawning when they shouldn't in extra rooms -Fixed escaping from an extra room to a base game off-grid room (such as devil via joker) then re-entering the extra room resulting in an infinitely looping bedroom ]]) TryAddChangelog("v1.67", [[-Missing door weight is now scaled correctly by original weight ]]) TryAddChangelog("v1.66", [[-Fixed persistent entity data not always unloading when the room changes -Room weight is now scaled by number of unavailable doors to make rooms with a large amount of unavailable doors more likely to appear ]]) TryAddChangelog("v1.65", [[-Fixed dead slot machines respawning in extra rooms ]]) TryAddChangelog("v1.64", [[-Disabled backdrop setting on non-custom floors ]]) TryAddChangelog("v1.63", [[-Fixed stage shadows not being properly centered in some L shaped rooms -Fixed black overlay in stage and room transitions not scaling with screen. ]]) TryAddChangelog("v1.62", [[-Fixed extra rooms containing persistent entities from the previous room, after you re-enter the room twice ]]) TryAddChangelog("v1.61", [[-Fixed extra rooms containing persistent entities from the previous room ]]) TryAddChangelog("v1.60", [[-Fixed Mom's Heart track not playing properly in Utero 2 -Fixed extra rooms (for example revelations' mirror room) not correctly unloading when exited by means other than a door ]]) end end) end Isaac.DebugString("[StageAPI] Fully Loaded, loading dependent mods.") StageAPI.MarkLoaded("StageAPI", "1.92", true, true) StageAPI.Loaded = true if StageAPI.ToCall then for _, fn in ipairs(StageAPI.ToCall) do fn() end end