content
stringlengths
5
1.05M
-- dataloader -- this scripy is specifically designed for progressive-growing GAN. -- will change this to multi-threaded 'loader' module for speed up. local opts = require 'script.opts' local loader = require 'data.loader' local opt = opts.parse(arg) local myloader = {} -- initial setting for dataloader. myloader.l_config = {} myloader.l_config.trainPath = opt.data_root_train myloader.l_config.nthreads = opt.nthreads myloader.l_config.batchSize = 64 myloader.l_config.loadSize = 8 myloader.l_config.sampleSize = 8 myloader.l_config.rotate = 0 myloader.l_config.crop = 'none' myloader.l_config.padding = true myloader.l_config.hflip = false myloader.l_config.keep_ratio = true myloader.l_config.whitenoise = 0 myloader.l_config.brightness = 0 print(myloader.l_config) -- create dataloader. local dataset = loader.new(myloader.l_config) function myloader.renew(self, l_config) print('re-configure dataloader setting...') dataset = loader.new(l_config) end function myloader:getBatch(target) return dataset:getBatch(target) end function myloader:size() return dataset:size() end return myloader
local slc = SL.Global.ActiveColorIndex local af = Def.ActorFrame{} -- - - - - - - - - - - -- Constants defining UI element position depending on horizontal or vertical screen local arrow_zoom = (IsVerticalScreen() and 0.07 or 0.1) local arrow_x = (IsVerticalScreen() and 35 or 50) af[#af+1] = Def.Quad{ InitCommand=function(self) self:zoomto(_screen.w,0):diffuse(Color.Black):Center() end, OnCommand=function(self) self:accelerate(0.3):zoomtoheight(128):diffusealpha(0.9):sleep(2.5) end, OffCommand=function(self) self:accelerate(0.3):zoomtoheight(0) end } -- loop to add 7 SM5 arrows to the primary ActorFrame for i=1,7 do af[#af+1] = Def.ActorFrame { InitCommand=function(self) self:Center() end, OnCommand=function(self) self:sleep(3):queuecommand("Hide") end, HideCommand=function(self) self:visible(false) end, LoadActor("white_logo.png")..{ InitCommand=cmd(zoom, arrow_zoom; diffuse, GetHexColor(slc-i-3); diffusealpha,0; x, (i-4) * arrow_x ), OnCommand=cmd(sleep, i*0.1 + 0.2; linear,0.75; diffusealpha,1; linear,0.75;diffusealpha,0) }, LoadActor("highlight.png")..{ InitCommand=cmd(zoom, arrow_zoom; diffusealpha,0; x, (i-4) * arrow_x), OnCommand=cmd(sleep, i*0.1 + 0.2; linear,0.75; diffusealpha,0.75; linear,0.75;diffusealpha,0) } } end af[#af+1] = LoadFont("Common Normal")..{ Text=ScreenString("ThemeDesign"), InitCommand=function(self) self:diffuse(GetHexColor(slc)):diffusealpha(0):Center() end, OnCommand=function(self) self:sleep(3):linear(0.25):diffusealpha(1) end, OffCommand=function(self) self:linear(0.25):diffusealpha(0) end, } return af
local EffectSprite3D = class("EffectSprite3D", function() return cc.Sprite3D:create() end) function EffectSprite3D:init(objFilePath, textureFilePath) self:initWithFile(objFilePath) self:setTexture(textureFilePath) end return EffectSprite3D
local vec2 = require("math.vec2") local vec3 = require("math.vec3") local color = require("math.color") local umath = require("math.umath") return function(pos, c, buf) local npos = (pos - 1) / (buf.size - 1) local to_center = vec2(0.5, 0.5) - npos local angle = math.atan2(to_center.y, to_center.x) local radius = umath.clamp(to_center:length() * 2, 0, 1) return color.hsv2rgb(vec3(angle / (2 * math.pi) + 0.5, radius, 1)) end
env = require('test_run') vclock_diff = require('fast_replica').vclock_diff test_run = env.new() SERVERS = { 'autobootstrap_guest1', 'autobootstrap_guest2', 'autobootstrap_guest3' } -- -- Start servers -- test_run:create_cluster(SERVERS, "replication", {args="0.1"}) -- -- Wait for full mesh -- test_run:wait_fullmesh(SERVERS) -- -- Check vclock -- vclock1 = test_run:get_vclock('autobootstrap_guest1') vclock_diff(vclock1, test_run:get_vclock('autobootstrap_guest2')) vclock_diff(vclock1, test_run:get_vclock('autobootstrap_guest3')) -- -- Insert rows on each server -- _ = test_run:cmd("switch autobootstrap_guest1") _ = box.space.test:insert({box.info.id}) _ = test_run:cmd("switch autobootstrap_guest2") _ = box.space.test:insert({box.info.id}) _ = test_run:cmd("switch autobootstrap_guest3") _ = box.space.test:insert({box.info.id}) _ = test_run:cmd("switch default") -- -- Synchronize -- vclock = test_run:get_cluster_vclock(SERVERS) vclock2 = test_run:wait_cluster_vclock(SERVERS, vclock) vclock_diff(vclock1, vclock2) -- -- Check result -- _ = test_run:cmd("switch autobootstrap_guest1") box.space.test:select() _ = test_run:cmd("switch autobootstrap_guest2") box.space.test:select() _ = test_run:cmd("switch autobootstrap_guest3") box.space.test:select() _ = test_run:cmd("switch default") -- -- Stop servers -- test_run:drop_cluster(SERVERS)
local defaultConfig = { playerTags = {} } TAGMAN = create_setting("tags", "tags.lua", defaultConfig, 0) TAGMAN:load()
-- Roll Component -- local Base = require 'modern' local Roll = Base:extend() -- New -- function Roll:new(host, data) -- self.host = host -- properties self.rollSpeedScale = 1.25 self.rollForgive = 0.15 -- flags self.isRolling = false -- timers self.tRollReq = 0 end -- Update -- function Roll:update(dt) self.tRollReq = self.tRollReq > 0 and self.tRollReq - dt or 0 end ---- ---- ---- ---- -- Request roll. -- function Roll:onRqRoll() self.tRollReq = self.rollForgive end -- Event: onRoll -- function Roll:onRoll() self.isRolling = true self.tRollReq = 0 -- reset end -- Event: offRoll -- function Roll:offRoll() self.isRolling = false end return Roll
--[[ Copyright (c) 2009 Edvin "Lego3" Linge Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local disease = {} disease.id = "hairyitis" disease.expertise_id = 3 disease.visuals_id = 1 disease.name = _S.diseases.hairyitis.name disease.cause = _S.diseases.hairyitis.cause disease.symptoms = _S.diseases.hairyitis.symptoms disease.cure = _S.diseases.hairyitis.cure disease.cure_price = 1150 disease.emergency_sound = "emerg008.wav" disease.emergency_number = 12 disease.initPatient = function(patient) patient:setType("Chewbacca Patient") -- NB: Layers have no effect on the appearance until cured, at which point -- they are standard male patient layers. The clinic does however sometimes -- change this so that a female emerge. patient:setLayer(0, math.random(1, 5) * 2) patient:setLayer(1, math.random(0, 3) * 2) patient:setLayer(2, math.random(0, 1) * 2) patient:setLayer(3, 0) patient:setLayer(4, 0) end -- Diagnosis rooms are the rooms other than the GPs office which can be visited -- to aid in diagnosis. The need not be visited, and if they are visited, the -- order in which they are visited is not fixed. disease.diagnosis_rooms = { "x_ray", "scanner", } -- Treatment rooms are the rooms which must be visited, in the given order, to -- cure the disease. disease.treatment_rooms = { "electrolysis", } -- If a machine is required a small icon should appear in the drug casebook. disease.requires_machine = true return disease
slot0 = class("WorldMapCell", import("...BaseEntity")) slot0.Fields = { terrainDir = "number", discovered = "boolean", attachments = "table", fogSairen = "boolean", dir = "number", column = "number", walkable = "boolean", fog = "boolean", row = "number", infov = "number", terrain = "number", inLight = "number", terrainStrong = "number", fogLight = "boolean" } slot0.EventAddAttachment = "WorldMapCell.EventAddAttachment" slot0.EventRemoveAttachment = "WorldMapCell.EventRemoveAttachment" slot0.EventUpdateInFov = "WorldMapCell.EventUpdateInFov" slot0.EventUpdateDiscovered = "WorldMapCell.EventUpdateDiscovered" slot0.EventUpdateFog = "WorldMapCell.EventUpdateFog" slot0.EventUpdateFogImage = "WorldMapCell.EventUpdateFogImage" slot0.EventUpdateTerrain = "WorldMapCell.EventUpdateTerrain" slot0.GetName = function (slot0, slot1) return "cell_" .. slot0 .. "_" .. slot1 end slot0.TerrainNone = 0 slot0.TerrainStream = 1 slot0.TerrainIce = 2 slot0.TerrainWind = 3 slot0.TerrainFog = 4 slot0.TerrainFire = 5 slot0.TerrainPoison = 6 slot0.Build = function (slot0) slot0.attachments = {} slot0.dir = 0 slot0.infov = 0 slot0.inLight = 0 slot0.fog = false slot0.fogLight = false slot0.fogSairen = false end slot0.Setup = function (slot0, slot1) slot0.row = slot1[1] slot0.column = slot1[2] slot0.walkable = slot1[3] end slot0.Dispose = function (slot0) WPool:ReturnArray(slot0.attachments) slot0:Clear() end slot0.AddAttachment = function (slot0, slot1) slot2 = WorldMapAttachment.SortOrder[slot1.type] slot3 = #slot0.attachments + 1 for slot7, slot8 in ipairs(slot0.attachments) do if WorldMapAttachment.SortOrder[slot8.type] < slot2 then slot3 = slot7 break end end table.insert(slot0.attachments, slot3, slot1) slot0:DispatchEvent(slot0.EventAddAttachment, slot1) if not slot0.discovered and slot1:ShouldMarkAsLurk() then slot1:UpdateLurk(true) end end slot0.RemoveAttachment = function (slot0, slot1) if slot1 == nil or type(slot1) == "number" then table.remove(slot0.attachments, slot1 or #slot0.attachments) slot0:DispatchEvent(slot0.EventRemoveAttachment, slot0.attachments[slot1 or #slot0.attachments]) WPool:Return(slot0.attachments[slot1 or #slot0.attachments]) elseif slot1.class == WorldMapAttachment then for slot5 = #slot0.attachments, 1, -1 do if slot0.attachments[slot5] == slot1 then slot0:RemoveAttachment(slot5) break end end end end slot0.ContainsAttachment = function (slot0, slot1) return _.any(slot0.attachments, function (slot0) return slot0 == slot0 end) end slot0.GetInFOV = function (slot0) if slot0.fog then return slot0.fogLight else return slot0.infov > 0 or slot0.inLight > 0 end end slot0.UpdateInFov = function (slot0, slot1) AfterCheck({ { function () return slot0:GetInFOV() end, function () slot0:DispatchEvent(slot1.EventUpdateInFov) end } }, function () slot0.infov = slot1 end) end slot0.ChangeInLight = function (slot0, slot1) AfterCheck({ { function () return slot0:GetInFOV() end, function () slot0:DispatchEvent(slot1.EventUpdateInFov) end } }, function () slot0.inLight = slot1 + ((slot0.inLight and 1) or -1) end) end slot0.InFog = function (slot0) if slot0.fog then return not slot0.fogLight else return slot0:GetTerrain() == slot0.TerrainFog end end slot0.LookSairenFog = function (slot0) return slot0.fogSairen or slot0:IsTerrainSairenFog() end slot0.UpdateFog = function (slot0, slot1, slot2, slot3) AfterCheck({ { function () return slot0:GetInFOV() end, function () slot0:DispatchEvent(slot1.EventUpdateInFov) end }, { function () return slot0:InFog() end, function () slot0:DispatchEvent(slot1.EventUpdateFog) end }, { function () return slot0:LookSairenFog() end, function () slot0:DispatchEvent(slot1.EventUpdateFogImage) end } }, function () slot0.fog = defaultValue(defaultValue, slot0.fog) slot0.fogLight = defaultValue(defaultValue, slot0.fogLight) slot0.fogSairen = defaultValue(slot0.fogLight, slot0.fogSairen) end) end slot0.UpdateDiscovered = function (slot0, slot1) if slot0.discovered ~= slot1 then slot0.discovered = slot1 slot0:DispatchEvent(slot0.EventUpdateDiscovered) end end slot0.GetTerrain = function (slot0) return slot0.terrain or slot0.TerrainNone end slot0.UpdateTerrain = function (slot0, slot1, slot2, slot3) AfterCheck({ { function () return slot0:InFog() end, function () slot0:DispatchEvent(slot1.EventUpdateFog) end }, { function () return slot0:LookSairenFog() end, function () slot0:DispatchEvent(slot1.EventUpdateFogImage) end } }, function () slot0.terrain = slot1 if slot0.terrain == slot2.TerrainStream then slot0.terrainDir = slot3 elseif slot0.terrain == slot2.TerrainWind then slot0.terrainDir = slot3 slot0.terrainStrong = slot4 elseif slot0.terrain == slot2.TerrainFog then slot0.terrainStrong = slot4 elseif slot0.terrain == slot2.TerrainPoison then slot0.terrainStrong = slot4 end slot0:DispatchEvent(slot2.EventUpdateTerrain) end) end slot0.GetAliveAttachments = function (slot0) return _.filter(slot0.attachments, function (slot0) return slot0:IsAlive() end) end slot0.GetAliveAttachment = function (slot0) return _.detect(slot0.attachments, function (slot0) return slot0:IsAlive() end) end slot0.GetDisplayAttachment = function (slot0) return _.detect(slot0.attachments, function (slot0) return slot0:IsAlive() and slot0:IsVisible() end) end slot0.GetInterativeAttachment = function (slot0) return _.detect(slot0.attachments, function (slot0) return WorldMapAttachment.IsInteractiveType(slot0.type) and slot0:IsAlive() and slot0:IsVisible() end) end slot0.GetEventAttachment = function (slot0) return _.detect(slot0.attachments, function (slot0) return slot0:IsAlive() and slot0.type == WorldMapAttachment.TypeEvent end) end slot0.GetCompassAttachment = function (slot0) slot1 = {} for slot5, slot6 in ipairs(slot0.attachments) do table.insert(slot1, slot5) end return _.detect(_.sort(slot1, function (slot0, slot1) return (slot0.attachments[slot0].config.compass_index or 0) > (slot0.attachments[slot1].config.compass_index or 0) end), function (slot0) if slot0.attachments[slot0]:ShouldMarkAsLurk() then return slot1:IsAlive() and slot1:IsVisible() and slot0.discovered elseif slot1.type == WorldMapAttachment.TypeEvent then return slot1:IsAlive() and slot1.config.visuality == 0 elseif slot1.type ~= WorldMapAttachment.TypeFleet and slot1.type ~= WorldMapAttachment.TypePort then return slot1:IsAlive() end end) and slot0.attachments[slot2] end slot0.FindAliveAttachment = function (slot0, slot1) return _.detect(slot0.attachments, function (slot0) return slot0:IsAlive() and slot0.type == slot0 end) end slot0.IsTerrainSairenFog = function (slot0) return slot0.terrain == slot0.TerrainFog and slot0.terrainStrong == 0 end slot0.CanLeave = function (slot0) return slot0.walkable and slot0:GetTerrainObstacleConfig("leave") and underscore.all(slot0.attachments, function (slot0) return not slot0:IsAlive() or slot0:CanLeave() end) end slot0.CanArrive = function (slot0) return slot0.walkable and slot0:GetTerrainObstacleConfig("arrive") and underscore.all(slot0.attachments, function (slot0) return not slot0:IsAlive() or slot0:CanArrive() end) end slot0.CanPass = function (slot0) return slot0.walkable and slot0:GetTerrainObstacleConfig("pass") and underscore.all(slot0.attachments, function (slot0) return not slot0:IsAlive() or slot0:CanPass() end) end slot0.IsSign = function (slot0) return _.any(slot0.attachments, function (slot0) return slot0:IsAlive() and slot0:IsSign() end) end slot0.ExistEnemy = function (slot0) return tobool(slot0:GetStageEnemy()) end slot0.GetStageEnemy = function (slot0) return _.detect(slot0.attachments, function (slot0) return slot0:IsAlive() and WorldMapAttachment.IsEnemyType(slot0.type) end) end slot0.GetDisplayQuad = function (slot0) slot1 = nil slot2 = slot0:GetDisplayAttachment() if not slot0:InFog() and slot2 then if slot2.type == WorldMapAttachment.TypeEvent then if slot2.config.object_icon and #slot3 > 0 then slot1 = slot3 end elseif WorldMapAttachment.IsEnemyType(slot2.type) then slot1 = { "cell_red" } elseif slot2.type == WorldMapAttachment.TypePort or slot2.type == WorldMapAttachment.TypeBox then slot1 = { "cell_yellow" } end end return slot1 end slot0.GetEmotion = function (slot0) return (slot0.terrain == slot0.TerrainPoison and WorldConst.PoisonEffect) or nil end slot0.GetScannerAttachment = function (slot0) slot2, slot3 = nil for slot7, slot8 in ipairs(slot1) do if slot8:IsScannerAttachment() and (not slot2 or slot3 < slot9) then slot2 = slot8 slot3 = slot9 end end return slot2 end slot0.TerrainObstacleConfig = { SairenFog = 4, [slot0.TerrainNone] = 7, [slot0.TerrainStream] = 6, [slot0.TerrainIce] = 6, [slot0.TerrainWind] = 2, [slot0.TerrainFog] = 6, [slot0.TerrainFire] = 7, [slot0.TerrainPoison] = 7 } slot0.GetTerrainObstacleConfig = function (slot0, slot1) return bit.band(slot0.TerrainObstacleConfig[(slot0:IsTerrainSairenFog() and "SairenFog") or slot0:GetTerrain()], WorldConst.GetObstacleKey(slot1)) > 0 end slot0.IsMovingTerrain = function (slot0) return slot0 == slot0.TerrainStream or slot0 == slot0.TerrainIce or slot0 == slot0.TerrainWind end return slot0
vacationHome = { type = "destructible", buildingTemplate = "object/building/military/pirate_warehouse.iff", terminal = { template = "object/tangible/terminal/terminal_destructible_building.iff", vectorCellID = 3, x = 0, z = 0.3, y = -6.0 }, childNpcs = { { npcTemplate = "giant_gubbur", npcName = "Faswald's Pet", vectorCellID = 3, x = 0, z = 0.3, y = -3.0 } } } venthan_chassu_missions = { { missionType = "destroy", buildingSpawn = vacationHome, primarySpawns = { { npcTemplate = "r5", npcName = "" } }, secondarySpawns = { }, { }, rewards = { { rewardType = "credits", amount = 250 } } }, { missionType = "assassinate", primarySpawns = { { npcTemplate = "critic_quest_venthan", npcName = "Faswald Vorsuble" } }, secondarySpawns = { { npcTemplate = "bodyguard", npcName = "" } }, itemSpawns = { }, rewards = { { rewardType = "credits", amount = 500 } } } } npcMapVenthanChassu = { { spawnData = { npcTemplate = "venthan_chassu", x = -6.4, z = -0.9, y = -20.0, direction = -9, cellID = 3005702, position = STAND }, npcNumber = 1, worldPosition = { x = -5219, y = -6433 }, stfFile = "@static_npc/corellia/venthan_chassu", missions = venthan_chassu_missions }, } VenthanChassu = ThemeParkLogic:new { npcMap = npcMapVenthanChassu, className = "VenthanChassu", screenPlayState = "venthan_chassu_quest", planetName = "corellia", distance = 300, } registerScreenPlay("VenthanChassu", true) venthan_chassu_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = VenthanChassu } venthan_chassu_mission_target_conv_handler = mission_target_conv_handler:new { themePark = VenthanChassu }
-- импорт оформлений для Awesom'a require'themes' -- правила хоткеев require'core/root/bindings' -- импорт основных виджетов require'core/widgets' -- разделители и прочие элементы оформления require'core/behavior/separators' -- по-умолчанию используем обычный вариант тегов if not _Awesome.switches.system.tags then require("core.root.tags_fallback") end -- генерируем основное меню на основе бла-бла-бла ;-) local mymainmenu, mylauncher = generateMenu() -- {{{ дополнительная проверка -- do -- local in_error = false -- awesome.connect_signal( -- "debug::error", -- function (err) -- -- если есть ошибка -- if in_error -- then -- return -- end -- -- включаем вывод -- in_error = true -- -- выводим подробную/известную информацию -- _Awesome.notify.errors(err) -- -- выключаем вывод -- in_error = false -- end -- ) -- end -- }}} require'core/root/tasklist' -- Java GUI's fix _Awesome.awful.util.spawn_with_shell("wmname LG3D") -- {{{ Wibox initialisation _Awesome._wibox.top = {} _Awesome._wibox.bottom = {} _Awesome._wibox.tag = {} -- ни в коем разе никак не локальная переменная mypromptbox = {} local mylayoutbox = {} local _tagList = {} _tagList.buttons = _Awesome.awful.util.table.join( _Awesome.awful.button( { }, 1, _Awesome.awful.tag.viewonly ), _Awesome.awful.button( { modkey }, 1, _Awesome.awful.client.movetotag ), _Awesome.awful.button( { }, 3, _Awesome.awful.tag.viewtoggle ), _Awesome.awful.button( { modkey }, 3, _Awesome.awful.client.toggletag ), _Awesome.awful.button( { }, 4, function(t) _Awesome.awful.tag.viewnext(_Awesome.awful.tag.getscreen(t)) end ), _Awesome.awful.button( { }, 5, function(t) _Awesome.awful.tag.viewprev(_Awesome.awful.tag.getscreen(t)) end ) ) for s = 1, screen.count() do mypromptbox[s] = _Awesome.awful.widget.prompt() -- icon indicating which layout we're using mylayoutbox[s] = _Awesome.awful.widget.layoutbox(s) mylayoutbox[s]:buttons( _Awesome.awful.util.table.join( _Awesome.awful.button( { }, 1, function () _Awesome.awful.layout.inc(_Awesome.awful.layout.layouts, 1) end ), _Awesome.awful.button( { }, 3, function () _Awesome.awful.layout.inc(_Awesome.awful.layout.layouts, -1) end ), _Awesome.awful.button( { }, 4, function () _Awesome.awful.layout.inc(_Awesome.awful.layout.layouts, 1) end ), _Awesome.awful.button( { }, 5, function () _Awesome.awful.layout.inc(_Awesome.awful.layout.layouts, -1) end ) ) ) local tagsh = 3 _tagList[s] = _Awesome.awful.widget.taglist( s, _Awesome.awful.widget.taglist.filter.all, _tagList.buttons ) mytasklist[s] = _Awesome.awful.widget.tasklist( s, _Awesome.awful.widget.tasklist.filter.currenttags, mytasklist.buttons ) if _Awesome.switches.panels.top then _Awesome._wibox.top[s] = _Awesome.awful.wibox( { position = "top", screen = s, border_width = _Awesome.beautiful.border_width, height = 22 } ) end -- Widgets that are aligned to the left local left_layout = _Awesome.wibox.layout.fixed.horizontal() -- Widgets that are aligned to the right local right_layout = _Awesome.wibox.layout.fixed.horizontal() --- }}} left_layout:add(_spr) left_layout:add(_tagList[s]) left_layout:add(mypromptbox[s]) left_layout:add(_spr) if s == 1 then right_layout:add(_Awesome.wibox.widget.systray()) end -- если разрешено отображаем виджеты if _Awesome.switches.system.widgets then right_layout:add(_spr) right_layout:add(arrl) -- отображаем все виджеты, независимо от того, -- включен тот или иной, в том случае если включены две панели if _Awesome.switches.panels.top and _Awesome.switches.panels.bottom then -- если разрешен отображаем if _Awesome.switches.widgets.network then right_layout:add(netdownicon) right_layout:add(netdowninfo) right_layout:add(netupicon) right_layout:add(netupinfo) end if _Awesome.switches.widgets.volume then right_layout:add(volicon) right_layout:add(volumewidget) end if _Awesome.switches.widgets.memmory then right_layout:add(memicon) right_layout:add(memwidget) end if _Awesome.switches.widgets.cpuinfo then right_layout:add(cpuicon) right_layout:add(cpuwidget) end if _Awesome.switches.widgets.temperature_cpu then right_layout:add(tempicon) right_layout:add(tempwidget) end if _Awesome.switches.widgets.filesysteminfo then right_layout:add(fsicon) right_layout:add(fswidget) end end -- если нижняя панель отключена if not _Awesome.switches.panels.bottom then right_layout:add(mylayoutbox[s]) end end --- }}} -- если одна из панелей отключена или отключены виджеты, -- отображаем минимум виджетов if _Awesome.switches.widgets.battery then right_layout:add(baticon) right_layout:add(batwidget) end if _Awesome.switches.widgets.clock then right_layout:add(widget_clock) right_layout:add(clockwidget) end -- Now bring it all together (with the tasklist in the middle) if _Awesome.switches.panels.top then local layout = _Awesome.wibox.layout.align.horizontal() layout:set_left(left_layout) -- если нижняя панель отключена if not _Awesome.switches.panels.bottom then layout:set_middle(mytasklist[s]) end layout:set_right(right_layout) _Awesome._wibox.top[s]:set_widget(layout) end -- если нижняя панель включена if _Awesome.switches.panels.bottom then -- Create the bottom wibox _Awesome._wibox.bottom[s] = _Awesome.awful.wibox( { position = "bottom", screen = s, border_width = _Awesome.beautiful.border_width, height = 20 } ) -- Widgets that are aligned to the bottom left bottom_left_layout = _Awesome.wibox.layout.fixed.horizontal() -- если верхняя панель отключена if not _Awesome.switches.panels.top then bottom_left_layout:add(left_layout) end -- Widgets that are aligned to the bottom right bottom_right_layout = _Awesome.wibox.layout.fixed.horizontal() -- если верхняя панель отключена if not _Awesome.switches.panels.top then bottom_right_layout:add(right_layout) end bottom_right_layout:add(mylayoutbox[s]) -- Now bring it all together (with the tasklist in the middle) bottom_layout = _Awesome.wibox.layout.align.horizontal() bottom_layout:set_left(bottom_left_layout) bottom_layout:set_middle(mytasklist[s]) bottom_layout:set_right(bottom_right_layout) _Awesome._wibox.bottom[s]:set_bg(_Awesome.beautiful.bg_normal) _Awesome._wibox.bottom[s]:set_widget(bottom_layout) end end -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal( "manage", function (c) c:connect_signal( "mouse::enter", function(c) if _Awesome.awful.layout.get(c.screen) ~= _Awesome.awful.layout.suit.magnifier and _Awesome.awful.client.focus.filter(c) then client.focus = c end end ) if not startup then if not c.size_hints.user_position and not c.size_hints.program_position then _Awesome.awful.placement.no_overlap(c) _Awesome.awful.placement.no_offscreen(c) end end if not awesome.startup then -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- _Awesome.awful.client.setslave(c) -- Put windows in a smart way, only if they does not set an initial position. if not c.size_hints.user_position and not c.size_hints.program_position then _Awesome.awful.placement.no_overlap(c) _Awesome.awful.placement.no_offscreen(c) end end end ) -- }}} -- {{{ Enable sloppy focus client.connect_signal( "mouse::enter", function(c) if _Awesome.awful.layout.get(c.screen) ~= _Awesome.awful.layout.suit.magnifier and _Awesome.awful.client.focus.filter(c) then client.focus = c end end ) client.connect_signal( "focus", function(c) c.border_color = _Awesome.beautiful.border_focus end ) client.connect_signal( "unfocus", function(c) c.border_color = _Awesome.beautiful.border_normal end ) -- }}} -- {{{ Default static wall if _Awesome.beautiful.wallpaper then for s = 1,screen.count() do _Awesome.gears.wallpaper.maximized(_Awesome.beautiful.wallpaper, s, true) end end -- }}}
local env=env local write local system=env.class(env.scripter) function system:ctor() self.process=nil self.proc=java.require("org.dbcli.SubSystem") self.prompt_pattern="^.+[>\\$#@:] *$" self.support_redirect=true end function system:kill_reader(cmds) if not self.reader then return end if cmds[1]:upper()==self.name:upper() then return end self.reader:kill() self.reader=nil end function system:get_last_line(cmd) if not self.process then return end local done,msg=pcall(self.process.getLastLine,self.process,cmd) if self.process:isClosed() then self:terminate() end env.checkerr(done,msg or '') return self.process~=nil and msg or nil end function system:get_lines(cmd,interval,count,prep) if not self.process then return end interval,count=tonumber(interval),tonumber(count) if interval and count then return self.process:getLinesInterval(cmd,math.ceil(interval),math.ceil(count),prep) else return self.process:getLines(cmd) end end function system:run_command(cmd,is_print,interval,count,prep) if not self.process then return end interval,count=tonumber(interval),tonumber(count) local done,msg if interval and count then done,msg=pcall(self.process.executeInterval,self.process,cmd,math.ceil(interval),math.ceil(count),is_print and true or false,prep) else done,msg=pcall(self.process.execute,self.process,cmd,is_print and true or false,self.block_input or false) end if self.process:isClosed() then self:terminate() end env.checkerr(done,msg or '') if self.process==nil then return end self.prompt=msg if self.enter_flag==true then env.set_subsystem(self.name,self.prompt) end end function system:terminate() if not self.process then return end self.process:close() self.process,self.enter_flag,self.startup_cmd=nil,nil,nil print("Sub-system '"..self.name.."' is terminated.") return env.set_subsystem(nil) end function system:set_work_dir(path,quiet) if path=="" then return print("Current working dir is "..self.work_dir) end path=path=="." and env._CACHE_PATH or path path=env.join_path(path,"") env.checkerr(os.exists(path)=='directory',"No such folder: %s!",path) self.work_dir=path if not quiet then print("Working dir changed to "..path) end if not self.process then return end end function system:list_work_dir(filter) os.execute((env.IS_WINDOWS and ('dir "'..self.work_dir..'" /B/S/A:-D ') or ('find "'..self.work_dir..'" -type f'))..(filter or "")) end function system:make_native_command(arg) local is_win=env.IS_WINDOWS local env,cmd={},{} local function enclose(s) return tostring(s):find("%s") and ('"'..s..'"') or s end env[#env+1]=(is_win and 'cd /d ' or 'cd ')..enclose(self.work_dir) for i,v in ipairs(self.startup_cmd) do cmd[#cmd+1]=enclose(v) end for i,v in ipairs(arg) do cmd[#cmd+1]=enclose(v) end env[#env+1]=table.concat(cmd," ") cmd=table.concat(env,is_win and ' & ' or " ; ") return cmd end function system:call_process(cmd,is_native) if cmd=='\1' then cmd='' end if not self.process or is_native==true then local args=env.parse_args(99,cmd or "") or {} for i=1,#args do local k=args[1]:upper() if k:sub(1,1)~='-' then break end if k=="-N" then is_native=true table.remove(args,1) elseif k:find("^%-D") then self.work_dir=args[1]:sub(3):gsub('"','') table.remove(args,1) end end for i=#args,1,-1 do if args[i]:trim() =='' then table.remove(args,i) end end self.env={} if not self.work_dir then self.work_dir=self.extend_dirs or self.script_dir or env._CACHE_PATH end local do_redirect=false if not self.process or not is_native then local boot_cmd=self.boot_cmd if not boot_cmd then boot_cmd=self.executable or self.name boot_cmd=type(boot_cmd)=='table' and boot_cmd or {boot_cmd} for i,cmd in ipairs(boot_cmd) do if env.IS_WINDOWS and not cmd:find('.',1,true) then boot_cmd[i]=cmd..'.exe' end end boot_cmd=os.find_extension(boot_cmd) self.boot_cmd=boot_cmd end self.startup_cmd,do_redirect=self:get_startup_cmd(args,is_native) if #args>0 then is_native = true end if not self.startup_cmd then return end table.insert(self.startup_cmd,1,boot_cmd) self:set_work_dir(self.work_dir,true) env.log_debug("subsystem","Command : " ..table.concat(self.startup_cmd," ")) env.log_debug("subsystem","Work dir: "..self.work_dir) env.log_debug("subsystem","Environment: \n"..table.dump(self.env)) end if (do_redirect or not is_native) and self.support_redirect or (is_native and not self.support_redirect) then --print(table.concat(self.startup_cmd," ")) if not self.process then env.printer.write("Connecting to "..self.name.."...") self.startup_cmd[1]=self.startup_cmd[1]:gsub('\\','\\\\') self.process=self.proc:create(self.prompt_pattern,self.work_dir,self.startup_cmd,self.env) self.msg_stack={} self:run_command(nil,false) env.printer.write("$DELLINE$") if not self.process then return end if self.after_process_created then self:after_process_created() end end if #args==0 then cmd=nil else cmd=table.concat(args," ") end else local line=self:make_native_command(args) local env1={} env.log_debug("subsystem","SQL: "..line) for k,v in pairs(self.env) do env1[k]=os.getenv(k) or "" env.uv.os.setenv(k,v) end terminal:echo(true) terminal:pause() pcall(os.execute,line) terminal:resume() for k,v in pairs(env1) do if v~="" then env.uv.os.setenv(k,v) else env.uv.os.unsetenv(k) end end return end end if not self.process then return end if not cmd then env.set_subsystem(self.name,self.prompt) self.enter_flag=true local help=[[ You are entering '%s' interactive mode, working dir is '%s'. To switch to the native CLI mode, execute '-n' or '.%s -n'. Type 'lls' to list the files in current working dir, to change the working dir, execute 'lcd <path>'. Type '.<cmd>' to run the root command, 'bye' to leave, or 'exit' to terminate.]] help=help:format(self.name,self.work_dir,self.name):gsub("%s%s%s+",'\n'):gsub("^%s+","") print(env.ansi.mask("PromptColor",help)) env.set_subsystem(self.name,self.prompt) return end local command=cmd:upper():gsub("^%s+","") if command=='BYE' then self.enter_flag=false return env.set_subsystem(nil) elseif command:find("^%-N") then return self:call_process(cmd,true) elseif command:find("^LLS ") or command=="LLS" then return self:list_work_dir(cmd:sub(5)) elseif command:find("^LCD ") or command=="LCD" then return self:set_work_dir(cmd:sub(5)) elseif command=='EXIT' then return self:terminate() end self.enter_flag=true self:run_command(cmd,true) end function system:__onload() self.sleep=env.sleep write=env.printer.write env.set_command{obj=self,cmd=self.name, help_func=self.description, call_func=self.call_process, is_multiline=false,parameters=2,color="PROMPTSUBCOLOR", is_blocknewline=false} env.event.snoop("BEFORE_COMMAND",self.kill_reader,self,1) end function system:onunload() self:terminate() end system.finalize='N/A' return system
include "layerLayout"; local fontSlant; -------------------------------------------------- -- Textures -------------------------------------- -------------------------------------------------- local textures = { noise = { }, numbers = { }, gauge = { effective = { }, excessive = { }, }, }; -------------------------------------------------- function theori.layer.doAsyncLoad() for i = 0, 9 do textures.numbers[i] = theori.graphics.queueTextureLoad("combo/" .. i); end for i = 0, 9 do textures.noise[i] = theori.graphics.queueTextureLoad("noise/" .. i); end textures.gauge.ratebg = theori.graphics.queueTextureLoad("game/gauge/rate_bg"); textures.gauge.effective.background = theori.graphics.queueTextureLoad("game/gauge/gauge_back_eff"); textures.gauge.effective.fillNormal = theori.graphics.queueTextureLoad("game/gauge/fill_normal_eff"); textures.gauge.effective.fillPass = theori.graphics.queueTextureLoad("game/gauge/fill_pass_eff"); textures.gauge.effective.outline = theori.graphics.queueTextureLoad("game/gauge/anim_outline_gauge_eff"); return true; end function theori.layer.doAsyncFinalize() return true; end function theori.layer.onClientSizeChanged(w, h) Layout.CalculateLayout(); end function theori.layer.init() fontSlant = theori.graphics.getStaticFont("slant"); theori.graphics.openCurtain(); end function theori.layer.update(delta, total) local w, h = LayoutWidth, LayoutHeight; Layout.Update(delta, total); end function theori.layer.render() Layout.CheckLayout(); Layout.DoTransform(); Layout.Render(); end local function renderScoreSpriteNum(x, y, w, r, g, b, a) local num = scoring.score; local dig = 8; local digTextures = { }; for i = dig, 1, -1 do local tento, tentom1 = math.pow(10, i), math.pow(10, i - 1); local tex = textures.numbers[math.floor((num % tento) / tentom1)]; table.insert(digTextures, tex); end local scaleFactor = 0.8; local scaleRatio = 1 / (2 * scaleFactor); local xPos = x; for i, texture in next, digTextures do local s; if (i <= 4) then s = w * scaleRatio / 4; else s = (w - (w * scaleRatio)) / 4; end theori.graphics.setFillToTexture(texture, r, g, b, a); theori.graphics.fillRect(xPos, y - s, s, s); xPos = xPos + s; end end -- Landscape Layout local function renderJacketPanel(x, y, w) local h = w * 0.5; -- values local margin = h * 0.05; local rounding = margin; local jacketSize = h * 0.8 - 2 * margin; local diffHeight = h - 3 * margin - jacketSize; local trackNumTotalHeight = h * 0.425; local gameInfoTotalHeight = h * 0.425; local progressWidth = w - 2 * margin - jacketSize; local progressHeight = h - trackNumTotalHeight - gameInfoTotalHeight; -- jacket/diff panel background theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.fillRoundedRectVarying(x, y, jacketSize + 2 * margin, h, 0, 0, rounding, rounding); -- track label background theori.graphics.fillRoundedRectVarying(x + jacketSize + 2 * margin, y, progressWidth, trackNumTotalHeight + progressHeight, 0, rounding, rounding, 0); -- jacket local jacketTexture = game.chart.getJacketTexture(); if (jacketTexture) then theori.graphics.setFillToTexture(jacketTexture, 255, 255, 255, 255); else theori.graphics.setFillToColor(0, 0, 0, 200); end theori.graphics.fillRoundedRectVarying(x + margin, x + margin, jacketSize, jacketSize, 0, rounding, 0, 0); -- diff frame theori.graphics.setFillToColor(0, 10, 40, 255); theori.graphics.fillRoundedRectVarying(x + margin, y + 2 * margin + jacketSize, jacketSize, diffHeight, 0, 0, rounding, rounding); -- progress bar frame theori.graphics.setFillToColor(255, 0, 200, 255); theori.graphics.fillRoundedRect(x + 3 * margin + jacketSize, y + trackNumTotalHeight + progressHeight / 4, progressWidth - 2 * margin, progressHeight / 2, progressHeight / 4); -- progress bar fill local progressBubbleSize = progressHeight / 4; local progressCenter = progressBubbleSize / 2 + x + 3 * margin + jacketSize + (progressWidth - 2 * margin - progressBubbleSize) * game.progress; theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.fillRect(x + 3 * margin + jacketSize + progressBubbleSize / 2, y + trackNumTotalHeight + progressHeight / 2 - 1, progressWidth - progressBubbleSize - 2 * margin, 2); theori.graphics.fillRoundedRect(progressCenter - progressBubbleSize * 0.5, y + trackNumTotalHeight + progressHeight / 2 - progressBubbleSize * 0.5, progressBubbleSize, progressBubbleSize, progressBubbleSize / 2); -- "Track N" theori.graphics.setFillToColor(0, 0, 0, 255); theori.graphics.setFont(fontSlant); theori.graphics.setFontSize(trackNumTotalHeight * 0.75); theori.graphics.setTextAlign(Anchor.BottomLeft); theori.graphics.fillString("Track", x + 2 * margin + jacketSize, y + trackNumTotalHeight); local trackTextWidth, _ = theori.graphics.measureString("Track "); theori.graphics.setFontSize(trackNumTotalHeight * 0.85); theori.graphics.fillString("Ex", x + 2 * margin + jacketSize + trackTextWidth, y + trackNumTotalHeight); -- game info text local textSpace = w - 2 * margin - jacketSize; theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.setFont(fontSlant); theori.graphics.setFontSize((gameInfoTotalHeight / 2) * 0.75); theori.graphics.setTextAlign(Anchor.BottomRight); theori.graphics.fillString("BPM", x + 2 * margin + jacketSize + textSpace * 0.6, y + trackNumTotalHeight + progressHeight + gameInfoTotalHeight / 2); theori.graphics.fillString("HI-SPEED", x + 2 * margin + jacketSize + textSpace * 0.6, y + trackNumTotalHeight + progressHeight + gameInfoTotalHeight * 0.95); theori.graphics.setTextAlign(Anchor.BottomLeft); theori.graphics.fillString(tostring(math.floor(game.bpm)), x + 2 * margin + jacketSize + textSpace * 0.7, y + trackNumTotalHeight + progressHeight + gameInfoTotalHeight / 2); theori.graphics.fillString(string.format("%.1f", game.hispeed), x + 2 * margin + jacketSize + textSpace * 0.7, y + trackNumTotalHeight + progressHeight + gameInfoTotalHeight * 0.95); end local function renderScorePanel(x, y, w) local h = w * 0.5; local margin = h * 0.05; local rounding = margin; local scoreHeight = h * 2 / 3; local chainHeight = h - scoreHeight; -- score background theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.fillRoundedRectVarying(x, y, w, scoreHeight, 0, 0, rounding, rounding); -- score label theori.graphics.setFillToColor(0, 0, 0, 255); theori.graphics.setFont(fontSlant); theori.graphics.setFontSize(scoreHeight * 0.4); theori.graphics.setTextAlign(Anchor.BottomLeft); theori.graphics.fillString("score", x + margin, y + scoreHeight * 0.4); -- score display renderScoreSpriteNum(x + margin, y + scoreHeight - margin, w - 2 * margin, 0, 0, 0, 255); -- max combo display theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.setFont(fontSlant); theori.graphics.setTextAlign(Anchor.TopLeft); theori.graphics.setFontSize(chainHeight * 0.55); theori.graphics.fillString("MAXIMUM CHAIN", x + w * 0.3, y + scoreHeight * 0.95); theori.graphics.setTextAlign(Anchor.TopRight); theori.graphics.fillString("9999", x + w * 0.25, y + scoreHeight * 0.95); end local function renderGauge(x, y, h) local gaugeAspect = textures.gauge.effective.background.aspectRatio; local gaugeTransitionPoint = 0.7; local w = h * gaugeAspect; x, y = x - w / 2, y - h / 2; local gy = y + h * (18 / 362); local gh = h * (328 / 362); -- bg theori.graphics.setFillToTexture(textures.gauge.effective.background, 255, 255, 255, 255); theori.graphics.fillRect(x, y, w, h); -- fill theori.graphics.saveScissor(); theori.graphics.scissor(x * LayoutScale, (gy + gh * (1 - scoring.gauge)) * LayoutScale, w * LayoutScale, (gh * scoring.gauge) * LayoutScale); if (scoring.gauge < gaugeTransitionPoint) then theori.graphics.setFillToTexture(textures.gauge.effective.fillNormal, 255, 255, 255, 255); else theori.graphics.setFillToTexture(textures.gauge.effective.fillPass, 255, 255, 255, 255); end theori.graphics.fillRect(x, y, w, h); theori.graphics.restoreScissor(); -- outline theori.graphics.setFillToTexture(textures.gauge.effective.outline, 255, 255, 255, 255); theori.graphics.fillRect(x, y, w, h); -- rate local rateAspect = textures.gauge.ratebg.aspectRatio; local rateW = w * 0.9; local rateH = rateW / rateAspect; local rateX, rateY = x - rateW * 0.8, gy + gh * (1 - scoring.gauge) - rateH / 2; theori.graphics.setFillToTexture(textures.gauge.ratebg, 255, 255, 255, 255); theori.graphics.fillRect(rateX, rateY, rateW, rateH); -- rate text theori.graphics.setFillToColor(255, 255, 255, 255); theori.graphics.setFont(nil); theori.graphics.setFontSize(rateH * 0.6); theori.graphics.setTextAlign(Anchor.MiddleRight); theori.graphics.fillString(tostring(math.floor(scoring.gauge * 100 + 0.5)), rateX + rateW * 0.65, rateY + rateH * 0.425); end function Layouts.Landscape.Render(self) local w, h = LayoutWidth, LayoutHeight; renderJacketPanel(0, 0, w * 0.2); renderScorePanel(w * 0.8, 0, w * 0.2); renderGauge(w * 0.75, h / 2, h * 0.55); end -- Wide Landscape Layout function Layouts.WideLandscape.Render(self) Layouts.Landscape:Render(); end -- Portrait Layout function Layouts.Portrait.Render(self) end -- Tall Portrait Layout function Layouts.TallPortrait.Render(self) Layouts.Portrait:Render(); end
local T, C, L = Tukui:unpack() local DataTexts = T.DataTexts ---------------------------------------------------------------- -- DataTexts ---------------------------------------------------------------- function DataTexts:AddDefaults() local Name = UnitName("player") local Realm = GetRealmName() TukuiDatabase.Variables[Realm][Name].DataTexts = {} TukuiDatabase.Variables[Realm][Name].DataTexts["Guild"] = { true, 1 } TukuiDatabase.Variables[Realm][Name].DataTexts["Character"] = { true, 2 } TukuiDatabase.Variables[Realm][Name].DataTexts["System"] = { true, 3 } TukuiDatabase.Variables[Realm][Name].DataTexts["Friends"] = { true, 4 } TukuiDatabase.Variables[Realm][Name].DataTexts["MicroMenu"] = { true, 5 } TukuiDatabase.Variables[Realm][Name].DataTexts["Gold"] = { true, 6 } TukuiDatabase.Variables[Realm][Name].DataTexts["Time"] = { true, 7 } end --[[ local baseEnable = DataTexts.Enable function DataTexts:Enable() -- first, we call the base function baseEnable(self) -- second, we edit it local DataTextLeft = self.Panels.Left local DataTextRight = self.Panels.Right local Padding = C.Chat.Padding + C.Lua.ScreenMargin DataTextLeft:ClearAllPoints() DataTextLeft:SetWidth(C.General.Themes.Value == "Tukui" and C.Chat.LeftWidth or 370) DataTextLeft:SetHeight(23) DataTextLeft:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", Padding, Padding) DataTextLeft:CreateBackdrop("Transparent") DataTextLeft:SetFrameStrata("BACKGROUND") DataTextLeft:SetFrameLevel(2) DataTextRight:ClearAllPoints() DataTextRight:SetWidth(C.General.Themes.Value == "Tukui" and C.Chat.RightWidth or 370) DataTextRight:SetHeight(23) DataTextRight:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -Padding, Padding) DataTextRight:CreateBackdrop("Transparent") DataTextRight:SetFrameStrata("BACKGROUND") DataTextRight:SetFrameLevel(2) end local RemoveData = function(self) if self.Data then self.Data.Position = 0 self.Data:Disable() end self.Data = nil end local SetData = function(self, object) -- Disable the old data text in use if self.Data then RemoveData(self) end local Panels = T.DataTexts.Panels -- Set the new data text self.Data = object self.Data:Enable() if (C.DataTexts.Font == "Pixel") then self.Data.Text:SetPoint("RIGHT", self, 0, 0) self.Data.Text:SetPoint("LEFT", self, 3, 0) self.Data.Text:SetPoint("TOP", self, 0, 0) self.Data.Text:SetPoint("BOTTOM", self, 0, 2) else self.Data.Text:SetPoint("RIGHT", self, 0, 0) self.Data.Text:SetPoint("LEFT", self, 0, 0) self.Data.Text:SetPoint("TOP", self, 0, -1) self.Data.Text:SetPoint("BOTTOM", self, 0, -1) end self.Data.Position = self.Num self.Data:SetAllPoints(self.Data.Text) if (Panels.Left and self.Data.Position >= 1 and self.Data.Position <= 3) then self.Data:SetParent(Panels.Left) elseif (Panels.Right and self.Data.Position >= 4 and self.Data.Position <= 6) then self.Data:SetParent(Panels.Right) elseif (Panels.Minimap and self.Data.Position == 7) then self.Data:SetParent(Panels.Minimap) end end function DataTexts:CreateAnchors() local DataTextLeft = DataTexts.Panels.Left local DataTextRight = DataTexts.Panels.Right local MinimapDataText = DataTexts.Panels.Minimap if (MinimapDataText) then self.NumAnchors = self.NumAnchors + 1 end local Spacing = 1 -- space between datatext frames local Number = 3 -- number of datatext per panel -- calcute frame size which devide a panel into n-equal parts. -- delta is the error between new width and referential width. local Size, Delta = T.EqualSizes(DataTextRight:GetWidth() - 2, Number, Spacing) for i = 1, self.NumAnchors do local Frame = CreateFrame("Button", nil, UIParent) Frame:SetHeight(DataTextLeft:GetHeight() - 2) Frame:SetFrameLevel(DataTextLeft:GetFrameLevel() + 1) Frame:SetFrameStrata("HIGH") Frame:EnableMouse(false) Frame.SetData = SetData Frame.RemoveData = RemoveData Frame.Num = i -- calculate datatext position in the datatext panel local pos = ((i > 3) and (i < 7)) and i - 3 or i -- if datatext position is less than deviation, increment width by 1 pixel if ((i < 7) and (Delta > 0) and (pos <= Delta)) then Frame:SetWidth(Size + 1) else Frame:SetWidth(Size) end Frame.Tex = Frame:CreateTexture() Frame.Tex:SetAllPoints() Frame.Tex:SetColorTexture(0.2, 1, 0.2, 0) self.Anchors[i] = Frame if (i == 1) then Frame:SetPoint("LEFT", DataTextLeft, "LEFT", 1, 0) elseif (i == 4) then Frame:SetPoint("LEFT", DataTextRight, "LEFT", 1, 0) elseif (i == 7) then Frame:SetPoint("CENTER", MinimapDataText, "CENTER", 0, 0) Frame:SetWidth(MinimapDataText:GetWidth() - 2) Frame:SetHeight(MinimapDataText:GetHeight() - 2) else Frame:SetPoint("LEFT", self.Anchors[i-1], "RIGHT", 1, 0) end end end -- local GetTooltipAnchor = function(self) -- local Position = self.Position -- local MinimapDataText = DataTexts.Panels.Minimap -- local From -- local Anchor = "ANCHOR_TOP" -- local X = 0 -- local Y = 16 -- if ((Position >= 1) and (Position <= 3)) then -- X = -1 -- Anchor = "ANCHOR_TOPLEFT" -- From = Chat.Panels.LeftChat -- elseif ((Position >= 4) and (Position <= 6)) then -- X = 1 -- Anchor = "ANCHOR_TOPRIGHT" -- From = Chat.Panels.RightChat -- elseif ((Position == 7) and MinimapDataText) then -- Anchor = "ANCHOR_BOTTOMLEFT" -- Y = -5 -- From = MinimapDataText -- end -- return From, Anchor, X, Y -- end -- -- Update Anchor -- for Name, DataText in pairs(DataTexts.Texts) do -- if (DataText.GetTooltipAnchor) then -- DataText.GetTooltipAnchor = GetTooltipAnchor -- end -- end ]]--
local glassBlockAreaController = {} glassBlockAreaController.name = "MaxHelpingHand/CustomizableGlassBlockAreaController" glassBlockAreaController.fillColor = {0.4, 0.4, 1.0, 0.4} glassBlockAreaController.borderColor = {0.4, 0.4, 1.0, 1.0} glassBlockAreaController.placements = { name = "field", data = { width = 8, height = 8, starColors = "ff7777,77ff77,7777ff,ff77ff,77ffff,ffff77", bgColor = "302040", wavy = false } } glassBlockAreaController.fieldInformation = { bgColor = { fieldType = "color" } } return glassBlockAreaController
local config = { broadcast = false } function onSay(cid, words, param, channel) if(param == '') then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command param required.") return true end local t = string.explode(param, ",", 1) local pid = getPlayerByNameWildcard(t[1]) if(not pid) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Player " .. t[1] .. " not found.") return true end if(getPlayerAccess(pid) >= getPlayerAccess(cid)) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Cannot perform action.") return true end local g, group = 1, getPlayerGroupId(pid) if(words:sub(2, 2) == "d") then g = -1 end local newGroup = group + g if(t[2] ~= nil) then for i, id in ipairs(getGroupList()) do local tmp = getGroupInfo(id) if(isInArray({tmp.id, tmp.name}, t[2])) then newGroup = id break end end end if(newGroup <= 0 or newGroup == group or not setPlayerGroupId(pid, newGroup)) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Cannot perform action.") return true end local str = "been " .. (group < newGroup and "promoted" or "demoted") .. " to " .. getGroupInfo(newGroup).name .. "." if(not config.broadcast) then doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, param .. " has " .. str) else doBroadcastMessage(param .. " has " .. str, MESSAGE_EVENT_ADVANCE) end doPlayerSendTextMessage(pid, MESSAGE_EVENT_ADVANCE, "You have " .. str) return true end
local config = require'lspconfig'.rust_analyzer.document_config require'lspconfig/configs'.rust_analyzer = nil -- important, immediately unset the loaded config again config.default_config.cmd[1] = "./rust-analyzer" return vim.tbl_extend('error', config, { -- adjusted from https://github.com/mattn/vim-lsp-settings/blob/master/installer/install-rust-analyzer.sh install_script = [[ os=$(uname -s | tr "[:upper:]" "[:lower:]") case $os in linux) platform="linux" ;; darwin) platform="mac" ;; esac curl -L -o "rust-analyzer-$platform" "https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-$platform" mv rust-analyzer-$platform rust-analyzer chmod +x rust-analyzer ]] })
local HooI return function(lib) HooI = lib local ClickableComponent = HooI.component.create("ClickableComponent") function ClickableComponent:initialize(...) HooI.initComponent(self, { {name = "executedCallback", varType = "function", default = function() print("click") end}, {name = "layer", varType = "number", default = 1}, {name = "dx", varType = "number", default = 0}, {name = "dy", varType = "number", default = 0}, {name = "dw", varType = "number", default = 0}, {name = "dh", varType = "number", default = 0}, }, ...) self.pressed = false end return ClickableComponent end
DefineClass.StorageDepot = { __parents = { "Building", "ResourceStockpileBase", "ShuttleLanding", "AutoTransportStateUIProps", }, game_flags = { gofPermanent = true }, properties = { -- add dont_save specifically for this class, as it has a Get function { template = true, name = T{765, "Pin Rollover"}, id = "pin_rollover", category = "Pin", editor = "text", default = "", translate = true, dont_save = true}, { template = true, category = "Demolish", name = T{175, "Use demolished state?"}, id = "use_demolished_state", editor = "bool", default = false, object_update = true }, { template = true, category = "Storage Space", name = T{8054, "Ignored by shuttles"}, id = "exclude_from_lr_transportation", editor = "bool", default = false }, }, entity = false, description = false, display_name = false, GetDisplayName = Building.GetDisplayName, max_x = 12, max_y = 5, max_z = 5, spacing_x = 13*guic, spacing_y = 16*guic, spacing_z = 1*guic, demand = false, supply = false, has_demand_request = false, has_supply_request = false, GetShapePoints = GridObject.GetShapePoints, auto_transportation_state = "Auto", --Storage depots do not accumulate dust (bug:0118697) accumulate_dust = false, maintenance_resource_type = "no_maintenance", --doesnt require maintenance. accumulate_maintenance_points = false, landing_spot_name = "Workshuttle", prio_button = false, on_off_button = false, min_threshold_amount = 0, OnCommandCenterWorkingChanged = Building.OnCommandCenterWorkingChanged, OnAddedByControl = Building.OnAddedByControl, OnRemovedByControl = Building.OnRemovedByControl, } function StorageDepot:GameInit() if not self.exclude_from_lr_transportation then LRManagerInstance:AddBuilding(self) end end function StorageDepot:AddToCityLabels() Building.AddToCityLabels(self) end function StorageDepot:SetResourceAutoTransportationState(resource, state) self.auto_transportation_state = state end function StorageDepot:CreateResourceRequests() Building.CreateResourceRequests(self) self.demand = {} self.supply = {} for _, resource_name in ipairs(AllResourcesList) do local max_name = "max_amount_"..resource_name if self:HasMember(max_name) then local demand = self:AddDemandRequest(resource_name, self[max_name], const.rfStorageDepot) local supply = self:AddSupplyRequest(resource_name, 0, const.rfStorageDepot + const.rfPairWithHigher) self.demand[resource_name] = demand self.supply[resource_name] = supply self["GetStored_"..resource_name]= function(self) return self.supply[resource_name]:GetActualAmount() end self["GetMaxAmount_"..resource_name]= function(self) return self[max_name] end end end end function StorageDepot:AddDepotResource(resource, amount) self.supply[resource]:AddAmount(amount) self.demand[resource]:AddAmount(-amount) self:SetCount(self.supply[resource]:GetActualAmount()) end StorageDepot.AddResource = StorageDepot.AddDepotResource function StorageDepot:DroneLoadResource(drone, request, resource, amount) if self.supply[resource] == request then self.demand[resource]:AddAmount(amount) self:SetCount(self.supply[resource]:GetActualAmount()) end end function StorageDepot:DroneUnloadResource(drone, request, resource, amount) Building.DroneUnloadResource(self, drone, request, resource, amount) if self.demand[resource] == request then self.supply[resource]:AddAmount(amount) self:SetCount(self.supply[resource]:GetActualAmount()) end end function StorageDepot:InitInside(dome) Building.InitInside(self, dome) ResourceStockpileBase.InitInside(self, dome) end function StorageDepot:InitOutside() Building.InitOutside(self) ResourceStockpileBase.InitOutside(self) end StorageDepot.MoveInside = Building.MoveInside function StorageDepot:ReturnStockpiledResources() local pos = self:GetVisualPos() if pos ~= InvalidPos() then for resource_flag, request in pairs(self.supply) do local amount = request:GetActualAmount() if amount > 0 then PlaceResourceStockpile_Delayed(pos, resource_flag, amount, self:GetAngle(), true) end end end self:ClearAllResources() end function StorageDepot:Done() --should this be in building::returnresources? if not self.exclude_from_lr_transportation then LRManagerInstance:RemoveBuilding(self) end self:ReturnStockpiledResources() end function StorageDepot:RoverWork(rover, request, resource, amount, reciprocal_req, interaction_type, total_amount) Building.RoverWork(self, rover, request, resource, amount) if resource ~= "clean" and resource ~= "repair" then --temp presentation rover:ContinuousTask(request, amount, "gatherStart", "gatherIdle", "gatherEnd", interaction_type == "load" and "Load" or "Unload", "step", g_Consts.RCRoverTransferResourceWorkTime, "add resource", reciprocal_req, total_amount) end end function StorageDepot:CheatFill() local resource = self.resource if self.supply[resource] then local max_name = "max_amount_"..resource self.supply[resource]:SetAmount(self[max_name]) self.demand[resource]:SetAmount(0) end self:SetCount(self.supply[resource]:GetActualAmount()) end function StorageDepot:CheatEmpty() local resource = self.resource if self.supply[resource] then local max_name = "max_amount_"..resource self.supply[resource]:SetAmount(0) self.demand[resource]:SetAmount(self[max_name]) end self:SetCount(self.supply[resource]:GetActualAmount()) end function StorageDepot:GetStoredAmount(resource) local req = not resource and self.supply[next(self.supply)] or self.supply[resource] return req and req:GetActualAmount() or 0 end function StorageDepot:GetEmptyStorage(resource) return self.demand[resource]:GetActualAmount() end function StorageDepot:GetTargetEmptyStorage(resource) return self.demand[resource]:GetTargetAmount() end function StorageDepot:Getui_Concrete() return T{766, "Concrete<right><concrete(Stored_Concrete,MaxAmount_Concrete)>", self} end function StorageDepot:Getui_Metals() return T{767, "Metals<right><metals(Stored_Metals,MaxAmount_Metals)>", self} end function StorageDepot:Getui_Polymers() return T{768, "Polymers<right><polymers(Stored_Polymers,MaxAmount_Polymers)>", self} end function StorageDepot:Getui_Food() return T{769, "Food<right><food(Stored_Food,MaxAmount_Food)>", self} end function StorageDepot:Getui_Electronics() return T{770, "Electronics<right><electronics(Stored_Electronics,MaxAmount_Electronics)>", self} end function StorageDepot:Getui_MachineParts() return T{771, "Machine Parts<right><machineparts(Stored_MachineParts,MaxAmount_MachineParts)>", self} end function StorageDepot:Getui_PreciousMetals() return T{772, "Rare Metals<right><preciousmetals(Stored_PreciousMetals,MaxAmount_PreciousMetals)>", self} end function StorageDepot:Getui_Fuel() return T{773, "Fuel<right><fuel(Stored_Fuel,MaxAmount_Fuel)>", self} end DefineClass.UniversalStorageDepot = { __parents = { "StorageDepot" }, properties = { { template = true, name = T{774, "Max Storage Per Resource"}, category = "Storage Space", id = "max_storage_per_resource", editor = "number", default = 30000, scale = const.ResourceScale }, { template = true, name = T{775, "Max Boxes On The X Axis"}, category = "Storage Space", id = "max_x", editor = "number", default = 2, help = "Max amount of boxes per axis, for multiple resources its per resource type."}, { template = true, name = T{7626, "Max Boxes On The Y Axis"}, category = "Storage Space", id = "max_y", editor = "number", default = 5, help = "Max amount of boxes per axis, for multiple resources its per resource type." }, { template = true, name = T{7627, "Max Boxes On The Z Axis"}, category = "Storage Space", id = "max_z", editor = "number", default = 3, help = "Max amount of boxes per axis, for multiple resources its per resource type." }, { template = true, name = T{776, "Storable Resources"}, category = "Storage Space", id = "storable_resources", editor = "table", default = {"Concrete", "Food", "Metals", "PreciousMetals","Polymers","Electronics", "MachineParts", "Fuel"}, help = "The type of resources this depot can store."}, { template = true, name = T{777, "Switch Fill Order"}, category = "Storage Space", id = "switch_fill_order", editor = "bool", default = true, help = "When true will fill in x of the spot dir first then y, the opposite when false."}, { template = true, name = T{7770, "Fill Group Idx"}, category = "Storage Space", id = "fill_group_idx", editor = "number", default = 5, help = "When true will fill in x of the spot dir first then y, the opposite when false."}, { id = "StoredAmount", editor = false }, { id = "stockpiled_amount", editor = "number", default = false, no_edit = true }, }, visual_cubes = false, --helper, to distinguish cube resource types auto_transportation_states = false, supply_r_flags = const.rfStorageDepot, demand_r_flags = const.rfStorageDepot + const.rfSpecialSupplyPairing, has_demand_request = true, has_supply_request = true, interest1 = false, interest2 = false, interest3 = false, interest4 = false, placed_cubes = false, counters = false, } function UniversalStorageDepot:Init() self.placement_offset = {} end function UniversalStorageDepot:GameInit() local len = #self.storable_resources for i = 1, len do local resource_name = self.storable_resources[i] local s_name = "Box" .. i if not self:HasSpot(s_name) and len == 1 and self:HasSpot("Box") then s_name = "Box" end self.placement_offset[resource_name] = GetEntitySpotPos(self:GetEntity(), self:GetSpotBeginIndex(s_name)) local amount = (self.stockpiled_amount[resource_name] or 0) self:SetCount(amount, resource_name) end self.resource = self.storable_resources if self.class == "UniversalStorageDepot" then HintDisable("HintStorageDepot") end end function UniversalStorageDepot:SetCount(new_count, resource) new_count = Clamp(new_count, 0, self.max_storage_per_resource) new_count = new_count / const.ResourceScale resource = resource or self.resource[1] local placed_cubes = self.visual_cubes[resource] local counters = self.counters or {} local count = counters[resource] or #placed_cubes if count == new_count then return end counters[resource] = new_count self.counters = counters return self:SetCountInternal(new_count, count, resource, placed_cubes, self.placement_offset[resource], -90*60, 0) end function UniversalStorageDepot:CreateResourceRequests() Building.CreateResourceRequests(self) local storable_resources = self.storable_resources assert(storable_resources, "Shared Storage Depot cannot initialize properly!") self.demand = {} self.supply = {} self.visual_cubes = { } self.auto_transportation_states = {} self.stockpiled_amount = self.stockpiled_amount or {} local total_stored = 0 for i = 1, #storable_resources do local resource_name = storable_resources[i] local amount = (self.stockpiled_amount[resource_name] or 0) local supply = self:AddSupplyRequest(resource_name, amount, bor(self.supply_r_flags, self.additional_supply_flags)) local demand = self:AddDemandRequest(resource_name, self.max_storage_per_resource - amount, self.demand_r_flags + self.additional_demand_flags) self.supply[resource_name] = supply self.demand[resource_name] = demand self.auto_transportation_states[resource_name] = ResourceStates[1] self.visual_cubes[resource_name] = {} --use name as key, in case we need the arr part of the table for something clever total_stored = total_stored + amount self["GetStored_"..resource_name]= function(self) return self.supply[resource_name]:GetActualAmount() end self["GetMaxAmount_"..resource_name] = function(self) return self.max_storage_per_resource end end end function UniversalStorageDepot:GetMaxStorage(resource) if resource then return self["GetMaxAmount_"..resource](self) else return #self.storable_resources * self.max_storage_per_resource end end --cpy paste from SharedStorageBaseVisualOnly function UniversalStorageDepot:GetStoredAmount(resource) if resource then return self.stockpiled_amount[resource] or 0 else local total = 0 for k, v in pairs(self.stockpiled_amount) do total = total + v end return total end end function UniversalStorageDepot:IsFull() return self:GetStoredAmount()>=self:GetMaxStorage() end function UniversalStorageDepot:SetResourceAutoTransportationState(resource, state) self.auto_transportation_states[resource] = state end function UniversalStorageDepot:AddResource(amount, resource) self.supply[resource]:AddAmount(amount) self.demand[resource]:AddAmount(-amount) self.stockpiled_amount[resource] = (self.stockpiled_amount[resource] or 0) + amount self:SetCount(self.supply[resource]:GetActualAmount(), resource) RebuildInfopanel(self) end UniversalStorageDepot.AddDepotResource = UniversalStorageDepot.AddResource UniversalStorageDepot.AddResourceAmount = UniversalStorageDepot.AddResource UniversalStorageDepot.SetResourceAmount = false --not impl. UniversalStorageDepot.SetCountFromRequest = false --not impl. function UniversalStorageDepot:DroneLoadResource(drone, request, resource, amount, skip_presentation) if self.supply[resource] == request then if not skip_presentation then --presentation drone:Face(self:GetPos(), 100) drone:StartFX("Pickup", resource) --resource to string drone:SetState("interact") Sleep(500) drone:StopFX() if not IsValid(self) or not IsValid(drone) then return end end --not presentation self.demand[resource]:AddAmount(amount) self.stockpiled_amount[resource] = self.stockpiled_amount[resource] - amount self:SetCount(self.supply[resource]:GetActualAmount(), resource) RebuildInfopanel(self) end end function UniversalStorageDepot:DroneUnloadResource(drone, request, resource, amount) Building.DroneUnloadResource(self, drone, request, resource, amount) if self.demand[resource] == request then self.supply[resource]:AddAmount(amount) self.stockpiled_amount[resource] = (self.stockpiled_amount[resource] or 0) + amount self:SetCount(self.supply[resource]:GetActualAmount(), resource) RebuildInfopanel(self) end end function UniversalStorageDepot:IsResourceEnabled(res_id) local req = self.demand[res_id] assert(req) return table.find(self.task_requests, req) end function UniversalStorageDepot:ToggleAcceptResource(res_id) if not IsValid(self) then return end local req = self.demand[res_id] local s_req = self.supply[res_id] assert(req) local task_requests = self.task_requests if not self.exclude_from_lr_transportation then LRManagerInstance:RemoveBuilding(self) end if table.find(task_requests, req) then self:InterruptDrones(nil,function(drone) return drone.d_request==req and drone end) self:DisconnectFromCommandCenters() table.remove_entry(self.task_requests, req) s_req:AddFlags(const.rfPostInQueue) s_req:ClearFlags(const.rfStorageDepot) else self:DisconnectFromCommandCenters() table.insert(self.task_requests, req) s_req:ClearFlags(const.rfPostInQueue) s_req:AddFlags(const.rfStorageDepot) end if not self.exclude_from_lr_transportation then LRManagerInstance:AddBuilding(self) end self:ConnectToCommandCenters() end function UniversalStorageDepot:GetIPTextColor(res_id) return self:IsResourceEnabled(res_id) and RGBA(233, 242, 255, 255) or RGBA(255, 69, 38, 255) end function OpenBaseResourcesSelector(context, idx, ctrl) context.resources_type = "base" OpenInfopanelItems(context, ctrl) end function OpenAdvancedResourcesSelector(context, idx, ctrl) context.resources_type = "advance" OpenInfopanelItems(context, ctrl) end function UniversalStorageDepot:CheatFill() local storable_resources = self.storable_resources local resource_count = #storable_resources self:InterruptDrones(nil, function(drone) local r = drone.d_request if r then if self.demand[r:GetResource()] == r then return drone end end end) for i = 1, resource_count do local resource_name = storable_resources[i] if self.supply[resource_name] then local a = self.demand[resource_name]:GetActualAmount() self:AddResource(a, resource_name) end end end function UniversalStorageDepot:ClearAllResources() local storable_resources = self.storable_resources local resource_count = #storable_resources for i = 1, resource_count do local resource_name = storable_resources[i] if self.supply[resource_name] then self.supply[resource_name]:SetAmount(0) self.demand[resource_name]:SetAmount(self.max_storage_per_resource) self.stockpiled_amount[resource_name] = 0 self:SetCount(0, resource_name) end end end UniversalStorageDepot.CheatEmpty = UniversalStorageDepot.ClearAllResources function UniversalStorageDepot:GetEmptyStorage(resource) if not resource then return self:GetMaxStorage() - self:GetStoredAmount() else return self.demand[resource]:GetActualAmount() end end function UniversalStorageDepot:TestReqConsistency() for resource, s_req in pairs(self.supply) do local total = self:GetMaxStorage(resource) --assert(s_req:GetActualAmount() + self.demand[resource]:GetActualAmount() == total) if s_req:GetActualAmount() + self.demand[resource]:GetActualAmount() ~= total then self:SetColorModifier(RGBA(255,0,0,0)) return false end end return true end function dbg_TestMapDepots() ForEach{class = "UniversalStorageDepot", area = "realm", exec = function(o) o:TestReqConsistency() end, } end DefineClass.MysteryDepot = { __parents = { "UniversalStorageDepot" }, } function MysteryDepot:GetDisplayName() return MysteryDepot.Getdisplay_name(self) end function MysteryDepot:GetDescription() return MysteryDepot.Getdescription(self) end function MysteryDepot:GetIPDescription() return MysteryDepot.Getdescription(self) end function MysteryDepot:Getdescription() local m = UICity.mystery or MysteryBase return m.depot_description end function MysteryDepot:Getdisplay_name() local m = UICity.mystery or MysteryBase return m.depot_display_name end function MysteryDepot:Getdisplay_name_pl() local m = UICity.mystery or MysteryBase return m.depot_display_name_pl end
if not minetest.get_modpath("advtrains") then print("[monitoring] advtrains extension not loaded") return else print("[monitoring] advtrains extension loaded") end local MP = minetest.get_modpath("monitoring_advtrains") dofile(MP.."/metrics.lua") dofile(MP.."/cleanup.lua")
-- /$$$$$$$$ /$$ /$$ /$$ -- | $$_____/ | $$ | $$ | $$ -- | $$ /$$$$$$ /$$$$$$$ /$$$$$$$ /$$ /$$ | $$ | $$ /$$$$$$ /$$$$$$$ /$$$$$$$ -- | $$$$$|____ $$| $$__ $$ /$$_____/| $$ | $$ | $$ / $$//$$__ $$| $$__ $$ /$$__ $$ -- | $$__/ /$$$$$$$| $$ \ $$| $$ | $$ | $$ \ $$ $$/| $$$$$$$$| $$ \ $$| $$ | $$ -- | $$ /$$__ $$| $$ | $$| $$ | $$ | $$ \ $$$/ | $$_____/| $$ | $$| $$ | $$ -- | $$ | $$$$$$$| $$ | $$| $$$$$$$| $$$$$$$ \ $/ | $$$$$$$| $$ | $$| $$$$$$$ -- |__/ \_______/|__/ |__/ \_______/ \____ $$ \_/ \_______/|__/ |__/ \_______/ -- /$$ | $$ -- | $$$$$$/ -- \______/ -- -- A full-featured, fully-integrated vendor mod for Minetest local display_node = (minetest.setting_get("fancy_vend_display_node") or "default:obsidian_glass") local max_logs = (tonumber(minetest.setting_get("fancy_vend_log_max")) or 40) local autorotate_speed = (tonumber(minetest.setting_get("fancy_vend_autorotate_speed")) or 1) local drop_vendor = "fancy_vend:player_vendor" -- Register a copy of the display node with no drops to make players separating the obsidian glass with something like a piston a non-issue. local display_node_def = table.copy(minetest.registered_nodes[display_node]) display_node_def.drop = "" display_node_def.groups.not_in_creative_inventory = 1 display_node_def.description = "Fancy Vendor Display Node (you hacker you!)" if pipeworks then display_node_def.digiline = { wire = { rules = pipeworks.digilines_rules } } end minetest.register_node("fancy_vend:display_node", display_node_def) -- Craftitem to display when vendor is inactive (Use just image for this???) minetest.register_craftitem("fancy_vend:inactive",{inventory_image = "inactive.png",}) minetest.register_privilege("admin_vendor", "Enables the user to set regular vendors to admin vendors.") minetest.register_privilege("disable_vendor", "Enables the user to set all vendors to inactive.") local function bts(bool) if bool == false then return "false" elseif bool == true then return "true" else return bool end end local function stb(str) if str == "false" then return false elseif str == "true" then return true else return str end end local modstorage = minetest.get_mod_storage() if modstorage:get_string("all_inactive_force") == "" then modstorage:set_string("all_inactive_force", "false") end local all_inactive_force = stb(modstorage:get_string("all_inactive_force")) minetest.register_chatcommand("disable_all_vendors", { description = "Toggle vendor inactivity.", privs = {disable_vendor=true}, func = function(name, param) if all_inactive_force then all_inactive_force = false modstorage:set_string("all_inactive_force", "false") else all_inactive_force = true modstorage:set_string("all_inactive_force", "true") end end, }) table.length = function(table) local length for i in pairs(table) do length = length + 1 end return length end local function send_message(pos, channel, msg) if channel and channel ~= "" then digilines.receptor_send(pos, digilines.rules.default, channel, msg) end end -- Awards if minetest.get_modpath("awards") then awards.register_achievement("fancy_vend_getting_fancy",{ title = "Getting Fancy", description = "Craft a fancy vendor.", trigger = { type = "craft", item = drop_vendor, target = 1, }, icon = "player_vend_front.png^awards_level1.png", }) awards.register_achievement("fancy_vend_wizard",{ title = "You're a Wizard", description = "Craft a copy tool.", trigger = { type = "craft", item = "fancy_vend:copy_tool", target = 1, }, icon = "copier.png", }) awards.register_achievement("fancy_vend_trader",{ title = "Trader", description = "Configure a depositor.", icon = "player_depo_front.png", }) awards.register_achievement("fancy_vend_seller",{ title = "Seller", description = "Configure a vendor.", icon = "player_vend_front.png^awards_level2.png", }) awards.register_achievement("fancy_vend_shop_keeper",{ title = "Shop Keeper", description = "Configure 10 vendors or depositors.", icon = "player_vend_front.png^awards_level3.png", }) awards.register_achievement("fancy_vend_merchant",{ title = "Merchant", description = "Configure 25 vendors or depositors.", icon = "player_vend_front.png^awards_level4.png", }) awards.register_achievement("fancy_vend_super_merchant",{ title = "Super Merchant", description = "Configure 100 vendors or depositors. How do you even have this much stuff to sell?", icon = "player_vend_front.png^awards_level5.png", }) awards.register_achievement("fancy_vend_god_merchant",{ title = "God Merchant", description = "Configure 9001 vendors or depositors. Ok wot.", icon = "player_vend_front.png^awards_level6.png", secret = true, -- Oi. Cheater. }) end local tmp = {} minetest.register_entity("fancy_vend:display_item",{ hp_max = 1, visual = "wielditem", visual_size = {x = 0.33, y = 0.33}, collisionbox = {0, 0, 0, 0, 0, 0}, physical = false, textures = {"air"}, on_activate = function(self, staticdata) if tmp.nodename ~= nil and tmp.texture ~= nil then self.nodename = tmp.nodename tmp.nodename = nil self.texture = tmp.texture tmp.texture = nil else if staticdata ~= nil and staticdata ~= "" then local data = staticdata:split(';') if data and data[1] and data[2] then self.nodename = data[1] self.texture = data[2] end end end if self.texture ~= nil then self.object:set_properties({textures = {self.texture}}) end self.object:set_properties({automatic_rotate = autorotate_speed}) end, get_staticdata = function(self) if self.nodename ~= nil and self.texture ~= nil then return self.nodename .. ';' .. self.texture end return "" end, }) local function remove_item(pos) local objs = nil objs = minetest.get_objects_inside_radius(pos, .5) if objs then for _, obj in ipairs(objs) do if obj and obj:get_luaentity() and obj:get_luaentity().name == "fancy_vend:display_item" then obj:remove() end end end end local function update_item(pos, node) pos.y = pos.y + 1 remove_item(pos) if minetest.get_node(pos).name ~= "fancy_vend:display_node" then minetest.log("warning", "[fancy_vend]: Placing display item inside "..minetest.get_node(pos).name.." at "..minetest.pos_to_string(pos).." is not permitted, aborting") return end pos.y = pos.y - 1 local meta = minetest.get_meta(pos) if meta:get_string("item") ~= "" then pos.y = pos.y + (12 / 16 + 0.11) tmp.nodename = node.name tmp.texture = ItemStack(meta:get_string("item")):get_name() local e = minetest.add_entity(pos,"fancy_vend:display_item") pos.y = pos.y - (12 / 16 + 0.11) end end -- ABM to refresh entities after clearobjects minetest.register_abm({ nodenames = {"fancy_vend:display_node"}, interval = 60, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local num num = #minetest.get_objects_inside_radius(pos, 0.5) pos.y = pos.y - 1 if num > 0 then return end update_item(pos, node) end }) local function set_vendor_settings(pos, SettingsDef) local meta = minetest.get_meta(pos) meta:set_string("settings", minetest.serialize(SettingsDef)) end local function reset_vendor_settings(pos) local settings_default = { input_item = "", -- Don't change this unless you plan on setting this up to add this item to the inventories output_item = "", -- Don't change this unless you plan on setting this up to add this item to the inventories input_item_qty = 1, output_item_qty = 1, admin_vendor = false, depositor = false, currency_eject = false, accept_output_only = false, split_incoming_stacks = false, inactive_force = false, accept_worn_input = true, accept_worn_output = true, digiline_channel = "", co_sellers = "", banned_buyers = "", auto_sort = false, } set_vendor_settings(pos, settings_default) return settings_default end local function get_vendor_settings(pos) local meta = minetest.get_meta(pos) local settings = minetest.deserialize(meta:get_string("settings")) if not settings then return reset_vendor_settings(pos) else -- If settings added by newer versions of fancy_vend are nil then send defaults if settings.auto_sort == nil then settings.auto_sort = false end return settings end end local function can_buy_from_vendor(pos, player) local settings = get_vendor_settings(pos) local banned_buyers = string.split((settings.banned_buyers or ""),",") for i in pairs(banned_buyers) do if banned_buyers[i] == player:get_player_name() then return false end end return true end local function can_modify_vendor(pos, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local is_owner = false if meta:get_string("owner") == player:get_player_name() or minetest.check_player_privs(player, {protection_bypass=true}) then is_owner = true end return is_owner end local function can_dig_vendor(pos, player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") and can_modify_vendor(pos, player) end local function can_access_vendor_inv(player, pos) local meta = minetest.get_meta(pos) if minetest.check_player_privs(player, {protection_bypass=true}) or meta:get_string("owner") == player:get_player_name() then return true end local settings = get_vendor_settings(pos) local co_sellers = string.split(settings.co_sellers,",") for i in pairs(co_sellers) do if co_sellers[i] == player:get_player_name() then return true end end return false end -- Inventory helpers: -- Function to sort inventory (Taken from technic_chests) local function sort_inventory(inv) local inlist = inv:get_list("main") local typecnt = {} local typekeys = {} for _, st in ipairs(inlist) do if not st:is_empty() then local n = st:get_name() local w = st:get_wear() local m = st:get_metadata() local k = string.format("%s %05d %s", n, w, m) if not typecnt[k] then typecnt[k] = { name = n, wear = w, metadata = m, stack_max = st:get_stack_max(), count = 0, } table.insert(typekeys, k) end typecnt[k].count = typecnt[k].count + st:get_count() end end table.sort(typekeys) local outlist = {} for _, k in ipairs(typekeys) do local tc = typecnt[k] while tc.count > 0 do local c = math.min(tc.count, tc.stack_max) table.insert(outlist, ItemStack({ name = tc.name, wear = tc.wear, metadata = tc.metadata, count = c, })) tc.count = tc.count - c end end if #outlist > #inlist then return end while #outlist < #inlist do table.insert(outlist, ItemStack(nil)) end inv:set_list("main", outlist) end local function free_slots(inv, listname, itemname, quantity) local size = inv:get_size(listname) local free = 0 for i=1,size do local stack = inv:get_stack(listname, i) if stack:is_empty() or stack:get_free_space() > 0 then if stack:is_empty() then free = free + ItemStack(itemname):get_stack_max() elseif stack:get_name() == itemname then free = free + stack:get_free_space() end end end if free < quantity then return false else return true end end local function inv_insert(inv, listname, itemstack, quantity, from_table, pos, input_eject) local stackmax = itemstack:get_stack_max() local stacks = {} local remaining_quantity = quantity -- Add the full stacks to the list while remaining_quantity > stackmax do table.insert(stacks, {name = itemstack:get_name(), count = stackmax}) remaining_quantity = remaining_quantity - stackmax end -- Add the remaining stack to the list table.insert(stacks, {name = itemstack:get_name(), count = remaining_quantity}) -- If tool add wears and metadatas, ignores if from_table = nil (eg, due to vendor beig admin vendor) if minetest.registered_tools[itemstack:get_name()] then for i in pairs(stacks) do local from_item_table = from_table[i].item:to_table() stacks[i].wear = from_item_table.wear stacks[i].metadata = from_item_table.metadata end end -- Add to inventory or eject to pipeworks/hoppers (whichever is applicable) local output_tube_connected = false local output_hopper_connected = false if input_eject and pos then local pos_under = vector.new(pos) pos_under.y = pos_under.y - 1 local node_under = minetest.get_node(pos_under) if minetest.get_item_group(node_under.name, "tubedevice") > 0 then output_tube_connected = true end if node_under.name == "hopper:hopper" or node_under.name == "hopper:hopper_side" then output_hopper_connected = true end end for i in pairs(stacks) do if output_tube_connected then pipeworks.tube_inject_item(pos, pos, vector.new(0, -1, 0), stacks[i], minetest.get_meta(pos):get_string("owner")) else local leftovers = ItemStack(stacks[i]) if output_hopper_connected then local pos_under = {x = pos.x, y = pos.y-1, z = pos.z} local hopper_inv = minetest.get_meta(pos_under):get_inventory() leftovers = hopper_inv:add_item("main", leftovers) end if not leftovers:is_empty() then inv:add_item(listname, leftovers) end end end end local function inv_remove(inv, listname, remove_table, itemstring, quantity) local count = 0 for i in pairs(remove_table) do count = count + remove_table[i].item:get_count() inv:set_stack(listname, remove_table[i].id, nil) end -- Add back items if too many were taken if count > quantity then inv:add_item(listname, ItemStack({name = itemstring, count = count - quantity})) end end local function inv_contains_items(inv, listname, itemstring, quantity, ignore_wear) local minimum = quantity local get_items = {} local count = 0 for i=1,inv:get_size(listname) do local stack = inv:get_stack(listname, i) if stack:get_name() == itemstring then if ignore_wear or (not minetest.registered_tools[itemstring] or stack:get_wear() == 0) then count = count + stack:get_count() table.insert(get_items, {id=i, item=stack}) if count >= minimum then return true, get_items end end end end return false end local function get_vendor_status(pos) local settings = get_vendor_settings(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if all_inactive_force then return false, "all_inactive_force" elseif settings.input_item == "" or settings.output_item == "" then return false, "unconfigured" elseif settings.inactive_force then return false, "inactive_force" elseif not minetest.check_player_privs(meta:get_string("owner"), {admin_vendor=true}) and settings.admin_vendor == true then return false, "no_privs" elseif not inv_contains_items(inv, "main", settings.output_item, settings.output_item_qty, settings.accept_worn_output) and not settings.admin_vendor then return false, "no_output" elseif not free_slots(inv, "main", settings.input_item, settings.input_item_qty) and not settings.admin_vendor then return false, "no_room" else return true end end local function make_inactive_string(errorcode) local status_str = "" if errorcode == "unconfigured" then status_str = status_str.." (unconfigured)" elseif errorcode == "inactive_force" then status_str = status_str.." (forced)" elseif errorcode == "no_output" then status_str = status_str.." (out of stock)" elseif errorcode == "no_room" then status_str = status_str.." (no room)" elseif errorcode == "no_privs" then status_str = status_str.." (seller has insufficient privilages)" elseif errorcode == "all_inactive_force" then status_str = status_str.." (all vendors disabled temporarily by admin)" end return status_str end -- adminstacks - inv insert issue -- wear - invcheck and inv get and insert issue local function run_inv_checks(pos, player, lots) local settings = get_vendor_settings(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local player_inv = player:get_inventory() local ct = {} -- Get input and output quantities after multiplying by lot count local output_qty = settings.output_item_qty * lots local input_qty = settings.input_item_qty * lots -- Perform inventory checks ct.player_has, ct.player_item_table = inv_contains_items(player_inv, "main", settings.input_item, input_qty, settings.accept_worn_input) ct.vendor_has, ct.vendor_item_table = inv_contains_items(inv, "main", settings.output_item, output_qty, settings.accept_worn_output) ct.player_fits = free_slots(inv, "main", settings.output_item, output_qty) ct.vendor_fits = free_slots(inv, "main", settings.input_item, input_qty) if ct.player_has and ct.vendor_has and ct.player_fits and ct.vendor_fits then ct.overall = true else ct.overall = false end return ct end local function get_max_lots(pos, player) local max = 0 while run_inv_checks(pos, player, max).overall do max = max + 1 end return max end local function make_purchase(pos, player, lots) if not can_buy_from_vendor(pos, player) then return false, "You cannot purchase from this vendor" end local settings = get_vendor_settings(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local player_inv = player:get_inventory() local status, errorcode = get_vendor_status(pos) -- Double check settings, vendors which were incorrectly set up before this bug fix won't matter anymore settings.input_item_qty = math.abs(settings.input_item_qty) settings.output_item_qty = math.abs(settings.output_item_qty) if status then -- Get input and output quantities after multiplying by lot count local output_qty = settings.output_item_qty * lots local input_qty = settings.input_item_qty * lots -- Perform inventory checks local ct = run_inv_checks(pos, player, lots) if ct.player_has then if ct.player_fits then if settings.admin_vendor then minetest.log("action", player:get_player_name().." trades "..settings.input_item_qty.." "..settings.input_item.." for "..settings.output_item_qty.." "..settings.output_item.." using vendor at "..minetest.pos_to_string(pos)) inv_remove(player_inv, "main", ct.player_item_table, settings.input_item, input_qty) inv_insert(player_inv, "main", ItemStack(settings.output_item), output_qty, nil) if minetest.get_modpath("digilines") then send_message(pos, settings.digiline_channel, msg) end return true, "Trade successful" elseif ct.vendor_has then if ct.vendor_fits then minetest.log("action", player:get_player_name().." trades "..settings.input_item_qty.." "..settings.input_item.." for "..settings.output_item_qty.." "..settings.output_item.." using vendor at "..minetest.pos_to_string(pos)) inv_remove(inv, "main", ct.vendor_item_table, settings.output_item, output_qty) inv_remove(player_inv, "main", ct.player_item_table, settings.input_item, input_qty) inv_insert(player_inv, "main", ItemStack(settings.output_item), output_qty, ct.vendor_item_table) inv_insert(inv, "main", ItemStack(settings.input_item), input_qty, ct.player_item_table, pos, (minetest.get_modpath("pipeworks") and settings.currency_eject)) return true, "Trade successful" else return false, "Vendor has insufficient space" end else return false, "Vendor has insufficient resources" end else return false, "You have insufficient space" end else return false, "You have insufficient funds" end else return false, "Vendor is inactive"..make_inactive_string(errorcode) end end local function get_vendor_buyer_fs(pos, player, lots) local base = "size[8,9]".. "label[0,0;Owner wants:]".. "label[0,1.25;for:]".. "button[0,2.7;2,1;buy;Buy]".. "label[2.8,2.9;lots.]".. "button[0,3.6;2,1;lot_fill;Fill lots to max.]".. "list[current_player;main;0,4.85;8,1;]".. "list[current_player;main;0,6.08;8,3;8]".. "listring[current_player;main]".. "field_close_on_enter[lot_count;false]" -- Add dynamic elements local settings = get_vendor_settings(pos) local meta = minetest.get_meta(pos) local status, errorcode = get_vendor_status(pos) local itemstuff = "item_image_button[0,0.4;1,1;"..settings.input_item..";ignore;]".. "label[0.9,0.6;"..settings.input_item_qty.." "..minetest.registered_items[settings.input_item].description.."]".. "item_image_button[0,1.7;1,1;"..settings.output_item..";ignore;]".. "label[0.9,1.9;"..settings.output_item_qty.." "..minetest.registered_items[settings.output_item].description.."]" local status_str if status then status_str = "active" else status_str = "inactive"..make_inactive_string(errorcode) end local status_fs = "label[4,0.4;Vendor status: "..status_str.."]".. "label[4,0.8;Message: "..meta:get_string("message").."]".. "label[4,0;Vendor owned by: "..meta:get_string("owner").."]" local setting_specific = "" if not settings.accept_worn_input then setting_specific = setting_specific.."label[4,1.6;Vendor will not accept worn tools.]" end if not settings.accept_worn_output then setting_specific = setting_specific.."label[4,1.2;Vendor will not sell worn tools.]" end local fields = "field[2.2,3.2;1,0.6;lot_count;;"..(lots or 1).."]" local fs = base..itemstuff..status_fs..setting_specific..fields return fs end local function get_vendor_settings_fs(pos) local base = "size[9,9]".. "label[2.8,0.5;Input item]".. "label[6.8,0.5;Output item]".. "image[0,1.3;1,1;debug_btn.png]".. "item_image_button[0,2.3;1,1;default:book;button_log;]".. "list[current_player;main;1,4.85;8,1;]".. "list[current_player;main;1,6.08;8,3;8]".. "listring[current_player;main]".. "button_exit[0,8;1,1;btn_exit;Done]" -- Add dynamic elements local pos_str = pos.x..","..pos.y..","..pos.z local settings = get_vendor_settings(pos) if settings.admin_vendor then base = base.."item_image[0,0.3;1,1;default:chest]" else base = base.."item_image_button[0,0.3;1,1;default:chest;button_inv;]" end local inv = "list[nodemeta:"..pos_str..";wanted_item;1,0.3;1,1;]".. "list[nodemeta:"..pos_str..";given_item;5,0.3;1,1;]".. "listring[nodemeta:"..pos_str..";wanted_item]".. "listring[nodemeta:"..pos_str..";given_item]" local fields = "field[2.2,0.8;1,0.6;input_item_qty;;"..settings.input_item_qty.."]".. "field[6.2,0.8;1,0.6;output_item_qty;;"..settings.output_item_qty.."]".. "field[1.3,4.1;2.66,1;co_sellers;Co-Sellers:;"..settings.co_sellers.."]".. "field[3.86,4.1;2.66,1;banned_buyers;Banned Buyers:;"..settings.banned_buyers.."]".. "field_close_on_enter[input_item_qty;false]".. "field_close_on_enter[output_item_qty;false]".. "field_close_on_enter[co_sellers;false]".. "field_close_on_enter[banned_buyers;false]" local checkboxes = "checkbox[1,2.2;inactive_force;Force vendor into an inactive state.;"..bts(settings.inactive_force).."]".. "checkbox[1,2.6;depositor;Set this vendor to a Depositor.;"..bts(settings.depositor).."]".. "checkbox[1,3.0;accept_worn_output;Sell worn tools.;"..bts(settings.accept_worn_output).."]".. "checkbox[5,3.0;accept_worn_input;Buy worn tools.;"..bts(settings.accept_worn_input).."]".. "checkbox[5,2.6;auto_sort;Automatically sort inventory.;"..bts(settings.auto_sort).."]" -- Admin vendor checkbox only if owner is admin local meta = minetest.get_meta(pos) if minetest.check_player_privs(meta:get_string("owner"), {admin_vendor=true}) or settings.admin_vendor then checkboxes = checkboxes.. "checkbox[5,2.2;admin_vendor;Set vendor to an admin vendor.;"..bts(settings.admin_vendor).."]" end -- Optional dependancy specific elements if minetest.get_modpath("pipeworks") or minetest.get_modpath("hopper") then checkboxes = checkboxes.. "checkbox[1,1.7;currency_eject;Eject incomming currency.;"..bts(settings.currency_eject).."]" if minetest.get_modpath("pipeworks") then checkboxes = checkboxes.. "checkbox[5,1.3;accept_output_only;Accept for-sale item only.;"..bts(settings.accept_output_only).."]".. "checkbox[1,1.3;split_incoming_stacks;Split incomming stacks.;"..bts(settings.split_incoming_stacks).."]" end end if minetest.get_modpath("digilines") then fields = fields.. "field[6.41,4.1;2.66,1;digiline_channel;Digiline Channel:;"..settings.digiline_channel.."]".. "field_close_on_enter[digiline_channel;false]" end local fs = base..inv..fields..checkboxes return fs end local function get_vendor_default_fs(pos, player) local base = "size[16,11]".. "item_image[0,0.3;1,1;default:chest]".. "list[current_player;main;4,6.85;8,1;]".. "list[current_player;main;4,8.08;8,3;8]".. "listring[current_player;main]".. "button[1,6.85;3,1;inv_tovendor;All To Vendor]".. "button[12,6.85;3,1;inv_fromvendor;All From Vendor]".. "button[1,8.08;3,1;inv_output_tovendor;Output To Vendor]".. "button[12,8.08;3,1;inv_input_fromvendor;Input From Vendor]".. "button[1,9.31;3,1;sort;Sort Inventory]".. "button_exit[0,10;1,1;btn_exit;Done]" -- Add dynamic elements local pos_str = pos.x..","..pos.y..","..pos.z local inv_lists = "list[nodemeta:"..pos_str..";main;1,0.3;15,6;]".. "listring[nodemeta:"..pos_str..";main]" local settings_btn = "" if can_modify_vendor(pos, player) then settings_btn = "image_button[0,1.3;1,1;debug_btn.png;button_settings;]".. "item_image_button[0,2.3;1,1;default:book;button_log;]" else settings_btn = "image[0,1.3;1,1;debug_btn.png]".. "item_image[0,2.3;1,1;default:book]" end local fs = base..inv_lists..settings_btn return fs end local function get_vendor_log_fs(pos) local base = "size[9,9]".. "image_button[0,1.3;1,1;debug_btn.png;button_settings;]".. "item_image[0,2.3;1,1;default:book]".. "button_exit[0,8;1,1;btn_exit;Done]" -- Add dynamic elements local meta = minetest.get_meta(pos) local logs = minetest.deserialize(meta:get_string("log")) local settings = get_vendor_settings(pos) if settings.admin_vendor then base = base.."item_image[0,0.3;1,1;default:chest]" else base = base.."item_image_button[0,0.3;1,1;default:chest;button_inv;]" end if not logs then logs = {"Error loading logs",} end local logs_tl = "textlist[1,0.5;7.8,8.6;logs;"..table.concat(logs, ",").."]".. "label[1,0;Showing (up to "..max_logs..") recent log entries:]" local fs = base..logs_tl return fs end local function show_vendor_formspec(player, pos) local settings = get_vendor_settings(pos) if can_access_vendor_inv(player, pos) then local status, errorcode = get_vendor_status(pos) if ((not status and errorcode == "unconfigured") and can_modify_vendor(pos, player)) or settings.admin_vendor then minetest.show_formspec(player:get_player_name(), "fancy_vend:settings;"..minetest.pos_to_string(pos), get_vendor_settings_fs(pos)) else minetest.show_formspec(player:get_player_name(), "fancy_vend:default;"..minetest.pos_to_string(pos), get_vendor_default_fs(pos, player)) end else minetest.show_formspec(player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), get_vendor_buyer_fs(pos, player, nil)) end end local function swap_vendor(pos, vendor_type) local node = minetest.get_node(pos) node.name = vendor_type minetest.swap_node(pos, node) end local function get_correct_vendor(settings) if settings.admin_vendor then if settings.depositor then return "fancy_vend:admin_depo" else return "fancy_vend:admin_vendor" end else if settings.depositor then return "fancy_vend:player_depo" else return "fancy_vend:player_vendor" end end end local function is_vendor(name) local vendor_names = { "fancy_vend:player_vendor", "fancy_vend:player_depo", "fancy_vend:admin_vendor", "fancy_vend:admin_depo", } for i,n in ipairs(vendor_names) do if name == n then return true end end return false end local function refresh_vendor(pos) local node = minetest.get_node(pos) if node.name:split(":")[1] ~= "fancy_vend" then return false, "not a vendor" end local settings = get_vendor_settings(pos) local meta = minetest.get_meta(pos) local status, errorcode = get_vendor_status(pos) local correct_vendor = get_correct_vendor(settings) if status then meta:set_string("infotext", (settings.admin_vendor and "Admin" or "Player").." Vendor trading "..settings.input_item_qty.." "..minetest.registered_items[settings.input_item].description.." for "..settings.output_item_qty.." "..minetest.registered_items[settings.output_item].description.." (owned by " .. meta:get_string("owner") .. ")") if meta:get_string("configured") == "" then meta:set_string("configured", "true") if minetest.get_modpath("awards") then local name = meta:get_string("owner") local data = awards.players[name] awards.increment_item_counter(data, "fancy_vend_configure", correct_vendor) if awards.get_item_count(data, "fancy_vend_configure", "fancy_vend:player_vendor") >= 1 then awards.unlock(name, "fancy_vend_seller") end if awards.get_item_count(data, "fancy_vend_configure", "fancy_vend:player_depo") >= 1 then awards.unlock(name, "fancy_vend_trader") end if awards.get_total_item_count(data, "fancy_vend_configure") >= 10 then awards.unlock(name, "fancy_vend_shop_keeper") end if awards.get_total_item_count(data, "fancy_vend_configure") >= 25 then awards.unlock(name, "fancy_vend_merchant") end if awards.get_total_item_count(data, "fancy_vend_configure") >= 100 then awards.unlock(name, "fancy_vend_super_merchant") end if awards.get_total_item_count(data, "fancy_vend_configure") >= 9001 then awards.unlock(name, "fancy_vend_god_merchant") end end end if settings.depositor then if meta:get_string("item") ~= settings.input_item then meta:set_string("item", settings.input_item) update_item(pos, node) end else if meta:get_string("item") ~= settings.output_item then meta:set_string("item", settings.output_item) update_item(pos, node) end end else meta:set_string("infotext", "Inactive "..(settings.admin_vendor and "Admin" or "Player").." Vendor"..make_inactive_string(errorcode).." (owned by " .. meta:get_string("owner") .. ")") if meta:get_string("item") ~= "fancy_vend:inactive" then meta:set_string("item", "fancy_vend:inactive") update_item(pos, node) end end if correct_vendor ~= node.name then swap_vendor(pos, correct_vendor) end end local function move_inv(frominv, toinv, filter) for i, v in ipairs(frominv:get_list("main") or {}) do if v:get_name() == filter or not filter then if toinv:room_for_item("main", v) then local leftover = toinv:add_item("main", v) frominv:remove_item("main", v) if leftover and not leftover:is_empty() then frominv:add_item("main", v) end end end end end minetest.register_on_player_receive_fields(function(player, formname, fields) local name = formname:split(":")[1] if name ~= "fancy_vend" then return end local formtype = formname:split(":")[2] formtype = formtype:split(";")[1] local pos = minetest.string_to_pos(formname:split(";")[2]) if not pos then return end local node = minetest.get_node(pos) if not is_vendor(node.name) then return end local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local player_inv = player:get_inventory() local settings = get_vendor_settings(pos) -- Handle settings changes if can_modify_vendor(pos, player) then for i in pairs(fields) do if stb(fields[i]) ~= settings[i] then settings[i] = stb(fields[i]) end end -- Make sure item values are positive settings.input_item_qty = math.abs(settings.input_item_qty) settings.output_item_qty = math.abs(settings.output_item_qty) -- Check number-only fields contain only numbers if not tonumber(settings.input_item_qty) then settings.input_item_qty = 1 else settings.input_item_qty = math.floor(tonumber(settings.input_item_qty)) end if not tonumber(settings.output_item_qty) then settings.output_item_qty = 1 else settings.output_item_qty = math.floor(tonumber(settings.output_item_qty)) end -- Check item quantities aren't too high (which could lead to additional processing for no reason), if so, set it to the maximum the player inventory can handle if ItemStack(settings.output_item):get_stack_max() * player_inv:get_size("main") < settings.output_item_qty then settings.output_item_qty = ItemStack(settings.output_item):get_stack_max() * player_inv:get_size("main") end if ItemStack(settings.input_item):get_stack_max() * player_inv:get_size("main") < settings.input_item_qty then settings.input_item_qty = ItemStack(settings.input_item):get_stack_max() * player_inv:get_size("main") end -- Admin vendor priv check if not minetest.check_player_privs(meta:get_string("owner"), {admin_vendor=true}) and fields.admin_vendor == "true" then settings.admin_vendor = false end set_vendor_settings(pos, settings) refresh_vendor(pos) end if fields.quit then if can_access_vendor_inv(player, pos) and settings.auto_sort then sort_inventory(inv) end return true end if fields.sort and can_access_vendor_inv(player, pos) then sort_inventory(inv) end if fields.buy then local lots = math.floor(tonumber(fields.lot_count) or 1) local success, message = make_purchase(pos, player, lots) if success then -- Add to vendor logs local logs = minetest.deserialize(meta:get_string("log")) for i in pairs(logs) do if i >= max_logs then table.remove(logs, 1) end end table.insert(logs, "Player "..player:get_player_name().." purchased "..lots.." lots from this vendor.") meta:set_string("log", minetest.serialize(logs)) -- Send digiline message if applicable if minetest.get_modpath("digilines") then local msg = { buyer = player:get_player_name(), lots = lots, settings = settings, } send_message(pos, settings.digiline_channel, msg) end end -- Set message and refresh vendor if message then meta:set_string("message", message) end refresh_vendor(pos) elseif fields.lot_fill then minetest.show_formspec(player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), get_vendor_buyer_fs(pos, player, get_max_lots(pos, player))) return true end if can_access_vendor_inv(player, pos) then if fields.inv_tovendor then minetest.log("action", player:get_player_name().." moves inventory contents to vendor at "..minetest.pos_to_string(pos)) move_inv(player_inv, inv, nil) refresh_vendor(pos) elseif fields.inv_output_tovendor then minetest.log("action", player:get_player_name().." moves output items in inventory to vendor at "..minetest.pos_to_string(pos)) move_inv(player_inv, inv, settings.output_item) refresh_vendor(pos) elseif fields.inv_fromvendor then minetest.log("action", player:get_player_name().." moves inventory contents from vendor at "..minetest.pos_to_string(pos)) move_inv(inv, player_inv, nil) refresh_vendor(pos) elseif fields.inv_input_fromvendor then minetest.log("action", player:get_player_name().." moves input items from vendor at "..minetest.pos_to_string(pos)) move_inv(inv, player_inv, settings.input_item) refresh_vendor(pos) end end -- Handle page changes if fields.button_log then minetest.show_formspec(player:get_player_name(), "fancy_vend:log;"..minetest.pos_to_string(pos), get_vendor_log_fs(pos)) return elseif fields.button_settings then minetest.show_formspec(player:get_player_name(), "fancy_vend:settings;"..minetest.pos_to_string(pos), get_vendor_settings_fs(pos)) return elseif fields.button_inv then minetest.show_formspec(player:get_player_name(), "fancy_vend:default;"..minetest.pos_to_string(pos), get_vendor_default_fs(pos, player)) return end -- Update formspec if formtype == "log" then minetest.show_formspec(player:get_player_name(), "fancy_vend:log;"..minetest.pos_to_string(pos), get_vendor_log_fs(pos, player)) elseif formtype == "settings" then minetest.show_formspec(player:get_player_name(), "fancy_vend:settings;"..minetest.pos_to_string(pos), get_vendor_settings_fs(pos, player)) elseif formtype == "default" then minetest.show_formspec(player:get_player_name(), "fancy_vend:default;"..minetest.pos_to_string(pos), get_vendor_default_fs(pos, player)) elseif formtype == "buyer" then minetest.show_formspec(player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), get_vendor_buyer_fs(pos, player, (tonumber(fields.lot_count) or 1))) end end) local vendor_template = { description = "Vending Machine", legacy_facedir_simple = true, paramtype2 = "facedir", groups = {choppy=2, oddly_breakable_by_hand=2, tubedevice=1, tubedevice_receiver=1}, selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 1.5, 0.5}, }, is_ground_content = false, light_source = 8, sounds = default.node_sound_wood_defaults(), drop = drop_vendor, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Unconfigured Player Vendor") meta:set_string("message", "Vendor initialized") meta:set_string("owner", "") local inv = meta:get_inventory() inv:set_size("main", 15*6) inv:set_size("wanted_item", 1*1) inv:set_size("given_item", 1*1) reset_vendor_settings(pos) meta:set_string("log", "") end, can_dig = can_dig_vendor, on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end local pointed_node_pos = minetest.get_pointed_thing_position(pointed_thing, false) local pointed_node = minetest.get_node(pointed_node_pos) if minetest.registered_nodes[pointed_node.name].buildable_to then pointed_thing.above = pointed_node_pos end -- Set variables for access later (for various checks, etc.) local name = placer:get_player_name() local above_node_pos = table.copy(pointed_thing.above) above_node_pos.y = above_node_pos.y + 1 local above_node = minetest.get_node(above_node_pos).name -- If node above is air or the display node, and it is not protected, attempt to place the vendor. If vendor sucessfully places, place display node above, otherwise alert the user if (minetest.registered_nodes[above_node].buildable_to or above_node == "fancy_vend:display_node") and not minetest.is_protected(above_node_pos, name) then local itemstack, success = minetest.item_place(itemstack, placer, pointed_thing, nil) if above_node ~= "fancy_vend:display_node" and success then minetest.set_node(above_node_pos, minetest.registered_nodes["fancy_vend:display_node"]) end -- Set owner local meta = minetest.get_meta(pointed_thing.above) meta:set_string("owner", placer:get_player_name() or "") -- Set default meta meta:set_string("log", minetest.serialize({"Vendor placed by "..placer:get_player_name(),})) reset_vendor_settings(pointed_thing.above) refresh_vendor(pointed_thing.above) else minetest.chat_send_player(name, "Vendors require 2 nodes of space.") end if minetest.get_modpath("pipeworks") then pipeworks.after_place(pointed_thing.above) end return itemstack end, on_dig = function(pos, node, digger) -- Set variables for access later (for various checks, etc.) local name = digger:get_player_name() local above_node_pos = table.copy(pos) above_node_pos.y = above_node_pos.y + 1 -- abandon if player shouldn't be able to dig node local can_dig = can_dig_vendor(pos, digger) if not can_dig then return end -- Try remove display node, if the whole node is able to be removed by the player, remove the display node and continue to remove vendor, if it doesn't exist and vendor can be dug continue to remove vendor. local success if minetest.get_node(above_node_pos).name == "fancy_vend:display_node" then if not minetest.is_protected(above_node_pos, name) and not minetest.is_protected(pos, name) then minetest.remove_node(above_node_pos) remove_item(above_node_pos) success = true else success = false end else if not minetest.is_protected(pos, name) then success = true else success = false end end -- If failed to remove display node, don't remove vendor. since protection for whole vendor was checked at display removal, protection need not be re-checked if success then minetest.remove_node(pos) minetest.handle_node_drops(pos, {drop_vendor}, digger) if minetest.get_modpath("pipeworks") then pipeworks.after_dig(pos) end end end, tube = { input_inventory = "main", connect_sides = {left = 1, right = 1, back = 1, bottom = 1}, insert_object = function(pos, node, stack, direction) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local remaining = inv:add_item("main", stack) refresh_vendor(pos) return remaining end, can_insert = function(pos, node, stack, direction) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local settings = get_vendor_settings(pos) if settings.split_stacks then stack = stack:peek_item(1) end if settings.accept_output_only then if stack:get_name() ~= settings.output_item then return false end end return inv:room_for_item("main", stack) end, }, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if not can_access_vendor_inv(player, pos) then return 0 end return count end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) if not can_access_vendor_inv(player, pos) then return 0 end if listname == "wanted_item" or listname == "given_item" then local inv = minetest.get_meta(pos):get_inventory() inv:set_stack(listname, index, ItemStack(stack:get_name())) local settings = get_vendor_settings(pos) if listname == "wanted_item" then settings.input_item = stack:get_name() elseif listname == "given_item" then settings.output_item = stack:get_name() end set_vendor_settings(pos, settings) return 0 end return stack:get_count() end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) if not can_access_vendor_inv(player, pos) then return 0 end if listname == "wanted_item" or listname == "given_item" then local inv = minetest.get_meta(pos):get_inventory() local fake_stack = inv:get_stack(listname, index) fake_stack:take_item(stack:get_count()) inv:set_stack(listname, index, fake_stack) local settings = get_vendor_settings(pos) if listname == "wanted_item" then settings.input_item = "" elseif listname == "given_item" then settings.output_item = "" end set_vendor_settings(pos, settings) return 0 end return stack:get_count() end, on_rightclick = function(pos, node, clicker) node = minetest.get_node(pos) if node.name == "fancy_vend:display_node" then pos.y = pos.y - 1 end show_vendor_formspec(clicker, pos) end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().." moves stuff in vendor at "..minetest.pos_to_string(pos)) refresh_vendor(pos) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().." moves "..stack:get_name().." to vendor at "..minetest.pos_to_string(pos)) refresh_vendor(pos) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().." takes "..stack:get_name().." from vendor at "..minetest.pos_to_string(pos)) refresh_vendor(pos) end, on_blast = function() -- TNT immunity end, } if pipeworks then vendor_template.digiline = { receptor = {}, effector = { action = function() end }, wire = { rules = pipeworks.digilines_rules }, } end local player_vendor = table.copy(vendor_template) player_vendor.tiles = { "player_vend.png", "player_vend.png", "player_vend.png", "player_vend.png", "player_vend.png", "player_vend_front.png", } local player_depo = table.copy(vendor_template) player_depo.tiles = { "player_depo.png", "player_depo.png", "player_depo.png", "player_depo.png", "player_depo.png", "player_depo_front.png", } player_depo.groups.not_in_creative_inventory = 1 local admin_vendor = table.copy(vendor_template) admin_vendor.tiles = { "admin_vend.png", "admin_vend.png", "admin_vend.png", "admin_vend.png", "admin_vend.png", "admin_vend_front.png", } admin_vendor.groups.not_in_creative_inventory = 1 local admin_depo = table.copy(vendor_template) admin_depo.tiles = { "admin_depo.png", "admin_depo.png", "admin_depo.png", "admin_depo.png", "admin_depo.png", "admin_depo_front.png", } admin_depo.groups.not_in_creative_inventory = 1 minetest.register_node("fancy_vend:player_vendor", player_vendor) minetest.register_node("fancy_vend:player_depo", player_depo) minetest.register_node("fancy_vend:admin_vendor", admin_vendor) minetest.register_node("fancy_vend:admin_depo", admin_depo) minetest.register_craft({ output = "fancy_vend:player_vendor", recipe = { { "default:gold_ingot",display_node, "default:gold_ingot"}, { "default:diamond", "default:mese_crystal", "default:diamond"}, { "default:gold_ingot","default:chest_locked","default:gold_ingot"}, } }) -- Hopper support if minetest.get_modpath("hopper") then hopper:add_container({ {"side", "fancy_vend:player_vendor", "main"} }) hopper:add_container({ {"side", "fancy_vend:player_depo", "main"} }) end --------------- -- Copy Tool -- --------------- local function get_vendor_pos_and_settings(pointed_thing) if pointed_thing.type ~= "node" then return false end local pos = minetest.get_pointed_thing_position(pointed_thing, false) local node = minetest.get_node(pos) if node.name == "fancy_vend:display_node" then pos.y = pos.y - 1 node = minetest.get_node(pos) end if not is_vendor(node.name) then return false end local settings = get_vendor_settings(pos) return pos, settings end minetest.register_tool("fancy_vend:copy_tool",{ inventory_image = "copier.png", description = "Geminio Wand (For copying vendor settings, right click to save settings, left click to set settings.)", stack_max = 1, on_place = function(itemstack, placer, pointed_thing) local pos, settings = get_vendor_pos_and_settings(pointed_thing) if not pos then return end local meta = itemstack:get_meta() meta:set_string("settings", minetest.serialize(settings)) minetest.chat_send_player(placer:get_player_name(), "Settings saved.") return itemstack end, on_use = function(itemstack, user, pointed_thing) local pos, current_settings = get_vendor_pos_and_settings(pointed_thing) if not pos then return end local meta = itemstack:get_meta() local node_meta = minetest.get_meta(pos) local new_settings = minetest.deserialize(meta:get_string("settings")) if can_modify_vendor(pos, user) then -- Admin vendor priv check if not minetest.check_player_privs(node_meta:get_string("owner"), {admin_vendor=true}) and new_settings.admin_vendor == true then settings.admin_vendor = false end new_settings.input_item = current_settings.input_item new_settings.input_item_qty = current_settings.input_item_qty new_settings.output_item = current_settings.output_item new_settings.output_item_qty = current_settings.output_item_qty -- Admin vendor priv check if not minetest.check_player_privs(node_meta:get_string("owner"), {admin_vendor=true}) and new_settings.admin_vendor then new_settings.admin_vendor = current_settings.admin_vendor end set_vendor_settings(pos, new_settings) refresh_vendor(pos) minetest.chat_send_player(user:get_player_name(), "Settings set.") else minetest.chat_send_player(user:get_player_name(), "You cannot modify this vendor.") end end, }) minetest.register_craft({ output = "fancy_vend:copy_tool", recipe = { {"default:stick","", "" }, {"", "default:obsidian_shard","" }, {"", "", "default:diamond"}, } }) minetest.register_craft({ output = "fancy_vend:copy_tool", recipe = { {"", "", "default:stick"}, {"", "default:obsidian_shard","" }, {"default:diamond","", "" }, } }) --------------------------- -- Vendor Upgrade System -- --------------------------- local old_vendor_mods = string.split((minetest.setting_get("fancy_vend_old_vendor_mods") or ""), ",") local old_vendor_mods_table = {} for i in pairs(old_vendor_mods) do old_vendor_mods_table[old_vendor_mods[i]] = true end local base_upgrade_template = { description = "Shop Upgrade (Try and place to upgrade)", legacy_facedir_simple = true, paramtype2 = "facedir", groups = {choppy=2, oddly_breakable_by_hand=2, not_in_creative_inventory=1}, is_ground_content = false, light_source = 8, sounds = default.node_sound_wood_defaults(), drop = drop_vendor, tiles = { "player_vend.png", "player_vend.png", "player_vend.png", "player_vend.png", "player_vend.png", "upgrade_front.png", }, on_place = function(itemstack, placer, pointed_thing) return ItemStack(drop_vendor.." "..itemstack:get_count()) end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.get_meta(pos) if player:get_player_name() ~= meta:get_string("owner") then return 0 end return count end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if player:get_player_name() ~= meta:get_string("owner") then return 0 end return stack:get_count() end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if player:get_player_name() ~= meta:get_string("owner") then return 0 end return stack:get_count() end, } local clear_craft_vendors = {} if old_vendor_mods_table["currency"] then local currency_template = table.copy(base_upgrade_template) currency_template.can_dig = function(pos, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() return inv:is_empty("stock") and inv:is_empty("customers_gave") and inv:is_empty("owner_wants") and inv:is_empty("owner_gives") and (meta:get_string("owner") == player:get_player_name() or minetest.check_player_privs(player:get_player_name(), {protection_bypass=true})) end currency_template.on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local list_name = "nodemeta:"..pos.x..','..pos.y..','..pos.z if clicker:get_player_name() == meta:get_string("owner") then minetest.show_formspec(clicker:get_player_name(),"fancy_vend:currency_shop_formspec", "size[8,9.5]".. "label[0,0;" .. "Customers gave:" .. "]".. "list["..list_name..";customers_gave;0,0.5;3,2;]".. "label[0,2.5;" .. "Your stock:" .. "]".. "list["..list_name..";stock;0,3;3,2;]".. "label[5,0;" .. "You want:" .. "]".. "list["..list_name..";owner_wants;5,0.5;3,2;]".. "label[5,2.5;" .. "In exchange, you give:" .. "]".. "list["..list_name..";owner_gives;5,3;3,2;]".. "list[current_player;main;0,5.5;8,4;]" ) end end minetest.register_node(":currency:shop", currency_template) table.insert(clear_craft_vendors, "currency:shop") end if old_vendor_mods_table["easyvend"] then local nodes = {"easyvend:vendor", "easyvend:vendor_on", "easyvend:depositor", "easyvend:depositor_on"} for i in pairs(nodes) do minetest.register_node(":"..nodes[i], base_upgrade_template) table.insert(clear_craft_vendors, nodes[i]) end end if old_vendor_mods_table["vendor"] then local nodes = {"vendor:vendor", "vendor:depositor"} for i in pairs(nodes) do minetest.register_node(":"..nodes[i], base_upgrade_template) table.insert(clear_craft_vendors, nodes[i]) end end if old_vendor_mods_table["money"] then local money_template = table.copy(base_upgrade_template) money_template.can_dig = function(pos, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() return inv:is_empty("main") and (meta:get_string("owner") == player:get_player_name() or minetest.check_player_privs(player:get_player_name(), {protection_bypass=true})) end money_template.on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) local list_name = "nodemeta:"..pos.x..','..pos.y..','..pos.z if clicker:get_player_name() == meta:get_string("owner") then minetest.show_formspec(clicker:get_player_name(),"fancy_vend:money_shop_formspec", "size[8,10;]".. "list["..listname..";main;0,0;8,4;]".. "list[current_player;main;0,6;8,4;]" ) end end local nodes = {"money:barter_shop", "money:shop", "money:admin_shop", "money:admin_barter_shop"} for i in pairs(nodes) do minetest.register_node(":"..nodes[i], money_template) table.insert(clear_craft_vendors, nodes[i]) end end for i_n in pairs(clear_craft_vendors) do local currency_crafts = minetest.get_all_craft_recipes(i_n) if currency_crafts then for i in pairs(currency_crafts) do minetest.clear_craft(currency_crafts[i]) end end end
--///////////////////////////////////////////////////////// --// Boss Spawn System // --// Created By TOXIC:6/11/2020 // --//////////////////////////////////////////////////////// --//////////////////////////////////////////////////////// --// Current Boss Planet Dungeon2 // --// Current Boss Type NPC // --/////////////////////////////////////////////////////// geo_acklaybossScreenplay = ScreenPlay:new { numberOfActs = 1, planet = "yavin4", } registerScreenPlay("geo_acklaybossScreenplay", true) ----------------------------- --Start GeoAcklayBoss ScreenPlay ----------------------------- function geo_acklaybossScreenplay:start() if (isZoneEnabled(self.planet)) then self:spawnMobiles() print("GeoAcklayBoss Loaded") end end ----------------------- --GeoAcklayBoss Has Spawned ----------------------- function geo_acklaybossScreenplay:spawnMobiles() local pBoss = spawnMobile("yavin4", "acklayboss", -1,-139.8,-34,-194.3,57,1627815)--Spawn GeoAcklayBoss local creature = CreatureObject(pBoss) print("GeoAcklayBoss Spawned") createObserver(OBJECTDESTRUCTION, "geo_acklaybossScreenplay", "bossDead", pBoss)--GeoAcklayBoss Has Died Trigger Respawn Function end --------------------------------------------------------------- --GeoAcklayBoss Has Died Respawn GeoAcklayBoss With A New Dynamic Spawn --------------------------------------------------------------- function geo_acklaybossScreenplay:bossDead(pBoss) print("GeoAcklayBoss Has Died") local creature = CreatureObject(pBoss) createEvent(120 * 1000, "geo_acklaybossScreenplay", "KillBoss", pBoss, "")--Despawn Corpse createEvent(10800 * 1000, "geo_acklaybossScreenplay", "KillSpawn", pBoss, "")--Respawn Boss In 3 Hours createEvent(1 * 1000, "geo_acklaybossScreenplay", "BroadcastDead", pBoss, "")--Broadcast Dead createEvent(10800 * 1000, "geo_acklaybossScreenplay", "KillSpawnCast3", pBoss, "")--Broadcast Respawn 1 return 0 end ----------------------- --Respawn GeoAcklayBoss Boss ----------------------- function geo_acklaybossScreenplay:KillSpawn() local pBoss = spawnMobile("yavin4", "acklayboss", -1,-139.8,-34,-194.3,57,1627815)--Spawn GeoAcklayBoss After Death 3 Hour Timer local creature = CreatureObject(pBoss) print("GeoAcklayBoss Respawned") createObserver(OBJECTDESTRUCTION, "geo_acklaybossScreenplay", "bossDead", pBoss) end ----------------------------------------------------------------------------- --GeoAcklayBoss Has Died Without Being Looted, "Abandon" Destroy NPC, Destroy Loot ----------------------------------------------------------------------------- function geo_acklaybossScreenplay:KillBoss(pBoss) dropObserver(pBoss, OBJECTDESTRUCTION) if SceneObject(pBoss) then print("GeoAcklayBoss Destroyed") SceneObject(pBoss):destroyObjectFromWorld() end return 0 end ---------------------------- --Broadcast Dead ---------------------------- function geo_acklaybossScreenplay:BroadcastDead(bossObject) local boss = LuaCreatureObject(bossObject) CreatureObject(bossObject):broadcastToServer("\\#63C8F9 Large Acklay Boss Has Died.") CreatureObject(bossObject):broadcastToDiscord("Large Acklay Boss Has Died.") end ----------------------- --Broadcast Respawn 1 ----------------------- function geo_acklaybossScreenplay:KillSpawnCast3(bossObject) local boss = LuaCreatureObject(bossObject) CreatureObject(bossObject):broadcastToServer("\\#63C8F9 Large Acklay Boss Respawning.") CreatureObject(bossObject):broadcastToDiscord("Large Acklay Boss Respawning.") end
vim.cmd([[syntax enable]]) vim.o.background = "dark" -- Set colorscheme (order is important here) vim.o.termguicolors = true local kanagawa_colors = require("kanagawa.colors").setup() local overrides = { -- new highlights carpYellow = { fg = kanagawa_colors.carpYellow, bg = "NONE", style = "NONE" }, -- overide existing highlights WhichKeyValue = { fg = kanagawa_colors.crystalBlue }, LineNr = { fg = kanagawa_colors.dragonBlue }, Comment = { fg = kanagawa_colors.springBlue }, Visual = { bg = kanagawa_colors.waveBlue2 }, IncSearch = { bg = kanagawa_colors.oniViolet }, MatchParen = { fg = kanagawa_colors.sakuraPink, style = "bold" }, -- for vim-matchup SpellBad = { fg = kanagawa_colors.peachRed, style = "bold" }, SpellCap = { fg = kanagawa_colors.peachRed, style = "bold" }, SpellRare = { fg = kanagawa_colors.peachRed, style = "bold" }, SpellLocal = { fg = kanagawa_colors.peachRed, style = "bold" }, } require("kanagawa").setup({ transparent = true, overrides = overrides, }) vim.g.tokynight_style = "night" vim.g.tokyonight_transparent = true vim.g.nightflyTransparent = "1" vim.cmd([[colorscheme kanagawa]])
Hitbox = Class{ init = function(self, shape, args, tag, xoffset, yoffset) xoffset = ifndef(xoffset, 0) yoffset = ifndef(yoffset, 0) self.HCShape = nil if shape == "rectangle" then args[1] = args[1] + xoffset args[2] = args[2] + yoffset self.HCShape = HC.rectangle(unpack(args)) elseif shape == "polygon" then for a = 1, #args, 2 do args[a] = args[a] + xoffset args[a+1] = args[a+1] + yoffset end self.HCShape = HC.polygon(unpack(args)) elseif shape == "circle" then args[1] = args[1] + xoffset args[2] = args[2] + yoffset self.HCShape = HC.circle(unpack(args)) elseif shape == "point" then args[1] = args[1] + xoffset args[2] = args[2] + yoffset self.HCShape = HC.point(unpack(args)) end self.HCShape.xoffset = 0--xoffset self.HCShape.yoffset = 0--yoffset if shape ~= "polygon" then self.HCShape.xoffset = (args[1] - xoffset) / 2 self.HCShape.yoffset = (args[2] - yoffset) / 2 end self.HCShape.tag = tag self._enabled = true self.color = {255,0,0,255*(.5)} self.parent = nil HC.register(self.HCShape) end, draw = function(self, mode) love.graphics.push("all") love.graphics.setColor(self.color) self.HCShape:draw(ifndef(mode, 'fill')) love.graphics.pop() end, getHCShape = function(self) return self.HCShape end, move = function(self, x, y) self.HCShape:move(x, y) end, moveTo = function(self, x, y) self.HCShape:moveTo(x+self.HCShape.xoffset, y+self.HCShape.yoffset) end, center = function(self) return self.HCShape:center() end, enable = function(self) if not self._enabled then self._enabled = true HC.register(self.HCShape) end end, disable = function(self) if self._enabled then self._enable = false HC.remove(self.HCShape) end end, setColor = function(self, new_color) self.color = hex2rgb(new_color) self.color[4] = 255/2 end, setParent = function(self, parent) self.parent = parent end } return Hitbox
import '*'
function getPerfectBonus(isPerfect) local perfectBonus if isPerfect then perfectBonus = exports.dpShared:getEconomicsProperty("tofu_perfect_mul") if not perfectBonus then perfectBonus = 1 end else perfectBonus = 1 end return perfectBonus end function getTimeBonus(timePassed) return 1 + math.max(0, (2 - (timePassed / 60)) / 2) end function getMoneyReward(perfectBonus, timeBonus) local money = exports.dpShared:getEconomicsProperty("tofu_prize") if not money then money = 0 end return math.floor(money * perfectBonus + money * (timeBonus - 1)) end function getXpReward(perfectBonus, timeBonus) local xp = exports.dpShared:getEconomicsProperty("tofu_xp") if not xp then xp = 0 end return math.floor(xp * perfectBonus + xp * (timeBonus - 1)) end
function create_pumpjack(args) local pumpjack = table.deepcopy(data.raw["mining-drill"]["pumpjack-mk2"]) pumpjack.name = args.name pumpjack.icon = "__built-in-beacons-fe-plus__/graphics/icons/" .. args.name .. ".png" pumpjack.icon_size = 64 pumpjack.icon_mipmaps = nil pumpjack.minable.result = args.name pumpjack.module_specification.module_slots = 0 pumpjack.mining_speed = args.mining_speed pumpjack.energy_usage = args.energy_usage pumpjack.energy_source = { type = "electric", usage_priority = "secondary-input", emissions_per_minute = args.emissions_per_minute, drain = "6.7MW" } pumpjack.allowed_effects = { } pumpjack.animations.north.layers[1].filename = "__built-in-beacons-fe-plus__/graphics/entity/beaconed-fe-pumpjack/" .. args.name .. "/pumpjack-horsehead.png" pumpjack.animations.north.layers[1].animation_speed = 1 pumpjack.animations.north.layers[1].hr_version.filename = "__built-in-beacons-fe-plus__/graphics/entity/beaconed-fe-pumpjack/" .. args.name .. "/hr-pumpjack-horsehead.png" pumpjack.animations.north.layers[1].hr_version.animation_speed = 1 local result,ingredients if settings.startup["upgradeable-recipes"].value then ingredients = args.upgradeable_ingredients result = args.upgradeable_result else ingredients = args.ingredients result = args.result end data:extend({ { type = "item", name = args.name, icon = pumpjack.icon, icon_size = pumpjack.icon_size, subgroup = "fb-machines", order = args.item_order, place_result = args.name, stack_size = 50 }, { type = "recipe", name = args.name, icon = pumpjack.icon, icon_size = pumpjack.icon_size, subgroup = "fb-machines", order = args.item_order, enabled = false, ingredients = ingredients, results = result } }) data:extend({pumpjack}) end
local mqtt = require('mqtt') local assert = require('assert') local tap = require('util/tap') local TAG = "mqtt" describe('test client - mqtt', function() --local client = mqtt.connect('mqtt://test.mosquitto.org') --local client = mqtt.connect('mqtt://192.168.77.108:1883') -- 这个客户端先订阅 /test-topic, 然后再向这个主题发消息, 最后收到自己推送的消息后退出进程 -- 主要测试了 connect, subscribe, publish 这几个方法 -- 这个测试需要用到 MQTT 服务器 local url = 'mqtt://127.0.0.1:1883' url = 'mqtt://iot.wotcloud.cn:1883' local client = mqtt.connect(url) local TOPIC = '/test-topic' local MESSAGE = 'Hello mqtt' client:on('connect', function() print(TAG, 'event', 'connect') client:subscribe(TOPIC) print(TAG, 'subscribe', TOPIC) setTimeout(100, function() print(TAG, 'publish', TOPIC, MESSAGE) client:publish(TOPIC, MESSAGE) end) end) client:on('message', function (topic, message) print(TAG, 'message', topic, message) assert.equal(topic, TOPIC) assert.equal(message, MESSAGE) client:close() print(TAG, "message is OK, auto exit...") end) client:on('error', function(errInfo) print(TAG, 'event', 'error', errInfo) end) end)
------------------------------------------------------------------------------- -- LISTENER by Tammya-MoonGuard (2017) -- -- The almighty Listener window. ------------------------------------------------------------------------------- local Main = ListenerAddon local L = Main.Locale Main.Frame = {} local Me = ListenerAddon.Frame local SharedMedia = LibStub("LibSharedMedia-3.0") ------------------------------------------------------------------------------- -- For chatbox:SetMaxLines() -- local CHAT_BUFFER_SIZE = 300 ------------------------------------------------------------------------------- -- When the frame scrolls, clicks are locked for this many seconds. This is to -- prevent clicking on something else accidentally when the frame scrolls. -- local CLICKBLOCK_TIME = 0.4 ------------------------------------------------------------------------------- -- The duration of the fading animation when a frame auto_fades out. -- local FADEOUT_DURATION = 1 ------------------------------------------------------------------------------- -- When a new frame is created, the filter is loaded with this. -- local DEFAULT_LISTEN_EVENTS = { "SAY", "EMOTE", "TEXT_EMOTE", "YELL", "PARTY", "PARTY_LEADER", "RAID", "RAID_LEADER", "RAID_WARNING", "ROLL" } ------------------------------------------------------------------------------- -- Chat events that should not make a notification. -- local SKIP_BEEP = { ONLINE = true; OFFLINE = true; CHANNEL_JOIN = true; CHANNEL_LEAVE = true; GUILD_ACHIEVEMENT = true; GUILD_MOTD = true; WHISPER_INFORM = true; } Me.SKIP_BEEP = SKIP_BEEP ------------------------------------------------------------------------------- -- Prefix behind name for these types of messages. -- local MSG_FORMAT_PREFIX = { PARTY = "[P] "; PARTY_LEADER = "[P] "; RAID = "[R] "; RAID_LEADER = "[R] "; RP1 = "[RP] "; RP2 = "[RP2] "; RP3 = "[RP3] "; RP4 = "[RP4] "; RP5 = "[RP5] "; RP6 = "[RP6] "; RP7 = "[RP7] "; RP8 = "[RP8] "; RP9 = "[RP9] "; RPW = "[RP!] "; INSTANCE_CHAT = "[I] "; INSTANCE_CHAT_LEADER = "[I] "; GUILD = "[G] "; OFFICER = "[O] "; RAID_WARNING = "[RW] "; CHANNEL = "[C] "; WHISPER = L["From"] .. " "; WHISPER_INFORM = L["To"] .. " "; } ------------------------------------------------------------------------------- -- Static methods ------------------------------------------------------------------------------- local ENTRY_CHAT_REMAP = { ROLL = "SYSTEM", OFFLINE = "SYSTEM", ONLINE = "SYSTEM", GUILD_MOTD = "GUILD", GUILD_ITEM_LOOTED = "GUILD_ACHIEVEMENT" } local function GetEntryColor( e ) local info if e.c then local index = GetChannelName( e.c ) info = ChatTypeInfo[ "CHANNEL" .. index ] if not info then info = ChatTypeInfo.CHANNEL end else local t = ENTRY_CHAT_REMAP[e.e] or e.e info = ChatTypeInfo[t] if not info then info = ChatTypeInfo.SAY end end return { info.r, info.g, info.b, 1 } end ------------------------------------------------------------------------------- -- Private methods ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Initialize member variables -- local function SetupMembers( self ) -- this is to be overridden by SetFrameIndex self.listen_events = {} -- the uppermost unread message ID -- nil if the window has no "unread" messages self.top_unread_id = nil -- when a new messages is added, this saves the time -- if the user clicks on the frame at the moment a message is added, -- its ignore to prevent error self.clickblock = 0 -- textures used for the tab strips on the left side of the window self.tab_texes = {} -- this is a list of things that we can pick from with the mouse self.pick_regions = { -- table of: -- { region = region, entry = entry } } -- cached auto_fade value self.auto_fade = 0 self.auto_fade_opacity = 0 -- time since last activity self.fade_time = 0 -- this dictates that the mouse is being held over a region --self.picked = nil (too complex) end ------------------------------------------------------------------------------- local function PickTextRegion( self, setup_highlight ) if self:IsMouseOver() then for _,v in pairs( self.pick_regions ) do if v.region:IsMouseOver() then if setup_highlight then self.chatbox.highlight:SetPoint( "TOP", v.region, "TOP" ) self.chatbox.highlight:SetPoint( "BOTTOM", v.region, "BOTTOM" ) self.chatbox.highlight:Show() end return v end end end if setup_highlight and self.chatbox.highlight:IsShown() then self.chatbox.highlight:Hide() end end ------------------------------------------------------------------------------- -- Setup the frames that form the edge around the window. -- local function CreateEdges( self ) if self.edges then return end self.edges = {} for i = 1,4 do table.insert( self.edges, self:CreateTexture( "BORDER" )) end end ------------------------------------------------------------------------------- -- Add or subtract from the frame's font size. -- local function AdjustFontSize( self, delta ) local size = 0 size = self.frameopts.font.size or self.baseopts.font.size size = size + delta self:SetFontSize( size ) end ------------------------------------------------------------------------------- -- Save the window layout in the database. -- local function SaveFrameLayout( self ) if not self.frame_index then return end local point, region, point2, x, y = self:GetPoint(1) local width, height = self:GetSize() width = math.floor( width + 0.5 ) height = math.floor( height + 0.5 ) if region then region = region:GetName() end local layout = { anchor = { point, region, point2, x, y }; width = width; height = height; } self.frameopts.layout = layout LibStub("AceConfigRegistry-3.0"):NotifyChange( "Listener Frame Settings" ) end ------------------------------------------------------------------------------- local function ShowOrHide( self, show, save ) if save then self.charopts.hidden = not show if show then self.fade_time = GetTime() end end if self.charopts.hidden then if Main.active_frame == self and self.frame_index ~= 1 then Main.SetActiveFrame( Main.frames[1] ) end end self:UpdateShown() end ------------------------------------------------------------------------------- -- This enables/disables mouse interaction according to options and the shift -- key. -- local function UpdateMouseLock( self ) self:EnableMouse( self.frameopts.enable_mouse or (self.frameopts.shift_mouse and IsShiftKeyDown()) ) if self.snooper then self.chatbox:EnableMouseWheel( self.frameopts.enable_scroll or (self.frameopts.shift_mouse and IsShiftKeyDown()) ) else self.chatbox:EnableMouseWheel( true ) end end ------------------------------------------------------------------------------- -- Add or remove player from the filter. -- -- @param name Name of player. -- @param mode 1 = add player; 0 = remove player; nil = reset player -- @param silent Don't print chat messages. -- local function AddOrRemovePlayer( self, name, mode, silent ) if mode ~= 1 and mode ~= 0 and mode ~= nil then error( "Invalid mode." ) end name = Main.FixupName( name ) if self.players[name] == mode then if not silent then if mode == 1 then Main.Print( string.format( L["Already listening to %s."], name ) ) elseif mode == 0 then Main.Print( string.format( L["%s is already filtered out."], name ) ) else Main.Print( string.format( L["%s wasn't found."], name ) ) end end return end self.players[name] = mode if not silent then if mode == 1 then Main.Print( string.format( L["Added %s."], name ) ) elseif mode == 0 then Main.Print( string.format( L["Removed %s."], name ) ) else Main.Print( string.format( L["Reset %s."], name ) ) end end self:RefreshChat() self:UpdateProbe() end ------------------------------------------------------------------------------- -- Returns true if an entry should be displayed according to event filters. -- local function EntryFilter( self, entry ) if entry.c then if entry.e == "CHANNEL" then return self.listen_events[ "#" .. entry.c ] else return self.listen_events[entry.e] and self.listen_events[ "#" .. entry.c ] end end return self.listen_events[entry.e] end ------------------------------------------------------------------------------- -- Public Methods ------------------------------------------------------------------------------- local Method = {} Me.methods = Method Method.EntryFilter = EntryFilter ------------------------------------------------------------------------------- -- Link this frame to the database. -- function Method:SetFrameIndex( index ) if index == nil then return end self.frame_index = index Me.InitOptions( index ) self.players = Main.db.char.frames[index].players self.listen_events = Main.db.char.frames[index].filter self.groups = Main.db.char.frames[index].groups -- baseopts exist at the profile level and may contain -- global options. -- frameopts are options that override them. -- for the snooper frameopts is stored on the profile level -- otherwise theyre at the character level. if index == 1 then self.frameopts = Main.db.profile.frame elseif index == 2 then self.frameopts = Main.db.profile.snoop else self.frameopts = Main.db.char.frames[index] end self.baseopts = Main.db.profile.frame -- char options exist only at the character level and are -- initialized when the frame is created self.charopts = Main.db.char.frames[index] -- to set the title. self:UpdateProbe() end ------------------------------------------------------------------------------- local TIMESTAMP = { -- HH:MM:SS [1] = function( t ) return date( "%H:%M:%S ", t ) end; -- HH:MM [2] = function( t ) return date( "%H:%M ", t ) end; -- HH:MM (12-hour) [3] = function( t ) return date( "%I:%M ", t ):gsub( "^0", "" ) end; -- MM:SS [4] = function( t ) return date( "%M:%S ", t ) end; -- MM [5] = function( t ) return date( "%M ", t ) end; } ------------------------------------------------------------------------------- -- Normal "name: text" local function MsgFormatNormal( e, name ) local prefix = MSG_FORMAT_PREFIX[e.e] or "" return prefix .. name .. ": " .. e.m end ------------------------------------------------------------------------------- local function MsgFormatNormalChannel( e, name ) local prefix = MSG_FORMAT_PREFIX[e.e] or "" local index = GetChannelName( e.c ) if index ~= 0 then prefix = prefix:gsub( "C", index ) else -- this is an unregistered channel local club, stream = e.c:match( "(%d+):(%d+)" ) if not club then prefix = prefix:gsub( "C", e.c ) else local club_info = C_Club.GetClubInfo( club ) channel_name = club_info.shortName if channel_name == "" then channel_name = club_info.name end local stream_info = C_Club.GetStreamInfo( club, stream ) if stream_info.streamType ~= Enum.ClubStreamType.General then channel_name = channel_name .. " - " .. stream_info.name end prefix = prefix:gsub( "C", channel_name ) end end return prefix .. name .. ": " .. e.m end ------------------------------------------------------------------------------- -- No separator between name and text. local function MsgFormatEmote( e, name ) if Main.db.profile.trp_emotes and e.m:sub(1,3) == "|| " then return e.m:sub( 4 ) end if e.m:sub( 1,2 ) == ", " or e.m:sub( 1,2 ) == "'s" then return name .. e.m end return name .. " " .. e.m end ------------------------------------------------------------------------------- -- <name> <msg> - name is substituted local function MsgFormatTextEmote( e, name ) if e.s == "" then return e.m end -- Some dumb global emote by bosses. -- Need to convert - to %- to avoid it triggering a pattern and -- invalidating the name match. local msg = e.m:gsub( e.s:gsub("%-","%%-"), name ) return msg end ------------------------------------------------------------------------------- -- x joined/left channel. local function MsgFormatJoinLeave( e, name ) local prefix = "[" .. GetChannelName( e.c ) .. "] " if e.e == "CHANNEL_JOIN" then return prefix .. L( "{1} joined channel.", name ) elseif e.e == "CHANNEL_LEAVE" then return prefix .. L( "{1} left channel.", name ) end return "<Error>" end ------------------------------------------------------------------------------- local function MsgFormatGuildMOTD( e, name ) return "|cffffffff" .. L["Guild Message of the Day: "] .. "|r" .. e.m end ------------------------------------------------------------------------------- local MSG_FORMAT_FUNCTIONS = { SAY = MsgFormatNormal; PARTY = MsgFormatNormal; PARTY_LEADER = MsgFormatNormal; RAID = MsgFormatNormal; RAID_LEADER = MsgFormatNormal; RAID_WARNING = MsgFormatNormal; RP = MsgFormatNormal; RPW = MsgFormatNormal; YELL = MsgFormatNormal; INSTANCE_CHAT = MsgFormatNormal; INSTANCE_CHAT_LEADER = MsgFormatNormal; GUILD = MsgFormatNormal; OFFICER = MsgFormatNormal; CHANNEL = MsgFormatNormalChannel; EMOTE = MsgFormatEmote; ONLINE = MsgFormatEmote; OFFLINE = MsgFormatEmote; GUILD_ITEM_LOOTED = MsgFormatEmote; GUILD_ACHIEVEMENT = MsgFormatEmote; CHANNEL_JOIN = MsgFormatJoinLeave; CHANNEL_LEAVE = MsgFormatJoinLeave; TEXT_EMOTE = MsgFormatTextEmote; ROLL = MsgFormatTextEmote; GUILD_MOTD = MsgFormatGuildMOTD; } ------------------------------------------------------------------------------- setmetatable( MSG_FORMAT_FUNCTIONS, { __index = function( table, key ) return MsgFormatNormal end; }) ------------------------------------------------------------------------------- function Method:FormatChatMessage( e ) local stamp = "" local ts = Main.db.profile.frame.timestamps if TIMESTAMP[ts] then stamp = "|cff808080" .. TIMESTAMP[ts](e.t) .. "|r" end -- get icon and name local name, shortname, icon, color = LibRPNames.Get( e.s, Main.guidmap[e.s] ) if Main.db.profile.shorten_names then name = shortname end if not icon then local alliance = UnitFactionGroup( "player" ) == "Alliance" if e.h then alliance = not alliance end if alliance then icon = "Inv_Misc_Tournaments_banner_Human" else icon = "Inv_Misc_Tournaments_banner_Orc" end end if icon and Main.db.profile.frame.show_icons then if Main.db.profile.frame.zoom_icons then icon = "|TInterface\\Icons\\" .. icon .. ":0:0:0:0:100:100:10:90:10:90:255:255:255|t " else icon = "|TInterface\\Icons\\" .. icon .. ":0|t " end else icon = "" end if color then name = "|c" .. color .. name .. "|r" end name = "|Hplayer:" .. e.s .. "|h" .. name .. "|h" return string.format( "%s%s%s", stamp, icon, MSG_FORMAT_FUNCTIONS[e.e]( e, name ) ) end ------------------------------------------------------------------------------- -- Blocks clicks temporarily. -- -- This is called when a new message is added, as to prevent accidental clicks -- when the frame is scrolling. -- function Method:SetClickBlock() self.clickblock = GetTime() end ------------------------------------------------------------------------------- -- Toggle the frame. -- function Method:Toggle() ShowOrHide( self, self.charopts.hidden, true ) end ------------------------------------------------------------------------------- -- Hide the frame. -- function Method:Close( dontsave ) ShowOrHide( self, false, not dontsave ) end ------------------------------------------------------------------------------- -- Show the frame. -- function Method:Open( dontsave ) ShowOrHide( self, true, not dontsave ) end ------------------------------------------------------------------------------- function Method:UpdateVisibility() local hover = self:IsMouseOver( 8, -8, -8, 8 ) local faded = self.auto_fade > 0 and GetTime() > self.fade_time + self.auto_fade self:ShowBar( (hover and not (self.frameopts.locked and self.frameopts.hide_bar_when_locked)) or self.dragging or (Main.active_frame == self and not faded) ) if self.auto_fade > 0 then local alpha = self:GetAlpha() local newalpha local time = GetTime() if hover then newalpha = 1 else local fadeout_start = self.fade_time + self.auto_fade if time >= fadeout_start then if time - fadeout_start < FADEOUT_DURATION then local d = (time - fadeout_start) / FADEOUT_DURATION newalpha = 1 + (self.auto_fade_opacity - 1) * d else newalpha = self.auto_fade_opacity if Main.active_frame == self and self.frame_index ~= 1 then Main.SetActiveFrame( Main.frames[1] ) end end else newalpha = 1 end end if alpha ~= newalpha then self:SetAlpha( newalpha ) end end end ------------------------------------------------------------------------------- function Method:ShowBar( show ) if show and not self.bar2:IsShown() then self.bar2:Show() self.chatbox:SetPoint( "TOP", self.bar2, "BOTTOM", 0, -1 ) elseif not show and self.bar2:IsShown() then self.bar2:Hide() self.chatbox:SetPoint( "TOP", self, 0, -2 ) end end ------------------------------------------------------------------------------- -- Set the chat font size. -- function Method:SetFontSize( size ) size = math.max( size, 6 ) size = math.min( size, 24 ) self.frameopts.font.size = size self:ApplyChatOptions() end ------------------------------------------------------------------------------- -- Load all options. -- function Method:ApplyOptions() self:SetFrameIndex( self.frame_index ) self:ApplyLayoutOptions() self:ApplyChatOptions() self:ApplyColorOptions() self:ApplyBarOptions() self:ApplyOtherOptions() end ------------------------------------------------------------------------------- function Method:ApplyOtherOptions() self.bar2.hidden_button:SetOn( self.charopts.showhidden ) self.auto_fade = self.frameopts.auto_fade or self.baseopts.auto_fade self.auto_fade_opacity = self.baseopts.auto_fade_opacity / 100 self:UpdateResizeShow() UpdateMouseLock( self ) end ------------------------------------------------------------------------------- function Method:ApplyColorOptions() local bgcolor = self.frameopts.color.bg or self.baseopts.color.bg self.bg:SetColorTexture( unpack( bgcolor )) local edgecolor = self.frameopts.color.edge or self.baseopts.color.edge for k,v in pairs( self.edges ) do v:SetColorTexture( unpack( edgecolor )) end local bar_color = self.frameopts.color.bar or self.baseopts.color.bar self.bar2.bg:SetColorTexture( unpack( bar_color ) ) end ------------------------------------------------------------------------------- -- Options for the positioning/size. -- function Method:ApplyLayoutOptions() local layout layout = self.frameopts.layout self:ClearAllPoints() local anchor = layout.anchor if not anchor or #anchor == 0 then if self.frame_index == 1 then -- primary self:SetPoint( "LEFT", 50, 0 ) else -- secondary self:SetPoint( "CENTER", 0, 0 ) end else local region = anchor[2] if not region then region = UIParent else region = _G[region] end self:SetPoint( anchor[1], region, anchor[3], anchor[4], anchor[5] ) end self:SetSize( math.max( layout.width, 50 ), math.max( layout.height, 50 ) ) -- setup edges local es = Main.db.profile.frame.edge_size if es == 0 then for _, edge in pairs( self.edges ) do edge:Hide() end else Me.CraftEdges( self, es ) end if self.charopts.hidden then self:Hide() else self:Show() end end ------------------------------------------------------------------------------- -- Options for the chat/text appearance. -- function Method:ApplyChatOptions() local outline = self.frameopts.font.outline or self.baseopts.font.outline local face = self.frameopts.font.face or self.baseopts.font.face local size = self.frameopts.font.size or self.baseopts.font.size local shadow = self.frameopts.font.shadow if shadow == nil then shadow = self.baseopts.font.shadow end if outline == 2 then outline = "OUTLINE" elseif outline == 3 then outline = "THICKOUTLINE" else outline = nil end face = SharedMedia:Fetch( "font", face ) self.chatbox:SetFont( face, size, outline ) if shadow then self.chatbox:SetShadowColor( 0, 0, 0, 0.8 ) self.chatbox:SetShadowOffset( 1, -1 ) else self.chatbox:SetShadowColor( 0, 0, 0, 0 ) end local tabsize = self.frameopts.tab_size or self.baseopts.tab_size self.chatbox:SetPoint( "LEFT", self, "LEFT", 2 + tabsize, 0 ) end ------------------------------------------------------------------------------- -- Options for the title bar. -- function Method:ApplyBarOptions() local o = self.frameopts.close_button if o == nil then o = self.baseopts.close_button end if not o then self.bar2.close_button:Hide() self.bar2.hidden_button:SetPoint( "TOPRIGHT", 0, 0 ) else self.bar2.close_button:Show() self.bar2.hidden_button:SetPoint( "TOPRIGHT", -15, 0 ) end end ------------------------------------------------------------------------------- -- Add chat events to the chat filter. -- -- Channels are treated differently. To listen to a channel, prefix name -- with #, e.g. "#secret" -- function Method:AddEvents( ... ) local arg = {...} local dirty = false for k,v in pairs(arg) do v = v:upper() if not self.listen_events[v] then self.listen_events[v] = true dirty = true end end if dirty then self:RefreshChat() end end ------------------------------------------------------------------------------- -- Remove chat events from display. -- function Method:RemoveEvents( ... ) local arg = {...} local dirty = false for k,v in pairs(arg) do v = v:upper() if self.listen_events[v] then self.listen_events[v] = nil dirty = true end end if dirty then self:RefreshChat() end end ------------------------------------------------------------------------------- -- Returns true if an event is being listened to. -- function Method:HasEvent( event ) if self.listen_events[event:upper()] then return true end return nil end ------------------------------------------------------------------------------- -- Returns true if this entry is displayed. -- function Method:ShowsEntry( entry ) return EntryFilter( self, entry ) end ------------------------------------------------------------------------------- -- Returns the listen_events table. -- This is a map of which events are being listened to. -- Do not modify the returned table. -- function Method:GetListenEvents() return self.listen_events end ------------------------------------------------------------------------------- -- Add player to filter. -- -- @param name Name of player. -- @param silent Do not print chat message. function Method:AddPlayer( name, silent ) AddOrRemovePlayer( self, name, 1, silent ) end ------------------------------------------------------------------------------- function Method:RemovePlayer( name, silent ) AddOrRemovePlayer( self, name, 0, silent ) end ------------------------------------------------------------------------------- -- Returns true if the window is listening to someone. -- function Method:ListeningTo( name ) -- filter path: -- global (listenall) -> group -> player -- local f = self.players[name] if IsInRaid() then local g = Main.raid_groups[name] if g then -- if f is default then try using group filter f = f or self.groups[g] end end return f == 1 or (self.charopts.listen_all and f ~= 0) end function Method:ResetGroupsFilter() for k,_ in pairs( self.groups ) do self.groups[k] = nil end end ------------------------------------------------------------------------------- -- Toggle filter for player. -- -- @param name Player name. -- @param silent Do not print chat message. -- function Method:TogglePlayer( name, silent ) name = Main.FixupName( name ) if self.players[name] == 1 then self:RemovePlayer( name, silent ) elseif self.players[name] == 0 then self:AddPlayer( name, silent ) else if self.charopts.listen_all then self:RemovePlayer( name, silent ) else self:AddPlayer( name, silent ) end end end ------------------------------------------------------------------------------- -- Called when the window is active and the probe target changes. -- function Method:UpdateProbe() if self.snooper then return end -- the snooper does not have this. local title = self.charopts.name if self.frame_index == 1 then title = "Listener" end local on = false local target, guid = Main:GetProbed() if target then on = self:ListeningTo( target ) local name, shortname = LibRPNames.Get( target ) title = Main.db.profile.shorten_names and shortname or name end self.bar2.title:SetText( title ) if on or not target then self.bar2.title.text:SetAlpha( 1.0 ) else self.bar2.title.text:SetAlpha( 0.5 ) end if Main.db.profile.frame.color.tab_target[4] > 0 then self:UpdateHighlight() end end ------------------------------------------------------------------------------- -- Add a message directly to the chat window. -- -- @param e Message event data. -- @param beep Enable playing a beep. -- function Method:AddMessage( e, beep, from_refresh ) if not EntryFilter( self, e ) then return false end if not self.refreshing then self.fade_time = GetTime() end local hidden = not self:ListeningTo( e.s ) if hidden and not self.bar2.hidden_button:IsShown() and not self.snooper then self.bar2.hidden_button:Show() end if e.r and not e.p and not hidden then -- not read and not from the player and not hidden if self:IsShown() then if beep and not SKIP_BEEP[e.e] then if self.charopts.sound then Main.PlayMessageBeep( self.frameopts.notify_sound or self.baseopts.notify_sound ) end if self.charopts.flash then Main.FlashClient() end end end if self.top_unread_id == nil then self.top_unread_id = e.id end end local color = GetEntryColor( e ) self.chatbox:AddMessage( self:FormatChatMessage( e ), color[1], color[2], color[3], nil, nil, nil, e ) -- autopopup/hideempty popup if not self:IsShown() and not from_refresh then if self.frameopts.auto_popup and not hidden then if self.frameopts.combathide and InCombatLockdown() then -- if we're in combat, just clear the hidden flag -- so that it opens when we exit combat self.charopts.hidden = false -- this causes the window to fade in after combat ends. self.fadein_after_combat = true else self:Open() end end if self.frameopts.hideempty then self:UpdateShown() end end return true end ------------------------------------------------------------------------------- -- Add a message into the chat window if it passes our filters. -- function Method:TryAddMessage( e, beep ) if self.charopts.showhidden or self:ListeningTo( e.s ) then if self:AddMessage( e, beep ) then if self.chatbox:GetScrollOffset() == 0 then self:SetClickBlock() end end else if EntryFilter( self, e ) and not self.snooper then self.bar2.hidden_button:Show() end end end ------------------------------------------------------------------------------- function Method:CheckUnread() self.top_unread_id = nil local id = nil for k,v in pairs( Main.unread_entries ) do if EntryFilter( self, k ) and self:ListeningTo( k.s ) then if not id or k.id < id then id = k.id end end end self.top_unread_id = id end ------------------------------------------------------------------------------- -- Update the unread messages marker. -- -- Sub function for UpdateHighlight. -- -- @param region This is the fontstring that is showing the first unread -- region -- local function UpdateReadmark( self, region, first_id ) -- todo: option for hiding readmark here. self.readmark:SetColorTexture( unpack( Main.db.profile.frame.color.readmark ) ) if region then -- set the marker here local point = region:GetTop() - self.chatbox:GetBottom() if point > self.chatbox:GetHeight()+1 then --point = self.chatbox:GetHeight() --self.readmark:SetHeight( 2 ) self.readmark:Hide() return else self.readmark:SetHeight( 1 ) end self.readmark:SetPoint( "TOP", self.chatbox, "BOTTOM", 0, point ) self.readmark:Show() elseif self.top_unread_id then if first_id < self.top_unread_id then -- past the bottom self.readmark:SetHeight( 2 ) self.readmark:SetPoint( "TOP", self, "BOTTOM", 0, 3 ) else -- past the top self.readmark:Hide() return --self.readmark:SetPoint( "TOP", self.chatbox, "BOTTOM", 0, self.chatbox:GetHeight() - 1 ) end self.readmark:Show() else -- no unread messages self.readmark:Hide() end end ------------------------------------------------------------------------------- function Method:UpdateHighlight() if not Main.db then return end -- not initialized yet local regions = {} -- create a list of message regions for k,v in pairs( { self.chatbox.FontStringContainer:GetRegions() } ) do if v:GetObjectType() == "FontString" and v:IsShown() then v:SetNonSpaceWrap( true ) -- a nice hack for nonspacewrap text table.insert( regions, v ) end end -- sort by Y table.sort( regions, function( a, b ) return a:GetTop() < b:GetTop() end) local bottom = self.chatbox:GetNumMessages() - self.chatbox:GetScrollOffset() local index = bottom local top_edge = self.chatbox:GetTop() + 1 -- that one pixel local first_unread_region = nil --local first_unread_id = 0 local tabsize = self.frameopts.tab_size or self.baseopts.tab_size -- we'll build the pick_regions table in here too! local pick_regions = {} local count = 0 for k,v in ipairs( regions ) do if index < 1 then break end local _,_,_,_,_,_,_,e = self.chatbox:GetMessageInfo( index ) index = index - 1 if not e then break end if v:GetBottom() < top_edge then -- within the chatbox only table.insert( pick_regions, { region = v, entry = e } ) local hidden = not self:ListeningTo( e.s ) v:SetAlpha( hidden and 0.35 or 1.0 ) if e.id == self.top_unread_id then first_unread_region = v end local targeted = (Main.GetProbed() == e.s) and (Main.db.profile.frame.color.tab_target[4] > 0) if tabsize > 0 and ((targeted or e.p) and not self.snooper) or e.h then -- setup block count = count + 1 if not self.tab_texes[count] then self.tab_texes[count] = self:CreateTexture() end local tex = self.tab_texes[count] tex:ClearAllPoints() tex:SetPoint( "LEFT", v, "LEFT", -1 - tabsize, 0 ) tex:SetPoint( "RIGHT", v, "LEFT", -1, 0 ) tex:SetPoint( "BOTTOM", v, "BOTTOM", 0, 0 ) local clip = math.max( v:GetTop() - top_edge, 0 ) tex:SetPoint( "TOP", v, "TOP", 0, -clip ) tex:SetBlendMode( "BLEND" ) if e.h then tex:SetColorTexture( unpack( Main.db.profile.frame.color.tab_marked ) ) elseif e.p then tex:SetColorTexture( unpack( Main.db.profile.frame.color.tab_self ) ) elseif targeted then tex:SetColorTexture( unpack( Main.db.profile.frame.color.tab_target ) ) end tex:Show() end end end self.pick_regions = pick_regions local _,_,_,_,_,_,_,e = self.chatbox:GetMessageInfo( bottom ) if e and (self.baseopts.color.readmark[4] > 0) and self.frameopts.readmark then UpdateReadmark( self, first_unread_region, e.id ) else self.readmark:Hide() end for i = count+1, #self.tab_texes do self.tab_texes[i]:Hide() end end ------------------------------------------------------------------------------- function Method:UpdateShown() if self:IsShown() then if self.charopts.hidden or ((not self.combat_ignore) and self.frameopts.combathide and ((InCombatLockdown() or Main.in_combat))) or (self.chatbox:GetNumMessages() == 0 and self.frameopts.hideempty and not self.mouseon) then self:Hide() end else if not self.charopts.hidden and not ((not self.combat_ignore) and self.frameopts.combathide and (InCombatLockdown() or Main.in_combat)) and not (self.chatbox:GetNumMessages() == 0 and self.frameopts.hideempty) then self:Show() end end end ------------------------------------------------------------------------------- function Method:RefreshChat() self.refreshing = true self.chatbox:Clear() self:CheckUnread() if not self.snooper then local entries = {} local listen_all = self.charopts.listen_all local showhidden = self.charopts.showhidden local start_messages = self.frameopts.start_messages or self.baseopts.start_messages local hashidden = false -- go through the chat list and populate entries for i = Main.next_lineid-1, Main.first_lineid, -1 do local entry = Main.chatlist[i] if entry then if EntryFilter( self, entry ) then if showhidden or self:ListeningTo( entry.s ) then table.insert( entries, entry ) else hashidden = true end end end -- break when we have enough messages if #entries >= start_messages then break end end if hashidden then self.bar2.hidden_button:Show() else self.bar2.hidden_button:Hide() end -- TODO: disable chatbox refreshes until this is done -- (check to see if its spammed.) for i = #entries, 1, -1 do self:AddMessage( entries[i], false, true ) end else if self.snoop_player then local chat = Main.chat_history[self.snoop_player] if chat then local entries = {} local start_messages = self.frameopts.start_messages or self.baseopts.start_messages for i = #chat, 1, -1 do local e = chat[i] if EntryFilter( self, e ) then table.insert( entries, e ) end if #entries >= start_messages then break end end for i = #entries, 1, -1 do self:AddMessage( entries[i], false, true ) end end end end self:UpdateShown() self.refreshing = false end ------------------------------------------------------------------------------- -- Set the window colors. -- -- @param bg, edge, bar Colors for the background, edge, and titlebar -- {r, g, b, a}, range = 0-1, pass nil to not change. -- function Method:SetColors( bg, edge, bar ) if bg then self.frameopts.color.bg = bg end if edge then self.frameopts.color.edge = edge end if bar then self.frameopts.color.bar = bar end self:ApplyColorOptions() end ------------------------------------------------------------------------------- -- Set Listen All mode. (default filter mode) -- function Method:SetListenAll( listen_all ) listen_all = not not listen_all if self.charopts.listen_all == listen_all then return end self.charopts.listen_all = listen_all self:RefreshChat() self:UpdateProbe() end ------------------------------------------------------------------------------- -- Enable/disable showing filtered out players. -- function Method:ShowHidden( showhidden ) showhidden = not not showhidden if self.charopts.showhidden == showhidden then return end self.charopts.showhidden = showhidden self:RefreshChat() if showhidden then self.bar2.hidden_button:SetOn( true ) else self.bar2.hidden_button:SetOn( false ) end end ------------------------------------------------------------------------------- -- Update the visibility of the resize thumb. -- function Method:UpdateResizeShow() if not self.frameopts.locked then self.resize_thumb:Show() return end if (self.mouseon and IsShiftKeyDown()) or self.doingSizing then self.resize_thumb:Show() else self.resize_thumb:Hide() end end ------------------------------------------------------------------------------- function Method:StartDragging() self.dragging = true self:StartMoving() end ------------------------------------------------------------------------------- function Method:StopDragging() if self.dragging then self.dragging = false self:StopMovingOrSizing() SaveFrameLayout( self ) end end ------------------------------------------------------------------------------- function Method:CombatHide( combat ) -- the combat_ignore flag is set when the user toggles the frame on -- so that, if they're in combat, they can turn on the frame -- on manually, still, but the next time they enter combat -- it will be reset. if combat then self.combat_ignore = nil end self:UpdateShown() if not combat and self.fadein_after_combat then self.fade_time = GetTime() end end ------------------------------------------------------------------------------- function Method:OpenConfig() Main.FrameConfig_Open( self ) end ------------------------------------------------------------------------------- function Method:CopyText() local text = "" for i = 1, self.chatbox:GetNumMessages() - self.chatbox:GetScrollOffset() do local msg = self.chatbox:GetMessageInfo( i ) if text ~= "" then text = text .. "\n" end text = text .. msg end -- filter out some things (icons) text = text:gsub( "|T.-|t%s*", "" ) Main.CopyFrame.Show( text ) end ------------------------------------------------------------------------------- function Method:MouseOn() self.mouseon = true self:UpdateResizeShow() end ------------------------------------------------------------------------------- function Method:MouseOff() self.mouseon = false C_Timer.After( 0.1, function() self:UpdateShown() self:UpdateResizeShow() end) end ------------------------------------------------------------------------------- function Method:OnModifierPressed() UpdateMouseLock( self ) end ------------------------------------------------------------------------------- -- Handlers (And psuedo ones.) ------------------------------------------------------------------------------- function Me.OnLoad( self ) -- populate with methods for k,v in pairs( Method ) do self[k] = v end SetupMembers( self ) -- initial settings self.chatbox:SetMaxLines( CHAT_BUFFER_SIZE ) self:EnableMouse( true ) self:SetClampedToScreen( true ) Me.CraftEdges( self, 2 ) hooksecurefunc( self.chatbox, "RefreshDisplay", function() Me.OnChatboxRefresh( self ) end) end ------------------------------------------------------------------------------- function Me.OnEnter( self ) self:MouseOn() self.show_highlight = true end ------------------------------------------------------------------------------- function Me.OnLeave( self ) self:MouseOff() self.show_highlight = false end ------------------------------------------------------------------------------- local function DoPainting( self, pid ) if not self.painting then return end local step = 1 if pid < self.painting_id then step = -1 end local showhidden = self.charopts.showhidden local found = false for id = self.painting_id, pid, step do local e = Main.chatlist[id] if e and e.h ~= self.painting_on and EntryFilter( self, e ) and (showhidden or self:ListeningTo( e.s )) then found = true Main.HighlightEntry( e, self.painting_on ) end end self.painting_id = pid end ------------------------------------------------------------------------------- function Me.OnUpdate( self ) self:UpdateVisibility() local picked = nil if (self.show_highlight or self.painting) then -- do some picking picked = PickTextRegion( self, true ) if self.painting and GetTime() > self.clickblock + CLICKBLOCK_TIME then if picked and picked.entry then DoPainting( self, picked.entry.id ) else local x,y = GetCursorPosition() local scale = UIParent:GetEffectiveScale() x = x / scale y = y / scale if x >= self.chatbox:GetLeft() and x <= self.chatbox:GetRight() then local p local top = self.pick_regions[#self.pick_regions] if top then top = top.region:GetTop() end if y <= self.chatbox:GetBottom() then p = self.pick_regions[1] elseif y >= top then p = self.pick_regions[#self.pick_regions] end if p and p.entry then DoPainting( self, p.entry.id ) end end end end else if self.chatbox.highlight:IsShown() then self.chatbox.highlight:Hide() end end end ------------------------------------------------------------------------------- function Me.OnMouseDown( self, button ) local active = Main.active_frame == self -- if not active and not self.snooper then -- Main.SetActiveFrame( self ) -- end local faded = false if self.auto_fade > 0 and GetTime() > self.fade_time + self.auto_fade then faded = true end if GetTime() > self.clickblock + CLICKBLOCK_TIME then local p = PickTextRegion( self, false ) if p then local tabsize = self.frameopts.tab_size or self.baseopts.tab_size if button == "LeftButton" and tabsize > 0 then self.painting = true self.painting_on = not p.entry.h if not self.painting_on then self.painting_on = nil end self.painting_id = p.entry.id Main.HighlightEntry( p.entry, not p.entry.h ) elseif button == "RightButton" then if IsShiftKeyDown() and not self.snooper then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:TogglePlayer( p.entry.s, true ) end end end end self.fade_time = GetTime() end ------------------------------------------------------------------------------- function Me.OnMouseUp( self ) self.painting = false end ------------------------------------------------------------------------------- -- For scrollwheel. -- function Me.OnChatboxScroll( self, delta ) local reps = IsShiftKeyDown() and 5 or 1 -- for the snooper, shift is used to activate the mouse sometimes -- if so, ignore the shift modifier in here. -- for normal windows, mouse wheel always works, so functionality is normal if self.snooper and self.frameopts.shift_mouse then reps = 1 end if delta > 0 then if IsAltKeyDown() then self.chatbox:ScrollToTop() elseif IsControlKeyDown() then AdjustFontSize( self, 1 ) else for i = 1, reps do self.chatbox:ScrollUp() end end else if IsAltKeyDown() then self.chatbox:ScrollToBottom() elseif IsControlKeyDown() then AdjustFontSize( self, -1 ) else for i = 1,reps do self.chatbox:ScrollDown() end end end self.fade_time = GetTime() end ------------------------------------------------------------------------------- local g_listener_copylink_text = "" StaticPopupDialogs["LISTENER_COPYLINK"] = { text = L["Copy Link"]; button1 = L["Got it!"]; timeout = 0, whileDead = true, hideOnEscape = true, enterClicksFirstButton = true, hasEditBox = true, EditBoxOnEscapePressed = function(self) self:GetParent():Hide(); end; EditBoxOnEnterPressed = function(self, data) self:GetParent():Hide(); end; OnShow = function ( self ) self.editBox:SetMaxLetters( 0 ) self.editBox:SetText( g_listener_copylink_text ) self.editBox:HighlightText() end } ------------------------------------------------------------------------------- function Me.OnChatboxHyperlinkClick( self, link, text, button ) if GetTime() < self.clickblock + CLICKBLOCK_TIME then -- block clicks when scroll changes return end if strsub(link, 1, 6) == "player" then local namelink, isGMLink; if strsub(link, 7, 8) == "GM" then namelink = strsub(link, 10); isGMLink = true; else namelink = strsub(link, 8); end local name, lineid, chatType, chatTarget = strsplit(":", namelink); if IsShiftKeyDown() and button == "RightButton" and not self.snooper then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:TogglePlayer( name, true ) return end end if link == "lrurl" then g_listener_copylink_text = text:match( "url|h(%S+)|h|r$" ) StaticPopup_Show( "LISTENER_COPYLINK" ) return end SetItemRef( link, text, button, DEFAULT_CHAT_FRAME ); self.fade_time = GetTime() end ------------------------------------------------------------------------------- function Me.OnChatboxRefresh( self ) -- show or hide the scroll marker if we are scrolled up if self.chatbox:GetScrollOffset() ~= 0 then self.scrollmark:Show() else self.scrollmark:Hide() end -- this should only be called when the scroll actually changes self:UpdateHighlight() end ------------------------------------------------------------------------------- function Me.TogglePlayerClicked( self, button ) if button == "LeftButton" then -- shift-click for normal windows toggles listen_all -- snooper doesn't have that feature if IsShiftKeyDown() and not self.snooper then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:SetListenAll( not self.charopts.listen_all ) else -- if you aren't targeting anyone, then left click -- opens the menu, otherwise it toggles the player -- local name = Main.GetProbed() if name and not self.snooper then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:TogglePlayer( name, true ) else if self.snooper then Main.Snoop2.ShowMenu() else self:ShowMenu() end end end elseif button == "RightButton" then if self.snooper then Main.Snoop2.ShowMenu() else self:ShowMenu() end end end ------------------------------------------------------------------------------- function Me.ShowHiddenClicked( self, button ) if button == "LeftButton" then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:ShowHidden( not self.charopts.showhidden ) end end ------------------------------------------------------------------------------- function Me.CloseClicked( self, button ) if button == "LeftButton" then PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON ) self:Close() end end ------------------------------------------------------------------------------- function Me.BarMouseDown( self ) self.fade_time = GetTime() if not self.snooper then Main.SelectFrame( self ) end if (not self.frameopts.locked) or IsShiftKeyDown() then self:StartDragging() end end function Me.BarMouseUp( self ) self:StopDragging() self.fade_time = GetTime() end function Me.BarDragStart( self ) end function Me.BarDragStop( self ) end ------------------------------------------------------------------------------- -- resize_thumb handlers. ------------------------------------------------------------------------------- function Me.ResizeThumb_OnMouseDown( self, button ) self:SetButtonState( "PUSHED", true ); self:GetHighlightTexture():Hide(); self:GetParent():StartSizing( "BOTTOMRIGHT" ); self:GetParent().doingSizing = true end ------------------------------------------------------------------------------- function Me.ResizeThumb_OnMouseUp( self, button ) self:SetButtonState( "NORMAL", false ); self:GetHighlightTexture():Show(); local parent = self:GetParent() parent:StopMovingOrSizing(); SaveFrameLayout( parent ) parent.doingSizing = false parent:UpdateResizeShow() end ------------------------------------------------------------------------------- function Me.ResizeThumb_OnLeave( self ) end ------------------------------------------------------------------------------- -- Other static functions ------------------------------------------------------------------------------- function Me.CraftEdges( frame, width ) if not frame.edges then frame.edges = {} for i = 1,4 do frame.edges[i] = frame:CreateTexture( "BORDER" ) end end -- top frame.edges[1]:SetPoint( "TOPLEFT", frame, "TOPLEFT", -width, width ) frame.edges[1]:SetPoint( "BOTTOMRIGHT", frame, "TOPRIGHT", width, 0 ) -- bottom frame.edges[2]:SetPoint( "TOPLEFT", frame, "BOTTOMLEFT", -width, 0 ) frame.edges[2]:SetPoint( "BOTTOMRIGHT", frame, "BOTTOMRIGHT", width, -width ) -- left frame.edges[3]:SetPoint( "TOPLEFT", frame, "TOPLEFT", -width, 0 ) frame.edges[3]:SetPoint( "BOTTOMRIGHT", frame, "BOTTOMLEFT", -0, 0 ) -- right frame.edges[4]:SetPoint( "TOPLEFT", frame, "TOPRIGHT", 0, 0 ) frame.edges[4]:SetPoint( "BOTTOMRIGHT", frame, "BOTTOMRIGHT", width, 0 ) for _, edge in pairs( frame.edges ) do edge:Show() end end ------------------------------------------------------------------------------- -- Initialize a section in the database for a new frame -- function Me.InitOptions( index ) -- only initialize things that are per-character options -- don't initialize things that you don't want in the -- primary frame's options if not Main.db.char.frames[index] then -- initial creation. Main.db.char.frames[index] = { players = {}; groups = {}; listen_all = true; filter = {}; -- filled in below showhidden = true; layout = { anchor = {}; width = 200; height = 300; }; hidden = false; color = {}; font = {}; readmark = true; enable_mouse = true; } for k,v in pairs( DEFAULT_LISTEN_EVENTS ) do Main.db.char.frames[index].filter[v] = true end end -- we also want to make sure that all tables are there so errors don't happen local data = Main.db.char.frames[index] data.players = data.players or {} data.groups = data.groups or {} data.filter = data.filter or {} data.layout = data.layout or { anchor = {}; width = 200; height = 300; } data.color = data.color or {} data.font = data.font or {} -- we might want to make an option for this. data.players[ UnitName("player") ] = 1 data.players[ "Guild" ] = 1 end ------------------------------------------------------------------------------- -- Apply the globally set options (ones that affect all frames, like the -- titlebar font). -- function Me.ApplyGlobalOptions() -- bar font local font = SharedMedia:Fetch( "font", Main.db.profile.frame.barfont.face ) ListenerBarFont:SetFont( font, Main.db.profile.frame.barfont.size ) end
local screenName = Var "LoadingScreen" local headerTextImage --this should probably be a metric if screenName == "ScreenSelectMusic" then headerTextImage = "Music.png" elseif screenName == "ScreenPlayerOptions" then headerTextImage = "Options.png" elseif screenName == "ScreenMapControllers" then headerTextImage = "Options.png" elseif screenName == "ScreenOptionsService" then headerTextImage = "optionsserv.png" elseif screenName == "ScreenOptionsServiceChild" then headerTextImage = "optionsserv.png" elseif screenName == "ScreenSelectStyle" then headerTextImage = "style.png" elseif screenName == "ScreenSelectDifficulty" then headerTextImage = "diff.png" elseif screenName == "ScreenEvaluationNormal" then headerTextImage = "eval.png" elseif screenName == "ScreenEvaluationSummary" then headerTextImage = "eval.png" elseif screenName == "ScreenEvaluationOni" then headerTextImage = "eval.png" elseif screenName == "ScreenEvaluationNonstop" then headerTextImage = "eval.png" end --Base Anchoring local out = Def.ActorFrame{ LoadActor("time_slash")..{ InitCommand=cmd(x,SCREEN_RIGHT-54;y,SCREEN_TOP+26;draworder,99); }; } --Text Anchoring if headerTextImage then table.insert(out,LoadActor(headerTextImage)..{ InitCommand=function(self) self:x(SCREEN_CENTER_X-160):y(SCREEN_TOP+40):diffusealpha(1) end; }) end return out
-------------------------------------------------------------------------------- -- Define the restrictions and set the number of initial states. -------------------------------------------------------------------------------- InitialRestrictions = {NFermions, NBosons, {"11 0000000000", NElectrons_#i, NElectrons_#i}, {"00 1111111111", NElectrons_#f, NElectrons_#f}} FinalRestrictions = {NFermions, NBosons, {"11 0000000000", NElectrons_#i - 1, NElectrons_#i - 1}, {"00 1111111111", NElectrons_#f + 1, NElectrons_#f + 1}} CalculationRestrictions = nil if PdHybridizationTerm then InitialRestrictions = {NFermions, NBosons, {"11 0000000000 000000", NElectrons_#i, NElectrons_#i}, {"00 1111111111 000000", NElectrons_#f, NElectrons_#f}, {"00 0000000000 111111", NElectrons_4p, NElectrons_4p}} FinalRestrictions = {NFermions, NBosons, {"11 0000000000 000000", NElectrons_#i - 1, NElectrons_#i - 1}, {"00 1111111111 000000", NElectrons_#f + 1, NElectrons_#f + 1}, {"00 0000000000 111111", NElectrons_4p, NElectrons_4p}} CalculationRestrictions = {NFermions, NBosons, {"00 0000000000 111111", NElectrons_4p, NElectrons_4p + 1}} end
--- -- Custom weapon base, used to derive from CS one, still very similar. -- See <a href="https://wiki.garrysmod.com/page/Category:Weapon">Weapon</a> -- @class Weapon local math = math local table = table local util = util local IsValid = IsValid local surface = surface local draw = draw local CreateClientConVar = CreateClientConVar if SERVER then AddCSLuaFile() end if CLIENT then -- hud help font surface.CreateFont("weapon_hud_help", {font = "Trebuchet24", size = 14, weight = 600}) end -- TTT SPECIAL EQUIPMENT FIELDS -- This must be set to one of the WEAPON_ types in TTT weapons for weapon -- carrying limits to work properly. See /gamemode/shared.lua for all possible -- weapon categories. SWEP.Kind = WEAPON_NONE -- If CanBuy is a table that contains ROLE_TRAITOR and/or ROLE_DETECTIVE, those -- players are allowed to purchase it and it will appear in their Equipment Menu -- for that purpose. If CanBuy is nil this weapon cannot be bought. -- Example: SWEP.CanBuy = { ROLE_TRAITOR } -- (just setting to nil here to document its existence, don't make this buyable) SWEP.CanBuy = nil if CLIENT then -- If this is a buyable weapon (ie. CanBuy is not nil) EquipMenuData must be -- a table containing some information to show in the Equipment Menu. See -- default equipment weapons for real-world examples. SWEP.EquipMenuData = nil -- Example data: -- SWEP.EquipMenuData = { -- -- Type tells players if it's a weapon or item -- type = "Weapon", -- -- Desc is the description in the menu. Needs manual linebreaks (via \n). -- desc = "Text." -- } -- This sets the icon shown for the weapon in the DNA sampler, search window, -- equipment menu (if buyable), etc. SWEP.Icon = "vgui/ttt/icon_nades" -- most generic icon I guess -- You can make your own weapon icon using the template in: -- /garrysmod/gamemodes/terrortown/template/ -- Open one of TTT's icons with VTFEdit to see what kind of settings to use -- when exporting to VTF. Once you have a VTF and VMT, you can -- resource.AddFile("materials/vgui/...") them here. GIVE YOUR ICON A UNIQUE -- FILENAME, or it WILL be overwritten by other servers! Gmod does not check -- if the files are different, it only looks at the name. I recommend you -- create your own directory so that this does not happen, -- eg. /materials/vgui/ttt/mycoolserver/mygun.vmt end -- MISC TTT-SPECIFIC BEHAVIOUR CONFIGURATION -- ALL weapons in TTT must have weapon_tttbase as their SWEP.Base. It provides -- some functions that TTT expects, and you will get errors without them. -- Of course this is weapon_tttbase itself, so I comment this out here. -- SWEP.Base = "weapon_tttbase" -- If true AND SWEP.Kind is not WEAPON_EQUIP, then this gun can be spawned as -- random weapon by a ttt_random_weapon entity. SWEP.AutoSpawnable = false -- Set to true if weapon can be manually dropped by players (with Q) SWEP.AllowDrop = true -- Set to true if weapon kills silently (no death scream) SWEP.IsSilent = false -- If this weapon should be given to players upon spawning, set a table of the -- roles this should happen for here -- SWEP.InLoadoutFor = {ROLE_TRAITOR, ROLE_DETECTIVE, ROLE_INNOCENT} -- use the Initialize hook to be able to use custom ROLE_XXX vars -- DO NOT set SWEP.WeaponID. Only the standard TTT weapons can have it. Custom -- SWEPs do not need it for anything. -- SWEP.WeaponID = nil -- YE OLDE SWEP STUFF if CLIENT then SWEP.DrawCrosshair = false SWEP.ViewModelFOV = 82 SWEP.ViewModelFlip = true SWEP.CSMuzzleFlashes = true end SWEP.Base = "weapon_base" SWEP.Category = "TTT" SWEP.Spawnable = false SWEP.IsGrenade = false SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Primary.Sound = Sound("Weapon_Pistol.Empty") SWEP.Primary.Recoil = 1.5 SWEP.Primary.Damage = 1 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.02 SWEP.Primary.Delay = 0.15 SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" SWEP.Primary.ClipMax = -1 SWEP.Secondary.ClipSize = 1 SWEP.Secondary.DefaultClip = 1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.Secondary.ClipMax = -1 SWEP.HeadshotMultiplier = 2.7 SWEP.StoredAmmo = 0 SWEP.IsDropped = false SWEP.DeploySpeed = 1.4 SWEP.PrimaryAnim = ACT_VM_PRIMARYATTACK SWEP.ReloadAnim = ACT_VM_RELOAD SWEP.fingerprints = {} -- Time needed to enter / leave the ironsight in seconds SWEP.IronSightTime = 0.25 -- The position offset applied when entering the ironsight SWEP.IronSightPos = Vector(0, 0, 0) -- The rotational offset applied when entering the ironsight SWEP.IronSightsAng = Vector(0, 0, 0) local sparkle = CLIENT and CreateClientConVar("ttt_crazy_sparks", "0", true) or nil local ttt2_hold_aim = CLIENT and CreateClientConVar("ttt2_hold_aim", 0, true, false, LANG.GetTranslationFromLanguage("hold_aim", "english"), 0, 1) or nil -- crosshair if CLIENT then local sights_opacity = CreateClientConVar("ttt_ironsights_crosshair_opacity", "0.8", true) local crosshair_brightness = CreateClientConVar("ttt_crosshair_brightness", "1.0", true) local crosshair_size = CreateClientConVar("ttt_crosshair_size", "1.0", true) local disable_crosshair = CreateClientConVar("ttt_disable_crosshair", "0", true) local enable_color_crosshair = CreateClientConVar("ttt_crosshair_color_enable", "0", true) local crosshair_color_r = CreateClientConVar("ttt_crosshair_color_r", "30", true) local crosshair_color_g = CreateClientConVar("ttt_crosshair_color_g", "160", true) local crosshair_color_b = CreateClientConVar("ttt_crosshair_color_b", "160", true) local enable_gap_crosshair = CreateClientConVar("ttt_crosshair_gap_enable", "0", true) local crosshair_gap = CreateClientConVar("ttt_crosshair_gap", "0", true) local crosshair_opacity = CreateClientConVar("ttt_crosshair_opacity", "1", true) local crosshair_static = CreateClientConVar("ttt_crosshair_static", "0", true) local crosshair_weaponscale = CreateClientConVar("ttt_crosshair_weaponscale", "1", true) local crosshair_thickness = CreateClientConVar("ttt_crosshair_thickness", "1", true) local crosshair_outlinethickness = CreateClientConVar("ttt_crosshair_outlinethickness", "0", true) local enable_dot_crosshair = CreateClientConVar("ttt_crosshair_dot", "0", true) --- -- @see https://wiki.facepunch.com/gmod/WEAPON:DrawHUD -- @realm client function SWEP:DrawHUD() if self.HUDHelp then self:DrawHelp() end local client = LocalPlayer() if disable_crosshair:GetBool() or not IsValid(client) or client.isSprinting and not GetGlobalBool("ttt2_sprint_crosshair", false) then return end local sights = not self.NoSights and self:GetIronsights() local x = math.floor(ScrW() * 0.5) local y = math.floor(ScrH() * 0.5) local scale = crosshair_weaponscale:GetBool() and math.max(0.2, 10 * self:GetPrimaryCone()) or 1 local timescale = 1 if not crosshair_static:GetBool() then timescale = (2 - math.Clamp((CurTime() - self:LastShootTime()) * 5, 0.0, 1.0)) end local alpha = sights and sights_opacity:GetFloat() or crosshair_opacity:GetFloat() local bright = crosshair_brightness:GetFloat() or 1 local gap = enable_gap_crosshair:GetBool() and math.floor(timescale * crosshair_gap:GetFloat()) or math.floor(20 * scale * timescale * (sights and 0.8 or 1)) local thickness = crosshair_thickness:GetFloat() local outline = math.floor(crosshair_outlinethickness:GetFloat()) local length = math.floor(gap + 25 * crosshair_size:GetFloat() * scale * timescale) local offset = thickness * 0.5 if outline > 0 then surface.SetDrawColor(0, 0, 0, 255 * alpha) surface.DrawRect(x - length - outline, y - offset - outline, length - gap + outline * 2, thickness + outline * 2) surface.DrawRect(x + gap - outline, y - offset - outline, length - gap + outline * 2, thickness + outline * 2) surface.DrawRect(x - offset - outline, y - length - outline, thickness + outline * 2, length - gap + outline * 2) surface.DrawRect(x - offset - outline, y + gap - outline, thickness + outline * 2, length - gap + outline * 2) end if enable_color_crosshair:GetBool() then surface.SetDrawColor(crosshair_color_r:GetInt() * bright, crosshair_color_g:GetInt() * bright, crosshair_color_b:GetInt() * bright, 255 * alpha) else -- somehow it seems this can be called before my player metatable -- additions have loaded if client.GetSubRoleData then local col = client:GetRoleColor() surface.SetDrawColor(col.r * bright, col.g * bright, col.b * bright, 255 * alpha) else surface.SetDrawColor(0, 255 * bright, 0, 255 * alpha) end end -- draw crosshair dot if enable_dot_crosshair:GetBool() then surface.DrawRect(x - thickness * 0.5, y - thickness * 0.5, thickness, thickness) end surface.DrawRect(x - length, y - offset, length - gap, thickness) surface.DrawRect(x + gap, y - offset, length - gap, thickness) surface.DrawRect(x - offset, y - length, thickness, length - gap) surface.DrawRect(x - offset, y + gap, thickness, length - gap) end local GetPTranslation = LANG.GetParamTranslation function SWEP:DrawHelp() local data = self.HUDHelp local translate = data.translatable local primary = data.primary local secondary = data.secondary if translate then primary = primary and GetPTranslation(primary, data.translate_params) secondary = secondary and GetPTranslation(secondary, data.translate_params) end draw.ShadowedText(secondary or primary, "weapon_hud_help", ScrW() * 0.5, ScrH() - 40, COLOR_WHITE, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP) -- if no secondary exists, primary is drawn at the bottom and no top line -- is drawn if secondary then draw.ShadowedText(primary, "weapon_hud_help", ScrW() * 0.5, ScrH() - 60, COLOR_WHITE, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP) end end -- mousebuttons are enough for most weapons local default_key_params = { primaryfire = Key("+attack", "LEFT MOUSE"), secondaryfire = Key("+attack2", "RIGHT MOUSE"), usekey = Key("+use", "USE") } function SWEP:AddHUDHelp(primary_text, secondary_text, translate, extra_params) extra_params = extra_params or {} self.HUDHelp = { primary = primary_text, secondary = secondary_text, translatable = translate, translate_params = table.Merge(extra_params, default_key_params) } end end --- -- Called if the player presses IN_ATTACK (Default: Left Mouse Button) -- Shooting functions largely copied from weapon_cs_base -- @param boolean worldsnd -- @see https://wiki.facepunch.com/gmod/WEAPON:PrimaryAttack -- @realm shared function SWEP:PrimaryAttack(worldsnd) self:SetNextSecondaryFire(CurTime() + self.Primary.Delay) self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) if not self:CanPrimaryAttack() then return end if not worldsnd then self:EmitSound(self.Primary.Sound, self.Primary.SoundLevel) elseif SERVER then sound.Play(self.Primary.Sound, self:GetPos(), self.Primary.SoundLevel) end self:ShootBullet(self.Primary.Damage, self.Primary.Recoil, self.Primary.NumShots, self:GetPrimaryCone()) self:TakePrimaryAmmo(1) local owner = self:GetOwner() if not IsValid(owner) or owner:IsNPC() or not owner.ViewPunch then return end owner:ViewPunch(Angle(util.SharedRandom(self:GetClass(), -0.2, -0.1, 0) * self.Primary.Recoil, util.SharedRandom(self:GetClass(), -0.1, 0.1, 1) * self.Primary.Recoil, 0)) end --- -- @param function setnext function SWEP:DryFire(setnext) if CLIENT and LocalPlayer() == self:GetOwner() then self:EmitSound("Weapon_Pistol.Empty") end setnext(self, CurTime() + 0.2) self:Reload() end --- -- Helper function for checking for no ammo. -- @return boolean -- @see https://wiki.facepunch.com/gmod/WEAPON:CanPrimaryAttack -- @realm shared function SWEP:CanPrimaryAttack() if not IsValid(self:GetOwner()) then return end if self:Clip1() <= 0 then self:DryFire(self.SetNextPrimaryFire) return false end return true end --- -- Helper function for checking for no ammo. -- @return boolean -- @see https://wiki.facepunch.com/gmod/WEAPON:CanSecondaryAttack -- @realm shared function SWEP:CanSecondaryAttack() if not IsValid(self:GetOwner()) then return end if self:Clip2() <= 0 then self:DryFire(self.SetNextSecondaryFire) return false end return true end local function Sparklies(attacker, tr, dmginfo) if not tr.HitWorld or tr.MatType ~= MAT_METAL then return end local eff = EffectData() eff:SetOrigin(tr.HitPos) eff:SetNormal(tr.HitNormal) util.Effect("cball_bounce", eff) end --- -- A convenience function to shoot bullets -- @param CTakeDamageInfo dmg -- @param number recoil -- @param number numbul -- @param number cone -- @see https://wiki.facepunch.com/gmod/WEAPON:ShootBullet -- @realm shared function SWEP:ShootBullet(dmg, recoil, numbul, cone) self:SendWeaponAnim(self.PrimaryAnim) self:GetOwner():MuzzleFlash() self:GetOwner():SetAnimation(PLAYER_ATTACK1) local sights = self:GetIronsights() numbul = numbul or 1 cone = cone or 0.01 local bullet = {} bullet.Num = numbul bullet.Src = self:GetOwner():GetShootPos() bullet.Dir = self:GetOwner():GetAimVector() bullet.Spread = Vector(cone, cone, 0) bullet.Tracer = 4 bullet.TracerName = self.Tracer or "Tracer" bullet.Force = 10 bullet.Damage = dmg if CLIENT and sparkle:GetBool() then bullet.Callback = Sparklies end self:GetOwner():FireBullets(bullet) -- Owner can die after firebullets if not IsValid(self:GetOwner()) or not self:GetOwner():Alive() or self:GetOwner():IsNPC() then return end if game.SinglePlayer() and SERVER or not game.SinglePlayer() and CLIENT and IsFirstTimePredicted() then -- reduce recoil if ironsighting recoil = sights and (recoil * 0.6) or recoil local eyeang = self:GetOwner():EyeAngles() eyeang.pitch = eyeang.pitch - recoil self:GetOwner():SetEyeAngles(eyeang) end end --- -- @return number function SWEP:GetPrimaryCone() local cone = self.Primary.Cone or 0.2 -- 10% accuracy bonus when sighting return self:GetIronsights() and (cone * 0.85) or cone end --- -- @param Player victim -- @param CTakeDamageInfo dmginfo -- @return number -- @realm shared function SWEP:GetHeadshotMultiplier(victim, dmginfo) return self.HeadshotMultiplier end --- -- @return boolean -- @realm shared function SWEP:IsEquipment() return WEPS.IsEquipment(self) end --- -- This hook draws the selection icon in the weapon selection menu. -- @see https://wiki.facepunch.com/gmod/WEAPON:DrawWeaponSelection -- @realm client function SWEP:DrawWeaponSelection() end --- -- Called if the player presses IN_ATTACK2 (Default: Right mouse button). -- You can override it to implement special attacks, but it is usually reserved for aiming with ironsights. -- @see https://wiki.facepunch.com/gmod/WEAPON:SecondaryAttack -- @realm shared function SWEP:SecondaryAttack() if self.NoSights or not self.IronSightsPos then return end local bNotIronsights = not self:GetIronsights() self:SetIronsights(bNotIronsights) self:SetZoom(bNotIronsights) self:SetNextSecondaryFire(CurTime() + 0.3) end --- -- Called when player has just switched to this weapon. -- @return[default=true] boolean -- @see https://wiki.facepunch.com/gmod/WEAPON:Deploy -- @realm shared function SWEP:Deploy() self:SetIronsights(false) self:SetZoom(false) return true end --- -- Called if the player presses IN_RELOAD -- @see https://wiki.facepunch.com/gmod/WEAPON:Reload -- @realm shared function SWEP:Reload() if self:Clip1() == self.Primary.ClipSize or self:GetOwner():GetAmmoCount(self.Primary.Ammo) <= 0 then return end self:DefaultReload(self.ReloadAnim) self:SetIronsights(false) self:SetZoom(false) end --- -- Called when the weapon entity is reloaded on a changelevel event -- @see https://wiki.facepunch.com/gmod/WEAPON:OnRestore -- @realm shared function SWEP:OnRestore() self.NextSecondaryAttack = 0 self:SetIronsights(false) self:SetZoom(false) end --- -- Returns how much of primary ammo the player has -- @return number|boolean -- @see https://wiki.facepunch.com/gmod/WEAPON:Ammo1 -- @realm shared function SWEP:Ammo1() return IsValid(self:GetOwner()) and self:GetOwner():GetAmmoCount(self.Primary.Ammo) or false end --- -- The OnDrop() hook is useless for this as it happens AFTER the drop. OwnerChange -- does not occur when a drop happens for some reason. Hence this thing. -- @realm server function SWEP:PreDrop() if CLIENT or not IsValid(self:GetOwner()) or self.Primary.Ammo == "none" then return end local ammo = self:Ammo1() -- Do not drop ammo if we have another gun that uses this type local weps = self:GetOwner():GetWeapons() for i = 1, #weps do local w = weps[i] if not IsValid(w) or w == self or w:GetPrimaryAmmoType() ~= self:GetPrimaryAmmoType() then continue end ammo = 0 end self.StoredAmmo = ammo if ammo > 0 then self:GetOwner():RemoveAmmo(ammo, self.Primary.Ammo) end end --- -- Helper function to slow down dropped weapons -- @realm server function SWEP:DampenDrop() -- For some reason gmod drops guns on death at a speed of 400 units, which -- catapults them away from the body. Here we want people to actually be able -- to find a given corpse's weapon, so we override the velocity here and call -- this when dropping guns on death. local phys = self:GetPhysicsObject() if IsValid(phys) then phys:SetVelocityInstantaneous(Vector(0, 0, - 75) + phys:GetVelocity() * 0.001) phys:AddAngleVelocity(phys:GetAngleVelocity() * -0.99) end end local SF_WEAPON_START_CONSTRAINED = 1 --- -- Called when a player has picked the weapon up -- Transfers the currently stored ammo to the new player and updates the fingerprints -- @param Player newowner -- @see https://wiki.facepunch.com/gmod/WEAPON:Equip -- @realm server function SWEP:Equip(newowner) if self:IsOnFire() then self:Extinguish() end self.fingerprints = self.fingerprints or {} if not table.HasValue(self.fingerprints, newowner) then self.fingerprints[#self.fingerprints + 1] = newowner end if self:HasSpawnFlags(SF_WEAPON_START_CONSTRAINED) then -- If this weapon started constrained, unset that spawnflag, or the -- weapon will be re-constrained and float local flags = self:GetSpawnFlags() local newflags = bit.band(flags, bit.bnot(SF_WEAPON_START_CONSTRAINED)) self:SetKeyValue("spawnflags", newflags) end if IsValid(newowner) and self.StoredAmmo > 0 and self.Primary.Ammo ~= "none" then local ammo = newowner:GetAmmoCount(self.Primary.Ammo) local given = math.min(self.StoredAmmo, self.Primary.ClipMax - ammo) newowner:GiveAmmo(given, self.Primary.Ammo) self.StoredAmmo = 0 end end --- -- We were bought as special equipment, some weapons will want to do something -- extra for their buyer -- @param Player buyer -- @realm server function SWEP:WasBought(buyer) end --- -- Zoom in or out. Use this in combination with SetIronsights. -- Look at weapon_ttt_m16 for an example of how to use this. -- @param boolean zoomIn -- @realm shared function SWEP:SetZoom(zoomIn) end --- -- Sets the flag signaling whether or not the ironsights should be used -- @param boolean b -- @realm shared function SWEP:SetIronsights(b) if b == self:GetIronsights() then return end self:SetIronsightsPredicted(b) self:SetIronsightsTime(CurTime()) if CLIENT then self:CalcViewModel() end end --- -- Gets the flag signaling whether or not the ironsights should be used -- @return boolean -- @realm shared function SWEP:GetIronsights() return self:GetIronsightsPredicted() end --- -- Dummy functions that will be replaced when SetupDataTables runs. These are -- here for when that does not happen (due to e.g. stacking base classes) -- @return[default=-1] number -- @realm shared function SWEP:GetIronsightsTime() return -1 end --- -- Dummy functions that will be replaced when SetupDataTables runs. These are -- here for when that does not happen (due to e.g. stacking base classes) function SWEP:SetIronsightsTime() end --- -- Dummy functions that will be replaced when SetupDataTables runs. These are -- here for when that does not happen (due to e.g. stacking base classes) -- @return[default=false] boolean -- @realm shared function SWEP:GetIronsightsPredicted() return false end --- -- Dummy functions that will be replaced when SetupDataTables runs. These are -- here for when that does not happen (due to e.g. stacking base classes) -- @realm shared function SWEP:SetIronsightsPredicted() end --- -- Called when the SWEP should set up its Data Tables. -- Sets up the networked vars for ironsights. -- @warning Weapons using their own DT vars will have to make sure they call this. -- @see https://wiki.facepunch.com/gmod/WEAPON:SetupDataTables -- @realm shared function SWEP:SetupDataTables() self:NetworkVar("Bool", 3, "IronsightsPredicted") self:NetworkVar("Float", 3, "IronsightsTime") end --- -- Called when the weapon entity is created. -- @see https://wiki.facepunch.com/gmod/WEAPON:Initialize -- @realm shared function SWEP:Initialize() if CLIENT and self:Clip1() == -1 then self:SetClip1(self.Primary.DefaultClip) elseif SERVER then self.fingerprints = {} self:SetIronsights(false) self:SetZoom(false) end self:SetDeploySpeed(self.DeploySpeed) -- compat for gmod update if self.SetHoldType then self:SetHoldType(self.HoldType or "pistol") end end --- -- @realm client function SWEP:CalcViewModel() if not CLIENT or not IsFirstTimePredicted() then return end self.bIron = self:GetIronsights() self.fIronTime = self:GetIronsightsTime() self.fCurrentTime = CurTime() self.fCurrentSysTime = SysTime() end --- -- Called when the swep thinks. -- @warning If you override Think in your SWEP, you should call BaseClass.Think(self) so as not to break ironsights -- @see https://wiki.facepunch.com/gmod/WEAPON:Think -- @realm shared function SWEP:Think() self:CalcViewModel() end --- -- Experimental. Enables a feature that causes a player who is using his ironsights and is killed (by a gun, and not a headshot) to fire an inaccurate dying shot. -- @return boolean -- @see http://www.troubleinterroristtown.com/config-and-commands/convars#TOC-Other-gameplay-settings -- @realm server function SWEP:DyingShot() if not self:GetIronsights() then return false end self:SetIronsights(false) self:SetZoom(false) if self:GetNextPrimaryFire() > CurTime() then return false end -- Owner should still be alive here local owner = self:GetOwner() if not IsValid(owner) then return false end local punch = self.Primary.Recoil or 5 -- Punch view to disorient aim before firing dying shot local eyeang = owner:EyeAngles() eyeang.pitch = eyeang.pitch - math.Rand(-punch, punch) eyeang.yaw = eyeang.yaw - math.Rand(-punch, punch) owner:SetEyeAngles(eyeang) MsgN(owner:Nick() .. " fired his DYING SHOT") owner.dying_wep = self self:PrimaryAttack(true) return true end local ttt_lowered = CreateConVar("ttt_ironsights_lowered", "1", FCVAR_ARCHIVE) local host_timescale = GetConVar("host_timescale") local LOWER_POS = Vector(0, 0, -2) local IRONSIGHT_TIME = 0.25 --- -- This hook allows you to adjust view model position and angles. -- @param Vector pos -- @param Angle ang -- @return Vector -- @return Angle -- @see https://wiki.facepunch.com/gmod/WEAPON:GetViewModelPosition -- @realm client function SWEP:GetViewModelPosition(pos, ang) if not self.IronSightsPos or self.bIron == nil then return pos, ang end local bIron = self.bIron local time = self.fCurrentTime + (SysTime() - self.fCurrentSysTime) * game.GetTimeScale() * host_timescale:GetFloat() if bIron then self.SwayScale = 0.3 self.BobScale = 0.1 else self.SwayScale = 1.0 self.BobScale = 1.0 end local fIronTime = self.fIronTime if not bIron and fIronTime < time - IRONSIGHT_TIME then return pos, ang end local mul = 1.0 if fIronTime > time - IRONSIGHT_TIME then mul = math.Clamp((time - fIronTime) / IRONSIGHT_TIME, 0, 1) if not bIron then mul = 1 - mul end end local offset = self.IronSightsPos + (ttt_lowered:GetBool() and LOWER_POS or vector_origin) if self.IronSightsAng then ang = Angle(ang) ang:RotateAroundAxis(ang:Right(), self.IronSightsAng.x * mul) ang:RotateAroundAxis(ang:Up(), self.IronSightsAng.y * mul) ang:RotateAroundAxis(ang:Forward(), self.IronSightsAng.z * mul) end pos = pos + offset.x * ang:Right() * mul pos = pos + offset.y * ang:Forward() * mul pos = pos + offset.z * ang:Up() * mul return pos, ang end --- -- Tell the server about the users preference regarding holding aim or toggle aim, -- necessary to avoid prediction issues local function UpdateHoldAimCV() net.Start("TTT2UpdateHoldAimConvar") net.WriteBool(ttt2_hold_aim:GetBool()) net.SendToServer() end hook.Add("KeyRelease", "TTT2ResetIronSights", function(ply, key) if key ~= IN_ATTACK2 or not IsValid(ply) then return end if not (CLIENT and ttt2_hold_aim:GetBool() or SERVER and ply.holdAim) then return end local wep = ply:GetActiveWeapon() if not IsValid(wep) or not wep:GetIronsights() then return end wep:SetIronsights(false) wep:SetZoom(false) end) if CLIENT then hook.Add("InitPostEntity", "TTT2InitHoldAimCV", function() UpdateHoldAimCV() end) cvars.AddChangeCallback("ttt2_hold_aim", function(cvar, old, new) UpdateHoldAimCV() end) else net.Receive("TTT2UpdateHoldAimConvar", function(len, ply) ply.holdAim = net.ReadBool() end) end
local game = { states = {idle={}, action={}, paused={}}, tests={}, growSpeed = 8, colorTime = 0, color = {0,0,0} } game.state = game.states.idle local Player = require "src/player" local contact = require "src/contact" local spawnManager = require "src/spawnManager" require "utils/utils" function game.load() game.music = love.audio.newSource("sounds/PerceptionSong.mp3") game.music:setLooping(true) game.font = love.graphics.newFont(20) spawnManager.load() end function game.start() game.contacted = nil game.timer = 0 game.blocks = {} game.growStack = 0 game.width,game.height = love.graphics.getDimensions() game.smallRadius = 0.08*game.width game.bigRadius = 0.27*game.width game.radius = game.smallRadius game.growDir = 1 game.center = {x=game.width/2,y=game.height/2} local player1Data = { input={left="left",right="right",switch="space"}, color = {255,0,0}, center = game.center } game.players = {Player.new(player1Data,game)} spawnManager.start(game) end function game.newRound() Player.speed = Player.speed*1.35 Block.speed = Block.speed*1.35 end function game.keypressed(key) game.state.keypressed(key) end function game.states.idle.keypressed(key) if key=="return" then game.state = game.states.action love.audio.play(game.music) game.start() end end function game.states.action.keypressed(key) if key=="return" then love.audio.pause(game.music) game.state = game.states.paused end for i,v in pairs(game.players) do if v:keypressed(key) then do return end end end end function game.states.paused.keypressed(key) if key=="return" then love.audio.resume(game.music) game.state = game.states.action end end function game.update(dt) game.state.update(dt) end function game.states.idle.update(dt) end function game.states.action.update(dt) game.colorTime = game.colorTime-dt if game.colorTime<0 then game.colorTime = 2 game.colorV = {} for i=1,3 do table.insert(game.colorV,(30+195*love.math.random()-game.color[i])/2) end else for i,v in ipairs(game.colorV) do game.color[i]= game.color[i]+v*dt end end game.timer = game.timer+dt for i,v in safePairs(game.blocks) do v:update(dt) if not v.alive then table.remove(game.blocks,i) game.growStack = game.growStack+3 end end if game.growStack>0 then local q = game.growSpeed*dt game.radius = game.radius+q*game.growDir if game.growDir==1 then if game.radius>game.bigRadius then game.growDir=-1 spawnManager.switch() end else if game.radius<game.smallRadius then game.growDir = 1 spawnManager.switch() end end game.growStack = game.growStack-q end for i,v in pairs(game.players) do v:update(dt) if contact.check(v,game.blocks,game) then love.audio.stop(game.music) Player.speed = Player.baseSpeed Block.speed = Block.baseSpeed game.state = game.states.idle do return end end end spawnManager.update(dt) end function game.states.paused.update(dt) end function game.draw() love.graphics.setColor(game.color) love.graphics.rectangle("fill",0,0,game.width,game.height) love.graphics.setColor(255,255,255) love.graphics.setFont(game.font) love.graphics.printf(math.floor(game.timer),game.width/2,game.height*0.1,500) love.graphics.translate(game.center.x,game.center.y) love.graphics.push() local c = {255-game.color[1],255-game.color[2],255-game.color[3]} love.graphics.setColor(c) love.graphics.scale(1,-1) love.graphics.circle("fill",0,0,game.radius,100) for i,v in pairs(game.players) do v:draw() end love.graphics.setColor(c) for i,v in pairs(game.blocks) do v:draw() end spawnManager.draw() if game.contacted ~= nil then love.graphics.setColor(0,255,0) game.contacted:draw() end love.graphics.pop() love.graphics.setColor(255,255,255) game.state.draw() end function game.states.idle.draw() love.graphics.print("Press enter to play") end function game.states.action.draw() end function game.states.paused.draw() love.graphics.print("Press enter to resume") end return game
-- functions I call at least three(ish) times local AddonName, Addon = ... -- create a frame, and then hide it function Addon:CreateHiddenFrame(...) local frame = CreateFrame(...) frame:Hide() return frame end -- A utility function for extending blizzard widget types (Frames, Buttons, etc) do -- extend basically just does a post hook of an existing object method -- its here so that I can not forget to do class.proto.thing when hooking -- thing local function class_Extend(class, method, func) if not (type(method) == 'string' and type(func) == 'function') then error('Usage: Class:Extend("method", func)', 2) end if type(class.proto[method]) ~= 'function' then error(('Parent has no method named %q'):format(method), 2) end class[method] = function(self, ...) class.proto[method](self, ...) return func(self, ...) end end function Addon:CreateClass(frameType, prototype) local class = self:CreateHiddenFrame(frameType) local class_mt = {__index = class} class.Bind = function(_, object) return setmetatable(object, class_mt) end if type(prototype) == 'table' then class.proto = prototype class.Extend = class_Extend setmetatable(class, {__index = prototype}) end return class end end -- returns a function that generates unique names for frames -- in the format <AddonName>_<Prefix>[1, 2, ...] function Addon:CreateNameGenerator(prefix) local id = 0 return function() id = id + 1 return ('%s_%s_%d'):format(AddonName, prefix, id) end end -- A functional way to fade a frame from one opacity to another without constantly -- creating new animation groups for the frame do -- set alpha on finished even though we SetToFinalAlpha(true) -- this is so that the action bars can react to the SetAlpha call and adjust -- cooldown appearances when bars are invisible local function animationGroup_OnFinished(self) if self.toAlpha then self:GetParent():SetAlpha(self.toAlpha) end end Addon.Fade = setmetatable( {}, { __call = function(self, addon, frame, toAlpha, delay, duration) return self[frame](toAlpha, delay, duration) end, __index = function(self, frame) local animationGroup = frame:CreateAnimationGroup() animationGroup:SetLooping('NONE') animationGroup:SetToFinalAlpha(true) animationGroup:SetScript('OnFinished', animationGroup_OnFinished) local fadeAnimation = animationGroup:CreateAnimation('Alpha') fadeAnimation:SetSmoothing('IN_OUT') fadeAnimation:SetOrder(0) local function func(toAlpha, delay, duration) local fromAlpha -- if we're not done animating, then figure out what alpha level -- we are at and pick up where we left off if not fadeAnimation:IsDone() then local start = fadeAnimation:GetFromAlpha() local delta = fadeAnimation:GetToAlpha() - start fromAlpha = start + delta * fadeAnimation:GetSmoothProgress() else fromAlpha = frame:GetAlpha() end fadeAnimation:SetFromAlpha(fromAlpha) fadeAnimation:SetToAlpha(toAlpha) fadeAnimation:SetStartDelay(delay) fadeAnimation:SetDuration(duration) animationGroup.toAlpha = toAlpha animationGroup:Restart() end self[frame] = func return func end } ) end -- somewhere between a debounce and a throttle function Addon:Defer(func, delay, arg1) delay = delay or 0 local waiting = false local function callback() func(arg1) waiting = false end return function() if not waiting then waiting = true C_Timer.After(delay or 0, callback) end end end
require 'war3library.libraries.interact.dzapi.dzapi' require 'war3library.libraries.interact.dzapi.player' require 'war3library.libraries.interact.dzapi.game'
local function Probe(region) return (region.scrollChild or region.GetScrollChild and region:GetScrollChild()) ~= nil end local function HybridDescribe(region, strings) local children = {region.scrollChild:GetChildren()} local scrollBar = region.scrollBar local _, range = scrollBar:GetMinMaxValues() local height = range + region:GetHeight() local processedOffset = 0 while processedOffset < height do local offset = min(processedOffset, range) scrollBar:SetValue(offset) offset = scrollBar:GetValue() local childHeight = not region.dynamic and children[1]:GetHeight() local alignedOffset = not region.dynamic and math.floor(offset / childHeight + 0.5) * childHeight or region.dynamic(offset) for index, child in ipairs(children) do if not child:IsEnabled() then return strings end alignedOffset = alignedOffset + child:GetHeight() if alignedOffset > processedOffset then Vimp_Strings(strings, child) end end processedOffset = alignedOffset end return strings end local function Describe(region, strings) local speak = false if not strings then region = Vimp_Reader:GetFocus() strings = {} speak = true end if region.scrollChild then HybridDescribe(region, strings) else local content = region:GetScrollChild() Vimp_Strings(strings, content:GetRegions()) Vimp_Strings(strings, content:GetChildren()) end if not speak then return strings end Vimp_Say({"Scroll", string.format("%d children", #strings)}) end local function HybridNext(backward, scroll, region) local scrollBar = scroll.scrollBar local content = scroll.scrollChild local _, range = scrollBar:GetMinMaxValues() local children = {content:GetChildren()} while not children[#children]:IsEnabled() do table.remove(children) end if #children == 0 then Vimp_Say("Nothing to read!") local driver = Vimp_Driver:ProbeRegion(scroll) driver.Dismiss() return end if not region then local offset = not backward and 0 or range scrollBar:SetValue(offset) while not children[#children]:IsEnabled() do table.remove(children) end local child = not backward and children[1] or children[#children] Vimp_Reader:SetFocus(child) local driver = Vimp_Driver:ProbeRegion(child) driver.Describe() return end local offset = scrollBar:GetValue() local alignedHeight = not scroll.dynamic and math.floor(offset / region:GetHeight() + 0.5) * region:GetHeight() or offset - select(2, scroll.dynamic(offset)) local next = nil for index, child in ipairs(children) do if child == region then next = children[not backward and index + 1 or index - 1] break end alignedHeight = alignedHeight + child:GetHeight() end if not next or not next:IsEnabled() then HybridNext(backward, scroll, nil) return end local nextHeight = next:GetHeight() local nextCenter = not backward and alignedHeight + region:GetHeight() + nextHeight / 2 or alignedHeight - nextHeight / 2 local offset = min(max(nextCenter - scroll:GetHeight() / 2, 0), range) scrollBar:SetValue(offset) offset = scrollBar:GetValue() local alignedHeight = not scroll.dynamic and math.floor(offset / nextHeight + 0.5) * nextHeight or offset - select(2, scroll.dynamic(offset)) region = nil for index, child in ipairs(children) do alignedHeight = alignedHeight + child:GetHeight() if alignedHeight > nextCenter then region = child break end end if not region or not region:IsEnabled() then HybridNext(backward, scroll, nil) return end Vimp_Reader:SetFocus(region) local driver = Vimp_Driver:ProbeRegion(region) driver.Describe(region) end local function Next(backward) local region = Vimp_Reader:GetFocus() local scroll = Vimp_Reader:GetParent() if region == scroll then region = nil end if scroll.scrollChild then HybridNext(backward, scroll, region) return end local content = scroll:GetScrollChild() local children = {} Vimp_Children(children, content:GetRegions()) Vimp_Children(children, content:GetChildren()) if #children == 0 then Vimp_Say("Nothing to read!") local driver = Vimp_Driver:ProbeRegion(scroll) driver.Dismiss() return end local first, last, increment = 1, #children, 1 if backward then first, last, increment = last, first, -1 end for index = first, last, increment do local child = children[index] if not region then region = child break end if child == region then region = nil end end if not region then region = children[first] end local scrollHorizontalOrigin, scrollVerticalOrigin, scrollWidth, scrollHeight = scroll:GetScaledRect() local scrollScale = scroll:GetEffectiveScale() local regionHorizontalOrigin, regionVerticalOrigin, regionWidth, regionHeight = region:GetScaledRect() local horizontalRange = scroll:GetHorizontalScrollRange() local verticalRange = scroll:GetVerticalScrollRange() if horizontalRange > 0 then local scrollCenter = scrollHorizontalOrigin + scrollWidth / 2 local regionCenter = regionHorizontalOrigin + regionWidth / 2 local offset = regionCenter - scrollCenter local old = scroll:GetHorizontalScroll() local new = old + offset / scrollScale new = max(0, min(new, horizontalRange)) scroll:SetHorizontalScroll(new) end if verticalRange > 0 then local scrollCenter = scrollVerticalOrigin + scrollHeight / 2 local regionCenter = regionVerticalOrigin + regionHeight / 2 local offset = regionCenter - scrollCenter local old = scroll:GetVerticalScroll() local new = old - offset / scrollScale new = max(0, min(new, verticalRange)) scroll:SetVerticalScroll(new) end Vimp_Reader:SetFocus(region) local driver = Vimp_Driver:ProbeRegion(region) driver.Describe() end local function Activate() local focus = Vimp_Reader:GetFocus() local parent = Vimp_Reader:GetParent() if focus == parent then Vimp_Say("Already interacting with the scroll!") return end local strings = {"Enter", "Scroll"} Vimp_Say(strings) Vimp_Reader:Push(focus) Next(false) end local function Dismiss() Vimp_Reader:Pop() local strings = {"Exit", "Scroll"} Vimp_Say(strings) Describe() end Vimp_Driver:Create(Probe, Describe, Next, Activate, Dismiss, Vimp_Dummy)
local gbc = cc.import("#gbc") local SocketTimer = cc.class("SocketTimer", gbc.NgxTimerBase) local client = require "resty.websocket_client" local ngx_sleep = ngx.sleep local string_sub = string.sub local table_concat = table.concat local netpack = cc.import("#netpack") local net_decode = netpack.decode --param --[[ uri -- 服务器地址 authorization --授权码 channel --共享通道 msg --附带消息 ]]-- function SocketTimer:ctor(config, param, ...) SocketTimer.super.ctor(self, config, param, ...) end function SocketTimer:OnClosed(_redis) -- body end function SocketTimer:OnConnected() -- body end function SocketTimer:connect() if self._socket == nil then local socket = client:new() local ok, err = socket:connect(self.param.uri, { protocols = { "gbc-auth-"..self.param.authorization, "gbc-msg-"..self.param.msg, }, }) if not ok then cc.printerror("wb connect:"..err) return false end cc.printf(string.format("%s is connect success", self.param.uri)) self._socket = socket self:OnConnected() return true end return true end function SocketTimer:closeSocket(redis) if self._socket ~= nil then local socket = self._socket self._socket = nil socket:set_keepalive() self:OnClosed(redis) end end function SocketTimer:ProcessMessage(frame, ftype) self:safeFunction(function () if frame then local data, err = net_decode(frame) if err then cc.printerror(string.format("can not decode frame err:%s [%d]", err, #frame)) return end if type(data) == "table" and data.connectid then --cc.printf(string.format("decode success length[%d]", #frame)) if data.tp == 1 then self:sendControlMessage(data.connectid, data.message) else self:sendMessageToConnectID(data.connectid, data.message) end else cc.printf(string.format("net_decode data is not table length:[%d] ftype:[%s]", #frame, ftype)) end end end) end function SocketTimer:runEventLoop() local sub, _err = self:getRedis():makeSubscribeLoop(self.param.channel) if not sub then cc.printerror("makeSubscribeLoop failure") return false end local this = self sub:start(function(subRedis, _channel, msg) if this._socket ~= nil then local _, err = this._socket:send_binary(msg) if err then cc.printf("sub close socket:"..err) this:closeSocket(subRedis) end else cc.printf("send_binary failed:"..msg) end end, self.param.channel) cc.printf("subscribe channel:"..self.param.channel) local frames = {} while true do if self._socket then while self._socket do local frame, ftype, err = self._socket:recv_frame() if err then if err == "again" then table.insert(frames, frame) break -- recv next message end if string_sub(err, -7) == "timeout" then break -- recv next message end cc.printf("close socket:"..err) self:closeSocket(self:getRedis()) end if #frames > 0 then -- merging fragmented frames table.insert(frames, frame) frame = table_concat(frames) frames = {} end if ftype == "close" then self:closeSocket(self:getRedis()) break elseif ftype == "ping" then if self._socket then self._socket:send_pong() end elseif ftype == "pong" then -- client ponged elseif ftype == "text" or ftype == "binary" then self:ProcessMessage(frame, ftype) else cc.printwarn("[SocketTimer:%s] unknown frame type \"%s\"", self.param.channel, tostring(ftype)) end end else self:connect() ngx_sleep(5) end end end return SocketTimer
local life = require "life" local drawLife = require "draw_life" -- Provide sys object _G.sys = {} _G.sys['randf'] = math.random local drawCell = function(x, y, isAlive) print("drawSquare (" .. x .. ", " .. y .. ") " .. ((isAlive == 1) and "x" or "o")) end describe("Life", function() describe("Generation of new cells", function() cells = {} cells[0] = {} it("One cell on a 1x1 grid", function() cells[0][0] = true local cellsNext = life.nextGeneration(cells) assert.truthy(cellsNext[0][0] == false) end) it("Three horizontal cells on a small 3x3 grid", function() cells[0][0] = false cells[0][1] = true cells[0][2] = false cells[1] = {} cells[1][0] = false cells[1][1] = true cells[1][2] = false cells[2] = {} cells[2][0] = false cells[2][1] = true cells[2][2] = false print(" --- before ---") life.printCells(cells) local cellsNext = life.nextGeneration(cells) print(" --- after ---") life.printCells(cellsNext) print("draw cells gen =====") drawLife.generation(drawCell, cells) print("draw cells next gen =====") drawLife.generation(drawCell, cellsNext) print("draw cells diff gen =====") drawLife.generationDiff(drawCell, cells, cellsNext) cells = cellsNext print("draw cells again") drawLife.generation(drawCell, cells) -- Two columns have no cells assert.truthy(cellsNext[0][0] == false) assert.truthy(cellsNext[0][1] == false) assert.truthy(cellsNext[0][2] == false) assert.truthy(cellsNext[2][0] == false) assert.truthy(cellsNext[2][1] == false) assert.truthy(cellsNext[2][2] == false) -- Middle colum has alive cells assert.truthy(cellsNext[1][0] == true) assert.truthy(cellsNext[1][1] == true) assert.truthy(cellsNext[1][2] == true) end) it("Generating random 5x5 grid", function() local cells = life.randomizeGeneration(cells, 5, 5) life.printCells(cells) end) end) end)
-- TEST SUITE FOR LUA SCRIPTS -- Requires lunatests from https://github.com/silentbicycle/lunatest -- To run tests simply -- lua luatests.lua -- package.path = package.path .. ";stdnet/lib/lua/?.lua;tests/lua/?.lua" -- To run the debugger in eclipse you need to install the DBGp Client -- http://wiki.eclipse.org/Koneki/LDT/User_Guide/Concepts/Debugger#Source_Mapping -- Then create a lua project where to run the debug server pcall(function() require("debugger")() end) require("lunatest") print '==============================' print('To run just some tests, add "-t [pattern]"') print '==============================' lunatest.suite("tests/lua/utils") lunatest.suite("tests/lua/odm") lunatest.suite("tests/lua/columnts") lunatest.run()
local msg = require 'mp.msg' local function on_start() local streamOpenFN = mp.get_property_native("stream-open-filename") if (type(streamOpenFN) ~= "string") then do return end end msg.log("info", "open file: " .. streamOpenFN) local file = io.open(streamOpenFN,"rb") if not file then return nil end local block = file:read(8) file:close() if (block == 'EV000001') then msg.log("info", "crypto marker: EV000001") mp.set_property( "stream-open-filename", "crypto:///" .. streamOpenFN ) msg.log("info", "stream-open-filename: crypto:///" .. streamOpenFN) end end mp.add_hook("on_load", 50, on_start)
a = 74 -352- 21-3
-- https://steamcommunity.com/sharedfiles/filedetails/?id=2165338357 local PANEL = { PanelManager = nil } --[[ Description: Panel manager initialization --]] function PANEL:Init() self.PanelManager = DFCL:New(self:GetName()) self.PanelManager:AddMouseClickListener() self.PanelManager:AddContextMenuListener() self.PanelManager:AddPanel(self, true) timer.Simple(0.3, function() local panels = self:GetChildren() for _, panel in pairs(panels) do self.PanelManager:AddPanel(panel) end end) end --[[ Description: Activates the synchronization of the panel manager and the children of the main panel -------------- @param (Float : 1) sync_time - Sync refresh rate in seconds --]] function PANEL:ChildSync(sync_time) sync_time = sync_time or 1 local PanelEventName = self.PanelManager:GetEventName() local SyncEventName = PanelEventName .. "_ChildrenSync" timer.Create(SyncEventName, sync_time, 0, function() if (not IsValid(self)) then return end local panels = self:GetChildren() local panelsExists = self.PanelManager:GetPanels() for _, panel in pairs(panels) do if (not table.HasValue(panelsExists, panel)) then self.PanelManager:AddPanel(panel) end end end) hook.Add("DFCL_Destruct_" .. PanelEventName, SyncEventName, function() if (timer.Exists(SyncEventName)) then timer.Remove(SyncEventName) end hook.Remove("DFCL_Destruct_" .. PanelEventName, SyncEventName) end) end --[[ Description: Adds focus tracking for a panel group with the specified name. If the context menu closes, the focus will return, provided that it was previously. -------------- @param (String) panelName - Panel name (Example: "DTextEntry") --]] function PANEL:AddFocusName(panelName) self.PanelManager:AddFocusName(panelName) end --[[ Description: Deletes focus tracking for a panel group. -------------- @param (String) panelName - Panel name (Example: "DTextEntry") --]] function PANEL:RemoveFocusName(panelName) self.PanelManager:RemoveFocusName(panelName) end --[[ Description: Adds focus tracking for a panel. If the context menu closes, the focus will return, provided that it was previously. -------------- @param (Panel) panel - A panel object --]] function PANEL:AddFocusPanel(panel) self.PanelManager:AddFocusPanel(panel) end --[[ Description: Deletes focus tracking for a panel. -------------- @param (Panel) panel - A panel object --]] function PANEL:RemoveFocusPanel(panel) self.PanelManager:RemoveFocusPanel(panel) end --[[ Description: Returns the panel manager -------------- @return (Metatable) - Meta table panel manager --]] function PANEL:GetPanelManager() return self.PanelManager end --[[ Description: Destroys the panel manager and all its dependencies --]] function PANEL:Destruct() self.PanelManager:Destruct() end --[[ Description: Destroys the panel manager and all its dependencies when closing the panel WARNING: When overloaded, the method will have to be called manually. --]] function PANEL:OnClose() self.PanelManager:Destruct() end --[[ Description: Destroys the panel manager and all its dependencies when removing a panel WARNING: When overloaded, the method will have to be called manually. --]] function PANEL:OnRemove() self.PanelManager:Destruct() end vgui.Register("DFrameContext", PANEL, "DFrame")
-- -- battery.lua -- battery status notification -- local naughty = require("naughty") local beautiful = require("beautiful") -- ======================================== -- Config -- ======================================== -- notify when battery is below certain amount local low_battery_threshold = 15 -- re-notify low battery every x seconds local low_battery_reminder_interval = 300 -- icons path local icons_path = beautiful.icons_path .. "battery/" -- ======================================== -- Logic -- ======================================== -- check whether battery is low local is_battery_low = function (percentage, status) return percentage >= 0 and percentage < low_battery_threshold and status ~= "Charging" end -- show low battery notification local notify_low_battery = function () naughty.notify { preset = naughty.config.presets.critical, icon = icons_path .. "battery-outline.svg", timeout = 5, title = "Low Battery", text = "Time to plug in soon!", } end -- show charger plugged notification local notify_charger_plugged = function () naughty.notify { icon = icons_path .. "charger-plugged.svg", title = "AC Adapter", text = "AC Adapter plugged in.", } end -- show charger unplugged notification local notify_charger_unplugged = function () naughty.notify { icon = icons_path .. "charger-unplugged.svg", title = "AC Adapter", text = "AC Adapter unplugged.", } end -- ======================================== -- Initialization -- ======================================== local last_battery_check = os.time() awesome.connect_signal("daemon::battery::status", function(_, stat) local seconds_since_last_check = os.difftime(os.time(), last_battery_check) if is_battery_low(stat.percentage, stat.status) and seconds_since_last_check > low_battery_reminder_interval then last_battery_check = os.time() notify_low_battery() end end) awesome.connect_signal("daemon::charger::status", function(plugged) if plugged then notify_charger_plugged() else notify_charger_unplugged() end end)
--- === cp.18n === --- --- CommandPost's Internationalisation & Localisation Manger. local require = require local log = require "hs.logger".new "i18n" local fs = require "hs.fs" local host = require "hs.host" local json = require "hs.json" local config = require "cp.config" local tools = require "cp.tools" local i18n = require "i18n" local locale = host.locale local read = json.read local dir = fs.dir local mod = {} -- getLanguageCode(t) -> string -- Function -- Gets the language code from a table -- -- Parameters: -- * The table containing the language data -- -- Returns: -- * A string with the language code local function getLanguageCode(t) -- TODO: There has to be a smarter way to do this? for id, _ in pairs(t) do -- luacheck: ignore return id end end --- cp.18n.init() -> none --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init() local cpi18n = i18n --- cp.i18n.installedLanguages -> table --- Variable --- A table containing all of the installed languages. cpi18n.installedLanguages = {} local userLocale if config.get("language") == nil then userLocale = locale.current() else userLocale = config.get("language") end local languagePath = config.languagePath local allLanguages = {} local iterFn, dirObj = dir(languagePath) if not iterFn then log.ef("An error occured in cp.18n.init: %s", dirObj) else for file in dir(languagePath) do if file:sub(-5) == ".json" then local path = languagePath .. "/" .. file local data = read(path) if data then -------------------------------------------------------------------------------- -- Only load English and the active language: -------------------------------------------------------------------------------- if (data["en"] or data[userLocale]) then allLanguages = tools.mergeTable(allLanguages, data) end -------------------------------------------------------------------------------- -- Add language to the table of installed languages: -------------------------------------------------------------------------------- local fileLanguage = file:sub(1, -6) local languageCode = getLanguageCode(data) table.insert(cpi18n.installedLanguages, { id = languageCode, language = fileLanguage }) end end end end if next(allLanguages) ~= nil then cpi18n.load(allLanguages) end -------------------------------------------------------------------------------- -- Sort the table of installed languages: -------------------------------------------------------------------------------- table.sort(cpi18n.installedLanguages, function(a, b) return a.language < b.language end) cpi18n.setLocale(userLocale) return cpi18n end return mod.init()
--------------------------- -- 显示装备绿字前缀 --------------------------- local LibEvent = LibStub:GetLibrary("LibEvent.7000") local locale = GetLocale():sub(1,2) local shown = { ITEM_MOD_HASTE_RATING_SHORT = { r=0.9, g=0.9, b=0 }, ITEM_MOD_MASTERY_RATING_SHORT = { r=0, g=0.9, b=0.1 }, ITEM_MOD_CRIT_RATING_SHORT = { r=0.9, g=0.3, b=0.1 }, ITEM_MOD_VERSATILITY = { r=0, g=0.9, b=0.8 }, } local function strsubutf8(s, i, j) local bytes = strlen(s) local startByte = 1 local endByte = bytes local len = 0 local pos = 1 local b while pos <= bytes do len = len + 1 if (len == i) then startByte = pos end b = string.byte(s, pos) if (b >= 240) then pos = pos + 4 elseif (b >= 224) then pos = pos + 3 elseif (b >= 192) then pos = pos + 2 else pos = pos + 1 end if (len == j) then endByte = pos - 1 break end end return strsub(s, startByte, endByte) end local function IsGreenStateEnabled() if (locale ~= "zh") then return false elseif InspectDB.green then return true end end LibEvent:attachTrigger("INSPECT_FRAME_CREATED", function(this, frame, parent) if not IsGreenStateEnabled() then return end local i = 1 local itemframe local backdrop = { bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Buttons\\WHITE8X8", tile = true, tileSize = 8, edgeSize = 1, insets = {left = 1, right = 1, top = 1, bottom = 1} } while(frame["item"..i]) do itemframe = frame["item"..i] itemframe.label:SetBackdrop({}) itemframe.label.text:SetText("") itemframe.label:SetWidth(68) local j = 1 for k, v in pairs(shown) do itemframe[k] = CreateFrame("Frame", nil, itemframe) itemframe[k]:SetSize(16, 14) itemframe[k]:SetPoint("LEFT", (j-1)*17, 0) itemframe[k]:SetBackdrop(backdrop) itemframe[k]:SetBackdropBorderColor(v.r, v.g, v.b, 0.25) itemframe[k]:SetBackdropColor(0, 0, 0, 0.5) itemframe[k].text = itemframe[k]:CreateFontString(nil, "ARTWORK") itemframe[k].text:SetFont(UNIT_NAME_FONT, 12, "NORMAL") itemframe[k].text:SetPoint("CENTER") itemframe[k].text:SetText(strsubutf8(_G[k] or k,1,1)) itemframe[k].text:SetTextColor(v.r, v.g, v.b) itemframe[k].text:SetShadowOffset(-1, -1) itemframe[k].text:SetShadowColor(0, 0, 0, 0.9) j = j + 1 end i = i + 1 end end) LibEvent:attachTrigger("INSPECT_ITEMFRAME_UPDATED", function(this, itemframe) if not IsGreenStateEnabled() then return end for k in pairs(shown) do if (itemframe[k]) then itemframe[k]:SetAlpha(0.05) end end if (itemframe.link) then local stats = GetItemStats(itemframe.link) for k in pairs(stats) do if (shown[k] and itemframe[k]) then itemframe[k]:SetAlpha(1) end end end end)
function Initialize() measure_seconds = SKIN:GetMeasure("MeasureSeconds") previous_value = measure_seconds:GetValue() current_framecount = 0 end function Update() if measure_seconds:GetValue() ~= previous_value then SKIN:Bang("!SetOption", "MeterFPS", "Text", current_framecount .. " fps") current_framecount = 0 previous_value = measure_seconds:GetValue() end current_framecount = current_framecount + 1 end
require 'circle' Arc = { x = 0, y = 0, radius = 0, width = 1, dot_radius = 0, start_rads = 0, end_rads = 0, total_rads = 0, direction = 'cw', player = 0, co = nil } function Arc:update(dr) self.total_rads = self.total_rads + dr self.end_rads = self.end_rads + (self.direction == 'acw' and -dr or dr) end function Arc:changeDirection() dx = math.cos(self.end_rads) * self.radius * 2 dy = math.sin(self.end_rads) * self.radius * 2 start_rads = self.end_rads + (self.direction == 'acw' and math.pi or -math.pi) new_arc = Arc:new({ x = self.x + dx, y = self.y + dy, radius = self.radius, width = self.width, dot_radius = self.dot_radius, start_rads = start_rads, end_rads = start_rads, total_rads = self.total_rads, direction = self.direction == 'acw' and 'cw' or 'acw', player = self.player }) return new_arc end function Arc:addToCollider(collider) local co = collider:circle(self.x, self.y, self.radius) co.arc = self -- Hard reference to collider object needed to stop GC self.co = co end function Arc:rads() return self.direction == 'acw' and self.end_rads or self.end_rads - math.pi end function Arc:intersectsSelf() local arc_delta = self.end_rads - self.start_rads return math.abs(arc_delta) >= math.pi * 2 end function Arc:intersectsArc(other) -- Special case self intersect if self == other then return (math.abs(self.end_rads - self.start_rads) >= 2 * math.pi) and 1 or 0 end local intersect_angles = intersectAngles(self, other) if intersect_angles == nil then -- overlapping (should not happen) return getAdjustedBetween(other.start_rads, other.end_rads, self.end_rads) and 1 or 0 else local intersects = 0; for i, angles in pairs(intersect_angles) do local self_intersect, other_intersect = getAdjustedBetween(self.start_rads, self.end_rads, angles[1]), getAdjustedBetween(other.start_rads, other.end_rads, angles[2]) if self_intersect and other_intersect then if self.player ~= other.player then intersects = intersects + 1 else -- Can't hit own line until at least 2 * pi past intersection. This stops adjoining arc segments from intersecting until a full circle is complete. local other_total_at_intersect = other:totalWithEnd(other_intersect) if self.total_rads - other_total_at_intersect >= 2 * math.pi then intersects = intersects + 1 end end end end return intersects end end function getAdjustedBetween(start_rads, end_rads, query_rads) start_rads, end_rads = math.min(start_rads, end_rads), math.max(start_rads, end_rads) local two_pi = 2 * math.pi -- Adjust query which is in 0..2*pi range to the (possible) range of our arc. query_rads = query_rads + two_pi * math.floor(start_rads / two_pi) query_rads = (start_rads <= query_rads) and query_rads or query_rads + two_pi return (start_rads <= query_rads and query_rads <= end_rads) and query_rads or nil end function Arc:totalWithEnd(new_end) local end_delta = self.end_rads - new_end return self.total_rads - math.abs(end_delta) end function Arc:drawArc(trail_color) love.graphics.setColor(trail_color[1], trail_color[2], trail_color[3], trail_color[4]) love.graphics.setLineWidth(self.width) local length = math.abs(self.start_rads - self.end_rads) * self.radius if length >= 5 then love.graphics.arc('line', 'open', self.x, self.y, self.radius, self.start_rads, self.end_rads) else -- love.graphics.arc doesn't draw anything for very small arcs love.graphics.line(self.x + self.radius * math.cos(self.start_rads), self.y + self.radius * math.sin(self.start_rads), self.x + self.radius * math.cos(self.end_rads), self.y + self.radius * math.sin(self.end_rads)) end end function Arc:drawEnd(trail_length_font, trail_color, size, trail_length) love.graphics.setColor(trail_color[1], trail_color[2], trail_color[3], trail_color[4]) local point = self:endPos() love.graphics.circle('fill', point.x, point.y, self.dot_radius * size) love.graphics.circle('line', point.x, point.y, self.dot_radius * size) love.graphics.setFont(trail_length_font) love.graphics.translate(point.x, point.y) love.graphics.rotate(self.end_rads) local font_height = trail_length_font:getHeight() love.graphics.setColor(1, 1, 1, 0.5) love.graphics.print(string.format('%.2f', trail_length), font_height / 1.5, -font_height / 2.4) love.graphics.origin() end function Arc:endPos() local x = self.x + math.cos(self.end_rads) * self.radius local y = self.y + math.sin(self.end_rads) * self.radius return { x = x, y = y } end function Arc:length() return math.abs(self.end_rads - self.start_rads) end function Arc:toJson() return { direction = self.direction, end_rads = self.end_rads, radius = self.radius, start_rads = self.start_rads, total_rads = self.total_rads, x = self.x, y = self.y, } end function Arc:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function math.sign(n) return n > 0 and 1 or n < 0 and -1 or 0 end
-- Configuration file for the RV32IM on, Spike Simulator -- Intended to run with the Proxy Kernel --specific_files = sf( "boot.s utils.s hostif_%s.c platform.c host.c", comp.cpu:lower() ) specific_files = sf( "platform.c stubs.c hostif_linux.c syscalls.c ", comp.cpu:lower() ) local ldscript = "src/platform/riscv32spike/riscv_local.ld" -- Override default optimize settings --delcf{ "-O3", "-fomit-frame-pointer" } --addcf{ "-O0", "-g" } addcf{"-g", "-O3"} -- Prepend with path specific_files = utils.prepend_path( specific_files, sf( "src/platform/%s", platform ) ) --local ldscript = sf( "src/platform/%s/%s", platform, ldscript ) -- Standard GCC flags addcf{ '-ffunction-sections', '-fdata-sections', '-fno-strict-aliasing', '-Wall'} --addlf{ '-nostartfiles', '-nostdlib', '-T', ldscript, '-Wl,--gc-sections', '-Wl,--allow-multiple-definition' } addlf{ '-Wl,--allow-multiple-definition','-Wl,--gc-sections' , '-T', ldscript } addlib{ 'c','gcc','m' } local target_flags = { '-march=rv32im' ,'-mabi=ilp32' } --,'-mstrict-align'} addcf{ target_flags} --addcf{ target_flags, '-fno-builtin', '-fno-stack-protector' } --addlf{ target_flags, '-Wl,-e,start', '-Wl,-static' } --addaf{ '-felf' } -- Also tell the builder that we don't need dependency checks for assembler files builder:set_asm_dep_cmd( false ) -- Toolset data tools.riscv32spike = {} -- Programming function for i386 (not needed, empty function) tools.riscv32spike.progfunc = function( target, deps ) print "Run the simulator (./run_elua_sim.sh) and enjoy :) Linux only." return 0 end -- Add the programming function explicitly for this target tools.riscv32spike.pre_build = function() local t = builder:target( "#phony:prog", { exetarget }, tools.riscv32spike.progfunc ) builder:add_target( t, "build eLua firmware image", { "prog" } ) end
----------------------------------- -- Area: Nashmau -- NPC: Awaheen -- Standard Info NPC ----------------------------------- local ID = require("scripts/zones/Nashmau/IDs"); ----------------------------------- function onTrade(player,npc,trade) -- Trade: Receive: -- 1 x Imperial Gold Piece (2187) 5 x Imperial Mythril Piece(2186) -- 1 x Imperial Mythril Piece(2186) 2 x Imperial Silver Piece(2185) -- 1 x Imperial Silver Piece (2185) 5 x Imperial Bronze Piece(2184) local nbr = 0; local reward = 0; if (trade:getItemCount() == 1) then if (trade:hasItemQty(2187,1)) then nbr = 5 ; reward = 2186; elseif (trade:hasItemQty(2186,1)) then nbr = 2 ; reward = 2185; elseif (trade:hasItemQty(2185,1)) then nbr = 5 ; reward = 2184; end end if (reward > 0) then local boucle; if (player:getFreeSlotsCount() >= 1) then player:tradeComplete(); player:addItem(reward,nbr); for boucle=1,nbr,1 do player:messageSpecial(ID.text.ITEM_OBTAINED,reward); end else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,reward); end end end; function onTrigger(player,npc) player:startEvent(240); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
object_mobile_keyan_farlander = object_mobile_shared_keyan_farlander:new { } ObjectTemplates:addTemplate(object_mobile_keyan_farlander, "object/mobile/keyan_farlander.iff")
local fn = require 'core.fn' obj = {} if not obj.list then obj.list = {} end obj.__index = obj obj.__next_obj_id = 0 obj.instance_meta = { __call = function(object, ...) return obj.instance(object, ...) end, __index = function(object, key) return obj.get_attribute(object, key) end, __newindex = function(object, key, value) return obj.set_attribute(object, key, value) end, __tostring = fn.to_string -- instance_of = function(object, type) return obj.is_instance(object, type) end, -- subclass = function(base, class_name) return obj.subclass(base, class_name) end } setmetatable(obj.instance_meta, obj) function obj.__next_id() local id = obj.__next_obj_id obj.__next_obj_id = obj.__next_obj_id + 1 return id end function obj.type(type_name) return obj.list[type_name] end function obj.type_exists(type_name) return obj.list[type_name] ~= nil end function obj.type_list() local result = {} for k,v in pairs(obj.list) do result[#result+1] = obj.list[k] end return result end function obj.is_object(table) if type(table) == 'table' then return table['__classtype'] ~= nil end return nil end function obj.assert_object(object) if obj.is_object(object) then return true else error('Error in obj.assert_object(object) : object was not of object type') return nil end end function obj.same_type(object, other) return (object.__classid == other.__classid) end function obj.is_instance(object) return obj.is_object(object) and object.__isinstance end function obj.is_prototype(object) return obj.is_object(object) and (object.__instanceid == -1) end function obj.instance_of(object, type) if obj.assert_object(object) and obj.assert_object(type) then local object_is_instance = obj.is_instance(object) local type_is_type = obj.is_object(type) if obj.same_type(object, type) then return object_is_instance and type_is_type end else error('Error in obj.instance_of(object, type) : Only objects can be instances of type objects') return nil end end function obj.new(class_name, constructor, ...) if class_name and type(class_name) == 'string' then if not obj.list[class_name] then local class = { __classid = obj.__next_id(), __instanceid = -1, __next_instance_id = 0, __classtype = true, __isinstance = false, class_name = class_name, attributes = {}, superclasses = {}, subclasses = {}, constructor = nil, arguments = {...} } setmetatable(class, obj.instance_meta) if type(constructor) == 'function' then rawset(class, 'constructor', constructor) end obj.list[class.class_name] = class return class else error('Error in obj.new(class_name, ...) : obj.list already contains a class named "'..class_name..'"') return nil end else --[[TODO: Replace with Expect]] error('Error in obj.new(class_name, ...) : class_name invalid') return nil end end function obj.subclass(base, class_name, constructor, ...) if obj.is_object(base) then local type = obj.new(class_name, function (instance, ...) local base_result = nil if type(base.constructor) == 'function' then base_result = base.constructor() end return base_result, constructor(...) end, ...) obj.add_superclass(type, base) return type else error('Error in obj.subclass(base, class_name) : base must be a type object') return nil end end function obj.descends_from(object, type) if obj.assert_object(object) and obj.assert_object(type) then local has_subclasses = (#type.subclasses > 0) if has_subclasses then -- If object is type, or object is among type's subclasses, true if fn.satisfy(type.subclasses, obj.same_type, object) or obj.same_type(object, type) then return true else -- Otherwise recursively check object descends_from type's subclasses for k,v in pairs(type.subclasses) do if obj.descends_from(object, obj.type(v)) then return true end end end end return false end return nil end function obj.add_superclass(base, superclass) if obj.assert_object(base) and obj.assert_object(superclass) then if obj.same_type(base, superclass) then error("obj.add_superclass(base, superclass): base and superclass must be different types") return nil end if base.superclasses[superclass] then error("obj.add_superclass(base, superclass): superclass is an existing superclass of base") end if obj.descends_from(base, superclass) or obj.descends_from(superclass, base) then error("obj.add_superclass(base, superclass): neither base nor superclass may descend from one another") return nil else local base_super = rawget(base, 'superclasses') local super_subs = rawget(superclass, 'subclasses') rawset(base_super, #base_super+1, obj.name(superclass)) rawset(super_subs, #super_subs+1, obj.name(base)) return true end end end function obj.add_subclass(base, subclass) return obj.add_superclass(subclass, base) end function obj.identity(class) return class.__classid, class.__instanceid end function obj.name(class) return class.class_name end function obj.instance(class, ...) local instance = fn.clone(class) instance.arguments = fn.clone({...}) instance.attributes = fn.clone(rawget(class, 'attributes')) instance.subclasses = fn.clone(rawget(class, 'subclasses')) instance.superclasses = fn.clone(rawget(class, 'superclasses')) instance.constructor = class.constructor instance.class_name = obj.name(class) instance.__classid, instance.__instanceid = obj.identity(class) instance.__classtype = true instance.__isinstance = true if class.__next_instance_id ~= nil then instance.__instanceid = rawget(class, '__next_instance_id') rawset(class, '__next_instance_id', rawget(class, '__next_instance_id') + 1) end instance.__next_instance_id = nil setmetatable(instance, obj.instance_meta) if instance.constructor ~= nil and type(instance.constructor) == 'function' then instance.constructor(instance, ...) end return instance end function obj.get_attribute(object, key) if obj.assert_object(object) then local attributes = rawget(object, 'attributes') local instance_attribute = rawget(attributes, key) if not instance_attribute then local superclasses = rawget(object, 'superclasses') for k,v in pairs(superclasses) do instance_attribute = obj.get_attribute(obj.list[v], key) if instance_attribute then return instance_attribute end end end return instance_attribute end end function obj.set_attribute(object, key, value) object.attributes[key] = value return object.attributes[key] end return obj
--- Allows the player to determine where he is and where he can go -- @classmod LookCommand -- region imports local class = require('classes/class') local prototype = require('prototypes/prototype') require('prototypes/command') local adventurers = require('functional/game_context/adventurers') local LookEvent = require('classes/events/look') -- endregion local LookCommand = {} function LookCommand.priority() return 'explicit' end function LookCommand:parse(game_ctx, local_ctx, text) if game_ctx.in_setup_phase then return end if text == '/look' then local loc_advn_nm = adventurers.get_local_name(game_ctx, local_ctx) return true, { LookEvent:new{ adventurer_name = loc_advn_nm } } end return false, nil end prototype.support(LookCommand, 'command') return class.create('LookCommand', LookCommand)
-------------------------------- -- @module BillboardParticleSystem -- @extend Node,TextureProtocol -- @parent_module cc -------------------------------- -- size variance in pixels of each particle -- @function [parent=#BillboardParticleSystem] getStartSizeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- start color of each particle -- @function [parent=#BillboardParticleSystem] getStartColor -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- particles movement type: Free or Grouped<br> -- since v0.8 -- @function [parent=#BillboardParticleSystem] getPositionType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setPosVar -- @param self -- @param #vec2_table pos -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getEndSpin -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRotatePerSecondVar -- @param self -- @param #float degrees -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getStartSpinVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getRadialAccelVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- end size variance in pixels of each particle -- @function [parent=#BillboardParticleSystem] getEndSizeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRotation -- @param self -- @param #float newRotation -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setTangentialAccel -- @param self -- @param #float t -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setScaleY -- @param self -- @param #float newScaleY -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setScaleX -- @param self -- @param #float newScaleX -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getRadialAccel -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartRadius -- @param self -- @param #float startRadius -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRotatePerSecond -- @param self -- @param #float degrees -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndSize -- @param self -- @param #float endSize -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getGravity -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getTangentialAccel -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndRadius -- @param self -- @param #float endRadius -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getSpeed -- @param self -- @return float#float ret (return value: float) -------------------------------- -- angle and angle variation of each particle -- @function [parent=#BillboardParticleSystem] getAngle -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndColor -- @param self -- @param #color4f_table color -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartSpin -- @param self -- @param #float spin -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setDuration -- @param self -- @param #float duration -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setTexture -- @param self -- @param #cc.Texture2D texture -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- Position variance of the emitter -- @function [parent=#BillboardParticleSystem] getPosVar -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] isBlendAdditive -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getSpeedVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setPositionType -- @param self -- @param #int type -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- stop emitting particles. Running particles will continue to run until they die -- @function [parent=#BillboardParticleSystem] stopSystem -- @param self -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- sourcePosition of the emitter -- @function [parent=#BillboardParticleSystem] getSourcePosition -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setLifeVar -- @param self -- @param #float lifeVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setTotalParticles -- @param self -- @param #int totalParticles -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndColorVar -- @param self -- @param #color4f_table color -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getAtlasIndex -- @param self -- @return int#int ret (return value: int) -------------------------------- -- start size in pixels of each particle -- @function [parent=#BillboardParticleSystem] getStartSize -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setTextureWithRect -- @param self -- @param #cc.Texture2D texture -- @param #rect_table rect -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartSpinVar -- @param self -- @param #float pinVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- Kill all living particles. -- @function [parent=#BillboardParticleSystem] resetSystem -- @param self -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setAtlasIndex -- @param self -- @param #int index -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setTangentialAccelVar -- @param self -- @param #float t -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- How many seconds the emitter will run. -1 means 'forever' -- @function [parent=#BillboardParticleSystem] getDuration -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getEndRadius -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setDepthTestEnabled -- @param self -- @param #bool enable -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRadialAccelVar -- @param self -- @param #float t -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartSize -- @param self -- @param #float startSize -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setSpeed -- @param self -- @param #float speed -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getStartSpin -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getRotatePerSecond -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEmitterMode -- @param self -- @param #int mode -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndRadiusVar -- @param self -- @param #float endRadiusVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setSourcePosition -- @param self -- @param #vec2_table pos -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getEndSpinVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setBlendAdditive -- @param self -- @param #bool value -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setLife -- @param self -- @param #float life -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setAngleVar -- @param self -- @param #float angleVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRotationIsDir -- @param self -- @param #bool t -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndSizeVar -- @param self -- @param #float sizeVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setAngle -- @param self -- @param #float angle -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getTangentialAccelVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Switch between different kind of emitter modes:<br> -- - kParticleModeGravity: uses gravity, speed, radial and tangential acceleration<br> -- - kParticleModeRadius: uses radius movement + rotation -- @function [parent=#BillboardParticleSystem] getEmitterMode -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndSpinVar -- @param self -- @param #float endSpinVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- angle variance of each particle -- @function [parent=#BillboardParticleSystem] getAngleVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartColor -- @param self -- @param #color4f_table color -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getRotatePerSecondVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- end size in pixels of each particle -- @function [parent=#BillboardParticleSystem] getEndSize -- @param self -- @return float#float ret (return value: float) -------------------------------- -- life, and life variation of each particle -- @function [parent=#BillboardParticleSystem] getLife -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setSpeedVar -- @param self -- @param #float speed -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setGravity -- @param self -- @param #vec2_table g -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEmissionRate -- @param self -- @param #float rate -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- end color variance of each particle -- @function [parent=#BillboardParticleSystem] getEndColorVar -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getRotationIsDir -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setScale -- @param self -- @param #float s -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- emission rate of the particles -- @function [parent=#BillboardParticleSystem] getEmissionRate -- @param self -- @return float#float ret (return value: float) -------------------------------- -- end color and end color variation of each particle -- @function [parent=#BillboardParticleSystem] getEndColor -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- life variance of each particle -- @function [parent=#BillboardParticleSystem] getLifeVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setCamera -- @param self -- @param #cc.Camera camera -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartSizeVar -- @param self -- @param #float sizeVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- does the alpha value modify color -- @function [parent=#BillboardParticleSystem] setOpacityModifyRGB -- @param self -- @param #bool opacityModifyRGB -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getStartRadius -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Quantity of particles that are being simulated at the moment -- @function [parent=#BillboardParticleSystem] getParticleCount -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getStartRadiusVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartColorVar -- @param self -- @param #color4f_table color -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setEndSpin -- @param self -- @param #float endSpin -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setRadialAccel -- @param self -- @param #float t -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] setStartRadiusVar -- @param self -- @param #float startRadiusVar -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] getEndRadiusVar -- @param self -- @return float#float ret (return value: float) -------------------------------- -- start color variance of each particle -- @function [parent=#BillboardParticleSystem] getStartColorVar -- @param self -- @return color4f_table#color4f_table ret (return value: color4f_table) -------------------------------- -- @overload self, map_table -- @overload self, string -- @function [parent=#BillboardParticleSystem] create -- @param self -- @param #string filename -- @return BillboardParticleSystem#BillboardParticleSystem ret (return value: cc.BillboardParticleSystem) -------------------------------- -- -- @function [parent=#BillboardParticleSystem] BillboardParticleSystem -- @param self -- @return BillboardParticleSystem#BillboardParticleSystem self (return value: cc.BillboardParticleSystem) return nil
--[[ Ourlife: RPG This program is free software; you can redistribute it and/or modify it under the terms of the GNU (General Public License) as puslisched by the free software fundation; either version 3 of the license, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. (c) 2014 OurLife. All rights reserved. ]] function toggleBlur(state, power) if state then blurData.fxPower=power or 1 showBlur() else hideBlur() end end
local TradeSkillUI = { Name = "TradeSkillUI", Type = "System", Namespace = "C_TradeSkillUI", Functions = { { Name = "CraftRecipe", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "numCasts", Type = "number", Nilable = false, Default = 1 }, { Name = "optionalReagents", Type = "table", InnerType = "OptionalReagentInfo", Nilable = true }, { Name = "recipeLevel", Type = "number", Nilable = true }, }, }, { Name = "GetAllProfessionTradeSkillLines", Type = "Function", Returns = { { Name = "skillLineID", Type = "table", InnerType = "number", Nilable = false }, }, }, { Name = "GetOptionalReagentBonusText", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "optionalReagentIndex", Type = "number", Nilable = false }, { Name = "optionalReagents", Type = "table", InnerType = "OptionalReagentInfo", Nilable = false }, }, Returns = { { Name = "bonusText", Type = "string", Nilable = false }, }, }, { Name = "GetOptionalReagentInfo", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, }, Returns = { { Name = "slots", Type = "table", InnerType = "OptionalReagentSlot", Nilable = false }, }, }, { Name = "GetRecipeInfo", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "recipeLevel", Type = "number", Nilable = true }, }, Returns = { { Name = "recipeInfo", Type = "TradeSkillRecipeInfo", Nilable = true }, }, }, { Name = "GetRecipeNumReagents", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "recipeLevel", Type = "number", Nilable = true }, }, Returns = { { Name = "numReagents", Type = "number", Nilable = false }, }, }, { Name = "GetRecipeReagentInfo", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "reagentIndex", Type = "number", Nilable = false }, { Name = "recipeLevel", Type = "number", Nilable = true }, }, Returns = { { Name = "reagentName", Type = "string", Nilable = true }, { Name = "reagentFileID", Type = "number", Nilable = true }, { Name = "reagentCount", Type = "number", Nilable = false }, { Name = "playerReagentCount", Type = "number", Nilable = false }, }, }, { Name = "GetRecipeRepeatCount", Type = "Function", Returns = { { Name = "recastTimes", Type = "number", Nilable = false }, }, }, { Name = "GetTradeSkillDisplayName", Type = "Function", Arguments = { { Name = "skillLineID", Type = "number", Nilable = false }, }, Returns = { { Name = "professionDisplayName", Type = "string", Nilable = false }, }, }, { Name = "GetTradeSkillLine", Type = "Function", Returns = { { Name = "skillLineID", Type = "number", Nilable = false }, { Name = "skillLineDisplayName", Type = "string", Nilable = false }, { Name = "skillLineRank", Type = "number", Nilable = false }, { Name = "skillLineMaxRank", Type = "number", Nilable = false }, { Name = "skillLineModifier", Type = "number", Nilable = false }, { Name = "parentSkillLineID", Type = "number", Nilable = true }, { Name = "parentSkillLineDisplayName", Type = "string", Nilable = true }, }, }, { Name = "GetTradeSkillLineInfoByID", Type = "Function", Arguments = { { Name = "skillLineID", Type = "number", Nilable = false }, }, Returns = { { Name = "skillLineDisplayName", Type = "string", Nilable = false }, { Name = "skillLineRank", Type = "number", Nilable = false }, { Name = "skillLineMaxRank", Type = "number", Nilable = false }, { Name = "skillLineModifier", Type = "number", Nilable = false }, { Name = "parentSkillLineID", Type = "number", Nilable = true }, }, }, { Name = "IsEmptySkillLineCategory", Type = "Function", Arguments = { { Name = "categoryID", Type = "number", Nilable = false }, }, Returns = { { Name = "effectivelyKnown", Type = "bool", Nilable = false }, }, }, { Name = "SetRecipeRepeatCount", Type = "Function", Arguments = { { Name = "recipeSpellID", Type = "number", Nilable = false }, { Name = "numCasts", Type = "number", Nilable = false, Default = 1 }, { Name = "optionalReagents", Type = "table", InnerType = "OptionalReagentInfo", Nilable = true }, }, }, }, Events = { { Name = "NewRecipeLearned", Type = "Event", LiteralName = "NEW_RECIPE_LEARNED", Payload = { { Name = "recipeID", Type = "number", Nilable = false }, { Name = "recipeLevel", Type = "number", Nilable = true }, { Name = "baseRecipeID", Type = "number", Nilable = true }, }, }, { Name = "ObliterumForgeClose", Type = "Event", LiteralName = "OBLITERUM_FORGE_CLOSE", }, { Name = "ObliterumForgePendingItemChanged", Type = "Event", LiteralName = "OBLITERUM_FORGE_PENDING_ITEM_CHANGED", }, { Name = "ObliterumForgeShow", Type = "Event", LiteralName = "OBLITERUM_FORGE_SHOW", }, { Name = "TradeSkillClose", Type = "Event", LiteralName = "TRADE_SKILL_CLOSE", }, { Name = "TradeSkillDataSourceChanged", Type = "Event", LiteralName = "TRADE_SKILL_DATA_SOURCE_CHANGED", }, { Name = "TradeSkillDataSourceChanging", Type = "Event", LiteralName = "TRADE_SKILL_DATA_SOURCE_CHANGING", }, { Name = "TradeSkillDetailsUpdate", Type = "Event", LiteralName = "TRADE_SKILL_DETAILS_UPDATE", }, { Name = "TradeSkillListUpdate", Type = "Event", LiteralName = "TRADE_SKILL_LIST_UPDATE", }, { Name = "TradeSkillNameUpdate", Type = "Event", LiteralName = "TRADE_SKILL_NAME_UPDATE", }, { Name = "TradeSkillOptionalReagentBonusTextUpdated", Type = "Event", LiteralName = "TRADE_SKILL_OPTIONAL_REAGENT_BONUS_TEXT_UPDATED", Payload = { { Name = "itemID", Type = "number", Nilable = false }, }, }, { Name = "TradeSkillShow", Type = "Event", LiteralName = "TRADE_SKILL_SHOW", }, { Name = "UpdateTradeskillRecast", Type = "Event", LiteralName = "UPDATE_TRADESKILL_RECAST", }, }, Tables = { { Name = "OptionalReagentItemFlag", Type = "Enumeration", NumValues = 1, MinValue = 0, MaxValue = 0, Fields = { { Name = "TooltipShowsAsStatModifications", Type = "OptionalReagentItemFlag", EnumValue = 0 }, }, }, { Name = "OptionalReagentSlot", Type = "Structure", Fields = { { Name = "requiredSkillRank", Type = "number", Nilable = false }, { Name = "lockedReason", Type = "string", Nilable = true }, { Name = "slotText", Type = "string", Nilable = true }, { Name = "options", Type = "table", InnerType = "number", Nilable = false }, }, }, }, }; APIDocumentation:AddDocumentationTable(TradeSkillUI);
require 'window' local myfile = require 'myfile' require 'mystring' require 'scratch' --Reload hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function() hs.reload() end) hs.alert.show("Hammerspoon config reloaded") --Force command apps I use to be visible hs.hotkey.bind({"shift"}, "F12", function() os.execute("open -a Terminal") hs.timer.doAfter(0.2, function() fillLeftOneThird() --hs.timer.doAfter(0.2, function() --os.execute("open -a Simulator") --hs.timer.doAfter(0.2, function() --fillLeftOneThird() hs.timer.doAfter(0.2, function() os.execute("open -a MacVim") hs.timer.doAfter(0.2, function() fillRightTwoThird() end) end) --end) --end) end) end) --Test "direct" shortcuts instead of Commander hs.hotkey.bind({"ctrl", "shift"}, "f", function() os.execute("open -a Finder") end) hs.hotkey.bind({"ctrl", "shift"}, "i", function() os.execute("open -a Simulator") end) --Conflicts with move tab to right in Vim --hs.hotkey.bind({"ctrl", "shift"}, "l", function() --os.execute("open -a Slack") --end) hs.hotkey.bind({"ctrl", "shift"}, "o", function() os.execute("open -a 'OmniOutliner Professional'") end) hs.hotkey.bind({"ctrl", "shift"}, "s", function() os.execute("open -a Safari") end) hs.hotkey.bind({"ctrl", "shift"}, "t", function() os.execute("open -a Terminal") end) hs.hotkey.bind({"ctrl", "shift"}, "v", function() os.execute("open -a MacVim") end) hs.hotkey.bind({"ctrl", "shift"}, "w", function() os.execute("open -a Wunderlist") end) hs.hotkey.bind({"ctrl", "shift"}, "x", function() os.execute("open -a Xcode") end) local downloadsDir = os.getenv("HOME") .. "/Downloads/" downloadsDir = myfile:escapeFileName(downloadsDir) downloadsWatcher = hs.pathwatcher.new(downloadsDir, function(changed) for _,file in pairs(changed) do moveProvisioningProfiles(file) moveAirDroppedImages(file) moveAirDroppedVideos(file) moveCerts(file) moveEpub(file) end end) downloadsWatcher:start() hs.shutdownCallback = function() downloadsWatcher:stop() end --Strangely, this doesn't append a -1, -2 for duplicate filenames with generateUniqueDestinationFilename(). Maybe due to a space in the path? But good in this case, because I want to replace provisioning profiles with the same name if it exists function moveProvisioningProfiles(filename) return moveDownloadedFilesToDirectory(filename, "", "mobileprovision", "Provisioning Profile", "/Users/hboon/Dropbox/hb-and-ml-common/Provisioning Profiles/") end function moveAirDroppedImages(filename) moveAirDroppedImageAndVideos(filename, ".png", "image") return moveAirDroppedImageAndVideos(filename, ".jpg", "image") end function moveAirDroppedVideos(filename) return moveAirDroppedImageAndVideos(filename, ".mov", "video") end function moveAirDroppedImageAndVideos(filename, ext, fileType) return moveDownloadedFilesToDesktop(filename, "img_", ext, fileType) end function moveCerts(filename) return moveDownloadedFilesToDesktop(filename, "", "cer", "Cert") end function moveEpub(filename) return moveDownloadedFilesToDirectory(filename, "", "epub", "ePub", "/Users/hboon/Dropbox/book-drop/") end function moveDownloadedFilesToDesktop(filename, prefix, ext, fileType) local destDir = os.getenv("HOME") .. "/Desktop/" destDir = myfile:escapeFileName(destDir) local name = filename:match( "([^/]+)$" ) --Must check against filename (with space verbatim), and not against escapedSrc (with \\space) if string.lower(filename:sub(-string.len(ext))) == ext and string.lower(name:sub(1, string.len(prefix))) == prefix and myfile:exists(filename) then name = generateUniqueDestinationFilename(name, destDir) --TODO need to escape the destination filename too local escapedSrc = myfile:escapeFileName(filename) os.execute("mv ${escapedSrc} ${destDir}${name}" % {escapedSrc=escapedSrc, destDir=destDir, name=name}) local msg = "Moved ${fileType} ${name} from ${from} to ${to}" % {fileType=fileType, name=name, from="Downloads/", to="Desktop/"} hs.notify.new({title="Hammerspoon", informativeText=msg}):send() return true end return false end --Change moveDownloadedFilesToDesktop() to call this, passing in destDir function moveDownloadedFilesToDirectory(filename, prefix, ext, fileType, destDir) destDir = myfile:escapeFileName(destDir) local name = filename:match( "([^/]+)$" ) --Must check against filename (with space verbatim), and not against escapedSrc (with \\space) if string.lower(filename:sub(-string.len(ext))) == ext and string.lower(name:sub(1, string.len(prefix))) == prefix and myfile:exists(filename) then name = generateUniqueDestinationFilename(name, destDir) --TODO need to escape the destination filename too local escapedSrc = myfile:escapeFileName(filename) os.execute("mv ${escapedSrc} ${destDir}${name}" % {escapedSrc=escapedSrc, destDir=destDir, name=name}) local msg = "Moved ${fileType} ${name} from ${from} to ${to}" % {fileType=fileType, name=name, from="Downloads/", to="Desktop/"} hs.notify.new({title="Hammerspoon", informativeText=msg}):send() return true end return false end -- Appends a -1 or -2, etc if file already exists. e.g. "abc.ext" -> "abc-1.ext" function generateUniqueDestinationFilename(name, destDir) local destFilename = destDir .. name while myfile:exists(destFilename) do --TODO need to escape the destination filename too local nameWithoutExt, _, extWithDot = myfile:breakFilename(name) local nameWithoutNum, num = breakTrailingNumeric(nameWithoutExt) if num then num = num+1 else num = 1 end name = nameWithoutNum .. "-" .. num .. extWithDot destFilename = destDir .. name end return name end -- "abc-1" -> "abc", 1 -- "abc" -> "abc", nil function breakTrailingNumeric(name) if string.find(name, "-") then local _, _, num = string.find(name, "([^-]*)$") -- TODO check if end with "-XXX" a number return name:sub(1, string.len(name)-string.len(num)-1), math.ceil(num+0) else return name, nil end end
require('onmt.init') local tester = ... local tensorTest = torch.TestSuite() local function reuseTest(a, size) local b = onmt.utils.Tensor.reuseTensor(a, size) tester:eq(torch.pointer(b:storage()), torch.pointer(a:storage())) tester:eq(b:ne(0):sum(), 0) end local function compareStorage(a, b, func) if torch.isTensor(a) then return func(torch.pointer(a:storage()), torch.pointer(b:storage())) else for k, _ in pairs(a) do if not compareStorage(a[k], b[k], func) then return false end end return true end end local function sharedStorage(a, b) return compareStorage(a, b, function (p1, p2) return p1 == p2 end) end local function nonSharedStorage(a, b) return compareStorage(a, b, function (p1, p2) return p1 ~= p2 end) end function tensorTest.reuse_smaller() local a = torch.Tensor(10, 200) reuseTest(a, { 5, 200 }) end function tensorTest.reuse_same() local a = torch.Tensor(10, 200) reuseTest(a, a:size()) end function tensorTest.reuse_multipleResize() local a = torch.Tensor(10, 200) reuseTest(a, { 5, 200 }) reuseTest(a, { 10, 200 }) end function tensorTest.reuseTable() local a = { torch.Tensor(10, 200), torch.Tensor(10, 200) } local b = onmt.utils.Tensor.reuseTensorTable(a, {5, 100}) tester:ne(torch.pointer(b), torch.pointer(a)) tester:eq(sharedStorage(a, b), true) end function tensorTest.recursiveApply_empty() local identity = function (t) return t end local t = {} local expected = {} tester:eq(onmt.utils.Tensor.recursiveApply(t, identity), expected) end function tensorTest.recursiveApply_inline() local addOne = function (t) return t:add(1) end local t = torch.Tensor({0, 0}) local expected = torch.Tensor({1, 1}) tester:eq(onmt.utils.Tensor.recursiveApply(t, addOne), expected) end function tensorTest.recursiveApply_nested() local addOne = function (t) return t:add(1) end local t = { { torch.Tensor({0, 0}), torch.Tensor({0}) }, torch.Tensor({0}) } local expected = { { torch.Tensor({1, 1}), torch.Tensor({1}) }, torch.Tensor({1}) } tester:eq(onmt.utils.Tensor.recursiveApply(t, addOne), expected) end function tensorTest.recursiveClone() local t = { { torch.Tensor({0, 0}), torch.Tensor({0}) }, torch.Tensor({0}) } local clone = onmt.utils.Tensor.recursiveClone(t) tester:eq(clone, t) tester:eq(nonSharedStorage(t, clone), true) end function tensorTest.deepClone() local t = { { torch.Tensor({0, 0}), torch.Tensor({0}) }, torch.Tensor({0}) } local clone = onmt.utils.Tensor.deepClone(t) tester:eq(clone, t) tester:eq(nonSharedStorage(t, clone), true) end function tensorTest.recursiveSet() local a = { { torch.Tensor({0, 0}), torch.Tensor({0}) }, torch.Tensor({0}) } local b = { { torch.Tensor({1, 1}), torch.Tensor({1}) }, torch.Tensor({1}) } onmt.utils.Tensor.recursiveSet(a, b) tester:eq(a, b) tester:eq(sharedStorage(a, b), true) end function tensorTest.recursiveAdd_empty() local a = {} local b = {} tester:eq(onmt.utils.Tensor.recursiveAdd(a, b), {}) end function tensorTest.recursiveAdd_inline() local a = torch.Tensor({1, 1}) local b = torch.Tensor({2, 2}) tester:eq(onmt.utils.Tensor.recursiveAdd(a, b), torch.Tensor({3, 3})) end function tensorTest.recursiveAdd_nested() local a = { { torch.Tensor({1, 1}), torch.Tensor({2}) }, torch.Tensor({3}) } local b = { { torch.Tensor({1, 1}), torch.Tensor({2}) }, torch.Tensor({3}) } local c = { { torch.Tensor({2, 2}), torch.Tensor({4}) }, torch.Tensor({6}) } tester:eq(onmt.utils.Tensor.recursiveAdd(a, b), c) end function tensorTest.find() local function find(l, v) for i=1,#l do if l[i]==v then return i end end return 0 end local l = {1,4,6,13,17,23} local t=torch.LongTensor{1,4,6,13,17,23} for i = 1,30 do tester:eq(onmt.utils.Tensor.find(t,i),find(l,i)) end tester:eq(onmt.utils.Tensor.find(t,torch.LongTensor{3,4,5,6,7}),torch.LongTensor{0,2,0,3,0}) tester:eq(onmt.utils.Tensor.find(t,100,1),1) end return tensorTest
--====================================== --th style boss --====================================== boss = Class(enemybase) function boss:init(x, y, name, cards, bg, diff) enemybase.init(self,999999999) self.x = x self.y = y self.img = 'undefined' --boss魔法阵 self.aura_alpha = 255 --法阵透明度 self.aura_alpha_d = 4 --法阵透明度单帧变化值 self.aura_scale = 1 --法阵大小比例 self._bosssys = BossSystem(self, name, cards, bg, diff) --boss系统 --boss行走图 self._wisys = BossWalkImageSystem(self) --行走图系统 --boss ex if self.ex == nil then Kill(self) --开始执行通常符卡系统 end ex.AddBoss(self) --加入ex的boss表中 lstg.tmpvar.boss = self end --!警告:潜在的多玩家适配问题 function boss:frame() --出屏判定关闭 SetAttr(self, 'colli', BoxCheck(self, lstg.world.boundl, lstg.world.boundr, lstg.world.boundb, lstg.world.boundt) and self._colli) --血量下限 self.hp = max(0, self.hp) --符卡系统检查hp self._bosssys:CheckHP() --执行自身task self._bosssys:DoTask() --行走图系统帧逻辑 self._wisys:frame() --受击闪烁 if self.dmgt then self.dmgt = max(0, self.dmgt - 1) end --boss系统帧逻辑 self._bosssys:frame() --魔法阵透明度更新 self.aura_alpha = self.aura_alpha + self.aura_alpha_d self.aura_alpha = min(max(0, self.aura_alpha), 128) end function boss:render() for i=1,25 do SetImageState('boss_aura_3D'..i, 'mul+add', Color(self.aura_alpha, 255, 255, 255)) end Render('boss_aura_3D'..self.ani % 25 + 1, self.x, self.y, self.ani * 0.75, 0.92 * self.aura_scale, (0.8 + 0.12 * cos(self.ani * 0.75)) * self.aura_scale) self._bosssys:render() self._wisys:render(self.dmgt, self.dmgmaxt)--by OLC,行走图系统 end function boss:take_damage(dmg) if self.dmgmaxt then self.dmgt = self.dmgmaxt end if not self.protect then local dmg0 = dmg * self.dmg_factor self.spell_damage = self.spell_damage+dmg0 self.hp = self.hp - dmg0 lstg.var.score = lstg.var.score + 10 end end function boss:kill() _kill_servants(self) self._bosssys:kill() --boss行为更新 if self._bosssys:next() then --切换到下一个行为 PreserveObject(self) else --没有下一个行为了,清除自身和附属的组件 boss.del(self) end end function boss:del() self._bosssys:del() if self.class.defeat then self.class.defeat(self) end ex.RemoveBoss(self) end ---------------------------------------- Include"Thlib\\enemy\\boss_resources.lua" Include"Thlib\\enemy\\boss_system.lua" Include"Thlib\\enemy\\boss_function.lua" Include"Thlib\\enemy\\boss_card.lua" Include"Thlib\\enemy\\boss_dialog.lua" Include"Thlib\\enemy\\boss_other.lua" Include"Thlib\\enemy\\boss_ui.lua"
--Free code from the Roblox Developer Wiki: https://developer.roblox.com/en-us/articles/Player-Player-Collisions local PhysicsService = game:GetService("PhysicsService") local Players = game:GetService("Players") PhysicsService:CreateCollisionGroup("CoinStacks") PhysicsService:CreateCollisionGroup("Coins") PhysicsService:CreateCollisionGroup("Players") PhysicsService:CollisionGroupSetCollidable("CoinStacks", "Coins", false) PhysicsService:CollisionGroupSetCollidable("Coins", "Coins", false) PhysicsService:CollisionGroupSetCollidable("Players", "Coins", false) local previousCollisionGroups = {} local function setCollisionGroup(object) if object:IsA("BasePart") then previousCollisionGroups[object] = object.CollisionGroupId PhysicsService:SetPartCollisionGroup(object, "Players") end end local function setCollisionGroupRecursive(object) setCollisionGroup(object) for _, child in ipairs(object:GetChildren()) do setCollisionGroupRecursive(child) end end local function resetCollisionGroup(object) local previousCollisionGroupId = previousCollisionGroups[object] if not previousCollisionGroupId then return end local previousCollisionGroupName = PhysicsService:GetCollisionGroupName(previousCollisionGroupId) if not previousCollisionGroupName then return end PhysicsService:SetPartCollisionGroup(object, previousCollisionGroupName) previousCollisionGroups[object] = nil end local function onCharacterAdded(character) setCollisionGroupRecursive(character) character.DescendantAdded:Connect(setCollisionGroup) character.DescendantRemoving:Connect(resetCollisionGroup) end local function onPlayerAdded(player) player.CharacterAdded:Connect(onCharacterAdded) end Players.PlayerAdded:Connect(onPlayerAdded)
local constants = {} constants.blacklisted_item_types = { ["blueprint"] = true, ["blueprint-book"] = true, ["copy-paste-tool"] = true, ["deconstruction-item"] = true, ["selection-tool"] = true, ["upgrade-item"] = true, } constants.default_overrides = { ["base"] = { -- circuits ["red-wire"] = "green-wire", ["green-wire"] = "small-lamp", ["small-lamp"] = "arithmetic-combinator", ["arithmetic-combinator"] = "decider-combinator", ["decider-combinator"] = "constant-combinator", ["constant-combinator"] = "power-switch", ["power-switch"] = "programmable-speaker", -- electric poles ["small-electric-pole"] = "medium-electric-pole", ["medium-electric-pole"] = "big-electric-pole", ["big-electric-pole"] = "substation", -- inserters ["burner-inserter"] = "inserter", ["inserter"] = "long-handed-inserter", ["long-handed-inserter"] = "fast-inserter", ["fast-inserter"] = "filter-inserter", ["filter-inserter"] = "stack-inserter", ["stack-inserter"] = "stack-filter-inserter", -- logistic chests ["steel-chest"] = "logistic-chest-active-provider", ["logistic-chest-active-provider"] = "logistic-chest-passive-provider", ["logistic-chest-passive-provider"] = "logistic-chest-storage", ["logistic-chest-storage"] = "logistic-chest-buffer", ["logistic-chest-buffer"] = "logistic-chest-requester", -- pipes ["pipe"] = "pipe-to-ground", -- rails ["rail"] = "rail-signal", ["rail-signal"] = "rail-chain-signal", ["rail-chain-signal"] = "train-stop", -- trains ["locomotive"] = "cargo-wagon", ["cargo-wagon"] = "fluid-wagon", ["fluid-wagon"] = "artillery-wagon", -- tiles ["landfill"] = "stone-brick", ["stone-brick"] = "concrete", ["concrete"] = "hazard-concrete", ["hazard-concrete"] = "refined-concrete", ["refined-concrete"] = "refined-hazard-concrete", }, ["deadlock-beltboxes-loaders"] = { ["express-transport-belt-loader"] = "ultra-fast-belt-loader", ["ultra-fast-belt-loader"] = "extreme-fast-belt-loader", ["extreme-fast-belt-loader"] = "ultra-express-belt-loader", ["ultra-express-belt-loader"] = "extreme-express-belt-loader", ["extreme-express-belt-loader"] = "ultimate-belt-loader", }, ["UltimateBelts"] = { ["express-transport-belt"] = "ultra-fast-belt", ["ultra-fast-belt"] = "extreme-fast-belt", ["extreme-fast-belt"] = "ultra-express-belt", ["ultra-express-belt"] = "extreme-express-belt", ["extreme-express-belt"] = "ultimate-belt", ["express-underground-belt"] = "ultra-fast-underground-belt", ["ultra-fast-underground-belt"] = "extreme-fast-underground-belt", ["extreme-fast-underground-belt"] = "ultra-express-underground-belt", ["ultra-express-underground-belt"] = "extreme-express-underground-belt", ["extreme-express-underground-belt"] = "original-ultimate-underground-belt", ["express-splitter"] = "ultra-fast-splitter", ["ultra-fast-splitter"] = "extreme-fast-splitter", ["extreme-fast-splitter"] = "ultra-express-splitter", ["ultra-express-splitter"] = "extreme-express-splitter", ["extreme-express-splitter"] = "original-ultimate-splitter", }, } constants.interface_version = 1 constants.item_scroll_input_names = { "cen-scroll-next", "cen-scroll-previous", } constants.path_frame_columns = 5 constants.path_frame_max_rows = 3 constants.setting_name_mapping = { ["cen-spawn-items-when-cheating"] = "spawn_items_when_cheating", ["cen-ghost-cursor-transitions"] = "ghost_cursor_transitions", ["cen-enable-tile-pipette"] = "tile_pipette", } return constants
local DEFAULT_DISP_WIDTH = 320 local DISPL_WIDTH2 = DEFAULT_DISP_WIDTH local DISPL_HEIGHT2 = 150 local DISPL_HEIGHT2b = 150 local DISPL_HEIGHT3 = 13 local ANIM_STRIPE = 10 local ANIM_STRIPEb = 8 return { DEFAULT_DISP_WIDTH = DEFAULT_DISP_WIDTH, WIDTH1 = math.floor(720/2), HEIGHT1 = 160, DISPL_WIDTH1 = DEFAULT_DISP_WIDTH, DISPL_HEIGHT1 = 79, ANIM_STRIPE = ANIM_STRIPE, WIDTH2 = 320, DISPL_WIDTH2 = DEFAULT_DISP_WIDTH, DISPL_HEIGHT2 = DISPL_HEIGHT2, HEIGHT2 = DISPL_HEIGHT2*ANIM_STRIPE, CHECKERBOARD_HEIGHT = 100, ANIM_STRIPEb = ANIM_STRIPEb, WIDTH2b = math.floor(720/2), DISPL_WIDTH2b = DEFAULT_DISP_WIDTH, DISPL_HEIGHT2b = DISPL_HEIGHT2b, HEIGHT2b = DISPL_HEIGHT2b*ANIM_STRIPEb, WIDTH3 = math.floor(720/2), DISPL_HEIGHT3 = DISPL_HEIGHT3, HEIGHT3 = DISPL_HEIGHT3 * 2, COLOUR_PURPLE_DARK = hg.Color(42/255.0, 18/255.0, 33/255.0, 1.0), COLOUR_PURPLE = hg.Color(74/255.0, 34/255.0, 81/255.0, 1.0), COLOUR_PURPLE_LIGHT = hg.Color(95/255.0, 0/255.0, 75/255.0, 1.0), }
ITEM.name = "Request Device" ITEM.model = Model("models/gibs/shield_scanner_gib1.mdl") ITEM.description = "A box with rounded corners, housing two buttons." ITEM.price = 20
----------------------------------------------------------------------------------------- -- -- view1.lua -- ----------------------------------------------------------------------------------------- local composer = require( "composer" ) local widget = require( "widget" ) widget.setTheme( "widget_theme_android_holo_dark" ) local scene = composer.newScene() function scene:create( event ) local sceneGroup = self.view --composer.gotoScene( "scene.nfp" ) end function scene:key(event) if ( event.keyName == "back" ) or ("b"==event.keyName) then -- handle the back key press however you choose composer.gotoScene("scene.menu", {effect = "crossFade", time = 500}) return true end end function scene:show( event ) local sceneGroup = self.view local phase = event.phase if phase == "will" then elseif phase == "did" then -- Called when the scene is now on screen -- INSERT code here to make the scene come alive -- e.g. start timers, begin animation, play audio, etc. end end function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if event.phase == "will" then -- -- INSERT code here to pause the scene -- e.g. stop timers, stop animation, unload sounds, etc.) elseif phase == "did" then composer.removeScene("scene.nfp-menu", true) end end function scene:destroy( event ) local sceneG = self.view -- Called prior to the removal of scene's "view" (sceneGroup) -- INSERT code here to cleanup the scene -- e.g. remove display objects, remove touch listeners, save state, etc. end -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) Runtime:addEventListener( "key", scene ) ----------------------------------------------------------------------------------------- return scene
#!/bin/sh _=[[ . "${0%/*}/regress.sh" exec runlua -r5.2 "$0" "$@" ]] local unix = require"unix" local regress = require"regress".export".*" local rfd, wfd = check(unix.socketpair(unix.AF_UNIX, unix.SOCK_DGRAM)) local msg = "hello world" check(unix.write(wfd, msg)) local rmsg = check(unix.read(rfd, #msg)) check(msg == rmsg, string.format("expected '%s', got '%s'", msg, rmsg or "?")) say"OK"
local checkbox = { x = 1, y = 1, backColour = colours.lightGrey, foreColour = colours.black, char = "x", selected = false, group = "_MAIN", visible = true, label = "A Checkbox", type = "checkbox", automl = "", automt = "", autox = "", autoy = "", wrap = "left", marginleft = 0, margintop = 0, } checkbox.__index = checkbox function checkbox:getPercentages() if type(self.marginleft) == "string" then self.marginleft = cobalt.getPercentage( self.marginleft ) self.automl = self.marginleft end if type(self.margintop) == "string" then self.margintop = cobalt.getPercentage( self.margintop ) self.automt = self.margintop end if type(self.x) == "string" then self.x = cobalt.getPercentage( self.x ) self.autox = self.x end if type(self.y) == "string" then self.y = cobalt.getPercentage( self.y ) self.autoy = self.y end end function checkbox.new( data, parent ) data = data or { } if data.style then local t = data.style for k, v in pairs( t ) do if not data[k] then data[k] = v end end data.style = nil end local self = setmetatable(data,checkbox) if not self.val then self.val = self.label end self.w = #self.label + 2 self.parent = parent self:getPercentages() self:resize() self.state = data.state or parent.state table.insert( parent.children, self ) return self end function checkbox:setMargins( t, l ) if t then self.margintop = t or self.margintop if type(t) == "string" then self:getPercentages() else self.automt = "none" end end if l then self.marginleft = l or self.marginleft if type(l) == "string" then self:getPercentages() else self.automl = "none" end end self:resize() end function checkbox:resize() if type( self.automl ) == "number" then self.marginleft = math.floor( self.parent.w * self.automl ) end if type( self.automt ) == "number" then self.margintop = math.floor( self.parent.h * self.automt ) end if self.autox and type( self.autox ) == "number" then self.x = math.ceil( self.parent.w * self.autox ) end if self.autoy and type( self.autoy ) == "number" then self.y = math.ceil( self.parent.h * self.autoy ) end end function checkbox:getAbsX() return self.x + self.parent:getAbsX() - 1 + self.marginleft end function checkbox:getAbsY() return self.y + self.parent:getAbsY() - 1 + self.margintop end function checkbox:draw() self.w = #self.label + 2 if self.wrap == "center" then self.x = math.ceil( self.parent.w/2 - self.w/2 ) + self.marginleft end if self.state == cobalt.state or self.state == "_ALL" and self.visible then local char = " " if self.selected then char = self.char end self.parent.surf:drawPixel( math.ceil(self.x + self.marginleft), math.ceil(self.y + self.margintop), char, self.backColour, self.foreColour ) self.parent.surf:drawText( math.ceil(self.x+2 + self.marginleft), math.ceil(self.y+ self.margintop), self.label, nil, self.foreColour ) end end function checkbox:mousepressed( x, y, button ) if self.state == cobalt.state or self.state == "_ALL" and self.visible then if button == 1 and x >= self:getAbsX() and x <= self:getAbsX() + self.w and y == self:getAbsY() then end else self.selected = false end end function checkbox:mousereleased( x, y, button ) if self.state == cobalt.state or self.state == "_ALL" and self.visible then if button == 1 and x == self:getAbsX() and y == self:getAbsY() then self.selected = not self.selected end else self.selected = false end end return checkbox
--- === hs.plist === --- --- Read and write Property List files local USERDATA_TAG = "hs.plist" local module = require(USERDATA_TAG..".internal") -- Return Module Object -------------------------------------------------- return module
----------------------------------------------------------------------------------------------------------------------------------------- -- VRP ----------------------------------------------------------------------------------------------------------------------------------------- local Tunnel = module("vrp","lib/Tunnel") local Proxy = module("vrp","lib/Proxy") local Tools = module("vrp","lib/Tools") vRP = Proxy.getInterface("vRP") vRPclient = Tunnel.getInterface("vRP") ----------------------------------------------------------------------------------------------------------------------------------------- -- CONEXÃO ----------------------------------------------------------------------------------------------------------------------------------------- src = {} Tunnel.bindInterface("vrp_garages",src) vCLIENT = Tunnel.getInterface("vrp_garages") local idgens = Tools.newIDGenerator() ----------------------------------------------------------------------------------------------------------------------------------------- -- WEBHOOK ----------------------------------------------------------------------------------------------------------------------------------------- local webhookvehs = "https://discordapp.com/api/webhooks/624333204005847080/SIzBZGgCZ0EO3-g6QCcQRRvuxflHuKzJyTorJ7xuDCLYhdc1j5Y0hxpVRg7PSs7jvkGQ" local webhookdesmanche = "https://discordapp.com/api/webhooks/596294964791476244/hIooSmNC775KlicOzIoaJh1jdh7XQKSL1dFy4xSqV2qdkwXCVjNnsxaAimf8-9GL02xi" function SendWebhookMessage(webhook,message) if webhook ~= nil and webhook ~= "" then PerformHttpRequest(webhook, function(err, text, headers) end, 'POST', json.encode({content = message}), { ['Content-Type'] = 'application/json' }) end end ----------------------------------------------------------------------------------------------------------------------------------------- -- VARIAVEIS ----------------------------------------------------------------------------------------------------------------------------------------- local police = {} local vehlist = {} local trydoors = {} trydoors["CORREDOR"] = true trydoors["CREATIVE"] = true ----------------------------------------------------------------------------------------------------------------------------------------- -- RETURNVEHICLESEVERYONE ----------------------------------------------------------------------------------------------------------------------------------------- function src.returnVehicleEveryone(placa) return trydoors[placa] end ----------------------------------------------------------------------------------------------------------------------------------------- -- SETPLATEEVERYONE ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("setPlateEveryone") AddEventHandler("setPlateEveryone",function(plate) trydoors[plate] = true vCLIENT.syncTrydoors(-1,trydoors) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- PLAYERSPAWN ----------------------------------------------------------------------------------------------------------------------------------------- AddEventHandler("vRP:playerSpawn",function(user_id,source) vCLIENT.syncTrydoors(source,trydoors) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- GARAGES ----------------------------------------------------------------------------------------------------------------------------------------- local garages = { [1] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [2] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [3] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [4] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [5] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [6] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [7] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [8] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [9] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [10] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [11] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [12] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [13] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [14] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [15] = { ['name'] = "Garagem", ['payment'] = true, ['public'] = true }, [16] = { ['name'] = "Policia", ['payment'] = false, ['perm'] = "policia.permissao" }, [17] = { ['name'] = "Policia", ['payment'] = false, ['perm'] = "policia.permissao" }, [18] = { ['name'] = "Policia", ['payment'] = false, ['perm'] = "policia.permissao" }, [19] = { ['name'] = "SID", ['payment'] = false, ['perm'] = "policia.permissao" }, [20] = { ['name'] = "PoliciaB", ['payment'] = false, ['perm'] = "policia.permissao" }, [21] = { ['name'] = "PoliciaB", ['payment'] = false, ['perm'] = "policia.permissao" }, [22] = { ['name'] = "PoliciaH", ['payment'] = false, ['perm'] = "policia.permissao" }, [23] = { ['name'] = "PoliciaH", ['payment'] = false, ['perm'] = "policia.permissao" }, [24] = { ['name'] = "PoliciaA", ['payment'] = false, ['perm'] = "policia.permissao" }, [25] = { ['name'] = "Paramedico", ['payment'] = false, ['perm'] = "paramedico.permissao" }, [26] = { ['name'] = "Paramedico", ['payment'] = false, ['perm'] = "paramedico.permissao" }, [27] = { ['name'] = "Paramedico", ['payment'] = false, ['perm'] = "paramedico.permissao" }, [28] = { ['name'] = "ParamedicoH", ['payment'] = false, ['perm'] = "paramedico.permissao" }, [29] = { ['name'] = "ParamedicoH", ['payment'] = false, ['perm'] = "paramedico.permissao" }, [30] = { ['name'] = "Mecanico", ['payment'] = false, ['perm'] = "mecanico.permissao" }, [31] = { ['name'] = "Mecanico", ['payment'] = false, ['perm'] = "mecanico.permissao" }, [32] = { ['name'] = "Taxista", ['payment'] = false, ['perm'] = "taxista.permissao" }, [33] = { ['name'] = "Taxista", ['payment'] = false, ['perm'] = "taxista.permissao" }, [34] = { ['name'] = "Motorista", ['payment'] = false, ['perm'] = "livre" }, [35] = { ['name'] = "Motorista", ['payment'] = false, ['perm'] = "livre" }, [36] = { ['name'] = "Carteiro", ['payment'] = false, ['perm'] = "livre" }, [37] = { ['name'] = "Carteiro", ['payment'] = false, ['perm'] = "livre" }, [38] = { ['name'] = "Lixeiro", ['payment'] = false, ['perm'] = "livre" }, [39] = { ['name'] = "Minerador", ['payment'] = false, ['perm'] = "livre" }, [40] = { ['name'] = "Lenhador", ['payment'] = false, ['perm'] = "livre" }, [41] = { ['name'] = "Leiteiro", ['payment'] = false, ['perm'] = "livre" }, [42] = { ['name'] = "Caminhoneiro", ['payment'] = false, ['perm'] = "livre" }, --[43] = { ['name'] = "Cargas", ['payment'] = false, ['perm'] = "livre" }, [44] = { ['name'] = "Juiz", ['payment'] = true, ['perm'] = "juiz.permissao" }, [45] = { ['name'] = "Advogado", ['payment'] = true, ['perm'] = "advogado.permissao" }, [46] = { ['name'] = "Embarcações", ['payment'] = false, ['perm'] = "livre" }, [47] = { ['name'] = "Embarcações", ['payment'] = false, ['perm'] = "livre" }, [48] = { ['name'] = "Embarcações", ['payment'] = false, ['perm'] = "livre" }, [49] = { ['name'] = "Embarcações", ['payment'] = false, ['perm'] = "livre" }, [50] = { ['name'] = "Serpentes", ['payment'] = false, ['perm'] = "serpentes.permissao" }, --[51] = { ['name'] = "SerpentesBarcos", ['payment'] = true, ['perm'] = "serpentes.permissao" }, [52] = { ['name'] = "Motoclub", ['payment'] = false, ['perm'] = "motoclub.permissao" }, [53] = { ['name'] = "Roxos", ['payment'] = false, ['perm'] = "PurplePermission" }, [54] = { ['name'] = "Amarelos", ['payment'] = false, ['perm'] = "YellowPermission" }, [55] = { ['name'] = "Vermelhos", ['payment'] = false, ['perm'] = "RedPermission" }, --[56] = { ['name'] = "Marabuntas", ['payment'] = true, ['perm'] = "marabuntas.permissao" }, [57] = { ['name'] = "Mafia", ['payment'] = false, ['perm'] = "mafia.permissao" }, [58] = { ['name'] = "Yakuza", ['payment'] = false, ['perm'] = "yakuza.permissao" }, --[59] = { ['name'] = "Corleone", ['payment'] = true, ['perm'] = "corleone.permissao" }, --[60] = { ['name'] = "Cosanostra", ['payment'] = true, ['perm'] = "cosanostra.permissao" }, [61] = { ['name'] = "Concessionaria", ['payment'] = false, ['public'] = true }, [62] = { ['name'] = "Concessionaria", ['payment'] = false, ['perm'] = "conce.permissao" }, [63] = { ['name'] = "Concessionaria", ['payment'] = false, ['perm'] = "conce.permissao" }, [64] = { ['name'] = "Bicicletario", ['payment'] = true, ['perm'] = "livre" }, [65] = { ['name'] = "Bicicletario", ['payment'] = true, ['perm'] = "livre" }, [66] = { ['name'] = "Colheita", ['payment'] = false, ['perm'] = "livre" }, [67] = { ['name'] = "WarArena", ['payment'] = false, ['perm'] = "livre" }, [69] = { ['name'] = "Transportadora", ['payment'] = false, ['perm'] = "transportadora.permissao" }, [70] = { ['name'] = "TransportadoraA", ['payment'] = false, ['perm'] = "transportadora.permissao" }, [71] = { ['name'] = "FedexAir", ['payment'] = false, ['perm'] = "fedex.permissao" }, [72] = { ['name'] = "Concessionaria", ['payment'] = false, ['perm'] = "platina.permissao" }, ----------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------FORTHILLS----------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- [145] = { ['name'] = "FH01", ['payment'] = false, ['public'] = false }, [148] = { ['name'] = "FH04", ['payment'] = false, ['public'] = false }, [150] = { ['name'] = "FH06", ['payment'] = false, ['public'] = false }, [152] = { ['name'] = "FH08", ['payment'] = false, ['public'] = false }, [155] = { ['name'] = "FH11", ['payment'] = false, ['public'] = false }, [159] = { ['name'] = "FH15", ['payment'] = false, ['public'] = false }, [163] = { ['name'] = "FH19", ['payment'] = false, ['public'] = false }, [167] = { ['name'] = "FH23", ['payment'] = false, ['public'] = false }, [168] = { ['name'] = "FH24", ['payment'] = false, ['public'] = false }, [170] = { ['name'] = "FH26", ['payment'] = false, ['public'] = false }, [173] = { ['name'] = "FH29", ['payment'] = false, ['public'] = false }, [175] = { ['name'] = "FH31", ['payment'] = false, ['public'] = false }, [176] = { ['name'] = "FH32", ['payment'] = false, ['public'] = false }, [179] = { ['name'] = "FH35", ['payment'] = false, ['public'] = false }, [189] = { ['name'] = "FH45", ['payment'] = false, ['public'] = false }, [192] = { ['name'] = "FH48", ['payment'] = false, ['public'] = false }, [193] = { ['name'] = "FH49", ['payment'] = false, ['public'] = false }, [196] = { ['name'] = "FH52", ['payment'] = false, ['public'] = false }, [198] = { ['name'] = "FH54", ['payment'] = false, ['public'] = false }, [199] = { ['name'] = "FH55", ['payment'] = false, ['public'] = false }, [200] = { ['name'] = "FH56", ['payment'] = false, ['public'] = false }, [202] = { ['name'] = "FH58", ['payment'] = false, ['public'] = false }, [203] = { ['name'] = "FH59", ['payment'] = false, ['public'] = false }, [212] = { ['name'] = "FH68", ['payment'] = false, ['public'] = false }, [225] = { ['name'] = "FH81", ['payment'] = false, ['public'] = false }, [235] = { ['name'] = "FH91", ['payment'] = false, ['public'] = false }, [236] = { ['name'] = "FH92", ['payment'] = false, ['public'] = false }, [237] = { ['name'] = "FH93", ['payment'] = false, ['public'] = false }, [238] = { ['name'] = "FH94", ['payment'] = false, ['public'] = false }, [240] = { ['name'] = "FH96", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------LUXURY-------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- [245] = { ['name'] = "LX01", ['payment'] = false, ['public'] = false }, [246] = { ['name'] = "LX02", ['payment'] = false, ['public'] = false }, [247] = { ['name'] = "LX03", ['payment'] = false, ['public'] = false }, [248] = { ['name'] = "LX04", ['payment'] = false, ['public'] = false }, [249] = { ['name'] = "LX05", ['payment'] = false, ['public'] = false }, [250] = { ['name'] = "LX06", ['payment'] = false, ['public'] = false }, [251] = { ['name'] = "LX07", ['payment'] = false, ['public'] = false }, [252] = { ['name'] = "LX08", ['payment'] = false, ['public'] = false }, [253] = { ['name'] = "LX09", ['payment'] = false, ['public'] = false }, [254] = { ['name'] = "LX10", ['payment'] = false, ['public'] = false }, [255] = { ['name'] = "LX11", ['payment'] = false, ['public'] = false }, [256] = { ['name'] = "LX12", ['payment'] = false, ['public'] = false }, [257] = { ['name'] = "LX13", ['payment'] = false, ['public'] = false }, [258] = { ['name'] = "LX14", ['payment'] = false, ['public'] = false }, [259] = { ['name'] = "LX15", ['payment'] = false, ['public'] = false }, [260] = { ['name'] = "LX16", ['payment'] = false, ['public'] = false }, [261] = { ['name'] = "LX17", ['payment'] = false, ['public'] = false }, [262] = { ['name'] = "LX18", ['payment'] = false, ['public'] = false }, [263] = { ['name'] = "LX19", ['payment'] = false, ['public'] = false }, [264] = { ['name'] = "LX20", ['payment'] = false, ['public'] = false }, [265] = { ['name'] = "LX21", ['payment'] = false, ['public'] = false }, [266] = { ['name'] = "LX22", ['payment'] = false, ['public'] = false }, [267] = { ['name'] = "LX23", ['payment'] = false, ['public'] = false }, [268] = { ['name'] = "LX24", ['payment'] = false, ['public'] = false }, [269] = { ['name'] = "LX25", ['payment'] = false, ['public'] = false }, [270] = { ['name'] = "LX26", ['payment'] = false, ['public'] = false }, [271] = { ['name'] = "LX27", ['payment'] = false, ['public'] = false }, [272] = { ['name'] = "LX28", ['payment'] = false, ['public'] = false }, [273] = { ['name'] = "LX29", ['payment'] = false, ['public'] = false }, [276] = { ['name'] = "LX32", ['payment'] = false, ['public'] = false }, [278] = { ['name'] = "LX34", ['payment'] = false, ['public'] = false }, [279] = { ['name'] = "LX35", ['payment'] = false, ['public'] = false }, [280] = { ['name'] = "LX36", ['payment'] = false, ['public'] = false }, [281] = { ['name'] = "LX37", ['payment'] = false, ['public'] = false }, [282] = { ['name'] = "LX38", ['payment'] = false, ['public'] = false }, [283] = { ['name'] = "LX39", ['payment'] = false, ['public'] = false }, [284] = { ['name'] = "LX40", ['payment'] = false, ['public'] = false }, [285] = { ['name'] = "LX41", ['payment'] = false, ['public'] = false }, [286] = { ['name'] = "LX42", ['payment'] = false, ['public'] = false }, [287] = { ['name'] = "LX43", ['payment'] = false, ['public'] = false }, [288] = { ['name'] = "LX44", ['payment'] = false, ['public'] = false }, [289] = { ['name'] = "LX45", ['payment'] = false, ['public'] = false }, [290] = { ['name'] = "LX46", ['payment'] = false, ['public'] = false }, [291] = { ['name'] = "LX47", ['payment'] = false, ['public'] = false }, [292] = { ['name'] = "LX48", ['payment'] = false, ['public'] = false }, [294] = { ['name'] = "LX50", ['payment'] = false, ['public'] = false }, [295] = { ['name'] = "LX51", ['payment'] = false, ['public'] = false }, [296] = { ['name'] = "LX52", ['payment'] = false, ['public'] = false }, [297] = { ['name'] = "LX53", ['payment'] = false, ['public'] = false }, [298] = { ['name'] = "LX54", ['payment'] = false, ['public'] = false }, [299] = { ['name'] = "LX55", ['payment'] = false, ['public'] = false }, [300] = { ['name'] = "LX56", ['payment'] = false, ['public'] = false }, [302] = { ['name'] = "LX58", ['payment'] = false, ['public'] = false }, [303] = { ['name'] = "LX59", ['payment'] = false, ['public'] = false }, [304] = { ['name'] = "LX60", ['payment'] = false, ['public'] = false }, [305] = { ['name'] = "LX61", ['payment'] = false, ['public'] = false }, [306] = { ['name'] = "LX62", ['payment'] = false, ['public'] = false }, [307] = { ['name'] = "LX63", ['payment'] = false, ['public'] = false }, [308] = { ['name'] = "LX64", ['payment'] = false, ['public'] = false }, [309] = { ['name'] = "LX65", ['payment'] = false, ['public'] = false }, [310] = { ['name'] = "LX66", ['payment'] = false, ['public'] = false }, [311] = { ['name'] = "LX67", ['payment'] = false, ['public'] = false }, [312] = { ['name'] = "LX68", ['payment'] = false, ['public'] = false }, [313] = { ['name'] = "LX69", ['payment'] = false, ['public'] = false }, [314] = { ['name'] = "LX70", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------SAMIR------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- [315] = { ['name'] = "LS01", ['payment'] = false, ['public'] = false }, [316] = { ['name'] = "LS02", ['payment'] = false, ['public'] = false }, [317] = { ['name'] = "LS03", ['payment'] = false, ['public'] = false }, [318] = { ['name'] = "LS04", ['payment'] = false, ['public'] = false }, [319] = { ['name'] = "LS05", ['payment'] = false, ['public'] = false }, [320] = { ['name'] = "LS06", ['payment'] = false, ['public'] = false }, [321] = { ['name'] = "LS07", ['payment'] = false, ['public'] = false }, [322] = { ['name'] = "LS08", ['payment'] = false, ['public'] = false }, [323] = { ['name'] = "LS09", ['payment'] = false, ['public'] = false }, [324] = { ['name'] = "LS10", ['payment'] = false, ['public'] = false }, [325] = { ['name'] = "LS11", ['payment'] = false, ['public'] = false }, [326] = { ['name'] = "LS12", ['payment'] = false, ['public'] = false }, [327] = { ['name'] = "LS13", ['payment'] = false, ['public'] = false }, [328] = { ['name'] = "LS14", ['payment'] = false, ['public'] = false }, [329] = { ['name'] = "LS15", ['payment'] = false, ['public'] = false }, [330] = { ['name'] = "LS16", ['payment'] = false, ['public'] = false }, [331] = { ['name'] = "LS17", ['payment'] = false, ['public'] = false }, [332] = { ['name'] = "LS18", ['payment'] = false, ['public'] = false }, [333] = { ['name'] = "LS19", ['payment'] = false, ['public'] = false }, [334] = { ['name'] = "LS20", ['payment'] = false, ['public'] = false }, [335] = { ['name'] = "LS21", ['payment'] = false, ['public'] = false }, [336] = { ['name'] = "LS22", ['payment'] = false, ['public'] = false }, [337] = { ['name'] = "LS23", ['payment'] = false, ['public'] = false }, [338] = { ['name'] = "LS24", ['payment'] = false, ['public'] = false }, [339] = { ['name'] = "LS25", ['payment'] = false, ['public'] = false }, [340] = { ['name'] = "LS26", ['payment'] = false, ['public'] = false }, [341] = { ['name'] = "LS27", ['payment'] = false, ['public'] = false }, [342] = { ['name'] = "LS28", ['payment'] = false, ['public'] = false }, [343] = { ['name'] = "LS29", ['payment'] = false, ['public'] = false }, [344] = { ['name'] = "LS30", ['payment'] = false, ['public'] = false }, [345] = { ['name'] = "LS31", ['payment'] = false, ['public'] = false }, [346] = { ['name'] = "LS32", ['payment'] = false, ['public'] = false }, [347] = { ['name'] = "LS33", ['payment'] = false, ['public'] = false }, [348] = { ['name'] = "LS34", ['payment'] = false, ['public'] = false }, [349] = { ['name'] = "LS35", ['payment'] = false, ['public'] = false }, [350] = { ['name'] = "LS36", ['payment'] = false, ['public'] = false }, [351] = { ['name'] = "LS37", ['payment'] = false, ['public'] = false }, [352] = { ['name'] = "LS38", ['payment'] = false, ['public'] = false }, [353] = { ['name'] = "LS39", ['payment'] = false, ['public'] = false }, [354] = { ['name'] = "LS40", ['payment'] = false, ['public'] = false }, [355] = { ['name'] = "LS41", ['payment'] = false, ['public'] = false }, [356] = { ['name'] = "LS42", ['payment'] = false, ['public'] = false }, [357] = { ['name'] = "LS43", ['payment'] = false, ['public'] = false }, [358] = { ['name'] = "LS44", ['payment'] = false, ['public'] = false }, [359] = { ['name'] = "LS45", ['payment'] = false, ['public'] = false }, [360] = { ['name'] = "LS46", ['payment'] = false, ['public'] = false }, [361] = { ['name'] = "LS47", ['payment'] = false, ['public'] = false }, [362] = { ['name'] = "LS48", ['payment'] = false, ['public'] = false }, [363] = { ['name'] = "LS49", ['payment'] = false, ['public'] = false }, [364] = { ['name'] = "LS50", ['payment'] = false, ['public'] = false }, [365] = { ['name'] = "LS51", ['payment'] = false, ['public'] = false }, [366] = { ['name'] = "LS52", ['payment'] = false, ['public'] = false }, [367] = { ['name'] = "LS53", ['payment'] = false, ['public'] = false }, [368] = { ['name'] = "LS54", ['payment'] = false, ['public'] = false }, [369] = { ['name'] = "LS55", ['payment'] = false, ['public'] = false }, [370] = { ['name'] = "LS56", ['payment'] = false, ['public'] = false }, [371] = { ['name'] = "LS57", ['payment'] = false, ['public'] = false }, [372] = { ['name'] = "LS58", ['payment'] = false, ['public'] = false }, [373] = { ['name'] = "LS59", ['payment'] = false, ['public'] = false }, [374] = { ['name'] = "LS60", ['payment'] = false, ['public'] = false }, [375] = { ['name'] = "LS61", ['payment'] = false, ['public'] = false }, [376] = { ['name'] = "LS62", ['payment'] = false, ['public'] = false }, [377] = { ['name'] = "LS63", ['payment'] = false, ['public'] = false }, [378] = { ['name'] = "LS64", ['payment'] = false, ['public'] = false }, [379] = { ['name'] = "LS65", ['payment'] = false, ['public'] = false }, [380] = { ['name'] = "LS66", ['payment'] = false, ['public'] = false }, [381] = { ['name'] = "LS67", ['payment'] = false, ['public'] = false }, [382] = { ['name'] = "LS68", ['payment'] = false, ['public'] = false }, [383] = { ['name'] = "LS69", ['payment'] = false, ['public'] = false }, [384] = { ['name'] = "LS70", ['payment'] = false, ['public'] = false }, [385] = { ['name'] = "LS71", ['payment'] = false, ['public'] = false }, [386] = { ['name'] = "LS72", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------KRONDORS------------------------------------------------------------------------ ----------------------------------------------------------------------------------------------------------------------------------------- [387] = { ['name'] = "KR01", ['payment'] = false, ['public'] = false }, [388] = { ['name'] = "KR02", ['payment'] = false, ['public'] = false }, [389] = { ['name'] = "KR03", ['payment'] = false, ['public'] = false }, [390] = { ['name'] = "KR04", ['payment'] = false, ['public'] = false }, [391] = { ['name'] = "KR05", ['payment'] = false, ['public'] = false }, [392] = { ['name'] = "KR06", ['payment'] = false, ['public'] = false }, [393] = { ['name'] = "KR07", ['payment'] = false, ['public'] = false }, [394] = { ['name'] = "KR08", ['payment'] = false, ['public'] = false }, [395] = { ['name'] = "KR09", ['payment'] = false, ['public'] = false }, [396] = { ['name'] = "KR10", ['payment'] = false, ['public'] = false }, [397] = { ['name'] = "KR11", ['payment'] = false, ['public'] = false }, [398] = { ['name'] = "KR12", ['payment'] = false, ['public'] = false }, [399] = { ['name'] = "KR13", ['payment'] = false, ['public'] = false }, [400] = { ['name'] = "KR14", ['payment'] = false, ['public'] = false }, [401] = { ['name'] = "KR15", ['payment'] = false, ['public'] = false }, [402] = { ['name'] = "KR16", ['payment'] = false, ['public'] = false }, [403] = { ['name'] = "KR17", ['payment'] = false, ['public'] = false }, [404] = { ['name'] = "KR18", ['payment'] = false, ['public'] = false }, [405] = { ['name'] = "KR19", ['payment'] = false, ['public'] = false }, [406] = { ['name'] = "KR20", ['payment'] = false, ['public'] = false }, [407] = { ['name'] = "KR21", ['payment'] = false, ['public'] = false }, [408] = { ['name'] = "KR22", ['payment'] = false, ['public'] = false }, [409] = { ['name'] = "KR23", ['payment'] = false, ['public'] = false }, [410] = { ['name'] = "KR24", ['payment'] = false, ['public'] = false }, [411] = { ['name'] = "KR25", ['payment'] = false, ['public'] = false }, [412] = { ['name'] = "KR26", ['payment'] = false, ['public'] = false }, [413] = { ['name'] = "KR27", ['payment'] = false, ['public'] = false }, [414] = { ['name'] = "KR28", ['payment'] = false, ['public'] = false }, [415] = { ['name'] = "KR29", ['payment'] = false, ['public'] = false }, [416] = { ['name'] = "KR30", ['payment'] = false, ['public'] = false }, [417] = { ['name'] = "KR31", ['payment'] = false, ['public'] = false }, [418] = { ['name'] = "KR32", ['payment'] = false, ['public'] = false }, [419] = { ['name'] = "KR33", ['payment'] = false, ['public'] = false }, [420] = { ['name'] = "KR34", ['payment'] = false, ['public'] = false }, [421] = { ['name'] = "KR35", ['payment'] = false, ['public'] = false }, [422] = { ['name'] = "KR36", ['payment'] = false, ['public'] = false }, [423] = { ['name'] = "KR37", ['payment'] = false, ['public'] = false }, [424] = { ['name'] = "KR38", ['payment'] = false, ['public'] = false }, [425] = { ['name'] = "KR39", ['payment'] = false, ['public'] = false }, [426] = { ['name'] = "KR40", ['payment'] = false, ['public'] = false }, [427] = { ['name'] = "KR41", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------LOSVAGOS------------------------------------------------------------------------ ----------------------------------------------------------------------------------------------------------------------------------------- [428] = { ['name'] = "LV01", ['payment'] = false, ['public'] = false }, [429] = { ['name'] = "LV02", ['payment'] = false, ['public'] = false }, [430] = { ['name'] = "LV03", ['payment'] = false, ['public'] = false }, [431] = { ['name'] = "LV04", ['payment'] = false, ['public'] = false }, [432] = { ['name'] = "LV05", ['payment'] = false, ['public'] = false }, [433] = { ['name'] = "LV06", ['payment'] = false, ['public'] = false }, [434] = { ['name'] = "LV07", ['payment'] = false, ['public'] = false }, [435] = { ['name'] = "LV08", ['payment'] = false, ['public'] = false }, [436] = { ['name'] = "LV09", ['payment'] = false, ['public'] = false }, [437] = { ['name'] = "LV10", ['payment'] = false, ['public'] = false }, [438] = { ['name'] = "LV11", ['payment'] = false, ['public'] = false }, [439] = { ['name'] = "LV12", ['payment'] = false, ['public'] = false }, [440] = { ['name'] = "LV13", ['payment'] = false, ['public'] = false }, [441] = { ['name'] = "LV14", ['payment'] = false, ['public'] = false }, [442] = { ['name'] = "LV15", ['payment'] = false, ['public'] = false }, [443] = { ['name'] = "LV16", ['payment'] = false, ['public'] = false }, [444] = { ['name'] = "LV17", ['payment'] = false, ['public'] = false }, [445] = { ['name'] = "LV18", ['payment'] = false, ['public'] = false }, [446] = { ['name'] = "LV19", ['payment'] = false, ['public'] = false }, [447] = { ['name'] = "LV20", ['payment'] = false, ['public'] = false }, [448] = { ['name'] = "LV21", ['payment'] = false, ['public'] = false }, [449] = { ['name'] = "LV22", ['payment'] = false, ['public'] = false }, [450] = { ['name'] = "LV23", ['payment'] = false, ['public'] = false }, [451] = { ['name'] = "LV24", ['payment'] = false, ['public'] = false }, [452] = { ['name'] = "LV25", ['payment'] = false, ['public'] = false }, [453] = { ['name'] = "LV26", ['payment'] = false, ['public'] = false }, [454] = { ['name'] = "LV27", ['payment'] = false, ['public'] = false }, [455] = { ['name'] = "LV28", ['payment'] = false, ['public'] = false }, [456] = { ['name'] = "LV29", ['payment'] = false, ['public'] = false }, [457] = { ['name'] = "LV30", ['payment'] = false, ['public'] = false }, [458] = { ['name'] = "LV31", ['payment'] = false, ['public'] = false }, [459] = { ['name'] = "LV32", ['payment'] = false, ['public'] = false }, [460] = { ['name'] = "LV33", ['payment'] = false, ['public'] = false }, [461] = { ['name'] = "LV34", ['payment'] = false, ['public'] = false }, [462] = { ['name'] = "LV35", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------PALETOBAY------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- [463] = { ['name'] = "PB01", ['payment'] = false, ['public'] = false }, [464] = { ['name'] = "PB02", ['payment'] = false, ['public'] = false }, [465] = { ['name'] = "PB03", ['payment'] = false, ['public'] = false }, [466] = { ['name'] = "PB04", ['payment'] = false, ['public'] = false }, [467] = { ['name'] = "PB05", ['payment'] = false, ['public'] = false }, [468] = { ['name'] = "PB06", ['payment'] = false, ['public'] = false }, [469] = { ['name'] = "PB07", ['payment'] = false, ['public'] = false }, [470] = { ['name'] = "PB08", ['payment'] = false, ['public'] = false }, [471] = { ['name'] = "PB09", ['payment'] = false, ['public'] = false }, [472] = { ['name'] = "PB10", ['payment'] = false, ['public'] = false }, [473] = { ['name'] = "PB11", ['payment'] = false, ['public'] = false }, [474] = { ['name'] = "PB12", ['payment'] = false, ['public'] = false }, [475] = { ['name'] = "PB13", ['payment'] = false, ['public'] = false }, [476] = { ['name'] = "PB14", ['payment'] = false, ['public'] = false }, [477] = { ['name'] = "PB15", ['payment'] = false, ['public'] = false }, [478] = { ['name'] = "PB16", ['payment'] = false, ['public'] = false }, [479] = { ['name'] = "PB17", ['payment'] = false, ['public'] = false }, [480] = { ['name'] = "PB18", ['payment'] = false, ['public'] = false }, [481] = { ['name'] = "PB19", ['payment'] = false, ['public'] = false }, [482] = { ['name'] = "PB20", ['payment'] = false, ['public'] = false }, [483] = { ['name'] = "PB21", ['payment'] = false, ['public'] = false }, [484] = { ['name'] = "PB22", ['payment'] = false, ['public'] = false }, [485] = { ['name'] = "PB23", ['payment'] = false, ['public'] = false }, [486] = { ['name'] = "PB24", ['payment'] = false, ['public'] = false }, [487] = { ['name'] = "PB25", ['payment'] = false, ['public'] = false }, [488] = { ['name'] = "PB26", ['payment'] = false, ['public'] = false }, [489] = { ['name'] = "PB27", ['payment'] = false, ['public'] = false }, [490] = { ['name'] = "PB28", ['payment'] = false, ['public'] = false }, [491] = { ['name'] = "PB29", ['payment'] = false, ['public'] = false }, [492] = { ['name'] = "PB30", ['payment'] = false, ['public'] = false }, [493] = { ['name'] = "PB31", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- -----------------------------------------------------MANSAO------------------------------------------------------------------------------ ----------------------------------------------------------------------------------------------------------------------------------------- [600] = { ['name'] = "MS01", ['payment'] = false, ['public'] = false }, [601] = { ['name'] = "MS02", ['payment'] = false, ['public'] = false }, [602] = { ['name'] = "MS03", ['payment'] = false, ['public'] = false }, [603] = { ['name'] = "MS04", ['payment'] = false, ['public'] = false }, [604] = { ['name'] = "MS05", ['payment'] = false, ['public'] = false }, [605] = { ['name'] = "MS06", ['payment'] = false, ['public'] = false }, [606] = { ['name'] = "MS07", ['payment'] = false, ['public'] = false }, [607] = { ['name'] = "MS08", ['payment'] = false, ['public'] = false }, [608] = { ['name'] = "MS09", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------SANDYSHORE------------------------------------------------------------------ ----------------------------------------------------------------------------------------------------------------------------------------- [609] = { ['name'] = "SS01", ['payment'] = false, ['public'] = false }, ----------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------TREVORHOUSE----------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- [610] = { ['name'] = "TR01", ['payment'] = false, ['public'] = false }, } ----------------------------------------------------------------------------------------------------------------------------------------- -- GARAGENS ----------------------------------------------------------------------------------------------------------------------------------------- local workgarage = { ["Policia"] = { "policiacharger2018", "policiachallenger2018", --"policiamustanggt", --"policiasilverado", "policiatahoe", --"policiaexplorer", "policiavictoria", "policiaimpala", "policiakawasaki", "policiaharley", "fbi2" }, ["SID"] = { "policiadurango", "policiacharger2018", "policiaschaftersid" }, ["PoliciaB"] = { "pbus" }, ["PoliciaH"] = { "policiaheli" }, ["PoliciaA"] = { "velum2", "policiaheli" }, ["Paramedico"] = { "paramedicoambu", "paramedicocharger2014", --"paramedicotahoe" }, ["ParamedicoH"] = { "paramedicoheli", "seasparrow" }, ["Mecanico"] = { "flatbed", "towtruck", "towtruck2" }, ["Taxista"] = { "dltaxi" }, ["Motorista"] = { "dlbus" }, ["Carteiro"] = { "dlfedexvan", "tribike3" }, ["Lixeiro"] = { "trash2" }, ["Minerador"] = { "tiptruck" }, ["Lenhador"] = { "ratloader" }, ["Leiteiro"] = { "youga2" }, ["Caminhoneiro"] = { "phantom", "packer" }, ["Juiz"] = { "baller6" }, ["Advogado"] = { "felon2" }, ["Bicicletario"] = { "scorcher", "tribike", "tribike2", "tribike3", "fixter", "cruiser", "bmx", --"snowmobile" }, ["Colheita"] = { "tractor2", "rebel" }, ["Embarcações"] = { "dinghy", "jetmax", "marquis", "seashark3", "speeder", "speeder2", "squalo", "suntrap", "toro", "toro2", "tropic", "tropic2", "predator" }, ["FedexAir"] = { "dlfedexcessna", "dlfedex737", "dlfedexdc10f" }, } ----------------------------------------------------------------------------------------------------------------------------------------- -- MYVEHICLES ----------------------------------------------------------------------------------------------------------------------------------------- function src.myVehicles(work) local source = source local user_id = vRP.getUserId(source) local myvehicles = {} local ipva = "" local status = "" if user_id then if workgarage[work] then for k,v in pairs(workgarage) do if k == work then for k2,v2 in pairs(v) do status = "<span class=\"green\">"..k.."</span>" ipva = "<span class=\"green\">Pago</span>" table.insert(myvehicles,{ name = v2, name2 = vRP.vehicleName(v2), engine = 100, body = 100, fuel = 100, status = status, ipva = ipva }) end end end return myvehicles else local vehicle = vRP.query("creative/get_vehicle",{ user_id = parseInt(user_id) }) local address = vRP.query("homes/get_homeuserid",{ user_id = parseInt(user_id) }) if #address > 0 then for k,v in pairs(address) do if v.home == work then for k2,v2 in pairs(vehicle) do if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.5)).."</span>" elseif vehicle[k2].detido == 1 then status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>" else status = "<span class=\"green\">Gratuita</span>" end if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then ipva = "<span class=\"red\">Atrasado</span>" else ipva = "<span class=\"green\">Pago</span>" end table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva }) end return myvehicles else for k2,v2 in pairs(vehicle) do if parseInt(os.time()) <= parseInt(vehicle[k2].time+24*60*60) then status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.5)).."</span>" elseif vehicle[k2].detido == 1 then status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.1)).."</span>" else status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k2].vehicle)*0.005)).."</span>" end if parseInt(os.time()) >= parseInt(vehicle[k2].ipva+24*15*60*60) then ipva = "<span class=\"red\">Atrasado</span>" else ipva = "<span class=\"green\">Pago</span>" end table.insert(myvehicles,{ name = vehicle[k2].vehicle, name2 = vRP.vehicleName(vehicle[k2].vehicle), engine = parseInt(vehicle[k2].engine*0.1), body = parseInt(vehicle[k2].body*0.1), fuel = parseInt(vehicle[k2].fuel), status = status, ipva = ipva }) end return myvehicles end end else for k,v in pairs(vehicle) do if parseInt(os.time()) <= parseInt(vehicle[k].time+24*60*60) then status = "<span class=\"red\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k].vehicle)*0.5)).."</span>" elseif vehicle[k].detido == 1 then status = "<span class=\"orange\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k].vehicle)*0.1)).."</span>" else status = "<span class=\"green\">$"..vRP.format(parseInt(vRP.vehiclePrice(vehicle[k].vehicle)*0.005)).."</span>" end if parseInt(os.time()) >= parseInt(vehicle[k].ipva+24*15*60*60) then ipva = "<span class=\"red\">Atrasado</span>" else ipva = "<span class=\"green\">Pago</span>" end table.insert(myvehicles,{ name = vehicle[k].vehicle, name2 = vRP.vehicleName(vehicle[k].vehicle), engine = parseInt(vehicle[k].engine*0.1), body = parseInt(vehicle[k].body*0.1), fuel = parseInt(vehicle[k].fuel), status = status, ipva = ipva }) end return myvehicles end end end end ----------------------------------------------------------------------------------------------------------------------------------------- -- SPAWNVEHICLES ----------------------------------------------------------------------------------------------------------------------------------------- function src.spawnVehicles(name,use) if name then local source = source local user_id = vRP.getUserId(source) if user_id then local identity = vRP.getUserIdentity(user_id) local value = vRP.getUData(parseInt(user_id),"vRP:multas") local multas = json.decode(value) or 0 if multas > 0 then TriggerClientEvent("Notify",source,"negado","Você tem multas pendentes.",10000) return end if not vCLIENT.returnVehicle(source,name) then local vehicle = vRP.query("creative/get_vehicles",{ user_id = parseInt(user_id), vehicle = name }) local tuning = vRP.getSData("custom:u"..user_id.."veh_"..name) or {} local custom = json.decode(tuning) or {} if vehicle[1] ~= nil then if parseInt(os.time()) <= parseInt(vehicle[1].time+24*60*60) then local ok = vRP.request(source,"Veículo na retenção, deseja acionar o seguro pagando <b>$"..vRP.format(parseInt(vRP.vehiclePrice(name)*0.5)).."</b> dólares ?",60) if ok then if vRP.tryFullPayment(user_id,parseInt(vRP.vehiclePrice(name)*0.5)) then vRP.execute("creative/set_detido",{ user_id = parseInt(user_id), vehicle = name, detido = 0, time = 0 }) TriggerClientEvent("Notify",source,"sucesso","Veículo liberado.",10000) else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",10000) end end elseif parseInt(vehicle[1].detido) >= 1 then local ok = vRP.request(source,"Veículo na detenção, deseja acionar o seguro pagando <b>$"..vRP.format(parseInt(vRP.vehiclePrice(name)*0.1)).."</b> dólares ?",60) if ok then if vRP.tryFullPayment(user_id,parseInt(vRP.vehiclePrice(name)*0.1)) then vRP.execute("creative/set_detido",{ user_id = parseInt(user_id), vehicle = name, detido = 0, time = 0 }) TriggerClientEvent("Notify",source,"sucesso","Veículo liberado.",10000) else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",10000) end end else if parseInt(os.time()) <= parseInt(vehicle[1].ipva+24*15*60*60) then if garages[use].payment then if vRP.hasPermission(user_id,"platina.permissao") or vRP.vehicleClass(tostring(name)) == "exclusive" or vRP.vehicleClass(tostring(name)) == "rental" then local spawnveh,vehid = vCLIENT.spawnVehicle(source,name,vehicle[1].engine,vehicle[1].body,vehicle[1].fuel,custom) if spawnveh then vehlist[vehid] = { user_id,name } TriggerEvent("setPlateEveryone",identity.registration) TriggerClientEvent("Notify",source,"sucesso","Veículo <b>Isento de Taxas</b>.",10000) end elseif (vRP.getBankMoney(user_id)+vRP.getMoney(user_id)) >= parseInt(vRP.vehiclePrice(name)*0.005 and not (vRP.hasPermission(user_id,"platina.permissao") or vRP.vehicleClass(tostring(name)) == "exclusive" or vRP.vehicleClass(tostring(name)) == "rental")) then if vRP.tryFullPayment(user_id,parseInt(vRP.vehiclePrice(name)*0.005)) then local spawnveh,vehid = vCLIENT.spawnVehicle(source,name,vehicle[1].engine,vehicle[1].body,vehicle[1].fuel,custom) if spawnveh then vehlist[vehid] = { user_id,name } TriggerEvent("setPlateEveryone",identity.registration) end else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",10000) return end end else local spawnveh,vehid = vCLIENT.spawnVehicle(source,name,vehicle[1].engine,vehicle[1].body,vehicle[1].fuel,custom) if spawnveh then vehlist[vehid] = { user_id,name } TriggerEvent("setPlateEveryone",identity.registration) end end else if vRP.hasPermission(user_id,"platina.permissao") or vRP.vehicleClass(tostring(name)) == "exclusive" or vRP.vehicleClass(tostring(name)) == "rental" then local ok = vRP.request(source,"Deseja pagar o <b>Vehicle Tax</b> do veículo <b>"..vRP.vehicleName(name).."</b> por <b>$"..vRP.format(parseInt(vRP.vehiclePrice(name)*0.02)).."</b> dólares ?",60) if ok then if vRP.tryFullPayment(user_id,parseInt(vRP.vehiclePrice(name)*0.02)) then vRP.execute("creative/set_ipva",{ user_id = parseInt(user_id), vehicle = name, ipva = parseInt(os.time()) }) TriggerClientEvent("Notify",source,"sucesso","Pagamento do <b>Vehicle Tax</b> conclúido com sucesso.",10000) else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",10000) end end else local ok = vRP.request(source,"Deseja pagar o <b>Vehicle Tax</b> do veículo <b>"..vRP.vehicleName(name).."</b> por <b>$"..vRP.format(parseInt(vRP.vehiclePrice(name)*0.05)).."</b> dólares ?",60) if ok then if vRP.tryFullPayment(user_id,parseInt(vRP.vehiclePrice(name)*0.05)) then vRP.execute("creative/set_ipva",{ user_id = parseInt(user_id), vehicle = name, ipva = parseInt(os.time()) }) TriggerClientEvent("Notify",source,"sucesso","Pagamento do <b>Vehicle Tax</b> conclúido com sucesso.",10000) else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",10000) end end end end end else local spawnveh,vehid = vCLIENT.spawnVehicle(source,name,1000,1000,100,custom) if spawnveh then vehlist[vehid] = { user_id,name } TriggerEvent("setPlateEveryone",identity.registration) end end else TriggerClientEvent("Notify",source,"aviso","Já possui um veículo deste modelo fora da garagem.",10000) end end end end ----------------------------------------------------------------------------------------------------------------------------------------- -- DELETEVEHICLES ----------------------------------------------------------------------------------------------------------------------------------------- function src.deleteVehicles() local source = source local user_id = vRP.getUserId(source) if user_id then local vehicle = vRPclient.getNearestVehicle(source,30) if vehicle then vCLIENT.deleteVehicle(source,vehicle) end end end ----------------------------------------------------------------------------------------------------------------------------------------- -- DESMANCHE ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("desmancheVehicles") AddEventHandler("desmancheVehicles",function() local source = source local user_id = vRP.getUserId(source) if user_id then local vehicle,vnetid,placa,vname,lock,banned = vRPclient.vehList(source,7) if vehicle and placa then local puser_id = vRP.getUserByRegistration(placa) if puser_id then vRP.execute("creative/set_detido",{ user_id = parseInt(puser_id), vehicle = vname, detido = 1, time = parseInt(os.time()) }) exports["pd-inventory"]:giveItem(user_id,"dinheirosujo",parseInt(vRP.vehiclePrice(vname)*0.1,true)) vCLIENT.deleteVehicle(source,vehicle) local identity = vRP.getUserIdentity(user_id) local identity2 = vRP.getUserIdentity(puser_id) SendWebhookMessage(webhookdesmanche,"```prolog\n[ID]: "..user_id.." "..identity.name.." "..identity.firstname.." \n[DESMANCHOU]: "..vRP.vehicleName(vname).." \n[DO ID]: "..puser_id.." "..identity2.name.." "..identity2.firstname.." \n[VALOR]: $"..vRP.format(parseInt(vRP.vehiclePrice(vname)*0.1)).." "..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```") end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- DV ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('dv',function(source,args,rawCommand) local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") or vRP.hasPermission(user_id,"suporte.permissao") then local vehicle = vRPclient.getNearestVehicle(source,7) if vehicle then vCLIENT.deleteVehicle(source,vehicle) end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- DV AREA ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('dvarea',function(source,args,rawCommand) local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") then if args[1] then local x,y,z = vRPclient.getPosition(source) TriggerClientEvent('dvarea',source,x,y,z,args[1]) end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- VEHICLELOCK ----------------------------------------------------------------------------------------------------------------------------------------- function src.vehicleLock() local source = source local user_id = vRP.getUserId(source) if user_id then local vehicle,vnetid,placa,vname,lock,banned = vRPclient.vehList(source,7) if vehicle and placa then local placa_user_id = vRP.getUserByRegistration(placa) if user_id == placa_user_id then vCLIENT.vehicleClientLock(-1,vnetid,lock) TriggerClientEvent("vrp_sound:source",source,'lock',0.5) vRPclient._CarregarObjeto(source,"anim@mp_player_intmenu@key_fob@","fob_click","p_car_keys_01",49,57005,0.11,0.03,-0.03,90.0,0.0,0.0) if lock == 1 then TriggerClientEvent("Notify",source,"importante","Veículo <b>trancado</b> com sucesso.",8000) else TriggerClientEvent("Notify",source,"importante","Veículo <b>destrancado</b> com sucesso.",8000) end Citizen.Wait(800) vRPclient._DeletarObjeto(source) end end end end ----------------------------------------------------------------------------------------------------------------------------------------- -- TRYDELETE ----------------------------------------------------------------------------------------------------------------------------------------- function src.tryDelete(vehid,vehengine,vehbody,vehfuel) if vehlist[vehid] and vehid ~= 0 then local user_id = vehlist[vehid][1] local vehname = vehlist[vehid][2] local player = vRP.getUserSource(user_id) if player then vCLIENT.syncNameDelete(player,vehname) end if vehengine <= 100 then vehengine = 100 end if vehbody <= 100 then vehbody = 100 end if vehfuel >= 100 then vehfuel = 100 end local vehicle = vRP.query("creative/get_vehicles",{ user_id = parseInt(user_id), vehicle = vehname }) if vehicle[1] ~= nil then vRP.execute("creative/set_update_vehicles",{ user_id = parseInt(user_id), vehicle = vehname, engine = parseInt(vehengine), body = parseInt(vehbody), fuel = parseInt(vehfuel) }) end end vCLIENT.syncVehicle(-1,vehid) end ----------------------------------------------------------------------------------------------------------------------------------------- -- TRYDELETEVEH ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("trydeleteveh") AddEventHandler("trydeleteveh",function(vehid) vCLIENT.syncVehicle(-1,vehid) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- RETURNHOUSES ----------------------------------------------------------------------------------------------------------------------------------------- function src.returnHouses(nome,garage) local source = source local user_id = vRP.getUserId(source) if user_id then if not vRP.searchReturn(source,user_id) then local address = vRP.query("homes/get_homeuserid",{ user_id = parseInt(user_id) }) if #address > 0 then for k,v in pairs(address) do if v.home == garages[garage].name then if parseInt(v.garage) == 1 then local resultOwner = vRP.query("homes/get_homeuseridowner",{ home = tostring(nome) }) if resultOwner[1] then if parseInt(os.time()) >= parseInt(resultOwner[1].tax+24*14*60*60) and vRP.hasPermission(user_id,"platina.permissao") and (string.find(v.home,"FH") or string.find(v.home,"LX") or string.find(v.home,"MS") or string.find(v.home,"SS")) then vCLIENT.openGarage(source,nome,garage) else if parseInt(os.time()) >= parseInt(resultOwner[1].tax+24*14*60*60) then TriggerClientEvent("Notify",source,"aviso","A <b>Property Tax</b> da residência está atrasada.",10000) return false else vCLIENT.openGarage(source,nome,garage) end end end end end end end if garages[garage].perm == "livre" then return vCLIENT.openGarage(source,nome,garage) elseif garages[garage].perm then if vRP.hasPermission(user_id,garages[garage].perm) then return vCLIENT.openGarage(source,nome,garage) end elseif garages[garage].public then return vCLIENT.openGarage(source,nome,garage) end end return false end end ----------------------------------------------------------------------------------------------------------------------------------------- -- VEHICLE ANCORAR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('travar',function(source,args,rawCommand) local source = source local user_id = vRP.getUserId(source) local x,y,z = vRPclient.getPosition(source) if user_id then if vRP.hasPermission(user_id,"policia.permissao") or vRP.hasPermission(user_id,"conce.permissao") or vRP.hasPermission(user_id,"admin.permissao") then if vRPclient.isInVehicle(source) then if vRP.hasPermission(user_id,"admin.permissao") or (vRPclient.checkDistance(source,-1046.38,-860.83,4.92,20) or vRPclient.checkDistance(source,-483.41,6025.20,31.35,20)) then local vehicle,vnetid,placa,vname,lock,banned = vRPclient.vehList(source,7) if vehicle then TriggerClientEvent("progress",source,5000,"travar/destravar") SetTimeout(5000,function() vCLIENT.vehicleAnchor(source,vehicle,x,y,z) end) end end end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- BOAT ANCORAR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('ancorar',function(source,args,rawCommand) local source = source local user_id = vRP.getUserId(source) if user_id then if vRPclient.isInVehicle(source) then local vehicle,vnetid,placa,vname,lock,banned = vRPclient.vehList(source,7) if vehicle then vCLIENT.boatAnchor(source,vehicle) end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- CAR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('car',function(source,args,rawCommand) local user_id = vRP.getUserId(source) if user_id then local identity = vRP.getUserIdentity(user_id) if vRP.hasPermission(user_id,"admin.permissao") then if args[1] then TriggerClientEvent('spawnarveiculo',source,args[1]) TriggerEvent("setPlateEveryone",identity.registration) end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- VEHS ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('vehs',function(source,args,rawCommand) local user_id = vRP.getUserId(source) if user_id then if args[1] and parseInt(args[2]) > 0 then local nplayer = vRP.getUserSource(parseInt(args[2])) local myvehicles = vRP.query("creative/get_vehicles",{ user_id = parseInt(user_id), vehicle = tostring(args[1]) }) local value = vRP.getUData(parseInt(user_id),"vRP:multas") local multas = json.decode(value) or 0 if multas > 0 then TriggerClientEvent("Notify",source,"negado","Você tem multas pendentes.",10000) return end if parseInt(os.time()) >= parseInt(myvehicles[1].ipva+24*15*60*60) then TriggerClientEvent("Notify",source,"negado","Seu <b>Vehicle Tax</b> está atrasado.",10000) return end if vRP.searchReturn(source,user_id) then return end if myvehicles[1] then if (vRP.vehicleClass(tostring(args[1])) == "exclusive" or vRP.vehicleClass(tostring(args[1])) == "rental" or vRP.vehicleClass(tostring(args[1])) == "vip") and not vRP.hasPermission(user_id,"admin.permissao") then TriggerClientEvent("Notify",source,"negado","<b>"..vRP.vehicleName(tostring(args[1])).."</b> não pode ser transferido</b>.",10000) else local identity = vRP.getUserIdentity(parseInt(args[2])) local identity2 = vRP.getUserIdentity(user_id) local price = tonumber(sanitizeString(vRP.prompt(source,"Valor:",""),"\"[]{}+=?!_()#@%/\\|,.",false)) if nplayer ~= nil then if vRP.request(source,"Deseja vender um <b>"..vRP.vehicleName(tostring(args[1])).."</b> para <b>"..identity.name.." "..identity.firstname.."</b> por <b>$"..vRP.format(parseInt(price)).."</b> dólares ?",30) then if vRP.request(nplayer,"Aceita comprar um <b>"..vRP.vehicleName(tostring(args[1])).."</b> de <b>"..identity2.name.." "..identity2.firstname.."</b> por <b>$"..vRP.format(parseInt(price)).."</b> dólares ?",30) then local vehicle = vRP.query("creative/get_vehicles",{ user_id = parseInt(args[2]), vehicle = tostring(args[1]) }) if parseInt(price) > 0 then if vehicle[1] then TriggerClientEvent("Notify",source,"negado","<b>"..identity.name.." "..identity.firstname.."</b> já possui este modelo de veículo.",10000) TriggerClientEvent("Notify",nplayer,"negado","Você já possui um <b>"..vRP.vehicleName(tostring(args[1])).."</b> em sua garagem.",10000) return end local value = vRP.getUData(parseInt(args[2]),"vRP:multas") local multas = json.decode(value) or 0 if multas > 0 and parseInt(args[2]) then TriggerClientEvent("Notify",source,"negado","<b>"..identity.name.." "..identity.firstname.."</b> possui multas pendentes.",10000) TriggerClientEvent("Notify",nplayer,"negado","Você tem multas pendentes.",10000) return end local maxvehs = vRP.query("creative/con_maxvehs",{ user_id = parseInt(args[2]) }) local maxcars = vRP.query("creative/get_users",{ user_id = parseInt(args[2]) }) if vRP.hasPermission(parseInt(args[2]),"conce.permissao") then if parseInt(maxvehs[1].qtd) >= parseInt(maxcars[1].garagem) + 100 then TriggerClientEvent("Notify",source,"importante","<b>"..identity.name.." "..identity.firstname.."</b> atingiu o número máximo de veículos em sua garagem.",8000) TriggerClientEvent("Notify",nplayer,"importante","Você atingiu o número máximo de veículos em sua garagem.",8000) return end elseif vRP.hasPermission(parseInt(args[2]),"ouro.permissao") then if parseInt(maxvehs[1].qtd) >= parseInt(maxcars[1].garagem) + 3 then TriggerClientEvent("Notify",source,"importante","<b>"..identity.name.." "..identity.firstname.."</b> atingiu o número máximo de veículos em sua garagem.",8000) TriggerClientEvent("Notify",nplayer,"importante","Você atingiu o número máximo de veículos em sua garagem.",8000) return end elseif vRP.hasPermission(parseInt(args[2]),"platina.permissao") then if parseInt(maxvehs[1].qtd) >= parseInt(maxcars[1].garagem) + 6 then TriggerClientEvent("Notify",source,"importante","<b>"..identity.name.." "..identity.firstname.."</b> atingiu o número máximo de veículos em sua garagem.",8000) TriggerClientEvent("Notify",nplayer,"importante","Você atingiu o número máximo de veículos em sua garagem.",8000) return end else if parseInt(maxvehs[1].qtd) >= parseInt(maxcars[1].garagem) then TriggerClientEvent("Notify",source,"importante","<b>"..identity.name.." "..identity.firstname.."</b> atingiu o número máximo de veículos em sua garagem.",8000) TriggerClientEvent("Notify",nplayer,"importante","Você atingiu o número máximo de veículos em sua garagem.",8000) return end end if vRP.tryFullPayment(parseInt(args[2]),parseInt(price)) then vRP.execute("creative/move_vehicle",{ user_id = parseInt(user_id), nuser_id = parseInt(args[2]), vehicle = tostring(args[1]) }) local custom = vRP.getSData("custom:u"..parseInt(user_id).."veh_"..tostring(args[1])) local custom2 = json.decode(custom) if custom2 then vRP.setSData("custom:u"..parseInt(args[2]).."veh_"..tostring(args[1]),json.encode(custom2)) vRP.execute("creative/rem_srv_data",{ dkey = "custom:u"..parseInt(user_id).."veh_"..tostring(args[1]) }) end local chest = vRP.getSData("chest:u"..parseInt(user_id).."veh_"..tostring(args[1])) local chest2 = json.decode(chest) if chest2 then vRP.setSData("chest:u"..parseInt(args[2]).."veh_"..tostring(args[1]),json.encode(chest2)) vRP.execute("creative/rem_srv_data",{ dkey = "chest:u"..parseInt(user_id).."veh_"..tostring(args[1]) }) end TriggerClientEvent("Notify",source,"sucesso","Você Vendeu <b>"..vRP.vehicleName(tostring(args[1])).."</b> e Recebeu <b>$"..vRP.format(parseInt(price)).."</b> dólares.",20000) TriggerClientEvent("Notify",nplayer,"importante","Você recebeu as chaves do veículo <b>"..vRP.vehicleName(tostring(args[1])).."</b> de <b>"..identity2.name.." "..identity2.firstname.."</b> e pagou <b>$"..vRP.format(parseInt(price)).."</b> dólares.",40000) vRPclient.playSound(source,"Hack_Success","DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS") vRPclient.playSound(nplayer,"Hack_Success","DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS") vRP.giveMoney(user_id,parseInt(price)) SendWebhookMessage(webhookvehs,"```prolog\n[ID]: "..user_id.." "..identity2.name.." "..identity2.firstname.." \n[VENDEU]: "..vRP.vehicleName(tostring(args[1])).." \n[PARA O ID]: "..(args[2]).." "..identity.name.." "..identity.firstname.." \n[VALOR]: $"..vRP.format(parseInt(price)).." "..os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S").." \r```") end else TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.",8000) TriggerClientEvent("Notify",nplayer,"negado","Dinheiro insuficiente.",8000) end end end end end end else local vehicle = vRP.query("creative/get_vehicle",{ user_id = parseInt(user_id) }) for k,v in pairs(vehicle) do if parseInt(os.time()) >= parseInt(v.ipva+24*15*60*60) then TriggerClientEvent("Notify",source,"negado","<b>Modelo:</b> "..vRP.vehicleName(v.vehicle).." <b>("..v.vehicle..")</b><br>Vehicle Tax: <b>Atrasado</b>",20000) else TriggerClientEvent("Notify",source,"importante","<b>Modelo:</b> "..vRP.vehicleName(v.vehicle).." <b>("..v.vehicle..")</b><br>Vehicle Tax: <b>"..vRPclient.getTimeFunction(source,parseInt(86400*15-(os.time()-v.ipva))).."</b>.",20000) end end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- REPARAR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("tryreparar") AddEventHandler("tryreparar",function(nveh) TriggerClientEvent("syncreparar",-1,nveh) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- REPARAR PNEUS ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("tryrepararpneus") AddEventHandler("tryrepararpneus",function(nveh) TriggerClientEvent("syncrepararpneus",-1,nveh) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- MOTOR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterServerEvent("trymotor") AddEventHandler("trymotor",function(nveh) TriggerClientEvent("syncmotor",-1,nveh) end) ----------------------------------------------------------------------------------------------------------------------------------------- -- SAVELIVERY ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('savelivery',function(source,args,rawCommand) local source = source local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") or vRP.hasPermission(user_id,"mecanico.permissao") then local vehicle,vnetid,placa,vname = vRPclient.vehList(source,7) if vehicle and placa then local puser_id = vRP.getUserByRegistration(placa) if puser_id then local custom = json.decode(vRP.getSData("custom:u"..parseInt(puser_id).."veh_"..vname)) local livery = vCLIENT.returnlivery(source,livery) custom.liveries = livery --print(json.encode(custom)) vRP.setSData("custom:u"..parseInt(puser_id).."veh_"..vname,json.encode(custom)) end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- SAVECOLOR ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('savecolor',function(source,args,rawCommand) local source = source local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") or vRP.hasPermission(user_id,"mecanico.permissao") then local vehicle,vnetid,placa,vname = vRPclient.vehList(source,7) if vehicle and placa then local puser_id = vRP.getUserByRegistration(placa) if puser_id then local custom = json.decode(vRP.getSData("custom:u"..parseInt(puser_id).."veh_"..vname)) local r1,g1,b1 = vCLIENT.returncolor1(source,r,g,b) local r2,g2,b2 = vCLIENT.returncolor2(source,r,g,b) custom.customcolor1 = {r1,g1,b1} custom.customcolor2 = {r2,g2,b2} vRP.setSData("custom:u"..parseInt(puser_id).."veh_"..vname,json.encode(custom)) end end end end) ----------------------------------------------------------------------------------------------------------------------------------------- -- CHECK LIVERY PERMISSION ----------------------------------------------------------------------------------------------------------------------------------------- function src.CheckLiveryPermission() local source = source local user_id = vRP.getUserId(source) return (vRP.hasPermission(user_id,"admin.permissao") or vRP.hasPermission(user_id,"mecanico.permissao")) end ----------------------------------------------------------------------------------------------------------------------------------------- -- CHECK COLOR PERMISSION ----------------------------------------------------------------------------------------------------------------------------------------- function src.CheckColorPermission() local source = source local user_id = vRP.getUserId(source) return (vRP.hasPermission(user_id,"admin.permissao") or vRP.hasPermission(user_id,"mecanico.permissao")) end ----------------------------------------------------------------------------------------------------------------------------------------- -- HASH ----------------------------------------------------------------------------------------------------------------------------------------- RegisterCommand('hash',function(source,args,rawCommand) local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") then local vehhash = vCLIENT.getHash(source,vehiclehash) vRP.prompt(source,"Hash:",""..vehhash) end end)
local clone = require('modutram.helper.clone') return function (a, b) local merged = clone(a) for key, value in pairs(b) do merged[key] = value end return merged end
RP.Character = class("Character", RP.Base) local char = RP.Character char.bounty = 0 char.name = "Character" char.model = "models/kleiner.mdl" char.title = "" char.alive = true char.deathCount = 0 char.experience = 0 char.upgradePoints = 0 char.stats = RP.Stats() function char:__tostring() local str = "Character ('" .. char.name .. "', " .. self.id .. "): {\n" str = str .. tostring(self.stats) str = str .. "\n}" return str end
return {InstCall_regs_coeffs=4}
local key = KEYS[1] local len = ARGV[1] if redis.call('exists', key) == 0 then redis.call('set', key, 0) return 0 end local current = tonumber(redis.call('get', key)) current = (tonumber(current) + 1) % tonumber(len) redis.call('set', key, current) return current
require ("lib.lclass") class "Processor" function Processor:Processor () -- end function Processor:onStart () -- end function Processor:onStop () -- end function Processor:onUpdate (dt) -- end function Processor:onRender () -- end
-- The following two lines define two functions which will be used on this exercise. -- For now you can just ignore them local function lua_greater_or_equal_5_3() return table.move end local function lua_greater_or_equal_5_2() return _G.rawlen end function test_coroutine_is_of_type_table() assert_equal("table", type(coroutine)) end function test_table_coroutine_contains_six_or_seven_elements() local counter = 0 for key in pairs(coroutine) do counter = counter + 1 end if lua_greater_or_equal_5_3() then -- if you are on Lua >=5.3 assert_equal(7, counter) else -- if you are on Lua <=5.2 assert_equal(6, counter) end end -- Table elements: -- create resume status -- running wrap yield -- Lua 5.3: isyieldable function test_all_elements_of_table_coroutine_are_of_type_function() for key, value in pairs(coroutine) do assert_equal("function", type(value)) end end function test_created_coroutine_is_of_type_thread() local corothread = coroutine.create( function() end ) assert_equal("thread", type(corothread)) end function test_status_of_created_coroutine_is_suspended() local corothread = coroutine.create( function() end ) assert_equal("suspended", coroutine.status(corothread)) end function test_created_coroutine_can_be_successfully_resumed() local corothread = coroutine.create( function() end ) assert_equal(true, coroutine.resume(corothread)) end function test_coroutine_without_yield_is_dead_after_resume() local corothread = coroutine.create( function() end ) coroutine.resume(corothread) assert_equal("dead", coroutine.status(corothread)) end function test_coroutine_with_yield_is_suspended_after_first_resume() local corothread = coroutine.create( function() coroutine.yield() end ) coroutine.resume(corothread) assert_equal("suspended", coroutine.status(corothread)) end function test_coroutine_with_yield_is_dead_after_second_resume() local corothread = coroutine.create( function() coroutine.yield() end ) coroutine.resume(corothread) coroutine.resume(corothread) assert_equal("dead", coroutine.status(corothread)) end function test_resuming_dead_coroutine_results_in_error() local corothread = coroutine.create( function() end ) local errorfree1, _ = coroutine.resume(corothread) local errorfree2, errdescr = coroutine.resume(corothread) assert_equal(true, errorfree1) assert_equal(false, errorfree2) assert_equal("cannot resume dead coroutine", errdescr) end function test_status_of_coroutine_that_resumed_another_coroutine_is_normal() local corothread1, corothread2, statusthread1 corothread1 = coroutine.create( function() coroutine.resume(corothread2) end ) corothread2 = coroutine.create( function() statusthread1 = coroutine.status(corothread1) end ) coroutine.resume(corothread1) assert_equal("normal", statusthread1) end function test_coroutine_running_returns_current_coroutine() local val1, val2, val3 local cor = coroutine.create( function() val3 = coroutine.running() coroutine.yield() end ) val1 = coroutine.running() coroutine.resume(cor) val2 = coroutine.running() -- The behavior of coroutine.running has changed -- There is an "always-running main coroutine" in Lua >= 5.2 -- Plus, coroutine.running returns a second parameter (see below) if lua_greater_or_equal_5_2() then assert_equal("thread", type(val1)) assert_equal("thread", type(val2)) assert_equal(true, val1 == val2) assert_equal(false, val1 == val3) assert_equal(true, val3 == cor) else -- In Lua 5.1 and LuaJIT, there is no "main coroutine", to coroutine.running can return nil assert_equal("thread", type(val1)) assert_equal("thread", type(val2)) assert_equal(true, val1 == val2) assert_equal(true, val3 == cor) end end -- The following 2 tests only apply to Lua >= 5.2, because coroutine.running returns a second value there if lua_greater_or_equal_5_2() then function test_coroutine_running_returns_true_if_running_coroutine_is_main_one() local _, ismaincoro = coroutine.running() assert_equal(true, ismaincoro) end function test_coroutine_running_returns_false_if_running_coroutine_is_not_main_one() local ismaincoro = true local corothread = coroutine.create( function() _, ismaincoro = coroutine.running(corothread) end ) coroutine.resume(corothread) assert_equal(false, ismaincoro) end end -- The following 2 tests only apply to 5.3, since coroutine.isyieldable doesn't exist in previous versions of Lua if lua_greater_or_equal_5_3() then function test_main_thread_is_not_yieldable() assert_equal(false, coroutine.isyieldable()) end function test_running_coroutine_is_yieldable() local isyieldable = false local corothread = coroutine.create( function() isyieldable = coroutine.isyieldable() end ) coroutine.resume(corothread) assert_equal(true, isyieldable) end end function test_resume_with_no_yield_passes_arguments_to_coroutine_main_function() local myvar local corothread = coroutine.create( function(arg1) myvar = arg1 end ) coroutine.resume(corothread, 42) assert_equal(42, myvar) end function test_yield_returns_arguments_from_corresponding_resume_call() local retval1, retval2 local corothread = coroutine.create( function() retval1, retval2 = coroutine.yield() end ) coroutine.resume(corothread) coroutine.resume(corothread, 42, 21) assert_equal(42, retval1) assert_equal(21, retval2) end function test_arguments_to_yield_are_passed_to_resume_call() local corothread = coroutine.create( function() coroutine.yield("mystatus") end ) local errorfree, argumentfromyield = coroutine.resume(corothread) assert_equal(true, errorfree) assert_equal("mystatus", argumentfromyield) end function test_return_values_from_main_function_go_to_corresponding_resume() local corothread = coroutine.create( function() return 84, 168 end ) local errorfree, retval1, retval2 = coroutine.resume(corothread) assert_equal(true, errorfree) assert_equal(84, retval1) assert_equal(168, retval2) end function test_coroutine_wrap_returns_function() local wrapfunc = coroutine.wrap( function() end ) assert_equal("function", type(wrapfunc)) end function test_coroutine_wrap_does_not_resume_created_coroutine() local isexecuted = false local wrapfunc = coroutine.wrap( function() isexecuted = true end ) assert_equal(false, isexecuted) end function test_calling_function_returned_by_wrap_resumes_created_coroutine() local isexecuted = false local wrapfunc = coroutine.wrap( function() isexecuted = true end ) wrapfunc() assert_equal(true, isexecuted) end function test_errors_inside_coroutines_are_propagated_to_caller() -- note that with coroutine.wrap, the behaviour is different: -- here, the error is raised immediately local corothread = coroutine.create( function() error("Error inside coroutine") end ) errorfree, message = coroutine.resume(corothread) assert_equal(false, errorfree) assert_equal(true, "Error inside coroutine" == string.match(message, "Error inside coroutine")) end function test_coroutines_can_called_recursively() local function rec_reverse(char) if char then rev_string = rec_reverse(coroutine.yield()) or '' return rev_string .. char end end local wrap_func = coroutine.wrap(rec_reverse) string.gsub("Reversing with coroutines", ".", wrap_func) assert_equal("senituoroc htiw gnisreveR", wrap_func()) end
UI.Separator() local followThis = tostring(storage.followLeader) FloorChangers = { Ladders = { Up = {1948, 5542, 16693, 16692}, Down = {432, 412, 469, 1949, 469} }, Holes = { Up = {}, Down = {293, 294, 595, 4728, 385, 9853} }, RopeSpots = { Up = {386,}, Down = {} }, Stairs = { Up = {16690, 1958, 7548, 7544, 1952, 1950, 1947, 7542, 855, 856, 1978, 1977, 6911, 6915, 1954, 5259, 20492, 1956, 1957, 1955, 5257}, Down = {482, 414, 413, 437, 7731, 469, 413, 434, 469, 859, 438, 6127, 566, 7476, 4826} }, Sewers = { Up = {}, Down = {435} }, } local target = followThis local lastKnownPosition local function goLastKnown() if getDistanceBetween(pos(), {x = lastKnownPosition.x, y = lastKnownPosition.y, z = lastKnownPosition.z}) > 1 then local newTile = g_map.getTile({x = lastKnownPosition.x, y = lastKnownPosition.y, z = lastKnownPosition.z}) if newTile then g_game.use(newTile:getTopUseThing()) delay(math.random(300, 700)) end end end local function handleUse(pos) goLastKnown() local lastZ = posz() if posz() == lastZ then local newTile = g_map.getTile({x = pos.x, y = pos.y, z = pos.z}) if newTile then g_game.use(newTile:getTopUseThing()) delay(math.random(400, 800)) end end end local function handleStep(pos) goLastKnown() local lastZ = posz() if posz() == lastZ then autoWalk(pos) delay(math.random(400, 800)) end end local function handleRope(pos) goLastKnown() local lastZ = posz() if posz() == lastZ then local newTile = g_map.getTile({x = pos.x, y = pos.y, z = pos.z}) if newTile then useWith(3003, newTile:getTopUseThing()) delay(math.random(400, 800)) end end end local floorChangeSelector = { Ladders = {Up = handleUse, Down = handleStep}, Holes = {Up = handleStep, Down = handleStep}, RopeSpots = {Up = handleRope, Down = handleRope}, Stairs = {Up = handleStep, Down = handleStep}, Sewers = {Up = handleUse, Down = handleUse}, } local function checkTargetPos() local c = getCreatureByName(target) if c and c:getPosition().z == posz() then lastKnownPosition = c:getPosition() end end local function distance(pos1, pos2) local pos2 = pos2 or lastKnownPosition or pos() return math.abs(pos1.x - pos2.x) + math.abs(pos1.y - pos2.y) end local function executeClosest(possibilities) local closest local closestDistance = 99999 for _, data in ipairs(possibilities) do local dist = distance(data.pos) if dist < closestDistance then closest = data closestDistance = dist end end if closest then closest.changer(closest.pos) end end local function handleFloorChange() local c = getCreatureByName(target) local range = 2 local p = pos() local possibleChangers = {} for _, dir in ipairs({"Down", "Up"}) do for changer, data in pairs(FloorChangers) do for x = -range, range do for y = -range, range do local tile = g_map.getTile({x = p.x + x, y = p.y + y, z = p.z}) if tile then if table.find(data[dir], tile:getTopUseThing():getId()) then table.insert(possibleChangers, {changer = floorChangeSelector[changer][dir], pos = {x = p.x + x, y = p.y + y, z = p.z}}) end end end end end end executeClosest(possibleChangers) end local function targetMissing() for _, n in ipairs(getSpectators(false)) do if n:getName() == target then return n:getPosition().z ~= posz() end end return true end macro(500, "Advanced Follow", "", function(macro) local c = getCreatureByName(target) if g_game.isFollowing() then if g_game.getFollowingCreature() ~= c then g_game.cancelFollow() g_game.follow(c) end end if c and not g_game.isFollowing() then g_game.follow(c) elseif c and g_game.isFollowing() and getDistanceBetween(pos(), c:getPosition()) > 1 then g_game.cancelFollow() g_game.follow(c) end checkTargetPos() if targetMissing() and lastKnownPosition then handleFloorChange() end end) UI.Label("Follow Player:") addTextEdit("playerToFollow", storage.followLeader or "Trala", function(widget, text) storage.followLeader = text target = tostring(text) end)
-- Autogenerated from KST: please remove this line if doing any edits by hand! local luaunit = require("luaunit") require("position_abs") TestPositionAbs = {} function TestPositionAbs:test_position_abs() local r = PositionAbs:from_file("src/position_abs.bin") luaunit.assertEquals(r.index_offset, 32) luaunit.assertEquals(r.index.entry, "foo") end
-- Lua uses '--' as comment to end of line read the -- manual for more comment options. pktgen.screen("off");
---@type i18n local i18n = ECSLoader:ImportModule("i18n") local rangedConfigTranslations = { ["Show Ranged Stats"] = { ["enUS"] = true, ["deDE"] = "Fernkampfwerte anzeigen", ["frFR"] = "À distance Général", ["zhCN"] = "显示远程属性", }, ["Shows/Hides all ranged stats."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt alle Fernkampfwerte.", ["frFR"] = "Affiche/cache toutes les statistiques à distance.", ["zhCN"] = "显示/隐藏 所有远程属性", }, ["Ranged Attack Power"] = { ["enUS"] = true, ["deDE"] = "Fernkampf Angriffskraft", ["frFR"] = "Puissance d'attaque à distance", ["zhCN"] = "远程攻击强度", }, ["Shows/Hides the ranged attack power value."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt den Fernkampf Angriffskraftwert.", ["frFR"] = "Affiche/Cache la puissance d'attaque à distance.", ["zhCN"] = "显示/隐藏 远程攻击强度", }, ["Ranged Crit"] = { ["enUS"] = true, ["deDE"] = "Fernkampf Kritisch", ["frFR"] = "Critique à distance", ["zhCN"] = "远程暴击", }, ["Shows/Hides the ranged crit chance."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt die Chance im Fernkampf kritisch zu treffen.", ["frFR"] = "Affiche/cache les chances de coup critique à distance.", ["zhCN"] = "显示/隐藏 远程暴击", }, ["Shows/Hides the ranged attack speed."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt das Fernkampf Angriffstempo.", ["frFR"] = false, ["zhCN"] = false, }, ["Ranged Hit"] = { ["enUS"] = true, ["deDE"] = "Fernkampf Trefferwertung", ["frFR"] = "Toucher à distance", ["zhCN"] = "远程命中", }, ["Ranged Hit Values"] = { ["enUS"] = true, ["deDE"] = "Fernkampf Trefferwertung", ["frFR"] = "Valeurs de toucher à distance", ["zhCN"] = "远程命中率", }, ["Shows/Hides all ranged hit chance."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt alle Trefferwertungen im Fernkampf.", ["frFR"] = "Affiche/cache les chances de toucher à distance.", ["zhCN"] = "显示/隐藏 所有远程命中", }, ["Shows/Hides the ranged hit rating."] = { ["frFR"] = false, ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt die Fernkampf Trefferwertung.", ["zhCN"] = false, }, ["Shows/Hides the ranged hit bonus."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt den Bonus auf die Fernkampf Trefferwertung.", ["frFR"] = "Affiche/cache le bonus de toucher à distance.", ["zhCN"] = "显示/隐藏 远程命中率", }, ["Shows/Hides the ranged miss chance against enemies on the same level."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt die Chance einen Gegner des gleichen Levels im Fernkampf zu verfehlen.", ["frFR"] = "Affiche/cache les chances de rater à distance contre un ennemi du même niveau.", ["zhCN"] = "显示/隐藏 针对同等级敌人的远程未命中率", }, ["Shows/Hides the ranged miss chance against boss enemies (+3 Level)."] = { ["enUS"] = true, ["deDE"] = "Zeigt/Versteckt die Chance einen Gegner mit 3 Level über dem eigenen im Fernkampf zu verfehlen.", ["frFR"] = "Affiche/cache les chances de rater à distance contre un boss de 3 niveaux supérieurs.", ["zhCN"] = "显示/隐藏 针对BOSS的远程未命中率 (+3 等级)。", }, } for k, v in pairs(rangedConfigTranslations) do i18n.translations[k] = v end
----------------------------------- -- Area: Port Jeuno -- NPC: Tsolag -- Type: NPC -- !pos -13 8 53 246 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
-- Strategy profile initialization routine -- Defines Strategy profile properties and Strategy parameters -- TODO: Add minimal and maximal value of numeric parameters and default color of the streams function Init() strategy:name("3 EMA Pullback 2.0"); strategy:description("No description"); strategy:type(core.Both); strategy:setTag("NonOptimizableParameters", "SendEmail,PlaySound,Email,SoundFile,RecurrentSound,ShowAlert"); strategy.parameters:addGroup("Price Parameters"); strategy.parameters:addString("TF", "Time frame ('t1', 'm1', 'm5', etc.)", "", "m1"); strategy.parameters:setFlag("TF", core.FLAG_PERIODS); strategy.parameters:addGroup("Parameters"); strategy.parameters:addInteger("FastEMA", "Fast EMA Periods", "No description", 50); strategy.parameters:addInteger("MedEMA", "Medium EMA Periods", "No description", 150); strategy.parameters:addInteger("SlowEMA", "Slow EMA Periods", "No description", 250); strategy.parameters:addGroup("Stage 1 High/Low Parameters"); strategy.parameters:addInteger("LookBack", "LookBack Periods", "No description", 100); strategy.parameters:addBoolean("EnableStage1Timeframe", "EnableStage1Timeframe", "if set to yes, high/low can only be made when time is between TimeRangeStart and TimeRangeEnd", true); strategy.parameters:addString("TimeRangeStart", "TimeRangeStart", "set the time to start looking for high/low", "03:00:00"); strategy.parameters:addString("TimeRangeEnd", "TimeRangeEnd", "set the time to stop looking for high/low", "17:00:00"); strategy.parameters:addGroup("Trading Parameters"); strategy.parameters:addBoolean("AllowTrade", "Allow strategy to trade", "", true); strategy.parameters:setFlag("AllowTrade", core.FLAG_ALLOW_TRADE); strategy.parameters:addString("Account", "Account to trade on", "", ""); strategy.parameters:setFlag("Account", core.FLAG_ACCOUNT); strategy.parameters:addInteger("Amount", "Trade Amount in Lots", "", 1, 1, 100); strategy.parameters:addBoolean("SetLimit", "Set Limit Orders", "", true); strategy.parameters:addInteger("Limit", "Limit Order in pips", "", 30, 1, 10000); strategy.parameters:addBoolean("SetStop", "Set Stop Orders", "", true); strategy.parameters:addInteger("Stop", "Stop Order in pips", "", 30, 1, 10000); strategy.parameters:addBoolean("TrailingStop", "Trailing stop order", "", false); strategy.parameters:addGroup("Notification"); strategy.parameters:addBoolean("ShowAlert", "Show Alert", "", true); strategy.parameters:addBoolean("PlaySound", "Play Sound", "", false); strategy.parameters:addBoolean("RecurrentSound", "Recurrent Sound", "", false); strategy.parameters:addFile("SoundFile", "Sound File", "", ""); strategy.parameters:setFlag("SoundFile", core.FLAG_SOUND); strategy.parameters:addBoolean("SendEmail", "Send Email", "", false); strategy.parameters:addString("Email", "Email", "", ""); strategy.parameters:setFlag("Email", core.FLAG_EMAIL); end -- strategy instance initialization routine -- Processes strategy parameters and creates output streams -- TODO: Calculate all constants, create instances all necessary indicators and load all required libraries -- Parameters block local FastEMA; local MedEMA; local SlowEMA; local LookBack; local gSource = nil; -- the source stream local PlaySound; local RecurrentSound; local SoundFile; local Email; local SendEmail; local AllowTrade; local Account; local Amount; local BaseSize; local SetLimit; local Limit; local SetStop; local Stop; local TrailingStop; local Offer; local CanClose; --TODO: Add variable(s) for your indicator(s) if needed local iEMAFast; local iEMAMed; local iEMASlow; local EnableStage1Timeframe; local TimeRangeStart; local TimeRangeEnd; local PrevHigh; local Prevlow; -- Routine function Prepare(nameOnly) FastEMA = instance.parameters.FastEMA; MedEMA = instance.parameters.MedEMA; SlowEMA = instance.parameters.SlowEMA; LookBack = instance.parameters.LookBack; EnableStage1Timeframe = instance.parameters.EnableStage1Timeframe; TimeRangeStart = instance.parameters.TimeRangeStart; TimeRangeEnd = instance.parameters.TimeRangeEnd; local name = profile:id() .. "(" .. instance.bid:instrument() .. ", " .. tostring(FastEMA) .. ", " .. tostring(MedEMA) .. ", " .. tostring(SlowEMA) .. ", " .. tostring(LookBack).. ", " .. tostring(EnableStage1Timeframe) .. ")"; instance:name(name); if nameOnly then return ; end ShowAlert = instance.parameters.ShowAlert; PlaySound = instance.parameters.PlaySound; if PlaySound then RecurrentSound = instance.parameters.RecurrentSound; SoundFile = instance.parameters.SoundFile; else SoundFile = nil; end assert(not(PlaySound) or (PlaySound and SoundFile ~= ""), "Sound file must be specified"); SendEmail = instance.parameters.SendEmail; if SendEmail then Email = instance.parameters.Email; else Email = nil; end assert(not(SendEmail) or (SendEmail and Email ~= ""), "E-mail address must be specified"); AllowTrade = instance.parameters.AllowTrade; if AllowTrade then Account = instance.parameters.Account; Amount = instance.parameters.Amount; BaseSize = core.host:execute("getTradingProperty", "baseUnitSize", instance.bid:instrument(), Account); Offer = core.host:findTable("offers"):find("Instrument", instance.bid:instrument()).OfferID; CanClose = core.host:execute("getTradingProperty", "canCreateMarketClose", instance.bid:instrument(), Account); SetLimit = instance.parameters.SetLimit; Limit = instance.parameters.Limit * instance.bid:pipSize(); SetStop = instance.parameters.SetStop; Stop = instance.parameters.Stop * instance.bid:pipSize(); TrailingStop = instance.parameters.TrailingStop; end gSource = ExtSubscribe(1, nil, instance.parameters.TF, true, "bar"); tSource = ExtSubscribe(2, nil, "t1", true, "bar"); --TODO: Find indicator's profile, intialize parameters, and create indicator's instance (if needed) iEMAFast = core.indicators:create("EMA", gSource.close, FastEMA) iEMAMed = core.indicators:create("EMA", gSource.close, MedEMA) iEMASlow = core.indicators:create("EMA", gSource.close, SlowEMA) end local Stage1Status = "Neutral"; -- possible values are "Neutral", "Buy", "Sell" -- strategy calculation routine -- TODO: Add your code for decision making -- TODO: Update the instance of your indicator(s) if needed function ExtUpdate(id, source, period) -- update indicators iEMAFast:update(core.UpdateLast); iEMAMed:update(core.UpdateLast); iEMASlow:update(core.UpdateLast); -- check for data --if not iEMAFast.DATA:hasData(period) or not iEMAMed.DATA:hasData(period) or not iEMAMed.DATA:hasData(period) then --core.host:trace("Not Enough Data. Checking Next Bar...") --return; --end -- close of bar, Stage 1, making sure EMAs are lined up and price has reached 100 bar high/low if id == 1 and not haveTrades() then -- create a range of candles local range = core.rangeTo(period-1, LookBack) -- find high and low local High, Highpos = mathex.max(gSource.high, range) local Low, Lowpos = mathex.min(gSource.low, range) -- buy setup, if Price > Fast > Med > Slow AND close Price is above 100 period high if gSource.close[period] > iEMAFast.DATA[period] and iEMAFast.DATA[period] > iEMAMed.DATA[period] and iEMAMed.DATA[period] > iEMASlow.DATA[period] and gSource.close[period] > High then if not EnableStage1Timeframe or insideTimeRange() then Stage1Status = "Buy" terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Looking for Buy Trigger...", instance.bid:date(NOW)); PrevHigh, PrevHighpos = mathex.max(gSource.high, core.rangeTo(period-10, 50)) else Stage1Status = "Neutral" terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "New High Occurred Outside of Time Range, Removing Any Prior Signal...", instance.bid:date(NOW)); end end -- sell setup, if Price < Fast < Med < Slow AND close Price is below 100 period low if gSource.close[period] < iEMAFast.DATA[period] and iEMAFast.DATA[period] < iEMAMed.DATA[period] and iEMAMed.DATA[period] < iEMASlow.DATA[period] and gSource.close[period] < Low then if not EnableStage1Timeframe or insideTimeRange() then Stage1Status = "Sell" terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Looking for Sell Trigger...", instance.bid:date(NOW)); PrevLow, PrevLowpos = mathex.min(gSource.low, core.rangeTo(period-10, 50)) else Stage1Status = "Neutral" terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "New Low Occurred Outside of Time Range, Removing Any Prior Signal...", instance.bid:date(NOW)); end end end -- every tick, Stage 2, Stage1Status must not be "Neutral" and trigger buy/sell when Fast EMA is hit or crossed if id == 2 and Stage1Status ~= "Neutral" then --core.host:trace("EMA Value = " .. tostring(iEMAFast.DATA[iEMAFast.DATA:size()-1])); -- Buy trigger if Stage1Status == "Buy" and instance.bid[NOW] <= iEMAFast.DATA[iEMAFast.DATA:size()-1] then Stage1Status = "Neutral" -- BUY if instance.bid[NOW] >= PrevHigh - instance.bid:pipSize()*5 then enter("B") terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Opening Buy Trade...", instance.bid:date(NOW)); else -- NOT PLACING A BUY TRADE terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Price is Below PrevHigh-5, Skipping Buy Signal...", instance.bid:date(NOW)); end end -- Sell trigger if Stage1Status == "Sell" and instance.bid[NOW] >= iEMAFast.DATA[iEMAFast.DATA:size()-1] then Stage1Status = "Neutral" -- SELL if instance.bid[NOW] <= PrevLow + instance.bid:pipSize()*5 then enter("S") terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Opening Sell Trade...", instance.bid:date(NOW)); else -- NOT PLACING A SELL TRADE terminal:alertMessage(instance.bid:instrument(), instance.bid[NOW], "Price is Above PrevLow+5, Skipping Sell Signal...", instance.bid:date(NOW)); end end end end -- open positions in direction BuySell function enter(BuySell) local valuemap, success, msg; valuemap = core.valuemap(); valuemap.OrderType = "OM"; valuemap.OfferID = Offer; valuemap.AcctID = Account; valuemap.Quantity = Amount * BaseSize; valuemap.BuySell = BuySell; valuemap.GTC = "GTC"; if SetLimit then -- set limit order valuemap.PegTypeLimit = "O"; if BuySell == "B" then valuemap.PegPriceOffsetPipsLimit = Limit/instance.bid:pipSize(); else valuemap.PegPriceOffsetPipsLimit = -Limit/instance.bid:pipSize(); end end if SetStop then -- set stop order valuemap.PegTypeStop = "O"; if BuySell == "B" then valuemap.PegPriceOffsetPipsStop = -Stop/instance.bid:pipSize(); else valuemap.PegPriceOffsetPipsStop = Stop/instance.bid:pipSize(); end if TrailingStop then valuemap.TrailStepStop = 1; end end if (not CanClose) and (StopLoss > 0 or TakeProfit > 0) then valuemap.EntryLimitStop = "Y" end success, msg = terminal:execute(100, valuemap); if not(success) then terminal:alertMessage(instance.bid:instrument(), instance.bid[instance.bid:size() - 1], "open order failure: " .. msg, instance.bid:date(instance.bid:size() - 1)); return false; end return true; end -- return true if trade is found (can check single side as well) function haveTrades(BuySell) local enum, row; local found = false; enum = core.host:findTable("trades"):enumerator(); row = enum:next(); while (not found) and (row ~= nil) do if row.AccountID == Account and row.OfferID == Offer and (row.BS == BuySell or BuySell == nil) then found = true; end row = enum:next(); end return found; end function insideTimeRange() local currentTime = core.host:execute("getServerTime"); local startTimeToday = ConvertStrToTime(TimeRangeStart); local endTimeToday = ConvertStrToTime(TimeRangeEnd); --compare current time if startTimeToday <= endTimeToday then if currentTime >= startTimeToday and currentTime < endTimeToday then return true; end else if currentTime >= startTimeToday or currentTime < endTimeToday then return true; end end return false; end --Converts a time in string to time value function ConvertStrToTime(timeString, source, period) local h, m, s; local currentTime = core.host:execute("getServerTime"); local nowTable = core.dateToTable(currentTime); for HH, MM, SS in string.gmatch(timeString, "(%w+):(%w+):(%w+)") do h = tonumber(HH); m = tonumber(MM); s = tonumber(SS); end local time = core.datetime(nowTable.year, nowTable.month, nowTable.day, h, m, s); return time; end dofile(core.app_path() .. "\\strategies\\standard\\include\\helper.lua");
local helpers = require('test.functional.helpers')(after_each) local Screen = require('test.functional.ui.screen') local clear, feed, command = helpers.clear, helpers.feed, helpers.command local insert = helpers.insert if helpers.pending_win32(pending) then return end describe('Screen', function() local screen before_each(function() clear() screen = Screen.new(nil,10) screen:attach() screen:set_default_attr_ids( { [0] = {bold=true, foreground=Screen.colors.Blue}, [1] = {foreground = Screen.colors.LightGrey, background = Screen.colors.DarkGray} } ) end) after_each(function() screen:detach() end) describe("match and conceal", function() before_each(function() command("let &conceallevel=1") end) describe("multiple", function() before_each(function() insert([[ && && && && && && ]]) command("syn match dAmpersand '[&][&]' conceal cchar=∧") end) it("double characters.", function() screen:expect([[ {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | ^ | {0:~ }| {0:~ }| | ]]) end) it('double characters and move the cursor one line up.', function() feed("k") screen:expect([[ {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | ^&& | | {0:~ }| {0:~ }| | ]]) end) it('double characters and move the cursor to the beginning of the file.', function() feed("gg") screen:expect([[ ^&& | {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | | {0:~ }| {0:~ }| | ]]) end) it('double characters and move the cursor to the second line in the file.', function() feed("ggj") screen:expect([[ {1:∧} | ^&& | {1:∧} | {1:∧} | {1:∧} | {1:∧} | | {0:~ }| {0:~ }| | ]]) end) it('double characters and then move the cursor to the beginning of the file and back to the end of the file.', function() feed("ggG") screen:expect([[ {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | {1:∧} | ^ | {0:~ }| {0:~ }| | ]]) end) end) -- multiple it("keyword instances in initially in the document.", function() feed("2ilambda<cr><ESC>") command("let &conceallevel=1") command("syn keyword kLambda lambda conceal cchar=λ") screen:expect([[ {1:λ} | {1:λ} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) -- Keyword describe("regions in the document", function() before_each(function() feed("2") insert("<r> a region of text </r>\n") command("let &conceallevel=1") end) it('initially and conceal it.', function() command("syn region rText start='<r>' end='</r>' conceal cchar=R") screen:expect([[ {1:R} | {1:R} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it('initially and conceal its start tag and end tag.', function() -- concealends has a known bug (todo.txt) where the first match won't -- be replaced with cchar. command("syn region rText matchgroup=rMatch start='<r>' end='</r>' concealends cchar=-") screen:expect([[ {1: } a region of text {1:-} | {1: } a region of text {1:-} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it('that are nested and conceal the nested region\'s start and end tags.', function() command("syn region rText contains=rText matchgroup=rMatch start='<r>' end='</r>' concealends cchar=-") insert("<r> A region with <r> a nested <r> nested region.</r> </r> </r>\n") screen:expect([[ {1: } a region of text {1:-} | {1: } a region of text {1:-} | {1: } A region with {1: } a nested {1: } nested region.{1:-} | {1:-} {1:-} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) end) -- regions in the document describe("a region of text", function() before_each(function() command("syntax conceal on") feed("2") insert("<r> a region of text </r>\n") command("syn region rText start='<r>' end='</r>' cchar=-") end) it("and turn on implicit concealing", function() screen:expect([[ {1:-} | {1:-} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it("and then turn on, then off, and then back on implicit concealing.", function() command("syntax conceal off") feed("2") insert("<i> italian text </i>\n") command("syn region iText start='<i>' end='</i>' cchar=*") screen:expect([[ {1:-} | {1:-} | <i> italian text </i> | <i> italian text </i> | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) command("syntax conceal on") command("syn region iText start='<i>' end='</i>' cchar=*") screen:expect([[ {1:-} | {1:-} | {1:*} | {1:*} | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) end) -- a region of text (implicit concealing) end) -- match and conceal describe("let the conceal level be", function() before_each(function() insert("// No Conceal\n") insert('"Conceal without a cchar"\n') insert("+ With cchar\n\n") command("syn match noConceal '^//.*$'") command("syn match concealNoCchar '\".\\{-}\"$' conceal") command("syn match concealWCchar '^+.\\{-}$' conceal cchar=C") end) it("0. No concealing.", function() command("let &conceallevel=0") screen:expect([[ // No Conceal | "Conceal without a cchar" | + With cchar | | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it("1. Conceal using cchar or reference listchars.", function() command("let &conceallevel=1") screen:expect([[ // No Conceal | {1: } | {1:C} | | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it("2. Hidden unless cchar is set.", function() command("let &conceallevel=2") screen:expect([[ // No Conceal | | {1:C} | | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) it("3. Hide all concealed text.", function() command("let &conceallevel=3") screen:expect([[ // No Conceal | | | | ^ | {0:~ }| {0:~ }| {0:~ }| {0:~ }| | ]]) end) end) -- conceallevel end)
require 'Properties' require 'Level' require 'Camera' require 'Common' Annihilator = {list = {}} local function tag(c, strength, Annihilatorthing) local tag = {} local alpha = 0 if Annihilatorthing.Special == "Neumann" then alpha = Annihilatorthing.SpecialPower end Level:setPixel(c.x,c.y, c.r, c.g, c.b, alpha) tag.LifeTime = strength * Properties.FadeLengthFactor tag.TimeLeft = tag.LifeTime tag.Color = {r=c.r,g=c.g,b=c.b} tag.Pos = {x=c.x,y=c.y} table.insert(Annihilator.list,tag) end function Annihilator:tag(Annihilatorthing) if not Annihilatorthing.collisions then return end for _,c in ipairs(Annihilatorthing.collisions) do c.r, c.g, c.b, c.a = Level:getPixel(c.x,c.y) if c.a >= Properties.CollisionAlpha then if (Annihilatorthing.Effector == "Precision" ) or (Annihilatorthing.OperationStrength >= Materials:getHardness(c.r,c.g,c.b,c.a) ) then tag(c,Annihilatorthing.OperationStrength,Annihilatorthing) end end end end function Annihilator:update(dt) for index = #Annihilator.list,1,-1 do if Annihilator.list[index].TimeLeft <= 0 then table.remove(Annihilator.list,index) else Annihilator.list[index].TimeLeft = Annihilator.list[index].TimeLeft - dt end end end function Annihilator:draw() for _,tag in ipairs(Annihilator.list) do local cx, cy = Camera:worldToScreen(tag.Pos.x,tag.Pos.y) local fade = tag.TimeLeft / tag.LifeTime love.graphics.setColor(tag.Color.r,tag.Color.g,tag.Color.b,255*fade) love.graphics.points(cx,cy) end end
local COMMAND = Clockwork.command:New("SolvedAccept"); COMMAND.tip = "Use when you have solved a help request."; COMMAND.arguments = 0; function COMMAND:OnRun(player, arguments) local requestID = tonumber(arguments[1]); if (!requestID) then Clockwork.player:Notify(player, "Invalid request ID."); return; end; local request = vStaffRequests[requestID]; if (!request) then Clockwork.player:Notify(player, "Invalid request ID."); return; end; local request = vStaffRequests[requestID]; if (request.requesterSteamID != player:SteamID()) then Clockwork.player:Notify(player, "You can only mark your own help requests as solved!"); return; end; if (request.hasBeenSolved) then Clockwork.player:Notify(player, "This request has already been marked as solved."); return; end; vStaffRequests[requestID].hasBeenSolved = true; local staffer = Clockwork.player:FindByID(request.accepterSteamID); if (staffer) then local helpRequestsMarkedSolved = staffer:GetCharacterData("HelpRequestsMarkedSolved") or 0; staffer:SetCharacterData("HelpRequestsMarkedSolved", helpRequestsMarkedSolved + 1); Clockwork.player:SetSafePosition(staffer, staffer.preHelpRequestPos); Clockwork.player:Notify(player, "Your help request is now marked as solved: the staff member has been returned to their original position."); else Clockwork.player:Notify(player, "Your help request is now marked as solved."); end; Clockwork.player:Notify(staffer, "The help request is now marked as solved: you have been returned to your original position."); end; COMMAND:Register();
local ffi = require('ffi') ffi.cdef [[ int isalnum(int c); int isalpha(int c); int iscntrl(int c); int isdigit(int c); int isgraph(int c); int islower(int c); int isprint(int c); int ispunct(int c); int isspace(int c); int isupper(int c); int isxdigit(int c); int tolower(int c); int toupper(int c); ]] -- local M = {} return M
Lib = {} Lib.foo = function (x,y) return x + y end Lib.goo = function (x,y) return x - y end Lib = { foo = function (x,y) return x + y end, goo = function (x,y) return x - y end } Lib = {} function Lib.foo (x,y) return x + y end function Lib.goo (x,y) return x - y end
-- #LD34 - 2015 by <weldale@gmail.com> -- #LD31 - 2014 by <weldale@gmail.com> -- Adapted from: Paddle Game - #LD30 -- by <weldale@gmail.com> https://github.com/xicalango/ld30 -- Original: Rocks-n-Blaster -- #LD48 -- by <weldale@gmail.com> https://github.com/xicalango/Rocks-n-Blaster GameState = class("GameState") function GameState:onActivation() end function GameState:onDeactivation() end function GameState:onStateChange(oldState) return true end function GameState:update(dt) end function GameState:draw() end function GameState:keypressed(key, isRepeated) end function GameState:keyreleased(key) end function GameState:mousepressed(x, y, button) end function GameState:mousereleased(x, y, button) end NilGameState = GameState:subclass("NilGameState") GameStateManager = class("GameStateManager") function GameStateManager:initialize() self.states = {} self.currentState = NilGameState:new() self.currentStateClass = NilGameState self.nextStateClass = nil self.activationParameters = nil end function GameStateManager:draw() self.currentState:draw() end function GameStateManager:update(dt) if self.nextStateClass then self:_changeState() end self.currentState:update(dt) end function GameStateManager:keypressed(key, isRepeated) self.currentState:keypressed(key, isRepeated) end function GameStateManager:keyreleased(key) self.currentState:keyreleased(key) end function GameStateManager:mousepressed(x, y, button) self.currentState:mousepressed(x, y, button) end function GameStateManager:mousereleased(x, y, button) self.currentState:mousereleased(x, y, button) end function GameStateManager:registerState(stateClass) self.states[stateClass] = stateClass:new() end function GameStateManager:registerAll(states) for k,v in pairs(states) do self.states[k] = v end end function GameStateManager:changeState(stateClass, ...) assert( self.states[stateClass] ) self.nextStateClass = stateClass self.activationParameters = {...} end function GameStateManager:getCurrentState() return self.currentState end function GameStateManager:_changeState() if self.states[self.nextStateClass]:onStateChange( self.currentStateClass ) then self.currentState:onDeactivation() self.currentStateClass = self.nextStateClass self.currentState = self.states[self.nextStateClass] self.currentState:onActivation(unpack(self.activationParameters)) end self.nextStateClass = nil self.activationParameters = nil end
LuaExtend = { } ---------------------------------------------------------------------------- ------------------------------gameobject操作相关---------------------------- ---------------------------------------------------------------------------- function LuaExtend:setActive(obj,isActive) CS.LuaExtend.setActive(obj,isActive) end function LuaExtend:setObjPos(obj,x,y,z) CS.LuaExtend.setObjPos(obj,x,y,z) end function LuaExtend:setObjPosTable(obj,lst) CS.LuaExtend.setObjPos(obj,lst[1],lst[2],lst[3]) end function LuaExtend:getAngle(dir) return CS.LuaExtend.getAngle(dir) end ---------------------------------------------------------------------------- ------------------------------UI相关---------------------------------------- ---------------------------------------------------------------------------- --设置UI在Canvas的层 function LuaExtend:setUINode(obj,node) CS.LuaExtend.setUINode(obj,node) end --设置Image sprite function LuaExtend:setSprite(obj,name) CS.LuaExtend.setSprite(obj,name) end --给UI添加一个eventListener function LuaExtend:addEventListener(obj) return CS.LuaExtend.addEventListener(obj) end --根据UI节点路径查找 function LuaExtend:getNode(root,path) return CS.LuaExtend.getNode(root,path) end --递归查找UI下面的一个节点 function LuaExtend:getNodeByRecursion(root,nodeName) return CS.LuaExtend.getNodeByRecursion(root,nodeName) end --设置UI的material属性 function LuaExtend:setMaterialFloat(img,key,val) CS.LuaExtend.setMaterialFloat(img,key,val) end ---------------------------------------------------------------------------- ------------------------------DoTween相关----------------------------------- ---------------------------------------------------------------------------- function LuaExtend:doUpDownScaleAnim(obj,title,onComplete) return CS.LuaExtend.doUpDownScaleAnim(obj,title,onComplete) end function LuaExtend:doLocalMoveTo(obj,dur,endVal,call,delay) delay = delay and delay or 0 CS.LuaExtend.doLocalMoveTo(obj,dur,endVal,call,delay) end --销毁tween function LuaExtend:killTweener(tw,isDoComplete) CS.LuaExtend.killTweener(tw,isDoComplete) end --旋转 function LuaExtend:lerpRotation(obj,dir) CS.LuaExtend.lerpRotation(obj,dir) end --dofloat function LuaExtend:doFloatTo(call,startVal,endVal,dur,finish) return CS.LuaExtend.doFloatTo(call,startVal,endVal,dur,finish) end --------------------------------------------------------------------------- ------------------------------对象池相关----------------------------------- --------------------------------------------------------------------------- --销毁gameObject 对象池会处理 function LuaExtend:destroyObj(obj) CS.LuaExtend.destroyObj(obj) end --加载gameObject function LuaExtend:loadObj(url,callBack) CS.LuaExtend.loadObj(url,callBack) end --加载场景 function LuaExtend:loadScene(level,progress) CS.LuaExtend.loadScene(level,progress) end --摄像机相关 function LuaExtend:setCameraPlayer(player) CS.LuaExtend.setCameraPlayer(player) end function LuaExtend:doShake(time,att,hor,ver) CS.LuaExtend.doShake(time,att,hor,ver) end --------------------------------------------------------------------------- ------------------------------数学相关----------------------------------- --------------------------------------------------------------------------- function LuaExtend:getVectorAngle(v1,v2) return CS.LuaExtend.getVectorAngle(v1,v2) end function LuaExtend:getMillTimer() return CS.LuaExtend.getMillTimer() end function LuaExtend:getSecTimer() return CS.LuaExtend.getSecTimer() end function LuaExtend:unloadAllAssetBundle() CS.LuaExtend.unloadAllAssetBundle() end
--[[ File name: gameDatabase.lua Description: lookup values in the game database Author: oldmilk --]] local module = {} local InsertService = game:GetService("InsertService") -- updateConfig: update the game config/database function module.updateConfig() warn("Game database updating....") if game.ReplicatedStorage:FindFirstChild("gameDatabase") ~= nil then game.ReplicatedStorage.gameDatabase:Destroy() end InsertService:LoadAsset(7418954161):GetChildren()[1].Parent = game.ReplicatedStorage warn("Game database updated!") end -- runStartupConfig: run the server startup function located in the game database function module.runStartupConfig() local gameConfig = require(game.ReplicatedStorage:WaitForChild("gameDatabase")) gameConfig.server.startupConfig() end -- getLootTable: returns the raw loot table data for a given mob function module.getLootTable(mobName) local gameConfig = require(game.ReplicatedStorage:WaitForChild("gameDatabase")) if gameConfig.lootTables[mobName] == nil then error("Failed to lookup: invalid mobName") else return gameConfig["lootTables"][mobName] end end -- getItemInfo: returns the raw item info for a given item function module.getItemInfo(itemName) local gameConfig = require(game.ReplicatedStorage:WaitForChild("gameDatabase")) if gameConfig["items"][itemName] == nil then error("Failed to lookup: invalid itemName") else return gameConfig["items"][itemName] end end return module
AddEventHandler('esx:getSharedObject', function(cb) cb(ESX) end) function getSharedObject() return ESX end --ikNox#6088
local function isTable(value) return type(value) == 'table' end return isTable
--鉄獣戦線 ケラス -- --Script by JustFish function c101102007.initial_effect(c) --special summon from hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101102007,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,101102007) e1:SetCost(c101102007.spcost) e1:SetTarget(c101102007.sptg) e1:SetOperation(c101102007.spop) c:RegisterEffect(e1) --special summon from extra local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(101102007,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,101102007+100) e2:SetCost(c101102007.spcost1) e2:SetTarget(c101102007.sptg1) e2:SetOperation(c101102007.spop1) c:RegisterEffect(e2) end function c101102007.cfilter(c) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsDiscardable() end function c101102007.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101102007.cfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.DiscardHand(tp,c101102007.cfilter,1,1,REASON_COST+REASON_DISCARD,e:GetHandler()) end function c101102007.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c101102007.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function c101102007.spcost1(e,tp,eg,ep,ev,re,r,rp,chk) e:SetLabel(100) return true end function c101102007.cfilter1(c) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToRemoveAsCost() end function c101102007.fselect(g,tg) return tg:IsExists(Card.IsLink,1,nil,#g) end function c101102007.spfilter(c,e,tp) return c:IsType(TYPE_LINK) and c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.GetLocationCountFromEx(tp,tp,nil,c)>0 end function c101102007.sptg1(e,tp,eg,ep,ev,re,r,rp,chk) local cg=Duel.GetMatchingGroup(c101102007.cfilter1,tp,LOCATION_GRAVE,0,nil) local tg=Duel.GetMatchingGroup(c101102007.spfilter,tp,LOCATION_EXTRA,0,nil,e,tp) local _,maxlink=tg:GetMaxGroup(Card.GetLink) if chk==0 then if e:GetLabel()~=100 then return false end e:SetLabel(0) if #tg==0 then return false end return cg:CheckSubGroup(c101102007.fselect,1,maxlink,tg) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local rg=cg:SelectSubGroup(tp,c101102007.fselect,false,1,maxlink,tg) Duel.Remove(rg,POS_FACEUP,REASON_COST) e:SetLabel(rg:GetCount()) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c101102007.spfilter1(c,e,tp,lk) return c101102007.spfilter(c,e,tp) and c:IsLink(lk) end function c101102007.spop1(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_BE_LINK_MATERIAL) e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE) e1:SetTargetRange(0xff,0xff) e1:SetTarget(aux.NOT(aux.TargetBoolFunction(Card.IsRace,RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST))) e1:SetValue(c101102007.sumlimit) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local lk=e:GetLabel() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c101102007.spfilter1,tp,LOCATION_EXTRA,0,1,1,nil,e,tp,lk) local tc=g:GetFirst() if tc then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function c101102007.sumlimit(e,c) if not c then return false end return c:IsControler(e:GetHandlerPlayer()) end
object_tangible_tcg_series1_decorative_painting_alliance_propaganda = object_tangible_tcg_series1_shared_decorative_painting_alliance_propaganda:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series1_decorative_painting_alliance_propaganda, "object/tangible/tcg/series1/decorative_painting_alliance_propaganda.iff")
-- THE BASE MOBILE FACTORY PROTOTYPE -- -- Create Mobile Factory entity (Copy from base tank) -- local mf = table.deepcopy(data.raw.car.tank) mf.name = "MobileFactory" mf.order = "a" mf.equipment_grid = "MFEquipmentGrid" mf.minable = {mining_time = 1.5, result = "MobileFactory"} mf.inventory_size = 10 mf.max_health = 2500 mf.consumption = "700KW" mf.weight = 25000 mf.braking_power = "600kW" mf.rotation_speed = 0.30 / 60 mf.guns = {"mfTank-machine-gun"} mf.collision_box = {{-1.5, -2.5}, {1.0, 2.5}} mf.selection_box = {{-2, -3.5}, {1.6, 2.5}} --[[ mf.animation = { priority = "low", width = 300, height = 300, frame_count = 1, direction_count = 71, shift = util.by_pixel(-4.75, -10), animation_speed = 8, max_advance = 1, scale = 1, stripes = { { filename = "__Mobile_Factory_Graphics__/graphics/mobile- factory/mobile-factory.png", width_in_frames = 10, height_in_frames = 8 } } } --]] mf.animation = { layers = { { priority = "low", width = 269, height = 212, frame_count = 2, direction_count = 64, shift = util.by_pixel(-4.75, -10), animation_speed = 8, max_advance = 1, scale = 1, stripes = { { filename = "__base__/graphics/entity/tank/hr-tank-base-1.png", width_in_frames = 2, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-2.png", width_in_frames = 2, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-3.png", width_in_frames = 2, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-4.png", width_in_frames = 2, height_in_frames = 16 } } }, { priority = "low", width = 207, height = 166, frame_count = 2, direction_count = 64, shift = util.by_pixel(-4.75, -21), max_advance = 1, line_length = 2, stripes = util.multiplystripes(2, { { filename = "__base__/graphics/entity/tank/hr-tank-base-mask-1.png", width_in_frames = 1, height_in_frames = 22 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-mask-2.png", width_in_frames = 1, height_in_frames = 22 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-mask-3.png", width_in_frames = 1, height_in_frames = 20 } }), scale = 1 }, { priority = "low", width = 301, height = 194, frame_count = 2, draw_as_shadow = true, direction_count = 64, shift = util.by_pixel(17.75, 7), max_advance = 1, stripes = util.multiplystripes(2, { { filename = "__base__/graphics/entity/tank/hr-tank-base-shadow-1.png", width_in_frames = 1, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-shadow-2.png", width_in_frames = 1, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-shadow-3.png", width_in_frames = 1, height_in_frames = 16 }, { filename = "__base__/graphics/entity/tank/hr-tank-base-shadow-4.png", width_in_frames = 1, height_in_frames = 16 } }), scale = 1 } } } mf.turret_animation = { layers = { { filename = "__base__/graphics/entity/tank/hr-tank-turret.png", priority = "low", line_length = 8, width = 179, height = 132, frame_count = 1, direction_count = 64, shift = util.by_pixel(-4.75, -50), animation_speed = 8, scale = 1 }, { filename = "__base__/graphics/entity/tank/hr-tank-turret-mask.png", priority = "low", line_length = 8, width = 72, height = 66, frame_count = 1, direction_count = 64, shift = util.by_pixel(-5, -50), scale = 1 }, { filename = "__base__/graphics/entity/tank/hr-tank-turret-shadow.png", priority = "low", line_length = 8, width = 193, height = 134, frame_count = 1, draw_as_shadow = true, direction_count = 64, shift = util.by_pixel(51.25, 6.5), scale = 1 } } } data:extend{mf} -- Create Mobile Factory Item -- local mfI = {} mfI.type = "item-with-entity-data" mfI.name = "MobileFactory" mfI.icon = "__Mobile_Factory_Graphics__/graphics/mobile- factory/tank.png" mfI.icon_size = 32 mfI.place_result = "MobileFactory" mfI.subgroup = "MobileFactory" mfI.order = "a" mfI.stack_size = 1 data:extend{mfI} -- Create the Mobile Factory Recipe -- local mfR = {} mfR.type = "recipe" mfR.name = "MobileFactory" mfR.energy_required = 10 mfR.ingredients = { {"DimensionalCircuit", 25}, {"MachineFrame2", 6} } mfR.result = "MobileFactory" data:extend{mfR} function createNewMF(name, color, size, order, icon) local nMFE = table.deepcopy(data.raw.car.MobileFactory) nMFE.name = name nMFE.order = order nMFE.minable = {mining_time = 1.5, result = name} nMFE.animation.layers[2].tint = color nMFE.turret_animation.layers[2].tint = color nMFE.animation.layers[1].scale = size nMFE.turret_animation.layers[1].scale = size nMFE.animation.layers[2].scale = size nMFE.turret_animation.layers[2].scale = size nMFE.animation.layers[3].scale = size nMFE.turret_animation.layers[3].scale = size nMFE.turret_animation.layers[1].shift = util.by_pixel(-4.75, -50*size) nMFE.turret_animation.layers[2].shift = util.by_pixel(-5, -50*size) nMFE.turret_animation.layers[3].shift = util.by_pixel(51.25, 6.5*size) nMFE.collision_box = {{-2*size, -3.5*size}, {1.6*size, 2.5*size}} nMFE.selection_box = nMFE.collision_box data:extend{nMFE} local nMFI = table.deepcopy(data.raw["item-with-entity-data"].MobileFactory) nMFI.name = name nMFI.order = order nMFI.icon = icon nMFI.place_result = name data:extend{nMFI} local nMFR = table.deepcopy(data.raw.recipe.MobileFactory) nMFR.name = name nMFR.result = name nMFR.enabled = false data:extend{nMFR} local nMFT = {} nMFT.name = name nMFT.type = "technology" nMFT.icon = icon nMFT.icon_size = 32 nMFT.unit = { count=1000, time=2, ingredients={ {"DimensionalSample", 1} } } nMFT.prerequisites = {"DimensionalCrystal"} nMFT.effects = {{type="unlock-recipe", recipe=name}} data:extend{nMFT} end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") util.PrecacheSound("ambient.steam01") --Extra Resources Added by DataSchmuck for the McBuild's Community include("shared.lua") DEFINE_BASECLASS("base_rd3_entity") function ENT:Initialize() BaseClass.Initialize(self) self.damaged = 0 self.venten = false self.ventoxy = false self.ventco2 = false self.venthyd = false self.ventnit = false self.ventwat = false self.venthwwat = false self.ventamount = 1000 if WireAddon ~= nil then self.WireDebugName = self.PrintName self.Inputs = Wire_CreateInputs(self, {"Vent Amount", "Expel Energy", "Vent Oxygen", "Vent Co2", "Vent Hydrogen", "Vent Nitrogen", "Leak Water", "Leak Heavy Water"}) self.Outputs = Wire_CreateOutputs(self, {"Energy", "Oxygen", "Co2", "Hydrogen", "Nitrogen", "Water", "Hvy Water", "Max Energy", "Max Oxygen", "Max Co2", "Max Hydrogen", "Max Nitrogen", "Max Water", "Max Hvy Water"}) else self.Inputs = { { Name = "Vent" } } end self.caf.custom.masschangeoverride = true end function ENT:TriggerInput(iname, value) if iname == "Expel Energy" then if value ~= 1 then self.venten = false else self.venten = true end elseif iname == "Vent Oxygen" then if value ~= 1 then self.ventoxy = false else self.ventoxy = true end elseif iname == "Vent Co2" then if value ~= 1 then self.ventco2 = false else self.ventco2 = true end elseif iname == "Vent Hydrogen" then if value ~= 1 then self.venthyd = false else self.venthyd = true end elseif iname == "Vent Nitrogen" then if value ~= 1 then self.ventnit = false else self.ventnit = true end elseif iname == "Leak Water" then if value ~= 1 then self.ventwat = false else self.ventwat = true end elseif iname == "Leak Heavy Water" then if value ~= 1 then self.venthwwat = false else self.venthwat = true end elseif iname == "Vent Amount" then if value ~= 0 then self.ventamount = math.abs(value) else self.ventamount = 1000 end end end function ENT:Damage() if self.damaged == 0 then self.damaged = 1 self:EmitSound("PhysicsCannister.ThrusterLoop") self:EmitSound("ambient.steam01") end end function ENT:Repair() BaseClass.Repair(self) self:SetColor(Color(255, 255, 255, 255)) self.damaged = 0 self:StopSound("PhysicsCannister.ThrusterLoop") self:StopSound("ambient.steam01") end function ENT:Destruct() if CAF and CAF.GetAddon("Life Support") then CAF.GetAddon("Life Support").Destruct(self, true) end end function ENT:OnRemove() BaseClass.OnRemove(self) local air = self:GetResourceAmount("oxygen") local co2 = self:GetResourceAmount("carbon dioxide") local hydrogen = self:GetResourceAmount("hydrogen") local nitrogen = self:GetResourceAmount("nitrogen") if self.environment then self.environment:Convert(-1, 0, air) self.environment:Convert(-1, 1, co2) self.environment:Convert(-1, 3, hydrogen) self.environment:Convert(-1, 2, nitrogen) end self:StopSound("PhysicsCannister.ThrusterLoop") self:StopSound("ambient.steam01") end function ENT:LeakHvyWater() local heavywater = self:GetResourceAmount("heavy water") if heavywater >= self.ventamount then self:ConsumeResource("heavy water", self.ventamount) else self:ConsumeResource("heavy water", heavywater) self:StopSound("PhysicsCannister.ThrusterLoop") --Change to a new Liquid Vent/Escaping Sound end end function ENT:VentCo2() local co2 = self:GetResourceAmount("carbon dioxide") if co2 >= self.ventamount then self:ConsumeResource("carbon dioxide", self.ventamount) if self.environment then self.environment:Convert(-1, 1, self.ventamount) end else self:ConsumeResource("carbon dioxide", co2) if self.environment then self.environment:Convert(-1, 1, co2) end self:StopSound("PhysicsCannister.ThrusterLoop") --Change to a new co2 Vent/Escaping Sound end end function ENT:VentO2() local air = self:GetResourceAmount("oxygen") if air > 0 then if air >= self.ventamount then self:ConsumeResource("oxygen", self.ventamount) if self.environment then self.environment:Convert(-1, 0, self.ventamount) end else self:ConsumeResource("oxygen", air) if self.environment then self.environment:Convert(-1, 0, air) end self:StopSound("PhysicsCannister.ThrusterLoop") end end end function ENT:VentHydrogen() local hydrogen = self:GetResourceAmount("hydrogen") if hydrogen >= self.ventamount then self:ConsumeResource("hydrogen", self.ventamount) if self.environment then self.environment:Convert(-1, 3, self.ventamount) end else self:ConsumeResource("hydrogen", hydrogen) if self.environment then self.environment:Convert(-1, 3, hydrogen) end self:StopSound("PhysicsCannister.ThrusterLoop") --Change to a new air Vent/Escaping Sound end end function ENT:VentNitrogen() local nitrogen = self:GetResourceAmount("nitrogen") if nitrogen >= self.ventamount then self:ConsumeResource("nitrogen", self.ventamount) if self.environment then self.environment:Convert(-1, 2, self.ventamount) end else self:ConsumeResource("nitrogen", nitrogen) if self.environment then self.environment:Convert(-1, 2, nitrogen) end self:StopSound("PhysicsCannister.ThrusterLoop") --Change to a new air Vent/Escaping Sound end end function ENT:ExpEnergy() local energy = self:GetResourceAmount("energy") if energy == 0 then return end local waterlevel = 0 if CAF then waterlevel = self:WaterLevel2() else waterlevel = self:WaterLevel() end if waterlevel > 0 then zapme(self:GetPos(), 1) local tmp = ents.FindInSphere(self:GetPos(), 600) for _, ply in ipairs(tmp) do --??? wont that be zaping any player in any water??? should do a dist check first and have damage based on dist if ply:IsPlayer() and ply:WaterLevel() > 0 then zapme(ply:GetPos(), 1) ply:TakeDamage(ply:WaterLevel() * energy / 100, 0) end end self.maxenergy = self:GetUnitCapacity("energy") --??? loose all energy on net when damaged and in water??? that sounds crazy to me if energy >= self.maxenergy then self:ConsumeResource("energy", self.maxenergy) else self:ConsumeResource("energy", energy) end else if energy >= self.ventamount then self:ConsumeResource("energy", self.ventamount) else self:ConsumeResource("energy", energy) end end end function ENT:LeakWater() local water = self:GetResourceAmount("water") if water == 0 then return end if water >= self.ventamount then self:ConsumeResource("water", self.ventamount) else self:ConsumeResource("water", water) self:StopSound("ambient.steam01") end end function ENT:UpdateMass() --[[local RD = CAF.GetAddon("Resource Distribution") local mul = 0.5 local div = math.Round(RD.GetNetworkCapacity(self, "carbon dioxide")/self.MAXRESOURCE) local mass = self.mass + ((RD.GetResourceAmount(self, "carbon dioxide") * mul)/div) -- self.mass = default mass + need a good multiplier local phys = self:GetPhysicsObject() if phys:IsValid() then if phys:GetMass() ~= mass then phys:SetMass(mass) phys:Wake() end end]] end function ENT:Think() if self.damaged == 1 or self.venten then self:ExpEnergy() end if self.damaged == 1 or self.ventoxy then self:VentO2() end if self.damaged == 1 or self.ventnit then self:VentNitrogen() end if self.damaged == 1 or self.venthyd then self:VentHydrogen() end if self.damaged == 1 or self.ventco2 then self:VentCo2() end if self.damaged == 1 or self.ventwat then self:LeakWater() end if self.damaged == 1 or self.venthwat then self:LeakHvyWater() end self:UpdateMass() BaseClass.Think(self) return true end function ENT:UpdateWireOutput() self:DoUpdateWireOutput("Hydrogen", "hydrogen") self:DoUpdateWireOutput("Co2", "carbon dioxide") self:DoUpdateWireOutput("Nitrogen", "nitrogen") self:DoUpdateWireOutput("Hvy Water", "heavy water") self:DoUpdateWireOutput("Oxygen", "oxygen") self:DoUpdateWireOutput("Energy", "energy") self:DoUpdateWireOutput("Water", "water") end
local _tl_compat; if (tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3 then local p, m = true, require('compat53.module'); if p then _tl_compat = m end end; local coroutine = _tl_compat and _tl_compat.coroutine or coroutine; local io = _tl_compat and _tl_compat.io or io; local ipairs = _tl_compat and _tl_compat.ipairs or ipairs; local os = _tl_compat and _tl_compat.os or os; local string = _tl_compat and _tl_compat.string or string; local table = _tl_compat and _tl_compat.table or table; local _tl_table_unpack = unpack or table.unpack local argparse = require("argparse") local tl = require("tl") local command = require("cyan.command") local common = require("cyan.tlcommon") local config = require("cyan.config") local cs = require("cyan.colorstring") local fs = require("cyan.fs") local graph = require("cyan.graph") local log = require("cyan.log") local script = require("cyan.script") local util = require("cyan.util") local ivalues = util.tab.ivalues local function exists_and_is_dir(prefix, p) if not p:exists() then log.err(string.format("%s %q does not exist", prefix, p:to_real_path())) return false elseif not p:is_directory() then log.err(string.format("%s %q is not a directory", prefix, p:to_real_path())) return false end return true end local function report_dep_errors(env, source_dir) local ok = true for name in ivalues(env.loaded_order) do local res = env.loaded[name] if not fs.path.new(res.filename, true):is_in(source_dir) then if (res.syntax_errors and #res.syntax_errors > 0) or #res.type_errors > 0 then if (res.syntax_errors and #res.syntax_errors > 0) then common.report_errors(log.err, res.syntax_errors, res.filename, "(Out of project) syntax error") end if #res.type_errors > 0 then common.report_errors(log.err, res.type_errors, res.filename, "(Out of project) type error") end ok = false end end end return ok end local function build(args, loaded_config, starting_dir) if not loaded_config then log.err(config.filename, " not found") return 1 end local source_dir = fs.path.new(loaded_config.source_dir or "./") if not exists_and_is_dir("Source dir", source_dir) then return 1 end local build_dir = fs.path.new(loaded_config.build_dir or "./") if not build_dir:exists() then local succ, err = build_dir:mkdir() if not succ then log.err(string.format("Failed to create build dir %q: %s", build_dir:to_real_path(), err)) return 1 end elseif not build_dir:is_directory() then log.err(string.format("Build dir %q is not a directory", build_dir:to_real_path())) return 1 end local env, env_err = common.init_env_from_config(loaded_config) if not env then log.err("Could not initialize Teal environment:\n", env_err) return 1 end if not script.emit_hook("pre") then return 1 end local include = loaded_config.include or {} local exclude = loaded_config.exclude or {} local dag, cycles = graph.scan_dir(source_dir, include, exclude) if not dag then log.err( "Circular dependency detected in the following files:\n ", _tl_table_unpack(util.tab.intersperse(cycles, "\n "))) return 1 end local exit = 0 log.debug("Built dependency graph") local function display_filename(f) return cs.highlight(cs.colors.file, f:relative_to(starting_dir)) end local function get_output_name(src) local out = src:copy() out:remove_leading(source_dir) out:prepend(build_dir) local base = fs.extension_split(out[#out]) out[#out] = base .. ".lua" return out end local function source_is_newer(src) local target = get_output_name(src) local newer if args.update_all then newer = true else local in_t, out_t = src:mod_time(), target:mod_time() or -1 newer = in_t > out_t end if newer then log.extra("Source ", display_filename(src), " is newer than target (", display_filename(target), ")") if not script.emit_hook("file_updated", src:copy()) then exit = 1 coroutine.yield() end end return newer end if not coroutine.wrap(function() dag:mark_each(source_is_newer) return true end)() then return exit end local to_write = {} local function process_node(n, compile) local path = n.input:to_real_path() local out = get_output_name(n.input) n.output = out local parsed = common.parse_file(path) if #parsed.errs > 0 then common.report_errors(log.err, parsed.errs, path, "syntax error") exit = 1 return end local result = common.type_check_ast(parsed.ast, { filename = path, env = env, }) if not common.report_result(result, loaded_config) then exit = 1 return end log.info("Type checked ", display_filename(n.input)) if compile then local ok, err = n.output:mk_parent_dirs() if ok then table.insert(to_write, { n, parsed.ast }) else log.err("Unable to create parent dirs to ", display_filename(n.output), ":", err) exit = 1 end end end for n in dag:marked_nodes("typecheck") do process_node(n, false) end if exit ~= 0 then return exit end for n in dag:marked_nodes("compile") do process_node(n, true) end if exit ~= 0 then report_dep_errors(env, source_dir) return exit end if args.check_only then return exit end for node_ast in ivalues(to_write) do local n, ast = node_ast[1], node_ast[2] local fh, err = io.open(n.output:to_real_path(), "w") if not fh then log.err("Error opening file ", display_filename(n.output), ": ", err) exit = 1 else fh:write(common.compile_ast(ast)) fh:close() log.info("Wrote ", display_filename(n.output)) end end if #to_write > 0 then if not script.emit_hook("post") then return 1 end end if build_dir ~= source_dir then local expected_files = {} for n in dag:nodes() do log.debug(n.input, " -> ", get_output_name(n.input)) local p = get_output_name(n.input) p:remove_leading(build_dir) expected_files[p:tostring()] = true end local unexpected_files = {} for p in fs.scan_dir(build_dir) do log.debug("checking if ", p:tostring(), " is expected...") if expected_files[p:tostring()] then log.debug(" yes") else log.debug(" no") table.insert(unexpected_files, p) end end if #unexpected_files > 0 then if args.prune then for _, p in ipairs(unexpected_files) do local file = build_dir .. p local disp = display_filename(file) local real = file:relative_to(fs.cwd()) local ok, err = os.remove(real) if ok then log.info("Pruned file ", disp) else log.err("Unable to prune file '", disp, "': ", err) end end else local strs = {} for _, p in ipairs(unexpected_files) do table.insert(strs, "\n ") table.insert(strs, display_filename(p)) end table.insert(strs, "\nhint: use `cyan build --prune` to automatically delete these files") log.warn("Unexpected files in build directory:", _tl_table_unpack(strs)) end end end if not report_dep_errors(env, source_dir) then log.warn("There were errors in out of project files. Your project may not work as expected.") end return exit end command.new({ name = "build", description = [[Build a project based on tlconfig.lua.]], exec = build, argparse = function(cmd) cmd:flag("-u --update-all", "Force recompilation of every file in your project.") cmd:flag("-c --check-only", "Only type check files.") cmd:flag("-p --prune", "Remove any unexpected files in the build directory.") end, script_hooks = { "pre", "post", "file_updated" }, })
-- globals netSSID="SSID" netPWD="SSID-NET-PASSWORD" httpPort=80 -- locals local connReset=true -- functions function createHttpServer(httpRequestsHandler) print("Creating HTTP server at port " .. httpPort) srv=net.createServer(net.TCP) srv:listen(httpPort, httpRequestsHandler) end function autoConnectWifiSAP() if wifi.sta.getip() == nil then if not connReset then print("Connection to " .. netSSID .. ": OFFLINE") print("Attempting reconnection... please wait.") end wifi.setmode(wifi.STATION) wifi.sta.config(netSSID, netPWD) print("Connecting to " .. netSSID .. "...") connReset=true else if connReset then print("Connection to " .. netSSID .. ": ESTABLISHED") print("MCU assigned IP Address: " .. wifi.sta.getip()) connReset=false end end end
local m_template = nil function CreateProfilesForm() local form=createWidget(nil, "configProfilesForm", "Form", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 600, 280, 800, 450) priority(form, 5500) hide(form) local panel=createWidget(form, nil, "Panel") setLocaleText(createWidget(form, "configProfilesHeader", "TextView", WIDGET_ALIGN_CENTER, nil, 250, 20, nil, 20)) setText(createWidget(form, "closeButton", "Button", WIDGET_ALIGN_HIGH, WIDGET_ALIGN_LOW, 20, 20, 20, 20), "x") createWidget(form, "container", "ScrollableContainer", nil, nil, 560, 150, 20, 42) setLocaleText(createWidget(form, "saveAsProfileButton", "Button", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 330, 25, 20, 200)) setLocaleText(createWidget(form, "importProfileButton", "Button", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 330, 25, 20, 230)) createWidget(form, "EditLine1", "EditLine", nil, nil, 210, 25, 360, 200) DnD.Init(form, panel, true) return form end
local uv = require "lluv" local ut = require "lluv.utils" local spawn = require "spylog.spawn".spawn_ex local log = require "spylog.log" local Args = require "spylog.args" local path = require "path" local environ = require "environ.process" local MAX_LINE_LENGTH = 4096 local function build_cb(buffer, cb) return function(data) buffer:append(data) while true do local str = buffer:read("*l") if not str then break end cb(str) end end end local function process_monitor(cmd, opt, cb) local opt = opt or {} local proto = 'process' local args, tail = opt.args if args then if type(args) == 'string' then args, tail = Args.split(args) if not args then log.error("[process][%s] Can not parse argument string: %s", cmd, opt.args) return false end end else local tmp_cmd = cmd cmd, args, tail = Args.split_command(cmd) if not cmd then log.error("[process] Can not parse command string: %s", cmd) end end cmd = path.normalize(cmd) local source_name = opt.__name or (cmd and path.basename(cmd)) or 'unknown' local log_header = '[' .. proto .. ']' ..'[' .. source_name .. ']' if tail and #tail > 0 then log.warning("%s Unused command arguments: %q", log_header, tail) end local env if opt.env then env = {} for k, v in pairs(opt.env) do if type(k) == 'number' then env[#env + 1] = v .. '=' .. environ.getenv(v) else env[#env + 1] = k .. '=' .. environ.expand(v) end end end local eol if type(opt.eol) == 'table' then eol = opt.eol else eol = {opt.eol} end local restart = opt.restart or 10 if not tonumber(restart) then log.warning("%s restart timeout have to be a number but got: %q", log_header, tostring(restart)) restart = 10 end restart = tonumber(restart) if restart < 1 then log.warning("%s restart timout have to be greater than 1 but got: %d", log_header, restart) end restart = restart * 1000 local max_line = opt and opt.max_line or MAX_LINE_LENGTH if not tonumber(max_line) then log.warning("%s max_line option have to be a number but got: %q", log_header, tostring(restart)) max_line = MAX_LINE_LENGTH end max_line = tonumber(max_line) if max_line < MAX_LINE_LENGTH then log.warning("%s too short `max_line` option: %d, use default one: %d", log_header, max_line, MAX_LINE_LENGTH) end local monitor = {} if type(opt.monitor) == 'string' then monitor[opt.monitor] = 'true' elseif type(opt.monitor) == 'table' then for i = 1, #opt.monitor do monitor[ opt.monitor[i] ] = true end end if not (monitor.sdtout or monitor.sdterr) then monitor.stdout = true end local stdout_buffer, on_stdout, stderr_buffer, on_stderr if monitor.stdout then stdout_buffer = ut.Buffer.new(eol[1], eol[2]) on_stdout = build_cb(stdout_buffer, cb) end if monitor.stderr then stderr_buffer = ut.Buffer.new(eol[1], eol[2]) on_stderr = build_cb(stderr_buffer, cb) end local restart_timer = uv.timer() local function start() log.info('%s creating process: %s %s', log_header, cmd, (args and table.concat(args, ' ') or '')) if stdout_buffer then stdout_buffer:reset() end if stderr_buffer then stderr_buffer:reset() end local pid local process, err = spawn(cmd, args, env, nil, function(typ, err, status, signal) if typ == 'exit' then restart_timer:again(restart) log.warning('%s process with pid %s exit %s; status: %s; signal: %s', log_header, tostring(pid), tostring(err), tostring(status), tostring(signal)) end end, on_stdout, on_stderr ) if not process then log.error('%s can not spawn process: %s', log_header, tostring(err)) restart_timer:again(restart) end pid = err log.info('%s created process with pid %s', log_header, tostring(pid)) end restart_timer:start(function(self) self:stop() start() end) end local function process_filter(filter, t) return filter.match(t) end return { monitor = process_monitor; filter = process_filter; }
local waterIds = {493, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 7236, 10499, 15401, 15402} local lootTrash = {2234, 2238, 2376, 2509, 2667} local lootCommon = {2152, 2167, 2168, 2669, 7588, 7589} local lootRare = {2143, 2146, 2149, 7158, 7159} local lootVeryRare = {7632, 7633, 10220} local useWorms = true function onUse(player, item, fromPosition, target, toPosition, isHotkey) if not isInArray(waterIds, target.itemid) then return false end local targetId = target.itemid if targetId == 10499 then local owner = target:getAttribute(ITEM_ATTRIBUTE_CORPSEOWNER) if owner ~= 0 and owner ~= player.uid then player:sendTextMessage(MESSAGE_STATUS_SMALL, "You are not the owner.") return true end toPosition:sendMagicEffect(CONST_ME_WATERSPLASH) target:remove() local rareChance = math.random(100) if rareChance == 1 then player:addItem(lootVeryRare[math.random(#lootVeryRare)], 1) elseif rareChance <= 3 then player:addItem(lootRare[math.random(#lootRare)], 1) elseif rareChance <= 10 then player:addItem(lootCommon[math.random(#lootCommon)], 1) else player:addItem(lootTrash[math.random(#lootTrash)], 1) end return true end if targetId ~= 7236 then toPosition:sendMagicEffect(CONST_ME_LOSEENERGY) end if targetId == 493 or targetId == 15402 then return true end player:addSkillTries(SKILL_FISHING, 1) if math.random(100) <= math.min(math.max(10 + (player:getEffectiveSkillLevel(SKILL_FISHING) - 10) * 0.597, 10), 50) then if useWorms and not player:removeItem("worm", 1) then return true end if targetId == 15401 then target:transform(targetId + 1) target:decay() if math.random(100) >= 97 then player:addItem(15405, 1) return true end elseif targetId == 7236 then target:transform(targetId + 1) target:decay() local rareChance = math.random(100) if rareChance == 1 then player:addItem(7158, 1) return true elseif rareChance <= 4 then player:addItem(2669, 1) return true elseif rareChance <= 10 then player:addItem(7159, 1) return true end end player:addItem("fish", 1) end return true end
require 'nngraph' require 'cunn' require 'cudnn' require 'hdf5' require 'image' require 'optim' require 'paths' local vis = dofile('../codes_lua/vis.lua') local matio = require 'matio' local test_ind = matio.load('../data_release/benchmark/ind.mat','test_ind'):view(-1) local test_set_pair_ind = matio.load('../data_release/benchmark/ind.mat','test_set_pair_ind'):view(-1) local dispSurrogate = dofile('../codes_lua/dispSurrogate.lua') local disp = require 'display' local getNet = dofile('../codes_lua/getNet.lua') torch.setdefaulttensortype('torch.FloatTensor') -- Randomly shuffle local randperm = torch.randperm(test_ind:size(1)) for i = 1, test_ind:size(1) do test_ind[i] = test_ind[randperm[i]] test_set_pair_ind[i] = test_set_pair_ind[randperm[i]] end -- If you want to get the whole test set results on the benchmark, please comment all the lines in the following block, as well as the lines below the `Visualize' label. -------------------------- Visualization at your choice ---------------------------- local num_to_show = 64 -- Please note that now the second stage is pix2pix, and hence it is not dependent to language inputs and noise. -- Unconment the following two lines to condition only on the same original person. -- local selected_original_person_id = test_ind[torch.randperm(test_ind:size(1)):narrow(1,1,1)[1]] -- for i = 1, num_to_show do test_ind[i] = selected_original_person_id; end -- Uncomment the following two lines to condition only on the same language specification. -- local selected_text_provider_id = test_set_pair_ind[torch.randperm(test_set_pair_ind:size(1)):narrow(1,1,1)[1]] -- for i = 1, num_to_show do test_set_pair_ind[i] = selected_text_provider_id; end test_ind = test_ind[{{1,num_to_show}}]; test_set_pair_ind = test_set_pair_ind[{{1,num_to_show}}] ------------------------------------------------------------------------------------ -- Loading test phase inputs local lr = matio.load('../data_release/test_phase_inputs/sr1_8.mat','d') lr = lr:permute(4,3,1,2) lr = lr:contiguous() local text = matio.load('../data_release/test_phase_inputs/encode_hn2_rnn_100_2_full.mat', 'hn2') text = text:contiguous() local h5file = hdf5.open('../data_release/test_phase_inputs/G2.h5','r') local ih = h5file:read('/ih'):all() -- the original image is the required input ih = ih:permute(1,2,4,3) local b_ = h5file:read('/b_'):all() -- we assume a state-of-the-art segmentation network can get good human parsing results b_ = b_:permute(1,2,4,3) local ih_mean = h5file:read('/ih_mean'):all() ih_mean = ih_mean:view(1,3,128,128) ih_mean = ih_mean:permute(1,2,4,3) h5file:close() -- Stage 1 network construction local testConf = {} testConf.n_map_all = 7 testConf.n_z = 80 testConf.nt_input = 100 testConf.n_condition = 4 testConf.disp_win_id = 50 testConf.win_size = 128 testConf.lr_win_size = 8 testConf.nc = 3 testConf.n_condition_2 = 3 local a = torch.load('./off_the_shelf_model/sr1.t7') G1 = a.G a = nil -- Pickout only the test data local lr_tmp = lr:clone() local text_tmp = text:clone() lr = torch.Tensor(test_ind:size(1), testConf.n_condition, testConf.lr_win_size, testConf.lr_win_size) text = torch.Tensor(test_ind:size(1), testConf.nt_input, 1,1) local test_set_ih = torch.Tensor(test_ind:size(1), ih:size(2), testConf.win_size, testConf.win_size) local test_set_b_ = torch.Tensor(test_ind:size(1), 1, testConf.win_size, testConf.win_size) local text_provider = torch.Tensor(test_ind:size(1), ih:size(2), testConf.win_size, testConf.win_size) for i = 1, test_ind:size(1) do lr[{{i},{},{},{}}] = lr_tmp[{{test_ind[i]},{},{},{}}] text[{{i},{},{},{}}] = text_tmp[{{test_set_pair_ind[i]},{}}]:view(1, testConf.nt_input, 1, 1) test_set_ih[{{i},{},{},{}}] = ih[{{test_ind[i]},{},{},{}}] test_set_b_[{{i},{},{},{}}] = b_[{{test_ind[i]},{},{},{}}] text_provider[{{i},{},{},{}}] = ih[{{test_set_pair_ind[i]},{},{},{}}] end lr_tmp = nil text_tmp = nil ih = nil b_ = nil -- Containers for Stage 1 local condition = torch.Tensor(1, testConf.n_condition, testConf.lr_win_size, testConf.lr_win_size) condition = condition:cuda() local noise = torch.Tensor(1, testConf.n_z, 1, 1) noise = noise:cuda() local encode = torch.Tensor(1, testConf.nt_input, 1, 1) encode = encode:cuda() local out1 = torch.Tensor(test_set_ih:size(1), testConf.n_map_all, testConf.win_size, testConf.win_size) -- Running Stage 1 for i = 1, test_set_ih:size(1) do noise:normal(0,1) condition:copy(lr[{{i},{},{},{}}]) encode:copy(text[{{i},{},{},{}}]) out1[{{i},{},{},{}}] = G1:forward{noise, encode, condition}:float() if i % 100 == 0 then print('A' .. tostring(i)) end end local kernel = image.gaussian(5,3):float():contiguous() out1_p = out1:clone() for i = 1, out1_p:size(1) do for j = 1, out1_p:size(2) do out1_p[{{i},{j},{},{}}] = image.convolve(out1[{{i},{j},{},{}}]:view(testConf.win_size, testConf.win_size), kernel, 'same'):contiguous():view(1,1,testConf.win_size, testConf.win_size) end end -- Stage 2 stuffs -- This demo's Stage 2 is the original pix2pix's re-implementation. Hence, the generated texture is high quality but cannot be controlled by the language specification and also lacking in variations. local cb = {torch.Tensor{3,2,1,1,2,3,2}, torch.Tensor{2,3,3,2,1,1,2}, torch.Tensor{1,1,2,3,3,2,2}} for i = 1,testConf.n_condition_2 do cb[i] = cb[i] * 0.25 end local H = torch.Tensor{0.0030,0.0133,0.0219,0.0133,0.0030,0.0133,0.0596,0.0983,0.0596,0.0133,0.0219,0.0983,0.1621,0.0983,0.0219,0.0133,0.0596,0.0983,0.0596,0.0133,0.0030,0.0133,0.0219,0.0133,0.0030}:view(5,5) local out1pmax _, out1pmax = torch.max(out1_p:float(), 2) out1pmax[out1pmax:eq(testConf.n_map_all)] = 0 local batch_condition = torch.Tensor(test_set_ih:size(1), testConf.n_condition_2, testConf.win_size, testConf.win_size) for i = 1,test_set_ih:size(1) do local t = out1pmax[{{i},{1},{},{}}] for j = 1,testConf.n_condition_2 do local u = torch.Tensor(1,1,testConf.win_size, testConf.win_size) for k = 1,testConf.n_map_all do u[t:eq(k%testConf.n_map_all)] = cb[j][k] end local v = image.convolve(u:squeeze():float(), H:float(), 'same'):contiguous() batch_condition[{{i},{j},{},{}}] = v:view(1,1,testConf.win_size, testConf.win_size) end end batch_condition = batch_condition - 0.5 local b = torch.load('./off_the_shelf_model/ih1_pix2pix_original.t7') local G2 = b.G condition = torch.Tensor(1, testConf.n_condition_2, testConf.win_size, testConf.win_size) condition = condition:cuda() local out2 = torch.Tensor(test_set_ih:size(1), testConf.nc, testConf.win_size, testConf.win_size) local out2_final = out2:clone() for i = 1, test_set_ih:size(1) do condition:copy(batch_condition[{{i},{},{},{}}]) out2[{{i},{},{},{}}] = G2:forward(condition):float() + ih_mean test_set_ih[{{i},{},{},{}}] = test_set_ih[{{i},{},{},{}}] + ih_mean text_provider[{{i},{},{},{}}] = text_provider[{{i},{},{},{}}] + ih_mean -- Post processing for hair + face + and balance the skin color using the median of the original region. for j = 1, testConf.nc do local t = out2[{{i},{j},{},{}}] local s = test_set_ih[{{i},{j},{},{}}] local ori_b_ = test_set_b_[{{i},{},{},{}}] local now_b_ = out1pmax[{{i},{},{},{}}] t[ori_b_:eq(1)] = s[ori_b_:eq(1)] t[ori_b_:eq(2)] = s[ori_b_:eq(2)] if ori_b_:eq(5):sum() > 0 and now_b_:eq(5):sum() > 0 then local sc5 = s[ori_b_:eq(5)]:median() t[now_b_:eq(5)] = (t[now_b_:eq(5)] + sc5[1]) / 2 end if ori_b_:eq(6):sum() > 0 and now_b_:eq(6):sum() > 0 then local sc6 = s[ori_b_:eq(6)]:median() t[now_b_:eq(6)] = (t[now_b_:eq(6)] + sc6[1]) / 2 end out2_final[{{i},{j},{},{}}] = t end if i % 100 == 0 then print('B' .. tostring(i)) end end -- Visualize engJ = matio.load('../data_release/benchmark/language_original.mat','engJ') print(string.format('Text input for the %d samples:', num_to_show)) local ss = {} for i = 1, num_to_show do local s = tostring(i) .. ': ' for j = 1, engJ[test_set_pair_ind[i]][1]:size(1) do s = s .. string.format('%c', engJ[test_set_pair_ind[i]][1][j]) end print(s) ss[i] = s end dispSurrogate(test_set_ih[{{1,num_to_show},{},{},{}}], 159, 'original') dispSurrogate(out1_p[{{1,num_to_show},{},{},{}}], 163, 'stage_1_output', 'm2c') dispSurrogate(out2_final[{{1,num_to_show},{},{},{}}], 167, 'out2_post_p2p')
brackaset_male = Creature:new { objectName = "@mob/creature_names:brackaset_male", socialGroup = "brackaset", faction = "", level = 30, chanceHit = 0.39, damageMin = 280, damageMax = 290, baseXp = 3005, baseHAM = 8500, baseHAMmax = 10300, armor = 0, resists = {130,130,120,20,20,-1,-1,-1,-1}, meatType = "meat_wild", meatAmount = 100, hideType = "hide_leathery", hideAmount = 91, boneType = "bone_mammal", boneAmount = 81, milk = 0, tamingChance = 0.25, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/brackaset_hue.iff"}, hues = { 16, 17, 18, 19, 20, 21, 22, 23 }, controlDeviceTemplate = "object/intangible/pet/brackaset_hue.iff", scale = 1.1, lootGroups = { { groups = { {group = "brackaset_common", chance = 10000000} }, lootChance = 1600000 } }, weapons = {}, conversationTemplate = "", attacks = { {"",""}, {"posturedownattack",""} } } CreatureTemplates:addCreatureTemplate(brackaset_male, "brackaset_male")