content
stringlengths
5
1.05M
local garbage = { {-194053.0625, -44136.609375, 1151.7413330078}, {-194469.140625, -44692.0546875, 1148.1514892578}, {-194456.3125, -46672.43359375, 1148.1514892578}, {-195033.765625, -47723.33203125, 1148.1505126953}, {-193969.0625, -48198.5859375, 1148.1505126953}, {-188525.78125, -47113.9140625, 1148.1505126953}, {-186823.390625, -48089.51171875, 1148.1505126953}, {-185500.203125, -47879.328125, 1149.2749023438}, {-188907.484375, -45118.65625, 1148.1513671875}, {-188907.4375, -44785.44140625, 1148.1511230469}, {-187602.71875, -35908.48046875, 1148.1502685547}, {-185509.0625, -35852.6484375, 1148.1502685547}, {-183735.515625, -40732.31640625, 1148.1510009766}, {-183735.1875, -41032.85546875, 1148.1513671875}, {-181748.671875, -42604.5546875, 1148.1510009766}, {-174117.25, -64476.62890625, 1148.1500244141}, {-173928.5625, -65023.953125, 1148.1500244141}, {-171019.53125, -64636.78515625, 1147.9018554688}, {-171019.515625, -64289.4765625, 1147.9018554688}, {-177116.421875, -66945.5078125, 1147.8018798828}, {-177256.546875, -67133.3984375, 1147.8018798828}, {-177254.53125, -67421.0859375, 1147.8018798828}, {-177313.078125, -67631.65625, 1147.8018798828}, {-178402.5, -65967.1484375, 1147.8018798828}, {-178402.609375, -66264.390625, 1147.8018798828}, {-181053.5625, -67383.1796875, 1152.0147705078}, {-181692.828125, -67535.34375, 1147.8939208984}, {-182089.484375, -67001.578125, 1158.0418701172}, {-182054.15625, -66423.890625, 1147.7019042969}, {-169279.421875, -45646.53125, 1149.9621582031}, {-169674.1875, -44335.6953125, 1148.1510009766}, {-173141.53125, -41913.3671875, 1148.1510009766}, {-174834.375, -41834.4609375, 1148.1510009766}, {-174729.078125, -36123.36328125, 1148.1505126953}, {-177445.0625, -36783.41796875, 1148.1502685547}, {-177951.09375, -37955.8359375, 1148.1520996094}, {-183322.484375, -47967.45703125, 1153.2230224609}, {-186047.5625, -52065.39453125, 1146.94921875} } AddEvent("OnPlayerStartEnterVehicle", function(vehicle) if GetVehiclePropertyValue(vehicle, "owner") == 0 then if GetVehiclePropertyValue(vehicle, "garbage_bags") ~= nil then if GetPlayerPropertyValue(GetPlayerId(), "job") ~= "GARBAGE" then return false end end if GetVehiclePropertyValue(vehicle, "delivery_packages") ~= nil then if GetPlayerPropertyValue(GetPlayerId(), "job") ~= "DELIVERY" then return false end end end end) AddEvent("OnKeyPress", function(key) if key == "E" then if GetPlayerPropertyValue(GetPlayerId(), "job") == "GARBAGE" then local px, py, pz = GetPlayerLocation() for i=1,#garbage do if GetDistance3D(px, py, pz, garbage[i][1], garbage[i][2], garbage[i][3]) < 100 then CallRemoteEvent("GarbageCollect", i) return end end end end end)
Material{ name="Kevlar", density=1.44e+3, Spull=3.6e+9, Spush=0.0, Kpull=154.0e+9, Kpush=0.0, reflectivity=0.6, Tmelt=350 } Material{ name="Steel" , density=7.89e+3, Spull=1.2e+9, Spush=0.0, Kpull=200.0e+9, Kpush=0.0, reflectivity=0.85, Tmelt=800 } --Material{ name="Titanium" , density=7.89e+3, Spull=3.6e+9, Spush=0.0, Kpull=154.0e+9, Kpush=0.0, reflectivity=0.7, Tmelt=450 } origin = {0.0,0.0,0.0} xvec = {1.0,0.0,0.0} yvec = {0.0,1.0,0.0} zvec = {0.0,0.0,1.0} function tanks( n,aOff, R, r, L, z0 ) for i=1,n do local a = (i/n + aOff)*2*math.pi Tank( {math.cos(a)*R,math.sin(a)*R,z0}, zvec, {r,r,L}, "H2") end end function girderFan( n, aOff, w, h, z0,z1, nseg, thick, shielded ) local tipNode = Node({0.0,0.0,z1}); local a = aOff*2*math.pi local gd0 = Girder( tipNode, Node({math.cos(a)*w,math.sin(a)*h,z0}), xvec, nseg, 2, {thick,thick}, "steel") local ogd = gd0; for i=1,n do local gd=gd0 if i<n then local a = (i/n + aOff)*2*math.pi gd = Girder( tipNode, Node({math.cos(a)*w,math.sin(a)*h,z0}), xvec, nseg, 2, {thick,thick}, "steel" ) end if shielded then Shield( ogd,0.0,1.0, gd,0.0,1.0 ) end ogd = gd; end end
class 'Bind' local toBind = nil local binds = {} local unbind = false local color = Color( 240, 195, 55 ) function Bind:__init() self.cooldown = 1 timer = Timer() self.cooltime = 0 Events:Subscribe( "LocalPlayerChat", self, self.LocalPlayerChat ) Events:Subscribe( "KeyDown", self, self.KeyDown ) end function Bind:LocalPlayerChat( args ) if string.sub(args.text,1,6) == "/bind " then toBind = string.sub(args.text, 7) if string.sub(toBind,1,1) == "/" then Chat:Print( "[Привязка] ", Color.White, "Нажмите клавишу, которую вы хотите связать с командой " .. toBind, Color.Red ) end elseif string.sub(args.text,1,5) == "/bind" then Chat:Print( "[Привязка] ", Color.White, "Пример использования:", color, " /bind /jesus", Color.White ) Chat:Print( "[Привязка] ", Color.White, "Вам будет предложено нажать клавишу для привязки команды.", color ) Chat:Print( "[Привязка] ", Color.White, "Другие команды:", color, " /unbind, /unbindall, /list", Color.White ) elseif args.text == "/unbindall" then binds = {} Chat:Print( "[Привязка] ", Color.White, "Все клавиши отвязаны.", color ) UpdateKeys() elseif string.sub(args.text,1,7) == "/unbindall" then Chat:Print( "[Привязка] ", Color.White, "Введите /unbindall, чтобы отвязать все клавиши.", color ) elseif args.text == "/unbind" then unbind = true Chat:Print ("[Привязка] ", Color.White, "Нажмите клавишу, которую вы хотели бы отвязать.", color ) elseif string.sub(args.text,1,7) == "/unbind" then Chat:Print( "[Привязка] ", Color.White, "Введите /unbind, чтобы отвязать клавишу", color ) elseif args.text == "/list" then for k,v in pairs(binds) do Chat:Print( "[Привязка] ", Color.White, k .. " (" .. string.char(k) .. ") делает " .. v, color ) end end end function Bind:KeyDown( args ) local time = Client:GetElapsedSeconds() if unbind then if binds[args.key] then Chat:Print( "[Привязка] ", Color.White, "Команда " .. binds[args.key] .. " отвязана от " .. args.key .. " ("..string.char(args.key) .. ")", color ) binds[args.key] = nil unbind = false UpdateKeys() else Chat:Print( "[Привязка] ", Color.White, "Никакая команда не была связана с кнопкой " .. args.key .. " (" .. string.char(args.key) .. ")", color ) unbind = false end elseif toBind then if string.sub(toBind,1,1) == "/" then local message = "" if string.sub(toBind,1,1) == "/" then message = message .. "Команда " end message = message .. toBind .. " привязана к клавише " .. args.key .. " ("..string.char(args.key)..")" if binds[args.key] then message = message .. ", изменено на " .. binds[args.key] end binds[args.key] = toBind Chat:Print( "[Привязка] ", Color.White, message, color ) toBind = nil UpdateKeys() end elseif binds[args.key] then if time < self.cooltime then return end Events:Fire("LocalPlayerChat", {text=binds[args.key]}) Network:Send("SimulateCommand", binds[args.key]) self.cooltime = time + self.cooldown end end function UpdateKeys() Network:Send( "SQLSave", binds ) end Network:Subscribe( "SQLLoad", function( args ) binds = args if next(binds) == nil then else print( "Привязка клавиш загружена!" ) end end ) bind = Bind()
-- Submodule for emulating the control of a script as a process. local time = require 'concurrent.time' local process = require 'concurrent.process' local message = require 'concurrent.message' local scheduler = require 'concurrent.scheduler' local concurrent process.processes[0] = 0 -- Root process has PID of 0. message.mailboxes[0] = {} -- Root process mailbox. -- The existing versions of these functions are renamed before replacing them. process._self = process.self process._isalive = process.isalive scheduler._wait_yield = scheduler.wait_yield scheduler._sleep_yield = scheduler.sleep_yield -- Returns 0 if the process is not a coroutine. function process.self() return process._self() or 0 end -- The root process is always alive. function process.isalive(pid) if pid ~= 0 then return process._isalive(pid) end return true end -- Special care must be taken if the root process is blocked. function scheduler.wait_yield() concurrent = concurrent or require 'concurrent' local s = concurrent.self() if s ~= 0 then return scheduler._wait_yield() end while true do if scheduler.barriers[s] then break end concurrent.step() concurrent.tick() end end -- Special care must be taken if the root process is sleeping. function scheduler.sleep_yield() concurrent = concurrent or require 'concurrent' local timeouts = scheduler.timeouts local mailboxes = message.mailboxes local s = concurrent.self() if s ~= 0 then return scheduler._sleep_yield() end while true do if #mailboxes[s] > 0 then break end if timeouts[s] and time.time() - timeouts[s] >= 0 then timeouts[s] = nil return end concurrent.step() concurrent.tick() end end return process
local msg = require('virgo/protocol/messages') local sigar = require('sigar') --[[ Manifest.get ]]-- local Manifest = msg.Request:extend() function Manifest:initialize() msg.Request.initialize(self) self.method = 'check_schedule.get' end function Manifest:serialize(msgId) self.params.blah = 1 return msg.Request.serialize(self, msgId) end --[[ System Info ]]-- local SystemInfoResponse = msg.Response:extend() function SystemInfoResponse:initialize(replyToMsg, result) msg.Response.initialize(self, replyToMsg) local s = sigar:new() local cpus = s:cpus() local netifs = s:netifs() self.sysinfo = s:sysinfo() self.netifs = {} self.cpus = {} for i=1,#cpus do self.cpus[i] = {} self.cpus[i].info = cpus[i]:info() self.cpus[i].data = cpus[i]:data() end for i=1,#netifs do self.netifs[i] = {} self.netifs[i].info = netifs[i]:info() self.netifs[i].usage = netifs[i]:usage() end end function SystemInfoResponse:serialize(msgId) self.result.sysinfo = self.sysinfo self.result.cpus = self.cpus self.result.netifs = self.netifs return msg.Response.serialize(self, msgId) end --[[ Metrics Request ]]-- local MetricsRequest = msg.Request:extend() function MetricsRequest:initialize(check, checkResult) msg.Request.initialize(self) self.check = check self.checkResult = checkResult self.method = 'check_metrics.post' end function MetricsRequest:serialize(msgId) self.params.state = self.checkResult:getState() self.params.status = self.checkResult:getStatus() self.params.metrics = self.checkResult:serialize() self.params.timestamp = self.checkResult:getTimestamp() self.params.min_check_period = self.checkResult:getMinimumCheckPeriod() self.params.check_id = self.check.id self.params.check_type = self.check.getType() return msg.Request.serialize(self, msgId) end --[[ ScheduleChangeAck ]]-- local ScheduleChangeAck = msg.Response:extend() function ScheduleChangeAck:initialize(replyTo) msg.Response.initialize(self, replyTo) end function ScheduleChangeAck:serialize(msgId) return msg.Response.serialize(self, msgId) end --[[ HostInfoTypesResponse ]]-- local HostInfoTypesResponse = msg.Response:extend() function HostInfoTypesResponse:initialize(replyTo, types) msg.Response.initialize(self, replyTo) self.result = {types = types} end function HostInfoTypesResponse:serialize(msgId) return msg.Response.serialize(self, msgId) end --[[ HostInfoResponse ]]-- local HostInfoResponse = msg.Response:extend() function HostInfoResponse:initialize(replyTo, info) msg.Response.initialize(self, replyTo) self.result = info end function HostInfoResponse:serialize(msgId) return msg.Response.serialize(self, msgId) end --[[ CheckTestResponse ]]-- local CheckTestResponse = msg.Response:extend() function CheckTestResponse:initialize(replyTo, result) msg.Response.initialize(self, replyTo) self.result.metrics = result:serialize() self.result.state = result:getState() self.result.status = result:getStatus() end function CheckTestResponse:serialize(msgId) return msg.Response.serialize(self, msgId) end --[[ CheckTargetsResponse ]]-- local CheckTargetsResponse = msg.Response:extend() function CheckTargetsResponse:initialize(replyTo, targets) msg.Response.initialize(self, replyTo) self.result.targets = targets end function CheckTargetsResponse:serialize(msgId) return msg.Response.serialize(self, msgId) end --[[ Config File Post ]]-- local ConfigFilePost = msg.Request:extend() function ConfigFilePost:initialize(files) msg.Request.initialize(self) self.files = files self.method = 'config_file.post' end function ConfigFilePost:serialize(msgId) if next(self.files) ~= nil then self.params.config_data = self.files else -- this forces the params to be treated as a hash self.params.dummy = 1 end return msg.Request.serialize(self, msgId) end local exports = {} exports.Manifest = Manifest exports.MetricsRequest = MetricsRequest exports.SystemInfoResponse = SystemInfoResponse exports.ScheduleChangeAck = ScheduleChangeAck exports.HostInfoTypesResponse = HostInfoTypesResponse exports.HostInfoResponse = HostInfoResponse exports.CheckTestResponse = CheckTestResponse exports.CheckTargetsResponse = CheckTargetsResponse exports.ConfigFilePost = ConfigFilePost return exports
local pricing = { gunstore = { wp_beretta = 1000, wp_glock17 = 1000, mag_pistol = 100, wp_pumpgun = 2000, wp_m16 = 5000, mag_rifle = 200 } } local function getPrice(store, item) if pricing[store] == nil then return 0 end if pricing[store][item] == nil then return 0 end return pricing[store][item] end AddRemoteEvent("StoreBuyItem", function(player, store, item, amount) local price = getPrice(store, item) * amount if price == 0 then return end if GetPlayerCash(player) < price then AddPlayerChat(player, _("not_enough_cash")) return end SetPlayerCash(player, GetPlayerCash(player) - price) AddPlayerInventoryItem(player, item, amount) end) AddRemoteEvent("StoreSellItem", function(player, store, item, amount) local price = getPrice(store, item) * amount if price == 0 then return end if GetPlayerInventoryItemAmount(player, item) < amount then AddPlayerChat(_("not_enough_items", _("item_"..item))) return end SetPlayerCash(player, GetPlayerCash(player) + price) RemovePlayerInventoryItem(player, item, amount) end)
local altars = { Position(32777, 31982, 9), Position(32779, 31977, 9), Position(32781, 31982, 9) } function onUse(player, item, fromPosition, target, toPosition, isHotkey) if player:getStorageValue(Storage.TheInquisition.Questline) == 8 then player:setStorageValue(Storage.TheInquisition.Questline, 9) player:setStorageValue(Storage.TheInquisition.Mission03, 4) -- The Inquisition Questlog- "Mission 3: Vampire Hunt" local k = {} for i = 1, #altars do local tmp = Tile(altars[i]):getItemById(2199) if not tmp then Game.createMonster("The Count", toPosition) return true else k[#k + 1] = tmp end end for i = 1, #k do k[i]:remove() end Game.createMonster("The Weakened Count", toPosition) return true end end
local Mob = require('mob') local Maph = require('maph') local DeathPoof = require('mob.particle.death_poof') local sin, cos, pi = math.sin, math.cos, math.pi local DarterDart = {} DarterDart.__index = DarterDart setmetatable(DarterDart, {__index = Mob}) function DarterDart.new(sprite) local self = setmetatable(Mob.new(), DarterDart) self.tags.darter_dart = true self.sprite = sprite --- The number of seconds left before the mob disappears. self.life_time = 10 --- The distance at which the dart hurts enemies. self.enemy_hurt_dist = 16 --- The distance at which the dart hurts players. self.player_hurt_dist = 12 --- Then amount of damage the dart deals to mobs. self.damage = 100 --- Whether or not the dart was hit back. --- Is toggled to `true` when the player smacks it. self.was_hit = false return self end function DarterDart:tick(dt, game) self.x = self.x + self.xspd * dt self.y = self.y + self.yspd * dt -- update angle self.angle = Maph.angle(self.xspd, self.yspd) - math.pi -- hurt players for mob in pairs(game.world:tagged('player')) do if Maph.distance(self.x, self.y, mob.x, mob.y) < self.player_hurt_dist then if mob.hurt then mob:hurt(game, self.damage, self) game.world:addMob(DeathPoof.new(game.assets, self.x, self.y)) self.is_alive = false return nil end end end -- hurt enemies if self.was_hit then for mob in pairs(game.world:tagged('enemy')) do if Maph.distance(self.x, self.y, mob.x, mob.y) < self.enemy_hurt_dist then if mob.hurt then mob:hurt(game, self.damage, self) game.world:addMob(DeathPoof.new(game.assets, self.x, self.y)) self.is_alive = false return nil end end end end -- destroy when hitting walls local xx, yy = game.map:posToIdx(self.x, self.y) if xx and yy and game.map:isSolid(xx, yy) then game.world:addMob(DeathPoof.new(game.assets, self.x, self.y)) self.is_alive = false return nil end -- destroy when expired self.life_time = self.life_time - dt if self.life_time <= 0 then game.world:addMob(DeathPoof.new(game.assets, self.x, self.y)) self.is_alive = false return nil end end function DarterDart:hitBack(other, angle) if not self.was_hit then local speed = Maph.hypot(self.xspd, self.yspd) self.xspd = sin(angle) * speed self.yspd = -cos(angle) * speed self.was_hit = true end end return DarterDart
--Parse Table for i in ipairs (drinks.drink_table) do local desc = drinks.drink_table[i][1] local craft = drinks.drink_table[i][2] local color = drinks.drink_table[i][3] local health = drinks.drink_table[i][4] health = health or 1 -- The color of the drink is all done in code, so we don't need to have multiple images. --Actual Node registration minetest.register_node('drinks:jbu_'..desc..'', { description = 'Bucket of '..craft..' Juice', drawtype = "plantlike", tiles = {'bucket.png^(drinks_bucket_contents.png^[colorize:'..color..':200)'}, inventory_image = 'bucket.png^(drinks_bucket_contents.png^[colorize:'..color..':200)', wield_image = 'bucket.png^(drinks_bucket_contents.png^[colorize:'..color..':200)', paramtype = "light", juice_type = craft, is_ground_content = false, walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25} }, groups = {vessel=1,dig_immediate=3,attached_node=1, drink = 1}, sounds = default.node_sound_defaults(), }) drinks.register_item('drinks:jcu_'..desc, 'vessels:drinking_glass', { description = 'Cup of '..craft..' Juice', groups = {drink=1}, juice_type = craft, inventory_image = 'drinks_glass_contents.png^[colorize:'..color..':200^drinks_drinking_glass.png', on_use = function(itemstack, user, pointed_thing) thirsty.drink(user, 4, 20) local eat_func = minetest.item_eat(health, 'vessels:drinking_glass') return eat_func(itemstack, user, pointed_thing) end, }) drinks.register_item('drinks:jbo_'..desc, 'vessels:glass_bottle',{ description = 'Bottle of '..craft..' Juice', groups = {drink = 1}, juice_type = craft, inventory_image = 'drinks_bottle_contents.png^[colorize:'..color..':200^drinks_glass_bottle.png', on_use = function(itemstack, user, pointed_thing) thirsty.drink(user, 8, 20) local eat_func = minetest.item_eat((health*2), 'vessels:glass_bottle') return eat_func(itemstack, user, pointed_thing) end, }) drinks.register_item('drinks:jsb_'..desc, 'vessels:steel_bottle',{ description = 'Heavy Steel Bottle ('..craft..' Juice)', groups = {drink = 1}, juice_type = craft, inventory_image = 'vessels_steel_bottle.png', on_use = function(itemstack, user, pointed_thing) thirsty.drink(user, 8, 20) local eat_func = minetest.item_eat((health*2), 'vessels:steel_bottle') return eat_func(itemstack, user, pointed_thing) end, }) end
addon.name = 'pouches'; addon.author = 'getawaycoxn'; addon.version = '1.0'; addon.desc = 'Uses any silt and bead pouches in your main inventory'; addon.link = 'https://github.com/GetAwayCoxn/Pouches'; --[[ 1.0 - Creation Known Issues - Quick/repeated use of start after stop will result in command line chat message errors in game and not using all items Worse with more pouches available for use due to how I implemented use_pouches() with :repeating, best to let it finish once it has started for now. ]] require('common'); local chat = require('chat'); local active = false; local silt_total = 0; local bead_total = 0; local total = 0; ashita.events.register('command', 'command_cb', function (e) local args = e.command:args(); if (#args == 0) then return; end if (args[1] ~= '/pouches') then return; end e.blocked = true; if (args[2] == 'help') then print(chat.header(addon.name) .. chat.message('Pouches will use silt pouches and bead pouches from your inventory bag')); print(chat.header(addon.name) .. chat.message('The only commands are [start] and [stop]')); elseif (args[2] == 'start') then active = true; count_pouches(); if total == 0 then print(chat.header(addon.name) .. chat.message('No pouches found, process aborted.')); return; end print(chat.header(addon.name) .. chat.message('Pouches starting ... ' .. silt_total .. ' silt pouches and ' .. bead_total .. ' bead pouches. Use "/pouches stop" to abort.')); use_pouches:repeating(0, total, 5); elseif (args[2] == 'stop') then active = false; print(chat.header(addon.name) .. chat.message('Pouches stopped.')); end end); function count_pouches() silt_total = 0; bead_total = 0; local silt = AshitaCore:GetResourceManager():GetItemByName('Silt Pouch',0); local bead = AshitaCore:GetResourceManager():GetItemByName('Bead Pouch',0); local inventory = AshitaCore:GetMemoryManager():GetInventory(); for x = 0, inventory:GetContainerCountMax(0) do local item = inventory:GetContainerItem(0, x); if (item ~= nil and item.Id == silt.Id) then silt_total = silt_total + item.Count; end end for x = 0, inventory:GetContainerCountMax(0) do local item = inventory:GetContainerItem(0, x); if (item ~= nil and item.Id == bead.Id) then bead_total = bead_total + item.Count; end end total = silt_total + bead_total; end function use_pouches() if active ~= true then return end if (silt_total > 0) then AshitaCore:GetChatManager():QueueCommand(1, '/item "Silt Pouch" <me>'); silt_total = silt_total -1; elseif (bead_total > 0) then AshitaCore:GetChatManager():QueueCommand(1, '/item "Bead Pouch" <me>'); bead_total = bead_total - 1; end if silt_total == 0 and bead_total == 0 then active = false; print(chat.header(addon.name) .. chat.message('Pouches complete.')); end end
ENT.Type = "point" ENT.Base = "base_point" ENT.Spawnable = false function ENT:SetupDataTables() self:NetworkVar("String", 0, "DTName") self:NetworkVar("String", 1, "DTDesc") self:NetworkVar("String", 2, "DTOwner") self:NetworkVar("Int", 0, "DTPrice") end
--[[ PERKS LootboxWheel - README v 0.1.0 - 2020/12/16 by: Estlogic (META) (https://www.coregames.com/user/385b45d7abdb499f8664c6cb01df521b) WitcherSilver (META) (https://www.coregames.com/user/e730c40ae54d4c588658667927acc6d8) Morticai (META) (https://www.coregames.com/user/d1073dbcc404405cbef8ce728e53d380) This package is a work in progress. Description: PERKS LootboxWheel is a component that allows creators to set up a loot table and easily implement an in-game interface for players to roll for random loot, visualize the odds and the result of the roll, and view a satisfying animation that reveals the reward. This component comes with: 1) LootboxGenerator 2) LootboxSpawner 3) DropRateSign 4) DropTable 5) Loot Machine Animation Fantasy 6) Lootbox Wheel Shuffler Scripts 7) SpinWheel 8) Display Setup ===== 1. To begin adjusting this component, first select the LootboxGenerator.lua found under the PERKS_LootboxWheel folder. 2. Once selected, there are several custom properties but the two you'll want to focus on are: 1) CurrencyName - The name of the resource, players will spend to spin the wheel. (Ex => "gold", "coins", etc) 2) RollCost - Is the cost of how much a player will spend to spin the wheel each time (Ex => 50 "gold") Prize Settings ============== To adjust the visuals of of the lootboxes select the LootboxSpawner.lua it has several custom properties: 1, ChangePrizeCamera - When enabled, the "ChangePrizeCamera" property will override the player camera during the loot box reveal animation. 2, Loot_Box - The next five custom properties are all of the asset refrences to the various lootboxes that will change visually based on the rarity of the lootbox the player has won. 3. ChestSpawnMarker - This is an object that must be in your game, it's currently found in the Loot Machine Animation Fantasy(Client Context). The chest will spawn from this objects world position. 4. LootboxGenerator - Is a Core Object Refrence to the LootboxGenerator.lua script in your heirarchy 5. Loot_Machine - A Core Object Refrence to your Loot_Machine found under the Loot Machine Animation Fantasy (Client Context) To customize your Loot Machine please refrence "Customizing Loot Machine" found further in this ReadMe. Customizing Loot Machine ======================== Any of these templates are interchangeable; shout out to @AwkwardGameDev and @Mucusinator for their contribution! All these templates are animated with the script "Loot_Box_Animation_Fantasy". reach out to @WitcherSilver for help with animations. 1. There are several examples of loot boxes that can be easily assigned to different rarities of the loot machine. These are all found in the Project Content and follow the naming convention: "Loot_Box_rarity_theme". 2. To assign a different loot box visual, find the template in Project Contect, then select the Loot_Box_Spawner script in the hierarchy. Drag the desired template into the custom property of the desired rarity, and that loot box will appear when that rarity is rolled. 3. Replacing the geometry on the loot machine is fairly simple. The animation is looking for the groups called "left_door", "right_door", and "platform", so you can replace the geometry *inside* these groups. Any other static geometry can be replaced at your discretion. 4. Replacing the geometry on the loot boxes is a bit more complicated. The animation is looking for specific groups, so the geometry inside can be replaced without too much issue. Check out the script "Loot_Box_Animation_Fantasy" for more information about the animation sequence. For more information about loot box animations, reach out to @WitcherSilver#0787 on Discord. Adding / Changing Rewards ========================= To add or modify the rewards players can earn, there are two places needing to be adjusted. 1. First open the DropTable group found inside of the PERKS_LootboxWheel folder. 2. Click on the drop down arrow next to DropTable to reveal the children of the group. 3. You'll find Common, Uncommon, Rare, Epic and Legendary as further nested groups. Depending on the rarity of the item you'd like choose the apporiate group and click the drop down narrow to reveal the groups children. 4. To modify an item click an exsisting Prize_ItemInfo.lua under the apporiate rarity group to edit the items info. There you'll find the following custom properties: 1) ID - Unique ID of the item 2) Name - Name of the folder found under => Loot Machine Animation Fantasy => Reward 3) Cost - Leave as 0 4) MUID - Not needed 5. You'll also need to be sure the client side model is found inside of the Reward group which is a child of Loot Machine Animation Fantasy. 6. Select on of the folders with the prefix STORE_, you'll find STORE_Iteminfo.lua as a child of each folder. To edit this info please refrence the META_CosmeticStore_README.lua ]]--
local player, red, blue, orange, green, map, colors, GNL, positions, graphics, sounds, points, rollControl, options, _loc, flags, randomValue, menu, game, gameFunc game = {} gameFunc = {} local loc_startingLevel function game.load(loc_startingLevelw) main.difficulty = 1 loc_startingLevel = loc_startingLevelw options = { gridMode = "fill" } randomValue = {} _loc = { levelCheck = { claimed = 0 }, quake = 0, quakeTime = 0.5, cellSize = 32, scoreAcc = 10, labelLine = 30, scoreTileIndex = 1, point_rot = 0, colorChange = 10, newMapCheck = 0, levelColorCheck = 0, levelColorCheckMult = 15, levelTransition_count = 3, randomCounter = 0, moveCounter = 0, deathAnim = 0, usernameIndex = 1, username = {"","","","","",""} } if main.difficulty >= 1 then _loc.scoreAcc = 50 elseif main.difficulty >= 2 then _loc.scoreAcc = 80 elseif main.difficulty >= 3 then _loc.scoreAcc = 120 end flags = { debug = { doAutoMove = true, canDie = true }, sound = { upScore = false, downScore = false, normal = true, song = true, death = false }, playerAct = false, paused = false, reload = true, rollPoints = true, restartRollControl = true, newPoint = true, newDest = false, scoreTileUp = true, changeStageColor = true, renewTime = false, quake = false, ghostOut = false, levelTransition = false, restart = false, quit = false, gameover = false, submit = false } local sprite_sheet = extensions.anim8.newGrid(22, 22, 154, 115) player = { grid_x = 160, grid_y = 288, act_x = 200, act_y = 200, speed = 10, orientation = "left", level = 1, score = 0, scorePrint = 0, time = 15, dead = false, lives = 3 } red = { grid_x = 736, grid_y = 224, act_x = 200, act_y = 200, speed = 10, destPoint = 1 } blue = { grid_x = 736, grid_y = 256, act_x = 200, act_y = 200, speed = 10, destPoint = 1 } orange = { grid_x = 736, grid_y = 288, act_x = 200, act_y = 200, speed = 10, destPoint = 1 } green = { grid_x = 736, grid_y = 320, act_x = 200, act_y = 200, speed = 10, destPoint = 1 } map = { {n,n,n,n,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {n,n,n,n,1,6,0,0,0,0,6,0,0,0,6,0,0,0,6,1}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,2.2,6,0,0,0,0,6,0,0,0,6,0,0,0,6,2.0}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,1,1,0,1,n,3,3,3}, {n,n,n,n,1,6,0,0,6,0,6,0,0,0,6,0,6,1,0,1,n,3,4,3}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,1,n,3,4,3}, {n,n,n,n,1,0,1,0,0,1,0,1,0,0,0,1,0,1,0,1,n,3,4,3}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,1,n,3,4,3}, {n,n,n,n,1,0,1,1,6,0,6,0,0,0,0,0,6,1,0,1,n,3,3,3}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,0,1,0,1}, {n,n,n,n,2.1,6,0,0,6,1,0,1,0,1,0,1,6,0,6,2.3}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,1,6,0,0,0,0,6,0,0,0,6,0,0,0,6,1}, {n,n,n,n,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} } colors = { stage = {0, 115, 239}, ghostWall = {255, 140, 16}, ghostFloor = {148, 84, 25}, warpColor = {18, 11, 55}, warpColor2 = {81, 11, 55}, default = {225, 225, 225, 255}, number = {0, 115, 239}, redGhost = {204, 51, 51}, blueGhost = {51, 204, 204}, orangeGhost = {204, 102, 102}, greenGhost = {204, 204, 51}, scoreColor = {200, 200, 200, 255}, scoreTile = {0, 0, 16}, levelColor = {255, 255, 255}, menu = { normal = {15, 133, 220}, selected = {243, 208, 42} } } _loc.actStageColor = colors.stage GNL = { problems = {}, answers = {}, color = {}, current = 1 } positions = { X = { [1] = 192, [2] = 352, [3] = 480, [4] = 608, [5] = 192, [6] = 352, [7] = 480, [8] = 608, [9] = 192, [10] = 288, [11] = 352, [12] = 480, [13] = 544, [14] = 288, [15] = 352, [16] = 544, [17] = 192, [18] = 288, [19] = 544, [20] = 608, [21] = 192, [22] = 352, [23] = 480, [24] = 608 }, Y = { [1] = 64, [2] = 64, [3] = 64, [4] = 64, [5] = 128, [6] = 128, [7] = 128, [8] = 128, [9] = 224, [10] = 224, [11] = 224, [12] = 224, [13] = 224, [14] = 352, [15] = 352, [16] = 352, [17] = 416, [18] = 416, [19] = 416, [20] = 416, [21] = 480, [22] = 480, [23] = 480, [24] = 480, } } rollControl = {} graphics = { sprites = love.graphics.newImage("assets/graphics/pacghost.png"), pacman_anim = extensions.anim8.newAnimation(sprite_sheet("1-2", 1), 0.009), pacman_death1 = extensions.anim8.newAnimation(sprite_sheet("3-7", 1, "1-7", 2), 0.09), red_anim = extensions.anim8.newAnimation(sprite_sheet(1, 3), 1), blue_anim = extensions.anim8.newAnimation(sprite_sheet(1, 3), 1), orange_anim = extensions.anim8.newAnimation(sprite_sheet(1, 3), 1), green_anim = extensions.anim8.newAnimation(sprite_sheet(1, 3), 1), pac_point = extensions.anim8.newAnimation(sprite_sheet(2, 3), 1), levelTransition_image = love.graphics.newImage("assets/graphics/levelTransition.png") } graphics.levelTransition = love.graphics.newParticleSystem(graphics.levelTransition_image, 1000) graphics.levelTransition:setParticleLifetime(1,10) graphics.levelTransition:setEmissionRate(500) graphics.levelTransition:setSizeVariation(1) graphics.levelTransition:setLinearAcceleration(-250, -250, 250, 250) sounds = { chomp = love.audio.newSource("assets/sounds/pacman_chomp.wav"), chomp_count = 0.3, loading = love.audio.newSource("assets/sounds/pacman_loading.wav"), loaded = love.audio.newSource("assets/sounds/pacman_loaded.wav"), death = love.audio.newSource("assets/sounds/pacman_death.wav"), death_count = 1.3, scoreIncrease = love.audio.newSource("assets/sounds/scoreUp.mp3"), scoreDecrease = love.audio.newSource("assets/sounds/scoreDown.mp3") } points = { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true } menu = { pause = { index = 1, cursorPos = { ((main.graphics.buttonLine * 2) - 48/2), ((main.graphics.buttonLine * 3) - 48/2), ((main.graphics.buttonLine * 4) - 48/2) } }, gameover = { index = 1, cursorPos = { ((main.graphics.buttonLine * 2) - 48/2), ((main.graphics.buttonLine * 3) - 48/2), } } } if loc_startingLevel then gameFunc.newLevel(loc_startingLevel) end end function game.update(dt) if player.level > 7 then colors.stage = {0, 115, 239} end dt = dt * 1 if flags.restart then return "restart" end if flags.quit then return "quit" end _loc.dt = dt randomValue[1] = map[(player.grid_y / _loc.cellSize)][(player.grid_x / _loc.cellSize)] randomValue[2] = player.grid_y.."|"..player.grid_x randomValue[3] = nil randomValue[4] = _loc.levelCheck.claimed randomValue[5] = nil if flags.paused then menu.pause.selected = menu.pause.index elseif flags.reload then local rollControl_index = 0 local tempGNL = {} if main.difficulty <= 2 then GNL.color = { [1] = {gameRandom(1, 255, 34), gameRandom(1, 255, 455), gameRandom(1, 255, 321)}, [2] = {gameRandom(1, 255, 45), gameRandom(1, 255, 54), gameRandom(1, 255, 564)}, [3] = {gameRandom(1, 255, 67), gameRandom(1, 255, 564), gameRandom(1, 255, 531)}, [4] = {gameRandom(1, 255, 85), gameRandom(1, 255, 665), gameRandom(1, 255, 564)}, [5] = {gameRandom(1, 255, 26), gameRandom(1, 255, 452), gameRandom(1, 255, 231)}, [6] = {gameRandom(1, 255, 78), gameRandom(1, 255, 564), gameRandom(1, 255, 22)}, [7] = {gameRandom(1, 255, 10), gameRandom(1, 255, 564), gameRandom(1, 255, 564)}, [8] = {gameRandom(1, 255, 5), gameRandom(1, 255, 564), gameRandom(1, 255, 85)}, [9] = {gameRandom(1, 255, 32), gameRandom(1, 255, 564), gameRandom(1, 255, 86)}, [10] = {gameRandom(1, 255, 123), gameRandom(1, 255, 546), gameRandom(1, 255, 54)}, [11] = {gameRandom(1, 255, 243), gameRandom(1, 255, 45), gameRandom(1, 255, 864)}, [12] = {gameRandom(1, 255, 69), gameRandom(1, 255, 666), gameRandom(1, 255, 69)}, [13] = {gameRandom(1, 255, 96), gameRandom(1, 255, 54), gameRandom(1, 255, 87)}, [14] = {gameRandom(1, 255, 52), gameRandom(1, 255, 752), gameRandom(1, 255, 645)}, [15] = {gameRandom(1, 255, 47), gameRandom(1, 255, 321), gameRandom(1, 255, 645)}, [16] = {gameRandom(1, 255, 21), gameRandom(1, 255, 322), gameRandom(1, 255, 666)}, [17] = {gameRandom(1, 255, 6), gameRandom(1, 255, 585), gameRandom(1, 255, 45)}, [18] = {gameRandom(1, 255, 2), gameRandom(1, 255, 84), gameRandom(1, 255, 4568)}, [19] = {gameRandom(1, 255, 4), gameRandom(1, 255, 645), gameRandom(1, 255, 545)}, [20] = {gameRandom(1, 255, 122), gameRandom(1, 255, 64), gameRandom(1, 255, 546)}, [21] = {gameRandom(1, 255, 91), gameRandom(1, 255, 684), gameRandom(1, 255, 458)}, [22] = {gameRandom(1, 255, 111), gameRandom(1, 255, 514), gameRandom(1, 255, 125)}, [23] = {gameRandom(1, 255, 223), gameRandom(1, 255, 864), gameRandom(1, 255, 333)}, [24] = {gameRandom(1, 255, 36), gameRandom(1, 255, 352), gameRandom(1, 255, 254)} } else GNL.color = {} local index = 1 while index <= 24 do GNL.color[index] = colors.number index = index + 1 end end if flags.restartRollControl then rollControl[1] = true rollControl[2] = true rollControl[3] = true rollControl[4] = true rollControl[5] = true rollControl[6] = true rollControl[7] = true rollControl[8] = true rollControl[9] = true rollControl[10] = true rollControl[11] = true rollControl[12] = true rollControl[13] = true rollControl[14] = true rollControl[15] = true rollControl[16] = true rollControl[17] = true rollControl[18] = true rollControl[19] = true rollControl[20] = true rollControl[21] = true rollControl[22] = true rollControl[23] = true rollControl[24] = true flags.restartRollControl = false end if rollControl[1] then tempGNL.GNL1_A = gameRandom(-10, 10, 544, main.difficulty) tempGNL.GNL1_B = gameRandom(-5, 13, 197, main.difficulty) rollControl[1] = false GNL.problems[1] = tostring(tempGNL.GNL1_A.."+"..tempGNL.GNL1_B) GNL.answers[1] = tempGNL.GNL1_A + tempGNL.GNL1_B end if rollControl[2] then tempGNL.GNL2_A = gameRandom(-5, 5, 543, main.difficulty) tempGNL.GNL2_B = gameRandom(1, 16, 546, main.difficulty) rollControl[2] = false GNL.problems[2] = tostring(tempGNL.GNL2_A.."-"..tempGNL.GNL2_B) GNL.answers[2] = tempGNL.GNL2_A -tempGNL.GNL2_B end if rollControl[3] then tempGNL.GNL3_A = gameRandom(-7, 5, 5455, main.difficulty) tempGNL.GNL3_B = gameRandom(-64, 55, 53415, main.difficulty) rollControl[3] = false GNL.problems[3] = tostring(tempGNL.GNL3_A.."+"..tempGNL.GNL3_B) GNL.answers[3] = tempGNL.GNL3_A + tempGNL.GNL3_B end if rollControl[4] then tempGNL.GNL4_A = gameRandom(-14, 15, 654, main.difficulty) tempGNL.GNL4_B = gameRandom(3, 8, 64546, main.difficulty) rollControl[4] = false GNL.problems[4] = tostring(tempGNL.GNL4_A.."-"..tempGNL.GNL4_B) GNL.answers[4] = tempGNL.GNL4_A - tempGNL.GNL4_B end if rollControl[5] then tempGNL.GNL5_A = math.floor(main.difficulty * math.random(-9, 2)) math.randomseed((os.clock() + main.randomEnsurer)*7) tempGNL.GNL5_B = math.floor(main.difficulty * math.random(-2, 16)) math.randomseed((os.clock() + main.randomEnsurer)*8) rollControl[5] = false GNL.problems[5] = tostring(tempGNL.GNL5_A.."+"..tempGNL.GNL5_B) GNL.answers[5] = tempGNL.GNL5_A + tempGNL.GNL5_B end if rollControl[6] then tempGNL.GNL6_A = math.floor(main.difficulty * math.random(-5, 10)) math.randomseed((os.clock() + main.randomEnsurer)*9) tempGNL.GNL6_B = math.floor(main.difficulty * math.random(1, 16)) math.randomseed((os.clock() + main.randomEnsurer)/2) rollControl[6] = false GNL.problems[6] = tostring(tempGNL.GNL6_A.."x"..tempGNL.GNL6_B) GNL.answers[6] = tempGNL.GNL6_A * tempGNL.GNL6_B end if rollControl[7] then tempGNL.GNL7_A = math.floor(main.difficulty * math.random(-2, 21)) math.randomseed((os.clock() + main.randomEnsurer)/3) tempGNL.GNL7_B = math.floor(main.difficulty * math.random(-2, 10)) math.randomseed((os.clock() + main.randomEnsurer)/4) rollControl[7] = false GNL.problems[7] = tostring(tempGNL.GNL7_A.."x"..tempGNL.GNL7_B) GNL.answers[7] = tempGNL.GNL7_A * tempGNL.GNL7_B end if rollControl[8] then tempGNL.GNL8_A = math.floor(main.difficulty * math.random(-2, 15)) math.randomseed((os.clock() + main.randomEnsurer)/5) tempGNL.GNL8_B = math.floor(main.difficulty * math.random(3, 8)) math.randomseed((os.clock() + main.randomEnsurer)/6) rollControl[8] = false GNL.problems[8] = tostring(tempGNL.GNL8_A.."x"..tempGNL.GNL8_B) GNL.answers[8] = tempGNL.GNL8_A * tempGNL.GNL8_B end if rollControl[9] then tempGNL.GNL9_A = math.floor(main.difficulty * math.random(-5, 5)) math.randomseed((os.clock() + main.randomEnsurer)/7) tempGNL.GNL9_B = math.floor(main.difficulty * math.random(0, 2)) math.randomseed((os.clock() + main.randomEnsurer)/8) rollControl[9] = false GNL.problems[9] = tostring(tempGNL.GNL9_A.."x"..tempGNL.GNL9_B) GNL.answers[9] = tempGNL.GNL9_A * tempGNL.GNL9_B end if rollControl[10] then tempGNL.GNL10_A = math.floor(main.difficulty * math.random(-2, 3)) math.randomseed((os.clock() + main.randomEnsurer)/9) tempGNL.GNL10_B = math.floor(main.difficulty * math.random(4, 5)) math.randomseed((os.clock() + main.randomEnsurer)+12) rollControl[10] = false GNL.problems[10] = tostring(tempGNL.GNL10_A.."x"..tempGNL.GNL10_B) GNL.answers[10] = tempGNL.GNL10_A * tempGNL.GNL10_B end if rollControl[11] then tempGNL.GNL11_A = math.floor(main.difficulty * math.random(-1, 9)) math.randomseed((os.clock() + main.randomEnsurer)+13) tempGNL.GNL11_B = math.floor(main.difficulty * math.random(1, 6)) math.randomseed((os.clock() + main.randomEnsurer)+14) rollControl[11] = false GNL.problems[11] = tostring(tempGNL.GNL11_A.."x"..tempGNL.GNL11_B) GNL.answers[11] = tempGNL.GNL11_A * tempGNL.GNL11_B end if rollControl[12] then tempGNL.GNL12_A = math.floor(main.difficulty * math.random(1, 5)) math.randomseed((os.clock() + main.randomEnsurer)+15) tempGNL.GNL12_B = math.floor(main.difficulty * math.random(0, 3)) math.randomseed((os.clock() + main.randomEnsurer)+16) rollControl[12] = false GNL.problems[12] = tostring(tempGNL.GNL12_A.."x"..tempGNL.GNL12_B) GNL.answers[12] = tempGNL.GNL12_A * tempGNL.GNL12_B end if rollControl[13] then tempGNL.GNL13_A = math.floor(main.difficulty * math.random(1, 9)) math.randomseed((os.clock() + main.randomEnsurer)+17) tempGNL.GNL13_B = math.floor(main.difficulty * math.random(1, 3)) math.randomseed((os.clock() + main.randomEnsurer)+18) rollControl[13] = false GNL.problems[13] = tostring(tempGNL.GNL13_A.."x"..tempGNL.GNL13_B) GNL.answers[13] = tempGNL.GNL13_A * tempGNL.GNL13_B end if rollControl[14] then tempGNL.GNL14_A = math.floor(main.difficulty * math.random(-1, 10)) math.randomseed((os.clock() + main.randomEnsurer)+19) tempGNL.GNL14_B = math.floor(main.difficulty * math.random(1, 10)) math.randomseed((os.clock() + main.randomEnsurer)-10) rollControl[14] = false GNL.problems[14] = tostring(tempGNL.GNL14_A.."x"..tempGNL.GNL14_B) GNL.answers[14] = tempGNL.GNL14_A * tempGNL.GNL14_B end if rollControl[15] then tempGNL.GNL15_A = math.floor(main.difficulty * math.random(7, 10)) math.randomseed((os.clock() + main.randomEnsurer)-20) tempGNL.GNL15_B = math.floor(main.difficulty * math.random(2, 8)) math.randomseed((os.clock() + main.randomEnsurer)-30) rollControl[15] = false GNL.problems[15] = tostring(tempGNL.GNL15_A.."x"..tempGNL.GNL15_B) GNL.answers[15] = tempGNL.GNL15_A * tempGNL.GNL15_B end if rollControl[16] then tempGNL.GNL16_A = math.floor(main.difficulty * math.random(3, 6)) math.randomseed((os.clock() + main.randomEnsurer)-40) tempGNL.GNL16_B = math.floor(main.difficulty * math.random(-6, 10)) math.randomseed((os.clock() + main.randomEnsurer)-50) rollControl[16] = false GNL.problems[16] = tostring(tempGNL.GNL16_A.."/"..tempGNL.GNL16_B) GNL.answers[16] = math.floor(tempGNL.GNL16_A / tempGNL.GNL16_B) end if rollControl[17] then tempGNL.GNL17_A = math.floor(main.difficulty * math.random(-2, 9)) math.randomseed((os.clock() + main.randomEnsurer)-60) tempGNL.GNL17_B = math.floor(main.difficulty * math.random(3, 56)) math.randomseed((os.clock() + main.randomEnsurer)-70) rollControl[17] = false GNL.problems[17] = tostring(tempGNL.GNL17_A.."/"..tempGNL.GNL17_B) GNL.answers[17] = math.floor(tempGNL.GNL17_A / tempGNL.GNL17_B) end if rollControl[18] then tempGNL.GNL18_A = math.floor(main.difficulty * math.random(-5, 11)) math.randomseed((os.clock() + main.randomEnsurer)-80) tempGNL.GNL18_B = math.floor(main.difficulty * math.random(10, 13)) math.randomseed((os.clock() + main.randomEnsurer)-90) rollControl[18] = false GNL.problems[18] = tostring(tempGNL.GNL18_A.."/"..tempGNL.GNL18_B) GNL.answers[18] = math.floor(tempGNL.GNL18_A / tempGNL.GNL18_B) end if rollControl[19] then tempGNL.GNL19_A = math.floor(main.difficulty * math.random(4, 10)) math.randomseed((os.clock() + main.randomEnsurer)+10) tempGNL.GNL19_B = math.floor(main.difficulty * math.random(1, 10)) math.randomseed((os.clock() + main.randomEnsurer)+20) rollControl[19] = false GNL.problems[19] = tostring(tempGNL.GNL19_A.."/"..tempGNL.GNL19_B) GNL.answers[19] = math.floor(tempGNL.GNL19_A / tempGNL.GNL19_B) end if rollControl[20] then tempGNL.GNL20_A = math.floor(main.difficulty * math.random(1, 16)) math.randomseed((os.clock() + main.randomEnsurer)+30) tempGNL.GNL20_B = math.floor(main.difficulty * math.random(0, 1)) math.randomseed((os.clock() + main.randomEnsurer)+40) rollControl[20] = false GNL.problems[20] = tostring(tempGNL.GNL20_A.."/"..tempGNL.GNL20_B) GNL.answers[20] = math.floor(tempGNL.GNL20_A / tempGNL.GNL20_B) end if rollControl[21] then tempGNL.GNL21_A = math.floor(main.difficulty * math.random(-1, 13)) math.randomseed((os.clock() + main.randomEnsurer)+50) tempGNL.GNL21_B = math.floor(main.difficulty * math.random(1, 4)) math.randomseed((os.clock() + main.randomEnsurer)+560) rollControl[21] = false GNL.problems[21] = tostring(tempGNL.GNL21_A.."x"..tempGNL.GNL21_B) GNL.answers[21] = tempGNL.GNL21_A * tempGNL.GNL21_B end if rollControl[22] then tempGNL.GNL22_A = math.floor(main.difficulty * math.random(-7, 12)) math.randomseed((os.clock() + main.randomEnsurer)+6) tempGNL.GNL22_B = math.floor(main.difficulty * math.random(1, 20)) math.randomseed((os.clock() + main.randomEnsurer)+60) rollControl[22] = false GNL.problems[22] = tostring(tempGNL.GNL22_A.."-"..tempGNL.GNL22_B) GNL.answers[22] = tempGNL.GNL22_A - tempGNL.GNL22_B end if rollControl[23] then tempGNL.GNL23_A = math.floor(main.difficulty * math.random(30, 60)) math.randomseed((os.clock() + main.randomEnsurer)+70) tempGNL.GNL23_B = math.floor(main.difficulty * math.random(-5, 30)) math.randomseed((os.clock() + main.randomEnsurer)+80) rollControl[23] = false GNL.problems[23] = tostring(tempGNL.GNL23_A.."-"..tempGNL.GNL23_B) GNL.answers[23] = tempGNL.GNL23_A - tempGNL.GNL23_B end if rollControl[24] then tempGNL.GNL24_A = math.floor(main.difficulty * math.random(-1, 3)) math.randomseed((os.clock() + main.randomEnsurer)+90) tempGNL.GNL24_B = math.floor(main.difficulty * math.random(1, 10)) math.randomseed((os.clock() + main.randomEnsurer)*10) rollControl[24] = false GNL.problems[24] = tostring(tempGNL.GNL24_A.."x"..tempGNL.GNL24_B) GNL.answers[24] = tempGNL.GNL24_A * tempGNL.GNL24_B end flags.reload = false elseif player.dead then if _loc.deathAnim <= 1 then graphics.pacman_death1:update(dt) _loc.deathAnim = _loc.deathAnim + dt else flags.gameover = true end menu.gameover.selected = menu.gameover.index if main.flags.debug.tools then _loc.randomCounter = _loc.randomCounter + 1 end if flags.confirmSubmit then local file_scores = love.filesystem.newFile("scores") file_scores:open("a") file_scores:write((_loc.username[1].._loc.username[2].._loc.username[3].._loc.username[4].._loc.username[5].._loc.username[6].."\n"..player.score)) file_scores:close() return "quit" end else graphics.pacman_anim:update(dt) player.act_y = player.act_y - math.floor(((player.act_y - player.grid_y)) * player.speed * dt) player.act_x = player.act_x - math.floor(((player.act_x - player.grid_x)) * player.speed * dt) red.act_y = red.act_y - ((red.act_y - red.grid_y) * red.speed * dt) red.act_x = red.act_x - ((red.act_x - red.grid_x) * red.speed * dt) blue.act_y = blue.act_y - ((blue.act_y - blue.grid_y) * blue.speed * dt) blue.act_x = blue.act_x - ((blue.act_x - blue.grid_x) * blue.speed * dt) orange.act_y = orange.act_y - ((orange.act_y - orange.grid_y) * orange.speed * dt) orange.act_x = orange.act_x - ((orange.act_x - orange.grid_x) * orange.speed * dt) green.act_y = green.act_y - ((green.act_y - green.grid_y) * green.speed * dt) green.act_x = green.act_x - ((green.act_x - green.grid_x) * green.speed * dt) if player.scorePrint < player.score then player.scorePrint = player.scorePrint + _loc.scoreAcc elseif player.scorePrint > player.score then player.scorePrint = player.scorePrint - _loc.scoreAcc end if _loc.levelCheck.claimed >= 24 then _loc.levelCheck.claimed = 0 gameFunc.newLevel() end if player.score == 0 then colors.scoreColor = {200, 200, 200, 255} elseif player.score < 0 then colors.scoreColor = {239, 64, 35, 255} elseif player.score > 0 then colors.scoreColor = {67, 120, 188, 255} end if flags.changeStageColor then if main.difficulty <= 3 then colors.stage = GNL.color[GNL.current] end if _loc.actStageColor[1] < colors.stage[1] then _loc.actStageColor[1] = _loc.actStageColor[1] + _loc.colorChange else _loc.actStageColor[1] = _loc.actStageColor[1] - _loc.colorChange end if _loc.actStageColor[2] < colors.stage[2] then _loc.actStageColor[2] = _loc.actStageColor[2] + _loc.colorChange else _loc.actStageColor[2] = _loc.actStageColor[2] - _loc.colorChange end if _loc.actStageColor[3] < colors.stage[3] then _loc.actStageColor[3] = _loc.actStageColor[3] + _loc.colorChange else _loc.actStageColor[3] = _loc.actStageColor[3] - _loc.colorChange end end if flags.newPoint then GNL.current = gameFunc.newPoint() local a = 1 local isNumber = false if type(GNL.current) == type(a) then isNumber = true end assert(isNumber, "No new number issued.") flags.newPoint = false end if flags.newDest then red.grid_x = positions.X[red.destPoint] red.grid_y = positions.Y[red.destPoint] blue.grid_x = positions.X[blue.destPoint] blue.grid_y = positions.Y[blue.destPoint] orange.grid_x = positions.X[orange.destPoint] orange.grid_y = positions.Y[orange.destPoint] green.grid_x = positions.X[green.destPoint] green.grid_y = positions.Y[green.destPoint] red.destPoint, blue.destPoint, orange.destPoint, green.destPoint = gameFunc.newGhostDest() local a = 1 local isNumber = false if type(red.destPoint) == type(a) then isNumber = true if type(blue.destPoint) == type(a) then isNumber = true if type(orange.destPoint) == type(a) then isNumber = true if type(green.destPoint) == type(a) then isNumber = true else isNumber = false end else isNumber = false end else isNumber = false end else isNumber = false end assert(isNumber, "No new number issued.") flags.newDest = false end if _loc.scoreTileIndex == 10 and flags.scoreTileUp then _loc.scoreTileIndex = 1 flags.scoreTileUp = false elseif _loc.scoreTileIndex == 10 and not flags.scoreTileUp then _loc.scoreTileIndex = 1 flags.scoreTileUp = true end if flags.scoreTileUp then _loc.scoreTileIndex = _loc.scoreTileIndex + 1 colors.scoreTile[1] = colors.scoreTile[1] + 4 colors.scoreTile[2] = colors.scoreTile[2] + 8 colors.scoreTile[3] = colors.scoreTile[3] + 16 else _loc.scoreTileIndex = _loc.scoreTileIndex + 1 colors.scoreTile[1] = colors.scoreTile[1] - 4 colors.scoreTile[2] = colors.scoreTile[2] - 8 colors.scoreTile[3] = colors.scoreTile[3] - 16 end if _loc.point_rot > 6 then _loc.point_rot = 0 end _loc.point_rot = _loc.point_rot + (6 * dt) if flags.renewTime then gameFunc.renewTime() flags.renewTime = false end player.time = player.time - dt if player.time <= 0 then flags.renewTime = true end if flags.quake then gameFunc.funcQuake() if _loc.quakeTime <= 0 then flags.quake = false _loc.quake = 0 end end if flags.debug.canDie then if player.grid_y == red.grid_y then if player.grid_x == red.grid_x then player.dead = true end elseif player.grid_y == blue.grid_y then if player.grid_x == blue.grid_x then player.dead = true end elseif player.grid_y == orange.grid_y then if player.grid_x == orange.grid_x then player.dead = true end elseif player.grid_y == green.grid_y then if player.grid_x == green.grid_x then player.dead = true end end end if flags.ghostOut then if _loc.newMapCheck == 0 then map = { {n,n,n,n,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {n,n,n,n,1,6,0,0,0,0,6,0,0,0,6,0,0,0,6,1}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,2.2,6,0,0,0,0,6,0,0,0,6,0,0,0,6,2.0}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,1,6,0,0,6,0,6,0,0,0,6,0,6,1,0,1}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,1}, {n,n,n,n,1,0,1,0,0,1,0,1,0,0,0,1,0,1,0,1}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,1,1,0,1,0,1}, {n,n,n,n,1,0,1,1,6,0,6,0,0,0,0,0,6,1,0,1}, {n,n,n,n,1,0,1,1,0,1,0,1,1,1,0,1,0,1,0,1}, {n,n,n,n,2.1,6,0,0,6,1,0,1,0,1,0,1,6,0,6,2.3}, {n,n,n,n,1,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1}, {n,n,n,n,1,6,0,0,0,0,6,0,0,0,6,0,0,0,6,1}, {n,n,n,n,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} } _loc.newMapCheck = 1 end end if _loc.levelColor == 1 then colors.levelColor = {gameRandom((127-(_loc.levelColorCheck*_loc.levelColorCheckMult)),(127+(_loc.levelColorCheck*_loc.levelColorCheckMult)), 54+funcVar.game.gameRandom_calls), gameRandom((127-(_loc.levelColorCheck*_loc.levelColorCheckMult)),(127+(_loc.levelColorCheck*_loc.levelColorCheckMult)), 697+funcVar.game.gameRandom_calls), gameRandom((127-(_loc.levelColorCheck*_loc.levelColorCheckMult)),(127+(_loc.levelColorCheck*_loc.levelColorCheckMult)), 6452+funcVar.game.gameRandom_calls)} end if flags.levelTransition then graphics.levelTransition:update(dt) graphics.levelTransition:setColors(255, 255, 255, 255, 255, 255, 255, 0) end if _loc.levelTransition_count > 0 then _loc.levelTransition_count = _loc.levelTransition_count -dt else _loc.levelTransition_count = 0 flags.levelTransition = false graphics.levelTransition:reset() end if flags.debug.doAutoMove then if _loc.moveCounter >= 0.2 then player.act_y = player.grid_y player.act_x = player.grid_x _loc.moveCounter = 0 end if flags.playerMoved then if player.grid_y == player.act_y then if player.grid_x == player.act_x then if player.orientation == "up" then if mathMap(0, -1) then player.grid_y = player.grid_y - _loc.cellSize flags.playerMoved = true end elseif player.orientation == "down" then if mathMap(0, 1) then player.grid_y = player.grid_y + _loc.cellSize flags.playerMoved = true end elseif player.orientation == "left" then if mathMap(-1, 0) then player.grid_x = player.grid_x - _loc.cellSize flags.playerMoved = true end elseif player.orientation == "right" then if mathMap(1, 0) then player.grid_x = player.grid_x + _loc.cellSize flags.playerMoved = true end end end end end _loc.moveCounter = _loc.moveCounter + dt end end end function game.draw() if flags.paused then love.graphics.setFont(main.graphics.fonts.SGtitle) love.graphics.setColor(255, 216, 0, 255) love.graphics.printf("PAUSED", 0, 40, 800, "center") love.graphics.setFont(main.graphics.fonts.SGheader2) if menu.pause.selected == 1 then love.graphics.setColor(colors.menu.selected) else love.graphics.setColor(colors.menu.normal) end love.graphics.printf("RESUME", 0, main.graphics.buttonLine * 2, 800, "center") if menu.pause.selected == 2 then love.graphics.setColor(colors.menu.selected) else love.graphics.setColor(colors.menu.normal) end love.graphics.printf("RESTART", 0, main.graphics.buttonLine * 3, 800, "center") if menu.pause.selected == 3 then love.graphics.setColor(colors.menu.selected) else love.graphics.setColor(colors.menu.normal) end love.graphics.printf("QUIT", 0, main.graphics.buttonLine * 4, 800, "center") love.graphics.setColor(main.colors.cursor) main.graphics.menuCursor:draw(main.graphics.miscSprites, 200, menu.pause.cursorPos[menu.pause.index], 0, 1.5, 1.5) elseif flags.reload then elseif player.dead and not flags.gameover then graphics.pacman_death1:draw(graphics.sprites, main.window_middleX, main.window_middleY, 0, 5,5, 22/2, 22/2) elseif flags.gameover then love.graphics.setFont(main.graphics.fonts.SGtitle) love.graphics.setColor(156, 54, 33) love.graphics.printf("GAME OVER", 0, 40, 800, "center") love.graphics.setFont(main.graphics.fonts.SGheader2) if menu.gameover.selected == 1 then love.graphics.setColor(colors.menu.selected) else love.graphics.setColor(colors.menu.normal) end love.graphics.printf("RESTART", 0, main.graphics.buttonLine * 2, 800, "center") if menu.gameover.selected == 2 then love.graphics.setColor(colors.menu.selected) else love.graphics.setColor(colors.menu.normal) end love.graphics.printf("SUBMIT", 0, main.graphics.buttonLine * 3, 800, "center") love.graphics.setColor(151, 27, 30) main.graphics.menuCursor:draw(main.graphics.miscSprites, 200, menu.gameover.cursorPos[menu.gameover.index], 0, 1.5, 1.5) if flags.submit then love.graphics.setColor(colors.default) love.graphics.setFont(main.graphics.fonts.SGheader) love.graphics.printf(_loc.username[1].._loc.username[2].._loc.username[3].._loc.username[4].._loc.username[5].._loc.username[6] or "", -30, main.graphics.buttonLine * 4, 800, "center") love.graphics.printf("PRESS ENTER TO SUBMIT!", 30, main.graphics.buttonLine * 5, 800, "center") end else love.graphics.setColor(_loc.actStageColor, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 1 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)+_loc.quake, (y * _loc.cellSize)-_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(_loc.actStageColor[1], _loc.actStageColor[2], _loc.actStageColor[3], 4) for y=1, #map do for x=1, #map[y] do if map[y][x] == 0 or map[y][x] == 6 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)-_loc.quake, (y * _loc.cellSize)+_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(colors.ghostWall, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 3 then love.graphics.rectangle("fill", (x * _loc.cellSize)-_loc.quake, (y * _loc.cellSize)-_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(colors.ghostFloor, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 4 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)-_loc.quake, (y * _loc.cellSize)+_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(colors.warpColor, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 2.0 or map[y][x] == 2.1 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)+(_loc.quake*-1), (y * _loc.cellSize)-_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(colors.warpColor2, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 2.2 or map[y][x] == 2.3 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)+(_loc.quake*-1), (y * _loc.cellSize)-_loc.quake, _loc.cellSize, _loc.cellSize) end end end love.graphics.setColor(colors.scoreTile, 255) for y=1, #map do for x=1, #map[y] do if map[y][x] == 5 then love.graphics.rectangle(options.gridMode, (x * _loc.cellSize)+_loc.quake, (y * _loc.cellSize)-_loc.quake, _loc.cellSize, _loc.cellSize) end end end if true then local index = 1 while index <= 24 do if points[index] then love.graphics.setColor(colors.scoreTile) graphics.pac_point:draw(graphics.sprites, positions.X[index]+16, positions.Y[index]+20, _loc.point_rot, 2,2, 22/2,22/2) love.graphics.setColor(GNL.color[index], 255) love.graphics.print(GNL.answers[index], positions.X[index], positions.Y[index], 0, 1, 1) else love.graphics.setColor(GNL.color[index][1], GNL.color[index][2],GNL.color[index][3], 10) love.graphics.print(GNL.answers[index], positions.X[index], positions.Y[index], 0, 1, 1) end index = index +1 end end love.graphics.setColor(colors.default) love.graphics.setColor(colors.scoreColor) love.graphics.print("Score: "..math.floor(player.scorePrint), 5, (_loc.labelLine * 2)) love.graphics.setColor(GNL.color[GNL.current][1]-80,GNL.color[GNL.current][2]+80,GNL.color[GNL.current][3]-20,255) love.graphics.rectangle("fill", main.window_middleX-240, -40, 16*32, 80) love.graphics.setColor(GNL.color[GNL.current],255) love.graphics.setFont(main.graphics.fonts.REGheader) love.graphics.printf("Answer = "..GNL.problems[GNL.current], 0, (_loc.labelLine * 0.3), 800, "center") love.graphics.setFont(main.graphics.fonts.REGnormal) love.graphics.setColor(colors.levelColor) love.graphics.print("Level: "..player.level, 5, (_loc.labelLine * 1)) love.graphics.setColor(colors.default) love.graphics.print("Time left: "..math.ceil(player.time), 5, (_loc.labelLine * 3)) if main.difficulty == 1 then love.graphics.setColor(colors.redGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 4)) love.graphics.setColor(GNL.color[red.destPoint], 255) love.graphics.print(GNL.answers[red.destPoint], 40, (_loc.labelLine * 5)) love.graphics.setColor(colors.blueGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 6)) love.graphics.setColor(GNL.color[blue.destPoint], 255) love.graphics.print(GNL.answers[blue.destPoint], 40, (_loc.labelLine * 7)) love.graphics.setColor(colors.orangeGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 8)) love.graphics.setColor(GNL.color[orange.destPoint], 255) love.graphics.print(GNL.answers[orange.destPoint], 40, (_loc.labelLine * 9)) love.graphics.setColor(colors.greenGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 10)) love.graphics.setColor(GNL.color[green.destPoint], 255) love.graphics.print(GNL.answers[green.destPoint], 40, (_loc.labelLine * 11)) else love.graphics.setColor(colors.redGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 5)) love.graphics.setColor(GNL.color[red.destPoint], 255) love.graphics.print(GNL.problems[red.destPoint], 40, (_loc.labelLine * 6)) love.graphics.setColor(colors.blueGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 7)) love.graphics.setColor(GNL.color[blue.destPoint], 255) love.graphics.print(GNL.problems[blue.destPoint], 40, (_loc.labelLine * 8)) love.graphics.setColor(colors.orangeGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 9)) love.graphics.setColor(GNL.color[orange.destPoint], 255) love.graphics.print(GNL.problems[orange.destPoint], 40, (_loc.labelLine * 10)) love.graphics.setColor(colors.greenGhost, 255) love.graphics.print("Watch for: ", 5, (_loc.labelLine * 11)) love.graphics.setColor(GNL.color[green.destPoint], 255) love.graphics.print(GNL.problems[green.destPoint], 40, (_loc.labelLine * 12)) end -- love.graphics.setColor(colors.default) if player.orientation == "up" then graphics.pacman_anim:draw(graphics.sprites, player.act_x-2, player.act_y-2, 1.58, main.actor_scaleX, main.actor_scaleY, 0, 22) elseif player.orientation == "down" then graphics.pacman_anim:draw(graphics.sprites, player.act_x-2, player.act_y-2, -1.58, main.actor_scaleX, main.actor_scaleY, 22, 0) elseif player.orientation == "left" then graphics.pacman_anim:draw(graphics.sprites, player.act_x-2, player.act_y-2, 0, main.actor_scaleX, main.actor_scaleY) elseif player.orientation == "right" then graphics.pacman_anim:draw(graphics.sprites, player.act_x-2, player.act_y-2, math.pi, main.actor_scaleX, main.actor_scaleY, 22, 22) end -- love.graphics.setColor(colors.redGhost) graphics.red_anim:draw(graphics.sprites, red.act_x, red.act_y, 0, main.actor_scaleX, main.actor_scaleY) love.graphics.setColor(colors.blueGhost) graphics.blue_anim:draw(graphics.sprites, blue.act_x, blue.act_y, 0, main.actor_scaleX, main.actor_scaleY) love.graphics.setColor(colors.orangeGhost) graphics.orange_anim:draw(graphics.sprites, orange.act_x, orange.act_y, 0, main.actor_scaleX, main.actor_scaleY) love.graphics.setColor(colors.greenGhost) graphics.green_anim:draw(graphics.sprites, green.act_x, green.act_y, 0, main.actor_scaleX, main.actor_scaleY) -- if flags.levelTransition then love.graphics.setColor(colors.levelColor) love.graphics.draw(graphics.levelTransition, love.graphics.getWidth() * 0.5, love.graphics.getHeight() * 0.5, _loc.point_rot) end end love.graphics.setColor(colors.default) love.graphics.setFont(main.graphics.fonts.REGnormal) if main.flags.debug.tools then love.graphics.print("Temp monitor: "..tostring(randomValue[1]).."|"..tostring(randomValue[2]).."|"..tostring(randomValue[3]).."|"..tostring(randomValue[4]).."|"..tostring(randomValue[5]), 0, 1) end end function game.keypressed(key) if not flags.submit then if flags.paused then if key == "down" then if menu.pause.index < 3 then menu.pause.index = menu.pause.index + 1 end elseif key == "up" then if menu.pause.index > 1 then menu.pause.index = menu.pause.index - 1 end end if key == "return" then if menu.pause.index == 1 then flags.paused = false elseif menu.pause.index == 2 then flags.restart = true elseif menu.pause.index == 3 then flags.quit = true end end elseif flags.reload then elseif flags.gameover then if key == "down" then if menu.gameover.index < 2 then menu.gameover.index = menu.gameover.index + 1 end elseif key == "up" then if menu.gameover.index > 1 then menu.gameover.index = menu.gameover.index - 1 end end if key == "return" then if menu.gameover.index == 1 then flags.restart = true elseif menu.gameover.index == 2 then flags.submit = true end end else if key == "up" then if mathMap(0, -1) then player.grid_y = player.grid_y - _loc.cellSize player.orientation = "up" flags.playerMoved = true end elseif key == "down" then if mathMap(0, 1) then player.grid_y = player.grid_y + _loc.cellSize player.orientation = "down" flags.playerMoved = true end elseif key == "left" then if mathMap(-1, 0) then player.grid_x = player.grid_x - _loc.cellSize player.orientation = "left" flags.playerMoved = true end elseif key == "right" then if mathMap(1, 0) then player.grid_x = player.grid_x + _loc.cellSize player.orientation = "right" flags.playerMoved = true end end if key == "space" then local act = playerAct() if main.flags.debug.tools then _loc.act = act end if act == "right" then flags.newPoint = true flags.sound.upScore = true gameFunc.playSound() if main.difficulty == 1 then player.score = player.score + 500 elseif main.difficulty == 2 then player.score = player.score + 800 elseif main.difficulty == 3 then player.score = player.score + 1200 end elseif act == "wrong" then flags.newDest = true flags.renewTime = true flags.quake = true _loc.quakeTime = 10 flags.sound.downScore = true gameFunc.playSound() if main.difficulty >= 1 then player.score = player.score - 250 elseif main.difficulty >= 2 then player.score = player.score - 400 elseif main.difficulty >= 3 then player.score = player.score - 600 end end end if main.flags.debug.tools then if key == "q" then player.dead = false end if love.keyboard.isDown("lctrl") or love.keyboard.isDown("rctrl") then if key == "up" then _loc.levelCheck.claimed = _loc.levelCheck.claimed + 1 elseif key == "down" then _loc.levelCheck.claimed = _loc.levelCheck.claimed - 1 end end end if key == "return" then flags.renewTime = true end if key == "escape" then if flags.paused then flags.paused = false else flags.paused = true end end end else if key == "backspace" then _loc.username[_loc.usernameIndex] = "" if _loc.usernameIndex > 1 then _loc.usernameIndex = _loc.usernameIndex - 1 end elseif key == "return" then flags.confirmSubmit = true else local keyConverted local key = string.upper(key) _loc.username[_loc.usernameIndex] = key if _loc.usernameIndex < 6 then _loc.usernameIndex = _loc.usernameIndex + 1 end end end end function mathMap(x, y) funcVar.game.mathMap_calls = funcVar.game.mathMap_calls + 1 if map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 0 or map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 6 then return true elseif map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 2.0 then player.grid_y = 128 player.grid_x = 640 elseif map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 2.1 then player.grid_y = 128 player.grid_x = 160 elseif map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 2.2 then player.grid_y = 416 player.grid_x = 640 elseif map[(player.grid_y / _loc.cellSize) + y][(player.grid_x / _loc.cellSize) + x] == 2.3 then player.grid_y = 416 player.grid_x = 160 end return false end function gameRandom(x, y, z, w) math.randomseed(69 * os.clock() + main.randomEnsurer * z) local a if w then a = math.floor(math.random(x, y) * w) else a = math.random(x, y) end funcVar.game.gameRandom_calls = funcVar.game.gameRandom_calls + 1 return a end function playerAct() if player.grid_x == positions.X[GNL.current] then if player.grid_y == positions.Y[GNL.current] then points[GNL.current] = false _loc.levelCheck.claimed = _loc.levelCheck.claimed + 1 return "right" end elseif map[(player.grid_y / _loc.cellSize)][(player.grid_x / _loc.cellSize)] == 6 then return "wrong" end return "not" end function game.unload() end function gameFunc.newPoint() funcVar.game.newPoint_calls = funcVar.game.newPoint_calls + 1 _loc.a = 0 local count = 1 while count <= 29 do count = count + 1 _loc.a = gameRandom(1, 24, funcVar.game.gameRandom_calls) if points[_loc.a] then return _loc.a end end return false end function gameFunc.newGhostDest() funcVar.game.newGhostDest_calls = funcVar.game.newGhostDest_calls + 1 local r, b, o, g r = gameRandom(1, 24, funcVar.game.newGhostDest_calls+1) b = gameRandom(1, 24, funcVar.game.newGhostDest_calls/2) o = gameRandom(1, 24, funcVar.game.newGhostDest_calls*3) g = gameRandom(1, 24, funcVar.game.newGhostDest_calls-4) return r, b, o, g end function gameFunc.renewTime() flags.newDest = true if main.difficulty >= 1 then player.time = 30 end if main.difficulty >= 2 then player.time = 20 end if main.difficulty >= 3 then player.time = 10 end if not flags.ghostOut then flags.ghostOut = true end end function gameFunc.funcQuake() funcVar.game.funcQuake_calls = funcVar.game.funcQuake_calls + 1 _loc.quake = gameRandom(-15, 15, funcVar.game.funcQuake_calls) _loc.quakeTime = _loc.quakeTime - 1 end function gameFunc.playSound() if main.flags.options.playSounds then if flags.sound.normal then end if flags.sound.upScore then sounds.scoreIncrease:play() flags.sound.upScore = false end if flags.sound.downScore then sounds.scoreDecrease:play() flags.sound.downScore = false end if flags.sound.death then sounds.death:play() flags.sound.death = false end end if main.flags.options.playMusic then if flags.sound.song then end end end function gameFunc.newLevel(x) if not x then x = 2 flags.levelTransition = true _loc.levelTransition_count = 3 main.difficulty = main.difficulty + 0.2 flags.reload = true flags.rollPoints = true flags.restartRollControl = true flags.newPoint = true end while 1 < x do player.level = player.level + 1 _loc.levelColor = 1 _loc.levelColorCheck = _loc.levelColorCheck + 2 flags.reload = true main.difficulty = main.difficulty + 0.2 x = x - 1 end local index = 24 while index > 0 do points[index] = true index = index - 1 end end return game
local aa = class("aa",cc.Node); function aa:ctor() self:init(); end function aa:init() local layer = cc.Layer:create(); self:addChild(layer); local title = cc.Label:createWithSystemFont("demoaaaaaaaaaa","",36); title:setPosition(display.cx,display.height-70); layer:add(title); local bb = require(".b.bb") self:addChild(bb:create()) end return aa;
-- TODO: finish datastore local package = { Name = "BanUtil", Description = "A plugin that adds a ban system to Commander, meant to be used with the command", Author = "7kayoh", Class = "Plugin", Category = "Server", Target = {} } function package.Target.extenderFunction(player, wrapper) end function package.Target:Init() package.Target.Settings = require(package.Core.Settings) package.API.extendPlayerWrapper(package.Target.extenderFunction) end return package
math.randomseed(getTickCount()) local magnetSlowDownTime = 7000 local markersRespawn = 5000 local marker = {} local markerTimer = {} local powerTypes = {} local fullPowerTypesList = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", "jump", "rock", "smoke", "nitro", "speed", "fly", "kmz", "minigun", } ------------------------ -- Gamemode Detection -- ------------------------ addEvent('onMapStarting') addEventHandler('onMapStarting', resourceRoot, function(mapInfo, mapOptions, gameOptions) currentMap = mapInfo.resname currentGameMode = string.upper(mapInfo.modename) if currentGameMode == "DESTRUCTION DERBY" then powerTypes = { "repair", "spikes", --"boost", "oil", "hay", "barrels", "ramp", "rocket", --"magnet", "jump", "rock", --"smoke", "nitro", --"speed", --"fly", --"kmz", "minigun", } elseif currentGameMode == "FREEROAM" then --race powerTypes = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", --"jump", "rock", "smoke", "nitro", "speed", "fly", "kmz", "minigun", } elseif currentGameMode == "SPRINT" then --also race powerTypes = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", --"jump", "rock", "smoke", "nitro", "speed", "fly", "kmz", "minigun", } elseif currentGameMode == "CAPTURE THE FLAG" then powerTypes = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", "jump", "rock", "smoke", "nitro", "speed", "fly", "kmz", "minigun", } elseif currentGameMode == "REACH THE FLAG" then powerTypes = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", "jump", "rock", "smoke", "nitro", "speed", "fly", --"kmz", "minigun", } elseif currentGameMode == "NEVER THE SAME" then powerTypes = { --"repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", --"jump", "rock", "smoke", --"nitro", "speed", "fly", "kmz", "minigun", } elseif currentGameMode == "SHOOTER" then powerTypes = { "repair", "spikes", "boost", "oil", "hay", "barrels", "ramp", "rocket", "magnet", "jump", "rock", "smoke", "nitro", "speed", "fly", --"kmz", "minigun", } end local powerTypes2 = checkItemsListInMapSettings() if powerTypes2 then powerTypes = powerTypes2 end triggerClientEvent(root, "getAllowedPowerTypes", resourceRoot, powerTypes) end ) function checkItemsListInMapSettings() local powerTypesList = get(currentMap..".coremarkers_items") if powerTypesList then local powerTypesTemp = {} for power in string.gmatch(powerTypesList, '([^,]+)') do --outputChatBox(power) local isPower = false for i=1, #fullPowerTypesList do if power == fullPowerTypesList[i] then isPower = true end end if isPower then --outputChatBox(power.." - checked, correct") table.insert(powerTypesTemp, power) else --outputChatBox("You have incorrect item '"..power.."' in your list, default items list will be used") return false end end if #powerTypesTemp ~= 0 then return powerTypesTemp end end end addEvent("requestAllowedPowerTypes", true) addEventHandler("requestAllowedPowerTypes", resourceRoot, function() triggerClientEvent(client, "getAllowedPowerTypes", resourceRoot, powerTypes) end ) -------------------- -- Initialization -- -------------------- addEventHandler("onResourceStart", resourceRoot, function() outputChatBox( '#ffffff"Core Markers" by #00dd22AleksCore #fffffflaunched.', root, 255, 0, 0, true) showText_Create() showText( 54, 201, 46, "Pick-up markers (boxes)\n @\nPress LMB or LCTRL button", 12000, all) setTimer( function() textItemSetColor(showText_Text, 54, 201, 46, 255) setTimer( function() textItemSetColor(showText_Text, 255, 255, 255, 255) end , 600, 1) end , 1000, 11) local coremarkers = getElementsByType("coremarker") if #coremarkers > 0 then --new way, coremarkers as elements placed into .map file using mrgreen map editor plugin for _, element in ipairs(coremarkers) do if getElementType(getElementParent(element)) == "map" then --for map editor. 'mapContainer' parent means objects created by map editor, ignore them local x, y, z = getElementPosition(element) spawnPickup(element, x, y, z) end end else --old way, coremarkers as solid boxes for _, object in ipairs(getElementsByType("object")) do if getElementModel(object) == 3798 then local x, y, z = getElementPosition(object) spawnPickup(object, x, y, z) end end end end ) --------------------------- -- Spawn Pickups Handler -- --------------------------- function spawnPickup(object, x, y, z, isRespawn) if not z then return end --for tests if object == nil or getElementType(object) == "coremarker" then object = createObject(3798, x, y, z+0.3) end local marker = createMarker(x, y, z-2.75, "cylinder", 3.3, 0, 255, 0, 255) local col = createColSphere(x, y, z, 3.7) setElementParent(object, col) setElementParent(marker, col) setObjectScale(object, 0.6) setElementCollisionsEnabled(object, false) addEventHandler("onColShapeHit", col, getRandomPower) ------------------------ -- Floating Animation -- ------------------------ local animationSpeed = 1 --the more the slower local box_posZ = 0.3 local amplitude = 0.1 local easing = "InOutQuad" moveObject(object, animationSpeed*1000, x, y, z+box_posZ+amplitude, 0, 0, 0, easing) setTimer( function() if isElement(object) then moveObject(object, animationSpeed*1000, x, y, z+box_posZ-amplitude, 0, 0, 0, easing) end end , animationSpeed*1000, 1) setTimer( function() if isElement(object) then moveObject(object, animationSpeed*1000, x, y, z+box_posZ+amplitude, 0, 0, 0, easing) setTimer( function() if isElement(object) then moveObject(object, animationSpeed*1000, x, y, z+box_posZ-amplitude, 0, 0, 0, easing) end end, animationSpeed*1000, 1) end end , animationSpeed*2000, 0) end --------------------------------------------- -- Markers/Pickups Handler - onColShapeHit -- --------------------------------------------- function getRandomPower(thePlayer) --onColShapeHit if getElementType(thePlayer) == "player" then if getElementData(thePlayer, "coremarkers_powerType") == false then setElementData(thePlayer, "coremarkers_powerType", true) triggerClientEvent(thePlayer, "getRandomPower", resourceRoot) if not source then return end --ignore markers respawn if getRandomPower triggered using bind (for tests only) --------------------- -- Markers Respawn -- --------------------- local x, y, z = getElementPosition(source) if currentMap and get(currentMap..".coremarkers_respawn") ~= false and type(get(currentMap..".coremarkers_respawn")) == "number" and get(currentMap..".coremarkers_respawn") >= 0 then setTimer(spawnPickup, get(currentMap..".coremarkers_respawn"), 1, nil, x, y, z, true) else setTimer(spawnPickup, markersRespawn, 1, nil, x, y, z, true) end removeEventHandler("onColShapeHit", source, getRandomPower) destroyElement(source) end end end --[[For tests only for k,v in pairs(getElementsByType("player")) do bindKey(v, "mouse5", "down", getRandomPower) end ]] ----------------------- -- Drop Spikes Event -- ----------------------- addEvent("dropSpikes", true) addEventHandler("dropSpikes", resourceRoot, function (x, y, z, rz) local spikes = createObject(2892, 0, 0, -200, 0, 0, rz+90) setObjectScale(spikes, 0.5) setElementPosition(spikes, x, y, z+0.1) local spikesCol = createColSphere(x, y, z, 2.6) setElementParent(spikes, spikesCol) addEventHandler("onColShapeHit", spikesCol, function(thePlayer) if getElementType(thePlayer) == "player" then if not getElementData(thePlayer, "coremarkers_isPlayerRektBySpikes") then local _, _, pz = getElementPosition(thePlayer) --player posZ local _, _, sz = getElementPosition(source) --spikes posZ if pz >= sz then setVehicleWheelStates(getPedOccupiedVehicle(thePlayer), 1, 1, 1, 1) setElementData(thePlayer, "coremarkers_isPlayerRektBySpikes", true, true) triggerClientEvent(thePlayer, "spikesTimerFunction", resourceRoot) destroyElement(source) end end end end ) end ) addEvent("onPlayerPickUpRacePickup", true) addEventHandler("onPlayerPickUpRacePickup", resourceRoot, function(pickupID, pickupType) if pickupType == "repair" then setElementData(source, "coremarkers_isPlayerRektBySpikes", false, true) end end ) --------------------- --- Drop Hay Event -- --------------------- addEvent("dropHay", true) addEventHandler("dropHay", resourceRoot, function (x, y, z, rz) createObject(3374, x, y, z+1.5, 0, 0, rz+90) end ) ---------------------- --- Drop Rock Event -- ---------------------- addEvent("dropRock", true) addEventHandler("dropRock", resourceRoot, function (x, y, z, rz) createObject(1305, x, y, z+1.5, 0, 0, rz+90) end ) ------------------ --- Smoke Event -- ------------------ addEvent("doSmoke", true) addEventHandler("doSmoke", resourceRoot, function (x, y, z, rz) local theVehicle = getPedOccupiedVehicle(client) triggerClientEvent(root, "createSmokeEffect", resourceRoot, x, y, z, rz, theVehicle) end ) ---------------------- --- Drop Ramp Event -- ---------------------- droppedRampTimer = {} addEvent("dropRamp", true) addEventHandler("dropRamp", resourceRoot, function (x, y, z, rz) local ramp = createObject(13645, x, y, z+0.4, 4, 0, rz) local rampCol = createColSphere(x, y, z+0.4, 4) attachElements(rampCol, ramp, 0, 1.5, 0) setElementParent(ramp, rampCol) addEventHandler("onColShapeHit", rampCol, function(hitElement) if getElementType(hitElement) == "player" then if not isTimer(droppedRampTimer[source]) then droppedRampTimer[source] = setTimer( function(col) if isElement(col) then destroyElement(col) end end , 30000, 1, source) end end end ) end ) -------------------------- --- Drop Barrels Events -- -------------------------- barrelCreator = {} addEvent("dropBarrels", true) addEventHandler("dropBarrels", resourceRoot, function (x, y, z, rz) local barrels = {} barrels[1] = createObject(1225, x, y, z+0.4) barrels[2] = createObject(1225, x+0.5, y+0.5, z+0.4) barrels[3] = createObject(1225, x-0.5, y-0.5, z+0.4) barrels[4] = createObject(1225, x+0.5, y-0.5, z+0.4) barrels[5] = createObject(1225, x-0.5, y+0.5, z+0.4) for _, barrel in ipairs(barrels) do barrelCreator[barrel] = client end end ) addEvent("destroyBarrel", true) addEventHandler("destroyBarrel", resourceRoot, function(barrel) if barrelCreator and barrelCreator[barrel] and isElement(barrelCreator[barrel]) then destroyElement(barrel) end end ) ---------------------------- -- Rocket Launcher Events -- ---------------------------- local rocketLauncher = {} addEvent("createRocketLauncher", true) addEventHandler("createRocketLauncher", resourceRoot, function(maxY) local theVehicle = getPedOccupiedVehicle(client) rocketLauncher[client] = createObject(360, 0, 0, -50) attachElements(rocketLauncher[client], theVehicle, -0.04, maxY-0.3, -0.14, 0, 0, 270) end ) addEvent("removeRocketLauncher", true) addEventHandler("removeRocketLauncher", resourceRoot, function() if rocketLauncher and isElement(rocketLauncher[client]) then destroyElement(rocketLauncher[client]) end end ) function vehicleChange(oldModel, newModel) if getElementType(source) == "vehicle" then local thePlayer = getVehicleOccupant(source) if isElement(thePlayer) and getElementData(thePlayer, "coremarkers_powerType") == "rocket" then local _, _, _, _, maxY, _ = getVehicleBoundingBox(newModel) attachElements(rocketLauncher[thePlayer], source, -0.04, maxY-0.3, -0.14, 0, 0, 270) end end end addEventHandler("onElementModelChange", resourceRoot, vehicleChange) --------------------- --- Drop Oil Event -- --------------------- addEvent("dropOil", true) addEventHandler("dropOil", resourceRoot, function (x, y, z, rz) local oil = createObject(2717, x, y, z, 90, 0, 0) setObjectScale(oil, 2) local oilCol = createColSphere(x, y, z+0.4, 2) setElementParent(oil, oilCol) setElementData(oilCol, "creator", client) --temporary protection for creator from oil setTimer( --remove protection after 2s function() if isElement(oilCol) then setElementData(oilCol, "creator", nil) end end , 2000, 1) addEventHandler("onColShapeHit", oilCol, function(thePlayer) if getElementType(thePlayer) == "player" then if getElementData(source, "creator") == thePlayer then return end if math.random(2) == 1 then setElementAngularVelocity(getPedOccupiedVehicle(thePlayer),0, 0, 0.146) else setElementAngularVelocity(getPedOccupiedVehicle(thePlayer),0, 0, -0.146) end destroyElement(source) end end ) end ) -------------------- -- Kamikaze Event -- -------------------- kamikazeTimer = {} preKamikazeTimer = {} addEvent("kamikazeMode", true) addEventHandler("kamikazeMode", resourceRoot, function() local theVehicle = getPedOccupiedVehicle(client) local marker = attachMarker(theVehicle, 6000, 255, 0, 0, 80) triggerClientEvent(root, "create3DSound", resourceRoot, theVehicle, "kmz.mp3") if isElement(kamikazeTimer[client]) then killTimer(kamikazeTimer[client]) end kamikazeTimer[client] = setTimer( function(theVehicle, thePlayer) if not isElement(theVehicle) then return end setElementData(thePlayer, "kamikaze", true, true) local x, y, z = getElementPosition(theVehicle) createExplosion(x, y, z, 10, thePlayer) createExplosion(x+3, y, z, 10, thePlayer) createExplosion(x-3, y, z, 10, thePlayer) createExplosion(x, y+3, z, 10, thePlayer) createExplosion(x, y-3, z, 10, thePlayer) blowVehicle(theVehicle, true) ---- setTimer( function(thePlayer) setElementData(thePlayer, "kamikaze", false, true) end , 5000, 1, thePlayer) ---- end , kmzItemTime, 1, theVehicle, client) if isElement(preKamikazeTimer[client]) then killTimer(preKamikazeTimer[client]) end preKamikazeTimer[client] = setTimer( function(marker) setTimer( function(marker) if isElement(marker) then setMarkerColor(marker, 255, 255, 255, 255) local size = getMarkerSize(marker) setMarkerSize(marker, size+0.5) end end , 50, 20, marker) end , 4800, 1, marker) end ) -------------------- -- Speed X2 Event -- -------------------- local speedMarkerColorTimer = {} addEvent("speedMode", true) addEventHandler("speedMode", resourceRoot, function(speedItemTime) local theVehicle = getPedOccupiedVehicle(client) local marker = attachMarker(theVehicle, speedItemTime+200, 255, 125, 0, 80) speedMarkerColorTimer[client] = setTimer( function(marker) if isElement(marker) then local r, g, b = getMarkerColor(marker) if g == 125 then setMarkerColor(marker, 255, 0, 255, 80) else setMarkerColor(marker, 255, 125, 0, 80) end end end , 200, (speedItemTime/200)+1, marker) end ) --------------- -- Fly Event -- --------------- addEvent("flyMode", true) addEventHandler("flyMode", resourceRoot, function(flyItemTime) local theVehicle = getPedOccupiedVehicle(client) attachMarker(theVehicle, flyItemTime+200, 125, 0, 125, 80) end ) ------------------ -- Magnet Event -- ------------------ addEvent("doMagnet", true) addEventHandler("doMagnet", resourceRoot, function() -----------for tests --[[for k, victim in ipairs(getElementsByType("player")) do setElementData(victim, "coremarkers_isPlayerSlowedDown", true, true) triggerClientEvent(victim, "slowDownPlayer", resourceRoot, magnetSlowDownTime) attachMarker(getPedOccupiedVehicle(victim), magnetSlowDownTime, 0, 0, 255, 80) sendClientMessage('#FFFFFF'..getPlayerName(client)..'#00DDFF slows down #FFFFFF'..getPlayerName(victim)..'.', root, 255, 255, 255, "bottom") end]] ---------------------------------- local killer_rank = getElementData(client, "race rank") if type(killer_rank) == "number" and killer_rank >= 2 then for k, victim in ipairs(getElementsByType("player")) do local rank = getElementData(victim, "race rank") if type(rank) == "number" then if rank == 1 and getElementData(victim, "state") == "alive" then setElementData(victim, "coremarkers_isPlayerSlowedDown", true, true) triggerClientEvent(victim, "slowDownPlayer", resourceRoot, magnetSlowDownTime) attachMarker(getPedOccupiedVehicle(victim), magnetSlowDownTime, 0, 0, 255, 80) sendClientMessage('#FFFFFF'..getPlayerName(client)..'#00DDFF slows down #FFFFFF'..getPlayerName(victim)..'.', root, 255, 255, 255, "bottom") if speedMarkerColorTimer and isTimer(speedMarkerColorTimer[victim]) then killTimer(speedMarkerColorTimer[victim]) end triggerClientEvent(root, "stop3DSound", resourceRoot, getPedOccupiedVehicle(victim)) end end end elseif killer_rank == 1 then sendClientMessage("Magnet slows down only 1st player, you can't use it against yourself", client, 255, 0, 0, "bottom") end end ) --------------------------------------- -- Reset Everything On Death/Respawn -- --------------------------------------- function resetAllTheStuff() if getElementType(source) == "player" then player = source elseif getElementType(source) == "vehicle" then player = getVehicleOccupant(source) end setElementData(player, "coremarkers_isPlayerSlowedDown", false, true) setElementData(player, "coremarkers_isPlayerRektBySpikes", false, true) triggerClientEvent(player, "removePower", resourceRoot) triggerClientEvent(player, "hideSpikesRepairHUD", resourceRoot) triggerClientEvent(player, "stopSpeed", resourceRoot) triggerClientEvent(player, "stopFly", resourceRoot) if isTimer(kamikazeTimer[player]) then killTimer(kamikazeTimer[player]) end if isTimer(preKamikazeTimer[player]) then killTimer(preKamikazeTimer[player]) end if isElement(marker[player]) then destroyElement(marker[player]) end if isTimer(markerTimer[player]) then killTimer(markerTimer[player]) end if rocketLauncher and isElement(rocketLauncher[player]) then destroyElement(rocketLauncher[player]) end unbindKey(player, "mouse1", "both", preShootMinigun) unbindKey(player, "lctrl", "both", preShootMinigun) end addEvent("onPlayerRaceWasted", true) addEventHandler("onPlayerRaceWasted", root, resetAllTheStuff) addEventHandler ("onVehicleEnter", root, resetAllTheStuff) addEventHandler("onElementDataChange", root, function(dataName,oldValue) if dataName == "state" then if getElementData(source, dataName) == "spectating" or getElementData(source, dataName) ~= "alive"then resetAllTheStuff(source) end end end ) -------------------------- -- Repair Vehicle Event -- -------------------------- addEvent("fixVehicle", true) addEventHandler("fixVehicle", resourceRoot, function(fix) local theVehicle = getPedOccupiedVehicle(client) if fix then fixVehicle(theVehicle) end setVehicleWheelStates(theVehicle, 0, 0, 0, 0) setElementData(client, "coremarkers_isPlayerRektBySpikes", false, true) playSoundFrontEnd(client, 46) end ) ----------------- -- Nitro Event -- ----------------- addEvent("giveNitro", true) addEventHandler("giveNitro", resourceRoot, function() local theVehicle = getPedOccupiedVehicle(client) addVehicleUpgrade(theVehicle, 1010) playSoundFrontEnd(client, 46) end ) ---------------- -- Jump Event -- ---------------- addEvent("doJump", true) addEventHandler("doJump", resourceRoot, function() local theVehicle = getPedOccupiedVehicle(client) local x, y, z = getElementVelocity(theVehicle) setElementVelocity(theVehicle, x, y, z+0.3) end ) ----------------------------- -- Function: Attach Marker -- ----------------------------- function attachMarker(theVehicle, timer, r, g, b, a) local player = theVehicle and getVehicleOccupant(theVehicle) or client local vehicle = theVehicle or getPedOccupiedVehicle(client) if isElement(marker[player]) then destroyElement(marker[player]) end marker[player] = createMarker( 0, 0, -200, 'corona', 2, r, g, b, 80) attachElements(marker[player], vehicle) markerTimer[player] = setTimer(function(marker) if isElement(marker) then destroyElement(marker) end end, timer, 1, marker[player]) return marker[player] end addEvent("attachMarker", true) addEventHandler("attachMarker", resourceRoot, attachMarker) ----------------------- -- Kills Information -- ----------------------- addEvent("Kill", true) addEventHandler("Kill", root, function (killer) if getElementType(killer) == "vehicle" then killer = getVehicleOccupant(killer) end if getElementType(killer) == "object" then if barrelCreator[killer] then killer = barrelCreator[killer] else return end end local victim = client local a = string.gsub (getElementData(victim, 'vip.colorNick') or getPlayerName(victim), '#%x%x%x%x%x%x', '' ) local b = string.gsub (getElementData(killer, 'vip.colorNick') or getPlayerName(killer), '#%x%x%x%x%x%x', '' ) sendClientMessage(a .. " was killed by " .. b, root, 255, 255, 255, "bottom") end ) ------------------------------ -- Function: Start Sound 3D -- ------------------------------ function startSound3D(sound) local theVehicle = getPedOccupiedVehicle(client) triggerClientEvent(root, "create3DSound", resourceRoot, theVehicle, sound) end addEvent("startSound3D", true) addEventHandler("startSound3D", resourceRoot, startSound3D) ------------- -- Minigun -- ------------- function preShootMinigun(thePlayer, key, keyState) if keyState == "down" then triggerClientEvent(root, "startShootMinigun", resourceRoot, thePlayer) else triggerClientEvent(root, "stopShootMinigun", resourceRoot, thePlayer) end end function preGiveMinigun() local theVehicle = getPedOccupiedVehicle(client) triggerClientEvent(root, "giveMinigun", resourceRoot, theVehicle) bindKey(client, "mouse1", "both", preShootMinigun) bindKey(client, "lctrl", "both", preShootMinigun) end addEvent("preGiveMinigun", true) addEventHandler("preGiveMinigun", resourceRoot, preGiveMinigun) function removeMinigun() unbindKey(client, "mouse1", "both", preShootMinigun) unbindKey(client, "lctrl", "both", preShootMinigun) end addEvent("removeMinigun", true) addEventHandler("removeMinigun", resourceRoot, removeMinigun) -------------------------------------------- -- Force CoreMarkers to stop on map stops -- -------------------------------------------- addEvent('onGamemodeMapStop', true) addEventHandler('onGamemodeMapStop', root, function() if getResourceState(resource) == "running" then stopResource(resource) end end )
addSearchPath(moduleDirectory .. "/acars/")
local path = (...):gsub("[^%.]*$", "") local M = require(path .. 'master') local CyclicList, Vec2 CyclicList, Vec2 = M.CyclicList, M.Vec2 local dot, wedge dot, wedge = Vec2.dot, Vec2.wedge local clamp, sgn do local _obj_0 = M.math clamp, sgn = _obj_0.clamp, _obj_0.sgn end local geometry = { } geometry.closest_edge_point = function(P, A, B) local u = B - A local t = clamp(dot(P - A, u) / u:lenS(), 0, 1) return A + t * u end geometry.bounding_box = function(points) local minx, miny, maxx, maxy = math.huge, math.huge, -math.huge, -math.huge for _index_0 = 1, #points do local v = points[_index_0] minx = math.min(minx, v.x) miny = math.min(miny, v.y) maxx = math.max(maxx, v.x) maxy = math.max(maxy, v.y) end return { x = minx, y = miny }, { x = maxx, y = maxy } end geometry.is_point_in_triangle = function(P, A, B, C) local sda = wedge(A - C, B - C) local s = sgn(sda) local a = wedge(P - C, B - C) local b = wedge(P - C, C - A) return s * a >= 0 and s * b >= 0 and s * (a + b) <= math.abs(sda) end geometry.centroid = function(points) local P = CyclicList(points) local W = 0 local C = Vec2() for i = 1, #points do local tmp = wedge(P[i], P[i + 1]) W = W + tmp C = C + ((P[i] + P[i + 1]) * tmp) end return C / (3 * W) end return geometry
local att = {} att.name = "md_muzl" att.displayName = "Enhanced Muzzlebrake" att.displayNameShort = "Mzlbrake" att.statModifiers = {RecoilMult = -.2, AimSpreadMult = .5, OverallMouseSensMult = -0.05, MaxSpreadIncMult = 0.25 } if CLIENT then att.displayIcon = surface.GetTextureID("atts/md_muzl") att.description = {[1] = {t = "Decreases recoil.", c = CustomizableWeaponry.textColors.POSITIVE}} end function att:attachFunc() end function att:detachFunc() end CustomizableWeaponry:registerAttachment(att)
local function get_options(player, is_alt) local player_settings = settings.get_player_settings(player) local prefix = "yastool_" .. (is_alt and "alt_" or "normal_") local options = {} for _, option_name in ipairs({ "snap_to_grid", "resolution_limit", "pixels_per_tile_limit", "show_gui", "show_entity_info", "anti_alias", "path" }) do options[option_name] = player_settings[prefix .. option_name].value end return options end local function normalize_coordinate(options, value) if options.snap_to_grid then return math.floor(value + 0.5) else return value end end local function on_selection(event) if event.item ~= "yastool" then return end local player = game.players[event.player_index] local is_alt = event.name == defines.events.on_player_alt_selected_area local options = get_options(player, is_alt) local left_top_x = normalize_coordinate(options, event.area.left_top.x) local left_top_y = normalize_coordinate(options, event.area.left_top.y) local right_bottom_x = normalize_coordinate(options, event.area.right_bottom.x) local right_bottom_y = normalize_coordinate(options, event.area.right_bottom.y) local center_x = (left_top_x + right_bottom_x) / 2 local center_y = (left_top_y + right_bottom_y) / 2 local tile_width = right_bottom_x - left_top_x local tile_height = right_bottom_y - left_top_y -- Figure out resolution (image size in pixels). -- It has to be a multiple of area size in tiles. -- The higher the multiplier, the higher the quality of the resulting image. -- However, there should be some limits. -- Resolution shouldn't be higher than some limit (e.g. 4096) in each dimension. -- The multiplier itself shouldn't be too high either - doesn't make sense -- to make 4096x4096 screenshot of a single tile. -- First, try pinning resolution for the longer dimension of the area to maximum allowed value. -- If the multiplier is too large, set it to its limit. local max_tile_size = math.max(tile_width, tile_height) local pixels_per_tile = options.resolution_limit / max_tile_size if pixels_per_tile > options.pixels_per_tile_limit then pixels_per_tile = options.pixels_per_tile_limit end local pixel_width = math.floor(tile_width * pixels_per_tile) local pixel_height = math.floor(tile_height * pixels_per_tile) if pixel_width < 1 or pixel_height < 1 then player.print(("Screenshot area is too small - calculated resolution is %dx%d, should be at least 1x1"):format( pixel_width, pixel_height)) return end local size_limit = options.anti_alias and 8192 or 16384 if pixel_width > size_limit or pixel_height > size_limit then player.print(("Screenshot area is too large - calculated resolution is %dx%d, should be at most %dx%d"):format( pixel_width, pixel_height, size_limit, size_limit)) return end local zoom = pixels_per_tile / 32 local path = options.path:gsub("{tick}", ("%d"):format(event.tick)) player.print(("Saving a screenshot (%.10gx%.10g tiles, %dx%d pixels) to %s"):format( tile_width, tile_height, pixel_width, pixel_height, path)) game.take_screenshot({ player = player, by_player = player, position = {x = center_x, y = center_y}, resolution = {x = pixel_width, y = pixel_height}, zoom = zoom, show_gui = options.show_gui, show_entity_info = options.show_entity_info, anti_alias = options.anti_alias, path = path }) end script.on_event({defines.events.on_player_selected_area, defines.events.on_player_alt_selected_area}, on_selection)
-- this file includes the whole library -- -- it tries to handle dependencies and makes sure higher order modules are included -- before modules that depend on it. local myPackages = { "lively_epsilon/src/cron.lua", "lively_epsilon/src/event_handler.lua", "lively_epsilon/src/util.lua", "utils.lua", "lively_epsilon/src/utility/ee.lua", "lively_epsilon/src/utility/log.lua", "lively_epsilon/src/utility/lua.lua", "lively_epsilon/src/utility/type_inspect.lua", "lively_epsilon/src/utility/comms.lua", "lively_epsilon/src/shim.lua", "lively_epsilon/src/chat/chatter.lua", "lively_epsilon/src/chat/chat_factory.lua", "lively_epsilon/src/chat/chat_noise.lua", "lively_epsilon/src/menu/menu.lua", "lively_epsilon/src/menu/menu_item.lua", "lively_epsilon/src/menu/gm_menu.lua", "lively_epsilon/src/domain/trait/generic/tags.lua", "lively_epsilon/src/domain/product.lua", "lively_epsilon/src/domain/person.lua", "lively_epsilon/src/domain/ship_template_based.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/storage_rooms.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/comms.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/crew.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/events.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/mission_broker.lua", "lively_epsilon/src/domain/trait/shipTemplateBased/upgrade_broker.lua", "lively_epsilon/src/domain/station.lua", "lively_epsilon/src/domain/trait/station/merchant.lua", "lively_epsilon/src/comms/merchant.lua", "lively_epsilon/src/comms/mission_broker.lua", "lively_epsilon/src/comms/upgrade_broker.lua", "lively_epsilon/src/domain/trait/station/production.lua", "lively_epsilon/src/domain/mission.lua", "lively_epsilon/src/domain/mission_all_of.lua", "lively_epsilon/src/domain/mission_chain.lua", "lively_epsilon/src/domain/trait/mission/broker.lua", "lively_epsilon/src/domain/trait/mission/for_player.lua", "lively_epsilon/src/domain/trait/mission/time_limit.lua", "lively_epsilon/src/domain/fleet.lua", "lively_epsilon/src/domain/ship.lua", "lively_epsilon/src/domain/trait/ship/crew.lua", "lively_epsilon/src/domain/trait/ship/events.lua", "lively_epsilon/src/domain/trait/ship/fleet.lua", "lively_epsilon/src/orders/generic.lua", "lively_epsilon/src/orders/attack.lua", "lively_epsilon/src/orders/defend.lua", "lively_epsilon/src/orders/dock.lua", "lively_epsilon/src/orders/fly_to.lua", "lively_epsilon/src/orders/order_queue.lua", "lively_epsilon/src/orders/roaming.lua", "lively_epsilon/src/orders/use.lua", "lively_epsilon/src/domain/player.lua", "lively_epsilon/src/domain/trait/player/menu.lua", "lively_epsilon/src/domain/trait/player/mission_tracker.lua", "lively_epsilon/src/domain/trait/player/mission_display.lua", "lively_epsilon/src/domain/trait/player/power_presets.lua", "lively_epsilon/src/domain/trait/player/quick_dial.lua", "lively_epsilon/src/domain/trait/player/storage.lua", "lively_epsilon/src/domain/trait/player/storage_display.lua", "lively_epsilon/src/domain/trait/player/upgrade_tracker.lua", "lively_epsilon/src/domain/trait/player/upgrade_display.lua", "lively_epsilon/src/domain/broker_upgrade.lua", "lively_epsilon/src/behaviors/miner.lua", "lively_epsilon/src/behaviors/trader.lua", "lively_epsilon/src/missions/answer.lua", "lively_epsilon/src/missions/bring_product.lua", "lively_epsilon/src/missions/capture.lua", "lively_epsilon/src/missions/crew_for_rent.lua", "lively_epsilon/src/missions/disable.lua", "lively_epsilon/src/missions/destroy.lua", "lively_epsilon/src/missions/destroy_raging_miner.lua", "lively_epsilon/src/missions/pick_up.lua", "lively_epsilon/src/missions/scan.lua", "lively_epsilon/src/missions/transport_token.lua", "lively_epsilon/src/missions/transport_product.lua", "lively_epsilon/src/missions/visit.lua", "lively_epsilon/src/missions/way_points.lua", "lively_epsilon/src/tools/story_comms.lua", "lively_epsilon/src/tools/comms.lua", "lively_epsilon/src/translator/inspector.lua", "lively_epsilon/src/translator/translator.lua", } if package ~= nil and package.path ~= nil then local basePath = debug.getinfo(1).source if basePath:sub(1,1) == "@" then basePath = basePath:sub(2) end if basePath:sub(-8) == "init.lua" then basePath = basePath:sub(1, -9) end basePath = "./" .. basePath package.path = package.path .. ";" .. basePath .. "?.lua" -- when running tests local prefix = "lively_epsilon/" for _, package in pairs(myPackages) do if package:sub(1, prefix:len()) == prefix then package = package:sub(prefix:len() + 1) end local name = package:match("^(.+).lua$") require(name) end else -- within empty epsilon for _, package in pairs(myPackages) do require(package) end end
----------------------------------- -- Area: Southern San d'Oria -- NPC: Chat Manual -- Type: Tutorial NPC -- !pos -68.800 2.000 -46.560 230 ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(6106); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
-- Created by LuaView. -- Copyright (c) 2017, Alibaba Group. All rights reserved. -- -- This source code is licensed under the MIT. -- For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. --1. 普通设置url,size,center view = Image() view.frame(0, 0, 200, 200) view.backgroundColor(0xffaa0000) --view.image("animate1") --2. 普通构造传url bmp = Bitmap("https://gju1.alicdn.com/bao/uploaded/i4/100000120700895002/TB2Qu0_fXXXXXb9XpXXXXXXXXXX_!!0-0-juitemmedia.jpg_560x560Q90.jpg", function(ok) if(ok) then view.image(bmp) else view.image("animate1") end end) spriteBmp = function(t) local w, h = t.size() t.sprite(0, 0, w / 2, h / 2, function(newBmp) view.image(newBmp) bmp = newBmp end) Toast("width = " .. w .. " height = " .. h) end view.callback(function() spriteBmp(bmp) end) view2 = Image() view2.frame(0, 200, 200, 200) bmp2 = Bitmap("animate1", function(ok) view2.image(ok and bmp2) end) view2.callback(function() local n = 5; local w, h = bmp2.size() local sw = w / 5; local vw = view2.width() / 5 local x = 0 local vx = 0; for i = 1, n do x = (i - 1) * sw vx = (i - 1) * vw + (i - 1) * 2 local v = Image() v.frame(vx, 403, vw, h) v.image(bmp2.sprite(x, 0, sw, h)) end end)
meshes = { { vertexes = {{-13,-2},{-13,2},{-12,3},{-8,3},{-7,2},{-7,-2},{-8,-3},{-12,-3}, {-13,-8},{-6,-8},{-2,-3},{-2,3},{-6,8},{-13,8},{-5,15},{8,15},{14,8},{2,8},{5,3},{15,0},{5,-3},{2,-8},{14,-8},{8,-15},{-5,-15}}, colors = {0xff0000ff, 0xff0000ff, 0xff0000ff, 0x454545ff, 0x454545ff, 0x454545ff, 0x454545ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0x454545ff, 0x454545ff, 0x454545ff, 0x454545ff, 0x454545ff, 0xff0000ff, 0xff0000ff, 0xff0000ff}, segments = {{0,1,2,3,4,5,6,7,0}, {8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,8}} } }
return {'acda'}
-- Widget is based on the AceGUIWidget-DropDown.lua supplied with AceGUI-3.0 -- Widget created by Yssaril LoadAddOn("LibSharedMedia-3.0") local AceGUI = LibStub("AceGUI-3.0") local Media = LibStub("LibSharedMedia-3.0") AceGUISharedMediaWidgets = {} do AceGUIWidgetLSMlists = { ['font'] = Media:HashTable("font"), ['sound'] = Media:HashTable("sound"), ['statusbar'] = Media:HashTable("statusbar"), ['border'] = Media:HashTable("border"), ['background'] = Media:HashTable("background"), } local min, max, floor = math.min, math.max, math.floor local function fixlevels(parent,...) local i = 1 local child = select(i, ...) while child do child:SetFrameLevel(parent:GetFrameLevel()+1) fixlevels(child, child:GetChildren()) i = i + 1 child = select(i, ...) end end local function OnItemValueChanged(this, event, checked) local self = this.userdata.obj if self.multiselect then self:Fire("OnValueChanged", this.userdata.value, checked) else if checked then self:SetValue(this.userdata.value) self:Fire("OnValueChanged", this.userdata.value) else this:SetValue(true) end self.pullout:Close() end end local function SetValue(self, value) if value then self:SetText(value or "") end self.value = value end AceGUISharedMediaWidgets.fixlevels = fixlevels AceGUISharedMediaWidgets.OnItemValueChanged = OnItemValueChanged AceGUISharedMediaWidgets.SetValue = SetValue end
local Module = require"Toolbox.Import.Module" return { Basic = Module.Child"Basic"; Aliasable = Module.Child"Aliasable"; Templates = Module.Child"Templates"; }
local granite = { {"granite", "Granite grey"}, {"graniteR", "Granite corten"}, {"graniteA", "Granite avory"}, {"graniteP", "Granite pink"}, {"graniteB", "Granite black"}, {"graniteBC", "Granite black center"}, } local stairs_mod = minetest.get_modpath("stairs") local stairsplus_mod = minetest.get_modpath("moreblocks") and minetest.global_exists("stairsplus") for _, granite in pairs(granite) do if stairsplus_mod then stairsplus:register_all("summer", granite[1], "summer:" .. granite[1], { description = granite[2] .. " Summer", tiles = {granite[1] .. ".png"}, groups = {cracky = 3}, sounds = default.node_sound_stone_defaults(), }) stairsplus:register_alias_all("summer", granite[1], "summer", granite[1]) minetest.register_alias("stairs:slab_summer_".. granite[1], "summer:slab_baked_granite_" .. granite[1]) minetest.register_alias("stairs:stair_summer_".. granite[1], "summer:stair_baked_granite_" .. granite[1]) -- register all stair types for stairs redo elseif stairs_mod and stairs.mod then stairs.register_all("summer_" .. granite[1], "summer:" .. granite[1], {cracky = 3}, {granite[1] .. ".png"}, granite[2] .. " Summer", default.node_sound_stone_defaults()) -- register stair and slab using default stairs elseif stairs_mod then stairs.register_stair_and_slab("summer_".. granite[1], "summer:".. granite[1], {cracky = 3}, {granite[1] .. ".png"}, granite[2] .. " Summer Stair", granite[2] .. " Summer Slab", default.node_sound_stone_defaults()) end end --GRANITE minetest.register_node("summer:granite", { description = "Granite", tiles = {"granite.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='"summer:mattoneG" 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("summer:graniteA", { description = "GraniteA", tiles = {"graniteA.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='"summer:mattoneA" 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("summer:graniteP", { description = "GraniteP", tiles = {"graniteP.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='"summer:mattoneP" 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("summer:graniteR", { description = "GraniteR", tiles = {"graniteR.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='summer:mattoneR 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("summer:graniteBC", { description = "Granite", tiles = {"graniteBC.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='"summer:mattoneG" 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("summer:graniteB", { description = "Granite", tiles = {"graniteB.png"}, material = minetest.digprop_constanttime(1), groups = {cracky = 3, stone = 1}, --drop ='"summer:mattoneG" 9', stack_max = 9999, --legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) --craft GRANITE minetest.register_craft({ output = '"summer:graniteBC" 5', recipe = { { "", "", "" }, { "summer:pietraA", "", "" }, { "summer:graniteB", "", "" }, }, }) minetest.register_craft({ output = '"summer:graniteB" 5', recipe = { { "", "", "" }, { "summer:graniteP", "summer:graniteA", "" }, { "summer:graniteR", "summer:graniteG", "" }, }, }) minetest.register_craft({ output = '"summer:graniteR" 5', recipe = { { "summer:mattoneR", "summer:mattoneR", "summer:mattoneR" }, { "summer:mattoneR", "summer:mattoneR", "summer:mattoneR" }, { "summer:mattoneR", "summer:mattoneR", "summer:mattoneR" }, }, }) minetest.register_craft({ output = '"summer:graniteA" 5', recipe = { { "summer:mattoneA", "summer:mattoneA", "summer:mattoneA" }, { "summer:mattoneA", "summer:mattoneA", "summer:mattoneA" }, { "summer:mattoneA", "summer:mattoneA", "summer:mattoneA" }, }, }) minetest.register_craft({ output = '"summer:granite" 5', recipe = { { "summer:mattoneG", "summer:mattoneG", "summer:mattoneG" }, { "summer:mattoneG", "summer:mattoneG", "summer:mattoneG" }, { "summer:mattoneG", "summer:mattoneG", "summer:mattoneG" }, }, }) minetest.register_craft({ output = '"summer:graniteP" 5', recipe = { { "summer:mattoneP", "summer:mattoneP", "summer:mattoneP" }, { "summer:mattoneP", "summer:mattoneP", "summer:mattoneP" }, { "summer:mattoneP", "summer:mattoneP", "summer:mattoneP" }, }, })
local ffi = require "ffi" local ffi_new = ffi.new local ffi_gc = ffi.gc local ffi_str = ffi.string local ffi_copy = ffi.copy local C = ffi.C local setmetatable = setmetatable local _M = { _VERSION = '0.10' } local mt = { __index = _M } ffi.cdef[[ typedef struct engine_st ENGINE; typedef struct evp_cipher_st EVP_CIPHER; typedef struct evp_cipher_ctx_st { const EVP_CIPHER *cipher; ENGINE *engine; int encrypt; int buf_len; unsigned char oiv[16]; unsigned char iv[16]; unsigned char buf[32]; int num; void *app_data; int key_len; unsigned long flags; void *cipher_data; int final_used; int block_mask; unsigned char final[32]; } EVP_CIPHER_CTX; const EVP_CIPHER *EVP_get_cipherbyname(const char *name); EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv, int enc); int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl); int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a); void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx); ]] local buf_size = 2048 local buf = ffi_new("unsigned char[?]", buf_size) local function c_uchar(s) local c_s = ffi_new("unsigned char[?]", #s) ffi_copy(c_s, s) return c_s end function cleanup(ctx) C.EVP_CIPHER_CTX_cleanup(ctx) C.EVP_CIPHER_CTX_free(ctx) end function _M:new(cipher_name, key, iv, op) local o = { ["_cipher"] = C.EVP_get_cipherbyname(cipher_name), ["_ctx"] = C.EVP_CIPHER_CTX_new() } if (not o._cipher) or (not o._ctx) then ngx.log(ngx.INFO, "openssl failed to create cipher or ctx ", cipher_name) return nil end setmetatable(o, mt) local r = C.EVP_CipherInit_ex(o._ctx, o._cipher, nil, c_uchar(key), c_uchar(iv), op) if r == 0 then ngx.log(ngx.INFO, "openssl failed to call EVP_CipherInit_ex ", cipher_name, " ", key, " ", iv) return nil end ffi_gc(o._ctx, cleanup) return o end function _M:update(data) local out_len = ffi_new("int[1]") local l = #data if buf_size < l then buf_size = l * 2 buf = ffi_new("unsigned char[?]", buf_size) end if C.EVP_CipherUpdate(self._ctx, buf, out_len, c_uchar(data), l) == 0 then ngx.log(ngx.INFO, "openssl failed to call EVP_CipherUpdate") return nil end return ffi_str(buf, out_len[0]) end function _M:encrypt(data) return self:update(data) end function _M:decrypt(data) return self:update(data) end local function create_cipher(alg, key, iv, op) return _M:new(alg, key, iv, op) end _M.ciphers = { ["aes-128-cfb"] = {16, 16, create_cipher}, ["aes-192-cfb"] = {24, 16, create_cipher}, ["aes-256-cfb"] = {32, 16, create_cipher}, ["aes-128-ofb"] = {16, 16, create_cipher}, ["aes-192-ofb"] = {24, 16, create_cipher}, ["aes-256-ofb"] = {32, 16, create_cipher}, ["aes-128-ctr"] = {16, 16, create_cipher}, ["aes-192-ctr"] = {24, 16, create_cipher}, ["aes-256-ctr"] = {32, 16, create_cipher}, ["aes-128-cfb8"] = {16, 16, create_cipher}, ["aes-192-cfb8"] = {24, 16, create_cipher}, ["aes-256-cfb8"] = {32, 16, create_cipher}, ["aes-128-cfb1"] = {16, 16, create_cipher}, ["aes-192-cfb1"] = {24, 16, create_cipher}, ["aes-256-cfb1"] = {32, 16, create_cipher}, ["bf-cfb"] = {16, 8, create_cipher}, ["camellia-128-cfb"] = {16, 16, create_cipher}, ["camellia-192-cfb"] = {24, 16, create_cipher}, ["camellia-256-cfb"] = {32, 16, create_cipher}, ["cast5-cfb"] = {16, 8, create_cipher}, ["des-cfb"] = {8, 8, create_cipher}, ["idea-cfb"] = {16, 8, create_cipher}, ["rc2-cfb"] = {16, 8, create_cipher}, ["rc4"] = {16, 0, create_cipher}, ["seed-cfb"] = {16, 16, create_cipher} } return _M
local function reverse(arr) local len = #arr local max = math.floor(len / 2) for i=1, max do local idx = len + 1 - i arr[i], arr[idx] = arr[idx], arr[i] end end local start = os.clock() local N = 20000000 local list = {} for i=1, N do list[i] = i end reverse(list) local seconds = os.clock() - start print('elapsed: ' .. seconds .. 's')
SPELL.Name = "Air Blast" SPELL.Combo = "wind shield" SPELL.Icon = Material("magic/spell_icons/airblast") SPELL.Description = "Throws away everything that is in front of you" PrecacheParticleSystem("airblast") if SERVER then function SPELL:OnCasted(ply) ply:EmitSound("^weapons/underwater_explode3.wav") local eyeAngles = ply:EyeAngles() local forward = eyeAngles:Forward() ParticleEffect("airblast", ply:EyePos() + forward * 50, eyeAngles, ply) for k,v in ipairs(ents.FindInSphere(ply:EyePos() + forward * 100, 150)) do if !v:IsSolid() or v == ply then continue end local phys = v:GetPhysicsObject() if v:IsPlayer() then v:SetVelocity(forward * 1000) elseif v:IsNPC() then v:SetVelocity(forward * 10000) else local phys = v:GetPhysicsObject() if IsValid(phys) then phys:SetVelocity(forward * 2000) end end end end else end
local standards = require "luacheck.standards" local builtin_standards = {} local function def_to_std(def) return {read_globals = def.fields} end local function add_defs(...) local res = {} for _, def in ipairs({...}) do standards.add_std_table(res, def_to_std(def)) end return res end local empty = {} local function def_fields(...) local fields = {} for _, field in ipairs({...}) do fields[field] = empty end return {fields = fields} end local string_defs = {} string_defs.min = def_fields("byte", "char", "dump", "find", "format", "gmatch", "gsub", "len", "lower", "match", "rep", "reverse", "sub", "upper") string_defs.lua51 = add_defs(string_defs.min, def_fields("gfind")) string_defs.lua52 = string_defs.min string_defs.lua53 = add_defs(string_defs.min, def_fields("pack", "packsize", "unpack")) string_defs.luajit = string_defs.lua51 local file_defs = {} file_defs.min = { fields = { __gc = empty, __index = {other_fields = true}, __tostring = empty, close = empty, flush = empty, lines = empty, read = empty, seek = empty, setvbuf = empty, write = empty } } file_defs.lua51 = file_defs.min file_defs.lua52 = file_defs.min file_defs.lua53 = add_defs(file_defs.min, {fields = {__name = string_defs.lua53}}) file_defs.luajit = file_defs.min local function make_min_def(method_defs) local string_def = string_defs[method_defs] local file_def = file_defs[method_defs] return { fields = { _G = {other_fields = true, read_only = false}, _VERSION = string_def, arg = {other_fields = true}, assert = empty, collectgarbage = empty, coroutine = def_fields("create", "resume", "running", "status", "wrap", "yield"), debug = def_fields("debug", "gethook", "getinfo", "getlocal", "getmetatable", "getregistry", "getupvalue", "sethook", "setlocal", "setmetatable", "setupvalue", "traceback"), dofile = empty, error = empty, getmetatable = empty, io = { fields = { close = empty, flush = empty, input = empty, lines = empty, open = empty, output = empty, popen = empty, read = empty, stderr = file_def, stdin = file_def, stdout = file_def, tmpfile = empty, type = empty, write = empty } }, ipairs = empty, load = empty, loadfile = empty, math = def_fields("abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "floor", "fmod", "huge", "log", "max", "min", "modf", "pi", "rad", "random", "randomseed", "sin", "sqrt", "tan"), next = empty, os = def_fields("clock", "date", "difftime", "execute", "exit", "getenv", "remove", "rename", "setlocale", "time", "tmpname"), package = { fields = { config = string_def, cpath = {fields = string_def.fields, read_only = false}, loaded = {other_fields = true, read_only = false}, loadlib = empty, path = {fields = string_def.fields, read_only = false}, preload = {other_fields = true, read_only = false} } }, pairs = empty, pcall = empty, print = empty, rawequal = empty, rawget = empty, rawset = empty, require = empty, select = empty, setmetatable = empty, string = string_def, table = def_fields("concat", "insert", "remove", "sort"), tonumber = empty, tostring = empty, type = empty, xpcall = empty } } end local bit32_def = def_fields("arshift", "band", "bnot", "bor", "btest", "bxor", "extract", "lrotate", "lshift", "replace", "rrotate", "rshift") local lua_defs = {} lua_defs.min = make_min_def("min") lua_defs.lua51 = add_defs(make_min_def("lua52"), { fields = { debug = def_fields("getfenv", "setfenv"), getfenv = empty, loadstring = empty, math = def_fields("atan2", "cosh", "frexp", "ldexp", "log10", "pow", "sinh", "tanh"), module = empty, newproxy = empty, package = { fields = { loaders = {other_fields = true, read_only = false}, seeall = empty } }, setfenv = empty, table = def_fields("maxn"), unpack = empty } }) lua_defs.lua51c = add_defs(lua_defs.lua51, make_min_def("lua51"), { fields = { gcinfo = empty, math = def_fields("mod"), table = def_fields("foreach", "foreachi", "getn", "setn") } }) lua_defs.lua52 = add_defs(make_min_def("lua52"), { fields = { _ENV = {other_fields = true, read_only = false}, bit32 = bit32_def, debug = def_fields("getuservalue", "setuservalue", "upvalueid", "upvaluejoin"), math = def_fields("atan2", "cosh", "frexp", "ldexp", "pow", "sinh", "tanh"), package = { fields = { searchers = {other_fields = true, read_only = false}, searchpath = empty } }, rawlen = empty, table = def_fields("pack", "unpack") } }) lua_defs.lua52c = add_defs(lua_defs.lua52, { fields = { loadstring = empty, math = def_fields("log10"), module = empty, package = { fields = { loaders = {other_fields = true, read_only = false}, seeall = empty } }, table = def_fields("maxn"), unpack = empty } }) lua_defs.lua53 = add_defs(make_min_def("lua53"), { fields = { _ENV = {other_fields = true, read_only = false}, coroutine = def_fields("isyieldable"), debug = def_fields("getuservalue", "setuservalue", "upvalueid", "upvaluejoin"), math = def_fields("maxinteger", "mininteger", "tointeger", "type", "ult"), package = { fields = { searchers = {other_fields = true, read_only = false}, searchpath = empty } }, rawlen = empty, table = def_fields("move", "pack", "unpack"), utf8 = { fields = { char = empty, charpattern = string_defs.lua53, codepoint = empty, codes = empty, len = empty, offset = empty } } } }) lua_defs.lua53c = add_defs(lua_defs.lua53, { fields = { bit32 = bit32_def, math = def_fields("atan2", "cosh", "frexp", "ldexp", "log10", "pow", "sinh", "tanh") } }) lua_defs.luajit = add_defs(make_min_def("luajit"), { fields = { bit = def_fields("arshift", "band", "bnot", "bor", "bswap", "bxor", "lshift", "rol", "ror", "rshift", "tobit", "tohex"), coroutine = def_fields("isyieldable"), debug = def_fields("getfenv", "setfenv", "upvalueid", "upvaluejoin"), gcinfo = empty, getfenv = empty, jit = {other_fields = true}, loadstring = empty, math = def_fields("atan2", "cosh", "frexp", "ldexp", "log10", "mod", "pow", "sinh", "tanh"), module = empty, newproxy = empty, package = { fields = { loaders = {other_fields = true, read_only = false}, searchpath = empty, seeall = empty } }, setfenv = empty, table = def_fields("clear", "foreach", "foreachi", "getn", "maxn", "move", "new"), unpack = empty } }) lua_defs.ngx_lua = add_defs(lua_defs.luajit, { fields = { ngx = {other_fields = true, read_only = false}, ndk = {other_fields = true} } }) lua_defs.max = add_defs(lua_defs.lua51c, lua_defs.lua52c, lua_defs.lua53c, lua_defs.luajit) for name, def in pairs(lua_defs) do builtin_standards[name] = def_to_std(def) end local function detect_default_std() if rawget(_G, "jit") then return "luajit" elseif _VERSION == "Lua 5.1" then return "lua51c" elseif _VERSION == "Lua 5.2" then return "lua52c" elseif _VERSION == "Lua 5.3" then return "lua53c" else return "max" end end builtin_standards._G = builtin_standards[detect_default_std()] builtin_standards.busted = { read_globals = { "describe", "insulate", "expose", "it", "pending", "before_each", "after_each", "lazy_setup", "lazy_teardown", "strict_setup", "strict_teardown", "setup", "teardown", "context", "spec", "test", "assert", "spy", "mock", "stub", "finally" } } builtin_standards.rockspec = { globals = { "rockspec_format", "package", "version", "description", "supported_platforms", "dependencies", "external_dependencies", "source", "build" } } builtin_standards.none = {} return builtin_standards
function class(kls, base) if not base then base = { } end kls.__index = function (self, key) local get = function (this, key) local t = rawget(this, key) if t then return t end t = kls[key] if t then return t end return base[key] end local t = get(self, 'get_' .. key) if t then return t(self) end return get(self, key) end kls.__newindex = function (self, key, value) local t = rawget(self, 'set_' .. key) if t then return t(self, value) end rawset(self, key, value) end setmetatable(kls, base) return kls end function new(kls, ...) local obj = { } setmetatable(obj, kls) obj:new(...) return obj end function is(obj, kls) repeat if obj == kls then return true end obj = getmetatable(obj) until not obj return false end function call(fn, ...) return fn(...) end function apply(fn, ...) return fn(...) end function length(obj) return #obj end
workspace "Learn Vulkan" configurations {"Debug", "Release"} architecture "x64" project "Learn Vulkan" location "Learn Vulkan" kind "ConsoleApp" language "C++" targetdir "bin/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" objdir "bin-int/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}/%{prj.name}" files { "%{prj.name}/src/**.hpp", "%{prj.name}/src/**.cpp" } libdirs {"libs", "C:/VulkanSDK/1.2.176.1/Lib"} links {"glfw3", "vulkan-1"} includedirs {"vendor/GLFW/include", "vendor/GLM/glm", "C:/VulkanSDK/1.2.176.1/Include"} filter "configurations:Debug" symbols "On" filter "configurations:Release" optimize "On" filter "system:windows" cppdialect "C++17" systemversion "10.0.19041.0"
return { money = {e={["bg"]={255,0,0,255},["justify"]=3}, resize=function(self) local d = self.d local p=self.p local w=200 self.h = 30 self.w = w self.x = p.x + p.w - w self.y = p.y end }, }
-------------------------------------------------------------------------------- local tostrlib = {} local done = {} local stack = {} local depth = 0 local tostring = tostring local apitype = common.GetApiType local FromWs = userMods.FromWString local s_format = string.format local s_rep = string.rep local s_sub = string.sub local t_insert = table.insert local t_remove = table.remove local t_concat = table.concat local t_sort = table.sort local t_getn = table.getn local m_floor = math.floor -------------------------------------------------------------------------------- local function comp( tab ) local v1, v2, tv1, tv2, tk1, tk2 return function( k1, k2 ) v1, v2 = tab[ k1 ], tab[ k2 ] tv1, tv2 = apitype( v1 ), apitype( v2 ) tk1, tk2 = apitype( k1 ), apitype( k2 ) if tv1 ~= tv2 then return tv1 < tv2 end if tk1 ~= tk2 then return tk1 < tk2 end if tk1 == "number" or tk1 == "string" then return k1 < k2 else return tostring( k1 ) < tostring( k2 ) end end end -------------------------------------------------------------------------------- local function sortpairs( tab ) local list = {} for k, _ in pairs( tab ) do t_insert( list, k ) end t_sort( list, comp( tab ) ) local first = list[ 1 ] local keys = {} for i, k in pairs( list ) do keys[ k ] = list[ i + 1 ] end return function( tab, key ) key = key == nil and first or keys[ key ] return key, key and tab[ key ] end, tab, nil end -------------------------------------------------------------------------------- function advtostring( val, flat, brief ) if val ~= nil then flat = flat ~= false local method = tostrlib[ apitype( val ) ] or tostrlib[ type( val ) ] return method( val, flat, brief ) end return tostring( val ) end -------------------------------------------------------------------------------- local advtostring = advtostring -------------------------------------------------------------------------------- tostrlib[ "table" ] = function( val, flat, brief ) if brief and brief <= depth then return tostring( val ) end local out = {} local nosub, count = true, 0 for k, v in pairs( val ) do count = count + 1 if ( type( v ) == "table" and next( v ) ~= nil and ( not brief or brief > ( depth + 1 ) ) and stack[ v ] == nil ) or count > 8 then nosub = false break end end if not done[ val ] then done[ val ] = "self" end if not stack[ val ] then stack[ val ] = done[ val ] end depth = depth + 1 local prefix = ( flat or nosub ) and " " or ( "\n" .. s_rep( "\t", depth ) ) local key, t for k, v in sortpairs( val ) do t = type( k ) key = s_format( t == "string" and ((string.find(k, ' ')) and "[ '%s' ] = " or "%s = ") or "[ %s ] = ", t == "string" and k or advtostring( k, true, 0 ) ) --key = s_format( t == "string" and "%s = " or "[ %s ] = ", t == "string" and k or advtostring( k, true, 0 ) ) if done[ v ] == nil then if type( v ) == "table" then done[ v ] = s_format( t == "string" and "%s.%s" or "%s[ %s ]", done[ val ], tostring( k ) ) end end if stack[ v ] == nil then t_insert( out, s_format( "%s%s%s", prefix, key, advtostring( v, flat, brief ) ) ) else t_insert( out, s_format( "%s%s%s", prefix, key, stack[ v ] ) ) end t_insert( out, "," ) end depth = depth - 1 prefix = ( flat or nosub ) and " " or ( "\n" .. s_rep( "\t", depth ) ) stack[ val ] = nil if depth == 0 then done = {} end if t_getn( out ) == 0 then t_insert( out, "{}" ) else t_remove( out ) t_insert( out, 1, "{" ) t_insert( out, prefix .. "}" ) end return t_concat( out ) end -------------------------------------------------------------------------------- tostrlib[ "number" ] = function( val ) return tostring( m_floor( val * 1000 + 0.5 ) / 1000 ) end -------------------------------------------------------------------------------- tostrlib[ "string" ] = function( val ) return s_format( "\"%s\"", val ) end -------------------------------------------------------------------------------- tostrlib[ "WString" ] = function( val ) return s_format( "WString: [[%s]]", FromWs( val ) ) end -------------------------------------------------------------------------------- local function GetFullName( widget ) local stack = {} repeat t_insert( stack, 1, widget:GetName() ) t_insert( stack, 1, "." ) widget = widget:GetParent() until widget == nil t_remove( stack, 1 ) return t_concat( stack ) end -------------------------------------------------------------------------------- local function widgettostring( widget ) local apitype = apitype( widget ) return s_format( "%s: %s [[%s]]: \"%s\"", apitype, s_sub( tostring( widget ), -8 ), widget:__towatch(), GetFullName( widget ) ) end -------------------------------------------------------------------------------- tostrlib[ "FormSafe" ] = widgettostring tostrlib[ "PanelSafe" ] = widgettostring tostrlib[ "ButtonSafe" ] = widgettostring tostrlib[ "TextViewSafe" ] = widgettostring tostrlib[ "ScrollableContainerSafe" ] = widgettostring -------------------------------------------------------------------------------- tostrlib[ "ValuedObjectLua" ] = function( val ) return s_format( "ValuedObjectLua: [[%s]]", FromWs( val:GetText() ) ) end -------------------------------------------------------------------------------- local a_GetCurrencyInfo = avatar.GetCurrencyInfo tostrlib[ "CurrencyId" ] = function( val ) local currency = a_GetCurrencyInfo( val ) return s_format( "CurrencyId: [[%s]] %d", FromWs( currency.name ), currency.value ) end -------------------------------------------------------------------------------- local c_GetTexturePath = common.GetTexturePath tostrlib[ "TextureId" ] = function( val ) return s_format( "TextureId: \"%s\"", c_GetTexturePath( val ) ) end -------------------------------------------------------------------------------- local a_GetSpellInfo = spellLib.GetDescription tostrlib[ "SpellId" ] = function( val ) local _t = a_GetSpellInfo( val ) return s_format( "SpellId: \"%s\"", FromWs( _t and _t.name or 'nil' ) ) end -------------------------------------------------------------------------------- local a_GetActionGroupInfo = avatar.GetActionGroupInfo tostrlib[ "ActionGroupId" ] = function( val ) return s_format( "ActionGroupId: [[%s]]", FromWs( a_GetActionGroupInfo( val ).name ) ) end -------------------------------------------------------------------------------- local c_ExtractWStringFromValuedText = common.ExtractWStringFromValuedText tostrlib[ "ValuedText" ] = function( val ) return s_format( "ValuedText: [[%s]]", FromWs( c_ExtractWStringFromValuedText( val ) ) ) end -------------------------------------------------------------------------------- tostrlib[ "BuffId" ] = function( val ) return s_format( "BuffId: %s [[%s]]", s_sub( tostring( val ), -8 ), val:__towatch() ) end -------------------------------------------------------------------------------- tostrlib[ "function" ] = tostring tostrlib[ "boolean" ] = tostring -------------------------------------------------------------------------------- tostrlib[ "userdata" ] = function( val ) return s_format( "%s: %s", apitype( val ), s_sub( tostring( val ), -8 ) ) end --------------------------------------------------------------------------------
--region LuaCodeWriter local LuaCodeWriter = fclass() function LuaCodeWriter:ctor(config) config = config or {} self.blockStart = config.blockStart or '{' self.blockEnd = config.blockEnd or '}' self.blockFromNewLine = config.blockFromNewLine if self.blockFromNewLine == nil then self.blockFromNewLine = true end if config.usingTabs then self.indentStr = '\t' else self.indentStr = ' ' end self.usingTabs = config.usingTabs self.endOfLine = config.endOfLine or '\n' self.lines = {} self.indent = 0 self:writeMark() end function LuaCodeWriter:writeMark() table.insert(self.lines, '--- This is an automatically generated class by FairyGUI. Please do not modify it. ---') table.insert(self.lines, '') end function LuaCodeWriter:writeln(format, ...) if not format then table.insert(self.lines, '') return end local str = '' for i = 0, self.indent - 1 do str = str .. self.indentStr end str = str .. string.format(format, ...) table.insert(self.lines, str) return self end function LuaCodeWriter:startBlock() if self.blockFromNewLine or #self.lines == 0 then self:writeln(self.blockStart) else local str = self.lines[#self.lines] self.lines[#self.lines] = str .. ' ' .. self.blockStart end self.indent = self.indent + 1 return self end function LuaCodeWriter:endBlock() self.indent = self.indent - 1 self:writeln(self.blockEnd) return self end function LuaCodeWriter:incIndent() self.indent = self.indent + 1 return self end function LuaCodeWriter:decIndent() self.indent = self.indent - 1 return self end function LuaCodeWriter:reset() if #self.lines > 0 then self.lines = {} end self.indent = 0 self:writeMark() end function LuaCodeWriter:tostring() return table.concat(self.lines, self.endOfLine) end function LuaCodeWriter:save(filePath) local str = table.concat(self.lines, self.endOfLine) CS.System.IO.File.WriteAllText(filePath, str) end --endregion local projectCustomPropertiesDic; local customPropKeys = { key_gen_lua = { name = "key_gen_lua", default_value = "true" }, key_lua_file_extension_name = { name = "key_lua_file_extension_name", default_value = "lua" }, key_lua_path_root = { name = "key_lua_path_root", default_value = "UIGenCode/" }, key_wrapper_namespace = { name = "key_wrapper_namespace", default_value = "CS.FairyGUI" }, } local function get_project_custom_property_value(key_name) if (projectCustomPropertiesDic and projectCustomPropertiesDic:ContainsKey(key_name)) then return projectCustomPropertiesDic:get_Item(key_name); else return customPropKeys[key_name].default_value; end end function onPublish(handler) if not handler.genCode or handler.publishDescOnly then return end projectCustomPropertiesDic = App.project:GetSettings("CustomProperties").elements; local gen_lua = get_project_custom_property_value(customPropKeys.key_gen_lua.name); if (gen_lua == "true") then handler.genCode = false --prevent default output App.consoleView:Clear(); fprint("Handling gen lua code in plugin.") genCode(handler) end end function genCode(handler) local settings = handler.project:GetSettings("Publish").codeGeneration local codePkgName = handler:ToFilename(handler.pkg.name); --convert chinese to pinyin, remove special chars etc. local exportCodePath = handler.exportCodePath .. '/' .. codePkgName local lua_file_extension_name = get_project_custom_property_value(customPropKeys.key_lua_file_extension_name.name); local lua_path_root = get_project_custom_property_value(customPropKeys.key_lua_path_root.name); lua_path_root = string.gsub(lua_path_root, "/", "."); lua_path_root = string.gsub(lua_path_root, "\\", "."); local namespaceName = codePkgName local key_wrapper_namespace = get_project_custom_property_value(customPropKeys.key_wrapper_namespace.name); if settings.packageName ~= nil and settings.packageName ~= '' then namespaceName = settings.packageName .. '.' .. namespaceName; end --CollectClasses(stripeMemeber, stripeClass, fguiNamespace) local classes = handler:CollectClasses(settings.ignoreNoname, settings.ignoreNoname, key_wrapper_namespace) handler:SetupCodeFolder(exportCodePath, lua_file_extension_name) --check if target folder exists, and delete old files local getMemberByName = settings.getMemberByName local classTemplateTxt = CS.System.IO.File.ReadAllText(PluginPath .. "/component_template.txt"); if (classTemplateTxt == "") then fprint("component_template.txt content null.") return ; end local classCnt = classes.Count local writer = LuaCodeWriter.new({ blockFromNewLine = false, usingTabs = true }) for i = 0, classCnt - 1 do local _classTemplateTxt = classTemplateTxt; local classInfo = classes[i] local members = classInfo.members writer:reset() _classTemplateTxt = string.gsub(_classTemplateTxt, "$className", classInfo.className); _classTemplateTxt = string.gsub(_classTemplateTxt, "$superClassName", classInfo.superClassName); if (key_wrapper_namespace ~= "") then _classTemplateTxt = string.gsub(_classTemplateTxt, "$namespace", key_wrapper_namespace .. "."); else _classTemplateTxt = string.gsub(_classTemplateTxt, "$namespace", ""); end local _classFieldAnnotation = string.format('---@field public %s %s\n', "__ui", classInfo.superClassName); local memberCnt = members.Count for j = 0, memberCnt - 1 do if (j > 0) then _classFieldAnnotation = _classFieldAnnotation .. "\n"; end local memberInfo = members[j] _classFieldAnnotation = _classFieldAnnotation .. string.format('---@field public %s %s', memberInfo.varName, memberInfo.type); end _classTemplateTxt = string.gsub(_classTemplateTxt, "$classFieldAnnotation", _classFieldAnnotation); local _childClassConstructors = "---@sub item class constructor\n" local findCustomUI = false for j = 0, memberCnt - 1 do if (j > 0) then _childClassConstructors = _childClassConstructors .. "\n"; end local memberInfo = members[j] if string.find(memberInfo.type, "UI_") then findCustomUI = true _childClassConstructors = _childClassConstructors .. string.format('local class_%s\n', memberInfo.type) _childClassConstructors = _childClassConstructors .. string.format('if %s then\n', memberInfo.type) _childClassConstructors = _childClassConstructors .. string.format(' class_%s = %s\n', memberInfo.type, memberInfo.type) _childClassConstructors = _childClassConstructors .. string.format('else\n') _childClassConstructors = _childClassConstructors .. string.format(' class_%s = require("%s%s.%s")\n', memberInfo.type, lua_path_root, codePkgName, memberInfo.type) _childClassConstructors = _childClassConstructors .. "end" end end if not findCustomUI then _childClassConstructors = "" end _classTemplateTxt = string.gsub(_classTemplateTxt, "$childClassConstructors", _childClassConstructors); local _urlValue = string.format('"ui://%s%s"', handler.pkg.id, classInfo.classId) _classTemplateTxt = string.gsub(_classTemplateTxt, "$urlValue", _urlValue); _classTemplateTxt = string.gsub(_classTemplateTxt, "$uiPackageName", handler.pkg.name); _classTemplateTxt = string.gsub(_classTemplateTxt, "$uiResName", classInfo.resName); local _classFieldInstatiation = ""; for j = 0, memberCnt - 1 do local memberInfo = members[j] if j > 0 then _classFieldInstatiation = _classFieldInstatiation .. "\n"; end _classFieldInstatiation = _classFieldInstatiation .. "\t"; if memberInfo.group == 0 then local getChildString = "" if getMemberByName then getChildString = string.format('GetChild("%s")', memberInfo.name) else getChildString = string.format('GetChildAt("%s")', memberInfo.index) end if string.find(memberInfo.type, "UI_") then _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = class_%s.CreateFromInst(self.__ui:%s);', memberInfo.varName, memberInfo.type, getChildString); else _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = self.__ui:%s;', memberInfo.varName, getChildString); end elseif memberInfo.group == 1 then if getMemberByName then _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = self.__ui:GetController("%s");', memberInfo.varName, memberInfo.name); else _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = self.__ui:GetControllerAt("%s");', memberInfo.varName, memberInfo.index); end else if getMemberByName then _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = self.__ui:GetTransition("%s");', memberInfo.varName, memberInfo.name); else _classFieldInstatiation = _classFieldInstatiation .. string.format('self.%s = self.__ui:GetTransitionAt("%s");', memberInfo.varName, memberInfo.index); end end end _classTemplateTxt = string.gsub(_classTemplateTxt, "$classFieldInstantiation", _classFieldInstatiation); writer:writeln('%s', _classTemplateTxt); writer:save(exportCodePath .. '/' .. classInfo.className .. '.' .. lua_file_extension_name) end writer:reset() local binderTemplateTxt = CS.System.IO.File.ReadAllText(PluginPath .. "/binder_template.txt"); if (binderTemplateTxt == "") then fprint("binder_template.txt content null.") return ; end local binderName = codePkgName .. 'Binder' local _requireStatement = ""; for i = 0, classCnt - 1 do if (i > 0) then _requireStatement = _requireStatement .. "\n"; end local classInfo = classes[i] _requireStatement = _requireStatement .. string.format('_G.%s = require("%s%s.%s");', classInfo.className, lua_path_root, codePkgName, classInfo.className); end binderTemplateTxt = string.gsub(binderTemplateTxt, "$requireStatement", _requireStatement); binderTemplateTxt = string.gsub(binderTemplateTxt, "$binderClassName", binderName); local _bindStatement = ""; for i = 0, classCnt - 1 do if (i > 0) then _bindStatement = _bindStatement .. "\n"; end local classInfo = classes[i] _bindStatement = _bindStatement .. "\t"; if (key_wrapper_namespace ~= "") then _bindStatement = _bindStatement .. string.format('%sUIObjectFactory.SetPackageItemExtension(%s.URL, typeof(%s));', key_wrapper_namespace .. ".", classInfo.className, classInfo.className); else _bindStatement = _bindStatement .. string.format('UIObjectFactory.SetPackageItemExtension(%s.URL,typeof(%s));', classInfo.className, classInfo.className); end end binderTemplateTxt = string.gsub(binderTemplateTxt, "$bindStatement", _bindStatement); writer:writeln('%s', binderTemplateTxt); writer:save(exportCodePath .. '/' .. binderName .. '.' .. lua_file_extension_name) writer:reset() local _readSuccess, _initTxt = pcall(function() return CS.System.IO.File.ReadAllText(handler.exportCodePath .. "/init.lua"); end); if(not _readSuccess) then _initTxt = ""; end local _requireStatement = string.format('local %s = require("%s%s.%s");',binderName, lua_path_root,codePkgName, binderName); _requireStatement = _requireStatement .. string.format('\n%s:BindAll();',binderName); if(string.find(_initTxt,_requireStatement,1,true) == nil) then _requireStatement = _requireStatement .. "\n"; _initTxt = _initTxt .. _requireStatement; CS.System.IO.File.WriteAllText(handler.exportCodePath .. "/init.lua", _initTxt); end end
DifferentialType = {} ---@type number DifferentialType.Open_4W = 3 ---@type number DifferentialType.Open_RearDrive = 5 ---@type number DifferentialType.LimitedSlip_FrontDrive = 1 ---@type number DifferentialType.LimitedSlip_RearDrive = 2 ---@type number DifferentialType.LimitedSlip_4W = 0 ---@type number DifferentialType.Open_FrontDrive = 4
-- Note: starting with Redis 5, the replication method described in this section (scripts effects replication) is the default and does not need to be explicitly enabled. redis.replicate_commands(); local namespace = KEYS[1]; local configId = ARGV[1]; local targetVersion = ARGV[2]; local op = 'rollback'; local versionField = "version"; local hashField = "hash"; local configIdxKey = namespace .. ":cfg_idx"; local configHistoryIdxKey = namespace .. ":cfg_htr_idx:" .. configId; local configKey = namespace .. ":cfg:" .. configId; local function getConfigHistoryKey(version) return namespace .. ":cfg_htr:" .. configId .. ":" .. tostring(version); end local targetConfigHistoryKey = getConfigHistoryKey(targetVersion); local targetHistoryConfigArray = redis.call("hgetall", targetConfigHistoryKey) if #targetHistoryConfigArray == 0 then return 0; end local function arrayToDictionary(arrayTable) local dicTable = {}; for idx, val in ipairs(arrayTable) do if idx % 2 == 1 then dicTable[val] = arrayTable[idx + 1] end end return dicTable; end local function addHistory(currentVersion, configKey, op) local configHistoryKey = getConfigHistoryKey(currentVersion); redis.call("zadd", configHistoryIdxKey, currentVersion, configHistoryKey); redis.call("rename", configKey, configHistoryKey); local opTime = redis.call('time')[1]; return redis.call("hmset", configHistoryKey, 'op', op, "opTime", opTime); end local targetHistoryConfig = arrayToDictionary(targetHistoryConfigArray); local targetHash = targetHistoryConfig[hashField]; local currentHash = redis.call("hget", configKey, hashField) if (currentHash ~= nil) and (currentHash == targetHash) then return 0; end redis.call("sadd", configIdxKey, configKey, configKey) local currentVersion = redis.call("hget", configKey, versionField) local nextVersion = currentVersion + 1; addHistory(currentVersion, configKey, op) local data = targetHistoryConfig["data"]; local createTime = redis.call('time')[1]; local result = redis.call("hmset", configKey, "configId", configId, "data", data, hashField, targetHash, versionField, nextVersion, "createTime", createTime); redis.call("publish", configKey, op); return result;
if not modules then modules = { } end modules ['mtx-server'] = { version = 1.001, comment = "companion to mtxrun.lua", author = "Hans Hagen & Taco Hoekwater", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local helpinfo = [[ <?xml version="1.0"?> <application> <metadata> <entry name="name">mtx-server</entry> <entry name="detail">Simple Webserver For Helpers</entry> <entry name="version">0.10</entry> </metadata> <flags> <category name="basic"> <subcategory> <flag name="start"><short>start server</short></flag> <flag name="port"><short>port to listen to</short></flag> <flag name="root"><short>server root</short></flag> <flag name="scripts"><short>scripts sub path</short></flag> <flag name="index"><short>index file</short></flag> <flag name="auto"><short>start on own path</short></flag> </subcategory> </category> </flags> </application> ]] local application = logs.application { name = "mtx-server", banner = "Simple Webserver For Helpers 0.10", helpinfo = helpinfo, } local tonumber, tostring, loadfile, type = tonumber, tostring, loadfile, type local find, gsub = string.find, string.gsub local joinpath, filesuffix, dirname, is_qualified_path = file.join, file.suffix, file.dirname, file.is_qualified_path local loaddata = io.loaddata local P, C, patterns, lpegmatch = lpeg.P, lpeg.C, lpeg.patterns, lpeg.match local formatters = string.formatters local urlhashed, urlquery = url.hashed, url.query local report = application.report local gettime = os.gettimeofday or os.clock scripts = scripts or { } scripts.webserver = scripts.webserver or { } dofile(resolvers.findfile("luat-soc.lua","tex")) local socket = socket or require("socket") ----- http = http or require("socket.http") -- not needed -- The following two lists are taken from webrick (ruby) and -- extended with a few extra suffixes. local mimetypes = { ai = 'application/postscript', asc = 'text/plain', avi = 'video/x-msvideo', bin = 'application/octet-stream', bmp = 'image/bmp', bz2 = 'application/x-bzip2', cer = 'application/pkix-cert', class = 'application/octet-stream', crl = 'application/pkix-crl', crt = 'application/x-x509-ca-cert', css = 'text/css', dms = 'application/octet-stream', doc = 'application/msword', dvi = 'application/x-dvi', eps = 'application/postscript', etx = 'text/x-setext', exe = 'application/octet-stream', gif = 'image/gif', gz = 'application/x-tar', hqx = 'application/mac-binhex40', htm = 'text/html', html = 'text/html', jpe = 'image/jpeg', jpeg = 'image/jpeg', jpg = 'image/jpeg', lha = 'application/octet-stream', lzh = 'application/octet-stream', mov = 'video/quicktime', mpe = 'video/mpeg', mpeg = 'video/mpeg', mpg = 'video/mpeg', pbm = 'image/x-portable-bitmap', pdf = 'application/pdf', pgm = 'image/x-portable-graymap', png = 'image/png', pnm = 'image/x-portable-anymap', ppm = 'image/x-portable-pixmap', ppt = 'application/vnd.ms-powerpoint', ps = 'application/postscript', qt = 'video/quicktime', ras = 'image/x-cmu-raster', rb = 'text/plain', rd = 'text/plain', rgb = 'image/x-rgb', rtf = 'application/rtf', sgm = 'text/sgml', sgml = 'text/sgml', snd = 'audio/basic', tar = 'application/x-tar', tgz = 'application/x-tar', tif = 'image/tiff', tiff = 'image/tiff', txt = 'text/plain', xbm = 'image/x-xbitmap', xls = 'application/vnd.ms-excel', xml = 'text/xml', xpm = 'image/x-xpixmap', xwd = 'image/x-xwindowdump', zip = 'application/zip', } local messages = { [100] = 'Continue', [101] = 'Switching Protocols', [200] = 'OK', [201] = 'Created', [202] = 'Accepted', [203] = 'Non-Authoritative Information', [204] = 'No Content', [205] = 'Reset Content', [206] = 'Partial Content', [300] = 'Multiple Choices', [301] = 'Moved Permanently', [302] = 'Found', [303] = 'See Other', [304] = 'Not Modified', [305] = 'Use Proxy', [307] = 'Temporary Redirect', [400] = 'Bad Request', [401] = 'Unauthorized', [402] = 'Payment Required', [403] = 'Forbidden', [404] = 'Not Found', [405] = 'Method Not Allowed', [406] = 'Not Acceptable', [407] = 'Proxy Authentication Required', [408] = 'Request Timeout', [409] = 'Conflict', [410] = 'Gone', [411] = 'Length Required', [412] = 'Precondition Failed', [413] = 'Request Entity Too Large', [414] = 'Request-URI Too Large', [415] = 'Unsupported Media Type', [416] = 'Request Range Not Satisfiable', [417] = 'Expectation Failed', [500] = 'Internal Server Error', [501] = 'Not Implemented', [502] = 'Bad Gateway', [503] = 'Service Unavailable', [504] = 'Gateway Timeout', [505] = 'HTTP Version Not Supported', } local f_content_length = formatters["Content-Length: %s\r\n"] local f_content_type = formatters["Content-Type: %s\r\n"] local f_error_title = formatters["<head><title>%s %s</title></head><html><h2>%s %s</h2></html>"] local handlers = { } local function errormessage(client,configuration,n) local data = f_error_title(n,messages[n],n,messages[n]) report("handling error %s: %s",n,messages[n]) handlers.generic(client,configuration,data,nil,true) end local validpaths, registered = { }, { } function scripts.webserver.registerpath(name) if not registered[name] then local cleanname = gsub(name,"%.%.","deleted-parent") report("registering path: %s",cleanname) validpaths[#validpaths+1] = cleanname registered[name] = true end end function handlers.generic(client,configuration,data,suffix,iscontent) local name = data if not iscontent then report("requested file: %s",name) local fullname = joinpath(configuration.root,name) data = loaddata(fullname) or "" if data == "" then for n=1,#validpaths do local fullname = joinpath(validpaths[n],name) data = loaddata(fullname) or "" if data ~= "" then report("sending generic file: %s",fullname) break end end else report("sending generic file: %s",fullname) end end if data and data ~= "" then client:send("HTTP/1.1 200 OK\r\n") client:send("Connection: close\r\n") client:send(f_content_length(#data)) client:send(f_content_type(suffix and mimetypes[suffix] or "text/html")) client:send("Cache-Control: no-cache, no-store, must-revalidate, max-age=0\r\n") client:send("\r\n") client:send(data) client:send("\r\n") else report("unknown file: %s",tostring(name)) errormessage(client,configuration,404) end end -- return os.date() -- return { content = "crap" } -- return function(configuration,filename) -- return { content = filename } -- end local loaded = { } function handlers.lua(client,configuration,filename,suffix,iscontent,hashed) -- filename will disappear, and become hashed.filename local filename = joinpath(configuration.scripts,filename) if not is_qualified_path(filename) then filename = joinpath(configuration.root,filename) end -- todo: split url in components, see l-url; rather trivial local result, keep = loaded[filename], false if result then report("reusing script: %s",filename) else report("locating script: %s",filename) if lfs.isfile(filename) then report("loading script: %s",filename) result = loadfile(filename) report("return type: %s",type(result)) if result and type(result) == "function" then -- result() should return a table { [type=,] [length=,] content= }, function or string result, keep = result() if keep then report("saving script: %s",type(result)) loaded[filename] = result end end else report("problematic script: %s",filename) errormessage(client,configuration,404) end end if result then if type(result) == "function" then report("running script: %s",filename) result = result(configuration,filename,hashed) -- second argument will become query end if result and type(result) == "string" then result = { content = result } end if result and type(result) == "table" then if result.content then local suffix = result.type or "text/html" local action = handlers[suffix] or handlers.generic action(client,configuration,result.content,suffix,true) -- content elseif result.filename then local suffix = filesuffix(result.filename) or "text/html" local action = handlers[suffix] or handlers.generic action(client,configuration,result.filename,suffix,false) -- filename else report("no content of filename in result") errormessage(client,configuration,404) end else report("no valid result") errormessage(client,configuration,500) end else report("no result") errormessage(client,configuration,404) end end handlers.luc = handlers.lua handlers.html = handlers.htm local indices = { "index.htm", "index.html" } local portnumber = 8088 local newline = patterns.newline local spacer = patterns.spacer local whitespace = patterns.whitespace local method = P("GET") + P("POST") local identify = (1-method)^0 * C(method) * spacer^1 * C((1-spacer)^1) * spacer^1 * P("HTTP/") * (1-whitespace)^0 * C(P(1)^0) function scripts.webserver.run(configuration) -- check configuration configuration.port = tonumber(configuration.port or os.getenv("MTX_SERVER_PORT") or portnumber) or portnumber if not configuration.root or not lfs.isdir(configuration.root) then configuration.root = os.getenv("MTX_SERVER_ROOT") or "." end -- locate root and index file in tex tree if not lfs.isdir(configuration.root) then for i=1,#indices do local name = indices[i] local root = resolvers.resolve("path:" .. name) or "" if root ~= "" then configuration.root = root configuration.index = configuration.index or name break end end end configuration.root = dir.expandname(configuration.root) if not configuration.index then for i=1,#indices do local name = indices[i] if lfs.isfile(joinpath(configuration.root,name)) then configuration.index = name -- we will prepend the rootpath later break end end configuration.index = configuration.index or "unknown" end if not configuration.scripts or configuration.scripts == "" then configuration.scripts = dir.expandname(joinpath(configuration.root or ".",configuration.scripts or ".")) end -- so far for checks report("running at port: %s",configuration.port) report("document root: %s",configuration.root or resolvers.ownpath) report("main index file: %s",configuration.index) report("scripts subpath: %s",configuration.scripts) report("context services: http://localhost:%s/mtx-server-ctx-startup.lua",configuration.port) local server = assert(socket.bind("*", configuration.port)) local script = configuration.script while true do -- blocking -- local start = gettime() local client = server:accept() client:settimeout(configuration.timeout or 60) local request, e = client:receive() if e then -- probably a time out -- errormessage(client,configuration,404) else local from = client:getpeername() report("request from: %s",tostring(from)) report("request data: %s",tostring(request)) -- local fullurl = match(request,"(GET) (.+) HTTP/.*$") or "" -- todo: more clever / post -- if fullurl == "" then local method, fullurl, body = lpegmatch(identify,request) if method == "" or fullurl == "" then report("no url") errormessage(client,configuration,404) else -- todo: method: POST fullurl = url.unescapeget(fullurl) report("requested url: %s",fullurl) -- fullurl = socket.url.unescape(fullurl) -- happens later local hashed = urlhashed(fullurl) local query = urlquery(hashed.query) local filename = hashed.path -- hm, not query? hashed.body = body if script then filename = script report("forced script: %s",filename) local suffix = filesuffix(filename) local action = handlers[suffix] or handlers.generic if action then report("performing action: %s",filename) action(client,configuration,filename,suffix,false,hashed) -- filename and no content else report("invalid action: %s",filename) errormessage(client,configuration,404) end elseif filename then local rawname = socket.url.unescape(filename) filename = rawname report("requested action: %s",filename or "?") if find(filename,"%.%.") then filename = nil -- invalid path end if filename == nil or filename == "" or filename == "/" then filename = configuration.index report("invalid filename, forcing: %s",filename) end local suffix = filesuffix(filename) local action = handlers[suffix] or handlers.generic if action then report("performing action: %s",filename or "?") action(client,configuration,filename,suffix,false,hashed) -- filename and no content else report("invalid action: %s",filename or "?") errormessage(client,configuration,404) end else report("invalid request") errormessage(client,configuration,404) end end end client:close() -- report("time spent with client: %0.03f seconds",gettime()-start) end end if environment.argument("auto") then local path = resolvers.findfile("mtx-server.lua") or "." scripts.webserver.run { port = environment.argument("port"), root = environment.argument("root") or dirname(path) or ".", scripts = environment.argument("scripts") or dirname(path) or ".", script = environment.argument("script"), } elseif environment.argument("start") then scripts.webserver.run { port = environment.argument("port"), root = environment.argument("root") or ".", -- "e:/websites/www.pragma-ade.com", index = environment.argument("index"), scripts = environment.argument("scripts"), script = environment.argument("script"), } elseif environment.argument("exporthelp") then application.export(environment.argument("exporthelp"),environment.files[1]) else application.help() end -- mtxrun --script server --start => http://localhost:8088/mtx-server-ctx-startup.lua
return {'osogovgebergte'}
local M = {} M.user_mgr = nil M.common_handler = nil return M
local ffi = require 'ffi' require 'exports.mswindows.guids' ffi.cdef [[ typedef struct WAVEFORMATEX { uint16_t wFormatTag; uint16_t nChannels; uint32_t nSamplesPerSec; uint32_t nAvgBytesPerSec; uint16_t nBlockAlign; uint16_t wBitsPerSample; uint16_t cbSize; } WAVEFORMATEX; #pragma pack(1) typedef struct WAVEFORMATEXTENSIBLE { uint16_t wFormatTag; uint16_t nChannels; uint32_t nSamplesPerSec; uint32_t nAvgBytesPerSec; uint16_t nBlockAlign; uint16_t wBitsPerSample; uint16_t cbSize; uint16_t wValidBitsPerSample; uint32_t dwChannelMask; GUID SubFormat; } WAVEFORMATEXTENSIBLE; #pragma pack(pop) enum { WAVE_FORMAT_PCM = 0x0001, WAVE_FORMAT_EXTENSIBLE = 0xFFFE }; ]] return ffi.C
require "scripts.GameUtils" require "scripts/library/timers" --require("gamemode.spark.abilities...runes.bounty_rune") local Rune = { Properties = { rune_type = {default = "bounty_rune", description = ""}, }, } function Rune:OnActivate() Debug.Log("Rune:OnActivate") CreateTimer(function() self:Init() end,0.1); end function Rune:Init() self.rightClickHandler = OnRightClickedNotificationBus.Connect(self,self.entityId) self.pickupAbility = CreateAbility("runes/"..self.Properties.rune_type) end function Rune:OnRightClickedFilter() Debug.Log("Rune:OnRightClicked()"); FilterResult(FilterResult.FILTER_PREVENT); local unitId = SelectionRequestBus.Broadcast.GetMainSelectedUnit() if not HasTag(unitId,"hero") then return end local castContext = CastContext() castContext.Caster = unitId castContext.Target = self.entityId castContext.Ability = GetId(self.pickupAbility) castContext.BehaviorUsed = CastingBehavior(CastingBehavior.UNIT_TARGET) UnitRequestBus.Event.NewOrder(unitId,CastOrder(castContext),false); end function Rune:OnDeactivate() if self.pickupAbility then self.pickupAbility:DetachAndDestroy(); self.rightClickHandler:Disconnect() end end return Rune;
local room_max_players = 12 onEvent("PacketReceived", function(channel, id, packet) if channel ~= "bots" then return end if id == 0 then if packet == room.shortName then tfm.exec.setRoomMaxPlayers(room_max_players + 10) addNewTimer(15000, tfm.exec.setRoomMaxPlayers, room_max_players) end end end)
local openssl = require'openssl' local ssl,pkey,x509 = openssl.ssl,openssl.pkey,openssl.x509 local M = {} local function load(path) local f = assert(io.open(path,'r')) if f then local c = f:read('*all') f:close() return c end end function M.new(params) local protocol = params.protocol and string.upper(string.sub(params.protocol,1,3)) ..string.sub(params.protocol,4,-1) or 'TLSv1_2' local ctx = ssl.ctx_new(protocol,params.ciphers) local xkey = nil if (type(params.password)=='nil') then xkey = assert(pkey.read(load(params.key),true,'pem')) elseif (type(params.password)=='string') then xkey = assert(pkey.read(load(params.key),true,'pem',params.password)) elseif (type(params.password)=='function') then local p = assert(params.password()) xkey = assert(pkey.read(load(params.key),true,'pem',p)) end assert(xkey) local xcert = nil if (params.certificate) then xcert = assert(x509.read(load(params.certificate))) end assert(ctx:use( xkey, xcert)) if(params.cafile or params.capath) then ctx:verify_locations(params.cafile,params.capath) end unpack = unpack or table.unpack if(params.verify) then ctx:verify_mode(params.verify) end if params.options then local args = {} for i=1,#params.options do table.insert(args,params.options[i]) end ctx:options(unpack(args)) end if params.verifyext then for k,v in pairs(params.verifyext) do params.verifyext[k] = string.gsub(v,'lsec_','') end ctx:set_cert_verify(params.verifyext) end if params.dhparam then ctx:set_tmp('dh',params.dhparam) end if params.curve then ctx:set_tmp('ecdh',params.curve) end return ctx end return M
class("HarvestResourceCommand", pm.SimpleCommand).execute = function (slot0, slot1) slot3 = id2res(slot2) slot5 = getProxy(PlayerProxy).getData(slot4) slot6 = nil if slot1:getBody() == 1 then slot6 = slot5:getLevelMaxGold() elseif slot2 == 2 then slot6 = slot5:getLevelMaxOil() end if slot6 <= slot5[slot3] then pg.TipsMgr.GetInstance():ShowTips(i18n("player_harvestResource_error_fullBag")) return end pg.ConnectionMgr.GetInstance():Send(11013, { number = 0, type = slot2 }, 11014, function (slot0) if slot0.result == 0 then if slot0 - slot1[] < slot1[slot2 .. "Field"] then slot1:addResources({ [slot2] = slot1 }) slot1[slot2 .. "Field"] = slot1[slot2 .. "Field"] - slot1 else slot1:addResources({ [slot1[slot2 .. "Field"]] = slot1[slot2 .. "Field"] }) slot1[slot2 .. "Field"] = 0 end slot3:updatePlayer(slot1) slot3:sendNotification(GAME.HARVEST_RES_DONE, { type = GAME.HARVEST_RES_DONE, outPut = slot2 }) pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_UI_ACADEMY_GETMATERIAL) else pg.TipsMgr.GetInstance():ShowTips(errorTip("player_harvestResource", slot0.result)) end end) end return class("HarvestResourceCommand", pm.SimpleCommand)
X = {} local IBUtil = require(GetScriptDirectory() .. "/ItemBuildlogic"); local npcBot = GetBot(); local talents = IBUtil.FillTalenTable(npcBot); local skills = IBUtil.FillSkillTable(npcBot, IBUtil.GetSlotPattern(3)); X["items"] = { "item_poor_mans_shield", "item_boots", "item_magic_wand", "item_phase_boots", "item_desolator", "item_sange_and_yasha", "item_silver_edge", "item_blink", "item_monkey_king_bar" }; X["skills"] = IBUtil.GetBuildPattern( "normal", {1,2,1,2,1,4,1,2,2,3,4,3,3,3,4}, skills, {2,4,5,8}, talents ); return X
name = "Dig" author = "MeltWS" description = [[Dig Maps]] local pf = require "Pathfinder/MoveToApp" -- requesting table with methods local map = nil local DigMaps = { "Route 15", "Route 14", } function onPathAction() map = getMapName() if not pf.moveTo(map, DigMaps[1]) then table.remove(DigMaps, 1) if DigMaps[1] then log("Map " .. map .. ", no more dig to do, moving to:" .. tostring(DigMaps[1])) pf.moveTo(map, DigMaps[1]) else fatal("No more maps to dig") end end end function onBattleAction() run() end
-- Called on Spell Start -- Blinks the target to the target point, if the point is beyond max blink range then blink the maximum range]] function Blink(keys) local point = keys.target_points[1] local caster = keys.caster local casterPos = caster:GetAbsOrigin() local difference = point - casterPos difference.z = 0.0 local difference_norm_vector = difference:Normalized() local ability = keys.ability local ability_level = ability:GetLevel() - 1 local range = ability:GetLevelSpecialValueFor("blink_range", ability_level) if difference:Length2D() > range then point = casterPos + difference_norm_vector * range end -- Start Particle local blinkIndex = ParticleManager:CreateParticle("particles/items_fx/blink_dagger_start.vpcf", PATTACH_ABSORIGIN, caster) Timers:CreateTimer( 1, function() ParticleManager:DestroyParticle(blinkIndex, false) ParticleManager:ReleaseParticleIndex(blinkIndex) return nil end ) -- Teleporting caster and preventing getting stuck FindClearSpaceForUnit(caster, point, false) -- Disjoint disjointable/dodgeable projectiles ProjectileManager:ProjectileDodge(caster) -- End Particle local blink_end_index = ParticleManager:CreateParticle("particles/items_fx/blink_dagger_end.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:ReleaseParticleIndex(blink_end_index) end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("core.base.option") import("core.project.config") import("lib.detect.cache") import("lib.detect.find_tool") -- has the given flags for the current tool? -- -- @param name the tool name -- @param flags the flags -- @param opt the argument options, .e.g {verbose = false, program = "", toolkind = "[cc|cxx|ld|ar|sh|gc|rc|dc|mm|mxx]"} -- -- @return true or false -- -- @code -- local ok = has_flags("clang", "-g") -- local ok = has_flags("clang", {"-g", "-O0"}, {program = "xcrun -sdk macosx clang"}) -- local ok = has_flags("clang", "-g", {toolkind = "cxx"}) -- @endcode -- function main(name, flags, opt) -- init options opt = opt or {} -- find tool program and version first opt.version = true local tool = find_tool(name, opt) if not tool then return false end -- wrap flags flags = table.wrap(flags) -- split flag group, .e.g "-I /xxx" => {"-I", "/xxx"} local results = {} for _, flag in ipairs(flags) do flag = flag:trim() if #flag > 0 then if flag:find(" ", 1, true) then table.join2(results, os.argv(flag)) else table.insert(results, flag) end end end flags = results -- init tool opt.toolname = tool.name opt.program = tool.program opt.programver = tool.version -- get tool arch -- -- some tools select arch by path environment, not be flags, .e.g cl.exe of msvc) -- so, it will affect the cache result -- local arch = config.get("arch") or os.arch() -- init cache key local key = tool.program .. "_" .. (tool.version or "") .. "_" .. (opt.toolkind or "") .. "_" .. table.concat(flags, " ") .. "_" .. arch -- @note avoid detect the same program in the same time if running in the coroutine (.e.g ccache) local coroutine_running = coroutine.running() if coroutine_running then while _g._checking ~= nil and _g._checking == key do local curdir = os.curdir() coroutine.yield() os.cd(curdir) end end -- attempt to get result from cache first local cacheinfo = cache.load("lib.detect.has_flags") local result = cacheinfo[key] if result ~= nil then return result end -- detect.tools.xxx.has_flags(flags, opt)? _g._checking = ifelse(coroutine_running, key, nil) local hasflags = import("detect.tools." .. tool.name .. ".has_flags", {try = true}) local errors = nil if hasflags then result, errors = hasflags(flags, opt) else result = try { function () os.runv(tool.program, flags); return true end, catch { function (errs) errors = errs end }} end _g._checking = nil -- trace if option.get("verbose") or opt.verbose then cprint("checking for the flags(%s) %s ... %s", path.filename(tool.program), table.concat(flags, " "), ifelse(result, "${green}ok", "${red}no")) if errors and #errors > 0 then cprint("${dim red}check error:${clear}${dim} %s", errors:trim()) end end -- save result to cache cacheinfo[key] = ifelse(result, result, false) cache.save("lib.detect.has_flags", cacheinfo) -- ok? return result end
--[[ This code is not injected into Discordia; It is identical to the one used in Discordia, only defined here for ease of access. Code below is copied from SinisterRectus/Discordia with minor modifications, All rights reserved for the original maintainer. --]] local fs = require("fs") local Resolver = require("client/Resolver") local splitPath = require("pathjoin").splitPath local function parseFile(obj, files) local obj_type = type(obj) if obj_type == "string" then local data, err = fs.readFileSync(obj) if not data then return nil, err end files = files or {} table.insert(files, {table.remove(splitPath(obj)), data}) elseif obj_type == "table" and type(obj[1]) == "string" and type(obj[2]) == "string" then files = files or {} table.insert(files, obj) else return nil, "Invalid file object: " .. tostring(obj) end return files end local function parseMention(obj, mentions) if type(obj) == "table" and obj.mentionString then mentions = mentions or {} table.insert(mentions, obj.mentionString) else return nil, "Unmentionable object: " .. tostring(obj) end return mentions end local blacklisted_fields = { content = true, code = true, mention = true, mentions = true, file = true, files = true, reference = true, payload_json = true, } local function parseMessage(content) local err if type(content) == "table" then ---@type table local tbl = content content = tbl.content if type(tbl.code) == "string" then content = string.format("```%s\n%s\n```", tbl.code, content) elseif tbl.code == true then content = string.format("```\n%s\n```", content) end local mentions if tbl.mention then mentions, err = parseMention(tbl.mention) if err then return nil, err end end if type(tbl.mentions) == "table" then for _, mention in ipairs(tbl.mentions) do mentions, err = parseMention(mention, mentions) if err then return nil, err end end end if mentions then table.insert(mentions, content) content = table.concat(mentions, ' ') end local files if tbl.file then files, err = parseFile(tbl.file) if err then return nil, err end end if type(tbl.files) == "table" then for _, file in ipairs(tbl.files) do files, err = parseFile(file, files) if err then return nil, err end end end local refMessage, refMention if tbl.reference then refMessage = {message_id = Resolver.messageId(tbl.reference.message)} refMention = { parse = {"users", "roles", "everyone"}, replied_user = not not tbl.reference.mention, } end local result = { content = content, message_reference = tbl.message_reference or refMessage, allowed_mentions = tbl.allowed_mentions or refMention, } for k, v in pairs(tbl) do if not blacklisted_fields[k] then result[k] = v end end return result, files else return {content = content} end end return { parseMessage = parseMessage, }
object_tangible_loot_npc_loot_cloth_box_generic = object_tangible_loot_npc_loot_shared_cloth_box_generic:new { } ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_cloth_box_generic, "object/tangible/loot/npc/loot/cloth_box_generic.iff")
local default = require 'lib.gui.default' local Class=require 'lib.hc.class' local Container = require 'lib.gui.container' local MouseManager = require 'lib.gui.mouseManager' local ZoneClicker = require 'lib.gui.zoneClicker' local lg = love.graphics local Window=Class{inherits={Container},name="Window"} local WindowComp=Class {name='WindowComp'} local WindowDragger=Class {inherits={MouseManager}} function Window:construct(title,w,h) local wcomp = WindowComp(title) local mw,mh = wcomp:getMinDimension() if mw > w then w = mw end if mh > h then h = mh end Container.construct(self,w,h,wcomp) end function WindowDragger:construct(window,ox,oy) self.w = window self.ox,self.oy=ox,oy end function WindowDragger:move(x,y) local dx,dy = x-self.ox,y-self.oy self.w:move(dx,dy) self:add(dx,dy) end function WindowDragger:unclick(left,x,y) if left then return true end end function WindowComp:construct(title) self.title = title self.tw = default.titleFont:getWidth(title) self.th = default.titleFont:getHeight() + 4 self.bw = default.titleFont:getWidth("X")+4 end function WindowComp:getMinDimension() return self.tw+self.bw+15,self.th+5 end function WindowComp:draw(sx,sy) lg.setColor(default.bgColor) lg.rectangle('fill',sx,sy,self.w,self.h) lg.setColor(default.fgColor) lg.rectangle('line',sx,sy,self.w,self.h) lg.line(sx,sy+self.th,sx+self.w-1,sy+self.th) lg.line(sx+self.w-self.bw,sy,sx+self.w-self.bw,sy+self.th) lg.setFont(default.titleFont) lg.printf(self.title,sx,sy+2,self.w-self.bw,'center') if self.active then lg.rectangle('fill',sx+self.w-self.bw,sy,self.bw,self.th) lg.setColor(default.bgColor) end lg.printf("X",sx+self.w-self.bw,sy+2,self.bw,'center') end function WindowComp:click(left,x,y) self.parent.parent:top(self.parent) if left then if y < self.th and x >= self.w - self.bw then local zc = ZoneClicker(self,self.w-self.bw,0,self.bw,self.th,true) zc.ackCB = function (v) self.active=false; if v then local cb = self.closeCB or self.parent.closeCB if cb then cb() end end end return zc else return WindowDragger(self.parent,x,y) end end end function Window:setMainComponent(comp) self.children={comp} comp.parent=self local mw,mh = self.background:getMinDimension() if mw < comp.w+10 then mw = comp.w +10 end local fh = mh + comp.h+10 comp.x = math.floor((mw - comp.w)/2) comp.y = mh + 2 self:setDimension(mw,fh) end return Window
-- Created by Lef, UnifyID -- Handle your ML state here. -- Local module local M ={} function M.handleOutputFile(filename, content) -- TODO: Placeholder for real ML processing -- Dear ML Engineer who's gonna read this, -- Feel free to use your model to return the -- output vector of your model. print("Output file: " .. filename .. "...") return 42 end function M.handleTrainFile(filename, content) -- TODO: Placeholder for real ML processing per row -- Dear ML Engineer who's gonna read this, -- Feel free to train your model inside this function. -- Each file will be received, printing them will show -- their format. print("Training file: " .. filename .. "...") print(filecontent) end function M.handleInputFile(filename, content) -- TODO: Placeholder for real ML processing per row -- Dear ML Engineer who's gonna read this, -- Feel free to train your model inside this function. -- Each file will be received, printing them will show -- their format. print("Input file: " .. filename .. "...") print(filecontent) end return M
local oldvguicreate = vgui.Create function vgui.Create(...) print(arg[1]) return oldvguicreate(unpack(arg)) end
local h = require('helpful') vim.api.nvim_exec('filetype plugin indent on', true) vim.api.nvim_exec('syntax enable', true) local indent = 2 h.setoption { scrolloff = 3, sidescrolloff = 5, mouse = 'a', termguicolors = true, guifont = 'FiraCode NF', laststatus = 2, showtabline = 2, signcolumn = 'yes', number = true, cursorline = true, showmode = false, list = true, listchars = 'tab:>-,trail:·,eol:↲', -- ↵↲⏎ foldmethod = 'expr', foldexpr = 'nvim_treesitter#foldexpr()', foldlevel = 99, wrap = false, linebreak = true, breakindent = true, breakindentopt = 'shift:2', showbreak = '> ', tabstop = indent, softtabstop = indent, shiftwidth = indent, smartindent = true, copyindent = false, expandtab = true, incsearch = true, hlsearch = true, ignorecase = true, smartcase = true, updatetime = 100, backspace = 'indent,eol,start', splitbelow = true, splitright = true, completeopt ='menuone,noinsert,noselect', } -- reassign in buffer and window scope because nvim vim.bo.tabstop = indent vim.bo.softtabstop = indent vim.bo.shiftwidth = indent vim.bo.smartindent = true vim.bo.expandtab = true vim.wo.signcolumn = 'yes' vim.wo.number = true vim.wo.cursorline = true vim.wo.foldmethod = 'expr' vim.wo.foldexpr = 'nvim_treesitter#foldexpr()' vim.wo.foldlevel = 99 vim.wo.list = true vim.wo.wrap = false vim.wo.linebreak = true vim.wo.breakindent = true vim.wo.breakindentopt = 'shift:2' vim.api.nvim_exec([[set shortmess+=c]], true) h.setglobal { netrw_banner = 0, netrw_liststyle = 3, netrw_browse_split = 4, netrw_winsize = 20, netrw_home = vim.fn.stdpath('data'), vimsyn_embed = 'lPr', } -- vim.api.nvim_exec([[autocmd! User GoyoEnter Limelight]], true) -- vim.api.nvim_exec([[autocmd! User GoyoLeave Limelight!]], true)
local BasePlugin = require "kong.plugins.base_plugin" local body_modifier = require "kong.plugins.reskeymod.body_modifier" local concat = table.concat local lower = string.lower local find = string.find local kong = kong local ngx = ngx -- Check if rename_body_key is enabled -- Return True or False local function is_body_transform_set(conf) return #conf.rename_body_key.json > 0 end -- Check if content_type is application/json -- Return True of False local function is_json_body(content_type) return content_type and find(lower(content_type), "application/json", nil, true) end local ResKeyModHandler = BasePlugin:extend() function ResKeyModHandler:new() ResKeyModHandler.super.new(self, "reskeymod") end function ResKeyModHandler:body_filter(conf) ResKeyModHandler.super.body_filter(self) if is_body_transform_set(conf) and is_json_body(kong.response.get_header("Content-Type")) then local ctx = ngx.ctx local chunk, eof = ngx.arg[1], ngx.arg[2] ctx.rt_body_chunks = ctx.rt_body_chunks or {} ctx.rt_body_chunk_number = ctx.rt_body_chunk_number or 1 if eof then local chunks = concat(ctx.rt_body_chunks) local body = body_modifier.modify_json_body(conf, chunks) ngx.arg[1] = body or chunks else ctx.rt_body_chunks[ctx.rt_body_chunk_number] = chunk ctx.rt_body_chunk_number = ctx.rt_body_chunk_number + 1 ngx.arg[1] = nil end end end ResKeyModHandler.PRIORITY = 800 ResKeyModHandler.VERSION = "1.0.0" return ResKeyModHandler
local route_2_0 = DoorSlot("route_2","0") local route_2_0_hub = DoorSlotHub("route_2","0",route_2_0) route_2_0:setHubIcon(route_2_0_hub) local route_2_1 = DoorSlot("route_2","1") local route_2_1_hub = DoorSlotHub("route_2","1",route_2_1) route_2_1:setHubIcon(route_2_1_hub) local route_2_2 = DoorSlot("route_2","2") local route_2_2_hub = DoorSlotHub("route_2","2",route_2_2) route_2_2:setHubIcon(route_2_2_hub) local route_2_3 = DoorSlot("route_2","3") local route_2_3_hub = DoorSlotHub("route_2","3",route_2_3) route_2_3:setHubIcon(route_2_3_hub) local route_2_4 = DoorSlot("route_2","4") local route_2_4_hub = DoorSlotHub("route_2","4",route_2_4) route_2_4:setHubIcon(route_2_4_hub) local route_2_5 = DoorSlot("route_2","5") local route_2_5_hub = DoorSlotHub("route_2","5",route_2_5) route_2_5:setHubIcon(route_2_5_hub)
-- -- Register biomes -- -- All mapgens except mgv6 function terrain.register_biomes(upper_limit) --[[ minetest.register_biome({ name = "icesheet", node_dust = "default:snowblock", node_top = "default:snowblock", depth_top = 1, node_filler = "default:snowblock", depth_filler = 3, node_stone = "default:cave_ice", node_water_top = "default:ice", depth_water_top = 10, node_river_water = "default:ice", node_riverbed = "default:gravel", depth_riverbed = 2, y_max = upper_limit, y_min = -8, heat_point = 0, humidity_point = 73, }) minetest.register_biome({ name = "icesheet_ocean", node_dust = "default:snowblock", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_water_top = "default:ice", depth_water_top = 10, y_max = -9, y_min = -112, heat_point = 0, humidity_point = 73, }) -- Tundra minetest.register_biome({ name = "tundra_highland", node_dust = "default:snow", node_riverbed = "default:gravel", depth_riverbed = 2, y_max = upper_limit, y_min = 47, heat_point = 0, humidity_point = 40, }) minetest.register_biome({ name = "tundra", node_top = "default:permafrost_with_stones", depth_top = 1, node_filler = "default:permafrost", depth_filler = 1, node_riverbed = "default:gravel", depth_riverbed = 2, vertical_blend = 4, y_max = 46, y_min = 2, heat_point = 0, humidity_point = 40, }) ]]-- minetest.register_biome({ name = "tundra_beach", node_top = "rock:gravel", depth_top = 1, node_filler = "rock:gravel", depth_filler = 2, node_riverbed = "rock:gravel", depth_riverbed = 2, vertical_blend = 1, y_max = 1, y_min = -3, heat_point = 0, humidity_point = 40, }) minetest.register_biome({ name = "tundra_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "rock:gravel", depth_riverbed = 2, vertical_blend = 1, y_max = -4, y_min = -112, heat_point = 0, humidity_point = 40, }) -- Taiga --[[ minetest.register_biome({ name = "taiga", node_dust = "default:snow", node_top = "soil:dirt_with_snow", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 4, heat_point = 25, humidity_point = 70, }) minetest.register_biome({ name = "taiga_ocean", node_dust = "default:snow", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 3, y_min = -112, heat_point = 25, humidity_point = 70, }) -- Snowy grassland minetest.register_biome({ name = "snowy_grassland", node_dust = "default:snow", node_top = "soil:dirt_with_snow", depth_top = 1, node_filler = "soil:dirt", depth_filler = 1, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 4, heat_point = 20, humidity_point = 35, }) minetest.register_biome({ name = "snowy_grassland_ocean", node_dust = "default:snow", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 3, y_min = -112, heat_point = 20, humidity_point = 35, }) ]]-- -- Grassland minetest.register_biome({ name = "grassland", node_top = "soil:grass", depth_top = 1, node_filler = "soil:dirt", depth_filler = 1, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 6, heat_point = 50, humidity_point = 35, }) minetest.register_biome({ name = "grassland_dunes", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 2, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 5, y_min = 4, heat_point = 50, humidity_point = 35, }) minetest.register_biome({ name = "grassland_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 3, y_min = -112, heat_point = 50, humidity_point = 35, }) -- Coniferous forest --[[ minetest.register_biome({ name = "coniferous_forest", node_top = "soil:dirt_with_coniferous_litter", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 6, heat_point = 45, humidity_point = 70, }) ]]-- minetest.register_biome({ name = "coniferous_forest_dunes", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 5, y_min = 4, heat_point = 45, humidity_point = 70, }) minetest.register_biome({ name = "coniferous_forest_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 3, y_min = -112, heat_point = 45, humidity_point = 70, }) -- Deciduous forest minetest.register_biome({ name = "deciduous_forest", node_top = "soil:grass", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 1, heat_point = 60, humidity_point = 68, }) minetest.register_biome({ name = "deciduous_forest_shore", node_top = "soil:dirt", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 0, y_min = -1, heat_point = 60, humidity_point = 68, }) minetest.register_biome({ name = "deciduous_forest_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = -2, y_min = -112, heat_point = 60, humidity_point = 68, }) -- Desert minetest.register_biome({ name = "desert", node_top = "sand:desert", depth_top = 1, node_filler = "sand:desert", depth_filler = 1, node_stone = "rock:desert", node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 4, heat_point = 92, humidity_point = 16, }) minetest.register_biome({ name = "desert_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_stone = "rock:desert", node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 3, y_min = -112, heat_point = 92, humidity_point = 16, }) -- Sandstone desert minetest.register_biome({ name = "sandstone_desert", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 1, node_stone = "sand:stone", node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 4, heat_point = 60, humidity_point = 0, }) minetest.register_biome({ name = "sandstone_desert_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_stone = "sand:stone", node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 3, y_min = -112, heat_point = 60, humidity_point = 0, }) -- Cold desert --[[ minetest.register_biome({ name = "cold_desert", node_top = "default:silver_sand", depth_top = 1, node_filler = "default:silver_sand", depth_filler = 1, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 4, heat_point = 40, humidity_point = 0, }) ]]-- minetest.register_biome({ name = "cold_desert_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = 3, y_min = -112, heat_point = 40, humidity_point = 0, }) -- Savanna minetest.register_biome({ name = "savanna", node_top = "soil:grass_dry", depth_top = 1, node_filler = "soil:dirt", depth_filler = 1, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 1, heat_point = 89, humidity_point = 42, }) minetest.register_biome({ name = "savanna_shore", node_top = "soil:dirt", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 0, y_min = -1, heat_point = 89, humidity_point = 42, }) minetest.register_biome({ name = "savanna_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = -2, y_min = -112, heat_point = 89, humidity_point = 42, }) -- Rainforest minetest.register_biome({ name = "rainforest", node_top = "soil:rainforest", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = upper_limit, y_min = 1, heat_point = 86, humidity_point = 65, }) minetest.register_biome({ name = "rainforest_swamp", node_top = "soil:dirt", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, y_max = 0, y_min = -1, heat_point = 86, humidity_point = 65, }) minetest.register_biome({ name = "rainforest_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, node_riverbed = "sand:sand", depth_riverbed = 2, vertical_blend = 1, y_max = -2, y_min = -112, heat_point = 86, humidity_point = 65, }) -- Underground minetest.register_biome({ name = "underground", y_max = -113, y_min = -31000, heat_point = 50, humidity_point = 50, }) end -- Biomes for floatlands -- TODO Temporary simple biomes to be replaced by special floatland biomes later. function terrain.register_floatland_biomes(floatland_level, shadow_limit) minetest.register_biome({ name = "floatland_grassland", node_top = "soil:grass", depth_top = 1, node_filler = "soil:dirt", depth_filler = 1, y_max = 31000, y_min = floatland_level + 2, heat_point = 50, humidity_point = 25, }) --[[ minetest.register_biome({ name = "floatland_coniferous_forest", node_top = "soil:dirt_with_coniferous_litter", depth_top = 1, node_filler = "soil:dirt", depth_filler = 3, y_max = 31000, y_min = floatland_level + 2, heat_point = 50, humidity_point = 75, }) ]]-- minetest.register_biome({ name = "floatland_ocean", node_top = "sand:sand", depth_top = 1, node_filler = "sand:sand", depth_filler = 3, y_max = floatland_level + 1, y_min = shadow_limit, heat_point = 50, humidity_point = 50, }) end
mission_proto = { [1] = { type = 1, sontype = 1, missiontype = 2, param = { {10}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [2] = { type = 1, sontype = 1, missiontype = 2, param = { {20}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [3] = { type = 1, sontype = 1, missiontype = 2, param = { {30}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [4] = { type = 1, sontype = 1, missiontype = 2, param = { {40}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [5] = { type = 1, sontype = 1, missiontype = 2, param = { {50}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [6] = { type = 1, sontype = 1, missiontype = 2, param = { {60}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [7] = { type = 1, sontype = 1, missiontype = 2, param = { {70}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [8] = { type = 1, sontype = 1, missiontype = 2, param = { {80}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [9] = { type = 1, sontype = 1, missiontype = 2, param = { {90}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, [10] = { type = 1, sontype = 1, missiontype = 2, param = { {100}, }, reward = { {1, 5, 100}, }, funcid = 5, times = 1, }, } return mission_proto
--[[ Copyright 2015 vurtual VurtualRuler98@gmail.com vurtual.org Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- if (SERVER) then AddCSLuaFile("shared.lua") end if (CLIENT) then SWEP.PrintName = "ins2 'M91/30 Tranquilizer'" SWEP.Author = "vurtual" SWEP.Slot = 2 SWEP.SlotPos = 0 end SWEP.Anims=SWEP.Anims or {} SWEP.IronSightHeight=1 SWEP.Category = "KSwep Special" SWEP.Base = "weapon_kswep_tranqbase" SWEP.Primary.Delay = 0.8 SWEP.Primary.Damage = 0 SWEP.Primary.Spread = 0.003 SWEP.Spawnable = true SWEP.DefaultZero=100 SWEP.DefaultBattlesightZero=0 SWEP.DefaultZerodata = { mils=false, bc=0.1, min=100, max=2000, step=0, default=100, battlesight=false } SWEP.MuzzleVelMod=1.04 SWEP.MagClass="Box" SWEP.DrawOnce=false SWEP.SingleReloadFiringPin=false SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_mosin.mdl" SWEP.WorldModel = "models/weapons/w_snip_awp.mdl" SWEP.FlashlightModel="models/weapons/upgrades/a_flashlight_band.mdl" SWEP.LaserModel="models/weapons/upgrades/a_laser_band.mdl" SWEP.UseHands = false SWEP.MagSize = 1 SWEP.MaxMags = 5 SWEP.MaxMagsBonus=20 SWEP.Primary.ClipSize = SWEP.MagSize SWEP.Caliber = "vammo_762x54t" SWEP.MagType = "box_762x54t" SWEP.SingleClips=true SWEP.ReloadClipSize=20 SWEP.Primary.Sound = Sound("Weapon_tmosin.Single") SWEP.Primary.SoundEmpty = Sound("weapon_mosin.Empty") SWEP.ViewModelFlip = false SWEP.Secondary.Ammo = "" SWEP.CurrentlyReloading=0 SWEP.ReloadAnimTime=0 SWEP.RecoilMassModifier=1 SWEP.HandlingModifier=180 SWEP.InsAnims=true SWEP.Auto=false SWEP.Firemode=true SWEP.HoldType="ar2" SWEP.HoldOpen=false SWEP.Length=48 SWEP.OpenBolt=true SWEP.LengthSup=0 SWEP.Suppressable=false SWEP.SuppressorModel=nil SWEP.MuzzleVelModSup= 1 SWEP.RecoilModSup=1 SWEP.SpreadModSup=0 SWEP.IdleType="passive" SWEP.SelectFire=false --SWEP.MidReloadAnimEmpty=ACT_VM_RELOAD_INSERT_PULL SWEP.Anims.StartReloadAnim = ACT_VM_RELOAD SWEP.Anims.MidReloadAnim = ACT_VM_RELOAD_INSERT SWEP.Anims.EndReloadAnim = ACT_VM_RELOAD_END --SWEP.MidReloadAnimEmpty=ACT_VM_RELOADEMPTY --SWEP.SafetyAnim=ACT_VM_FIREMODE --SWEP.SingleReloadChambers=true SWEP.SingleReloadChambers=false SWEP.SingleReload=true SWEP.HoldOpen=true SWEP.IronSightsPos = Vector(-2.81, -7, 1.455) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.ScopeOffsetPos=Vector(0,-5,-1.72) SWEP.ScopeOffsetAng=Vector(0,0,0) SWEP.InsNoIronAnim=true SWEP.MergeAttachments = { } SWEP.OpticMountModel = "models/weapons/upgrades/a_modkit_mosin.mdl" SWEP.DefaultSight=nil SWEP.NoDefaultSightModel=true SWEP.InsAttachments=true SWEP.Anims.InitialDrawAnim=ACT_VM_READY SWEP.CanFlashlight=true SWEP.WaitShot=true SWEP.SingleShotChambers=true SWEP.TranqMultiplier=1.5 SWEP.Anims.ShootLastAnim=ACT_VM_SHOOTLAST SWEP.Anims.IronShootLastAnim=ACT_VM_ISHOOT_LAST SWEP.EmptyAnims=true SWEP.Anims.IdleAnimEmpty=ACT_VM_IDLE_EMPTY SWEP.Anims.IronAnimEmpty=ACT_VM_IIDLE_EMPTY function SWEP:ReloadAct(force) self:ReloadTube() end function SWEP:DiscoverModelAnims() self:SetAnim("ShootAnim",self:DiscoverAnim("ACT_VM_PRIMARYATTACK_START")) self:SetAnim("IronShootAnim",self:DiscoverAnim("ACT_VM_ISHOOT_START")) self:SetAnim("RunAnim",self:DiscoverAnim("ACT_VM_SPRINT")) end
--[[ Copyright 2019 Matix8981 <biuro@devlogic.pl> <mateusz8981@gmail.com> ]] function ReadFile(path) local file = fileOpen(path) if not file then return false end local data = fileRead(file, fileGetSize(file)) fileClose(file) return data end function WriteFile(path, text) if fileExists(path) then fileDelete(path) end local file = fileCreate(path) local result = fileWrite(text) fileClose(file) return result end local Variables = fromJSON(ReadFile("variables.json")) function GetVariable(table, row) if table == nil and row == nil then return Variables elseif row == nil then return Variables[table] else return Variables[table][row] end end function SetVariable(table, row, value) if not table then return false end if not row or not not Variables[table] then Variables[table] = {} -- Czyszczenie tablicy else if isElement(value) then return false end Variables[table][row] = value end WriteFile("variables.json", toJSON(value)) end
--[[ This code is a heavily modified version of and based on the code found in https://github.com/anibali/infogan ]]-- ------------------------------------------------- -- -- MAIN CODE & TRAINING -- ------------------------------------------------- -- STANDARD PACKAGES require('torch') require('image') require('nn') require('optim') -- NON-STANDARD PACKAGES -- Bindings to CUDA require('cutorch') require('cunn') require('cudnn') -- Plotting library require 'gnuplot' pl = require('pl.import_into')() tnt = require('torchnet') nninit = require('nninit') -- CUSTOM SCRIPTS -- Contains all parameters and paths require 'configuration' -- Contains helper functions for training and evaluation require 'helper_functions' -- Creates the model and criterion functions require 'model_and_criterion' -- Contains functions for plotting and synthetic image creation require 'plotting_and_image_creation' -- Creates a dataset object to return labeled and unlabeled training batches dataset = require('dataset') --[[ INITIATLISATION ]] if classifier_set then C1 = torch.load(classifier_path):cuda() end train_data = dataset.new(dataset_train_path, unlabelled_percentage, dataset_test_path) train_iter_labelled = train_data:make_iterator(batch_size) train_iter_unlabelled = train_data:make_iterator_unlabelled(batch_size) -- Save the current parameters params = {} params.n_epochs = n_epochs params.n_updates_per_epoch = n_updates_per_epoch params.batch_size = batch_size params.info_reg_sup_coef_learn = info_reg_sup_coef_learn params.info_reg_sup_coef_train = info_reg_sup_coef_train params.info_reg_unsup_coef_learn = info_reg_unsup_coef_learn params.info_reg_unsup_coef_train = info_reg_unsup_coef_train params.disc_learning_rate = disc_learning_rate params.gen_learning_rate = gen_learning_rate params.rng_seed = rng_seed params.n_cont_vars = n_cont_vars params.n_noise_vars = n_noise_vars params.n_classes_per_lc = n_classes_per_lc params.unlabelled_percentage = unlabelled_percentage params.unlabelled_sampling_prob = unlabelled_sampling_prob params.additive_prob_growth = additive_prob_growth params.sampling_prob_growth = tostring(sampling_prob_growth) params.instance_noise_std = instance_noise_std params.instance_noise_annealing = instance_noise_annealing params.G = tostring(generator) params.D = tostring(discriminator) torch.save(outFolder .. 'params.t7', params) --[[ LOGGING ]] log_text = require('torchnet.log.view.text') log_keys = {'epoch', 'fake_loss', 'info_loss_semsup','info_loss_unsup', 'real_loss', 'gen_loss', 'time'} log = tnt.Log{ keys = log_keys, onFlush = { log_text{ keys = log_keys, format = {'epoch=%3d', 'fake_loss=%8.5f', 'info_loss_semsup=%8.6f', 'info_loss_unsup=%8.6f', 'real_loss=%8.6f', 'gen_loss=%8.6f', 'time=%5.2fs'} } } } --[[ TRAINING ]] real_input = torch.CudaTensor() gen_input = torch.CudaTensor() fake_input = torch.CudaTensor() disc_target = torch.CudaTensor() target = torch.CudaTensor() disc_params, disc_grad_params = discriminator:getParameters() gen_params, gen_grad_params = generator:getParameters() fake_loss_meter = tnt.AverageValueMeter() info_loss_semsup_meter = tnt.AverageValueMeter() info_loss_unsup_meter = tnt.AverageValueMeter() real_loss_meter = tnt.AverageValueMeter() gen_loss_meter = tnt.AverageValueMeter() time_meter = tnt.TimeMeter() mean_class_losses_1 = torch.Tensor(n_epochs) infoHead_performance = torch.Tensor(n_epochs, 3) gradient_norms = torch.Tensor(n_epochs, 3) -- Calculate outputs and gradients for the discriminator do_discriminator_step = function(new_params) if new_params ~= disc_params then disc_params:copy(new_params) end disc_grad_params:zero() local loss_real = 0 local loss_fake = 0 local loss_info = 0 local loss_info_unsup = 0 local loss_info_semsup_real = 0 local loss_info_semsup_fake = 0 local ri_size = real_input:size() -- Add instance noise to real input if (instance_noise_std > 0) then real_input:add(torch.Tensor(real_input:size()):typeAs(real_input):normal(0, instance_noise_std)) end -- Train with real images (from dataset) local batch_size = real_input:size(1) disc_target:resize(batch_size, 1) local dbodyout = discriminator_body:forward(real_input) local dheadout = discriminator_head:forward(dbodyout) disc_target:fill(1) loss_real = disc_head_criterion:forward(dheadout, disc_target) local dloss_ddheadout = disc_head_criterion:backward(dheadout, disc_target) local dloss_ddheadin = discriminator_head:backward(dbodyout, dloss_ddheadout) discriminator_body:backward(real_input, dloss_ddheadin) if labelled_batch then -- Train info_head_semsup with real labeled images local iheadout_semsup_real = info_head_semsup:forward(dbodyout) local info_target_semsup_real = target loss_info_semsup = info_head_semsup_crit:forward(iheadout_semsup_real, info_target_semsup_real) * info_reg_sup_coef_train local dloss_diheadout_semsup_real = info_head_semsup_crit:backward(iheadout_semsup_real, info_target_semsup_real) dloss_diheadout_semsup_real:mul(info_reg_sup_coef_train) local dloss_diheadin_semsup_real = info_head_semsup:backward(dbodyout, dloss_diheadout_semsup_real) discriminator_body:backward(real_input, dloss_diheadin_semsup_real) end gen_input:resize(ri_size[1], n_gen_inputs) -- Train with fake images (from generator) for i = 1, #n_classes_per_lc do random_one_hot(gen_input:narrow(2, c_offset[i], n_classes_per_lc[i])) end if n_cont_vars > 0 then gen_input:narrow(2, c_offset[#c_offset], n_cont_vars):uniform(-1, 1) end gen_input:narrow(2, n_salient_vars + 1, n_noise_vars):normal(0, 1) generator:forward(gen_input) fake_input:resizeAs(generator.output):copy(generator.output) -- Add instance noise to fake_input if (instance_noise_std > 0) then fake_input:add(torch.Tensor(fake_input:size()):typeAs(fake_input):normal(0, instance_noise_std)) end local dbodyout = discriminator_body:forward(fake_input) -- Train discriminator head with fake images local dheadout = discriminator_head:forward(dbodyout) disc_target:fill(0) loss_fake = disc_head_criterion:forward(dheadout, disc_target) local dloss_ddheadout = disc_head_criterion:backward(dheadout, disc_target) local dloss_ddheadin = discriminator_head:backward(dbodyout, dloss_ddheadout) discriminator_body:backward(fake_input, dloss_ddheadin) if unlabelled_percentage == 1 then -- Train info_head_semsup with fake images local iheadout_semsup_fake = info_head_semsup:forward(dbodyout) local info_target_semsup_fake = salient_input_to_target(gen_input:narrow(2, 1, n_salient_vars), true) loss_info_semsup = info_head_semsup_crit:forward(iheadout_semsup_fake, info_target_semsup_fake) * info_reg_sup_coef_train local dloss_diheadout_semsup_real = info_head_semsup_crit:backward(iheadout_semsup_fake, info_target_semsup_fake) dloss_diheadout_semsup_real:mul(info_reg_sup_coef_train) local dloss_diheadin_semsup_fake = info_head_semsup:backward(dbodyout, dloss_diheadout_semsup_real) discriminator_body:backward(fake_input, dloss_diheadin_semsup_fake) end -- Train info_head_unsup with fake images loss_info_unsup = 0 if info_head_unsup ~= nil then local iheadout_unsup = info_head_unsup:forward(dbodyout) local info_target_unsup = salient_input_to_target(gen_input:narrow(2, 1, n_salient_vars), false) loss_info_unsup = info_head_unsup_crit:forward(iheadout_unsup, info_target_unsup) * info_reg_unsup_coef_train local dloss_diheadout_unsup = info_head_unsup_crit:backward(iheadout_unsup, info_target_unsup) for i, t in ipairs(dloss_diheadout_unsup) do t:mul(info_reg_unsup_coef_train) end local dloss_diheadin_unsup = info_head_unsup:backward(dbodyout, dloss_diheadout_unsup) discriminator_body:backward(fake_input, dloss_diheadin_unsup) end loss_info = loss_info_unsup + loss_info_semsup -- Update average value meters real_loss_meter:add(loss_real) fake_loss_meter:add(loss_fake) info_loss_semsup_meter:add(loss_info_semsup) info_loss_unsup_meter:add(loss_info_unsup) -- Calculate combined loss local loss = loss_real + loss_fake + loss_info -- Anneal instance noise instance_noise_std = instance_noise_std * instance_noise_annealing return loss, disc_grad_params end -- Calculate outputs and gradients for the generator do_generator_step = function(new_params) if new_params ~= gen_params then gen_params:copy(new_params) end gen_grad_params:zero() disc_target:fill(1) fake_input:resizeAs(generator.output):copy(generator.output) local dbodyout = discriminator_body:forward(fake_input) -- Train discriminator head with fake images local dheadout = discriminator_head:forward(dbodyout) -- Disc_head gen_loss = disc_head_criterion:forward(dheadout, disc_target) local dloss_ddheadout = disc_head_criterion:updateGradInput(dheadout, disc_target) local dloss_ddheadin = discriminator_head:updateGradInput(dbodyout, dloss_ddheadout) dloss_dgout = discriminator_body:updateGradInput(fake_input, dloss_ddheadin) gen_loss_meter:add(gen_loss) generator:backward(gen_input, dloss_dgout) -- Semsup_head local iheadout_semsup_fake = info_head_semsup:forward(dbodyout) local info_target_semsup_fake = salient_input_to_target(gen_input:narrow(2, 1, n_salient_vars), true) loss_info_semsup_fake = info_head_semsup_crit:forward(iheadout_semsup_fake, info_target_semsup_fake) * info_reg_sup_coef_learn local dloss_diheadout_semsup_fake = info_head_semsup_crit:updateGradInput(iheadout_semsup_fake, info_target_semsup_fake) dloss_diheadout_semsup_fake:mul(info_reg_sup_coef_learn) local dloss_diheadin_semsup_fake = info_head_semsup:updateGradInput(dbodyout, dloss_diheadout_semsup_fake) -- Unsup_head local dloss_diheadin_unsup = torch.zeros(dloss_ddheadin:size()):typeAs(dloss_ddheadin) if info_head_unsup ~= nil then local iheadout_unsup = info_head_unsup:forward(dbodyout) local info_target_unsup = salient_input_to_target(gen_input:narrow(2, 1, n_salient_vars), false) loss_info_unsup = info_head_unsup_crit:forward(iheadout_unsup, info_target_unsup) * info_reg_unsup_coef_learn local dloss_diheadout_unsup = info_head_unsup_crit:updateGradInput(iheadout_unsup, info_target_unsup) for i, t in ipairs(dloss_diheadout_unsup) do t:mul(info_reg_unsup_coef_learn) end dloss_diheadin_unsup = info_head_unsup:updateGradInput(dbodyout, dloss_diheadout_unsup) end dloss_dgout = discriminator_body:updateGradInput(fake_input, dloss_diheadin_semsup_fake + dloss_diheadin_unsup) gen_loss_meter:add(gen_loss) generator:backward(gen_input, dloss_dgout) return gen_loss, gen_grad_params end -- Discriminator optimiser disc_optimiser = { method = optim.adam, config = { epsilon = 1e-8, learningRate = disc_learning_rate, beta1 = 0.5 }, state = {} } -- Generator optimiser gen_optimiser = { method = optim.adam, config = { epsilon = 1e-8, learningRate = gen_learning_rate, beta1 = 0.5 }, state = {} } iter_inst_labelled = train_iter_labelled() iter_inst_unlabelled = train_iter_unlabelled() fake_losses = {} info_losses_semsup = {} info_losses_unsup = {} real_losses = {} gen_losses = {} curr_epoch = 0 -- Training loop for epoch = 1, n_epochs do fake_loss_meter:reset() info_loss_semsup_meter:reset() info_loss_unsup_meter:reset() real_loss_meter:reset() gen_loss_meter:reset() time_meter:reset() curr_epoch = epoch local n_labelled_sampled = 0 local n_unlabelled_sampled = 0 discriminator:training() generator:training() -- Do training iterations for the epoch for iteration = 1, n_updates_per_epoch do local sample -- Biased coin toss to decide if we sampling from labelled or unlabelled data if torch.bernoulli(unlabelled_sampling_prob) == 0 then sample = iter_inst_labelled() n_labelled_sampled = n_labelled_sampled + 1 labelled_batch = true else sample = iter_inst_unlabelled() n_unlabelled_sampled = n_unlabelled_sampled + 1 labelled_batch = false end if not sample or sample.input:size(1) < batch_size then -- Restart iterator if labelled_batch then iter_inst_labelled = train_iter_labelled() sample = iter_inst_labelled() else iter_inst_unlabelled = train_iter_unlabelled() sample = iter_inst_unlabelled() end end -- Copy real inputs from the dataset onto the GPU input = sample.input real_input:resize(input:size()):copy(input) target:resize(sample.target:size()):copy(sample.target) -- Update the discriminator network disc_optimiser.method( do_discriminator_step, disc_params, disc_optimiser.config, disc_optimiser.state ) -- Update the generator network gen_optimiser.method( do_generator_step, gen_params, gen_optimiser.config, gen_optimiser.state ) end print('unlabelled_sampling_prob: ' .. unlabelled_sampling_prob .. ' n_labelled_sampled: ' .. n_labelled_sampled .. ' n_unlabelled_sampled: ' .. n_unlabelled_sampled) if sampling_prob_growth then -- Grow the unlabelled sampling probability if unlabelled_sampling_prob < unlabelled_percentage then unlabelled_sampling_prob = unlabelled_sampling_prob + additive_prob_growth end if unlabelled_sampling_prob > unlabelled_percentage then unlabelled_sampling_prob = unlabelled_percentage end end fake_images = create_images() -- Update log log:set{ epoch = epoch, fake_loss = fake_loss_meter:value(), info_loss_semsup = info_loss_semsup_meter:value(), info_loss_unsup = info_loss_unsup_meter:value(), real_loss = real_loss_meter:value(), gen_loss = gen_loss_meter:value(), time = time_meter:value() } log:flush() -- Save metrics info_losses_semsup[#info_losses_semsup+1] = info_loss_semsup_meter:value() info_losses_unsup[#info_losses_unsup+1] = info_loss_unsup_meter:value() real_losses[#real_losses+1] = real_loss_meter:value() gen_losses[#gen_losses+1] = gen_loss_meter:value() fake_losses[#fake_losses+1] = fake_loss_meter:value() infoHead_performance[{{epoch}, {1}}] = evaluate_infoHead_real(discriminator) infoHead_performance[{{epoch}, {2}}], infoHead_performance[{{epoch}, {3}}] = evaluate_infoHead_fake(generator, discriminator) if classifier_set then mean_class_losses_1[epoch] = test_signal(generator, C1) end -- Save the discriminator and generator models local model_dir = pl.path.join(outFolder, 'models') pl.dir.makepath(model_dir) discriminator:clearState() local model_disc_file = pl.path.join(model_dir, 'infogan_svhn_disc.t7') torch.save(model_disc_file, discriminator) generator:clearState() local model_gen_file = pl.path.join(model_dir, 'infogan_svhn_gen.t7') torch.save(model_gen_file, generator) -- Save images every 10 epochs local image_dir = pl.path.join(outFolder, 'images') pl.dir.makepath(image_dir) if epoch % 10 == 0 then for i = 1, #fake_images do local image_basename = string.format('fake_images_%d_%04d.png', i, epoch) image.save(pl.path.join(image_dir, image_basename), fake_images[i]) image_basename = string.format('final_fake_images_%d.png', i, epoch) image.save(pl.path.join(image_dir, image_basename), fake_images[i]) end end collectgarbage() end plot_final_metrics()
-- Generated from template if BattleArena == nil then BattleArena = class({}) end require("game_setup") function Precache( context ) --[[ Precache things we know we'll use. Possible file types include (but not limited to): PrecacheResource( "model", "*.vmdl", context ) PrecacheResource( "soundfile", "*.vsndevts", context ) PrecacheResource( "particle", "*.vpcf", context ) PrecacheResource( "particle_folder", "particles/folder", context ) ]] PrecacheResource( "particle", "particles/econ/items/mirana/mirana_crescent_arrow/mirana_spell_crescent_arrow.vpcf", context ) end require("game_setup") -- Create the game mode when we activate function Activate() GameRules.AddonTemplate = BattleArena() GameRules.AddonTemplate:InitGameMode() end function BattleArena:InitGameMode() print( "Template addon is loaded." ) GameRules:GetGameModeEntity():SetThink( "OnThink", self, "GlobalThink", 2 ) GameSetup:init() CreateUnitByName("johnboy", Vector(0,1300,0), true, nil, nil, DOTA_TEAM_BADGUYS) end -- Evaluate the state of the game function BattleArena:OnThink() if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then --print( "Template addon script is running." ) elseif GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then return nil end return 1 end
CMD.name = 'SetRank' CMD.description = 'command.setrank.description' CMD.syntax = 'command.setrank.syntax' CMD.permission = 'assistant' CMD.category = 'permission.categories.character_management' CMD.arguments = 2 CMD.player_arg = 1 CMD.aliases = { 'plysetrank', 'charsetrank' } function CMD:on_run(player, targets, rank) rank = tonumber(rank) if !rank then player:notify('error.invalid_value') return end self:notify_staff('command.setrank.message', { player = get_player_name(player), target = util.player_list_to_string(targets), rank = rank }) for k, v in ipairs(targets) do local faction_table = v:get_faction() local rank_table = faction_table:get_rank(rank) if rank_table then v:set_rank(rank) v:notify('notification.rank_changed', { rank = rank_table.id }) end end end
--[[headerData = { type = "header", name = "My Header", -- or string id or function returning a string width = "full", --or "half" (optional) reference = "MyAddonHeader" -- unique global reference to control (optional) } ]] local widgetVersion = 7 local LAM = LibStub("LibAddonMenu-2.0") if not LAM:RegisterWidget("header", widgetVersion) then return end local wm = WINDOW_MANAGER local tinsert = table.insert local function UpdateValue(control) control.header:SetText(LAM.util.GetStringFromValue(control.data.name)) end local MIN_HEIGHT = 30 function LAMCreateControl.header(parent, headerData, controlName) local control = LAM.util.CreateBaseControl(parent, headerData, controlName) local isHalfWidth = control.isHalfWidth local width = control:GetWidth() control:SetDimensions(isHalfWidth and width / 2 or width, MIN_HEIGHT) control.divider = wm:CreateControlFromVirtual(nil, control, "ZO_Options_Divider") local divider = control.divider divider:SetWidth(isHalfWidth and width / 2 or width) divider:SetAnchor(TOPLEFT) control.header = wm:CreateControlFromVirtual(nil, control, "ZO_Options_SectionTitleLabel") local header = control.header header:SetAnchor(TOPLEFT, divider, BOTTOMLEFT) header:SetAnchor(BOTTOMRIGHT) header:SetText(LAM.util.GetStringFromValue(headerData.name)) control.UpdateValue = UpdateValue if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list tinsert(control.panel.controlsToRefresh, control) end return control end
local g2d = {} local g = lovr.graphics local tbl_add, min, sin,cos, rad = table.insert, math.min, math.sin,math.cos, math.rad local base = ... local ffi = require 'ffi' local C = ffi.os == 'Windows' and ffi.load('glfw3') or ffi.C local C_str = ffi.string ffi.cdef [[ typedef struct GLFWwindow GLFWwindow; GLFWwindow* glfwGetCurrentContext(void); typedef void(*GLFWwindowsizefun) (GLFWwindow*, int, int); GLFWwindowsizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWwindowsizefun callback); ]] local p_proj = lovr.math.newMat4() -- perspective projection matrix local o_proj = lovr.math.newMat4() -- orthographic projection matrix local Z_NEAR, Z_FAR = -1, 1 local function updProj( w,h ) o_proj:set( 2/w, 0, 0, 0, 0, 2/-h, 0, 0, 0, 0, -2/(Z_FAR-Z_NEAR), 0, -w/w, 1, -(Z_FAR+Z_NEAR)/(Z_FAR-Z_NEAR), 1 ) end local W = C.glfwGetCurrentContext() C.glfwSetFramebufferSizeCallback(W, function( _, w,h ) updProj(w,h) end) --------------------------------------------------------------------------------------------------------------- local max_vertices, max_indices local batch, varr, vertices local vmap, indices ffi.cdef([[ struct vertex { float position[2]; uint8_t color[4]; }; ]]) local ct_vertex = ffi.typeof("struct vertex") local vCount = 0 -- current vertex count local mIndex = 0 -- vertex map last index local imgMat = lovr.graphics.newMaterial() local imgMesh = g.newMesh( {{"lovrPosition", "float", 2}, {"lovrTexCoord", "float", 2}}, 4, "triangles", 'static', false) imgMesh:setVertexMap({1,2,3, 3,4,1}) imgMesh:setMaterial(imgMat) --------------------------------------------------------------------------------------------------------------- local basicFont local lStack = {} -- lua stack for fonts and shaders local stack, maxStack local curstack = 0 ffi.cdef([[ typedef struct { uint8_t color[4]; uint16_t lineWidth; uint16_t pointSize; bool wireframe; // font // shader } stackData; ]]) -- struct to keep lovr graphics stack local gStack = { r=1, g=1, b=1, a=1, wireframe = false } --------------------------------------------------------------------------------------------------------------- function g2d.init( maxTriangles, stackSize, zNear, zFar, useVeraSans ) max_vertices = maxTriangles and maxTriangles*3 or 15000 -- by default maximum is 5k triangles max_indices = maxTriangles and maxTriangles*6 or 30000 -- vertex buffer batch = g.newMesh( {{"lovrPosition", "float", 2}, {"lovrVertexColor", "ubyte", 4}}, max_vertices, "triangles", 'dynamic', false) varr = lovr.data.newBlob(max_vertices * ffi.sizeof(ct_vertex), "varr") vertices = ffi.cast("struct vertex*", varr:getPointer()) -- vertex map vmap = lovr.data.newBlob(max_indices * ffi.sizeof("uint16_t"), "vmap") indices = ffi.cast("uint16_t*", vmap:getPointer()) -- stack maxStack = stackSize or 64 curstack = 0 stack = ffi.new("stackData["..maxStack.."]") -- stack setup stack[0].color[0] = 255 stack[0].color[1] = 255 stack[0].color[2] = 255 stack[0].color[3] = 255 stack[0].lineWidth = 1 stack[0].pointSize = 1 stack[0].wireframe = false basicFont = useVeraSans and g.newFont(base .. "/Vera.ttf", 12, 5, 100) or g.newFont(12, 10, 5) basicFont:setPixelDensity(1) basicFont:setFlipEnabled(true) lStack[0] = {font = basicFont} -- projection Z_NEAR = zNear or -1 Z_FAR = zFar or 1 updProj(g.getDimensions()) return g2d end --------------------------------------------------------------------------------------------------------------- local function flushBatch() if vCount > 0 then batch:setVertices(varr, 1, vCount) batch:setVertexMap(vmap, 2) batch:setDrawRange(1, mIndex) g.setColor(1,1,1) batch:draw() g.flush() end vCount = 0 mIndex = 0 end local function makeLine( ... ) local arg = type(...) == "table" and (...) or {...} local lastindex = math.min( #arg-2, (max_vertices-vCount)*0.5 ) local lW = stack[curstack].lineWidth*0.5 local x1,y1,x2,y2, nx,ny, len for i=1, lastindex, 2 do x1,y1 = arg[i], arg[i+1] x2,y2 = arg[i+2], arg[i+3] nx,ny = y1-y2, x2-x1 len = (nx*nx + ny*ny)^0.5 + 0.000001 nx,ny = nx/len, ny/len -- not protected from division by zero -- vertex 1 vertices[vCount].position[0] = x1-nx*lW vertices[vCount].position[1] = y1-ny*lW -- vertex 2 vertices[vCount+1].position[0] = x2-nx*lW vertices[vCount+1].position[1] = y2-ny*lW -- vertex 3 vertices[vCount+2].position[0] = x2+nx*lW vertices[vCount+2].position[1] = y2+ny*lW -- vertex 4 vertices[vCount+3].position[0] = x1+nx*lW vertices[vCount+3].position[1] = y1+ny*lW -- set vertex color from current stack ffi.copy(vertices[vCount].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+1].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+2].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+3].color, stack[curstack].color, 4) -- add indices to vertex map indices[mIndex] = vCount indices[mIndex+1] = vCount+1 indices[mIndex+2] = vCount+2 indices[mIndex+3] = vCount+2 indices[mIndex+4] = vCount+3 indices[mIndex+5] = vCount vCount = vCount + 4 mIndex = mIndex + 6 end if lastindex < #arg-2 then flushBatch() makeLine( select(lastindex+1, unpack(arg)) ) end end local function makeRect( x,y, w,h ) if vCount + 4 > max_vertices or mIndex + 6 > max_indices then flushBatch() end -- vertex 1 vertices[vCount].position[0] = x vertices[vCount].position[1] = y -- vertex 2 vertices[vCount+1].position[0] = x+w vertices[vCount+1].position[1] = y -- vertex 3 vertices[vCount+2].position[0] = x+w vertices[vCount+2].position[1] = y+h -- vertex 4 vertices[vCount+3].position[0] = x vertices[vCount+3].position[1] = y+h -- set vertex color from current stack ffi.copy(vertices[vCount].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+1].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+2].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+3].color, stack[curstack].color, 4) -- add indices to vertex map indices[mIndex] = vCount indices[mIndex+1] = vCount+1 indices[mIndex+2] = vCount+2 indices[mIndex+3] = vCount+2 indices[mIndex+4] = vCount+3 indices[mIndex+5] = vCount vCount = vCount + 4 mIndex = mIndex + 6 end local function makeCircle( x,y, r, s ) if vCount + s+1 > max_vertices or mIndex + s*3 > max_indices then flushBatch() end local first = vCount vertices[vCount].position[0] = x vertices[vCount].position[1] = y -- copy color from stack ffi.copy(vertices[vCount].color, stack[curstack].color, 4) vCount = vCount + 1 for i=0, 360, 360/s do vertices[vCount].position[0] = x + cos(rad(i))*r vertices[vCount].position[1] = y + sin(rad(i))*r -- copy color from stack ffi.copy(vertices[vCount].color, stack[curstack].color, 4) vCount = vCount + 1 end for i=first, first+s-1 do indices[mIndex] = first indices[mIndex+1] = i indices[mIndex+2] = i+1 mIndex = mIndex + 3 end indices[mIndex] = first indices[mIndex+1] = first+s indices[mIndex+2] = first+1 mIndex = mIndex + 3 end -- API -------------------------------------------------------------------------------------------------------- function g2d.points( ... ) local arg = type(...) == "table" and (...) or {...} local lastindex = min( #arg, (max_vertices-vCount)*0.5 ) local pS = stack[curstack].pointSize*0.5 for j=1, lastindex, 2 do local x,y = arg[j]+0.5, arg[j+1]+0.5 -- vertex 1 vertices[vCount].position[0] = x-pS vertices[vCount].position[1] = y-pS -- vertex 2 vertices[vCount+1].position[0] = x+pS vertices[vCount+1].position[1] = y-pS -- vertex 3 vertices[vCount+2].position[0] = x+pS vertices[vCount+2].position[1] = y+pS -- vertex 4 vertices[vCount+3].position[0] = x-pS vertices[vCount+3].position[1] = y+pS -- set vertex color from current stack ffi.copy(vertices[vCount].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+1].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+2].color, stack[curstack].color, 4) ffi.copy(vertices[vCount+3].color, stack[curstack].color, 4) -- add indices to vertex map indices[mIndex] = vCount indices[mIndex+1] = vCount+1 indices[mIndex+2] = vCount+2 indices[mIndex+3] = vCount+2 indices[mIndex+4] = vCount+3 indices[mIndex+5] = vCount vCount = vCount + 4 mIndex = mIndex + 6 end if lastindex < #arg then flushBatch() g2d.points(select(lastindex+1, unpack(arg))) end end function g2d.print( text, x,y, r, halign, valign ) g.setColor( stack[curstack].color[0]/255, stack[curstack].color[1]/255, stack[curstack].color[2]/255, stack[curstack].color[3]/255) g.print(text, x or 0, y or 0, 0, 1, r or 0, 0,0,1, 0, halign or "left", valign or "top") g.setColor(1,1,1) end function g2d.line( ... ) makeLine( ... ) end function g2d.rectangle( mode, x,y, w,h ) if mode == "fill" then makeRect(x,y, w,h) elseif mode == "line" then makeLine(x,y, x+w,y, x+w,y+h, x,y+h, x,y) end end function g2d.circle( mode, x,y, radius, segments ) segments = segments or 30 if mode == "fill" then makeCircle( x,y, radius, segments ) elseif mode == "line" then local pts = {} for i=0, 360, 360/segments do table.insert(pts, x + cos( rad(i))*radius ) table.insert(pts, y + sin( rad(i))*radius ) end makeLine(unpack(pts)) end end function g2d.draw( texture, x,y, r ) x,y,r = x or 0, y or 0, r or 0 local w,h = texture:getDimensions() imgMat:setColor(stack[curstack].color[0]/255, stack[curstack].color[1]/255, stack[curstack].color[2]/255, stack[curstack].color[3]/255) imgMat:setTexture(texture) imgMesh:setVertices( {{0,0, 0,1}, {w,0, 1,1}, {w,h, 1,0}, {0,h, 0,0}} ) imgMesh:draw(x,y,0, 1, r, 0,0,1) end --------------------------------------------------------------------------------------------------------------- function g2d.reset() g.setShader() g.setColor(1,1,1) g.setFont( basicFont ) stack[curstack].color[0] = 255 stack[curstack].color[1] = 255 stack[curstack].color[2] = 255 stack[curstack].color[3] = 255 stack[curstack].lineWidth = 1 stack[curstack].pointSize = 1 stack[curstack].wireframe = false lStack[curstack] = {font = basicFont} end function g2d.set() -- save current stack p_proj = g.getProjection(1, p_proj) gStack.r, gStack.g, gStack.b, gStack.a = g.getColor() gStack.wireframe = g.isWireframe() gStack.shader = g.getShader() gStack.font = g.getFont() -- set orthographic projection g.push() g.origin() g.setColor(1,1,1) g.setProjection(1, o_proj) g.setFont(lStack[curstack].font) end function g2d.unset() -- draw everything last in the batch on the screen flushBatch() -- turn back lovr stack g.pop() g.setProjection(1, p_proj) g.setColor(gStack.r, gStack.g, gStack.b, gStack.a) g.setWireframe(gStack.wireframe) g.setShader(gStack.shader) g.setFont(gStack.font) end function g2d.push() curstack = curstack + 1 if curstack >= maxStack then error("Stack is too deep! ("..maxStack..")", 2) end lStack[curstack] = {font = basicFont} ffi.copy(stack[curstack], stack[curstack-1], ffi.sizeof("stackData")) end function g2d.pop() if curstack == 0 then error("Too much pop() calls!", 2) end curstack = curstack - 1 -- change font and shader g.setFont(lStack[curstack].font) end --------------------------------------------------------------------------------------------------------------- function g2d.setFont( font ) lStack[curstack].font = font or basicFont lStack[curstack].font:setPixelDensity(1) lStack[curstack].font:setFlipEnabled(true) g.setFont(lStack[curstack].font) end function g2d.getFont() return lStack[curstack].font end function g2d.setShader( s ) flushBatch() lStack[curstack].shader = s g.setShader(s) end function g2d.getShader() return lStack[curstack].shader end function g2d.setColor( r, _g, b, a ) stack[curstack].color[0] = r*255 stack[curstack].color[1] = _g*255 stack[curstack].color[2] = b*255 stack[curstack].color[3] = a and a*255 or 255 end function g2d.getColor() return stack[curstack].color[0]/255, stack[curstack].color[1]/255, stack[curstack].color[2]/255, stack[curstack].color[3]/255 end function g2d.setWireframe( enable ) flushBatch() g.setWireframe(enable) stack[curstack].wireframe = enable end function g2d.isWireframe() return stack[curstack].wireframe end function g2d.setLineWidth( val ) stack[curstack].lineWidth = val end function g2d.getLineWidth() return stack[curstack].lineWidth end function g2d.setPointSize( val ) stack[curstack].pointSize = val end function g2d.getPointSize() return stack[curstack].pointSize end --------------------------------------------------------------------------------------------------------------- return g2d
local Slot = require('motras_slot') local t = require('motras_types') local Station = require('motras_station') local AssetSlotCache = require('motras_asset_slot_cache') describe('AssetSlotCache', function () local assetSlotId = Slot.makeId({type = t.UNDERPASS, gridX = 1, gridY = 2, assetId = 3}) local assetSlot = Slot:new{id = assetSlotId} local station = Station:new{} local platform = station:initializeAndRegister(Slot.makeId({type = t.PLATFORM, gridX = 1, gridY = 2})) describe('addAssetSlot', function () it ('adds asset slot to cache', function () local assetSlotCache = AssetSlotCache:new{} assetSlotCache:addAssetSlot(assetSlot) assert.are.equal(assetSlot, assetSlotCache.assetSlots[1][2][1]) end) end) describe('getAllAssetSlotsForGridElement', function () it ('gets all slots for specific grid element', function () local assetSlotCache = AssetSlotCache:new{} assetSlotCache:addAssetSlot(assetSlot) assert.are.same({ assetSlot }, assetSlotCache:getAllAssetSlotsForGridElement(platform)) end) it ('returns empty table, when no asset slot is added for this element', function () local assetSlotCache = AssetSlotCache:new{} local otherPlatform = station:initializeAndRegister(Slot.makeId({type = t.PLATFORM, gridX = 0, gridY = 0})) assert.are.same({}, assetSlotCache:getAllAssetSlotsForGridElement(otherPlatform)) end) end) describe('bindAssetSlotsToGridElement', function () it ('binds asset slots to grid element', function () local assetSlotCache = AssetSlotCache:new{} assetSlotCache:addAssetSlot(assetSlot) assetSlotCache:bindAssetSlotsToGridElement(platform) assert.are.equal(assetSlotId, platform:getAsset(3):getSlotId()) end) end) end)
-- Copyright (c) 2020 Reese Danzer -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT -- This module supplys the file-management functions to init.lua, -- specifically: creation of output paths, map paths, and tagging of paths, -- as well as retagging on death. These functions will only work if -- they were initialized on startup while the noita api was still available. --SOURCE --https://stackoverflow.com/questions/1340230/check-if-directory-exists-in-lua --check if a file or directory exists in this path function exists(file) local ok, err, code = os.rename(file, file) if not ok then if code == 13 then -- Permission denied, but it exists return true end end return ok end function pathMaster(seedstr) --takes seedstr, makes either new seed dir or new batch dir within seed dir ngp = SessionNumbersGetValue('NEW_GAME_PLUS_COUNT') ngstr = '' if ngp ~= '0' then ngstr = '[NG' .. ngp .. ']_' end drstr = '' if GameIsDailyRun() then drstr = '[DR]_' end dprstr = '' if ModIsEnabled('daily_practice') then dprstr = '[DPR]_' end ntmrstr = '' if ModIsEnabled('nightmare') then ntmrstr = '[NTMR]_' end mapName = ngstr .. drstr .. dprstr .. ntmrstr .. seedstr rawPath = 'mods\\advanced_cartography\\raws\\' .. mapName .. '\\' if not exists(rawPath) then os.execute('mkdir ' .. rawPath) end mapPath = 'mods\\advanced_cartography\\maps\\' .. mapName .. '\\' if not exists(mapPath) then os.execute('mkdir ' .. mapPath) end local cnt = 0 local photoPath = '' repeat photoPath = rawPath .. cnt .. '\\' cnt = cnt + 1 until not exists(photoPath) os.execute ('mkdir ' .. photoPath) if not exists(photoPath) then print('AC Error: file path not initialized\n') end print('AC: Screenshot Directory: ' .. photoPath) return photoPath end function death() --when the player dies, this function gets called --and marks the seed dir with [DEAD] if exists(rawPath) then local deadPath = '[DEAD]_' .. mapName if exists('mods\\advanced_cartography\\raws\\' .. deadPath) then local cnt = 2 repeat deadPath = '[DEAD' .. cnt .. 'x]_' .. mapName cnt = cnt + 1 until not exists('mods\\advanced_cartography\\raws\\' .. deadPath) end print('AC: Death: map name changed to ' .. deadPath) os.execute('rename ' .. rawPath .. ' ' .. deadPath) os.execute('rename ' .. mapPath .. ' ' .. deadPath) else print("AC Error: you appear to have died in a world that doesn't exist") end end function delete(path) print('AC: attempting to delete ' .. path) os.execute('del ' .. '"' .. path .. '"') end
--[[ Gastric - SlaveScripts.lua Provides spells, events, and movement for mobs between entries 70005 and 70007. Designed for the ACDB project! -- By Gastricpenguin ]] -- Master's Slave function mSlave_Plague(Unit) player = Unit:getClosestPlayer () Unit:CastSpellOnTarget (16458, player) end function mSlave_OnLeaveCombat(Unit) Unit:RemoveEvents() end function mSlave_OnCombat(Unit, Event) Unit:RegisterEvent("mSlave_Plague",10000, 0) end RegisterUnitEvent(70005, 1, "mSlave_OnCombat") RegisterUnitEvent(70005, 2, "mSlave_OnLeaveCombat") --Slave Driver function dSlave_Buff(Unit) Unit:CastSpell(42084) end function dSlave_OnLeaveCombat(Unit) Unit:RemoveEvents() end function dSlave_OnCombat(Unit, Event) Unit:CastSpell(33079) Unit:RegisterEvent("dSlave_Buff",10000, 0) end RegisterUnitEvent(70006, 1, "dSlave_OnCombat") RegisterUnitEvent(70006, 2, "dSlave_OnLeaveCombat") --Pet Fido : CHECK TO SEE IF THIS FIGHT WORKS! function FidoCheckA(Unit) if Unit:GetHealthPct() < 75 then Unit:RemoveEvents() Unit:CastSpell(32651) end end function Fido_Bite(Unit) player = Unit:getClosestPlayer () Unit:CastSpellOnTarget (30113, player) end function Fido_OnLeaveCombat(Unit) Unit:RemoveEvents() end function Fido_OnCombat(Unit, Event) Unit:RegisterEvent("FidoCheckA",1000, 0) Unit:RegisterEvent("Fido_Bite",10000, 0) end RegisterUnitEvent(70008, 1, "Fido_OnCombat") RegisterUnitEvent(70008, 2, "Fido_OnLeaveCombat") --Slave Overlord function OverlordCheckA(Unit) x = Unit:GetX() y = Unit:GetY() z = Unit:GetZ() o = Unit:GetO() if Unit:GetHealthPct() < 40 then Unit:SpawnCreature(70005, x, y, z, o, 17, 10000); end end function Overlord_Cleave(Unit) player = Unit:getClosestPlayer () Unit:CastSpellOnTarget (15579, player) end function Overlord_OnCombat(Unit, Event) Unit:SendChatMessage (12, 0, "Taste my blade!") Unit:RegisterEvent("OverlordCheckA",12000, 0) Unit:RegisterEvent("Overlord_Cleave",10000, 0) end function Overlord_OnLeaveCombat(Unit) Unit:RemoveEvents() end function Overlord_OnDeath(Unit) Unit:SendChatMessage (12, 0, "What? Impossible!") Unit:RemoveEvents() end RegisterUnitEvent(70007, 1, "Overlord_OnCombat") RegisterUnitEvent(70007, 4, "Overlord_OnDeath") RegisterUnitEvent(70007, 2, "Overlord_OnLeaveCombat")
local AddonName, AddonTable = ... -- Raid: Sunwell Plateau (25 Normal) AddonTable.sp = { -- Shared Boss Loot 34664, -- Sunmote 34848, -- Bracers of the Forgotton Conqueror 34851, -- Bracers of the Forgotton Protector 34852, -- Bracers of the Forgotton Vanquisher 34853, -- Belt of the Forgotton Conqueror 34854, -- Belt of the Forgotton Protector 34855, -- Belt of the Forgotton Vanquisher 34856, -- Boots of the Forgotton Conqueror 34857, -- Boots of the Forgotton Protector 34858, -- Boots of the Forgotton Vanquisher -- Kalecgos 34164, -- Dragonscale-Encrusted Longblade 34165, -- Fang of Kalecgos 34169, -- Breeches of Natural Aggression 34167, -- Legplates of the Holy Juggernaut 34170, -- Pantaloons of Calming Strife 34168, -- Starstalker Legguards 34166, -- Band of Lucent Beams -- Brutallus 34176, -- Reign of Misery 34179, -- Heart of the Pit 34177, -- Clutch of Demise 34178, -- Collar of the Pit Lord 34180, -- Felfury Legplates 34181, -- Legplates of Calamity -- Felmyst 34182, -- Grand Magister's Staff of Torrents 34185, -- Sword Breaker's Bulwark 34184, -- Brooch of the Highborne 35352, -- Borderland Fortress Grips 34186, -- Chain Links of the Tumultuous Storm 34188, -- Leggings of the Immortal Night -- The Eredar Twins 34198, -- Stanchion of Primal Instinct 34199, -- Archon's Gavel 34203, -- Grip of Mannoroth 34197, -- Shiv of Exsanguination 34196, -- Golden Bow of Quel'Thalas 34206, -- Book of Highborne Hymns 34204, -- Amulet of Unfettered Magics 35290, -- Sin'dorei Pendant of Conquest 35291, -- Sin'dorei Pendant of Salvation 35292, -- Sin'dorei Pendant of Triumph 34210, -- Amice of the Convoker 34208, -- Equilibrium Epaulets 34194, -- Mantle of the Golden Forest 34192, -- Pauldrons of Perseverance 34202, -- Shawl of Wonderment 34195, -- Shoulderpads of Vehemence 34209, -- Spaulders of Reclamation 34193, -- Spaulders of the Thalassian Savior 34190, -- Crimson Paragon's Cover 34205, -- Shroud of Redeemed Souls 34189, -- Band of Ruinous Delight -- M'uru 34214, -- Muramasa, 34231, -- Aegis of Angelic Fortune 34232, -- Fel Conqueror Raiments 34229, -- Garments of Serene Shores 34211, -- Harness of Carnal Instinct 34216, -- Heroic Judicator's Chestguard 34233, -- Robes of Faltered Light 34212, -- Sunglow Vest 34228, -- Vicious Hawkstrider Hauberk 34215, -- Warharness of Reckless Fury 34240, -- Gauntlets of the Soothed Soul 34234, -- Shadowed Gauntlets of Paroxysm 34213, -- Ring of Hardened Resolve 34230, -- Ring of Omnipotence 35282, -- Sin'dorei Band of Dominance 35283, -- Sin'dorei Band of Salvation 35284, -- Sin'dorei Band of Triumph 34427, -- Blackended Naaru Sliver 34430, -- Glimmering Naaru Sliver 34429, -- Shifting Naaru Sliver 34428, -- Steely Naaru Sliver -- Kil'jaeden 34247, -- Apolyon, the Soul-Render 34337, -- Golden Staff of the Sin'dorei 34329, -- Crux of the Apocalypse 34335, -- Hammer of Sanctification 34331, -- Hand of the Deceiver 34336, -- Sunflare 34334, -- Thori'dal, the Stars' Fury 34333, -- Coif of Alleria 34245, -- Cover of Ursol the Wise 34332, -- Cowl of Gul'dan 34339, -- Cowl of Light's Purity 34345, -- Crown of Anasterian 34340, -- Dark Conjuror's Collar 34244, -- Duplicitous Guise 34243, -- Helm of Burning Righteousness 34241, -- Cloak of Unforgivable Sin 34242, -- Tattered Cape of Antonidas 34341, -- Borderland Paingrips 34344, -- Handguards of Defiled Worlds 34342, -- Handguards of the Dawn 34343, -- Thalassian Ranger Gauntlets }
local camera = {} camera.x = 0 camera.y = 0 camera.scaleX = 1 camera.scaleY = 1 camera.rotation = 0 camera.isVector = true function camera:set() love.graphics.push() love.graphics.rotate(-self.rotation) love.graphics.scale(1 / self.scaleX, 1 / self.scaleY) love.graphics.translate(-self.x, -self.y) end function camera:unset() love.graphics.pop() end function camera:move(dx, dy) self.x = self.x + (dx or 0) self.y = self.y + (dy or 0) end function camera:rotate(dr) self.rotation = self.rotation + dr end function camera:scale(sx, sy) sx = sx or 1 self.scaleX = self.scaleX * sx self.scaleY = self.scaleY * (sy or sx) end function camera:setPosition(x, y) self.x = x or self.x self.y = y or self.y end function camera:setScale(sx, sy) self.scaleX = sx or self.scaleX self.scaleY = sy or self.scaleY end return camera
data:extend( { { type = "item", name = "blueprint-deployer", icon = "__recursive-blueprints__/graphics/blueprint-deployer-icon.png", flags = {"goes-to-quickbar"}, subgroup = "tool", order = "c[automated-construction]-c[blueprint-deployer]", place_result = "blueprint-deployer", stack_size = 50 }, { type = "item", name = "blueprint-digitizer", icon = "__recursive-blueprints__/graphics/blueprint-deployer-icon.png", flags = {"goes-to-quickbar"}, subgroup = "tool", order = "c[automated-construction]-c[blueprint-digitizer]", place_result = "blueprint-digitizer", stack_size = 50 }, { type = "item", name = "blueprint-printer", icon = "__recursive-blueprints__/graphics/blueprint-printer-icon.png", flags = {"goes-to-quickbar"}, subgroup = "tool", order = "c[automated-construction]-c[blueprint-printer]", place_result = "blueprint-printer", stack_size = 50 }, } )
player_manager.AddValidModel( "PMC2_11", "models/player/PMC_2/PMC__11.mdl" ) list.Set( "PlayerOptionsModel", "PMC2_11", "models/player/PMC_2/PMC__11.mdl" )
local gtable = require("gears.table") local musicbus = { callbacks = {} } -- Connect to dbus and wait for invocations of -- org.awesomewm.awful.Playback.Status. Registered callbacks are then called -- with the transmitted data. Primarily this allows external processes to send -- currently played music metadata to the awesome music widget in a simple -- manner. dbus.connect_signal("org.awesomewm.awful.Playback", function(data, status) if data.member == "Status" then for _, callback in ipairs(musicbus.callbacks) do callback(status) end end end) -- register a new callback function musicbus.connect(callback) table.insert(musicbus.callbacks, callback) end -- remove an existing callback function musicbus.disconnect(callback) table.remove(musicbus.callbacks, gtable.hasitem(musicbus.callbacks, callback)) end return musicbus
-- Generated by LairTool rori_vrobal_bull_lair_neutral_medium = Lair:new { mobiles = {{"vrobal_bull",1},{"vrobal_sow",1}}, spawnLimit = 15, buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_brambles_large.iff"}, buildingsEasy = {"object/tangible/lair/base/poi_all_lair_brambles_large.iff"}, buildingsMedium = {"object/tangible/lair/base/poi_all_lair_brambles_large.iff"}, buildingsHard = {"object/tangible/lair/base/poi_all_lair_brambles_large.iff"}, buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_brambles_large.iff"} } addLairTemplate("rori_vrobal_bull_lair_neutral_medium", rori_vrobal_bull_lair_neutral_medium)
--[[ @author Sebastian "CrosRoad95" Jura <sebajura1234@gmail.com> @copyright 2011-2021 Sebastian Jura <sebajura1234@gmail.com> @license MIT ]]-- local function follow() local dokogo=getElementData(localPlayer,"kajdanki") if (not dokogo or not isElement(dokogo)) then setElementData(localPlayer,"kajdanki", nil) removeEventHandler("onClientPreRender", root, follow) triggerServerEvent("setPedAnimation", localPlayer) return end -- setElementInterior(localPlayer, getElementInterior(dokogo)) -- setElementDimension(localPlayer, getElementDimension(dokogo)) if (getPedOccupiedVehicle(dokogo) or getElementInterior(dokogo)~=getElementInterior(localPlayer) or getElementDimension(dokogo)~=getElementDimension(localPlayer)) then setElementData(localPlayer,"kajdanki", nil) removeEventHandler("onClientPreRender", root, follow) triggerServerEvent("setPedAnimation", localPlayer) return end local x,y,z=getElementPosition(dokogo) local x2,y2,z2=getElementPosition(localPlayer) local kat=0 kat=math.deg(math.atan(-1*(x2-x)/(y2-y))) if (y2-y)<0 then kat=kat+180.0 end kat=(kat+180)%360 -- rx,ry,rz=getElementRotation(localPlayer) -- setElementRotation(localPlayer, rx,ry,kat) setPedRotation(localPlayer, kat) local dist=getDistanceBetweenPoints3D(x,y,z,x2,y2,z2) if (dist<1) then setControlState("forwards", false) else setControlState("forwards", true) end if (dist>30) then setElementPosition(localPlayer, x+math.random(-1,1), y+math.random(-1,1), z+math.random(0,10)/10) return end if (dist>2) then setControlState("sprint", true) setControlState("walk", false) else setControlState("walk", true) setControlState("sprint", false) end -- setPedAnimation(localPlayer, "ped" ,"WALK_csaw", 0, true, true, true ) -- triggerServerEvent("spac", localPlayer) end ---- function menu_zakuj(args) local x,y,z=getElementPosition(localPlayer) local x2,y2,z2=getElementPosition(args.with) if (getDistanceBetweenPoints3D(x,y,z,x2,y2,z2)>5) then outputChatBox("Podejdź bliżej.", 255,0,0,true) return end triggerServerEvent("onKajdankiZakuj", resourceRoot, localPlayer, args.with) end addEvent("onKajdankiZakuj", true) addEventHandler("onKajdankiZakuj", resourceRoot, function(kto) local obecnie=getElementData(localPlayer, "kajdanki") if (obecnie and obecnie==kto) then setElementData(localPlayer,"kajdanki", false) removeEventHandler("onClientPreRender", root, follow) triggerServerEvent("setPedAnimation", localPlayer) outputChatBox(getPlayerName(kto):gsub("#%x%x%x%x%x%x","") .. " zdejmuje z Ciebie kajdanki.",0,0,255) return end outputChatBox(getPlayerName(kto):gsub("#%x%x%x%x%x%x","") .. " zakuwa Cię w kajdanki.",0,0,255) setElementData(localPlayer,"kajdanki", kto) addEventHandler("onClientPreRender", root, follow) end) ------------------------------- local obecnie=getElementData(localPlayer, "kajdanki") if (obecnie and isElement(obecnie)) then addEventHandler("onClientPreRender", root, follow) end
function create() local progress = {} local progressBars = {} function progress.newBar(x, y, width, height, colour, vertical) if not height then height = 25 end if not colour then colour = {0.02, 1, 0.06} end progressBars[#progressBars+1] = {x=x, y=y, width=width, height=height, colour=colour, vertical=vertical, progress=0} return #progressBars end function progress.drawPBars() for id, bar in ipairs(progressBars) do local w, h = bar.width, bar.height if bar.vertical then local t = h h = w w = t end love.graphics.setColor(bar["colour"][1]+0.8, bar["colour"][2]+0.8, bar["colour"][3]+0.8) love.graphics.rectangle("fill", bar.x, bar.y, w, h) local w, h = bar.progress*(bar.width-4), bar.height-4 if bar.vertical then local t = h h = w w = t end love.graphics.setColor(bar["colour"][1]*0.95, bar["colour"][2]*0.95, bar["colour"][3]*0.95) love.graphics.rectangle("fill", bar.x+2, bar.y+2, w, h) end end function progress.setProgress(id, progress) progressBars[id]["progress"] = progress end function progress.delete(id) progressBars[id] = nil end return progress end return create
gt_frame=Class{} function gt_frame:init(x, y, w, h, col, outline) self.x=x self.y=y self.width=w self.height=h self.col=col self.hidden=false self.outline=outline end function gt_frame:draw() if(self.hidden) then return end love.graphics.setLineStyle("rough") love.graphics.setColor(self.col.r/255, self.col.g/255, self.col.b/255, self.col.alpha/100) love.graphics.rectangle("fill", self.x, self.y, self.width, self.height) love.graphics.setColor(self.outline.r/255, self.outline.g/255, self.outline.b/255, self.outline.alpha/100) -- RIGHT HAND SIDE love.graphics.line(self.x+self.width, self.y+1, self.x+self.width, self.y+self.height-1) -- TOP love.graphics.line(self.x+1, self.y, self.x+self.width-1, self.y) --BOTTOM love.graphics.line(self.x+1, self.y+self.height, self.x+self.width-1, self.y+self.height) -- LEFT HAND SIDE love.graphics.line(self.x, self.y+1, self.x, self.y+self.height-1) love.graphics.setPointSize(3) --pixel top left hand side love.graphics.points(self.x+.5, self.y+.5) --pixel top right hand side love.graphics.points(self.x+((self.width)-.5), self.y+.5) --pixel bottom right hand side love.graphics.points(self.x+.5, self.y+(self.height)-0.5) --pixel top bottom hand left side love.graphics.points(self.x+((self.width)-.5), self.y+(self.height)-0.5) love.graphics.setLineStyle("smooth") love.graphics.setColor(255/255, 255/255, 255/255, 100/100) end
-- Install packer local install_path = vim.fn.stdpath 'data' .. '/site/pack/packer/start/packer.nvim' if vim.fn.empty(vim.fn.glob(install_path)) > 0 then vim.fn.system({'git', 'clone', '--depth=1', 'https://github.com/wbthomason/packer.nvim', install_path}) end vim.api.nvim_exec( [[ augroup Packer autocmd! autocmd BufWritePost init.lua PackerCompile augroup end ]], false ) local use = require('packer').use require('packer').startup(function() use 'wbthomason/packer.nvim' -- Package manager use 'tpope/vim-sleuth' use 'tpope/vim-sensible' use 'tpope/vim-fugitive' -- Git commands in nvim use 'tpope/vim-rhubarb' -- Fugitive-companion to interact with github use 'tpope/vim-commentary' -- "gc" to comment visual regions/lines use 'ludovicchabant/vim-gutentags' -- Automatic tags management -- UI to select things (files, grep results, open buffers...) use { 'nvim-telescope/telescope.nvim', requires = { 'nvim-lua/plenary.nvim' } } use 'danilo-augusto/vim-afterglow' -- use 'joshdick/onedark.vim' use 'itchyny/lightline.vim' -- Fancier statusline -- Add indentation guides even on blank lines use 'lukas-reineke/indent-blankline.nvim' -- Add git related info in the signs columns and popups use { 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim' } } -- Highlight, edit, and navigate code using a fast incremental parsing library use 'nvim-treesitter/nvim-treesitter' -- Additional textobjects for treesitter use 'nvim-treesitter/nvim-treesitter-textobjects' use 'neovim/nvim-lspconfig' -- Collection of configurations for built-in LSP client use 'hrsh7th/nvim-cmp' -- Autocompletion plugin use 'hrsh7th/cmp-nvim-lsp' use 'saadparwaiz1/cmp_luasnip' use 'L3MON4D3/LuaSnip' -- Snippets plugin use 'fatih/vim-go' end) -- Omat vim.o.tabstop = 4 vim.o.softtabstop = 4 vim.o.shiftwidth = 4 vim.o.smarttab = true vim.g.netrw_banner = 0 vim.g.netrw_liststyle = 3 vim.g.netrw_browse_split = 4 vim.g.netrw_altv = 1 vim.g.netrw_winsize = 25 vim.api.nvim_exec( [[ augroup ProjectDrawer autocmd! autocmd VimEnter * :Vexplore augroup end ]], false ) --Incremental live completion (note: this is now a default on master) vim.o.inccommand = 'nosplit' --Set highlight on search vim.o.hlsearch = false --Make line numbers default vim.wo.number = true --Do not save when switching buffers (note: this is now a default on master) vim.o.hidden = true --Enable mouse mode vim.o.mouse = 'a' --Enable break indent vim.o.breakindent = true --Save undo history vim.opt.undofile = true --Case insensitive searching UNLESS /C or capital in search vim.o.ignorecase = true vim.o.smartcase = true --Decrease update time vim.o.updatetime = 250 vim.wo.signcolumn = 'yes' --Set colorscheme (order is important here) vim.o.termguicolors = true vim.g.afterglow_italic_comments = 1 vim.cmd [[colorscheme afterglow]] -- vim.cmd [[colorscheme onedark]] --Set statusbar vim.g.lightline = { colorscheme = 'one', active = { left = { { 'mode', 'paste' }, { 'gitbranch', 'readonly', 'filename', 'modified' } } }, component_function = { gitbranch = 'fugitive#head' }, } --Remap space as leader key vim.api.nvim_set_keymap('', '<Space>', '<Nop>', { noremap = true, silent = true }) vim.g.mapleader = ' ' vim.g.maplocalleader = ' ' --Remap for dealing with word wrap vim.api.nvim_set_keymap('n', 'k', "v:count == 0 ? 'gk' : 'k'", { noremap = true, expr = true, silent = true }) vim.api.nvim_set_keymap('n', 'j', "v:count == 0 ? 'gj' : 'j'", { noremap = true, expr = true, silent = true }) -- Highlight on yank vim.api.nvim_exec( [[ augroup YankHighlight autocmd! autocmd TextYankPost * silent! lua vim.highlight.on_yank() augroup end ]], false ) -- Y yank until the end of line (note: this is now a default on master) vim.api.nvim_set_keymap('n', 'Y', 'y$', { noremap = true }) -- Tabs --Map blankline vim.g.indent_blankline_char = '┊' vim.g.indent_blankline_filetype_exclude = { 'help', 'packer' } vim.g.indent_blankline_buftype_exclude = { 'terminal', 'nofile' } vim.g.indent_blankline_char_highlight = 'LineNr' vim.g.indent_blankline_show_trailing_blankline_indent = false -- Gitsigns require('gitsigns').setup { signs = { add = { hl = 'GitGutterAdd', text = '+' }, change = { hl = 'GitGutterChange', text = '~' }, delete = { hl = 'GitGutterDelete', text = '_' }, topdelete = { hl = 'GitGutterDelete', text = '‾' }, changedelete = { hl = 'GitGutterChange', text = '~' }, }, } -- Telescope require('telescope').setup { defaults = { mappings = { i = { ['<C-u>'] = false, ['<C-d>'] = false, }, }, }, } --Add leader shortcuts vim.api.nvim_set_keymap('n', '<leader><space>', [[<cmd>lua require('telescope.builtin').buffers()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>sf', [[<cmd>lua require('telescope.builtin').find_files({previewer = false})<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>sb', [[<cmd>lua require('telescope.builtin').current_buffer_fuzzy_find()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>sh', [[<cmd>lua require('telescope.builtin').help_tags()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>st', [[<cmd>lua require('telescope.builtin').tags()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>sd', [[<cmd>lua require('telescope.builtin').grep_string()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>sp', [[<cmd>lua require('telescope.builtin').live_grep()<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>so', [[<cmd>lua require('telescope.builtin').tags{ only_current_buffer = true }<CR>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>?', [[<cmd>lua require('telescope.builtin').oldfiles()<CR>]], { noremap = true, silent = true }) -- Treesitter configuration -- Parsers must be installed manually via :TSInstall require('nvim-treesitter.configs').setup { highlight = { enable = true, -- false will disable the whole extension }, incremental_selection = { enable = true, keymaps = { init_selection = 'gnn', node_incremental = 'grn', scope_incremental = 'grc', node_decremental = 'grm', }, }, indent = { enable = true, }, textobjects = { select = { enable = true, lookahead = true, -- Automatically jump forward to textobj, similar to targets.vim keymaps = { -- You can use the capture groups defined in textobjects.scm ['af'] = '@function.outer', ['if'] = '@function.inner', ['ac'] = '@class.outer', ['ic'] = '@class.inner', }, }, move = { enable = true, set_jumps = true, -- whether to set jumps in the jumplist goto_next_start = { [']m'] = '@function.outer', [']]'] = '@class.outer', }, goto_next_end = { [']M'] = '@function.outer', [']['] = '@class.outer', }, goto_previous_start = { ['[m'] = '@function.outer', ['[['] = '@class.outer', }, goto_previous_end = { ['[M'] = '@function.outer', ['[]'] = '@class.outer', }, }, }, } -- LSP settings local nvim_lsp = require 'lspconfig' local on_attach = function(_, bufnr) vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') local opts = { noremap = true, silent = true } vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts) -- vim.api.nvim_buf_set_keymap(bufnr, 'v', '<leader>ca', '<cmd>lua vim.lsp.buf.range_code_action()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>so', [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<CR>]], opts) vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]] end -- nvim-cmp supports additional completion capabilities local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) -- Enable the following language servers local servers = { 'pylsp', 'gopls' } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { on_attach = on_attach, capabilities = capabilities, } end -- require'lspconfig'.gopls.setup{} -- Example custom server local sumneko_root_path = vim.fn.getenv 'HOME' .. '/.local/bin/sumneko_lua' -- Change to your sumneko root installation local sumneko_binary = sumneko_root_path .. '/bin/linux/lua-language-server' -- Make runtime files discoverable to the server local runtime_path = vim.split(package.path, ';') table.insert(runtime_path, 'lua/?.lua') table.insert(runtime_path, 'lua/?/init.lua') require('lspconfig').sumneko_lua.setup { cmd = { sumneko_binary, '-E', sumneko_root_path .. '/main.lua' }, on_attach = on_attach, capabilities = capabilities, settings = { Lua = { runtime = { -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim) version = 'LuaJIT', -- Setup your lua path path = runtime_path, }, diagnostics = { -- Get the language server to recognize the `vim` global globals = { 'vim' }, }, workspace = { -- Make the server aware of Neovim runtime files library = vim.api.nvim_get_runtime_file('', true), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, }, }, } -- Set completeopt to have a better completion experience vim.o.completeopt = 'menuone,noselect' -- luasnip setup local luasnip = require 'luasnip' -- nvim-cmp setup local cmp = require 'cmp' cmp.setup { snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, }, mapping = { ['<C-p>'] = cmp.mapping.select_prev_item(), ['<C-n>'] = cmp.mapping.select_next_item(), ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = true, }, ['<Tab>'] = function(fallback) if vim.fn.pumvisible() == 1 then vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<C-n>', true, true, true), 'n') elseif luasnip.expand_or_jumpable() then vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<Plug>luasnip-expand-or-jump', true, true, true), '') else fallback() end end, ['<S-Tab>'] = function(fallback) if vim.fn.pumvisible() == 1 then vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<C-p>', true, true, true), 'n') elseif luasnip.jumpable(-1) then vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<Plug>luasnip-jump-prev', true, true, true), '') else fallback() end end, }, sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, }, }
----------------------------------- -- Area: Leujaoam Sanctum (Leujaoam Cleansing) -- Mob: Leujaoam Worm ----------------------------------- function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) local instance = mob:getInstance() instance:setProgress(instance:getProgress() + 1) end
local _, ns = ... local B, C, L, DB, P = unpack(ns) local oUF = _G.oUF or ns.oUF local UF = P:RegisterModule("UnitFrames") local NUF = B:GetModule("UnitFrames") function UF:SetTag(frame) local name = frame.nameText local mystyle = frame.mystyle local colorStr = UF.db["NameColor"] and frame.Health.colorClass and "" or "[color]" if name then if mystyle == "player" then frame:Tag(name, " "..colorStr.."[name]") elseif mystyle == "target" then frame:Tag(name, "[fulllevel] "..colorStr.."[name][afkdnd]") elseif mystyle == "focus" then frame:Tag(name, colorStr.."[name][afkdnd]") elseif mystyle == "arena" then frame:Tag(name, "[arenaspec] "..colorStr.."[name]") elseif mystyle == "raid" and C.db["UFs"]["SimpleMode"] and C.db["UFs"]["ShowTeamIndex"] and not frame.isPartyPet and not frame.isPartyFrame then frame:Tag(name, "[group]."..colorStr.."[name]") elseif mystyle ~= "nameplate" then frame:Tag(name, colorStr.."[name]") end name:UpdateTag() end end function UF:UpdateNameText() for _, frame in pairs(oUF.objects) do UF:SetTag(frame) end end function UF:SetNameTextHook() hooksecurefunc(NUF, "CreateHealthText", function(self, frame) UF:SetTag(frame) end) end function UF:SetupNameText() UF:SetNameTextHook() UF:UpdateNameText() hooksecurefunc(NUF, "UpdateTextScale", UF.UpdateNameText) hooksecurefunc(NUF, "UpdateRaidTextScale", UF.UpdateNameText) end function UF:OnLogin() P:Delay(1, function() UF:SetupNameText() UF:SetRoleIconsHook() UF:UpdateRoleIcons() UF:UpdateUFsFader() UF:UpdateAurasFilter() end) end
require("rest-nvim").setup({ result_split_horizontal = false, skip_ssl_verification = false, highlight = { enabled = true, timeout = 150, }, jump_to_request = false, }) vim.cmd[[ nmap <C-r> <Plug>RestNvim ]]
-- // Dependencies local Library = loadstring(game:HttpGet("https://pastebin.com/raw/PTrFUueU"))() local ESP = loadstring(game:HttpGet("https://kiriot22.com/releases/ESP.lua"))() -- // UI Theme Library.theme.accentcolor = Color3.new(0.011764, 0.521568, 1) Library.theme.background = "rbxassetid://2151741365" Library.theme.tilesize = 0.77 -- [[ INFO: Gun mods by Stefanuk12 and Viktor Reznov on v3rm! ]] -- -- // Initalize ESP ESP.Players = false ESP.TeamColor = true ESP:Toggle(true) -- // Configuration local Configuration = { AReload = 0, RecoilControl = 0, EReload = 0, SReload = 0, ReloadTime = 0, EquipTime = 0, Spread = 10, MaxSpread = 10, Range = 1000, Auto = true, FireRate = 0.8, BFireRate = 0.8, UnlimitedAmmo = true } -- // Services local runService = game:GetService("RunService") local replicatedStorage = game:GetService("ReplicatedStorage") local players = game:GetService("Players") -- // Loop through every weapon local function modifyWeapons() for _, weapon in ipairs(replicatedStorage.Weapons:GetChildren()) do -- // lol for _, config in ipairs(weapon:GetChildren()) do -- // Disable "Anti Cheat" for _, conn in ipairs(getconnections(config.Changed)) do conn:Disable() end -- // Set according to Configuration, making sure it exists local modConfig = Configuration[config.Name] if modConfig then config.Value = modConfig end end end end -- // Variables local localPlayer = players.LocalPlayer local PlayerGui = localPlayer.PlayerGui local Variables = PlayerGui.GUI.Client.Variables -- // UI Components local Window = Library:CreateWindow("Floppa Hub", Vector2.new(492, 598), Enum.KeyCode.RightShift) do local visualsTab = Window:CreateTab("Visuals") do local espSec = visualsTab:CreateSector("ESP", "left") do espSec:AddToggle( "Enabled", false, function(bool) ESP.Players = bool end ) espSec:AddToggle( "Team Color", true, function(bool) ESP.TeamColor = bool end ) espSec:AddToggle( "Tracers", false, function(bool) ESP.Tracers = bool end ) espSec:AddToggle( "Boxes", true, function(bool) ESP.Boxes = bool end ) espSec:AddToggle( "Names", true, function(bool) ESP.Names = bool end ) end local mainTab = Window:CreateTab("Arsenal") do local modsSec = mainTab:CreateSector("Gun Mods", "left") do modsSec:AddToggle( "Infinite Ammo", false, function(bool) Configuration.UnlimitedAmmo = bool modifyWeapons() end ) modsSec:AddToggle( "Always Automatic", false, function(bool) Configuration.Auto = bool modifyWeapons() end ) modsSec:AddToggle( "Infinite Ammo", false, function(bool) Configuration.UnlimitedAmmo = bool modifyWeapons() end ) modsSec:AddToggle( "Infinite Ammo", false, function(bool) Configuration.UnlimitedAmmo = bool modifyWeapons() end ) modsSec:AddToggle( "Fast Equip", false, function(bool) Configuration.EquipTime = 0 modifyWeapons() end ) modsSec:AddToggle( "No Reload Time", false, function(bool) Configuration.ReloadTime = 0 modifyWeapons() end ) modsSec:AddToggle( "Fast Fire Rate", false, function(bool) Configuration.FireRate = 0.000001 modifyWeapons() end ) end end end local settingsTab = Window:CreateTab("Settings") do if syn then settingsTab:CreateConfigSystem("left") else print("Your exploit doesnt support this.") end end end task.spawn( function() while task.wait() do -- // Make sure is enabled if Configuration.UnlimitedAmmo then -- // Set Variables.ammocount.Value = 300 Variables.ammocount2.Value = 300 Variables.primarystored.Value = 300 Variables.secondarystored.Value = 300 end end end )
object_tangible_meatlump_event_meatlump_food_palette_01_11 = object_tangible_meatlump_event_shared_meatlump_food_palette_01_11:new { } ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_food_palette_01_11, "object/tangible/meatlump/event/meatlump_food_palette_01_11.iff")
local ran_before return function(options) if ran_before then ngx.log(ngx.WARN, debug.traceback("attempt to re-run the globalpatches", 2)) return end ngx.log(ngx.DEBUG, "installing the globalpatches") ran_before = true options = options or {} local meta = require "kong.meta" _G._KONG = { _NAME = meta._NAME, _VERSION = meta._VERSION } if options.cli then ngx.IS_CLI = true -- luacheck: globals ngx.exit ngx.exit = function() end end do -- deal with ffi re-loading issues if options.rbusted then -- pre-load the ffi module, such that it becomes part of the environment -- and Busted will not try to GC and reload it. The ffi is not suited -- for that and will occasionally segfault if done so. local ffi = require "ffi" -- Now patch ffi.cdef to only be called once with each definition local old_cdef = ffi.cdef local exists = {} ffi.cdef = function(def) if exists[def] then return end exists[def] = true return old_cdef(def) end end end do -- implement `sleep` in the `init_worker` context -- initialization code regularly uses the shm and locks. -- the resty-lock is based on sleeping while waiting, but that api -- is unavailable. Hence we implement a BLOCKING sleep, only in -- the init_worker context. local get_phase= ngx.get_phase local ngx_sleep = ngx.sleep local alternative_sleep = require("socket").sleep -- luacheck: globals ngx.sleep ngx.sleep = function(s) if get_phase() == "init_worker" then ngx.log(ngx.WARN, "executing a blocking 'sleep' (", s, " seconds)") return alternative_sleep(s) end return ngx_sleep(s) end end do -- implement a Lua based shm for: cli (and hence rbusted) if options.cli then -- ngx.shared.DICT proxy -- https://github.com/bsm/fakengx/blob/master/fakengx.lua -- with minor fixes and addtions such as exptime -- -- See https://github.com/openresty/resty-cli/pull/12 -- for a definitive solution of using shms in CLI local SharedDict = {} local function set(data, key, value) data[key] = { value = value, info = {expired = false} } end function SharedDict:new() return setmetatable({data = {}}, {__index = self}) end function SharedDict:get(key) return self.data[key] and self.data[key].value, nil end SharedDict.get_stale = SharedDict.get function SharedDict:set(key, value) set(self.data, key, value) return true, nil, false end SharedDict.safe_set = SharedDict.set function SharedDict:add(key, value, exptime) if self.data[key] ~= nil then return false, "exists", false end if exptime then ngx.timer.at(exptime, function() self.data[key] = nil end) end set(self.data, key, value) return true, nil, false end SharedDict.safe_add = SharedDict.add function SharedDict:replace(key, value) if self.data[key] == nil then return false, "not found", false end set(self.data, key, value) return true, nil, false end function SharedDict:delete(key) if self.data[key] ~= nil then self.data[key] = nil end return true end function SharedDict:incr(key, value, init) if not self.data[key] then if not init then return nil, "not found" else self.data[key] = { value = init } end elseif type(self.data[key].value) ~= "number" then return nil, "not a number" end self.data[key].value = self.data[key].value + value return self.data[key].value, nil end function SharedDict:flush_all() for _, item in pairs(self.data) do item.info.expired = true end end function SharedDict:flush_expired(n) local data = self.data local flushed = 0 for key, item in pairs(self.data) do if item.info.expired then data[key] = nil flushed = flushed + 1 if n and flushed == n then break end end end self.data = data return flushed end function SharedDict:get_keys(n) n = n or 1024 local i = 0 local keys = {} for k in pairs(self.data) do keys[#keys+1] = k i = i + 1 if n ~= 0 and i == n then break end end return keys end -- hack _G.ngx.shared = setmetatable({}, { __index = function(self, key) local shm = rawget(self, key) if not shm then shm = SharedDict:new() rawset(self, key, shm) end return shm end }) end end do -- randomseeding patch for: cli, rbusted and OpenResty --- Seeds the random generator, use with care. -- Once - properly - seeded, this method is replaced with a stub -- one. This is to enforce best-practices for seeding in ngx_lua, -- and prevents third-party modules from overriding our correct seed -- (many modules make a wrong usage of `math.randomseed()` by calling -- it multiple times or by not useing unique seeds for Nginx workers). -- -- This patched method will create a unique seed per worker process, -- using a combination of both time and the worker's pid. local util = require "kong.tools.utils" local seeds = {} local randomseed = math.randomseed _G.math.randomseed = function() local seed = seeds[ngx.worker.pid()] if not seed then if not options.cli and ngx.get_phase() ~= "init_worker" then ngx.log(ngx.WARN, debug.traceback("math.randomseed() must be " .. "called in init_worker context", 2)) end local bytes, err = util.get_rand_bytes(8) if bytes then ngx.log(ngx.DEBUG, "seeding PRNG from OpenSSL RAND_bytes()") local t = {} for i = 1, #bytes do local byte = string.byte(bytes, i) t[#t+1] = byte end local str = table.concat(t) if #str > 12 then -- truncate the final number to prevent integer overflow, -- since math.randomseed() could get cast to a platform-specific -- integer with a different size and get truncated, hence, lose -- randomness. -- double-precision floating point should be able to represent numbers -- without rounding with up to 15/16 digits but let's use 12 of them. str = string.sub(str, 1, 12) end seed = tonumber(str) else ngx.log(ngx.ERR, "could not seed from OpenSSL RAND_bytes, seeding ", "PRNG with time and worker pid instead (this can ", "result to duplicated seeds): ", err) seed = ngx.now()*1000 + ngx.worker.pid() end ngx.log(ngx.DEBUG, "random seed: ", seed, " for worker nb ", ngx.worker.id()) if not options.cli then local ok, err = ngx.shared.kong:safe_set("pid: " .. ngx.worker.pid(), seed) if not ok then ngx.log(ngx.WARN, "could not store PRNG seed in kong shm: ", err) end end randomseed(seed) seeds[ngx.worker.pid()] = seed else ngx.log(ngx.DEBUG, debug.traceback("attempt to seed random number " .. "generator, but already seeded with: " .. tostring(seed), 2)) end return seed end end do -- cosockets connect patch for dns resolution for: cli, rbusted and OpenResty local sub = string.sub --- Patch the TCP connect and UDP setpeername methods such that all -- connections will be resolved first by the internal DNS resolver. -- STEP 1: load code that should not be using the patched versions require "resty.dns.resolver" -- will cache TCP and UDP functions -- STEP 2: forward declaration of locals to hold stuff loaded AFTER patching local toip -- STEP 3: store original unpatched versions local old_tcp = ngx.socket.tcp local old_udp = ngx.socket.udp local old_tcp_connect local old_udp_setpeername -- need to do the extra check here: https://github.com/openresty/lua-nginx-module/issues/860 local function strip_nils(first, second) if second then return first, second elseif first then return first end end local function resolve_connect(f, sock, host, port, opts) if sub(host, 1, 5) ~= "unix:" then host, port = toip(host, port) if not host then return nil, "[toip() name lookup failed]: " .. tostring(port) end end return f(sock, host, strip_nils(port, opts)) end local function tcp_resolve_connect(sock, host, port, opts) return resolve_connect(old_tcp_connect, sock, host, port, opts) end local function udp_resolve_setpeername(sock, host, port) return resolve_connect(old_udp_setpeername, sock, host, port) end -- STEP 4: patch globals _G.ngx.socket.tcp = function(...) local sock = old_tcp(...) if not old_tcp_connect then old_tcp_connect = sock.connect end sock.connect = tcp_resolve_connect return sock end _G.ngx.socket.udp = function(...) local sock = old_udp(...) if not old_udp_setpeername then old_udp_setpeername = sock.setpeername end sock.setpeername = udp_resolve_setpeername return sock end -- STEP 5: load code that should be using the patched versions, if any (because of dependency chain) toip = require("resty.dns.client").toip -- this will load utils and penlight modules for example end end
http://piratepad.net/0XP4FyvShw
-- compatible CUDA require 'torch' require 'nn' local GlobalkMaxPooling, parent = torch.class('nn.GlobalkMaxPooling', 'nn.Module') function GlobalkMaxPooling:__init(nMax) parent.__init(self) self.nMax = nMax or 1 self.output = torch.Tensor() self.indices = torch.Tensor() end function GlobalkMaxPooling:updateOutput(input) local batchSize = 0 local numChannels = 0 local h = 0 local w = 0 if input:dim() == 4 then -- batch batchSize = input:size(1) numChannels = input:size(2) h = input:size(3) w = input:size(4) elseif input:dim() == 3 then -- image batchSize = 1 numChannels = input:size(1) h = input:size(2) w = input:size(3) else print('error in GlobalkMaxPooling:updateOutput - incorrect input size') end local nMax = self.nMax if nMax <= 0 then nMax = math.max(1, math.floor(h * w)) elseif nMax < 1 then nMax = math.max(1, math.floor(nMax * h * w)) end self.output:typeAs(input):resize(batchSize, numChannels, 1, 1) local x = input:view(batchSize, numChannels, h*w) -- sort scores by decreasing order local scoreSorted, indices = torch.sort(x, x:size():size(), true) -- compute top max self.indices = indices[{{},{},{1,nMax}}] torch.sum(self.output, scoreSorted[{{},{},{1,nMax}}], 3) self.output:div(nMax) if input:dim() == 4 then self.output = self.output:view(batchSize, numChannels, 1, 1) elseif input:dim() == 3 then self.output = self.output:view(numChannels, 1, 1) end return self.output end function GlobalkMaxPooling:updateGradInput(input, gradOutput) if input:dim() == 4 then -- batch batchSize = input:size(1) numChannels = input:size(2) h = input:size(3) w = input:size(4) elseif input:dim() == 3 then -- image batchSize = 1 numChannels = input:size(1) h = input:size(2) w = input:size(3) else print('error in GlobalkMaxPooling:updateGradInput - incorrect input size') end local nMax = self.nMax if nMax <= 0 then nMax = math.max(1, math.floor(h * w)) elseif nMax < 1 then nMax = math.max(1, math.floor(nMax * h * w)) end local yMax = torch.expand(gradOutput:clone():view(batchSize, numChannels, 1), batchSize, numChannels, nMax) local z = torch.zeros(batchSize, numChannels, h*w):typeAs(input) self.gradInput = z:scatter(3, self.indices, yMax):div(nMax) if input:dim() == 4 then self.gradInput = self.gradInput:view(batchSize, numChannels, h, w) elseif input:dim() == 3 then self.gradInput = self.gradInput:view(numChannels, h, w) end return self.gradInput end function GlobalkMaxPooling:empty() self.gradInput:resize() self.gradInput:storage():resize(0) self.output:resize() self.output:storage():resize(0) self.indices:resize() self.indices:storage():resize(0) end function GlobalkMaxPooling:__tostring__() local s = string.format('%s(nMax=%d)', torch.type(self), self.nMax) return s end
-- parseit.lua INCOMPLETE -- Glenn G. Chappell -- 2021-02-17 -- -- For CS F331 / CSCE A331 Spring 2021 -- Solution to Assignment 4, Exercise 1 -- Requires lexit.lua -- Changed made by Luke Underwood -- Updated: 2/22/2021 -- Completed: 2/24/2021 local lexit = require "lexit" -- ********************************************************************* -- Module Table Initialization -- ********************************************************************* local parseit = {} -- Our module -- ********************************************************************* -- Variables -- ********************************************************************* -- For lexer iteration local iter -- Iterator returned by lexit.lex local state -- State for above iterator (maybe not used) local lexer_out_s -- Return value #1 from above iterator local lexer_out_c -- Return value #2 from above iterator -- For current lexeme local lexstr = "" -- String form of current lexeme local lexcat = 0 -- Category of current lexeme: -- one of categories below, or 0 for past the end -- ********************************************************************* -- Symbolic Constants for AST -- ********************************************************************* local STMT_LIST = 1 local WRITE_STMT = 2 local RETURN_STMT = 3 local ASSN_STMT = 4 local FUNC_CALL = 5 local FUNC_DEF = 6 local IF_STMT = 7 local FOR_LOOP = 8 local STRLIT_OUT = 9 local CR_OUT = 10 local DQ_OUT = 11 local CHAR_CALL = 12 local BIN_OP = 13 local UN_OP = 14 local NUMLIT_VAL = 15 local BOOLLIT_VAL = 16 local READNUM_CALL = 17 local SIMPLE_VAR = 18 local ARRAY_VAR = 19 -- ********************************************************************* -- Utility Functions -- ********************************************************************* -- advance -- Go to next lexeme and load it into lexstr, lexcat. -- Should be called once before any parsing is done. -- Function init must be called before this function is called. local function advance() -- Advance the iterator lexer_out_s, lexer_out_c = iter(state, lexer_out_s) -- If we're not past the end, copy current lexeme into vars if lexer_out_s ~= nil then lexstr, lexcat = lexer_out_s, lexer_out_c else lexstr, lexcat = "", 0 end end -- init -- Initial call. Sets input for parsing functions. local function init(prog) iter, state, lexer_out_s = lexit.lex(prog) advance() end -- atEnd -- Return true if pos has reached end of input. -- Function init must be called before this function is called. local function atEnd() return lexcat == 0 end -- matchString -- Given string, see if current lexeme string form is equal to it. If -- so, then advance to next lexeme & return true. If not, then do not -- advance, return false. -- Function init must be called before this function is called. local function matchString(s) if lexstr == s then advance() return true else return false end end -- matchCat -- Given lexeme category (integer), see if current lexeme category is -- equal to it. If so, then advance to next lexeme & return true. If -- not, then do not advance, return false. -- Function init must be called before this function is called. local function matchCat(c) if lexcat == c then advance() return true else return false end end -- ********************************************************************* -- "local" Statements for Parsing Functions -- ********************************************************************* local parse_program local parse_stmt_list local parse_simple_stmt local parse_complex_stmt local parse_write_arg local parse_expr local parse_compare_expr local parse_arith_expr local parse_term local parse_factor -- ********************************************************************* -- The Parser: Function "parse" - EXPORTED -- ********************************************************************* -- parse -- Given program, initialize parser and call parsing function for start -- symbol. Returns pair of booleans & AST. First boolean indicates -- successful parse or not. Second boolean indicates whether the parser -- reached the end of the input or not. AST is only valid if first -- boolean is true. function parseit.parse(prog) -- Initialization init(prog) -- Get results from parsing local good, ast = parse_program() -- Parse start symbol local done = atEnd() -- And return them return good, done, ast end -- ********************************************************************* -- Parsing Functions -- ********************************************************************* -- Each of the following is a parsing function for a nonterminal in the -- grammar. Each function parses the nonterminal in its name and returns -- a pair: boolean, AST. On a successul parse, the boolean is true, the -- AST is valid, and the current lexeme is just past the end of the -- string the nonterminal expanded into. Otherwise, the boolean is -- false, the AST is not valid, and no guarantees are made about the -- current lexeme. See the AST Specification near the beginning of this -- file for the format of the returned AST. -- NOTE. Declare parsing functions "local" above, but not below. This -- allows them to be called before their definitions. -- parse_program -- Parsing function for nonterminal "program". -- Function init must be called before this function is called. function parse_program() -- function simplified to point out its uselessness -- like honestly why is statement list even a part of the grammar? -- we have a single nonterminal going to a single nonterminal -- why?? return parse_stmt_list() end -- parse_stmt_list -- Parsing function for nonterminal "stmt_list". -- Function init must be called before this function is called. function parse_stmt_list() local good, ast1, ast2 ast1 = { STMT_LIST } while true do if lexstr == "write" -- simple statements or lexstr == "return" or lexcat == lexit.ID then good, ast2 = parse_simple_stmt() if not good then return false, nil end if not matchString(";") then return false, nil end elseif lexstr == "def" -- complex statements or lexstr == "if" or lexstr == "for" then good, ast2 = parse_complex_stmt() if not good then return false, nil end else break end table.insert(ast1, ast2) end return true, ast1 end -- parse_simple_stmt -- Parsing function for nonterminal "simple_stmt". -- Function init must be called before this function is called. function parse_simple_stmt() local good, ast1, ast2, savelex, arrayflag if matchString("write") then -- write statements if not matchString("(") then return false, nil end if matchString(")") then return true, { WRITE_STMT } end good, ast1 = parse_write_arg() if not good then return false, nil end ast2 = { WRITE_STMT, ast1 } while matchString(",") do good, ast1 = parse_write_arg() if not good then return false, nil end table.insert(ast2, ast1) end if not matchString(")") then return false, nil end return true, ast2 elseif matchString("return") then -- return statements good, ast1 = parse_expr() if not good then return false, nil end return true, { RETURN_STMT, ast1 } elseif lexcat == lexit.ID then -- statements starting with an ID savelex = lexstr advance() if matchString("(") then if not matchString(")") then return false, nil end return true, { FUNC_CALL, savelex } end if matchString("[") then good, ast1 = parse_expr() if not good then return false, nil end if not matchString("]") then return false, nil end ast1 = { ASSN_STMT, { ARRAY_VAR, savelex, ast1 } } else ast1 = { ASSN_STMT, { SIMPLE_VAR, savelex } } end if matchString("=") then good, ast2 = parse_expr() if not good then return false, nil end table.insert(ast1, ast2) return true, ast1 else return false, nil end else return false, nil end end -- parse_complex_stmt -- Parsing function for nonterminal "complex_stmt". -- Function init must be called before this function is called. function parse_complex_stmt() local good, ast1, ast2, ast3, ast4, savelex if matchString("def") then -- function definitions savelex = lexstr if not matchCat(lexit.ID) then return false, nil end if not( matchString("(") and matchString(")") and matchString ("{") ) then return false, nil end good, ast1 = parse_stmt_list() if not good then return false, nil end if not matchString ("}") then return false, nil end return true, { FUNC_DEF, savelex, ast1 } elseif matchString("if") then -- if statements ast1 = { IF_STMT } good, ast2 = parse_expr() if not good then return false, nil end table.insert(ast1, ast2) if not matchString("{") then return false, nil end good, ast2 = parse_stmt_list() if not good then return false, nil end if not matchString("}") then return false, nil end table.insert(ast1, ast2) while true do if not matchString("elseif") then break end good, ast2 = parse_expr() if not good then return false, nil end table.insert(ast1, ast2) if not matchString("{") then return false, nil end good, ast2 = parse_stmt_list() if not good then return false, nil end if not matchString("}") then return false, nil end table.insert(ast1, ast2) end if matchString("else") then if not matchString("{") then return false, nil end good, ast2 = parse_stmt_list() if not good then return false, nil end if not matchString("}") then return false, nil end table.insert(ast1, ast2) end return true, ast1 elseif matchString("for") then -- for loops if not matchString("(") then return false, nil end if matchString(";") then ast1 = {} else good, ast1 = parse_simple_stmt() if not good then return false, nil end if not matchString(";") then return false, nil end end if matchString(";") then ast2 = {} else good, ast2 = parse_expr() if not good then return false, nil end if not matchString(";") then return false, nil end end if matchString(")") then ast3 = {} else good, ast3 = parse_simple_stmt() if not good then return false, nil end if not matchString(")") then return false, nil end end if not matchString("{") then return false, nil end good, ast4 = parse_stmt_list() if not good then return false, nil end if not matchString("}") then return false, nil end return true, { FOR_LOOP, ast1, ast2, ast3, ast4 } else -- make sure we don't run off end return false, nil end end -- parse_write_arg -- Parsing function for nonterminal "write_arg". -- Function init must be called before this function is called. function parse_write_arg() local savelex, good, ast1 savelex = lexstr if matchCat(lexit.STRLIT) then -- string literal return true, { STRLIT_OUT, savelex } elseif matchString("cr") then -- carriage return return true, { CR_OUT } elseif matchString("dq") then -- double quote return true, { DQ_OUT } elseif matchString("char") then -- char call if not matchString("(") then return false, nil end good, ast1 = parse_expr() if not good then return false, nil end if not matchString(")") then return false, nil end return true, { CHAR_CALL, ast1 } else -- expression return parse_expr() end end -- parse_expr -- Parsing function for nonterminal "expr". -- Function init must be called before this function is called. function parse_expr() local good, ast1, ast2, ast3, savelex good, ast1 = parse_compare_expr() -- first term if not good then return false, nil end while true do -- add the rest of the terms savelex = lexstr if not ( matchString("and") or matchString("or") ) then break end good, ast2 = parse_compare_expr() if not good then return false, nil end ast1 = { { BIN_OP, savelex }, ast1, ast2 } end return true, ast1 end -- parse_compare_expr -- Parsing function for nonterminal "compare_expr". -- Function init must be called before this function is called. function parse_compare_expr() local good, ast1, ast2, ast3, savelex good, ast1 = parse_arith_expr() -- first term if not good then return false, nil end while true do -- add the rest of the terms savelex = lexstr if not ( matchString("==") or matchString("!=") or matchString("<") or matchString("<=") or matchString(">") or matchString(">=") ) then break end good, ast2 = parse_arith_expr() if not good then return false, nil end ast1 = { { BIN_OP, savelex }, ast1, ast2 } end return true, ast1 end -- parse_arith_expr -- Parsing function for nonterminal "arith_expr". -- Function init must be called before this function is called. function parse_arith_expr() local good, ast1, ast2, ast3, savelex good, ast1 = parse_term() -- first term if not good then return false, nil end while true do -- add the rest of the terms savelex = lexstr if not ( matchString("+") or matchString("-") ) then break end good, ast2 = parse_term() if not good then return false, nil end ast1 = { { BIN_OP, savelex }, ast1, ast2 } end if binop then return true, ast3 else return true, ast1 end end -- parse_term -- Parsing function for nonterminal "term". -- Function init must be called before this function is called. function parse_term() local good, ast1, ast2, ast3, savelex good, ast1 = parse_factor() -- first term if not good then return false, nil end while true do -- add the rest of the terms savelex = lexstr if not ( matchString("*") or matchString("/") or matchString("%") ) then break end good, ast2 = parse_factor() if not good then return false, nil end ast1 = { { BIN_OP, savelex }, ast1, ast2 } end return true, ast1 end -- parse_factor -- Parsing function for nonterminal "factor". -- Function init must be called before this function is called. function parse_factor() local good, ast1, ast2, savelex savelex = lexstr -- parenthesized expression if matchString("(") then good, ast1 = parse_expr() if not good then return false, nil end if not matchString(")") then return false, nil end return true, ast1 -- unary operators elseif matchString("+") or matchString("-") or matchString("not") then good, ast1 = parse_factor() if not good then return false, nil end return true, { { UN_OP, savelex}, ast1 } -- numeric literal elseif matchCat(lexit.NUMLIT) then return true, { NUMLIT_VAL, savelex } -- boolean literal elseif matchString("true") or matchString("false") then return true, { BOOLLIT_VAL, savelex } -- readnum call elseif matchString("readnum") and matchString("(") and matchString(")") then return true, { READNUM_CALL } -- factors starting with an identifier elseif matchCat(lexit.ID) then if matchString("(") and matchString(")") then return true, { FUNC_CALL, savelex } elseif matchString("[") then good, ast1 = parse_expr() if not good then return nil, false end if not matchString("]") then return nil, false end return true, { ARRAY_VAR, savelex, ast1 } else return true, { SIMPLE_VAR, savelex } end -- make sure we don't run off end else return false, nil end end -- ********************************************************************* -- Module Table Return -- ********************************************************************* return parseit
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- NOTE: this script is functionally equivalent to bin/mac/CompileScripts.sh -- If you are changing this one, you probably want to change the other. -------------------------------------------------------------------------------- local args = {...} -------------------------------------------------------------------------------- -- Functions -------------------------------------------------------------------------------- local function fileExists( path ) local f = io.open( path, "r" ) if f then f:close() return true end return false end local function checkError( passesCheck, msg ) if not passesCheck then if not msg then msg = "Exiting due to errors (above)." end print( "ERROR: ", msg ) -- os.exit( -1 ) end end local function execute( ... ) local args = { ... } local cmd = table.concat( args, ' ' ) local f = io.popen( cmd ) local result = f:read( "*a" ) f:close() return result end local function os_execute( ... ) local args = { ... } local cmd = table.concat( args, ' ' ) local rc = os.execute( cmd ) print("execute: ", cmd, "retcode: ", rc) return rc end local function touch( path ) io.open( path, "w" ):close() end local function escape( param ) return '"' .. param .. '"' end -------------------------------------------------------------------------------- -- Arguments -------------------------------------------------------------------------------- local PLATFORM local CORONA_ROOT if args then PLATFORM = args[1] CORONA_ROOT = args[2] end --[[ -- Platform of caller local PLATFORM if os.getenv("WINDIR") then PLATFORM = "win32" else local ostype = os.getenv( "OSTYPE" ) print( "OSTYPE,", ostype) if nil ~= string.find( ostype:lower(), "darwin", 1, true ) then PLATFORM = "mac" end end checkError( PLATFORM, "Could not determine platform." ) --]] -- Location of CoronaEnterprise directory checkError( PLATFORM, "Could not determine the OS this script is running on." ) checkError( CORONA_ROOT, "Could not determine path to 'Native' directory." ) local BIN_DIR = CORONA_ROOT .. "/Corona/" .. PLATFORM .. "/bin" if PLATFORM == "win" then BIN_DIR = CORONA_ROOT .. "\\Corona\\" .. PLATFORM .. "\\bin" end local BUILDER_PATH = BIN_DIR .. "/CoronaBuilder.app/Contents/MacOS/CoronaBuilder" if PLATFORM == "win" then BUILDER_PATH = BIN_DIR .. "\\CoronaBuilder.exe" end checkError( fileExists( BUILDER_PATH ), "Required CoronaBuilder tool not found at (" .. BUILDER_PATH .. ")" ) -------------------------------------------------------------------------------- -- Environment variables -------------------------------------------------------------------------------- -- [Required] TARGET_PLATFORM = os.getenv( "TARGET_PLATFORM" ) checkError( TARGET_PLATFORM, "Missing target device platform." ) -- [Required] Optional on iOS/Mac PROJECT_DIR = os.getenv( "PROJECT_DIR" ) checkError( PROJECT_DIR, "Missing environment variable 'PROJECT_DIR'." ) -- [Required] Optional on iOS/Mac CONFIGURATION = os.getenv( "CONFIGURATION" ) if not CONFIGURATION then CONFIGURATION = "debug" print( "WARNING: Defaulting to 'debug' configuration." ) end checkError( CONFIGURATION ) -- [Optional] Assuming you're okay with defaults CORONA_ASSETS_DIR = os.getenv( "CORONA_ASSETS_DIR" ) if not CORONA_ASSETS_DIR then CORONA_ASSETS_DIR = PROJECT_DIR .. "/../Corona" if PLATFORM == "win" then CORONA_ASSETS_DIR = PROJECT_DIR .. "\\..\\Corona" end end -- [Required] Optional on iOS/Mac CORONA_TARGET_RESOURCES_DIR = os.getenv( "CORONA_TARGET_RESOURCES_DIR" ) if not CORONA_TARGET_RESOURCES_DIR then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- $TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH TARGET_BUILD_DIR = os.getenv( "TARGET_BUILD_DIR" ) UNLOCALIZED_RESOURCES_FOLDER_PATH = os.getenv( "UNLOCALIZED_RESOURCES_FOLDER_PATH" ) if TARGET_BUILD_DIR and UNLOCALIZED_RESOURCES_FOLDER_PATH then CORONA_TARGET_RESOURCES_DIR = TARGET_BUILD_DIR .. '/' .. UNLOCALIZED_RESOURCES_FOLDER_PATH end end end checkError( CORONA_TARGET_RESOURCES_DIR, "Missing target build resources directory." ) -- [Required] Optional on iOS/Mac CORONA_TARGET_EXECUTABLE_DIR = os.getenv( "CORONA_TARGET_EXECUTABLE_DIR" ) if not CORONA_TARGET_EXECUTABLE_DIR then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- $TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH TARGET_BUILD_DIR = os.getenv( "TARGET_BUILD_DIR" ) EXECUTABLE_FOLDER_PATH = os.getenv( "EXECUTABLE_FOLDER_PATH" ) if TARGET_BUILD_DIR and EXECUTABLE_FOLDER_PATH then CORONA_TARGET_EXECUTABLE_DIR = TARGET_BUILD_DIR .. '/' .. EXECUTABLE_FOLDER_PATH end end end checkError( CORONA_TARGET_EXECUTABLE_DIR, "Missing target build executable directory." ) -- [Required] Optional on iOS/Mac BUNDLE_ID = os.getenv( "BUNDLE_ID" ) if not BUNDLE_ID then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then -- local cmd = '/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$TARGET_BUILD_DIR/$INFOPLIST_PATH"' BUNDLE_ID = execute( cmd ) end end -- Remove trailing whitespace (including newline) if BUNDLE_ID then BUNDLE_ID = BUNDLE_ID:gsub( '%s', "" ) end -- [Required] Optional on iOS/Mac local APP_ID = os.getenv( "APP_ID" ) if not APP_ID then if "ios" == TARGET_PLATFORM or "mac" == TARGET_PLATFORM then local cmd = '/usr/libexec/PlistBuddy -c "Print :CoronaAppId" "$TARGET_BUILD_DIR/$INFOPLIST_PATH" 2>/dev/null' APP_ID = execute( cmd ) end end -- Assign if all else fails if "" == APP_ID or not APP_ID then if BUNDLE_ID then APP_ID = BUNDLE_ID end end -- Remove trailing whitespace (including newline) if APP_ID then APP_ID = APP_ID:gsub( '%s', "" ) end -- Ignore the given Bundle ID and App ID for Android Enterprise builds. -- This is because most enterprise users do not know to set the package name in the "build.xml" file. if "android" == TARGET_PLATFORM then BUNDLE_ID = nil APP_ID = nil end local RESOURCE_EXT = ".car" if "ios" == TARGET_PLATFORM then RESOURCE_EXT = ".corona-archive" end -- [Optional] USER_ID = os.getenv( "USER_ID" ) if not USER_ID then USER_ID = '345' end if BUNDLE_ID then print( "Using Bundle Id: (" .. BUNDLE_ID .. ")" ) end if APP_ID then print( "Using AppId: (" .. APP_ID .. ")" ) end -------------------------------------------------------------------------------- -- Main -------------------------------------------------------------------------------- -- Copy project resources, compile Lua scripts, etc -- "$BIN_DIR/CopyResources.sh" $CONFIGURATION "$CORONA_ASSETS_DIR" "$CORONA_TARGET_RESOURCES_DIR" "$BIN_DIR" local CopyResourcesScript = escape( BIN_DIR .. "/CopyResources.sh" ) if PLATFORM == "win" then CopyResourcesScript = 'cmd /Q/C "' .. escape( BIN_DIR .. "\\CopyResources.bat" ) .. ' ' .. CONFIGURATION .. ' ' .. escape( CORONA_ASSETS_DIR ) .. ' ' .. escape( CORONA_TARGET_RESOURCES_DIR ) .. ' ' .. escape( BIN_DIR ) .. '"' local result = os_execute(CopyResourcesScript) checkError( 0 == tonumber( result ) ) else local result = os_execute( CopyResourcesScript, CONFIGURATION, escape( CORONA_ASSETS_DIR ), escape( CORONA_TARGET_RESOURCES_DIR ), escape( BIN_DIR ) ) checkError( 0 == tonumber( result ) ) end -- Config.lua TMP_FILE = os.tmpname() if PLATFORM == "win" then TMP_FILE = os.getenv('TMP')..TMP_FILE end CONFIG_META = TMP_FILE -- "$TARGET_BUILD_DIR/config.metadata.lua" local pl = require "pl" local pl_dir = require "pl.dir" local pl_path = require "pl.path" local pl_file = require "pl.file" PROJECT_NAME = pl_path.basename( PROJECT_DIR ) -- `basename "$PROJECT_DIR"` MODE="distribution" if nil ~= string.find( CONFIGURATION:lower(), "Debug", 1, true ) then MODE="developer" end print("Creating application.metadata ...") local config_meta_format = [[ -- Ensure existence of "application" table if not application or type( application ) ~= "table" then application = {} end application.metadata = { appName = "%s", appVersion = "1.0", %s %s userId = "%s", mode = "%s", } ]] local bundleIdTableEntry = "" if BUNDLE_ID then bundleIdTableEntry = 'appPackageId = "' .. tostring(BUNDLE_ID) .. '",' end local appIdTableEntry = "" if APP_ID then appIdTableEntry = 'appId = "' .. tostring(APP_ID) .. '",' end local config_meta = string.format( config_meta_format, PROJECT_NAME, bundleIdTableEntry, appIdTableEntry, USER_ID, MODE ) local config_meta_file = io.open( CONFIG_META, "w+" ) print("CONFIG_META=", CONFIG_META, "config_meta_file=", config_meta_file, config_meta) config_meta_file:write( config_meta ) config_meta_file:close() -- Concatenate config.metadata.lua into config.lu overwriting original config.lu CONFIG_DST = CORONA_TARGET_EXECUTABLE_DIR .. "/config.lu" CONFIG_SRC = CORONA_TARGET_EXECUTABLE_DIR .. "/config.orig.lu" if not fileExists( CONFIG_DST ) then touch( CONFIG_SRC ) else pl_file.move( CONFIG_DST, CONFIG_SRC ) end -- "$LUAC" -s -o "$CONFIG_DST" "$CONFIG_SRC" "$CONFIG_META" if PLATFORM == "win" then LUAC = 'cmd /Q/C "' .. escape( BIN_DIR .. "\\luac.exe" ) .. ' ' .. '-s -o' .. ' ' .. escape( CONFIG_DST ) .. ' ' .. escape( CONFIG_SRC ) .. ' ' .. escape( CONFIG_META ) .. '"' local result = os_execute(LUAC) checkError( 0 == result, "Failed to compile Lua files." ) else LUAC = BIN_DIR .. "/luac" local result = os_execute( escape(LUAC), '-s -o', escape( CONFIG_DST ), escape( CONFIG_SRC ), escape( CONFIG_META ) ) checkError( 0 == result, "Failed to compile Lua files." ) end pl_file.delete( CONFIG_SRC ) pl_file.delete( CONFIG_META ) -- Create resource.{car,corona-archive} from *.lu -- "$BUILDER_PATH" car "$CORONA_TARGET_EXECUTABLE_DIR/resource.corona-archive" "$CORONA_TARGET_EXECUTABLE_DIR"/*.lu print( 'Archiving ' .. CORONA_TARGET_EXECUTABLE_DIR ..'/*.lu into ' .. CORONA_TARGET_EXECUTABLE_DIR .. '/resource' .. RESOURCE_EXT ) if PLATFORM == "win" then local result = os_execute( 'cmd /Q/C "dir /s/b', escape( CORONA_TARGET_EXECUTABLE_DIR .. "\\*.lu"), '|', escape( BUILDER_PATH ), 'car', '-f -', -- read file list from stdin escape( CORONA_TARGET_EXECUTABLE_DIR .. "/resource" .. RESOURCE_EXT ), '"') checkError( 0 == result, "Failed to generate resource" .. RESOURCE_EXT ) else local result = os_execute( 'find -H', escape( CORONA_TARGET_EXECUTABLE_DIR ), '-maxdepth 1 -name "*.lu" -print', -- avoid cmd line length issues with "*.lu" '|', escape( BUILDER_PATH ), 'car', '-f -', -- read file list from stdin escape( CORONA_TARGET_EXECUTABLE_DIR .. "/resource" .. RESOURCE_EXT ) ) checkError( 0 == result, "Failed to generate resource" .. RESOURCE_EXT ) end -- rm -f "$CORONA_TARGET_EXECUTABLE_DIR"/*.lu if PLATFORM == "win" then print( 'Removing: ' .. CORONA_TARGET_EXECUTABLE_DIR .. '\\*.lu' ) local result = os_execute('del', CORONA_TARGET_EXECUTABLE_DIR .. "\\*.lu") else print( 'Removing: ' .. CORONA_TARGET_EXECUTABLE_DIR .. '/*.lu' ) local result = os_execute( 'find -H', escape( CORONA_TARGET_EXECUTABLE_DIR ), '-maxdepth 1 -name "*.lu" -exec rm -f {} \\;') end
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") if CLIENT then SWEP.DrawCrosshair = false SWEP.PrintName = "Winchester 1895" SWEP.CSMuzzleFlashes = true SWEP.ViewModelMovementScale = 1.15 SWEP.IconLetter = "i" SWEP.MuzzleEffect = "muzzleflash_SR25" SWEP.MuzzleAttachmentName = "muzzle" SWEP.PosBasedMuz = true SWEP.SnapToGrip = true SWEP.ShellScale = 0.7 SWEP.ShellOffsetMul = 2 SWEP.ShellPosOffset = {x = 5, y = -200, z = 0} SWEP.ForeGripOffsetCycle_Draw = 0 SWEP.ForeGripOffsetCycle_Reload = 0.9 SWEP.ForeGripOffsetCycle_Reload_Empty = 0.8 SWEP.ShellDelay = 0.8 SWEP.FireMoveMod = 0.6 SWEP.IronsightPos = Vector(-2.05, 0.839, 0.757) SWEP.IronsightAng = Vector(-0.094, -0.013, 0.28) SWEP.EoTechPos = Vector(-3.24, -12, 0.22) SWEP.EoTechAng = Vector(-0.15, 0.02, 0) SWEP.AimpointPos = Vector(-3.23, -12, 0.34) SWEP.AimpointAng = Vector(-0.15, 0.02, 0) SWEP.MicroT1Pos = Vector(-3.24, 0, 0.47) SWEP.MicroT1Ang = Vector(-0.15, 0.02, 0) SWEP.ReflexPos = Vector(-3.22, -12, 0.6) SWEP.ReflexAng = Vector(-0.15, 0.02, 0) SWEP.CmorePos = Vector(-3.21, -12, 0.5) SWEP.CmoreAng = Vector(-0.15, 0.02, 0) SWEP.ShortDotPos = Vector(-3.22, -17, 0.435) SWEP.ShortDotAng = Vector(-0.15, 0.02, 0) SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0.02, forward = 0} SWEP.NXSPos = Vector(-3.25, -14, 0.325) SWEP.NXSAng = Vector(-0.15, 0.02, 0) SWEP.NXSAlign = {right = 0, up = 0.02, forward = 0} SWEP.SprintPos = Vector(3.029, -0.805, -2.201) SWEP.SprintAng = Vector(-4.926, 38.693, -18.292) SWEP.CustomizePos = Vector(5.519, 0, -1.601) SWEP.CustomizeAng = Vector(21.106, 25.326, 10.553) SWEP.SightWithRail = true //SWEP.DisableSprintViewSimulation = true SWEP.AttachmentModelsVM = { } SWEP.LuaVMRecoilAxisMod = {vert = 0.5, hor = 1, roll = 1, forward = 0.5, pitch = 0.5} SWEP.LaserPosAdjust = Vector(0, 0, 0) SWEP.LaserAngAdjust = Angle(0, 179.5, 0) SWEP.WS_PistolLaserPosAdjust = Vector(0, 0, 0) SWEP.WS_PistolLaserAngAdjust = Angle(0, 0, 0) end SWEP.LuaViewmodelRecoil = false SWEP.Attachments = { ["+reload"] = {header = "Ammo", offset = {800, 150}, atts = {"am_hollowpoint", "am_armorpiercing"}} } SWEP.Animations = { fire = {"shoot"}, reload_start = "reload_start_empty", insert = "reload_insert", reload_end = "reload_end_empty", idle = "idle", //base_idle draw = "draw"} SWEP.Sounds = { reload_start_empty = {[1] = {time = 0.5, sound = "CW_W9422_BOLTBACK"}}, reload_insert = {[1] = {time = 0.4, sound = "CW_W9422_INSERT"}}, reload_end_empty = {[1] = {time = 0.3, sound = "CW_W9422_BOLTFORWORD"}}, shoot = { [1] = {time = 0.6, sound = "CW_W9422_BOLTBACK"}, [2] = {time = 0.8, sound = "CW_W9422_BOLTFORWORD"}}} SWEP.SpeedDec = 20 SWEP.ADSFireAnim = true SWEP.BipodFireAnim = true SWEP.UseHands = true SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.HoldType = "ar2" SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "crossbow" SWEP.FireModes = {"bolt"} SWEP.Base = "cw_base" SWEP.Category = "STALKER Weapons" SWEP.Author = "gumlefar & verne" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.WearDamage = 0.05 SWEP.WearEffect = 0.02 SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/weapons/c_rif_win1895.mdl" SWEP.WorldModel = "models/weapons/w_rif_win1895.mdl" SWEP.DrawTraditionalWorldModel = false SWEP.WM = "models/weapons/w_rif_win1895.mdl" SWEP.WMPos = Vector(-1, 10, 1.5) SWEP.WMAng = Vector(-9,1,180) SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 5 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "7.62x54MMR" SWEP.FireDelay = 1.45 SWEP.FireSound = "CW_W9422_FIRE" SWEP.FireSoundSuppressed = "CW_WS_MOSIN_SUB" SWEP.Recoil = 3.1 SWEP.AimViewModelFOV = 50 SWEP.CustomizationMenuScale = 0.018 SWEP.ForceBackToHipAfterAimedShot = true SWEP.GlobalDelayOnShoot = 1.1 SWEP.HipSpread = 0.15 SWEP.AimSpread = 0.005 SWEP.VelocitySensitivity = 5 SWEP.MaxSpreadInc = 0.4 SWEP.SpreadPerShot = 0.3 SWEP.SpreadCooldown = 0.4 SWEP.Shots = 1 SWEP.Damage = 158 SWEP.DeployTime = 1 /* SWEP.ReloadSpeed = 1 SWEP.ReloadTime = 2.4 SWEP.ReloadTime_Empty = 3.8 SWEP.ReloadHalt = 2.7 SWEP.ReloadHalt_Empty = 4.1 */ SWEP.ReloadStartTime = 0.6 SWEP.InsertShellTime = 1 SWEP.ReloadFinishWait = 1 SWEP.ShotgunReload = true SWEP.Chamberable = false
return { version = "1.1", luaversion = "5.1", tiledversion = "0.16.0", orientation = "orthogonal", renderorder = "right-down", width = 24, height = 24, tilewidth = 16, tileheight = 16, nextobjectid = 38, properties = {}, tilesets = { { name = "tileset", firstgid = 1, filename = "../../tileset.tsx", tilewidth = 16, tileheight = 16, spacing = 0, margin = 0, image = "../art/tileset.png", imagewidth = 320, imageheight = 320, tileoffset = { x = 0, y = 0 }, properties = {}, terrains = { { name = "Wall", tile = 0, properties = {} }, { name = "Markings", tile = 40, properties = {} }, { name = "Plain Wall", tile = 80, properties = {} } }, tilecount = 400, tiles = { { id = 0, terrain = { -1, -1, -1, 0 } }, { id = 1, terrain = { -1, -1, 0, -1 } }, { id = 2, terrain = { -1, 0, 0, 0 } }, { id = 3, terrain = { 0, -1, 0, 0 } }, { id = 4, terrain = { -1, -1, 0, 0 } }, { id = 5, terrain = { 0, -1, 0, -1 } }, { id = 7, terrain = { 0, 0, 0, 0 } }, { id = 20, terrain = { -1, 0, -1, -1 } }, { id = 21, terrain = { 0, -1, -1, -1 } }, { id = 22, terrain = { 0, 0, -1, 0 } }, { id = 23, terrain = { 0, 0, 0, -1 } }, { id = 24, terrain = { -1, 0, -1, 0 } }, { id = 25, terrain = { 0, 0, -1, -1 } }, { id = 40, terrain = { 2, 2, 2, 1 } }, { id = 41, terrain = { 2, 2, 1, 2 } }, { id = 42, terrain = { 2, 2, 1, 1 } }, { id = 43, terrain = { 1, 2, 1, 2 } }, { id = 44, terrain = { 2, 1, 1, 1 } }, { id = 45, terrain = { 1, 2, 1, 1 } }, { id = 60, terrain = { 2, 1, 2, 2 } }, { id = 61, terrain = { 1, 2, 2, 2 } }, { id = 62, terrain = { 2, 1, 2, 1 } }, { id = 63, terrain = { 1, 1, 2, 2 } }, { id = 64, terrain = { 1, 1, 2, 1 } }, { id = 65, terrain = { 1, 1, 1, 2 } }, { id = 80, terrain = { 2, 2, 2, 2 } }, { id = 81, terrain = { 1, 1, 1, 1 } }, { id = 100, terrain = { 2, 2, 2, 2 } }, { id = 101, terrain = { 2, 2, 2, 2 } }, { id = 120, terrain = { 2, 2, 2, 2 } }, { id = 121, terrain = { 2, 2, 2, 2 } } } } }, layers = { { type = "tilelayer", name = "background", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, encoding = "lua", data = { 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 80, 80, 80, 80, 80, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 80, 80, 80, 80, 80, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 240, 80, 80, 80, 80, 80, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 81, 260, 260, 260, 260, 80, 80, 80, 80, 23, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 300, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 320, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 81, 81, 81, 81, 81, 81, 81, 81, 297, 320, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 298, 298, 298, 298, 298, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 298, 298, 298, 298, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 298, 298, 298, 298, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 298, 298, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 298, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 298, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 298, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 81, 81, 81, 81, 41, 43, 43, 43, 43, 43, 43, 42, 81, 81, 81, 81, 41, 43, 43, 43, 43, 42, 81, 80, 81, 81, 81, 81, 63, 82, 82, 82, 82, 82, 82, 44, 81, 81, 81, 81, 63, 82, 82, 82, 82, 44, 81, 80, 81, 81, 81, 81, 63, 82, 82, 82, 82, 82, 82, 44, 81, 81, 81, 81, 63, 82, 82, 82, 82, 44, 81, 80, 81, 81, 81, 81, 63, 85, 82, 84, 82, 83, 82, 44, 81, 81, 81, 81, 63, 83, 82, 84, 82, 44, 81, 80, 81, 81, 81, 81, 63, 82, 82, 82, 82, 82, 82, 44, 81, 81, 81, 81, 63, 82, 82, 82, 82, 44, 81, 81, 81, 81, 81, 81, 61, 64, 64, 64, 64, 64, 64, 62, 81, 81, 81, 81, 61, 64, 64, 64, 64, 62, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 80, 81, 81, 80, 80 } }, { type = "tilelayer", name = "decor", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 0, 0, 70, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 91, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 0, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 71, 0, 0, 0, 0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 91, 0, 0, 0, 0, 0, 0, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { type = "tilelayer", name = "platforms", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 47, 47, 47, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { type = "tilelayer", name = "walls", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, encoding = "lua", data = { 0, 27, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 3, 8, 8, 8, 8, 8, 8, 8, 8, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 8, 8, 8, 8, 8, 8, 8, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 26, 26, 26, 26, 26, 26, 26, 26, 23, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 297, 297, 297, 297, 297, 297, 298, 297, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 27, 3, 8, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 27, 3, 8, 8, 8, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 27, 3, 8, 8, 8, 8, 8, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 27, 3, 8, 8, 8, 8, 8, 8, 8, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 0, 27, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 27, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 5, 2, 0, 0, 0, 0, 1, 5, 3, 27, 3, 24, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 23, 24, 26, 22, 0, 0, 0, 0, 21, 26, 23, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 6, 0, 0, 0, 0, 0, 0, 0, 0, 25, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 22, 0, 0, 0, 0, 0, 0, 0, 0, 21, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 } }, { type = "tilelayer", name = "overlay", x = 0, y = 0, width = 24, height = 24, visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 277, 278, 279, 277, 278, 279, 277, 278, 0, 0, 0, 209, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { type = "objectgroup", name = "objects", visible = true, opacity = 1, offsetx = 0, offsety = 0, properties = {}, objects = { { id = 11, name = "initial_spawn", type = "spawn", shape = "rectangle", x = 128, y = 80, width = 16, height = 32, rotation = 0, visible = true, properties = {} }, { id = 16, name = "into_pyramid", type = "exit", shape = "rectangle", x = 368, y = 320, width = 32, height = 48, rotation = 0, visible = true, properties = { ["target"] = "shaft.from_entrance" } }, { id = 22, name = "tutorial", type = "trigger", shape = "rectangle", x = 230, y = 55, width = 146, height = 171, rotation = 0, visible = true, properties = { ["data"] = "drop" } }, { id = 25, name = "lore", type = "trigger", shape = "rectangle", x = 64, y = 256, width = 128, height = 112, rotation = 0, visible = true, properties = { ["data"] = "entry_hiero", ["on_contains"] = true } }, { id = 33, name = "tutorial", type = "trigger", shape = "rectangle", x = 40, y = 34.5, width = 189.5, height = 84, rotation = 0, visible = true, properties = { ["data"] = "movement" } }, { id = 35, name = "", type = "crate", shape = "rectangle", x = 344, y = 352, width = 16, height = 16, rotation = 0, visible = true, properties = {} }, { id = 37, name = "tutorial", type = "trigger", shape = "rectangle", x = 306.667, y = 288, width = 85.5, height = 84, rotation = 0, visible = true, properties = { ["data"] = "jump" } } } } } }
require "vstudio" local android = premake.extensions.android local vstudio = premake.vstudio local vs2010 = vstudio.vs2010 -- -- Fix file extensions for packaging projects when generating project files -- premake.override(vs2010, "generateProject", function(base, prj) if prj.system == android._ANDROID and android.isPackaging(prj.kind) then premake.eol("\r\n") premake.indent(" ") premake.escaper(vs2010.esc) local prjModified = premake.generate(prj, android._ANDROIDPROJ, android.androidproj.generate) -- Skip generation of empty user files local user = premake.capture(function() vstudio.vc2010.generateUser(prj) end) if #user > 0 then premake.generate(prj, android._ANDROIDPROJ .. ".user", function() premake.outln(user) end) end -- Only generate a filters file if the source tree actually has subfolders if premake.tree.hasbranches(premake.project.getsourcetree(prj)) then if premake.generate(prj, android._ANDROIDPROJ .. ".filters", vstudio.vc2010.generateFilters) == true and prjModified == false then -- vs workaround for issue where if only the .filters file is modified, VS doesn't automatically trigger a reload premake.touch(prj, android._ANDROIDPROJ) end end else base(prj) end end) -- -- Fix VS tool for packaging projects -- premake.override(vstudio, "tool", function(base, prj) if prj.system == android._ANDROID and android.isPackaging(prj.kind) then return "39E2626F-3545-4960-A6E8-258AD8476CE5" else return base(prj) end end) -- -- Fix file extensions for packaging projects when generating file paths -- premake.override(vstudio, "projectfile", function(base, prj) if prj.system == android._ANDROID and android.isPackaging(prj.kind) then return premake.filename(prj, android._ANDROIDPROJ) else return base(prj) end end) -- -- Project platform -- premake.override(vstudio, "projectPlatform", function(base, cfg) if cfg.system == android._ANDROID then return cfg.buildcfg else return base(cfg, win32) end end) -- -- Arch from config -- premake.override(vstudio, "archFromConfig", function(base, cfg, win32) if cfg.system == android._ANDROID then return cfg.architecture else return base(cfg, win32) end end)
local API = {}; ImmersionAPI = API; -- Version local IS_VANILLA = WOW_PROJECT_ID == WOW_PROJECT_CLASSIC or nil; local IS_RETAIL = WOW_PROJECT_ID == WOW_PROJECT_MAINLINE or nil; local IS_CLASSIC = WOW_PROJECT_ID == WOW_PROJECT_BURNING_CRUSADE_CLASSIC or nil; function API:IsVanilla() return IS_VANILLA end function API:IsRetail() return IS_RETAIL end function API:IsClassic() return IS_CLASSIC end function API:IsClassicOrVanilla() return IS_CLASSIC or IS_VANILLA end API.ITERATORS = { GOSSIP = (IS_VANILLA or IS_CLASSIC) and 2 or IS_RETAIL and 2; ACTIVE = (IS_VANILLA or IS_CLASSIC) and 6 or IS_RETAIL and 7; AVAILABLE = (IS_VANILLA or IS_CLASSIC) and 7 or IS_RETAIL and 8; } -- Chunk iterators function API:GetGossipOptionIterator(...) return self.ITERATORS.GOSSIP end function API:GetActiveQuestIterator(...) return self.ITERATORS.ACTIVE end function API:GetAvailableQuestIterator(...) return self.ITERATORS.AVAILABLE end -- Map select to table values local function map(lambda, step, ...) local data = {} for i = 1, select('#', ...), step do data[#data + 1] = lambda(nil, i, ...) end return data end function API:MapGossipAvailableQuests(i, ...) --local titleText, level, isTrivial, frequency, isRepeatable, isLegendary, isIgnored = select(i, ...); local title, level, trivial, frequency, repeatable, legendary, id = select(i, ...) return { title = title, questLevel = level, isTrivial = trivial, frequency = frequency, repeatable = repeatable, isLegendary = legendary, questID = id, } end function API:MapGossipActiveQuests(i, ...) local title, level, trivial, complete, legendary, id = select(i, ...) return { title = title, questLevel = level, isTrivial = trivial, isComplete = complete, isLegendary = legendary, questID = id, } end function API:MapGossipOptions(i, ...) local name, icon = select(i, ...) return { name = name, type = icon, } end -- Quest pickup API function API:CloseQuest(...) return CloseQuest and CloseQuest(...) end function API:GetGreetingText(...) return GetGreetingText and GetGreetingText(...) end function API:GetTitleText(...) return GetTitleText and GetTitleText(...) end function API:GetProgressText(...) return GetProgressText and GetProgressText(...) end function API:GetRewardText(...) return GetRewardText and GetRewardText(...) end function API:GetQuestText(...) return GetQuestText and GetQuestText(...) end function API:QuestGetAutoAccept(...) return QuestGetAutoAccept and QuestGetAutoAccept(...) end function API:QuestIsFromAdventureMap(...) return QuestIsFromAdventureMap and QuestIsFromAdventureMap(...) end function API:QuestIsFromAreaTrigger(...) return QuestIsFromAreaTrigger and QuestIsFromAreaTrigger(...) end function API:QuestFlagsPVP(...) return QuestFlagsPVP and QuestFlagsPVP(...) end function API:GetQuestIconOffer(quest) if QuestUtil and QuestUtil.GetQuestIconOffer then return QuestUtil.GetQuestIconOffer( quest.isLegendary, quest.frequency, quest.repeatable, QuestUtil.ShouldQuestIconsUseCampaignAppearance(quest.questID) ) end local icon = ( quest.isLegendary and 'AvailableLegendaryQuestIcon') or ( quest.frequency and quest.frequency > 1 and 'DailyQuestIcon') or ( quest.repeatable and 'DailyActiveQuestIcon') or ( 'AvailableQuestIcon' ) return ([[Interface\GossipFrame\%s]]):format(icon) end function API:GetQuestIconActive(quest) if QuestUtil and QuestUtil.GetQuestIconActive then return QuestUtil.GetQuestIconActive( quest.isComplete, quest.isLegendary, quest.frequency, quest.repeatable, QuestUtil.ShouldQuestIconsUseCampaignAppearance(quest.questID) ) end local icon = ( quest.isComplete ) and ( ( quest.isLegendary and 'ActiveLegendaryQuestIcon') or ( quest.isComplete and 'ActiveQuestIcon') ) or ( 'InCompleteQuestIcon' ) return ([[Interface\GossipFrame\%s]]):format(icon) end -- Quest content API function API:GetSuggestedGroupNum(...) return GetSuggestedGroupNum and GetSuggestedGroupNum(...) or 0 end function API:GetNumQuestRewards(...) return GetNumQuestRewards and GetNumQuestRewards(...) or 0 end function API:GetNumQuestChoices(...) return GetNumQuestChoices and GetNumQuestChoices(...) or 0 end function API:GetNumRewardCurrencies(...) return GetNumRewardCurrencies and GetNumRewardCurrencies(...) or 0 end function API:GetRewardMoney(...) return GetRewardMoney and GetRewardMoney(...) or 0 end function API:GetRewardSkillPoints(...) return GetRewardSkillPoints and GetRewardSkillPoints(...) or 0 end function API:GetRewardXP(...) return GetRewardXP and GetRewardXP(...) or 0 end function API:GetRewardArtifactXP(...) return GetRewardArtifactXP and GetRewardArtifactXP(...) or 0 end function API:GetRewardHonor(...) return GetRewardHonor and GetRewardHonor(...) or 0 end function API:GetRewardTitle(...) return GetRewardTitle and GetRewardTitle(...) end function API:GetNumRewardSpells(...) return GetNumRewardSpells and GetNumRewardSpells(...) or 0 end function API:GetMaxRewardCurrencies(...) return GetMaxRewardCurrencies and GetMaxRewardCurrencies(...) or 0 end function API:GetNumQuestItems(...) return GetNumQuestItems and GetNumQuestItems(...) or 0 end function API:GetQuestMoneyToGet(...) return GetQuestMoneyToGet and GetQuestMoneyToGet(...) or 0 end function API:GetNumQuestCurrencies(...) return GetNumQuestCurrencies and GetNumQuestCurrencies(...) or 0 end function API:GetSuperTrackedQuestID(...) return C_SuperTrack and C_SuperTrack.GetSuperTrackedQuestID(...) end function API:GetAvailableQuestInfo(...) if GetAvailableQuestInfo then return GetAvailableQuestInfo(...) end return IsAvailableQuestTrivial(...) end function API:IsActiveQuestLegendary(...) return IsActiveQuestLegendary and IsActiveQuestLegendary(...) end function API:IsQuestCompletable(...) return IsQuestCompletable and IsQuestCompletable(...) end -- Gossip API function API:CloseGossip(...) if CloseGossip then return CloseGossip(...) end return C_GossipInfo.CloseGossip(...) end function API:ForceGossip(...) if ForceGossip then return ForceGossip(...) end return C_GossipInfo.ForceGossip(...) end function API:CanAutoSelectGossip(dontAutoSelect) local gossip = self:GetGossipOptions() if ( #gossip > 0 and gossip[1].type:lower() ~= 'gossip') then if not dontAutoSelect then self:SelectGossipOption(1) end return true end end function API:GetGossipText(...) if GetGossipText then return GetGossipText(...) end return C_GossipInfo.GetText() end function API:GetNumGossipAvailableQuests(...) if GetNumGossipAvailableQuests then return GetNumGossipAvailableQuests(...) end return C_GossipInfo.GetNumAvailableQuests(...) end function API:GetNumGossipActiveQuests(...) if GetNumGossipActiveQuests then return GetNumGossipActiveQuests(...) end return C_GossipInfo.GetNumActiveQuests(...) end function API:GetNumGossipOptions(...) if GetNumGossipOptions then return GetNumGossipOptions(...) end return C_GossipInfo.GetNumOptions(...) end function API:GetGossipAvailableQuests(...) if GetGossipAvailableQuests then return map( API.MapGossipAvailableQuests, API:GetAvailableQuestIterator(), GetGossipAvailableQuests(...) ) end return C_GossipInfo.GetAvailableQuests(...) end function API:GetGossipActiveQuests(...) if GetGossipActiveQuests then return map( API.MapGossipActiveQuests, API:GetActiveQuestIterator(), GetGossipActiveQuests(...) ) end return C_GossipInfo.GetActiveQuests(...) end function API:GetGossipOptions(...) if GetGossipOptions then return map( API.MapGossipOptions, API:GetGossipOptionIterator(), GetGossipOptions(...) ) end return C_GossipInfo.GetOptions(...) end -- Gossip/quest selectors API function API:SelectActiveQuest(...) if SelectActiveQuest then return SelectActiveQuest(...) end end function API:SelectAvailableQuest(...) if SelectAvailableQuest then return SelectAvailableQuest(...) end end function API:SelectGossipOption(...) if SelectGossipOption then return SelectGossipOption(...) end return C_GossipInfo.SelectOption(...) end function API:SelectGossipActiveQuest(...) if SelectGossipActiveQuest then return SelectGossipActiveQuest(...) end return C_GossipInfo.SelectActiveQuest(...) end function API:SelectGossipAvailableQuest(...) if SelectGossipAvailableQuest then return SelectGossipAvailableQuest(...) end return C_GossipInfo.SelectAvailableQuest(...) end -- Misc function API:GetUnitName(...) return GetUnitName and GetUnitName(...) end function API:GetFriendshipReputation(...) if GetFriendshipReputation then return GetFriendshipReputation(...) end return 0 end function API:GetPortraitAtlas() if GetAtlasInfo and GetAtlasInfo('TalkingHeads-PortraitFrame') then return 'TalkingHeads-PortraitFrame'; end return 'TalkingHeads-Alliance-PortraitFrame'; end function API:IsAzeriteItem(...) if C_AzeriteEmpoweredItem then return C_AzeriteEmpoweredItem.IsAzeriteEmpoweredItemByID(...) and C_AzeriteEmpoweredItem.IsAzeritePreviewSourceDisplayable(...) end end function API:IsCharacterNewlyBoosted(...) return IsCharacterNewlyBoosted and IsCharacterNewlyBoosted(...) end function API:IsFollowerCollected(...) return C_Garrison and C_Garrison.IsFollowerCollected(...) end function API:GetNamePlateForUnit(...) return C_NamePlate and C_NamePlate.GetNamePlateForUnit(...) end function API:GetCreatureID(unit) local guid = unit and UnitGUID(unit) return guid and select(6, strsplit('-', guid)) end function API:CloseItemText(...) if CloseItemText then return CloseItemText(...) end end function API:GetQuestDetailsTheme(...) if C_QuestLog and C_QuestLog.GetQuestDetailsTheme then return C_QuestLog.GetQuestDetailsTheme(...) end end function API:GetQuestItemInfoLootType(...) if GetQuestItemInfoLootType then return GetQuestItemInfoLootType(...) end end
return { sound = { move = love.audio.newSource( "assets/wav/move3.wav", "static" ), move_water = love.audio.newSource( "assets/wav/move_water.wav", "static" ), serpent_move = love.audio.newSource( "assets/wav/move1.wav", "static" ), serpent_growl = love.audio.newSource( "assets/wav/serpent_growl.wav", "static" ), frog_jump = love.audio.newSource( "assets/wav/frog_jump.wav", "static" ), deer_jump = love.audio.newSource( "assets/wav/deer_jump.wav", "static" ), oh = love.audio.newSource( "assets/wav/oh.wav", "static" ), }, play = function( sound, volume ) sound:setVolume( volume and volume or 1 ) sound:play() end, play_positional = function( sound, volume, game_state, pos ) local dist_sq = game_state.player.camera_pos:distance_squared(pos) local max_dist = 20 if dist_sq < max_dist then local gain = ( volume and volume or 1 ) * ( 1 - dist_sq / max_dist ); sound:setVolume( gain ) sound:play() end end, }
----------------------------------------------------------------------------------------------- -- Client Lua Script for HousingDecorSetManager -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- require "Window" require "HousingLib" ----------------------------------------------------------------------------------------------- -- HousingDecorSetManager Module Definition ----------------------------------------------------------------------------------------------- local HousingDecorSetManager = {} ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- local knSaveVersion = 1 local knTimerDelay = 0.1 local knTimerDelayShort = 0.05 local knDecorListItemsPerLoad = 10 local ktInteriorZones = {412, 434, 435, 436, 437, 438, 439, 440, 441} local knMaxTextLength = 30720 ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function HousingDecorSetManager:new(o) o = o or {} setmetatable(o, self) self.__index = self -- initialize variables here o.tSavedData = { nSaveVersion = knSaveVersion, tDecorSets = {}, } return o end function HousingDecorSetManager:Init() Apollo.RegisterAddon(self) end function HousingDecorSetManager:OnSave(eType) if eType ~= GameLib.CodeEnumAddonSaveLevel.Account then return end return self.tSavedData end function HousingDecorSetManager:OnRestore(eType, tSavedData) if tSavedData and tSavedData.nSaveVersion == knSaveVersion then self.tSavedData = tSavedData end end ----------------------------------------------------------------------------------------------- -- HousingDecorSetManager OnLoad ----------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnLoad() -- load our form file self.xmlDoc = XmlDoc.CreateFromFile("HousingDecorSetManager.xml") self.xmlDoc:RegisterCallback("OnDocLoaded", self) end ----------------------------------------------------------------------------------------------- -- HousingDecorSetManager OnDocLoaded ----------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnDocLoaded() if self.xmlDoc ~= nil and self.xmlDoc:IsLoaded() then self.wndMain = Apollo.LoadForm(self.xmlDoc, "HousingDecorSetManagerForm", nil, self) if self.wndMain == nil then Apollo.AddAddonErrorText(self, "Could not load the main window for some reason.") return end self.wndNewSet = Apollo.LoadForm(self.xmlDoc, "CreateDecorSetForm", nil, self) self.wndCopySet = Apollo.LoadForm(self.xmlDoc, "CopySetForm", nil, self) self.wndLoadSet = Apollo.LoadForm(self.xmlDoc, "LoadSetForm", nil, self) self.wndPlaceAll = Apollo.LoadForm(self.xmlDoc, "PlaceAllForm", nil, self) self.wndPlugWarningPopup = Apollo.LoadForm(self.xmlDoc, "PopupPlugMismatchWarning", nil, self) self.wndAddDecorPopup = Apollo.LoadForm(self.xmlDoc, "PopupAddGroup", nil, self) self.wndMain:Show(false, true) self.wndNewSet:Show(false, true) self.wndCopySet:Show(false, true) self.wndLoadSet:Show(false, true) self.wndPlaceAll:Show(false, true) self.wndPlugWarningPopup:Show(false, true) self.wndAddDecorPopup:Show(false, true) -- if the xmlDoc is no longer needed, you should set it to nil self.xmlDoc = nil -- Register handlers for events, slash commands and timer, etc. Apollo.RegisterEventHandler("HousingPanelControlOpen", "OnPropertyEnter", self) Apollo.RegisterEventHandler("HousingPanelControlClose", "OnPropertyExit", self) Apollo.RegisterEventHandler("PlayerCurrencyChanged", "OnPlayerCurrencyChanged", self) Apollo.RegisterSlashCommand("DecorSetMgr", "OnHousingDecorSetManagerOn", self) Apollo.RegisterSlashCommand("dsm", "OnHousingDecorSetManagerOn", self) self.wndDecorSetListFrame = self.wndMain:FindChild("DecorSetListFrame") self.wndDecorListFrame = self.wndMain:FindChild("DecorListFrame") self.wndOptionsFrame = self.wndMain:FindChild("OptionsFrame") self.wndOptionsMinimizeBtn = self.wndOptionsFrame:FindChild("OptionsMinimizeBtn") self.wndOptionsPropertyFrame = self.wndOptionsFrame:FindChild("LandscapeOptionsFrame") self.wndOptionsCustomizationFrame = self.wndOptionsFrame:FindChild("CustomizationOptionsFrame") self.wndInteriorOptionsFrame = self.wndOptionsCustomizationFrame:FindChild("InteriorCustomizationOptionsFrame") self.wndExteriorOptionsFrame = self.wndOptionsCustomizationFrame:FindChild("ExteriorCustomizationOptionsFrame") self.wndOptionsTooltip = self.wndMain:FindChild("LandscapeRemodelTooltip") self.wndCashCredit = self.wndMain:FindChild("CashWindowCredit") self.wndCashCredit:SetMoneySystem(Money.CodeEnumCurrencyType.Credits) self.wndCashCredit:SetAmount(GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Credits), true) self.wndCashRenown = self.wndMain:FindChild("CashWindowRenown") self.wndCashRenown:SetMoneySystem(Money.CodeEnumCurrencyType.Renown) self.wndCashRenown:SetAmount(GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Renown), true) self.wndShareSetBtn = self.wndMain:FindChild("ShareSetBtn") self.wndShareSetBtn:Enable(false) self.wndDeleteSetBtn = self.wndMain:FindChild("DeleteSetBtn") self.wndDeleteSetBtn:Enable(false) self.wndDecorListFrame = self.wndMain:FindChild("DecorListFrame") self.wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self.wndDecorLoadingText = self.wndDecorListFrame:FindChild("LoadingText") self.wndDecorListBlocker = self.wndDecorListFrame:FindChild("WindowBlocker") self.wndOptionsMinimizeBtn:SetCheck(true) Apollo.RegisterTimerHandler("DecorListLoadTimer", "OnLoadNextDecorListItems", self) Apollo.RegisterTimerHandler("DecorPlacementTimer", "OnUpdatePlaceDecor", self) Apollo.RegisterTimerHandler("PlaceAllUpdateTimer", "OnUpdatePlaceAllDecor", self) Apollo.RegisterTimerHandler("PlaceAllUpdateTimerShort", "OnUpdatePlaceAllDecor", self) Apollo.CreateTimer("DecorListLoadTimer", knTimerDelayShort, false) Apollo.CreateTimer("DecorPlacementTimer", knTimerDelay, false) Apollo.CreateTimer("PlaceAllUpdateTimer", knTimerDelay, false) Apollo.CreateTimer("PlaceAllUpdateTimerShort", knTimerDelayShort, false) Apollo.StopTimer("DecorListLoadTimer") Apollo.StopTimer("DecorPlacementTimer") Apollo.StopTimer("PlaceAllUpdateTimer") Apollo.StopTimer("PlaceAllUpdateTimerShort") end end ----------------------------------------------------------------------------------------------- -- HousingDecorSetManager Functions ----------------------------------------------------------------------------------------------- -- Define general functions here -- on SlashCommand "/DecorSetMgr" function HousingDecorSetManager:OnHousingDecorSetManagerOn() self.wndMain:Invoke() -- show the window HousingLib.SetEditMode(true) local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") self:ShowDecorSetListItems(wndSetList, self.tSavedData.tDecorSets) local wndList = self.wndDecorListFrame:FindChild("DecorList") wndList:DeleteAll() self.wndMain:FindChild("HousingDecorSetForm"):FindChild("BG_ArtHeader"):SetText("") local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do self.wndOptionsPropertyFrame:FindChild("Plot"..idx):Enable(false) self.wndOptionsPropertyFrame:FindChild("OccupiedSprite."..idx):Show(false) self.wndOptionsPropertyFrame:FindChild("WarningSprite."..idx):Show(false) end self:OnPlayerCurrencyChanged() HousingLib:RefreshUI() end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnPropertyEnter(idPropertyInfo, idZone, bPlayerIsInside) if HousingLib.IsHousingWorld() then self.bOnProperty = true self.bPlayerIsInside = bPlayerIsInside == true --make sure we get true/false self.nIdZone = idZone local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndList:GetCellData( nRow, 1 ) self:ShowLandscapeOptions(tDecorSetData.plots) self:ShowRemodelOptions(tDecorSetData.intOptions, tDecorSetData.extOptions) local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) else self:ShowRemodelOptions(nil, nil) end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnPropertyExit() self.bOnProperty = false -- you've left your property! self:OnCloseHousingDecorSetManagerWindow() end function HousingDecorSetManager:OnPlayerCurrencyChanged() if not self.wndMain or not self.wndMain:IsShown() then return end self.wndCashCredit:SetAmount(GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Credits), true) self.wndCashRenown:SetAmount(GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Renown), true) end ----------------------------------------------------------------------------------------------- -- HousingDecorSetManagerForm Functions ----------------------------------------------------------------------------------------------- -- when the OK button is clicked function HousingDecorSetManager:OnOK() self.wndMain:Close() -- hide the window end -- when the Cancel button is clicked function HousingDecorSetManager:OnCancel() self.wndMain:Close() -- hide the window end function HousingDecorSetManager:OnCloseHousingDecorSetManagerWindow() self.wndDecorSetListFrame:FindChild("DecorSetList"):SetCurrentRow(0) self.wndDecorListFrame:FindChild("DecorList"):SetCurrentRow(0) if self.decorSelection ~= nil then self.decorSelection:CancelTransform() self.decorSelection = nil end self.wndNewSet:Show(false, true) self.wndCopySet:Show(false, true) self.wndLoadSet:Show(false, true) self.wndPlaceAll:Show(false, true) self.wndPlugWarningPopup:Show(false, true) self.wndAddDecorPopup:Show(false, true) Apollo.StopTimer("DecorPlacementTimer") self.wndMain:Close() -- hide the window end function HousingDecorSetManager:OnRestoreOptions( wndHandler, wndControl, eMouseButton ) local nLeft, nTop, nRight, nBottom = self.wndOptionsFrame:GetAnchorOffsets() self.wndOptionsFrame:SetAnchorOffsets(nLeft, nTop, nRight, nTop + 238) --This is a little hack to make it update the size of the DecorListFrame correctly local nLeft, nTop, nRight, nBottom = self.wndMain:GetAnchorOffsets() self.wndMain:SetAnchorOffsets(nLeft, nTop, nRight, nBottom) end function HousingDecorSetManager:OnMinimizeOptions( wndHandler, wndControl, eMouseButton ) local nLeft, nTop, nRight, nBottom = self.wndOptionsFrame:GetAnchorOffsets() self.wndOptionsFrame:SetAnchorOffsets(nLeft, nTop, nRight, nTop + 37) --This is a little hack to make it update the size of the DecorListFrame correctly local nLeft, nTop, nRight, nBottom = self.wndMain:GetAnchorOffsets() self.wndMain:SetAnchorOffsets(nLeft, nTop, nRight, nBottom) end function HousingDecorSetManager:OnOpenCreateNewSetWindow(wndHandler, wndControl) self.wndNewSet:Show(true, true) self.wndNewSet:ToFront() local wndSettingsFrame = self.wndNewSet:FindChild("SettingsFrame") wndSettingsFrame:SetRadioSel("IncludeDecorRadioGroup", 1) end function HousingDecorSetManager:OnPlaceBtn(wndHandler, wndControl) local wndList = self.wndDecorListFrame:FindChild("DecorList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorData = wndList:GetCellData( nRow, 1 ) if self:IsDecorAvailable(tDecorData) then self:PlaceDecor(tDecorData) end end end function HousingDecorSetManager:OnRemoveFromSetBtn(wndHandler, wndControl) local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndSetList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndSetList:GetCellData( nRow, 1 ) local wndList = self.wndDecorListFrame:FindChild("DecorList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorData = wndList:GetCellData( nRow, 1 ) for idx = 1, #tDecorSetData.decor do if tDecorSetData.decor[idx].name == tDecorData.name then table.remove(tDecorSetData.decor, idx) break end end end local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end end function HousingDecorSetManager:OnAddToSetBtn(wndHandler, wndControl) local decorSelection = HousingLib.GetResidence():GetSelectedDecor() if decorSelection ~= nil then if decorSelection:IsParent() then self.wndAddDecorPopup:Show(true) self.wndAddDecorPopup:ToFront() return else local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndSetList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndSetList:GetCellData( nRow, 1 ) local tNewDecorEntry = {} local tDecorIconInfo = decorSelection:GetDecorIconInfo() if tDecorIconInfo ~= nil then local tNewDecorEntry = {} tNewDecorEntry.name = decorSelection:GetName() tNewDecorEntry.index = nDecorCount tNewDecorEntry.decorIdLow, tNewDecorEntry.decorIdHi = decorSelection:GetId() tNewDecorEntry.positionX = tDecorIconInfo.fWorldPosX tNewDecorEntry.positionY = tDecorIconInfo.fWorldPosY tNewDecorEntry.positionZ = tDecorIconInfo.fWorldPosZ tNewDecorEntry.pitch = tDecorIconInfo.fPitch tNewDecorEntry.roll = tDecorIconInfo.fRoll tNewDecorEntry.yaw = tDecorIconInfo.fYaw tNewDecorEntry.scale = tDecorIconInfo.fScaleCurrent table.insert(tDecorSetData.decor, tNewDecorEntry) end local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end end end end function HousingDecorSetManager:OnAddDecorCancel(wndHandler, wndControl) self.wndAddDecorPopup:Show(false) end function HousingDecorSetManager:OnAddGroup(wndHandler, wndControl) local decorSelection = HousingLib.GetResidence():GetSelectedDecor() if decorSelection ~= nil then local tdecorChildren = decorSelection:GetChildren() local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndSetList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndSetList:GetCellData( nRow, 1 ) -- Add the parent local tNewDecorEntry = {} local nParentIndex = 0 local tDecorIconInfo = decorSelection:GetDecorIconInfo() if tDecorIconInfo ~= nil then local tNewDecorEntry = {} tNewDecorEntry.name = decorSelection:GetName() tNewDecorEntry.index = nDecorCount tNewDecorEntry.decorIdLow, tNewDecorEntry.decorIdHi = decorSelection:GetId() tNewDecorEntry.positionX = tDecorIconInfo.fWorldPosX tNewDecorEntry.positionY = tDecorIconInfo.fWorldPosY tNewDecorEntry.positionZ = tDecorIconInfo.fWorldPosZ tNewDecorEntry.pitch = tDecorIconInfo.fPitch tNewDecorEntry.roll = tDecorIconInfo.fRoll tNewDecorEntry.yaw = tDecorIconInfo.fYaw tNewDecorEntry.scale = tDecorIconInfo.fScaleCurrent table.insert(tDecorSetData.decor, tNewDecorEntry) nParentIndex = #tDecorSetData.decor end -- Add all the children for idx = 1, #tdecorChildren do local tNewDecorEntry = {} local tDecorIconInfo = tdecorChildren[idx]:GetDecorIconInfo() if tDecorIconInfo ~= nil then local tNewDecorEntry = {} tNewDecorEntry.name = tdecorChildren[idx]:GetName() tNewDecorEntry.index = nDecorCount tNewDecorEntry.decorIdLow, tNewDecorEntry.decorIdHi = tdecorChildren[idx]:GetId() tNewDecorEntry.positionX = tDecorIconInfo.fWorldPosX tNewDecorEntry.positionY = tDecorIconInfo.fWorldPosY tNewDecorEntry.positionZ = tDecorIconInfo.fWorldPosZ tNewDecorEntry.pitch = tDecorIconInfo.fPitch tNewDecorEntry.roll = tDecorIconInfo.fRoll tNewDecorEntry.yaw = tDecorIconInfo.fYaw tNewDecorEntry.scale = tDecorIconInfo.fScaleCurrent tNewDecorEntry.parent = nParentIndex table.insert(tDecorSetData.decor, tNewDecorEntry) end end local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end end end function HousingDecorSetManager:OnAddSingle(wndHandler, wndControl) local decorSelection = HousingLib.GetResidence():GetSelectedDecor() if decorSelection ~= nil then local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndSetList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndSetList:GetCellData( nRow, 1 ) local tNewDecorEntry = {} local tDecorIconInfo = decorSelection:GetDecorIconInfo() if tDecorIconInfo ~= nil then local tNewDecorEntry = {} tNewDecorEntry.name = decorSelection:GetName() tNewDecorEntry.index = nDecorCount tNewDecorEntry.decorIdLow, tNewDecorEntry.decorIdHi = decorSelection:GetId() tNewDecorEntry.positionX = tDecorIconInfo.fWorldPosX tNewDecorEntry.positionY = tDecorIconInfo.fWorldPosY tNewDecorEntry.positionZ = tDecorIconInfo.fWorldPosZ tNewDecorEntry.pitch = tDecorIconInfo.fPitch tNewDecorEntry.roll = tDecorIconInfo.fRoll tNewDecorEntry.yaw = tDecorIconInfo.fYaw tNewDecorEntry.scale = tDecorIconInfo.fScaleCurrent table.insert(tDecorSetData.decor, tNewDecorEntry) end local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end end end function HousingDecorSetManager:OnPlaceAllBtn(wndHandler, wndControl) local wndList = self.wndDecorListFrame:FindChild("DecorList") local monPlayerCash = GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Credits):GetAmount() local monPlayerRenown = GameLib.GetPlayerCurrency(Money.CodeEnumCurrencyType.Renown):GetAmount() local monTotalCash = 0 local monTotalRenown = 0 if not self.confirmedPlaceAll then local residence = HousingLib.GetResidence() if residence == nil then return end local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndSetList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndSetList:GetCellData( nRow, 1 ) if tDecorSetData.plots ~= nil and tDecorSetData.plots ~= {} then local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do local nPlugItemId = tDecorSetData.plots[idx] local pltPlot = HousingLib.GetPlot(idx) if pltPlot ~= nil and pltPlot:GetPlugItemId() ~= nPlugItemId then self.wndPlugWarningPopup:Show(true) self.wndPlugWarningPopup:ToFront() return end end end end end local nDecorCount = wndList:GetRowCount() if nDecorCount ~= 0 then local nPlacedDecor = 0 self.tPlaceAllDecorList = {} local nCantPlace = 0 local tCantPlaceList = {} local tDecorCrateList = HousingLib.GetResidence():GetDecorCrateList() for idx = 1, nDecorCount do --local tDecorData = wndList:GetCellData( idx, 1 ) local tDecorData = self.tCurrentDecorList[idx] local tCrateDecorData = nil if tDecorCrateList ~= nil and #tDecorCrateList ~= 0 then for idy = 1, #tDecorCrateList do local tData = tDecorCrateList[idy] if tData.strName == tDecorData.name then local tDecorIdData = table.remove(tDecorCrateList[idy].tDecorItems) if tDecorIdData ~= nil then tCrateDecorData = {} tCrateDecorData.strName = tData.strName tCrateDecorData.tDecorItems = {} tCrateDecorData.tDecorItems[1] = {} tCrateDecorData.tDecorItems[1].nDecorId = tDecorIdData.nDecorId tCrateDecorData.tDecorItems[1].nDecorIdHi = tDecorIdData.nDecorIdHi end if #tDecorCrateList[idy].tDecorItems == 0 then table.remove(tDecorCrateList, idy) end break end end end local tVendorDecorData = wndList:GetCellData( idx, 2 ) --if (tDecorData.positionY < -80 and self.bPlayerIsInside) or (tDecorData.positionY >= -80 and not self.bPlayerIsInside) then if tCrateDecorData ~= nil then nPlacedDecor = nPlacedDecor + 1 self.tPlaceAllDecorList[nPlacedDecor] = {} self.tPlaceAllDecorList[nPlacedDecor].tCrateDecorData = tCrateDecorData self.tPlaceAllDecorList[nPlacedDecor].tVendorDecorData = nil self.tPlaceAllDecorList[nPlacedDecor].tDecorData = tDecorData elseif tVendorDecorData ~= nil then local bCanAfford = false if tVendorDecorData.eCurrencyType == Money.CodeEnumCurrencyType.Credits then monTotalCash = monTotalCash + tVendorDecorData.nCost if monTotalCash <= monPlayerCash then bCanAfford = true end elseif tVendorDecorData.eCurrencyType == Money.CodeEnumCurrencyType.Renown then monTotalRenown = monTotalRenown + tVendorDecorData.nCost if monTotalRenown <= monPlayerRenown then bCanAfford = true end end if bCanAfford then nPlacedDecor = nPlacedDecor + 1 self.tPlaceAllDecorList[nPlacedDecor] = {} self.tPlaceAllDecorList[nPlacedDecor].tCrateDecorData = nil self.tPlaceAllDecorList[nPlacedDecor].tVendorDecorData = tVendorDecorData self.tPlaceAllDecorList[nPlacedDecor].tDecorData = tDecorData else nCantPlace = nCantPlace + 1 tCantPlaceList[nCantPlace] = tVendorDecorData end else nCantPlace = nCantPlace + 1 tCantPlaceList[nCantPlace] = tDecorData end --else --nCantPlace = nCantPlace + 1 --tCantPlaceList[nCantPlace] = tDecorData --end end self.wndPlaceAll:Show(true, true) self.wndPlaceAll:ToFront() local wndVerifyForm = self.wndPlaceAll:FindChild("VerifyPlaceAllForm") wndVerifyForm:Show(true) local wndProgressForm = self.wndPlaceAll:FindChild("PlaceAllProgressForm") wndProgressForm:Show(false) local wndCashTotal = self.wndPlaceAll:FindChild("CashWindowCreditTotal") wndCashTotal:SetMoneySystem(Money.CodeEnumCurrencyType.Credits) wndCashTotal:SetAmount(monTotalCash, true) local wndRenownTotal = self.wndPlaceAll:FindChild("CashWindowRenownTotal") wndRenownTotal:SetMoneySystem(Money.CodeEnumCurrencyType.Renown) wndRenownTotal:SetAmount(monTotalRenown, true) local wndCashYours = self.wndPlaceAll:FindChild("CashWindowCreditYours") wndCashYours:SetMoneySystem(Money.CodeEnumCurrencyType.Credits) wndCashYours:SetAmount(monPlayerCash, true) local wndRenownYours = self.wndPlaceAll:FindChild("CashWindowRenownYours") wndRenownYours:SetMoneySystem(Money.CodeEnumCurrencyType.Renown) wndRenownYours:SetAmount(monPlayerRenown, true) local wndDecorList = self.wndPlaceAll:FindChild("DecorList") self:ShowPlaceAllListItems(wndDecorList, tCantPlaceList) end end function HousingDecorSetManager:OnCancelPlaceAllBtn(wndHandler, wndControl) self.wndPlaceAll:Show(false, true) Apollo.StopTimer("PlaceAllUpdateTimer") end function HousingDecorSetManager:OnConfirmPlaceAllBtn(wndHandler, wndControl) local wndVerifyForm = self.wndPlaceAll:FindChild("VerifyPlaceAllForm") wndVerifyForm:Show(false) local wndProgressForm = self.wndPlaceAll:FindChild("PlaceAllProgressForm") wndProgressForm:Show(true) local wndProgressBar = wndProgressForm:FindChild("ProgressBar") local nTotalDecor = #self.tPlaceAllDecorList wndProgressBar:SetMax(nTotalDecor) wndProgressBar:SetProgress(0) self.nPlaceAllProgress = 1 self.nPlaceAllPass = 1 self.tPlacedDecorList = {} self.wndPlaceAll:FindChild("CurrentPassLabel"):SetText("Placing Decor...") self.tCurrentDecorData = nil Apollo.StartTimer("PlaceAllUpdateTimer") end function HousingDecorSetManager:OnCancelPlaceAllProgressBtn(wndHandler, wndControl) Apollo.StopTimer("PlaceAllUpdateTimer") if self.decorSelection ~= nil then self.decorSelection:CancelTransform() self.decorSelection = nil end self:OnPlaceAllBtn() end function HousingDecorSetManager:OnPlaceAllWarningContinue(wndHandler, wndControl) self.wndPlugWarningPopup:Show(false) self.confirmedPlaceAll = true self:OnPlaceAllBtn() end function HousingDecorSetManager:OnPlaceAllWarningCancel(wndHandler, wndControl) self.wndPlugWarningPopup:Show(false) end function HousingDecorSetManager:OnCloseCreateNewDecorSetWindow() self.wndNewSet:Show(false, true) end function HousingDecorSetManager:OnCancelCreateBtn() self.wndNewSet:Show(false, true) end function HousingDecorSetManager:OnCreateNewSetBtn(wndHandler, wndControl) local wndSettingsFrame = self.wndNewSet:FindChild("SettingsFrame") local wndNameEntry = wndSettingsFrame:FindChild("NewNameEntry") local strName = wndNameEntry:GetText() local nSaveOptions = wndSettingsFrame:GetRadioSel("IncludeDecorRadioGroup") local nNumSavedSets = #self.tSavedData.tDecorSets self.tSavedData.tDecorSets[nNumSavedSets+1] = {} self.tSavedData.tDecorSets[nNumSavedSets+1].name = strName self.tSavedData.tDecorSets[nNumSavedSets+1].decor = {} self.tSavedData.tDecorSets[nNumSavedSets+1].plots = {} self.tSavedData.tDecorSets[nNumSavedSets+1].intOptions = {} self.tSavedData.tDecorSets[nNumSavedSets+1].extOptions = {} if wndSettingsFrame:FindChild("IncludeLandscapeOptionsBtn"):IsChecked() then local residence = HousingLib.GetResidence() if residence == nil then return end local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do local pltPlot = HousingLib.GetPlot(idx) if pltPlot ~= nil then self.tSavedData.tDecorSets[nNumSavedSets+1].plots[idx] = pltPlot:GetPlugItemId() else self.tSavedData.tDecorSets[nNumSavedSets+1].plots[idx] = 0 end end end if wndSettingsFrame:FindChild("IncludeRemodelOptionsBtn"):IsChecked() then local residence = HousingLib.GetResidence() if residence == nil then return end local tExtRemodelValues = {} for eType = HousingLib.RemodelOptionTypeExterior.Roof, HousingLib.RemodelOptionTypeExterior.Ground do tExtRemodelValues[eType] = nil end local tBakedList = {} tBakedList = residence:GetBakedDecorDetails() for key, tData in pairs(tBakedList) do if tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Roof then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof] = {nId = tData.nId, strName = tData.strName} elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Wallpaper then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper] = {nId = tData.nId, strName = tData.strName} elseif tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Entryway then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entry] = {nId = tData.nId, strName = tData.strName} elseif tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Door then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door] = {nId = tData.nId, strName = tData.strName} elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Sky then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky] = {nId = tData.nId, strName = tData.strName} elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Music then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music] = {nId = tData.nId, strName = tData.strName} elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Ground then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground] = {nId = tData.nId, strName = tData.strName} end end self.tSavedData.tDecorSets[nNumSavedSets+1].extOptions = tExtRemodelValues for idx = 1, #ktInteriorZones do local tIntRemodelValues = {} local tSectorDecorList = residence:GetDecorDetailsBySector(ktInteriorZones[idx]) for key, tData in pairs(tSectorDecorList) do tIntRemodelValues[tData.eType] = {nId = tData.nId, strName = tData.strName} end self.tSavedData.tDecorSets[nNumSavedSets+1].intOptions[idx] = tIntRemodelValues end end if nSaveOptions ~= 4 then local tDecorParentList = {} local tDecorList = HousingLib.GetResidence():GetPlacedDecorList() if tDecorList ~= nil then local nDecorCount = 1 for idx = 1, #tDecorList do local decorCurrent = tDecorList[idx] local tDecorIconInfo = decorCurrent:GetDecorIconInfo() if tDecorIconInfo ~= nil then if (nSaveOptions ~= 3 and tDecorIconInfo.fWorldPosY < -80) or (nSaveOptions ~= 2 and tDecorIconInfo.fWorldPosY >= -80) then local tNewDecorEntry = {} tNewDecorEntry.name = decorCurrent:GetName() tNewDecorEntry.index = nDecorCount tNewDecorEntry.decorIdLow, tNewDecorEntry.decorIdHi = decorCurrent:GetId() tNewDecorEntry.positionX = tDecorIconInfo.fWorldPosX tNewDecorEntry.positionY = tDecorIconInfo.fWorldPosY tNewDecorEntry.positionZ = tDecorIconInfo.fWorldPosZ tNewDecorEntry.pitch = tDecorIconInfo.fPitch tNewDecorEntry.roll = tDecorIconInfo.fRoll tNewDecorEntry.yaw = tDecorIconInfo.fYaw tNewDecorEntry.scale = tDecorIconInfo.fScaleCurrent tNewDecorEntry.parent = 0 tDecorParentList[nDecorCount] = decorCurrent:GetParent() and decorCurrent:GetParent():GetHandle() or 0 self.tSavedData.tDecorSets[nNumSavedSets+1].decor[nDecorCount] = tNewDecorEntry nDecorCount = nDecorCount + 1 end end end for idx = 1, #self.tSavedData.tDecorSets[nNumSavedSets+1].decor do local nHandle = tDecorParentList[idx] local decor = HousingLib.GetResidence():GetDecorByHandle(nHandle) if decor ~= nil then for idy = 1, #self.tSavedData.tDecorSets[nNumSavedSets+1].decor do local decorIdLow = self.tSavedData.tDecorSets[nNumSavedSets+1].decor[idy].decorIdLow local decorIdHi = self.tSavedData.tDecorSets[nNumSavedSets+1].decor[idy].decorIdHi local decorIdLow2, decorIdHi2 = decor:GetId() if decorIdLow == decorIdLow2 and decorIdHi == decorIdHi2 then self.tSavedData.tDecorSets[nNumSavedSets+1].decor[idx].parent = idy break end end end end end end if decorSelection ~= nil then decorSelection:Deselect() end local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") self:ShowDecorSetListItems(wndList, self.tSavedData.tDecorSets) self.wndNewSet:Show(false, true) end function HousingDecorSetManager:OnDeleteSetBtn(wndHandler, wndControl) local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tCurrentDecorSetData = wndList:GetCellData( nRow, 1 ) for idx = 1, #self.tSavedData.tDecorSets do local tDecorSetData = self.tSavedData.tDecorSets[idx] if tDecorSetData == tCurrentDecorSetData then table.remove(self.tSavedData.tDecorSets, idx) break end end end local wndSetList = self.wndDecorSetListFrame:FindChild("DecorSetList") self:ShowDecorSetListItems(wndList, self.tSavedData.tDecorSets) wndSetList:SetCurrentRow(0) local wndList = self.wndDecorListFrame:FindChild("DecorList") wndList:DeleteAll() end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnDecorSetListItemChange(wndControl, wndHandler, nX, nY) -- Preview the selected item local nRow = wndControl:GetCurrentRow() if nRow ~= nil then local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local tDecorSetData = wndList:GetCellData( nRow, 1 ) self:ShowLandscapeOptions(tDecorSetData.plots) self:ShowRemodelOptions(tDecorSetData.intOptions, tDecorSetData.extOptions) local wndList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndList, tDecorSetData.decor) self.wndMain:FindChild("HousingDecorSetForm"):FindChild("BG_ArtHeader"):SetText(tDecorSetData.name) self.wndShareSetBtn:Enable(true) self.wndDeleteSetBtn:Enable(true) self.confirmedPlaceAll = false end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnDecorListItemChange(wndControl, wndHandler, nX, nY) -- Preview the selected item local nRow = wndControl:GetCurrentRow() if nRow ~= nil then local wndList = self.wndDecorListFrame:FindChild("DecorList") local tItemData = wndList:GetCellData( nRow, 1 ) local tVendorDecorData = wndList:GetCellData( nRow, 2 ) local wndBuyBtn = self.wndMain:FindChild("BuyBtn") local wndPlaceBtn = self.wndMain:FindChild("PlaceBtn") if tVendorDecorData ~= nil and tVendorDecorData ~= {} then wndBuyBtn:Show(true) wndBuyBtn:Enable(true) wndPlaceBtn:Show(false) local eCurrencyType = tVendorDecorData.eCurrencyType local eGroupCurrencyType = tVendorDecorData.eGroupCurrencyType local monCash = GameLib.GetPlayerCurrency(eCurrencyType, eGroupCurrencyType):GetAmount() wndBuyBtn:Enable(tVendorDecorData.nCost < monCash) else wndBuyBtn:Show(false) wndPlaceBtn:Show(true) end self.wndMain:FindChild("RemoveFromSetBtn"):Enable(true) end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnOnlyShowToggle() local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndList:GetCellData( nRow, 1 ) local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:IsDecorAvailable(tDecorData) -- first check the crate if self:IsDecorAvailableInCrate(tDecorData) == true then return true end -- if they dont have that item in their crate, check if it's purchaseable from the vendor if self:IsDecorAvailableOnVendor(tDecorData) == true then return true end return false end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:IsDecorAvailableInCrate(tDecorData) local tDecorCrateList = HousingLib.GetResidence():GetDecorCrateList() if tDecorCrateList ~= nil then for idx = 1, #tDecorCrateList do local tCratedDecorData = tDecorCrateList[idx] if tCratedDecorData.strName == tDecorData.name then return true end end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:IsDecorAvailableOnVendor(tDecorData) local tDecorVendorList = HousingLib.GetDecorCatalogList() if tDecorVendorList ~= nil then for idx = 1, #tDecorVendorList do local tVendorDecorData = tDecorVendorList[idx] if tVendorDecorData.strName == tDecorData.name then return true end end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:GetCrateDecorData(tDecorData) local tDecorCrateList = HousingLib.GetResidence():GetDecorCrateList() if tDecorCrateList ~= nil then for idx = 1, #tDecorCrateList do local tCratedDecorData = tDecorCrateList[idx] if tCratedDecorData.strName == tDecorData.name then return tCratedDecorData end end end return nil end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:GetVendorDecorData(tDecorData) local tDecorVendorList = HousingLib.GetDecorCatalogList() if tDecorVendorList ~= nil then for idx = 1, #tDecorVendorList do local tVendorDecorData = tDecorVendorList[idx] if tVendorDecorData.strName == tDecorData.name then return tVendorDecorData end end end return nil end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:PlaceDecor(tDecorData) -- first check the crate local tDecorCrateList = HousingLib.GetResidence():GetDecorCrateList() if tDecorCrateList ~= nil then for idx = 1, #tDecorCrateList do local tCratedDecorData = tDecorCrateList[idx] if tCratedDecorData.strName == tDecorData.name then self.decorSelection = HousingLib.PreviewCrateDecorAtLocation(tCratedDecorData.tDecorItems[1].nDecorId, tCratedDecorData.tDecorItems[1].nDecorIdHi, tDecorData.positionX, tDecorData.positionY, tDecorData.positionZ, tDecorData.pitch, tDecorData.roll, tDecorData.yaw, tDecorData.scale) self.tCurrentDecorData = tDecorData self.bFromCrate = true Apollo.StartTimer("DecorPlacementTimer") return end end end -- if they dont have that item in their crate, check if it's purchaseable from the vendor local tVendorDecorData = self:GetVendorDecorData(tDecorData) if tVendorDecorData ~= nil then local eCurrencyType = tVendorDecorData.eCurrencyType local eGroupCurrencyType = tVendorDecorData.eGroupCurrencyType local monCash = GameLib.GetPlayerCurrency(eCurrencyType, eGroupCurrencyType):GetAmount() if tVendorDecorData.nCost <= monCash then self.decorSelection = HousingLib.PreviewVendorDecorAtLocation(tVendorDecorData.nId, tDecorData.positionX, tDecorData.positionY, tDecorData.positionZ, tDecorData.pitch, tDecorData.roll, tDecorData.yaw, tDecorData.scale) self.tCurrentDecorData = tDecorData self.bFromCrate = false Apollo.StartTimer("DecorPlacementTimer") return else Print("Error! Could not purchase decor. Insufficient funds") end end end function HousingDecorSetManager:OnUpdatePlaceDecor() if self.decorSelection == nil then return end self.decorSelection:Place() self.tCurrentDecorData = nil self.decorSelection = nil end function HousingDecorSetManager:OnUpdatePlaceAllDecor() if self.nPlaceAllPass == 1 then if self.tCurrentDecorData ~= nil and self.decorSelection ~= nil then self.tPlacedDecorList[self.nPlaceAllProgress] = {} self.tPlacedDecorList[self.nPlaceAllProgress].nDecorIdLow, self.tPlacedDecorList[self.nPlaceAllProgress].nDecorIdHi = self.decorSelection:GetId() self.decorSelection:Place() local wndProgressForm = self.wndPlaceAll:FindChild("PlaceAllProgressForm") local wndProgressBar = wndProgressForm:FindChild("ProgressBar") self.nPlaceAllProgress = self.nPlaceAllProgress + 1 wndProgressBar:SetProgress(self.nPlaceAllProgress) end if self.nPlaceAllProgress <= #self.tPlaceAllDecorList then local tDecorDataSet = self.tPlaceAllDecorList[self.nPlaceAllProgress] self.tCurrentDecorData = tDecorDataSet.tDecorData if tDecorDataSet.tCrateDecorData ~= nil then self.bFromCrate = true self.decorSelection = HousingLib.PreviewCrateDecorAtLocation(tDecorDataSet.tCrateDecorData.tDecorItems[1].nDecorId, tDecorDataSet.tCrateDecorData.tDecorItems[1].nDecorIdHi, self.tCurrentDecorData.positionX, self.tCurrentDecorData.positionY, self.tCurrentDecorData.positionZ, self.tCurrentDecorData.pitch, self.tCurrentDecorData.roll, self.tCurrentDecorData.yaw, self.tCurrentDecorData.scale) elseif tDecorDataSet.tVendorDecorData ~= nil then self.bFromCrate = false self.decorSelection = HousingLib.PreviewVendorDecorAtLocation(tDecorDataSet.tVendorDecorData.nId, self.tCurrentDecorData.positionX, self.tCurrentDecorData.positionY, self.tCurrentDecorData.positionZ, self.tCurrentDecorData.pitch, self.tCurrentDecorData.roll, self.tCurrentDecorData.yaw, self.tCurrentDecorData.scale) end self.decorSelection:SetPosition(self.tCurrentDecorData.positionX, self.tCurrentDecorData.positionY, self.tCurrentDecorData.positionZ) if self.decorSelection == nil then Print("Decor preview failed! Skipping this decor.") self.tCurrentDecorData = nil end Apollo.StartTimer("PlaceAllUpdateTimer") return else self.nPlaceAllPass = 2 self.nPlaceAllProgress = 1 self.wndPlaceAll:FindChild("CurrentPassLabel"):SetText("Setting up links...") Apollo.StartTimer("PlaceAllUpdateTimer") return end elseif self.nPlaceAllPass == 2 then if self.nPlaceAllProgress <= #self.tPlaceAllDecorList then local tDecorDataSet = self.tPlaceAllDecorList[self.nPlaceAllProgress] self.tCurrentDecorData = tDecorDataSet.tDecorData local nParentIndex = self.tCurrentDecorData.parent if nParentIndex ~= 0 and self.tPlacedDecorList[nParentIndex] ~= nil then local decorParent = HousingLib.GetResidence():GetDecorById(self.tPlacedDecorList[nParentIndex].nDecorIdLow, self.tPlacedDecorList[nParentIndex].nDecorIdHi) local decorChild = HousingLib.GetResidence():GetDecorById(self.tPlacedDecorList[self.nPlaceAllProgress].nDecorIdLow, self.tPlacedDecorList[self.nPlaceAllProgress].nDecorIdHi) if decorChild ~= nil and decorParent ~= nil then decorChild:Link(decorParent) end end local wndProgressForm = self.wndPlaceAll:FindChild("PlaceAllProgressForm") local wndProgressBar = wndProgressForm:FindChild("ProgressBar") self.nPlaceAllProgress = self.nPlaceAllProgress + 1 wndProgressBar:SetProgress(self.nPlaceAllProgress) Apollo.StartTimer("PlaceAllUpdateTimer") return end end self.tCurrentDecorData = nil self.decorSelection = nil local wndProgressForm = self.wndPlaceAll:FindChild("PlaceAllProgressForm") wndProgressForm:Show(false, true) self:OnCancelPlaceAllBtn() end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:ShowDecorSetListItems(wndListControl, tSetList) if wndListControl ~= nil then wndListControl:DeleteAll() end if tSetList ~= nil and wndListControl ~= nil then -- populate the buttons with the item data for idx = 1, #tSetList do local tSetData = tSetList[idx] wndListControl:AddRow(" " .. tSetData.name, "", tSetData) end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:ShowLandscapeOptions(tLandscapeOptions) if tLandscapeOptions == nil or tLandscapeOptions[1] == nil or tLandscapeOptions == {} then local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do self.wndOptionsPropertyFrame:FindChild("Plot"..idx):Enable(false) --self.wndOptionsPropertyFrame:FindChild("Plot"..idx):SetTooltip("") self.wndOptionsPropertyFrame:FindChild("OccupiedSprite."..idx):Show(false) self.wndOptionsPropertyFrame:FindChild("WarningSprite."..idx):Show(false) end return end local residence = HousingLib.GetResidence() if residence == nil then return end local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do local nPlugItemId = tLandscapeOptions[idx] self.wndOptionsPropertyFrame:FindChild("OccupiedSprite."..idx):Show(nPlugItemId ~= nil and nPlugItemId ~= 0) local pltPlot = HousingLib.GetPlot(idx) self.wndOptionsPropertyFrame:FindChild("WarningSprite."..idx):Show(pltPlot ~= nil and pltPlot:GetPlugItemId() ~= nPlugItemId) self.wndOptionsPropertyFrame:FindChild("Plot"..idx):Enable(nPlugItemId ~= 0 or (pltPlot ~= nil and pltPlot:GetPlugItemId() ~= nPlugItemId)) --[[local tPlugItemData = HousingLib.GetPlugItem(nPlugItemId) if tPlugItemData ~= nil then local tCurrentPlugItemData = HousingLib.GetPlugItem(pltPlot:GetPlugItemId()) self.wndOptionsPropertyFrame:FindChild("Plot"..idx):SetTooltip("Saved Enhancement: "..tPlugItemData.strName) else self.wndOptionsPropertyFrame:FindChild("Plot"..idx):SetTooltip("") end--]] end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:ShowRemodelOptions(tIntRemodelOptionsList, tExtRemodelOptions) local wndIntCustomizationFrame = self.wndOptionsCustomizationFrame:FindChild("InteriorCustomizationOptionsFrame") local wndExtCustomizationFrame = self.wndOptionsCustomizationFrame:FindChild("ExteriorCustomizationOptionsFrame") wndIntCustomizationFrame:Show(self.bPlayerIsInside) wndExtCustomizationFrame:Show(not self.bPlayerIsInside) if self.bPlayerIsInside and tIntRemodelOptionsList ~= nil then local nInteriorZoneIndex = 0 for idx = 1, #ktInteriorZones do if ktInteriorZones[idx] == self.nIdZone then nInteriorZoneIndex = idx end end local tIntRemodelValues = {} local tSectorDecorList = HousingLib.GetResidence():GetDecorDetailsBySector(self.nIdZone) for key, tData in pairs(tSectorDecorList) do tIntRemodelValues[tData.eType] = tData end local tIntRemodelOptions = tIntRemodelOptionsList[nInteriorZoneIndex] if tIntRemodelOptions ~= nil then if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Ceiling] ~= nil then wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Ceiling].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Ceiling] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Ceiling].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Ceiling].nId then wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Ceiling] == nil then wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Ceiling")) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Ceiling] ~= nil then wndIntCustomizationFrame:FindChild("CeilingWindow"):FindChild("WarningSprite"):Show(true) end end if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Trim] ~= nil then wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Trim].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Trim] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Trim].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Trim].nId then wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Trim] == nil then wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Trim")) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Trim] ~= nil then wndIntCustomizationFrame:FindChild("TrimWindow"):FindChild("WarningSprite"):Show(true) end end if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Wallpaper] ~= nil then wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.CodeEnumDecorHookType.Wallpaper].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Wallpaper] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Wallpaper].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Wallpaper].nId then wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Wallpaper] == nil then wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Wallpaper")) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Wallpaper] ~= nil then wndIntCustomizationFrame:FindChild("WallpaperWindow"):FindChild("WarningSprite"):Show(true) end end if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Floor] ~= nil then wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Floor].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Floor] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Floor].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Floor].nId then wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Floor] == nil then wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Flooring")) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Floor] ~= nil then wndIntCustomizationFrame:FindChild("FloorWindow"):FindChild("WarningSprite"):Show(true) end end if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Lighting] ~= nil then wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Lighting].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Lighting] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Lighting].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Lighting].nId then wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Lighting] == nil then wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("Description"):SetText("Default Lighting") if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Lighting] ~= nil then wndIntCustomizationFrame:FindChild("LightingWindow"):FindChild("WarningSprite"):Show(true) end end if tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Music] ~= nil then wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("Description"):SetText(tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Music].strName) if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Music] ~= nil and tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Music].nId ~= tIntRemodelOptions[HousingLib.RemodelOptionTypeInterior.Music].nId then wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) elseif tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Music] == nil then wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) else wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(false) end else wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("Description"):SetText("Default Music") if tIntRemodelValues[HousingLib.RemodelOptionTypeInterior.Music] ~= nil then wndIntCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) end end end end if not self.bPlayerIsInside and tExtRemodelOptions ~= nil then local tExtRemodelValues = {} for eType = HousingLib.RemodelOptionTypeExterior.Roof, HousingLib.RemodelOptionTypeExterior.Ground do tExtRemodelValues[eType] = nil end local tBakedList = {} tBakedList = HousingLib.GetResidence():GetBakedDecorDetails() for key, tData in pairs(tBakedList) do if tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Roof then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof] = tData elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Wallpaper then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper] = tData elseif tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Entryway then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entry] = tData elseif tData.eHookType ~= nil and tData.eHookType == HousingLib.CodeEnumDecorHookType.Door then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door] = tData elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Sky then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky] = tData elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Music then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music] = tData elseif tData.eType ~= nil and tData.eType == HousingLib.RemodelOptionTypeExterior.Ground then tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground] = tData end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Roof] ~= nil then wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Roof].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Roof].nId then wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof] == nil then wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Roof")) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Roof] ~= nil then wndExtCustomizationFrame:FindChild("RoofWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Wallpaper] ~= nil then wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Wallpaper].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Wallpaper].nId then wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper] == nil then wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Wallpaper")) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Wallpaper] ~= nil then wndExtCustomizationFrame:FindChild("WallsWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Entryway] ~= nil then wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Entryway].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entryway] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entryway].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Entryway].nId then wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entryway] == nil then wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Entryway")) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Entryway] ~= nil then wndExtCustomizationFrame:FindChild("EntryWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Door] ~= nil then wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Door].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Door].nId then wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door] == nil then wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("Description"):SetText("Default Door") if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Door] ~= nil then wndExtCustomizationFrame:FindChild("DoorWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Sky] ~= nil then wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Sky].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Sky].nId then wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky] == nil then wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("Description"):SetText("Default Sky") if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Sky] ~= nil then wndExtCustomizationFrame:FindChild("SkyWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Music] ~= nil then wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Music].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Music].nId then wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music] == nil then wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("Description"):SetText("Default Music") if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Music] ~= nil then wndExtCustomizationFrame:FindChild("MusicWindow"):FindChild("WarningSprite"):Show(true) end end if tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Ground] ~= nil then wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("Description"):SetText(tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Ground].strName) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground] ~= nil and tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground].nId ~= tExtRemodelOptions[HousingLib.RemodelOptionTypeExterior.Ground].nId then wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("WarningSprite"):Show(true) elseif tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground] == nil then wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("WarningSprite"):Show(true) else wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("WarningSprite"):Show(false) end else wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("Description"):SetText(Apollo.GetString("CRB_Default_Ground")) if tExtRemodelValues[HousingLib.RemodelOptionTypeExterior.Ground] ~= nil then wndExtCustomizationFrame:FindChild("GroundWindow"):FindChild("WarningSprite"):Show(true) end end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:ShowDecorListItems(wndListControl, tDecorList) if wndListControl ~= nil then wndListControl:DeleteAll() end if tDecorList ~= nil and wndListControl ~= nil then self.wndDecorLoadingText:Show(true) self.wndDecorListBlocker:Show(true) wndListControl:Enable(false) self.tCurrentDecorList = tDecorList self.nDecorListLoadIndex = 1 self:OnLoadNextDecorListItems() end end function HousingDecorSetManager:OnLoadNextDecorListItems() local wndListControl = self.wndDecorList if self.tCurrentDecorList ~= nil and wndListControl ~= nil then for idx = self.nDecorListLoadIndex, self.nDecorListLoadIndex + knDecorListItemsPerLoad do local tDecorData = self.tCurrentDecorList[idx] if tDecorData ~= nil then self.nDecorListLoadIndex = self.nDecorListLoadIndex + 1 local bPrune = false local bIsInCrate = self:IsDecorAvailableInCrate(tDecorData) local tVendorDecorData = self:GetVendorDecorData(tDecorData) local bFilterNotOwned = self.wndDecorListFrame:FindChild("ShowOwnedOnlyBtn"):IsChecked() if bFilterNotOwned and not bIsInCrate then bPrune = true end if self.nDecorListFilter == 2 and tDecorData.positionY >= -80 then -- Interior Only bPrune = true elseif self.nDecorListFilter == 3 and tDecorData.positionY < -80 then -- Exterior only bPrune = true end if not bPrune then wndListControl:AddRow(" " .. tDecorData.name, "", tDecorData ) --if (tDecorData.positionY < -80 and not self.bPlayerIsInside) or (tDecorData.positionY >= -80 and self.bPlayerIsInside) then --wndListControl:EnableRow(idx, false) --end wndListControl:SetCellData(idx, 2, "", "", tVendorDecorData) if not bIsInCrate and tVendorDecorData ~= nil then local eCurrencyType = tVendorDecorData.eCurrencyType local eGroupCurrencyType = tVendorDecorData.eGroupCurrencyType local monCash = GameLib.GetPlayerCurrency(eCurrencyType, eGroupCurrencyType):GetAmount() self.wndCashCredit:SetMoneySystem(eCurrencyType, eGroupCurrencyType) if tVendorDecorData.nCost > monCash then strDoc = self.wndCashCredit:GetAMLDocForAmount(tVendorDecorData.nCost, true, crRed) else strDoc = self.wndCashCredit:GetAMLDocForAmount(tVendorDecorData.nCost, true, crWhite) end wndListControl:SetCellDoc(idx, 2, strDoc) self.wndCashCredit:SetMoneySystem(Money.CodeEnumCurrencyType.Credits, 0) elseif not bIsInCrate and tVendorDecorData == nil then wndListControl:EnableRow(idx, false) end end end if self.nDecorListLoadIndex > #self.tCurrentDecorList then break end end if self.nDecorListLoadIndex <= #self.tCurrentDecorList then Apollo.StartTimer("DecorListLoadTimer") else self.wndDecorLoadingText:Show(false) self.wndDecorListBlocker:Show(false) wndListControl:Enable(true) Apollo.StopTimer("DecorListLoadTimer") end end end --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:ShowPlaceAllListItems(wndListControl, tDecorList) if wndListControl ~= nil then wndListControl:DeleteAll() end if tDecorList~= nil and wndListControl ~= nil then -- populate the buttons with the item data for idx = 1, #tDecorList do local tDecorData = tDecorList[idx] if tDecorData.name ~= nil then wndListControl:AddRow(" " .. tDecorData.name, "", tDecorData ) if (tDecorData.positionY < -80 and not self.bPlayerIsInside) or (tDecorData.positionY >= -80 and self.bPlayerIsInside) then wndListControl:EnableRow(idx, false) end elseif tDecorData.eCurrencyType == nil then wndListControl:AddRow(" " .. tDecorData.strName, "", tDecorData ) elseif tDecorData.strName ~= nil then wndListControl:AddRow(" " .. tDecorData.strName, "", tDecorData ) local eCurrencyType = tDecorData.eCurrencyType local eGroupCurrencyType = tDecorData.eGroupCurrencyType local wndCash = self.wndPlaceAll:FindChild("CashWindowCreditTotal") wndCash:SetMoneySystem(eCurrencyType, eGroupCurrencyType) strDoc = wndCash:GetAMLDocForAmount(tDecorData.nCost, true, crRed) wndListControl:SetCellDoc(idx, 2, strDoc) wndCash:SetMoneySystem(Money.CodeEnumCurrencyType.Credits, 0) end end end end --------------------------------------------------------------------------------------------------- -- CopySetForm Functions --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnShareSetBtn(wndHandler, wndControl) local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then self.wndCopySet:Show(true, true) self.wndCopySet:ToFront() local wndTextBox = self.wndCopySet:FindChild("TextEditBox") local tDecorSetData = wndList:GetCellData( nRow, 1 ) tDecorSetData = self:ConvertSaveToSimpleData(tDecorSetData) local strEncodedSet = self:SaveTable(tDecorSetData) self.nCurrentPage = 1 self.nNumPages = 1 self.strEncodedSetPageList = {} if string.len(strEncodedSet) > knMaxTextLength then local nNumPages = 1 local nStrIndex = 1 local strEncodedSetPageList = {} while string.len(strEncodedSet) > knMaxTextLength do local pageText = string.sub(strEncodedSet, 1, knMaxTextLength) strEncodedSetPageList[nNumPages] = pageText nNumPages = nNumPages + 1 strEncodedSet = string.sub(strEncodedSet, knMaxTextLength + 1) end strEncodedSetPageList[nNumPages] = strEncodedSet self.nNumPages = nNumPages self.strEncodedSetPageList = strEncodedSetPageList wndTextBox:SetText(strEncodedSetPageList[1]) self.wndCopySet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndCopySet:FindChild("PrevBtn"):Enable(false) self.wndCopySet:FindChild("NextBtn"):Enable(true) else wndTextBox:SetText(strEncodedSet) self.wndCopySet:FindChild("CurrentPageText"):SetText("1/1") self.wndCopySet:FindChild("PrevBtn"):Enable(false) self.wndCopySet:FindChild("NextBtn"):Enable(false) end end end function HousingDecorSetManager:OnCloseCopySetWindow(wndHandler, wndControl) self.wndCopySet:Show(false, true) end function HousingDecorSetManager:OnPrevBtn(wndHandler, wndControl) self.nCurrentPage = self.nCurrentPage - 1 if self.nCurrentPage == 1 then self.wndCopySet:FindChild("PrevBtn"):Enable(false) end self.wndCopySet:FindChild("NextBtn"):Enable(true) self.wndCopySet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndCopySet:FindChild("TextEditBox"):SetText(self.strEncodedSetPageList[self.nCurrentPage]) end function HousingDecorSetManager:OnNextBtn(wndHandler, wndControl) self.nCurrentPage = self.nCurrentPage + 1 if self.nCurrentPage >= self.nNumPages then self.wndCopySet:FindChild("NextBtn"):Enable(false) end self.wndCopySet:FindChild("PrevBtn"):Enable(true) self.wndCopySet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndCopySet:FindChild("TextEditBox"):SetText(self.strEncodedSetPageList[self.nCurrentPage]) end --------------------------------------------------------------------------------------------------- -- LoadSetForm Functions --------------------------------------------------------------------------------------------------- function HousingDecorSetManager:OnOpenSetBtn(wndHandler, wndControl) self.wndLoadSet:Show(true, true) self.wndLoadSet:ToFront() local wndTextBox = self.wndLoadSet:FindChild("TextEditBox") wndTextBox:SetText("") local wndCreateBtn = self.wndLoadSet:FindChild("CreateSetBtn") wndCreateBtn:Enable(false) local wndNameEntry = self.wndLoadSet:FindChild("NewNameEntry") wndNameEntry:SetText("") wndNameEntry:Enable(false) self.wndLoadSet:FindChild("PrevBtn"):Enable(false) self.wndLoadSet:FindChild("NextBtn"):Enable(false) self.wndLoadSet:FindChild("CurrentPageText"):SetText("1/1") self.nCurrentPage = 1 self.nNumPages = 1 self.strEncodedSetPageList = {} end function HousingDecorSetManager:OnCancelLoadSetBtn(wndHandler, wndControl) self.wndLoadSet:Show(false, true) end function HousingDecorSetManager:OnLoadSetEditBoxChanged( wndHandler, wndControl, strText ) local wndTextBox = self.wndCopySet:FindChild("TextEditBox") if strText ~= nil and strText ~= "" then local wndCreateBtn = self.wndLoadSet:FindChild("CreateSetBtn") wndCreateBtn:Enable(true) self.strEncodedSetPageList[self.nCurrentPage] = strText local wndNameEntry = self.wndLoadSet:FindChild("NewNameEntry") wndNameEntry:Enable(true) --[[local tDecodedTable = self:LoadTable(strText) if tDecodedTable ~= nil then tDecodedTable = self:ConvertSimpleToSaveData(tDecodedTable) if tDecodedTable.name ~= nil then local wndNameEntry = self.wndLoadSet:FindChild("NewNameEntry") wndNameEntry:SetText(tDecodedTable.name) wndNameEntry:Enable(true) end end--]] end end function HousingDecorSetManager:OnCreateSetBtn(wndHandler, wndControl) local nNumSavedSets = #self.tSavedData.tDecorSets self.tSavedData.tDecorSets[nNumSavedSets+1] = {} local strText = "" for idx = 1, self.nNumPages do strText = strText .. self.strEncodedSetPageList[idx] end --local wndTextBox = self.wndLoadSet:FindChild("TextEditBox") --local strText = wndTextBox:GetText() local tDecodedTable = self:LoadTable(strText) if tDecodedTable ~= nil then tDecodedTable = self:ConvertSimpleToSaveData(tDecodedTable) self.tSavedData.tDecorSets[nNumSavedSets+1] = tDecodedTable local wndNameEntry = self.wndLoadSet:FindChild("NewNameEntry") local strName = wndNameEntry:GetText() self.tSavedData.tDecorSets[nNumSavedSets+1].name = strName end local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") self:ShowDecorSetListItems(wndList, self.tSavedData.tDecorSets) self.wndLoadSet:Show(false, true) end function HousingDecorSetManager:OnLoadSetPrevBtn(wndHandler, wndControl) self.nCurrentPage = self.nCurrentPage - 1 if self.nCurrentPage == 1 then self.wndLoadSet:FindChild("PrevBtn"):Enable(false) end self.wndLoadSet:FindChild("NextBtn"):Enable(true) self.wndLoadSet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndLoadSet:FindChild("TextEditBox"):SetText(self.strEncodedSetPageList[self.nCurrentPage]) end function HousingDecorSetManager:OnLoadSetNextBtn(wndHandler, wndControl) self.nCurrentPage = self.nCurrentPage + 1 if self.nCurrentPage >= self.nNumPages then self.wndLoadSet:FindChild("NextBtn"):Enable(false) end self.wndLoadSet:FindChild("PrevBtn"):Enable(true) self.wndLoadSet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndLoadSet:FindChild("TextEditBox"):SetText(self.strEncodedSetPageList[self.nCurrentPage]) end function HousingDecorSetManager:OnAddPageBtn(wndHandler, wndControl) self.nNumPages = self.nNumPages + 1 self.nCurrentPage = self.nCurrentPage + 1 self.wndLoadSet:FindChild("PrevBtn"):Enable(true) self.wndLoadSet:FindChild("CurrentPageText"):SetText(self.nCurrentPage.."/"..self.nNumPages) self.wndLoadSet:FindChild("TextEditBox"):SetText("") end function HousingDecorSetManager:OnMouseEnterPlot(wndHandler, wndControl, x, y) local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do if wndControl == self.wndOptionsPropertyFrame:FindChild("Plot"..idx) then local pltPlot = HousingLib.GetPlot(idx) local tPlugData = pltPlot ~= nil and HousingLib.GetPlugItem(pltPlot:GetPlugItemId()) or nil local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndList:GetCellData( nRow, 1 ) local tPlugItemData = HousingLib.GetPlugItem(tDecorSetData.plots[idx]) self.wndOptionsTooltip:FindChild("SavedLandscapeOptionText"):SetText(tPlugItemData ~= nil and tPlugItemData.strName or "[Empty]") --[[local strCurrentPlugText = "" if tDecorSetData.plots[idx] ~= pltPlot:GetPlugItemId() then strCurrentPlugText = string.format("<T TextColor=\"UI_WindowTextRed\">%s</T>", tPlugData ~= nil and tPlugData.strName or "[Empty]") else strCurrentPlugText = string.format("<T TextColor=\"UI_WindowTextDefault\">%s</T>", tPlugData ~= nil and tPlugData.strName or "[Empty]") end--]] self.wndOptionsTooltip:FindChild("CurrentLandscapeOptionText"):SetText(tPlugData ~= nil and tPlugData.strName or "[Empty]") self.wndOptionsTooltip:Show(true) local tMousePos = Apollo.GetMouse() self.wndOptionsTooltip:Move(tMousePos.x/2, tMousePos.y/2, self.wndOptionsTooltip:GetWidth(), self.wndOptionsTooltip:GetHeight()) end return end end end function HousingDecorSetManager:OnMouseExitPlot(wndHandler, wndControl, x, y) local nPlotCount = HousingLib.GetResidence():GetPlotCount() for idx = 1, nPlotCount do if wndControl == self.wndOptionsPropertyFrame:FindChild("Plot"..idx) then if not self.wndOptionsPropertyFrame:FindChild("Plot"..idx):ContainsMouse() then self.wndOptionsTooltip:Show(false) return end end end end function HousingDecorSetManager:OnViewDropdownBtnCheck( wndHandler, wndControl, eMouseButton ) self.wndDecorListFrame:FindChild("ViewDropdownWindow"):Show(true) end function HousingDecorSetManager:OnViewDropdownBtnUncheck( wndHandler, wndControl, eMouseButton ) self.wndDecorListFrame:FindChild("ViewDropdownWindow"):Show(false) end function HousingDecorSetManager:OnViewBtnChecked( wndHandler, wndControl, eMouseButton ) local wndDropdown = self.wndDecorListFrame:FindChild("ViewDropdownWindow") self.nDecorListFilter = wndDropdown:GetRadioSel("ViewSettingsBtn") self.wndDecorListFrame:FindChild("ViewDropdownLabel"):SetText("View: "..wndDropdown:FindChild("ViewBtn"..self.nDecorListFilter):GetText()) self.wndDecorListFrame:FindChild("ViewDropdownBtn"):SetCheck(false) wndDropdown:Show(false) local wndList = self.wndDecorSetListFrame:FindChild("DecorSetList") local nRow = wndList:GetCurrentRow() if nRow ~= nil then local tDecorSetData = wndList:GetCellData( nRow, 1 ) local wndDecorList = self.wndDecorListFrame:FindChild("DecorList") self:ShowDecorListItems(wndDecorList, tDecorSetData.decor) end return true end ----------------------------------------------------------------------------------------------- -- Initialization of CassPkg to encode and decode tables with base64 -- Credit to "Casstiel" on official wildstar forums ----------------------------------------------------------------------------------------------- -- from http://help.interfaceware.com/kb/112 function HousingDecorSetManager:SaveTable(Table) local savedTables = {} -- used to record tables that have been saved, so that we do not go into an infinite recursion local outFuncs = { ['string'] = function(value) return string.format("%q",value) end; ['boolean'] = function(value) if (value) then return 'true' else return 'false' end end; ['number'] = function(value) if (math.floor(value) == value) then return string.format('%u',math.floor(value)) else return string.format('%.3f',value) end end; ['userdata'] = function(value) return 'nil' end; } local outFuncsMeta = { __index = function(t,k) error('Invalid Type For SaveTable: '..k ) end } setmetatable(outFuncs,outFuncsMeta) local tableOut = function(value) if (savedTables[value]) then error('There is a cyclical reference (table value referencing another table value) in this set.'); end local outValue = function(value) return outFuncs[type(value)](value) end local out = '{' for i,v in pairs(value) do out = out..'['..outValue(i)..']='..outValue(v)..',' end savedTables[value] = true; --record that it has already been saved return out..'}' end outFuncs['table'] = tableOut; --return self:ascii_encode(tableOut(Table)) return tableOut(Table) end function HousingDecorSetManager:LoadTable(Input) -- note that this does not enforce anything, for simplicity --local decoded = self:ascii_decode(Input) return assert(loadstring('return '.. Input ))() end -- converting function HousingDecorSetManager:ConvertSaveToSimpleData(tSaveData) tSimpleData = {} local tStringMap = {} local tNameHeaderData = {} local index = 1 for idx = 1, #tSaveData.decor do if tStringMap[tSaveData.decor[idx].name] == nil then tStringMap[tSaveData.decor[idx].name] = index tNameHeaderData[index] = tSaveData.decor[idx].name index = index + 1 end end tSimpleData.name = tSaveData.name tSimpleData.text = tNameHeaderData tSimpleData.plugs = tSaveData.plots tSimpleData.extOptions = tSaveData.extOptions tSimpleData.intOptions = tSaveData.intOptions tSimpleData.decor = {} for idx = 1, #tSaveData.decor do tSimpleData.decor[idx] = {} tSimpleData.decor[idx].n = tStringMap[tSaveData.decor[idx].name] tSimpleData.decor[idx].x = tSaveData.decor[idx].positionX tSimpleData.decor[idx].y = tSaveData.decor[idx].positionY tSimpleData.decor[idx].z = tSaveData.decor[idx].positionZ if math.abs(tSaveData.decor[idx].pitch) >= 0.001 then tSimpleData.decor[idx].p = tSaveData.decor[idx].pitch end if math.abs(tSaveData.decor[idx].roll) >= 0.001 then tSimpleData.decor[idx].r = tSaveData.decor[idx].roll end if math.abs(tSaveData.decor[idx].yaw) >= 0.001 then tSimpleData.decor[idx].ya = tSaveData.decor[idx].yaw end if math.abs(tSaveData.decor[idx].scale - 1.0) >= 0.001 then tSimpleData.decor[idx].s = tSaveData.decor[idx].scale end end return tSimpleData end function HousingDecorSetManager:ConvertSimpleToSaveData(tSimpleData) tSaveData = {} local tNameHeaderData = tSimpleData.text tSaveData.name = tSimpleData.name tSaveData.plots = tSimpleData.plugs tSaveData.extOptions = tSimpleData.extOptions tSaveData.intOptions = tSimpleData.intOptions tSaveData.decor = {} for idx = 1, #tSimpleData.decor do tSaveData.decor[idx] = {} tSaveData.decor[idx].name = tNameHeaderData[tSimpleData.decor[idx].n] tSaveData.decor[idx].positionX = tSimpleData.decor[idx].x tSaveData.decor[idx].positionY = tSimpleData.decor[idx].y tSaveData.decor[idx].positionZ = tSimpleData.decor[idx].z if tSimpleData.decor[idx].p ~= nil then tSaveData.decor[idx].pitch = tSimpleData.decor[idx].p else tSaveData.decor[idx].pitch = 0.0 end if tSimpleData.decor[idx].r ~= nil then tSaveData.decor[idx].roll = tSimpleData.decor[idx].r else tSaveData.decor[idx].roll = 0.0 end if tSimpleData.decor[idx].ya ~= nil then tSaveData.decor[idx].yaw = tSimpleData.decor[idx].ya else tSaveData.decor[idx].yaw = 0.0 end if tSimpleData.decor[idx].s ~= nil then tSaveData.decor[idx].scale = tSimpleData.decor[idx].s else tSaveData.decor[idx].scale = 1.0 end end return tSaveData end --====================================================================-- -- Module: Ascii 85 Encoding in Pure Lua -- Author : Satheesh -- -- License: MIT --====================================================================-- function HousingDecorSetManager:decimalToBase85(num) local base = 85 local final = {} while num > 0 do table.insert(final,1,num % base) num = math.floor(num / base) end while #final < 5 do table.insert(final,1,0) end return final end function HousingDecorSetManager:base85ToDecimal(b85) local base = 85 local l = #b85 local final = 0 for i=l,1,-1 do local digit = b85[i] local val = digit * base^(l-i) final = final + val end return final end function HousingDecorSetManager:decimalToBinary(num) local base = 2 local bits = 8 local final = "" while num > 0 do final = "" .. (num % base ) .. final num = math.floor(num / base) end local l = final:len() if l == 0 then final = "0"..final end while final:len()%8 ~=0 do final = "0"..final end return final end function HousingDecorSetManager:binaryToDecimal(bin) local base = 2 local l = bin:len() local final = 0 for i=l,1,-1 do local digit = bin:sub(i,i) local val = digit * base^(l-i) final = final + val end return final end function HousingDecorSetManager:encode(substr) local l = substr:len() local combine = "" for i=1,l do local char = substr:sub(i,i) local byte = char:byte() local bin = self:decimalToBinary(byte) combine = combine..bin end local num = self:binaryToDecimal(combine) local b85 = self:decimalToBase85(num) local final = "" for i=1,#b85 do local char = tostring(b85[i]+33) final = final .. char:char() end if final == "!!!!!" then final = "z" end return final end function HousingDecorSetManager:decode(substr) local final = "" local l = substr:len() local combine = {} for i=1,l do local char = substr:sub(i,i) local byte = char:byte() byte = byte - 33 combine[i] = byte end local num = self:base85ToDecimal(combine) local bin = self:decimalToBinary(num) while bin:len() < 32 do bin = "0"..bin end local l = bin:len() local split = 8 for i=1,l,split do local sub = bin:sub(i,i+split-1) local byte = self:binaryToDecimal(sub) local char = tostring(byte):char() final = final..char end return final end function HousingDecorSetManager:ascii_encode(str) local final = "" local noOfZeros = 0 while str:len()%4~=0 do noOfZeros = noOfZeros + 1 str = str.."\0" end local l = str:len() for i=1,l,4 do local sub = str:sub(i,i+3) final = final .. self:encode(sub) end final = final:sub(1,-noOfZeros-1) final = "<~"..final.."~>" return final end function HousingDecorSetManager:ascii_decode(str) local final = "" str = str:sub(3,-3) str = str:gsub("z","!!!!!") local c = 5 local noOfZeros = 0 while str:len()%c~=0 do noOfZeros = noOfZeros + 1 str = str.."u" end local l = str:len() for i=1,l,c do local sub = str:sub(i,i+c-1) final = final .. self:decode(sub) end final = final:sub(1,-noOfZeros-1) return final end ----------------------------------------------------------------------------------------------- -- HousingDecorSetManager Instance ----------------------------------------------------------------------------------------------- local HousingDecorSetManagerInst = HousingDecorSetManager:new() HousingDecorSetManagerInst:Init()
---date created: 2021.8.4 ---reference: THlib/background/icepool/icepool.lua local BackgroundSession = require("BHElib.background.background_session") ---@class background.NightPassage:Prefab.Background local M = LuaClass("background.NightPassage", BackgroundSession) local Coordinates = require("BHElib.unclassified.coordinates_and_screen") --------------------------------------------------------------------------------------------------- local Vec3 = math.Vec3 --------------------------------------------------------------------------------------------------- local _image_road = "image:background_night_passage_road" local _image_pillar = "image:background_night_passage_pillar" local _image_ground = "image:background_night_passage_ground" LoadImageFromFile(_image_road, "THlib/background/temple/road.png") LoadImageFromFile(_image_pillar, "THlib/background/temple/pillar.png") LoadImageFromFile(_image_ground, "THlib/background/temple/ground.png") local _image_road_sprite = FindResSprite(_image_road) --------------------------------------------------------------------------------------------------- function M.__create(stage) local self = BackgroundSession.__create(stage, "3d", LAYER_BG) self.camera_target_pos = Vec3(0, 0, 0) -- where camera looks at self.camera_offset = Vec3(-2.2, 0, 1) self.camera_forward_speed = 0.013 self.fog_color = Color(255, 40, 0, 20) self.repeat_dx = 1 self.d = 0 self.c_x = 0 self.c_y = 0 return self end function M:ctor() self:update() end --------------------------------------------------------------------------------------------------- function M:update(dt) BackgroundSession.update(self, dt) local view3d = Coordinates.getView3d() self.d = self.d + self.camera_forward_speed local d = self.d - math.floor(self.d, self.repeat_dx) self.c_x = self.c_x + 0.03 self.c_y = 0 local camera_target_pos = self.camera_target_pos camera_target_pos.x = d local camera_eye_pos = (camera_target_pos + self.camera_offset) view3d.eye = {camera_eye_pos.x, camera_eye_pos.y, camera_eye_pos.z} view3d.at = {camera_target_pos.x, camera_target_pos.y, camera_target_pos.z} view3d.z = {0.5, 5} view3d.up = {camera_target_pos.x, camera_target_pos.y, camera_target_pos.z + 1} view3d.fovy = 0.7 view3d.fog = {3, 5, self.fog_color} view3d.dirty = true end local function TileHorizontallyWithImage(image_name, dx, z, xi_range, yi_range, base_x, base_y, flipped) local size = FindResSprite(image_name):getSprite():getContentSize() local scale = dx / size.height local width, height = dx, size.height * scale for j = xi_range[1], xi_range[2] do local xmin = base_x + j * width local xmax = xmin + width for i = yi_range[1], yi_range[2] do local ymin = base_y + i * height local ymax = ymin + height if not flipped then Render4V(image_name, xmax, ymin, z, xmax, ymax, z, xmin, ymax, z, xmin, ymin, z) else Render4V(image_name, xmax, ymax, z, xmax, ymin, z, xmin, ymin, z, xmin, ymax, z) end end end end local function RenderPillars(image_name, dx, y, pillar_height, xi_range, base_x, base_y, base_z, radius, imin, light_angle) local top_z = base_z + pillar_height for j = xi_range[2], xi_range[1], -1 do local pillar_x = base_x + j * dx local pillar_y = base_y + y local imax, di = imin + 7, 1 for i = imin, imax, di do -- compute two base points of the rectangles that touch the ground local angle1 = i * 45 - 22.5 local x1, y1 = pillar_x + radius * cos(angle1), pillar_y + radius * sin(angle1) local angle2 = angle1 + 45 local x2, y2 = pillar_x + radius * cos(angle2), pillar_y + radius * sin(angle2) local dot = cos(angle1) * cos(light_angle) + sin(angle1) * sin(light_angle) local brightness = 125 + 125 * dot SetImageState(image_name, "mul+alpha", Color(255, brightness, brightness, brightness)) Render4V(image_name, x2, y2, top_z, x1, y1, top_z, x1, y1, base_z, x2, y2, base_z) end end end function M:render() self:preRender() RenderClear(self.fog_color) -- clear the view port local repeat_dx = self.repeat_dx local c_x = self.c_x - math.floor(self.c_x, repeat_dx) - 0.5 local c_y = self.c_y - math.floor(self.c_y, repeat_dx) - 0.5 local alpha = self.timer * 1 if alpha > 255 then alpha = 255 end TileHorizontallyWithImage(_image_ground, repeat_dx, 0, {-2, 2}, {-1, -1}, 0, -0.5 * repeat_dx, false) TileHorizontallyWithImage(_image_ground, repeat_dx, 0, {-2, 2}, {1, 1}, 0, -0.5 * repeat_dx, true) TileHorizontallyWithImage(_image_road, repeat_dx, 0, {-2, 2}, {0, 0}, 0, -0.5 * repeat_dx, true) local size = _image_road_sprite:getSprite():getContentSize() local pillar_y = repeat_dx / size.height * size.width * 0.5 RenderPillars(_image_pillar, repeat_dx, pillar_y, 1, {-1, 3}, 0, 0, 0, 0.13, -1, 225) RenderPillars(_image_pillar, repeat_dx, -pillar_y, 1, {-1, 3}, 0, 0, 0, 0.13, -2, 225) self:postRender() end return M
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) write(m,"\n\t") local i=1 while x[i] do write(x[i]) i=i+1 if x[i] then write(",") end end write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
data:extend({ -- Sodium flouride { type = "item", name = "solid-sodium-floride", icon = "__extendedangels__/graphics/icons/solid-sodium-floride.png", icon_size = 32, subgroup = "petrochem-sodium", order = "j", stack_size = 200 }, -- Argon { type = "fluid", name = "gas-argon", icon = "__extendedangels__/graphics/icons/gas-argon.png", icon_size = 32, default_temperature = 100, heat_capacity = "0KJ", base_color = {r = 0/255, g = 0/255, b = 0/255}, flow_color = {r = 30/255, g = 143/255, b = 216/255}, max_temperature = 100, pressure_to_speed_ratio = 0.4, flow_to_energy_ratio = 0.59, }, }) if mods["Clowns-Processing"] then data:extend({ -- Disodium phosphate { type = "item", name = "solid-disodium-phosphate", icon = "__Clowns-Processing__/graphics/icons/solid-white-phosphorus.png", icon_size = 32, subgroup = "petrochem-sodium", order = "k", stack_size = 200 }, -- Tetrasodium pyrophosphate { type = "item", name = "solid-tetrasodium-pyrophosphate", icon = "__Clowns-Processing__/graphics/icons/solid-white-phosphorus.png", icon_size = 32, subgroup = "petrochem-sodium", order = "l", stack_size = 200 }, }) end