content
stringlengths
5
1.05M
local socket = require "socket" local ssl = require "ssl" --local apr = require "apr" function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function main() if tablelength(arg)==5 then cert = arg[3] local params = { mode = "client", protocol = "any", verify = "peer", options = "all", cafile = cert } local conn = socket.tcp() conn:connect(arg[1], arg[2]) conn = ssl.wrap(conn, params) conn:sni(arg[1]) local succ,err = conn:dohandshake() if succ then print("ACCEPT") else print(err) print("REJECT") end conn:close() elseif tablelength(arg) == 4 then print("UNSUPPORTED") else print(string.format( "Usage: %s <HOST> <PORT> (<CA-BUNDLE>)", arg[0] )) os.exit(1) end end main()
local character = require "src/character" --Should fail function test_pick_unknown_character() assert_error(function() character.pick('unknown', 'base') end, "Unknown character should fail") end function test_pick_unknown_costume() assert_error(function() character.pick('abed', 'unknown') end, "Unknown character should fail") end function test_pick_known_combination() character.pick('abed', 'base') end function test_load_unknown_character() assert_error(function() character.load('unknown') end, "Unknown character should fail") end function test_load_abed() local abed = character.load('abed') assert_equal(abed.name, 'abed') end function test_load_abed() local found = false for _, name in pairs(character.characters()) do if name == 'abed' then found = true end end assert_true(found, "Couldn't find Abed in characters") end function test_load_current() local character = character.current() assert_equal(character.name, 'abed') end function test_load_current() local character = character.current() character.state = 'walk' character.direction = 'left' character:reset() assert_equal(character.state, 'idle') assert_equal(character.direction, 'right') end function test_find_unrelated_costume() local c = character.findRelatedCostume('abed', 'unknown_category') assert_equal(c, 'base') end function test_find_related_costume() local c = character.findRelatedCostume('abed', 's1e7') assert_equal(c, 'batman') end
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local mod = E:GetModule('NamePlates_v1') local LSM = E.Libs.LSM --Lua functions local select, unpack = select, unpack local tinsert, tremove = tinsert, tremove local strlower, strsplit = strlower, strsplit local strmatch = strmatch --WoW API / Variables local CreateFrame = CreateFrame local UnitAura = UnitAura local UnitCanAttack = UnitCanAttack local UnitIsFriend = UnitIsFriend local UnitIsUnit = UnitIsUnit local auraCache = {} function mod:SetAura(aura, index, name, icon, count, duration, expirationTime, spellID, buffType, isStealable, isFriend) aura.icon:SetTexture(icon); aura.name = name aura.spellID = spellID aura.expirationTime = expirationTime if ( count > 1 ) then aura.count:Show(); aura.count:SetText(count); else aura.count:Hide(); end aura:SetID(index); if ( expirationTime and expirationTime ~= 0 ) then local startTime = expirationTime - duration; aura.cooldown:SetCooldown(startTime, duration); aura.cooldown:Show(); else aura.cooldown:Hide(); end if buffType == "Buffs" then if isStealable and not isFriend then aura.backdrop:SetBackdropBorderColor(237/255, 234/255, 142/255) else aura.backdrop:SetBackdropBorderColor(unpack(E.media.bordercolor)) end end aura:Show(); end function mod:HideAuraIcons(auras) for i=1, #auras.icons do auras.icons[i]:Hide() -- cancel any StyleFilterAuraWaitTimer timers if auras.icons[i].hasMinTimer then auras.icons[i].hasMinTimer:Cancel() auras.icons[i].hasMinTimer = nil end if auras.icons[i].hasMaxTimer then auras.icons[i].hasMaxTimer:Cancel() auras.icons[i].hasMaxTimer = nil end end end function mod:CheckFilter(name, caster, spellID, isFriend, isPlayer, isUnit, isBossDebuff, allowDuration, noDuration, canDispell, casterIsPlayer, ...) local friendCheck, filterName, filter, filterType, spellList, spell for i=1, select('#', ...) do filterName = select(i, ...) friendCheck = (isFriend and strmatch(filterName, "^Friendly:([^,]*)")) or (not isFriend and strmatch(filterName, "^Enemy:([^,]*)")) or nil if friendCheck ~= false then if friendCheck ~= nil and (G.unitframe.specialFilters[friendCheck] or E.global.unitframe.aurafilters[friendCheck]) then filterName = friendCheck -- this is for our filters to handle Friendly and Enemy end filter = E.global.unitframe.aurafilters[filterName] if filter then filterType = filter.type spellList = filter.spells spell = spellList and (spellList[spellID] or spellList[name]) if filterType and (filterType == 'Whitelist') and (spell and spell.enable) and allowDuration then return true elseif filterType and (filterType == 'Blacklist') and (spell and spell.enable) then return false end elseif filterName == 'Personal' and isPlayer and allowDuration then return true elseif filterName == 'nonPersonal' and (not isPlayer) and allowDuration then return true elseif filterName == 'Boss' and isBossDebuff and allowDuration then return true elseif filterName == 'CastByUnit' and (caster and isUnit) and allowDuration then return true elseif filterName == 'notCastByUnit' and (caster and not isUnit) and allowDuration then return true elseif filterName == 'Dispellable' and canDispell and allowDuration then return true elseif filterName == 'notDispellable' and (not canDispell) and allowDuration then return true elseif filterName == 'CastByNPC' and (not casterIsPlayer) and allowDuration then return true elseif filterName == 'CastByPlayers' and casterIsPlayer and allowDuration then return true elseif filterName == 'blockCastByPlayers' and casterIsPlayer then return false elseif filterName == 'blockNoDuration' and noDuration then return false elseif filterName == 'blockNonPersonal' and (not isPlayer) then return false elseif filterName == 'blockDispellable' and canDispell then return false elseif filterName == 'blockNotDispellable' and (not canDispell) then return false end end end end function mod:AuraFilter(frame, frameNum, index, buffType, minDuration, maxDuration, priority, name, texture, count, debuffType, duration, expiration, caster, isStealable, _, spellID, _, isBossDebuff, casterIsPlayer) if not name then return nil end -- checking for an aura that is not there, pass nil to break while loop local isFriend, filterCheck, isUnit, isPlayer, canDispell, allowDuration, noDuration = false noDuration = (not duration or duration == 0) allowDuration = noDuration or (duration and (duration > 0) and (maxDuration == 0 or duration <= maxDuration) and (minDuration == 0 or duration >= minDuration)) if priority ~= '' then isFriend = frame.unit and UnitIsFriend('player', frame.unit) and not UnitCanAttack('player', frame.unit) isPlayer = (caster == 'player' or caster == 'vehicle') isUnit = frame.unit and caster and UnitIsUnit(frame.unit, caster) canDispell = (buffType == 'Buffs' and isStealable) or (buffType == 'Debuffs' and debuffType and E:IsDispellableByMe(debuffType)) filterCheck = mod:CheckFilter(name, caster, spellID, isFriend, isPlayer, isUnit, isBossDebuff, allowDuration, noDuration, canDispell, casterIsPlayer, strsplit(",", priority)) else filterCheck = allowDuration and true -- Allow all auras to be shown when the filter list is empty, while obeying duration sliders end if filterCheck == true then mod:SetAura(frame[buffType].icons[frameNum], index, name, texture, count, duration, expiration, spellID, buffType, isStealable, isFriend) return true end return false end function mod:UpdateElement_Auras(frame) local hasBuffs, hasDebuffs, showAura = false, false local filterType, buffType, buffTypeLower, index, frameNum, maxAuras, minDuration, maxDuration, priority --Auras for i = 1, 2 do filterType = (i == 1 and 'HELPFUL' or 'HARMFUL') buffType = (i == 1 and 'Buffs' or 'Debuffs') buffTypeLower = strlower(buffType) index = 1; frameNum = 1; maxAuras = #frame[buffType].icons; minDuration = self.db.units[frame.UnitType][buffTypeLower].filters.minDuration maxDuration = self.db.units[frame.UnitType][buffTypeLower].filters.maxDuration priority = self.db.units[frame.UnitType][buffTypeLower].filters.priority self:HideAuraIcons(frame[buffType]) if(self.db.units[frame.UnitType][buffTypeLower].enable) then while ( frameNum <= maxAuras ) do showAura = mod:AuraFilter(frame, frameNum, index, buffType, minDuration, maxDuration, priority, UnitAura(frame.unit, index, filterType)) if showAura == nil then break -- used to break the while loop when index is over the limit of auras we have (unitaura name will pass nil) elseif showAura == true then -- has aura and passes checks if i == 1 then hasBuffs = true else hasDebuffs = true end frameNum = frameNum + 1; end index = index + 1; end end end local TopLevel = frame.HealthBar local TopOffset = ((self.db.units[frame.UnitType].showName and select(2, frame.Name:GetFont()) + 5) or 0) if(hasDebuffs) then TopOffset = TopOffset + 3 frame.Debuffs:SetPoint("BOTTOMLEFT", TopLevel, "TOPLEFT", 0, TopOffset) frame.Debuffs:SetPoint("BOTTOMRIGHT", TopLevel, "TOPRIGHT", 0, TopOffset) TopLevel = frame.Debuffs TopOffset = 3 end if(hasBuffs) then if(not hasDebuffs) then TopOffset = TopOffset + 3 end frame.Buffs:SetPoint("BOTTOMLEFT", TopLevel, "TOPLEFT", 0, TopOffset) frame.Buffs:SetPoint("BOTTOMRIGHT", TopLevel, "TOPRIGHT", 0, TopOffset) TopLevel = frame.Buffs TopOffset = 3 end if (frame.TopLevelFrame ~= TopLevel) then frame.TopLevelFrame = TopLevel frame.TopOffset = TopOffset if (self.db.classbar.enable and self.db.classbar.position ~= "BELOW") then mod:ClassBar_Update() end if (self.db.units[frame.UnitType].detection and self.db.units[frame.UnitType].detection.enable) then mod:ConfigureElement_Detection(frame) end if (self.db.units[frame.UnitType].portrait and self.db.units[frame.UnitType].portrait.enable) then mod:ConfigureElement_Portrait(frame) end end end function mod:UpdateCooldownTextPosition() if self and self.timer and self.timer.text then self.timer.text:ClearAllPoints() if mod.db.durationPosition == "TOPLEFT" then self.timer.text:Point("TOPLEFT", 1, 1) elseif mod.db.durationPosition == "BOTTOMLEFT" then self.timer.text:Point("BOTTOMLEFT", 1, 1) elseif mod.db.durationPosition == "TOPRIGHT" then self.timer.text:Point("TOPRIGHT", 1, 1) else self.timer.text:Point("CENTER", 0, 0) end end end function mod:UpdateCooldownSettings(cd) if cd and cd.CooldownSettings then cd.CooldownSettings.font = LSM:Fetch("font", self.db.font) cd.CooldownSettings.fontSize = self.db.fontSize cd.CooldownSettings.fontOutline = self.db.fontOutline if cd.timer then E:Cooldown_OnSizeChanged(cd.timer, cd:GetSize(), 'override') end end end function mod:CreateAuraIcon(parent) local aura = CreateFrame("Frame", nil, parent) self:StyleFrame(aura) aura.icon = aura:CreateTexture(nil, "OVERLAY") aura.icon:SetAllPoints() aura.icon:SetTexCoord(unpack(E.TexCoords)) aura.cooldown = CreateFrame("Cooldown", nil, aura, "CooldownFrameTemplate") aura.cooldown:SetAllPoints(aura) aura.cooldown:SetReverse(true) aura.cooldown.CooldownFontSize = 12 aura.cooldown.CooldownOverride = 'nameplates' aura.cooldown.CooldownPreHook = self.UpdateCooldownTextPosition aura.cooldown.CooldownSettings = { ['font'] = LSM:Fetch("font", self.db.font), ['fontSize'] = self.db.fontSize, ['fontOutline'] = self.db.fontOutline, } E:RegisterCooldown(aura.cooldown) aura.count = aura:CreateFontString(nil, "OVERLAY") aura.count:SetFont(LSM:Fetch("font", self.db.stackFont), self.db.stackFontSize, self.db.stackFontOutline) aura.count:Point("BOTTOMRIGHT", 1, 1) return aura end function mod:Auras_SizeChanged(width) local numAuras = #self.icons if numAuras == 0 then return end local overrideWidth = self.db.widthOverride and self.db.widthOverride > 0 and self.db.widthOverride local auraWidth = overrideWidth or (((width - E.mult * numAuras) / numAuras) - (E.PixelMode and 0 or 3)) local auraHeight = (self.db.baseHeight or 18) * (self:GetParent().HealthBar.currentScale or 1) for i=1, numAuras do self.icons[i]:SetWidth(auraWidth) self.icons[i]:SetHeight(auraHeight) end self:SetHeight(auraHeight) end function mod:UpdateAuraIcons(auras) local maxAuras = auras.db.numAuras local numCurrentAuras = #auras.icons if numCurrentAuras > maxAuras then for i = maxAuras, numCurrentAuras do tinsert(auraCache, auras.icons[i]) auras.icons[i]:Hide() auras.icons[i] = nil end end if numCurrentAuras ~= maxAuras then self.Auras_SizeChanged(auras, auras:GetWidth(), auras:GetHeight()) end local stackFont = LSM:Fetch("font", self.db.stackFont) local aurasHeight = auras.db.baseHeight or 18 for i=1, maxAuras do auras.icons[i] = auras.icons[i] or tremove(auraCache) or mod:CreateAuraIcon(auras) auras.icons[i]:SetParent(auras) auras.icons[i]:ClearAllPoints() auras.icons[i]:Hide() auras.icons[i]:SetHeight(aurasHeight) -- update stacks font on NAME_PLATE_UNIT_ADDED if auras.icons[i].count then auras.icons[i].count:SetFont(stackFont, self.db.stackFontSize, self.db.stackFontOutline) end -- update the cooldown text font defaults on NAME_PLATE_UNIT_ADDED self:UpdateCooldownSettings(auras.icons[i].cooldown) self.UpdateCooldownTextPosition(auras.icons[i].cooldown) if(auras.side == "LEFT") then if(i == 1) then auras.icons[i]:SetPoint("BOTTOMLEFT", auras, "BOTTOMLEFT") else auras.icons[i]:SetPoint("LEFT", auras.icons[i-1], "RIGHT", E.Border + E.Spacing*3, 0) end else if(i == 1) then auras.icons[i]:SetPoint("BOTTOMRIGHT", auras, "BOTTOMRIGHT") else auras.icons[i]:SetPoint("RIGHT", auras.icons[i-1], "LEFT", -(E.Border + E.Spacing*3), 0) end end end end function mod:ConstructElement_Auras(frame, side) local auras = CreateFrame("FRAME", nil, frame) auras:SetScript("OnSizeChanged", mod.Auras_SizeChanged) auras:SetHeight(18) -- this really doesn't matter auras.side = side auras.icons = {} return auras end
local M = {} M.trim = function(s) return s:gsub("%s+$", "") end return M
local gtable = require("gears.table") local awful = require("awful") local wibox = require("wibox") local widget = require("util.widgets") local beautiful = require("beautiful") local helpers = require("helpers") -- options local spacing = beautiful.tasklist_spacing or dpi(4) local align = beautiful.tasklist_align or "center" local fg = beautiful.tasklist_fg_normal or M.x.on_background local bg_normal = beautiful.tasklist_bg_normal or M.x.on_background .. M.e.dp00 local bg_focus = beautiful.tasklist_bg_focus or M.x.on_background .. M.e.dp01 local bg_urgent = beautiful.tasklist_bg_urgent or M.x.error -- remove few symbols beautiful.tasklist_plain_task_name=true local tasklist_widget = {} function tasklist_widget:buttons() local tasklist_buttons = gtable.join( awful.button({}, 1, function (c) if c == client.focus then c.minimized = true else c:emit_signal("request::activate", "tasklist", { raise = true }) end end), awful.button({}, 3, function() awful.menu.client_list({ theme = { width = 250 } }) end), awful.button({}, 4, function() awful.client.focus.byidx(1) end), awful.button({}, 5, function() awful.client.focus.byidx(-1) end)) return tasklist_buttons end function cheer_update(w, c, index) w.markup = helpers.colorize_text(w.text, M.x.error, M.t.high) if c.focus then w.markup = helpers.colorize_text(w.text, M.x.error, M.t.high) elseif c.unfocus then w.markup = helpers.colorize_text(w.text, M.x.error, M.t.medium) else w.markup = helpers.colorize_text(w.text, M.x.error, M.t.disabled) end end function tasklist_widget:select_template() if beautiful.tasklist_icon_only then return self:template_icon() else return self:template() end end function tasklist_widget:template_icon() local t = { { { id = "icon_role", forced_width = dpi(24), forced_height = dpi(24), widget = wibox.widget.imagebox }, margins = dpi(14), widget = wibox.container.margin }, id = "background_role", widget = wibox.container.background, create_callback = function(self, c, index, objects) end, update_callback = function(self, c, index, objects) end, } return t end function tasklist_widget:template() local t = { { { --nil, --{ id = "text_role", widget = wibox.widget.textbox, --}, --nil, --layout = wibox.layout.align.horizontal, }, id = "text_margin_role", forced_width = beautiful.tasklist_width or dpi(200), left = dpi(15), right = dpi(15), top = dpi(10), bottom = dpi(10), -- adjust in order to limit the name to one line widget = wibox.container.margin }, id = 'background_role', widget = wibox.container.background, create_callback = function(self, c, index, objects) --for _, w in ipairs(self:get_children()) do -- noti.info("found 1"..tostring(w)) --end --for i, o in ipairs(objects) do -- noti.info("found 2"..tostring(o)) -- noti.info("found 2"..tostring(o["window"])) --end --local w = self:get_children_by_id("text_role")[1] local w = self:get_children_by_id("text_role")[1] --self:get_children_by_id("text_role")[1].markup = "<b> ".. self:get_children_by_id("text_role")[1].text.." </b>" --w.markup = "<b> ".. w.text.." </b>" cheer_update(w, c, index) self:get_children_by_id("text_role")[1].markup = helpers.colorize_text(self:get_children_by_id("text_role")[1].text, M.x.error, M.t.disabled) --cheer_update(w, tag, index) end, update_callback = function(self, c, index, objects) local w = self:get_children_by_id("text_role")[1] --self:get_children_by_id("text_role")[1].markup = "<b> ".. self:get_children_by_id("text_role")[1].text.." </b>" --w.markup = "<b> ".. w.text.." </b>" cheer_update(w, c, index) self:get_children_by_id("text_role")[1].markup = helpers.colorize_text(self:get_children_by_id("text_role")[1].text, M.x.error, M.t.disabled) -- local w = self:get_children_by_id("text_role")[1] --cheer_update(w, tag, index) end } return t end function tasklist_widget:new(s) local widget = awful.widget.tasklist { screen = s, filter = awful.widget.tasklist.filter.currenttags, buttons = self:buttons(), style = self.style,{ --fg_normal = fg_normal, bg_normal = bg_normal or M.x.background, --fg_focus = fg_focus, bg_focus = bg_focus or M.x.background, align = align, }, widget_template = self:select_template() } return widget end return setmetatable(tasklist_widget, { __call = tasklist_widget.new, })
-- ############################### -- ## Project: MTA:Speedrace ## -- ## Name: RenderGarage ## -- ## Author: Noneatme ## -- ## Version: 1.0 ## -- ## License: See top Folder ## -- ############################### -- FUNCTIONS / METHODS -- local cFunc = {}; -- Local Functions local cSetting = {}; -- Local Settings RenderGarage = {}; RenderGarage.__index = RenderGarage; -- /////////////////////////////// -- ///// New ////// -- /////////////////////////////// function RenderGarage:New(...) local obj = setmetatable({}, {__index = self}); if obj.Constructor then obj:Constructor(...); end return obj; end -- /////////////////////////////// -- ///// Render ////// -- /////////////////////////////// function RenderGarage:Render() local interpolate; -- DOLLAR & TOKENS -- if(localPlayer:IsLoggedIn()) and (loadingScreen.state == false) then self.RenderManager:dxDrawImage(4, 721, 90, 83, "files/images/tokens.png", 0, 0, 0, tocolor(255, 255, 255, 255), true) self.RenderManager:dxDrawText(setDotsInNumber(tostring((getElementData(localPlayer, "account:Tokens") or 0))), 101, 736, 281, 794, tocolor(255, 255, 255, 255), 0.6, fontManager:GetDTFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawImage(3, 808, 87, 81, "files/images/dollar.png", 0, 0, 0, tocolor(255, 255, 255, 255), true) self.RenderManager:dxDrawText(setDotsInNumber(tostring((getElementData(localPlayer, "account:Dollar") or 0))), 99, 816, 279, 874, tocolor(255, 255, 255, 255), 0.6, fontManager:GetDTFont(), "center", "center", false, false, true, false, false) end if(self.opened) then if(self.inverted == false) then interpolate = { {self.RenderManager:interpolateBetween(0, 552, 0, 473, 552, 0, ((getTickCount()-self.startTick)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100*2)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100*3)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100*4)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100*5)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(0, 54, 0, 467, 54, 0, ((getTickCount()-self.startTick-100*6)/500), self.easingFunc)}, }; else interpolate = { {self.RenderManager:interpolateBetween(473, 552, 0, 0, 552, 0, ((getTickCount()-self.startTick)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100*2)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100*3)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100*4)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100*5)/500), self.easingFunc)}, {self.RenderManager:interpolateBetween(467, 54, 0, 0, 54, 0, ((getTickCount()-self.startTick-100*6)/500), self.easingFunc)}, }; end if(self.renderedPage == "main") then self.RenderManager:dxDrawText("Save House", 0, 110, 471, 160, tocolor(255, 255, 255, 255), 0.8, fontManager:GetNFSFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawRectangle(0, 163, interpolate[1][1], interpolate[1][2], tocolor(0, 0, 0, 117), true) local color = tocolor(0, 255, 255, 133); if(getElementData(self.pgMain.btn1, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 193, interpolate[2][1], interpolate[2][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 155, 133); if(getElementData(self.pgMain.btn2, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 257, interpolate[3][1], interpolate[3][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 55, 133); if(getElementData(self.pgMain.btn3, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 321, interpolate[4][1], interpolate[4][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(55, 255, 0, 133); if(getElementData(self.pgMain.btn4, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 386, interpolate[5][1], interpolate[5][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(155, 255, 0, 133); if(getElementData(self.pgMain.btn5, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 654, interpolate[6][1], interpolate[6][2], "files/images/aero-title.png", 0, 0, 0, color, true) self.RenderManager:dxDrawText("Enter World", 0, 193, interpolate[2][1], interpolate[2][2]+193, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Modify Car(s)", 0, 257, interpolate[3][1], interpolate[3][2]+257, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Settings", 0, 321, interpolate[4][1], interpolate[4][2]+321, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Bonus Settings", 0, 386, interpolate[5][1], interpolate[5][2]+386, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Exit Game", 0, 654, interpolate[6][1], interpolate[6][2]+654, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) elseif(self.renderedPage == "modcars") then self.RenderManager:dxDrawText("Modify Car(s)", 0, 110, 471, 160, tocolor(255, 255, 255, 255), 0.8, fontManager:GetNFSFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawRectangle(0, 163, interpolate[1][1], interpolate[1][2], tocolor(0, 0, 0, 117), true) local color = tocolor(0, 255, 255, 133); if(getElementData(self.pgModCars.btn1, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 193, interpolate[2][1], interpolate[2][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 155, 133); if(getElementData(self.pgModCars.btn2, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 257, interpolate[3][1], interpolate[3][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 55, 133); if(getElementData(self.pgModCars.btn3, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 321, interpolate[4][1], interpolate[4][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(155, 255, 0, 133); if(getElementData(self.pgModCars.btn4, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 654, interpolate[6][1], interpolate[6][2], "files/images/aero-title.png", 0, 0, 0, color, true) -- TEXT -- self.RenderManager:dxDrawText("Purchase cars", 0, 193, interpolate[2][1], interpolate[2][2]+193, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Select/sell cars", 0, 257, interpolate[3][1], interpolate[3][2]+257, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Tune car", 0, 321, interpolate[4][1], interpolate[4][2]+321, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Back", 0, 654, interpolate[6][1], interpolate[6][2]+654, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) elseif(self.renderedPage == "tunecar") then self.RenderManager:dxDrawText("Tune Car", 0, 110, 471, 160, tocolor(255, 255, 255, 255), 0.8, fontManager:GetNFSFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawRectangle(0, 163, interpolate[1][1], interpolate[1][2], tocolor(0, 0, 0, 117), true) local color = tocolor(0, 255, 255, 133); if(getElementData(self.pgTuneCars.btn1, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 193, interpolate[2][1], interpolate[2][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 155, 133); if(getElementData(self.pgTuneCars.btn2, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 257, interpolate[3][1], interpolate[3][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 55, 133); if(getElementData(self.pgTuneCars.btn3, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 321, interpolate[4][1], interpolate[4][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(155, 255, 0, 133); if(getElementData(self.pgTuneCars.btn4, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 654, interpolate[6][1], interpolate[6][2], "files/images/aero-title.png", 0, 0, 0, color, true) -- TEXT -- self.RenderManager:dxDrawText("Tuning Workshop", 0, 193, interpolate[2][1], interpolate[2][2]+193, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Skill Workshop", 0, 257, interpolate[3][1], interpolate[3][2]+257, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Paint Workshop", 0, 321, interpolate[4][1], interpolate[4][2]+321, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Back", 0, 654, interpolate[6][1], interpolate[6][2]+654, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) elseif(self.renderedPage == "settings") then self.RenderManager:dxDrawText("Settings", 0, 110, 471, 160, tocolor(255, 255, 255, 255), 0.8, fontManager:GetNFSFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawRectangle(0, 163, interpolate[1][1], interpolate[1][2], tocolor(0, 0, 0, 117), true) local color = tocolor(0, 255, 255, 133); if(getElementData(self.pgSettings.btn1, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 193, interpolate[2][1], interpolate[2][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 155, 133); if(getElementData(self.pgSettings.btn2, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 257, interpolate[3][1], interpolate[3][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 55, 133); if(getElementData(self.pgSettings.btn3, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 321, interpolate[4][1], interpolate[4][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(155, 255, 0, 133); if(getElementData(self.pgSettings.btn4, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 654, interpolate[6][1], interpolate[6][2], "files/images/aero-title.png", 0, 0, 0, color, true) -- TEXT -- self.RenderManager:dxDrawText("Audio Settings", 0, 193, interpolate[2][1], interpolate[2][2]+193, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Gameplay Settings", 0, 257, interpolate[3][1], interpolate[3][2]+257, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Shaders", 0, 321, interpolate[4][1], interpolate[4][2]+321, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Back", 0, 654, interpolate[6][1], interpolate[6][2]+654, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) elseif(self.renderedPage == "bonus") then self.RenderManager:dxDrawText("Bonus Settings", 0, 110, 471, 160, tocolor(255, 255, 255, 255), 0.8, fontManager:GetNFSFont(), "center", "center", false, false, true, false, false) self.RenderManager:dxDrawRectangle(0, 163, interpolate[1][1], interpolate[1][2], tocolor(0, 0, 0, 117), true) local color = tocolor(0, 255, 255, 133); if(getElementData(self.pgBonus.btn1, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 193, interpolate[2][1], interpolate[2][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 155, 133); if(getElementData(self.pgBonus.btn2, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 257, interpolate[3][1], interpolate[3][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(0, 255, 55, 133); if(getElementData(self.pgBonus.btn3, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 321, interpolate[4][1], interpolate[4][2], "files/images/aero-title.png", 0, 0, 0, color, true) color = tocolor(155, 255, 0, 133); if(getElementData(self.pgBonus.btn4, "hover")) then color = tocolor(255, 255, 255, 133); end self.RenderManager:dxDrawImage(0, 654, interpolate[6][1], interpolate[6][2], "files/images/aero-title.png", 0, 0, 0, color, true) -- TEXT -- self.RenderManager:dxDrawText("Reedem Code", 0, 193, interpolate[2][1], interpolate[2][2]+193, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Show Credits", 0, 257, interpolate[3][1], interpolate[3][2]+257, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Server License", 0, 321, interpolate[4][1], interpolate[4][2]+321, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) self.RenderManager:dxDrawText("Back", 0, 654, interpolate[6][1], interpolate[6][2]+654, tocolor(255, 255, 255, 255), 0.8, fontManager:GetDTFont(), "center", "center", true, false, true, false, false) end end end -- /////////////////////////////// -- ///// TriggerEnabled ////// -- /////////////////////////////// function RenderGarage:OpenPage(page) self:DisableGui(); if (isTimer(self.waitOpTimer)) then killTimer(self.waitOpTimer); -- Anti Bug end if(self.opened == false) then self.opened = true; -- Start einschub self.renderedPage = page; self.startTick = getTickCount(); self.inverted = false; self.waitOpTimer = setTimer(self.enableGuiFunction, 1000, 1, page); else --self:DisableGui(self.renderedPage); self.inverted = true; self.easingFunc = "InQuad"; self.startTick = getTickCount(); self.waitOpTimer = setTimer(function() self.opened = true; -- Start einschub self.renderedPage = page; self.startTick = getTickCount(); self.inverted = false; self.waitOpTimer = setTimer(self.enableGuiFunction, 1000, 1, page); end, 1200, 1) end if(page == "main") then local x, y, z, x2, y2, z2 = cameraMover:GetCamPos() cameraMover:SmoothMoveCamera(x, y, z, x2, y2, z2, 945.00122070313, 2057.3049316406, 12.775808334351, 852.44494628906, 2094.228515625, 4.4096307754517, 4000) elseif(page == "tunecar") then local x, y, z, x2, y2, z2 = cameraMover:GetCamPos(); cameraMover:SmoothMoveCamera(x, y, z, x2, y2, z2, 930.05505371094, 2073.896484375, 11.479271888733, 964.84899902344, 1980.1491699219, 12.389189720154, 3000); end end -- /////////////////////////////// -- ///// DisableGui ////// -- /////////////////////////////// function RenderGarage:DisableGui() for index, pages in pairs(self.guiPages) do for index2, guiEle in pairs(pages) do guiSetEnabled(guiEle, false); guiMoveToBack(guiEle); guiSetAlpha(guiEle, 0); end end end -- /////////////////////////////// -- ///// EnableGui ////// -- /////////////////////////////// function RenderGarage:EnableGui(page) if(page == "main") then for index2, guiEle in pairs(self.pgMain) do guiSetEnabled(guiEle, true); guiBringToFront(guiEle); end end if(page == "modcars") then for index2, guiEle in pairs(self.pgModCars) do guiSetEnabled(guiEle, true); guiBringToFront(guiEle); end end if(page == "settings") then for index2, guiEle in pairs(self.pgSettings) do guiSetEnabled(guiEle, true); guiBringToFront(guiEle); end end if(page == "bonus") then for index2, guiEle in pairs(self.pgBonus) do guiSetEnabled(guiEle, true); guiBringToFront(guiEle); end end if(page == "tunecar") then for index2, guiEle in pairs(self.pgTuneCars) do guiSetEnabled(guiEle, true); guiBringToFront(guiEle); end end end -- /////////////////////////////// -- ///// BuildGui ////// -- /////////////////////////////// function RenderGarage:BuildGui() -- PAGE MAIN -- self.pgMain.btn1 = self.RenderManager:guiCreateButton(0, 193, 467, 54, "", false, nil, true, true); self.pgMain.btn2 = self.RenderManager:guiCreateButton(0, 257, 467, 54, "", false, nil, true, true); self.pgMain.btn3 = self.RenderManager:guiCreateButton(0, 321, 467, 54, "", false, nil, true, true); self.pgMain.btn4 = self.RenderManager:guiCreateButton(0, 386, 467, 54, "", false, nil, true, true); --654 self.pgMain.btn5 = self.RenderManager:guiCreateButton(0, 654, 467, 54, "exit", false, nil, true, true); --654 -- PAGE MOD CARS -- self.pgModCars.btn1 = self.RenderManager:guiCreateButton(0, 193, 467, 54, "", false, nil, true, true); self.pgModCars.btn2 = self.RenderManager:guiCreateButton(0, 257, 467, 54, "", false, nil, true, true); self.pgModCars.btn3 = self.RenderManager:guiCreateButton(0, 321, 467, 54, "", false, nil, true, true); self.pgModCars.btn4 = self.RenderManager:guiCreateButton(0, 654, 467, 54, "back", false, nil, true, true); --654 -- PAGE Tune CARS -- self.pgTuneCars.btn1 = self.RenderManager:guiCreateButton(0, 193, 467, 54, "", false, nil, true, true); self.pgTuneCars.btn2 = self.RenderManager:guiCreateButton(0, 257, 467, 54, "", false, nil, true, true); self.pgTuneCars.btn3 = self.RenderManager:guiCreateButton(0, 321, 467, 54, "", false, nil, true, true); self.pgTuneCars.btn4 = self.RenderManager:guiCreateButton(0, 654, 467, 54, "back", false, nil, true, true); --654 -- SETTINGS -- self.pgSettings.btn1 = self.RenderManager:guiCreateButton(0, 193, 467, 54, "", false, nil, true, true); self.pgSettings.btn2 = self.RenderManager:guiCreateButton(0, 257, 467, 54, "", false, nil, true, true); self.pgSettings.btn3 = self.RenderManager:guiCreateButton(0, 321, 467, 54, "", false, nil, true, true); self.pgSettings.btn4 = self.RenderManager:guiCreateButton(0, 654, 467, 54, "back", false, nil, true, true); --654 -- BONUS SETTINGS -- self.pgBonus.btn1 = self.RenderManager:guiCreateButton(0, 193, 467, 54, "", false, nil, true, true); self.pgBonus.btn2 = self.RenderManager:guiCreateButton(0, 257, 467, 54, "", false, nil, true, true); self.pgBonus.btn3 = self.RenderManager:guiCreateButton(0, 321, 467, 54, "", false, nil, true, true); self.pgBonus.btn4 = self.RenderManager:guiCreateButton(0, 654, 467, 54, "back", false, nil, true, true); end -- /////////////////////////////// -- ///// DestroyGui ////// -- /////////////////////////////// function RenderGarage:DestroyGui() for index, pages in pairs(self.guiPages) do for index2, guiEle in pairs(pages) do destroyElement(guiEle); end end end -- /////////////////////////////// -- ///// HideGui ////// -- /////////////////////////////// function RenderGarage:Hide() for index, pages in pairs(self.guiPages) do for index2, guiEle in pairs(pages) do guiSetEnabled(guiEle, false); guiSetAlpha(guiEle, 0); end end self.inverted = true; self.easingFunc = "InQuad"; self.startTick = getTickCount(); setTimer(function() self.opened = false; end, 2000, 1) end -- /////////////////////////////// -- ///// Show ////// -- /////////////////////////////// function RenderGarage:Show() self:EnableGui(self.renderedPage); end -- /////////////////////////////// -- ///// Constructor ////// -- /////////////////////////////// function RenderGarage:Constructor(...) self.renderFunc = function() self:Render(); end self.enableGuiFunction = function(id) self:EnableGui(id); end self.RenderManager = RenderManager:New(aesx, aesy); self.easingFunc = "OutQuad"; self.opened = false; -- GUIS -- self.pgMain = {}; self.pgModCars = {}; self.pgSettings = {}; self.pgBonus = {}; self.pgTuneCars = {}; self:BuildGui(); self.guiPages = {self.pgMain, self.pgModCars, self.pgSettings, self.pgBonus, self.pgTuneCars}; self:DisableGui(); -- EVENTS -- addEventHandler("onClientRender", getRootElement(), self.renderFunc); logger:OutputInfo("[CALLING] RenderGarage: Constructor"); end -- /////////////////////////////// -- ///// Destructor ////// -- /////////////////////////////// function RenderGarage:Destructor(...) self:DestroyGui(); removeEventHandler("onClientRender", getRootElement(), self.renderFunc); end -- EVENT HANDLER --
local err = require("aspect.err") local compiler_error = err.compiler_error local quote_string = require("pl.stringx").quote_string local config = require("aspect.config") local utils = require("aspect.utils") local reserved_words = config.compiler.reserved_words local loop_keys = config.loop.keys local tag_type = config.compiler.tag_type local import_type = config.macro.import_type local concat = table.concat local insert = table.insert local tostring = tostring local pairs = pairs local tags = {} --- {% set %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_set(compiler, tok) local opts = {} local var = compiler:parse_var_name(tok, opts) if opts.var_system then compiler_error(tok, "syntax", "the system variable can not be changed") end if tok:is("|") or not tok:is_valid() then local tag = compiler:push_tag("set") local id = tag.id tag.var = var if tok:is("|") then tag.final = compiler:parse_filters(tok, '__.concat(_' .. tag.id .. ')') else tag.final = '__.concat(_' .. tag.id .. ')' end tag.append_text = function (_, text) return '_' .. id .. '[#_'.. id .. ' + 1] = ' .. quote_string(text) end tag.append_expr = function (_, lua) return '_' .. id .. '[#_'.. id .. ' + 1] = ' .. lua end return { "local " .. tag.var, "do", "local _" .. tag.id .. " = {}" } elseif tok:is("=") then compiler:push_var(var) compiler.tag_type = tag_type.EXPRESSION -- switch tag mode return 'local ' .. var .. ' = ' .. compiler:parse_expression(tok:next()) end end --- {% do %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_do(compiler, tok) return compiler:parse_expression(tok) end --- {% endset %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_endset(compiler, tok) tok:next() local tag = compiler:pop_tag("set") compiler:push_var(tag.var) return { tag.var .. " = " .. tag.final, "end" } end --- {% extends %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_extends(compiler, tok) if compiler.extends then compiler_error(tok, 'syntax', "Template already extended") end local info = {} local name = compiler:parse_expression(tok, info) if info.type == "string" then compiler.extends = {value = name, static = true} compiler.uses_tpl[name] = true else compiler.extends = {value = name, static = false} end end --- {% block block_name %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_block(compiler, tok) if not tok:is_word() then compiler_error(tok, "syntax", "expecting a valid block name") end if compiler:get_last_tag('macro') then compiler_error(tok, "syntax", "blocks can\'t be defined or used in macro") end local name = tok:get_token() tok:next() compiler.blocks[name] = { code = {}, parent = false, vars = {}, desc = nil, start_line = compiler.line } local tag_for, pos = compiler:get_last_tag("for") -- may be {{ loop }} used in the block (which may be replaced) while tag_for do tag_for.has_loop = true tag_for, pos = compiler:get_last_tag("for", pos - 1) end local tag = compiler:push_tag("block", compiler.blocks[name].code, "block." .. name, {}) tag.block_name = name end --- {% endblock %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_endblock(compiler, tok) local tag = compiler:pop_tag("block") if tok:is_valid() then if tok:is(tag.block_name) then tok:next() else compiler_error(tok, "syntax", "expecting block name " .. tag.block_name) end end compiler.blocks[tag.block_name].parent = tag.parent compiler.blocks[tag.block_name].end_line = compiler.line local vars = utils.implode_hashes(compiler:get_local_vars()) if vars then return '__.blocks.' .. tag.block_name .. '.body(__, __.setmetatable({ ' .. vars .. '}, { __index = _context }))' ; else return '__.blocks.' .. tag.block_name .. '.body(__, _context)' ; end end --- {% use %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_use(compiler, tok) if tok:is_string() then local uses = { name = tok:get_token(), line = compiler.line } compiler.uses_tpl[uses.name] = true compiler.uses[#compiler.uses + 1] = uses tok:next() if tok:is('with') then uses.with = {} tok:next() while tok:is_valid() do local block_name = tok:get_token() local alias_name = tok:next():require("as"):next():get_token() uses.with[block_name] = quote_string(alias_name) if not tok:next():is(",") then break end end end else compiler_error(tok, "syntax", "the template name") end end --- {% macro %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_macro(compiler, tok) if not tok:is_word() then compiler_error(tok, "syntax", "expecting a valid macro name") end local name = tok:get_token() compiler.macros[name] = {} local tag = compiler:push_tag("macro", compiler.macros[name], "macro." .. name, {}) tag.macro_name = name if tok:next():is("(") then local no = 1 repeat tok:next() if tok:is(")") then break end if not tok:is_word() then compiler_error(tok, "syntax", "expecting argument name") end local key = tok:get_token() local arg = "local " .. key .. " = _context." .. key .. " or _context[" .. no .. "] or " compiler:push_var(key) tok:next() if tok:is("=") then tok:next() compiler:append_code(arg .. compiler:parse_expression(tok)) else compiler:append_code(arg .. " nil") end no = no + 1 until not tok:is(",") tok:require(")"):next() end end --- {% endmacro %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_endmacro(compiler, tok) local tag = compiler:pop_tag("macro") if tok:is_valid() then tok:require(tag.macro_name):next() end end --- {% include {'tpl_1', 'tpl_2'} ignore missing only with {foo = 1} with context with vars %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_include(compiler, tok, ...) local info = {} local args = { name = compiler:parse_expression(tok, info), with_vars = true, with_context = true } if info.type == "string" then compiler.uses_tpl[args.name] = true end if tok:is('ignore') then tok:next():require('missing'):next() args.ignore_missing = true end if tok:is("only") then args.with_context = false args.with_vars = false tok:next() end while tok:is_valid() and tok:is('with') or tok:is('without') do local w = false if tok:is('with') then w = true end tok:next() if tok:is('context') then tok:next() args.with_context = w elseif tok:is('vars') then tok:next() args.with_vars = w elseif tok:is('{') then if not w then compiler_error(tok, "syntax", "'without' operator cannot be to apply to variables") end args.vars = compiler:parse_hash(tok) else compiler_error(tok, "syntax", "expecting 'context', 'vars' or variables") end end return tags.include(compiler, args) end --- --- @param compiler aspect.compiler --- @param args table --- args.name - tpl_1 or {'tpl_1', 'tpl_2'} --- args.ignore - ignore missing --- args.vars — {foo = 1, bar = 2} --- args.with_context - with context --- args.with_vars - with vars function tags.include(compiler, args) local vars, context = args.vars if args.with_vars then vars = utils.implode_hashes(vars, compiler:get_local_vars()) local tag, pos = compiler:get_last_tag("for") -- may be {{ loop }} used in included template while tag do tag.has_loop = true tag, pos = compiler:get_last_tag("for", pos - 1) end else vars = utils.implode_hashes(vars) end if vars and args.with_context then context = "__.setmetatable({" .. vars .. "}, { __index = _context })" elseif vars and not args.with_context then context = "{" .. vars .. "}" elseif not vars and args.with_context then context = "_context" else -- not with and not with_context context = "{}" end return '__.fn.include(__, ' .. args.name .. ', ' .. tostring(args.ignore_missing) .. ', ' .. context .. ')' end --- {% import %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_import(compiler, tok) local info = {} local from = compiler:parse_expression(tok, info) if info.type == "string" then compiler.uses_tpl[from] = true end tok:require("as"):next() local name = compiler:parse_var_name(tok) compiler.import[name] = import_type.GROUP return 'local ' .. name .. ' = __.fn.import(__, ' .. from .. ')' end --- {% from %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_from(compiler, tok) local info = {} local from = compiler:parse_expression(tok, info) if info.type == "string" then compiler.uses_tpl[from] = true end tok:require("import"):next() local names, aliases = {}, {} while tok:is_valid() do info = {} local name = compiler:parse_var_name(tok, info) if info.var_system then compiler_error(tok, "syntax", "system variables can't be changed") end insert(names, quote_string(name)) if tok:is("as") then name = compiler:parse_var_name(tok:next(), info) compiler.import[name] = import_type.SINGLE insert(aliases, name) if info.var_system then compiler_error(tok, "syntax", "system variables can't be changed") end else compiler.import[name] = import_type.SINGLE insert(aliases, name) end if tok:is(",") then tok:next() else break end end return 'local ' .. concat(aliases, ", ") .. ' = __.fn.import(__, ' .. from .. ', {'.. concat(names, ", ") .. '})' end --- {% for %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer function tags.tag_for(compiler, tok) local key, value, from, cond if tok:is_word() then value = tok:get_token() if reserved_words[value] then compiler_error(tok, "syntax", "reserved words can not be used as variable name") end compiler:push_var(value) tok:next() else compiler_error(tok, "syntax", "expecting variable name") end if tok:is(",") then key = value if tok:next():is_word() then value = tok:get_token() if reserved_words[value] then compiler_error(tok, "syntax", "reserved words can not be used as variable name") end compiler:push_var(value) tok:next() else compiler_error(tok, "syntax", "expecting variable name") end end local tag = compiler:push_tag('for', {}) from = compiler:parse_expression(tok:require("in"):next()) tag.has_loop = false tag.from = from tag.value = value tag.key = key while tok:is_valid() do if tok:is('if') then tok:next() local info = {} cond = compiler:parse_expression(tok, info) if info.type == "boolean" then tag.cond = "if " .. cond .. " then" else tag.cond = "if __.b(" .. cond .. ") then" end elseif tok:is("recursive") then if tag.nestedset then compiler_error(tok, "syntax", "nestedset() already declared") end tok:require("("):next() tag.recursive = compiler:parse_expression(tok:next()) tok:require(")"):next() elseif tok:is("nestedset") then if tag.recursive then compiler_error(tok, "syntax", "recursive() already declared") end tok:require("(") tag.nestedset = { left = compiler:parse_expression(tok:next()), right = compiler:parse_expression(tok:require(","):next()), level = compiler:parse_expression(tok:require(","):next()) } tok:require(")"):next() else break end end end --- {% break %} function tags.tag_break(compiler, tok) local tag = compiler:get_last_tag() if not tag then compiler_error(tok, "syntax") end if tag.name ~= "for" then compiler_error(tok, "syntax", "'break' allows only in 'for' tag") end return 'break' end --- {% endfor %} --- @param compiler aspect.compiler function tags.tag_endfor(compiler) local tag = compiler:pop_tag('for') local lua = tag.code_space local before = {} if tag.has_loop then if tag.has_loop == true then -- use all keys of {{ loop }} tag.has_loop = loop_keys end if tag.has_loop.revindex or tag.has_loop.revindex0 or tag.has_loop.last then tag.has_loop.length = true end --- before for before[#before + 1] = "do" before[#before + 1] = "local loop = {" if tag.has_loop.iteration then before[#before + 1] = "\titeration = 1," end if tag.has_loop.first then before[#before + 1] = "\tfirst = true," end if tag.has_loop.length or tag.has_loop.revindex or tag.has_loop.revindex0 or tag.has_loop.last then before[#before + 1] = "\tlength = __.f.length(" .. tag.from .. ")," end if tag.has_loop.index or tag.has_loop.last then before[#before + 1] = "\tindex = 1," end if tag.has_loop.index0 then before[#before + 1] = "\tindex0 = 0," end before[#before + 1] = "}" if tag.has_loop.revindex then before[#before + 1] = "loop.revindex = loop.length - 1" end if tag.has_loop.revindex0 then before[#before + 1] = "loop.revindex0 = loop.length" end if tag.has_loop.last then before[#before + 1] = "loop.last = (length == 1)" end end if tag.key then -- start of 'for' before[#before + 1] = 'for ' .. tag.key .. ', ' .. tag.value .. ' in __.iter(' .. tag.from .. ') do' else before[#before + 1] = 'for _, ' .. tag.value .. ' in __.iter(' .. tag.from .. ') do' end if tag.cond then -- start of 'if' before[#before + 1] = tag.cond end if tag.has_loop then if tag.has_loop.iteration then lua[#lua + 1] = "loop.iteration = loop.iteration + 1" end if tag.has_loop.prev_item then lua[#lua + 1] = "loop.prev_item = " .. tag.value end end if tag.cond then -- end of 'if' lua[#lua + 1] = "end" end if tag.has_loop then -- after for body if tag.has_loop.first then lua[#lua + 1] = "if loop.first then loop.first = false end" end if tag.cond then -- end of 'if' lua[#lua + 1] = "end" end if tag.has_loop.index or tag.has_loop.last then lua[#lua + 1] = "loop.index = loop.index + 1" end if tag.has_loop.index0 then lua[#lua + 1] = "loop.index0 = loop.index0 + 1" end if tag.has_loop.revindex then lua[#lua + 1] = "loop.revindex = loop.revindex - 1" end if tag.has_loop.revindex0 then lua[#lua + 1] = "loop.revindex0 = loop.revindex0 - 1" end if tag.has_loop.last then lua[#lua + 1] = "if loop.length == loop.index then loop.last = true end" end lua[#lua + 1] = "end" -- end of 'do' end lua[#lua + 1] = "end" -- end if 'for' utils.prepend_table(before, lua) return lua end --- {% if %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_if(compiler, tok) compiler:push_tag('if') local stats = {} local exp = compiler:parse_expression(tok, stats) if stats.type == "boolean" then return "if " .. exp .. " then" else return "if __.b(" .. exp .. ") then" end end --- {% elseif %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_elseif(compiler, tok) return "elseif __.b(" .. compiler:parse_expression(tok) .. ") then" end --- {% elif %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_elif(compiler, tok) return compiler:tag_elseif(tok) end --- {% else %} --- @param compiler aspect.compiler --- @return string function tags.tag_else(compiler) local tag = compiler:get_last_tag() if not tag then compiler_error(nil, "syntax", "Unexpected tag 'else', no one tag opened") end if tag.name ~= "for" and tag.name ~= "if" then compiler_error(nil, "syntax", "Unexpected tag 'else'") end return 'else' end --- {% endif %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_endif(compiler, tok) compiler:pop_tag('if') return 'end' end --- {% autoescape %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_autoescape(compiler, tok) local state = "true" if tok:is_boolean() then state = tok:get_token() tok:next() end local tag = compiler:push_tag('autoescape') return '__' .. tag.id .. " = __:autoescape(" .. state .. ")" end --- {% endautoescape %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_endautoescape(compiler) local tag = compiler:pop_tag('autoescape') return "__:autoescape(__" .. tag.id .. ")" end --- {% verbatim %} --- @param compiler aspect.compiler function tags.tag_verbatim(compiler) compiler.ignore = "endverbatim" compiler:push_tag("verbatim") end --- {% endverbatim %} --- @param compiler aspect.compiler function tags.tag_endverbatim(compiler) compiler:pop_tag("verbatim") return "local z=1" end --- {% with %} --- @param compiler aspect.compiler --- @param tok aspect.tokenizer --- @return string function tags.tag_with(compiler, tok) local code = {"do"} local dynamic = false -- all variables for scope from variable e.g. {% with vars %} local vars if tok:is("{") then vars = compiler:parse_hash(tok) elseif tok:is_word() then dynamic = tok:get_token() tok:next() end if tok:is("only") then compiler:push_tag("with", nil, nil, {}) tok:next() if dynamic then code[#code + 1] = "local _context = __.t(" .. dynamic .. ")" elseif vars then code[#code + 1] = "local _context = {" .. utils.implode_hashes(vars) .. "}" else code[#code + 1] = "local _context = {}" end else compiler:push_tag("with") if vars then for k, v in pairs(vars) do code[#code + 1] = "local " .. k .. " = " .. v compiler:push_var(k) end end if dynamic then code[#code + 1] = "local _context = __.setmetatable(__.t(" .. dynamic .. "), { __index = _context })" else -- allows __context end end return code end --- {% endwith %} --- @param compiler aspect.compiler --- @return string function tags.tag_endwith(compiler) compiler:pop_tag("with") return "end" end return tags
require('plugins.install-plugins') require('plugins.gruvbox') require('plugins.lualine') require('plugins.indent-blankline') require('plugins.telescope') require('plugins.nvim-lspconfig') require('plugins.rust-tools') require('plugins.nvim-cmp') require('plugins.nerdcommenter') require('plugins.treesitter') require('plugins.bufferline')
local config_dbg_core = slc.config("SL_CPC_DEBUG_SYSTEM_VIEW_LOG_CORE_EVENT") local config_dbg_endpoint = slc.config("SL_CPC_DEBUG_SYSTEM_VIEW_LOG_ENDPOINT_EVENT") if config_dbg_core.value == "1" and not slc.is_provided("segger_systemview") then validation.error( "Segger System View is required when SL_CPC_DEBUG_SYSTEM_VIEW_LOG_CORE_EVENT is enabled", validation.target_for_defines({"SL_CPC_DEBUG_SYSTEM_VIEW_LOG_CORE_EVENT"}), nil, nil) elseif config_dbg_endpoint.value == "1" and not slc.is_provided("segger_systemview") then validation.error( "Segger System View is required when SL_CPC_DEBUG_SYSTEM_VIEW_LOG_ENDPOINT_EVENT is enabled", validation.target_for_defines({"SL_CPC_DEBUG_SYSTEM_VIEW_LOG_ENDPOINT_EVENT"}), nil, nil) end
local args = {...} local done_command = args[1] print('Running tests') local status = dfhack.run_command('ai', 'validate') if status == CR_OK then print('test passed: df-ai:validate') else dfhack.printerr('test errored: df-ai:validate: status=' .. tostring(status)) end local f = io.open('test_status.json', 'w') f:write('{"ai":"passed"}') f:close() if done_command then dfhack.run_command(done_command) end
function Recipe.OnGiveXP.Woodwork3(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 3); end function Recipe.OnGiveXP.Woodwork5(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 5); end function Recipe.OnGiveXP.Woodwork10(recipe, ingredients, result, player) player:getXp():AddXP(Perks.Woodwork, 10); end -- These functions are defined to avoid breaking mods. Give3WoodworkXP = Recipe.OnGiveXP.Woodwork3 Give5WoodworkXP = Recipe.OnGiveXP.Woodwork5 Give10WoodworkXP = Recipe.OnGiveXP.Woodwork10 function Recipe.OnGiveXP.MetalWelding3(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 3); end function Recipe.OnGiveXP.MetalWelding5(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 5); end function Recipe.OnGiveXP.MetalWelding10(recipe, ingredients, result, player) player:getXp():AddXP(Perks.MetalWelding, 10); end -- These functions are defined to avoid breaking mods. Give3MetalWeldingXP = Recipe.OnGiveXP.MetalWelding3 Give5MetalWeldingXP = Recipe.OnGiveXP.MetalWelding5 Give10MetalWeldingXP = Recipe.OnGiveXP.MetalWelding10
local runtime = {} -- Restarts Hammerspoon (calling hs.reload()) runtime.restart = function (message) hs.alert.show(message or "Restarting Hammerspoon...") -- Give some time for alert to show up before reloading hs.timer.doAfter(0.1, hs.reload) end local globals = {} -- Guards an object from garbage collection runtime.guard = function (object) local caller = debug.getinfo(2) table.insert(globals, { object = object, file = caller.source:match("^@?(.+)"), line = caller.currentline, }) return object end -- Unguards a guarded object runtime.unguard = function (object) for i, tuple in ipairs(globals) do if tuple.object == object then table.remove(globals, i) break end end return object end runtime.globals = function () return globals end local restarter -- Enables or disable auto-restart when any of the *.lua files under -- ~/.hammerspoon/ is modified runtime.autorestart = function (flag) if flag then if restarter == nil then restarter = hs.pathwatcher.new("./", function (files) for _, file in ipairs(files) do if file:find("/[^./][^/]*%.lua$") then knu.runtime.restart() return end end end ) end restarter:start() else if restarter then restarter:stop() end end end return runtime
-- local on_attach = function(client) -- require'completion'.on_attach(client) -- end local M = {} local root_pattern = require("lspconfig/util").root_pattern function M.setup() -- lsp require("lspconfig").rust_analyzer.setup({ cmd = { DATA .. "/lsp_servers/rust/rust-analyzer" }, -- cmd = { "rust-analyzer" }, filetypes = { "rust" }, on_attach = require("lsp").common_on_attach, -- on_attach = on_attach, root_dir = root_pattern("Cargo.toml", "rust-project.json"), settings = { ["rust-analyzer"] = { assist = { importGranularity = "module", importPrefix = "self", }, cargo = { loadOutDirsFromCheck = true, allFeatures = true, }, procMacro = { enable = true, }, }, }, }) end return M
local Start = {} Start.scriptName = "OriginalStart" Start.defaultConfig = { START_ON_DOCK = false, CLEAN_ON_UNLOAD = true, CHANGE_CONFIG_SPAWN = true } Start.defaultData = { chargenPlayers = {} } Start.config = DataManager.loadConfiguration(Start.scriptName, Start.defaultConfig) Start.data = DataManager.loadData(Start.scriptName, Start.defaultData) Start.EXIT_DOOR = "119659-0" Start.CHARGEN_CELLS = { ["Imperial Prison Ship"] = true, ["-2, -9"] = true, ["Seyda Neen, Census and Excise Office"] = true } Start.OFFICE = "Seyda Neen, Census and Excise Office" Start.OFFICE_DOORS = { ["ex_nord_door_01"] = "119513-0", ["chargen_door_hall"] = "172860-0" } Start.deliveredCaiusPackage = nil --enable the census office contentFixer.ValidateCellChange = function(pid) return true end --disable the standard way of disabling chargen elements, to allow to enable ergala and chargen boat contentFixer.FixCell = function(pid) return end local spawnLocation = nil if not Start.config.START_ON_DOCK then spawnLocation = { cell = "Imperial Prison Ship", regionName = "bitter coast region", posX = 61, posY = -136.5, posZ = -104.25, rotX = 0, rotZ = -0.5 } else spawnLocation = { cell = "-2, -9", regionName = "bitter coast region", posX = -8861.18, posY = -73120.13, posZ = 92.26, rotX = 0, rotZ = -0.97 } end if Start.config.CHANGE_CONFIG_SPAWN then config.defaultSpawnCell = spawnLocation.cell config.defaultSpawnPos = { spawnLocation.posX, spawnLocation.posY, spawnLocation.posZ } config.defaultSpawnRot = { spawnLocation.rotX, spawnLocation.rotZ } end function Start.getPlayerName(pid) return string.lower(Players[pid].accountName) end function Start.isPlayerChargen(pid) return Start.data.chargenPlayers[Start.getPlayerName(pid)] ~= nil end function Start.teleportToSpawn(pid) local player = Players[pid] player.data.location = spawnLocation player:Save() tes3mp.SetCell(pid, spawnLocation.cell) tes3mp.SetRot( pid, spawnLocation.rotX, spawnLocation.rotZ ) tes3mp.SetPos( pid, spawnLocation.posX, spawnLocation.posY, spawnLocation.posZ ) tes3mp.SendCell(pid) tes3mp.SendPos(pid) end function Start.AddItem(pid, refId) local player = Players[pid] local item = { refId = refId, count = 1, charge = -1, enchantmentCharge = -1, soul = "" } player:LoadItemChanges({item}, enumerations.inventory.ADD) end local runConsole = logicHandler.RunConsoleCommandOnPlayer function Start.fixCharGen(pid) Start.data.chargenPlayers[Start.getPlayerName(pid)] = true --enable some parts of the chargen sequence runConsole(pid, "set CharGenState to 10", false) --skip jiub's question about player's name runConsole(pid, "set \"chargen name\".state to 20", false) --make the boat guard walk as normal runConsole(pid, "set \"chargen boat guard 2\".state to 0", false) --disable most speech and movement for the dock guard runConsole(pid, "set \"chargen dock guard\".state to -1", false) --disable ergala chargen runConsole(pid, "set \"chargen class\".state to -1", false) --allow to enter captain's room without the engraved ring runConsole(pid, "set \"chargen door captain\".done to 1", false) --allow to leave the building without the package runConsole(pid, "set \"CharGen Exit Door\".done to 1", false) end function Start.fixLogin(pid) Start.data.chargenPlayers[Start.getPlayerName(pid)] = nil --disable most of the obtrusive chargen logic runConsole(pid, "set CharGenState to -1", false) --no speech from saint jiub runConsole(pid, "set \"chargen name\".state to -1", false) --boat guard walks to the hatch runConsole(pid, "set \"chargen boat guard 2\".state to 40", false) --no speech from the woman inside the boat runConsole(pid, "set \"chargen boat guard 3\".state to 1", false) --no message when leaving through the boat hatch runConsole(pid, "set \"chargen_shipdoor\".done to 1", false) --no speech from the redguard on the boat runConsole(pid, "set \"chargen boat guard 1\".state to 10", false) --disable most speech and movement for the dock guard runConsole(pid, "set \"chargen dock guard\".state to -1", false) --disable ergala chargen runConsole(pid, "set \"chargen class\".state to -1", false) --no message when picking up the stat sheet runConsole(pid, "set \"chargen statssheet\".state to 20", false) --no speech from the guard at the door runConsole(pid, "set \"chargen door guard\".done to 1", false) --no message when taking the chargen dagger runConsole(pid, "set \"chargen dagger\".done to 1", false) --no message when sleeping on the bed in the census cellar runConsole(pid, "set \"CharGen_Bed\".done to 1", false) --no message after leaving main census building runConsole(pid, "set \"CharGen Exit Door\".done to 1", false) --no message about having a map runConsole(pid, "set \"chargen barrel fatigue\".done to 1", false) --no message about engraved ring runConsole(pid, "set \"ring_keley\".state to 30", false) --allow to enter captain's room without the engraved ring runConsole(pid, "set \"chargen door captain\".done to 1", false) --no message about Gravius runConsole(pid, "set \"CharGen Captain\".state to -1", false) --allow to leave the building without the package runConsole(pid, "set \"CharGen Captain\".done to 1", false) --no message about having a journal runConsole(pid, "set \"chargendoorjournal\".done to 1", false) end function Start.OnPlayerEndCharGenV(eventStatus, pid) if WorldInstance.data.customVariables == nil then WorldInstance.data.customVariables = {} end Start.deliveredCaiusPackage = WorldInstance.data.customVariables.deliveredCaiusPackage --disable the message about starting area being broken WorldInstance.data.customVariables.deliveredCaiusPackage = true end function Start.OnPlayerEndCharGen(eventStatus, pid) --return to the previous value WorldInstance.data.customVariables.deliveredCaiusPackage = Start.deliveredCaiusPackage if not Start.config.CHANGE_CONFIG_SPAWN then Start.teleportToSpawn(pid) end Start.fixCharGen(pid) --ДАЛЬШЕ ВЫ НЕ ПРОЙДЕТЕ ПОКА НЕ ПОЛУЧИТЕ БУМАГИ https://youtu.be/ppSPsvO19dU Start.AddItem(pid, "CharGen StatsSheet") end customEventHooks.registerValidator("OnPlayerEndCharGen", Start.OnPlayerEndCharGenV) customEventHooks.registerHandler("OnPlayerEndCharGen", Start.OnPlayerEndCharGen) function Start.OnPlayerFinishLogin(eventStatus, pid) if eventStatus.validCustomHandlers then if Start.isPlayerChargen(pid) then Start.fixCharGen(pid) else Start.fixLogin(pid) end end end customEventHooks.registerHandler("OnPlayerFinishLogin", Start.OnPlayerFinishLogin) Start.CellFixData = {} -- Delete the chargen scroll as we already gave it to the player Start.CellFixData[Start.OFFICE] = { 172859 } if Start.config.START_ON_DOCK then -- Delete the chargen boat and associated guards and objects Start.CellFixData["-1, -9"] = { 268178, 297457, 297459, 297460, 299125 } Start.CellFixData["-2, -9"] = { 172848, 172850, 289104, 297461, 397559 } Start.CellFixData["-2, -10"] = { 297463, 297464, 297465, 297466 } end function Start.OnCellLoad(eventStatus, pid, cellDescription) if eventStatus.validCustomHandlers then if Start.CellFixData[cellDescription] ~= nil then tes3mp.ClearObjectList() tes3mp.SetObjectListPid(pid) tes3mp.SetObjectListCell(cellDescription) for _, refNum in pairs(Start.CellFixData[cellDescription]) do tes3mp.SetObjectRefNum(refNum) tes3mp.SetObjectMpNum(0) tes3mp.SetObjectRefId("") tes3mp.AddObject() end tes3mp.SendObjectDelete() end end end customEventHooks.registerHandler("OnCellLoad", Start.OnCellLoad) function Start.OnPlayerCellChange(eventStatus, pid) local cellDescription = tes3mp.GetCell(pid) if Start.isPlayerChargen(pid) then --player has left the chargen area if Start.CHARGEN_CELLS[cellDescription] == nil then Start.fixLogin(pid) end end if cellDescription == Start.OFFICE then --unlock the census office doors local cellData = LoadedCells[cellDescription].data for refId, uniqueIndex in pairs(Start.OFFICE_DOORS) do if cellData.objectData[uniqueIndex] ~= nil then if cellData.objectData[uniqueIndex].lockLevel ~= 0 then cellData.objectData[uniqueIndex].lockLevel = 0 end else cellData.objectData[uniqueIndex] = { lockLevel = 0, refId = refId } end end LoadedCells[cellDescription]:LoadObjectsLocked(pid, cellData.objectData, Start.OFFICE_DOORS) end end customEventHooks.registerHandler("OnPlayerCellChange", Start.OnPlayerCellChange) function Start.cleanDockCell(pid, cellDescription) --clean up garbage objects spawned during character creation if cellDescription == "-2, -9" then local targetRefId = "chargencollision - extra" local cellData = LoadedCells[cellDescription].data for uniqueIndex, data in pairs(cellData.objectData) do if data.refId == targetRefId then cellData.objectData[uniqueIndex] = nil end end end end if Start.config.CLEAN_ON_UNLOAD then customEventHooks.registerValidator("OnCellUnload", function(eventStatus, pid, cellDescription) if eventStatus.validCustomHandlers then Start.cleanDockCell(pid, cellDescription) end end) end function Start.OnServerExit(eventStatus) if eventStatus.validCustomHandlers then DataManager.saveData(Start.scriptName, Start.data) end end customEventHooks.registerHandler("OnServerExit", Start.OnServerExit) function Start.OnObjectActivate(eventStatus, pid, cellDescription, objects, players) if eventStatus.validCustomHandlers then if Start.isPlayerChargen(pid) then for _, obj in pairs(objects) do if obj.uniqueIndex == Start.EXIT_DOOR then Start.fixLogin(pid) break end end end end end customEventHooks.registerHandler("OnObjectActivate", Start.OnObjectActivate) return Start
local combat = Combat() combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_ICEDAMAGE) combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_ICEAREA) combat:setArea(createCombatArea(AREA_WAVE4, AREADIAGONAL_WAVE4)) function onGetFormulaValues(player, level, maglevel) local min = (level / 5) + (maglevel * 0.81) + 4 local max = (level / 5) + (maglevel * 2) + 12 return -min, -max end combat:setCallback(CALLBACK_PARAM_LEVELMAGICVALUE, "onGetFormulaValues") local spell = Spell("instant") function spell.onCastSpell(creature, var) return combat:execute(creature, var) end spell:group("attack") spell:id(121) spell:name("Ice Wave") spell:words("exevo frigo hur") spell:level(18) spell:mana(25) spell:needDirection(true) spell:cooldown(4 * 1000) spell:groupCooldown(2 * 1000) spell:needLearn(false) spell:vocation("druid;true", "elder druid;true") spell:register()
minpac.add('tomtom/tcomment_vim', {type = 'opt'})
local utils = require "typesystem_utils" -- Type string of a type declaration built from its parts for error messages function typeDeclarationString( this, typnam, args) local rt = (this == 0 or not this) and typnam or (typedb:type_string(type(this) == "table" and this.type or this ) .. " " .. typnam) if (args) then rt = rt .. "(" .. utils.typeListString( typedb, args) .. ")" end return rt end
Letters = Def.ActorFrame{} for i=1,72 do Letters[#Letters+1] = Def.ActorFrame{ Def.ActorFrame{ OnCommand=function(self) _G['GG'..i]=self end; Def.ActorFrame{ OnCommand=function(self) _G['His'..i]=self end; LoadActor("testfont 8x16")..{ OnCommand=function(self) self:SetTextureFiltering(false); _G['let'..i]=self self:sleep(0) self:visible(false) self:x(999) self:y(999) self:animate(0) self:setstate(0) end } } } } end return Def.ActorFrame{ Def.Quad{ InitCommand=function(self) self:visible(false) -- Here lies Puuro's wacky sprite text system -- You should be able to just copy this xml and -- slap it to your simfile and the functions will work -- makeTextCommand controls which letter will be spat out. -- This system uses bitmap fonts which are output with -- a program called Codehead's Bitmap Font Generator -- Here's instructions for using these functions --[[ First, set a speech bubble with setBubble(dir,width,height) The parameters are: speech bubble arrow direction (0 or 1) width of the letters (optional, defaults to 10) height of the rows (optional, defaults to 10) example: setBubble(0,9,12) Then, use sayThis('string',speed,'filename.ogg') Parameters: String, aka the thing you want to say speed of an individual letter character speech sound example: setBubble(0,9,12) <-this is needed sayThis('Hello',0.06,'sans.ogg',1) remember to ALWAYS run setBubble before running sayThis or the previous text won't be cleared. Extra functions colourText(s,e,r,g,b,a) This function colours a part of the text Parameters: start end red green blue alpha transparency example: setBubble(0,9,12) <-this always comes first colourText(11,15,0,0,1,1) --the word 'blue' is in blue now sayThis('Imagine a blue stop sign',0.06,'sans.ogg',1) setTalkSpeeds(start,end,speed) This works similarly to colourText, except it changes the speed of the letters between the start and end values run this function AFTER sayThis or otherwise the speeds will be overridden example: setBubble(0,9,12) colourText(11,15,0,0,1,1) sayThis('Imagine a blue stop sign',0.06,'sans.ogg',1) setTalkSpeeds(11,15,0.4) --the word 'blue' appears slowly ]] txtOffset=9 spawnAmount=0; textSetter=1 letterNumber=1 talk_textSpeed=0.1 talk_active=0 talk_audio='sound.ogg' talk_speeds={} for i=1,80 do --let's make this table just a bit too large as a failsafe table.insert(talk_speeds,0.06) end talk_widths={} --fiskars function fucking founs fo kung dräckelll... skingg skäkl function setLetterWidth(ltr,wd) talk_widths[ltr] = wd end function spaceLetters() --this shit is kinda dumb for i=2,72 do for j=i,72 do if talk_widths[sanat[i]] ~= nil then _G['let'..j]:addx((talk_widths[sanat[i]])) else --_G['let'..i]:rotationz(20) end end end end function spawnLetters(num) --spawnAmount=num --letterNumber=1 --textSetter:queuecommand('makeText') end function clearThis() talk_active=0 textSetter:stoptweening() for i=1,72 do _G['let'..i]:visible(false) end end function colourText(s,e,r,g,b,a) for i=s,e do if r == 'ran' then n = (math.random(0,100))/100 elseif r == 'ran/2' then n = ((math.random(0,100))/100)/2 else n = r end if g == 'ran' then t = (math.random(0,100))/100 elseif g == 'ran/2' then t = ((math.random(0,100))/100)/2 else t = g end if b == 'ran' then p = (math.random(0,100))/100 elseif b == 'ran/2' then p = ((math.random(0,100))/100)/2 else p = b end _G['let'..i]:diffuse(n,t,p,a) end end function setTalkSpeeds(s,e,spd) for i=s,e do talk_speeds[i] = spd end end function effect(s,e,n,x,y,z,p) for i=s,e do if n ~= 'rainbow' then _G['let'..i]:stopeffect() _G['His'..i]:stopeffect() end if n == 'awesome' then _G['let'..i]:stopeffect() end _G['GG'..i]:stopeffect() if n == 'vibrate' or n == 'vib' then _G['let'..i]:vibrate() _G['let'..i]:effectmagnitude(x,y,z) _G['let'..i]:effectperiod(p) end if n == 'bob' then _G['let'..i]:bob() _G['let'..i]:effectmagnitude(x,y,z) _G['let'..i]:effectperiod(p) end if n == 'rainbow' then _G['GG'..i]:rainbow() end if n == 'awesome' then _G['let'..i]:bob() _G['let'..i]:effectmagnitude(x,y,z) _G['let'..i]:effectperiod(p) _G['His'..i]:bob() _G['His'..i]:effectmagnitude(y,x,z) _G['His'..i]:effectperiod(p) _G['His'..i]:effectoffset((math.abs(p/4.5-(i/4.5)))) end _G['let'..i]:effectoffset(i/4.5) _G['GG'..i]:effectoffset(i/4.5) end end function sayThis(stringi,spd,soundfile) textSetter:stoptweening() sanat = {} --this table has been set in letters.xml for i = 1,string.len(stringi) do --t[i] = string.byte(stringi,i) sanat[i] = string.sub(stringi,i, i) if sanat[i] == ' ' then sanat[i] = 'space' end end spawnAmount=string.len(stringi) letterNumber=1 talk_textSpeed=spd talk_active=1 talk_audio=soundfile for i=1,table.getn(talk_speeds) do talk_speeds[i] = spd end if spawnAmount<=72 then textSetter:queuecommand('makeText') elseif spawnAmount>72 then SCREENMAN:SystemMessage('String is too long') end end --string thingy ends here function newline(x) for i=x,72 do _G['let'..i]:addy(12) _G['let'..i]:addx((x*10.5)*-1) if i>=18+1 and i<=36+1 then _G['let'..i]:addy(-25+12) _G['let'..i]:addx(18*9+18*1.5) elseif i>=36+1 and i<=36+18+1 then _G['let'..i]:y(-21-(12+2)) _G['let'..i]:addx(18*9*2) elseif i>=36+18+1 and i<=36+36+1 then _G['let'..i]:y(-21-(12*2+4)) _G['let'..i]:addx(18*9*2) end end end function setBubble(dir,pxx,pxy) if not pxx then pxx=10 end if not pxy then pxy=12 end --set the y positions for i=1,72 do _G['let'..i]:y(-21) _G['let'..i]:visible(false) _G['let'..i]:setstate(0) _G['let'..i]:diffuse(0,0,0,1) _G['let'..i]:x(-55+(i*9)+(i*1.5)) _G['let'..i]:addy(-4); end --set the x positions bubble:x(0) bubble:y(0) bubble:setstate(dir) bubble:visible(true) end --bubble thingy ends here function hideBubble() bubble:visible(false) end end, }, LoadActor("origbubble 1x2.png")..{ OnCommand=function(self) self:SetTextureFiltering(false); bubble=self self:sleep(0) self:visible(false) self:animate(0) self:setstate(0) self:x(999) self:y(999) end, }, Letters, Def.Quad{ OnCommand=function(self) textSetter=self self:visible(false) sanat={} end, makeTextCommand=function(self) --self:sleep(talk_textSpeed) self:sleep(talk_speeds[letterNumber]) if spawnAmount>0 then spawnAmount=spawnAmount-1 if sanat[letterNumber] == 'A' then _G['let'..letterNumber]:setstate(33) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'B' then _G['let'..letterNumber]:setstate(34) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'C' then _G['let'..letterNumber]:setstate(35) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'D' then _G['let'..letterNumber]:setstate(36) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'E' then _G['let'..letterNumber]:setstate(37) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'F' then _G['let'..letterNumber]:setstate(38) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'G' then _G['let'..letterNumber]:setstate(39) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'H' then _G['let'..letterNumber]:setstate(40) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'I' then _G['let'..letterNumber]:setstate(41) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'J' then _G['let'..letterNumber]:setstate(42) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'K' then _G['let'..letterNumber]:setstate(43) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'L' then _G['let'..letterNumber]:setstate(44) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'M' then _G['let'..letterNumber]:setstate(45) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'N' then _G['let'..letterNumber]:setstate(46) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'O' then _G['let'..letterNumber]:setstate(47) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'P' then _G['let'..letterNumber]:setstate(48) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'Q' then _G['let'..letterNumber]:setstate(49) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'R' then _G['let'..letterNumber]:setstate(50) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'S' then _G['let'..letterNumber]:setstate(51) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'T' then _G['let'..letterNumber]:setstate(52) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'U' then _G['let'..letterNumber]:setstate(53) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'V' then _G['let'..letterNumber]:setstate(54) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'W' then _G['let'..letterNumber]:setstate(55) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'X' then _G['let'..letterNumber]:setstate(56) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'Y' then _G['let'..letterNumber]:setstate(57) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'Z' then _G['let'..letterNumber]:setstate(58) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'a' then _G['let'..letterNumber]:setstate(65) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'b' then _G['let'..letterNumber]:setstate(66) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'c' then _G['let'..letterNumber]:setstate(67) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'd' then _G['let'..letterNumber]:setstate(68) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'e' then _G['let'..letterNumber]:setstate(69) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'f' then _G['let'..letterNumber]:setstate(70) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'g' then _G['let'..letterNumber]:setstate(71) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'h' then _G['let'..letterNumber]:setstate(72) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'i' then _G['let'..letterNumber]:setstate(73) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'j' then _G['let'..letterNumber]:setstate(74) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'k' then _G['let'..letterNumber]:setstate(75) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'l' then _G['let'..letterNumber]:setstate(76) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'm' then _G['let'..letterNumber]:setstate(77) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'n' then _G['let'..letterNumber]:setstate(78) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'o' then _G['let'..letterNumber]:setstate(79) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'p' then _G['let'..letterNumber]:setstate(80) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'q' then _G['let'..letterNumber]:setstate(81) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'r' then _G['let'..letterNumber]:setstate(82) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 's' then _G['let'..letterNumber]:setstate(83) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 't' then _G['let'..letterNumber]:setstate(84) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'u' then _G['let'..letterNumber]:setstate(85) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'v' then _G['let'..letterNumber]:setstate(86) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'w' then _G['let'..letterNumber]:setstate(87) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'x' then _G['let'..letterNumber]:setstate(88) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'y' then _G['let'..letterNumber]:setstate(89) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'z' then _G['let'..letterNumber]:setstate(90) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '0' then _G['let'..letterNumber]:setstate(16) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '1' then _G['let'..letterNumber]:setstate(17) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '2' then _G['let'..letterNumber]:setstate(18) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '3' then _G['let'..letterNumber]:setstate(19) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '4' then _G['let'..letterNumber]:setstate(20) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '5' then _G['let'..letterNumber]:setstate(21) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '6' then _G['let'..letterNumber]:setstate(22) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '7' then _G['let'..letterNumber]:setstate(23) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '8' then _G['let'..letterNumber]:setstate(24) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '9' then _G['let'..letterNumber]:setstate(25) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '?' then _G['let'..letterNumber]:setstate(31) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '!' then _G['let'..letterNumber]:setstate(1) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '.' then _G['let'..letterNumber]:setstate(14) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == ',' then _G['let'..letterNumber]:setstate(12) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == ':' then _G['let'..letterNumber]:setstate(26) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == ';' then _G['let'..letterNumber]:setstate(27) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '&quot;' then _G['let'..letterNumber]:setstate(2) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '\'' then _G['let'..letterNumber]:setstate(7) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '(' then _G['let'..letterNumber]:setstate(8) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == ')' then _G['let'..letterNumber]:setstate(9) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '\[' then _G['let'..letterNumber]:setstate(59) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '\]' then _G['let'..letterNumber]:setstate(61) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '{' then _G['let'..letterNumber]:setstate(91) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '}' then _G['let'..letterNumber]:setstate(93) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '<' then _G['let'..letterNumber]:setstate(28) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '>' then _G['let'..letterNumber]:setstate(30) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '+' then _G['let'..letterNumber]:setstate(11) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '~' then _G['let'..letterNumber]:setstate(94) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '=' then _G['let'..letterNumber]:setstate(29) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '-' then _G['let'..letterNumber]:setstate(13) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '@' then _G['let'..letterNumber]:setstate(32) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '%' then _G['let'..letterNumber]:setstate(5) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '#' then _G['let'..letterNumber]:setstate(3) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '&' then _G['let'..letterNumber]:setstate(6) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '$' then _G['let'..letterNumber]:setstate(4) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '*' then _G['let'..letterNumber]:setstate(10) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '/' then _G['let'..letterNumber]:setstate(15) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '\\' then _G['let'..letterNumber]:setstate(60) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '^' then _G['let'..letterNumber]:setstate(62) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == '_' then _G['let'..letterNumber]:setstate(63) _G['let'..letterNumber]:basezoomx(1) if talk_audio ~= '' then SOUND:PlayOnce('/Themes/News/BGAnimations/text/lua/'..talk_audio); end elseif sanat[letterNumber] == 'space' then _G['let'..letterNumber]:setstate(1) _G['let'..letterNumber]:basezoomx(0) --]] end --...REALLY BRO?????????????? _G['let'..letterNumber]:visible(true) letterNumber=letterNumber+1 if talk_active==1 then self:queuecommand('makeText') end end end, }, }
-- Tests for spell checking with 'encoding' set to "utf-8". local helpers = require('test.functional.helpers')(after_each) local feed, insert, source = helpers.feed, helpers.insert, helpers.source local clear, feed_command, expect = helpers.clear, helpers.feed_command, helpers.expect local write_file, call = helpers.write_file, helpers.call local function write_latin1(name, text) text = call('iconv', text, 'utf-8', 'latin-1') write_file(name, text) end describe("spell checking with 'encoding' set to utf-8", function() setup(function() clear() feed_command("syntax off") write_latin1('Xtest1.aff',[[ SET ISO8859-1 TRY esianrtolcdugmphbyfvkwjkqxz-ëéèêïîäàâöüû'ESIANRTOLCDUGMPHBYFVKWJKQXZ FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ SOFOFROM abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ¿ SOFOTO ebctefghejklnnepkrstevvkesebctefghejklnnepkrstevvkeseeeeeeeceeeeeeeedneeeeeeeeeeepseeeeeeeeceeeeeeeedneeeeeeeeeeep? MIDWORD '- KEP = RAR ? BAD ! PFX I N 1 PFX I 0 in . PFX O Y 1 PFX O 0 out . SFX S Y 2 SFX S 0 s [^s] SFX S 0 es s SFX N N 3 SFX N 0 en [^n] SFX N 0 nen n SFX N 0 n . REP 3 REP g ch REP ch g REP svp s.v.p. MAP 9 MAP aàáâãäå MAP eèéêë MAP iìíîï MAP oòóôõö MAP uùúûü MAP nñ MAP cç MAP yÿý MAP sß ]]) write_latin1('Xtest1.dic', [[ 123456 test/NO # comment wrong Comment OK uk put/ISO the end deol déôr ]]) write_latin1('Xtest2.aff', [[ SET ISO8859-1 FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ PFXPOSTPONE MIDWORD '- KEP = RAR ? BAD ! PFX I N 1 PFX I 0 in . PFX O Y 1 PFX O 0 out [a-z] SFX S Y 2 SFX S 0 s [^s] SFX S 0 es s SFX N N 3 SFX N 0 en [^n] SFX N 0 nen n SFX N 0 n . REP 3 REP g ch REP ch g REP svp s.v.p. MAP 9 MAP aàáâãäå MAP eèéêë MAP iìíîï MAP oòóôõö MAP uùúûü MAP nñ MAP cç MAP yÿý MAP sß ]]) write_latin1('Xtest3.aff', [[ SET ISO8859-1 COMPOUNDMIN 3 COMPOUNDRULE m* NEEDCOMPOUND x ]]) write_latin1('Xtest3.dic', [[ 1234 foo/m bar/mx mï/m la/mx ]]) write_latin1('Xtest4.aff', [[ SET ISO8859-1 FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ COMPOUNDRULE m+ COMPOUNDRULE sm*e COMPOUNDRULE sm+ COMPOUNDMIN 3 COMPOUNDWORDMAX 3 COMPOUNDFORBIDFLAG t COMPOUNDSYLMAX 5 SYLLABLE aáeéiíoóöõuúüûy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui MAP 9 MAP aàáâãäå MAP eèéêë MAP iìíîï MAP oòóôõö MAP uùúûü MAP nñ MAP cç MAP yÿý MAP sß NEEDAFFIX x PFXPOSTPONE MIDWORD '- SFX q N 1 SFX q 0 -ok . SFX a Y 2 SFX a 0 s . SFX a 0 ize/t . PFX p N 1 PFX p 0 pre . PFX P N 1 PFX P 0 nou . ]]) write_latin1('Xtest4.dic', [[ 1234 word/mP util/am pro/xq tomato/m bork/mp start/s end/e ]]) write_latin1('Xtest5.aff', [[ SET ISO8859-1 FLAG long NEEDAFFIX !! COMPOUNDRULE ssmm*ee NEEDCOMPOUND xx COMPOUNDPERMITFLAG pp SFX 13 Y 1 SFX 13 0 bork . SFX a1 Y 1 SFX a1 0 a1 . SFX aé Y 1 SFX aé 0 aé . PFX zz Y 1 PFX zz 0 pre/pp . PFX yy Y 1 PFX yy 0 nou . ]]) write_latin1('Xtest5.dic', [[ 1234 foo/a1aé!! bar/zz13ee start/ss end/eeyy middle/mmxx ]]) write_latin1('Xtest6.aff', [[ SET ISO8859-1 FLAG caplong NEEDAFFIX A! COMPOUNDRULE sMm*Ee NEEDCOMPOUND Xx COMPOUNDPERMITFLAG p SFX N3 Y 1 SFX N3 0 bork . SFX A1 Y 1 SFX A1 0 a1 . SFX Aé Y 1 SFX Aé 0 aé . PFX Zz Y 1 PFX Zz 0 pre/p . ]]) write_latin1('Xtest6.dic', [[ 1234 mee/A1AéA! bar/ZzN3Ee lead/s end/Ee middle/MmXx ]]) write_latin1('Xtest7.aff', [[ SET ISO8859-1 FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ FLAG num NEEDAFFIX 9999 COMPOUNDRULE 2,77*123 NEEDCOMPOUND 1 COMPOUNDPERMITFLAG 432 SFX 61003 Y 1 SFX 61003 0 meat . SFX 391 Y 1 SFX 391 0 a1 . SFX 111 Y 1 SFX 111 0 aé . PFX 17 Y 1 PFX 17 0 pre/432 . ]]) write_latin1('Xtest7.dic', [[ 1234 mee/391,111,9999 bar/17,61003,123 lead/2 tail/123 middle/77,1 ]]) write_latin1('Xtest8.aff', [[ SET ISO8859-1 NOSPLITSUGS ]]) write_latin1('Xtest8.dic', [[ 1234 foo bar faabar ]]) write_latin1('Xtest9.aff', [[ ]]) write_latin1('Xtest9.dic', [[ 1234 foo bar ]]) write_latin1('Xtest-sal.aff', [[ SET ISO8859-1 TRY esianrtolcdugmphbyfvkwjkqxz-ëéèêïîäàâöüû'ESIANRTOLCDUGMPHBYFVKWJKQXZ FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ MIDWORD '- KEP = RAR ? BAD ! PFX I N 1 PFX I 0 in . PFX O Y 1 PFX O 0 out . SFX S Y 2 SFX S 0 s [^s] SFX S 0 es s SFX N N 3 SFX N 0 en [^n] SFX N 0 nen n SFX N 0 n . REP 3 REP g ch REP ch g REP svp s.v.p. MAP 9 MAP aàáâãäå MAP eèéêë MAP iìíîï MAP oòóôõö MAP uùúûü MAP nñ MAP cç MAP yÿý MAP sß SAL AH(AEIOUY)-^ *H SAL AR(AEIOUY)-^ *R SAL A(HR)^ * SAL A^ * SAL AH(AEIOUY)- H SAL AR(AEIOUY)- R SAL A(HR) _ SAL À^ * SAL Å^ * SAL BB- _ SAL B B SAL CQ- _ SAL CIA X SAL CH X SAL C(EIY)- S SAL CK K SAL COUGH^ KF SAL CC< C SAL C K SAL DG(EIY) K SAL DD- _ SAL D T SAL É< E SAL EH(AEIOUY)-^ *H SAL ER(AEIOUY)-^ *R SAL E(HR)^ * SAL ENOUGH^$ *NF SAL E^ * SAL EH(AEIOUY)- H SAL ER(AEIOUY)- R SAL E(HR) _ SAL FF- _ SAL F F SAL GN^ N SAL GN$ N SAL GNS$ NS SAL GNED$ N SAL GH(AEIOUY)- K SAL GH _ SAL GG9 K SAL G K SAL H H SAL IH(AEIOUY)-^ *H SAL IR(AEIOUY)-^ *R SAL I(HR)^ * SAL I^ * SAL ING6 N SAL IH(AEIOUY)- H SAL IR(AEIOUY)- R SAL I(HR) _ SAL J K SAL KN^ N SAL KK- _ SAL K K SAL LAUGH^ LF SAL LL- _ SAL L L SAL MB$ M SAL MM M SAL M M SAL NN- _ SAL N N SAL OH(AEIOUY)-^ *H SAL OR(AEIOUY)-^ *R SAL O(HR)^ * SAL O^ * SAL OH(AEIOUY)- H SAL OR(AEIOUY)- R SAL O(HR) _ SAL PH F SAL PN^ N SAL PP- _ SAL P P SAL Q K SAL RH^ R SAL ROUGH^ RF SAL RR- _ SAL R R SAL SCH(EOU)- SK SAL SC(IEY)- S SAL SH X SAL SI(AO)- X SAL SS- _ SAL S S SAL TI(AO)- X SAL TH @ SAL TCH-- _ SAL TOUGH^ TF SAL TT- _ SAL T T SAL UH(AEIOUY)-^ *H SAL UR(AEIOUY)-^ *R SAL U(HR)^ * SAL U^ * SAL UH(AEIOUY)- H SAL UR(AEIOUY)- R SAL U(HR) _ SAL V^ W SAL V F SAL WR^ R SAL WH^ W SAL W(AEIOU)- W SAL X^ S SAL X KS SAL Y(AEIOU)- Y SAL ZZ- _ SAL Z S ]]) write_file('Xtest.utf-8.add', [[ /regions=usgbnz elequint/2 elekwint/3 ]]) end) teardown(function() os.remove('Xtest-sal.aff') os.remove('Xtest.aff') os.remove('Xtest.dic') os.remove('Xtest.utf-8.add') os.remove('Xtest.utf-8.add.spl') os.remove('Xtest.utf-8.spl') os.remove('Xtest.utf-8.sug') os.remove('Xtest1.aff') os.remove('Xtest1.dic') os.remove('Xtest2.aff') os.remove('Xtest3.aff') os.remove('Xtest3.dic') os.remove('Xtest4.aff') os.remove('Xtest4.dic') os.remove('Xtest5.aff') os.remove('Xtest5.dic') os.remove('Xtest6.aff') os.remove('Xtest6.dic') os.remove('Xtest7.aff') os.remove('Xtest7.dic') os.remove('Xtest8.aff') os.remove('Xtest8.dic') os.remove('Xtest9.aff') os.remove('Xtest9.dic') end) -- Function to test .aff/.dic with list of good and bad words. This was a -- Vim function in the original legacy test. local function test_one(aff, dic) -- Generate a .spl file from a .dic and .aff file. if helpers.iswin() then os.execute('copy /y Xtest'..aff..'.aff Xtest.aff') os.execute('copy /y Xtest'..dic..'.dic Xtest.dic') else os.execute('cp -f Xtest'..aff..'.aff Xtest.aff') os.execute('cp -f Xtest'..dic..'.dic Xtest.dic') end source([[ set spellfile= function! SpellDumpNoShow() " spelling scores depend on what happens to be drawn on screen spelldump %yank quit endfunction $put ='' $put ='test ]]..aff..'-'..dic..[[' mkspell! Xtest Xtest " Use that spell file. set spl=Xtest.utf-8.spl spell " List all valid words. call SpellDumpNoShow() $put $put ='-------' " Find all bad words and suggestions for them. 1;/^]]..aff..[[good: normal 0f:]s let prevbad = '' while 1 let [bad, a] = spellbadword() if bad == '' || bad == prevbad || bad == 'badend' break endif let prevbad = bad let lst = spellsuggest(bad, 3) normal mm $put =bad $put =string(lst) normal `m]s endwhile ]]) end it('part 1-1', function() insert([[ 1good: wrong OK puts. Test the end bad: inputs comment ok Ok. test déôl end the badend test2: elequint test elekwint test elekwent asdf ]]) test_one(1, 1) feed_command([[$put =soundfold('goobledygoook')]]) feed_command([[$put =soundfold('kóopërÿnôven')]]) feed_command([[$put =soundfold('oeverloos gezwets edale')]]) -- And now with SAL instead of SOFO items; test automatic reloading. if helpers.iswin() then os.execute('copy /y Xtest-sal.aff Xtest.aff') else os.execute('cp -f Xtest-sal.aff Xtest.aff') end feed_command('mkspell! Xtest Xtest') feed_command([[$put =soundfold('goobledygoook')]]) feed_command([[$put =soundfold('kóopërÿnôven')]]) feed_command([[$put =soundfold('oeverloos gezwets edale')]]) -- Also use an addition file. feed_command('mkspell! Xtest.utf-8.add.spl Xtest.utf-8.add') feed_command('set spellfile=Xtest.utf-8.add') feed_command('/^test2:') feed(']s') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed_command('set spl=Xtest_us.utf-8.spl') feed_command('/^test2:') feed(']smm') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed('`m]s') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed_command('set spl=Xtest_gb.utf-8.spl') feed_command('/^test2:') feed(']smm') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed('`m]s') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed_command('set spl=Xtest_nz.utf-8.spl') feed_command('/^test2:') feed(']smm') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed('`m]s') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed_command('set spl=Xtest_ca.utf-8.spl') feed_command('/^test2:') feed(']smm') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed('`m]s') feed_command('let [str, a] = spellbadword()') feed_command('$put =str') feed_command('1,/^test 1-1/-1d') expect([[ test 1-1 # file: Xtest.utf-8.spl Comment deol déôr input OK output outputs outtest put puts test testen testn the end uk wrong ------- bad ['put', 'uk', 'OK'] inputs ['input', 'puts', 'outputs'] comment ['Comment', 'outtest', 'the end'] ok ['OK', 'uk', 'put'] Ok ['OK', 'Uk', 'Put'] test ['Test', 'testn', 'testen'] déôl ['deol', 'déôr', 'test'] end ['put', 'uk', 'test'] the ['put', 'uk', 'test'] gebletegek kepereneven everles gesvets etele kbltykk kprnfn *fls kswts tl elekwent elequint elekwint elekwint elekwent elequint elekwent elequint elekwint]]) end) it('part 2-1', function() insert([[ 2good: puts bad: inputs comment ok Ok end the. test déôl badend ]]) -- Postponed prefixes. test_one(2, 1) feed_command('1,/^test 2-1/-1d') expect([=[ test 2-1 # file: Xtest.utf-8.spl Comment deol déôr OK put input output puts outputs test outtest testen testn the end uk wrong ------- bad ['put', 'uk', 'OK'] inputs ['input', 'puts', 'outputs'] comment ['Comment'] ok ['OK', 'uk', 'put'] Ok ['OK', 'Uk', 'Put'] end ['put', 'uk', 'deol'] the ['put', 'uk', 'test'] test ['Test', 'testn', 'testen'] déôl ['deol', 'déôr', 'test']]=]) end) it('part 3-3', function() insert([[ Test rules for compounding. 3good: foo mï foobar foofoobar barfoo barbarfoo bad: bar la foomï barmï mïfoo mïbar mïmï lala mïla lamï foola labar badend ]]) test_one(3, 3) feed_command('1,/^test 3-3/-1d') expect([=[ test 3-3 # file: Xtest.utf-8.spl foo mï ------- bad ['foo', 'mï'] bar ['barfoo', 'foobar', 'foo'] la ['mï', 'foo'] foomï ['foo mï', 'foo', 'foofoo'] barmï ['barfoo', 'mï', 'barbar'] mïfoo ['mï foo', 'foo', 'foofoo'] mïbar ['foobar', 'barbar', 'mï'] mïmï ['mï mï', 'mï'] lala [] mïla ['mï', 'mï mï'] lamï ['mï', 'mï mï'] foola ['foo', 'foobar', 'foofoo'] labar ['barbar', 'foobar']]=]) end) it('part 4-4', function() insert([[ Tests for compounding. 4good: word util bork prebork start end wordutil wordutils pro-ok bork borkbork borkborkbork borkborkborkbork borkborkborkborkbork tomato tomatotomato startend startword startwordword startwordend startwordwordend startwordwordwordend prebork preborkbork preborkborkbork nouword bad: wordutilize pro borkborkborkborkborkbork tomatotomatotomato endstart endend startstart wordend wordstart preborkprebork preborkpreborkbork startwordwordwordwordend borkpreborkpreborkbork utilsbork startnouword badend ]]) test_one(4, 4) feed_command('1,/^test 4-4/-1d') expect([=[ test 4-4 # file: Xtest.utf-8.spl bork prebork end pro-ok start tomato util utilize utils word nouword ------- bad ['end', 'bork', 'word'] wordutilize ['word utilize', 'wordutils', 'wordutil'] pro ['bork', 'word', 'end'] borkborkborkborkborkbork ['bork borkborkborkborkbork', 'borkbork borkborkborkbork', 'borkborkbork borkborkbork'] tomatotomatotomato ['tomato tomatotomato', 'tomatotomato tomato', 'tomato tomato tomato'] endstart ['end start', 'start'] endend ['end end', 'end'] startstart ['start start'] wordend ['word end', 'word', 'wordword'] wordstart ['word start', 'bork start'] preborkprebork ['prebork prebork', 'preborkbork', 'preborkborkbork'] preborkpreborkbork ['prebork preborkbork', 'preborkborkbork', 'preborkborkborkbork'] startwordwordwordwordend ['startwordwordwordword end', 'startwordwordwordword', 'start wordwordwordword end'] borkpreborkpreborkbork ['bork preborkpreborkbork', 'bork prebork preborkbork', 'bork preborkprebork bork'] utilsbork ['utilbork', 'utils bork', 'util bork'] startnouword ['start nouword', 'startword', 'startborkword']]=]) end) it('part 5-5', function() insert([[ Test affix flags with two characters 5good: fooa1 fooaé bar prebar barbork prebarbork startprebar start end startend startmiddleend nouend bad: foo fooa2 prabar probarbirk middle startmiddle middleend endstart startprobar startnouend badend ]]) test_one(5, 5) feed_command('1,/^test 5-5/-1d') expect([=[ test 5-5 # file: Xtest.utf-8.spl bar barbork end fooa1 fooaé nouend prebar prebarbork start ------- bad ['bar', 'end', 'fooa1'] foo ['fooa1', 'fooaé', 'bar'] fooa2 ['fooa1', 'fooaé', 'bar'] prabar ['prebar', 'bar', 'bar bar'] probarbirk ['prebarbork'] middle [] startmiddle ['startmiddleend', 'startmiddlebar'] middleend [] endstart ['end start', 'start'] startprobar ['startprebar', 'start prebar', 'startbar'] startnouend ['start nouend', 'startend']]=]) end) it('part 6-6', function() insert([[ 6good: meea1 meeaé bar prebar barbork prebarbork leadprebar lead end leadend leadmiddleend bad: mee meea2 prabar probarbirk middle leadmiddle middleend endlead leadprobar badend ]]) test_one(6, 6) feed_command('1,/^test 6-6/-1d') expect([=[ test 6-6 # file: Xtest.utf-8.spl bar barbork end lead meea1 meeaé prebar prebarbork ------- bad ['bar', 'end', 'lead'] mee ['meea1', 'meeaé', 'bar'] meea2 ['meea1', 'meeaé', 'lead'] prabar ['prebar', 'bar', 'leadbar'] probarbirk ['prebarbork'] middle [] leadmiddle ['leadmiddleend', 'leadmiddlebar'] middleend [] endlead ['end lead', 'lead', 'end end'] leadprobar ['leadprebar', 'lead prebar', 'leadbar']]=]) end) it('part 7-7', function() insert([[ 7good: meea1 meeaé bar prebar barmeat prebarmeat leadprebar lead tail leadtail leadmiddletail bad: mee meea2 prabar probarmaat middle leadmiddle middletail taillead leadprobar badend ]]) -- Compound words. test_one(7, 7) -- Assert buffer contents. feed_command('1,/^test 7-7/-1d') expect([=[ test 7-7 # file: Xtest.utf-8.spl bar barmeat lead meea1 meeaé prebar prebarmeat tail ------- bad ['bar', 'lead', 'tail'] mee ['meea1', 'meeaé', 'bar'] meea2 ['meea1', 'meeaé', 'lead'] prabar ['prebar', 'bar', 'leadbar'] probarmaat ['prebarmeat'] middle [] leadmiddle ['leadmiddlebar'] middletail [] taillead ['tail lead', 'tail'] leadprobar ['leadprebar', 'lead prebar', 'leadbar']]=]) end) it('part 8-8', function() insert([[ 8good: foo bar faabar bad: foobar barfoo badend ]]) -- NOSPLITSUGS test_one(8, 8) -- Assert buffer contents. feed_command('1,/^test 8-8/-1d') expect([=[ test 8-8 # file: Xtest.utf-8.spl bar faabar foo ------- bad ['bar', 'foo'] foobar ['faabar', 'foo bar', 'bar'] barfoo ['bar foo', 'bar', 'foo']]=]) end) it('part 9-9', function() insert([[ 9good: 0b1011 0777 1234 0x01ff badend ]]) -- NOSPLITSUGS test_one(9, 9) -- Assert buffer contents. feed_command('1,/^test 9-9/-1d') expect([=[ test 9-9 # file: Xtest.utf-8.spl bar foo -------]=]) end) end)
function read_file(file) local input = io.open(file, 'r') if input ~= nil then io.input(input) local content = io.read() io.close(input) return content end return nil end prev_address = '' prev_value = '' while true do address = read_file('address.txt') value = read_file('value.txt') if address ~= nil and value ~= nil then hex_address = tonumber(address, 16) hex_value = tonumber(value, 16) if hex_value ~= nil and hex_address ~= nil then emu.message(address .. ': ' .. value) memory.writebyte(hex_address, hex_value) os.remove('address.txt') os.remove('value.txt') end end if address ~= nil and value ~= nil then prev_address = address prev_value = value end emu.frameadvance() end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" local CUSTOMBATTLESTATE_PB = require("CustomBattleState_pb") local CUSTOMBATTLETYPE_PB = require("CustomBattleType_pb") module('CustomBattleConfig_pb') CUSTOMBATTLECONFIG = protobuf.Descriptor(); local CUSTOMBATTLECONFIG_TAGTYPE_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_CONFIGID_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_SCALEMASK_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_NAME_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_DESC_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_HASPASSWORD_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_PASSWORD_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_ISFAIR_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_BATTLETIME_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_CREATOR_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_CREATORNAME_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_STATE_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_READYTIME_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_ISSYSTEM_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_TOKEN_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_TAGMASK_FIELD = protobuf.FieldDescriptor(); local CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD = protobuf.FieldDescriptor(); CUSTOMBATTLECONFIG_TAGTYPE_FIELD.name = "tagtype" CUSTOMBATTLECONFIG_TAGTYPE_FIELD.full_name = ".KKSG.CustomBattleConfig.tagtype" CUSTOMBATTLECONFIG_TAGTYPE_FIELD.number = 1 CUSTOMBATTLECONFIG_TAGTYPE_FIELD.index = 0 CUSTOMBATTLECONFIG_TAGTYPE_FIELD.label = 1 CUSTOMBATTLECONFIG_TAGTYPE_FIELD.has_default_value = false CUSTOMBATTLECONFIG_TAGTYPE_FIELD.default_value = 0 CUSTOMBATTLECONFIG_TAGTYPE_FIELD.type = 13 CUSTOMBATTLECONFIG_TAGTYPE_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_CONFIGID_FIELD.name = "configid" CUSTOMBATTLECONFIG_CONFIGID_FIELD.full_name = ".KKSG.CustomBattleConfig.configid" CUSTOMBATTLECONFIG_CONFIGID_FIELD.number = 2 CUSTOMBATTLECONFIG_CONFIGID_FIELD.index = 1 CUSTOMBATTLECONFIG_CONFIGID_FIELD.label = 1 CUSTOMBATTLECONFIG_CONFIGID_FIELD.has_default_value = false CUSTOMBATTLECONFIG_CONFIGID_FIELD.default_value = 0 CUSTOMBATTLECONFIG_CONFIGID_FIELD.type = 13 CUSTOMBATTLECONFIG_CONFIGID_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.name = "scalemask" CUSTOMBATTLECONFIG_SCALEMASK_FIELD.full_name = ".KKSG.CustomBattleConfig.scalemask" CUSTOMBATTLECONFIG_SCALEMASK_FIELD.number = 3 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.index = 2 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.label = 1 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.has_default_value = false CUSTOMBATTLECONFIG_SCALEMASK_FIELD.default_value = 0 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.type = 13 CUSTOMBATTLECONFIG_SCALEMASK_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_NAME_FIELD.name = "name" CUSTOMBATTLECONFIG_NAME_FIELD.full_name = ".KKSG.CustomBattleConfig.name" CUSTOMBATTLECONFIG_NAME_FIELD.number = 4 CUSTOMBATTLECONFIG_NAME_FIELD.index = 3 CUSTOMBATTLECONFIG_NAME_FIELD.label = 1 CUSTOMBATTLECONFIG_NAME_FIELD.has_default_value = false CUSTOMBATTLECONFIG_NAME_FIELD.default_value = "" CUSTOMBATTLECONFIG_NAME_FIELD.type = 9 CUSTOMBATTLECONFIG_NAME_FIELD.cpp_type = 9 CUSTOMBATTLECONFIG_DESC_FIELD.name = "desc" CUSTOMBATTLECONFIG_DESC_FIELD.full_name = ".KKSG.CustomBattleConfig.desc" CUSTOMBATTLECONFIG_DESC_FIELD.number = 5 CUSTOMBATTLECONFIG_DESC_FIELD.index = 4 CUSTOMBATTLECONFIG_DESC_FIELD.label = 1 CUSTOMBATTLECONFIG_DESC_FIELD.has_default_value = false CUSTOMBATTLECONFIG_DESC_FIELD.default_value = "" CUSTOMBATTLECONFIG_DESC_FIELD.type = 9 CUSTOMBATTLECONFIG_DESC_FIELD.cpp_type = 9 CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.name = "haspassword" CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.full_name = ".KKSG.CustomBattleConfig.haspassword" CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.number = 6 CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.index = 5 CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.label = 1 CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.has_default_value = false CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.default_value = false CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.type = 8 CUSTOMBATTLECONFIG_HASPASSWORD_FIELD.cpp_type = 7 CUSTOMBATTLECONFIG_PASSWORD_FIELD.name = "password" CUSTOMBATTLECONFIG_PASSWORD_FIELD.full_name = ".KKSG.CustomBattleConfig.password" CUSTOMBATTLECONFIG_PASSWORD_FIELD.number = 7 CUSTOMBATTLECONFIG_PASSWORD_FIELD.index = 6 CUSTOMBATTLECONFIG_PASSWORD_FIELD.label = 1 CUSTOMBATTLECONFIG_PASSWORD_FIELD.has_default_value = false CUSTOMBATTLECONFIG_PASSWORD_FIELD.default_value = "" CUSTOMBATTLECONFIG_PASSWORD_FIELD.type = 9 CUSTOMBATTLECONFIG_PASSWORD_FIELD.cpp_type = 9 CUSTOMBATTLECONFIG_ISFAIR_FIELD.name = "isfair" CUSTOMBATTLECONFIG_ISFAIR_FIELD.full_name = ".KKSG.CustomBattleConfig.isfair" CUSTOMBATTLECONFIG_ISFAIR_FIELD.number = 8 CUSTOMBATTLECONFIG_ISFAIR_FIELD.index = 7 CUSTOMBATTLECONFIG_ISFAIR_FIELD.label = 1 CUSTOMBATTLECONFIG_ISFAIR_FIELD.has_default_value = false CUSTOMBATTLECONFIG_ISFAIR_FIELD.default_value = false CUSTOMBATTLECONFIG_ISFAIR_FIELD.type = 8 CUSTOMBATTLECONFIG_ISFAIR_FIELD.cpp_type = 7 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.name = "battletime" CUSTOMBATTLECONFIG_BATTLETIME_FIELD.full_name = ".KKSG.CustomBattleConfig.battletime" CUSTOMBATTLECONFIG_BATTLETIME_FIELD.number = 9 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.index = 8 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.label = 1 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.has_default_value = false CUSTOMBATTLECONFIG_BATTLETIME_FIELD.default_value = 0 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.type = 13 CUSTOMBATTLECONFIG_BATTLETIME_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.name = "canjoincount" CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.full_name = ".KKSG.CustomBattleConfig.canjoincount" CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.number = 10 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.index = 9 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.label = 1 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.has_default_value = false CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.default_value = 0 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.type = 13 CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_CREATOR_FIELD.name = "creator" CUSTOMBATTLECONFIG_CREATOR_FIELD.full_name = ".KKSG.CustomBattleConfig.creator" CUSTOMBATTLECONFIG_CREATOR_FIELD.number = 11 CUSTOMBATTLECONFIG_CREATOR_FIELD.index = 10 CUSTOMBATTLECONFIG_CREATOR_FIELD.label = 1 CUSTOMBATTLECONFIG_CREATOR_FIELD.has_default_value = false CUSTOMBATTLECONFIG_CREATOR_FIELD.default_value = 0 CUSTOMBATTLECONFIG_CREATOR_FIELD.type = 4 CUSTOMBATTLECONFIG_CREATOR_FIELD.cpp_type = 4 CUSTOMBATTLECONFIG_CREATORNAME_FIELD.name = "creatorname" CUSTOMBATTLECONFIG_CREATORNAME_FIELD.full_name = ".KKSG.CustomBattleConfig.creatorname" CUSTOMBATTLECONFIG_CREATORNAME_FIELD.number = 12 CUSTOMBATTLECONFIG_CREATORNAME_FIELD.index = 11 CUSTOMBATTLECONFIG_CREATORNAME_FIELD.label = 1 CUSTOMBATTLECONFIG_CREATORNAME_FIELD.has_default_value = false CUSTOMBATTLECONFIG_CREATORNAME_FIELD.default_value = "" CUSTOMBATTLECONFIG_CREATORNAME_FIELD.type = 9 CUSTOMBATTLECONFIG_CREATORNAME_FIELD.cpp_type = 9 CUSTOMBATTLECONFIG_STATE_FIELD.name = "state" CUSTOMBATTLECONFIG_STATE_FIELD.full_name = ".KKSG.CustomBattleConfig.state" CUSTOMBATTLECONFIG_STATE_FIELD.number = 13 CUSTOMBATTLECONFIG_STATE_FIELD.index = 12 CUSTOMBATTLECONFIG_STATE_FIELD.label = 1 CUSTOMBATTLECONFIG_STATE_FIELD.has_default_value = false CUSTOMBATTLECONFIG_STATE_FIELD.default_value = nil CUSTOMBATTLECONFIG_STATE_FIELD.enum_type = CUSTOMBATTLESTATE_PB.CUSTOMBATTLESTATE CUSTOMBATTLECONFIG_STATE_FIELD.type = 14 CUSTOMBATTLECONFIG_STATE_FIELD.cpp_type = 8 CUSTOMBATTLECONFIG_READYTIME_FIELD.name = "readytime" CUSTOMBATTLECONFIG_READYTIME_FIELD.full_name = ".KKSG.CustomBattleConfig.readytime" CUSTOMBATTLECONFIG_READYTIME_FIELD.number = 14 CUSTOMBATTLECONFIG_READYTIME_FIELD.index = 13 CUSTOMBATTLECONFIG_READYTIME_FIELD.label = 1 CUSTOMBATTLECONFIG_READYTIME_FIELD.has_default_value = false CUSTOMBATTLECONFIG_READYTIME_FIELD.default_value = 0 CUSTOMBATTLECONFIG_READYTIME_FIELD.type = 13 CUSTOMBATTLECONFIG_READYTIME_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.name = "issystem" CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.full_name = ".KKSG.CustomBattleConfig.issystem" CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.number = 15 CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.index = 14 CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.label = 1 CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.has_default_value = false CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.default_value = false CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.type = 8 CUSTOMBATTLECONFIG_ISSYSTEM_FIELD.cpp_type = 7 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.name = "hasjoincount" CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.full_name = ".KKSG.CustomBattleConfig.hasjoincount" CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.number = 16 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.index = 15 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.label = 1 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.has_default_value = false CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.default_value = 0 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.type = 13 CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_TOKEN_FIELD.name = "token" CUSTOMBATTLECONFIG_TOKEN_FIELD.full_name = ".KKSG.CustomBattleConfig.token" CUSTOMBATTLECONFIG_TOKEN_FIELD.number = 17 CUSTOMBATTLECONFIG_TOKEN_FIELD.index = 16 CUSTOMBATTLECONFIG_TOKEN_FIELD.label = 1 CUSTOMBATTLECONFIG_TOKEN_FIELD.has_default_value = false CUSTOMBATTLECONFIG_TOKEN_FIELD.default_value = "" CUSTOMBATTLECONFIG_TOKEN_FIELD.type = 9 CUSTOMBATTLECONFIG_TOKEN_FIELD.cpp_type = 9 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.name = "battletimeconf" CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.full_name = ".KKSG.CustomBattleConfig.battletimeconf" CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.number = 18 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.index = 17 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.label = 1 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.has_default_value = false CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.default_value = 0 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.type = 13 CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_TAGMASK_FIELD.name = "tagmask" CUSTOMBATTLECONFIG_TAGMASK_FIELD.full_name = ".KKSG.CustomBattleConfig.tagmask" CUSTOMBATTLECONFIG_TAGMASK_FIELD.number = 19 CUSTOMBATTLECONFIG_TAGMASK_FIELD.index = 18 CUSTOMBATTLECONFIG_TAGMASK_FIELD.label = 1 CUSTOMBATTLECONFIG_TAGMASK_FIELD.has_default_value = false CUSTOMBATTLECONFIG_TAGMASK_FIELD.default_value = 0 CUSTOMBATTLECONFIG_TAGMASK_FIELD.type = 13 CUSTOMBATTLECONFIG_TAGMASK_FIELD.cpp_type = 3 CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.name = "fighttype" CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.full_name = ".KKSG.CustomBattleConfig.fighttype" CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.number = 20 CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.index = 19 CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.label = 1 CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.has_default_value = false CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.default_value = nil CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.enum_type = CUSTOMBATTLETYPE_PB.CUSTOMBATTLETYPE CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.type = 14 CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD.cpp_type = 8 CUSTOMBATTLECONFIG.name = "CustomBattleConfig" CUSTOMBATTLECONFIG.full_name = ".KKSG.CustomBattleConfig" CUSTOMBATTLECONFIG.nested_types = {} CUSTOMBATTLECONFIG.enum_types = {} CUSTOMBATTLECONFIG.fields = {CUSTOMBATTLECONFIG_TAGTYPE_FIELD, CUSTOMBATTLECONFIG_CONFIGID_FIELD, CUSTOMBATTLECONFIG_SCALEMASK_FIELD, CUSTOMBATTLECONFIG_NAME_FIELD, CUSTOMBATTLECONFIG_DESC_FIELD, CUSTOMBATTLECONFIG_HASPASSWORD_FIELD, CUSTOMBATTLECONFIG_PASSWORD_FIELD, CUSTOMBATTLECONFIG_ISFAIR_FIELD, CUSTOMBATTLECONFIG_BATTLETIME_FIELD, CUSTOMBATTLECONFIG_CANJOINCOUNT_FIELD, CUSTOMBATTLECONFIG_CREATOR_FIELD, CUSTOMBATTLECONFIG_CREATORNAME_FIELD, CUSTOMBATTLECONFIG_STATE_FIELD, CUSTOMBATTLECONFIG_READYTIME_FIELD, CUSTOMBATTLECONFIG_ISSYSTEM_FIELD, CUSTOMBATTLECONFIG_HASJOINCOUNT_FIELD, CUSTOMBATTLECONFIG_TOKEN_FIELD, CUSTOMBATTLECONFIG_BATTLETIMECONF_FIELD, CUSTOMBATTLECONFIG_TAGMASK_FIELD, CUSTOMBATTLECONFIG_FIGHTTYPE_FIELD} CUSTOMBATTLECONFIG.is_extendable = false CUSTOMBATTLECONFIG.extensions = {} CustomBattleConfig = protobuf.Message(CUSTOMBATTLECONFIG)
--[[ TheNexusAvenger Manages inventories for players. --]] local CHARACTER_ARMOR_SLOTS = { "Head", "Body", "Legs", } local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage")) local ServerScriptServiceProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ServerScriptService")) local Armor = ReplicatedStorageProject:GetResource("Data.Armor") local Inventory = ReplicatedStorageProject:GetResource("State.Inventory.Inventory") local InventoryService = ReplicatedStorageProject:GetResource("External.NexusInstance.NexusInstance"):Extend() InventoryService:SetClassName("InventoryService") InventoryService.PlayerInventories = {} --Set up the replicaiton. local InventoryReplication = Instance.new("Folder") InventoryReplication.Name = "Inventory" InventoryReplication.Parent = ReplicatedStorageProject:GetResource("Replication") local SwapItemsEvent = Instance.new("RemoteEvent") SwapItemsEvent.Name = "SwapItems" SwapItemsEvent.Parent = InventoryReplication --[[ Returns the persistent stat container for the player. --]] function InventoryService:GetInventory(Player) --Create the inventory if it doesn't exist. if not InventoryService.PlayerInventories[Player] then InventoryService.PlayerInventories[Player] = Inventory.new(Player:WaitForChild("PersistentStats"):WaitForChild("Inventory")) end --Return the inventory. return InventoryService.PlayerInventories[Player] end --[[ Awards an armor item to the given player. Attempts to equip the armor if the slot is empty. --]] function InventoryService:AwardItem(Player,Id) --Get the armor data. local ArmorData = nil for _,ArmorItem in pairs(Armor) do if ArmorItem.Id == Id and ArmorItem.Cost then ArmorData = ArmorItem break end end if not ArmorData then return end --Add the item and equip it if the player's slot is empty. local PlayerInventory = self:GetInventory(Player) local Slot = ArmorData.Slot local NewSlot = PlayerInventory:AddItem(Id) if Slot and PlayerInventory:GetItemAtSlot(Slot) == nil then PlayerInventory:SwapItems(Slot,NewSlot) end end --[[ Damages the equipped armor with the given tag. --]] function InventoryService:DamageArmor(Player,Tag,Multiplier) Multiplier = Multiplier or 1 if Multiplier == 0 then return end --Return if the player is not in a round. --RoundService can't be defined above due to a recursive dependency. if not ServerScriptServiceProject:GetResource("Service.RoundService"):GetPlayerRoundContainer(Player) then return end --Damage the armor in the slots. local PlayerInventory = self:GetInventory(Player) for _,Slot in pairs(CHARACTER_ARMOR_SLOTS) do local Item = PlayerInventory:GetItemAtSlot(Slot) if Item then --Get the item data. local ItemData for _,ArmorData in pairs(Armor) do if ArmorData.Id == Item.Id then ItemData = ArmorData break end end --Damage the armor for the modifiers. if ItemData and ItemData.Modifiers then local ModifierValue = ItemData.Modifiers[Tag] if ModifierValue then PlayerInventory:DamageItem(Slot,ModifierValue * Multiplier) end end end end end --Connect swapping slots. SwapItemsEvent.OnServerEvent:Connect(function(Player,Slot1,Slot2) InventoryService:GetInventory(Player):SwapItems(Slot1,Slot2) end) --Connect players leaving. Players.PlayerRemoving:Connect(function(Player) if InventoryService.PlayerInventories[Player] then InventoryService.PlayerInventories[Player]:Destroy() InventoryService.PlayerInventories[Player] = nil end end) return InventoryService
data:add_type { name = "dialog", fields = { { name = "nodes", type = types.map(types.string, types.any) -- TODO } } } data:add { _type = "elona_sys.dialog", _id = "ignores_you", nodes = { __start = { text = { {"talk.ignores_you", args = function(t) return {t.speaker} end}, } }, } }
function InitServer() slot2 = "server" slot0 = getCSVField(slot1) end return
--------------------------------------------------------------- -- EasyMotion.lua: Combo shortcuts for targeting --------------------------------------------------------------- -- Creates a set of combinations for different pools of units, -- in order to alleviate targeting. A healer's delight. -- Thanks to Yoki for original concept! :) local addOn, db = ... --------------------------------------------------------------- -- Key sets and their integer identifiers for input processing local Key = { L = { UP = ConsolePort:GetUIControlKey('CP_L_UP'), DOWN = ConsolePort:GetUIControlKey('CP_L_DOWN'), LEFT = ConsolePort:GetUIControlKey('CP_L_LEFT'), RIGHT = ConsolePort:GetUIControlKey('CP_L_RIGHT'), }, R = { UP = ConsolePort:GetUIControlKey('CP_R_UP'), DOWN = ConsolePort:GetUIControlKey('CP_R_DOWN'), LEFT = ConsolePort:GetUIControlKey('CP_R_LEFT'), RIGHT = ConsolePort:GetUIControlKey('CP_R_RIGHT'), }, } --------------------------------------------------------------- -- Get action/input handlers, EasyMotion -> EM for brevity local EM, Input = ConsolePortEasyMotionButton, ConsolePortEasyMotionInput -- Link functions for world targeting EM.HighlightTarget = TargetPriorityHighlightStart EM.GetNamePlateForUnit = C_NamePlate.GetNamePlateForUnit -- Mixin functions for the hotkey display local HotkeyMixin, GroupMixin = {}, {} -- Initialize secure namespace --------------------------------------------------------------- EM:Execute([[ -- References to other frames headers = newtable() -- Unit tables units, ignore, plates, sorted = newtable(), newtable(), newtable(), newtable() -- Binding tables btns, bindings, lookup = newtable(), newtable(), newtable() -- Ignore mouseover/target ignore.mouseover = true ignore.target = true bindRef = 'ConsolePortEasyMotionInput' MAX = self:GetAttribute('maxcombos') ]]) for side, set in pairs(Key) do EM:Execute('btns.'..side..' = newtable()') for name, keyID in pairs(set) do EM:Execute(format([[ btns.%s.%s = '%s' ]], side, name, keyID)) end end -- Run snippets --------------------------------------------------------------- for name, script in pairs({ -- Parse the input Input = [[ key = ... input = input and tonumber( input .. key ) or tonumber(key) self:CallMethod('Filter', tostring(input)) ]], -- Set the new target SetTarget = [[ local unit = lookup[input] if unit then self:SetAttribute('macrotext', '/target '..unit) elseif defaultToTab then self:SetAttribute('macrotext', '/targetenemy') end self:ClearBindings() if self:GetAttribute('ghostMode') then self:CallMethod('HideBindings', unit, true) self:RunAttribute('DisplayBindings', true) self:RunAttribute('Wipe') else self:RunAttribute('Wipe') self:CallMethod('HideBindings', unit) end pool = nil ]], -- Create key combinations e.g. -> (1, 2, 3, ..., 12, 13, 14, ..., 122, 123, 124) CreateBindings = [[ -- instantiate a keySet with a fixed format local keySet = newtable(set.UP, set.LEFT, set.DOWN, set.RIGHT) local current = 1 for _, k1 in ipairs(keySet) do bindings[current] = tonumber(k1) current = current + 1 for _, k2 in ipairs(keySet) do bindings[current] = tonumber(k2 .. k1) current = current + 1 for _, k3 in ipairs(keySet) do bindings[current] = tonumber(k3 .. k2 .. k1) current = current + 1 end end end table.sort(bindings) ]], -- Assign units to key combinations AssignUnits = [[ self:RunAttribute('CreateBindings') for i, unit in pairs(sorted) do local binding = bindings[i] lookup[binding] = unit end ]], -- Refresh everything on down press Refresh = [[ pool, onDown = ... if not onDown then self:RunAttribute('SetTarget') return end self:SetAttribute('macrotext', nil) self:RunAttribute('Wipe') self:RunAttribute('SetBindings', pool) self:RunAttribute('UpdateUnits', pool) self:RunAttribute('SortUnits') self:RunAttribute('AssignUnits', pool) self:RunAttribute('DisplayBindings') ]], -- Feed existing nameplate units into the unit table UpdatePlates = [[ for plate in pairs(plates) do units[plate] = true end ]], -- Find existing unit frames UpdateFrames = [[ local stack if not current then stack = newtable(self:GetParent():GetChildren()) elseif current:IsVisible() then local unit = current:GetAttribute('unit') if unit and not ignore[unit] and not headers[current] then units[unit] = true end stack = newtable(current:GetChildren()) end if stack then for i, frame in pairs(stack) do if frame:IsProtected() then current = frame self:RunAttribute('UpdateFrames') end end end ]], -- Update sources of units UpdateUnits = [[ local pool = ... if pool == 'frames' then self:RunAttribute('UpdateFrames') elseif pool == 'plates' or pool == 'tab' then self:RunAttribute('UpdatePlates') end ]], -- Sort the units by name, to retain some coherence when setting up bindings SortUnits = [[ local specific = self:GetAttribute('unitpool') for unit in pairs(units) do if ( not specific ) then sorted[#sorted + 1] = unit else specific = specific:gsub(';', '\n') for token in specific:gmatch('[%a%p]+') do if unit:match(token) then sorted[#sorted + 1] = unit break end end end end table.sort(sorted) ]], -- Set the bindings that control the input SetBindings = [[ local pool = ... if pool == 'frames' then set = btns[frameSet] side = frameSet modifier = frameMod elseif pool == 'plates' then set = btns[plateSet] side = plateSet modifier = plateMod elseif pool == 'tab' then set = btns[tabSet] side = tabSet modifier = tabMod end if set then for binding, keyID in pairs(set) do local key = GetBindingKey('CP_' .. side .. '_' .. binding) if key then self:SetBindingClick(true, key, bindRef, keyID) self:SetBindingClick(true, modifier..key, bindRef, keyID) end end end ]], -- Display the bindings on frames/plates DisplayBindings = [[ local ghostMode = ... self:CallMethod('SetFramePool', pool, side) self:CallMethod('HideBindings', ghostMode) for binding, unit in pairs(lookup) do self:CallMethod('DisplayBinding', tostring(binding), unit, ghostMode) end ]], -- Wipe tables and settings Wipe = [[ lookup = wipe(lookup) units = wipe(units) sorted = wipe(sorted) bindings = wipe(bindings) defaultToTab = nil current = nil input = nil set = nil ]], OnNewSettings = [[ ignore.player = self:GetAttribute('ignorePlayer') ]], }) do EM:SetAttribute(name, script) end -- EM secure input wrappers for name, script in pairs({ PreClick = [[ -- Unit frames if button == 'LeftButton' then self:RunAttribute('Refresh', 'frames', down) -- Nameplates elseif button == 'RightButton' then self:RunAttribute('Refresh', 'plates', down) -- Combined nameplates/nearest elseif button == 'MiddleButton' then self:RunAttribute('Refresh', 'tab', down) if down then defaultToTab = true self:CallMethod('HighlightTarget', false) end end ]], }) do EM:WrapScript(EM, name, script) end -- Secure input wrappers for name, script in pairs({ OnClick = [[ if down then owner:RunAttribute('Input', button) end ]], }) do EM:WrapScript(Input, name, script) end function EM:OnNewBindings(...) local keys = { plate = {ConsolePort:GetCurrentBindingOwner('CLICK ConsolePortEasyMotionButton:RightButton')}, frame = {ConsolePort:GetCurrentBindingOwner('CLICK ConsolePortEasyMotionButton:LeftButton')}, tab = {ConsolePort:GetCurrentBindingOwner('CLICK ConsolePortEasyMotionButton:MiddleButton')}, } if db.Settings.unitHotkeyPool then self:SetAttribute('unitpool', db.Settings.unitHotkeyPool) end self:SetAttribute('ignorePlayer', db.Settings.unitHotkeyIgnorePlayer) self:SetAttribute('ghostMode', db.Settings.unitHotkeyGhostMode) self:Execute([[self:RunAttribute('OnNewSettings')]]) local hSet = db.Settings.unitHotkeySet if hSet then hSet = hSet:lower() hSet = hSet:match('left') and 'L' or hSet:match('right') and 'R' end for unitType, info in pairs(keys) do local key, mod = unpack(info) if key and mod then local set = hSet or ( key:match('CP_R_') and 'L' or 'R' ) self:Execute(format([[ %sSet = '%s' %sMod = '%s' ]], unitType, set, unitType, mod)) end end end ConsolePort:RegisterCallback('OnNewBindings', EM.OnNewBindings, EM) EM.FramePool = {} EM.ActiveFrames = 0 EM.UnitFrames = {} EM.InputCodes = { 'CP_R_RIGHT', -- 1 'CP_R_LEFT', -- 2 'CP_R_UP', -- 3 'CP_L_UP', -- 4 'CP_L_DOWN', -- 5 'CP_L_LEFT', -- 6 'CP_L_RIGHT', -- 7 'CP_R_DOWN', -- 8 } function EM:SetFramePool(unitType, side) self.unitType = unitType self.set = Key[side] if unitType == 'frames' then wipe(self.UnitFrames) self:RefreshUnitFrames() end end function EM:AddFrameForUnit(frame, unit) local frames = self.UnitFrames frames[unit] = frames[unit] or {} frames[unit][frame] = true end function EM:GetUnitFramesForUnit(unit) return pairs(self.UnitFrames[unit] or {}) end function EM:RefreshUnitFrames(current) local stack if not current then stack = {self:GetParent():GetChildren()} elseif current:IsVisible() then local unit = current:GetAttribute('unit') if unit then self:AddFrameForUnit(current, unit) end stack = {current:GetChildren()} end if stack then for i, frame in pairs(stack) do if not frame:IsForbidden() and frame:IsProtected() then self:RefreshUnitFrames(frame) end end end end function EM:Filter(input) local filter = '^' .. input for idx, frame in self:GetFrames() do if frame.isActive and frame.binding:match(filter) then local icon, level, previous = frame.Keys, 0 for id in input:gmatch('%d') do id = tonumber(id) if previous then previous:Hide() tremove(frame.ShownKeys, previous.shownID) end previous = icon[id] icon = icon[id] level = level + 1 end frame:Adjust(level > 1 and level) frame:IndicateFilterMatch() else frame:Clear() end end end function EM:DisplayBinding(binding, unit, ghostMode) local plate = not ghostMode and self.GetNamePlateForUnit(unit) if plate and plate.UnitFrame then self:AddFrameForUnit(plate.UnitFrame, unit) end for frame in self:GetUnitFramesForUnit(unit) do local hotkey = self:GetHotkey(binding) hotkey:DrawIconsForBinding(binding) hotkey:SetAlpha(ghostMode and 0.5 or 1) hotkey.unit = unit if self.unitType == 'frames' then hotkey:SetUnitFrame(frame) end end end function EM:HideBindings(unit, ghostMode) self.ActiveFrames = 0 for _, frame in self:GetFrames() do if unit and frame.unit == unit then frame:Animate(ghostMode) else frame:Clear() end end end function EM:GetHotkey(binding) local frame self.ActiveFrames = self.ActiveFrames + 1 if self.ActiveFrames > #self.FramePool then frame = CreateFrame('Frame', 'ConsolePortEasyMotionDisplay'..self.ActiveFrames, self) frame:SetFrameStrata("TOOLTIP") frame.size = db.Settings.unitHotkeySize or 32 frame.offsetX = db.Settings.unitHotkeyOffsetX or 0 frame.offsetY = db.Settings.unitHotkeyOffsetY or -8 frame.anchor = db.Settings.unitHotkeyAnchor or 'CENTER' frame:SetSize(1, 1) frame:Hide() frame.Keys = {} frame.ShownKeys = {} frame.GetNamePlateForUnit = C_NamePlate.GetNamePlateForUnit Mixin(frame, HotkeyMixin) self.FramePool[self.ActiveFrames] = frame else frame = self.FramePool[self.ActiveFrames] end frame.binding = binding frame.isActive = true return frame end function EM:GetFrames() return pairs(self.FramePool) end function HotkeyMixin:Clear() self.isActive = false self.binding = nil self.unit = nil self:SetParent(EM) self:SetFrameLevel(1) self:SetSize(1, 1) self:SetScale(1) self:ClearAllPoints() self:Hide() for _, icon in pairs(self.ShownKeys) do icon:Hide() end wipe(self.ShownKeys) end function HotkeyMixin:Adjust(depth) local offset = depth and #self.ShownKeys + depth or #self.ShownKeys self:SetWidth( offset * ( self.size * 0.75 ) ) end function HotkeyMixin:IndicateFilterMatch() if not self.Indicate then self.Indicate = self:CreateAnimationGroup() self.Indicate.Enlarge = self.Indicate:CreateAnimation('SCALE') --- self.Indicate.Enlarge:SetOrigin('CENTER', 0, 0) self.Indicate.Enlarge:SetScale(1.35, 1.35) self.Indicate.Enlarge:SetDuration(0.1) self.Indicate.Enlarge:SetSmoothing('OUT') --- end self.Indicate:Finish() self.Indicate:Play() end function HotkeyMixin:DrawIconsForBinding(binding) binding = binding or self.binding local icon, shown = self.Keys, 0 for id in binding:gmatch('%d') do id = tonumber(id) local size = self.size if icon[id] then icon = icon[id] else icon[id] = self:CreateTexture(nil, 'OVERLAY') icon = icon[id] icon:SetTexture(db.ICONS[EM.InputCodes[id]]) icon:SetSize(size, size) end shown = shown + 1 self.ShownKeys[shown] = icon icon.shownID = shown icon:SetPoint('LEFT', ( shown - 1) * ( size * 0.75 ), 0) icon:Show() end self:Adjust() end function HotkeyMixin:Animate(ghostMode) if not self.Match then self.Match = self:CreateAnimationGroup() self.Match.Enlarge = self.Match:CreateAnimation('SCALE') self.Match.Shrink = self.Match:CreateAnimation('SCALE') self.Match.Alpha = self.Match:CreateAnimation('ALPHA') --- self.Match.Enlarge:SetOrigin('CENTER', 0, 0) self.Match.Enlarge:SetScale(2, 2) self.Match.Enlarge:SetDuration(0.1) self.Match.Enlarge:SetSmoothing('OUT') --- self.Match.Shrink:SetOrigin('CENTER', 0, 0) self.Match.Shrink:SetScale(0.25, 0.25) self.Match.Shrink:SetDuration(0.2) self.Match.Shrink:SetStartDelay(0.1) self.Match.Shrink:SetSmoothing('OUT') --- self.Match.Alpha:SetStartDelay(0.1) self.Match.Alpha:SetFromAlpha(1) self.Match.Alpha:SetToAlpha(0) self.Match.Alpha:SetDuration(0.2) --- Mixin(self.Match, GroupMixin) end self.Match:Finish() self.Match:SetScript('OnFinished', ghostMode and self.Match.RedrawOnFinish or self.Match.ClearOnFinish) self.Match:Play() end function HotkeyMixin:SetNamePlate(plate) if plate and plate.UnitFrame then self:SetParent(WorldFrame) self:SetPoint('CENTER', plate.UnitFrame, 0, 0) self:Show() self:SetScale(UIParent:GetScale()) self:SetFrameLevel(plate.UnitFrame:GetFrameLevel() + 1) end end function HotkeyMixin:SetUnitFrame(frame) if frame then self:SetParent(UIParent) self:SetPoint(self.anchor, frame, self.offsetX, self.offsetY) self:Show() self:SetScale(1) self:SetFrameLevel(frame:GetFrameLevel() + 1) end end function GroupMixin:ClearOnFinish() self:GetParent():Clear() end function GroupMixin:RedrawOnFinish() local parent = self:GetParent() parent:DrawIconsForBinding(parent.binding) parent:SetAlpha(0.5) end
slot0 = class("SecondSummaryPage3", import(".SummaryAnimationPage")) slot0.OnInit = function (slot0) setActive(slot0._tf:Find("propose_panel"), slot0.summaryInfoVO.isProPose) setActive(slot0._tf:Find("un_panel"), not slot0.summaryInfoVO.isProPose) if slot0.summaryInfoVO.isProPose then slot2 = slot0._tf:Find("propose_panel") setPaintingPrefabAsync(slot2:Find("paint_panel/painting"), slot1, "chuanwu") setText(slot2:Find("window_4/ship_name/Text"), slot0.summaryInfoVO.firstProposeName) setText(slot2:Find("window_4/day/Text"), slot0.summaryInfoVO.proposeTime) setText(slot2:Find("window_5/number/Text"), slot0.summaryInfoVO.proposeCount) end end slot0.Show = function (slot0, slot1) slot0.super.Show(slot0, slot1, slot0._tf:Find((slot0.summaryInfoVO.isProPose and "propose_panel") or "un_panel")) end return slot0
local Nskin = {} -- [1.] Button Redirects -- Defining on which direction the other directions should be based on -- This will let us use less files which is quite handy to keep the noteskin directory nice -- Do remember this will Redirect all the files of that Direction to the Direction its pointed to -- Here, we're only going to cover directions that'll fall back unto different files depending of the game/style -- Alternative Notes will not be implemented yet in this release. Nskin.ButtonRedir = { -- ordinal directions UpLeft = GAMESTATE:GetCurrentGame():GetName() == 'pump' and "Mini" or "Global", UpRight = GAMESTATE:GetCurrentGame():GetName() == 'pump' and "Mini" or "Global", DownLeft = GAMESTATE:GetCurrentGame():GetName() == 'pump' and "Mini" or "Global", DownRight = GAMESTATE:GetCurrentGame():GetName() == 'pump' and "Mini" or "Global", -- centre is center Center = GAMESTATE:GetCurrentGame():GetName() == 'pump' and "Mini" or "Global", -- if gamemode is beat, fallback on different elements, else global Key1 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "White" or "Global", Key2 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "Blue" or "Global", Key3 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "White" or "Global", Key4 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "Blue" or "Global", Key5 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "White" or "Global", Key6 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "Blue" or "Global", Key7 = GAMESTATE:GetCurrentGame():GetName() == 'beat' and "White" or "Global", scratch = "Scratch", } -- [2.] Element Redirects -- Define elements that need to be redirected Nskin.ElementRedir = { ["Tap Fake"] = "Tap Note", ["Hold Explosion"] = "Tap Explosion Dim", ["Roll Explosion"] = "Hold Explosion", ["Hold Head Inactive"] = "Hold Head Inactive", ["Hold Head Active"] = "Hold Head Inactive", ["Roll Head Active"] = "Hold Head Inactive", ["Roll Head Inactive"] = "Hold Head Inactive", ["Roll Bottomcap Inactive"] = "Hold Bottomcap Inactive", ["Roll Bottomcap Active"] = "Hold Bottomcap Active", } -- [4.] Element Rotations -- Parts of noteskins which we want to rotate -- Tap Explosions are set to false as they'll be rotated in Fallback Explosion Nskin.PartsToRotate = { ["Receptor"] = true, ["Tap Explosion Bright"] = true, ["Tap Explosion Dim"] = true, ["Tap Note"] = true, ["Tap Fake"] = true, ["Tap Lift"] = true, ["Tap Addition"] = true, ["Hold Explosion"] = true, ["Hold Head Active"] = true, ["Hold Head Inactive"] = true, ["Roll Explosion"] = true, ["Roll Head Active"] = true, ["Roll Head Inactive"] = true, } -- [5.] Blank Redirects -- Parts that should be Redirected to _Blank.png -- you can add/remove stuff if you want Nskin.Blank = { ["Hold Topcap Active"] = true, ["Hold Topcap Inactive"] = true, ["Roll Topcap Active"] = true, ["Roll Topcap Inactive"] = true, ["Hold Tail Active"] = true, ["Hold Tail Inactive"] = true, ["Roll Tail Active"] = true, ["Roll Tail Inactive"] = true, ["Center Hold Topcap"] = true, } -- [6.] Buttons and Elements -- Between here we usally put all the commands the noteskin.lua needs to do, some are extern in other files -- If you need help with lua go to https://quietly-turning.github.io/Lua-For-SM5/Luadoc/Lua.xml there are a bunch of codes there -- Also check out common it has a load of lua codes in files there -- Just play a bit with lua its not that hard if you understand coding -- But SM can be a bum in some cases, and some codes jut wont work if you dont have the noteskin on FallbackNoteSkin=common in the metric.ini function Nskin.Load() local sButton = Var "Button" local sElement = Var "Element" -- [6a.] Global Elements -- This is where arguments related to all gametypes are covered. -- Setting global button local Button = Nskin.ButtonRedir[sButton] or "Global" -- Setting global element local Element = Nskin.ElementRedir[sElement] or sElement -- Set Hold/Roll Heads to Tap Notes -- Making it so it only works on the beat game mode -- Otherwise, points to the element itself. if GAMESTATE:GetCurrentGame():GetName() == 'beat' and string.find(sElement, "Head") then Element = "Tap Note" else Element = Nskin.ElementRedir[sElement] or sElement end -- Explosion is universal if string.find(Element, "Explosion") then Button = "Global" end -- Mines only stem from one direction. -- I swear if you start singing One Direction songs if string.find(Element, "Tap Mine") then Button = "Global" end -- [6b.] Others -- Returning first part of the code, The redirects, Second part is for commands local t = LoadActor(NOTESKIN:GetPath(Button,Element)) -- Set blank redirects if Nskin.Blank[sElement] then t = Def.Actor {} -- Check if element is sprite only if Var "SpriteOnly" then t = LoadActor(NOTESKIN:GetPath("","_blank")) end end if Nskin.PartsToRotate[sElement] then t.BaseRotationZ = nil end return t end -- > -- dont forget to return cuz else it wont work > return Nskin
--- Library for using a Rnr content based bus. -- @module rnr_client -- @alias device local M = {} --- Initialize and starts the module. -- This is called automatically by toribio if the _load_ attribute for the module in the configuration file is set to -- true. -- @param conf the configuration table (see @{conf}). M.init = function(conf) local toribio = require 'toribio' local selector = require 'tasks/selector' local sched = require 'sched' local log = require 'log' local ip = conf.ip or '127.0.0.1' local port = conf.port or 8182 local function parse_params(data) local params={} local k, v for _, linea in ipairs(data) do k, v = string.match(linea, "^%s*(.-)%s*=%s*(.-)%s*$") if k and v then params[k]=v end end for k, v in pairs(params) do params[k]=v end return params end local device={ --- Name of the device (in this case, 'rnr_client'). name = 'rnr_client', --- Module name (in this case, 'rnr_client'). module = 'rnr_client', } --- Open a new connection. -- The descriptor allows object-oriented acces to methods, like connd:emite_notification(data) -- @return a connection descriptor (see @{connd}) on success, _nil, message_ on failure. device.new_connection = function () local notification_arrival = {} --signal local function get_incomming_handler() local notification_lines return function(sktd, line, err) --print ('++++++++', sktd, line, err) --if not line then return end if line == 'NOTIFICATION' then notification_lines = {} elseif line == 'END' then if notification_lines then local notification = parse_params(notification_lines) sched.signal(notification_arrival, notification) notification_lines = nil end elseif notification_lines then notification_lines[#notification_lines+1]=line end return true end end local skt, err = selector.new_tcp_client(ip, port, nil, nil, 'line', get_incomming_handler()) if not skt then log('RNRCLIENT', 'ERROR', 'Failed to connect to %s:%s with error: %s', tostring(ip), tostring(port),tostring(err)) return nil, err end local connd = setmetatable({ task = selector.task, events = { notification_arrival = notification_arrival }, skt = skt, }, {__index=device}) return connd end --- Add a Subscription. -- When subscribed, matching notification will arrive as signals (see @{connd}) -- @param connd a connection descriptor. -- @param subscrib_id a unique subscription id. If nil, a random one will be generated. -- @param filter an array contaning the subscription filter. Each entry in the array is a table -- containing 'attr', 'op' and 'value' fields describing an expression. -- @return _true_ on succes, _nil, err_ on failure -- @usage local rnr = bobot.wait_for_device('rnr_client') --rnr.subscribe( 'subscrib100', { -- {attrib='sensor', op='=', value='node1'}, -- {attrib='temperature', op='>', value='30'}, --}) device.subscribe = function (connd, subscrib_id, filter) subscrib_id = subscrib_id or tostring(math.random(2^30)) local vlines={[1]='SUBSCRIBE', [2]='subscription_id='..subscrib_id, [3] = 'FILTER'} for _, r in ipairs(filter) do vlines[#vlines+1]= tostring(r.attrib) .. r.op .. tostring(r.value) end vlines[#vlines+1]= 'END\n' local s = table.concat(vlines, '\n') return connd.skt:send_sync(s) end --- Remove a Subscription. -- @param connd a connection descriptor. -- @param subscrib_id a unique subscription id. -- @return _true_ on succes, _nil, err_ on failure device.unsubscribe = function (connd, subscrib_id) local s ='UNSUBSCRIBE\nsubscription_id='..subscrib_id.. '\nEND\n' return connd.skt:send_sync(s) end --- Emit a Notification. -- @param connd a connection descriptor. -- @param data a table with the data to be sent. -- @return _true_ on succes, _nil, err_ on failure -- @usage local rnr = bobot.wait_for_device('rnr_client') --rnr.subscribe( 'notif100', {sensor = 'node2', temperature = 25} ) device.emit_notification = function (connd, data) data.notification_id = data.notification_id or tostring(math.random(2^30)) local vlines={[1]='NOTIFICATION'} for k, v in pairs(data) do vlines[#vlines+1]= tostring(k) .. '=' .. tostring(v) end vlines[#vlines+1]= 'END\n' local s = table.concat(vlines, '\n') return connd.skt:send_sync(s) end log('RNRCLIENT', 'INFO', 'Device %s created: %s', device.module, device.name) toribio.add_device(device) end return M --- Connection descriptor. -- This table is populated by toribio from the configuration file. -- @table connd -- @field task task that will emit signals associated to this device. -- @field events task that will emit signals associated to this device. -- It is a table with a single field, `notification_arrival`, a new notification has arrived. -- The first parameter of the signal is a table with the notification's content. --- Configuration Table. -- This table is populated by toribio from the configuration file. -- @table conf -- @field ip the ip where the Rnr agent listens (defaults to '127.0.0.1') -- @field port the port where the Rnr agent listens (defaults to 8182)
------------------------------------------------- -- Game Setup Logic ------------------------------------------------- include( "InstanceManager" ); include ("SetupParameters"); -- Instance managers for dynamic game options (parent is set dynamically). g_BooleanParameterManager = InstanceManager:new("BooleanParameterInstance", "CheckBox"); g_PullDownParameterManager = InstanceManager:new("PullDownParameterInstance", "Root"); g_SliderParameterManager = InstanceManager:new("SliderParameterInstance", "Root"); g_StringParameterManager = InstanceManager:new("StringParameterInstance", "StringRoot"); g_ButtonParameterManager = InstanceManager:new("ButtonParameterInstance", "ButtonRoot"); g_ParameterFactories = {}; -- This is a mapping of instanced controls to their parameters. -- It's used to cross reference the parameter from the control -- in order to sort that control. g_SortingMap = {}; ------------------------------------------------------------------------------- -- Determine which UI stack the parameters should be placed in. ------------------------------------------------------------------------------- function GetControlStack(group) local gameModeParametersStack = Controls.GameModeParameterStack; if(gameModeParametersStack == nil) then gameModeParametersStack = Controls.PrimaryParametersStack; end local triage = { ["BasicGameOptions"] = Controls.PrimaryParametersStack, ["GameOptions"] = Controls.PrimaryParametersStack, ["BasicMapOptions"] = Controls.PrimaryParametersStack, ["MapOptions"] = Controls.PrimaryParametersStack, ["GameModes"] = gameModeParametersStack; ["Victories"] = Controls.VictoryParameterStack, --["BanOptions"] = Controls.BanParametersStack, --["BanPoolOptions"] = Controls.BanPoolParametersStack, ["TournamentOptions"] = Controls.TournamentParametersStack, ["TradingOptions"] = Controls.TradingParametersStack, ["AdvancedOptions"] = Controls.SecondaryParametersStack, }; -- Triage or default to advanced. return triage[group]; end ------------------------------------------------------------------------------- -- This function wrapper allows us to override this function and prevent -- network broadcasts for every change made - used currently in Options.lua ------------------------------------------------------------------------------- function BroadcastGameConfigChanges() Network.BroadcastGameConfig(); end ------------------------------------------------------------------------------- -- Parameter Hooks ------------------------------------------------------------------------------- function Parameters_Config_EndWrite(o, config_changed) SetupParameters.Config_EndWrite(o, config_changed); -- Dispatch a Lua event notifying that the configuration has changed. -- This will eventually be handled by the configuration layer itself. if(config_changed) then SetupParameters_Log("Marking Configuration as Changed."); if(GameSetup_ConfigurationChanged) then GameSetup_ConfigurationChanged(); end end end function GameParameters_SyncAuxConfigurationValues(o, parameter) local result = SetupParameters.Parameter_SyncAuxConfigurationValues(o, parameter); -- If we don't already need to resync and the parameter is MapSize, perform additional checks. if(not result and parameter.ParameterId == "MapSize" and MapSize_ValueNeedsChanging) then return MapSize_ValueNeedsChanging(parameter); end return result; end function GameParameters_WriteAuxParameterValues(o, parameter) SetupParameters.Config_WriteAuxParameterValues(o, parameter); -- Some additional work if the parameter is MapSize. if(parameter.ParameterId == "MapSize" and MapSize_ValueChanged) then MapSize_ValueChanged(parameter); end if(parameter.ParameterId == "Ruleset" and GameSetup_PlayerCountChanged) then GameSetup_PlayerCountChanged(); end end ------------------------------------------------------------------------------- -- Hook to determine whether a parameter is relevant to this setup. -- Parameters not relevant will be completely ignored. ------------------------------------------------------------------------------- function GetRelevantParameters(o, parameter) -- If we have a player id, only care about player parameters. if(o.PlayerId ~= nil and parameter.ConfigurationGroup ~= "Player") then return false; -- If we don't have a player id, ignore any player parameters. elseif(o.PlayerId == nil and parameter.ConfigurationGroup == "Player") then return false; elseif(not GameConfiguration.IsAnyMultiplayer()) then return parameter.SupportsSinglePlayer; elseif(GameConfiguration.IsHotseat()) then return parameter.SupportsHotSeat; elseif(GameConfiguration.IsLANMultiplayer()) then return parameter.SupportsLANMultiplayer; elseif(GameConfiguration.IsInternetMultiplayer()) then return parameter.SupportsInternetMultiplayer; elseif(GameConfiguration.IsPlayByCloud()) then return parameter.SupportsPlayByCloud; end return true; end function GameParameters_UI_DefaultCreateParameterDriver(o, parameter, parent) if(parent == nil) then parent = GetControlStack(parameter.GroupId); end local control; -- If there is no parent, don't visualize the control. This is most likely a player parameter. if(parent == nil) then return; end; if(parameter.Domain == "bool") then local c = g_BooleanParameterManager:GetInstance(); -- Store the root control, NOT the instance table. g_SortingMap[tostring(c.CheckBox)] = parameter; --c.CheckBox:GetTextButton():SetText(parameter.Name); c.CheckBox:SetText(parameter.Name); local tooltip = parameter.Description; if(parameter.Invalid) then tooltip = string.format("[COLOR_RED]%s[ENDCOLOR][NEWLINE]%s", Locale.Lookup(parameter.InvalidReason), tooltip); end c.CheckBox:SetToolTipString(tooltip); c.CheckBox:RegisterCallback(Mouse.eLClick, function() o:SetParameterValue(parameter, not c.CheckBox:IsSelected()); BroadcastGameConfigChanges(); end); c.CheckBox:ChangeParent(parent); control = { Control = c, UpdateValue = function(value, parameter) -- Sometimes the parameter name is changed, be sure to update it. c.CheckBox:SetText(parameter.Name); local tooltip = parameter.Description; if(parameter.Invalid) then tooltip = string.format("[COLOR_RED]%s[ENDCOLOR][NEWLINE]%s", Locale.Lookup(parameter.InvalidReason), tooltip); end c.CheckBox:SetToolTipString(tooltip); -- We have to invalidate the selection state in order -- to trick the button to use the right vis state.. -- Please change this to a real check box in the future...please c.CheckBox:SetSelected(not value); c.CheckBox:SetSelected(value); end, SetEnabled = function(enabled) c.CheckBox:SetDisabled(not enabled); end, SetVisible = function(visible) c.CheckBox:SetHide(not visible); end, Destroy = function() g_BooleanParameterManager:ReleaseInstance(c); end, }; elseif(parameter.Domain == "int" or parameter.Domain == "uint" or parameter.Domain == "text") then local c = g_StringParameterManager:GetInstance(); -- Store the root control, NOT the instance table. g_SortingMap[tostring(c.StringRoot)] = parameter; c.StringName:SetText(parameter.Name); c.StringRoot:SetToolTipString(parameter.Description); c.StringEdit:SetEnabled(true); local canChangeEnableState = true; if(parameter.Domain == "int") then c.StringEdit:SetNumberInput(true); c.StringEdit:SetMaxCharacters(16); c.StringEdit:RegisterCommitCallback(function(textString) o:SetParameterValue(parameter, tonumber(textString)); BroadcastGameConfigChanges(); end); elseif(parameter.Domain == "uint") then c.StringEdit:SetNumberInput(true); c.StringEdit:SetMaxCharacters(16); c.StringEdit:RegisterCommitCallback(function(textString) local value = math.max(tonumber(textString) or 0, 0); o:SetParameterValue(parameter, value); BroadcastGameConfigChanges(); end); else c.StringEdit:SetNumberInput(false); c.StringEdit:SetMaxCharacters(64); if UI.HasFeature("TextEntry") == true then c.StringEdit:RegisterCommitCallback(function(textString) o:SetParameterValue(parameter, textString); BroadcastGameConfigChanges(); end); else canChangeEnableState = false; c.StringEdit:SetEnabled(false); end end c.StringRoot:ChangeParent(parent); control = { Control = c, UpdateValue = function(value) c.StringEdit:SetText(value); end, SetEnabled = function(enabled) if canChangeEnableState then c.StringRoot:SetDisabled(not enabled); c.StringEdit:SetDisabled(not enabled); end end, SetVisible = function(visible) c.StringRoot:SetHide(not visible); end, Destroy = function() g_StringParameterManager:ReleaseInstance(c); end, }; elseif (parameter.Values and parameter.Values.Type == "IntRange") then -- Range local minimumValue = parameter.Values.MinimumValue; local maximumValue = parameter.Values.MaximumValue; -- Get the UI instance local c = g_SliderParameterManager:GetInstance(); -- Store the root control, NOT the instance table. g_SortingMap[tostring(c.Root)] = parameter; c.Root:ChangeParent(parent); if c.StringName ~= nil then c.StringName:SetText(parameter.Name); end c.OptionTitle:SetText(parameter.Name); c.Root:SetToolTipString(parameter.Description); c.OptionSlider:RegisterSliderCallback(function() local stepNum = c.OptionSlider:GetStep(); -- This method can get called pretty frequently, try and throttle it. if(parameter.Value ~= minimumValue + stepNum) then o:SetParameterValue(parameter, minimumValue + stepNum); BroadcastGameConfigChanges(); end end); control = { Control = c, UpdateValue = function(value) if(value) then c.OptionSlider:SetStep(value - minimumValue); c.NumberDisplay:SetText(tostring(value)); end end, UpdateValues = function(values) c.OptionSlider:SetNumSteps(values.MaximumValue - values.MinimumValue); minimumValue = values.MinimumValue; maximumValue = values.MaximumValue; end, SetEnabled = function(enabled, parameter) c.OptionSlider:SetHide(not enabled or parameter.Values == nil or parameter.Values.MinimumValue == parameter.Values.MaximumValue); end, SetVisible = function(visible, parameter) c.Root:SetHide(not visible or parameter.Value == nil ); end, Destroy = function() g_SliderParameterManager:ReleaseInstance(c); end, }; elseif (parameter.Values and parameter.Array) then -- MultiValue Array -- NOTE: This is a limited fall-back implementation of the multi-select parameters. -- Get the UI instance local c = g_PullDownParameterManager:GetInstance(); -- Store the root control, NOT the instance table. g_SortingMap[tostring(c.Root)] = parameter; c.Root:ChangeParent(parent); if c.StringName ~= nil then c.StringName:SetText(parameter.Name); end local cache = {}; control = { Control = c, Cache = cache, UpdateValue = function(value, p) local valueText = Locale.Lookup("LOC_SELECTION_NOTHING"); if(type(value) == "table") then local count = #value; if (parameter.UxHint ~= nil and parameter.UxHint == "InvertSelection") then if(count == 0) then valueText = Locale.Lookup("LOC_SELECTION_EVERYTHING"); elseif(count == #p.Values) then valueText = Locale.Lookup("LOC_SELECTION_NOTHING"); else valueText = Locale.Lookup("LOC_SELECTION_CUSTOM", #p.Values-count); end else if(count == 0) then valueText = Locale.Lookup("LOC_SELECTION_NOTHING"); elseif(count == #p.Values) then valueText = Locale.Lookup("LOC_SELECTION_EVERYTHING"); else valueText = Locale.Lookup("LOC_SELECTION_CUSTOM", count); end end end if(cache.ValueText ~= valueText) then local button = c.PullDown:GetButton(); button:SetText(valueText); cache.ValueText = valueText; end end, UpdateValues = function(values) -- Do nothing. end, SetEnabled = function(enabled, parameter) c.PullDown:SetDisabled(true); end, SetVisible = function(visible) c.Root:SetHide(not visible); end, Destroy = function() g_PullDownParameterManager:ReleaseInstance(c); end, }; elseif (parameter.Values) then -- MultiValue -- Get the UI instance local c = g_PullDownParameterManager:GetInstance(); -- Store the root control, NOT the instance table. g_SortingMap[tostring(c.Root)] = parameter; c.Root:ChangeParent(parent); if c.StringName ~= nil then c.StringName:SetText(parameter.Name); end local cache = {}; control = { Control = c, Cache = cache, UpdateValue = function(value) local valueText = value and value.Name or nil; local valueDescription = value and value.Description or nil -- If value.Description doesn't exist, try value.RawDescription. -- This allows dropdowns on Advanced Setup to properly track the user selection. if valueDescription == nil and value and value.RawDescription then valueDescription = Locale.Lookup(value.RawDescription); end if(cache.ValueText ~= valueText or cache.ValueDescription ~= valueDescription) then local button = c.PullDown:GetButton(); button:SetText(valueText); button:SetToolTipString(valueDescription); cache.ValueText = valueText; cache.ValueDescription = valueDescription; end end, UpdateValues = function(values) local refresh = false; local cValues = cache.Values; if(cValues and #cValues == #values) then for i,v in ipairs(values) do local cv = cValues[i]; if(cv == nil) then refresh = true; break; elseif(cv.QueryId ~= v.QueryId or cv.QueryIndex ~= v.QueryIndex or cv.Invalid ~= v.Invalid or cv.InvalidReason ~= v.InvalidReason) then refresh = true; break; end end else refresh = true; end if(refresh) then c.PullDown:ClearEntries(); for i,v in ipairs(values) do local entry = {}; c.PullDown:BuildEntry( "InstanceOne", entry ); entry.Button:SetText(v.Name); entry.Button:SetToolTipString(Locale.Lookup(v.RawDescription)); entry.Button:RegisterCallback(Mouse.eLClick, function() o:SetParameterValue(parameter, v); BroadcastGameConfigChanges(); end); end cache.Values = values; c.PullDown:CalculateInternals(); end end, SetEnabled = function(enabled, parameter) c.PullDown:SetDisabled(not enabled or #parameter.Values <= 1); end, SetVisible = function(visible) c.Root:SetHide(not visible); end, Destroy = function() g_PullDownParameterManager:ReleaseInstance(c); end, }; end return control; end -- The method used to create a UI control associated with the parameter. -- Returns either a control or table that will be used in other parameter view related hooks. function GameParameters_UI_CreateParameter(o, parameter) local func = g_ParameterFactories[parameter.ParameterId]; local control; if(func) then control = func(o, parameter); else control = GameParameters_UI_DefaultCreateParameterDriver(o, parameter); end o.Controls[parameter.ParameterId] = control; end -- Called whenever a parameter is no longer relevant and should be destroyed. function UI_DestroyParameter(o, parameter) local control = o.Controls[parameter.ParameterId]; if(control) then if(control.Destroy) then control.Destroy(); end for i,v in ipairs(control) do if(v.Destroy) then v.Destroy(); end end o.Controls[parameter.ParameterId] = nil; end end -- Called whenever a parameter's possible values have been updated. function UI_SetParameterPossibleValues(o, parameter) local control = o.Controls[parameter.ParameterId]; if(control) then if(control.UpdateValues) then control.UpdateValues(parameter.Values, parameter); end for i,v in ipairs(control) do if(v.UpdateValues) then v.UpdateValues(parameter.Values, parameter); end end end end -- Called whenever a parameter's value has been updated. function UI_SetParameterValue(o, parameter) local control = o.Controls[parameter.ParameterId]; if(control) then if(control.UpdateValue) then control.UpdateValue(parameter.Value, parameter); end for i,v in ipairs(control) do if(v.UpdateValue) then v.UpdateValue(parameter.Value, parameter); end end end end -- Called whenever a parameter is enabled. function UI_SetParameterEnabled(o, parameter) local control = o.Controls[parameter.ParameterId]; if(control) then if(control.SetEnabled) then control.SetEnabled(parameter.Enabled, parameter); end for i,v in ipairs(control) do if(v.SetEnabled) then v.SetEnabled(parameter.Enabled, parameter); end end end end -- Called whenever a parameter is visible. function UI_SetParameterVisible(o, parameter) local control = o.Controls[parameter.ParameterId]; if(control) then if(control.SetVisible) then control.SetVisible(parameter.Visible, parameter); end for i,v in ipairs(control) do if(v.SetVisible) then v.SetVisible(parameter.Visible, parameter); end end end end ------------------------------------------------------------------------------- -- Called after a refresh was performed. -- Update all of the game option stacks and scroll panels. ------------------------------------------------------------------------------- function GameParameters_UI_AfterRefresh(o) -- All parameters are provided with a sort index and are manipulated -- in that particular order. -- However, destroying and re-creating parameters can get expensive -- and thus is avoided. Because of this, some parameters may be -- created in a bad order. -- It is up to this function to ensure order is maintained as well -- as refresh/resize any containers. -- FYI: Because of the way we're sorting, we need to delete instances -- rather than release them. This is because releasing merely hides it -- but it still gets thrown in for sorting, which is frustrating. local sort = function(a,b) -- ForgUI requires a strict weak ordering sort. local ap = g_SortingMap[tostring(a)]; local bp = g_SortingMap[tostring(b)]; if(ap == nil and bp ~= nil) then return true; elseif(ap == nil and bp == nil) then return tostring(a) < tostring(b); elseif(ap ~= nil and bp == nil) then return false; else return o.Utility_SortFunction(ap, bp); end end local stacks = { {Controls.PrimaryParametersStack}, {Controls.SecondaryParametersStack,Controls.SecondaryParametersHeader}, {Controls.GameModeParameterStack,Controls.GameModeParametersHeader}, {Controls.VictoryParameterStack,Controls.VictoryParametersHeader} }; for i,v in ipairs(stacks) do local s = v[1]; local h = v[2]; if(s) then local children = s:GetChildren(); local hide = true; for _,c in ipairs(children) do if(c:IsVisible()) then hide = false; break; end end if(h) then h:SetHide(hide); end s:SetHide(hide); end end for i,v in ipairs(stacks) do local s = v[1]; if(s and s:IsVisible()) then s:SortChildren(sort); end end for i,v in ipairs(stacks) do local s = v[1]; if(s) then s:CalculateSize(); s:ReprocessAnchoring(); end end Controls.ParametersStack:CalculateSize(); Controls.ParametersStack:ReprocessAnchoring(); if Controls.ParametersScrollPanel then Controls.ParametersScrollPanel:CalculateInternalSize(); end end ------------------------------------------------------------------------------- -- Perform any additional operations on relevant parameters. -- In this case, adjust the parameter group so that they are sorted properly. ------------------------------------------------------------------------------- function GameParameters_PostProcess(o, parameter) -- Move all groups into 1 singular group for sorting purposes. --local triage = { --["BasicGameOptions"] = "GameOptions", --["BasicMapOptions"] = "GameOptions", --["MapOptions"] = "GameOptions", --}; -- --parameter.GroupId = triage[parameter.GroupId] or parameter.GroupId; end -- Generate the game setup parameters and populate the UI. function BuildGameSetup(createParameterFunc) -- If BuildGameSetup is called twice, call HideGameSetup to reset things. if(g_GameParameters) then HideGameSetup(); end print("Building Game Setup"); g_GameParameters = SetupParameters.new(); g_GameParameters.Config_EndWrite = Parameters_Config_EndWrite; g_GameParameters.Parameter_GetRelevant = GetRelevantParameters; g_GameParameters.Parameter_PostProcess = GameParameters_PostProcess; g_GameParameters.Parameter_SyncAuxConfigurationValues = GameParameters_SyncAuxConfigurationValues; g_GameParameters.Config_WriteAuxParameterValues = GameParameters_WriteAuxParameterValues; g_GameParameters.UI_BeforeRefresh = UI_BeforeRefresh; g_GameParameters.UI_AfterRefresh = GameParameters_UI_AfterRefresh; g_GameParameters.UI_CreateParameter = createParameterFunc ~= nil and createParameterFunc or GameParameters_UI_CreateParameter; g_GameParameters.UI_DestroyParameter = UI_DestroyParameter; g_GameParameters.UI_SetParameterPossibleValues = UI_SetParameterPossibleValues; g_GameParameters.UI_SetParameterValue = UI_SetParameterValue; g_GameParameters.UI_SetParameterEnabled = UI_SetParameterEnabled; g_GameParameters.UI_SetParameterVisible = UI_SetParameterVisible; -- Optional overrides. if(GameParameters_FilterValues) then g_GameParameters.Default_Parameter_FilterValues = g_GameParameters.Parameter_FilterValues; g_GameParameters.Parameter_FilterValues = GameParameters_FilterValues; end g_GameParameters:Initialize(); g_GameParameters:FullRefresh(); end -- Generate the game setup parameters and populate the UI. function BuildHeadlessGameSetup() -- If BuildGameSetup is called twice, call HideGameSetup to reset things. if(g_GameParameters) then HideGameSetup(); end print("Building Headless Game Setup"); g_GameParameters = SetupParameters.new(); g_GameParameters.Config_EndWrite = Parameters_Config_EndWrite; g_GameParameters.Parameter_GetRelevant = GetRelevantParameters; g_GameParameters.Parameter_PostProcess = GameParameters_PostProcess; g_GameParameters.Parameter_SyncAuxConfigurationValues = GameParameters_SyncAuxConfigurationValues; g_GameParameters.Config_WriteAuxParameterValues = GameParameters_WriteAuxParameterValues; g_GameParameters.UpdateVisualization = function() end g_GameParameters.UI_AfterRefresh = nil; g_GameParameters.UI_CreateParameter = nil; g_GameParameters.UI_DestroyParameter = nil; g_GameParameters.UI_SetParameterPossibleValues = nil; g_GameParameters.UI_SetParameterValue = nil; g_GameParameters.UI_SetParameterEnabled = nil; g_GameParameters.UI_SetParameterVisible = nil; -- Optional overrides. if(GameParameters_FilterValues) then g_GameParameters.Default_Parameter_FilterValues = g_GameParameters.Parameter_FilterValues; g_GameParameters.Parameter_FilterValues = GameParameters_FilterValues; end g_GameParameters:Initialize(); end -- =========================================================================== -- Hide game setup parameters. function HideGameSetup(hideParameterFunc) print("Hiding Game Setup"); -- Shutdown and nil out the game parameters. if(g_GameParameters) then g_GameParameters:Shutdown(); g_GameParameters = nil; end -- Reset all UI instances. if(hideParameterFunc == nil) then g_BooleanParameterManager:ResetInstances(); g_PullDownParameterManager:ResetInstances(); g_SliderParameterManager:ResetInstances(); g_StringParameterManager:ResetInstances(); g_ButtonParameterManager:ResetInstances(); else hideParameterFunc(); end end -- =========================================================================== function MapSize_ValueNeedsChanging(p) local results = CachedQuery("SELECT * from MapSizes where Domain = ? and MapSizeType = ? LIMIT 1", p.Value.Domain, p.Value.Value); local minPlayers = 2; local maxPlayers = 2; local defPlayers = 2; local minCityStates = 0; local maxCityStates = 0; local defCityStates = 0; if(results) then for i, v in ipairs(results) do minPlayers = v.MinPlayers; maxPlayers = v.MaxPlayers; defPlayers = v.DefaultPlayers; minCityStates = v.MinCityStates; maxCityStates = v.MaxCityStates; defCityStates = v.DefaultCityStates; end end -- TODO: Add Min/Max city states, set defaults. if(MapConfiguration.GetMinMajorPlayers() ~= minPlayers) then SetupParameters_Log("Min Major Players: " .. MapConfiguration.GetMinMajorPlayers() .. " should be " .. minPlayers); return true; elseif(MapConfiguration.GetMaxMajorPlayers() ~= maxPlayers) then SetupParameters_Log("Max Major Players: " .. MapConfiguration.GetMaxMajorPlayers() .. " should be " .. maxPlayers); return true; elseif(MapConfiguration.GetMinMinorPlayers() ~= minCityStates) then SetupParameters_Log("Min Minor Players: " .. MapConfiguration.GetMinMinorPlayers() .. " should be " .. minCityStates); return true; elseif(MapConfiguration.GetMaxMinorPlayers() ~= maxCityStates) then SetupParameters_Log("Max Minor Players: " .. MapConfiguration.GetMaxMinorPlayers() .. " should be " .. maxCityStates); return true; end return false; end function MapSize_ValueChanged(p) SetupParameters_Log("MAP SIZE CHANGED"); -- The map size has changed! -- Adjust the number of players to match the default players of the map size. local results = CachedQuery("SELECT * from MapSizes where Domain = ? and MapSizeType = ? LIMIT 1", p.Value.Domain, p.Value.Value); local minPlayers = 2; local maxPlayers = 2; local defPlayers = 2; local minCityStates = 0; local maxCityStates = 0; local defCityStates = 0; if(results) then for i, v in ipairs(results) do minPlayers = v.MinPlayers; maxPlayers = v.MaxPlayers; defPlayers = v.DefaultPlayers; minCityStates = v.MinCityStates; maxCityStates = v.MaxCityStates; defCityStates = v.DefaultCityStates; end end MapConfiguration.SetMinMajorPlayers(minPlayers); MapConfiguration.SetMaxMajorPlayers(maxPlayers); MapConfiguration.SetMinMinorPlayers(minCityStates); MapConfiguration.SetMaxMinorPlayers(maxCityStates); GameConfiguration.SetValue("CITY_STATE_COUNT", defCityStates); -- Clamp participating player count in network multiplayer so we only ever auto-spawn players up to the supported limit. local mpMaxSupportedPlayers = 8; -- The officially supported number of players in network multiplayer games. local participatingCount = defPlayers + GameConfiguration.GetHiddenPlayerCount(); if GameConfiguration.IsNetworkMultiplayer() or GameConfiguration.IsPlayByCloud() then participatingCount = math.clamp(participatingCount, 0, mpMaxSupportedPlayers); end SetupParameters_Log("Setting participating player count to " .. tonumber(participatingCount)); local playerCountChange = GameConfiguration.SetParticipatingPlayerCount(participatingCount); Network.BroadcastGameConfig(true); -- NOTE: This used to only be called if playerCountChange was non-zero. -- This needs to be called more frequently than that because each player slot entry's add/remove button -- needs to be potentially updated to reflect the min/max player constraints. if(GameSetup_PlayerCountChanged) then GameSetup_PlayerCountChanged(); end end function GetGameModeInfo(gameModeType) local item_query : string = "SELECT * FROM GameModeItems where GameModeType = ? ORDER BY SortIndex"; local item_results : table = CachedQuery(item_query, gameModeType); return item_results[1]; end
local addonName = "KibsItemLevelContinued" local addonNamespace = LibStub and LibStub(addonName .. "-1.0", true) if not addonNamespace or addonNamespace.loaded.Debug then return end addonNamespace.loaded.Debug = true local queue = {} local printer addonNamespace.Debug = function(...) if printer then printer(...) else table.insert(queue, { ... }) end end addonNamespace.SetDebugPrinter = function(callback) printer = callback if printer then for _, args in ipairs(queue) do printer(unpack(args)) end queue = {} end end
local account = require('account') local ffi = require('ffi') local list = require('list') local string = require('string') local settings = require('settings') local table = require('table') local ui = require('core.ui') local world = require('world') local state = require('mv.state') local mv = require('mv.mv') local display do local defaults = { visible = false, x = 370, y = 0, width = 600, height = 340, address = '', active = false, } display = settings.load(defaults, 'browser', true) end local data = {} local tonumber = tonumber local save = settings.save local init = state.init local hex_address = mv.hex.address local hex_raw = mv.hex.raw local hex_space = mv.hex.space local hex_zero = mv.hex.zero -- Adjusting _G to allow arbitrary module loading setmetatable(_G, { __index = function(t, k) local ok, res = pcall(require, k) if not ok then return nil end rawset(t, k, res) return res end, }) -- Public operations local browser = {} browser.name = 'browse' local getters = {} browser.get_value = function() local value = display.address local address = tonumber(value, 16) if address ~= nil and address > 0 and address <= 0xFFFFFFFF then return address end local getter = getters[value] if not getter then getter = loadstring('return ' .. value) getters[value] = getter end local ok, result = pcall(getter) if ok and type(result) == 'cdata' then return value end return nil end browser.running = function() return display.active end browser.visible = function() return display.visible end browser.show = function(value) display.visible = value save('browser') end browser.start = function(value) data.address = value display.active = true display.visible = true save('browser') end browser.stop = function() data.address = nil display.active = false save('browser') end -- Command handling local browse_command = function(address) display.address = address if browser.valid() then browser.start() end end mv.command:register('browse', browse_command, '<address:integer>') -- UI do local button = ui.button local edit = ui.edit local location = ui.location local text = ui.text browser.dashboard = function(pos) local active = browser.running() pos(10, 10) text('[Browsing]{bold 16px} ' .. (active and '[on]{green}' or '[off]{red}')) pos(20, 32) text('Address') pos(70, -2) ui.size(280, 23) display.address = edit('mv_browse_address', display.address) pos(20, 30) local value = browser.get_value() if button('mv_browse_start', active and 'Restart browser' or 'Start browser', { enabled = value ~= nil }) then browser.start(value) end pos(120, 0) if button('mv_browse_stop', 'Stop browser', { enabled = active }) then browser.stop() end end browser.state = init(display, { title = 'Memory Viewer Browser', }) do local ffi_cast = ffi.cast local ffi_string = ffi.string local string_byte = string.byte local string_char = string.char local string_format = string.format local table_concat = table.concat local table_insert = table.insert local ptr_type = ffi.typeof('void*') local lead_lines = {} do local hex_1 = {} local hex_2 = {} for i = 0x00, 0x1F do hex_1[i] = hex_raw[i % 0x10] hex_2[i] = hex_space[i % 0x10] end for i = 0x0, 0xF do lead_lines[i] = ' | ' .. table_concat(hex_2, ' ', i, i + 0xF) .. ' | ' .. table_concat(hex_1, '', i, i + 0xF) end end local lookup_byte = {} for i = 0x00, 0xFF do lookup_byte[i] = '.' end for i = 0x20, 0x7E do lookup_byte[i] = string_char(i) end local escape = { '\\', '[', ']', '{', '}', } for i = 1, #escape do local char = escape[i] lookup_byte[string_byte(char)] = '\\' .. char end local offsets = {} for i = 0, 4 do local value = 0x10^i local hex = string_format('0x%x', value) table_insert(offsets, 1, { name = 'mv_browse_back_' .. hex, label = '- ' .. hex, value = -value, }) table_insert(offsets, { name = 'mv_browse_forward_' .. hex, label = '+ ' .. hex, value = value, }) end browser.window = function() local address = data.address if not address then return end if type(address) == 'string' then local ok, result = pcall(getters[address]) if not ok or result == nil then text('Invalid expression: ' .. address .. ' (' .. tostring(result) .. ')') return end address = tonumber(ffi_cast('intptr_t', result)) end local lines = list() lines:add(lead_lines[address % 0x10]) lines:add('-----------------------------------------------------------------------------') for i = 0x00, 0x1F do local line_address = address + i * 0x10 local line = {string_byte(ffi_string(ffi_cast(ptr_type, line_address), 0x10), 0x01, 0x10)} local chars = {} for j = 0x01, 0x10 do chars[j] = lookup_byte[line[j]] line[j] = hex_zero[line[j]] end lines:add(hex_address(line_address) .. ' | ' .. table_concat(line, ' ', 0x01, 0x10) .. ' | ' .. table_concat(chars, '', 0x01, 0x10)) end text('[' .. table_concat(lines, '\n') .. ']{Consolas 12px}') location(525, 36) for i = 1, #offsets do local offset = offsets[i] if button(offset.name, offset.label) then data.address = address + offset.value end end end end browser.button = function() return 'MV - Browser', 85 end browser.save = function() save('browser') end end -- Initialize do local reset = function() browser.stop() end account.login:register(reset) account.logout:register(reset) world.zone_change:register(reset) reset() end return browser
-- This script is ran when the user is running a local app/sandbox local share = teverse.construct("guiTextBox", { parent = teverse.coreInterface, size = guiCoord(0, 60, 0, 16), position = guiCoord(0.5, -65, 1, -16), strokeRadius = 2, text = "Share", textAlign = "middle", textSize = 12 }) local reload = teverse.construct("guiTextBox", { parent = teverse.coreInterface, size = guiCoord(0, 60, 0, 16), position = guiCoord(0.5, 5, 1, -16), strokeRadius = 2, text = "Reload", textAlign = "middle", textSize = 12 }) local test = teverse.construct("guiTextBox", { parent = teverse.coreInterface, size = guiCoord(0, 90, 0, 16), position = guiCoord(1.0, -140, 1, -16), strokeRadius = 2, text = "Remote Test", textAlign = "middle", textSize = 12 }) reload:on("mouseLeftUp", function() teverse.apps:reload() end) share:on("mouseLeftUp", function() share.visible = false reload.visible = false local backdrop = teverse.construct("guiFrame", { parent = teverse.coreInterface, size = guiCoord(1, 0, 1, 0), position = guiCoord(0, 0, 0, 0), backgroundColour = colour(.25, .25, .25), backgroundAlpha = 0.6, zIndex = 1000 }) local spinner = teverse.construct("guiIcon", { parent = backdrop, size = guiCoord(0, 40, 0, 40), position = guiCoord(0.5, -20, 0.5, -20), iconMax = 40, iconColour = colour(1, 1, 1), iconType = "faSolid", iconId = "spinner", iconAlpha = 0.9 }) spawn(function() while sleep() and spinner.alive do spinner.rotation = spinner.rotation + math.rad(1) end end) teverse.apps:upload() local success, result = teverse.apps:waitFor("upload") spinner:destroy() local container = teverse.construct("guiTextBox", { parent = backdrop, size = guiCoord(0, 460, 0, 120), position = guiCoord(0.5, -230, 0.5, -60), backgroundColour = colour(1, 1, 1), dropShadowAlpha = 0.3, }) local label = teverse.construct("guiTextBox", { parent = container, size = guiCoord(1.0, -20, 1.0, -20), position = guiCoord(0, 10, 0, 10), backgroundAlpha = 0.0, textSize = 16, textWrap = true, textAlign = "topLeft", textFont = "tevurl:fonts/firaCodeRegular.otf" }) local title = teverse.construct("guiTextBox", { parent = backdrop, size = guiCoord(0, 460, 0, 20), position = guiCoord(0.5, -230, 0.5, -80), backgroundColour = colour(0.9, 0.9, 0.9), textSize = 18, dropShadowAlpha = 0.3, textAlign = "middle", zIndex = 2 }) if success then title.backgroundColour = colour.rgb(70, 179, 88) title.textColour = colour.white() title.text = "Uploaded" label.text = "Your app has been submitted\n\nApp Id: " .. result.id .. "\nApp Name: " .. result.name .. "\nPckg Id: " .. result.packageId .. "\nPckg Version: " .. result.packageVersion else title.backgroundColour = colour.rgb(179, 70, 70) title.textColour = colour.white() title.text = "Something went wrong" label.text = result end teverse.input:waitFor("mouseLeftUp") teverse.apps:reload() end) test:on("mouseLeftUp", function() test.visible = false reload.visible = false local backdrop = teverse.construct("guiFrame", { parent = teverse.coreInterface, size = guiCoord(1, 0, 1, 0), position = guiCoord(0, 0, 0, 0), backgroundColour = colour(.25, .25, .25), backgroundAlpha = 0.6, zIndex = 1000 }) local spinner = teverse.construct("guiIcon", { parent = backdrop, size = guiCoord(0, 40, 0, 40), position = guiCoord(0.5, -20, 0.5, -20), iconMax = 40, iconColour = colour(1, 1, 1), iconType = "faSolid", iconId = "spinner", iconAlpha = 0.9 }) spawn(function() while sleep() and spinner.alive do spinner.rotation = spinner.rotation + math.rad(1) end end) teverse.apps:test() local success, result = teverse.apps:waitFor("upload") spinner:destroy() local container = teverse.construct("guiTextBox", { parent = backdrop, size = guiCoord(0, 460, 0, 120), position = guiCoord(0.5, -230, 0.5, -60), backgroundColour = colour(1, 1, 1), dropShadowAlpha = 0.3, }) local label = teverse.construct("guiTextBox", { parent = container, size = guiCoord(1.0, -20, 1.0, -20), position = guiCoord(0, 10, 0, 10), backgroundAlpha = 0.0, textSize = 16, textWrap = true, textAlign = "topLeft", textFont = "tevurl:fonts/firaCodeRegular.otf" }) local title = teverse.construct("guiTextBox", { parent = backdrop, size = guiCoord(0, 460, 0, 20), position = guiCoord(0.5, -230, 0.5, -80), backgroundColour = colour(0.9, 0.9, 0.9), textSize = 18, dropShadowAlpha = 0.3, textAlign = "middle", zIndex = 2 }) if success then teverse.apps:reload() else title.backgroundColour = colour.rgb(179, 70, 70) title.textColour = colour.white() title.text = "Something went wrong" label.text = result end end)
---@diagnostic disable: lowercase-global, undefined-global package.path = '../moontale-unity/Packages/com.hmilne.moontale/Runtime/?.lua;' .. package.path before_each(function() _G.Log = print _text = spy.new(function() end) _clear = spy.new(function() end) _push = spy.new(function() end) _pop = spy.new(function() end) _invalidate = spy.new(function() end) _G.Invalidate = _invalidate _G.Clear = _clear _G.Text = _text _G.Push = _push _G.Pop = _pop require('moontale') end) after_each(function() package.loaded['moontale'] = nil end) describe("Clear()", function() it("calls parent", function() Clear() assert.spy(_clear).was.called(1) end) end) describe("Event()", function() it("pushes a link tag", function() Event(function() end)("Foo") assert.spy(_push).was.called_with('a', '1') assert.spy(_text).was.called_with('Foo') assert.spy(_pop).was.called(1) end) it("responds to raised event", function() local s = spy.new(function() end) Event(s)("Foo") RaiseEvent("eventType", "1") assert.spy(s).was.called_with("eventType") end) it("merges nested events into one tag", function() Event(function() end)(function() Event(function() end)("Foo") end) assert.spy(_push).was.called(1) assert.spy(_pop).was.called(1) end) end) describe("Show()", function() it("can accept strings", function() Show("Foo") assert.spy(_text).was.called_with("Foo") end) it("can accept numbers", function() Show(123) assert.spy(_text).was.called_with("123") end) it("can accept render functions", function() Show(function() Text("Foo") end) assert.spy(_text).was.called_with("Foo") end) end) describe("Display()", function() it("shows passage content", function() _G.Passages = {foo = {content = function() Text("Bar") end}} Display("foo") assert.spy(_text).was.called_with("Bar") end) end) describe("Hover()", function() it("switches changers on mouseover", function() _G.Passages = {p = {content = function() Hover(Style.foo, Style.bar)("Foo") end}} Jump('p') assert.spy(_clear).was.called(1) assert.spy(_push).was.called_with("bar") assert.spy(_push).was.called_with("a", "1") RaiseEvent("mouseover", "1") assert.spy(_clear).was.called(2) assert.spy(_push).was.called_with("foo") end) end) describe("Once()", function() it("executes only the first time", function() local s = spy.new(function() end) _G.Passages = {p = { content = function() Once(function() s() end) end } } Jump('p') assert.spy(s).was.called(1) Reload() assert.spy(s).was.called(1) end) it("accepts a table value to set variables", function() _G.x = nil _G.y = nil _G.Passages = {p = { content = function() Once { x = 1, y = 2 } end } } Jump('p') assert.is_equal(_G.x, 1) assert.is_equal(_G.y, 2) end) end) describe("If()", function() it("shows the content if the condition is true", function() If(true)("Foo") assert.spy(_text).was.called_with("Foo") end) it("hides the content if the condition is false", function () If(false)("Foo") assert.spy(_text).was_not.called() end) end) describe("ElseIf()", function () it("shows the content if the condition is true", function () If(false)("Foo") ElseIf(false)("Bar") ElseIf(true)("Baz") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Baz") end) it("hides the content if the condition is false", function () If(false)("Foo") ElseIf(false)("Bar") assert.spy(_text).was_not.called() end) it("hides the content if the previous If() was taken", function () If(true)("Foo") ElseIf(true)("Bar") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Foo") end) it("hides the content if the previous ElseIf() was taken", function () If(false)("Foo") ElseIf(true)("Bar") ElseIf(true)("Baz") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Bar") end) end) describe("Else()", function () it("shows the content if the previous branch was not taken", function () If(false)("Foo") Else("Bar") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Bar") end) it("hides the content if the previous branch was taken", function () If(true)("Foo") Else("Bar") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Foo") end) end) describe("Style", function () it("pushes the named tag", function () Style.foo("Bar") assert.spy(_push).was.called_with("foo") assert.spy(_text).was.called_with("Bar") assert.spy(_pop).was.called_with() end) it("can be overridden", function () local s = spy.new(function() end) Style.foo = s Style.foo("Bar") Style.foo = nil assert.spy(s).was.called(1) end) end) describe("Align", function () it("pushes the named alignment", function () Align.foo("Bar") assert.spy(_push).was.called_with("align", "foo") assert.spy(_text).was.called_with("Bar") assert.spy(_pop).was.called_with() end) end) describe("Color", function () it("pushes the named colour", function () Color.lightgrey("Bar") assert.spy(_push).was.called_with("color", "#d3d3d3") assert.spy(_text).was.called_with("Bar") assert.spy(_pop).was.called_with() end) it("pushes the given hex colour", function () Color["#123456"]("Bar") assert.spy(_push).was.called_with("color", "#123456") assert.spy(_text).was.called_with("Bar") assert.spy(_pop).was.called_with() end) end) describe("Click()", function() it("only responds to click events", function () local s = spy.new(function() end) On.click(s)("Foo") RaiseEvent("not-click", "1") assert.spy(s).was_not.called() RaiseEvent("click", "1") assert.spy(s).was.called(1) end) end) describe("Link()", function () it("jumps to the given passage on click", function () local s = spy.new(function() end) _G.Passages = {q = { content = s}} Link('q')("Foo") RaiseEvent("click", "1") assert.spy(s).was.called(1) end) end) describe("Repeat()", function () it("repeats the content N times", function () Repeat(12)("Foo") assert.spy(_text).was.called(12) assert.spy(_text).was.called_with("Foo") end) end) describe("ForEach()", function () it("iterates over table literal", function () ForEach {a = 1, b = 2, c = 3}(function() Text(key..value) end) assert.spy(_text).was.called_with('a1') assert.spy(_text).was.called_with('b2') assert.spy(_text).was.called_with('c3') end) it("accepts names for iteration variables", function () ForEach({a = 1, b = 2, c = 3}, 'x', 'y')(function() Text(x..y) end) assert.spy(_text).was.called_with('a1') assert.spy(_text).was.called_with('b2') assert.spy(_text).was.called_with('c3') end) end) describe("Name", function () it("can be used to store and retrieve content", function () Name.foo("Bar") Show(foo) assert.spy(_text).was.called_with("Bar") end) end) describe("Combine()", function () it("combines multiple changers into one", function () Combine(Style.foo, Style.bar)("Baz") assert.spy(_push).was.called_with('foo') assert.spy(_push).was.called_with('bar') assert.spy(_text).was.called_with('Baz') assert.spy(_pop).was.called(2) end) it("accepts a single argument", function () Combine(Style.foo)("Baz") assert.spy(_push).was.called_with('foo') assert.spy(_text).was.called_with('Baz') assert.spy(_pop).was.called(1) end) end) describe("Delay()", function () it("pauses execution until enough time has passed", function () _G.Passages = {a = {content = function () Text("Foo") Delay(2) Text("Bar") end}} Jump("a") assert.spy(_text).was.called(1) assert.spy(_text).was.called_with("Foo") Update(1) assert.spy(_text).was.called(1) Update(1) assert.spy(_text).was.called(2) end) end) describe("Typewriter()", function () it("displays letters one at a time", function () _G.Passages = {a = {content = function() Typewriter("ABCDEF") end}} Jump("a") for i=1,6 do assert.spy(_text).was.called(i) Update(0.01) end end) end) describe("LinkReplace()", function () it("shows the first argument normally", function () _G.Passages = {a = {content = function() LinkReplace("Foo")("Bar") end}} Jump("a") assert.spy(_text).was.called_with("Foo") end) it("shows the second argument after clicking", function () _G.Passages = {a = {content = function() LinkReplace("Foo")("Bar") end}} Jump("a") RaiseEvent("click", 1) assert.spy(_clear).was.called(2) assert.spy(_text).was.called_with("Bar") end) end) describe("special passage tags", function () it("displays 'startup' passages on a SoftReset", function () _G.Passages = { a = {tags = {startup = true}, content = function () Text('Foo') end}, b = {tags = { }, content = function () Text('Bar') end}, } _G.StartPassage = 'b' SoftReset() assert.spy(_text).was.called(2) assert.spy(_text).was.called_with('Foo') assert.spy(_text).was.called_with('Bar') end) it("displays 'header' passages at the start of every passage", function () _G.Passages = { a = {tags = {header = true}, content = function () Text('Foo') end}, b = {tags = { }, content = function () Text('Bar') end}, } CollectSpecialPassages() Jump('b') assert.spy(_text).was.called(2) assert.spy(_text).was.called_with('Foo') assert.spy(_text).was.called_with('Bar') end) it("dispays 'footer' passages at the end of every passage", function () _G.Passages = { a = {tags = {footer = true}, content = function () Text('Foo') end}, b = {tags = { }, content = function () Text('Bar') end}, } CollectSpecialPassages() Jump('b') assert.spy(_text).was.called(2) assert.spy(_text).was.called_with('Foo') assert.spy(_text).was.called_with('Bar') end) end)
-- file: 'thanks.lua' -- desc: to print the list of the contributing guys function list_iter (t) local i = 0 local n = table.getn(t) return function () i = i + 1 if i <= n then return t[i] end end end helpful_guys = { "----参与翻译----", "buxiu", "凤舞影天", "zhang3", "morler", "lambda", "sunlight", "\n", "----参与校对----", "凤舞影天", "doyle", "flicker", "花生魔人", "zhang3", "Kasi", "\n" } for e in list_iter(helpful_guys) do print(e) end
--[[ -- 作者:左笑林 -- 日期:2017-03-02 -- 文件名:file_operation.lua -- 版权说明:南京正溯网络科技有限公司.版权所有©copy right. -- 本文件主要用于文件相关操作语句的扩展函数 --]] local lfs = require("lfs") local _M ={} _M.__index = _M; function _M.new() return setmetatable({},_M) end function getType(path) return lfs.attributes(path).mode end function getSize(path) return lfs.attributes(path).size end function isDir(path) return getType(path) == "directory" end function findx(str,x) for i = 1,#str do if string.sub(str,-i,-i) == x then return -i end end end function getName(str) return string.sub(str,findx(str,"/") + 1,-1) end function getJson(path) local table = "{" for file in lfs.dir(path) do p = path .. "/" .. file if file ~= "." and file ~= '..' then if isDir(p) then s = "{'text':'".. file .. "','type':'" .. getType(p) .. "','path':'" .. p .. "','children':[]}," else s = "{'text':'".. file .. "','type':'" .. getType(p) .. "','path':'" .. p .. "','size':" .. getSize(p) .. ",'leaf':true}," end table = table .. s end end table = table .. "}" return table end return _M
-- settings for various lsp local yamlls_settings = { yaml = { schemas = { ['https://json.schemastore.org/ansible-playbook'] = '*-pb.{yml,yaml}', ['http://json.schemastore.org/gitlab-ci'] = '.gitlab-ci.{yml,yaml}', }, validate = true, hover = true, completion = true, format = { enable = true } } } -- lsp attaching local has_lsp, nvim_lsp = pcall(require, 'lspconfig') if has_lsp then nvim_lsp.bashls.setup{on_attach = on_attach_lsp} nvim_lsp.vimls.setup{on_attach = on_attach_lsp} nvim_lsp.jsonls.setup{on_attach = on_attach_lsp} nvim_lsp.yamlls.setup{settings = yamlls_settings, on_attach = on_attach } nvim_lsp.dockerls.setup{on_attach = on_attach_lsp} nvim_lsp.html.setup{on_attach = on_attach_lsp} nvim_lsp.cssls.setup{on_attach = on_attach_lsp} nvim_lsp.tsserver.setup{on_attach = on_attach_lsp} nvim_lsp.pyright.setup{on_attach = on_attach_lsp} nvim_lsp.r_language_server.setup{on_attach = on_attach_lsp} nvim_lsp.gopls.setup{on_attach = on_attach_lsp} nvim_lsp.rust_analyzer.setup{on_attach = on_attach_lsp} end -- treesitter settings require'nvim-treesitter.configs'.setup { ensure_installed = "maintained", highlight = { enable = true, disable = { }, }, }
local root = script.Parent.Parent local PluginModules = root:FindFirstChild("PluginModules") local Color = require(PluginModules:FindFirstChild("Color")) local PluginEnums = require(PluginModules:FindFirstChild("PluginEnums")) local Style = require(PluginModules:FindFirstChild("Style")) local includes = root:FindFirstChild("includes") local Roact = require(includes:FindFirstChild("Roact")) local RoactRodux = require(includes:FindFirstChild("RoactRodux")) local Components = root:FindFirstChild("Components") local Button = require(Components:FindFirstChild("Button")) local ColorGrids = require(Components:FindFirstChild("ColorGrids")) local StandardComponents = require(Components:FindFirstChild("StandardComponents")) local StandardTextLabel = StandardComponents.TextLabel --- local MIN_STEPS = 4 local MAX_STEPS = 14 local ColorVariations = Roact.PureComponent:extend("ColorVariations") ColorVariations.render = function(self) local variationSteps = self.props.variationSteps local modifiedColors = { Hues = {}, Shades = {}, Tints = {}, Tones = {}, } for i = 1, variationSteps do local color = Color.fromColor3(self.props.color) modifiedColors.Shades[i] = Color.toColor3(Color.darken(color, i/2)) modifiedColors.Tints[i] = Color.toColor3(Color.brighten(color, i/2)) modifiedColors.Tones[i] = Color.toColor3(Color.desaturate(color, i/2)) local h, s, b = Color.toHSB(color) h = (h + (i / (MAX_STEPS + 1))) % 1 modifiedColors.Hues[i] = Color.toColor3(Color.fromHSB(h, s, b)) end return Roact.createFragment({ ColorStepsPicker = Roact.createElement("Frame", { AnchorPoint = Vector2.new(1, 0), Size = UDim2.new(0, (Style.StandardButtonSize * 2) + (Style.MinorElementPadding * 3) + 20 + 60, 0, Style.StandardButtonSize), Position = UDim2.new(1, 0, 0, 0), BackgroundTransparency = 1, BorderSizePixel = 0, }, { IncrementButton = Roact.createElement(Button, { AnchorPoint = Vector2.new(1, 0.5), Position = UDim2.new(1, 0, 0.5, 0), displayType = "image", image = Style.AddImage, disabled = (variationSteps >= MAX_STEPS), onActivated = function() self.props.updateVariationSteps(variationSteps + 1) end, }), DecrementButton = Roact.createElement(Button, { AnchorPoint = Vector2.new(0, 0.5), Position = UDim2.new(0, 60 + Style.MinorElementPadding, 0.5, 0), displayType = "image", image = Style.SubtractImage, disabled = (variationSteps <= MIN_STEPS), onActivated = function() self.props.updateVariationSteps(variationSteps - 1) end, }), StepsLabel = Roact.createElement(StandardTextLabel, { AnchorPoint = Vector2.new(0, 0.5), Size = UDim2.new(0, 60, 1, 0), Position = UDim2.new(0, 0, 0.5, 0), Text = "Color Steps", }), StepsCountLabel = Roact.createElement(StandardTextLabel, { AnchorPoint = Vector2.new(1, 0.5), Size = UDim2.new(0, 20, 1, 0), Position = UDim2.new(1, -(Style.StandardButtonSize + Style.MinorElementPadding), 0.5, 0), Text = variationSteps, TextXAlignment = Enum.TextXAlignment.Center, TextYAlignment = Enum.TextYAlignment.Center, }) }), Colors = Roact.createElement(ColorGrids, { AnchorPoint = Vector2.new(0.5, 1), Position = UDim2.new(0.5, 0, 1, 0), Size = UDim2.new(1, -2, 1, -(Style.StandardButtonSize + Style.MinorElementPadding + 2)), named = true, colorLists = modifiedColors, onColorSelected = function(index, schemeName) self.props.setColor(modifiedColors[schemeName][index]) end }) }) end --- return RoactRodux.connect(function(state) return { color = state.colorEditor.color, variationSteps = state.sessionData.variationSteps, } end, function(dispatch) return { setColor = function(color) dispatch({ type = PluginEnums.StoreActionType.ColorEditor_SetColor, color = color }) end, updateVariationSteps = function(steps) dispatch({ type = PluginEnums.StoreActionType.UpdateSessionData, slice = { variationSteps = steps } }) end, } end)(ColorVariations)
local USER_ID = KEYS[1] local GROUP_ID = KEYS[2] local NOW = tonumber(KEYS[3]) local BUCKET_LIFETIME_MS = tonumber(KEYS[4]) local bucket_now = redis.call('zscore', 'bi:' .. GROUP_ID, USER_ID) if bucket_now ~= nil and bucket_now ~= false and tonumber(bucket_now) + BUCKET_LIFETIME_MS > NOW then redis.call('zadd', 'bi:' .. GROUP_ID, NOW, USER_ID) local k = 'b:' .. GROUP_ID .. ":" .. USER_ID local all_subscription_inbox = redis.call('smembers', k) redis.call('del', k) if #all_subscription_inbox > 0 then local out = {} for i=1, #all_subscription_inbox, 1 do local mk = 'm:' .. GROUP_ID .. ':' .. all_subscription_inbox[i] local theMessage = redis.call('hget', mk, 'c') local newR = redis.call('hincrby', mk, 'r', -1) if newR < 1 then redis.call('del', mk) end table.insert(out, theMessage) end return table.concat(out, ',') else return 0 end else return -1 end
local ldb = require("lua-db.lua_db") local raw = {} -- this module contains some shortcuts for encoding/decoding raw pixel -- data from lua-db. No headers are checked, but the string lenght must -- must match width*height*4. The raw pixel format is always 32bpp RGBA. -- string+dimensions to new drawbuffer function raw.decode_from_string_drawbuffer(str, width, height) local db = ldb.new(width, height) assert(db:load_data(str)) return db end -- filepath+dimensions to new drawbuffer function raw.decode_from_file_drawbuffer(filepath, width, height) local file = assert(io.open(filepath, "rb")) local str = file:read("*a") return raw.decode_from_string_drawbuffer(str, width, height) end -- decode from a file into a new drawbuffer function raw.decode_from_file_drawbuffer(filepath, width, height) local file = assert(io.open(filepath, "rb")) local str = file:read("*a") return raw.decode_from_string_drawbuffer(str, width, height) end -- drawbuffer to string(dump data) function raw.encode_from_drawbuffer(db) local str = db:dump_data() return str end return raw
object_tangible_food_generic_drink_deuterium_pyro = object_tangible_food_generic_shared_drink_deuterium_pyro:new { } ObjectTemplates:addTemplate(object_tangible_food_generic_drink_deuterium_pyro, "object/tangible/food/generic/drink_deuterium_pyro.iff")
require "Polycode/Scene" class "CollisionScene" (Scene) function CollisionScene:CollisionScene(...) if type(arg[1]) == "table" and count(arg) == 1 then if ""..arg[1]:class() == "Scene" then self.__ptr = arg[1].__ptr return end end for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Physics3D.CollisionScene(unpack(arg)) Polycore.__ptr_lookup[self.__ptr] = self end end function CollisionScene:initCollisionScene() local retVal = Physics3D.CollisionScene_initCollisionScene(self.__ptr) end function CollisionScene:Update() local retVal = Physics3D.CollisionScene_Update(self.__ptr) end function CollisionScene:enableCollision(entity, val) local retVal = Physics3D.CollisionScene_enableCollision(self.__ptr, entity.__ptr, val) end function CollisionScene:getCollisionEntityByObject(collisionObject) local retVal = Physics3D.CollisionScene_getCollisionEntityByObject(self.__ptr, collisionObject.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionSceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:getFirstEntityInRay(origin, dest) local retVal = Physics3D.CollisionScene_getFirstEntityInRay(self.__ptr, origin.__ptr, dest.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = RayTestResult("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:getCollisionByScreenEntity(ent) local retVal = Physics3D.CollisionScene_getCollisionByScreenEntity(self.__ptr, ent.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionSceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:testCollision(ent1, ent2) local retVal = Physics3D.CollisionScene_testCollision(self.__ptr, ent1.__ptr, ent2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionResult("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:testCollisionOnCollisionChild(cEnt1, cEnt2) local retVal = Physics3D.CollisionScene_testCollisionOnCollisionChild(self.__ptr, cEnt1.__ptr, cEnt2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionResult("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:testCollisionOnCollisionChild_Convex(cEnt1, cEnt2) local retVal = Physics3D.CollisionScene_testCollisionOnCollisionChild_Convex(self.__ptr, cEnt1.__ptr, cEnt2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionResult("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:testCollisionOnCollisionChild_RayTest(cEnt1, cEnt2) local retVal = Physics3D.CollisionScene_testCollisionOnCollisionChild_RayTest(self.__ptr, cEnt1.__ptr, cEnt2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionResult("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:getCollisionNormalFromCollisionEnts(cEnt1, cEnt2) local retVal = Physics3D.CollisionScene_getCollisionNormalFromCollisionEnts(self.__ptr, cEnt1.__ptr, cEnt2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Vector3("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:getCollisionNormal(ent1, ent2) local retVal = Physics3D.CollisionScene_getCollisionNormal(self.__ptr, ent1.__ptr, ent2.__ptr) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = Vector3("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:applyVelocity(entity, x, y, z) local retVal = Physics3D.CollisionScene_applyVelocity(self.__ptr, entity.__ptr, x, y, z) end function CollisionScene:loadCollisionChild(entity, autoCollide, type) local retVal = Physics3D.CollisionScene_loadCollisionChild(self.__ptr, entity.__ptr, autoCollide, type) end function CollisionScene:enableGravity(entity) local retVal = Physics3D.CollisionScene_enableGravity(self.__ptr, entity.__ptr) end function CollisionScene:stopTrackingCollision(entity) local retVal = Physics3D.CollisionScene_stopTrackingCollision(self.__ptr, entity.__ptr) end function CollisionScene:addCollisionChild(newEntity, autoCollide, type, group) local retVal = Physics3D.CollisionScene_addCollisionChild(self.__ptr, newEntity.__ptr, autoCollide, type, group) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionSceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:trackCollision(newEntity, autoCollide, type, group) local retVal = Physics3D.CollisionScene_trackCollision(self.__ptr, newEntity.__ptr, autoCollide, type, group) if retVal == nil then return nil end if Polycore.__ptr_lookup[retVal] ~= nil then return Polycore.__ptr_lookup[retVal] else Polycore.__ptr_lookup[retVal] = CollisionSceneEntity("__skip_ptr__") Polycore.__ptr_lookup[retVal].__ptr = retVal return Polycore.__ptr_lookup[retVal] end end function CollisionScene:adjustForCollision(collisionEntity) local retVal = Physics3D.CollisionScene_adjustForCollision(self.__ptr, collisionEntity.__ptr) end function CollisionScene:__delete() Polycore.__ptr_lookup[self.__ptr] = nil Physics3D.delete_CollisionScene(self.__ptr) end
local ucursor = require 'luci.model.uci'.cursor() local json = require 'luci.jsonc' local server_section = arg[1] local local_port = arg[3] local host = arg[4] local server = ucursor:get_all('vssr', server_section) local ssr = { server = host, server_port = server.server_port, local_address = '0.0.0.0', local_port = local_port, password = server.password, timeout = (server.timeout ~= nil) and server.timeout or 60, method = server.encrypt_method, protocol = server.protocol, protocol_param = server.protocol_param, obfs = server.obfs, obfs_param = server.obfs_param, reuse_port = true, fast_open = (server.fast_open == '1') and true or false } print(json.stringify(ssr, 1))
local BattleMemories = {}; local Players = GAMESTATE:GetHumanPlayers(); local thisTapTiming = {} return Def.ActorFrame{ Def.Quad{--Timing InitCommand=cmd(zoom,20;visible,false); OnCommand=function(self) for pn in ivalues(Players) do thisTapTiming[pn] = {}; end end; JudgmentMessageCommand=function(self,params) if params.HoldNoteScore then return end; local smallTapNoteScore = ToEnumShortString(params.TapNoteScore) local TName,Length = LoadModule("Options.SmartTapNoteScore.lua")() local thisTime = GAMESTATE:GetCurMusicSeconds() if FindInTable(smallTapNoteScore, TName) then if thisTapTiming[params.Player] == nil then thisTapTiming[params.Player] = {} end if params.TapNoteScore == "TapNoteScore_Miss" then thisTapTiming[params.Player][#thisTapTiming[params.Player]+1] = {thisTime,params.TapNoteScore,1}; else thisTapTiming[params.Player][#thisTapTiming[params.Player]+1] = {thisTime,params.TapNoteScore,params.TapNoteOffset}; end end end; OffCommand=function(self) for pn in ivalues(Players) do TP.Eva.TapTiming[pn] = thisTapTiming[pn]; end end; }; --[[Def.Quad{--Battle Memories Condition = (not GAMESTATE:IsCourseMode()) ; InitCommand=cmd(zoom,20;visible,false); JudgmentMessageCommand=function(self,params) PP[params.Player] = params; LP = params.Player; self:sleep(0.05):queuecommand("Addto") end; AddtoCommand=function(self) local params = PP[LP] local tsc = params.TapNoteScore if params.HoldNoteScore then tsc = "nil" end BattleMemories[params.Player] = (BattleMemories[params.Player] or "").. string.format("{%.3f,\"%s\",%.2f,\"%s\"},\n", GAMESTATE:GetCurMusicSeconds(),tostring(tsc), STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetPercentDancePoints()*100, STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetGrade()) LS[params.Player] = STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetPercentDancePoints()*100 -- printf("<1>%d <2>%s <3>%s <4>%s\n%s", -- math.random(1,9), -- tostring(PROFILEMAN:GetProfile(LP):GetGUID()), -- tostring(PROFILEMAN:GetProfileDir("ProfileSlot_Player1")), -- string.gsub( tostring(GAMESTATE:GetCurrentSong():GetSongDir()),"/Songs/",""), -- tostring(GAMESTATE:GetCurrentSteps(LP):GetHash()) -- ) --printf("LP is %s!",tostring(LP)) end; OffCommand=function(self) if GAMESTATE:GetCurMusicSeconds() >= GAMESTATE:GetCurrentSong():GetLastSecond()-1 then for k,LP in pairs(GAMESTATE:GetHumanPlayers()) do if PROFILEMAN:GetProfile(LP):GetDisplayName() then local PathA = tostring(PROFILEMAN:GetProfileDir(LP == PLAYER_1 and "ProfileSlot_Player1" or "ProfileSlot_Player2")).."Memories/BattleMemories/" local PathB = (string.gsub( tostring(GAMESTATE:GetCurrentSong():GetSongDir()),"/Songs/","") or "SomeSong/")..tostring(ToEnumShortString(GAMESTATE:GetCurrentSteps(LP):GetStepsType())).."/"; local PathC; if tostring(GAMESTATE:GetCurrentSteps(LP):GetDifficulty()) == "Difficulty_Edit" then PathC = tostring(GAMESTATE:GetCurrentSteps(LP):GetHash())..".lua" else PathC = tostring(ToEnumShortString(GAMESTATE:GetCurrentSteps(LP):GetDifficulty()))..".lua" end if FILEMAN:DoesFileExist(PathA..PathB..PathC) then local TOD = LoadActor(PathA..PathB..PathC); if LS[LP] == nil then--some how when you play with Both Input return; end --printf("%.2f vs %.2f is %s",LS , TOD[#TOD][3],LS <= TOD[#TOD][3] and "No Highscore..." or "Whatever") if LS[LP] <= TOD[#TOD][3] then return; end end local f = RageFileUtil.CreateRageFile() if f:Open(PathA..PathB..PathC, 2) then if BattleMemories[LP] ~= nil then--Some how f:Write("return {"..BattleMemories[LP]:sub(1,BattleMemories[LP]:len()-2).."};") end --printf("Saving at %s%s%s!!",PathA,PathB,PathC) end f:destroy() --SaveProfileCustom(PROFILEMAN:GetProfile(LP), dir) end end end end; };]] };
---Factory API documentation ---Functions for controlling factory components which are used to ---dynamically spawn game objects into the runtime. ---@class factory factory = {} ---loaded factory.STATUS_LOADED = nil ---loading factory.STATUS_LOADING = nil ---unloaded factory.STATUS_UNLOADED = nil ---The URL identifies which factory should create the game object. ---If the game object is created inside of the frame (e.g. from an update callback), the game object will be created instantly, but none of its component will be updated in the same frame. ---Properties defined in scripts in the created game object can be overridden through the properties-parameter below. ---See go.property for more information on script properties. --- Calling factory.create <> on a factory that is marked as dynamic without having loaded resources ---using factory.load <> will synchronously load and create resources which may affect application performance. ---@param url string|hash|url the factory that should create a game object. ---@param position vector3 the position of the new game object, the position of the game object calling factory.create() is used by default, or if the value is nil. ---@param rotation quaternion the rotation of the new game object, the rotation of the game object calling factory.create() is used by default, or if the value is nil. ---@param properties table the properties defined in a script attached to the new game object. ---@param scale number|vector3 the scale of the new game object (must be greater than 0), the scale of the game object containing the factory is used by default, or if the value is nil ---@return hash the global id of the spawned game object function factory.create(url, position, rotation, properties, scale) end ---This returns status of the factory. ---Calling this function when the factory is not marked as dynamic loading always returns ---factory.STATUS_LOADED. ---@param url string|hash|url the factory component to get status from ---@return constant status of the factory component function factory.get_status(url) end ---Resources are referenced by the factory component until the existing (parent) collection is destroyed or factory.unload is called. ---Calling this function when the factory is not marked as dynamic loading does nothing. ---@param url string|hash|url the factory component to load ---@param complete_function function(self, url, result)) function to call when resources are loaded. function factory.load(url, complete_function) end ---This decreases the reference count for each resource loaded with factory.load. If reference is zero, the resource is destroyed. ---Calling this function when the factory is not marked as dynamic loading does nothing. ---@param url string|hash|url the factory component to unload function factory.unload(url) end return factory
local utils = {} function utils.get_value_or_default(table, name, default) if table and not (table[name] == nil) then local actual_type, expected_type = type(table[name]), type(default) assert( type(table[name]) == type(default), string.format('Invalid type for "%s". Expected "%s", but found "%s".', name, actual_type, expected_type) ) return table[name] else return default end end function utils.get_word_boundaries_in_line(line, word, line_pos) local len = string.len(line) if line_pos > len then return nil, nil end local i = 1 local word_start, word_end = string.find(line, word, i) local closest_word_start, closest_word_end = word_start, word_end while i <= len do i = i + 1 word_start, word_end = string.find(line, word, i) if word_start and word_end and math.abs(line_pos - word_start) < math.abs(line_pos - closest_word_start) and math.abs(word_end - line_pos) < math.abs(closest_word_end - line_pos) then closest_word_start, closest_word_end = word_start, word_end end end if closest_word_start and closest_word_end and (closest_word_start > line_pos or closest_word_end < line_pos) then return nil, nil end return closest_word_start, closest_word_end end function utils.set_qf_list(changes) if changes then local qf_list, i = {}, 0 for file, data in pairs(changes) do local buf_id = -1 if vim.uri and vim.uri.uri_to_bufnr then buf_id = vim.uri.uri_to_bufnr(file) else local file_path = string.gsub(file, 'file://', '') buf_id = vim.fn.bufadd(file_path) end vim.fn.bufload(buf_id) file = string.gsub(file, 'file://', '') for _, change in ipairs(data) do local row, col = change.range.start.line, change.range.start.character i = i + 1 local line = vim.api.nvim_buf_get_lines(buf_id, row, row + 1, false) qf_list[i] = { text = line and line[1], filename = file, lnum = row, col = col, } end end if qf_list and i > 0 then vim.fn.setqflist(qf_list) end end end return utils
digtron.doc = {} if not minetest.get_modpath("doc") then return end local coal_fuel = minetest.get_craft_result({method="fuel", width=1, items={"default:coal_lump"}}).time local dig_stone_count = coal_fuel/digtron.config.dig_cost_cracky local dig_dirt_count = coal_fuel/digtron.config.dig_cost_crumbly local dig_wood_count = coal_fuel/digtron.config.dig_cost_choppy local build_count = coal_fuel/digtron.config.build_cost local battery_ratio = (10000/digtron.config.power_ratio) / coal_fuel -- internationalization boilerplate local MP = minetest.get_modpath(minetest.get_current_modname()) local S, NS = dofile(MP.."/intllib.lua") local pipeworks_enabled = minetest.get_modpath("pipeworks") ~= nil local hoppers_enabled = minetest.get_modpath("hopper") and hopper ~= nil and hopper.add_container ~= nil digtron.doc.core_longdesc = S("A crafting component used in the manufacture of all Digtron block types.") digtron.doc.core_usagehelp = S("Place the Digtron Core in the center of the crafting grid. All Digtron recipes consist of arranging various other materials around the central Digtron Core.") -------------------------------------------------------------------- digtron.doc.builder_longdesc = S("A 'builder' module for a Digtron. By itself it does nothing, but as part of a Digtron it is used to construct user-defined blocks.") digtron.doc.builder_usagehelp = S("A builder head is the most complex component of this system. It has period and offset properties, and also an inventory slot where you \"program\" it by placing an example of the block type that you want it to build." .."\n\n".. "When the \"Save & Show\" button is clicked the properties for period and offset will be saved, and markers will briefly be shown to indicate where the nearest spots corresponding to those values are. The builder will build its output at those locations provided it is moving along the matching axis." .."\n\n".. "There is also an \"Extrusion\" setting. This allows your builder to extrude a line of identical blocks from the builder output, in the direction the output side is facing, until it reaches an obstruction or until it reaches the extrusion limit. This can be useful for placing columns below a bridge, or for filling a large volume with a uniform block type without requiring a large number of builder heads." .."\n\n".. "The \"output\" side of a builder is the side with a black crosshair on it." .."\n\n".. "Builders also have a \"facing\" setting. If you haven't memorized the meaning of the 24 facing values yet, builder heads have a helpful \"Read & Save\" button to fill this value in for you. Simply build a temporary instance of the block in the output location in front of the builder, adjust it to the orientation you want using the screwdriver tool, and then when you click the \"Read & Save\" button the block's facing will be read and saved." .."\n\n".. "Note: if more than one builder tries to build into the same space simultaneously, it is not predictable which builder will take priority. One will succeed and the other will fail. You should arrange your builders to avoid this for consistent results.") -------------------------------------------------------------------- digtron.doc.inventory_longdesc = S("Stores building materials for use by builder heads and materials dug up by digger heads.") digtron.doc.inventory_usagehelp = S("Inventory modules have the same capacity as a chest. They're used both for storing the products of the digger heads and as the source of materials used by the builder heads. A digging machine whose builder heads are laying down cobble can automatically self-replenish in this way, but note that an inventory module is still required as buffer space even if the digger heads produced everything needed by the builder heads in a given cycle." .."\n\n".. "Inventory modules are not required for a digging-only machine. If there's not enough storage space to hold the materials produced by the digging heads the excess material will be ejected out the back of the control block. They're handy for accumulating ores and other building materials, though." .."\n\n".. "Digging machines can have multiple inventory modules added to expand their capacity.") if hoppers_enabled then digtron.doc.inventory_usagehelp = digtron.doc.inventory_usagehelp .."\n\n".. S("Digtron inventory modules are compatible with hoppers, adjacent hoppers will add to or take from their inventories. Hoppers are not part of the Digtron and will not move with it, however. They may be useful for creating a \"docking station\" for a Digtron.") end if pipeworks_enabled then digtron.doc.inventory_usagehelp = digtron.doc.inventory_usagehelp .."\n\n".. S("Inventory modules are compatible with Pipeworks blocks. When a Digtron moves one of the inventory modules adjacent to a pipe it will automatically hook up to it, and disconnect again when it moves on.") end local standard_fuel_doc = S("When a control unit is triggered, it will tally up how much fuel is required for the next cycle and then burn items from the fuel hopper until a sufficient amount of heat has been generated to power the operation. Any leftover heat will be retained by the control unit for use in the next cycle; this is the \"heat remaining in controller furnace\". This means you don't have to worry too much about what kinds of fuel you put in the fuel store, none will be wasted (unless you dig away a control unit with some heat remaining in it, that heat does get wasted)." .."\n\n".. "By using one lump of coal as fuel a digtron can:\n".. "\tBuild @1 blocks\n".. "\tDig @2 stone blocks\n".. "\tDig @3 wood blocks\n".. "\tDig @4 dirt or sand blocks", math.floor(build_count), math.floor(dig_stone_count), math.floor(dig_wood_count), math.floor(dig_dirt_count)) digtron.doc.fuelstore_longdesc = S("Stores fuel to run a Digtron") digtron.doc.fuelstore_usagehelp = S("Digtrons have an appetite. Build operations and dig operations require a certain amount of fuel, and that fuel comes from fuel store modules. Note that movement does not require fuel, only digging and building.") .."\n\n".. standard_fuel_doc if hoppers_enabled then digtron.doc.fuelstore_usagehelp = digtron.doc.fuelstore_usagehelp .."\n\n".. S("Digtron fuel store modules are compatible with hoppers, adjacent hoppers will add to or take from their inventories. Hoppers are not part of the Digtron and will not move with it, however. They may be useful for creating a \"docking station\" for a Digtron.") end if pipeworks_enabled then digtron.doc.fuelstore_usagehelp = digtron.doc.fuelstore_usagehelp .."\n\n".. S("Fuel modules are compatible with Pipeworks blocks. When a Digtron moves one of the inventory modules adjacent to a pipe it will automatically hook up to it, and disconnect again when it moves on.") end -- Battery holders digtron.doc.battery_holder_longdesc = S("Holds RE batteries to run a Digtron") digtron.doc.battery_holder_usagehelp = S("Digtrons have an appetite, and it can be satisfied by electricity as well. Build operations and dig operations require a certain amount of power, and that power comes from the batteries place in the holder. Note that movement does not consume charge, only digging and building." .."\n\n".. "When a control unit is triggered, it will tally up how much power is required for the next cycle and then discharge the batteries in the battery holder until a sufficient amount of heat has been generated to power the operation. Any leftover heat will be retained by the control unit for use in the next cycle; this is the \"heat remaining in controller furnace\". Thus no power is wasted (unless you dig away a control unit with some heat remaining in it, that heat does get wasted), and the discharged batteries can be taken away to be recharged." .."\n\n".. "One fully charged battery can:\n".. "\tBuild @1 blocks\n".. "\tDig @2 stone blocks\n".. "\tDig @3 wood blocks\n".. "\tDig @4 dirt or sand blocks", math.floor(build_count*battery_ratio), math.floor(dig_stone_count*battery_ratio), math.floor(dig_wood_count*battery_ratio), math.floor(dig_dirt_count*battery_ratio)) if pipeworks_enabled then digtron.doc.battery_holder_usagehelp = digtron.doc.battery_holder_usagehelp .."\n\n".. S("Fuel modules are compatible with Pipeworks blocks. When a Digtron moves one of the inventory modules adjacent to a pipe it will automatically hook up to it, and disconnect again when it moves on.") end digtron.doc.combined_storage_longdesc = S("Stores fuel for a Digtron and also has an inventory for building materials") digtron.doc.combined_storage_usagehelp = S("For smaller jobs the two dedicated modules may simply be too much of a good thing, wasting precious Digtron space to give unneeded capacity. The combined storage module is the best of both worlds, splitting its internal space between building material inventory and fuel storage. It has 3/4 building material capacity and 1/4 fuel storage capacity.") .. "\n\n" .. standard_fuel_doc if hoppers_enabled then digtron.doc.combined_storage_usagehelp = digtron.doc.combined_storage_usagehelp .."\n\n".. S("Digtron inventory modules are compatible with hoppers, adjacent hoppers will add to or take from their inventories. A hopper on top of a combined inventory module will insert items into its general inventory, a side hopper will insert items into its fuel inventory, and a hopper on the bottom of a combined inventory module will take items from its general inventory. Hoppers are not part of the Digtron and will not move with it, however. They may be useful for creating a \"docking station\" for a Digtron.") end if pipeworks_enabled then digtron.doc.combined_storage_usagehelp = digtron.doc.combined_storage_usagehelp .."\n\n".. S("Combination modules are compatible with Pipeworks blocks. When a Digtron moves one of the inventory modules adjacent to a pipe it will automatically hook up to it, and disconnect again when it moves on. Items are extracted from the \"main\" inventory, and items coming into the combination module from any direction except the underside are inserted into \"main\". However, a pipe entering the combination module from the underside will attempt to insert items into the \"fuel\" inventory instead.") end --------------------------------------------------------------------- local locked_suffix = "\n\n" .. S("This is the \"locked\" version of the Digtron crate. It can only be used by the player who placed it.") digtron.doc.empty_crate_longdesc = S("An empty crate that a Digtron can be stored in") digtron.doc.empty_crate_usagehelp = S("Digtrons can be pushed around and rotated, and that may be enough for getting them perfectly positioned for the start of a run. But once your digger is a kilometer down under a shaft filled with stairs, how to get it back to the surface to run another pass?" .."\n\n".. "Place an empty Digtron crate next to a Digtron and right-click it to pack the Digtron (and all its inventory and settings) into the crate. You can then collect the crate, bring it somewhere else, build the crate, and then unpack the Digtron from it again. The Digtron will appear in the same relative location and orientation to the crate as when it was packed away inside it.") digtron.doc.loaded_crate_longdesc = S("A crate containing a Digtron array") digtron.doc.loaded_crate_usagehelp = S("This crate contains a Digtron assembly that was stored in it earlier. Place it somewhere and right-click on it to access the label text that was applied to it. There's also a button that causes it to display the shape the deployed Digtron would take if you unpacked the crate, marking unbuildable blocks with a warning marker. And finally there's a button to actually deploy the Digtron, replacing this loaded crate with an empty that can be reused later.") digtron.doc.empty_locked_crate_longdesc = digtron.doc.empty_crate_longdesc digtron.doc.empty_locked_crate_usagehelp = digtron.doc.empty_crate_usagehelp .. locked_suffix digtron.doc.loaded_locked_crate_longdesc = digtron.doc.loaded_crate_longdesc digtron.doc.loaded_locked_crate_usagehelp = digtron.doc.loaded_crate_usagehelp .. locked_suffix ---------------------------------------------------------------------- digtron.doc.controller_longdesc = S("A basic controller to make a Digtron array move and operate.") digtron.doc.controller_usagehelp = S("Right-click on this module to make the digging machine go one step. The digging machine will go in the direction that the control module is oriented." .."\n\n".. "A control module can only trigger once per second. Gives you time to enjoy the scenery and smell the flowers (or their mulched remains, at any rate)." .."\n\n".. "If you're standing within the digging machine's volume, or in a block adjacent to it, you will be pulled along with the machine when it moves.") digtron.doc.auto_controller_longdesc = S("A more sophisticated controller that includes the ability to set the number of cycles it will run for, as well as diagonal movement.") digtron.doc.auto_controller_usagehelp = S("An Auto-control module can be set to run for an arbitrary number of cycles. Once it's running, right-click on it again to interrupt its rampage. If anything interrupts it - the player's click, an undiggable obstruction, running out of fuel - it will remember the number of remaining cycles so that you can fix the problem and set it running again to complete the original plan." .."\n\n".. "The digging machine will go in the direction that the control module is oriented." .."\n\n".. "Auto-controllers can also be set to move diagonally by setting the \"Slope\" parameter to a non-zero value. The controller will then shunt the Digtron in the direction of the arrows painted on its sides every X steps it moves. The Digtron will trigger dig heads when it shunts to the side, but will not trigger builder modules or intermittent dig heads. The \"Offset\" setting determines at what point the lateral motion will take place." .."\n\n".. "The \"Stop block\" inventory slot in an auto-controller allows you to program an auto-controller to treat certain block types as impenetrable obstructions. This can allow you to fence a Digtron in with something so you don't have to carefully count exactly how many steps it should take, for example." .."\n\n".. "Note that the Digtron detects an undiggable block by the item that would be produced when digging it. Setting cobble as the stop block will make both cobble and regular stone undiggable, but setting a block of regular stone (produced from cobble in a furnace) as the stop block will *not* stop a Digtron from digging regular stone (since digging regular stone produces cobble, not stone).") digtron.doc.pusher_longdesc = S("A simplified controller that merely moves a Digtron around without triggering its builder or digger modules") digtron.doc.pusher_usagehelp = S("Aka the \"can you rebuild it six inches to the left\" module. This is a much simplified control module that does not trigger the digger or builder heads when right-clicked, it only moves the digging machine. It's up to you to ensure there's space for it to move into." .."\n\n".. "Since movement alone does not require fuel, a pusher module has no internal furnace. Pushers also don't require traction, since their primary purpose is repositioning Digtrons let's say they have a built-in crane or something.") digtron.doc.axle_longdesc = S("A device that allows one to rotate their Digtron into new orientations") digtron.doc.axle_usagehelp = S("This magical module can rotate a Digtron array in place around itself. Right-clicking on it will rotate the Digtron 90 degrees in the direction the orange arrows on its sides indicate (widdershins around the Y axis by default, use the screwdriver to change this) assuming there's space for the Digtron in its new orientation. Builders and diggers will not trigger on rotation.") --------------------------------------------------------------------- digtron.doc.digger_longdesc = S("A standard Digtron digger head") digtron.doc.digger_usagehelp = S("Facing of a digger head is significant; it will excavate material from the block on the spinning grinder wheel face of the digger head. Generally speaking, you'll want these to face forward - though having them aimed to the sides can also be useful.") digtron.doc.dual_digger_longdesc = S("Two standard Digtron digger heads merged at 90 degrees to each other") digtron.doc.dual_digger_usagehelp = S("This digger head is mainly of use when you want to build a Digtron capable of digging diagonal paths. A normal one-direction dig head would be unable to clear blocks in both of the directions it would be called upon to move, resulting in a stuck Digtron." .."\n\n".. "One can also make use of dual dig heads to simplify the size and layout of a Digtron, though this is generally not of practical use.") digtron.doc.dual_soft_digger_longdesc = S("Two standard soft-material Digtron digger heads merged at 90 degrees to each other") digtron.doc.dual_soft_digger_usagehelp = S("This digger head is mainly of use when you want to build a Digtron capable of digging diagonal paths. A normal one-direction dig head would be unable to clear blocks in both of the directions it would be called upon to move, resulting in a stuck Digtron." .."\n\n".. "Like a normal single-direction soft digger head, this digger only excavates material belonging to groups softer than stone." .."\n\n".. "One can make use of dual dig heads to simplify the size and layout of a Digtron.") digtron.doc.intermittent_digger_longdesc = S("A standard Digtron digger head that only triggers periodically") digtron.doc.intermittent_digger_usagehelp = S("This is a standard digger head capable of digging any material, but it will only trigger periodically as the Digtron moves. This can be useful for punching regularly-spaced holes in a tunnel wall, for example.") digtron.doc.intermittent_soft_digger_longdesc = S("A standard soft-material Digtron digger head that only triggers periodically") digtron.doc.intermittent_soft_digger_usagehelp = S("This is a standard soft-material digger head capable of digging any material, but it will only trigger periodically as the Digtron moves. This can be useful for punching regularly-spaced holes in a tunnel wall, for example.") digtron.doc.soft_digger_longdesc = S("A Digtron digger head that only excavates soft materials") digtron.doc.soft_digger_usagehelp = S("This specialized digger head is designed to excavate only softer material such as sand or gravel. In technical terms, this digger digs blocks belonging to the \"crumbly\", \"choppy\", \"snappy\", \"oddly_diggable_by_hand\" and \"fleshy\" groups." .."\n\n".. "The intended purpose of this digger is to be aimed at the ceiling or walls of a tunnel being dug, making spaces to allow shoring blocks to be inserted into unstable roofs but leaving the wall alone if it's composed of a more stable material." .."\n\n".. "It can also serve as part of a lawnmower or tree-harvester.") --------------------------------------------------------------------- digtron.doc.power_connector_longdesc = S("High-voltage power connector allowing a Digtron to be powered from a Technic power network.") digtron.doc.power_connector_usagehelp = S("A power connector node automatically hooks into adjacent high-voltage (HV) power cables, but it must be configured to set how much power it will draw from the attached network. Right-click on the power connector to bring up a form that shows the current estimated maximum power usage of the Digtron the power connector is part of and a field where a power value can be entered. The estimated maximum power usage is the amount of power this Digtron will use in the worst case situation, with all of its digger heads digging the toughest material and all of its builder heads building a block simultaneously." .."\n\n".. "You can set the power connector's usage lower than this, and if the Digtron is unable to get sufficient power from the network it will use on-board batteries or burnable fuel to make up the shortfall.") --------------------------------------------------------------------- digtron.doc.inventory_ejector_longdesc = S("An outlet that can be used to eject accumulated detritus from a Digtron's inventory.") digtron.doc.inventory_ejector_usagehelp = S("When this block is punched it will search the entire inventory of the Digtron and will eject a stack of items taken from it, provided the items are not set for use by any of the Digtron's builders. It will not eject if the destination block is occupied.") if pipeworks_enabled then digtron.doc.inventory_ejector_usagehelp = digtron.doc.inventory_ejector_usagehelp .."\n\n".. S("Item ejectors are compatible with pipeworks and will automatically connect to a pipeworks tube if one is adjacent in the output location.") end --------------------------------------------------------------------- digtron.doc.duplicator_longdesc = S("A device for duplicating an adjacent Digtron using parts from its inventory.") digtron.doc.duplicator_usagehelp = S("Place the duplicator block adjacent to a Digtron, and then fill the duplicator's inventory with enough parts to recreate the adjacent Digtron. Then place an empty Digtron crate at the duplicator's output (the side with the black \"+\") and click the \"Duplicate\" button in the duplicator's right-click GUI. If enough parts are available the Digtron will be duplicated and packed into the crate, along with all of its programming but with empty inventories.") --------------------------------------------------------------------- digtron.doc.structure_longdesc = S("Structural component for a Digtron array") digtron.doc.structure_usagehelp = S("These blocks allow otherwise-disconnected sections of digtron blocks to be linked together. They are not usually necessary for simple diggers but more elaborate builder arrays might have builder blocks that can't be placed directly adjacent to other digtron blocks and these blocks can serve to keep them connected to the controller." .."\n\n".. "They may also be used for providing additional traction if your digtron array is very tall compared to the terrain surface that it's touching." .."\n\n".. "You can also use them decoratively, or to build a platform to stand on as you ride your mighty mechanical leviathan through the landscape.") digtron.doc.light_longdesc = S("Digtron light source") digtron.doc.light_usagehelp = S("A light source that moves along with the digging machine. Convenient if you're digging a tunnel that you don't intend to outfit with torches or other permanent light fixtures. Not quite as bright as a torch since the protective lens tends to get grimy while burrowing through the earth.") digtron.doc.panel_longdesc = S("Digtron panel") digtron.doc.panel_usagehelp = S("A structural panel that can be made part of a Digtron to provide shelter for an operator, keep sand out of the Digtron's innards, or just to look cool.") digtron.doc.edge_panel_longdesc = S("Digtron edge panel") digtron.doc.edge_panel_usagehelp = S("A pair of structural panels that can be made part of a Digtron to provide shelter for an operator, keep sand out of the Digtron's innards, or just to look cool.") digtron.doc.corner_panel_longdesc = S("Digtron corner panel") digtron.doc.corner_panel_usagehelp = S("A trio of structural panels that can be made part of a Digtron to provide shelter for an operator, keep sand out of the Digtron's innards, or just to look cool.") doc.add_category("digtron", { name = S("Digtron"), description = S("The Digtron system is a set of blocks used to construct tunnel-boring and construction machines."), sorting = "custom", sorting_data = {"summary", "concepts", "noises", "tips"}, build_formspec = doc.entry_builders.text_and_gallery, }) doc.add_entry("digtron", "summary", { name = S("Summary"), data = { text = S("Digtron blocks can be used to construct highly customizable and modular tunnel-boring machines, bridge-builders, road-pavers, wall-o-matics, and other such construction/destruction contraptions." .."\n\n".. "The basic blocks that can be assembled into a functioning digging machine are:" .."\n\n".. "* Diggers, which excavate material in front of them when the machine is triggered\n".. "* Builders, which build a user-configured block in front of them\n".. "* Inventory modules, which hold material produced by the digger and provide material to the builders\n".. "* Control block, used to trigger the machine and move it in a particular direction." .."\n\n".. "A digging machine's components must be connected to the control block via a path leading through the faces of the blocks - diagonal connections across edges and corners don't count.") }}) doc.add_entry("digtron", "concepts", { name = S("Concepts"), data = { text = S("Several general concepts are important when building more sophisticated diggers." .."\n\n".. "Facing - a number between 0-23 that determines which direction a block is facing and what orientation it has. Not all blocks make use of facing (basic blocks such as cobble or sand have no facing, for example) so it's not always necessary to set this when configuring a builder head. The facing of already-placed blocks can be altered through the use of the screwdriver tool." .."\n\n".. "Period - Builder and digger heads can be made periodic by changing the period value to something other than 1. This determines how frequently they trigger. A period of 1 triggers on every block, a period of 2 triggers once every second block, a period of 3 triggers once every third block, etc. These are useful when setting up a machine to place regularly-spaced features as it goes. For example, you could have a builder head that places a torch every 8 steps, or a digger block that punches a landing in the side of a vertical stairwell at every level." .."\n\n".. "Offset - The location at which a periodic module triggers is globally uniform. This is handy if you want to line up the blocks you're building (for example, placing pillars and a crosspiece every 4 blocks in a tunnel, or punching alcoves in a wall to place glass windows). If you wish to change how the pattern lines up, modify the \"offset\" setting." .."\n\n".. "Shift-right-clicking - since most of the blocks of the digging machine have control screens associated with right-clicking, building additional blocks on top of them or rotating them with the screwdriver requires the shift key to be held down when right-clicking on them." .."\n\n".. "Traction - Digtrons cannot fly. By default, they need to be touching one block of solid ground for every three blocks of Digtron in order to move. Digtrons can fall, though - traction is never needed when a Digtron is moving downward. \"Pusher\" controllers can ignore the need for traction when moving in any direction.") }}) doc.add_entry("digtron", "noises", { name = S("Audio cues"), data = { text = S("When a digging machine is unable to complete a cycle it will make one of several noises to indicate what the problem is. It will also set its mouseover text to explain what went wrong." .."\n\n".. "Squealing traction wheels indicates a mobility problem. If the squealing is accompanied by a buzzer, the digging machine has encountered an obstruction it can't dig through. This could be a protected region (the digging machine has only the priviledges of the player triggering it), a chest containing items, or perhaps the digger was incorrectly designed and can't dig the correctly sized and shaped cavity for it to move forward into. There are many possibilities." .."\n\n".. "Squealing traction wheels with no accompanying buzzer indicates that the digging machine doesn't have enough solid adjacent blocks to push off of. Tunnel boring machines cannot fly or swim, not even through lava, and they don't dig fast enough to \"catch sick air\" when they emerge from a cliffside. If you wish to cross a chasm you'll need to ensure that there are builder heads placing a solid surface as you go. If you've built a very tall digtron with a small surface footprint you may need to improve its traction by adding structural modules that touch the ground." .."\n\n".. "A buzzer by itself indicates that the Digtron has run out of fuel. There may be traces remaining in the hopper, but they're not enough to execute the next dig/build cycle." .."\n\n".. "A ringing bell indicates that there are insufficient materials in inventory to supply all the builder heads for this cycle." .."\n\n".. "A short high-pitched honk means that one or more of the builder heads don't have an item set. A common oversight, especially with large and elaborate digging machines, that might be hard to notice and annoying to fix if not noticed right away." .."\n\n".. "Splashing water sounds means your Digtron is digging adjacent to (or through) water-containing blocks. Digtrons are waterproof, but this might be a useful indication that you should take care when installing doors in the tunnel walls you've placed here." .."\n\n".. "A triple \"voop voop voop!\" alarm indicates that there is lava adjacent to your Digtron. Digtrons can't penetrate lava by default, and this alarm indicates that a non-lava-proof Digtron operator may wish to exercise caution when opening the door to clear the obstruction.") }}) doc.add_entry("digtron", "tips", { name = S("Tips and Tricks"), data = { text = S("To more easily visualize the operation of a Digtron, imagine that its cycle of operation follows these steps in order:" .."\n\n".. "* Dig\n* Move\n* Build\n* Allow dust to settle (ie, sand and gravel fall)" .."\n\n".. "If you're building a repeating pattern of blocks, your periodicity should be one larger than your largest offset. For example, if you've laid out builders to create a set of spiral stairs and the offsets are from 0 to 11, you'll want to use periodicity 12." .."\n\n".. "A good way to program a set of builders is to build a complete example of the structure you want them to create, then place builders against the structure and have them \"read\" all of its facings. This also lets you more easily visualize the tricks that might be needed to allow the digtron to pass through the structure as it's being built.") }})
-- // Information --[[ Original Thread: https://v3rmillion.net/showthread.php?tid=1140457 ]] -- // Dependencies local CommandHandler, CommandClass = loadstring(game:HttpGet("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Commands/Module.lua"))() -- // Services local Players = game:GetService("Players") local Workspace = game:GetService("Workspace") local ReplicatedStorage = game:GetService("ReplicatedStorage") -- // Vars local LocalPlayer = Players.LocalPlayer local dropAmmo = Workspace.ServerStuff.dropAmmo local SayMessageRequest = ReplicatedStorage.DefaultChatSystemChatEvents.SayMessageRequest -- // Chat a message to everyone local function ChatMessage(Message) SayMessageRequest:FireServer(Message, "All") end -- // Teleports to player, performes callback, teleports back local function GoToCallback(Player, Callback) -- // Vars local Character = LocalPlayer.Character local PlayerCharacter = Player.Character -- // Make sure isn't dead if (not Character) then return ChatMessage("I am currently dead") end if (not PlayerCharacter) then return ChatMessage("You are dead") end -- // Vars local HumanoidRootPart = Character.HumanoidRootPart local SavedCFrame = HumanoidRootPart.CFrame -- // Teleport HumanoidRootPart.CFrame = PlayerCharacter.HumanoidRootPart.CFrame wait(0.25) -- // Callback Callback() wait(0.25) -- // Teleport back HumanoidRootPart.CFrame = SavedCFrame end -- // local Handler = CommandHandler.new({ Members = {}, MemberType = "Blacklist", }) -- // Help command CommandClass.new({ Name = {"help", "cmds"}, Description = "Shows this.", Handler = Handler, Members = {}, MemberType = "Blacklist", Callback = function() -- // Loop through each help message for _, Command in ipairs(Handler:HelpMenu():split("\n")) do -- // Chat it, delay ChatMessage(Command) wait(0.5) end end }) -- // MRE command CommandClass.new({ Name = {"mre", "lunchbox"}, Description = "Gives you an mre lunchbox (mom packed a gogurt)", Handler = Handler, Members = {}, MemberType = "Blacklist", Callback = function(ExecutePlayer) GoToCallback(ExecutePlayer, function() dropAmmo:FireServer("rations", "MRE") end) end }) -- // Water command CommandClass.new({ Name = {"water", "bottle", "thirsty", "aquafill"}, Description = "Gives you a water bottle (Its not dasani)", Handler = Handler, Members = {}, MemberType = "Blacklist", Callback = function(ExecutePlayer) GoToCallback(ExecutePlayer, function() dropAmmo:FireServer("rations", "Bottle") end) end }) -- // Scrap command CommandClass.new({ Name = {"scrap"}, Description = "Gives you 500 scrap", Handler = Handler, Members = {}, MemberType = "Blacklist", Callback = function(ExecutePlayer) GoToCallback(ExecutePlayer, function() dropAmmo:FireServer("scrap", 500) end) end }) -- // Ammo command local AmmoTypes = {"light", "short", "small", "medium", "heavy", "long", "shells"} CommandClass.new({ Name = {"ammo"}, Description = "Gives you lots of ammo (Case sensitve, e.g. to get light ammo would be !ammo Light)", ArgParse = {"string"}, Handler = Handler, Members = {}, MemberType = "Blacklist", Callback = function(ExecutePlayer, Arguments) -- // Validate ammo local AmmoType = Arguments[1] if not (table.find(AmmoTypes, Arguments[1]:lower())) then return end -- // Make first character uppercase AmmoType = AmmoType:gsub("^%l", string.upper) -- // GoToCallback(ExecutePlayer, function() dropAmmo:FireServer(AmmoType, 500) end) end }) -- // Start Handler:StartChatListen()
includes("Core") includes("StaticBuilds")
--- -- Server and client both need this for scoring event logs -- @section Scoring local pairs = pairs local IsValid = IsValid -- Weapon AMMO_ enum stuff, used only in score.lua/cl_score.lua these days -- Not actually ammo identifiers anymore, but still weapon identifiers. Used -- only in round report (score.lua) to save bandwidth because we can't use -- pooled strings there. Custom SWEPs are sent as classname string and don't -- need to bother with these. AMMO_DEAGLE = 2 AMMO_PISTOL = 3 AMMO_MAC10 = 4 AMMO_RIFLE = 5 AMMO_SHOTGUN = 7 -- Following are custom, intentionally out of ammo enum range AMMO_CROWBAR = 50 AMMO_SIPISTOL = 51 AMMO_C4 = 52 AMMO_FLARE = 53 AMMO_KNIFE = 54 AMMO_M249 = 55 AMMO_M16 = 56 AMMO_DISCOMB = 57 AMMO_POLTER = 58 AMMO_TELEPORT = 59 AMMO_RADIO = 60 AMMO_DEFUSER = 61 AMMO_WTESTER = 62 AMMO_BEACON = 63 AMMO_HEALTHSTATION = 64 AMMO_MOLOTOV = 65 AMMO_SMOKE = 66 AMMO_BINOCULARS = 67 AMMO_PUSH = 68 AMMO_STUN = 69 AMMO_CSE = 70 AMMO_DECOY = 71 AMMO_GLOCK = 72 local WeaponNames --- -- Returns a list of @{Weapon} names -- @return table -- @realm shared function GetWeaponClassNames() if WeaponNames then return WeaponNames end local tbl = {} local weps = weapons.GetList() for i = 1, #weps do local v = weps[i] if v == nil or v.WeaponID == nil then continue end tbl[v.WeaponID] = WEPS.GetClass(v) end for _, v in pairs(scripted_ents.GetList()) do local id = istable(v) and (v.WeaponID or (v.t and v.t.WeaponID)) or nil if id == nil then continue end tbl[id] = WEPS.GetClass(v) end WeaponNames = tbl return WeaponNames end --- -- Reverse lookup from enum to SWEP table. -- Returns a @{Weapon} based on the given ammo -- @param number ammo -- @return Weapon -- @realm shared function EnumToSWEP(ammo) local e2w = GetWeaponClassNames() or {} if e2w[ammo] then return util.WeaponForClass(e2w[ammo]) else return end end --- -- Returns a @{Weapon}'s key based on the given ammo -- @param number ammo -- @param string key -- @return any -- @realm shared function EnumToSWEPKey(ammo, key) local swep = EnumToSWEP(ammo) return swep and swep[key] end --- -- Something the client can display -- This used to be done with a big table of AMMO_ ids to names, now we just use -- the weapon PrintNames. This means it is no longer usable from the server (not -- used there anyway), and means capitalization is slightly less pretty. -- @param number ammo -- @return any same as @{EnumToSWEPKey} -- @realm shared -- @see EnumToSWEPKey function EnumToWep(ammo) return EnumToSWEPKey(ammo, "PrintName") end --- -- something cheap to send over the network -- @param Weapon wep -- @return string the @{Weapon} id -- @realm shared function WepToEnum(wep) if not IsValid(wep) then return end return wep.WeaponID end
-- Borrowed this from Factorio yatm.fluids.fluid_registry.register("yatm_refinery", "vapourized_light_oil", { description = "Vapourized Light Oil", groups = { gas = 1, vapourized = 1, vapourized_light_oil = 1, }, tiles = { source = "yatm_vapourized_light_oil_source.png", flowing = "yatm_vapourized_light_oil_flowing.png", }, fluid_tank = { groups = { gas_tank = 1 }, }, })
do return end -- BROKEN PIECE OF SHIT! :argh: GARRRRRYYYYYYYYYYYYYY!!!!!!!!!!!! function CatmullRomCams.SV.Save(save_data) if not CatmullRomCams.Tracks[player.GetByID(1):UniqueID()] then return end local SaveGameData = {} -- I'm assuming here that you can only save games in singleplayer. Tell me if I'm wrong though! :V for numpad_key, track in pairs(CatmullRomCams.Tracks[player.GetByID(1):UniqueID()]) do SaveGameData[numpad_key] = 1--{} if false then for index, node in ipairs(track) do SaveGameData[numpad_key][index] = {Ent = node:EntIndex(), Data = node:RequestSaveData(true)} end end end return saverestore.WriteTable(SaveGameData, save_data) end function CatmullRomCams.SV.Restore(restore_data) local SavedGameData = saverestore.ReadTable(restore_data) local plyID = player.GetByID(1):UniqueID() PrintTable(SavedGameData) for numpad_key, track in pairs(SavedGameData) do if false then CatmullRomCams.Tracks[plyID][numpad_key] = {} for index, data in ipairs(track) do CatmullRomCams.Tracks[plyID][numpad_key][index] = ents.GetByIndex(node.Ent) CatmullRomCams.Tracks[plyID][numpad_key][index]:ApplyEngineSaveData(node.Data, index == 1) print("Loaded ", CatmullRomCams.Tracks[plyID][numpad_key][index], "'s saverestore data.\nDumping:") PrintTable(node.Data) end end end end saverestore.AddSaveHook( "CatmullRomCams_SaveRestore", CatmullRomCams.SV.Save) saverestore.AddRestoreHook("CatmullRomCams_SaveRestore", CatmullRomCams.SV.Restore)
local cmd = 'gcc -O0 -g -shared -fPIC ' .. ' -I /usr/include/lua5.1/ %s -o %s -llua5.1' return function(pattern) local codegen = require 'lpeg2c.codegen' local c = codegen(pattern) local tmp = os.tmpname() local c_filename = tmp .. '.c' local c_file = io.open(c_filename, 'w') c_file:write(c) c_file:close() local so_filename = tmp .. '.so' local cmd = cmd:format(c_filename, so_filename) os.execute(cmd) local f = assert(package.loadlib( so_filename, 'lua_lpeg2c_match')) os.remove(so_filename) os.remove(c_filename) os.remove(tmp) return f end
local has_telescope, telescope = pcall(require, "telescope") if not has_telescope then error("This plugin requires nvim-telescope/telescope.nvim") end local find = require("telescope._extensions.software-licenses.find") local health = require("telescope._extensions.software-licenses.health") return telescope.register_extension { setup = function(opts) return opts end, exports = {find = find.licenses, health = health.check} }
local button1x, button1y = 1,1 local text1 = " Menu " local button2x, button2y = 3,10 local text2 = "Shutdown" local button3x, button3y = 4,11 local text3 = "Reboot" local button4x, button4y = 2,3 local text4 = " Settings " local button5x, button5y = 2,4 local text5 = " Programs " local menu = 0 local backgroundColorFile = fs.open("M-OS_Rebirthed/config/desktop-background-color.config","r") local backgroundColor = backgroundColorFile.readLine() local function centerText(text) local x,y = term.getSize() local x2,y2 = term.getCursorPos() term.setCursorPos(math.ceil((x / 2) - (text:len() / 2)), y2) print(text) end function drawScreen() menu = 0 if backgroundColor == "1" then term.setBackgroundColor(colors.orange) elseif backgroundColor == "2" then term.setBackgroundColor(colors.magenta) elseif backgroundColor == "3" then term.setBackgroundColor(colors.lightBlue) elseif backgroundColor == "4" then term.setBackgroundColor(colors.yellow) elseif backgroundColor == "5" then term.setBackgroundColor(colors.lime) elseif backgroundColor == "6" then term.setBackgroundColor(colors.cyan) elseif backgroundColor == "7" then term.setBackgroundColor(colors.gray) elseif backgroundColor == "8" then term.setBackgroundColor(colors.lightGray) elseif backgroundColor == "9" then term.setBackgroundColor(colors.cyan) elseif backgroundColor == "a" then term.setBackgroundColor(colors.purple) elseif backgroundColor == "b" then term.setBackgroundColor(colors.blue) elseif backgroundColor == "c" then term.setBackgroundColor(colors.brown) elseif backgroundColor == "d" then term.setBackgroundColor(colors.green) elseif backgroundColor == "e" then term.setBackgroundColor(colors.red) elseif backgroundColor == "f" then term.setBackgroundColor(colors.black) else term.setBackgroundColor(colors.lightBlue) end term.clear() if backgroundColor == "7" then term.setBackgroundColor(colors.lightGray) term.setCursorPos(button1x, button1y) term.clearLine() term.setTextColor(colors.gray) print(text1) else term.setBackgroundColor(colors.gray) term.setCursorPos(button1x, button1y) term.clearLine() term.setTextColor(colors.lightGray) print(text1) end end function goodbye() term.clear() term.setCursorPos(0,h/2) centerText("Goodbye") end function drawMenu() menu = 1 if backgroundColor == "7" then term.setCursorPos(button1x, button1y) term.setBackgroundColor(colors.gray) term.setTextColor(colors.lightGray) print(text1) paintutils.drawFilledBox(1,2,12,12,colors.lightGray) term.setTextColor(colors.gray) term.setCursorPos(button4x, button4y) print(text4) term.setCursorPos(button5x, button5y) print(text5) term.setCursorPos(button2x, button2y) print(text2) term.setCursorPos(button3x, button3y) print(text3) else term.setCursorPos(button1x, button1y) term.setBackgroundColor(colors.lightGray) term.setTextColor(colors.gray) print(text1) paintutils.drawFilledBox(1,2,12,12,colors.gray) term.setTextColor(colors.lightGray) term.setCursorPos(button4x, button4y) print(text4) term.setCursorPos(button5x, button5y) print(text5) term.setCursorPos(button2x, button2y) print(text2) term.setCursorPos(button3x, button3y) print(text3) end end drawScreen() while true do local event, button, cx, cy = os.pullEventRaw() if event == "mouse_click" then if button == 1 then if menu == 0 then if cx >= button1x and cx < text1:len() and cy == button1y then drawMenu() else drawScreen() end elseif menu == 1 then if cx >= button2x and cx < text2:len() and cy == button2y then os.shutdown() elseif cx >= button3x and cx < text3:len() and cy == button3y then os.reboot() elseif cx >= button4x and cx < text4:len() and cy == button4y then shell.run("M-OS_Rebirthed/settings.lua") elseif cx >= button5x and cx < text4:len() and cy == button5y then shell.run("M-OS_Rebirthed/programs.lua") elseif cx >= button1x and cx < text1:len() and cy == button1y then drawScreen() else drawScreen() end else drawScreen() end end end end
WayHandlers = require("lib/way_handlers") local Startpoint_secure = {} -- determine if this way can be used as a start/end point for routing function Startpoint_secure.startpoint_secure(profile,way,result,data) local highway = way:get_value_by_key("highway") local tunnel = way:get_value_by_key("tunnel") if highway ~= "motorway" and highway ~= "motorway_link" and (not tunnel or tunnel == "") then WayHandlers.startpoint(way,result,data,profile) else result.is_startpoint = false end end return Startpoint_secure
vessel=import.FlightGlobals.ActiveVessel vdv=vessel.VesselDeltaV currentStageNum=vessel.currentStage function printStageMass(stageNum) local sdv=vdv.GetStage(stageNum) if sdv!=nil then print("Stage "..stageNum) print("Start Mass:"..sdv.startMass) print("End Mass: "..sdv.endMass) print("Dry Mass: "..sdv.dryMass) print("Fuel Mass: "..sdv.fuelMass) print("Total Mass:"..sdv.stageMass) end end for i=currentStageNum,3,-1 do printStageMass(i) end
--- Premake 5 Glasslight Ninja generator. --- Mykola Konyk, 2021 local p = premake local project = p.project local config = p.config local ninja = p.modules.ninja ninja.project = {} local m = ninja.project -- Write out a build option. function m.write_build_option(option_name, options) if options ~= nil and #options > 0 then p.w(" " .. option_name .. " = $") for _, opt in ipairs(options) do if next(options, _) == nil then p.w(" " .. opt) else p.w(" " .. opt .. " $") end end else p.w(" " .. option_name .. " = ") end end function m.write_build_rule(prj, cfg, rule) local build_file_dir = prj.ninja.build_file_dir local object_files = prj.ninja.object_files local target = path.getrelative(build_file_dir, path.join(cfg.buildtarget.directory, cfg.buildtarget.name)) if object_files ~= nil and #object_files > 0 then p.w("build " .. target .. ": " .. rule .. " || $") for _, obj_file in ipairs(object_files) do if next(object_files, _) == nil then p.w(" " .. obj_file) else p.w(" " .. obj_file .. " $") end end else p.w("build " .. target .. ": " .. rule) end end -- Generate a response file. function m.generate_response(prj) for _, obj_file in ipairs(prj.ninja.object_files) do p.w(obj_file) end p.w(" ") end -- Retrieve dependent libs. function m.get_dep_libs(cfg, s1, s2) local location = cfg.project.location local deps = config.getlinks(cfg, s1, s2) local deps_new = {} for _, dep in ipairs(deps) do local dep_path = path.join(location, dep) table.insert(deps_new, dep_path) end return deps_new end -- Generate a project file. function m.generate(prj) local cfg = prj.ninja.current_cfg local toolset = ninja.get_toolset(cfg) local build_file_dir = prj.ninja.build_file_dir p.w("# project build file") p.w("# generated with premake5 ninja") p.w("") p.w("ninja_required_version = 1.10") p.w("include rules.ninja") p.w("") p.w("# build rules") p.w("") local object_files = {} for _, file in ipairs(cfg.files) do file = path.getrelative(build_file_dir, file) local object_file = path.getrelative(build_file_dir, path.join(cfg.objdir, ninja.remove_relative_dots(path.replaceextension(file, "o")))) if path.iscfile(file) then local cflags = ninja.to_list(ninja.get_cflags(cfg)) local includes = ninja.to_list(ninja.get_includes(cfg, true)) local defines = ninja.to_list(ninja.get_defines(cfg)) table.insert(object_files, object_file) p.w("# Source c file: " .. file) p.w("build " .. object_file .. ": cc " .. file .. " ||") p.w(" flags = " .. cflags) p.w(" includes = " .. includes) p.w(" defines = " .. defines) p.w("") elseif path.iscppfile(file) then local cxxflags = ninja.to_list(ninja.get_cxxflags(cfg)) local includes = ninja.to_list(ninja.get_includes(cfg, true)) local defines = ninja.to_list(ninja.get_defines(cfg)) table.insert(object_files, object_file) p.w("# Source cxx file: " .. file) p.w("build " .. object_file .. ": cxx " .. file .. " ||") p.w(" flags = " .. cxxflags) p.w(" includes = " .. includes) p.w(" defines = " .. defines) p.w("") elseif path.iscppheader(file) then p.w("# Source header file: " .. file) p.w("") end end prj.ninja.object_files = object_files local rule = "" if cfg.kind == p.CONSOLEAPP then p.w("# Console application: " .. cfg.buildtarget.name) if cfg.language == p.C then rule = "link_cc" elseif cfg.language == p.CPP then rule = "link_cxx" end elseif cfg.kind == p.SHAREDLIB then p.w("# Shared library: " .. cfg.buildtarget.name) if cfg.language == p.C then rule = "link_cc" elseif cfg.language == p.CPP then rule = "link_cxx" end elseif cfg.kind == p.STATICLIB then p.w("# Static library: " .. cfg.buildtarget.name) rule = "ar" else p.error("Unsupported target kind") end if rule == "" then p.error("Unsupported target type") end m.write_build_rule(prj, cfg, rule) do local responsefile = path.replaceextension(path.join(build_file_dir, cfg.buildtarget.name), ".response") p.generate(prj, responsefile, m.generate_response) p.w(" responsefile = " .. responsefile) end m.write_build_option("pre_link", {}) m.write_build_option("dep_libs", m.get_dep_libs(cfg, "siblings", "fullpath")) m.write_build_option("sys_libs", config.getlinks(cfg, "system", "fullpath")) m.write_build_option("link_options", table.join(cfg.linkoptions, table.join(toolset.getldflags(cfg), ninja.get_library_paths(cfg, true)))) p.w("") end
--[[ Code obtained from NovaFusion http://nova-fusion.com/2011/04/19/cameras-in-love2d-part-1-the-basics/ --]] local camera = {} camera.pos = require "vector" camera.x = 0 camera.y = 0 camera.scaleX = 1 camera.scaleY = 1 camera.rotation = 0 camera.layers = {} function camera:set() love.graphics.push() love.graphics.rotate(-self.rotation) love.graphics.scale(1 / self.scaleX, 1 / self.scaleY) love.graphics.translate(-self.x, -self.y) end function camera:unset() love.graphics.pop() end function camera:move(dx, dy) self.x = self.x + (dx or 0) self.y = self.y + (dy or 0) end function camera:roate(dr) self.rotation = self.rotation + dr end function camera:scale(sx, sy) sx = sx or 1 self.scaleX = self.scaleX * sx self.scaleY = self.scaleY * (sy or sx) end function camera:setPos(x, y) local x = x - 300 self.x = x or self.x self.y = y or self.y end function camera:setScale(sx, sy) self.scaleX = sx or self.scaleX self.scaleY = sy or self.scaleY end function camera:newLayer(scale, func) table.insert(self.layers, { draw = func, scale = scale}) table.sort(self.layers, function(a, b) return a.scale < b.scale end) end function camera:draw() local bx, by = self.x, self.y for _, v in ipairs(self.layers) do self.x = bx * v.scale self.y = by * v.scale camera:set() v.draw() camera:unset() end end return camera
local map = require 'map' local opts = { noremap = true, silent = true } local telescope = require 'telescope' telescope.setup { extensions = { project = { base_dirs = { { path = '~/REPO', max_depth = 4 }, }, hidden_files = true, -- default: false }, }, defaults = { preview = false, prompt_prefix = '▶ ', selection_caret = '▶ ', layout_config = { horizontal = { preview_width = 0.5 } }, file_ignore_patterns = { 'node_modules/.*', '%.env' }, }, pickers = { file_browser = { theme = 'dropdown' }, find_files = { theme = 'dropdown' }, live_grep = { theme = 'dropdown' }, buffers = { theme = 'dropdown' }, help_tags = { theme = 'dropdown' }, }, } map('n', ';;', ":lua require'telescope'.extensions.project.project{ display_type = 'full' }<CR>", opts) map('n', ';a', "<cmd> lua require('telescope.builtin').file_browser{ cwd = vim.fn.expand('%:p:h')}<cr>", opts) map( 'n', '<c-p>', "<cmd> lua require('telescope.builtin').find_files({find_command = {'rg', '--files', '--hidden', '-g', '!.git'}})<cr>", opts ) map('n', '<c-b>', "<cmd> lua require('telescope.builtin').buffers({ show_all_buffers = true })<cr>", opts) map('n', '<c-g>', "<cmd> lua require('telescope.builtin').live_grep()<cr>", opts)
-- {% extends 'init.base_template.lua' %} -- {% block content %} local elixir_ls_bin = "/elixir-ls/language_server.sh" require('lspconfig').elixirls.setup{ cmd = {elixir_ls_bin}, on_attach = on_attach, capabilities = capabilities, settings = { elixirLS = { dialyzerEnabled = false, fetchDeps = false } } } -- {% endblock %}
--local notifiedPlayerIds = {} local md = TGNSMessageDisplayer.Create() local exemptRookies = {} local Plugin = {} function Plugin:CreateCommands() local exemptCommand = self:BindCommand( "sh_letrookiecommand", nil, function(client, playerPredicate) local player = TGNS.GetPlayer(client) if playerPredicate == nil or playerPredicate == "" then md:ToPlayerNotifyError(player, "You must specify a player.") else local targetPlayer = TGNS.GetPlayerMatching(playerPredicate, nil) if targetPlayer ~= nil then local targetClient = TGNS.GetClient(targetPlayer) if targetClient then if TGNS.PlayerIsRookie(targetPlayer) then exemptRookies[targetClient] = true md:ToPlayerNotifyInfo(player, string.format("%s may command.", TGNS.GetClientName(targetClient))) else md:ToPlayerNotifyError(player, string.format("%s is not a Rookie.", TGNS.GetClientName(targetClient))) end else md:ToPlayerNotifyError(player, string.format("Error locating %s client.", TGNS.GetPlayerName(targetPlayer))) end else md:ToPlayerNotifyError(player, string.format("'%s' does not uniquely match a player.", playerPredicate)) end end end, true) exemptCommand:AddParam{ Type = "string", TakeRestOfLine = true, Optional = true } exemptCommand:Help( "<player> Allow player to command." ) end function Plugin:Initialise() self.Enabled = true local restrictions = { {advisory=function(playerName, teamName) return string.format("Rookies with fewer than 20 TGNS games may not command. %s: help %s fight from the ground!", teamName, playerName) end, test=function(player, numberOfAliveTeammates) local client = TGNS.GetClient(player) local playerIsExempt = client and exemptRookies[client] or false return (TGNS.PlayerIsRookie(player) and not playerIsExempt) and Balance.GetTotalGamesPlayed(TGNS.GetClient(player)) < 20 end}, {advisory=function(playerName, teamName) return string.format("Commanders must be voicecomm vouched when 3+ Primer signer teammates. %s: can anyone vouch %s?", teamName, playerName) end, test=function(player, numberOfAliveTeammates) local client = TGNS.GetClient(player) return #TGNS.Where(TGNS.GetClients(TGNS.GetPlayersOnSameTeam(player)), TGNS.HasClientSignedPrimerWithGames) >= 3 and not (Shine.Plugins.scoreboard:IsVouched(client) or TGNS.HasClientSignedPrimer(client)) end} } local originalGetIsPlayerValidForCommander originalGetIsPlayerValidForCommander = TGNS.ReplaceClassMethod("CommandStructure", "GetIsPlayerValidForCommander", function(self, player) local result = originalGetIsPlayerValidForCommander(self, player) if result and not Shine.Plugins.communityslots:IsClientRecentCommander(TGNS.GetClient(player)) then local playerShouldBePreventedFromCommanding local numberOfAliveTeammates = #TGNS.Where(TGNS.GetPlayersOnSameTeam(player), TGNS.IsPlayerAlive) local infantryPortalCountProvidesExemption if TGNS.PlayerIsMarine(player) then local chairs = TGNS.GetTeamCommandStructures(kMarineTeamType) local workingInfantryPortals = 0 TGNS.DoFor(chairs, function(c) workingInfantryPortals = workingInfantryPortals + TGNS.GetNumberOfWorkingInfantryPortals(c) end) if workingInfantryPortals == 0 then infantryPortalCountProvidesExemption = true end end if ((not TGNS.IsGameInProgress()) or (numberOfAliveTeammates > 2)) and Shine.Plugins.bots:GetTotalNumberOfBots() == 0 and not infantryPortalCountProvidesExemption then TGNS.DoFor(restrictions, function(restriction) playerShouldBePreventedFromCommanding = restriction.test(player, playerName, numberOfAliveTeammates) if playerShouldBePreventedFromCommanding then local playerName = TGNS.GetPlayerName(player) local teamName = TGNS.GetPlayerTeamName(player) md:ToTeamNotifyError(TGNS.GetPlayerTeamNumber(player), string.format("%s: %s", playerName, restriction.advisory(playerName, teamName))) return playerShouldBePreventedFromCommanding end end) end result = not playerShouldBePreventedFromCommanding end return result end) self:CreateCommands() return true end function Plugin:Cleanup() --Cleanup your extra stuff like timers, data etc. self.BaseClass.Cleanup( self ) end Shine:RegisterExtension("groundedrookies", Plugin )
-- Copyright (c) 2018, Souche Inc. local Object = require "utility.object" local Array = require "utility.array" local Function = require "utility.function" local String = require "utility.string" local fs = require "fs" local inner_modules = require "test.inner_modules" return function(name, loaded_modules) local path = package.path local cpath = package.cpath local loaded = Object.assign({}, package.loaded) table.clear(package.loaded) Object.assign(package.loaded, inner_modules, package_loaded or {}, loaded_modules) package.path = package_path or package.path package.cpath = package_cpath or package.cpath local file, err = package.searchpath(name, package.path, ".", "/") if not file then error(err) end if not String.endsWith(file, ".lua") then error("unsupport file: " .. file) end local content, err = fs.read(file) if not content then error(err) end local env = Object.assign({}, _G) env._G = env local lines = Array(String.split(content, "\n")) local fn, err = load(function() local line = nil while(not line and #lines > 0) do line = lines:shift() if String.startsWith(line, "local ") then line = String.trimLeft(string.sub(line, 6)) end end if line then return line .. "\n" else return line end end, content, "bt", env) local ok, res if type(fn) == "function" then ok, res = pcall(fn) end package.path = path package.cpath = cpath table.clear(package.loaded) Object.assign(package.loaded, loaded) if type(fn) ~= "function" or not ok then error(err or res) end if type(res) == "function" then local _res = res res = setmetatable({}, { __call = function(self, ...) return Function.apply(_res, {...}) end }) end if type(res) == "table" then local index = res local metatable = getmetatable(res) while (metatable and metatable.__index) do index = metatable.__index metatable = getmetatable(index) end setmetatable(index, Object.assign(metatable or {}, { __index = { __set__ = function(self, k, v) env[k] = v end, __get__ = function(self, k) return env[k] end } })) else error("module should be a table or function") end return res end
local vim, lsp = vim, vim.lsp local M = {} -- coc diagnostic local function get_coc_diagnostic(diag_type) local has_info, info = pcall(vim.api.nvim_buf_get_var, 0, 'coc_diagnostic_info') if not has_info then return end if info[diag_type] > 0 then return info[diag_type] end return '' end -- nvim-lspconfig -- see https://github.com/neovim/nvim-lspconfig local function get_nvim_lsp_diagnostic(diag_type) if next(lsp.buf_get_clients(0)) == nil then return '' end local active_clients = lsp.get_active_clients() if active_clients then local count = 0 for _, client in ipairs(active_clients) do count = count + vim.tbl_count(vim.diagnostic.get(vim.api.nvim_get_current_buf(), {severity = diag_type})) -- Fix as get_count was deprecated in 0.6.1 -- lsp.diagnostic.get_count(api.nvim_get_current_buf(),diag_type,client.id) end if count ~= 0 then return count .. ' ' end end end function M.get_diagnostic_error() if vim.fn.exists('*coc#rpc#start_server') == 1 then return get_coc_diagnostic('error') elseif not vim.tbl_isempty(lsp.buf_get_clients(0)) then return get_nvim_lsp_diagnostic(vim.diagnostic.severity.ERROR) end return '' end function M.get_diagnostic_warn() if vim.fn.exists('*coc#rpc#start_server') == 1 then return get_coc_diagnostic('warning') elseif not vim.tbl_isempty(lsp.buf_get_clients(0)) then return get_nvim_lsp_diagnostic(vim.diagnostic.severity.WARN) end return '' end function M.get_diagnostic_hint() if vim.fn.exists('*coc#rpc#start_server') == 1 then return get_coc_diagnostic('hint') elseif not vim.tbl_isempty(lsp.buf_get_clients(0)) then return get_nvim_lsp_diagnostic(vim.diagnostic.severity.HINT) end return '' end function M.get_diagnostic_info() if vim.fn.exists('*coc#rpc#start_server') == 1 then return get_coc_diagnostic('information') elseif not vim.tbl_isempty(lsp.buf_get_clients(0)) then return get_nvim_lsp_diagnostic(vim.diagnostic.severity.INFO) end return '' end return M
Test = require('connecttest') require('cardinalities') local events = require('events') local mobile_session = require('mobile_session') local mobile = require('mobile_connection') local tcp = require('tcp_connection') local file_connection = require('file_connection') --------------------------------------------------------------------------------------------- -----------------------------Required Shared Libraries--------------------------------------- --------------------------------------------------------------------------------------------- require('user_modules/AppTypes') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local policyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') APIName = "DeleteFile" -- use for above required scripts. local iTimeout = 5000 local str255Chars = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" local appID0 local iPutFile_SpaceAvailable = 0 local iSpaceAvailable_BeforePutFile = 0 config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" local appIDAndDeviceMac = config.application1.registerAppInterfaceParams.fullAppID.. "_" .. config.deviceMAC.. "/" --local strAppFolder = config.SDLStoragePath..appIDAndDeviceMac strAppFolder = config.pathToSDL .. "storage/"..appIDAndDeviceMac --Process different audio states for media and non-media application local audibleState if commonFunctions:isMediaApp() then audibleState = "AUDIBLE" else audibleState = "NOT_AUDIBLE" end --------------------------------------------------------------------------------------------- -------------------------------------------Common functions------------------------------------- --------------------------------------------------------------------------------------------- --Description: Function used to check file is existed on expected path --file_name: file want to check function file_check(file_name) local file_found=io.open(file_name, "r") if file_found==nil then return false else return true end end -- Test case sending request and checking results in case SUCCESS local function TC_DeleteFile_SUCCESS(self, strTestCaseName, strFileName, strFileType) Test[strTestCaseName] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = strFileName }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. strFileName, fileType = strFileType, appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = nil }) :ValidIf (function(_,data) if data.payload.spaceAvailable == nil then commonFunctions:printError("spaceAvailable parameter is missed") return false else if file_check(strAppFolder .. strFileName) == true then print(" \27[36m File is not delete from storage \27[0m ") return false else return true end end end) end end -- Test case sending request and checking results and spaceAvailable in case SUCCESS local function TC_DeleteFile_Check_spaceAvailable_SUCCESS(self, strTestCaseName, strFileName, strFileType) Test[strTestCaseName] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = strFileName }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. strFileName, fileType = strFileType, appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", spaceAvailable = iSpaceAvailable_BeforePutFile, info = nil}) :Do(function(_,data) --Store spaceAvailable value --iSpaceAvailable_BeforePutFile = data.payload.spaceAvailable --commonFunctions:printError("DeleteFile:spaceAvailable: " .. data.payload.spaceAvailable ) end) end end -- Put file to prepare for delete file step. function putfile(self, strFileName, strFileType, blnPersistentFile, blnSystemFile, strFileNameOnMobile) local strTestCaseName, strSyncFileName, strFileNameOnLocal1 if type(strFileName) == "table" then strTestCaseName = "PutFile_"..strFileName.reportName strSyncFileName = strFileName.fileName elseif type(strFileName) == "string" then strTestCaseName = "PutFile_"..strFileName strSyncFileName = strFileName else commonFunctions:printError("Error: putfile function, strFileName is wrong value type: " .. tostring(strFileName)) end if strFileNameOnMobile ==nil then strFileNameOnMobile = "action.png" end Test[strTestCaseName] = function(self) --mobile side: sending Futfile request local cid = self.mobileSession:SendRPC("PutFile", { syncFileName = strSyncFileName, fileType = strFileType, persistentFile = blnPersistentFile, systemFile = blnSystemFile }, "files/"..strFileNameOnMobile) --mobile side: expect Futfile response EXPECT_RESPONSE(cid, { success = true}) :Do(function(_,data) --Store spaceAvailable value iPutFile_SpaceAvailable = data.payload.spaceAvailable end) :ValidIf(function(_, data) if file_check(strAppFolder .. strSyncFileName) == false and systemFile == false then print(" \27[36m File is not put to storage \27[0m ") return false else return true end end) end end local function ExpectOnHMIStatusWithAudioStateChanged(self, request, timeout, level) if request == nil then request = "BOTH" end if level == nil then level = "FULL" end if timeout == nil then timeout = 10000 end if level == "FULL" then if self.isMediaApplication == true or Test.appHMITypes["NAVIGATION"] == true then if request == "BOTH" then --mobile side: OnHMIStatus notifications EXPECT_NOTIFICATION("OnHMIStatus", { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}, { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "VRSESSION"}, { hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "VRSESSION"}, { hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "HMI_OBSCURED"}, { hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "HMI_OBSCURED"}, { hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "MAIN"}) :Times(6) elseif request == "VR" then --mobile side: OnHMIStatus notification EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" }, { systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" }, { systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "AUDIBLE" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" }) :Times(5) :Timeout(timeout) elseif request == "MANUAL" then --mobile side: OnHMIStatus notification EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" }, { systemContext = "HMI_OBSCURED", hmiLevel = level, audioStreamingState = "ATTENUATED" }, { systemContext = "HMI_OBSCURED", hmiLevel = level, audioStreamingState = "AUDIBLE" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" }) :Times(4) :Timeout(timeout) end elseif self.isMediaApplication == false then if request == "BOTH" then --mobile side: OnHMIStatus notifications EXPECT_NOTIFICATION("OnHMIStatus", { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "VRSESSION"}, { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "HMI_OBSCURED"}, { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) :Times(3) :Timeout(timeout) elseif request == "VR" then --any OnHMIStatusNotifications EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" }) :Times(2) :Timeout(timeout) elseif request == "MANUAL" then --mobile side: OnHMIStatus notification EXPECT_NOTIFICATION("OnHMIStatus", { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "HMI_OBSCURED"}, { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) :Times(2) end end elseif level == "LIMITED" then if self.isMediaApplication == true or Test.appHMITypes["NAVIGATION"] == true then if request == "BOTH" then --mobile side: OnHMIStatus notifications EXPECT_NOTIFICATION("OnHMIStatus", { hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}, { hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "MAIN"}, { hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "MAIN"}) :Times(3) elseif request == "VR" then --mobile side: OnHMIStatus notification EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" }) :Times(3) :Timeout(timeout) elseif request == "MANUAL" then --mobile side: OnHMIStatus notification EXPECT_NOTIFICATION("OnHMIStatus", { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" }, { systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" }) :Times(2) :Timeout(timeout) end elseif self.isMediaApplication == false then EXPECT_NOTIFICATION("OnHMIStatus") :Times(0) DelayedExp(1000) end elseif level == "BACKGROUND" then EXPECT_NOTIFICATION("OnHMIStatus") :Times(0) DelayedExp(1000) end end local function SendOnSystemContext(self, ctx) self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications[config.application1.registerAppInterfaceParams.appName], systemContext = ctx }) end --------------------------------------------------------------------------------------------- -------------------------------------------Preconditions------------------------------------- --------------------------------------------------------------------------------------------- commonSteps:DeleteLogsFileAndPolicyTable() --Print new line to separate new test cases group commonFunctions:newTestCasesGroup("Preconditions") --1. Activate application commonSteps:ActivationApp() --2. Update policy to allow request --TODO: Will be updated after policy flow implementation --policyTable:precondition_updatePolicy_AllowFunctionInHmiLeves({"BACKGROUND", "FULL", "LIMITED", "NONE"}) policyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/ptu_general.json") --------------------------------------------------------------------------------------------- -----------------------------------------I TEST BLOCK---------------------------------------- --CommonRequestCheck: Check of mandatory/conditional request's parameters (mobile protocol)-- --------------------------------------------------------------------------------------------- --Check: -- request with all parameters -- request with only mandatory parameters -- request with all combinations of conditional-mandatory parameters (if exist) -- request with one by one conditional parameters (each case - one conditional parameter) -- request with missing mandatory parameters one by one (each case - missing one mandatory parameter) -- request with all parameters are missing -- request with fake parameters (fake - not from protocol, from another request) -- request is sent with invalid JSON structure -- different conditions of correlationID parameter (invalid, several the same etc.) --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** I TEST BLOCK: Check of mandatory/conditional request's parameters (mobile protocol) ******************************") end --Begin test suit PositiveRequestCheck --Description: -- request with all parameters -- request with only mandatory parameters -- request with all combinations of conditional-mandatory parameters (if exist) -- request with one by one conditional parameters (each case - one conditional parameter) -- request with missing mandatory parameters one by one (each case - missing one mandatory parameter) -- request with all parameters are missing -- request with fake parameters (fake - not from protocol, from another request) -- request is sent with invalid JSON structure -- different conditions of correlationID parameter (invalid, several the same etc.) --Begin test case PositiveRequestCheck.1 --Description: check request with all parameters --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 --Verification criteria: --Precondition: PutFile putfile(self, "test.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_test.png", "test.png", "GRAPHIC_PNG") --End test case CommonRequestCheck.1 --Begin test case PositiveRequestCheck.2 --Description: check request with only mandatory parameters --> The same as CommonRequestCheck.1 --End test case PositiveRequestCheck.2 --Skipped CommonRequestCheck.3-4: There next checks are not applicable: -- request with all combinations of conditional-mandatory parameters (if exist) -- request with one by one conditional parameters (each case - one conditional parameter) --Begin test case CommonRequestCheck.5 --Description: This test is intended to check request with missing mandatory parameters one by one (each case - missing one mandatory parameter) --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715 --Verification criteria: SDL responses invalid data function Test:DeleteFile_missing_mandatory_parameters_syncFileName_INVALID_DATA() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { }) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA", info = nil}) :Timeout(iTimeout) end --End test case CommonRequestCheck.5 --Begin test case PositiveRequestCheck.6 --Description: check request with all parameters are missing --> The same as PositiveRequestCheck.5 --End test case PositiveRequestCheck.6 --Begin test case PositiveRequestCheck.7 --Description: check request with fake parameters (fake - not from protocol, from another request) --Begin test case CommonRequestCheck.7.1 --Description: Check request with fake parameters --Requirement id in JAMA/or Jira ID: APPLINK-4518 --Verification criteria: According to xml tests by Ford team all fake parameters should be ignored by SDL --Precondition: PutFile putfile(self, "test.png", "GRAPHIC_PNG") function Test:DeleteFile_FakeParameters_SUCCESS() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { fakeParameter = 123, syncFileName = "test.png" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. "test.png", fileType = "GRAPHIC_PNG", appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) :ValidIf(function(_,data) if data.params.fakeParameter then commonFunctions:printError(" SDL re-sends fake parameters to HMI in BasicCommunication.OnFileRemoved") return false else return true end end) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) end --End test case CommonRequestCheck.7.1 --Begin test case CommonRequestCheck.7.2 --Description: Check request with parameters of other request --Requirement id in JAMA/or Jira ID: APPLINK-4518 --Verification criteria: SDL ignores parameters of other request --Precondition: PutFile putfile(self, "test.png", "GRAPHIC_PNG") function Test:DeleteFile_ParametersOfOtherRequest_SUCCESS() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "test.png", ttsChunks = { TTSChunk = { text ="SpeakFirst", type ="TEXT", }, TTSChunk = { text ="SpeakSecond", type ="TEXT", } } }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. "test.png", fileType = "GRAPHIC_PNG", appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) :ValidIf(function(_,data) if data.params.ttsChunks then commonFunctions:printError(" SDL re-sends parameters of other request to HMI in BasicCommunication.OnFileRemoved") return false else return true end end) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) end --End test case CommonRequestCheck.7.2 --End test case PositiveRequestCheck.7 --Begin test case CommonRequestCheck.8. --Description: Check request is sent with invalid JSON structure --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715 --Verification criteria: The request with wrong JSON syntax is sent, the response comes with INVALID_DATA result code. --Precondition: PutFile putfile(self, "test.png", "GRAPHIC_PNG") -- missing ':' after syncFileName --payload = '{"syncFileName":"test.png"}' local payload = '{"syncFileName" "test.png"}' commonTestCases:VerifyInvalidJsonRequest(33, payload) --End test case CommonRequestCheck.8 --Begin test case CommonRequestCheck.9 --Description: check request correlation Id is duplicated --Requirement id in JAMA/or Jira ID: --Verification criteria: SDL responses SUCCESS --Precondition: PutFile putfile(self, "test1.png", "GRAPHIC_PNG") putfile(self, "test2.png", "GRAPHIC_PNG") function Test:DeleteFile_Duplicated_CorrelationID_SUCCESS() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "test1.png" }) local msg = { serviceType = 7, frameInfo = 0, rpcType = 0, rpcFunctionId = 33, --DeleteFileID rpcCorrelationId = cid, payload = '{"syncFileName":"test2.png"}' } --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. "test1.png", fileType = "GRAPHIC_PNG", appID = self.applications[config.application1.registerAppInterfaceParams.appName] }, { fileName = strAppFolder .. "test2.png", fileType = "GRAPHIC_PNG", appID = self.applications[config.application1.registerAppInterfaceParams.appName] } ) :Times(2) :Do(function(exp,data) if exp.occurences == 1 then self.mobileSession:Send(msg) end end) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"}) :Times(2) end --End test case CommonRequestCheck.9 ----------------------------------------------------------------------------------------- --End test suit PositiveRequestCheck --------------------------------------------------------------------------------------------- ----------------------------------------II TEST BLOCK---------------------------------------- ----------------------------------------Positive cases--------------------------------------- --------------------------------------------------------------------------------------------- --=================================================================================-- --------------------------------Positive request check------------------------------- --=================================================================================-- --check of each request parameter value in bound and boundary conditions --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** II TEST BLOCK: Positive request check ******************************") end --Begin test suit PositiveRequestCheck --Description: check of each request parameter value in bound and boundary conditions --Begin test case PositiveRequestCheck.1 --Description: Check request with syncFileName parameter value in bound and boundary conditions --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 --Verification criteria: DeleteFile response is SUCCESS arrFileType = {"GRAPHIC_BMP", "GRAPHIC_JPEG", "GRAPHIC_PNG", "AUDIO_WAVE", "AUDIO_MP3", "AUDIO_AAC", "BINARY", "JSON"} arrPersistentFile = {false, true} arrSystemFile = {false} arrFileName = { {fileName = "a", reportName = "min_length_a"}, {fileName = "test", reportName = "middle_length_test"}, {fileName = str255Chars, reportName = "max_length_255_characters"} } for j = 1, #arrFileName do for n = 1, #arrFileType do for m = 1, #arrPersistentFile do for i = 1, #arrSystemFile do -- Precondition Test["ListFiles"] = function(self) --mobile side: sending ListFiles request local cid = self.mobileSession:SendRPC("ListFiles", {} ) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" } ) :Do(function(_,data) --Store spaceAvailable value iSpaceAvailable_BeforePutFile = data.payload.spaceAvailable --commonFunctions:printError("ListFiles: spaceAvailable: " .. data.payload.spaceAvailable) end) end --Precondition: PutFile putfile(self, arrFileName[j], arrFileType[n], arrPersistentFile[m], arrSystemFile[i]) strTestCaseName = "DeleteFile_" .. tostring(arrFileName[j].reportName) .. "_FileType_" .. tostring(arrFileType[n]) .. "_PersistentFile_" .. tostring(arrPersistentFile[m]) .. "_SystemFile_" .. tostring(arrSystemFile[i]) TC_DeleteFile_Check_spaceAvailable_SUCCESS(self, strTestCaseName, arrFileName[j].fileName, arrFileType[n]) end end end end --End test suit PositiveRequestCheck.1 --End test suit PositiveRequestCheck --=================================================================================-- --------------------------------Positive response check------------------------------ --=================================================================================-- --------Checks----------- -- parameters with values in boundary conditions --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** II TEST BLOCK: Positive response check ******************************") commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.") os.execute("sleep "..tonumber(5)) end --Begin test suit PositiveResponseCheck --Description: Check positive responses --There is response from HMI => Ignore this check. --End test suit PositiveResponseCheck ---------------------------------------------------------------------------------------------- ----------------------------------------III TEST BLOCK---------------------------------------- ----------------------------------------Negative cases---------------------------------------- ---------------------------------------------------------------------------------------------- --=================================================================================-- ---------------------------------Negative request check------------------------------ --=================================================================================-- --------Checks----------- -- outbound values -- invalid values(empty, missing, nonexistent, duplicate, invalid characters) -- parameters with wrong type -- invalid json --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** III TEST BLOCK: Negative request check ******************************") end --Begin test suit NegativeRequestCheck --Description: check of each request parameter value out of bound, missing, with wrong type, empty, duplicate etc. --Begin test case NegativeRequestCheck.1 --Description: check of syncFileName parameter value out bound --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715 --Verification criteria: SDL returns INVALID_DATA --Begin test case NegativeRequestCheck.1.1 --Description: check of syncFileName parameter value out lower bound function Test:DeleteFile_empty_outLowerBound_INVALID_DATA() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) end --End test case NegativeRequestCheck.1.1 --Begin test case NegativeRequestCheck.1.2 --Description: check of syncFileName parameter value out upper bound (256 characters) function Test:DeleteFile_outUpperBound_OfPutFileName_256_INVALID_DATA() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = str255Chars .. "x" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) end --End test case NegativeRequestCheck.1.2 --Begin test case NegativeRequestCheck.1.3 --Description: check of syncFileName parameter value out upper bound (501 characters) function Test:DeleteFile_outUpperBound_501_INVALID_DATA() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = str255Chars .. str255Chars .. "x" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) end --End test case NegativeRequestCheck.1.3 --End test case NegativeRequestCheck.1 --Begin test case NegativeRequestCheck.2 --Description: check of syncFileName parameter is invalid values(empty, missing, nonexistent, duplicate, invalid characters) --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715 --Verification criteria: SDL returns INVALID_DATA --Begin test case NegativeRequestCheck.2.1 --Description: check of syncFileName parameter is invalid values(empty) --It is covered in out lower bound case --End test case NegativeRequestCheck.2.1 --Begin test case NegativeRequestCheck.2.2 --Description: check of syncFileName parameter is invalid values(missing) --It is covered by DeleteFile_missing_mandatory_parameters_syncFileName_INVALID_DATA --End test case NegativeRequestCheck.2.2 --Begin test case NegativeRequestCheck.2.3 --Description: check of syncFileName parameter is invalid values(nonexistent) Test["DeleteFile_syncFileName_nonexistentValue_INVALID_DATA"] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "nonexistentValue" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {}) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) :Timeout(iTimeout) end --End test case NegativeRequestCheck.2.3 --Begin test case NegativeRequestCheck.2.4 --Description: check of syncFileName parameter is invalid values(duplicate) --It is not applicable --End test case NegativeRequestCheck.2.4 --Begin test case NegativeRequestCheck.2.5 --Description: check of syncFileName parameter is invalid values(invalid characters) --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715, APPLINK-8083 --Verification criteria: SDL returns INVALID_DATA --Begin test case NegativeRequestCheck.2.5.1 --Description: newline character --Precondition putfile(self, "test1.png", "GRAPHIC_PNG") Test["DeleteFile_syncFileName_invalid_characters_newline_INVALID_DATA"] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "te\nst1.png" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) :Timeout(12000) end --End test case NegativeRequestCheck.2.5.1 --Begin test case NegativeRequestCheck.2.5.2 --Description: newline character Test["DeleteFile_syncFileName_invalid_characters_tab_INVALID_DATA"] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "te\tst1.png" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) :Timeout(12000) end --End test case NegativeRequestCheck.2.5.2 --End test case NegativeRequestCheck.2.5 --End test case NegativeRequestCheck.2 --Begin test case NegativeRequestCheck.3 --Description: check of syncFileName parameter is wrong type --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715 --Verification criteria: SDL returns INVALID_DATA Test["DeleteFile_syncFileName_wrongType_INVALID_DATA"] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = 123 }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { syncFileName = "ON\nSCREEN_PRESETS" }) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil}) :Timeout(iTimeout) end --End test case NegativeRequestCheck.3 --Begin test case NegativeRequestCheck.4 --Description: request is invalid json --payload = '{"syncFileName":"test.png"}' local Payload = '{"syncFileName", "test.png"}' commonTestCases:VerifyInvalidJsonRequest(33, Payload) --End test case NegativeRequestCheck.4 --Begin test case NegativeRequestCheck.5 --Description: Delete system file. --Requirement id in JAMA/or Jira ID: APPLINK-14119 --Verification criteria: SDL returns INVALID_DATA arrFileType = {"GRAPHIC_BMP", "GRAPHIC_JPEG", "GRAPHIC_PNG", "AUDIO_WAVE", "AUDIO_MP3", "AUDIO_AAC", "BINARY", "JSON"} arrPersistentFile = {false, true} --Defect: APPLINK-14212: DeleteFile response: spaceAvailable parameter is wrong value arrSystemFile = {true} arrFileName = { {fileName = "a", reportName = "min_length_a"}, {fileName = "test", reportName = "middle_length_test"}, {fileName = str255Chars, reportName = "max_length_255_characters"} } for j = 1, #arrFileName do for n = 1, #arrFileType do for m = 1, #arrPersistentFile do for i = 1, #arrSystemFile do --Precondition: PutFile putfile(self, arrFileName[j], arrFileType[n], arrPersistentFile[m], arrSystemFile[i]) strTestCaseName = "DeleteFile_" .. tostring(arrFileName[j].reportName) .. "_FileType_" .. tostring(arrFileType[n]) .. "_PersistentFile_" .. tostring(arrPersistentFile[m]) .. "_SystemFile_" .. tostring(arrSystemFile[i]) Test[strTestCaseName] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = arrFileName[j].fileName }) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"}) end end end end end --End test case NegativeRequestCheck.5 --End test suit NegativeRequestCheck --=================================================================================-- ---------------------------------Negative response check------------------------------ --=================================================================================-- --------Checks----------- -- outbound values -- invalid values(empty, missing, nonexistent, invalid characters) -- parameters with wrong type -- invalid json --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** III TEST BLOCK: Negative response check ******************************") commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.") end --Begin test suit NegativeResponseCheck --Description: check of each request parameter value out of bound, missing, with wrong type, empty, duplicate etc. --There is no response from HMI for this request. => Skipped this part. --End test suit NegativeResponseCheck ---------------------------------------------------------------------------------------------- ----------------------------------------IV TEST BLOCK----------------------------------------- ---------------------------------------Result code check-------------------------------------- ---------------------------------------------------------------------------------------------- --Check all uncovered pairs resultCodes+success --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** IV TEST BLOCK: Result code check ******************************") end --Begin test suit ResultCodeCheck --Description: check result code of response to Mobile (SDLAQ-CRS-713) --Begin test case ResultCodeCheck.1 --Description: Check resultCode: SUCCESS --It is covered by test case CommonRequestCheck.1 --End test case resultCodeCheck.1 --Begin test case resultCodeCheck.2 --Description: Check resultCode: INVALID_DATA --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715 --Verification criteria: SDL response INVALID_DATA resultCode to Mobile -- It is covered by DeleteFile_empty_outLowerBound_INVALID_DATA --End test case resultCodeCheck.2 --Begin test case resultCodeCheck.3 --Description: Check resultCode: OUT_OF_MEMORY --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-716 --Verification criteria: SDL returns OUT_OF_MEMORY result code for DeleteFile request IN CASE SDL lacks memory RAM for executing it. --ToDo: Can not check this case. --End test case resultCodeCheck.3 --Begin test case resultCodeCheck.4 --Description: Check resultCode: TOO_MANY_PENDING_REQUESTS --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-717 --Verification criteria: The system has more than 1000 requests at a time that haven't been responded yet.The system sends the responses with TOO_MANY_PENDING_REQUESTS error code for all further requests, until there are less than 1000 requests at a time that have not been responded by the system yet. --Move to another script: ATF_DeleteFile_TOO_MANY_PENDING_REQUESTS.lua --End test case resultCodeCheck.4 --Begin test case resultCodeCheck.5 --Description: Check resultCode: APPLICATION_NOT_REGISTERED --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-718 --Verification criteria: SDL sends APPLICATION_NOT_REGISTERED result code when the app sends a request within the same connection before RegisterAppInterface has been performed yet. -- Unregister application commonSteps:UnregisterApplication() --Send DeleteFile when application not registered yet. function Test:DeleteFile_resultCode_APPLICATION_NOT_REGISTERED() --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "test.png" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Timeout(iTimeout) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, {success = false, resultCode = "APPLICATION_NOT_REGISTERED", info = nil}) :Timeout(iTimeout) end -- Register application again commonSteps:RegisterAppInterface() --ToDo: Work around to help script continnue running due to error with UnregisterApplication and RegisterAppInterface again. Remove it when it is not necessary. commonSteps:RegisterAppInterface() -- Activate app again commonSteps:ActivationApp() --End test case resultCodeCheck.5 --Begin test case resultCodeCheck.6 --Description: Check resultCode: REJECTED --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-719, SDLAQ-CRS-2281 --Verification criteria: --1. In case app in HMI level of NONE sends DeleteFile_request AND the number of requests more than value of 'DeleteFileRequest' param defined in .ini file SDL must respond REJECTED result code to this mobile app -- Precondition 1: Put 6 files putfile(self, "test1.png", "GRAPHIC_PNG") putfile(self, "test2.png", "GRAPHIC_PNG") putfile(self, "test3.png", "GRAPHIC_PNG") putfile(self, "test4.png", "GRAPHIC_PNG") putfile(self, "test5.png", "GRAPHIC_PNG") putfile(self, "test6.png", "GRAPHIC_PNG") -- Precondition 2: Change app to NONE HMI level commonSteps:DeactivateAppToNoneHmiLevel() -- Precondition 3: Send DeleteFile 5 times TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test1_png_SUCCESS", "test1.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test2_png_SUCCESS", "test2.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test3_png_SUCCESS", "test3.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test4_png_SUCCESS", "test4.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test5_png_SUCCESS", "test5.png", "GRAPHIC_PNG") Test["DeleteFile_NONE_HMI_LEVEL_test6_png_REJECTED"] = function(self) --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = "test6.png" }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} ) :Times(0) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = false, resultCode = "REJECTED" }) end -- Activate app again commonSteps:ActivationApp() TC_DeleteFile_SUCCESS(self, "DeleteFile_FULL_HMI_LEVEL_test6_png_SUCCESS", "test6.png", "GRAPHIC_PNG") --End test case resultCodeCheck.6 --Begin test case resultCodeCheck.7 --Description: Check resultCode: GENERIC_ERROR --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-720 --Verification criteria: GENERIC_ERROR comes as a result code in response when all other codes aren't applicable or the unknown issue occurred. --ToDo: Don't know how to produce this case. --End test case resultCodeCheck.7 --Begin test case resultCodeCheck.8 --Description: Check resultCode: UNSUPPORTED_REQUEST --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-1041 (APPLINK-9867 question) --Verification criteria: The platform doesn't support file operations, the UNSUPPORTED_REQUEST responseCode is obtained. General request result is success=false. --ToDo: This requirement is not applicable because current SDL supports DeleteFile API --End test case resultCodeCheck.8 --End test suit resultCodeCheck ---------------------------------------------------------------------------------------------- -----------------------------------------V TEST BLOCK----------------------------------------- ---------------------------------------HMI negative cases------------------------------------- ---------------------------------------------------------------------------------------------- --------Checks----------- -- requests without responses from HMI -- invalid structure of response -- several responses from HMI to one request -- fake parameters -- HMI correlation id check -- wrong response with correct HMI id --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** V TEST BLOCK: HMI negative cases ******************************") commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.") end --Begin test suit HMINegativeCheck --Description: Check negative response from HMI --There is no response from HMI for this request. => Skipped this part. --End test suit HMINegativeCheck ---------------------------------------------------------------------------------------------- -----------------------------------------VI TEST BLOCK---------------------------------------- -------------------------Sequence with emulating of user's action(s)-------------------------- ---------------------------------------------------------------------------------------------- -- Check different request sequence with timeout, emulating of user's actions --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** VI TEST BLOCK: Sequence with emulating of user's action(s) ******************************") end --Begin test suit SequenceCheck --Description: TC's checks SDL behavior by processing -- different request sequence with timeout -- with emulating of user's actions --Begin test case SequenceCheck.1 --Description: Check scenario in test case TC_DeleteFile_01: Delete files from SDL Core with next file types: -- GRAPHIC_BMP -- GRAPHIC_JPEG -- GRAPHIC_PNG -- AUDIO_WAVE -- AUDIO_MP3 --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 --Verification criteria: DeleteFile request is sent for a file already stored in the app's local cache on SDL (app's folder on SDL) and not marked as persistent file on SDL during current ignition/session cycle, the result of the request is deleting the corresponding file from the app's folder on SDL. -- Precondition: PutFile icon_bmp.bmp, icon_jpg.jpeg, icon_png.png, tone_wave.wav, tone_mp3.mp3 putfile(self, "icon_bmp.bmp", "GRAPHIC_BMP", false, false, "icon_bmp.bmp") putfile(self, "icon_jpg.jpeg", "GRAPHIC_JPEG", false, false, "icon_jpg.jpeg") putfile(self, "icon_png.png", "GRAPHIC_PNG", false, false, "icon_png.png") putfile(self, "tone_wave.wav", "AUDIO_WAVE", false, false, "tone_wave.wav") putfile(self, "tone_mp3.mp3", "AUDIO_MP3", false, false, "tone_mp3.mp3") Test["ListFile_ContainsPutFiles"] = function(self) --mobile side: sending ListFiles request local cid = self.mobileSession:SendRPC("ListFiles", {} ) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", filenames = { "icon_bmp.bmp", "icon_jpg.jpeg", "icon_png.png", "tone_mp3.mp3", "tone_wave.wav" } } ) end TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_bmp.bmp", "icon_bmp.bmp", "GRAPHIC_BMP") TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_jpg.jpeg", "icon_jpg.jpeg", "GRAPHIC_JPEG") TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_png.png", "icon_png.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_tone_wave.wav", "tone_wave.wav", "AUDIO_WAVE") TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_tone_mp3.mp3", "tone_mp3.mp3", "AUDIO_MP3") Test["ListFile_WihtoutDeletedFiles"] = function(self) --mobile side: sending ListFiles request local cid = self.mobileSession:SendRPC("ListFiles", {} ) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" } ) :ValidIf(function(_,data) local removedFileNames = { "icon_bmp.bmp", "icon_jpg.jpeg", "icon_png.png", "tone_mp3.mp3", "tone_wave.wav" } local blnResult = true if data.payload.filenames ~= nil then for i = 1, #removedFileNames do for j =1, #data.payload.filenames do if removedFileNames[i] == data.payload.filenames[j] then commonFunctions:printError("Failed: " .. removedFileNames[i] .. " is still in result of ListFiles request") blnResult = false break end end end else print( " \27[32m ListFiles response came without filenames \27[0m " ) return true end return blnResult end) end --End test case SequenceCheck.1 ---------------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_01") --Begin test case SequenceCheck.2 --Description: Cover TC_OnFileRemoved_01 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-329 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing app icon to default after deleting file which was set for app icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_01(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:SetAppIcon() --mobile side: sending SetAppIcon request local cid = self.mobileSession:SendRPC("SetAppIcon",{ syncFileName = imageFile }) --hmi side: expect UI.SetAppIcon request EXPECT_HMICALL("UI.SetAppIcon", { appID = self.applications[config.application1.registerAppInterfaceParams.appName], syncFileName = { imageType = "DYNAMIC", value = strAppFolder .. imageFile } }) :Do(function(_,data) --hmi side: sending UI.SetAppIcon response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect SetAppIcon response EXPECT_RESPONSE(cid, { resultCode = "SUCCESS", success = true }) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_01(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.2 ---------------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_02") --Begin test case SequenceCheck.3 --Description: Cover TC_OnFileRemoved_02 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-330 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing Show image to default after deleting file which was set for Show image. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_02(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:Show() --mobile side: sending Show request local cidShow = self.mobileSession:SendRPC("Show", { mediaClock = "12:34", mainField1 = "Show Line 1", mainField2 = "Show Line 2", mainField3 = "Show Line 3", mainField4 = "Show Line 4", graphic = { value = imageFile, imageType = "DYNAMIC" }, secondaryGraphic = { value = imageFile, imageType = "DYNAMIC" }, statusBar = "new status bar", mediaTrack = "Media Track" }) --hmi side: expect UI.Show request EXPECT_HMICALL("UI.Show", { graphic = { imageType = "DYNAMIC", value = strAppFolder..imageFile }, secondaryGraphic = { imageType = "DYNAMIC", value = strAppFolder..imageFile }, showStrings = { { fieldName = "mainField1", fieldText = "Show Line 1" }, { fieldName = "mainField2", fieldText = "Show Line 2" }, { fieldName = "mainField3", fieldText = "Show Line 3" }, { fieldName = "mainField4", fieldText = "Show Line 4" }, { fieldName = "mediaClock", fieldText = "12:34" }, { fieldName = "mediaTrack", fieldText = "Media Track" }, { fieldName = "statusBar", fieldText = "new status bar" } } }) :Do(function(_,data) --hmi side: sending UI.Show response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect Show response EXPECT_RESPONSE(cidShow, { success = true, resultCode = "SUCCESS" }) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_02(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.3 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_03") --Begin test case SequenceCheck.4 --Description: Cover TC_OnFileRemoved_03 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-331 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Command icon to default after deleting file which was set for the icon of this Command. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). function Test:AddSubMenu() --mobile side: sending AddSubMenu request local cid = self.mobileSession:SendRPC("AddSubMenu", { menuID = 10, position = 500, menuName ="TestMenu" }) --hmi side: expect UI.AddSubMenu request EXPECT_HMICALL("UI.AddSubMenu", { menuID = 10, menuParams = { position = 500, menuName ="TestMenu" } }) :Do(function(_,data) --hmi side: sending UI.AddSubMenu response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect AddSubMenu response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) --mobile side: expect OnHashChange notification EXPECT_NOTIFICATION("OnHashChange") end local function TC_OnFileRemoved_03(imageFile, imageTypeValue, commandID) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:AddCommand() --mobile side: sending AddCommand request local cid = self.mobileSession:SendRPC("AddCommand", { cmdID = commandID, menuParams = { parentID = 10, position = 0, menuName ="TestCommand"..commandID }, cmdIcon = { value = imageFile, imageType ="DYNAMIC" } }) --hmi side: expect UI.AddCommand request EXPECT_HMICALL("UI.AddCommand", { cmdID = commandID, cmdIcon = { value = strAppFolder..imageFile, imageType = "DYNAMIC" }, menuParams = { parentID = 10, position = 0, menuName ="TestCommand"..commandID } }) :Do(function(_,data) --hmi side: sending UI.AddCommand response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect AddCommand response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) --mobile side: expect OnHashChange notification EXPECT_NOTIFICATION("OnHashChange") end function Test:OpenOptionsMenu() SendOnSystemContext(self,"MENU") EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MENU"}) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) function Test:BackToMain() SendOnSystemContext(self,"MAIN") EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MAIN"}) end end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_03(imageFile[i].fileName, imageFile[i].fileType, i+10) end --End test case SequenceCheck.4 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_04") --Begin test case SequenceCheck.5 --Description: Cover TC_OnFileRemoved_04 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-332 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the SoftButton icon to default after deleting file which was set for the icon of this SoftButton. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_04(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:ShowWithSoftButton() --mobile side: sending Show request local cidShow = self.mobileSession:SendRPC("Show", { mediaClock = "12:34", mainField1 = "Show Line 1", mainField2 = "Show Line 2", mainField3 = "Show Line 3", mainField4 = "Show Line 4", graphic = { value = imageFile, imageType = "DYNAMIC" }, secondaryGraphic = { value = imageFile, imageType = "DYNAMIC" }, statusBar = "new status bar", mediaTrack = "Media Track", softButtons = { { text = "", systemAction = "DEFAULT_ACTION", type = "IMAGE", isHighlighted = true, image = { imageType = "DYNAMIC", value = imageFile }, softButtonID = 1 } } }) --hmi side: expect UI.Show request EXPECT_HMICALL("UI.Show", { graphic = { imageType = "DYNAMIC", value = strAppFolder..imageFile }, secondaryGraphic = { imageType = "DYNAMIC", value = strAppFolder..imageFile }, showStrings = { { fieldName = "mainField1", fieldText = "Show Line 1" }, { fieldName = "mainField2", fieldText = "Show Line 2" }, { fieldName = "mainField3", fieldText = "Show Line 3" }, { fieldName = "mainField4", fieldText = "Show Line 4" }, { fieldName = "mediaClock", fieldText = "12:34" }, { fieldName = "mediaTrack", fieldText = "Media Track" }, { fieldName = "statusBar", fieldText = "new status bar" } }, softButtons = { { systemAction = "DEFAULT_ACTION", type = "IMAGE", isHighlighted = true, --[[ TODO: update after resolving APPLINK-16052 image = { imageType = "DYNAMIC", value = strAppFolder..imageFile },]] softButtonID = 1 } } }) :Do(function(_,data) --hmi side: sending UI.Show response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect Show response EXPECT_RESPONSE(cidShow, { success = true, resultCode = "SUCCESS" }) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_04(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.5 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_05") --Begin test case SequenceCheck.6 --Description: Cover TC_OnFileRemoved_05 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-333 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Turn icon of TurnList to default after deleting file which was set for the icon of this Turn. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_05(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:UpdateTurnList() --mobile side: send UpdateTurnList request local CorIdUpdateTurnList = self.mobileSession:SendRPC("UpdateTurnList", { turnList = { { navigationText ="Text", turnIcon = { value = imageFile, imageType ="DYNAMIC", } } } }) --hmi side: expect Navigation.UpdateTurnList request EXPECT_HMICALL("Navigation.UpdateTurnList"--[[ TODO: update after resolving APPLINK-16052, { turnList = { { navigationText = { fieldText = "Text", fieldName = "turnText" }, turnIcon = { value =strAppFolder..imageFile, imageType ="DYNAMIC", } } } }]]) :Do(function(_,data) --hmi side: send Navigation.UpdateTurnList response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS",{}) end) --mobile side: expect UpdateTurnList response EXPECT_RESPONSE(CorIdUpdateTurnList, { success = true, resultCode = "SUCCESS" }) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_05(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.6 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_06") --Begin test case SequenceCheck.7 --Description: Cover TC_OnFileRemoved_06 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-334 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Turn icon, Next Turn icon to default after deleting file which was set for the Turn icon and Next Turn icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_06(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:ShowConstantTBT() --mobile side: sending ShowConstantTBT request cid = self.mobileSession:SendRPC("ShowConstantTBT", { navigationText1 ="navigationText1", navigationText2 ="navigationText2", eta ="12:34", totalDistance ="100miles", turnIcon = { value =imageFile, imageType ="DYNAMIC", }, nextTurnIcon = { value =imageFile, imageType ="DYNAMIC", }, distanceToManeuver = 50.5, distanceToManeuverScale = 100.5, maneuverComplete = false, softButtons = { { type ="BOTH", text ="Close", image = { value =imageFile, imageType ="DYNAMIC", }, isHighlighted = true, softButtonID = 44, systemAction ="DEFAULT_ACTION", }, }, }) --hmi side: expect Navigation.ShowConstantTBT request EXPECT_HMICALL("Navigation.ShowConstantTBT", { navigationTexts = { { fieldName = "navigationText1", fieldText = "navigationText1" }, { fieldName = "navigationText2", fieldText = "navigationText2" }, { fieldName = "ETA", fieldText = "12:34" }, { fieldName = "totalDistance", fieldText = "100miles" } }, turnIcon = { value =strAppFolder..imageFile, imageType ="DYNAMIC", }, nextTurnIcon = { value =strAppFolder..imageFile, imageType ="DYNAMIC", }, distanceToManeuver = 50.5, distanceToManeuverScale = 100.5, maneuverComplete = false, softButtons = { { type ="BOTH", text ="Close", --[[ TODO: update after resolving APPLINK-16052 image = { value =strAppFolder..imageFile, imageType ="DYNAMIC", }, ]] isHighlighted = true, softButtonID = 44, systemAction ="DEFAULT_ACTION", }, }, }) :Do(function(_,data) --hmi side: sending Navigation.ShowConstantTBT response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect SetGlobalProperties response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_06(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.7 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_07") --Begin test case SequenceCheck.8 --Description: Cover TC_OnFileRemoved_07 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-335 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the VRHelp Item icon to default after deleting file which was set for the VRHelp Item icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_07(imageFile, imageTypeValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:SetGlobalProperties() --mobile side: sending SetGlobalProperties request cid = self.mobileSession:SendRPC("SetGlobalProperties", { menuTitle = "Menu Title", timeoutPrompt = { { text = "Timeout prompt", type = "TEXT" } }, vrHelp = { { position = 1, image = { value = imageFile, imageType = "DYNAMIC" }, text = "Help me!" } }, menuIcon = { value = imageFile, imageType = "DYNAMIC" }, helpPrompt = { { text = "Help prompt", type = "TEXT" } }, vrHelpTitle = "New VR help title", keyboardProperties = { keyboardLayout = "QWERTY", keypressMode = "SINGLE_KEYPRESS", limitedCharacterList = { "a" }, language = "EN-US", autoCompleteText = "Daemon, Freedom" } }) --hmi side: expect TTS.SetGlobalProperties request EXPECT_HMICALL("TTS.SetGlobalProperties", { timeoutPrompt = { { text = "Timeout prompt", type = "TEXT" } }, helpPrompt = { { text = "Help prompt", type = "TEXT" } } }) :Do(function(_,data) --hmi side: sending TTS.SetGlobalProperties response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) :Timeout(iTimeout) --hmi side: expect UI.SetGlobalProperties request EXPECT_HMICALL("UI.SetGlobalProperties", { menuTitle = "Menu Title", vrHelp = { { position = 1, --[[ TODO: update after resolving APPLINK-16052 image = { imageType = "DYNAMIC", value = strAppFolder .. imageFile },]] text = "Help me!" } }, menuIcon = { imageType = "DYNAMIC", value = strAppFolder .. imageFile }, vrHelpTitle = "New VR help title", keyboardProperties = { keyboardLayout = "QWERTY", keypressMode = "SINGLE_KEYPRESS", --[[ TODO: update after resolving APPLINK-16047 limitedCharacterList = { "a" },]] language = "EN-US", autoCompleteText = "Daemon, Freedom" } }) :Do(function(_,data) --hmi side: sending UI.SetGlobalProperties response self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) :Timeout(iTimeout) --mobile side: expect SetGlobalProperties response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"}) :Timeout(iTimeout) end function Test:OpenVRMenu() SendOnSystemContext(self,"VRSESSION") EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "VRSESSION"}) end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) function Test:BackToMain() SendOnSystemContext(self,"MAIN") EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MAIN"}) end end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_07(imageFile[i].fileName, imageFile[i].fileType) end --End test case SequenceCheck.8 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_08") --Begin test case SequenceCheck.9 --Description: Cover TC_OnFileRemoved_08 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-336 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Choice icon to default after deleting file, which was set for the Choice icon, during PerformInteraction. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_08(imageFile, imageTypeValue, idValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:CreateInteractionChoiceSet() --mobile side: sending CreateInteractionChoiceSet request local cid = self.mobileSession:SendRPC("CreateInteractionChoiceSet", { interactionChoiceSetID = idValue, choiceSet = { { choiceID = idValue, menuName ="Choice"..idValue, vrCommands = { "VRChoice"..idValue, }, image = { value =imageFile, imageType ="DYNAMIC", }, } } }) --hmi side: expect VR.AddCommand request EXPECT_HMICALL("VR.AddCommand", { cmdID = idValue, appID = self.applications[config.application1.registerAppInterfaceParams.appName], type = "Choice", vrCommands = {"VRChoice"..idValue} }) :Do(function(_,data) --hmi side: sending VR.AddCommand response grammarIDValue = data.params.grammarID self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect CreateInteractionChoiceSet response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) --mobile side: expect OnHashChange notification EXPECT_NOTIFICATION("OnHashChange") end function Test:PerformInteraction() local paramsSend = { initialText = "StartPerformInteraction", initialPrompt = { { text = " Make your choice ", type = "TEXT", } }, interactionMode = "MANUAL_ONLY", interactionChoiceSetIDList = { idValue }, helpPrompt = { { text = " Help Prompt ", type = "TEXT", } }, timeoutPrompt = { { text = " Time out ", type = "TEXT", } }, timeout = 5000, vrHelp = { { text = " New VRHelp ", position = 1, image = { value = strAppFolder..imageFile, imageType = "DYNAMIC", } } }, interactionLayout = "ICON_ONLY" } --mobile side: sending PerformInteraction request cid = self.mobileSession:SendRPC("PerformInteraction", paramsSend) --hmi side: expect VR.PerformInteraction request EXPECT_HMICALL("VR.PerformInteraction", { helpPrompt = paramsSend.helpPrompt, initialPrompt = paramsSend.initialPrompt, timeout = paramsSend.timeout, timeoutPrompt = paramsSend.timeoutPrompt }) :Do(function(_,data) --Send notification to start TTS self.hmiConnection:SendNotification("TTS.Started") self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.") end) --hmi side: expect UI.PerformInteraction request EXPECT_HMICALL("UI.PerformInteraction", { timeout = paramsSend.timeout, choiceSet = { { choiceID = idValue, --[[ TODO: update after resolving APPLINK-16052 image = { value = strAppFolder..imageFile, imageType = "DYNAMIC", },]] menuName = "Choice"..idValue } }, initialText = { fieldName = "initialInteractionText", fieldText = paramsSend.initialText } }) :Do(function(_,data) SendOnSystemContext(self,"HMI_OBSCURED") --mobile side: sending DeleteFile request local cid = self.mobileSession:SendRPC("DeleteFile", { syncFileName = imageFile }) --hmi side: expect BasicCommunication.OnFileRemoved request EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", { fileName = strAppFolder .. imageFile, fileType = imageTypeValue, appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) --mobile side: expect DeleteFile response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = nil }) :ValidIf (function(_,data) if data.payload.spaceAvailable == nil then commonFunctions:printError("spaceAvailable parameter is missed") return false else if file_check(strAppFolder .. imageFile) == true then print(" \27[36m File is not delete from storage \27[0m ") return false else return true end end end) local function uiResponse() --hmi side: send UI.PerformInteraction response self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.") --Send notification to stop TTS self.hmiConnection:SendNotification("TTS.Stopped") SendOnSystemContext(self,"MAIN") end RUN_AFTER(uiResponse, 1000) end) --mobile side: OnHMIStatus notifications ExpectOnHMIStatusWithAudioStateChanged(self, "MANUAL",_, "FULL") --mobile side: expect PerformInteraction response EXPECT_RESPONSE(cid, { success = false, resultCode = "TIMED_OUT"}) end end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_08(imageFile[i].fileName, imageFile[i].fileType, i+20) end --End test case SequenceCheck.9 ----------------------------------------------------------------------------------------- --Print new line to separate new test cases commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_09") --Begin test case SequenceCheck.10 --Description: Cover TC_OnFileRemoved_09 --Requirement id in JAMA/or Jira ID: SDLAQ-TC-338 --Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Choice icon to default after deleting file, which was set for the Choice icon, before PerformInteraction. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types). local function TC_OnFileRemoved_09(imageFile, imageTypeValue, idValue) putfile(self, imageFile, imageTypeValue,_,_,imageFile) function Test:CreateInteractionChoiceSet() --mobile side: sending CreateInteractionChoiceSet request local cid = self.mobileSession:SendRPC("CreateInteractionChoiceSet", { interactionChoiceSetID = idValue, choiceSet = { { choiceID = idValue, menuName ="Choice"..idValue, vrCommands = { "VRChoice"..idValue, }, image = { value =imageFile, imageType ="DYNAMIC", }, } } }) --hmi side: expect VR.AddCommand request EXPECT_HMICALL("VR.AddCommand", { cmdID = idValue, appID = self.applications[config.application1.registerAppInterfaceParams.appName], type = "Choice", vrCommands = {"VRChoice"..idValue} }) :Do(function(_,data) --hmi side: sending VR.AddCommand response grammarIDValue = data.params.grammarID self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) --mobile side: expect CreateInteractionChoiceSet response EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" }) --mobile side: expect OnHashChange notification EXPECT_NOTIFICATION("OnHashChange") end TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue) function Test:PerformInteraction() local paramsSend = { initialText = "StartPerformInteraction", initialPrompt = { { text = " Make your choice ", type = "TEXT", } }, interactionMode = "MANUAL_ONLY", interactionChoiceSetIDList = { idValue }, helpPrompt = { { text = " Help Prompt ", type = "TEXT", } }, timeoutPrompt = { { text = " Time out ", type = "TEXT", } }, timeout = 5000, interactionLayout = "ICON_ONLY" } --mobile side: sending PerformInteraction request cid = self.mobileSession:SendRPC("PerformInteraction", paramsSend) --hmi side: expect VR.PerformInteraction request EXPECT_HMICALL("VR.PerformInteraction", { helpPrompt = paramsSend.helpPrompt, initialPrompt = paramsSend.initialPrompt, timeout = paramsSend.timeout, timeoutPrompt = paramsSend.timeoutPrompt }) :Do(function(_,data) --Send notification to start TTS self.hmiConnection:SendNotification("TTS.Started") self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.") end) --hmi side: expect UI.PerformInteraction request EXPECT_HMICALL("UI.PerformInteraction", { timeout = paramsSend.timeout, choiceSet = { { choiceID = idValue, --[[ TODO: update after resolving APPLINK-16052 image = { value = strAppFolder..imageFile, imageType = "DYNAMIC", },]] menuName = "Choice"..idValue } }, initialText = { fieldName = "initialInteractionText", fieldText = paramsSend.initialText } }) :Do(function(_,data) --hmi side: send UI.PerformInteraction response SendOnSystemContext(self,"HMI_OBSCURED") self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.") --Send notification to stop TTS self.hmiConnection:SendNotification("TTS.Stopped") SendOnSystemContext(self,"MAIN") end) --mobile side: OnHMIStatus notifications ExpectOnHMIStatusWithAudioStateChanged(self, "MANUAL",_, "FULL") --mobile side: expect PerformInteraction response EXPECT_RESPONSE(cid, { success = false, resultCode = "TIMED_OUT"}) end end local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"}, {fileName = "action.bmp", fileType ="GRAPHIC_BMP"}, {fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}} for i=1,#imageFile do TC_OnFileRemoved_09(imageFile[i].fileName, imageFile[i].fileType, i+30) end --End test case SequenceCheck.10 --End test suit SequenceCheck ---------------------------------------------------------------------------------------------- -----------------------------------------VII TEST BLOCK--------------------------------------- --------------------------------------Different HMIStatus------------------------------------- ---------------------------------------------------------------------------------------------- -- processing of request/response in different HMIlevels, SystemContext, AudioStreamingState --Write NewTestBlock to ATF log function Test:NewTestBlock() commonFunctions:printError("****************************** VII TEST BLOCK: Different HMIStatus ******************************") end --Begin test suit DifferentHMIlevel --Description: processing API in different HMILevel --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810 --Verification criteria: DeleteFile is allowed in NONE, LIMITED, BACKGROUND and FULL HMI level --Begin test case DifferentHMIlevel.1 --Description: Check DeleteFile request when application is in NONE HMI level --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810 --Verification criteria: DeleteFile is allowed in NONE HMI level -- Precondition 1: Change app to NONE HMI level commonSteps:DeactivateAppToNoneHmiLevel() -- Precondition 2: PutFile putfile(self, "test.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_NONE_SUCCESS", "test.png", "GRAPHIC_PNG") --Postcondition: Activate app commonSteps:ActivationApp() --End test case DifferentHMIlevel.1 --Begin test case DifferentHMIlevel.2 --Description: Check DeleteFile request when application is in LIMITED HMI level --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810 --Verification criteria: DeleteFile is allowed in LIMITED HMI level if commonFunctions:isMediaApp() then -- Precondition 1: Change app to LIMITED commonSteps:ChangeHMIToLimited() -- Precondition 2: Put file putfile(self, "test.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_LIMITED_SUCCESS", "test.png", "GRAPHIC_PNG") end --End test case DifferentHMIlevel.2 --Begin test case DifferentHMIlevel.3 --Description: Check DeleteFile request when application is in BACKGOUND HMI level --Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810 --Verification criteria: DeleteFile is allowed in BACKGOUND HMI level -- Precondition 1: Change app to BACKGOUND HMI level commonTestCases:ChangeAppToBackgroundHmiLevel() -- Precondition 2: Put file putfile(self, "test.png", "GRAPHIC_PNG") TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_BACKGROUND_SUCCESS", "test.png", "GRAPHIC_PNG") --End test case DifferentHMIlevel.3 --End test suit DifferentHMIlevel --Postcondition: restore sdl_preloaded_pt.json policyTable:Restore_preloaded_pt() return Test
local a={ssid="DoT-"..string.format("%x",node.chipid()*256):sub(0,6):upper(),pwd="",auth=false,mode=3,login="admin",pass="0000"}local function b(c,d)local e,f=pcall(sjson.encode,d)if f and file.open(c,"w")then file.write(f)file.close()end end;local function g(h)local i,f;if file.open(h,"r")then i,f=pcall(sjson.decode,file.read())file.close()end;return i and f end;local function j(k)local l,m=k==1 and g("setting.json")m=l or a;if not settings then b("setting.json",m)end;m.token=tostring(node.random(100000))return m end;local function n(o)local h,p;for q,r in pairs(file.list())do if q:match(o.ext and"(.*)%."..o.ext or o.name.."%.[rn][ue][nt]$")then h=g(q:match("(.*)%.")..".init")if q and h then h.run=o.name and true or h.run;h,p=pcall(dofile(q),h)print(q,(p and""or"not ").."running")end end end;return p end;local function s(o)if type(o)=="table"then for t,r in pairs(o)do file.remove(r)end else file.remove(o)end;return o end;local function u(o)local v=g(o.Fname)if v then for w,k in pairs(v)do v[w]=o[w]==nil and k or o[w]end;b(o.Fname,v)return true end;return false end;return function(o)local x;if type(o)=="table"then if o.run then x=n(o.run)end;if o.list then x=file.list()end;if o.init then x=g(o.init)end;if o.save then x=u(o.save)end;if o.del then x=s(o.del)end;if o.def then x=j(o.def)end end;return x end
return{ [[ 猎魔词缀参考 金环 固定基底词缀: 0 获得 20 级的主动技能【猫之势】 获得 20 级的主动技能【鸟之势】 获得 20 级的主动技能【蛛之势】 获得 20 级的主动技能【蟹之势】 ]], [[ +3弓 林野猎弓 工艺: true 前缀: {range:0.5}LocalIncreaseSocketedGemLevel1 前缀: {range:1}LocalIncreaseSocketedBowGemLevel2 前缀: None 后缀: None 后缀: None 后缀: {range:1}LocalIncreasedAttackSpeed2 品质: 20 插槽: G-G-G-G-G-G 等级需求: 56 固定基底词缀: 0 此物品上装备的技能石等级 +1 此物品上装备的【弓技能石】等级 +2 攻击速度提高 10% ]],[[ +3弓(火焰) 短弓 工艺: true 前缀: {range:0.5}LocalIncreaseSocketedGemLevel1 前缀: None 前缀: None 后缀: None 后缀: None 后缀: {range:1}LocalIncreasedAttackSpeed2 品质: 20 插槽: G-G-G-G-G-G 等级需求: 40 固定基底词缀: 0 此物品上装备的技能石等级 +1 攻击速度提高 10% {custom}此物品上装备的【火焰技能石】等级 +2 ]],[[ 浮夸弓 粗制弓 工艺: true 前缀: {range:0.5}WeaponElementalDamageOnWeapons3_ 前缀: None 前缀: None 后缀: {range:0.5}Dexterity5 后缀: None 后缀: {range:1}LocalIncreasedAttackSpeed2 品质: 20 插槽: G-B-B-B-B-R 等级需求: 35 固定基底词缀: 0 +30 敏捷 攻击速度提高 10% 攻击技能的火焰、冰霜、闪电伤害提高 26% {custom}击中时有 10% 几率施放 20 级的【火焰爆破】 ]],[[ +3火灵杖 风暴长杖 工艺: true 前缀: {range:0.5}LocalIncreaseSocketedGemLevel1 前缀: {range:1}LocalIncreaseSocketedFireGemLevel2_ 前缀: None 后缀: None 后缀: None 后缀: {range:0.5}IncreasedCastSpeedTwoHand4 品质: 20 插槽: B-B-B-B-B-B 等级需求: 64 固定基底词缀: 1 20% 攻击格挡率 此物品上装备的技能石等级 +1 此物品上装备的【火焰技能石】等级 +2 施法速度提高 23% {custom}可以拥有多个大师工艺属性 {crafted}此物品上的技能石受到 1 级的 血魔法 辅助 {crafted}受到的持续性伤害降低 5% ]],[[ 双附加短杖 恶魔短杖 塑界之器 工艺: true 前缀: {range:1}ElementalDamagePercentAddedAsChaosUber1 前缀: {range:0.5}PhysicalAddedAsLightningUber2 前缀: None 后缀: None 后缀: None 后缀: None 品质: 20 插槽: R-R-R 等级需求: 70 固定基底词缀: 1 伤害穿透 6% 火焰、冰霜、闪电抗性 获得额外闪电伤害, 其数值等同于物理伤害的 31% 获得额外混沌伤害,其数值等同于火焰、冰霜、闪电伤害的 15% ]],[[ 正火头 永恒坚盔 裂界之器 工艺: true 前缀: {range:0.5}AreaDamageSupportedUber2_ 前缀: None 前缀: None 后缀: None 后缀: {range:0.901}IncreasedBurningDamageSupportedUber2 后缀: None 品质: 20 插槽: R-R-R-R 等级需求: 69 固定基底词缀: 0 此物品上的技能石受到 18 级的 提高燃烧伤害 辅助 此物品上的技能石受到 18 级的 集中效应 辅助 燃烧伤害提高 30% 范围伤害提高 21% {custom}此物品上的技能石火焰、冰霜、闪电总伤害额外提高 30% ]],[[ 攻速生命手套 扣钉手套 工艺: true 前缀: {range:0.035}IncreasedLife7 前缀: None 前缀: None 后缀: {range:0.324}IncreasedAttackSpeed3 后缀: {range:0.268}FireResist6 后缀: {range:0.239}LightningResist6 品质: 20 插槽: R-R-R-R 等级需求: 70 固定基底词缀: 1 {range:0.5}近战伤害提高 (16-20)% 攻击速度提高 12% +70 最大生命 +37% 火焰抗性 +37% 闪电抗性 ]],[[ 生命跑鞋 迷踪短靴 工艺: true 前缀: {range:0.352}IncreasedLife7 前缀: {range:0.204}MovementVelocity5 前缀: None 后缀: {range:1}FireResist4 后缀: {range:1}LightningResist4 后缀: {range:1}ColdResist4 品质: 20 插槽: G-G-G-G 等级需求: 69 固定基底词缀: 0 +73 最大生命 +29% 火焰抗性 +29% 冰霜抗性 +29% 闪电抗性 移动速度提高 30% ]],[[ 格挡转换盾 瓦尔轻盾 塑界之器 工艺: true 前缀: None 前缀: None 前缀: None 后缀: {range:0.592}BlockAppliesToSpellsShieldUber2_ 后缀: {range:1}RecoverLifePercentOnBlockUber1_ 后缀: None 品质: 20 插槽: G-G-G 等级需求: 63 固定基底词缀: 1 移动速度提高 3% 46% 的攻击格挡率同样套用于法术格挡 格挡时回复 5% 最大生命 {crafted}+(55-64) 最大生命 ]],[[ 空手珠宝 凶残之凝珠宝 工艺: true 前缀: {range:1}AbyssJewelAddedLife2 前缀: None 后缀: {range:1}AbyssAddedPhysicalSuffixJewel3 后缀: {range:1}AbyssAllResistancesJewel1 品质: 0 等级需求: 48 固定基底词缀: 0 攻击附加 5 - 8 基础物理伤害 +35 最大生命 获得 +10% 火焰、冰霜、闪电抗性 ]],[[ 召唤深渊珠宝 苍白之凝珠宝 工艺: true 前缀: {range:1}AbyssJewelAddedLife2 前缀: None 后缀: {range:0.5}AbyssMinionDamageIfMinionSkillUsedRecentlyJewel1 后缀: None 品质: 0 等级需求: 28 固定基底词缀: 0 +35 最大生命 近期内你若使用了召唤生物技能,则召唤生物伤害提高 18% ]],[[ 双附加闪电(弓) 锐利之凝珠宝 工艺: true 前缀: {range:0.183}AbyssAddedLightningDamageWithBowsJewel5 前缀: None 后缀: {range:0.486}AbyssAddedLightningSuffixJewel4 后缀: None 品质: 0 等级需求: 56 固定基底词缀: 0 攻击附加 3 - 53 基础闪电伤害 弓攻击附加 4 - 58 基础闪电伤害 ]],[[ 双附加闪电(法杖) 锐利之凝珠宝 工艺: true 前缀: {range:0.056}AbyssAddedLightningDamageWithWandsJewel5 前缀: None 后缀: {range:0.521}AbyssAddedLightningSuffixJewel4 后缀: None 品质: 0 等级需求: 56 固定基底词缀: 0 攻击附加 4 - 53 基础闪电伤害 法杖攻击附加 3 - 57 基础闪电伤害 ]],[[ M神双打细剑 宝饰细剑 工艺: true 前缀: {range:0.986}LocalIncreasedPhysicalDamagePercent1 前缀: {range:0.479}LocalAddedColdDamage8 前缀: None 后缀: {range:0.394}LocalIncreasedAttackSpeed7 后缀: {range:0.746}LocalCriticalStrikeChance3 后缀: None 品质: 20 插槽: G-G-G 等级需求: 68 固定基底词缀: 1 +25% 攻击和法术暴击伤害加成 该装备的物理伤害提高 49% 附加 36 - 68 基础冰霜伤害 攻击速度提高 24% {range:0.5}该装备的攻击暴击率提高 23% {crafted}{range:0.524}附加 11 - 21 基础物理伤害 ]], }
Color = { ["black"] = { 0, 0, 0 }, ["red"] = { 255, 0, 0 }, ["green"] = { 0, 255, 0 }, ["blue "] = { 0, 0, 255 }, ["white"] = { 255, 255, 255 }, ["brown"] = { 165, 42, 42 }, ["cyan"] = { 0, 255, 255 }, ["darkblue"] = { 0, 0, 139 }, ["darkred"] = { 139, 0, 0 }, ["fuchsia"] = { 255, 0, 255 }, ["gold"] = { 255, 215, 0 }, ["gray"] = { 127, 127, 127 }, ["grey"] = { 127, 127, 127 }, ["lightblue"] = { 173, 216, 230 }, ["lightgreen"] = { 144, 238, 144 }, ["magenta"] = { 255, 0, 255 }, ["maroon"] = { 128, 0, 0 }, ["navyblue"] = { 159, 175, 223 }, ["orange"] = { 255, 165, 0 }, ["palegreen"] = { 152, 251, 152 }, ["pink"] = { 255, 192, 203 }, ["purple"] = { 128, 0, 128 }, ["royalblue"] = { 65, 105, 225 }, ["salmon"] = { 250, 128, 114 }, ["seagreen"] = { 46, 139, 87 }, ["silver"] = { 192, 192, 192 }, ["turquoise"] = { 64, 224, 208 }, ["violet"] = { 238, 130, 238 }, ["yellow"] = { 255, 255, 0 } } Color.mt = { __index = function() return { 0, 0, 0 } end } setmetatable(Color,Color.mt) function copyTable(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 end function deepcopy(t) -- This function recursively copies a table's contents, and ensures that metatables are preserved. That is, it will correctly clone a pure Lua object. if type(t) ~= 'table' then return t end local mt = getmetatable(t) local res = {} for k,v in pairs(t) do if type(v) == 'table' then v = deepcopy(v) end res[k] = v end setmetatable(res,mt) return res end -- from http://snippets.luacode.org/snippets/Deep_copy_of_a_Lua_Table_2 function screenRefresh() return platform.window:invalidate() end function pww() return platform.window:width() end function pwh() return platform.window:height() end function drawPoint(gc, x, y) gc:fillRect(x, y, 1, 1) end function drawCircle(gc, x, y, diameter) gc:drawArc(x - diameter/2, y - diameter/2, diameter,diameter,0,360) end function drawCenteredString(gc, str) gc:drawString(str, .5*(pww() - gc:getStringWidth(str)), .5*pwh(), "middle") end function drawXCenteredString(gc, str, y) gc:drawString(str, .5*(pww() - gc:getStringWidth(str)), y, "top") end function setColor(gc,theColor) if type(theColor) == "string" then theColor = string.lower(theColor) if type(Color[theColor]) == "table" then gc:setColorRGB(unpack(Color[theColor])) end elseif type(theColor) == "table" then gc:setColorRGB(unpack(theColor)) end end function verticalBar(gc,x) gc:fillRect(gc,x,0,1,pwh()) end function horizontalBar(gc,y) gc:fillRect(gc,0,y,pww(),1) end function nativeBar(gc, screen, y) gc:setColorRGB(128,128,128) gc:fillRect(screen.x+5, screen.y+y, screen.w-10, 2) end function drawSquare(gc,x,y,l) gc:drawPolyLine(gc,{(x-l/2),(y-l/2), (x+l/2),(y-l/2), (x+l/2),(y+l/2), (x-l/2),(y+l/2), (x-l/2),(y-l/2)}) end function drawRoundRect(gc,x,y,wd,ht,rd) -- wd = width, ht = height, rd = radius of the rounded corner x = x-wd/2 -- let the center of the square be the origin (x coord) y = y-ht/2 -- same for y coord if rd > ht/2 then rd = ht/2 end -- avoid drawing cool but unexpected shapes. This will draw a circle (max rd) gc:drawLine(x + rd, y, x + wd - (rd), y); gc:drawArc(x + wd - (rd*2), y + ht - (rd*2), rd*2, rd*2, 270, 90); gc:drawLine(x + wd, y + rd, x + wd, y + ht - (rd)); gc:drawArc(x + wd - (rd*2), y, rd*2, rd*2,0,90); gc:drawLine(x + wd - (rd), y + ht, x + rd, y + ht); gc:drawArc(x, y, rd*2, rd*2, 90, 90); gc:drawLine(x, y + ht - (rd), x, y + rd); gc:drawArc(x, y + ht - (rd*2), rd*2, rd*2, 180, 90); end function fillRoundRect(gc,x,y,wd,ht,radius) -- wd = width and ht = height -- renders badly when transparency (alpha) is not at maximum >< will re-code later if radius > ht/2 then radius = ht/2 end -- avoid drawing cool but unexpected shapes. This will draw a circle (max radius) gc:fillPolygon({(x-wd/2),(y-ht/2+radius), (x+wd/2),(y-ht/2+radius), (x+wd/2),(y+ht/2-radius), (x-wd/2),(y+ht/2-radius), (x-wd/2),(y-ht/2+radius)}) gc:fillPolygon({(x-wd/2-radius+1),(y-ht/2), (x+wd/2-radius+1),(y-ht/2), (x+wd/2-radius+1),(y+ht/2), (x-wd/2+radius),(y+ht/2), (x-wd/2+radius),(y-ht/2)}) x = x-wd/2 -- let the center of the square be the origin (x coord) y = y-ht/2 -- same gc:fillArc(x + wd - (radius*2), y + ht - (radius*2), radius*2, radius*2, 1, -91); gc:fillArc(x + wd - (radius*2), y, radius*2, radius*2,-2,91); gc:fillArc(x, y, radius*2, radius*2, 85, 95); gc:fillArc(x, y + ht - (radius*2), radius*2, radius*2, 180, 95); end function textLim(gc, text, max) local ttext, out = "","" local width = gc:getStringWidth(text) if width<max then return text, width else for i=1, #text do ttext = text:usub(1, i) if gc:getStringWidth(ttext .. "..")>max then break end out = ttext end return out .. "..", gc:getStringWidth(out .. "..") end end
return "6592822488931338589815525425236818285229555616392928433262436847386544514648645288129834834862363847542262953164877694234514375164927616649264122487182321437459646851966649732474925353281699895326824852555747127547527163197544539468632369858413232684269835288817735678173986264554586412678364433327621627496939956645283712453265255261565511586373551439198276373843771249563722914847255524452675842558622845416218195374459386785618255129831539984559644185369543662821311686162137672168266152494656448824719791398797359326412235723234585539515385352426579831251943911197862994974133738196775618715739412713224837531544346114877971977411275354168752719858889347588136787894798476123335894514342411742111135337286449968879251481449757294167363867119927811513529711239534914119292833111624483472466781475951494348516125474142532923858941279569675445694654355314925386833175795464912974865287564866767924677333599828829875283753669783176288899797691713766199641716546284841387455733132519649365113182432238477673375234793394595435816924453585513973119548841577126141962776649294322189695375451743747581241922657947182232454611837512564776273929815169367899818698892234618847815155578736875295629917247977658723868641411493551796998791839776335793682643551875947346347344695869874564432566956882395424267187552799458352121248147371938943799995158617871393289534789214852747976587432857675156884837634687257363975437535621197887877326295229195663235129213398178282549432599455965759999159247295857366485345759516622427833518837458236123723353817444545271644684925297477149298484753858863551357266259935298184325926848958828192317538375317946457985874965434486829387647425222952585293626473351211161684297351932771462665621764392833122236577353669215833721772482863775629244619639234636853267934895783891823877845198326665728659328729472456175285229681244974389248235457688922179237895954959228638193933854787917647154837695422429184757725387589969781672596568421191236374563718951738499591454571728641951699981615249635314789251239677393251756396"
-- Generated by CSharp.lua Compiler local System = System local DCETHotfix = DCET.Hotfix System.namespace("DCET.Hotfix", function (namespace) namespace.class("AMHandler_1", function (namespace) return function (Message) local Handle, GetMessageType Handle = function (this, session, msg) return System.async(function (async, this, session, msg) local message = System.as(msg, Message) if message == nil then DCETHotfix.Log.Error("消息类型转换错误: " .. msg:GetType():getName() .. " to " .. System.typeof(Message):getName()) end System.try(function () async:Await(Run(this, session, message)) end, function (default) local e = default DCETHotfix.Log.Error(e) end) end, nil, this, session, msg) end GetMessageType = function (this) return System.typeof(Message) end return { __inherits__ = function (out) return { out.DCET.Hotfix.IMHandler } end, Handle = Handle, GetMessageType = GetMessageType } end end) end)
---- -- -- A hello world spreadsheet using the xlsxwriter.lua module. -- -- Copyright 2014-2015, John McNamara, jmcnamara@cpan.org -- local Workbook = require "xlsxwriter.workbook" local workbook = Workbook:new("hello_world.xlsx") local worksheet = workbook:add_worksheet() worksheet:write("A1", "Hello world") workbook:close()
local awful = require('awful') local naughty = require('naughty') local util = {} function util.client_is_valid(c) return pcall(function () return c.valid end) and c.valid end function util.next_valid_client(cs) if #cs == 0 then return end local c = table.remove(cs) if util.client_is_valid(c) then return c end return next_valid(cs) end function util.selected_tag(s) s = s or awful.screen.focused() return s.selected_tag end function util.clientinfo(c) c = c or client.focus if not c then return end local props = { valid = c.valid, window = c.window, name = c.name, type = c.type, class = c.class, instance = c.instance, floating = c.floating, fullscreen = c.fullscreen, screen = c.screen.index, startup_id = c.startup_id, wm_launch_id = c.wm_launch_id, single_instance_id = c.single_instance_id, cmdline = c.cmdline, launch_panel = c.launch_panel or false, maximized = c.maximized, maximized_vertical = c.maximized_vertical, maximized_horizontal = c.maximized_horizontal, } local text = '' for k, v in pairs(props) do text = text .. string.format('\n%s: %s', k, v) end naughty.notification { title = 'Client info', message = text, position = 'top_middle', } end return util
local BenchmarkBpClass = Inherit(CppObjectBase) function BenchmarkBpClass:Start() self.m_TestResult = {} -- GlueFunc self:TestBPReflection() self:TestGlueFunction() self:TestDynamicMultiCast() end function BenchmarkBpClass:TestBPReflection( ) self:TestFunc("TestCallFunc_0param") self:TestFunc("TestCallFunc_1param_int", 1) self:TestFunc("TestCallFunc_1param_int_ref", 1) self:TestFunc("TestCallFunc_1param_FVector", FVector.New(1,2,3)) self:TestFunc("TestCallFunc_1param_FVector_ref", FVector.New(1,2,3)) self:TestFunc("TestCallFunc_3param", i, self, FVector.New(1,2,3)) self:TestFunc("TestCallFunc_Ret_int") self:TestFunc("TestCallFunc_Ret_FVector" ) self:TestReadWrite("ReadWriteInt", 1) self:TestReadWrite("ReadWriteVector", FVector.New(1,2,3)) end function BenchmarkBpClass:TestGlueFunction( ) self:TestFunc("Glue_TestCallFunc_0param") self:TestFunc("Glue_TestCallFunc_1param_int", 1) self:TestFunc("Glue_TestCallFunc_1param_int_ref", 1) self:TestFunc("Glue_TestCallFunc_1param_FVector", FVector.New(1,2,3)) self:TestFunc("Glue_TestCallFunc_1param_FVector_ref", FVector.New(1,2,3)) self:TestFunc("Glue_TestCallFunc_3param", i, self, FVector.New(1,2,3)) self:TestFunc("Glue_TestCallFunc_Ret_int") self:TestFunc("Glue_TestCallFunc_Ret_FVector" ) self:TestReadWrite("Glue_ReadWriteInt", 1) self:TestReadWrite("Glue_ReadWriteVector", FVector.New(1,2,3)) end function BenchmarkBpClass:TestDynamicMultiCast() local CallCount = 100000 local function f() end self.BenchDelegate_2Param:Add(InsCallBack(f, self)) local t = os.clock() self:Call_BenchDelegate_2Param(CallCount) local t1 = os.clock() self.BenchDelegate_2Param:RemoveAll() self.BenchDelegate_2Param:Add(f) local t2 = os.clock() self:Call_BenchDelegate_2Param(CallCount) local t3 = os.clock() a_("BenchDelegate_2Param", t1-t, t3-t2) end function BenchmarkBpClass:TestFunc(FuncName, ...) self.m_TestResult[FuncName] = self.m_TestResult[FuncName] or {} local TestResult = "" local TestCount = 1000000 local cppins = self._cppinstance_ local TestFunc = self[FuncName] local t = os.clock() for i = 1, TestCount do self[FuncName](self, ...) end local t1 = os.clock() for i = 1, TestCount do cppins[FuncName](cppins, ...) end local t2 = os.clock() for i = 1, TestCount do TestFunc(self, ...) end local t3 = os.clock() a_(FuncName, t1-t, t2-t1, t3-t2) end function BenchmarkBpClass:TestReadWrite(PropertyName, Data) local TestCount = 1000000 local cppins = self._cppinstance_ local readfunc = self["LuaGet_"..PropertyName] local writefunc = self["LuaSet_"..PropertyName] local t = os.clock() for i = 1, TestCount do local x = self[PropertyName] end local t1 = os.clock() for i = 1, TestCount do local x = cppins[PropertyName] end local t2 = os.clock() if readfunc then for i = 1, TestCount do local x = readfunc(self) end end local t3 = os.clock() a_(PropertyName, "Read", t1-t, t2-t1, t3-t2) local t4 = os.clock() for i = 1, TestCount do self[PropertyName] = Data end local t5 = os.clock() for i = 1, TestCount do cppins[PropertyName] = Data end local t6 = os.clock() if writefunc then for i = 1, TestCount do writefunc(self, Data) end end local t7 = os.clock() a_(PropertyName, "Writ", t5-t4, t6-t5, t7-t6) end return BenchmarkBpClass
--get the addon namespace local addon, ns = ... --get the config values local cfg = ns.cfg local barcfg = cfg.bars.bags if not barcfg.disable then local bar = CreateFrame("Frame","rABS_Bags",UIParent, "SecureHandlerStateTemplate") bar:SetWidth(200) bar:SetHeight(40) bar:SetPoint(barcfg.pos.a1,barcfg.pos.af,barcfg.pos.a2,barcfg.pos.x,barcfg.pos.y) bar:SetHitRectInsets(-cfg.barinset, -cfg.barinset, -cfg.barinset, -cfg.barinset) bar:SetScale(barcfg.barscale) if barcfg.testmode then bar:SetBackdrop(cfg.backdrop) bar:SetBackdropColor(1,0.8,1,0.6) end cfg.applyDragFunctionality(bar,barcfg.userplaced,barcfg.locked) local BagButtons = { MainMenuBarBackpackButton, CharacterBag0Slot, CharacterBag1Slot, CharacterBag2Slot, CharacterBag3Slot, KeyRingButton, } for _, f in pairs(BagButtons) do f:SetParent(bar); end MainMenuBarBackpackButton:ClearAllPoints(); MainMenuBarBackpackButton:SetPoint("BOTTOMRIGHT", 0, 0); if barcfg.showonmouseover then local function lighton(alpha) for _, f in pairs(BagButtons) do f:SetAlpha(alpha) end end bar:EnableMouse(true) bar:SetScript("OnEnter", function(self) lighton(1) end) bar:SetScript("OnLeave", function(self) lighton(0) end) for _, f in pairs(BagButtons) do f:SetAlpha(0) f:HookScript("OnEnter", function(self) lighton(1) end) f:HookScript("OnLeave", function(self) lighton(0) end) end bar:SetScript("OnEvent", function(self) lighton(0) end) bar:RegisterEvent("PLAYER_ENTERING_WORLD") end end
local t = Def.ActorFrame { Def.Sprite { Texture = NOTESKIN:GetPath("_down", "tap mine underlay"), Frames = Sprite.LinearFrames(1, 1), InitCommand = function(self) self:diffuseshift():effectcolor1(0.4, 0, 0, 1):effectcolor2(1, 0, 0, 1):effectclock("beat") end }, Def.Sprite { Texture = NOTESKIN:GetPath("_down", "tap mine base"), Frames = Sprite.LinearFrames(1, 1), InitCommand = function(self) self:spin():effectclock("beat"):effectmagnitude(0, 0, 80) end }, Def.Sprite { Texture = NOTESKIN:GetPath("_down", "tap mine overlay"), Frames = Sprite.LinearFrames(1, 1), InitCommand = function(self) self:spin():effectclock("beat"):effectmagnitude(0, 0, -40) end } } return t
fx_version 'cerulean' games 'gta5' client_scripts { 'client.lua' } server_scripts { 'Auth.lua', 'server.lua' }
object_draft_schematic_food_drink_rancoraid = object_draft_schematic_food_shared_drink_rancoraid:new { } ObjectTemplates:addTemplate(object_draft_schematic_food_drink_rancoraid, "object/draft_schematic/food/drink_rancoraid.iff")
ESX = nil local PlayersSelling = {} local jagerbomb = 1 local golem = 1 local whiskycoca = 1 local rhumcoca = 1 local vodkaenergy = 1 local vodkafruit = 1 local rhumfruit = 1 local teqpaf = 1 local mojito = 1 local mixapero = 1 local metreshooter = 1 local jagercerbere = 1 TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) if Config.MaxInService ~= -1 then TriggerEvent('esx_service:activateService', 'unicorn', Config.MaxInService) end TriggerEvent('esx_phone:registerNumber', 'unicorn', _U('unicorn_customer'), true, true) TriggerEvent('esx_society:registerSociety', 'unicorn', 'Unicorn', 'society_unicorn', 'society_unicorn', 'society_unicorn', {type = 'private'}) RegisterServerEvent('esx_unicornjob:getStockItem') AddEventHandler('esx_unicornjob:getStockItem', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn', function(inventory) local item = inventory.getItem(itemName) if item.count >= count then inventory.removeItem(itemName, count) xPlayer.addInventoryItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('quantity_invalid')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('you_removed') .. count .. ' ' .. item.label) end) end) ESX.RegisterServerCallback('esx_unicornjob:getStockItems', function(source, cb) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn', function(inventory) cb(inventory.items) end) end) RegisterServerEvent('esx_unicornjob:putStockItems') AddEventHandler('esx_unicornjob:putStockItems', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn', function(inventory) local item = inventory.getItem(itemName) local playerItemCount = xPlayer.getInventoryItem(itemName).count if item.count >= 0 and count <= playerItemCount then xPlayer.removeInventoryItem(itemName, count) inventory.addItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('invalid_quantity')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('you_added') .. count .. ' ' .. item.label) end) end) RegisterServerEvent('esx_unicornjob:getFridgeStockItem') AddEventHandler('esx_unicornjob:getFridgeStockItem', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn_fridge', function(inventory) local item = inventory.getItem(itemName) if item.count >= count then inventory.removeItem(itemName, count) xPlayer.addInventoryItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('quantity_invalid')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('you_removed') .. count .. ' ' .. item.label) end) end) ESX.RegisterServerCallback('esx_unicornjob:getFridgeStockItems', function(source, cb) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn_fridge', function(inventory) cb(inventory.items) end) end) RegisterServerEvent('esx_unicornjob:putFridgeStockItems') AddEventHandler('esx_unicornjob:putFridgeStockItems', function(itemName, count) local xPlayer = ESX.GetPlayerFromId(source) TriggerEvent('esx_addoninventory:getSharedInventory', 'society_unicorn_fridge', function(inventory) local item = inventory.getItem(itemName) local playerItemCount = xPlayer.getInventoryItem(itemName).count if item.count >= 0 and count <= playerItemCount then xPlayer.removeInventoryItem(itemName, count) inventory.addItem(itemName, count) else TriggerClientEvent('esx:showNotification', xPlayer.source, _U('invalid_quantity')) end TriggerClientEvent('esx:showNotification', xPlayer.source, _U('you_added') .. count .. ' ' .. item.label) end) end) RegisterServerEvent('esx_unicornjob:buyItem') AddEventHandler('esx_unicornjob:buyItem', function(itemName, price, itemLabel) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local limit = xPlayer.getInventoryItem(itemName).limit local qtty = xPlayer.getInventoryItem(itemName).count local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil and societyAccount.money >= price then if qtty < limit then societyAccount.removeMoney(price) xPlayer.addInventoryItem(itemName, 1) TriggerClientEvent('esx:showNotification', _source, _U('bought') .. itemLabel) else TriggerClientEvent('esx:showNotification', _source, _U('max_item')) end else TriggerClientEvent('esx:showNotification', _source, _U('not_enough')) end end) RegisterServerEvent('esx_unicornjob:craftingCoktails') AddEventHandler('esx_unicornjob:craftingCoktails', function(itemValue) local _source = source local _itemValue = itemValue TriggerClientEvent('esx:showNotification', _source, _U('assembling_cocktail')) if _itemValue == 'jagerbomb' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('redbull').count local bethQuantity = xPlayer.getInventoryItem('jager').count if alephQuantity < 2 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('redbull') .. '~w~') elseif bethQuantity < 2 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('jager') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('redbull', 1) xPlayer.removeInventoryItem('jager', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('jagerbomb') .. ' ~w~!') xPlayer.removeInventoryItem('redbull', 1) xPlayer.removeInventoryItem('jager', 1) xPlayer.addInventoryItem('jagerbomb', 1) end end end) end if _itemValue == 'golem' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('limonade').count local bethQuantity = xPlayer.getInventoryItem('vodka').count local gimelQuantity = xPlayer.getInventoryItem('ice').count if alephQuantity < 2 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('limonade') .. '~w~') elseif bethQuantity < 2 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('vodka') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('ice') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('golem') .. ' ~w~!') xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) xPlayer.addInventoryItem('golem', 1) end end end) end if _itemValue == 'whiskycoca' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('cocacola').count local bethQuantity = xPlayer.getInventoryItem('whisky').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('cocacola') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('whisky') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('cocacola', 1) xPlayer.removeInventoryItem('whisky', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('whiskycoca') .. ' ~w~!') xPlayer.removeInventoryItem('cocacola', 1) xPlayer.removeInventoryItem('whisky', 1) xPlayer.addInventoryItem('whiskycoca', 1) end end end) end if _itemValue == 'rhumcoca' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('cocacola').count local bethQuantity = xPlayer.getInventoryItem('rhum').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('cocacola') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('rhum') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('cocacola', 1) xPlayer.removeInventoryItem('rhum', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('rhumcoca') .. ' ~w~!') xPlayer.removeInventoryItem('cocacola', 1) xPlayer.removeInventoryItem('rhum', 1) xPlayer.addInventoryItem('rhumcoca', 1) end end end) end if _itemValue == 'vodkaenergy' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('redbull').count local bethQuantity = xPlayer.getInventoryItem('vodka').count local gimelQuantity = xPlayer.getInventoryItem('ice').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('redbull') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('vodka') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('ice') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('redbull', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('vodkaenergy') .. ' ~w~!') xPlayer.removeInventoryItem('redbull', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) xPlayer.addInventoryItem('vodkaenergy', 1) end end end) end if _itemValue == 'vodkafruit' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('jusfruit').count local bethQuantity = xPlayer.getInventoryItem('vodka').count local gimelQuantity = xPlayer.getInventoryItem('ice').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('jusfruit') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('vodka') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('ice') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('jusfruit', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('vodkafruit') .. ' ~w~!') xPlayer.removeInventoryItem('jusfruit', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('ice', 1) xPlayer.addInventoryItem('vodkafruit', 1) end end end) end if _itemValue == 'rhumfruit' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('jusfruit').count local bethQuantity = xPlayer.getInventoryItem('rhum').count local gimelQuantity = xPlayer.getInventoryItem('ice').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('jusfruit') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('rhum') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('ice') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('jusfruit', 1) xPlayer.removeInventoryItem('rhum', 1) xPlayer.removeInventoryItem('ice', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('rhumfruit') .. ' ~w~!') xPlayer.removeInventoryItem('jusfruit', 1) xPlayer.removeInventoryItem('rhum', 1) xPlayer.removeInventoryItem('ice', 1) xPlayer.addInventoryItem('rhumfruit', 1) end end end) end if _itemValue == 'teqpaf' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('limonade').count local bethQuantity = xPlayer.getInventoryItem('tequila').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('limonade') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('tequila') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('tequila', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('teqpaf') .. ' ~w~!') xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('tequila', 1) xPlayer.addInventoryItem('teqpaf', 1) end end end) end if _itemValue == 'mojito' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('rhum').count local bethQuantity = xPlayer.getInventoryItem('limonade').count local gimelQuantity = xPlayer.getInventoryItem('menthe').count local daletQuantity = xPlayer.getInventoryItem('ice').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('rhum') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('limonade') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('menthe') .. '~w~') elseif daletQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('ice') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('rhum', 1) xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('menthe', 1) xPlayer.removeInventoryItem('ice', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('mojito') .. ' ~w~!') xPlayer.removeInventoryItem('rhum', 1) xPlayer.removeInventoryItem('limonade', 1) xPlayer.removeInventoryItem('menthe', 1) xPlayer.removeInventoryItem('ice', 1) xPlayer.addInventoryItem('mojito', 1) end end end) end if _itemValue == 'mixapero' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('bolcacahuetes').count local bethQuantity = xPlayer.getInventoryItem('bolnoixcajou').count local gimelQuantity = xPlayer.getInventoryItem('bolpistache').count local daletQuantity = xPlayer.getInventoryItem('bolchips').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('bolcacahuetes') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('bolnoixcajou') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('bolpistache') .. '~w~') elseif daletQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('bolchips') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('bolcacahuetes', 1) xPlayer.removeInventoryItem('bolnoixcajou', 1) xPlayer.removeInventoryItem('bolpistache', 1) xPlayer.removeInventoryItem('bolchips', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('mixapero') .. ' ~w~!') xPlayer.removeInventoryItem('bolcacahuetes', 1) xPlayer.removeInventoryItem('bolnoixcajou', 1) xPlayer.removeInventoryItem('bolpistache', 1) xPlayer.removeInventoryItem('bolchips', 1) xPlayer.addInventoryItem('mixapero', 1) end end end) end if _itemValue == 'metreshooter' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('jager').count local bethQuantity = xPlayer.getInventoryItem('vodka').count local gimelQuantity = xPlayer.getInventoryItem('whisky').count local daletQuantity = xPlayer.getInventoryItem('tequila').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('jager') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('vodka') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('whisky') .. '~w~') elseif daletQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('tequila') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('jager', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('whisky', 1) xPlayer.removeInventoryItem('tequila', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('metreshooter') .. ' ~w~!') xPlayer.removeInventoryItem('jager', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('whisky', 1) xPlayer.removeInventoryItem('tequila', 1) xPlayer.addInventoryItem('metreshooter', 1) end end end) end if _itemValue == 'jagercerbere' then SetTimeout(1000, function() local xPlayer = ESX.GetPlayerFromId(_source) local alephQuantity = xPlayer.getInventoryItem('jagerbomb').count local bethQuantity = xPlayer.getInventoryItem('vodka').count local gimelQuantity = xPlayer.getInventoryItem('tequila').count if alephQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('jagerbomb') .. '~w~') elseif bethQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('vodka') .. '~w~') elseif gimelQuantity < 1 then TriggerClientEvent('esx:showNotification', _source, _U('not_enough') .. _U('tequila') .. '~w~') else local chanceToMiss = math.random(100) if chanceToMiss <= Config.MissCraft then TriggerClientEvent('esx:showNotification', _source, _U('craft_miss')) xPlayer.removeInventoryItem('jagerbomb', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('tequila', 1) else TriggerClientEvent('esx:showNotification', _source, _U('craft') .. _U('jagercerbere') .. ' ~w~!') xPlayer.removeInventoryItem('jagerbomb', 1) xPlayer.removeInventoryItem('vodka', 1) xPlayer.removeInventoryItem('tequila', 1) xPlayer.addInventoryItem('jagercerbere', 1) end end end) end end) ESX.RegisterServerCallback('esx_unicornjob:getVaultWeapons', function(source, cb) TriggerEvent('esx_datastore:getSharedDataStore', 'society_unicorn', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end cb(weapons) end) end) ESX.RegisterServerCallback('esx_unicornjob:addVaultWeapon', function(source, cb, weaponName) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeWeapon(weaponName) TriggerEvent('esx_datastore:getSharedDataStore', 'society_unicorn', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end local foundWeapon = false for i=1, #weapons, 1 do if weapons[i].name == weaponName then weapons[i].count = weapons[i].count + 1 foundWeapon = true end end if not foundWeapon then table.insert(weapons, { name = weaponName, count = 1 }) end store.set('weapons', weapons) cb() end) end) ESX.RegisterServerCallback('esx_unicornjob:removeVaultWeapon', function(source, cb, weaponName) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.addWeapon(weaponName, 1000) TriggerEvent('esx_datastore:getSharedDataStore', 'society_unicorn', function(store) local weapons = store.get('weapons') if weapons == nil then weapons = {} end local foundWeapon = false for i=1, #weapons, 1 do if weapons[i].name == weaponName then weapons[i].count = (weapons[i].count > 0 and weapons[i].count - 1 or 0) foundWeapon = true end end if not foundWeapon then table.insert(weapons, { name = weaponName, count = 0 }) end store.set('weapons', weapons) cb() end) end) ESX.RegisterServerCallback('esx_unicornjob:getPlayerInventory', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) local items = xPlayer.inventory cb({ items = items }) end) local function SellJB(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('jagerbomb').count <= 0 then jagerbomb = 0 else jagerbomb = 1 end if jagerbomb == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('jagerbomb').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) jagerbomb = 0 return else if (jagerbomb == 1) then SetTimeout(1100, function() --local argent = math.random(12,17) local money = math.random(12,17) xPlayer.removeInventoryItem('jagerbomb', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellJB(source,zone) end) end end end end end local function SellG(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('golem').count <= 0 then golem = 0 else golem = 1 end if golem == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('golem').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) golem = 0 return else if (golem == 1) then SetTimeout(1100, function() --local argent = math.random(14,19) local money = math.random(14,19) xPlayer.removeInventoryItem('golem', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellG(source,zone) end) end end end end end local function SellWC(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('whiskycoca').count <= 0 then whiskycoca = 0 else whiskycoca = 1 end if whiskycoca == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('whiskycoca').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) whiskycoca = 0 return else if (whiskycoca == 1) then SetTimeout(1100, function() --local argent = math.random(12,17) local money = math.random(12,17) xPlayer.removeInventoryItem('whiskycoca', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellWC(source,zone) end) end end end end end local function SellRC(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('rhumcoca').count <= 0 then rhumcoca = 0 else rhumcoca = 1 end if rhumcoca == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('rhumcoca').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) rhumcoca = 0 return else if (rhumcoca == 1) then SetTimeout(1100, function() --local argent = math.random(12,17) local money = math.random(12,17) xPlayer.removeInventoryItem('rhumcoca', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellRC(source,zone) end) end end end end end local function SellVRB(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('vodkaenergy').count <= 0 then vodkaenergy = 0 else vodkaenergy = 1 end if vodkaenergy == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('vodkaenergy').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) vodkaenergy = 0 return else if (vodkaenergy == 1) then SetTimeout(1100, function() --local argent = math.random(14,19) local money = math.random(14,19) xPlayer.removeInventoryItem('vodkaenergy', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellVRB(source,zone) end) end end end end end local function SellVF(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('vodkafruit').count <= 0 then vodkafruit = 0 else vodkafruit = 1 end if vodkafruit == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('vodkafruit').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) vodkafruit = 0 return else if (vodkafruit == 1) then SetTimeout(1100, function() --local argent = math.random(14,19) local money = math.random(14,19) xPlayer.removeInventoryItem('vodkafruit', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellVF(source,zone) end) end end end end end local function SellRF(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('rhumfruit').count <= 0 then rhumfruit = 0 else rhumfruit = 1 end if rhumfruit == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('rhumfruit').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) rhumfruit = 0 return else if (rhumfruit == 1) then SetTimeout(1100, function() --local argent = math.random(14,19) local money = math.random(14,19) xPlayer.removeInventoryItem('rhumfruit', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellRF(source,zone) end) end end end end end local function SellTP(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('teqpaf').count <= 0 then teqpaf = 0 else teqpaf = 1 end if teqpaf == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('teqpaf').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) teqpaf = 0 return else if (teqpaf == 1) then SetTimeout(1100, function() --local argent = math.random(12,17) local money = math.random(12,17) xPlayer.removeInventoryItem('teqpaf', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellTP(source,zone) end) end end end end end local function SellM(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('mojito').count <= 0 then mojito = 0 else mojito = 1 end if mojito == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('mojito').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) mojito = 0 return else if (mojito == 1) then SetTimeout(1100, function() --local argent = math.random(17,22) local money = math.random(17,22) xPlayer.removeInventoryItem('mojito', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellM(source,zone) end) end end end end end local function SellMA(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('mixapero').count <= 0 then mixapero = 0 else mixapero = 1 end if mixapero == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('mixapero').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) mixapero = 0 return else if (mixapero == 1) then SetTimeout(1100, function() --local argent = math.random(25,30) local money = math.random(25,30) xPlayer.removeInventoryItem('mixapero', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellMA(source,zone) end) end end end end end local function SellMS(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('metreshooter').count <= 0 then metreshooter = 0 else metreshooter = 1 end if metreshooter == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('metreshooter').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) metreshooter = 0 return else if (metreshooter == 1) then SetTimeout(1100, function() --local argent = math.random(30,40) local money = math.random(30,40) xPlayer.removeInventoryItem('metreshooter', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellMS(source,zone) end) end end end end end local function SellJC(source, zone) if PlayersSelling[source] == true then local xPlayer = ESX.GetPlayerFromId(source) if zone == 'SellFarm' then if xPlayer.getInventoryItem('jagercerbere').count <= 0 then jagercerbere = 0 else jagercerbere = 1 end if jagercerbere == 0 then TriggerClientEvent('esx:showNotification', source, _U('no_product_sale')) return elseif xPlayer.getInventoryItem('jagercerbere').count <= 0 then TriggerClientEvent('esx:showNotification', source, _U('no_drink_sale')) jagercerbere = 0 return else if (jagercerbere == 1) then SetTimeout(1100, function() --local argent = math.random(22,27) local money = math.random(22,27) xPlayer.removeInventoryItem('jagercerbere', 1) local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_unicorn', function(account) societyAccount = account end) if societyAccount ~= nil then xPlayer.addMoney(argent) societyAccount.addMoney(money) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('have_earned') .. argent) TriggerClientEvent('esx:showNotification', xPlayer.source, _U('comp_earned') .. money) end SellJC(source,zone) end) end end end end end RegisterServerEvent('esx_unicornjob:startSell') AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellJB(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellG(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellWC(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellRC(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellVRB(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellVF(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellRF(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellTP(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellM(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellMA(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellMS(_source, zone) end end) AddEventHandler('esx_unicornjob:startSell', function(zone) local _source = source if PlayersSelling[_source] == false then TriggerClientEvent('esx:showNotification', _source, '~r~C\'est pas bien de glitch ~w~') PlayersSelling[_source]=false else PlayersSelling[_source]=true TriggerClientEvent('esx:showNotification', _source, _U('sale_in_prog')) SellJC(_source, zone) end end) RegisterServerEvent('esx_unicornjob:stopSell') AddEventHandler('esx_unicornjob:stopSell', function() local _source = source if PlayersSelling[_source] == true then PlayersSelling[_source]=false TriggerClientEvent('esx:showNotification', _source, 'Vous sortez de la ~r~zone') else TriggerClientEvent('esx:showNotification', _source, 'Vous pouvez ~g~vendre') PlayersSelling[_source]=true end end)
local setmetatable = setmetatable local _M = {} function _M:new(create_app, Router, Group, Request, Response) local instance = {} instance.router = Router instance.group = Group instance.request = Request instance.response = Response instance.fn = create_app instance.app = nil setmetatable(instance, { __index = self, __call = self.create_app }) return instance end -- Generally, this shouled only be used by `lor` framework itself. function _M:create_app(options) self.app = self.fn(options) return self.app end function _M:Router(options) return self.group:new(options) end function _M:Request() return self.request:new() end function _M:Response() return self.response:new() end return _M
local TestAssetItem = DClass("TestAssetItem", BaseComponent) _G.TestAssetItem = TestAssetItem function TestAssetItem:init() self.icon = self.transform:Find("Icon"):GetComponent(typeof(Image)) local icons = { "Icon/Head/10001", "Icon/Head/10002", "Icon/Head/10003", "Icon/Buff/Buff01", "Icon/Buff/Buff02", "Icon/Buff/Buff03", "Icon/ItemIcon/10001", "Icon/ItemIcon/10002", "Icon/ItemIcon/10003", "Icon/SpriteStar/Quality_SSS", "Icon/SpriteStar/Quality_SS", "Icon/SpriteStar/Quality_S", "Icon/SpriteStar/Quality_A", "Icon/SpriteStar/Quality_B", "Icon/ItemQuality/Quality_Big01", "Icon/ItemQuality/Quality_Big02", "Icon/ItemQuality/Quality_Big03", "Icon/ItemQuality/Quality_Big04", "Icon/ItemQuality/Quality_Big05", } self:setSprite(self.icon, icons[math.random(1,#icons)]) end
local actor, super = Class(Actor, "kris_lw") function actor:init() super:init(self) -- Display name (optional) self.name = "Kris" -- Width and height for this actor, used to determine its center self.width = 19 self.height = 37 -- Hitbox for this actor in the overworld (optional, uses width and height by default) self.hitbox = {0, 25, 19, 14} -- Color for this actor used in outline areas (optional, defaults to red) self.color = {0, 1, 1} -- Path to this actor's sprites (defaults to "") self.path = "party/kris/light" -- This actor's default sprite or animation, relative to the path (defaults to "") self.default = "walk" -- Sound to play when this actor speaks (optional) self.voice = nil -- Path to this actor's portrait for dialogue (optional) self.portrait_path = nil -- Offset position for this actor's portrait (optional) self.portrait_offset = nil -- Whether this actor as a follower will blush when close to the player self.can_blush = false -- Table of sprite animations self.animations = {} -- Table of sprite offsets (indexed by sprite name) self.offsets = {} end return actor
AddObjectCommand = Command:extends{} AddObjectCommand.className = "AddObjectCommand" function AddObjectCommand:init(objType, params) self.objType = objType self.params = params end function AddObjectCommand:execute() local bridge = ObjectBridge.GetObjectBridge(self.objType) local objectID = bridge.s11n:Add(self.params) self.params.objectID = objectID self.params.__modelID = bridge.getObjectModelID(objectID) end function AddObjectCommand:unexecute() local bridge = ObjectBridge.GetObjectBridge(self.objType) if not self.params.__modelID then Log.Warning("No modelID for un-add (remove).") end local objectID = bridge.getObjectSpringID(self.params.__modelID) if not objectID then Log.Warning("No objectID for un-add (remove) for modelID: .", self.params.__modelID) end bridge.s11n:Remove(objectID) end
error('shard should not be mandatory dependency')
local S = core.get_translator("wardrobe") wardrobe.formspec_name = "wardrobe_wardrobeSkinForm" function wardrobe.show_formspec(player, page) local pname = player:get_player_name() if not pname or pname == "" then return end local page_count = math.ceil(wardrobe.skin_count / wardrobe.skins_per_page) local page_prev = page-1 local page_next = page+1 if page_prev < 1 then page_prev = page_count elseif page_next > page_count then page_next = 1 end local n = wardrobe.skin_count if n <= 0 then return end local nPages = math.ceil(n / wardrobe.skins_per_page) if not page or page > nPages then page = 1 end local s = 1 + wardrobe.skins_per_page*(page-1) -- first skin index for page local e = math.min(s+wardrobe.skins_per_page-1, n) -- last skin index for page local skins = {} for i = s, e do local skin = wardrobe.skins[i] local skinName = core.formspec_escape(wardrobe.skinNames[skin]) table.insert(skins, {skin, skinName}) end local formspec if not wardrobe.previews then formspec = "size[5,10]" .. "label[0,0;" .. S("Change Into:") .. "]" .. "label[1.8,0.5;" .. S("Page @1", tostring(page) .. " / " .. tostring(page_count)) .. "]" for idx, s in ipairs(skins) do formspec = formspec .. "button_exit[0," .. idx ..";5,1;s:" .. s[1] .. ";" .. s[2] .. "]" end formspec = formspec .. "button[1.5,9;1,1;n:p" .. tostring(page_prev) .. ";" .. S("<<") .. "]" .. "button[2.5,9;1,1;n:p" .. tostring(page_next) .. ";" .. S(">>") .. "]" else formspec = "size[12,10]" .. "label[0,0;" .. S("Change Into:") .. "]" .. "label[5.3,0.5;" .. S("Page @1", tostring(page) .. " / " .. tostring(page_count)) .. "]" local border_l = 0 local addon = 1 for idx, s in ipairs(skins) do local preview = s[1]:split(".png")[1] .. "-preview.png" if idx % 5 == 0 then addon = 1 border_l = border_l + 6 end formspec = formspec .. "button_exit[" .. border_l .. "," .. addon+.5 ..";5,1;s:" .. s[1] .. ";" .. s[2] .. "]" if wardrobe.cached_previews[s[1]] then formspec = formspec .. "image[" .. border_l+5 .. "," .. addon .. ";1,2;" .. preview .."]" end addon = addon + 2 end formspec = formspec .. "button[5,9;1,1;n:p" .. tostring(page_prev) .. ";" .. S("<<") .. "]" .. "button[6,9;1,1;n:p" .. tostring(page_next) .. ";" .. S(">>") .. "]" end core.show_formspec(pname, wardrobe.formspec_name, formspec) end core.register_on_player_receive_fields(function(player, formName, fields) if formName ~= wardrobe.formspec_name then return end local pname = player:get_player_name() if not pname or pname == "" then return end for fieldName in pairs(fields) do if #fieldName > 2 then local action = string.sub(fieldName, 1, 1) local value = string.sub(fieldName, 3) if action == "n" then wardrobe.show_formspec(player, tonumber(string.sub(value, 2))) return elseif action == "s" then wardrobe.changePlayerSkin(pname, value) return end end end end)
--############################################################################# --# Console HTML5 Plugin --# (c)2018 C. Byerley (develephant) --############################################################################# local lib local platform = system.getInfo("platform") if platform == 'html5' then lib = require("console_js") else -- wrapper for non web platforms local CoronaLibrary = require "CoronaLibrary" -- Create stub library for simulator lib = CoronaLibrary:new{ name='console', publisherId='com.develephant' } -- Alert for non-HTML5 platforms local function defaultFunction() print( "WARNING: The '" .. lib.name .. "' library is not available on this platform." ) end lib.log = defaultFunction end return lib
object_building_kashyyyk_poi_kash_shaman_ritual_fire = object_building_kashyyyk_shared_poi_kash_shaman_ritual_fire:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_shaman_ritual_fire, "object/building/kashyyyk/poi_kash_shaman_ritual_fire.iff")
if (not system) then if (not (CachesDirectory and DocumentsDirectory and ResourceDirectory and TemporaryDirectory)) then return nil end local caches_path = CachesDirectory.."/lua-script.zip$?.lua;" local documents_path = DocumentsDirectory.."/lua-script.zip$?.lua;" local resource_path = ResourceDirectory.."$assets/lua-script/?.lua;" package.path = caches_path..documents_path..resource_path print("### CachesDirectory = "..CachesDirectory) print("### DocumentsDirectory = "..DocumentsDirectory) print("### ResourceDirectory = "..ResourceDirectory) print("### TemporaryDirectory = "..TemporaryDirectory) print("### package.path = "..package.path) end return require("system.config")
return { treginifile = { type = 'treginifile', fields = { create = { ret = 'treginifile' }, readinteger = { ret = 'integer' }, writeinteger = { type = 'procedure' } } } }
--[[ General Lua Libraries for Lua 5.1, 5.2 & 5.3 Copyright (C) 2002-2018 stdlib authors ]] --[[-- Additions to the core math module. The module table returned by `std.math` also contains all of the entries from the core math table. An hygienic way to import this module, then, is simply to override the core `math` locally: local math = require 'std.math' @corelibrary std.math ]] local _ = require 'std._base' local argscheck = _.typecheck and _.typecheck.argscheck _ = nil local _ENV = require 'std.normalize' { 'math', merge = 'table.merge', } --[[ ================= ]]-- --[[ Implementatation. ]]-- --[[ ================= ]]-- local M local _floor = math.floor local function floor(n, p) if(p or 0) == 0 then return _floor(n) end local e = 10 ^ p return _floor(n * e) / e end local function round(n, p) local e = 10 ^(p or 0) return _floor(n * e + 0.5) / e end --[[ ================= ]]-- --[[ Public Interface. ]]-- --[[ ================= ]]-- local function X(decl, fn) return argscheck and argscheck('std.math.' .. decl, fn) or fn end M = { --- Core Functions -- @section corefuncs --- Extend `math.floor` to take the number of decimal places. -- @function floor -- @number n number -- @int[opt=0] p number of decimal places to truncate to -- @treturn number `n` truncated to `p` decimal places -- @usage -- tenths = floor(magnitude, 1) floor = X('floor(number, ?int)', floor), --- Round a number to a given number of decimal places. -- @function round -- @number n number -- @int[opt=0] p number of decimal places to round to -- @treturn number `n` rounded to `p` decimal places -- @usage -- roughly = round(exactly, 2) round = X('round(number, ?int)', round), } return merge(math, M)
local VariationalDropout, parent = torch.class('onmt.VariationalDropout', 'nn.Module') function VariationalDropout:__init(p) parent.__init(self) self.p = p or 0.5 self.train = true if self.p >= 1 or self.p < 0 then error('<dropout> illegal percentage, must be 0 <= p < 1') end self.noiseInit = torch.Tensor(1):zero() self.sharedNoise = torch.Tensor(1,1) end function VariationalDropout.initializeNetwork(net) net:apply(function(m) if m.noiseInit then m.noiseInit[1] = 0 end end) end function VariationalDropout:updateOutput(input) self.output:resizeAs(input):copy(input) if self.p > 0 and self.train then self.sharedNoise:resizeAs(input) if self.noiseInit[1] == 0 then self.sharedNoise:bernoulli(1 - self.p) self.sharedNoise:div(1 - self.p) self.noiseInit[1] = 1 end self.output:cmul(self.sharedNoise) end return self.output end function VariationalDropout:updateGradInput(_, gradOutput) self.gradInput:resizeAs(gradOutput):copy(gradOutput) if self.p > 0 and self.train then -- Simply mask the gradients with the sharedNoise vector. self.gradInput:cmul(self.sharedNoise) end return self.gradInput end function VariationalDropout:setp(p) self.p = p end function VariationalDropout:__tostring__() return string.format('%s(%f)', torch.type(self), self.p) end function VariationalDropout:clearState() if self.sharedNoise then self.noiseInit[1] = 0 self.sharedNoise:set() end return parent.clearState(self) end
local LibQuest = Wheel:Set("LibQuest", 1) if (not LibQuest) then return end local LibMessage = Wheel("LibMessage") assert(LibMessage, "LibQuest requires LibMessage to be loaded.") local LibEvent = Wheel("LibEvent") assert(LibEvent, "LibQuest requires LibEvent to be loaded.") LibMessage:Embed(LibQuest) LibEvent:Embed(LibQuest) -- Library registries LibQuest.embeds = LibQuest.embeds or {} local embedMethods = { } LibQuest.Embed = function(self, target) for method in pairs(embedMethods) do target[method] = self[method] end self.embeds[target] = true return target end -- Upgrade existing embeds, if any for target in pairs(LibQuest.embeds) do LibQuest:Embed(target) end
return Command 'cuddle' :setCategory 'Roleplay' :setDesc 'Cuddles the mentioned user.' :setAliases {'snuggles'} :setUsage '<@user>' :run(function(msg, args, util) local user = msg.mentionedUsers:toArray()[1] p(util.giphy 'cuddle') local embed = util.Embed() :setTitle(msg.author.name..' cuddles '..user.name) :setImage(util.giphy 'cuddle' ) :setColor 'random' :setFooter(settings.footer) :setTimestamp() :finish(); msg.channel:send(embed) end);
Config = {} Config.Ped = { {label='Stripteaseuse 1',type=5, hash='s_f_y_stripper_01'}, {label='Stripteaseuse 2',type=5, hash='s_f_y_stripper_02'}, {label='Stripteaseuse Fat',type=5, hash='a_f_m_fatcult_01'}, {label='Stripteaseurs 1',type=5, hash='a_m_y_musclbeac_01'}, {label='Stripteaseurs SM',type=5, hash='a_m_m_acult_01'}, } Config.Salle = { scene1 = { label = 'Fond scene gauche', pos = {x=101.884, y=-1289.77, z=29.258, a=290.598}, }, scene2 = { label = 'Fond scene droit', pos = {x=104.6779, y=-1295.2697, z=29.258, a=297.289}, }, scene3 = { label = 'Fond scene centre', pos = {x=104.0453, y=-1292.199, z=29.258, a=298.912}, }, scene4 = { label = 'scene centre', pos = {x=107.359, y=-1290.2869, z=28.8587, a=297.33}, }, scene5 = { label = 'scene avant gauche', pos = {x=112.0371 ,y=-1286.2375, z=28.4586, a=30.04}, }, scene6 = { label = 'scene avant droit', pos = {x=113.205, y=-1288.293, z=28.4586, a=211.88}, } } Config.Dict = { show1={ label = 'Lap dance 1', name = 'mini@strip_club@lap_dance@ld_girl_a_song_a_p1', anim ='ld_girl_a_song_a_p1_f', }, show2={ label = 'Lap dance 2', name = 'mini@strip_club@lap_dance@ld_girl_a_song_a_p2', anim ='ld_girl_a_song_a_p2_f', }, show3={ label = 'Lap dance 3', name = 'mini@strip_club@lap_dance@ld_girl_a_song_a_p3', anim ='ld_girl_a_song_a_p3_f', }, show4={ label = 'pole_dance', name = 'mini@strip_club@pole_dance@pole_dance1', anim ='pd_dance_0', }, } Config.Zones = { Pos = { x = 122.35705566406, y = -1281.4152832031, z = 29.480518341064}, }
local noise = love.math.noise local function update(s, dt, camera) if s.remaining < 0 then return end local k = s.remaining / s.duration local x = (noise(s.seed+0, s.remaining * s.freq) - 0.5) * 2 local y = (noise(s.seed+1, s.remaining * s.freq) - 0.5) * 2 local angle = (noise(s.seed+2, s.remaining * s.freq) - 0.5) * 2 local d = s.magnitude * k x, y = x * d, y * d angle = angle * s.rotationMagnitude camera.cx, camera.cy = camera.cx + x, camera.cy + y camera.angle = camera.angle + angle s.remaining = s.remaining - dt end local class = { update = update } class.__index = class local function new(dist, rot, time, freq) return setmetatable({ seed = math.random() * 1000, remaining = time, duration = time, freq = freq, magnitude = dist, rotationMagnitude = rot }, class) end return { new = new, class = class }
--Script Name : jlp_Remove items and time selection, tracks, env depending on focus --Author : Jean Loup Pecquais --Description : Remove items and time selection, tracks, env depending on focus --v1.0.0 local libPath = reaper.GetExtState("Reaper Evolution", "libPath") if not libPath or libPath == "" then reaper.MB("Reaper Evolution library is not found. Please refer to user guide", "Library not found", 0) return end loadfile(libPath .. "reaVolutionLib.lua")() ------------------------------------------------------------------------------------------------------------- local frames = 10 reaper.PreventUIRefresh(-1*frames) reaper.Undo_BeginBlock() local delete = reaper.NamedCommandLookup("_SWS_SMARTREMOVE") reaper.Main_OnCommandEx(delete, 0, 0) reaper.Main_OnCommandEx(40289, 0, 0) if reaper.GetCursorContext() == 1 then if reaper.GetToggleCommandState(40573) ~= 1 then reaper.Main_OnCommandEx(40635, 0, 0) --Time selection: Remove time selection end end reaper.Undo_EndBlock("Remove items, tracks or envelope depending on focus", -1) reaper.PreventUIRefresh(frames)
local table = require("hs/lang/table") local TextureManager = require("hs/core/TextureManager") local DisplayObject = require("hs/core/DisplayObject") local Event = require("hs/core/Event") -------------------------------------------------------------------------------- -- 単一のテクスチャを描画する為のクラスです. -- -- @class table -- @name Sprite -------------------------------------------------------------------------------- local M = DisplayObject() -- プロパティ定義 M:setPropertyName("texture") M:setPropertyName("flipX") M:setPropertyName("flipY") --------------------------------------- -- コンストラクタです. -- @name Sprite:new -- @param texture テクスチャ、もしくは、パス -- @param params 設定プロパティテーブル --------------------------------------- function M:init(texture, params) M:super(self) -- textureの設定 if texture then self:setTexture(texture) end if params then table.copy(params, self) end -- UVマッピングを更新 self:updateUVRect() end function M:onInitial() DisplayObject.onInitial(self) self._flipX = false self._flipY = false end --------------------------------------- -- MOAIDeckを生成します. --------------------------------------- function M:newDeck() local deck = MOAIGfxQuad2D.new() deck:setUVRect(0, 0, 1, 1) return deck end --------------------------------------- -- UVマッピングを更新します. --------------------------------------- function M:updateUVRect() local x1 = self.flipX and 1 or 0 local y1 = self.flipY and 1 or 0 local x2 = self.flipX and 0 or 1 local y2 = self.flipY and 0 or 1 self.deck:setUVRect(x1, y1, x2, y2) end --------------------------------------- -- テキスチャを設定します. -- サイズも自動で設定されます. --------------------------------------- function M:setTexture(texture) if type(texture) == "string" then texture = TextureManager:get(texture) end if not self._initialized and texture then local width, height = texture:getSize() self:setSize(width, height) self._initialized = true end self.deck:setTexture(texture) self._texture = texture end --------------------------------------- -- テクスチャを返します. --------------------------------------- function M:getTexture() return self._texture end --------------------------------------- -- flipXを設定します. --------------------------------------- function M:setFlipX(value) self._flipX = value self:updateUVRect() end --------------------------------------- -- flipXを返します. --------------------------------------- function M:getFlipX() return self._flipX end --------------------------------------- -- flipYを設定します. --------------------------------------- function M:setFlipY(value) self._flipY = value self:updateUVRect() end --------------------------------------- -- flipYを返します. --------------------------------------- function M:getFlipY() return self._flipY end --------------------------------------- -- 表示オブジェクトのサイズを設定します. --------------------------------------- function M:setSize(width, height) DisplayObject.setSize(self, width, height) self.deck:setRect(0, 0, self.width, self.height) end return M
-- data.lua data.raw.item["artillery-turret"].sound = { filename = "__EpicArtillerySounds__/sounds/KABOOM.ogg", volume = 1 } data.raw.gun["artillery-wagon-cannon"].attack_parameters.sound = { filename = "__EpicArtillerySounds__/sounds/KABOOM.ogg", volume = 1 } -- integrations require("integrations.bigger-artillery.data") require("integrations.lightArtillery.data")
--[[ ---- SettingsLib About | SettingsLib is a general Settings Library for every exploit-related use-case. Project Link | https://github.com/YieldingExploiter/Scripts/blob/main/src/glib/settings/Script.lua Supported Environments | Script-Ware | Synapse-X | Krnl Required Functions | readfile | writefile | isfile | isfolder License | Copyright © 2021 YieldingCoder | | 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. ]] -- return (function() -- ANCHOR Pure Lua JSON Stringify/Parse Implementation local JSON = {} local function b( c ) if type(c) ~= 'table' then return type(c) end local d = 1; for e in pairs(c) do if c[d] ~= nil then d = d + 1 else return 'table' end end if d == 1 then return 'table' else return 'array' end end local function f( g ) local h = { '\\'; '"'; '/'; '\b'; '\f'; '\n'; '\r'; '\t' } local i = { '\\'; '"'; '/'; 'b'; 'f'; 'n'; 'r'; 't' } for d, j in ipairs(h) do g = g:gsub(j, '\\' .. i[d]) end return g end local function k( l, m, n, o ) m = m + #l:match('^%s*', m) if l:sub(m, m) ~= n then if o then error('Expected ' .. n .. ' near position ' .. m) end return m, false end return m + 1, true end local function p( l, m, q ) q = q or '' local r = 'End of input found while parsing string.' if m > #l then error(r) end local j = l:sub(m, m) if j == '"' then return q, m + 1 end if j ~= '\\' then return p(l, m + 1, q .. j) end local s = { b = '\b'; f = '\f'; n = '\n'; r = '\r'; t = '\t' } local t = l:sub(m + 1, m + 1) if not t then error(r) end return p(l, m + 2, q .. (s[t] or t)) end local function u( l, m ) local v = l:match('^-?%d+%.?%d*[eE]?[+-]?%d*', m) local q = tonumber(v) if not q then error('Error parsing number at position ' .. m .. '.') end return q, m + #v end function JSON.stringify( c, w ) local g = {} local x = b(c) if x == 'array' then if w then error('Can\'t encode array as key.') end g[#g + 1] = '[' for d, q in ipairs(c) do if d > 1 then g[#g + 1] = ', ' end g[#g + 1] = JSON.stringify(q) end g[#g + 1] = ']' elseif x == 'table' then if w then error('Can\'t encode table as key.') end g[#g + 1] = '{' for y, z in pairs(c) do if #g > 1 then g[#g + 1] = ', ' end g[#g + 1] = JSON.stringify(y, true) g[#g + 1] = ':' g[#g + 1] = JSON.stringify(z) end g[#g + 1] = '}' elseif x == 'string' then return '"' .. f(c) .. '"' elseif x == 'number' then if w then return '"' .. tostring(c) .. '"' end return tostring(c) elseif x == 'boolean' then return tostring(c) elseif x == 'nil' then return 'null' else error('Unjsonifiable type: ' .. x .. '.') end return table.concat(g) end JSON.null = {} function JSON.parse( l, m, A ) m = m or 1; if m > #l then error('Reached unexpected end of input.') end local m = m + #l:match('^%s*', m) local B = l:sub(m, m) if B == '{' then local c, C, D = {}, true, true; m = m + 1; while true do C, m = JSON.parse(l, m, '}') if C == nil then return c, m end if not D then error('Comma missing between object items.') end m = k(l, m, ':', true) c[C], m = JSON.parse(l, m) m, D = k(l, m, ',') end elseif B == '[' then local E, q, D = {}, true, true; m = m + 1; while true do q, m = JSON.parse(l, m, ']') if q == nil then return E, m end if not D then error('Comma missing between array items.') end E[#E + 1] = q; m, D = k(l, m, ',') end elseif B == '"' then return p(l, m + 1) elseif B == '-' or B:match('%d') then return u(l, m) elseif B == A then return nil, m + 1 else local F = { ['true'] = true; ['false'] = false; ['null'] = JSON.null } for G, H in pairs(F) do local I = m + #G - 1; if l:sub(m, I) == G then return H, I + 1 end end local J = 'position ' .. m .. ': ' .. l:sub(m, m + 10) error('Invalid json syntax starting at ' .. J) end end -- ANCHOR Constants local confDir = 'cfg.settingsLib' -- ANCHOR Ensure Function Stuff local isFile = getfenv().isfile or function() return true end local isFolder = getfenv().isfolder or function() end if not writefile or not readfile or not makefolder then error('Invalid Environment') end -- ANCHOR Main Class local Settings = {} Settings['JSONImplementation'] = setmetatable( {}, { __index = JSON; __newindex = function( t, k, v ) error('Cannot assign to table') end; } ) Settings['Name'] = 'Unknown'; Settings['-v>>9_82'] = {}; -- Settings.Settings = setmetatable({},{ -- __newindex = function(t,k,v) -- t:ForceSave() -- end -- }) function Settings:Set( k, v ) self['-v>>9_82'][k] = v; self:ForceSave(); return self; end function Settings:Get( k ) return self['-v>>9_82'][k]; end function Settings:Default( k, d ) if typeof(self:Get(k)) == 'nil' then self:Set(k, d) end return self; end function Settings:ForceSave() if not isFolder(confDir) then makefolder(confDir) end writefile(confDir .. '/' .. self.Name .. '.sl', JSON.stringify(self['-v>>9_82'])) if not isfile or not isfile(confDir .. '/README.md') then writefile( confDir .. '/README.md', [[ # SettingsLib Config Folder ## This Folder This folder contains the individual Files in [SLJSON](https://github.com/YieldingExploiter/Scripts/blob/main/src/glib/settings/docs/SLJSON.md) Format ## About SettingsLib SettingsLib is a general Settings Library for every Roblox Exploit-related use-case. ## Project Link [https://github.com/YieldingExploiter/Scripts/blob/main/src/glib/settings/Script.lua](https://github.com/YieldingExploiter/Scripts/blob/main/src/glib/settings/Script.lua) ## LICENSE Copyright © 2021 YieldingCoder 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. ]] ) end end function Settings:Reload() local path = confDir .. '/' .. self.Name .. '.sl' if isFile(path) then self['-v>>9_82'] = JSON.parse(readfile(path)) else self['-v>>9_82'] = { ['__sl.issljson'] = true }; end return self; end Settings.Version = 1; Settings.New = function( ScriptName ) if not ScriptName then error('Provide the script name as the first parameter to Settings.new!') end local self = setmetatable({}, { __index = Settings }) self.Name = ScriptName; self.New = function() error('Function Unavailable as a Proprety of SettingsInstance') end; self['-v>>9_82'] = {}; self:Reload(); self:ForceSave(); if not self['-v>>9_82']['__sl.issljson'] then warn( 'Invalid SLJSON File - Missing __sl.issljson=true. Potential Corruption Occured.' ); self:Set('__sl.potentialCorruptionDetected', true) else self:Set('__sl.potentialCorruptionDetected', false) end self:Set('__sl.slversion', Settings.Version) return self end; Settings.new = Settings.New; Settings.__proto__ = Settings; return Settings; end)()
include("shared.lua") function ENT:Initialize() self.CanDraw = GetConVarNumber("metrostroi_drawsignaldebug")>0 for k,v in pairs(self.ValidModels) do if v==self:GetModel() then self.CanDraw = true break end end end function ENT:Draw() if not self.CanDraw then return end self:DrawModel() end cvars.AddChangeCallback("metrostroi_drawsignaldebug", function() for k,auto in pairs(ents.FindByClass("gmod_train_autodrive_coil")) do if auto.Initialize then auto:Initialize() end end end,"AutodriveCoil")
function computeDistance(pt1, pt2) local squareSum = 0 for k, v in pairs(pt1) do squareSum = squareSum + (pt1[k]-pt2[k])*(pt1[k]-pt2[k]) end return math.sqrt(squareSum) end function computeRelativeOrientation(currentPos, targetPos) local ori if targetPos[1]-currentPos[1] >= 0 then ori = {0, 0, math.atan((targetPos[2]-currentPos[2])/(targetPos[1]-currentPos[1]))} else ori = {0, 0, math.pi+math.atan((targetPos[2]-currentPos[2])/(targetPos[1]-currentPos[1]))} end return ori end function checkPositionValid(inputPosition) -- print('check validity!') -- local goalPostition -- if #inputPosition == 2 then -- goalPostition = inputPosition -- elseif #inputPosition == 3 then -- goalPostition = {inputPosition[1], inputPosition[2]} -- else -- print('Target dimention incorrect!') -- return false -- end -- local goalPostition = inputPosition -- if not simExtOMPL_isStateValid(taskHandle, inputPosition) == 1 then -- return false -- end local goalPostition = {inputPosition[1], inputPosition[2], droneHeight} -- print(targetHandle, inspect(stateSpaceHandle), inspect(inputPosition), inspect(goalPostition)) -- print(heliSuffix, inspect(droneHandles)) if simExtOMPL_isStateValid(taskHandle, inputPosition) ~= 1 then return false end -- Check collision with other drones for k, v in pairs(droneHandles) do if k ~= (heliSuffix+2) and computeDistance(goalPostition, simGetObjectPosition(v, -1)) < 1 then return false end end -- Check if the path is valid local currentTargetPos = simGetObjectPosition(targetObj, -1) local r, path = computePath({currentTargetPos[1], currentTargetPos[2]}, inputPosition) if r == 0 then return false end -- -- Check collision with buildings -- local currentTargetPos = simGetObjectPosition(targetObj, -1) -- simSetObjectPosition(targetObj, -1, goalPostition) -- for k, v in pairs(obstacleHandles) do -- print('Obstacle', simGetObjectName(v)) -- local r, dis = simCheckDistance(targetObj, v, 5) -- if r==1 then -- print('distance', simGetObjectName(v), inspect(goalPostition), simCheckCollision(targetObj, v), inspect(dis)) -- end -- if simCheckCollision(targetObj, v) == 1 then -- simSetObjectPosition(targetObj, -1, currentTargetPos) -- return false -- end -- end -- simSetObjectPosition(targetObj, -1, currentTargetPos) -- local r, tag, locLow, locHigh = simCheckOctreePointOccupancy(simGetObjectHandle('Octree'), 0, goalPostition) -- print('octree check', inspect(goalPostition), r, tag, locLow, locHigh) -- if r == 1 then -- return false -- end return true end function setTargetPos(pos) -- ********** Using OMPL simSetObjectPosition(targetObj, -1, pos) -- ********** Using OMPL -- -- ********** Using acceleration -- totalTargetTargetDistance = 0 -- currentTargetTargetProgress = 0 -- targetV = {0, 0} -- targetDirection = {0, 0} -- simSetObjectPosition(targetObj, -1, pos) -- -- ********** Using acceleration end function setTargetTarget(pos, ori) -- ********** Using OMPL targetPath = {} targetTargetPosition = pos pathCalculated = 0 currentIndexOnPath = 1 -- -- Do the path planning by OMPL -- local currentTargetPos = simGetObjectPosition(targetObj,-1) -- local r, path = computePath({currentTargetPos[1], currentTargetPos[2]}, {targetTargetPosition[1], targetTargetPosition[2]}) -- if r ~= 0 then -- targetPath = path -- visualize2dPath(targetPath, currentTargetPos[3]) -- pathCalculated = 1 -- end -- ********** Using OMPL -- -- ********** Using acceleration -- local targetTargetPosition = pos -- local targetPos = simGetObjectPosition(targetObj, -1) -- totalTargetTargetDistance = computeDistance(targetPos, targetTargetPosition) -- if totalTargetTargetDistance > targetTargetDisThresh then -- currentTargetTargetProgress = 0 -- targetV = {0, 0} -- targetDirection = {(pos[1]-targetPos[1])/totalTargetTargetDistance, (pos[2]-targetPos[2])/totalTargetTargetDistance} -- elseif totalTargetTargetDistance > 0 then -- setTargetPos(pos) -- end -- -- ********** Using acceleration -- simSetObjectOrientation(targetObj, -1, ori) end function setTrackingTarget(objHandle) if objHandle ~= trackingTargetHandle then trackingTargetHandle = objHandle if objHandle == -1 then lastTrackingTargetPos = nil else pathCalculated = 3 end end end function checkVisible(position) position[3] = 0.8 -- For human tracking local m = simGetObjectMatrix(frontSensor,-1) m = simGetInvertedMatrix(m) local position_camera = simMultiplyVector(m,position) if position_camera[3] < 0 then return false end local currentAngleX = math.atan(position_camera[1] / position_camera[3]) local currentAngleY = math.atan(position_camera[2] / position_camera[3]) if math.abs(currentAngleX) < halfAngleX and math.abs(currentAngleY) < halfAngleY then return true else return false end end function getObjectPositionFromSensor(objHandle) local position = simGetObjectPosition(objHandle, -1) if checkVisible(position) then return position else return nil end end function visualize2dPath(path, height) initPos = {path[1], path[2]} if not _lineContainer then _lineContainer=simAddDrawingObject(sim_drawing_lines,3,0,-1,99999,{0.2,0.2,0.2}) end simAddDrawingObjectItem(_lineContainer,nil) if path then local pc=#path/2 for i=1, pc-1 do lineDat={path[(i-1)*2+1],path[(i-1)*2+2],height,path[i*2+1],path[i*2+2],height} simAddDrawingObjectItem(_lineContainer,lineDat) end end end function computePath(desiredInitPos, desiredTargetPos) -- if not (checkPositionValid(desiredInitPos) and checkPositionValid(desiredTargetPos)) then -- return 0, {} -- end -- print('computing path for', inspect(desiredInitPos), inspect(desiredTargetPos)) -- desiredInitPos[3] = 8 -- desiredTargetPos[3] = 8 local maxTime = 0.5 -- local minStates = 100 simExtOMPL_setStartState(taskHandle, desiredInitPos) simExtOMPL_setGoalState(taskHandle, desiredTargetPos) -- local r, path = simExtOMPL_compute(taskHandle, maxTime, -1, minStates) -- r = 0 if not successful local r, path = simExtOMPL_compute(taskHandle, maxTime) -- r = 0 if not successful return r, path end function updateTarget() -- ********** Using OMPL -- print('Current index on path', currentIndexOnPath) -- print('pathCalculated', pathCalculated) if pathCalculated==0 then local currentTargetPos = simGetObjectPosition(targetObj,-1) -- print('compute path for', inspect(targetTargetPosition)) -- print('updateTarget: not calculated', inspect(targetTargetPosition), checkPositionValid({targetTargetPosition[1], targetTargetPosition[2]})) local r, path = computePath({currentTargetPos[1], currentTargetPos[2]}, {targetTargetPosition[1], targetTargetPosition[2]}) if r ~= 0 then targetPath = path -- visualize2dPath(targetPath, currentTargetPos[3]) pathCalculated = 1 end end if pathCalculated==1 then if currentIndexOnPath < #targetPath-2 then local currentTargetPos = simGetObjectPosition(targetObj,-1) local currentTargetPos2d = {currentTargetPos[1], currentTargetPos[2]} while true do local nextPos = {targetPath[currentIndexOnPath], targetPath[currentIndexOnPath+1]} if computeDistance(currentTargetPos2d, nextPos) > droneSpeed or currentIndexOnPath >= #targetPath-2 then -- if checkPositionValid({targetPath[currentIndexOnPath], targetPath[currentIndexOnPath+1]}) then -- break -- end break end currentIndexOnPath = currentIndexOnPath + 2 end -- print(inspect({targetPath[currentIndexOnPath], targetPath[currentIndexOnPath+1], currentTargetPos[3]})) setTargetPos({targetPath[currentIndexOnPath], targetPath[currentIndexOnPath+1], currentTargetPos[3]}) simSetObjectOrientation(targetObj, -1, computeRelativeOrientation(simGetObjectPosition(targetObj,-1), lastTrackingTargetPos)) else pathCalculated = 2 end elseif pathCalculated==2 then setTargetPos(targetTargetPosition) simSetObjectOrientation(targetObj, -1, computeRelativeOrientation(simGetObjectPosition(targetObj,-1), lastTrackingTargetPos)) pathCalculated = 3 else -- idle end -- ********** Using OMPL -- -- ********** Using acceleration -- if totalTargetTargetDistance > 0 then -- if currentTargetTargetProgress <= totalTargetTargetDistance/2 then -- -- targetV = {targetDirection[1]*targetAcceleration, targetDirection[2]*targetAcceleration} -- targetV = {targetV[1]+targetDirection[1]*targetAcceleration, targetV[2]+targetDirection[2]*targetAcceleration} -- elseif currentTargetTargetProgress <= totalTargetTargetDistance then -- -- targetV = {targetDirection[1]*targetAcceleration, targetDirection[2]*targetAcceleration} -- targetV = {targetV[1]-targetDirection[1]*targetAcceleration, targetV[2]-targetDirection[2]*targetAcceleration} -- else -- -- Already pass target -- setTargetPos(pos) -- end -- local targetPos = simGetObjectPosition(targetObj, -1) -- simSetObjectPosition(targetObj, -1, {targetPos[1]+targetV[1], targetPos[2]+targetV[2], targetPos[3]}) -- currentTargetTargetProgress = currentTargetTargetProgress + math.sqrt(targetV[1]*targetV[1]+targetV[2]*targetV[2]) -- end -- -- ********** Using acceleration end function createPlanningSpace( ) targetPath = {} targetTargetPosition = simGetObjectPosition(targetObj, -1) pathCalculated = 3 -- 0=not calculated, 1=calculated, 2=completed, 3=waiting currentIndexOnPath=1 taskHandle = simExtOMPL_createTask('droneTargetTask') stateSpaceHandle = {simExtOMPL_createStateSpace('droneStateSpace', sim_ompl_statespacetype_position2d, heli, {0, 0}, {228, 213}, 1)} -- stateSpaceHandle = {simExtOMPL_createStateSpace('droneStateSpace', sim_ompl_statespacetype_position2d, heli, {-25, -25}, {25, 25}, 1)} -- For testing simExtOMPL_setStateValidityCheckingResolution(taskHandle, 0.001) droneAppoxVol = simGetCollectionHandle('drone_approxVolume') droneObstacles = simGetCollectionHandle('drone_obstacles') simExtOMPL_setStateSpace(taskHandle, stateSpaceHandle) simExtOMPL_setAlgorithm(taskHandle, sim_ompl_algorithm_BiTRRT) simExtOMPL_setCollisionPairs(taskHandle, {droneAppoxVol, droneObstacles}) simExtOMPL_setVerboseLevel(taskHandle, 0) -- 0 to suppress any message end if (sim_call_type==sim_childscriptcall_initialization) then -- Make sure we have version 2.4.13 or above (the particles are not supported otherwise) v=simGetInt32Parameter(sim_intparam_program_version) if (v<20413) then simDisplayDialog('Warning','The propeller model is only fully supported from V-REP version 2.4.13 and above.&&nThis simulation will not run as expected!',sim_dlgstyle_ok,false,'',nil,{0.8,0,0,0,0,0}) end -- Detatch the manipulation sphere: targetObj=simGetObjectHandle('Quadricopter_target') simSetObjectParent(targetObj,-1,true) -- This control algo was quickly written and is dirty and not optimal. It just serves as a SIMPLE example d=simGetObjectHandle('Quadricopter_base') particlesAreVisible=simGetScriptSimulationParameter(sim_handle_self,'particlesAreVisible') simSetScriptSimulationParameter(sim_handle_tree,'particlesAreVisible',tostring(particlesAreVisible)) simulateParticles=simGetScriptSimulationParameter(sim_handle_self,'simulateParticles') simSetScriptSimulationParameter(sim_handle_tree,'simulateParticles',tostring(simulateParticles)) propellerScripts={-1,-1,-1,-1} for i=1,4,1 do propellerScripts[i]=simGetScriptHandle('Quadricopter_propeller_respondable'..i) end heli=simGetObjectAssociatedWithScript(sim_handle_self) particlesTargetVelocities={0,0,0,0} pParam=2 iParam=0 dParam=0 vParam=-2 cumul=0 lastE=0 pAlphaE=0 pBetaE=0 psp2=0 psp1=0 prevEuler=0 fakeShadow=simGetScriptSimulationParameter(sim_handle_self,'fakeShadow') if (fakeShadow) then shadowCont=simAddDrawingObject(sim_drawing_discpoints+sim_drawing_cyclic+sim_drawing_25percenttransparency+sim_drawing_50percenttransparency+sim_drawing_itemsizes,0.2,0,-1,1) end -- Tracking purpose local alpha = 45 local objectHeight = 0.8 droneHeight = simGetObjectPosition(heli, -1)[3] inspect = require('inspect') trackingRadius = (droneHeight - objectHeight) * math.tan(alpha*math.pi/180.0) lastTrackingTargetPos = nil trackingTargetHandle = -1 -- Compute path for the target itself droneSpeed = 1 -- 1m/50ms is 44.7387mph -- ********** Using OMPL createPlanningSpace() local dronePos = simGetObjectPosition(heli, -1) simExtOMPL_setStartState(taskHandle, {dronePos[1], dronePos[2]}) simExtOMPL_setGoalState(taskHandle, {dronePos[1]+math.random(), dronePos[2]+math.random()}) local r, path = simExtOMPL_compute(taskHandle, 0.01) -- r = 0 if not successful -- ********** Using OMPL -- -- ********** Using acceleration -- targetTargetDisThresh = 0.1 -- targetAcceleration = 0.1 -- totalTargetTargetDistance = 0 -- currentTargetTargetProgress = 0 -- targetV = {0, 0} -- targetDirection = {0, 0} -- -- ********** Using acceleration -- Handle multiple drones droneHandles = simGetObjectsInTree(simGetObjectHandle('drones#'), sim_handle_all, 3) obstacleHandles = simGetObjectsInTree(simGetObjectHandle('Obstacles#'), sim_handle_all, 3) heliSuffix = simGetNameSuffix(simGetObjectName(heli)) totalDrones = #droneHandles -- totalDrones = 0 -- local allObjHandles = simGetObjectsInTree(sim_handle_scene, sim_handle_all, 3) -- for i=1,#allObjHandles do -- -- print(simGetObjectName(allObjHandles[i])) -- if string.sub(simGetObjectName(allObjHandles[i]),1,12)=='Quadricopter' then -- totalDrones = totalDrones + 1 -- end -- end -- totalDrones = totalDrones-(heliSuffix+2) -- Detached targets are duplicated -- Prepare 2 floating views with the camera views: -- floorCam=simGetObjectHandle('Quadricopter_floorCamera') -- frontCam=simGetObjectHandle('Quadricopter_frontCamera') resolutionX = 640 resolutionY = 480 mapResolutionX = 213 mapResolutionY = 228 frontSensor=simGetObjectHandle('Quadricopter_frontVisionSensor') passiveDetectSensor=simGetObjectHandle('Quadricopter_passiveDetectVisionSensor') passiveMapSensor=simGetObjectHandle('Quadricopter_passiveMapVisionSensor') perspectiveAngle = 60*math.pi/180 -- perspectiveAngle = simGetObjectFloatParameter(frontSensor, 1004) local ratio=resolutionX/resolutionY if (ratio>1) then halfAngleX = perspectiveAngle/2 halfAngleY = math.atan(math.tan(perspectiveAngle/2)/ratio) else halfAngleX = math.atan(math.tan(perspectiveAngle/2)*ratio) halfAngleY = perspectiveAngle/2 end simSetObjectInt32Parameter(frontSensor, 1002, resolutionX) simSetObjectInt32Parameter(frontSensor, 1003, resolutionY) simSetObjectInt32Parameter(passiveDetectSensor, 1002, mapResolutionX) simSetObjectInt32Parameter(passiveDetectSensor, 1003, mapResolutionY) simSetObjectInt32Parameter(passiveMapSensor, 1002, mapResolutionX) simSetObjectInt32Parameter(passiveMapSensor, 1003, mapResolutionY) simSetObjectFloatParameter(frontSensor, 1004, perspectiveAngle) simSetObjectFloatParameter(passiveDetectSensor, 1004, perspectiveAngle) simSetObjectFloatParameter(passiveMapSensor, 1004, perspectiveAngle) local viewSizeX = 0.15 local viewSizeY = 0.2 frontView=simFloatingViewAdd(1-2.5*viewSizeX,1-0.5*viewSizeY-viewSizeY*(heliSuffix+1),viewSizeX,viewSizeY,15) detectView=simFloatingViewAdd(1-1.5*viewSizeX,1-0.5*viewSizeY-viewSizeY*(heliSuffix+1),viewSizeX,viewSizeY,15) mapView=simFloatingViewAdd(1-0.5*viewSizeX,1-0.5*viewSizeY-viewSizeY*(heliSuffix+1),viewSizeX,viewSizeY,15) simAdjustView(frontView,frontSensor,64) simAdjustView(detectView,passiveDetectSensor,64) simAdjustView(mapView,passiveMapSensor,64) -- Enable an image publisher and subscriber: publisher=simExtRosInterface_advertise('/image', 'sensor_msgs/Image') simExtRosInterface_publisherTreatUInt8ArrayAsString(publisher) -- treat uint8 arrays as strings (much faster, tables/arrays are kind of slow in Lua) detectSubscriber=simExtRosInterface_subscribe('/detection', 'sensor_msgs/Image', 'detectionMessage_callback', totalDrones) simExtRosInterface_subscriberTreatUInt8ArrayAsString(detectSubscriber) -- treat uint8 arrays as strings (much faster, tables/arrays are kind of slow in Lua) mapSubscriber=simExtRosInterface_subscribe('/map', 'sensor_msgs/Image', 'mapMessage_callback', totalDrones) simExtRosInterface_subscriberTreatUInt8ArrayAsString(mapSubscriber) end if (sim_call_type==sim_childscriptcall_cleanup) then simSetObjectParent(targetObj,heli,true) simRemoveDrawingObject(shadowCont) simFloatingViewRemove(frontView) simFloatingViewRemove(detectView) simFloatingViewRemove(mapView) -- Shut down publisher and subscriber. Not really needed from a simulation script (automatic shutdown) simExtRosInterface_shutdownPublisher(publisher) simExtRosInterface_shutdownSubscriber(detectSubscriber) simExtRosInterface_shutdownSubscriber(mapSubscriber) end function track() local currentPos = simGetObjectPosition(targetObj, -1) local targetPos = simGetObjectPosition(trackingTargetHandle, -1) -- local dis = computeDistance({currentPos[1], currentPos[2]}, {targetPos[1], targetPos[2]}) -- local pos = {(currentPos[1]-targetPos[1])*trackingRadius/dis+targetPos[1], (currentPos[2]-targetPos[2])*trackingRadius/dis+targetPos[2], droneHeight} -- local ori -- if targetPos[1]-currentPos[1] >= 0 then -- ori = {0, 0, math.atan((targetPos[2]-currentPos[2])/(targetPos[1]-currentPos[1]))} -- else -- ori = {0, 0, math.pi+math.atan((targetPos[2]-currentPos[2])/(targetPos[1]-currentPos[1]))} -- end local theta if currentPos[1]-targetPos[1] >= 0 then theta = math.atan((currentPos[2]-targetPos[2])/(currentPos[1]-targetPos[1])) else theta = math.pi+math.atan((currentPos[2]-targetPos[2])/(currentPos[1]-targetPos[1])) end local pos, ori local divideAngle = 24 for i = 0,divideAngle-1 do pos = {targetPos[1]+trackingRadius*math.cos(theta+i*2*math.pi/divideAngle), targetPos[2]+trackingRadius*math.sin(theta+i*2*math.pi/divideAngle), droneHeight} if checkPositionValid({pos[1], pos[2]}) then break -- local r, path = computePath({currentPos[1], currentPos[2]}, {pos[1], pos[2]}) -- if r~=0 then -- break -- end end end if pos then ori = computeRelativeOrientation(pos, targetPos) end return pos, ori end function detectionMessage_callback(msg) -- Apply the received image to the passive vision sensor that acts as an image container if tonumber(msg.header.frame_id) == heliSuffix then simSetVisionSensorCharImage(passiveDetectSensor,msg.data) end end function mapMessage_callback(msg) -- Apply the received image to the passive vision sensor that acts as an image container if tonumber(msg.header.frame_id) == heliSuffix then simSetVisionSensorCharImage(passiveMapSensor,msg.data) end end function publishImage() -- Publish the image of the active vision sensor: local heliSuffix = simGetNameSuffix(simGetObjectName(heli)) local data,w,h=simGetVisionSensorCharImage(frontSensor) local imageData={} imageData['header']={seq=0,stamp=simExtRosInterface_getTime(), frame_id=tostring(heliSuffix)} imageData['height']=h imageData['width']=w imageData['encoding']='rgb8' imageData['is_bigendian']=1 imageData['step']=w*3 imageData['data']=data simExtRosInterface_publish(publisher,imageData) end if (sim_call_type==sim_childscriptcall_sensing) then -- Handle vision sensors publishImage() end if (sim_call_type==sim_childscriptcall_actuation) then -- print('updateTarget begin', heliSuffix) updateTarget() -- print('updateTarget end', heliSuffix) -- Handle tracking if pathCalculated == 3 then if trackingTargetHandle ~= -1 then local trackingTargetPos = simGetObjectPosition(trackingTargetHandle, -1) if lastTrackingTargetPos == nil or computeDistance(trackingTargetPos, lastTrackingTargetPos) > 3 then lastTrackingTargetPos = trackingTargetPos local newTargetTargetPos, newTargetTargetOri = track() if newTargetTargetPos then -- print('handle tracking: setTargetTarget', inspect(newTargetTargetPos)) setTargetTarget(newTargetTargetPos, newTargetTargetOri) end end end end -- Move drone to target position if the current position is not valid -- print('Checking heli valid', pathCalculated) if pathCalculated == 0 then local heliPos = simGetObjectPosition(heli, -1) if not checkPositionValid({heliPos[1], heliPos[2]}) then -- print('Heli position not valid!', heliSuffix) local newTargetTargetPos, newTargetTargetOri = track() if newTargetTargetPos then -- setTargetTarget(newTargetTargetPos, newTargetTargetOri) pathCalculated = 3 simSetObjectPosition(targetObj, -1, newTargetTargetPos) simSetObjectOrientation(targetObj, -1, newTargetTargetOri) end -- simSetObjectPosition(targetObj, -1, targetTargetPosition) end end -- print('heli position checked') -- Testing target movement simSetObjectPosition(heli, -1, simGetObjectPosition(targetObj, -1)) simSetObjectOrientation(heli, -1, simGetObjectOrientation(targetObj, -1)) -- Original quadricopter control code s=simGetObjectSizeFactor(d) pos=simGetObjectPosition(d,-1) if (fakeShadow) then itemData={pos[1],pos[2],0.002,0,0,1,0.2*s} simAddDrawingObjectItem(shadowCont,itemData) end -- Vertical control: targetPos=simGetObjectPosition(targetObj,-1) pos=simGetObjectPosition(d,-1) l=simGetVelocity(heli) e=(targetPos[3]-pos[3]) cumul=cumul+e pv=pParam*e thrust=5.335+pv+iParam*cumul+dParam*(e-lastE)+l[3]*vParam lastE=e -- Horizontal control: sp=simGetObjectPosition(targetObj,d) m=simGetObjectMatrix(d,-1) vx={1,0,0} vx=simMultiplyVector(m,vx) vy={0,1,0} vy=simMultiplyVector(m,vy) alphaE=(vy[3]-m[12]) alphaCorr=0.25*alphaE+2.1*(alphaE-pAlphaE) betaE=(vx[3]-m[12]) betaCorr=-0.25*betaE-2.1*(betaE-pBetaE) pAlphaE=alphaE pBetaE=betaE alphaCorr=alphaCorr+sp[2]*0.005+1*(sp[2]-psp2) betaCorr=betaCorr-sp[1]*0.005-1*(sp[1]-psp1) psp2=sp[2] psp1=sp[1] -- Rotational control: euler=simGetObjectOrientation(d,targetObj) rotCorr=euler[3]*0.1+2*(euler[3]-prevEuler) prevEuler=euler[3] -- Decide of the motor velocities: particlesTargetVelocities[1]=thrust*(1-alphaCorr+betaCorr+rotCorr) particlesTargetVelocities[2]=thrust*(1-alphaCorr-betaCorr-rotCorr) particlesTargetVelocities[3]=thrust*(1+alphaCorr-betaCorr+rotCorr) particlesTargetVelocities[4]=thrust*(1+alphaCorr+betaCorr-rotCorr) -- Send the desired motor velocities to the 4 rotors: for i=1,4,1 do simSetScriptSimulationParameter(propellerScripts[i],'particleVelocity',particlesTargetVelocities[i]) end end
-------------------------------------------------------------------------- -- Moonshine - a Lua virtual machine. -- -- Email: moonshine@gamesys.co.uk -- http://moonshinejs.org -- -- Copyright (c) 2013-2015 Gamesys Limited. All rights reserved. -- -- 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. -- -- TABLE FUNCTIONS -- concat local a = {2, 4, "moo", 102} local b = table.concat ({}) local c = table.concat ({}, ':') local d = table.concat ({}, ', ', 3) --local e = table.concat ({}, ', ', 3, 4) local f = table.concat (a) local g = table.concat (a, '-') local h = table.concat (a, '..', 2) local i = table.concat (a, '+', 2, 3) assertTrue (b == '', 'table.concat() should return an empty string if passed an empty table [1]') assertTrue (c == '', 'table.concat() should return an empty string if passed an empty table [2]') assertTrue (d == '', 'table.concat() should return an empty string if passed an empty table [3]') --assertTrue (e == '', 'table.concat() should return an empty string if passed an empty table [4]') assertTrue (f == '24moo102', 'table.concat() should return all items in the table in argument 1 in a string with no spaces, when arguments 2 and 3 are absent') assertTrue (g == '2-4-moo-102', 'table.concat() should return return all items in the table in argument 1 in a string delimited by argument 2, when argument 3 is absent') assertTrue (h == '4..moo..102', 'table.concat() should return the items in the table in argument 1 from the nth index in a string delimited by argument 2, when n is the third argument') assertTrue (i == '4+moo', 'table.concat() should return the items in the table in argument 1 from the nth index to the mth index in a string delimited by argument 2, when n is the third argument and m is the forth argument') -- getn do local a = {'a', 'b', 'c'} local b = {'a', 'b', 'c', nil} local c = {'a', nil, 'b', 'c'} local d = {'a', nil, 'b', 'c', nil} local e = {'a', 'b', 'c', moo = 123 } local f = { moo = 123 } local g = {} assertTrue (table.getn (a) == 3, 'table.getn() should return the size of the array part of a table') assertTrue (table.getn (b) == 3, 'table.getn() should ignore nils at the end of the array part of a table') assertTrue (table.getn (c) == 4, 'table.getn() should include nils in the middle of the array part of a table') assertTrue (table.getn (d) == 1, 'table.getn() should return the same random value as C implementation when the last item is nil') assertTrue (table.getn (e) == 3, 'table.getn() should ignore the hash part of a table') assertTrue (table.getn (f) == 0, 'table.getn() should return zero when the array part of a table is empty') assertTrue (table.getn (g) == 0, 'table.getn() should return zero when the table is empty') end -- insert local b = {} local w = table.insert (b, 'Lewis') local c = {} local x = table.insert (c, 3, 'Jenson') local d = {'We', 'exist', 'to'} local y = table.insert (d, 'win') local e = {1, 1998, 1, 1999} local z = table.insert (e, 3, 'Mika') local f = {'Kimi'} local z2 = table.insert (f, 4, 2) assertTrue (b[1] == 'Lewis', 'table.insert() should add argument 2 to the end of the table in argument 1, when the third argument is absent [1]') assertTrue (b[2] == nil, 'table.insert() should only add argument 2 to the end of the table in argument 1, when the third argument is absent [2]') assertTrue (c[1] == nil, 'table.insert() should pad the table with nils when the desired index is greater than the length of the table [1]') assertTrue (c[2] == nil, 'table.insert() should pad the table with nils when the desired index is greater than the length of the table [2]') assertTrue (c[3] == 'Jenson', 'table.insert() should add argument 2 to the end of the table in argument 1, when the third argument is greater than the length of the table [1]') assertTrue (c[4] == nil, 'table.insert() should only add argument 2 to the end of the table in argument 1, when the third argument is greater than the length of the table [2]') assertTrue (d[1] == 'We', 'table.insert() should not affect existing items in the table when the third argument is missing [1]') assertTrue (d[2] == 'exist', 'table.insert() should not affect existing items in the table when the third argument is missing [2]') assertTrue (d[3] == 'to', 'table.insert() should not affect existing items in the table when the third argument is missing [3]') assertTrue (d[4] == 'win', 'table.insert() should add argument 2 to the end of the table in argument 1, when the third argument is missing [1]') assertTrue (d[5] == nil, 'table.insert() should only add argument 2 to the end of the table in argument 1, when the third argument is missing [2]') assertTrue (e[1] == 1, 'table.insert() should not affect existing items in the table at indices less than that specified in the third argument [1]') assertTrue (e[2] == 1998, 'table.insert() should not affect existing items in the table at indices less than that specified in the third argument [2]') assertTrue (e[3] == 'Mika', 'table.insert() should add argument 3 into the table in argument 1 at the index specified in argument 2') assertTrue (e[4] == 1, 'table.insert() should shift items in the table in argument 1 down by one after and including the index at argument 2 [1]') assertTrue (e[5] == 1999, 'table.insert() should shift items in the table in argument 1 down by one after and including the index at argument 2 [2]') assertTrue (e[6] == nil, 'table.insert() should only add one index to the table in argument 1 [1]') assertTrue (f[1] == 'Kimi', 'table.insert() should not affect existing items in the table at indices less than that specified in the third argument [3]') assertTrue (f[2] == nil, 'table.insert() should pad the table with nils when the desired index is greater than the length of the table [3]') assertTrue (f[3] == nil, 'table.insert() should pad the table with nils when the desired index is greater than the length of the table [4]') assertTrue (f[4] == 2, 'table.insert() should not affect existing items in the table at indices less than that specified in the third argument [2]') assertTrue (f[5] == nil, 'table.insert() should only add one index to the table in argument 1 [2]') assertTrue (w == nil, 'table.insert() should update list in place and return nil') assertTrue (x == nil, 'table.insert() should update list in place and return nil') assertTrue (y == nil, 'table.insert() should update list in place and return nil') assertTrue (z == nil, 'table.insert() should update list in place and return nil') assertTrue (z2 == nil, 'table.insert() should update list in place and return nil') local function insertStringKey () table.insert({}, 'string key', 1) end a, b = pcall(insertStringKey) assertTrue (a == false, 'table.insert() should error when passed a string key') local function insertStringKey () table.insert({}, '23', 1) end a, b = pcall(insertStringKey) assertTrue (a, 'table.insert() should not error when passed a string key that can be coerced to a number [1]') local function insertStringKey () table.insert({}, '1.23e33', 1) end a, b = pcall(insertStringKey) assertTrue (a, 'table.insert() should not error when passed a string key that can be coerced to a number [2]') local function insertStringKey () table.insert({}, '-23', 1) end a, b = pcall(insertStringKey) assertTrue (a, 'table.insert() should not error when passed a string key that can be coerced to a negative number') -- maxn local a = table.maxn ({}) local b = table.maxn ({1, 2, 4, 8}) local c = table.maxn ({nil, nil, 123}) local d = {} table.insert (d, 3, 'Moo') local e = table.maxn (d) assertTrue (a == 0, 'table.maxn() should return zero when passed an empty table') assertTrue (b == 4, 'table.maxn() should return the highest index in the passed table [1]') assertTrue (c == 3, 'table.maxn() should return the highest index in the passed table [2]') assertTrue (e == 3, 'table.maxn() should return the highest index in the passed table [3]') assertTrue (#d == 0, 'Length operator should return the first empty index minus one [1]') -- remove local a = {14, 2, "Hello", 298} local b = table.remove (a) local c = {14, 2, "Hello", 298} local d = table.remove (c, 3) local e = {14, 2} local f = table.remove (e, 6) local g = table.remove ({}, 1) assertTrue (a[1] == 14, 'table.remove() should not affect items before the removed index [1]') assertTrue (a[2] == 2, 'table.remove() should not affect items before the removed index [2]') assertTrue (a[3] == "Hello", 'table.remove() should not affect items before the removed index [3]') assertTrue (a[4] == nil, 'table.remove() should remove the last item in the table when second argument is absent') assertTrue (b == 298, 'table.remove() should return the removed item [1]') assertTrue (c[1] == 14, 'table.remove() should not affect items before the removed index [3]') assertTrue (c[2] == 2, 'table.remove() should not affect items before the removed index [4]') assertTrue (c[3] == 298, 'table.remove() should remove the item at the index specified by the second argument and shift subsequent item down') assertTrue (c[4] == nil, 'table.remove() should decrease the length of the table by one') assertTrue (d == 'Hello', 'table.remove() should return the removed item [2]') assertTrue (e[1] == 14, 'table.remove() should not affect items before the removed index [5]') assertTrue (e[2] == 2, 'table.remove() should not affect items before the removed index [6]') assertTrue (e[3] == nil, 'table.remove() should not affect the table if the given index is past the length of the table') assertTrue (f == nil, 'table.remove() should return nil if the given index is past the length of the table [1]') assertTrue (g == nil, 'table.remove() should return nil if the given index is past the length of the table [2]') c = {nil, nil, 123} assertTrue (#c == 3, 'Length operator should return the first empty index minus one [2]') table.remove (c, 1) assertTrue (#c == 0, 'Length operator should return the first empty index minus one [3]') assertTrue (c[1] == nil, 'table.remove() should shift values down if index <= initial length [1]') assertTrue (c[2] == 123, 'table.remove() should shift values down if index <= initial length [2]') assertTrue (c[3] == nil, 'table.remove() should shift values down if index <= initial length [3]') table.remove (c, 1) assertTrue (#c == 0, 'Length operator should return the first empty index minus one [4]') assertTrue (c[1] == nil, 'table.remove() should not affect the array if index > initial length [1]') assertTrue (c[2] == 123, 'table.remove() should not affect the array if index > initial length [2]') assertTrue (c[3] == nil, 'table.remove() should not affect the array if index > initial length [3]') table.remove (c, 2) assertTrue (#c == 0, 'Length operator should return the first empty index minus one [5]') assertTrue (c[1] == nil, 'table.remove() should not affect the array if index > initial length [4]') assertTrue (c[2] == 123, 'table.remove() should not affect the array if index > initial length [5]') assertTrue (c[3] == nil, 'table.remove() should not affect the array if index > initial length [6]') -- sort local a = { 1, 2, 3, 6, 5, 4, 20 } table.sort (a) assertTrue (a[1] == 1, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [1]') assertTrue (a[2] == 2, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [2]') assertTrue (a[3] == 3, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [3]') assertTrue (a[4] == 4, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [4]') assertTrue (a[5] == 5, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [5]') assertTrue (a[6] == 6, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [6]') assertTrue (a[7] == 20, 'table.sort() should sort elements into alphnumeric order, when not passed a sort function [7]') assertTrue (a[8] == nil, 'table.sort() should not affect the table if the given index is past the length of the table') local a = { 1, 2, 3, 6, 5, 4, 20 } table.sort (a, function (a, b) return b < a end) assertTrue (a[1] == 20, 'table.sort() should sort elements into order defined by sort function [1]') assertTrue (a[2] == 6, 'table.sort() should sort elements into order defined by sort function [2]') assertTrue (a[3] == 5, 'table.sort() should sort elements into order defined by sort function [3]') assertTrue (a[4] == 4, 'table.sort() should sort elements into order defined by sort function [4]') assertTrue (a[5] == 3, 'table.sort() should sort elements into order defined by sort function [5]') assertTrue (a[6] == 2, 'table.sort() should sort elements into order defined by sort function [6]') assertTrue (a[7] == 1, 'table.sort() should sort elements into order defined by sort function [7]') assertTrue (a[8] == nil, 'table.sort() should not affect the table if the given index is past the length of the table')