content
stringlengths
5
1.05M
PLUGIN.name = "Player Spawn Points" PLUGIN.author = "STEAM_0:1:29606990" PLUGIN.description = "" local PLUGIN = PLUGIN PLUGIN.spawners = PLUGIN.spawners or {} ix.util.Include("sv_plugin.lua", "server") if (CLIENT) then net.Receive("ixPlayerSpawnerSync", function() for _, v in ipairs(PLUGIN.spawners) do if (IsValid(v.drawModel)) then v.drawModel:Remove() end end PLUGIN.spawners = net.ReadTable() for _, v in ipairs(PLUGIN.spawners) do local model = ClientsideModel(LocalPlayer():GetModel()) model:SetNoDraw(true) model:SetMaterial("models/wireframe") v.drawModel = model end hook.Add("PostDrawTranslucentRenderables", PLUGIN.name, function() local wep = LocalPlayer():GetActiveWeapon() if (IsValid(wep) and wep:GetClass() == 'gmod_tool' and GetConVarString("gmod_toolmode") == "player_spawn_points_tool") then for _, v in ipairs(PLUGIN.spawners) do if (IsValid(v.drawModel) and v.position) then v.drawModel:SetPos(v.position) if (v.angles) then v.drawModel:SetAngles(v.angles) end v.drawModel:SetupBones() v.drawModel:DrawModel() end end else for _, v in ipairs(PLUGIN.spawners) do if (IsValid(v.drawModel)) then v.drawModel:SetNoDraw(true) end end end end) end) local owner, w, h, ft, clmp clmp = math.Clamp local aprg, aprg2 = 0, 0 function ix.hud.DrawDeath() end hook.Add("PreDrawHUD", "ix.hud.DrawDeath", function() cam.Start2D() owner = LocalPlayer() ft = FrameTime() w, h = ScrW(), ScrH() if (owner:GetCharacter()) then if (owner:Alive()) then if (aprg != 0) then aprg2 = clmp(aprg2 - ft*1.3, 0, 1) if (aprg2 == 0) then aprg = clmp(aprg - ft*.7, 0, 1) end end else if (aprg2 != 1) then aprg = clmp(aprg + ft*.5, 0, 1) if (aprg == 1) then aprg2 = clmp(aprg2 + ft*.4, 0, 1) end end end end if (IsValid(ix.gui.characterMenu) and ix.gui.characterMenu:IsVisible() or !owner:GetCharacter()) then return end surface.SetDrawColor(0, 0, 0, math.ceil((aprg^.5) * 200)) surface.DrawRect(-1, -1, w+2, h+2) ix.util.DrawText( string.utf8upper(L"youreDead"), w/2, h/2, ColorAlpha(color_white, aprg2 * 255), 1, 1, "ixMenuButtonHugeFont", aprg2 * 255 ) cam.End2D() end) hook.Add( "HUDShouldDraw", "Hide_CHudDamageIndicator", function( name ) if (name == "CHudDamageIndicator" and LocalPlayer():Health() <= 0) then return false end end) local function DeathTimer() local client = LocalPlayer and LocalPlayer() or nil if (!client) then return end if (client.GetCharacter and client:GetCharacter()) then if (client:Alive()) then if (IsValid(ix.gui.death_menu)) then LocalPlayer().deathTime = nil ix.gui.death_menu:SetMouseInputEnabled(false) ix.gui.death_menu:Remove() end else if (!IsValid(ix.gui.death_menu)) then client.deathTime = client.deathTime or RealTime() + ix.config.Get("spawnTime", 5) ix.gui.death_menu = vgui.Create("ixDeathScreenMenu") ix.gui.death_menu:SetMouseInputEnabled(true) hook.Run("LocalPlayerDeath") end end end end timer.Create("ixDeathScreenMenu", 0.25, 0, DeathTimer) gameevent.Listen("entity_killed") hook.Add("entity_killed", "ixDeathScreenMenu", function(data) local victim = data.entindex_killed if (victim and victim == LocalPlayer():EntIndex()) then DeathTimer() end end) end
--[[ FiveM Scripts Copyright C 2018 Sighmir This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or at your option any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] cfg = {} cfg.blips = true -- enable blips cfg.seconds = 120 -- seconds to rob cfg.cooldown = 300 -- time between robbaries cfg.cops = 2 -- minimum cops online cfg.permission = "holdup.police" -- permission given to cops cfg.holdups = { -- list of stores ["paleto_twentyfourseven"] = { position = { ['x'] = 1734.48046875, ['y'] = 6420.38134765625, ['z'] = 34.5372314453125 }, -- 1734.48046875, 6420.38134765625, 34.5372314453125 reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Paleto Bay)", lastrobbed = 0 -- this is always 0 }, ["sandyshores_twentyfoursever"] = { position = { ['x'] = 1960.7580566406, ['y'] = 3749.26367187, ['z'] = 31.3437423706055 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Sandy Shores)", lastrobbed = 0 }, ["bar_one"] = { position = { ['x'] = 1986.1240234375, ['y'] = 3053.8747558594, ['z'] = 47.215171813965 }, reward = 100 + math.random(10000,20000), nameofstore = "Yellow Jack. (Sandy Shores)", lastrobbed = 0 }, ["littleseoul_twentyfourseven"] = { position = { ['x'] = -709.17022705078, ['y'] = -904.21722412109, ['z'] = 19.215591430664 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Little Seoul)", lastrobbed = 0 }, ["southlossantos_gasstop"] = { position = { ['x'] = 28.7538948059082, ['y'] = -1339.8212890625, ['z'] = 29.4970436096191 }, reward = 100 + math.random(10000,20000), nameofstore = "Limited LTD Gas Stop. (South Los Santos)", lastrobbed = 0 }, ["southlossantos_twentyfourseven"] = { position = { ['x'] = -43.1531448364258, ['y'] = -1748.75244140625, ['z'] = 29.4209976196289 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (South Los Santos)", lastrobbed = 0 }, ["vinewood_twentyfourseven"] = { position = { ['x'] = 378.030487060547, ['y'] = 332.944427490234, ['z'] = 103.566375732422 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Vinewood)", lastrobbed = 0 }, ["eastlossantos_robsliquor"] = { position = { ['x'] = 1126.68029785156, ['y'] = -980.39501953125, ['z'] = 45.4157257080078 }, reward = 100 + math.random(10000,20000), nameofstore = "Rob's Liquor. (East Los Santos)", lastrobbed = 0 }, ["sandyshores_twentyfourseven"] = { position = { ['x'] = 2673.32006835938, ['y'] = 3286.4150390625, ['z'] = 55.241138458252 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Sandy Shores)", lastrobbed = 0 }, ["grapeseed_gasstop"] = { position = { ['x'] = 1707.52648925781, ['y'] = 4920.05126953125, ['z'] = 42.0636787414551 }, reward = 100 + math.random(10000,20000), nameofstore = "Limited LTD Gas Stop. (Grapeseed)", lastrobbed = 0 }, ["morningwood_robsliquor"] = { position = { ['x'] = -1479.22424316406, ['y'] = -375.097686767578, ['z'] = 39.1632804870605 }, reward = 100 + math.random(10000,20000), nameofstore = "Rob's Liquor. (Morning Wood)", lastrobbed = 0 }, ["chumash_robsliquor"] = { position = { ['x'] = -2959.37524414063, ['y'] = 387.556365966797, ['z'] = 14.043158531189 }, reward = 100 + math.random(10000,20000), nameofstore = "Rob's Liquor. (Chumash)", lastrobbed = 0 }, ["delperro_robsliquor"] = { position = { ['x'] = -1220.14123535156, ['y'] = -915.712158203125, ['z'] = 11.3261671066284 }, reward = 100 + math.random(10000,20000), nameofstore = "Rob's Liquor. (Del Perro)", lastrobbed = 0 }, ["eastlossantos_gasstop"] = { position = { ['x'] = 1160.06237792969, ['y'] = -314.061828613281, ['z'] = 69.2050628662109 }, reward = 100 + math.random(10000,20000), nameofstore = "Limited LTD Gas Stop. (East Los Santos)", lastrobbed = 0 }, ["tongva_gasstop"] = { position = { ['x'] = -1829.00427246094, ['y'] = 798.903076171875, ['z'] = 138.186706542969 }, reward = 100 + math.random(10000,20000), nameofstore = "Limited LTD Gas Stop. (Tongva Valley)", lastrobbed = 0 }, ["tataviam_twentyfourseven"] = { position = { ['x'] = 2549.400390625, ['y'] = 385.048309326172, ['z'] = 108.622955322266 }, reward = 100 + math.random(10000,20000), nameofstore = "Twenty Four Seven. (Tataviam Mountains)", lastrobbed = 0 }, ["rockford_jewlery"] = { position = { ['x'] = -621.989135742188, ['y'] = -230.804443359375, ['z'] = 38.0570297241211 }, reward = 10000 + math.random(500,10000), nameofstore = " Vangelico Jewelry Store. (Rockford Hills)", lastrobbed = 0 } }
widget = { plugin = 'pulse', cb = function(t) if t.mute then return 'V X' end local percent = (t.cur / t.norm) * 100 return string.format('V %d', math.floor(0.5 + percent)) end, }
local ps_common = require("lj2ps.ps_common") local Matrix = require("lj2ps.ps_matrix") local GraphicState = require("lj2ps.ps_graphicsstate") local exports = {} -- Graphics State - Device Independent -- gsave -- grestore local function gsave(vm) vm.Driver:gSave() return true end exports.gsave = gsave local function grestore(vm) vm.Driver:gRestore() return true end exports.grestore = grestore -- grestoreall -- initgraphics -- gstate local function gstate(vm) local gs = GraphicState(); vm.OperandStack:push(gs) return true end exports.gstate = gstate -- setgstate -- currentgstate -- setlinewidth -- currentlinewidth local function setlinewidth(vm) local value = vm.OperandStack:pop() --print("setlinewidth: ", value) vm.Driver:setLineWidth(value) return true end exports.setlinewidth = setlinewidth -- setlinecap local function setlinecap(vm) local value = vm.OperandStack:pop() vm.Driver:setLineCap(value) return true end exports.setlinecap = setlinecap -- currentlinecap local function currentlinecap(vm) local value = vm.Driver:getLineCap() vm.OperandStack:push(value) return true end exports.currentlinecap = currentlinecap -- setlinejoin -- currentlinejoin local function setlinejoin(vm) local value = vm.OperandStack:pop() vm.Driver:setLineJoin(value) return true end exports.setlinejoin = setlinejoin -- setmiterlimit -- currentmiterlimit local function setmiterlimit(vm) local num = vm.OperandStack:pop() -- set the miter limit return true end exports.setmiterlimit = setmiterlimit -- setstrokeadjust -- currentstrokeadjust -- setdash -- currentdash local function setdash(vm) local offset = vm.OperandStack:pop() local arr = vm.OperandStack:pop() vm.Driver.CurrentState.Dash = {offset=offset, array=arr} return true end exports.setdash = setdash local function currentdash(vm) local dsh = vm.Driver.CurrentState.Dash vm.OperandStack:push(dsh.array) vm.OperandStack:push(dsh.offset) return true end exports.currentdash = currentdash -- setcolorspace -- currentcolorspace -- setcolor -- currentcolor -- setgray -- currentgray local function setgray(vm) local value = vm.OperandStack:pop() vm.Driver:setGraya(value) return true end exports.setgray = setgray local function setgraya(vm) local a = vm.OperandStack:pop() local value = vm.OperandStack:pop() vm.Driver:setGraya(value, a) return true end exports.setgraya = setgraya -- sethsbcolor -- currenthsbcolor -- hue saturation brightness sethsbcolor -- --[[ HSVtoRGB h,s,v ==> [0..1] https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion --]] local function round(n) if n >= 0 then return math.floor(n+0.5) else return math.ceil(n-0.5) end end local function map255(val) return math.min(math.floor(val*256),255) end -- mapToRange -- take a val [0..1], and map it to [0..range] -- local function mapToRange(val, range) return math.min(math.floor(val*(range+1)),range) end --[[ https://en.wikipedia.org/wiki/HSL_and_HSV 'alternate' polynomial based implementation ]] local function HSLToRGB(H,S,L) -- we want H in degrees H = mapToRange(H,360.0) local function fn(n) local k = math.fmod((n + H/30.0), 12) local a = S * math.min(L, 1.0 - L) return L - a * math.max(math.min(k-3.0, 9.0-k,1.0),-1.0) end local R1, G1, B1 = fn(0), fn(8), fn(4) --print("HSL, RGB: ", H, S, L, " ", R, G, B) return R1, G1, B1 end --[[ h,s,v => [0..1] h - hue, is converted to degrees [0..360] https://en.wikipedia.org/wiki/HSL_and_HSV ]] local function HSVToRGB(H,S,V) -- we want H in degrees H = mapToRange(H,360.0) -- figure out the chroma local C = V * S -- figure out RGB local H1 = H / 60.0 local X = C * (1-math.abs(math.fmod(H1, 2)-1)) local R1, G1, B1 if H1 >= 0 and H1 <= 1 then R1,G1,B1 = C, X, 0 end if H1 > 1 and H1 <= 2 then R1, G1, B1 = X, C, 0 end if H1 > 2 and H1 <= 3 then R1, G1, B1 = 0, C, X end if H1 > 3 and H1 <= 4 then R1, G1, B1 = 0, X, C end if H1 > 4 and H1 <= 5 then R1, G1, B1 = X, 0, C end if H1 > 5 and H1 <= 6 then R1, G1, B1 = C, 0, X end local m = V - C local R = R1 + m local G = G1 + m local B = B1 + m --print("HSV, RGB: ", H, S, V, " ", R, G, B) return R, G, B end local function sethsbcolor(vm) local brightness = vm.OperandStack:pop() local saturation = vm.OperandStack:pop() local hue = vm.OperandStack:pop() -- create an rgb color from the hsb values local r, g, b = HSVToRGB(hue, saturation, brightness) --local r, g, b = HSLToRGB(hue, saturation, brightness) --print("sethsbcolor: ", hue, saturation, brightness, r, g, b) vm.Driver:setRgbaColor(r,g,b,1.0) return true end exports.sethsbcolor = sethsbcolor -- setrgbcolor -- currentrgbcolor local function setrgbcolor(vm) local b = vm.OperandStack:pop() local g = vm.OperandStack:pop() local r = vm.OperandStack:pop() vm.Driver:setRgbaColor(r,g,b,1.0) return true end exports.setrgbcolor = setrgbcolor local function setrgbacolor(vm) local a = vm.OperandStack:pop() local b = vm.OperandStack:pop() local g = vm.OperandStack:pop() local r = vm.OperandStack:pop() vm.Driver:setRgbaColor(r,g,b, a) return true end exports.setrgbacolor = setrgbacolor -- setcmykcolor -- currentcmykcolor -- cyan magenta yellow black setcmykcolor - local function setcmykcolor(vm) local black = vm.OperandStack:pop() local yellow = vm.OperandStack:pop() local magenta = vm.OperandStack:pop() local cyan = vm.OperandStack:pop() local r = (1-cyan) * (1-black) local g = (1-magenta) * (1-black) local b = (1-yellow) * (1-black) vm.Driver:setRgbaColor(r,g,b,1.0) return true end exports.setcmykcolor = setcmykcolor --[[ -- Graphics State - Device Dependent --]] --sethalftone --currenthalftone --setscreen -- frequency angle proc setscreen – local function setscreen(vm) local proc = vm.OperandStack:pop() local angle = vm.OperandStack:pop() local frequency = vm.OperandStack:pop() -- do some stuff with setscreen end exports.setscreen = setscreen --currentscreen --setcolorscreen --currentcolorscreen --settransfer --currenttransfer --setcolortransfer --currentcolortransfer --setblackgeneration --currentblackgeneration --setundercolorremoval --currentundercolorremoval --setcolorrendering --currentcolorrendering --setflat --currentflat local function setflat(vm) local num = vm.OperandStack:pop() vm.Driver.CurrentState.Flat = num return true end exports.setflat = setflat local function currentflat(vm) local num = vm.Driver.CurrentState.Flat; vm.OperandStack:push(num) return true end exports.currentflat = currentflat --setoverprint --currentoverprint -- Coordinate System and Matrix Operators --matrix -- by default, create identity matrix and push -- it on the operand stack local function matrix(vm) local m = Matrix:createIdentity() vm.OperandStack:push(m) return true end exports.matrix = matrix --initmatrix -- - initmatrix - local function initmatrix(vm) return false end exports.initmatrix = initmatrix --identmatix -- take whatever thing that's on the top -- of the stack and give it identity matrix values local function identmatrix(vm) local m = vm.OperandStack:pop() m[0]=1 m[1]=0 m[2]=0 m[3]=1 m[4]=0 m[5]=0 vm.OperandStack:push(m) return true end exports.identmatrix =identmatrix --defaultmatrix --matrix currentmatrix matrix local function currentmatrix(vm) local m = vm.OperandStack:pop() local m1 = vm.Driver:currentMatrix() vm.OperandStack:push(m1) return true end exports.currentmatrix = currentmatrix --setmatrix local function setmatrix(vm) local m = vm.OperandStack:pop() vm.Driver:setMatrix(m) return true end exports.setmatrix = setmatrix -- translate -- tx ty translate - -- tx ty matrix translate matrix -- local function translate(vm) local tx, ty local m = vm.OperandStack:pop() if type(m) == "number" then -- change user coordinate space local ty = m local tx = vm.OperandStack:pop() vm.Driver:translate(tx, ty) else -- create a translation matrix and -- put it back on the stack local ty = vm.OperandStack:pop() local tx = vm.OperandStack:pop() local m1 = Matrix:createTranslation(tx, ty) vm.OperandStack:push(m1) end return true end exports.translate = translate --scale -- sx sy scale - -- sx sy matrix scale matrix local function scale(vm) local m = vm.OperandStack:pop() if type(m) == "number" then local sy = m local sx = vm.OperandStack:pop() vm.Driver:scale(sx, sy) else local sy = vm.OperandStack:pop() local sx = vm.OperandStack:pop() local m1 = Matrix:createScaling(sx, sy) vm.OperandStack:push(m1) end return true end exports.scale = scale --rotate -- angle rotate - -- angle matrix rotate matrix local function rotate(vm) local m = vm.OperandStack:pop() if type(m) == "number" then local angle = m vm.Driver:rotateBy(angle) else local angle = vm.OperandStack:pop() local m1 = Matrix:createRotation(angle) vm.OperandStack:push(m1) end return true end exports.rotate = rotate -- concat -- matrix concat local function concat(vm) local m = vm.OperandStack:pop() --print("concat: ", m) m = Matrix:createFromArray(m) assert(m ~= nil) vm.Driver:concat(m) return true end exports.concat = concat --concatmatrix -- matrix1 matrix2 matrix3 concatmatrix matrix3 local function concatmatrix(vm) local m3 = Matrix:createFromArray(vm.OperandStack:pop()) local m2 = Matrix:createFromArray(vm.OperandStack:pop()) local m1 = Matrix:createFromArray(vm.OperandStack:pop()) m3 = m1; m3:preMultiplyBy(m2); vm.OperandStack:push(m3) return true end exports.concatmatrix = concatmatrix --transform -- transform a single point -- x y transform x1 y1 -- x y matrix transform x1 y1 local function transform(vm) local m = vm.OperandStack:pop() local x, y if type(m) == "number" then local y = m local x = vm.OperandStack:pop() local m1 = vm.Driver:currentMatrix(); local x1, y1 = m1:transformPoint(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) else -- the matrix was given as a parameter -- get the inverse of it m = Matrix:createFromArray(m) local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() local x1, y1 = m:transformPoint(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) end return true end exports.transform = transform --dtransform local function dtransform(vm) local m = vm.OperandStack:pop() local x, y if type(m) == "number" then local y = m local x = vm.OperandStack:pop() local m1 = vm.Driver:currentMatrix(); local x1, y1 = m1:dtransform(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) else -- the matrix was given as a parameter -- get the inverse of it m = Matrix:createFromArray(m) local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() local x1, y1 = m:dtransform(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) end return true end exports.dtransform = dtransform --itransform local function itransform(vm) local arg1 = vm.OperandStack:pop() local x, y if type(arg1) == "number" then local y = arg1 local x = vm.OperandStack:pop() local m = vm.Driver:currentMatrix(); local m1 = m:createInverse(); local x1, y1 = m1:transformPoint(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) else -- the matrix was given as a parameter -- get the inverse of it local m1 = Matrix:createFromArray(arg1) m1 = m1:createInverse(); assert(m1 ~= nil) local y = vm.OperandStack:pop() local x = xm.OperandStack:pop() local x1, y1 = m1:transformPoint(x, y) vm.OperandStack:push(x1) vm.OperandStack:push(y1) end return true end exports.itransform = itransform --idtransform --invertmatrix -- matrix1 matrix2 invertmatrix matrix2 local function invertmatrix(vm) local m2 = vm.OperandStack:pop() local m1 = vm.OperandStack:pop() -- make sure we have an actual matrix -- and not just an array local matrix1 = Matrix:createFromArray(m1) --print("invertmatrix - matrix1") --print(matrix1) local m1inv = matrix1:createInverse() assert(m1inv ~= nil) vm.OperandStack:push(m1inv) return true end exports.invertmatrix = invertmatrix --[[ -- Path construction --]] --newpath local function newpath(vm) vm.Driver:newPath() return true end exports.newpath = newpath --currentpoint local function currentpoint(vm) -- get Position from current GraphState -- push x, y onto operand stack local pos = vm.Driver:getCurrentPosition() if not pos then error("currentpoint; is not currently defined") end vm.OperandStack:push(pos[1]) vm.OperandStack:push(pos[2]) return true end exports.currentpoint = currentpoint --moveto local function moveto(vm) local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() vm.Driver:moveTo(x, y) return true end exports.moveto = moveto --rmoveto local function rmoveto(vm) local dy = vm.OperandStack:pop() local dx = vm.OperandStack:pop() local curr = vm.Driver:getCurrentPosition() vm.Driver:moveTo(curr[1]+dx, curr[2]+dy) return true end exports.rmoveto = rmoveto --lineto local function lineto(vm) local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() --print("OP:lineto: ", x, y) vm.Driver:lineTo(x, y) return true end exports.lineto = lineto --rlineto local function rlineto(vm) local dy = vm.OperandStack:pop() local dx = vm.OperandStack:pop() local curr = vm.Driver:getCurrentPosition() vm.Driver:lineTo(curr[1]+dx, curr[2]+dy) return true end exports.rlineto = rlineto --arc local function arc(vm) local angle2 = vm.OperandStack:pop() local angle1 = vm.OperandStack:pop() local r = vm.OperandStack:pop() local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() vm.Driver:arc(x, y, r, angle1, angle2) return true end exports.arc = arc --arcn local function arcn(vm) local angle2 = vm.OperandStack:pop() local angle1 = vm.OperandStack:pop() local r = vm.OperandStack:pop() local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() local rangle1 = 360 - angle1 local rangle2 = 360 - angle2 vm.Driver:arc(x, y, r, rangle1, rangle2) return true end exports.arcn = arcn --arct local function arct(vm) local r = vm.OperandStack:pop() local y2 = vm.OperandStack:pop() local x2 = vm.OperandStack:pop() local y1 = vm.OperandStack:pop() local x1 = vm.OperandStack:pop() vm.Driver:arct(x1, y1, x2,y2, r) return true end exports.arct = arct --arcto --curveto --rcurveto local function curveto(vm) local y3 = vm.OperandStack:pop() local x3 = vm.OperandStack:pop() local y2 = vm.OperandStack:pop() local x2 = vm.OperandStack:pop() local y1 = vm.OperandStack:pop() local x1 = vm.OperandStack:pop() vm.Driver:curveTo(x1, y1, x2, y2, x3, y3) return true end exports.curveto = curveto local function rcurveto(vm) local dy3 = vm.OperandStack:pop() local dx3 = vm.OperandStack:pop() local dy2 = vm.OperandStack:pop() local dx2 = vm.OperandStack:pop() local dy1 = vm.OperandStack:pop() local dx1 = vm.OperandStack:pop() local curr = vm.Driver:getCurrentPosition() local x = curr[1] local y = curr[2] vm.Driver:curveTo(x+dx1, y+dy1, x+dx2, y+dy2, x+dx3, y+dy3) return true end exports.rcurveto = rcurveto local function closepath(vm) vm.Driver:closePath() end exports.closepath = closepath --flattenpath local function flattenpath(vm) return true end exports.flattenpath = flattenpath --reversepath --strokepath --ustrokepath --charpath -- string bool charpath - local function charpath(vm) local abool = vm.OperandStack:pop() local str = vm.OperandStack:pop() -- use current font to get outline of string vm.Driver:charPath(str) return true end exports.charpath = charpath --uappend --clippath local function clippath(vm) local cpath = vm.Driver:clipPath() vm.Driver:setPath(cpath) return true end exports.clippath = clippath --setbbox local function setbbox(vm) -- setclip based on specified -- rectangular bounds local ury = vm.OperandStack:pop() local urx = vm.OperandStack:pop() local lly = vm.OperandStack:pop() local llx = vm.OperandStack:pop() local w = urx-llx local h = ury-lly vm.Driver.DC:clipRectI(BLRectI(llx,lly,urx-llx, ury-lly)) return true end exports.setbbox = setbbox --pathbbox -- pathbbox llx lly urx ury local function pathbbox(vm) local x1,y1,x2,y2 = vm.Driver:pathBox() vm.OperandStack:push(x1) vm.OperandStack:push(y1) vm.OperandStack:push(x2) vm.OperandStack:push(y2) return true end exports.pathbbox = pathbbox --pathforall --upath --initclip local function initclip(vm) --print("INITCLIP") return true end exports.initclip = initclip --clip local function clip(vm) return true end exports.clip = clip --eoclip --rectclip --ucache -- Painting Operators --erasepage local function erasepage(vm) vm.Driver:erasepage() return true end exports.erasepage = erasepage --stroke local function stroke(vm) vm.Driver:stroke() return true end exports.stroke = stroke --fill local function fill(vm) vm.Driver:fill() return true end exports.fill = fill --eofill -- use even odd rule local function eofill(vm) vm.Driver:fill() return true; end exports.eofill = eofill --rectstroke local function rectstroke(vm) local height = vm.OperandStack:pop() local width = vm.OperandStack:pop() local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() vm.Driver:rectStroke(x,y,width,height) return true end exports.rectstroke = rectstroke --rectfill local function rectfill(vm) local height = vm.OperandStack:pop() local width = vm.OperandStack:pop() local y = vm.OperandStack:pop() local x = vm.OperandStack:pop() vm.Driver:rectFill(x,y,width,height) return true end exports.rectfill = rectfill --ustroke --ufill --ueofill --shfill --[[ -- Form and Pattern Operators --]] --makepattern --setpattern --setpattern --execform --[[ -- Device Setup -]] --showpage local function showpage(vm) vm.Driver:showPage() end exports.showpage = showpage --copypage --setpagedevice --currentpagedevice --nulldevice --[[ -- font operators --]] --definefont --composefont --undefinefont --findfont local function findfont(vm) local key = vm.OperandStack:pop() -- find font based on family name local face = vm.Driver:findFontFace(key) --print("findfont, face: ", key, face) -- put that object on the stack if face then -- put the actual BLFaceCore object on the stack vm.OperandStack:push(face) else -- push an error on the stack vm.OperandStack:push(ps_common.NULL) end return true end exports.findfont = findfont --scalefont local function scalefont(vm) -- pop size off the stack local size = vm.OperandStack:pop() local face = vm.OperandStack:pop() --print("scaleFont: ", face) local font = face:createFont(size) vm.OperandStack:push(font) vm.Driver:setFont(font) return true end exports.scalefont = scalefont --makefont --setfont local function setfont(vm) local font = vm.OperandStack:pop() vm.Driver:setFont(font) return true end exports.setfont = setfont --rootfont --currentfont local function currentfont(vm) vm.OperandStack:push(vm.Driver.CurrentState.Font) return true end exports.currentfont = currentfont --setfont local function selectfont(vm) -- findfont -- scalefont -- setfont local scale = vm.OperandStack:pop() local key = vm.OperandStack:pop() -- findfont local face = vm.Driver:findFontFace(key) -- scalefont local font = face:createFont(scale) -- setfont vm.Driver:setFont(font) return true end exports.selectfont = selectfont --show local function show(vm) local str = vm.OperandStack:pop() vm.Driver:show(str) return true end exports.show = show --ashow local function ashow(vm) local str = vm.OperandStack:pop() local ay = vm.OperandStack:pop() local ax = vm.OperandStack:pop() print("OP:ashow; ", ax, ay, str.value) vm.Driver:show({ax, ay}, str.value) return true end --exports.ashow = ashow --widthshow --awidthshow --xshow --xyshow --yshow --glyphshow --stringwidth --string stringwidth wx wy local function stringwidth(vm) local str = vm.OperandStack:pop() local wx, wy = vm.Driver:stringWidth(str) vm.OperandStack:push(wx) vm.OperandStack:push(wy) print("OP:stringwidth: ", wx, wy) return true end exports.stringwidth = stringwidth --cshow --kshow -- image -- width height bits/sample matrix datasrc image - -- dict image - local function image(vm) -- based on datasrc, we can figure out which form -- of the operand is being used local datasrc = vm.OperandStack:pop() local m = vm.OperandStack:pop() local bps = vm.OperandStack:pop() local height = vm.OperandStack:pop() local width = vm.OperandStack:pop() return true end --FontDirectory --GlobalFontDirectory --StandardEncoding --ISOLatin1Encoding --findencoding --setcachedevice --setcachedevice2 --setcharwidth return exports
-- restops.lua return { GET = 1, PUT = 2, DELETE = 3, }
assert(Global.CLIENT or Global.SERVER) assert(not (Global.CLIENT and Global.SERVER)) log(DEBUG, string.format("Generating LogicEntity system with CLIENT = %s", tostring(Global.CLIENT))) RootLogicEntity = class() function RootLogicEntity:__tostring () return "LogicEntity" end RootLogicEntity.shouldAct = true function RootLogicEntity:__init () self.tags = StateArray() self._persistent = StateBoolean() end function RootLogicEntity:_generalSetup () log(DEBUG, "RootLogicEntity._generalSetup") if self._generalSetupComplete then return nil end Signals.addMethods(self) self.actionSystem = ActionSystem(self) self.stateVariableValues = {} self.stateVariableValueTimestamps = {} self.deactivated = false self:_setupVariables() self._generalSetupComplete = true end function RootLogicEntity:_generalDeactivate () self:clearActions() CAPI.unregisterLogicEntity(self.uniqueId) self.deactivated = true end function RootLogicEntity:_getStateDatum (key) return self.stateVariableValues[key] end function RootLogicEntity:act (seconds) self.actionSystem:manageActions(seconds) end function RootLogicEntity:queueAction (action) self.actionSystem:queue(action) end function RootLogicEntity:clearActions () self.actionSystem:clear() end function RootLogicEntity:addTag (tag) if not self.hasTag(tag) then self.tags:push(tag) end end function RootLogicEntity:removeTag (tag) log(DEBUG, "remove") self.tags = table.filterarray(self.tags:asArray(), function (_tag) return _tag ~= tag end) end function RootLogicEntity:hasTag (tag) log(INFO, string.format("I can has %s, looking in %s", tostring(tag), JSON.encode(self.tags))) return (table.findarray(self.tags:asArray(), tag) >= 0) end function RootLogicEntity:_setupHandlers (handlerNames) local prefix = onModifyPrefix() for i = 1, #handlerNames do self.connect(prefix .. handlerNames[i], self[ "_set_" .. handlerNames[i] ]) end end function RootLogicEntity:_setupVariables () local _names = table.keys(self) for i = 1, #_names do local variable = self[ _names[i] ] if isVariable(variable) then variable:_register(_names[i], self) end end end function RootLogicEntity:createStateDataDict (targetClientNumber, kwargs) targetClientNumber = defaultValue(targetClientNumber, MessageSystem.ALL_CLIENTS) kwargs = defaultValue(kwargs, {}) log(DEBUG, string.format("createStateDataDict(): %s %i, %i", tostring(self), self.uniqueId, targetClientNumber)) local ret = {} local _names = table.keys(self) for i = 1, #_names do local variable = self[ _names[i] ] if isVariable(variable) and variable.hasHistory then if targetClientNumber >= 0 and not variable:shouldSend(self, targetClientNumber) then return nil end local value = self[variable._name] if value then log(INFO, string.format("createStateDataDict() addding %s:%s", variable._name, JSON.encode(value))) local _key = variable._name if kwargs.compressed then _key = MessageSystem.toProtocolId(tostring(self), variable._name) end ret[tostring(_key)] = variable:toData(value) log(INFO, "createStateDataDict() currently...") log(INFO, string.format("createStateDataDict() currently: %s", JSON.encode(ret))) end end end log(DEBUG, string.format("createStateDataDict() returns: %s", JSON.encode(ret))) if not kwargs.compressed then return ret end _names = table.keys(ret) for i = 1, #_names do if ret[ _names[i] ] and ret[ _names[i] ] ~= "" then if tonumber(ret[ _names[i] ]) then ret[ _names[i] ] = tonumber(ret[ _names[i] ]) elseif ret[ _names[i] ] == "[]" then ret[ _names[i] ] = nil end end end ret = JSON.encode(ret) log(DEBUG, string.format("pre-compression: %s", ret)) local tmp = { function (data) local ret = string.gsub(data, "\", \"", "\",\"") return ret end, function (data) local ret = string.gsub(data, "\"(%w+)\":", "\"%1\":") return ret end, function (data) local ret = string.gsub(data, ":\"(%d+)\"", ":\"%1\"") return ret end, function (data) local ret = string.gsub(data, "\"%[%]\"", "[]") return ret end, function (data) local ret = string.gsub(data, ":\"(%d+)%.(%d+)\"", ":\"%1\".\"%2\"") return ret end, function (data) local ret = string.gsub(data, ", ", ",") return ret end } for i = 1, #tmp do local nextel = tmp[i](ret) if string.len(nextel) < string.len(ret) and JSON.encode(JSON.decode(nextel)) == JSON.encode(JSON.decode(ret)) then ret = nextel end end tmp = nil log(DEBUG, string.format("compressed: %s", ret)) return string.sub(ret, 2, string.len(ret) - 1) end function RootLogicEntity:_updateCompleteStateData (stateData) log(DEBUG, string.format("updating complete state data for %i with %s (%s)", self.uniqueId, stateData, type(stateData))) if string.sub(stateData, 1, 1) ~= "{" then stateData = "{" .. stateData .. "}" end local newStateData = JSON.decode(stateData) assert(type(newStateData) == "table") self.initialized = true for a,b in pairs(newStateData) do local key = a local val = b if key then key = MessageSystem.fromProtocolId(tostring(self), tonumber(key)) end log(DEBUG, string.format("update of complete state datum: %s = %s", tostring(key), tostring(val))) self:_setStateDatum(key, val, nil, true) log(DEBUG, "update of complete state datum ok") end end ----------------------------------------------------------------------------- local ClientLogicEntity = class(RootLogicEntity) function ClientLogicEntity:clientActivate (kwargs) self:_generalSetup() if not self._sauerType then log(DEBUG, string.format("non-Sauer entity going to be set up: %s,%s", tostring(self), tostring(self._sauerType))) CAPI.setupNonSauer(self) end self.initialized = false end function ClientLogicEntity:clientDeactivate () self:_generalDeactivate() end function ClientLogicEntity:_setStateDatum (key, value, actorUniqueId) log(DEBUG, string.format("Setting state datum: %s = %s for %i", tostring(key), JSON.encode(value), self.uniqueId)) local variable = self[__SV_PREFIX .. key] local customSynchFromHere = variable.customSynch and self._controlledHere local clientSet = variable.clientSet if actorUniqueId == null and not customSynchFromHere then -- hacky checking for "definition" via string .. FIXME log(DEBUG, "Sending request/notification to server") MessageSystem.send(variable.reliable and CAPI.StateDataChangeRequest or CAPI.UnreliableStateDataChangeRequest, self.uniqueId, MessageSystem.toProtocolId(tostring(self), variable._name), variable:toWire(value)) end if actorUniqueId ~= null or clientSet or customSynchFromHere then log(INFO, "Updating locally") if actorUniqueId ~= null then value = variable:fromWire(value) end assert(variable:validate(value)) self:emit("client_onModify_" .. key, value, actorUniqueId ~= null) self.stateVariableValues[key] = value end end function ClientLogicEntity:clientAct (seconds) log(INFO, string.format("ClientLogicEntity.clientAct, %i", self.uniqueId)) self.actionSystem:manageActions(seconds) end ClientLogicEntity.renderDynamic = null ----------------------------------------------------------------------------- local ServerLogicEntity = class(RootLogicEntity) ServerLogicEntity.sentCompleteNotification = false function ServerLogicEntity:init (uniqueId, kwargs) log(DEBUG, string.format("ServerLogicEntity.init(%i, %s)", uniqueId, tostring(kwargs))) assert(uniqueId) assert(type(uniqueId) == "number") self.uniqueId = uniqueId self:_logicEntitySetup() self.tags = {} kwargs = defaultValue(kwargs, {}) self._persistent = defaultValue(kwargs._persistent, false) end function ServerLogicEntity:activate (kwargs) log(DEBUG, string.format("ServerLogicEntity.activate(%s)", tostring(kwargs))) self:_logicEntitySetup() if not self._sauerType then log(DEBUG, string.format("non-Sauer entity going to be set up: %s, %s", tostring(self), tostring(self._sauerType))) CAPI.setupNonSauer(self) self:_flushQueuedStateVariableChanges() end if kwargs and kwargs.stateData then self:_updateCompleteStateData(kwargs.stateData) end self:sendCompleteNotification(MessageSystem.ALL_CLIENTS) self.sentCompleteNotification = true log(DEBUG, "LE activate complete") end function ServerLogicEntity:sendCompleteNotification (clientNumber) clientNumber = defaultValue(clientNumber, MessageSystem.ALL_CLIENTS) local clientNumbers = clientNumber == MessageSystem.ALL_CLIENTS and getClientNumbers() or { clientNumber } log(DEBUG, string.format("LE.sendCompleteNotification: %i, %i", self.clientNumber, self.uniqueId)) for i = 1, #clientNumbers do MessageSystem.send( clientNumbers[i], CAPI.LogicEntityCompleteNotification, self.clientNumber and self.clientNumber or -1, self.uniqueId, tostring(self), self:createStateDataDict(currClientNumber, { compressed = true })) end log(DEBUG, "Le.sendCompleteNotification complete") end function ServerLogicEntity:_logicEntitySetup () if not self.initialized then log(DEBUG, "LE setup") self:_generalSetup() self._queuedStateVariableChanges = {} self._queuedStateVariableChangesComplete = false self.initialized = true log(DEBUG, "LE setup complete") end end function ServerLogicEntity:deactivate () self:_generalDeactivate() MessageSystem.send(MessageSystem.ALL_CLIENTS, CAPI.LogicEntityRemoval, self.uniqueId) end function ServerLogicEntity:click (button, clicker) end function ServerLogicEntity:_setStateDatum (key, value, actorUniqueId, internalOp) log(INFO, string.format("Setting state datum: %s = %s (%s) : %s", key, tostring(value), type(value), JSON.encode(value))) local _class = tostring(self) local variable = self[__SV_PREFIX .. key] if not variable then log(WARNING, string.format("Ignoring state data setting for unknown (possibly deprecated) variable: %s", key)) return nil end if actorUniqueId then value = variable:fromWire(value) if not variable.clientWrite then log(ERROR, string.format("Client %i tried to change %s", actorUniqueId, key)) return nil end elseif internalOp then value = variable:fromData(value) end log(DEBUG, string.format("Translated value: %s = %s (%s) : %s", key, tostring(value), type(value), JSON.encode(value))) local ret = self:emit("onModify_" .. key, value, actorUniqueId) if ret then if ret == "CancelStateDataUpdate" then return nil else error(ret) end end self.stateVariableValues[key] = value log(INFO, string.format("New state data: %s", tostring(self.stateVariableValues[key]))) local customSynchFromHere = variable.customSynch and self._controlledHere if (not internalOp) and variable.clientRead then if not customSynchFromHere then if not self.sentCompleteNotification then return nil end local cn = -1 if variable.clientSet and actorUniqueId then cn = getEntity(actorUniqueId).clientNumber end local rel = CAPI.UnreliableStateDataUpdate if variable.reliable then rel = CAPI.StateDataUpdate end local args = { null, rel, self.uniqueId, MessageSystem.toProtocolId(_class, key), variable:toWire(value), cn } local _clientNumbers = getClientNumbers() for i = 1, #_clientNumbers do if not variable:shouldSend(self, _clientNumbers[i]) then return nil end args[1] = _clientNumbers[i] MessageSystem.send(unpack(args)) end end end end function ServerLogicEntity:_queueStateVariableChange (key, value) log(DEBUG, string.format("Queueing SV change: %s - %s (%s)", key, tostring(value), type(value))) self._queuedStateVariableChanges[key] = value end function ServerLogicEntity:canCallCFuncs () return (self._queuedStateVariableChanges == null) end function ServerLogicEntity:_flushQueuedStateVariableChanges () log(DEBUG, string.format("Flushing Queued SV Changes for %i", self.uniqueId)) if self:canCallCFuncs() then return nil end local changes = self._queuedStateVariableChanges self._queuedStateVariableChanges = null assert(self:canCallCFuncs()) local _names = table.keys(changes) for i = 1, #_names do local value = changes[ _names[i] ] local variable = self[ __SV_PREFIX .. _names[i] ] log(DEBUG, string.format("(A) Flushing queued SV change: %s - %s (real: %s)", _names[i], tostring(value), tostring(self.stateVariableValues[key]))) self[ _names[i] ] = self.stateVariableValues[ _names[i] ] log(DEBUG, string.format("(B) Flushing of %s - ok", _names[i])) end self._queuedStateVariableChangesComplete = true end ----------------------------------------------------------------------------- if Global.CLIENT then LogicEntity = ClientLogicEntity else LogicEntity = ServerLogicEntity end
local Plugin = script.Parent.Parent.Parent local Constants = require(Plugin.Core.Util.Constants) local Libs = Plugin.Libs local Cryo = require(Libs.Cryo) local Rodux = require(Libs.Rodux) local t = require(Libs.t) local HttpService = game:GetService("HttpService") local Immutable = require(Plugin.Core.Util.Immutable) return Rodux.createReducer( -- This will be set by brushtool directly upon loading. nil, { StampObjectNew = function(state, action) local guid = action.guid if state.currentlyStamping == "" then return Cryo.Dictionary.join( state, { currentlyStamping = guid } ) end return state end, StampSelectedSet = function(state, action) local guid = action.guid return Cryo.Dictionary.join( state, { selected = guid } ) end, StampSelectedClear = function(state, action) return Cryo.Dictionary.join( state, { selected = "" } ) end, StampDeletingSet = function(state, action) local guid = action.guid return Cryo.Dictionary.join( state, { deleting = guid } ) end, StampDeletingClear = function(state, action) return Cryo.Dictionary.join( state, { deleting = "" } ) end, StampFilterSet = function(state, action) local filter = action.filter return Cryo.Dictionary.join( state, { filter = filter } ) end, StampIgnoreWaterSet = function(state, action) local ignoreWater = action.ignoreWater return Cryo.Dictionary.join( state, { ignoreWater = ignoreWater } ) end, StampIgnoreInvisibleSet = function(state, action) local ignoreInvisible = action.ignoreInvisible return Cryo.Dictionary.join( state, { ignoreInvisible = ignoreInvisible } ) end, StampRotationSet = function(state, action) local mode = action.mode local fixed = action.fixed local min = action.min local max = action.max return Cryo.Dictionary.join( state, { rotation = Cryo.Dictionary.join( state.rotation, { mode = mode, fixed = fixed, min = min, max = max } ) } ) end, StampScaleSet = function(state, action) local mode = action.mode local fixed = action.fixed local min = action.min local max = action.max return Cryo.Dictionary.join( state, { scale = Cryo.Dictionary.join( state.scale, { mode = mode, fixed = fixed, min = min, max = max } ) } ) end, StampOrientationSet = function(state, action) local mode = action.mode local custom = action.custom return Cryo.Dictionary.join( state, { orientation = Cryo.Dictionary.join( state.orientation, { mode = mode, custom = custom } ) } ) end, StampedParentSet = function(state, action) return Cryo.Dictionary.join( state, { stampedParent = action.stampedParent } ) end, StampCurrentlyStampingSet = function(state, action) return Cryo.Dictionary.join( state, { currentlyStamping = action.guid } ) end, StampCurrentlyStampingClear = function(state, action) return Cryo.Dictionary.join( state, { currentlyStamping = "" } ) end, _CopyFromState = function(state, action) return action.init.stamp end } )
local passive_only = false spawnlite = {} spawnlite.passive = {} spawnlite.agressive = {} spawnlite.water = {} spawnlite.air = {} spawnlite.mobs = {} spawnlite.mobs.passive = {} spawnlite.mobs.agressive = {} spawnlite.mobs.water = {} spawnlite.mobs.air = {} spawnlite.mobs.passive.now = 0 spawnlite.mobs.agressive.now = 0 spawnlite.mobs.water.now = 0 spawnlite.mobs.air.now = 0 --MOB SPAWNING LIMITS spawnlite.mobs.passive.max = 3 spawnlite.mobs.agressive.max = 5 spawnlite.mobs.water.max = 5 spawnlite.mobs.air.max = 5 local mobs = spawnlite.mobs local function is_space(pos,size) local x,y,z = 1,0,0 if size.x*size.y*size.z == 1 then return true end for i=2,size.x*size.y*size.z do if x > size.x-1 then x = 0 y = y + 1 end if y > size.y-1 then y = 0 z = z + 1 end if minetest.get_node({x=pos.x+x,y=pos.y+y,z=pos.z+z}).name ~= "air" then return false end x = x + 1 end --[[ local _, no_air = minetest.find_nodes_in_area(pos,{x=pos.x+size.x-1,y=pos.y+size.y-1,z=pos.z+size.z-1},{"air"}) if no_air ~= size.x*size.y*size.z then return false else return true end --]] return true end local function get_new_mob(passive) if passive then return spawnlite.passive[math.random(1,#spawnlite.passive)] else return spawnlite.agressive[math.random(1,#spawnlite.agressive)] end return nil end --Spawning variables local max_no = 1 --per player per spawn attempt --Area variables local width = 60 local half_width = width/2 local height = 80 local half_height = height/2 --Timing variables local timer = 0 local spawn_interval = 1 minetest.register_globalstep(function(dtime) timer = timer + dtime if timer < spawn_interval then return end timer = 0 local players = minetest.get_connected_players() local rand_x = math.random(0,width-1) - half_width local rand_z = math.random(0,width-1) - half_width local passive = passive_only or math.random(0,1) == 1 for i=1,#players do local spawned = 0 local pos = players[i]:getpos() local mob = get_new_mob(passive) local nodes = minetest.find_nodes_in_area_under_air( {x=pos.x+rand_x,y=pos.y-half_height,z=pos.z+rand_z} ,{x=pos.x+rand_x,y=pos.y+half_height,z=pos.z+rand_z} ,mob.nodes) for i=1,#nodes do --Spawn limit conditions if spawned > max_no then break end if passive and mobs.passive.now > mobs.passive.max then return elseif not passive and mobs.agressive.now > mobs.agressive.max then return end if mobs[mob.name].now > mobs[mob.name].max_no then break end --Tests to check that placement suitiability for mob local lightlevel = minetest.get_node_light( {x=pos.x+rand_x,y=nodes[i].y+1,z=pos.z+rand_z}) if lightlevel >= mob.min_light and lightlevel <= mob.max_light and nodes[i].y > mob.min_height and nodes[i].y < mob.max_height and is_space({x=pos.x+rand_x,y=nodes[i].y+1,z=pos.z+rand_z},mob.size) then --chance reduce overall mob spawn rate, but is useful for the programmer if not mob.chance then minetest.add_entity({x=pos.x+rand_x,y=nodes[i].y+1,z=pos.z+rand_z},mob.name) mobs[mob.name].now = mobs[mob.name].now + 1 if passive then mobs.passive.now = mobs.passive.now + 1 else mobs.agressive.now = mobs.agressive.now + 1 end spawned = spawned + 1 elseif math.random(1,1000) < mob.chance * 10 then minetest.add_entity({x=pos.x+rand_x,y=nodes[i].y+1,z=pos.z+rand_z},mob.name) mobs[mob.name].now = mobs[mob.name].now + 1 if passive then mobs.passive.now = mobs.passive.now + 1 else mobs.agressive.now = mobs.agressive.now + 1 end spawned = spawned + 1 end end end end end) local mob_count_timer = 0 local moblist_update_time = 5 minetest.register_globalstep(function(dtime) mob_count_timer = mob_count_timer + dtime if mob_count_timer < moblist_update_time then return end mob_count_timer = 0 for k,v in pairs(spawnlite.mobs) do v.now = 0 end for k,v in pairs(minetest.luaentities) do if v.name and mobs[v.name] then mobs[v.name].now = mobs[v.name].now + 1 end end for i=1,#spawnlite.passive do mobs.passive.now = mobs.passive.now + spawnlite.passive[i].now end for i=1,#spawnlite.agressive do mobs.agressive.now = mobs.agressive.now + spawnlite.agressive[i].now end --[[ for k,v in pairs(minetest.luaentities) do minetest.debug(k) minetest.debug(v.name) end --]] end) local function get_mob_size(def) local size = {} local box = def.collisionbox size.x = math.ceil(math.abs(box[1] - box[4])) size.y = math.ceil(math.abs(box[2] - box[5])) size.z = math.ceil(math.abs(box[3] - box[6])) return size end local function get_mob_group(def,nodes) if def.group then return def.group elseif nodes[1] == "air" then return "air" elseif nodes[1] == "default:water" then return "water" elseif def.type == "monster" then return "agressive" else return "passive" end return nil end spawnlite.register_specific = function(name,nodes,ignored_neighbors,min_light ,max_light,ignored_interval,chance_percent_1dp,max_no,min_height ,max_height,group) local mob = {} spawnlite.mobs[name] = spawnlite.mobs[name] or mob --Setup Mob Specific table mob.name = name mob.nodes = nodes mob.min_light = min_light or 0 mob.max_light = max_light or 16 mob.chance = chance_percent_1dp mob.max_no = max_no or 5 mob.now = 0 mob.min_height = min_height or -33000 mob.max_height = max_height or 33000 --Setup variables from mob def local mob_def = minetest.registered_entities[name] mob.size = get_mob_size(mob_def) mob.group = group or get_mob_group(mob_def,nodes) --Setup group table table.insert(spawnlite[mob.group],spawnlite.mobs[name]) end dofile(minetest.get_modpath("spawnlite").."/mobs/init.lua")
range = require ("init") function testIntegerRangeWithoutEnd () local sum = 0 for i in range (2) do sum = sum + i end local expected = 2 assert ( expected == sum, "sum should be " .. expected .. " but is " .. sum ) end function testIntegerRange () local sum = 0 for i in range (1, 10) do sum = sum + i end local expected = 55 assert ( expected == sum, "sum should be " .. expected .. " but is " .. sum ) end function testIntegerRangeReversed () local str = "" local sum = 0 for i in range (4, 1) do sum = sum + i str = str .. i end local expected_sum = 10 assert ( expected_sum == sum, "sum should be " .. expected_sum .. " but is " .. sum ) local expected_str = "4321" assert ( expected_str == str, "str should be " .. expected_str .. " but is " .. str ) end function testIntegerRangeWithStep () local sum = 0 for i in range (42, 1337, 2) do sum = sum + i end local expected = 446472 assert ( expected == sum, "sum should be " .. expected .. " but is " .. sum ) end function testFloatRange () local sum = 0 for i in range (0, 0.1, 0.01) do sum = sum + i end local expected = 0.55 local epsilon = 0.00000000000001 assert ( math.abs (expected - sum) < epsilon, "sum should be " .. expected .. " but is " .. sum ) end function testStringRangeWithoutEnd () local alpha = "" for i in range ("W") do alpha = alpha .. i end local expected = "W" assert ( expected == alpha, "alpha should be " .. expected .. " but is " .. alpha ) end function testStringRange () local alpha = "" for i in range ("W", "Z") do alpha = alpha .. i end local expected = "WXYZ" assert ( expected == alpha, "alpha should be " .. expected .. " but is " .. alpha ) end function testStringRangeReversed () local alpha = "" for i in range ("Z", "W") do alpha = alpha .. i end local expected = "ZYXW" assert ( expected == alpha, "alpha should be " .. expected .. " but is " .. alpha ) end function main () testIntegerRangeWithoutEnd () print ("succeeded testIntegerRangeWithoutEnd") testIntegerRange () print ("succeeded testIntegerRange") testIntegerRangeReversed () print ("succeeded testIntegerRangeReversed") testIntegerRangeWithStep () print ("succeeded testIntegerRangeWithStep") testFloatRange () print ("succeeded testFloatRange") testStringRange () print ("succeeded testStringRange") testStringRangeWithoutEnd () print ("succeeded testStringRangeWithoutEnd") testStringRangeReversed () print ("succeeded testStringRangeReversed") end main ()
if (...) == "-?" then printUsage( "reboot","Soft reboots LIKO-12", "reboot hard","Hard reboots LIKO-12" ) return end local args = {...} --Get the arguments passed to this program if tostring(args[1] or "soft") == "hard" then print("HARD REBOOTING ...") sleep(0.25) reboot(true) else print("SOFT REBOOTING ...") sleep(0.25) reboot(false) end
TRAIT.name = "Chaotic Alloys I" TRAIT.IconX = 1 TRAIT.IconY = 1 TRAIT.LevelReq = 3 TRAIT.SkillPointCost = 1 TRAIT.Incompatible = { } TRAIT.RequiredTraits = { "undivided" } TRAIT.icon = "vgui/skills/ability_warrior_defensivestance_1.png" TRAIT.category = "Blessings of Chaos Undivided"-- Common Passives, Warriors of Chaos, Lore of Light, Dark Magic TRAIT.desc = [[ The Nature of Chaos alloys and metals grant them an unique ability to restore itself. Armorrating: +10 Shield Regen: +5 Level Requirement: ]] .. TRAIT.LevelReq .. [[ Skill Point Cost:]] .. TRAIT.SkillPointCost .. [[ ]] TRAIT.class = { "chaos_warrior", "reaver", "asp_sorcerer" } local function onAquire(TRAIT, char) local naturalArmorRating = char:getData("naturalArmorRating", 0) naturalArmorRating = naturalArmorRating + 10 char:setData("naturalArmorRating", naturalArmorRating) end TRAIT.onAquire = onAquire
-- Point definition in Lua PointLua = {} PointLua.__index = PointLua PointLua.__class = 'PointLua' function PointLua:new(x, y) obj = {x = x, y = y, velocityX = 0, velocityY = 0} setmetatable(obj, self) -- This makes obj inherit from HUD return obj end function PointLua:setX(x) self.x = x; end function PointLua:getX() return self.x; end function PointLua:setY(y) self.y = y; end function PointLua:getY() return self.y; end function PointLua:setVelocityX(velocityX) self.velocityX = velocityX; end function PointLua:getVelocityX() return self.velocityX; end function PointLua:setVelocityY(velocityY) self.velocityY = velocityY; end function PointLua:getVelocityY() return self.velocityY; end function allScript(point,mouse,friction) -- some call saving precomputation diffX = mouse:getX() - point:getX(); diffY = mouse:getY() - point:getY(); -- modify velocity based on point decision distance = (diffX^2 + diffY^2)^0.5; if distance > 20 then point:setVelocityX(point:getVelocityX() + (diffX) / distance); point:setVelocityY(point:getVelocityY() + (diffY) / distance); elseif distance < 15 then point:setVelocityX(point:getVelocityX() - (diffX) / distance); point:setVelocityY(point:getVelocityY() - (diffY) / distance); end -- let the physics happen speed = (point:getVelocityX()^2 + point:getVelocityY()^2)^0.5; if speed <= friction then point:setVelocityX(0); point:setVelocityY(0); else -- apply friction point:setVelocityX((1 - friction / speed) * point:getVelocityX()); point:setVelocityY((1 - friction / speed) * point:getVelocityY()); -- move points point:setX(point:getX() + point:getVelocityX()); point:setY(point:getY() + point:getVelocityY()); end end --------------------------------------------- -- lua script controls the simulation loop and uses its own point objects -- function loopPointsScripted(pointCount, cyclesCount, friction) -- initialize the simulation initSimul(); points = {} for i=0,pointCount-1 do points[i] = PointLua:new(i,i); end -- start main loop for i=0,cyclesCount-1,1 do -- process input and if the app should quit, break if processInput() then break; end mouse = getMouse(); preDraw(); drawMouse(); for j=0,pointCount-1,1 do allScript(points[j], mouse, friction); drawPoint(points[j]:getX(), points[j]:getY()); end postDraw(); end -- clean resources cleanup(); end
-- @module table module ("table", package.seeall) --require "list" FIXME: allow require loops -- FIXME: use consistent name for result table: t_? (currently r and -- u) -- @func sort: Make table.sort return its result -- @param t: table -- @param c: comparator function -- @returns -- @param t: sorted table local _sort = sort function sort (t, c) _sort (t, c) return t end -- @func empty: Say whether table is empty -- @param t: table -- @returns -- @param f: true if empty or false otherwise function empty (t) return not next (t) end -- @func size: Find the number of elements in a table -- @param t: table -- @returns -- @param n: number of elements in t function size (t) local n = 0 for _ in pairs (t) do n = n + 1 end return n end -- @func indices: Make the list of indices of a table -- @param t: table -- @returns -- @param u: list of indices function indices (t) local u = {} for i, v in pairs (t) do insert (u, i) end return u end -- @func values: Make the list of values of a table -- @param t: table -- @returns -- @param u: list of values function values (t) local u = {} for i, v in pairs (t) do insert (u, v) end return u end -- @func invert: Invert a table -- @param t: table {i=v...} -- @returns -- @param u: inverted table {v=i...} function invert (t) local u = {} for i, v in pairs (t) do u[v] = i end return u end -- @func rearrange: Rearrange some indices of a table -- @param m: table {oldindex=newindex...} -- @param t: table to rearrange -- @returns -- @param r: rearranged table function rearrange (m, t) local r = clone (t) for i, v in pairs (m) do r[v] = t[i] r[i] = nil end return r end -- @func clone: Make a shallow copy of a table, including any -- metatable -- @param t: table -- @param nometa: if non-nil don't copy metatable -- @returns -- @param u: copy of table function clone (t, nometa) local u = {} if not nometa then setmetatable (u, getmetatable (t)) end for i, v in pairs (t) do u[i] = v end return u end -- @func merge: Merge two tables -- If there are duplicate fields, u's will be used. The metatable of -- the returned table is that of t -- @param t, u: tables -- @returns -- @param r: the merged table function merge (t, u) local r = clone (t) for i, v in pairs (u) do r[i] = v end return r end -- @func new: Make a table with a default entry value -- @param [x]: default entry value [nil] -- @param [t]: initial table [{}] -- @returns -- @param u: table for which u[i] is x if u[i] does not exist function new (x, t) return setmetatable (t or {}, {__index = function (t, i) return x end}) end
-- Rectivate / Deactivate local gvt = require 'luagravity' local state local app = gvt.start(function() state = 0 gvt.await(10) state = 1 gvt.await(10) state = 2 end) assert(state == 0) gvt.step(app, 'dt', 10) gvt.step(app, 'dt', 0) assert(state == 1) gvt.deactivate(app) gvt.step(app, 'dt', 10) gvt.step(app, 'dt', 0) assert(state == 1) gvt.step(app, 'dt', 10) gvt.step(app, 'dt', 0) assert(state == 1) gvt.reactivate(app) gvt.step(app, 'dt', 10) gvt.step(app, 'dt', 0) assert(state == 2, state) print '===> OK'
test = require 'u-test' common = require 'common' function SetupTest_Handler() print("SetupTest_Handler") local hr = GetLastError() SetCheckHR(1) if hr ~= 0 then print("Calling XalAddUserWithUiAsync") XalAddUserWithUiAsync() else test.stopTest(); end end test.StartSetupTest = function() print("Running shared test.StartSetupTest") SetCheckHR(0) common.init(SetupTest_Handler) end function OnXalAddUserWithUiAsync() print("In OnXalAddUserWithUiAsync") XblContextCreateHandle() XalUserGetGamertag() XalUserGetId() test.stopTest(); end
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Sending PTS to mobile application -- [HMI API] SystemRequest request/response -- -- Description: -- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS -- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be -- assigned as "JSON" in mobile app notification. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- 2. Performed steps -- HMI->SDL:BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID) -- -- Expected result: -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local mobile_session = require("mobile_session") local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local utils = require ('user_modules/utils') --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("user_modules/connecttest_resumption") require('cardinalities') require('user_modules/AppTypes') local HMIAppID --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:ConnectMobile() self:connectMobile() end function Test:StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end function Test:RAI() local corId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }) :Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Times(0) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.registerAppInterfaceParams.appName } }) :Do( function(_, d1) HMIAppID = d1.params.application.appID end) self.mobileSession:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) :Do( function() self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN" }) self.mobileSession:ExpectNotification("OnPermissionsChange") :Times(1) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Trigger_getting_device_consent() local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = HMIAppID }) EXPECT_HMIRESPONSE(requestId1) :Do( function(_, d1) if d1.result.isSDLAllowed ~= true then local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", { language = "EN-US", messageCodes = { "DataConsent" } }) EXPECT_HMIRESPONSE(requestId2) :Do( function() self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", { allowed = true, source = "GUI", device = { id = utils.getDeviceMAC(), name = utils.getDeviceName() } }) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do( function(_, d2) self.hmiConnection:SendResponse(d2.id,"BasicCommunication.ActivateApp", "SUCCESS", { }) self.mobileSession:ExpectNotification("OnHMIStatus", { hmiLevel = "FULL", audioStreamingState = "AUDIBLE", systemContext = "MAIN" }) end) end) end end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }):Times(2) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do( function(_, d) self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { }) local requestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(requestId) :Do( function() local policy_file_name = "PolicyTableUpdate" self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = policy_file_name }) self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) end) end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
local CrateModule = { crates = { ["Starter"] = { common = 60, uncommon = 30, rare = 10, legendary = 0, currency = "Coins", productId = 0, price = 500 }, ["Spotty"] = { common = 40, uncommon = 30, rare = 25, legendary = 5, currency = "Coins", productId = 0, price = 2000 }, ["Royal Deluxe"] = { common = 35, uncommon = 30, rare = 20, legendary = 15, currency = "R", productId = nil, price = 0 }, } } return CrateModule
-- Player perk mapping. local Perks = {} -- Perks are separated by governing skill. -- They are grouped into areas - which has nothing to do with any practical aspects of the skill. -- Instead, areas have requirements and this governs at what skill level the perk is unlocked. -- Ultimate "perks" are actually referred to as traits and work a bit differently. -- Note that perks are not meant to be prefixed. Perks = { Annihilation = { HailOfBullets = "Demolition_Area_01_Perk_1", PumpItLouder = "Demolition_Area_02_Perk_1", InYourFace = "Demolition_Area_02_Perk_2", Bloodrush = "Demolition_Area_03_Perk_1", DeadCenter = "Demolition_Area_03_Perk_2", Bulldozer = "Demolition_Area_04_Perk_1", Mongoose = "Demolition_Area_04_Perk_2", MomentumShift = "Demolition_Area_05_Perk_1", Massacre = "Demolition_Area_05_Perk_2", SkeetShooter = "Demolition_Area_06_Perk_1", HeavyLead = "Demolition_Area_06_Perk_2", Unstoppable = "Demolition_Area_07_Perk_1", Manic = "Demolition_Area_07_Perk_2", SpeedDemon = "Demolition_Area_08_Perk_1", BurnBabyBurn = "Demolition_Area_08_Perk_2", HitTheDeck = "Demolition_Area_09_Perk_1", PoppinOff = "Demolition_Area_09_Perk_2", Biathlete = "Demolition_Area_10_Perk_1" -- Literally an unimplemented perk. -- NotImplemented = "Demolition_Area_10_Perk_2" }, Athletics = { Regeneration = "Athletics_Area_01_Perk_1", PackMule = "Athletics_Area_01_Perk_2", Invincible = "Athletics_Area_02_Perk_1", TrueGrit = "Athletics_Area_02_Perk_2", Epimorphosis = "Athletics_Area_03_Perk_1", SoftOnYourFeet = "Athletics_Area_03_Perk_2", SteelAndChrome = "Athletics_Area_04_Perk_1", Gladiator = "Athletics_Area_04_Perk_2", DividedAttention = "Athletics_Area_05_Perk_1", Multitasker = "Athletics_Area_05_Perk_2", LikeButterfly = "Athletics_Area_05_Perk_3", Transporter = "Athletics_Area_06_Perk_1", StrongerTogether = "Athletics_Area_06_Perk_2", CardioCure = "Athletics_Area_06_Perk_3", HumanShield = "Athletics_Area_07_Perk_1", Marathoner = "Athletics_Area_07_Perk_2", DogOfWar = "Athletics_Area_08_Perk_1", Wolverine = "Athletics_Area_08_Perk_2", SteelShell = "Athletics_Area_09_Perk_1", TheRock = "Athletics_Area_10_Perk_1", Indestructible = "Athletics_Area_10_Perk_2" }, Assault = { Bulletjock = "Assault_Area_01_Perk_1", EagleEye = "Assault_Area_01_Perk_2", CoveringKillshot = "Assault_Area_02_Perk_1", TooCloseForComfort = "Assault_Area_02_Perk_2", Bullseye = "Assault_Area_03_Perk_1", Executioner = "Assault_Area_03_Perk_2", ShootReloadRepeat = "Assault_Area_04_Perk_1", DuckHunter = "Assault_Area_04_Perk_2", NervesOfSteel = "Assault_Area_05_Perk_1", FeelTheFlow = "Assault_Area_05_Perk_2", TrenchWarfare = "Assault_Area_06_Perk_1", HuntersHands = "Assault_Area_06_Perk_2", SkullSkipper = "Assault_Area_07_Perk_1", NamedBullets = "Assault_Area_07_Perk_2", Bunker = "Assault_Area_08_Perk_1", RecoilWrangler = "Assault_Area_08_Perk_2", InPerspective = "Assault_Area_09_Perk_1", LongShot = "Assault_Area_09_Perk_2", SavageStoic = "Assault_Area_10_Perk_1" }, Blades = { StingLikeABee = "Kenjutsu_Area_01_Perk_1", RoaringWaters = "Kenjutsu_Area_01_Perk_2", CrimsonDance = "Kenjutsu_Area_02_Perk_1", SlowAndSteady = "Kenjutsu_Area_02_Perk_2", FlightOfTheSparrow = "Kenjutsu_Area_03_Perk_1", OffensiveDefense = "Kenjutsu_Area_03_Perk_2", StuckPig = "Kenjutsu_Area_04_Perk_1", ShiftingSands = "Kenjutsu_Area_04_Perk_2", BlessedBlade = "Kenjutsu_Area_05_Perk_1", UnbrokenSpirit = "Kenjutsu_Area_05_Perk_2", Bloodlust = "Kenjutsu_Area_06_Perk_1", FloatLikeAButterfly = "Kenjutsu_Area_06_Perk_2", FieryBlast = "Kenjutsu_Area_07_Perk_1", JudgeJuryAndExecutioner = "Kenjutsu_Area_07_Perk_2", CrimsonTide = "Kenjutsu_Area_08_Perk_1", Deathbolt = "Kenjutsu_Area_08_Perk_2" }, BreachProtocol = { BigSleep = "Hacking_Area_01_Perk_1", MassVulnerability = "Hacking_Area_01_Perk_2", AlmostIn = "Hacking_Area_02_Perk_1", AdvancedDatamine = "Hacking_Area_02_Perk_2", MassVulnerabilityResistances = "Hacking_Area_03_Perk_1", ExtendedNetworkInterface = "Hacking_Area_03_Perk_2", TurretShutdown = "Hacking_Area_04_Perk_1", DatamineMastermind = "Hacking_Area_04_Perk_2", TotalRecall = "Hacking_Area_05_Perk_1", DatamineVirtuoso = "Hacking_Area_06_Perk_1", TurretTamer = "Hacking_Area_06_Perk_2", Efficiency = "Hacking_Area_07_Perk_1", CloudCache = "Hacking_Area_07_Perk_2", MassVulnerabilityQuickhacks = "Hacking_Area_08_Perk_1", TotalerRecall = "Hacking_Area_08_Perk_2", Hackathon = "Hacking_Area_09_Perk_1", HeadStart = "Hacking_Area_09_Perk_2", Compression = "Hacking_Area_10_Perk_1", BufferOptimization = "Hacking_Area_10_Perk_2" }, ColdBlood = { ColdBlood = "ColdBlood_Area_01_Perk_1", WillToSurvive = "ColdBlood_Area_02_Perk_1", IcyVeins = "ColdBlood_Area_02_Perk_2", CriticalCondition = "ColdBlood_Area_03_Perk_1", FrostySynapses = "ColdBlood_Area_03_Perk_2", DefensiveClotting = "ColdBlood_Area_04_Perk_1", RapidBloodflow = "ColdBlood_Area_04_Perk_2", ColdestBlood = "ColdBlood_Area_05_Perk_1", FrozenPrecision = "ColdBlood_Area_05_Perk_2", Predator = "ColdBlood_Area_06_Perk_1", BloodBrawl = "ColdBlood_Area_06_Perk_2", QuickTransfer = "ColdBlood_Area_06_Perk_3", Bloodswell = "ColdBlood_Area_07_Perk_1", ColdAndCalculating = "ColdBlood_Area_07_Perk_2", Coolagulant = "ColdBlood_Area_08_Perk_1", Unbreakable = "ColdBlood_Area_08_Perk_2", PainIsAnIllusion = "ColdBlood_Area_09_Perk_1", Immunity = "ColdBlood_Area_10_Perk_1" }, Crafting = { Mechanic = "Crafting_Area_01_Perk_1", Junkophile = "Crafting_Area_01_Perk_2", TrueCraftsman = "Crafting_Area_02_Perk_1", Scrapper = "Crafting_Area_02_Perk_2", Workshop = "Crafting_Area_03_Perk_1", Innovation = "Crafting_Area_04_Perk_1", Sapper = "Crafting_Area_04_Perk_2", FieldTechnician = "Crafting_Area_05_Perk_1", TwoHundredPercentEfficiency = "Crafting_Area_05_Perk_2", ExNihilo = "Crafting_Area_06_Perk_1", EfficientUpgrades = "Crafting_Area_06_Perk_2", GreaseMonkey = "Crafting_Area_06_Perk_3", CostOptimization = "Crafting_Area_07_Perk_1", LetThereBeLight = "Crafting_Area_07_Perk_2", WasteNotWantNot = "Crafting_Area_08_Perk_1", TuneUp = "Crafting_Area_08_Perk_2", EdgerunnerArtisan = "Crafting_Area_09_Perk_1", CuttingEdge = "Crafting_Area_10_Perk_1" }, Engineering = { MechLoother = "Engineering_Area_01_Perk_1", BlastShielding = "Engineering_Area_01_Perk_2", CantTouchThis = "Engineering_Area_02_Perk_1", Grenadier = "Engineering_Area_02_Perk_2", Shrapnel = "Engineering_Area_03_Perk_1", Bladerunner = "Engineering_Area_04_Perk_1", UpToEleven = "Engineering_Area_04_Perk_2", LockAndLoad = "Engineering_Area_04_Perk_3", BiggerBooms = "Engineering_Area_05_Perk_1", Condensation = "Engineering_Area_05_Perk_2", Tesla = "Engineering_Area_06_Perk_1", LightningBolt = "Engineering_Area_06_Perk_2", Ubercharge = "Engineering_Area_07_Perk_1", Insulation = "Engineering_Area_07_Perk_2", GunWhisperer = "Engineering_Area_07_Perk_3", FuckAllWalls = "Engineering_Area_08_Perk_1", PlayTheAngles = "Engineering_Area_08_Perk_2", LicketySplit = "Engineering_Area_09_Perk_1", Jackpot = "Engineering_Area_10_Perk_1", Superconductor = "Engineering_Area_10_Perk_2" }, Handguns = { Gunslinger = "Gunslinger_Area_01_Perk_1", HighNoon = "Gunslinger_Area_01_Perk_2", RioBravo = "Gunslinger_Area_02_Perk_1", Desperado = "Gunslinger_Area_02_Perk_2", OnTheFly = "Gunslinger_Area_03_Perk_1", LongShotDropPop = "Gunslinger_Area_03_Perk_2", SteadyHand = "Gunslinger_Area_04_Perk_1", OKCorral = "Gunslinger_Area_04_Perk_2", VanishingPoint = "Gunslinger_Area_04_Perk_3", AFistfulOfEurodollars = "Gunslinger_Area_05_Perk_1", FromHeadToToe = "Gunslinger_Area_05_Perk_2", GrandFinale = "Gunslinger_Area_06_Perk_1", Acrobat = "Gunslinger_Area_06_Perk_2", AttritionalFire = "Gunslinger_Area_07_Perk_1", WildWest = "Gunslinger_Area_07_Perk_2", SnowballEffect = "Gunslinger_Area_08_Perk_1", Westworld = "Gunslinger_Area_08_Perk_2", LeadSponge = "Gunslinger_Area_09_Perk_1", Brainpower = "Gunslinger_Area_10_Perk_1" }, Quickhacking = { Biosynergy = "CombatHacking_Area_01_Perk_1", Bloodware = "CombatHacking_Area_01_Perk_2", ForgetMeNot = "CombatHacking_Area_02_Perk_1", ISpy = "CombatHacking_Area_02_Perk_2", HackersManual = "CombatHacking_Area_02_Perk_3", DaisyChain = "CombatHacking_Area_03_Perk_1", WeakLink = "CombatHacking_Area_03_Perk_2", SignalSupport = "CombatHacking_Area_04_Perk_1", SubliminalMesage = "CombatHacking_Area_05_Perk_1", Mnemonic = "CombatHacking_Area_06_Perk_1", Diffusion = "CombatHacking_Area_06_Perk_2", Plague = "CombatHacking_Area_07_Perk_1", CriticalError = "CombatHacking_Area_08_Perk_1", HackerOverlord = "CombatHacking_Area_08_Perk_2", Anamnesis = "CombatHacking_Area_09_Perk_1", Optimization = "CombatHacking_Area_10_Perk_1", BartmossLegacy = "CombatHacking_Area_10_Perk_2" }, Stealth = { SilentAndDeadly = "Stealth_Area_01_Perk_1", CrouchingTiger = "Stealth_Area_01_Perk_2", HiddenDragon = "Stealth_Area_02_Perk_1", DaggerDealer = "Stealth_Area_02_Perk_2", AttractionAndRepulsion = "Stealth_Area_02_Perk_3", StrikeFromTheShadows = "Stealth_Area_03_Perk_1", Assassin = "Stealth_Area_03_Perk_2", LegUp = "Stealth_Area_03_Perk_3", Sniper = "Stealth_Area_04_Perk_1", Cutthroat = "Stealth_Area_04_Perk_2", CleanWork = "Stealth_Area_05_Perk_1", AggressiveAntitoxins = "Stealth_Area_05_Perk_2", StunningBlows = "Stealth_Area_05_Perk_3", Ghost = "Stealth_Area_06_Perk_1", FromTheShadows = "Stealth_Area_06_Perk_2", Commando = "Stealth_Area_07_Perk_1", Rattlesnake = "Stealth_Area_07_Perk_2", VenomousFangs = "Stealth_Area_07_Perk_3", RestorativeShadows = "Stealth_Area_08_Perk_1", HastyRetreat = "Stealth_Area_08_Perk_2", SilentFinisher = "Stealth_Area_08_Perk_3", Neurotoxin = "Stealth_Area_09_Perk_1", CheatDeath = "Stealth_Area_09_Perk_2", HastenTheInevitable = "Stealth_Area_09_Perk_3", Ninjutsu = "Stealth_Area_10_Perk_1" }, StreetBrawler = { Flurry = "Brawling_Area_01_Perk_1", CrushingBlows = "Brawling_Area_01_Perk_2", Juggernaut = "Brawling_Area_02_Perk_1", Dazed = "Brawling_Area_02_Perk_2", Rush = "Brawling_Area_03_Perk_1", EfficientBlows = "Brawling_Area_03_Perk_2", HumanFortress = "Brawling_Area_04_Perk_1", OpportuneStrike = "Brawling_Area_04_Perk_2", Payback = "Brawling_Area_05_Perk_1", Reinvigorate = "Brawling_Area_05_Perk_2", BreathingSpace = "Brawling_Area_06_Perk_1", Relentless = "Brawling_Area_06_Perk_2", Frenzy = "Brawling_Area_07_Perk_1", Thrash = "Brawling_Area_07_Perk_2", BidingTime = "Brawling_Area_08_Perk_1", Unshakable = "Brawling_Area_08_Perk_2" } } return Perks
-- Copyright (c) 2019 teverse.com -- theme.lua local themeController = {} print ("DEBUG: Loading theme.lua") -- values from default are used in all styles unless overridden. themeController.currentTheme = { default = { fontFile = "OpenSans-Regular", backgroundColour = colour:fromRGB(37, 37, 47), textColour = colour:fromRGB(255, 255, 255) }, main = { backgroundColour = colour:fromRGB(37, 37, 47), textColour = colour:fromRGB(255, 255, 255), }, secondary = { backgroundColour = colour:fromRGB(25, 33, 34), textColour = colour:fromRGB(255, 255, 255) }, primary = { backgroundColour = colour:fromRGB(39, 39, 50), textColour = colour:fromRGB(255,255,255) }, light = { backgroundColour = colour:fromRGB(255,255,255), textColour = colour:fromRGB(25, 33, 34), }, tools = { selected = colour:fromRGB(42, 151, 255), hovered = colour(1, 1, 1), deselected = colour(0.6, 0.6, 0.6) } } themeController.guis = {} --make this a weak metatable (keys) themeController.set = function(theme) themeController.currentTheme = theme for gui, style in pairs(themeController.guis) do themeController.applyTheme(gui) end end themeController.applyTheme = function(gui) local styleName = themeController.guis[gui] local style = themeController.currentTheme[styleName] if not style then style = {} end if themeController.currentTheme["default"] then for property, value in pairs(themeController.currentTheme["default"]) do if not style[property] and gui[property] and gui[property] ~= value then --Chosen style does not have this property gui[property] = value end end end for property, value in pairs(style) do if gui[property] and gui[property] ~= value then gui[property] = value end end end themeController.add = function(gui, style) if themeController.guis[gui] then return end themeController.guis[gui] = style themeController.applyTheme(gui) end return themeController
name = "Settings Menu" popUp = false local nameIVT = INSPECTOR_VARIABLE_TYPE.INSPECTOR_STRING nameIV = InspectorVariable.new("name", nameIVT, name) NewVariable(nameIV) function Start() child = Find(name) child:Active(false) end -- Called each loop iteration function UpdateUI(dt) if (gameObject:GetButton():IsPressed()) then popUp = not popUp child:Active(popUp) end end print("UI_OpenSettingsPopUp.lua compiled succesfully")
-- ======================================================================================= -- Plugin: OBJ_MANAGE.lua -- Programmer: Cooper Santillan -- Last Modified: October 23, 2021 10:55am -- ======================================================================================= -- Description: All functions used to maintain the Maker+ plugin suite. -- ======================================================================================= -- ======================================================================================= -- ========================================================================== PLUGIN ===== -- ==== maker.create.plugin ============================================================== -- Description: -- -- Inputs: -- number -- what macro number do you want to place this in -- name -- label name for the macro -- task -- what plugin to use -- userName -- what user is using this -- ======================================================================================= function maker.create.plugin(number, name, task, userName) local makerVar = "MAKER" local title if(name == nil) then title = task else title = name end --gma.cmd("BlindEdit On") gma.cmd("Store Macro " ..number) gma.cmd("Store Macro 1." ..number ..".1 thru Macro 1." ..number ..".3") gma.cmd("Label Macro " ..number .." \"" ..maker.util.underVer(title, "Macro") .."\"") gma.cmd("Assign Macro 1." ..number ..".1 /cmd=\"SetUserVar $" ..makerVar .." = " ..maker.util.pack({userName, task, maker.util.underVer(name, "Sequence")}) .."\"") --gma.cmd("Assign Macro 1." ..number ..".2 /wait=0.1") gma.cmd("Assign Macro 1." ..number ..".3 /cmd=\"Plugin CALLER\"") --gma.cmd("BlindEdit Off") end -- ==== END OF maker.create.plugin ======================================================= -- ==== maker.edit.plugin ================================================================ -- Description: -- -- Inputs: -- number -- what macro number do you want to place this in -- name -- label name for the macro -- plugin -- what plugin to use -- ======================================================================================= function maker.edit.plugin(number, name, plugin, userName) local makerVar = "MAKER" gma.cmd("Label Macro " ..number .." \"" ..maker.util.underVer(name, "Macro") .."\"") gma.cmd("Assign Macro 1." ..number ..".1 /cmd=\"SetUserVar $" ..makerVar .." = " ..maker.util.pack({userName, plugin, maker.util.underVer(name, "Sequence")}) .."\"") gma.cmd("Assign Macro 1." ..number ..".2 /wait=0.1") gma.cmd("Assign Macro 1." ..number ..".3 /cmd=\"Plugin CALLER\"") end -- ==== END OF maker.edit.plugin ========================================================= -- ==== maker.delete.plugin ============================================================== -- Description: -- -- Inputs: -- number -- what macro number do you want to place this in -- ======================================================================================= function maker.delete.plugin(number) gma.cmd("Delete Macro " ..number .." /nc") end -- ==== END OF maker.delete.plugin ======================================================= -- ==== maker.copy.plugin ================================================================ -- Description: -- -- Inputs: -- source -- which one to copy -- destination -- new macro to create -- ======================================================================================= function maker.copy.plugin(source, destination) gma.cmd("Copy Macro " ..source .." At " ..destination .." /nc") end -- ==== END OF maker.copy.plugin ========================================================= -- ==== maker.move.plugin ================================================================ -- Description: -- -- Inputs: -- source -- macro to move -- destination -- where to make macro land -- ======================================================================================= function maker.move.plugin(source, destination) gma.cmd("Move Macro " ..source .." At " ..destination) end -- ==== END OF maker.move.plugin ========================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================== SEQUENCE ===== -- ==== maker.create.sequence ============================================================ -- Description: -- -- Inputs: -- number -- what sequence number do you want to place this in -- name -- label name for the sequence -- group -- what group to use -- ======================================================================================= function maker.create.sequence(number, name, group) --gma.cmd("BlindEdit On") maker.util.group(group) gma.cmd("Store Sequence " ..number .." Cue 1") gma.cmd("ClearAll") --gma.sleep(0.1) gma.cmd("Store Sequence " ..number .." Cue 2 /o") gma.cmd("Label Sequence " ..number .." \"" ..maker.util.underVer(name, "Sequence") .."\"") gma.cmd("Label Sequence " ..number .." Cue 1 \"S - " ..maker.util.underVer(name, "Macro"):gsub(" V%d+" , "") .."\"") gma.cmd("Appearance Sequence " ..number .." Cue 1 /r=50.2 /g=36.9 /b=0") gma.cmd("Assign Sequence " ..number .." Cue 1 /MIB=Early /Info=\"HL: %\"") --gma.cmd("BlindEdit Off") end -- ==== END OF maker.create.sequence ===================================================== -- ==== maker.edit.sequence ============================================================== -- Description: -- -- Inputs: -- number -- what sequence number do you want to place this in -- name -- label name for the sequence -- ======================================================================================= function maker.edit.sequence(number, name) gma.cmd("Label Sequence " ..number .." \"" ..maker.util.underVer(name, "Sequence") .."\"") gma.cmd("Label Sequence " ..number .." Cue 1 \"S - " ..string.gsub(maker.util.underVer(name, "Macro"), " V%d+" , "")) end -- ==== END OF maker.edit.sequence ======================================================= -- ==== maker.delete.sequence ============================================================ -- Description: -- -- Inputs: -- number -- what sequence number do you want to place this in -- ======================================================================================= function maker.delete.sequence(number) gma.cmd("Delete Sequence " ..number .." /nc") end -- ==== END OF maker.delete.sequence ===================================================== -- ==== maker.copy.sequence ============================================================== -- Description: -- -- Inputs: -- source -- which one to copy -- destination -- new sequence to create -- ======================================================================================= function maker.copy.sequence(source, destination) gma.cmd("Copy Sequence " ..source .." At " ..destination .." /nc") end -- ==== END OF maker.copy.sequence ======================================================= -- ==== maker.move.sequence ============================================================== -- Description: -- -- Inputs: -- source -- sequence to move -- destination -- where to make sequence land -- ======================================================================================= function maker.move.sequence(source, destination) gma.cmd("Move Sequence " ..source .." At " ..destination) end -- ==== END OF maker.move.sequence ======================================================= -- ======================================================================================= -- ======================================================================================= -- ========================================================================== EFFECT ===== -- ==== maker.create.effect ============================================================== -- Description: -- -- Inputs: -- number -- what effect number do you want to place this in -- name -- label name for the effect -- ======================================================================================= function maker.create.effect(number, name) --gma.cmd("BlindEdit On") gma.cmd("ClearAll") gma.cmd("Store Effect " ..number .." /o") gma.cmd("Label Effect " ..number .." \"" ..maker.util.underVer(name, "Macro") .."\"") --gma.cmd("BlindEdit Off") end -- ==== END OF maker.create.effect ======================================================= -- ==== maker.edit.effect ================================================================ -- Description: -- -- Inputs: -- number -- what effect number do you want to place this in -- name -- label name for the effect -- ======================================================================================= function maker.edit.effect(number, name) gma.cmd("Label Effect " ..number .." \"" ..name .."\"") end -- ==== END OF maker.edit.effect ========================================================= -- ==== maker.delete.effect ============================================================== -- Description: -- -- Inputs: -- number -- what effect number do you want to place this in -- ======================================================================================= function maker.delete.effect(number) gma.cmd("Delete Effect " ..number .." /nc") end -- ==== END OF maker.delete.effect ======================================================= -- ==== maker.copy.effect ================================================================ -- Description: -- -- Inputs: -- source -- which one to copy -- destination -- new effect to create -- ======================================================================================= function maker.copy.effect(source, destination) gma.cmd("Copy Effect " ..source .." At " ..destination .." /nc") end -- ==== END OF maker.copy.effect ========================================================= -- ==== maker.move.effect ================================================================ -- Description: -- -- Inputs: -- source -- effect to move -- destination -- where to make effect land -- ======================================================================================= function maker.move.effect(source, destination, poolSize) gma.cmd("Move Effect " ..source .." Thru " ..(source + (poolSize - 2)) .." At " ..destination) end -- ==== END OF maker.move.effect ========================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================== TIMECODE ===== -- ==== maker.create.timecode ============================================================ -- Description: -- -- Inputs: -- number -- what timecode number do you want to place this in -- name -- label name for the timecode -- ======================================================================================= function maker.create.timecode(number, name) --gma.cmd("BlindEdit On") gma.cmd("Store Timecode " ..number) gma.cmd("Label Timecode " ..number .." \"" ..maker.util.underVer(name, "Macro") .."\"") --gma.cmd("BlindEdit Off") end -- ==== END OF maker.create.timecode ===================================================== -- ==== maker.edit.timecode ============================================================== -- Description: -- -- Inputs: -- number -- what timecode number do you want to place this in -- name -- label name for the timecode -- ======================================================================================= function maker.edit.timecode(number, name) gma.cmd("Label Timecode " ..number .." \"" ..name .."\"") end -- ==== END OF maker.edit.timecode ======================================================= -- ==== maker.delete.timecode ============================================================ -- Description: -- -- Inputs: -- number -- what timecode number do you want to place this in -- ======================================================================================= function maker.delete.timecode(number) gma.cmd("Delete Timecode " ..number .." /nc") end -- ==== END OF maker.delete.timecode ===================================================== -- ==== maker.copy.timecode ============================================================== -- Description: -- -- Inputs: -- source -- which one to copy -- destination -- new timecode to create -- ======================================================================================= function maker.copy.timecode(source, destination) gma.cmd("Copy Timecode " ..source .." At " ..destination .." /nc") end -- ==== END OF maker.copy.timecode ======================================================= -- ==== maker.move.timecode ============================================================== -- Description: -- -- Inputs: -- source -- timecode to move -- destination -- where to make timecode land -- ======================================================================================= function maker.move.timecode(source, destination) gma.cmd("Move Timecode " ..source .." At " ..destination) end -- ==== END OF maker.copy.timecode ======================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================================= -- ======================================================================================= -- ==== maker.manage ===================================================================== -- Description: -- -- Inputs: -- option -- Action wanted from SONGS or ADDONS -- user -- Table of information for SONGS and ADDONS -- number -- Choose workspace of either SONGS or ADDONS -- arg1 -- argument 1 -- arg2 -- argument 2 -- -- Output: {...} or false if option/addon could not be found -- ======================================================================================= function maker.manage(option, user, number, arg1, arg2) -- ===== MAKER ======================================================================= if ("MAKER" == string.upper(user.name[number])) then if(option:upper() == "INC") then local compensate = 0 if (0 == math.fmod(arg1 + arg2 , user.pool_size)) and (0 < arg1) then if(arg2 == 0) then arg2 = 1 end if(arg2 > 0) then compensate = 1 elseif(arg2 < 0) then compensate = -1 end end if(arg2 == 0) then arg2 = 1 end return arg1 + arg2 + compensate; elseif(option:upper() == "CURRENT") then if (0 == math.fmod(arg1, user.pool_size)) then return arg1 + 1 else return arg1 end elseif(option:upper() == "CREATE") then maker.create.plugin(arg2, arg1, user.name[number], user.self) elseif(option:upper() == "EDIT" ) then maker.edit.plugin(arg2, arg1, user.name[number], user.self) elseif(option:upper() == "DELETE") then maker.delete.plugin(arg1) elseif(option:upper() == "COPY" ) then maker.copy.plugin(arg1, arg2) elseif(option:upper() == "MOVE" ) then maker.move.plugin(arg1, arg2) elseif(option:upper() == "POOL" ) then return "Macro", "Plugin" else return false end -- ===== ADDER ======================================================================= elseif ("ADDER" == string.upper(user.name[number])) then if(option:upper() == "INC") then local compensate = 0 if (0 == math.fmod(arg1 + arg2 , user.pool_size)) and (0 < arg1) then if(arg2 == 0) then arg2 = 1 end if(arg2 > 0) then compensate = 1 elseif(arg2 < 0) then compensate = -1 end end if(arg2 == 0) then arg2 = 1 end return arg1 + arg2 + compensate; elseif(option:upper() == "CURRENT") then if (0 == math.fmod(arg1, user.pool_size)) then return arg1 + 1 else return arg1 end elseif(option:upper() == "CREATE") then maker.create.plugin(arg2, arg1, user.name[number], user.self) elseif(option:upper() == "EDIT" ) then maker.edit.plugin(arg2, arg1, user.name[number], user.self) elseif(option:upper() == "DELETE") then maker.delete.plugin(arg1) elseif(option:upper() == "COPY" ) then maker.copy.plugin(arg1, arg2) elseif(option:upper() == "MOVE" ) then maker.move.plugin(arg1, arg2) elseif(option:upper() == "POOL" ) then return "Macro", "Plugin" else return false end -- ===== SONGS ======================================================================= elseif ("SONGS" == string.upper(user.name[number])) then if(option:upper() == "INC") then local compensate = 0 if (0 == math.fmod(arg1 + arg2 , user.pool_size)) and (0 < arg1) then if(arg2 == 0) then arg2 = 1 end if(arg2 > 0) then compensate = 1 elseif(arg2 < 0) then compensate = -1 end end if(arg2 == 0) then arg2 = 1 end return arg1 + arg2 + compensate; elseif(option:upper() == "CURRENT") then if (0 == math.fmod(arg1, user.pool_size)) then return arg1 + 1 else return arg1 end elseif(option:upper() == "CREATE") then maker.create.sequence(arg2, arg1, user.group) elseif(option:upper() == "EDIT" ) then maker.edit.sequence(arg2, arg1) elseif(option:upper() == "DELETE") then maker.delete.sequence(arg1) elseif(option:upper() == "COPY" ) then maker.copy.sequence(arg1, arg2) elseif(option:upper() == "MOVE" ) then maker.move.sequence(arg1, arg2) elseif(option:upper() == "POOL" ) then return "Sequence", "Sequence" else return false end -- ===== EFFECT ====================================================================== elseif ("EFFECT" == string.upper(user.name[number])) then if(option:upper() == "INC") then local compensate = 1 if (arg1 == 0) then compensate = 0 end if(arg2 == 0) then arg2 = 1 end return (((math.floor(arg1/user.pool_size)) * user.pool_size) + (user.pool_size * arg2)) + compensate elseif(option:upper() == "CURRENT") then return (((math.floor(arg1/user.pool_size)) * user.pool_size)) + 1 elseif(option:upper() == "CREATE") then maker.create.effect(arg2, arg1) elseif(option:upper() == "EDIT" ) then maker.edit.effect(arg2, arg1) elseif(option:upper() == "DELETE") then maker.delete.effect(arg1) elseif(option:upper() == "COPY" ) then maker.copy.effect(arg1, arg2) elseif(option:upper() == "MOVE" ) then maker.move.effect(arg1, arg2, user.pool_size) elseif(option:upper() == "POOL" ) then return "Effect", nil else return false end -- ===== TIMECODE ==================================================================== elseif ("TIMECODE" == string.upper(user.name[number])) then if(option:upper() == "INC") then if(arg2 == 0) then arg2 = 1 end return arg1 + arg2 elseif(option:upper() == "CURRENT") then return arg1 elseif(option:upper() == "CREATE") then maker.create.timecode(arg2, arg1) elseif(option:upper() == "EDIT" ) then maker.edit.timecode(arg2, arg1) elseif(option:upper() == "DELETE") then maker.delete.timecode(arg1) elseif(option:upper() == "COPY" ) then maker.copy.timecode(arg1, arg2) elseif(option:upper() == "MOVE" ) then maker.move.timecode(arg1, arg2) elseif(option:upper() == "POOL" ) then return "Timecode", nil else return false end else return false; end return true; end -- ==== END OF maker.manage ==============================================================
require "guild" function post() if not session:isLogged() then http:redirect("/") return end local guild = db:singleQuery("SELECT name, ownerid, id FROM guilds WHERE name = ?", http.postValues["guild-name"]) if guild == nil then http:redirect("/") return end if not isGuildOwner(session:loggedAccount().ID, guild) then http:redirect("/") return end http:parseMultiPartForm() local logoImage = http:formFile("guild-logo") if logoImage == nil then session:setFlash("validationError", "Invalid logo image") http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name)) return end if not logoImage:isValidPNG() then session:setFlash("validationError", "Logo image can only be png") http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name)) return end logoImage:saveFileAsPNG("public/images/guild-images/" .. guild.name .. ".png", 64, 64) session:setFlash("success", "Logo updated") http:redirect("/subtopic/community/guilds/view?name=" .. url:encode(guild.name)) end
--[[ Mojang Session API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) OpenAPI spec version: 2020-06-05 Generated by: https://openapi-generator.tech ]] --[[ Unit tests for openapiclient.model.player_profile_texture_property_value Automatically generated by openapi-generator (https://openapi-generator.tech) Please update as you see appropriate ]] describe("player_profile_texture_property_value", function() local openapiclient_player_profile_texture_property_value = require "openapiclient.model.player_profile_texture_property_value" -- unit tests for the property 'timestamp' describe("property timestamp test", function() it("should work", function() -- TODO assertion here: http://olivinelabs.com/busted/#asserts end) end) -- unit tests for the property 'profile_id' describe("property profile_id test", function() it("should work", function() -- TODO assertion here: http://olivinelabs.com/busted/#asserts end) end) -- unit tests for the property 'profile_name' describe("property profile_name test", function() it("should work", function() -- TODO assertion here: http://olivinelabs.com/busted/#asserts end) end) -- unit tests for the property 'signature_required' describe("property signature_required test", function() it("should work", function() -- TODO assertion here: http://olivinelabs.com/busted/#asserts end) end) -- unit tests for the property 'textures' describe("property textures test", function() it("should work", function() -- TODO assertion here: http://olivinelabs.com/busted/#asserts end) end) end)
local PLAYER = FindMetaTable("Player") if SERVER then function PLAYER:SetHuman() self:SetTeam(TEAM_HUMANS) self:AllowFlashlight(true) player_manager.SetPlayerClass(self, "player_ritual_human") end function PLAYER:SetDemon() self:SetTeam(TEAM_DEMONS) self:AllowFlashlight(false) player_manager.SetPlayerClass(self, "player_ritual_demon") end end function PLAYER:IsHuman() return self:Team() == TEAM_HUMANS end function PLAYER:IsDemon() return self:Team() == TEAM_DEMONS end local bonestocheck = { "ValveBiped.Bip01_Head1", "ValveBiped.Bip01_Pelvis", } function PLAYER:VisibleTo(ply, c, mask) local epos = c and CLIENT and EyePos() or ply:EyePos() for k,v in pairs(bonestocheck) do local bid = self:LookupBone(v) if bid then local tr = util.TraceLine({ start = epos, endpos = self:GetBonePosition(bid), mask = mask or MASK_SHOT, filter = ply, }) if tr.Entity == self then return true, tr end end end return false end function PLAYER:CanSee(ply, c) return ply:VisibleTo(self, c) end if SERVER then util.AddNetworkString("ritual_progress") -- Networked to cl_hud.lua function PLAYER:DisplayProgress(time, start) net.Start("ritual_progress") net.WriteBool(true) net.WriteFloat(time) if start then net.WriteBool(true) net.WriteFloat(start) else net.WriteBool(false) end net.Send(self) end function PLAYER:HideProgress() net.Start("ritual_progress") net.WriteBool(false) net.Send(self) end end
-- 首先继承Controller基类 local Index_Controller = Controller:new() function Index_Controller:indexAction() ngx.say('Hello,MicroMVC') return true end return Index_Controller
-- Petit script pour configurer les choses secrètes que l'on n'aimerait -- pas être exportées sur Internet (github) -- faut donc le mettre ailleurs que dans le dépôt ! print("\n credential.lua zf181205.1910 \n") cli_ssid="3g-s7" cli_pwd="12234567"
return PlaceObj("ModDef", { "title", "Fix Projector Lamp", "id", "ChoGGi_FixProjectorLamp", "lua_revision", 1007000, -- Picard "steam_id", "2387107341", "pops_any_uuid", "d1288e04-d8e6-41a6-b4ba-5a0e84d4c1ac", "version", 1, "version_major", 0, "version_minor", 1, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, "TagBuildings", true, "TagOther", true, "description", [[For some reason the devs put it in the Decorations instead of the Outside Decorations category. This mod moves it to the correct category. ]], })
object_draft_schematic_furniture_furniture_table_jedi_dark_s01 = object_draft_schematic_furniture_shared_furniture_table_jedi_dark_s01:new { } ObjectTemplates:addTemplate(object_draft_schematic_furniture_furniture_table_jedi_dark_s01, "object/draft_schematic/furniture/furniture_table_jedi_dark_s01.iff")
local BasePlugin = require "kong.plugins.base_plugin" local host = os.getenv("SPLUNK_HOST") --Ex: gateway-datacenter.company.com local KongClusterDrain = BasePlugin:extend() KongClusterDrain.PRIORITY = 3 --The standard request termination plugin is 2 so we need to run before that and beat it out in priority. KongClusterDrain.VERSION = "1.1.0" function KongClusterDrain:new() KongClusterDrain.super.new(self, "kong-cluster-drain") end function KongClusterDrain:access(conf) KongClusterDrain.super.access(self) if conf.hostname == host then --If host has been set check if match and start throwing http status for maintenance return kong.response.exit(503, { message = "Scheduled Maintenance" }) end return --If no match on host then just return end return KongClusterDrain
--[[ A top-down action game made with Bitty Engine Copyright (C) 2021 Tony Wang, all rights reserved Engine page: https://paladin-t.github.io/bitty/ Game page: https://paladin-t.github.io/games/hb/ ]] Tips = class({ --[[ Variables. ]] _game = nil, _content = nil, --[[ Constructor. ]] ctor = function (self, options) Object.ctor(self, nil, nil, nil) self._game = options.game end, --[[ Meta methods. ]] __tostring = function (self) return 'Tips' end, --[[ Methods. ]] content = function (self) return self._content end, setContent = function (self, content) self._content = content return self end, behave = function (self, delta, _1) return self end, update = function (self, delta) if self._game.state.playing then font(FONT_NORMAL_TEXT) local txt = self._content local textWidth, textHeight = measure(txt, FONT_NORMAL_TEXT) text(txt, self.x - textWidth * 0.5 + 1, self.y - textHeight - 15, Color.new(0, 0, 0)) text(txt, self.x - textWidth * 0.5, self.y - textHeight - 16, COLOR_CLEAR_TEXT) font(nil) end end }, Object)
local _, TIC = ... TIC:RegisterEvent("BAG_UPDATE_DELAYED") local bags = {0, -1, -2, -3, -4} local temp = {} function TIC:BAG_UPDATE_DELAYED() wipe(temp) -- count items in bags for bag = 0, 4 do for slot = 1, GetContainerNumSlots(bag) do local icon, itemCount, locked, quality, readable, lootable, itemLink, isFiltered, noValue, itemID = GetContainerItemInfo(bag, slot) if itemID then if not temp[itemID] then temp[itemID] = {} temp[itemID][1] = itemCount temp[itemID][2] = string.match(itemLink, "|h%[(.+)%]|h") temp[itemID][3] = "|T" .. icon .. ":0|t" temp[itemID][4] = quality else temp[itemID][1] = temp[itemID][1] + itemCount end end end end -- count bags for _, slot in ipairs(bags) do local icon, itemCount, locked, quality, readable, lootable, itemLink, isFiltered, noValue, itemID = GetContainerItemInfo(0, slot) if itemID then if not temp[itemID] then temp[itemID] = {} temp[itemID][1] = itemCount temp[itemID][2] = string.match(itemLink, "|h%[(.+)%]|h") temp[itemID][3] = "|T" .. icon .. ":0|t" temp[itemID][4] = quality else temp[itemID][1] = temp[itemID][1] + itemCount end end end -- save TIC:Save(temp, "bags") end
--[[-------------------------------------------------------------------- Grid Compact party and raid unit frames. Copyright (c) 2006-2009 Kyle Smith (Pastamancer) Copyright (c) 2009-2016 Phanx <addons@phanx.net> All rights reserved. See the accompanying LICENSE file for details. https://github.com/Phanx/Grid https://mods.curse.com/addons/wow/grid http://www.wowinterface.com/downloads/info5747-Grid.html ------------------------------------------------------------------------ Group.lua Grid status module for group leader, assistant, and master looter. ----------------------------------------------------------------------]] local _, Grid = ... local L = Grid.L local Roster = Grid:GetModule("GridRoster") local GetLootMethod, UnitAffectingCombat, UnitIsGroupAssistant, UnitIsGroupLeader, UnitIsUnit = GetLootMethod, UnitAffectingCombat, UnitIsGroupAssistant, UnitIsGroupLeader, UnitIsUnit local GridStatusName = Grid:NewStatusModule("GridStatusGroup") GridStatusName.menuName = L["Group"] GridStatusName.options = false GridStatusName.defaultDB = { leader = { enable = true, priority = 1, text = L["Group Leader ABBREVIATION"], color = { r = 0.65, g = 0.65, b = 1, a = 1, ignore = true }, hideInCombat = true, }, assistant = { enable = true, priority = 1, text = L["Group Assistant ABBREVIATION"], color = { r = 1, g = 0.75, b = 0.5, a = 1, ignore = true }, hideInCombat = true, }, master_looter = { enable = true, priority = 1, text = L["Master Looter ABBREVIATION"], color = { r = 1, g = 1, b = 0.4, a = 1, ignore = true }, hideInCombat = true, }, } function GridStatusName:PostInitialize() self:RegisterStatus("leader", L["Group Leader"]) self:RegisterStatus("assistant", L["Group Assistant"]) self:RegisterStatus("master_looter", L["Master Looter"]) end function GridStatusName:OnStatusEnable(status) self:RegisterEvent("GROUP_ROSTER_UPDATE", "UpdateAllUnits") self:RegisterEvent("PARTY_LEADER_CHANGED", "UpdateAllUnits") self:RegisterEvent("PARTY_LOOT_METHOD_CHANGED", "UpdateAllUnits") for status, settings in pairs(self.db.profile) do if settings.hideInCombat then self:RegisterEvent("PLAYER_REGEN_DISABLED", "UpdateAllUnits") self:RegisterEvent("PLAYER_REGEN_ENABLED", "UpdateAllUnits") break end end self:UpdateAllUnits("OnStatusEnable") end function GridStatusName:OnStatusDisable(status) if not self.db.profile[status] then return end local enable, combat for status, settings in pairs(self.db.profile) do if settings.enable then enable = true end if settings.hideInCombat then enable = true end end if not combat then self:UnregisterEvent("PLAYER_REGEN_DISABLED") self:UnregisterEvent("PLAYER_REGEN_ENABLED") end if not enable then self:UnregisterEvent("GROUP_ROSTER_UPDATE") self:UnregisterEvent("PARTY_LEADER_CHANGED") self:UnregisterEvent("PARTY_LOOT_METHOD_CHANGED") end self.core:SendStatusLostAllUnits(status) end function GridStatusName:UpdateAllUnits() local inCombat = UnitAffectingCombat("player") local leaderDB = self.db.profile.leader local assistantDB = self.db.profile.assistant local looterDB = self.db.profile.master_looter local looter if looterDB.enable and not (inCombat and looterDB.hideInCombat) then local method, pID, rID = GetLootMethod() if method == "master" then if rID then looter = "raid"..rID elseif pID then looter = pID == 0 and "player" or "party"..pID end end end if not looter then self.core:SendStatusLostAllUnits("master_looter") end for guid, unit in Roster:IterateRoster() do local isLeader = UnitIsGroupLeader(unit) if isLeader and leaderDB.enable and not (inCombat and leaderDB.hideInCombat) then self.core:SendStatusGained(guid, "leader", leaderDB.priority, nil, leaderDB.color, leaderDB.text, nil, nil, "Interface\\GroupFrame\\UI-Group-LeaderIcon" ) else self.core:SendStatusLost(guid, "leader") end if not isLeader and assistantDB.enable and UnitIsGroupAssistant(unit) and not (inCombat and assistantDB.hideInCombat) then self.core:SendStatusGained(guid, "assistant", assistantDB.priority, nil, assistantDB.color, assistantDB.text, nil, nil, "Interface\\GroupFrame\\UI-Group-AssistantIcon" ) else self.core:SendStatusLost(guid, "assistant") end if looter and UnitIsUnit(unit, looter) then self.core:SendStatusGained(guid, "master_looter", looterDB.priority, nil, looterDB.color, looterDB.text, nil, nil, "Interface\\GroupFrame\\UI-Group-MasterLooter" ) else self.core:SendStatusLost(guid, "master_looter") end end end
-- main tab VERSION = "1.2" UI.Label("Config version: " .. VERSION) UI.Separator() --local atk = Panels.FastAttack() UI.Button("Ingame macro editor", function(newText) UI.MultilineEditorWindow(storage.ingame_macros_main or "", {title="Macro editor", description="You can add your custom macros (or any other lua code) here"}, function(text) storage.ingame_macros_main = text reload() end) end) UI.Button("Ingame hotkey editor", function(newText) UI.MultilineEditorWindow(storage.ingame_hotkeys_main or "", {title="Hotkeys editor", description="You can add your custom hotkeys/singlehotkeys here"}, function(text) storage.ingame_hotkeys_main = text reload() end) end) UI.Separator() UI.Label("Armada Macros") dofile("/armada/default.lua") UI.Separator() UI.Label("Ingame Macros") for _, scripts in ipairs({storage.ingame_macros_main, storage.ingame_hotkeys_main}) do if type(scripts) == "string" and scripts:len() > 3 then local status, result = pcall(function() assert(load(scripts, "ingame_editor"))() end) if not status then error("Ingame edior error:\n" .. result) end end end UI.Separator() UI.Label("Links") UI.Button("Discord", function() g_platform.openUrl("https://discord.gg/2Z8Xupw") end) UI.Button("Donaciones", function() g_platform.openUrl("http://armada-azteca.com/azteca/donaciones") end) UI.Button("Wiki", function() g_platform.openUrl("http://armada-azteca.com/wiki") end)
local fastsplit = require("quantization.fastsplit") local palette = require("quantization.palette") local utils = require("utils") local draw = {} local PALETTE_CHARS = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"} local function TO_PALETTE_CHARS(i) return PALETTE_CHARS[i] end function draw.slice_image(image) local slices = {} for i = 1, image.size.y do local start = 1 + image.size.x * (i - 1) local finish = start + image.size.x - 1 slices[i] = fastsplit.slice(image.data, start, finish) end return slices end function draw.concat_hex(slices) return utils.map(function(slice) return table.concat(utils.map(TO_PALETTE_CHARS, slice)) end, slices) end function draw.draw_image(image, x, y) draw.set_palette(image.palette) local x = x or 1 local y = y or 1 local lines = draw.concat_hex(draw.slice_image(image)) local blank = (" "):rep(image.size.x) for i = 1, #lines do term.setCursorPos(x, y + i - 1) term.blit(blank, blank, lines[i]) end end function draw.set_palette(palette) for i, v in pairs(palette) do term.setPaletteColour(math.pow(2, i - 1), v.x, v.y, v.z) end end function draw.default_palette() draw.set_palette(palette.default()) end return draw
local Time = require "module.Time" local View = {} function View:Start(data) self.view = CS.SGK.UIReference.Setup(self.gameObject) self.AwardData = {} self.offlineAwardData = nil; self.nguiDragIconScript = self.view.ScrollView[CS.UIMultiScroller] self.nguiDragIconScript.RefreshIconCallback = (function (go,idx) --ERROR_LOG(sprinttb(self.AwardData[idx +1])) local objView = CS.SGK.UIReference.Setup(go) objView.read:SetActive(true) objView.name[UnityEngine.UI.Text].text = self.AwardData[idx +1][2] local s_time= os.date("*t",Time.now()) objView.time[UnityEngine.UI.Text].text = s_time.year.."."..s_time.month.."."..s_time.day objView.iconGrod[2]:SetActive(false) objView[CS.UGUIClickEventListener].enabled = true objView[CS.UGUIClickEventListener].onClick = (function () objView[CS.UGUIClickEventListener].enabled = false if self.AwardData[idx + 1][1] ~= 1 then utils.NetworkService.Send(195,{nil,self.AwardData[idx + 1][1]}) else self:ShowOfflineAward() end end) go:SetActive(true) end) self.AwardData = module.AwardModule.GetAward() self.nguiDragIconScript.DataCount = #self.AwardData self.view.getBtn[CS.UGUIClickEventListener].onClick = (function( ... ) for i = 1,#self.AwardData do if self.AwardData[i][1] ~= 1 then utils.NetworkService.Send(195,{nil,self.AwardData[i][1]}) else if self.offlineAwardData == nil then self:GetOfflineAwardData(); end module.AwardModule.GetOfflineAward(self.offlineAwardData[1].time, true) end end end) self:GetOfflineAwardData(); end function View:GetOfflineAwardData() local offlineAward = module.AwardModule.GetOfflineAwardList(); if offlineAward[3] then local list = offlineAward[3]; local awardList = {}; for i,v in ipairs(list) do if awardList[v[1]] == nil then awardList[v[1]] = {}; end local info = {}; info.drop_id = v[2]; info.count = v[3]; table.insert(awardList[v[1]], info) end local sortList = {} for k,v in pairs(awardList) do local info = {}; info.time = k; info.list = v; table.insert(sortList, info); end table.sort(sortList, function ( a,b ) return a.time < b.time; end) self.offlineAwardData = sortList; end -- print("奖励列表", sprinttb(self.offlineAwardData)) end function View:ShowOfflineAward() if self.offlineAwardData == nil then self:GetOfflineAwardData(); end if #self.offlineAwardData ~= 0 then DialogStack.PushPrefStact("OfflineAward", {list = self.offlineAwardData}, self.view.gameObject) end end function View:listEvent() return { "NOTIFY_REWARD_CHANGE", } end function View:onEvent(event,data) if event == "NOTIFY_REWARD_CHANGE" then self.AwardData = module.AwardModule.GetAward() if #self.AwardData > 0 then self.nguiDragIconScript.DataCount = #self.AwardData else DispatchEvent("KEYDOWN_ESCAPE") end if self.offlineAwardData ~= nil then self:GetOfflineAwardData(); end end end return View
local Stream = require("stream") local function compress(stream) return Stream(stream.dumpString()) end return compress
object_tangible_tcg_series5_hangar_ships_imperial_gunboat = object_tangible_tcg_series5_hangar_ships_shared_imperial_gunboat:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series5_hangar_ships_imperial_gunboat, "object/tangible/tcg/series5/hangar_ships/imperial_gunboat.iff")
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- Control Hammerspoon's dock icon -- -- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). ---@class hs.dockicon local M = {} hs.dockicon = M -- Bounce Hammerspoon's dock icon -- -- Parameters: -- * indefinitely - A boolean value, true if the dock icon should bounce until the dock icon is clicked, false if the dock icon should only bounce briefly -- -- Returns: -- * None function M.bounce(indefinitely, ...) end -- Hide Hammerspoon's dock icon -- -- Parameters: -- * None -- -- Returns: -- * None function M.hide() end -- Set Hammerspoon's dock icon badge -- -- Parameters: -- * badge - A string containing the label to place inside the dock icon badge. If the string is empty, the badge will be cleared -- -- Returns: -- * None function M.setBadge(badge, ...) end -- Make Hammerspoon's dock icon visible -- -- Parameters: -- * None -- -- Returns: -- * None function M.show() end -- Get or set a canvas object to be displayed as the Hamemrspoon dock icon -- -- Parameters: -- * `canvas` - an optional `hs.canvas` object specifying the canvas to be displayed as the dock icon for Hammerspoon. If an explicit `nil` is specified, the dock icon will revert to the Hammerspoon application icon. -- -- Returns: -- * If the dock icon is assigned a canvas object, that canvas object will be returned, otherwise returns nil. -- -- Notes: -- * If you update the canvas object by changing any of its components, it will not be reflected in the dock icon until you invoke [hs.dockicon.tileUpdate](#tileUpdate). function M.tileCanvas(canvas, ...) end -- Returns a table containing the size of the tile representing the dock icon. -- -- Parameters: -- * None -- -- Returns: -- * a table containing the size of the tile representing the dock icon for Hammerspoon. This table will contain `h` and `w` keys specifying the tile height and width as numbers. -- -- Notes: -- * the size returned specifies the display size of the dock icon tile. If your canvas item is larger than this, then only the top left portion corresponding to the size returned will be displayed. function M.tileSize() end -- Force an update of the dock icon. -- -- Parameters: -- * None -- -- Returns: -- * None -- -- Notes: -- * Changes made to a canvas object are not reflected automatically like they are when a canvas is being displayed on the screen; you must invoke this method after making changes to the canvas for the updates to be reflected in the dock icon. function M.tileUpdate() end -- Determine whether Hammerspoon's dock icon is visible -- -- Parameters: -- * None -- -- Returns: -- * A boolean, true if the dock icon is visible, false if not ---@return boolean function M.visible() end
Locales['fr'] = { ['skin_menu'] = 'Skin Menu', ['use_rotate_view'] = 'utilisez ~INPUT_VEH_FLY_ROLL_LEFT_ONLY~ et ~INPUT_VEH_FLY_ROLL_RIGHT_ONLY~ pour tourner la vue.', ['skin'] = 'changer de skin', ['saveskin'] = 'sauvegarder skin dans un fichier', ['confirm_escape'] = 'voulez-vous annuler le changeur de skin? Toutes les modifications ne sont pas enregistrées.', ['no'] = 'non', ['yes'] = 'oui', }
-- local log = require "log" local hutype = require "chestnut.mahjongroom.hutype" local function check_qidui(cards, ... ) -- body assert(cards and #cards > 0) local qing = true local jiang = 0 local gang = 0 local single = 0 local len = #cards local idx = 1 local a = cards[idx] idx = idx + 1 while idx <= len do if idx > len then single = single + 1 break end local b = cards[idx] idx = idx + 1 if b:eq(a) then if idx <= len then local c = cards[idx] idx = idx + 1 if a:eq(c) then if idx <= len then local d = cards[idx] idx = idx + 1 if d:eq(c) then jiang = jiang + 2 gang = gang + 1 if idx <= len then local e = cards[idx] idx = idx + 1 if e:tof() ~= a:tof() then qing = false end a = e else break end else jiang = jiang + 1 single = single + 1 if d:tof() ~= c:tof() then qing = false end a = d end else break end else if a:tof() ~= c:tof() then qing = false end jiang = jiang + 1 a = c end else jiang = jiang + 1 break end else single = single + 1 if b:tof() ~= a:tof() then qing = false end a = b end end local res = {} res.qing = qing res.jiang = jiang res.gang = gang res.single = single return res end local function check_qidui_hu(cards, ... ) -- body assert(cards and #cards > 0) local args = check_qidui(cards) local qing = args.qing local jiang = args.jiang local gang = args.gang local single = args.single local res = {} res.gang = gang if jiang == 7 and qing and gang >= 1 then res.code = hutype.QINGLONGQIDUI elseif jiang == 7 and qing then res.code = hutype.QINGQIDUI elseif jiang == 7 and gang >= 1 then res.code = hutype.LONGQIDUI elseif jiang == 7 then res.code = hutype.QIDUI else res.code = hutype.NONE end return res end local function check_qidui_jiao(cards, ... ) -- body assert(cards and #cards > 0) local args = check_qidui(cards) local qing = args.qing local jiang = args.jiang local gang = args.gang local single = args.single local res = {} res.gang = gang if qing and jiang == 6 and single == 1 and gang >= 1 then res.code = hutype.QINGLONGQIDUI elseif qing and jiang == 6 and single == 1 then res.code = hutype.QINGQIDUI elseif jiang == 6 and single == 1 and gang >= 1 then res.code = hutype.LONGQIDUI elseif jiang == 6 and single == 1 then res.code = hutype.QIDUI else res.code = hutype.NONE end return res end local function check_put(putcards, ... ) -- body assert(putcards and #putcards > 0) local qing = true local gang = 0 local ctype = putcards[1].cards[1]:tof() for k,v in pairs(putcards) do if v.cards[1]:tof() ~= ctype then qing = false end if #v.cards == 4 then gang = gang + 1 end end local res = {} res.qing = qing res.gang = gang res.ctype = ctype return res end local function check_sichuan(cards, putcards, ... ) -- body local qing = true local jiang = 0 local tong3 = 0 local lian3 = 0 local single = 0 local lian2 = 0 local ge2 = 0 local gang = 0 local len = #cards local idx = 1 local a = cards[idx] idx = idx + 1 while idx <= len do if idx > len then single = single + 1 break end local b = cards[idx] idx = idx + 1 if b:eq(a) then if idx > len then jiang = jiang + 1 break end local c = cards[idx] idx = idx + 1 if c:eq(a) then if idx > len then tong3 = tong3 + 1 break end local d = cards[idx] idx = idx + 1 if d:eq(a) then if idx > len then jiang = jiang + 1 gang = gang + 1 break end local e = cards[idx] idx = idx + 1 if e:tof() == a:tof() then if e:nof() == a:nof() + 1 then if idx > len then tong3 = tong3 + 1 lian2 = lian2 + 1 gang = gang + 1 break end local f = cards[idx] idx = idx + 1 if f:eq(e) then if idx > len then jiang = jiang + 3 gang = gang + 1 break end local g = cards[idx] idx = idx + 1 if g:tof() == f:tof() then if g:nof() == f:nof() + 1 then if idx > len then jiang = jiang + 3 single = single + 1 gang = gang + 1 break end local h = cards[idx] idx = idx + 1 if h:eq(g) then lian3 = lian3 + 2 jiang = jiang + 1 if idx <= len then local i = cards[idx] idx = idx + 1 if i:tof() ~= a:tof() then qing = false end a = i else break end else jiang = jiang + 3 single = single + 1 gang = gang + 1 if h:tof() ~= g:tof() then qing = false end a = h end else break end else qing = false jiang = jiang + 3 gang = gang + 1 a = g end elseif f:tof() == e:tof() then if f:nof() == e:nof() + 1 then tong3 = tong3 + 1 lian3 = lian3 + 1 gang = gang + 1 if idx <= len then local g = cards[idx] idx = idx + 1 if g:tof() ~= a:tof() then qing = false end a = g else break end else tong3 = tong3 + 1 lian2 = lian2 + 1 gang = gang + 1 a = f end else qing = false tong3 = tong3 + 1 lian2 = lian2 + 1 gang = gang + 1 a = f end else jiang = jiang + 2 gang = gang + 1 a = e end else qing = false jiang = jiang + 2 gang = gang + 1 a = e end elseif d:tof() == a:tof() then if d:nof() == a:nof() + 1 then if idx > len then jiang = jiang + 1 lian2 = lian2 + 1 break end local e = cards[idx] idx = idx + 1 if e:eq(d) then tong3 = tong3 + 1 a = d idx = idx - 1 elseif e:tof() == d:tof() then if e:nof() == d:nof() + 1 then if idx <= len then local f = cards[idx] idx = idx + 1 if f:tof() == e:tof() then if f:nof() == e:nof() + 1 then tong3 = tong3 + 1 lian3 = lian3 + 1 if idx <= len then local g = cards[idx] idx = idx + 1 if g:tof() ~= f:tof() then qing = false end a = g else break end else jiang = jiang + 1 lian3 = lian3 + 1 a = f end else qing = false jiang = jiang + 1 lian3 = lian3 + 1 a = f end else lian3 = lian3 + 1 jiang = jiang + 1 break end else jiang = jiang + 2 gang = gang + 1 a = e end else qing = false jiang = jiang + 2 gang = gang + 1 a = e end else tong3 = tong3 + 1 a = d end else qing = false tong3 = tong3 + 1 a = d end elseif c:tof() == b:tof() then if c:nof() == b:nof() + 1 then if idx > len then jiang = jiang + 1 single = single + 1 break end local d = cards[idx] idx = idx + 1 if d:eq(c) then if idx > len then jiang = jiang + 2 break end local e = cards[idx] idx = idx + 1 if e:eq(d) then if idx > len then jiang = jiang + 1 tong3 = tong3 + 1 break end local f = cards[idx] idx = idx + 1 if f:eq(e) then if idx > len then jiang = jiang + 3 break end local g = cards[idx] idx = idx + 1 if g:tof() == e:tof() then if g:nof() == e:nof() + 1 then if idx < len then jiang = jiang + 3 single = single + 1 break end local h = cards[idx] idx = idx + 1 if h:eq(g) then jiang = jiang + 1 lian3 = lian3 + 2 if idx <= len then local i = cards[idx] if i:tof() ~= a:tof() then qing = false end else break end else jiang = jiang + 3 single = single + 1 a = h end else jiang = jiang + 3 a = g end else qing = false jiang = jiang + 3 a = g end else jiang = jiang + 1 tong3 = tong3 + 1 a = f end elseif e:tof() == d:tof() then if e:nof() == d:nof() + 1 then if idx > len then lian3 = lian3 + 1 lian2 = lian2 + 1 break end local f = cards[idx] idx = idx + 1 if f:eq(e) then lian3 = lian3 + 2 if idx > len then break else local g = cards[idx] idx = idx + 1 if g:tof() ~= f:tof() then qing = false end a = g end else lian3 = lian3 + 1 lian2 = lian2 + 1 if f:tof() ~= e:tof() then qing = false end a = f end else jiang = jiang + 2 a = e end else qing = false jiang = jiang + 2 a = e end elseif d:tof() == c:tof() then if d:nof() == c:nof() + 1 then if idx > len then jiang = jiang + 1 lian2 = lian2 + 1 break end local e = cards[idx] idx = idx + 1 if e:tof() == d:tof() then if e:nof() == d:nof() + 1 then jiang = jiang + 1 lian3 = lian3 + 1 if idx <= len then local f = cards[idx] idx = idx + 1 if f:tof() ~= e:tof() then qing = false end a = f else break end else break end else break end else jiang = jiang + 1 a = c idx = idx - 1 end else qing = false jiang = jiang + 1 a = c idx = idx - 1 end else jiang = jiang + 1 a = c end else qing = false jiang = jiang + 1 a = c end elseif b:tof() == a:tof() then if b:nof() == a:nof() + 1 then if idx > len then lian2 = lian2 + 1 break end local c = cards[idx] idx = idx + 1 if c:eq(b) then if idx <= len then local d = cards[idx] idx = idx + 1 if d:eq(c) then if idx <= len then local e = cards[idx] idx = idx + 1 if e:eq(d) then if idx <= len then local f = cards[idx] idx = idx + 1 if f:tof() == e:tof() then if f:nof() == e:nof() + 1 then tong3 = tong3 + 1 lian3 = lian3 + 1 if idx <= len then local g = cards[idx] idx = idx + 1 if g:tof() ~= a:tof() then qing = false end a = g else break end else break end else break end else break end elseif e:tof() == d:tof() then if e:nof() == d:nof() + 1 then lian3 = lian3 + 1 jiang = jiang + 1 if idx <= len then local f = cards[idx] idx = idx + 1 if f:tof() ~= e:tof() then qing = false end a = f else break end else break end else break end else break end elseif d:tof() == c:tof() then if d:nof() == c:nof() + 1 then if idx <= len then local e = cards[idx] idx = idx + 1 if e:eq(d) then if idx <= len then local f = cards[idx] idx = idx + 1 if f:tof() == e:tof() then if f:nof() == e:nof() + 1 then print("step 1") lian3 = lian3 + 2 if idx <= len then local g = cards[idx] idx = idx + 1 if g:tof() ~= f:tof() then qing = false end a = g else break end else break end else break end else break end else break end else break end else break end end else break end elseif c:tof() == b:tof() then if c:nof() == b:nof() + 1 then if idx <= len then local d = cards[idx] idx = idx + 1 if d:eq(c) then if idx <= len then local e = cards[idx] idx = idx + 1 if e:eq(d) then if idx <= len then local f = cards[idx] idx = idx + 1 if f:eq(e) then lian3 = lian3 + 1 tong3 = tong3 + 1 gang = gang + 1 if idx <= len then local g = cards[idx] idx = idx + 1 if g:tof() ~= a:tof() then qing = false end a = g else break end else lian3 = lian3 + 1 jiang = jiang + 1 if f:tof() ~= a:tof() then qing = false end a = f end else lian3 = lian3 + 1 jiang = jiang + 1 break end else lian3 = lian3 + 1 a = d idx = idx - 1 end else lian2 = lian2 + 1 jiang = jiang + 1 break end else lian3 = lian3 + 1 if d:tof() ~= c:tof() then qing = false end a = d end else lian3 = lian3 + 1 break end else lian2 = lian2 + 1 a = c end else qing = false lian2 = lian2 + 1 a = c end elseif b:nof() == a:nof() + 2 then if idx > len then ge2 = ge2 + 1 break end local c = cards[idx] idx = idx + 1 if c:eq(b) then elseif c:tof() == b:tof() then if c:nof() == b:nof() + 1 then else ge2 = ge2 + 1 a = c end else qing = false ge2 = ge2 + 1 a = c end else single = single + 1 a = b end else qing = false single = single + 1 a = b end end local res = {} res.qing = qing res.jiang = jiang res.tong3 = tong3 res.lian3 = lian3 res.single = single res.lian2 = lian2 res.ge2 = ge2 res.gang = gang res.ctype = a:tof() return res end local _M = {} function _M.check_sichuan_hu(cards, putcards, ... ) -- body assert(cards and putcards) local res = check_qidui_hu(cards) if res.code ~= hutype.NONE then return res end local len = #cards local args = check_sichuan(cards, putcards) local qing = args.qing local jiang = args.jiang local tong3 = args.tong3 local lian3 = args.lian3 local single = args.single local lian2 = args.lian2 local gang = args.gang local ctype = args.ctype if #putcards > 0 then local putargs = check_put(putcards) if putargs.qing and qing then if putargs.ctype ~= ctype then qing = false end else qing = false end gang = gang + putargs.gang end local res = {} res.code = hutype.NONE res.gang = gang if jiang * 2 + tong3 * 3 + lian3 * 3 == len then if len == 2 and jiang == 1 then if qing and gang == 4 then res.code = hutype.QINGSHIBALUOHAN elseif gang == 4 then res.code = hutype.SHIBALUOHAN elseif qing then res.code = hutype.QINGJINGOUDIAO else res.code = hutype.JINGOUDIAO end elseif len == 5 then if jiang == 1 and tong3 == 1 and qing then res.code = hutype.QINGDUIDUI elseif jiang == 1 and tong3 == 1 then res.code = hutype.DUIDUIHU elseif jiang == 1 and qing then res.code = hutype.QINGYISE elseif jiang == 1 then res.code = hutype.PINGHU end elseif len == 8 then if jiang == 1 and tong3 == 2 and qing then res.code = hutype.QINGDUIDUI elseif jiang == 1 and tong3 == 2 then res.code = hutype.DUIDUIHU elseif jiang == 1 and qing then res.code = hutype.QINGYISE elseif jiang == 1 then res.code = hutype.PINGHU end elseif len == 11 then if jiang == 1 and tong3 == 3 and qing then res.code = hutype.QINGDUIDUI elseif jiang == 1 and tong3 == 3 then res.code = hutype.DUIDUIHU elseif jiang == 1 and qing then res.code = hutype.QINGYISE elseif jiang == 1 then res.code = hutype.PINGHU end elseif len == 14 then if jiang == 1 and tong3 == 4 and qing then res.code = hutype.QINGDUIDUI elseif jiang == 1 and tong3 == 4 then res.code = hutype.DUIDUIHU elseif jiang == 1 and qing then res.code = hutype.QINGYISE elseif jiang == 1 then res.code = hutype.PINGHU end end end return res end function _M.check_sichuan_jiao(cards, putcards, ... ) -- body assert(cards and putcards) local res = check_qidui_hu(cards) if res.code ~= hutype.NONE then return res end local len = #cards local args = check_sichuan(cards, putcards) local qing = args.qing local jiang = args.jiang local tong3 = args.tong3 local lian3 = args.lian3 local single = args.single local lian2 = args.lian2 local ge2 = args.ge2 local gang = args.gang local ctype = args.ctype print("len", len) print("qing:", qing) print("jiang", jiang) print("tong3", tong3) print("lian3", lian3) print("single", single) print("lian2", lian2) print("gang", gang) print("ge2", ge2) if #putcards > 0 then local putargs = check_put(putcards) if putargs.qing and qing then if putargs.ctype ~= ctype then qing = false end else qing = false end gang = gang + putargs.gang end local res = {} res.code = hutype.NONE res.gang = gang assert(jiang * 2 + tong3 * 3 + lian3 * 3 + single * 1 + lian2 * 2 + ge2 * 2 == len) if len == 1 and single == 1 then if qing and gang == 4 then res.code = hutype.QINGSHIBALUOHAN elseif gang == 4 then res.code = hutype.SHIBALUOHAN elseif qing then res.code = hutype.QINGJINGOUDIAO else res.code = hutype.JINGOUDIAO end elseif len == 4 then if qing and jiang == 2 then res.code = hutype.QINGDUIDUI elseif jiang == 2 then res.code = hutype.DUIDUIHU elseif qing and jiang == 1 and lian2 == 1 then res.code = hutype.QINGYISE elseif qing and single == 1 and lian3 == 1 then res.code = hutype.QINGYISE elseif qing and single == 1 and ge2 == 1 then res.code = hutype.QINGYISE elseif jiang == 1 and lian2 == 1 then res.code = hutype.PINGHU elseif single == 1 and lian3 == 1 then res.code = hutype.PINGHU elseif single == 1 and ge2 == 1 then res.code = hutype.PINGHU else res.code = hutype.NONE end elseif len == 7 then if qing and jiang == 2 and tong3 == 1 then res.code = hutype.QINGDUIDUI elseif jiang == 2 and tong3 == 1 then res.code = hutype.DUIDUIHU elseif qing and single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.QINGYISE elseif qing and single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.QINGYISE elseif qing and single == 0 and jiang == 1 and ge2 == 1 then res.code = hutype.QINGYISE elseif single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and ge2 == 1 then res.code = hutype.PINGHU else res.code = hutype.NONE end elseif len == 10 then if qing and jiang == 2 and tong3 == 2 then res.code = hutype.QINGDUIDUI elseif jiang == 2 and tong3 == 2 then res.code = hutype.DUIDUIHU elseif qing and single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.QINGYISE elseif qing and single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.QINGYISE elseif qing and single == 0 and jiang == 1 and ge2 == 1 then res.code = hutype.QINGYISE elseif single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and ge2 == 1 then res.code = hutype.PINGHU else res.code = hutype.NONE end elseif len == 13 then if qing and jiang == 2 and tong3 == 3 then res.code = hutype.QINGDUIDUI elseif jiang == 2 and tong3 == 3 then res.code = hutype.DUIDUIHU elseif qing and single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.QINGYISE elseif qing and single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.QINGYISE elseif single == 1 and jiang == 0 and lian2 == 0 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and lian2 == 1 then res.code = hutype.PINGHU elseif single == 0 and jiang == 1 and ge2 == 1 then res.code = hutype.PINGHU else res.code = hutype.NONE end end return res end return _M
local runtime = require 'jass.runtime' local console = require 'jass.console' local tostring = tostring local debug = debug console.enable = true runtime.handle_level = 2 runtime.sleep = true runtime.error_handle = function(msg) console.write("---------------------------------------") console.write(" LUA ERROR!! ") console.write("---------------------------------------") console.write(tostring(msg) .. "\n") console.write(debug.traceback()) console.write("---------------------------------------") end
ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) PlayerData = xPlayer end) ----- RegisterNetEvent('esx_borrmaskin:startDrill') AddEventHandler('esx_borrmaskin:startDrill', function(source) DrillAnimation() end) function DrillAnimation() local playerPed = GetPlayerPed(-1) Citizen.CreateThread(function() TaskStartScenarioInPlace(playerPed, "WORLD_HUMAN_CONST_DRILL", 0, true) end) end
local _, Engine = ... local Module = Engine:NewModule("Fonts") local gameLocale = GetLocale() local isLatin = ({ enUS = true, enGB = true, deDE = true, esES = true, esMX = true, frFR = true, itIT = true, ptBR = true, ptPT = true })[gameLocale] Module.SetUp = function(self) -- shortcuts to the fonts local config = self:GetStaticConfig("Fonts") self.fonts = { text_normal = config.fonts.text_normal.path, text_narrow = config.fonts.text_narrow.path, text_serif = config.fonts.text_serif.path, text_serif_italic = config.fonts.text_serif_italic.path, header_normal = config.fonts.header_normal.path, header_light = config.fonts.header_light.path, number = config.fonts.number.path, damage = config.fonts.damage.path } -- hash table to quickly tell us if font face supports the current locale local fonts = self.fonts self.canIUse = { [fonts.text_normal] = config.fonts.text_normal.locales[gameLocale], [fonts.text_narrow] = config.fonts.text_narrow.locales[gameLocale], [fonts.text_serif] = config.fonts.text_serif.locales[gameLocale], [fonts.text_serif_italic] = config.fonts.text_serif_italic.locales[gameLocale], [fonts.header_normal] = config.fonts.header_normal.locales[gameLocale], [fonts.header_light] = config.fonts.header_light.locales[gameLocale], [fonts.number] = config.fonts.number.locales[gameLocale], [fonts.damage] = config.fonts.damage.locales[gameLocale] } end Module.SetGameEngineFonts = function(self) local canIUse = self.canIUse local fonts = self.fonts -- game engine fonts -- *These will only be updated when the user -- relogs into the game from the character selection screen, -- not when simply reloading the user interface! if canIUse[fonts.header_light] then UNIT_NAME_FONT = fonts.header_light -- the following need the string to be the global name of a fontobject. weird. if Engine:IsBuild("WoD") then NAMEPLATE_FONT = "GameFontWhite" -- 12 NAMEPLATE_SPELLCAST_FONT = "GameFontWhiteTiny" -- 9 self:SetFont(GameFontWhite, fonts.header_light) elseif Engine:IsBuild("WotLK") then NAMEPLATE_FONT = fonts.header_light end end -- Legion features much nicer and smoother damage, -- so we should just leave that as it is. if not Engine:IsBuild("Legion") then if canIUse[fonts.damage] then DAMAGE_TEXT_FONT = fonts.damage end end if canIUse[fonts.text_normal] then STANDARD_TEXT_FONT = fonts.text_normal end -- default values UIDROPDOWNMENU_DEFAULT_TEXT_HEIGHT = 14 CHAT_FONT_HEIGHTS = { 12, 13, 14, 15, 16, 18, 20, 22 } if Engine:IsBuild("WoD") then if gameLocale == "ruRU" then -- cyrillic/russian if canIUse[fonts.header_light] then UNIT_NAME_FONT_CYRILLIC = fonts.header_light end elseif gameLocale == "koKR" then -- korean if canIUse[fonts.header_light] then UNIT_NAME_FONT_KOREAN = fonts.header_light end elseif gameLocale == "zhTW" or gameLocale == "zhCN" then -- chinese if canIUse[fonts.header_light] then UNIT_NAME_FONT_CHINESE = fonts.header_light end elseif isLatin then -- roman/latin if canIUse[fonts.header_light] then UNIT_NAME_FONT_ROMAN = fonts.header_light end end end end Module.SetFontObjects = function(self) local fonts = self.fonts self:SetFont(NumberFontNormal, fonts.number) self:SetFont(FriendsFont_Large, fonts.header_light) self:SetFont(GameFont_Gigantic, fonts.header_light) -- not present in WotLK self:SetFont(ChatBubbleFont, fonts.text_normal) -- not present in WotLK...? self:SetFont(FriendsFont_UserText, fonts.header_light) self:SetFont(QuestFont_Large, fonts.header_normal, 14, "", 0, 0, 0) -- 15 self:SetFont(QuestFont_Shadow_Huge, fonts.header_normal, 16, "", 0, 0, 0) -- 18 self:SetFont(QuestFont_Super_Huge, fonts.header_light, 18, "", 0, 0, 0) -- 24 garrison mission list -- not present in WotLK self:SetFont(DestinyFontLarge, fonts.header_normal) -- 18 -- not present in WotLK self:SetFont(DestinyFontHuge, fonts.header_light) -- 32 -- not present in WotLK self:SetFont(CoreAbilityFont, fonts.header_light) -- 32 -- not present in WotLK self:SetFont(QuestFont_Shadow_Small, fonts.header_normal, nil, "", 0, 0, 0) -- 14 -- not present in WotLK self:SetFont(MailFont_Large, fonts.header_normal, nil, "", 0, 0, 0) -- 15 -- floating combat text self:SetFont(CombatTextFont, self.fonts.damage, 100, "", -2.5, -2.5, .35) -- chat font self:SetFont(ChatFontNormal, nil, nil, "", -.75, -.75, 1) end Module.SetFont = function(self, fontObject, font, size, style, shadowX, shadowY, shadowA, r, g, b, shadowR, shadowG, shadowB) -- simple copout for non-existing fontobjects if not fontObject then return end local oldFont, oldSize, oldStyle = fontObject:GetFont() if not font then font = oldFont end if not size then size = oldSize end -- forcefully keep the outlines thin if not style then style = (oldStyle == "OUTLINE") and "THINOUTLINE" or oldStyle end -- don't change the font face if it doesn't support the current locale fontObject:SetFont(self.canIUse[font] and font or oldFont, size, style) if shadowX and shadowY then fontObject:SetShadowOffset(shadowX, shadowY) fontObject:SetShadowColor(shadowR or 0, shadowG or 0, shadowB or 0, shadowA or 1) end if r and g and b then fontObject:SetTextColor(r, g, b) end return fontObject end Module.HookCombatText = function(self) -- combat text -- COMBAT_TEXT_HEIGHT = 16 -- COMBAT_TEXT_CRIT_MAXHEIGHT = 16 -- COMBAT_TEXT_CRIT_MINHEIGHT = 16 -- COMBAT_TEXT_SCROLLSPEED = 3 COMBAT_TEXT_HEIGHT = 16 COMBAT_TEXT_CRIT_MAXHEIGHT = 16 COMBAT_TEXT_CRIT_MINHEIGHT = 16 COMBAT_TEXT_SCROLLSPEED = 3 hooksecurefunc("CombatText_UpdateDisplayedMessages", function() -- if COMBAT_TEXT_FLOAT_MODE == "1" then -- COMBAT_TEXT_LOCATIONS.startY = 484 -- COMBAT_TEXT_LOCATIONS.endY = 709 -- end COMBAT_TEXT_LOCATIONS.startY = 220 COMBAT_TEXT_LOCATIONS.endY = 440 end) end -- Fonts (especially game engine fonts) need to be set very early in the loading process, -- so for this specific module we'll bypass the normal loading order, and just fire away! Module:SetUp() Module:SetGameEngineFonts() Module:SetFontObjects() if IsAddOnLoaded("Blizzard_CombatText") then Module:HookCombatText() else Module.ADDON_LOADED = function(self, event, addon, ...) if addon == "Blizzard_CombatText" then self:HookCombatText() self:UnregisterEvent("ADDON_LOADED") end end Module:RegisterEvent("ADDON_LOADED") end
local members = redis.call("SMEMBERS", "processing") redis.call("DEL", "processing") local time = tonumber(redis.call("TIME")[1]) * 1000 for i = 1, #members, 1 do redis.call("ZADD", "processing", time, members[i]) end
local playsession = { {"TiTaN", {1338110}}, {"EPO666", {472199}}, {"die_ott", {13490}}, {"vvictor", {903576}}, {"MoeMoms", {40156}}, {"Menander", {2072809}}, {"Nikkichu", {2321995}}, {"BallisticGamer04", {8683}}, {"BootyMuncher123", {2368}}, {"TheHiddenManiac", {29350}}, {"Hitman451", {4014}}, {"PogomanD", {19967}}, {"Fireball_Whiskey", {16472}}, {"rocifier", {116186}}, {"everLord", {1052903}}, {"ausmister", {588784}}, {"JustronX", {147537}}, {"stargazer5683", {112503}}, {"Bartell", {22571}}, {"Piewdennis", {923856}}, {"CmonMate497", {27379}}, {"strongfive", {263282}}, {"banakeg", {2998}}, {"ArPiiX", {124059}}, {"exabyte", {756110}}, {"kaimix", {448546}}, {"To_Ya", {6378}}, {"foggyliziouz", {708904}}, {"sirvorlon", {477655}}, {"TCP", {681744}}, {"LymBAOBEI", {8668}}, {"Mampfaxo97", {9831}}, {"Renault_Laguna_Lover38", {1518}}, {"Hitclower", {23477}}, {"epicsmokey", {20866}}, {"Creator_Zhang", {135746}}, {"AroN57", {10023}}, {"RedPandaRam", {29162}}, {"BjoernarS", {25163}}, {"abrown4521", {447}}, {"snoetje", {247296}}, {"mad58max", {188996}}, {"Hiero", {15174}}, {"Corlin", {51436}}, {"kisPocok", {3361}}, {"realDonaldTrump", {30287}} } return playsession
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) local Vehicles = nil RegisterServerEvent('esx_lscustom:buyMod') AddEventHandler('esx_lscustom:buyMod', function(price) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) price = tonumber(price) if Config.IsMecanoJobOnly then local societyAccount = nil TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mecano', function(account) societyAccount = account end) if price < societyAccount.money then TriggerClientEvent('esx_lscustom:installMod', _source) TriggerClientEvent('esx:showNotification', _source, _U('purchased')) local society = {name = "mecano"} local mecanoPart = 0.1 -- TriggerEvent('esx_society:saveData',xPlayer,"purchase",society,price,(societyAccount.money-price)) TriggerEvent('esx_avan0x:logTransaction', 'society_mecano', 'society_mecano', 'CUSTOM', 'CUSTOM', "purchase_custom", price * (1 - mecanoPart)) TriggerEvent('esx_statejob:getTaxed', 'CUSTOM', price, function(toSociety) end) societyAccount.removeMoney(price * (1 - mecanoPart)) else TriggerClientEvent('esx_lscustom:cancelInstallMod', _source) TriggerClientEvent('esx:showNotification', _source, _U('not_enough_money')) end else if price < xPlayer.getMoney() then TriggerClientEvent('esx_lscustom:installMod', _source) TriggerClientEvent('esx:showNotification', _source, _U('purchased')) TriggerEvent('esx_statejob:getTaxed', 'CUSTOM', price, function(toSociety) end) xPlayer.removeMoney(price) else TriggerClientEvent('esx_lscustom:cancelInstallMod', _source) TriggerClientEvent('esx:showNotification', _source, _U('not_enough_money')) end end end) RegisterServerEvent('esx_lscustom:refreshOwnedVehicle') AddEventHandler('esx_lscustom:refreshOwnedVehicle', function(myCar) local xPlayer = ESX.GetPlayerFromId(source) MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE @plate = plate', { ['@plate'] = myCar.plate }, function(result) if result[1] then local vehicle = json.decode(result[1].vehicle) if vehicle.model == myCar.model then MySQL.Async.execute('UPDATE `owned_vehicles` SET `vehicle` = @vehicle WHERE `plate` = @plate', { ['@plate'] = myCar.plate, ['@vehicle'] = json.encode(myCar) }) else print(('esx_lscustom: %s a tenté de mettre à niveau un véhicule dont le modèle n\'était pas assorti !'):format(xPlayer.identifier)) end end end) end) ESX.RegisterServerCallback('esx_lscustom:getVehiclesPrices', function(source, cb) if Vehicles == nil then -- MySQL.Async.fetchAll('SELECT * FROM vehicles', {}, function(result) MySQL.Async.fetchAll('SELECT model, price FROM vehicles UNION SELECT model, price FROM vehicles_society', {}, function(result) local vehicles = {} for i=1, #result, 1 do table.insert(vehicles, { model = result[i].model, price = result[i].price }) end Vehicles = vehicles cb(Vehicles) end) else cb(Vehicles) end end) --------------------------------- --- Copyright by ikNox#6088 --- ---------------------------------
AI = {} function AI:load() self.img = love.graphics.newImage("assets/2.png") self.width = self.img:getWidth() self.height = self.img:getHeight() self.x = love.graphics.getWidth() - self.width - 50 self.y = love.graphics.getHeight() / 2 self.yVel = 0 self.speed = 500 self.timer = 0 self.rate = 0.5 end function AI:update(dt) self:movement(dt) self:checkBoundaries() self.timer = self.timer + dt if self.timer > self.rate then self.timer = 0 self:acquireTarget() end end function AI:movement(dt) self.y = self.y + self.yVel * dt end function AI:checkBoundaries() if self.y < 0 then self.y = 0 elseif self.y + self.height > love.graphics.getHeight() then self.y = love.graphics.getHeight() - self.height end end function AI:acquireTarget() if Ball.y + Ball.height < self.y then self.yVel = -self.speed elseif Ball.y > self.y + self.height then self.yVel = self.speed else self.yVel = 0 end end function AI:draw() love.graphics.draw(self.img, self.x, self.y) end
------------------------------------------------------------------------------------------------------------------------ -- Proposal: -- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0192-button_subscription_response_from_hmi.md ------------------------------------------------------------------------------------------------------------------------ -- Description: Check that SDL processes SubscribeButton/UnsubscribeButton RPC's with <button> parameter -- if HMI responds with any <successful> result code ------------------------------------------------------------------------------------------------------------------------ -- In case: -- 1. Mobile app requests SubscribeButton(<button>) -- 2. HMI responds with any <successful> resultCode to request: -- - "WARNINGS", "RETRY", "SAVED", "WRONG_LANGUAGE", "UNSUPPORTED_RESOURCE", "TRUNCATED_DATA" -- SDL does: -- - process responses from HMI -- - respond SubscribeButton(success=true,result_code=<successful>) to mobile app -- - send OnHashChange with updated hashId to mobile app -- - resend OnButtonEvent and OnButtonPress notifications to mobile App -- In case: -- 3. Mobile app requests UnsubscribeButton(<button>) -- 4. HMI responds with any <successful> resultCode to request: -- - "WARNINGS", "RETRY", "SAVED", "WRONG_LANGUAGE", "UNSUPPORTED_RESOURCE", "TRUNCATED_DATA" -- SDL does: -- - process responses from HMI -- - respond UnsubscribeButton(success=true,result_code=<successful>) to mobile app -- - send OnHashChange with updated hashId to mobile app -- - not resend OnButtonEvent and OnButtonPress notifications to mobile App ------------------------------------------------------------------------------------------------------------------------ --[[ Required Shared libraries ]] local common = require('test_scripts/API/ButtonSubscription/commonButtonSubscription') --[[ Local Variables ]] local appSessionId1 = 1 local buttonName = "OK" local successCodes = { "WARNINGS", "RETRY", "SAVED", "WRONG_LANGUAGE", "UNSUPPORTED_RESOURCE", "TRUNCATED_DATA" } --[[ Local function ]] local function rpcSuccess(pAppId, pRpc, pSuccessCodes) local cid = common.getMobileSession(pAppId):SendRPC(pRpc, { buttonName = buttonName }) common.getHMIConnection():ExpectRequest("Buttons." .. pRpc, { appID = common.getHMIAppId(pAppId), buttonName = buttonName }) :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, data.method, pSuccessCodes, { }) end) common.getHMIConnection():ExpectNotification("Buttons.OnButtonSubscription") :Times(0) common.getMobileSession(pAppId):ExpectResponse(cid, { success = true, resultCode = pSuccessCodes }) common.getMobileSession(pAppId):ExpectNotification("OnHashChange") :Do(function(_, data) common.hashId[pAppId] = data.payload.hashID end) end --[[ Scenario ]] common.runner.Title("Preconditions") common.runner.Step("Clean environment", common.preconditions) common.runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.runner.Step("App registration", common.registerAppWOPTU) common.runner.Step("App activation", common.activateApp) common.runner.Title("Test") for _, code in common.spairs(successCodes) do common.runner.Title("ButtonName parameter: " .. buttonName .. " with " .. code) common.runner.Step("SubscribeButton " .. buttonName .. " with " .. code, rpcSuccess, { appSessionId1, "SubscribeButton", code }) common.runner.Step("On Button Press " .. buttonName, common.buttonPress, { appSessionId1, buttonName }) common.runner.Step("UnsubscribeButton " .. buttonName .. " with " .. code, common.rpcSuccess, { appSessionId1, "UnsubscribeButton", buttonName }) common.runner.Step("Check unsubscribe " .. buttonName, common.buttonPress, { appSessionId1, buttonName, common.isNotExpected }) end common.runner.Title("Postconditions") common.runner.Step("Stop SDL", common.postconditions)
--[[ Copyright (C) 2018 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] -- Utilities for color conversion. local colors = {} --[[ Converts an HSV color value to RGB. Conversion formula adapted from http://en.wikipedia.org/wiki/HSV_color_space. Arguments: * 'h' Hue must be in range [0, 360) * 's' Saturation must be in range [0, 1] (default 1) * 'v' Value must be in range [0, 1] (default 1) Returns r, g, b each in the range [0, 255]. ]] function colors.hsvToRgb(h, s, v) s = s or 1 v = v or 1 local i = math.floor(h / 60) local f = h / 60 - i local p = v * (1 - s) local q = v * (1 - f * s) local t = v * (1 - (1 - f) * s) i = i % 6 local r, g, b if i == 0 then r, g, b = v, t, p elseif i == 1 then r, g, b = q, v, p elseif i == 2 then r, g, b = p, v, t elseif i == 3 then r, g, b = p, q, v elseif i == 4 then r, g, b = t, p, v elseif i == 5 then r, g, b = v, p, q end return r * 255, g * 255, b * 255 end --[[ Converts an HSL color value to RGB. Based on formula at https://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL. Assumes h ∈ [0°, 360°), s ∈ [0, 1] and l ∈ [0, 1]. Returns r, g, b each in the set [0, 255]. ]] function colors.hslToRgb(h, s, l) local c = (1 - math.abs(2 * l - 1)) * s local hprime = h / 60 local x = c * (1 - math.abs(hprime % 2 - 1)) local m = l - 0.5 * c c = c + m x = x + m local r, g, b if hprime <= 1 then r, g, b = c, x, m elseif hprime <= 2 then r, g, b = x, c, m elseif hprime <= 3 then r, g, b = m, c, x elseif hprime <= 4 then r, g, b = m, x, c elseif hprime <= 5 then r, g, b = x, m, c elseif hprime < 6 then r, g, b = c, m, x end return r * 255, g * 255, b * 255 end --[[ Converts an RGB color value to HSL. Based on formula at https://en.wikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma. Assumes r, g, b each in the set [0, 255]. Returns h ∈ [0°, 360°), s ∈ [0, 1] and l ∈ [0, 1]. ]] function colors.rgbToHsl(r, g, b) r, g, b = r / 255, g / 255, b / 255 local max, min = math.max(r, g, b), math.min(r, g, b) local h, s, l l = (max + min) * 0.5 if max == min then h, s = 0, 0 else local d = (max - min) * 0.5 s = l > 0.5 and d / (1 - l) or d / l h = max == r and ((g - b) / d + (g < b and 6 or 0)) or max == g and ((b - r) / d + 2) or max == b and ((r - g) / d + 4) h = 360 * h / 6 end return h, s, l end return colors
local Advice = require("api.Advice") local Extend = require("api.Extend") local IFeatLockedHatch = require("mod.elona.api.aspect.feat.IFeatLockedHatch") local UiMinimap_show_stair_locations = {} UiMinimap_show_stair_locations.after = {} function UiMinimap_show_stair_locations.after:init(...) local ext = Extend.get_or_create(self, "cheat") ext.stair_locations = {} end function UiMinimap_show_stair_locations.after:refresh_visible(map) if not self.tile_batch or map == nil then return end local ext = Extend.get(self, "cheat") local locs = {} for _, feat in map:iter_feats() do if feat._id == "elona.stairs_up" then locs[#locs+1] = { type = "up", x = feat.x, y = feat.y } elseif feat._id == "elona.stairs_down" or feat:get_aspect(IFeatLockedHatch) then locs[#locs+1] = { type = "down", x = feat.x, y = feat.y } end end ext.stair_locations = locs end function UiMinimap_show_stair_locations.after:draw(...) if not config.cheat.show_stair_locations then return end local ext = Extend.get(self, "cheat") for _, loc in ipairs(ext.stair_locations) do local x = math.clamp(loc.x * self.tw, 2, self.width - 8) local y = math.clamp(loc.y * self.th, 2, self.height - 8) self.t.base.minimap_marker_player:draw(self.x + x, self.y + y) end end for where, t in pairs(UiMinimap_show_stair_locations) do for fn_name, fn in pairs(t) do Advice.add(where, "api.gui.hud.UiMinimap", fn_name, ("Show stair locations: %s()"):format(fn_name), fn) end end
--异态魔女·毒-?? local m=14000508 local cm=_G["c"..m] cm.named_with_Spositch=1 xpcall(function() require("expansions/script/c14000501") end,function() require("script/c14000501") end) function cm.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,cm.xfilter,11,2) c:EnableReviveLimit() --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(m,0)) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_CHAIN_SOLVING) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(cm.thcon) e1:SetTarget(cm.thtg) e1:SetOperation(cm.thop) c:RegisterEffect(e1) --cannot be target local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetValue(1) c:RegisterEffect(e2) end function cm.xfilter(c) return spo.named(c) end function cm.thcon(e,tp,eg,ep,ev,re,r,rp) return rp==tp and re:IsHasType(EFFECT_TYPE_ACTIVATE) and (re:IsActiveType(TYPE_SPELL) or re:GetHandler():IsType(TYPE_SPELL) or spo.named(re:GetHandler())) end function cm.thfilter(c) return bit.band(c:GetOriginalType(),TYPE_MONSTER)~=0 and c:IsAbleToHand() and not c:IsForbidden() end function cm.ovfilter(c,e,tp) return c:IsType(TYPE_SPELL+TYPE_TRAP) and not c:IsType(TYPE_TOKEN) and (c:IsControler(tp) or c:IsAbleToChangeControler()) and not c:IsImmuneToEffect(e) end function cm.thtg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return e:GetHandler():GetOverlayCount()~=0 and e:GetHandler():GetOverlayGroup():IsExists(cm.thfilter,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_OVERLAY) end function cm.thop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local og=c:GetOverlayGroup() if og:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=og:Filter(cm.thfilter,nil,nil) local tc=g:Select(tp,1,1,nil):GetFirst() if tc then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) end end local cg=Duel.GetMatchingGroup(cm.ovfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,c,e,tp) if cg:GetCount()>0 and c:IsType(TYPE_XYZ) and c:IsRelateToEffect(e) and Duel.SelectYesNo(tp,aux.Stringid(m,1)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local tc=cg:Select(tp,1,1,c):GetFirst() if tc then local og=tc:GetOverlayGroup() if og:GetCount()>0 then Duel.SendtoGrave(og,REASON_RULE) end Duel.Overlay(c,Group.FromCards(tc)) end end end
local cmdsDir = "cmds" client_script (cmdsDir..[[/client_test.lua]]) server_script (cmdsDir..[[/server_test.lua]]) dependencies { "exp" }
--- Operations for game settings / stats. -- @module Noble.Settings -- Noble.Settings = {} -- This is the "class" that holds methods. local settings = nil -- This is the actual settings object. We keep it local to avoid direct tampering. local settingsDefault = nil -- We keep track of default values so they can be reset. local function keyChange(__dataDefault, __data) local defaultKeys = {} local keys = {} for key, value in pairs(__dataDefault) do table.insert(defaultKeys, key) end for key, value in pairs(__data) do table.insert(keys, key) end for i = 1, #keys, 1 do if (defaultKeys[i] ~= keys[i]) then return true end end return false end local function settingExists(__key) -- Check for valid data item. for key, value in pairs(settings) do if __key == key then return true end end error("BONK: Setting \'" .. __key .. "\' does not exist. Maybe you spellet ti wronlgly.", 3) return false end local settingsHaveBeenSetup = false --- Sets up the settings for your game. You can only run this once, and you must run it before using other `Noble.Settings` functions. It is recommended to place it in your main.lua, before `Noble.new()`. -- @tparam table __keyValuePairs table. Your game's settings, and thier default values, as key/value pairs. NOTE: Do not use "nil" as a value. -- @bool[opt=true] __saveToDisk Saves your default values immediatly to disk. -- @bool[opt=true] __modifyExistingOnKeyChange Updates the existing settings object on disk if you make changes to your settings keys (not values) during development or when updating your game. -- @usage -- Noble.Settings.setup({ -- difficulty = "normal", -- music = true, -- sfx = true, -- players = 2, -- highScore = 0 -- You can store persistant stats here, too! -- }) function Noble.Settings.setup(__keyValuePairs, __saveToDisk, __modifyExistingOnKeyChange) if (settingsHaveBeenSetup) then error("BONK: You can only run Noble.Settings.setup() once.") return else settingsHaveBeenSetup = true end local saveToDisk = __saveToDisk or true local modifyExistingOnKeyChange = __modifyExistingOnKeyChange or true settingsDefault = __keyValuePairs -- Get existing settings from disk, if any. settings = Datastore.read("Settings") if (settings == nil) then -- No settings on disk, so we create a new settings object using default values. settings = table.deepcopy(settingsDefault) elseif (modifyExistingOnKeyChange and keyChange(settingsDefault, settings)) then -- Found settings on disk, but key changes have been made... -- ...so we start with a new default settings object... local existingSettings = table.deepcopy(settings) settings = table.deepcopy(settingsDefault) for key, value in pairs(settings) do -- ...then copy settings with unchanged keys to the new settings object, -- naturally discarding keys that don't exist anymore. if (existingSettings[key] ~= nil) then settings[key] = existingSettings[key] end end end if (saveToDisk) then Noble.Settings.save() end end --- Get the value of a setting. -- @string __settingName The name of the setting. -- @treturn any The value of the requested setting. -- @see set function Noble.Settings.get(__settingName) if (settingExists(__settingName)) then return settings[__settingName] end end --- Set the value of a setting. -- @string __settingName The name of the setting. -- @tparam any __value The setting's new value -- @bool[opt=true] __saveToDisk Saves to disk immediately. Set to false if you prefer to manually save (via a confirm button, etc). -- @see get -- @see save function Noble.Settings.set(__settingName, __value, __saveToDisk) if (settingExists(__settingName)) then settings[__settingName] = __value local saveToDisk = __saveToDisk or true if (saveToDisk) then Noble.Settings.save() end end end --- Resets the value of a setting to its default value defined in `setup()`. -- @string __settingName The name of the setting. -- @bool[opt=true] __saveToDisk Saves to disk immediately. Set to false if you prefer to manually save (via a confirm button, etc). -- @see resetSome -- @see resetAll -- @see save function Noble.Settings.reset(__settingName, __saveToDisk) if (settingExists(__settingName)) then settings[__settingName] = settingsDefault[__settingName] local saveToDisk = __saveToDisk or true if (saveToDisk) then Noble.Settings.save() end end end --- Resets the value of multiple settings to thier default value defined in `setup()`. This is useful if you are storing persistant stats like high scores in `Settings` and want the player to be able to reset them seperately. -- @tparam table __settingNames The names of the settings, in an array-style table. -- @bool[opt=true] __saveToDisk Saves to disk immediately. Set to false if you prefer to manually save (via a confirm button, etc). -- @see resetAll -- @see save function Noble.Settings.resetSome(__settingNames, __saveToDisk) for i = 1, #__settingNames, 1 do Noble.Settings.reset(__settingNames[i], __saveToDisk) end end --- Resets all settings to thier default values defined in `setup()`. -- @bool[opt=true] __saveToDisk Saves to disk immediately. Set to false if you prefer to manually save (via a confirm button, etc). -- @see resetSome -- @see save function Noble.Settings.resetAll(__saveToDisk) settings = table.deepcopy(settingsDefault) local saveToDisk = __saveToDisk or true if (saveToDisk) then Noble.Settings.save() end end --- Saves settings to disk. -- You don't need to call this unless you set `__saveToDisk` as false when setting or resetting a setting (say that five times fast!). -- @see set -- @see reset -- @see resetAll function Noble.Settings.save() Datastore.write(settings, "Settings") end
local DotaQuiz = {} DotaQuiz.Identity = "dota_quiz" DotaQuiz.Locale = { ["name"] = { ["english"] = "Dota Quiz", ["russian"] = "Викторина", ["chinese"] = "测验", }, ["desc"] = { ["english"] = "Quiz #1 in Dota 2", ["russian"] = "Викторина #1 в Dota 2", ["chinese"] = "Dota 2中的测验#1" }, ["delay_before_quiz_load"] = { ["english"] = "Delay before quiz load", ["russian"] = "Задержка перед загрузкой викторины", ["chinese"] = "下载测验之前延迟" }, ["delay_before_quiz_start"] = { ["english"] = "Delay before quiz start", ["russian"] = "Задержка перед началом викторины", ["chinese"] = "在测验开始之前延迟" }, ["message_delay"] = { ["english"] = "Delay in message send (ms)", ["russian"] = "Задержка при отправке сообщений (мс)", ["chinese"] = "延迟发送消息" }, ["repeat_delay"] = { ["english"] = "Delay before question repeated", ["russian"] = "Задержка перед повторением вопроса", ["chinese"] = "延迟问题重复" }, ["delay_before_new_question"] = { ["english"] = "Delay before a new question", ["russian"] = "Задержка перед новым вопросом", ["chinese"] = "在一个新问题之前延迟" }, -- ["welcome"] = { ["english"] = "Welcome to Dota 2 Quiz.", ["russian"] = "Добро пожаловать в виктору Dota 2", ["chinese"] = "欢迎来到维克多·达塔2" }, ["willstart"] = { ["english"] = "Quiz will start in ", ["russian"] = "Викторина начнётся через ", ["chinese"] = "维克多开始了 " }, ["second"] = { ["english"] = " second.", ["russian"] = " секунд.", ["chinese"] = " 秒。" }, ["repeat"] = { ["english"] = "Repeat question:", ["russian"] = "Повтор вопроса:", ["chinese"] = "重复这个问题:" }, ["inthelead"] = { ["english"] = "In the lead: ", ["russian"] = "Лидирует: ", ["chinese"] = "领先:" }, ["stat"] = { ["english"] = "Quiz stat:", ["russian"] = "Статистика викторины:", ["chinese"] = "测验统计:" }, ["qend"] = { ["english"] = "Our quiz has ended. Winner is: ", ["russian"] = "Викторина закончилась. Победитель: ", ["chinese"] = "测验结束了。赢家:" }, ["qend"] = { ["english"] = "Our quiz has ended. Winner is: ", ["russian"] = "Викторина закончилась. Победитель: ", ["chinese"] = "测验结束了。赢家:" }, ["next"] = { ["english"] = "Next question in ", ["russian"] = "Следующий вопрос через: ", ["chinese"] = "下一个问题是: " }, ["correct"] = { ["english"] = "Correctly answered '", ["russian"] = "Правильно ответил '", ["chinese"] = "正确回答 '" }, ["score"] = { ["english"] = "' he got +1 score", ["russian"] = "' и получает +1 балл", ["chinese"] = "' 并获得+1点“" }, ["commands"] = { ["english"] = "The list of available commands can be viewed by entering in the chat 'dq!help'.", ["russian"] = "Список доступных команд можно посмотреть введя в чат 'dq!help'.", ["chinese"] = "可以通过输入聊天 “dq!help” 来查看可用命令的列表." }, ["helper"] = { ["english"] = "dq!stat - for statistics\r\ndq!lead - to see whos leading now", ["russian"] = "dq!stat - чтобы посмотреть статистику\r\ndq!lead - чтобы посмотреть кто сейчас побеждает", ["chinese"] = "dq!stat - 查看统计信息\r\ndq!lead - 看看谁现在赢了" } } function DotaQuiz.OnDraw() if GUI == nil then return end if GUI.SelectedLanguage == nil then return end if not GUI.Exist(DotaQuiz.Identity) then local GUI_Object = {} GUI_Object["perfect_name"] = DotaQuiz.Locale["name"] GUI_Object["perfect_desc"] = DotaQuiz.Locale["desc"] GUI_Object["perfect_author"] = 'paroxysm' GUI_Object["category"] = GUI.Category.General GUI.Initialize(DotaQuiz.Identity, GUI_Object) GUI.AddMenuItem(DotaQuiz.Identity, DotaQuiz.Identity .. "delay_before_quiz_load", DotaQuiz.Locale["delay_before_quiz_load"], GUI.MenuType.Slider, 1, 360, 60) GUI.AddMenuItem(DotaQuiz.Identity, DotaQuiz.Identity .. "delay_before_quiz_start", DotaQuiz.Locale["delay_before_quiz_start"], GUI.MenuType.Slider, 1, 360, 60) GUI.AddMenuItem(DotaQuiz.Identity, DotaQuiz.Identity .. "message_delay", DotaQuiz.Locale["message_delay"], GUI.MenuType.Slider, 64, 2048, 256) GUI.AddMenuItem(DotaQuiz.Identity, DotaQuiz.Identity .. "repeat_delay", DotaQuiz.Locale["repeat_delay"], GUI.MenuType.Slider, 1, 120, 60) GUI.AddMenuItem(DotaQuiz.Identity, DotaQuiz.Identity .. "delay_before_new_question", DotaQuiz.Locale["delay_before_new_question"], GUI.MenuType.Slider, 1, 360, 60) end end DotaQuiz.CurrentQuestion = nil DotaQuiz.GameQuestions = {} DotaQuiz.Say = {} DotaQuiz.Players = {} function DotaQuiz.DoQuiz() if GUI.SelectedLanguage == nil then return end if not GUI.IsEnabled(DotaQuiz.Identity) then return end if DotaQuiz.CurrentQuestion == nil then if DotaQuiz.GameQuestions ~= nil and Length(DotaQuiz.GameQuestions) > 0 then DotaQuiz.CurrentQuestion = DotaQuiz.GameQuestions[1] table.remove(DotaQuiz.GameQuestions, 1) DotaQuiz.CurrentQuestion["c"] = os.clock() local temp_ans = DotaQuiz.CurrentQuestion["a"][DotaQuiz.CurrentQuestion["r"]] DotaQuiz.Shake(DotaQuiz.CurrentQuestion["a"]) local i = 1 for _, v in pairs(DotaQuiz.CurrentQuestion["a"]) do if temp_ans == v then DotaQuiz.CurrentQuestion["r"] = i end i = i + 1 end DotaQuiz.SayQuestion() end end end DotaQuiz.Runing = false DotaQuiz.GameStart = false function DotaQuiz.SayQuestion() if not GUI.IsEnabled(DotaQuiz.Identity) then return end local t = DotaQuiz.Explode("\r\n", DotaQuiz.CurrentQuestion["q"]) for k, v in pairs(t) do DotaQuiz.Write(v) end local i = 1 for _, v in pairs(DotaQuiz.CurrentQuestion["a"]) do DotaQuiz.Write(i .. ") " .. v) i = i + 1 end end function DotaQuiz.OnGameStart() DotaQuiz.Runing = true end function DotaQuiz.OnGameEnd() DotaQuiz.QuizEnd() end DotaQuiz.CurrentSay = "" function DotaQuiz.Write(text) table.insert(DotaQuiz.Say, text) end function DotaQuiz.Talk() if Length(DotaQuiz.Say) > 0 then if DotaQuiz.CurrentSay == "" then Engine.ExecuteCommand("say " .. DotaQuiz.Say[1]) DotaQuiz.CurrentSay = DotaQuiz.Say[1] else Engine.ExecuteCommand("say " .. DotaQuiz.CurrentSay) end end end function DotaQuiz.OnUpdate() if GUI.SelectedLanguage == nil then return end if not GUI.IsEnabled(DotaQuiz.Identity) then return end if DotaQuiz.Runing == true then if GUI.SleepReady("game_start") then if DotaQuiz.GameStart then DotaQuiz.Runing = false DotaQuiz.Write(DotaQuiz.Locale["welcome"][GUI.SelectedLanguage]) DotaQuiz.Write(DotaQuiz.Locale["willstart"][GUI.SelectedLanguage] .. GUI.Get(DotaQuiz.Identity .. "delay_before_quiz_start") .. DotaQuiz.Locale["second"][GUI.SelectedLanguage]) DotaQuiz.Write(DotaQuiz.Locale["commands"][GUI.SelectedLanguage]) if Length(DotaQuizDB.Questions[GUI.SelectedLanguage]) == 0 then DotaQuiz.GameQuestions = DotaQuizDB.Questions["english"] else DotaQuiz.GameQuestions = DotaQuizDB.Questions[GUI.SelectedLanguage] end GUI.Write("DotaQuizDB -> " .. DotaQuizDB.Version) DotaQuiz.Shake(DotaQuiz.GameQuestions) GUI.Sleep("lets_quiz", tonumber(GUI.Get(DotaQuiz.Identity .. "delay_before_quiz_start"))) else DotaQuiz.GameStart = true GUI.Sleep("game_start", tonumber(GUI.Get(DotaQuiz.Identity .. "delay_before_quiz_load"))) end end end if DotaQuiz.CurrentQuestion == nil and GUI.SleepReady("lets_quiz") then DotaQuiz.DoQuiz() end if GUI.SleepReady("lets_talk") then DotaQuiz.Talk() GUI.Sleep("lets_talk", math.floor(tonumber(GUI.Get(DotaQuiz.Identity .. "message_delay")) / 1000)) end if GUI.SleepReady("repeat_delay") then if DotaQuiz.CurrentQuestion ~= nil and DotaQuiz.CurrentQuestion["c"] ~= nil and os.clock() > (DotaQuiz.CurrentQuestion["c"] + tonumber(GUI.Get(DotaQuiz.Identity .. "repeat_delay"))) then DotaQuiz.Write(DotaQuiz.Locale["repeat"][GUI.SelectedLanguage]) DotaQuiz.SayQuestion() end GUI.Sleep("repeat_delay", tonumber(GUI.Get(DotaQuiz.Identity .. "repeat_delay"))) end end function DotaQuiz.OnSayText(textEvent) if not GUI.IsEnabled(DotaQuiz.Identity) then return end local who = textEvent.params[1] local what = textEvent.params[2] if what == DotaQuiz.CurrentSay then table.remove(DotaQuiz.Say, 1) DotaQuiz.CurrentSay = "" DotaQuiz.TimeToSay = 1 else if DotaQuiz.CurrentQuestion ~= nil and what == tostring(DotaQuiz.CurrentQuestion["r"]) and who ~= nil then DotaQuiz.Write(DotaQuiz.Locale["correct"][GUI.SelectedLanguage] .. who .. DotaQuiz.Locale["score"][GUI.SelectedLanguage]) if DotaQuiz.Players[who] == nil then DotaQuiz.Players[who] = 1 else DotaQuiz.Players[who] = DotaQuiz.Players[who] + 1 end DotaQuiz.CurrentQuestion = nil if Length(DotaQuiz.GameQuestions) > 0 then table.insert(DotaQuiz.Say, DotaQuiz.Locale["inthelead"][GUI.SelectedLanguage] .. DotaQuiz.GetWinner()) table.insert(DotaQuiz.Say, DotaQuiz.Locale["next"][GUI.SelectedLanguage] .. GUI.Get(DotaQuiz.Identity .. "delay_before_new_question") .. DotaQuiz.Locale["second"][GUI.SelectedLanguage]) GUI.Sleep("lets_quiz", tonumber(GUI.Get(DotaQuiz.Identity .. "delay_before_new_question"))) else DotaQuiz.Write(DotaQuiz.Locale["qend"][GUI.SelectedLanguage] .. DotaQuiz.GetWinner()) end end end if GUI.SleepReady("dq_stat") then if what == "dq!stat" then DotaQuiz.Write(DotaQuiz.Locale["stat"][GUI.SelectedLanguage]) DotaQuiz.DrawAll() GUI.Sleep("dq_stat", 10) return end end if GUI.SleepReady("dq_lead") then if what == "dq!lead" then DotaQuiz.Write(DotaQuiz.Locale["inthelead"][GUI.SelectedLanguage] .. DotaQuiz.GetWinner()) GUI.Sleep("dq_lead", 10) return end end if GUI.SleepReady("dq_help") then if what == "dq!help" then local t = DotaQuiz.Explode("\r\n", DotaQuiz.Locale["helper"][GUI.SelectedLanguage]) for k, v in pairs(t) do DotaQuiz.Write(v) end GUI.Sleep("dq_help", 10) return end end end function DotaQuiz.QuizEnd() DotaQuiz.GameStart = false DotaQuiz.CurrentQuestion = nil DotaQuiz.Say = {} DotaQuiz.Players = {} DotaQuiz.GameQuestions = {} DotaQuiz.Runing = false end function DotaQuiz.DrawAll() for k, v in pairs(DotaQuiz.Players) do DotaQuiz.Write(k .. " >> " .. v) end end function DotaQuiz.GetWinner() local winner = "" local temp_score = 0 for k, v in pairs(DotaQuiz.Players) do if v > temp_score then temp_score = v winner = k end end return winner end function DotaQuiz.RemoveKey(t, key) local new = {} for k, v in pairs(t) do if k ~= key then new[k] = v end end return new end function DotaQuiz.Explode(div, str) if (div=='') then return false end local pos,arr = 0,{} for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(arr,string.sub(str,pos)) return arr end function DotaQuiz.Swap(array, index1, index2) array[index1], array[index2] = array[index2], array[index1] end function DotaQuiz.Shake(array) local counter = #array while counter > 1 do local index = math.random(counter) DotaQuiz.Swap(array, index, counter) counter = counter - 1 end end return DotaQuiz
local basic_handlers = { gmod_combine_lock={ Handle_Mouse1=function(caller,ent) ent:Backdoor() end, Handle_Mouse2=function(ent) end }, npc_rollermine={ Handle_Mouse1=function(caller,ent) local hacked=ent:GetSaveTable().m_bHackedByAlyx if hacked then ent:SetSaveValue( "m_bHackedByAlyx", false ) ent:SetSubMaterial(0,"models/roller/rollermine_sheet") ent:SetSubMaterial(1,"models/roller/rollermine_glow") else ent:SetSaveValue( "m_bHackedByAlyx", true ) ent:SetSubMaterial(0,"models/Roller/rollermine_hacked") ent:SetSubMaterial(1,"models/roller/rollermine_gloworange") end end, Handle_Mouse2=function(caller,ent) --should explode here end }, func_door={ Handle_Mouse1=function(caller,ent) ent:Fire("Toggle","0") end, Handle_Mouse2=function(caller,ent) if ent:GetSaveTable().m_bLocked then ent:Fire("Unlock","0") else ent:Fire("Lock","0") end end}, prop_dynamic={ Handle_Mouse1=function(caller,ent) --check models local seq=ent:GetSaveTable().sequence if seq==2 then ent:Fire("setanimation","close",0) elseif (seq==3 or seq==0 or seq == 1) then ent:Fire("setanimation","open",0) end end, Handle_Mouse2=function(caller,ent) end }, gmod_wire_combine_sensor_lock={ Handle_Mouse1=function(caller,ent) ent:Backdoor() end, Handle_Mouse2=function(caller,ent) end }, prop_door_rotating={ Handle_Mouse1=function(caller,ent) ent:Fire("Toggle","0") end, Handle_Mouse2=function(caller,ent) if ent:GetSaveTable().m_bLocked then ent:Fire("Unlock","0") else ent:Fire("Lock","0") end end } } WEAPON_ALYX_EMP.EMPHandlers:AddHandlers(basic_handlers)
local cli = require("tn.cli") local core = require("tn.core") local M = {} local function run() local editor = os.getenv("EDITOR") or os.getenv("VISUAL") local notes_dir_envvar = "TN_NOTES_DIR" local notes_dir = os.getenv(notes_dir_envvar) if not notes_dir then cli.write_message(io.stderr, "unable to local document directory, please set " .. notes_dir_envvar .."\n") os.exit(1) end if not editor then cli.write_message(io.stderr, "unable to determine editor, please set EDITOR variable\n") os.exit(1) end local success, cmd = pcall(cli.parse_args, arg) if not success or (cmd.options and cmd.options.help) then cli.write_usage(io.stderr) os.exit(1) end if cmd.options then if cmd.options.version then cli.write_version(io.stdout) os.exit(0) end if cmd.options["bash-completion"] then cli.write_bash_compl(io.stdout) os.exit(0) end if cmd.options.commands then cli.write_commands_compl(io.stdout) os.exit(0) end end local tn = core.Tn(notes_dir, editor, "md") if cmd.subcmd == "show" then local name = cmd.args[1] tn:show(name) end if cmd.subcmd == "list" then tn:list() end if cmd.subcmd == "file" then local name = cmd.args[1] local _, err = pcall(tn.file, tn, name) if err then os.exit(1) end end if cmd.subcmd == "edit" then local name = cmd.args[1] tn:edit(name) end if cmd.subcmd == "remove" then local name = cmd.args[1] tn:remove(name) end end M.run = run return M
----------------------------------- -- Area: Kazham -- NPC: Nenepp -- Standard Info NPC ----------------------------------- local ID = require("scripts/zones/Kazham/IDs") require("scripts/globals/pathfind") require("scripts/globals/quests") require("scripts/globals/titles") ----------------------------------- local path = { 29.014000, -11.00000, -183.884000, 31.023000, -11.00000, -183.538000, 33.091000, -11.00000, -183.738000 } function onSpawn(npc) npc:initNpcAi() npc:setPos(tpz.path.first(path)) onPath(npc) end function onPath(npc) tpz.path.patrol(npc, path) end function onTrade(player, npc, trade) -- item IDs -- 483 Broken Mithran Fishing Rod -- 22 Workbench -- 1008 Ten of Coins -- 1157 Sands of Silence -- 1158 Wandering Bulb -- 904 Giant Fish Bones -- 4599 Blackened Toad -- 905 Wyvern Skull -- 1147 Ancient Salt -- 4600 Lucky Egg local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.THE_OPO_OPO_AND_I) local progress = player:getCharVar("OPO_OPO_PROGRESS") local failed = player:getCharVar("OPO_OPO_FAILED") local goodtrade = trade:hasItemQty(4600, 1) local badtrade = (trade:hasItemQty(483, 1) or trade:hasItemQty(22, 1) or trade:hasItemQty(1157, 1) or trade:hasItemQty(1158, 1) or trade:hasItemQty(904, 1) or trade:hasItemQty(1008, 1) or trade:hasItemQty(905, 1) or trade:hasItemQty(4599, 1) or trade:hasItemQty(1147, 1)) if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if progress == 9 or failed == 10 then if goodtrade then player:startEvent(241) elseif badtrade then player:startEvent(238) end end end end function onTrigger(player, npc) local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.THE_OPO_OPO_AND_I) local progress = player:getCharVar("OPO_OPO_PROGRESS") local failed = player:getCharVar("OPO_OPO_FAILED") local retry = player:getCharVar("OPO_OPO_RETRY") if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if retry >= 1 then -- has failed on future npc so disregard previous successful trade player:startEvent(206) npc:wait() elseif (progress == 9 or failed == 10) then player:startEvent(212) -- asking for lucky egg elseif (progress >= 10 or failed >= 11) then player:startEvent(250) -- happy with lucky egg end else player:startEvent(206) npc:wait() end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option, npc) if (csid == 241) then -- correct trade, finished quest and receive opo opo crown and 3 pamamas local FreeSlots = player:getFreeSlotsCount() if (FreeSlots >= 4) then player:tradeComplete() player:addFame(KAZHAM, 75) player:completeQuest(OUTLANDS, tpz.quest.id.outlands.THE_OPO_OPO_AND_I) player:addItem(13870) -- opo opo crown player:messageSpecial(ID.text.ITEM_OBTAINED, 13870) player:addItem(4468, 3) -- 3 pamamas player:messageSpecial(ID.text.ITEM_OBTAINED, 4468, 3) player:setCharVar("OPO_OPO_PROGRESS", 0) player:setCharVar("OPO_OPO_FAILED", 0) player:setCharVar("OPO_OPO_RETRY", 0) player:setTitle(tpz.title.KING_OF_THE_OPOOPOS) else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED) end elseif (csid == 238) then -- wrong trade, restart at first opo player:setCharVar("OPO_OPO_FAILED", 1) player:setCharVar("OPO_OPO_RETRY", 10) else npc:wait(0) end end
require("lead-recipe-final-stacking") require("lead-recipe-modules") require("lead-recipe-colors") require("lead-recipe-final-5d") require("lead-recipe-final-rrr") ---- local util = require("__bzlead__.util"); if (not mods["pyrawores"] and not mods["bobplates"] and not mods["angelssmelting"]) then -- If furnaces are treated as furnaces, we need 2 outputs for i, entity in pairs(data.raw.furnace) do if entity.result_inventory_size ~= nil and entity.result_inventory_size < 2 and util.contains(entity.crafting_categories, "smelting") then entity.result_inventory_size = 2 end end end if mods["Krastorio2"] then util.replace_ingredient("rifle-magazine", "iron-plate", "lead-plate") util.replace_ingredient("anti-material-rifle-magazine", "iron-plate", "lead-plate") util.replace_some_ingredient("kr-crusher", "iron-beam", "lead-plate", 5) util.replace_ingredient("kr-shelter", "iron-plate", "lead-plate") util.add_ingredient("kr-advanced-furnace", "lead-plate", 20) util.replace_ingredient("uranium-fuel-cell", "steel-plate", "lead-plate") util.replace_some_ingredient("kr-fluid-storage-1", "steel-plate", "lead-plate", 10) util.replace_some_ingredient("kr-fluid-storage-2", "steel-plate", "lead-plate", 30) end if mods["space-exploration"] then util.replace_some_ingredient("se-pulveriser", "iron-plate", "lead-plate", 10) util.replace_some_ingredient("se-canister", "copper-plate", "lead-plate", 5) util.add_ingredient("industrial-furnace", "lead-plate", 20) util.add_ingredient("se-material-testing-pack", "lead-plate", 1) -- Organization data.raw.item["lead-plate"].subgroup = "plates" data.raw.recipe["lead-plate"].subgroup = "plates" end
-- AreCoordsCollidingWithExterior() local OwnedHouse = nil local AvailableHouses = {} local blips = {} local Knockings = {} local housespawn = false Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end while ESX.GetPlayerData().job == nil do Wait(0) end TriggerServerEvent('umt-warehouse:getOwned') while OwnedHouse == nil do Wait(0) end local WareHouse = AddBlipForCoord(vector3(Config.WareHouseBB["x"], Config.WareHouseBB["y"], Config.WareHouseBB["z"])) SetBlipSprite(WareHouse, 369) SetBlipColour(WareHouse, 2) SetBlipAsShortRange(WareHouse, true) SetBlipScale(WareHouse, 0.7) BeginTextCommandSetBlipName("STRING") AddTextComponentString("Warehouse") EndTextCommandSetBlipName(WareHouse) end) RegisterCommand('whenter', function() for k, v in pairs(Config.Houses) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 6.5 then -- HelpText('Warehouse gir /enter', k) toggleField(true) end end end) function HouseBuyMenu() ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'houseBuyFirstMenu', { title = 'Warehouses', align = 'left', elements = { {label = "Warehouse Satın Al", value = "warehouse_buy"}, {label = "Satın Aldığım Warehouse", value = "evlerim"}, {label = "Satın Alınabilen Warehouseleri Göster/Gizle", value = "evgoster"} } },function(data, menu) if data.current.value == "warehouse_buy" then BuyHouse() elseif data.current.value == "evlerim" then myHouse() elseif data.current.value == "evgoster" then menu.close() satilanEvler() end end,function(data, menu) menu.close() end) end function BuyHouse() local elements = {} local Houses = Config.Houses local doorID = Config.Houses[i] for x, y in pairs(Houses) do table.insert(elements, {label = x .." Nolu Warehouse Satın Al $".. Houses[x]["price"], value = x}) end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'buyHouse', { title = 'Depo Evi Satın Al', align = 'left', elements = elements },function(data, menu) if data.current.value then local evNo = data.current.value ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'buyHouseSoru', { title = evNo .. ' Nolu Warehouse Satın Almak İçin Emin misin', align = 'left', elements = { {label = "Evet", value = "yes"}, {label = "Hayır", value = "no"} } },function(data2, menu2) menu2.close() if data2.current.value == "yes" then ESX.UI.Menu.CloseAll() TriggerServerEvent('umt-warehouse:buyHouse', evNo) PlaySoundFrontend(-1, "LOOSE_MATCH", "HUD_MINI_GAME_SOUNDSET", 0) ChangePassword(evNo) end end,function(data2, menu2) menu2.close() end) end end,function(data, menu) menu.close() end) end function ChangePassword(evNo) ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'Ev Şifresi', { title = "Ev Şifresini Giriniz", }, function (data2, menu) local password = data2.value if password ~= nil then -- and newpassword == '' TriggerServerEvent("umt-warehouse:changeHousePassword", evNo, password ) TriggerEvent('notification', 'Şifreniz kayıt oldu! '.. '=> ' .. password, 2) menu.close() else TriggerEvent('notification', 'Geçersiz şifre!', 2) menu.close() end end, function (data2, menu) menu.close() end) end -- Kendi evini gösterme ve satma function myHouse() local elements = {} local evNo = OwnedHouse.houseId for k, v in pairs(Config.Houses) do if OwnedHouse.houseId == k then fiyat = math.floor(Config.Houses[k]['price']*(Config.SellPercentage/100)) if anahtar then table.insert(elements, {label = OwnedHouse.houseId .." Nolu Warehouse Anahtarını Bırak", value = OwnedHouse.houseId, durum = "sat"}) else table.insert(elements, {label = OwnedHouse.houseId .." Nolu Warehouseni Sat $".. fiyat, value = OwnedHouse.houseId, durum = "sat"}) table.insert(elements, {label = "Warehouse Şifresini Oluştur/Değiştir", value = OwnedHouse.houseId, durum = "sifre_degis"}) table.insert(elements, {label = "", value = OwnedHouse.houseId, durum = ""}) table.insert(elements, {label = "GARAJ (Yakında)", value = OwnedHouse.houseId, durum = "opengaragemenu"}) end end end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'myHouse', { title = 'Warehouse System', align = 'left', elements = elements },function(data, menu) if data.current.value then if data.current.durum == "sat" then if anahtar then yazi = data.current.value .. " Nolu Warehousenin Anahtarını Bırak" else yazi = data.current.value .. " Nolu Warehouse ".. fiyat .."$ Karşılığında Satmak İstediğinden Eminmisin" end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'myHouseSoruMenu', { title = yazi, align = 'left', elements = { {label = "Evet", value = "yes"}, {label = "Hayır", value = "no"} } },function(data2, menu2) menu2.close() if data2.current.value == "yes" then ESX.UI.Menu.CloseAll() TriggerServerEvent('umt-warehouse:sellHouse', data.current.value, anahtar) satinalindi = true end end,function(data2, menu2) menu2.close() end) elseif data.current.durum == "anahtar" then local player, distance = ESX.Game.GetClosestPlayer() if distance ~= -1 and distance <= 3.0 then TriggerServerEvent('umt-warehouse:anahtar-ver', GetPlayerServerId(player), data.current.value) else ESX.ShowNotification('Yakınlarda Kimse Yok') end elseif data.current.durum == "sifre_degis" then ESX.UI.Menu.CloseAll() ChangePassword(evNo) elseif data.current.durum == "opengaragemenu" then OpenGarageMenu() end end end,function(data, menu) menu.close() end) end function OpenGarageMenu() ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'pawn_sell_menu', { title = 'Araç garajı', elements = { {label = 'Garaja gir', value = 'opengarage'}, {label = '', value = ''}, {label = 'Aracını garaja çek', value = 'putgarage'}, } }, function(data, menu) if data.current.value == 'opengarage' then local coords = Config.Houses[OwnedHouse.houseId]['door'] local found, coords, heading = GetClosestVehicleNodeWithHeading(coords.x, coords.y, coords.z, 3.0, 100.0, 2.5) if found then ESX.UI.Menu.CloseAll() TriggerServerEvent('esx_garage:viewVehicles', coords, heading, 'housing') return else ESX.ShowNotification(Strings['No_Spawn']) end elseif data.current.value == 'putgarage' then if OwnedHouse.houseId == k then TriggerEvent('esx_garage:storeVehicle', 'housing') end end end, function(data, menu) menu.close() end ) end function satilanEvler() if not goster then goster = true for k, v in pairs(Config.Houses) do CreateBlip(v['door'], 374, 0, 0.45, '') end TriggerEvent('notification', 'Haritada Satın Alınabilen Evler Açıldı!', 2) else goster = false for k, v in pairs(blips) do RemoveBlip(v) end TriggerEvent('notification', 'Haritada Satın Alınabilen Evler Kapatıldı!', 2) end end RegisterNetEvent('umt-warehouse:spawnHouse') AddEventHandler('umt-warehouse:spawnHouse', function(coords, furniture) local prop = Config.Houses[OwnedHouse.houseId]['prop'] local house = EnterHouse(Config.Props[prop], coords) local player = PlayerPedId() local placed_furniture = {} for k, v in pairs(OwnedHouse['furniture']) do local model = GetHashKey(v['object']) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3])), false, false, false) SetEntityHeading(object, v['heading']) FreezeEntityPosition(object, true) SetEntityCoordsNoOffset(object, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3]))) table.insert(placed_furniture, object) end SetEntityHeading(house, 0.0) local exit = GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['door']) local storage = GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['storage']) -- local tablet = GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['tablet']) TriggerServerEvent('umt-warehouse:setInstanceCoords', exit, coords, prop, OwnedHouse['furniture']) DoScreenFadeOut(300) while not IsScreenFadedOut() do Wait(0) end for i = 1, 25 do if IsPedInAnyVehicle(player, true) then SetEntityCoords(GetVehiclePedIsUsing(player), exit) FreezeEntityPosition(PlayerPedId(), true) Wait(50) FreezeEntityPosition(PlayerPedId(), false) else SetEntityCoords(PlayerPedId(), exit) Wait(50) end end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), exit) Wait(50) end DoScreenFadeIn(300) local in_house = true ClearPedWetness(PlayerPedId()) while in_house do NetworkOverrideClockTime(15, 0, 0) ClearOverrideWeather() ClearWeatherTypePersist() SetWeatherTypePersist('EXTRASUNNY') SetWeatherTypeNow('EXTRASUNNY') SetWeatherTypeNowPersist('EXTRASUNNY') if Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 9.2 then DrawText3D(storage, "[E] Depo") HelpText('[E] Depo', storage) if IsControlJustReleased(0, 38) and Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 9.2 then ESX.UI.Menu.CloseAll() TriggerEvent("disc-inventoryhud:stash", "Warehouse - "..tostring(OwnedHouse.houseId)) end end if Vdist2(GetEntityCoords(PlayerPedId()), exit) <= 10 then HelpText('[E] - ÇIKIŞ', exit) if IsControlJustReleased(0, 38) then ESX.UI.Menu.CloseAll() local elements = { {label = 'Emin misiniz?', value = 'exit'}, } ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'manage_door', { title = 'Çıkış Yap', align = 'right', elements = elements, }, function(data, menu) if data.current.value == 'exit' then -- ESX.TriggerServerCallback('umt-warehouse:hasGuests', function(has) if not has then ESX.UI.Menu.CloseAll() TriggerServerEvent('umt-warehouse:deleteInstance') Wait(500) in_house = false housespawn = false return else ESX.ShowNotification(Strings['Guests']) end -- end) end end, function(data, menu) menu.close() end) end end Wait(0) end DeleteObject(house) for k, v in pairs(placed_furniture) do DeleteObject(v) end end) RegisterNetEvent('umt-warehouse:leaveHouse') AddEventHandler('umt-warehouse:leaveHouse', function(house) local player = PlayerPedId() local vehicle = GetVehiclePedIsIn(playerPed, false) DoScreenFadeOut(300) while not IsScreenFadedOut() do Wait(0) end if IsPedInAnyVehicle(player, true) then SetEntityCoords(GetVehiclePedIsUsing(PlayerPedId()), Config.Houses[house]['door']) else SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end end -- DeleteObject(house) DoScreenFadeIn(300) end) RegisterNetEvent('umt-warehouse:reloadHouses') AddEventHandler('umt-warehouse:reloadHouses', function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end while ESX.GetPlayerData().job == nil do Wait(0) end TriggerServerEvent('umt-warehouse:getOwned') end) RegisterNetEvent('umt-warehouse:setHouse') AddEventHandler('umt-warehouse:setHouse', function(house, purchasedHouses) OwnedHouse = house for k, v in pairs(blips) do RemoveBlip(v) end for k, v in pairs(purchasedHouses) do if v.houseid ~= OwnedHouse.houseId then AvailableHouses[v.houseid] = v.houseid end end for k, v in pairs(Config.Houses) do if OwnedHouse.houseId == k then CreateBlip(v['door'], 40, 3, 0.75, Strings['Your_House']) else if not AvailableHouses[k] then if Config.AddHouseBlips then CreateBlip(v['door'], 374, 0, 0.45, '') end else if Config.AddBoughtHouses then CreateBlip(v['door'], 374, 2, 0.45, Strings['Player_House']) end end end end end) EnterHouse = function(prop, coords) local obj = CreateObject(prop, coords, false) FreezeEntityPosition(obj, true) return obj end HelpText = function(msg, coords) if not coords or not Config.Use3DText then AddTextEntry(GetCurrentResourceName(), msg) DisplayHelpTextThisFrame(GetCurrentResourceName(), false) else DrawText3D(coords, string.gsub(msg, "~INPUT_CONTEXT~", "~r~[~w~E~r~]~w~"), 0.35) end end CreateBlip = function(coords, sprite, colour, scale, text) local blip = AddBlipForCoord(coords) SetBlipSprite(blip, sprite) SetBlipColour(blip, colour) SetBlipAsShortRange(blip, true) SetBlipScale(blip, scale) BeginTextCommandSetBlipName("STRING") AddTextComponentString(text) EndTextCommandSetBlipName(blip) table.insert(blips, blip) end local enableField = false function toggleField(enable) SetNuiFocus(enable, enable) enableField = enable SendNUIMessage({ type = "enableui", enable = enable }) end RegisterNUICallback('escape', function(data, cb) toggleField(false) SetNuiFocus(false, false) cb('ok') end) RegisterNUICallback('try', function(data, cb, evNo) toggleField(false) local code = tonumber(data.code) local playerCoords = GetEntityCoords(PlayerPedId()) local evNo = Config.Houses for k, v in pairs(evNo) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 6.5 then ESX.TriggerServerCallback('umt-warehouse:getHousePassword', function(housepassword) if housepassword == code then v.locked = not v.locked -- if OwnedHouse.houseId == k then -- EĞERKİ EV SAHİBİ HARİCİ GİRMESİNİ İSTEMİYORSAN KAPALI YERLERİ AÇABİLİRSİN TriggerServerEvent('umt-warehouse:enterHouse', k) housespawn = true -- else -- TriggerEvent('notification', 'Bu yer senin değil', 4) -- end end end, OwnedHouse.houseId) end end cb('ok') end) ----- CONTRACT KISMI ---- if OwnedHouse.houseid == k then & diyip ev ayarlarını açtırabiliriz ---- else attırıp local selectedHouse = nil local evNo = Config.Houses local satinalindi = false Citizen.CreateThread(function() local player = PlayerPedId() while true do local sleepthread = 1000 for k, v in pairs(Config.Houses) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 3.5 then if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 2.5 then sleepthread = 10 end while OwnedHouse == nil do local sleepthread = 1000 sleepthread = 10 end TriggerEvent('umt-warehouse:faraway') end end Citizen.Wait(sleepthread) end end) RegisterNetEvent('umt-warehouse:faraway') -- deneme kısmı AddEventHandler('umt-warehouse:faraway', function() for k, v in pairs(Config.Houses) do Wait(0) if OwnedHouse.houseId == k then local menuopen = false local pedCoords = GetEntityCoords(PlayerPedId()) local dst = GetDistanceBetweenCoords(pedCoords, v['door'], true) if dst <= 5.5 then DrawText3D(pedCoords, "[E] EV YONETIMI") if IsControlJustReleased(0, 38) then myHouse() menuopen = true end end else local pedCoords = GetEntityCoords(PlayerPedId()) local dst = GetDistanceBetweenCoords(pedCoords, v['door'], true) if dst <= 2.5 then -- DrawMarker(22, v['door'], vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 165, 40, 36, 150, false, false, 1, false, false, false) DrawText3D(pedCoords, "[E] SATIN AL") -- if dist <= 1.0 then if IsControlJustReleased(0, 38) then -- HelpText('[E] - satın al (DENEME)', v['door']) OpenBuyMenu(evNo) TriggerEvent('umt-warehouse:client:viewHouse', evNo) end end end end end) function OpenBuyMenu(evNo) for k, v in pairs(evNo) do openContract(true) end end RegisterNUICallback("buy", function(evNo) local evNo = Config.Houses for k, v in pairs(evNo) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 6.5 then TriggerServerEvent("umt-warehouse:buyHouse", k) Wait(200) exports['mythic_notify']:SendAlert('error', 'Ev Yönetiminden şifrenizi oluşturunuz') Wait(1200) -- SetNuiFocus(true, true) -- ChangePassword(k) satinalindi = true end end end) function InstructionButton(ControlButton) N_0xe83a3e3557a56640(ControlButton) end function InstructionButtonMessage(text) BeginTextCommandScaleformString("STRING") AddTextComponentScaleform(text) EndTextCommandScaleformString() end function disableViewCam() if viewCam then RenderScriptCams(false, true, 500, true, true) SetCamActive(cam, false) DestroyCam(cam, true) viewCam = false end end function openContract(bool) SetNuiFocus(bool, bool) SendNUIMessage({ type = "toggle", status = bool, }) contractOpen = bool end RegisterNUICallback('exit', function() openContract(false) disableViewCam() end) function setViewCam(coords, h, yaw) cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", 855.8841, -2120.14, 30.646, yaw, 0.00, h, 80.00, false, 0) SetCamActive(cam, true) RenderScriptCams(true, true, 500, true, true) viewCam = true end RegisterNetEvent('umt-warehouse:client:viewHouse') AddEventHandler('umt-warehouse:client:viewHouse', function(houseprice, brokerfee, bankfee, taxes, firstname, lastname) -- setViewCam(Config.Houses[closesthouse].coords.cam, Config.Houses[closesthouse].coords.cam.h, Config.Houses[closesthouse].coords.yaw) local evNo = Config.Houses for k, v in pairs(evNo) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 6.5 then Citizen.Wait(500) openContract(true) SendNUIMessage({ type = "setupContract", firstname = firstname, lastname = lastname, street = v['prop'], houseprice = v['price'], brokerfee = math.random(100, 100), bankfee = math.random(100, 1000), taxes = math.random(100, 4000), totalprice = (v['price'] + math.random(100, 100) + math.random(100, 1000) + math.random(100, 4000)) }) end end end)
local data_dir = vim.fn.stdpath('data') local lsp = require('modules.lsp') local capabilities = lsp.capabilities capabilities.textDocument.completion.completionItem.snippetSupport = true require'lspconfig'.cssls.setup { cmd = { "node", data_dir .. "/lspinstall/css/vscode-css/css-language-features/server/dist/node/cssServerMain.js", "--stdio" }, on_attach = lsp.common_on_attach, capabilities = capabilities }
gg.ignore_modules = { "gg%.service%.*", "gg%.like_skynet.*", "app%.game%.main", "app%.game%.httpd_main", "app%.scene%.main", } function gg.hotfix(modname) for i,prefix in ipairs({"../src/","gameserver/src/","loginserver/src/","src/"}) do if string.startswith(modname,prefix) then modname = modname:sub(#prefix+1) break end end local address = skynet.address(skynet.self()) local is_proto = modname:sub(1,5) == "proto" -- 只允许游戏逻辑+协议更新 if is_proto then local msg = string.format("op=hotfix,address=%s,module=%s",address,modname) logger.logf("info","hotfix",msg) print(msg) gg.actor.client:reload() return true end local is_path local replace_cnt modname,replace_cnt = string.gsub(modname,"/",".") if replace_cnt > 0 then is_path = true end modname,replace_cnt = string.gsub(modname,"\\",".") if replace_cnt > 0 then is_path = true end local suffix = modname:sub(-4,-1) if suffix == ".lua" then modname = modname:sub(1,-5) elseif is_path then return false,"ignore non lua file" end for i,pat in ipairs(gg.ignore_modules) do if modname == string.match(modname,pat) then return false,"ignore" end end local ok,err = gg.reload(modname) if not ok then local msg = string.format("op=hotfix,address=%s,module=%s,fail=%s",address,modname,err) logger.logf("error","hotfix",msg) print(msg) return false,msg end local msg = string.format("op=hotfix,address=%s,module=%s",address,modname) logger.logf("info","hotfix",msg) print(msg) return true end
-- Données pour le module local storeInfo = { order = 70, framed = true, text = _G.VOID_STORAGE, icon = 'Interface\\AddOns\\Kerviel\\img\\Void', } -- Environnement local Kerviel = LibStub('AceAddon-3.0'):GetAddon('Kerviel') local store = Kerviel:NewStore('VoidStorage', storeInfo) local L = LibStub('AceLocale-3.0'):GetLocale('Kerviel') -- Donnés local NUM_BLOCKS = 5 local NUM_COLUMNS_PER_BLOCK = 2 local NUM_SLOTS_PER_COLUMN = 8 local NUM_SLOTS_PER_BLOCK = NUM_COLUMNS_PER_BLOCK * NUM_SLOTS_PER_COLUMN local NUM_VOIDSTORAGE_PAGES = 2 local NUM_VOIDSTORAGE_SLOTS = NUM_BLOCKS * NUM_COLUMNS_PER_BLOCK * NUM_SLOTS_PER_COLUMN local frame, buttons local displayedPage -- Donnés sauvegardées local ns_defaults = { char = { unlocked = true, -- pages = {}, } } ------------------------------------------------------------------------------- -- Gestion du store ------------------------------------------------------------------------------- function store:IsStorageAvailableFor(charKey) local sv = rawget(self.db, 'sv') return sv.char and sv.char[charKey] and sv.char[charKey].pages end function store:SetDisplayedCharacter(msg, charKey) self:UpdateFrame(charKey) end function store:GetDataFor(charKey) local sv = rawget(self.db, 'sv') return sv.char and sv.char[charKey] end function store:GetFrame() if not frame then self:CreateFrame() end return frame end ------------------------------------------------------------------------------- -- Recherche d'objet ------------------------------------------------------------------------------- function store:SearchInChar(charKey, itemID) local results, found = nil, 0 local charData = self:GetDataFor(charKey) if charData and charData.pages then for page = 1, NUM_VOIDSTORAGE_PAGES do local pageData = charData.pages[page] or self.EmptyTable if pageData.slots then local count = 0 for j = 1, NUM_VOIDSTORAGE_SLOTS do local id, num = self:GetItem(pageData.slots, j) if id == itemID then count = count + num end end if count > 0 then results = results or Kerviel:NewTable() table.insert(results, { ['Chambre du vide #'..page] = count } ) found = found + count end end end end return found, results end ------------------------------------------------------------------------------- -- Gestion de la fenêtre ------------------------------------------------------------------------------- function store:UpdateFrame(charKey) -- Rien à faire si la frame n'est pas affichée if not frame or not frame:IsVisible() then return end -- charKey == nil > redessine la fenêtre seulement si le personnage actuel est affiché -- charKey == 'nom' > redessine la fenêtre pour le personnage demandé if not charKey then charKey = Kerviel.playerCharKey if charKey ~= Kerviel.displayedCharKey then return end end -- Trouve la DB pour le personnage demandé local charData = self:GetDataFor(charKey) if charData and charData.pages then frame.error:Hide() frame.contents:Show() if displayedPage == 1 then frame.contents.prevButton:Disable() frame.contents.nextButton:Enable() elseif displayedPage == NUM_VOIDSTORAGE_PAGES then frame.contents.prevButton:Enable() frame.contents.nextButton:Disable() end -- Redessine les 80 slots for i = 1, NUM_VOIDSTORAGE_SLOTS do self:UpdateItemButton(buttons[i], self:GetItem(charData.pages[displayedPage].slots, i)) end elseif charData and not charData.unlocked then frame.contents:Hide() frame.error:Show() frame.error.text:SetFormattedText('"%s" n\'a pas accès sa chambre du vide', charKey) else frame.contents:Hide() frame.error:Show() frame.error.text:SetFormattedText('Pas de données pour "%s"', charKey) end end ------------------------------------------------------------------------------- local function PrevButton_Click() if displayedPage > 1 then displayedPage = displayedPage - 1 store:UpdateFrame(Kerviel.displayedCharKey) end end local function NextButton_Click() if displayedPage < NUM_VOIDSTORAGE_PAGES then displayedPage = displayedPage + 1 store:UpdateFrame(Kerviel.displayedCharKey) end end local function Frame_OnShow() store:UpdateFrame(Kerviel.displayedCharKey) end function store:CreateFrame() -- Crée la frame frame = CreateFrame('Frame', nil, nil, 'KervielVoidStorageFrameTemplate') frame:SetScript('OnShow', Frame_OnShow) frame.contents.prevButton:SetScript('OnClick', PrevButton_Click) frame.contents.nextButton:SetScript('OnClick', NextButton_Click) displayedPage = 1 -- Crée les 8 * 2 * 5 = 80 boutons buttons = {} for i = 1, NUM_VOIDSTORAGE_SLOTS do local slot = CreateFrame('Button', nil, frame.contents.inner, 'KervielVoidStorageItemButtonTemplate') if i == 1 then slot:SetPoint('TOPLEFT', 10, -8) elseif (i % NUM_SLOTS_PER_COLUMN) == 1 then if (i % NUM_SLOTS_PER_BLOCK) == 1 then slot:SetPoint('TOPLEFT', buttons[i - 8], "TOPRIGHT", 14, 0) else slot:SetPoint("TOPLEFT", buttons[i - 8], "TOPRIGHT", 7, 0) end else slot:SetPoint("TOPLEFT", buttons[i - 1], "BOTTOMLEFT", 0, -5) end slot:SetID(i) table.insert(buttons, slot) end end ------------------------------------------------------------------------------- -- Gestion de la chambre du vide ------------------------------------------------------------------------------- function store:VOID_STORAGE_CONTENTS_UPDATE(evt) if self.db.char.unlocked then self.db.char.pages = Kerviel:NewTable(self.db.char.pages) for i = 1, NUM_VOIDSTORAGE_PAGES do self.db.char.pages[i] = Kerviel:NewTable(self.db.char.pages[i]) self.db.char.pages[i].slots = Kerviel:NewTable(self.db.char.pages[i].slots) for j = 1, NUM_VOIDSTORAGE_SLOTS do local id = GetVoidItemInfo(i, j) local changed = self:PutItem(self.db.char.pages[i].slots, j, id, 1) if changed and frame and frame:IsVisible() and i == displayedPage and Kerviel.displayedCharKey == Kerviel.playerCharKey then self:UpdateItemButton(buttons[j], self:GetItem(self.db.char.pages[i].slots, j)) end end end end -- Prévient la fenêtre principale de rafraîchir son menu self:NotifyUpdate() end ------------------------------------------------------------------------------- function store:VOID_STORAGE_UPDATE(evt) self.db.char.unlocked = CanUseVoidStorage() end ------------------------------------------------------------------------------- function store:VOID_TRANSFER_DONE(evt) self:VOID_STORAGE_CONTENTS_UPDATE(evt) end ------------------------------------------------------------------------------- function store:VOID_STORAGE_OPEN(evt) if IsVoidStorageReady() then self:VOID_STORAGE_CONTENTS_UPDATE(evt) end end ------------------------------------------------------------------------------- -- Initialisation ------------------------------------------------------------------------------- function store:OnEnable() -- Ecoute les événements self:RegisterEvent('VOID_STORAGE_OPEN') self:RegisterEvent('VOID_TRANSFER_DONE') self:RegisterEvent('VOID_STORAGE_UPDATE') self:RegisterEvent('VOID_STORAGE_CONTENTS_UPDATE') self:RegisterMessage('SetDisplayedCharacter') -- Pas dispo avant PLAYER_ENTERING_WORLD self.db.char.unlocked = CanUseVoidStorage() end ------------------------------------------------------------------------------- function store:OnInitialize() -- Initialise les données sauvegardées self.db = Kerviel.db:RegisterNamespace(self:GetName(), ns_defaults) end
-- =========================================================================== -- Cui In Game Note Screen -- =========================================================================== include("InstanceManager") include("cui_helper") include("cui_settings") -- =========================================================================== local cui_NoteEnter = InstanceManager:new("NoteEnter", "Top", Controls.NoteStack) local EMPTY_NOTE = Locale.Lookup("LOC_CUI_NOTE_EMPTY") local windowHeight = 0 local TOP_PANEL_OFFSET = 29 local NOTE = { NOTE0 = {field = "Note0", default = EMPTY_NOTE}, NOTE1 = {field = "Note1", default = EMPTY_NOTE}, NOTE2 = {field = "Note2", default = EMPTY_NOTE}, NOTE3 = {field = "Note3", default = EMPTY_NOTE}, NOTE4 = {field = "Note4", default = EMPTY_NOTE}, NOTE5 = {field = "Note5", default = EMPTY_NOTE}, NOTE6 = {field = "Note6", default = EMPTY_NOTE}, NOTE7 = {field = "Note7", default = EMPTY_NOTE}, NOTE8 = {field = "Note8", default = EMPTY_NOTE}, NOTE9 = {field = "Note9", default = EMPTY_NOTE} } local NOTE_TURN = { NOTE0 = {field = "NoteTurn0", default = 0}, NOTE1 = {field = "NoteTurn1", default = 0}, NOTE2 = {field = "NoteTurn2", default = 0}, NOTE3 = {field = "NoteTurn3", default = 0}, NOTE4 = {field = "NoteTurn4", default = 0}, NOTE5 = {field = "NoteTurn5", default = 0}, NOTE6 = {field = "NoteTurn6", default = 0}, NOTE7 = {field = "NoteTurn7", default = 0}, NOTE8 = {field = "NoteTurn8", default = 0}, NOTE9 = {field = "NoteTurn9", default = 0} } -- =========================================================================== function PopulateNoteList() cui_NoteEnter:ResetInstances() for i = 1, 10, 1 do local note = cui_NoteEnter:GetInstance() local index = "NOTE" .. (i - 1) local textSaved = CuiSettings:GetString(NOTE[index]) local turnSaved = CuiSettings:GetNumber(NOTE_TURN[index]) SetNote(note, textSaved, turnSaved) -- left click call back note.EditButton:RegisterCallback( Mouse.eLClick, function() note.Overview:SetHide(true) local sText = note.Overview:GetText() if IsEmpty(sText) then note.EditNote:SetText("") else note.EditNote:SetText(note.Overview:GetText()) end note.EditNote:SetHide(false) note.EditNote:TakeFocus() end ) -- right click call back note.EditButton:RegisterCallback( Mouse.eRClick, function() SetNote(note, nil, 0) SaveNote(index, nil, 0) end ) -- commit call back note.EditNote:RegisterCommitCallback( function(editBox) local userInput = note.EditNote:GetText() local currentTurn = Game.GetCurrentGameTurn() SetNote(note, userInput, currentTurn) SaveNote(index, userInput, currentTurn) end ) end Controls.NoteStack:CalculateSize() Controls.NoteStack:ReprocessAnchoring() end -- =========================================================================== function SaveNote(index, text, turn) if IsEmpty(text) then CuiSettings:SetString(NOTE[index], EMPTY_NOTE) CuiSettings:SetNumber(NOTE_TURN[index], 0) else CuiSettings:SetString(NOTE[index], text) CuiSettings:SetNumber(NOTE_TURN[index], turn) end end -- =========================================================================== function IsEmpty(text) if text == nil then return true end if text == EMPTY_NOTE then return true end if string.gsub(text, "^%s*(.-)%s*$", "%1") == nil then return true end return false end -- =========================================================================== function SetNote(note, text, turn) note.EditNote:SetHide(true) if IsEmpty(text) then note.Overview:SetText(EMPTY_NOTE) note.Overview:SetColorByName("Gray") turn = 0 else note.Overview:SetText(text) note.Overview:SetColorByName("White") end note.Overview:SetHide(false) if turn == 0 then note.LastEdit:SetText("") else note.LastEdit:SetText(Locale.Lookup("LOC_CUI_NOTE_LAST_EDIT", turn)) end end -- =========================================================================== function CloseOtherPanel() LuaEvents.LaunchBar_CloseTechTree() LuaEvents.LaunchBar_CloseCivicsTree() LuaEvents.LaunchBar_CloseGovernmentPanel() LuaEvents.LaunchBar_CloseReligionPanel() LuaEvents.LaunchBar_CloseGreatPeoplePopup() LuaEvents.LaunchBar_CloseGreatWorksOverview() if isExpansion1 then LuaEvents.GovernorPanel_Close() LuaEvents.HistoricMoments_Close() end if isExpansion2 then LuaEvents.Launchbar_Expansion2_ClimateScreen_Close() end end -- =========================================================================== function Open() if (Game.GetLocalPlayer() == -1) then return end CloseOtherPanel() if not UIManager:IsInPopupQueue(ContextPtr) then local kParameters = {} kParameters.RenderAtCurrentParent = true kParameters.InputAtCurrentParent = true kParameters.AlwaysVisibleInQueue = true UIManager:QueuePopup(ContextPtr, PopupPriority.Low, kParameters) UI.PlaySound("UI_Screen_Open") end PopulateNoteList() Controls.Vignette:SetSizeY(windowHeight) -- FullScreenVignetteConsumer Controls.ScreenAnimIn:SetToBeginning() Controls.ScreenAnimIn:Play() end -- =========================================================================== function Close() if not ContextPtr:IsHidden() then UI.PlaySound("UI_Screen_Close") end UIManager:DequeuePopup(ContextPtr) end -- =========================================================================== function ToggleNoteScreen() if ContextPtr:IsHidden() then Open() else Close() end end -- =========================================================================== function OnInit(isReload) if isReload then if not ContextPtr:IsHidden() then Open() end end end -- =========================================================================== function OnInputHandler(pInputStruct) local uiMsg = pInputStruct:GetMessageType() if uiMsg == KeyEvents.KeyUp then local uiKey = pInputStruct:GetKey() if uiKey == Keys.VK_ESCAPE then if not ContextPtr:IsHidden() then Close() return true end end end return false end -- =========================================================================== function Initialize() ContextPtr:SetHide(true) ContextPtr:SetInitHandler(OnInit) ContextPtr:SetInputHandler(OnInputHandler, true) Controls.CloseButton:RegisterCallback(Mouse.eLClick, Close) Controls.CloseButton:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end ) LuaEvents.Cui_ToggleNoteScreen.Add(ToggleNoteScreen) windowHeight = Controls.Vignette:GetSizeY() - TOP_PANEL_OFFSET end Initialize()
local locations = require("lua.locations") local locationsPositions = require("lua.locationspositions") local currentLocation = false local characters = { ["Fred"] = { x = 0, y = 0, z = 0, animationOffset = {0, 0}, visible = true, animation = "", rotation = "A", }, ["Grucha"] = { x = 0, y = 0, z = 0, animationOffset = {0, 0}, visible = false, animation = "", rotation = "A", }, } function getCharacterDirection(name) return characters[name].rotation end function restoreNpcPrevAnimation(anim) for k,v in pairs(characters) do if v.animation:lower() == anim:lower() then changeNpcAnimation(k, k .. "_stoi_" .. v.rotation) end end end function changeNpcAnimation(name, anim) if not characters[name] then return end local animation_old = getIdleAnimationData(characters[name].animation, name) local animation_new = getIdleAnimationData(anim, name) --local x, y = animation_new.attr.StartOffsetX, animation_new.attr.StartOffsetY local x, y = characters[name].animationOffset[1], characters[name].animationOffset[2] x, y = x + animation_new.attr.StartOffsetX, y + animation_new.attr.StartOffsetY if animation_old then x = x - animation_old.attr.EndOffsetX y = y - animation_old.attr.EndOffsetY end characters[name].animationOffset = {x, y} characters[name].animation = anim end function changeNpcAnimationToEnd(name) if not characters[name] then return end local animation = getIdleAnimationData(characters[name].animation, name) animation.Cycle.Current = 2 end function findLocationByName(name) for k,v in pairs(locations) do if v.attr.name == name then return v end end end function setCharacterVisible(name, state) if characters[name] then characters[name].visible = state return true end return false end function getHotpointByName(name) for _,location in pairs(locations) do for _,hotpoint in pairs(location.Hotpoints.Hotpoint) do if (hotpoint.attr and hotpoint.attr.name:lower() == name:lower() and hotpoint.attr.id:lower():find(currentLocation.attr.name:lower())) or (hotpoint.attr and hotpoint.attr.id:lower() == name:lower()) then return hotpoint end end end end function getHotpointFromAct(name) if not currentLocation then return false end local currentWorld = currentLocation.attr.name:upper() for d,c in pairs(getCurrentAct().Acts) do if c.name:upper() == currentWorld:upper() then for k,v in pairs(c.Hotpoints) do if v.id:upper() == name:upper() then return v end end break end end end function renderHotpoints(hotpoints) for k,c in pairs(hotpoints) do local v = c.attr local actdata = getHotpointFromAct(v.id) local visible = (actdata.display == "") if visible then local x, y = getScreenFromWorldPosition(v.x, v.y) local z = tonumber(v.z) if v.bitmap then local image = getImageByName(v.bitmap) dxDrawAbsoluteImage3D(x, y, 1, z, ('data/graphics/%08d.png'):format(image)) elseif v.idle_animation then renderIdleAnimation(x, y, z, v.idle_animation) end end end end function renderLayers(layers) for k,v in pairs(layers) do local x, y = getScreenFromWorldPosition(v.Position.attr.x, v.Position.attr.y) local z = tonumber(v.Depth.attr.z) local image = getImageByName(v.attr.name) dxDrawAbsoluteImage3D(x, y, 1, z, ('data/graphics/%08d.png'):format(image)) end end function renderBackgroundAnimations(layers) for k,v in pairs(layers) do local x, y = getScreenFromWorldPosition(v.attr.x, v.attr.y) local z = tonumber(v.attr.z) renderIdleAnimation(x, y, z, v.Animation) end end function findLocationChange(source, dest) for k,v in pairs(locationsPositions) do if v.source == source:upper() and v.dest == (dest or "NULL"):upper() then return v end end end function isInvertCloser(source, dest) if source == "A" and (dest == "H" or dest == "G" or dest == "F") then return true elseif source == "B" and (dest == "A" or dest == "H" or dest == "G") then return true elseif source == "C" and (dest == "B" or dest == "A" or dest == "H") then return true elseif source == "D" and (dest == "C" or dest == "B" or dest == "A") then return true elseif source == "E" and (dest == "D" or dest == "C" or dest == "B") then return true elseif source == "F" and (dest == "E" or dest == "D" or dest == "C") then return true elseif source == "G" and (dest == "F" or dest == "E" or dest == "D") then return true elseif source == "H" and (dest == "G" or dest == "F" or dest == "E") then return true end return false end function rotateNpc(name, dest) if characters[name].rotation == dest then print(characters[name].rotation .. " , " .. dest) return true end characters[name].rotateDest = dest local frame = getFrameByRotation(characters[name].rotation) assert(frame, "Zbugowałeś gre! (brak rotacji dla " .. name .. ")") local invert = isInvertCloser(characters[name].rotation, dest) if invert then frame = 23 - frame end if frame then setIdleAnimationFrame(name .. "_obrot" .. (invert and "_invert" or ""), frame) end changeNpcAnimation(name, name .. "_obrot" .. (invert and "_invert" or "")) return false end function getZFromWisMap(x, y) local image = getImageByName(currentLocation.attr.GameLogicMap) image = ('data/graphics/%08d.png'):format(image) local r, g, b = getImagePixelColor(x, y, image) return tonumber(g*255), (r>0.5) end function setWorld(name) local world = findLocationByName(name) if not world then return error("Lokacja nie istnieje!") end local prev = (currentLocation and currentLocation.attr.name) local change = findLocationChange(name, prev) currentLocation = world if change then characters.Fred.x = tonumber(change.fred_x) characters.Fred.y = tonumber(change.fred_y) local z, walkAble = getZFromWisMap(characters.Fred.x, characters.Fred.y) characters.Fred.z = z characters.Fred.rotation = change.fred_direction end onWorldChangeCutscene(name, prev) end local rotations = { [0] = "A", [3] = "B", [6] = "C", [9] = "D", [12] = "E", [15] = "F", [18] = "G", [21] = "H" } function getRotationByFrame(id) local id = tonumber(id) return rotations[id] end function getFrameByRotation(rot) for k,v in pairs(rotations) do if v == rot then return k end end return false end function renderCharacters(c) for k,v in pairs(c) do if v.visible then local animation = v.animation if type(animation) == "string" then animation = getIdleAnimationData(animation, k) end if v.animation:lower():find("_obrot") and v.rotateDest then local current = (animation.Cycle.Current or 1) local Cycle = stringToTable(animation.Cycle[current].attr.frames) local rotation = getRotationByFrame(Cycle[animation.Cycle[current].Current]) if rotation then v.rotation = rotation end if rotation == v.rotateDest then changeNpcAnimation(k, k .. "_stoi_" .. rotation) v.rotateDest = false onEndRotating() end end local scale = v.z/255+0.02 local x, y, z = v.x - v.animationOffset[1]*scale, v.y - v.animationOffset[2]*scale, v.z local w, h = getIdleAnimationSize(animation, k) w, h = w*scale, h*scale local x, y = getScreenFromWorldPosition(x, y) renderIdleAnimation(x, y, z, animation, w, h) end end end function setHotpointVisible(name, state) if not currentLocation then return end for k,v in pairs(currentLocation.Hotpoints.Hotpoint) do if v.attr.id:lower() == name:lower() then local actdata = getHotpointFromAct(v.attr.id) v.attr.Visible = (state and "1" or "0") actdata.display = (state and "" or "invisible") end end end function renderWorld() if not currentLocation then return end renderHotpoints(currentLocation.Hotpoints.Hotpoint) renderLayers(currentLocation.Layers.Layer) renderBackgroundAnimations(currentLocation.BackgroundAnimations.BackgroundAnimation) renderCharacters(characters) draw3DElements() end setWorld("Polana z grobem")
local tiny = require "lib/tiny" local collision = tiny.processingSystem() collision.filter = tiny.requireAll("map", "collision_layer") function collision:onAdd(e) local world for _, e in ipairs(self.world.entities) do if world then break end local filter = tiny.requireAll("box2d", "world") if filter(self.world, e) then world = e.world break end end for _, collider in ipairs(e.map_collision) do local shape = collider.shape local box2d_collider if shape == "polygon" then box2d_collider = world:newPolygonCollider(collider.points) end if shape == "rectangle" then box2d_collider = world:newRectangleCollider(collider.x, collider.y, collider.width, collider.height) end if shape == "ellipse" then print("ellipse not implemented") end if box2d_collider then box2d_collider:setType('static') end end end return collision
-------------------------------------------------------------------------------- --[[ Gravity Demonstrates the effect of the gravity parameter on particles. --]] -------------------------------------------------------------------------------- local CBE = require("CBE.CBE") local sample = CBE.newVent({ title = "laserVent", preset = "lasergun", positionType = "inRadius", -- Add a bit of randomness to the position rotateTowardVel = true, towardVelOffset = 90, lifeTime = 300, physics = { velocity = 20, gravityY = 0.5, autoCalculateAngles = true, angles = {{45, 65}} } }) sample:start()
local LoggerLib = require("__DedLib__/modules/logger") local Logger = LoggerLib.create("Template") local Util = require("__DedLib__/modules/util") local Storage = {} Storage.__index = Storage --[[ Quick usage: - call Storage.new() with on_init and on_load functions to handle those events - add Storage:on_init() and Storage:on_load() in your on_init/on_load respectively - - Alternatively, call the on_init_wrapped()/on_load_wrapped() if they are not in a function -- i.e. script.on_init(Storage:on_init_wrapped()) - call Storage:build_loggers() after any sub sections are created - - Storage.DataTypeName = {} with functions in this table are assumed, they can access their own logger at `Storage.DataTypeName._LOGGER` or `Storage.DataTypeName.get_logger()` In functions you can access a cached `Storage.global` which is a direct reference to the normal global (This access is _slightly_ faster for rapid use) ]]-- function Storage.new(args) local new = {} setmetatable(new, Storage) new.on_init_func = Util.ternary(type(args.on_init) == "function", args.on_init, function() end) new.on_load_func = Util.ternary(type(args.on_load) == "function", args.on_load, function() end) return new end function Storage:on_init() Logger:trace("Running Storage on_init...") Storage._cache_global() self:on_init_func() end function Storage:on_init_wrapped() return function() self:on_init() end end function Storage:on_load() Logger:trace("Running Storage on_load...") Storage._cache_global() self:on_load_func() end function Storage:on_load_wrapped() return function() self:on_load() end end function Storage:build_loggers() for name, subSection in pairs(self) do if type(subSection) == "table" then Logger:trace("Building Storage logger for %s", name) subSection._LOGGER = LoggerLib.create(name) function subSection.get_logger() return subSection._LOGGER end end end end -- Internal Methods function Storage._cache_global() Storage.global = global return Storage.global end return Storage
local t = { aaa = 123, bbb = 546 } function fff() local t = 123, b, c, d, e local function func() if aa then local t = 1231 end end return func end
-- crude implementation local breakpointer = {} local boundGuis = {} -- Store a list of breakpoints local breakpoints = { {"xs", 0}, {"sm", 576}, {"md", 768}, {"lg", 992}, {"xl", 1200}, {"xxl", 1600} } -- Remap these breakpoints into a dictionary for the end-user breakpointer.breakpoints = {} for i, v in pairs(breakpoints) do breakpointer.breakpoints[v[1]] = v[2] breakpoints[i][3] = i end local function getBreakpointFromSize(size) for _, v in pairs(breakpoints) do if v[2] == size then return v end end end -- Logic for selecting a breakpoint based on screen size local currentBreakpoint = breakpoints[1] local selectBreakpoint = function() local screenSize = core.input.screenSize currentBreakpoint = breakpoints[#breakpoints] for i = 1, #breakpoints do local bp = breakpoints[i] if bp[2] < screenSize.x then currentBreakpoint = bp end end print("BP is now", currentBreakpoint[1]) end selectBreakpoint() -- Logic for updating bound UIs on screen resize local updateUI = function(object) -- select appropriate breakpoint if boundGuis[object] and boundGuis[object][currentBreakpoint[1]] then for k, v in pairs(boundGuis[object][currentBreakpoint[1]]) do object[k] = v end end end -- Logic for binding a breakpoint to a object function breakpointer:bind(object, breakpoint, properties) local bp = breakpointer.breakpoints[breakpoint] if not type(breakpoint) == "string" or not bp then return error("Breakpoint invalid", 2) end bp = getBreakpointFromSize(bp) if not boundGuis[object] then boundGuis[object] = {} for _, v in pairs(breakpoints) do boundGuis[object][v[1]] = {} end object:on("destroying", function() boundGuis[object] = nil end) end for k, v in pairs(properties) do if object[k] ~= nil and type(object[k]) ~= "function" then -- apply properties to all breakpoints higher for i = bp[3], #breakpoints, 1 do local breakpoint = breakpoints[i] boundGuis[object][breakpoint[1]][k] = v end boundGuis[object][bp[1]][k] = v end end updateUI(object) end local function onResized() selectBreakpoint() for gui, _ in pairs(boundGuis) do updateUI(gui) end end core.input:on("screenResized", onResized) return breakpointer
------------- -- Chicken -- ------------- local follows = {} minetest.register_on_mods_loaded(function() for name, def in pairs(minetest.registered_items) do if name:match(":seed_") or name:match("_seed") then table.insert(follows, name) end end end) creatura.register_mob("animalia:chicken", { -- Stats max_health = 5, armor_groups = {fleshy = 150}, damage = 0, speed = 4, tracking_range = 16, despawn_after = 1500, -- Entity Physics stepheight = 1.1, max_fall = 8, turn_rate = 7, -- Visuals mesh = "animalia_chicken.b3d", hitbox = { width = 0.15, height = 0.3 }, visual_size = {x = 7, y = 7}, female_textures = { "animalia_chicken_1.png", "animalia_chicken_2.png", "animalia_chicken_3.png" }, male_textures = { "animalia_rooster_1.png", "animalia_rooster_2.png", "animalia_rooster_3.png" }, child_textures = {"animalia_chick.png"}, animations = { stand = {range = {x = 0, y = 0}, speed = 1, frame_blend = 0.3, loop = true}, walk = {range = {x = 10, y = 30}, speed = 30, frame_blend = 0.3, loop = true}, run = {range = {x = 10, y = 30}, speed = 45, frame_blend = 0.3, loop = true}, fall = {range = {x = 40, y = 60}, speed = 70, frame_blend = 0.3, loop = true}, }, -- Misc catch_with_net = true, sounds = { random = { name = "animalia_chicken_idle", gain = 0.5, distance = 8 }, hurt = { name = "animalia_chicken_hurt", gain = 0.5, distance = 8 }, death = { name = "animalia_chicken_death", gain = 0.5, distance = 8 } }, drops = { {name = "animalia:poultry_raw", min = 1, max = 3, chance = 1}, {name = "animalia:feather", min = 1, max = 3, chance = 2} }, follow = follows, head_data = { offset = {x = 0, y = 0.15, z = 0}, pitch_correction = 55, pivot_h = 0.25, pivot_v = 0.55 }, -- Function utility_stack = { [1] = { utility = "animalia:wander", get_score = function(self) return 0.1, {self, true} end }, [2] = { utility = "animalia:resist_fall", get_score = function(self) if not self.touching_ground then return 0.11, {self} end return 0 end }, [3] = { utility = "animalia:swim_to_land", get_score = function(self) if self.in_liquid then return 1, {self} end return 0 end }, [4] = { utility = "animalia:follow_player", get_score = function(self) if self.lasso_origin and type(self.lasso_origin) == "userdata" then return 0.8, {self, self.lasso_origin, true} end local player = creatura.get_nearby_player(self) if player and self:follow_wielded_item(player) then return 0.8, {self, player} end return 0 end }, [5] = { utility = "animalia:bird_breed", get_score = function(self) if self.breeding then return 0.9, {self} end return 0 end } }, activate_func = function(self) animalia.initialize_api(self) animalia.initialize_lasso(self) self.attention_span = 8 self._path = {} end, step_func = function(self) animalia.step_timers(self) animalia.head_tracking(self, 0.75, 0.75) animalia.do_growth(self, 60) animalia.update_lasso_effects(self) end, death_func = function(self) if self:get_utility() ~= "animalia:die" then self:initiate_utility("animalia:die", self) end end, on_rightclick = function(self, clicker) if animalia.feed(self, clicker, false, true) then return end animalia.add_libri_page(self, clicker, {name = "chicken", form = "pg_chicken;Chickens"}) end, on_punch = function(self, puncher, time_from_last_punch, tool_capabilities, direction, damage) creatura.basic_punch_func(self, puncher, time_from_last_punch, tool_capabilities, direction, damage) self:initiate_utility("animalia:flee_from_player", self, puncher) self:set_utility_score(1) end }) creatura.register_spawn_egg("animalia:chicken", "c6c6c6", "d22222")
slot0 = class("WorldMapTheme", import("...BaseEntity")) slot0.Fields = { sinAngle = "number", cellSpace = "table", fov = "number", offsetx = "number", assetSea = "string", offsetz = "number", cosAngle = "number", offsety = "number", cellSize = "table", angle = "number" } slot0.Setup = function (slot0, slot1) slot0.assetSea = slot1[1] slot0.angle = slot1[2] slot0.fov = slot1[3] slot0.offsetx = slot1[4] slot0.offsety = slot1[5] slot0.cellSize = Vector2.New(slot1[6], slot1[7]) slot0.cellSpace = Vector2.New(slot1[8], slot1[9]) slot0.offsetz = slot1[10] or 0 slot0.cosAngle = math.cos(slot1[10] or 0) slot0.sinAngle = math.sin(slot0.angle / 180 * math.pi) end slot0.GetLinePosition = function (slot0, slot1, slot2) return Vector3(Vector2(slot2 + 0.5, WorldConst.MaxRow * 0.5 - slot1 - 0.5).x * (slot0.cellSize.x + slot0.cellSpace.x), Vector2(slot2 + 0.5, WorldConst.MaxRow * 0.5 - slot1 - 0.5).y * (slot0.cellSize.y + slot0.cellSpace.y), 0) end slot0.X2Column = function (slot0, slot1) return math.round(slot1 / (slot0.cellSize.x + slot0.cellSpace.x) - 0.5) end slot0.Y2Row = function (slot0, slot1) return math.round(WorldConst.MaxRow * 0.5 - 0.5 - slot1 / (slot0.cellSize.y + slot0.cellSpace.y)) end return slot0
local F, C = unpack(select(2, ...)) local MAP = F:RegisterModule('Map') function MAP:OnLogin() self:SetupWorldMap() self:SetupMiniMap() end
ignoredID = -1 ignoredCheckpoints = {} function getAreaFromPos(x, y) return math.floor((y + 3000)/750)*8 + math.floor((x + 3000)/750) end function getCheckpointLinks(cp) local links = {} for id, area in pairs(cp.links) do if id ~= ignoredID then table.insert(links, checkpointsTable[area][id]) end end if #links > 1 then local newLinks = {} for i,link in ipairs(links) do if not ignoredCheckpoints[id] then table.insert(newLinks, link) end end if #newLinks == 0 then newLinks = links end links = newLinks end for i, link in ipairs(links) do ignoredCheckpoints[link] = true end return links end function getStartCheckpoint(x, y, z, angle) local areaID = getAreaFromPos(x, y) if not checkpointsTable[areaID] then return false end -- Поиск линий рядом local matchingCheckpoints = {} local dist, minDist, minCp, minCp2 for i, cp in pairs(checkpointsTable[areaID]) do for _, cp2 in ipairs(getCheckpointLinks(cp)) do local cDist = math.abs((math.min(cp.z, cp2.z) + math.abs(cp.z - cp2.z) / 2) - z) dist = getDistanceBetweenPointAndLine(x, y, cp.x, cp.y, cp2.x, cp2.y) + cDist * 10 if not minDist or dist < minDist then --table.insert(matchingCheckpoints, cp) minDist = dist minCp = cp minCp2 = cp2 end end end angle = (angle + 90) / 180 * math.pi local ox, oy = x + math.cos(angle) * 10, y + math.sin(angle) * 10 local angle1 = math.abs(getAngleBetweenThreePoints(minCp, {x=x, y=y}, {x=ox, y=oy})) --createMarker(minCp.x, minCp.y, minCp.z, "checkpoint", 1, 0, 255, 255) local angle2 = math.abs(getAngleBetweenThreePoints(minCp2,{x=x, y=y}, {x=ox, y=oy})) --createMarker(minCp2.x, minCp2.y, minCp2.z, "checkpoint", 1, 255, 255, 0) --createMarker(x, y, minCp2.z, "checkpoint", 1, 255, 255, 0) --createMarker(ox, oy, minCp2.z, "checkpoint", 1, 255, 255, 0) if angle2 < angle1 then local t = minCp minCp = minCp2 minCp2 = t end --createMarker(minCp.x, minCp.y, minCp.z, "checkpoint", 1, 0, 255, 255) return minCp, minCp2 end
local util = {} function util.split(str, sep, stop_at_first) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) string.gsub(str, pattern, function(c) fields[#fields+1] = c end) if stop_at_first and #fields > 1 then local s = fields[1]..sep fields = {fields[1], str:sub(s:len()+1,str:len())} end return fields end return util
vim.api.nvim_set_keymap("n", "<C-n>", "<cmd>NvimTreeToggle<CR>", { noremap = true }) vim.api.nvim_set_keymap("n", "<leader>t", "<cmd>NvimTreeFocus<CR>", { noremap = true })
local env,java=env,java local event,packer,cfg,init=env.event.callback,env.packer,env.set,env.init local set_command,exec_command=env.set_command,env.exec_command local mysql=env.class(env.db_core) mysql.module_list={ "help", "findobj", "mysql_exe", "usedb", "show", "info", "snap", "sql", "list", "ps", "tidb", "chart", "ssh", "dict", "autotrace", "mysqluc" } function mysql:ctor(isdefault) self.type="mysql" self.C,self.props={},{} self.JDBC_ADDRESS='https://mvnrepository.com/artifact/mysql/mysql-connector-java' end local native_cmds={} function mysql:connect(conn_str) local args local usr,pwd,conn_desc,url if type(conn_str)=="table" then args=conn_str usr,pwd,url=conn_str.user,packer.unpack_str(conn_str.password),conn_str.url:match("//(.*)$") args.password=pwd conn_str=string.format("%s/%s@%s",usr,pwd,url) else usr,pwd,conn_desc = string.match(conn_str or "","(.*)[/:](.*)@(.+)") if conn_desc == nil then return exec_command("HELP",{"CONNECT"}) end args={user=usr,password=pwd} if conn_desc:match("%?.*=.*") then local use_ssl=0 for k,v in conn_desc:gmatch("([^=%?&]+)%s*=%s*([^&]+)") do if k:lower()=='ssl_key' or k=='trustCertificateKeyStoreUrl' then local typ,ssl=os.exists(v) env.checkerr(typ=='file','Cannot find SSL TrustStore file: '..v) if ssl:find(':') and ssl:sub(1,1)~='/' then ssl='/'..ssl end args['trustCertificateKeyStoreUrl']='file://'..ssl:gsub('\\','/') args['verifyServerCertificate']='true' args['useSSL']='true' args['sslMode']='PREFERRED' use_ssl=use_ssl+1 elseif k:lower()=='ssl_pwd' or k:lower()=='ssl_password' or k=='trustCertificateKeyStorePassword' then env.checkerr(#v>=6,"Incorrect SSL TrustStore passowrd, it's length should not be less than 6 chars.") args['trustCertificateKeyStorePassword']=v use_ssl=use_ssl+2 else args[k]=v end end conn_desc=conn_desc:gsub("%?.*","") end usr,pwd,url,args.url=args.user,args.password,conn_desc,"jdbc:mysql://"..conn_desc end self.MAX_CACHE_SIZE=cfg.get('SQLCACHESIZE') self:merge_props(--https://docs.pingcap.com/tidb/stable/java-app-best-practices {driverClassName="com.mysql.cj.jdbc.Driver", allowPublicKeyRetrieval='true', rewriteBatchedStatements='true', useCachedCursor=self.MAX_CACHE_SIZE, useCursorFetch='true', useUnicode='true', useServerPrepStmts='true', cachePrepStmts='true', characterEncoding='utf8', connectionCollation='utf8mb4_unicode_ci', useCompression='true', callableStmtCacheSize=10, enableEscapeProcessing='false', allowMultiQueries="true", useSSL='false', serverTimezone='UTC', zeroDateTimeBehavior='convertToNull' },args) if event then event("BEFORE_mysql_CONNECT",self,sql,args,result) end env.set_title("") for k,v in pairs(args) do args[k]=tostring(v) end local data_source=java.new('com.mysql.cj.jdbc.MysqlDataSource') self.super.connect(self,args) --self.conn=java.cast(self.conn,"com.mysql.jdbc.JDBC4MySQLConnection") self.MAX_CACHE_SIZE=cfg.get('SQLCACHESIZE') local info=self:get_value([[select database(), version(), CONNECTION_ID(), user(), @@hostname, @@global.sql_mode, @@port, @@character_set_client]]) table.clear(self.props) local props=self.props props.privs={} if info then --[[ for _,n in ipairs(native_cmds) do local c=self:get_value('select count(1) from mysql.help_topic where name like :1',{n..'%'}) if c==0 then print(n) end end --]] local sql="set group_concat_max_len=4194304,sql_mode='"..info[6]..",ANSI'" props.db_version,props.sub_version=info[2]:match('^([%d%.]+%d)[^%w%.]*([%w%.]*)') props.db_server=info[5] props.db_user=info[4]:match("([^@]+)") props.db_conn_id=tostring(info[3]) props.database=info[1] or "" props.sql_mode=info[6] props.charset=info[8] args.database=info[1] or "" args.hostname=props.db_server args.port=info[7] self:check_readonly(cfg.get('READONLY'),self.conn:isReadOnly() and 'on' or 'off') if props.sub_version=='' then props.sub_version='Oracle' elseif props.sub_version:lower():find('tidb') then props.tidb,props.branch=true,'tidb' props.sub_version=info[2]:match(props.sub_version..'.-([%d%.]+%d)') sql=sql..",tidb_multi_statement_mode=ON" elseif props.sub_version:lower():find('maria') then props.maria,props.branch=true,'maria' props.sub_version=nil elseif props.sub_version:find('^%a') then props.branch,props[props.sub_version:lower()]=props.sub_version:lower(),true props.sub_version=info[2]:match(props.sub_version..'.-([%d%.]+%d)') end pcall(self.internal_call,self,sql) env._CACHE_PATH=env.join_path(env._CACHE_BASE,props.db_server,'') loader:mkdir(env._CACHE_PATH) env.set_title(('MySQL v%s(%s) Server: %s CID: %s'):format( props.db_version, (props.branch or '')..(props.branch and props.sub_version and ' v' or '')..(props.sub_version or ''), props.db_server, props.db_conn_id)) end if (tonumber(self.props.db_version:match("^%d+%.%d")) or 1)<5.5 then env.warn("You are connecting to a lower-vesion MySQL sever, some features may not support.") end self.connection_info=args if event then event("AFTER_MYSQL_CONNECT",self,sql,args,result) end print("Database connected.") end function mysql:exec(sql,...) local bypass=self:is_internal_call(sql) local args,prep_params=nil,{} local is_not_prep=type(sql)~="userdata" if type(select(1,...) or "")=="table" then args=select(1,...) if type(select(2,...) or "")=="table" then prep_params=select(2,...) end else args={...} end if is_not_prep then sql=event("BEFORE_MYSQL_EXEC",{self,sql,args}) [2] end local result,verticals=self.super.exec(self,sql,...) if is_not_prep and not bypass then event("AFTER_MYSQL_EXEC",self,sql,args,result) self.print_feed(sql,result) end return result,verticals end local cmd_no_arguments={ SHUTDOWN=1 } function mysql:command_call(sql,...) local bypass=self:is_internal_call(sql) local args=type(select(1,...)=="table") and ... or {...} sql=event("BEFORE_MYSQL_EXEC",{self,sql,args}) [2] local params=env.parse_args(2,sql) env.checkhelp(#params>1 or cmd_no_arguments[params[1]]) local result,verticals=self.super.exec(self,sql,{args},nil,nil,true) if not bypass then self.print_feed(sql,result) event("AFTER_MYSQL_EXEC",self,sql,args,result) end end function mysql:onload() self.db_types:load_sql_types('com.mysql.cj.MysqlType') local default_desc={"#MYSQL database SQL command",self.C.help.help_offline} local function add_default_sql_stmt(...) for _,cmd in ipairs({...}) do set_command(self,cmd, default_desc,self.command_call,true,1,true) native_cmds[#native_cmds+1]=type(cmd)=='table' and cmd[1] or cmd end end env.set.rename_command('ENV') add_default_sql_stmt({"SELECT","WITH"},'SET','DO','ALTER','ANALYZE','BINLOG','CACHE','CALL','CHANGE','CHECK','CHECKSUM','DEALLOCATE','DELETE','DROP','EXECUTE','FLUSH','GRANT','HANDLER','INSERT','ISOLATION','KILL','LOCK','OPTIMIZE','PREPARE','PURGE') add_default_sql_stmt('RENAME','REPAIR','REPLACE','RESET','REVOKE','SAVEPOINT','RELEASE','START','STOP','TRUNCATE','UPDATE','XA',"SIGNAL","RESIGNAL",{"DESC","EXPLAIN","DESCRBE"}) add_default_sql_stmt('IMPORT','LOAD','TABLE','VALUES','BEGIN','DECLARE','INSTALL','UNINSTALL','RESTART','SHUTDOWN','GET','CLONE') local conn_help = [[ Connect to mysql database. Usage: @@NAME <user>{:|/}<password>@<host>[:<port>][/<database>][?<properties>] or @@NAME <user>{:|/}<password>@<host>[:<port>][/<database>]?ssl_key=<jks_path>[&ssl_pwd=<jks_password>][&<properties>] or @@NAME <user>{:|/}<password>@[host1][:port1][,[host2][:port2]...][/database][?properties] or @@NAME <user>{:|/}<password>@address=(key1=value)[(key2=value)...][,address=(key3=value)[(key4=value)...][/database][?properties] Refer to "MySQL Connector/J Developer Guide" chapter 5.1 "Setting Configuration Propertie" for the available properties Example: @@NAME root/@localhost -- if not specify the port, then it is 3306 @@NAME root/root@localhost:3310 @@NAME root/root@localhost:3310/test?useCompression=false @@NAME root/root@localhost:3310/test?ssl_key=/home/hyee/trust.jks&ssl_pwd=123456 @@NAME root:root@address=(protocol=tcp)(host=primaryhost)(port=3306),address=(protocol=tcp)(host=secondaryhost1)(port=3310)(user=test2)/test ]] set_command(self,{"connect",'conn'}, conn_help,self.connect,false,2) set_command(self,"create", default_desc, self.command_call,self.check_completion,1,true) env.rename_command("HOST",{"SYSTEM","\\!","!"}) env.rename_command("TEE",{"WRITE"}) env.rename_command("SPOOL",{"TEE","\\t","SPOOL"}) env.rename_command("PRINT",{"PRINTVAR","PRI"}) env.rename_command("PROMPT",{"PRINT","ECHO","\\p"}) env.rename_command("HELP",{"HELP","\\h"}) env.event.snoop('ON_SQL_ERROR',self.handle_error,self) env.event.snoop('ON_SETTING_CHANGED',self.check_readonly,self) set_command(nil,{"delimiter","\\d"},"Set statement delimiter. Usage: @@NAME {<text>|default|back}", function(sep) if sep then env.set.doset("SQLTERMINATOR",';,'..sep..',\\g') end end,false,2) set_command(nil,{"PROMPT","\\R"},"Change your mysql prompt. Usage: @@NAME {<text>|default|back}", function(sep) env.set.doset("PROMPT",sep) end,false,2) end function mysql:check_readonly(name,value,org_value) if name~='READONLY' or value==org_value or not self:is_connect() then return end self.conn:setReadOnly(value=='on') end local ignore_errors={ ['No operations allowed after statement closed']='Connection is lost, please login again.', ['Software caused connection abort']='Connection is lost, please login again.' } function mysql:handle_error(info) for k,v in pairs(ignore_errors) do if info.error:lower():find(k:lower(),1,true) then info.sql=nil if v~='default' then info.error=v else info.error=info.error:match('^([^\n\r]+)') end return info end end local line,col=info.error:sub(1,1024):match('line (%d+) column (%d+)') if not line then line=info.error:sub(1,1024):match('at line (%d+) *[\r\n]+') end info.row,info.col=line,col or (line and 0 or nil) if line then info.error=info.error:gsub('You have an error.-syntax to use','Syntax error at',1) end end function mysql:check_datetime(datetime) local v=self:get_value([[select str_to_date(:1,'%y%m%d%H%i%s')]],{datetime},'') if v=='' then datetime=datetime:sub(3) v=self:get_value([[select str_to_date(:1,'%y%m%d%H%i%s')]],{datetime},'') env.checkerr(v~="","Invalid datetime format") end return datetime end function mysql:onunload() env.set_title("") end function mysql:finalize() env.set.change_default("NULL","NULL") env.set.change_default("AUTOCOMMIT","on") env.set.change_default("SQLTERMINATOR",";,$$,\\g") end return mysql.new()
local addon, ns = ... local LSM = LibStub("LibSharedMedia-3.0") local GetTime = GetTime local floor, fmod = floor, math.fmod local sort = table.sort local day, hour, minute = 86400, 3600, 60 ns.FormatTime = function(time) if time >= day then return format("%dd", floor(time/day + 0.5)) elseif time>= hour then return format("%dh", floor(time/hour + 0.5)) elseif time >= minute then return format("%dm", floor(time/minute + 0.5)) end return format("%d", fmod(time, minute)) end ns.MultiCheck = function(what, ...) for i = 1, select("#", ...) do if what == select(i, ...) then return true end end return false end ns.RegisterDefaultSetting = function(key, value) if nRaidDB == nil then nRaidDB = {} end if nRaidDB[key] == nil then nRaidDB[key] = value end end local function chsize(char) if not char then return 0 elseif char > 240 then return 4 elseif char > 225 then return 3 elseif char > 192 then return 2 else return 1 end end ns.utf8sub = function(str) local startIndex = 1 local startChar = 1 local numChars = nRaidDB.nameLength while startChar > 1 do local char = string.byte(str, startIndex) startIndex = startIndex + chsize(char) startChar = startChar - 1 end local currentIndex = startIndex while numChars > 0 and currentIndex <= #str do local char = string.byte(str, currentIndex) currentIndex = currentIndex + chsize(char) numChars = numChars -1 end return str:sub(startIndex, currentIndex - 1) end -- Sorts a table by key. ns.pairsByKeys = function(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 local iter = function () i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end ns.CreateAnchor = function(name) local heightMulti, widthMulti, location if name == "Raid" then if nRaidDB.orientation == "VERTICAL" then widthMulti = 8 heightMulti = 5 else widthMulti = 5 heightMulti = 8 end location = {"TOPLEFT", _G["oUF_NeavRaidControlsFrame"], "TOPRIGHT", 5, 0} else widthMulti = 2 heightMulti = 2 location = {"TOPLEFT", UIParent, "CENTER", 150, 0} end local totalWidth = (nRaidDB.frameWidth*widthMulti+7*(widthMulti-1))*nRaidDB.frameScale local totalHeight = (nRaidDB.frameHeight*heightMulti+7*(heightMulti-1))*nRaidDB.frameScale local anchorFrame = CreateFrame("Frame", addon.."_"..name.."_Anchor", UIParent) anchorFrame:SetSize(totalWidth, totalHeight) anchorFrame:SetPoint(unpack(location)) anchorFrame:SetFrameStrata("BACKGROUND") anchorFrame:SetMovable(true) anchorFrame:SetClampedToScreen(true) anchorFrame:SetUserPlaced(true) Mixin(anchorFrame, BackdropTemplateMixin) anchorFrame:SetBackdrop({bgFile="Interface\\MINIMAP\\TooltipBackdrop-Background",}) anchorFrame:CreateBeautyBorder(12) anchorFrame:EnableMouse(true) anchorFrame:RegisterForDrag("LeftButton") anchorFrame:Hide() anchorFrame.text = anchorFrame:CreateFontString(nil, "OVERLAY") anchorFrame.text:SetAllPoints(anchorFrame) anchorFrame.text:SetFont(STANDARD_TEXT_FONT, 13) anchorFrame.text:SetText(name.." Anchor") anchorFrame:SetScript("OnDragStart", function(self) self:StartMoving() end) anchorFrame:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) return anchorFrame end function ns.LockInCombat(frame) frame:SetScript("OnUpdate", function(self) if not InCombatLockdown() then self:Enable() else self:Disable() end end) end function ns.RegisterControl(control, parentFrame) if ( ( not parentFrame ) or ( not control ) ) then return end parentFrame.controls = parentFrame.controls or {} tinsert(parentFrame.controls, control) end function ns.GetDefaultValue(var) if var == "showSolo" then return false elseif var == "showParty" then return true elseif var == "assistFrame" then return false elseif var == "sortByRole" then return true elseif var == "showRoleIcons" then return true elseif var == "anchorToControls" then return false elseif var == "horizontalHealthBars" then return false elseif var == "powerBars" then return true elseif var == "manaOnlyPowerBars" then return true elseif var == "horizontalPowerBars" then return false elseif var == "orientation" then return "VERTICAL" elseif var == "initialAnchor" then return "TOPLEFT" elseif var == "font" then return "Interface\\AddOns\\oUF_NeavRaid\\media\\fontSmall.ttf" elseif var == "fontSize" then return 12 elseif var == "texture" then return "Interface\\AddOns\\oUF_NeavRaid\\media\\statusbarTexture" elseif var == "nameLength" then return 4 elseif var == "frameWidth" then return 48 elseif var == "frameHeight" then return 46 elseif var == "frameOffset" then return 7 elseif var == "frameScale" then return 1.2 elseif var == "indicatorSize" then return 7 elseif var == "debuffSize" then return 22 end end local prevControl function ns.CreateLabel(cfg) --[[ { type = "Label", name = "LabelName", parent = Options, label = L.LabelText, fontObject = "GameFontNormalLarge", relativeTo = LeftSide, relativePoint = "TOPLEFT", offsetX = 16, offsetY = -16, }, --]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -16 cfg.relativeTo = cfg.relativeTo or prevControl cfg.fontObject = cfg.fontObject or "GameFontNormalLarge" local label = cfg.parent:CreateFontString(cfg.name, "ARTWORK", cfg.fontObject) label:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) label:SetText(cfg.label) prevControl = label return label end function ns.CreateCheckBox(cfg) --[[ { type = "CheckBox", name = "Test", parent = parent, label = L.TestLabel, tooltip = L.TestTooltip, isCvar = nil or True, var = "TestVar", needsRestart = nil or True, disableInCombat = nil or True, func = function(self) -- Do stuff here. end, initialPoint = "TOPLEFT", relativeTo = frame, relativePoint, "BOTTOMLEFT", offsetX = 0, offsetY = -6, }, --]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -4 cfg.relativeTo = cfg.relativeTo or prevControl local checkBox = CreateFrame("CheckButton", cfg.name, cfg.parent, "InterfaceOptionsCheckButtonTemplate") checkBox:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) checkBox.Text:SetText(cfg.label) checkBox.GetValue = function(self) return checkBox:GetChecked() end checkBox.SetControl = function(self) checkBox:SetChecked(nRaidDB[cfg.var]) end checkBox.var = cfg.var checkBox.isCvar = cfg.isCvar if cfg.needsRestart then checkBox.restart = false end if cfg.tooltip then checkBox.tooltipText = cfg.tooltip end if cfg.disableInCombat then ns.LockInCombat(checkBox) end checkBox:SetScript("OnClick", function(self) local checked = self:GetChecked() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON) checkBox.value = checked if cfg.needsRestart then checkBox.restart = not checkBox.restart end if cfg.func then cfg.func(self) end end) ns.RegisterControl(checkBox, cfg.parent) prevControl = checkBox return checkBox end function ns.CreateSlider(cfg) --[[ { type = "Slider", name = "Test", parent = parent, label = L.TestLabel, isCvar = True, var = "nRaidDBVariableGoesHere", fromatString = "%.2f", minValue = 0, maxValue = 1, step = .10, needsRestart = True, disableInCombat = True, func = function(self) -- Do stuff here. end, initialPoint = "TOPLEFT", relativeTo = frame, relativePoint, "BOTTOMLEFT", offsetX = 0, offsetY = -6, }, --]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -26 cfg.relativeTo = cfg.relativeTo or prevControl local value if cfg.isCvar then value = BlizzardOptionsPanel_GetCVarSafe(cfg.var) else value = nRaidDB[cfg.var] end local slider = CreateFrame("Slider", cfg.name, cfg.parent, "OptionsSliderTemplate") slider:SetWidth(180) slider:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) slider.GetValue = function(self) return slider.value end slider.SetControl = function(self) slider:SetValue(nRaidDB[cfg.var]) end slider.value = value slider.var = cfg.var slider.textLow = _G[cfg.name.."Low"] slider.textHigh = _G[cfg.name.."High"] slider.text = _G[cfg.name.."Text"] slider:SetMinMaxValues(cfg.minValue, cfg.maxValue) slider.minValue, slider.maxValue = slider:GetMinMaxValues() slider:SetValue(value) slider:SetValueStep(cfg.step) slider:SetObeyStepOnDrag(true) slider.text:SetFormattedText(cfg.fromatString, value) slider.text:ClearAllPoints() slider.text:SetPoint("BOTTOMRIGHT", slider, "TOPRIGHT") slider.textHigh:Hide() slider.textLow:ClearAllPoints() slider.textLow:SetPoint("BOTTOMLEFT", slider, "TOPLEFT") slider.textLow:SetPoint("BOTTOMRIGHT", slider.text, "BOTTOMLEFT", -4, 0) slider.textLow:SetText(cfg.label) slider.textLow:SetJustifyH("LEFT") if cfg.disableInCombat then ns.LockInCombat(slider) end slider:SetScript("OnValueChanged", function(self, value) slider.text:SetFormattedText(cfg.fromatString, value) slider.value = value if cfg.func then cfg.func(self) end if cfg.needsRestart then if slider.value ~= slider.oldValue then slider.restart = true else slider.restart = false end end end) ns.RegisterControl(slider, cfg.parent) prevControl = slider return slider end function ns.CreateDropdown(cfg) cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -26 cfg.relativeTo = cfg.relativeTo or prevControl --[[ { type = "Dropdown", name = "TestDropdown", parent = Options, label = L.LocalizedName, var = "nRaidDBVariableGoesHere", needsRestart = true, func = function(self) -- Do stuff here. Only ran on click. end, optionsTable = { { text = L.TopLeft, value = 1, }, { text = L.BottomLeft, value = 2, }, { text = L.TopRight, value = 3, }, { text = L.BottomRight, value = 4, }, }, }, ]] local dropdown = CreateFrame("Button", cfg.name, cfg.parent, "UIDropDownMenuTemplate") dropdown:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) dropdown:EnableMouse(true) dropdown.GetValue = function(self) return UIDropDownMenu_GetSelectedValue(self) end dropdown.SetControl = function(self) self.value = nRaidDB[cfg.var] UIDropDownMenu_SetSelectedValue(dropdown, self.value) UIDropDownMenu_SetText(dropdown, cfg.optionsTable[self.value]) end dropdown.var = cfg.var dropdown.value = nRaidDB[cfg.var] dropdown.title = dropdown:CreateFontString("$parentTitle", "BACKGROUND", "GameFontNormalSmall") dropdown.title:SetPoint("BOTTOMLEFT", dropdown, "TOPLEFT", 20, 5) dropdown.title:SetText(cfg.label) local function Dropdown_OnClick(self) UIDropDownMenu_SetSelectedValue(dropdown, self.value) if cfg.func then cfg.func(dropdown) end if cfg.needsRestart then if self.value ~= dropdown.oldValue then dropdown.restart = true else dropdown.restart = false end end end local function Initialize(self, level) local selectedValue = UIDropDownMenu_GetSelectedValue(dropdown) local info = UIDropDownMenu_CreateInfo() for value, text in ns.pairsByKeys(cfg.optionsTable) do info.text = text info.value = value info.func = Dropdown_OnClick if info.value == selectedValue then info.checked = 1 UIDropDownMenu_SetText(dropdown, text) else info.checked = nil end UIDropDownMenu_AddButton(info) end end UIDropDownMenu_SetWidth(dropdown, 180) UIDropDownMenu_SetSelectedValue(dropdown, nRaidDB[cfg.var]) UIDropDownMenu_SetText(dropdown, cfg.optionsTable[nRaidDB[cfg.var]]) UIDropDownMenu_Initialize(dropdown, Initialize) ns.RegisterControl(dropdown, cfg.parent) prevControl = dropdown return dropdown end local function GetSharedMediaName(media, value) for k, v in pairs(LSM:HashTable(media)) do if v == value then return k end end end function ns.CreateSharedMeidaDropdown(cfg) --[[ { type = "SharedMedia", name = "SomethingDropdown" parent = Options, label = L.LocalizedName, var = "nRaidDBVariableGoesHere", func = function(self) -- Do stuff here. Only ran on click. end, needsRestart = true, mediaType = "font", SharedMedia types: background, border, font, statusbar, or sound. initialPoint = "TOPLEFT", relativeTo = frame, relativePoint, "BOTTOMLEFT", offsetX = 0, offsetY = -26, }, ]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -26 cfg.relativeTo = cfg.relativeTo or prevControl local dropdown = CreateFrame("Button", cfg.name, cfg.parent, "UIDropDownMenuTemplate") dropdown:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) dropdown:EnableMouse(true) dropdown.GetValue = function(self) return UIDropDownMenu_GetSelectedValue(self) end dropdown.SetControl = function(self) self.value = nRaidDB[cfg.var] UIDropDownMenu_SetSelectedValue(dropdown, self.value) UIDropDownMenu_SetText(dropdown, GetSharedMediaName(cfg.mediaType, nRaidDB[cfg.var])) end dropdown.var = cfg.var dropdown.title = dropdown:CreateFontString("$parentTitle", "BACKGROUND", "GameFontNormalSmall") dropdown.title:SetPoint("BOTTOMLEFT", dropdown, "TOPLEFT", 20, 5) dropdown.title:SetText(cfg.label) local function Dropdown_OnClick(self) UIDropDownMenu_SetSelectedValue(dropdown, self.value) if cfg.func then cfg.func(dropdown) end if cfg.needsRestart then if self.value ~= dropdown.oldValue then dropdown.restart = true else dropdown.restart = false end end end local function Initialize(self, level) local selectedValue = UIDropDownMenu_GetSelectedValue(dropdown) local info = UIDropDownMenu_CreateInfo() for key, value in ns.pairsByKeys(LSM:HashTable(cfg.mediaType)) do info.text = key info.value = value info.func = Dropdown_OnClick if info.value == selectedValue then info.checked = 1 UIDropDownMenu_SetText(dropdown, key) else info.checked = nil end if cfg.mediaType == "font" then local fontObject = CreateFont("NeavDropdownFont"..key) fontObject:SetFont(value, 13) info.fontObject = fontObject end UIDropDownMenu_AddButton(info) end end UIDropDownMenu_SetWidth(dropdown, 180) UIDropDownMenu_SetSelectedValue(dropdown, nRaidDB[cfg.var]) UIDropDownMenu_SetText(dropdown, GetSharedMediaName(cfg.mediaType, nRaidDB[cfg.var])) UIDropDownMenu_Initialize(dropdown, Initialize) ns.RegisterControl(dropdown, cfg.parent) prevControl = dropdown return dropdown end
local map = require("helpers").map map("n", "<leader>ps", ":PackerSync <CR>")
-- NOTE: this is the module object we return? local M = {} M.map = function(mode, lhs, rhs, opts) local options = { noremap = true, silent = true } if opts then options = vim.tbl_extend("force", options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end return M
AddCSLuaFile( "shared.lua" ) AddCSLuaFile( "cl_init.lua" ) include( 'shared.lua' ) ENT.DespawnTime = false function ENT:Initialize() self:DrawShadow(true) self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Entity:SetUseType( SIMPLE_USE ) local phys = self:GetPhysicsObject() if phys then phys:Wake() end end function ENT:Think() if self.DespawnTime then if self.DespawnTime < CurTime() then self:Remove() return end end if IsValid( self:GetOwner() ) then self.ActivePlayer = true end if self.ActivePlayer then if not self:GetOwner():IsValid() then self:Remove() end end end function ENT:Use( ply ) if self:GetItemType() == WOSTYPE.RAWMATERIAL then if wOS:HandleMaterialPickup( ply, self:GetItemName(), self:GetAmount() ) then self:Remove() end return end if wOS:HandleItemPickup( ply, self:GetItemName() ) then self:Remove() end end
----------------------------------- -- Area: King Ranperre's Tomb -- NM: Vrtra ----------------------------------- require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- local offsets = {1, 3, 5, 2, 4, 6} function onMobEngaged(mob, target) mob:resetLocalVars() end function onMobFight(mob, target) local spawnTime = mob:getLocalVar("spawnTime") local twohourTime = mob:getLocalVar("twohourTime") local fifteenBlock = mob:getBattleTime() / 15 if twohourTime == 0 then twohourTime = math.random(4, 6) mob:setLocalVar("twohourTime", twohourTime) end if spawnTime == 0 then spawnTime = math.random(3, 5) mob:setLocalVar("spawnTime", spawnTime) end if fifteenBlock > twohourTime then mob:useMobAbility(710) mob:setLocalVar("twohourTime", fifteenBlock + math.random(4, 6)) elseif fifteenBlock > spawnTime then local mobId = mob:getID() for i, offset in ipairs(offsets) do local pet = GetMobByID(mobId + offset) if not pet:isSpawned() then pet:spawn(60) local pos = mob:getPos() pet:setPos(pos.x, pos.y, pos.z) pet:updateEnmity(target) break end end mob:setLocalVar("spawnTime", fifteenBlock + 4) end end function onMobDisengage(mob, weather) for i, offset in ipairs(offsets) do DespawnMob(mob:getID()+offset) end end function onMobDeath(mob, player, isKiller) player:addTitle(tpz.title.VRTRA_VANQUISHER) end function onMobDespawn(mob) -- Set Vrtra's spawnpoint and respawn time (3-5 days) UpdateNMSpawnPoint(mob:getID()) mob:setRespawnTime(math.random(259200, 432000)) end
local M = {} local expect_object, dump_object local error, tostring, pairs, type, floor, huge, concat = error, tostring, pairs, type, math.floor, math.huge, table.concat local dump_type = {} function dump_type:string(nmemo, memo, acc) local nacc = #acc acc[nacc + 1] = '"' acc[nacc + 2] = self:gsub('"', '""') acc[nacc + 3] = '"' return nmemo end function dump_type:number(nmemo, memo, acc) acc[#acc + 1] = ("%.17g"):format(self) return nmemo end function dump_type:table(nmemo, memo, acc) if memo[self] then acc[#acc + 1] = '@' acc[#acc + 1] = tostring(memo[self]) return nmemo end nmemo = nmemo + 1 memo[self] = nmemo acc[#acc + 1] = '{' local nself = #self for i = 1, nself do -- don't use ipairs here, we need the gaps nmemo = dump_object(self[i], nmemo, memo, acc) acc[#acc + 1] = ',' end for k, v in pairs(self) do if type(k) ~= 'number' or floor(k) ~= k or k < 1 or k > nself then nmemo = dump_object(k, nmemo, memo, acc) acc[#acc + 1] = ':' nmemo = dump_object(v, nmemo, memo, acc) acc[#acc + 1] = ',' end end acc[#acc] = acc[#acc] == '{' and '{}' or '}' return nmemo end function dump_object(object, nmemo, memo, acc) if object == true then acc[#acc + 1] = 't' elseif object == false then acc[#acc + 1] = 'f' elseif object == nil then acc[#acc + 1] = 'n' elseif object ~= object then if (''..object):sub(1,1) == '-' then acc[#acc + 1] = 'N' else acc[#acc + 1] = 'Q' end elseif object == huge then acc[#acc + 1] = 'I' elseif object == -huge then acc[#acc + 1] = 'i' else local t = type(object) if not dump_type[t] then error('cannot dump type ' .. t) end return dump_type[t](object, nmemo, memo, acc) end return nmemo end function M.dumps(object) local nmemo = 0 local memo = {} local acc = {} dump_object(object, nmemo, memo, acc) return concat(acc) end local function invalid(i) error('invalid input at position ' .. i) end local nonzero_digit = {['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true} local is_digit = {['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true} local function expect_number(string, start) local i = start local head = string:sub(i, i) if head == '-' then i = i + 1 head = string:sub(i, i) end if nonzero_digit[head] then repeat i = i + 1 head = string:sub(i, i) until not is_digit[head] elseif head == '0' then i = i + 1 head = string:sub(i, i) else invalid(i) end if head == '.' then local oldi = i repeat i = i + 1 head = string:sub(i, i) until not is_digit[head] if i == oldi + 1 then invalid(i) end end if head == 'e' or head == 'E' then i = i + 1 head = string:sub(i, i) if head == '+' or head == '-' then i = i + 1 head = string:sub(i, i) end if not is_digit[head] then invalid(i) end repeat i = i + 1 head = string:sub(i, i) until not is_digit[head] end return tonumber(string:sub(start, i - 1)), i end local expect_object_head = { t = function(string, i) return true, i end, f = function(string, i) return false, i end, n = function(string, i) return nil, i end, Q = function(string, i) return -(0/0), i end, N = function(string, i) return 0/0, i end, I = function(string, i) return 1/0, i end, i = function(string, i) return -1/0, i end, ['"'] = function(string, i) local nexti = i - 1 repeat nexti = string:find('"', nexti + 1, true) + 1 until string:sub(nexti, nexti) ~= '"' return string:sub(i, nexti - 2):gsub('""', '"'), nexti end, ['0'] = function(string, i) return expect_number(string, i - 1) end, ['{'] = function(string, i, tables) local nt, k, v = {} local j = 1 tables[#tables + 1] = nt if string:sub(i, i) == '}' then return nt, i + 1 end while true do k, i = expect_object(string, i, tables) if string:sub(i, i) == ':' then v, i = expect_object(string, i + 1, tables) nt[k] = v else nt[j] = k j = j + 1 end local head = string:sub(i, i) if head == ',' then i = i + 1 elseif head == '}' then return nt, i + 1 else invalid(i) end end end, ['@'] = function(string, i, tables) local match = string:match('^%d+', i) local ref = tonumber(match) if tables[ref] then return tables[ref], i + #match end invalid(i) end, } expect_object_head['1'] = expect_object_head['0'] expect_object_head['2'] = expect_object_head['0'] expect_object_head['3'] = expect_object_head['0'] expect_object_head['4'] = expect_object_head['0'] expect_object_head['5'] = expect_object_head['0'] expect_object_head['6'] = expect_object_head['0'] expect_object_head['7'] = expect_object_head['0'] expect_object_head['8'] = expect_object_head['0'] expect_object_head['9'] = expect_object_head['0'] expect_object_head['-'] = expect_object_head['0'] expect_object_head['.'] = expect_object_head['0'] expect_object = function(string, i, tables) local head = string:sub(i, i) if expect_object_head[head] then return expect_object_head[head](string, i + 1, tables) end invalid(i) end function M.loads(string, maxsize) if #string > (maxsize or 10000) then error 'input too large' end return (expect_object(string, 1, {})) end return M
--refer to link below for more information --https://github.com/Cryotheus/minge_defense/blob/main/gamemodes/mingedefense/gamemode/loader.lua PECAN = {Build = 0, Version = "0.0.0d"} local config = { autorun = {player_expression_canvas = 4}, --100 player_expression_canvas = { editor = { context_menu = 5, --00 101 main = 21, --10 101 render = 29, --11 101 skin = 5 --0 101 }, panels = { editor = 5, frame = 5, icon_button = 5, material = 5, material_display = 5, material_editor = 5, material_editor_sidebar = 5, submaterial_selector = 5, texture = 5, texture_display = 5, texture_entry = 5, texture_viewer = 5 }, render = { kernel = 13 --1 101 }, client = 13, --1 101 server = 10 --1 010 } } --maximum amount of folders it may go down in the config tree local max_depth = 4 --local variables, don't change local fl_bit_band = bit.band local fl_bit_rshift = bit.rshift local highest_priority = 0 local load_order = {} local load_functions = { [1] = function(path) if CLIENT then include(path) end end, [2] = function(path) if SERVER then include(path) end end, [4] = function(path) if SERVER then AddCSLuaFile(path) end end } local load_function_shift = table.Count(load_functions) ----colors local color_print_red = Color(0, 255, 0) local color_print_white = color_white --local functions local function construct_order(config_table, depth, path) local tabs = " ]" .. string.rep(" ", depth) for key, value in pairs(config_table) do if istable(value) then MsgC(color_print_white, tabs .. key .. ":\n") if depth < max_depth then construct_order(value, depth + 1, path .. key .. "/") else MsgC(color_print_red, tabs .. " !!! MAX DEPTH !!!\n") end else MsgC(color_print_white, tabs .. key .. " = 0d" .. value .. "\n") local priority = fl_bit_rshift(value, load_function_shift) local script_path = path .. key if priority > highest_priority then highest_priority = priority end if load_order[priority] then load_order[priority][script_path] = fl_bit_band(value, 7) else load_order[priority] = {[script_path] = fl_bit_band(value, 7)} end end end end local function load_by_order() for priority = 0, highest_priority do local script_paths = load_order[priority] if script_paths then if priority == 0 then MsgC(color_print_white, " Loading scripts at level 0...\n") else MsgC(color_print_white, "\n Loading scripts at level " .. priority .. "...\n") end for script_path, bits in pairs(script_paths) do local script_path_extension = script_path .. ".lua" MsgC(color_print_white, " ] 0d" .. bits .. " " .. script_path_extension .. "\n") for bit_flag, func in pairs(load_functions) do if fl_bit_band(bits, bit_flag) > 0 then func(script_path_extension) end end end else MsgC(color_print_red, "Skipping level " .. priority .. " as it contains no scripts.\n") end end end local function load_scripts(command_reload) MsgC(color_print_white, "\n\\\\\\ ", color_print_red, "PECan", color_print_white, " ///\n\nConstructing load order...\n") construct_order(config, 1, "") MsgC(color_print_red, "\nConstructed load order.\n\nLoading scripts by load order...\n") load_by_order() MsgC(color_print_red, "\nLoaded scripts.\n\n", color_print_white, "/// ", color_print_red, "All scripts loaded.", color_print_white, " \\\\\\\n\n") hook.Call("PecanLoaded", PECAN, command_reload) end --concommands concommand.Add("pecan_debug", function() PrintTable(PECAN, 1) end, nil, "Print the PECAN global table.") concommand.Add("pecan_reload", function(ply) --is it possible to run a command from client and execute the serverside command when the command is shared? if not IsValid(ply) or ply:IsSuperAdmin() or LocalPlayer and ply == LocalPlayer() then load_scripts(true) end end, nil, "Reload all Pecan scripts.") --post function setup load_scripts(false)
local getDistanceBetweenOriginal; function onInit() if super and super.onInit() then super.onInit(); end getDistanceBetweenOriginal = Token.getDistanceBetween; Token.getDistanceBetween = getDistanceBetween; end function onMeasurePointer(pixellength, type, startx, starty, endx, endy) if not (getGridSize and getDistanceBaseUnits and getDistanceSuffix and Interface.getDistanceDiagMult and getDistanceDiagMult) then return ""; end local gridSize = getGridSize(); local units = getDistanceBaseUnits(); local suffix = getDistanceSuffix(); local diagMult = Interface.getDistanceDiagMult(); if getDistanceDiagMult() == 0 then diagMult = 0; end local startz = 0; local endz = 0; local ctNodeOrigin = getCTNodeAt(startx, starty, gridSize); local nDistBetween = 0; local sSizeIndex, tSizeIndex; local sourceDepth, targetDepth; if ctNodeOrigin then local ctNodeTarget = getCTNodeAt(endx, endy, gridSize); if ctNodeTarget then startz = HeightManager.getHeight(ctNodeOrigin) * gridSize / units; endz = HeightManager.getHeight(ctNodeTarget) * gridSize / units; sSizeIndex, tSizeIndex = HeightManager.getHeightDifferential(ctNodeOrigin, ctNodeTarget); sourceDepth = sSizeIndex * gridSize; targetDepth = tSizeIndex * gridSize; local sourceToken = CombatManager.getTokenFromCT(ctNodeOrigin); local targetToken = CombatManager.getTokenFromCT(ctNodeTarget); nDistBetween = getDistanceBetween(sourceToken, targetToken); -- Offset for the physical height of the token if startz <= targetDepth then startz = 0; else startz = math.abs(startz - targetDepth + gridSize); end if endz <= sourceDepth then endz = 0; else endz = math.abs(endz - sourceDepth + gridSize); end end end local distance = getDistanceBetween3D(startx, starty, startz, endx, endy, endz); if distance <= 5 then return ""; else local stringDistance = nil; if diagMult == 0 then stringDistance = string.format("%.1f", distance); else stringDistance = string.format("%.0f", distance); end return stringDistance .. suffix; end end function getCTNodeAt(sx, sy, gridSize) local tokens = getTokens(); for _, token in pairs(tokens) do local x, y = token.getPosition(); local ctNode = CombatManager.getCTFromToken(token); local bExact = true; local sizeMult = 0; if User.getRulesetName() == "5E" then local sSize = StringManager.trim(DB.getValue(ctNode, "size", ""):lower()); if sSize == "large" then sizeMult = 0.5; elseif sSize == "huge" then sizeMult = 1; elseif sSize == "gargantuan" then sizeMult = 1.5; bExact = false; end end local bFound = false; if bExact then bFound = exactMatch(sx, sy, x, y, sizeMult, gridSize); else bFound = matchWithin(sx, sy, x, y, sizeMult, gridSize); end if bFound then return ctNode; end end end -- Incorporating GKEnialb's work here (reformatted slightly, same functionality) function exactMatch(sx, sy, ex, ey, sizeMult, gridSize) local eq = false; if ex > sx then ex = ex - gridSize * sizeMult; elseif ex < sx then ex = ex + gridSize * sizeMult; end if ey > sy then ey = ey - gridSize * sizeMult; elseif ey < sy then ey = ey + gridSize * sizeMult; end if ex == sx and ey == sy then eq = true; end return eq; end function matchWithin(sx, sy, ex, ey, sizeMult, gridSize) local eq = false; local lbx = ex; local lby = ey; local ubx = ex; local uby = ey; if ex > sx then lbx = ex - gridSize * sizeMult; elseif ex < sx then ubx = ex + gridSize * sizeMult; end if ey > sy then lby = ey - gridSize * sizeMult; elseif ey < sy then uby = ey + gridSize * sizeMult; end if sx >= lbx and sx <= ubx and sy >= lby and sy <= uby then eq = true; end return eq; end -- Custom Override local function getDistanceBetween(sourceToken, targetToken) if not sourceToken and not targetToken then return; end local gridSize = getGridSize(); local units = getDistanceBaseUnits(); local startz = 0; local endz = 0; local ctNodeOrigin = CombatManager.getCTFromToken(sourceToken); if ctNodeOrigin then startz = HeightManager.getHeight(ctNodeOrigin) * gridSize / units; local ctNodeTarget = CombatManager.getCTFromToken(targetToken); if ctNodeTarget then endz = HeightManager.getHeight(ctNodeTarget) * gridSize / units; end end local startx, starty = sourceToken.getPosition(); local endx, endy = targetToken.getPosition(); local nDistance = getDistanceBetween3D(startx, starty, startz, endx, endy, endz); return nDistance; end function getDistanceBetween3D(startx, starty, startz, endx, endy, endz) local diagMult = Interface.getDistanceDiagMult(); if getDistanceDiagMult() == 0 then diagMult = 0; end local units = getDistanceBaseUnits(); local gridSize = getGridSize(); local distance = 0; local dx = math.abs(endx - startx); local dy = math.abs(endy - starty); local dz = math.abs(endz - startz); if diagMult == 1 then local longestLeg = math.max(dx, dy, dz); distance = math.floor(longestLeg / gridSize + 0.5) * units; elseif diagMult == 0 then local hypotenuse = math.sqrt((dx ^ 2) + (dy ^ 2) + (dz ^ 2)); distance = (hypotenuse / gridSize) * units; else local straight = math.max(dx, dy, dz); local diagonal = 0; if straight == dx then diagonal = math.floor((math.ceil(dy / gridSize) + math.ceil(dz / gridSize)) / 2) * gridSize; elseif straight == dy then diagonal = math.floor((math.ceil(dx / gridSize) + math.ceil(dz / gridSize)) / 2) * gridSize; else diagonal = math.floor((math.ceil(dx / gridSize) + math.ceil(dy / gridSize)) / 2) * gridSize; end distance = math.floor((straight + diagonal) / gridSize); distance = distance * units; end return distance; end
-- Mon Jul 16 23:34:53 2018 -- (c) Alexander Veledzimovich -- view KADZEN local ui = require('lib/lovui') local imd = require('lib/lovimd') local obj = require('game/obj') local set = require('game/set') local View = {} function View:new() self.ui = ui self.screen = nil self.uibg = love.graphics.newImage(set.IMG['uibg']) end function View:get_screen() return self.screen end function View:get_ui() return self.ui end function View:set_start_scr() self.screen = 'ui_scr' ui.Manager.clear() ui.Label{x=set.MIDWID, y=set.MIDHEI-20, anchor='s',angle=3, text=set.APPNAME:upper(), frm=0, fnt=set.TITLEFNT} ui.Button{x=set.MIDWID-114, y=set.MIDHEI+40, image=set.IMG['znet'], frm=0, fnt=set.MENUFNT, fntclr=set.LIGHTGRAY, com=function() Model:market() end} ui.Button{x=set.MIDWID+182, y=set.MIDHEI+366, anchor='s', image=set.IMG['start'], frm=0, fnt=set.TITLEFNT,fntclr=set.LIGHTGRAY, com=function() Model:startgame() end} local copyright = ui.HBox{x=set.MIDWID, y=set.HEI-4, anchor='s', sep=16} copyright:add( ui.Label{ text='© LÖVE Development Team https://love2d.org', fnt={nil,12}}, ui.Label{ text='© Game by Alexander Veledzimovich veledz@gmail.com', fnt={nil,12}}, ui.Label{ text='© Music by Eric Matyas www.soundimage.org', fnt={nil,12}}) end function View.buy(item,price) if tonumber(item.display.text)>item.var.val then item.var.val = tonumber(item.display.text) Model.stat.chip.val=Model.stat.chip.val+price item.var.val=item.var.val-1 elseif tonumber(item.display.text)<item.var.val then item.var.val = tonumber(item.display.text) if Model.stat.chip.val>=price then Model.stat.chip.val=Model.stat.chip.val-price item.var.val=item.var.val+1 end end end function View:set_market_scr() self.screen = 'market_scr' ui.Manager.clear() local menu = ui.VBox{x=set.MIDWID, y=set.MIDHEI, mode='fill',frm=20,sep=20} local top = ui.HBox{sep=50} top:add(ui.Label{text='Z.NET', fnt=set.TITLEFNT}, ui.Label{image=obj.Chip.img_lab,fntclr=set.WHITE}, ui.Label{text=' ',var=Model.stat.chip,fnt=set.TITLEFNT}) local products = ui.VBox{sep=20} local r1 = ui.HBox{sep=60} local r2 = ui.HBox{sep=60} local r3 = ui.HBox{sep=60} r1:add(ui.Label{image=obj.Hp.img_lab,fntclr=set.WHITE}, ui.Counter{var=Model.stat.hp,fnt={nil,32},min=1,max=10, com=function(counter) self.buy(counter,3) end}, ui.Label{text='3',fnt=set.TITLEFNT}) r2:add(ui.Label{image=obj.Ammo.img_lab,fntclr=set.WHITE}, ui.Counter{var=Model.stat.ammo,fnt={nil,32},max=13, com=function(counter) self.buy(counter,2) end}, ui.Label{text='2',fnt=set.TITLEFNT}) r3:add(ui.Label{image=obj.Upgrade.imgdata,fntclr=set.WHITE}, ui.Counter{var=Model.stat.dist,fnt={nil,32},min=1,max=10, com=function(counter) self.buy(counter,4) end}, ui.Label{text='4',fnt=set.TITLEFNT}) r1.items[2].max=set.MAXHP r2.items[2].max=set.MAXAMMO r3.items[2].max=set.MAXDIST products:add(r1,r2,r3) menu:add(top,ui.Sep(),products,ui.Sep(), ui.Button{text='OK', fnt=set.TITLEFNT, frm=0, com=function() local hp,ammo,dist,chip = Model:get_stat() Model.save_gamestat(hp,ammo,dist,chip) Model:restart() end}) end function View:set_level_scr(level) self.screen = 'level_scr' ui.Manager.clear() local leveltext = 'LEVEL '..level if level == 4 then leveltext = 'KILL THEM ALL!' end ui.LabelExe{x=set.MIDWID,y=set.MIDHEI,text=leveltext,time=90, fnt=set.TITLEFNT,com=function() Model:nextlevel() end} end function View:set_game_scr() self.screen = 'game_scr' ui.Manager.clear() local avatar = Model:get_avatar() local bars = ui.HBox{x=2,y=1,anchor='nw',sep=12} local hplab = ui.Label{image=imd.resize(obj.Hp.img_lab, set.SCALE),fntclr=set.WHITE} local hpbar = ui.ProgBar{image=imd.resize(obj.Hp.img_bar, set.SCALE),fntclr=set.WHITE, var=avatar.hp,frm=0,max=set.MAXHP} local ammolab = ui.Label{image=imd.resize(obj.Ammo.img_lab, set.SCALE),fntclr=set.WHITE} local ammobar = ui.ProgBar{image=imd.resize( obj.Bomb.imgdata,set.SCALE),fntclr=set.WHITE, var=avatar.ammo,frm=0,max=set.MAXAMMO} local chiplab = ui.Label{image=imd.resize(obj.Chip.img_lab, set.SCALE),fntclr=set.WHITE} local chipcount = ui.Label{text='',var=avatar.chip,fnt=set.MENUFNT, fntclr=set.WHITE} bars:add(hplab,hpbar,ammolab,ammobar,chiplab,chipcount) avatar.ammobar = ammobar end function View:set_fin_scr(fintext) self.screen = 'fin_scr' ui.Manager.clear() local modelscore = Model:get_score() local score = ui.VBox{x=set.MIDWID, y=set.MIDHEI,mode='fill',frm=20,sep=20} local table = ui.HBox{sep=60} local chipbox = ui.VBox{sep=20} local cb1 = ui.HBox{sep=60} cb1:add(ui.Label{image=obj.Chip.imgdata,fntclr=set.WHITE}, ui.Label{text=Model.stat.chip.val,fnt=set.TITLEFNT}) chipbox:add(cb1) local scorebox = ui.VBox{sep=20} local r1 = ui.HBox{sep=60} local r2 = ui.HBox{sep=60} local r3 = ui.HBox{sep=60} local r4 = ui.HBox{sep=60} r1:add(ui.Label{image=obj.Star.imgdata,fntclr=set.WHITE}, ui.Label{text=modelscore['star'].val,fnt=set.TITLEFNT}) r2:add(ui.Label{image=obj.Tank.imgdata,fntclr=set.WHITE}, ui.Label{text=modelscore['tank'].val,fnt=set.TITLEFNT}) r3:add(ui.Label{image=obj.Hunter.imgdata,fntclr=set.WHITE}, ui.Label{text=modelscore['hunter'].val,fnt=set.TITLEFNT}) scorebox:add(r1,r2,r3) table:add(scorebox,chipbox) score:add(ui.Label{text=fintext,fnt=set.TITLEFNT}, ui.Sep(),table, r4, ui.Sep(), ui.Button{text='RESTART',fnt=set.TITLEFNT,frm=0, com=function() Model:restart() end}) end function View:set_label(text,bool) local x = set.MIDWID local y = set.MIDHEI if self.label then self.label:remove() end if bool then self.label=ui.Label{x=x,y=y,text=text, fnt=set.MENUFNT, fntclr=set.DARKRED, anchor='s'} end end local Canvas = love.graphics.newCanvas(set.WID+set.TILESIZE/2, set.HEI+set.TILESIZE/2) function View:draw() love.graphics.setColor(set.WHITE) if self.screen=='ui_scr' then love.graphics.draw(self.uibg) end if self.screen=='game_scr' then love.graphics.setCanvas(Canvas) love.graphics.clear() -- fade local fade = Model:get_fade() love.graphics.setColor({fade,fade,fade,fade}) -- sprite batch floor love.graphics.draw(obj.Floor:getSprite().table) -- sprite batch wall love.graphics.draw(obj.Wall:getSprite().table) -- items local items = Model:get_objects() for i=1,#items do if items[i].draw then items[i]:draw() end end -- particle for particle in pairs(Model:get_particles()) do love.graphics.draw(particle) end love.graphics.setCanvas() love.graphics.draw(Canvas,-set.TILESIZE/2,-set.TILESIZE/2) end ui.Manager.draw() if self.screen=='ui_scr' then -- particle for particle in pairs(Model:get_particles()) do love.graphics.draw(particle) end end end return View
local class = require "class" local new_tab = require("sys").new_tab local log = require "logging" local Log = log:new({ dump = true, path = 'internal-TCP' }) local type = type local assert = assert local io_open = io.open local spack = string.pack local insert = table.insert local remove = table.remove local dns = require "protocol.dns" local dns_resolve = dns.resolve local co = require "internal.Co" local co_new = co.new local co_wakeup = co.wakeup local co_spawn = co.spawn local co_self = co.self local co_wait = coroutine.yield local ti = require "internal.Timer" local ti_timeout = ti.timeout local tcp = require "tcp" local tcp_new = tcp.new local tcp_ssl_new = tcp.new_ssl local tcp_ssl_new_fd = tcp.new_ssl_fd local tcp_start = tcp.start local tcp_stop = tcp.stop local tcp_free_ssl = tcp.free_ssl local tcp_close = tcp.close local tcp_connect = tcp.connect local tcp_ssl_do_handshake = tcp.ssl_connect local tcp_read = tcp.read local tcp_sslread = tcp.ssl_read local tcp_write = tcp.write local tcp_ssl_write = tcp.ssl_write local tcp_listen = tcp.listen local tcp_listen_ex = tcp.listen_ex local tcp_sendfile = tcp.sendfile local tcp_peek = tcp.peek local tcp_sslpeek = tcp.sslpeek local tcp_new_client_fd = tcp.new_client_fd local tcp_new_server_fd = tcp.new_server_fd local tcp_new_sever_unixsock_fd = tcp.new_server_unixsock_fd local tcp_new_client_unixsock_fd = tcp.new_client_unixsock_fd local tcp_ssl_verify = tcp.ssl_verify local tcp_ssl_set_fd = tcp.ssl_set_fd local tcp_ssl_set_alpn = tcp.ssl_set_alpn local tcp_ssl_get_alpn = tcp.ssl_get_alpn local tcp_set_read_buf = tcp.tcp_set_read_buf local tcp_set_write_buf = tcp.tcp_set_write_buf local ssl_set_connect_server = tcp.ssl_set_connect_server local tcp_ssl_set_accept_mode = tcp.ssl_set_accept_mode local tcp_ssl_set_connect_mode = tcp.ssl_set_connect_mode local tcp_ssl_set_privatekey = tcp.ssl_set_privatekey local tcp_ssl_set_certificate = tcp.ssl_set_certificate local tcp_ssl_set_userdata_key = tcp.ssl_set_userdata_key local EVENT_READ = 0x01 local EVENT_WRITE = 0x02 local POOL = new_tab(1 << 10, 0) local function tcp_pop() return remove(POOL) or tcp_new() end local function tcp_push(tcp) return insert(POOL, tcp) end local TCP = class("TCP") function TCP:ctor(...) --[[ -- 当前socke运行模式 self.mode = nil -- 默认关闭定时器 self._timeout = nil -- 默认backlog self._backlog = 128 -- connect 或 accept 得到的文件描述符 self.fd = nil -- listen unix domain socket 文件描述符 self.ufd = nil -- ssl 对象 self.ssl = nil self.ssl_ctx = nil -- 密钥与证书路径 self.privatekey_path = nil self.certificate_path = nil -- 配套密码 self.ssl_password = nil --]] end -- 超时时间 function TCP:timeout(Interval) if Interval and Interval > 0 then self._timeout = Interval end return self end -- 设置fd function TCP:set_fd(fd) if not self.fd then self.fd = fd end return self end -- 设置backlog function TCP:set_backlog(backlog) if type(backlog) == 'number' and backlog > 0 then self._backlog = backlog end return self end -- 开启验证 function TCP:ssl_set_verify() if not self.ssl or not self.ssl_ctx then self.ssl, self.ssl_ctx = tcp_ssl_new() end return tcp_ssl_verify(self.ssl, self.ssl_ctx) end -- 设置NPN/ALPN function TCP:ssl_set_alpn(protocol) if type(protocol) == 'string' and protocol ~= '' then if not self.ssl or not self.ssl_ctx then self.ssl, self.ssl_ctx = tcp_ssl_new() end self.alpn = protocol end end -- 获取NPN/ALPN function TCP:ssl_get_alpn() if not self.ssl or not self.ssl_ctx then return end return tcp_ssl_get_alpn(self.ssl, self.ssl_ctx) end -- 设置私钥 function TCP:ssl_set_privatekey(privatekey_path) if not self.ssl or not self.ssl_ctx then self.ssl, self.ssl_ctx = tcp_ssl_new() end assert(type(privatekey_path) == 'string' and privatekey_path ~= '', "Invalid privatekey_path") self.privatekey_path = privatekey_path return tcp_ssl_set_privatekey(self.ssl, self.ssl_ctx, self.privatekey_path) end -- 设置证书 function TCP:ssl_set_certificate(certificate_path) if not self.ssl or not self.ssl_ctx then self.ssl, self.ssl_ctx = tcp_ssl_new() end assert(type(certificate_path) == 'string' and certificate_path ~= '', "Invalid certificate_path") self.certificate_path = certificate_path return tcp_ssl_set_certificate(self.ssl, self.ssl_ctx, self.certificate_path) end -- 设置证书与私钥的密码 function TCP:ssl_set_password(password) if not self.ssl or not self.ssl_ctx then self.ssl, self.ssl_ctx = tcp_ssl_new() end assert(type(password) == 'string', "not have ssl or ssl_ctx.") self.ssl_password = password return tcp_ssl_set_userdata_key(self.ssl, self.ssl_ctx, self.ssl_password) end -- sendfile实现. function TCP:sendfile (filename, offset) if self.ssl or self.ssl_ctx then return self:ssl_sendfile(filename, offset) end if type(filename) == 'string' and filename ~= '' then local co = co_self() self.SEND_IO = tcp_pop() self.sendfile_current_co = co_self() self.sendfile_co = co_new(function (ok) tcp_stop(self.SEND_IO) tcp_push(self.SEND_IO) self.SEND_IO = nil self.sendfile_co = nil self.sendfile_current_co = nil return co_wakeup(co, ok) end) tcp_sendfile(self.SEND_IO, self.sendfile_co, filename, self.fd, offset or 65535) return co_wait() end end -- ssl_sendfile实现 function TCP:ssl_sendfile(filename, offset) if type(filename) ~= 'string' or filename == '' then return nil, "Invalid filename." end local f, err = io_open(filename, "r") if not f then return nil, err end for buf in f:lines(offset or 65535) do if not self:ssl_send(buf) then return false, f:close() end end return true, f:close() end function TCP:send(buf) if self.ssl then return self:ssl_send(buf) end if not self.fd or type(buf) ~= 'string' or buf == '' then return end local wlen = tcp_write(self.fd, buf, 0) if not wlen or wlen == #buf then return wlen == #buf end assert(not self.send_co, "[TCP ERROR]: Try to call the 'send' method multiple times.") -- 缓解发送大量数据集的时候调用频繁的问题 if not self.wsize or self.wsize < #buf then self.wsize = #buf if self.wsize > (1 << 16) then if self.wsize > (1 << 20) then self.wsize = 1 << 20 end tcp_set_write_buf(self.fd, self.wsize); end end local co = co_self() self.SEND_IO = tcp_pop() self.send_current_co = co_self() self.send_co = co_new(function ( ) while 1 do local len = tcp_write(self.fd, buf, wlen) if not len or len + wlen == #buf then tcp_stop(self.SEND_IO) tcp_push(self.SEND_IO) self.SEND_IO = nil self.send_co = nil self.send_current_co = nil return co_wakeup(co, (len or 0) + wlen == #buf) end wlen = wlen + len co_wait() end end) tcp_start(self.SEND_IO, self.fd, EVENT_WRITE, self.send_co) return co_wait() end function TCP:ssl_send(buf) if not self.fd or not self.ssl or type(buf) ~= 'string' or buf == '' then return nil, "SSL Write Buffer error." end local ssl = self.ssl local wlen = tcp_ssl_write(ssl, buf, #buf) if not wlen or wlen == #buf then return wlen == #buf end assert(not self.send_co, "[TCP ERROR]: Try to call the 'send' method multiple times.") -- 缓解发送大量数据集的时候调用频繁的问题 if not self.wsize or self.wsize < #buf then self.wsize = #buf if self.wsize > (1 << 16) then if self.wsize > (1 << 20) then self.wsize = 1 << 20 end tcp_set_write_buf(self.fd, self.wsize); end end local co = co_self() self.SEND_IO = tcp_pop() self.send_current_co = co_self() self.send_co = co_new(function ( ) while 1 do local len = tcp_ssl_write(ssl, buf, #buf) if not len or len == #buf then tcp_stop(self.SEND_IO) tcp_push(self.SEND_IO) self.SEND_IO = nil self.send_co = nil self.send_current_co = nil return co_wakeup(co, len == #buf) end co_wait() end end) tcp_start(self.SEND_IO, self.fd, EVENT_WRITE, self.send_co) return co_wait() end -- READLINE function TCP:readline(sp, nosp) if self.ssl then return self:ssl_readline(sp, nosp) end if type(sp) ~= 'string' or #sp < 1 then return nil, "Invalid separator." end assert(not self.read_co, "[TCP ERROR]: Try to call the 'recv' method multiple times.") local buffer local msize = 65535 while 1 do ::CONTONIE:: local buf, bsize = tcp_peek(self.fd, msize, true) if not buf then if bsize ~= 0 then return false, bsize end local co = co_self() self.READ_IO = tcp_pop() self.read_co = co_new(function ( ) if self.timer then self.timer:stop() self.timer = nil end tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.READ_IO = nil self.read_co = nil return co_wakeup(co, true) end) self.timer = ti_timeout(self._timeout, function ( ) tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.timer = nil self.READ_IO = nil self.read_co = nil self.read_current_co = nil return co_wakeup(co, nil, "read timeout") end) tcp_start(self.READ_IO, self.fd, EVENT_READ, self.read_co) local ok, errinfo = co_wait() if not ok then return false, errinfo end goto CONTONIE end buffer = buffer and (buffer .. buf) or buf local s, e = buffer:find(sp) if s and e then tcp_peek(self.fd, #buf - (#buffer - e), false) if nosp then e = s - 1 end return buffer:sub(1, e), e end tcp_peek(self.fd, bsize, false) end end -- SSL READLINE function TCP:ssl_readline(sp, nosp) if not self.ssl then return self:readline(sp, nosp) end if type(sp) ~= 'string' or #sp < 1 then return nil, "Invalid separator." end assert(not self.read_co, "[TCP ERROR]: Try to call the 'recv' method multiple times.") local buffer local msize = 65535 -- 开始读取数据 while 1 do ::CONTONIE:: local buf, bsize = tcp_sslpeek(self.ssl, msize, true) if not buf then if bsize ~= 0 then return false, bsize end local co = co_self() self.READ_IO = tcp_pop() self.read_co = co_new(function ( ) if self.timer then self.timer:stop() self.timer = nil end tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.READ_IO = nil self.read_co = nil return co_wakeup(co, true) end) self.timer = ti_timeout(self._timeout, function ( ) tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.timer = nil self.READ_IO = nil self.read_co = nil self.read_current_co = nil return co_wakeup(co, nil, "read timeout") end) tcp_start(self.READ_IO, self.fd, EVENT_READ, self.read_co) local ok, errinfo = co_wait() if not ok then return false, errinfo end goto CONTONIE end buffer = buffer and (buffer .. buf) or buf local s, e = buffer:find(sp) if s and e then tcp_sslpeek(self.ssl, #buf - (#buffer - e), false) if nosp then e = s - 1 end return buffer:sub(1, e), e end tcp_sslpeek(self.ssl, bsize, false) end end function TCP:recv(bytes) if self.ssl then return self:ssl_recv(bytes) end local fd = self.fd local data, len = tcp_read(fd, bytes) if type(len) ~= 'number' or len > 0 then return data, len end assert(not self.read_co, "[TCP ERROR]: Try to call the 'recv' method multiple times.") -- 优化大数据集的调用次数太多的问题 if not self.rsize or self.rsize < bytes then self.rsize = bytes if self.rsize > (1 << 16) then if self.rsize > (1 << 20) then self.rsize = 1 << 20 end tcp_set_read_buf(fd, self.rsize); end end local coctx = co_self() self.READ_IO = tcp_pop() self.read_current_co = co_self() self.read_co = co_new(function ( ) local buf, bsize = tcp_read(fd, bytes) if self.timer then self.timer:stop() self.timer = nil end tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.READ_IO = nil self.read_co = nil self.read_current_co = nil return co_wakeup(coctx, buf, bsize) end) self.timer = ti_timeout(self._timeout, function ( ) tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.timer = nil self.read_co = nil self.READ_IO = nil self.read_current_co = nil return co_wakeup(coctx, nil, "read timeout") end) tcp_start(self.READ_IO, fd, EVENT_READ, self.read_co) return co_wait() end function TCP:ssl_recv(bytes) local ssl = self.ssl if not ssl then Log:ERROR("Please use recv method :)") return nil, "Please use recv method :)" end local buf, len = tcp_sslread(ssl, bytes) if buf then return buf, len end assert(not self.read_co, "[TCP ERROR]: Try to call the 'recv' method multiple times.") -- 优化大数据集的调用次数太多的问题 if not self.rsize or self.rsize < bytes then self.rsize = bytes if self.rsize > (1 << 16) then if self.rsize > (1 << 20) then self.rsize = 1 << 20 end tcp_set_read_buf(self.fd, self.rsize); end end local coctx = co_self() self.READ_IO = tcp_pop() self.read_current_co = co_self() self.read_co = co_new(function ( ) while true do local buffer, bsize = tcp_sslread(ssl, bytes) if (buffer and bsize) or (not buffer and not bsize) then if self.timer then self.timer:stop() self.timer = nil end tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.READ_IO = nil self.read_co = nil self.read_current_co = nil return co_wakeup(coctx, buffer, bsize) end co_wait() end end) self.timer = ti_timeout(self._timeout, function ( ) tcp_push(self.READ_IO) tcp_stop(self.READ_IO) self.timer = nil self.READ_IO = nil self.read_co = nil self.read_current_co = nil return co_wakeup(coctx, nil, "read timeout") end) tcp_start(self.READ_IO, self.fd, EVENT_READ, self.read_co) return co_wait() end function TCP:listen(ip, port, cb) self.mode = "server" self.LISTEN_IO = tcp_pop() self.fd = tcp_new_server_fd(ip, port, self._backlog or 128) if not self.fd then return nil, "Listen port failed. Please check if the port is already occupied." end if type(cb) ~= 'function' then return nil, "Listen function was invalid." end self.listen_co = co_new(function (fd, ipaddr, port) while 1 do if fd and ipaddr then co_spawn(cb, fd, ipaddr, port) fd, ipaddr, port = co_wait() end end end) return true, tcp_listen(self.LISTEN_IO, self.fd, self.listen_co) end local function ssl_accept(callback, fd, ipaddr, port, opt) local sock = TCP:new() sock:set_fd(fd):timeout(5) -- 如果ssl握手长期未完成则选择断开连接 sock.ssl, sock.ssl_ctx = tcp_ssl_new_fd(fd) if type(opt.pw) == 'string' and opt.pw ~= '' then sock:ssl_set_password(opt.pw) end sock.mode = "server" sock:ssl_set_alpn(opt.alpn) sock:ssl_set_certificate(opt.cert) sock:ssl_set_privatekey(opt.key) tcp_ssl_set_accept_mode(sock.ssl, sock.ssl_ctx) if not sock:ssl_handshake() then return sock:close() end return callback(sock, ipaddr, port) end function TCP:listen_ssl(ip, port, opt, cb) self.mode = "server" self.LISTEN_SSL_IO = tcp_pop() self.sfd = tcp_new_server_fd(ip, port, self._backlog or 128) if not self.sfd then return nil, "Listen port failed. Please check if the port is already occupied." end if type(opt) ~= 'table' then return nil, "ssl listen must have key/cert/pw(optional)." end if type(opt.pw) == 'string' and opt.pw ~= '' then self:ssl_set_password(opt.pw) end self:ssl_set_certificate(opt.cert) self:ssl_set_privatekey(opt.key) -- 验证证书与私钥有效性 if not self:ssl_set_verify() then return nil, "The certificate does not match the private key." end if type(cb) ~= 'function' then return nil, "Listen function was invalid." end local sslopt = { timeout = self.timeout, alpn = self.alpn, cert = opt.cert, key = opt.key, pw = opt.pw } self.listen_ssl_co = co_new(function (fd, ipaddr, port) while 1 do if fd and ipaddr then co_spawn(ssl_accept, cb, fd, ipaddr, port, sslopt) fd, ipaddr, port = co_wait() end end end) return true, tcp_listen(self.LISTEN_SSL_IO, self.sfd, self.listen_ssl_co) end function TCP:listen_ex(unix_domain_path, removed, cb) self.mode = "server" self.LISTEN_EX_IO = tcp_pop() self.ufd = tcp_new_sever_unixsock_fd(unix_domain_path, removed or true, self._backlog or 128) if not self.ufd then return nil, "Listen_ex unix domain socket failed. Please check the domain_path was exists and access." end if type(cb) ~= 'function' then return nil, "Listen_ex function was invalid." end self.listen_ex_co = co_new(function (fd) while 1 do if fd then co_spawn(cb, fd, "127.0.0.1") fd = co_wait() end end end) return true, tcp_listen_ex(self.LISTEN_EX_IO, self.ufd, self.listen_ex_co) end function TCP:connect_ex(path) self.mode = "client" self.fd = tcp_new_client_unixsock_fd(assert(type(path) == 'string' and path, "Invalid unix domain path.")) if not self.fd then return nil, "Connect to unix domain socket failed." end return true end function TCP:connect(domain, port) self.mode = "client" local ok, IP = dns_resolve(domain) if not ok then return nil, "Can't resolve this domain or ip:" .. (domain or IP or "") end self.fd = tcp_new_client_fd(IP, port) if not self.fd then return nil, "Connect This host fault! "..(domain or "no domain")..":"..(port or "no port") end local co = co_self() self.CONNECT_IO = tcp_pop() self.connect_current_co = co_self() self.connect_co = co_new(function (connected, errinfo) if self.timer then self.timer:stop() self.timer = nil end tcp_push(self.CONNECT_IO) tcp_stop(self.CONNECT_IO) self.connect_current_co = nil self.CONNECT_IO = nil self.connect_co = nil return co_wakeup(co, connected, errinfo) end) self.timer = ti_timeout(self._timeout, function () tcp_push(self.CONNECT_IO) tcp_stop(self.CONNECT_IO) self.timer = nil self.CONNECT_IO = nil self.connect_co = nil self.connect_current_co = nil return co_wakeup(co, nil, 'connect timeout.') end) tcp_connect(self.CONNECT_IO, self.fd, self.connect_co) return co_wait() end function TCP:ssl_connect(domain, port) local ok, errinfo = self:connect(domain, port) if not ok then return false, errinfo end return self:ssl_handshake(domain) end local function event_wait(self, event) -- 当前协程对象 local co = co_self() self.connect_current_co = co -- 从对象池之中取出一个观察者对象 self.CONNECT_IO = tcp_pop() -- 读/写回调 self.connect_co = co_new(function ( ) -- 如果事件在超时之前到来需要停止定时器 if self.timer then self.timer:stop() self.timer = nil end -- 停止当前IO事件观察者并且将其放入对象池之中 tcp_stop(self.CONNECT_IO) tcp_push(self.CONNECT_IO) self.CONNECT_IO = nil self.connect_co = nil self.connect_current_co = nil -- 唤醒协程 return co_wakeup(co, true) end) -- 定时器回调 self.timer = ti_timeout(self._timeout, function ( ) -- 停止当前IO事件观察者并且将其放入对象池之中 tcp_push(self.CONNECT_IO) tcp_stop(self.CONNECT_IO) self.timer = nil self.CONNECT_IO = nil self.connect_co = nil self.connect_current_co = nil -- 唤醒协程 return co_wakeup(co, nil, 'connect timeout.') end) -- 注册I/O事件 tcp_start(self.CONNECT_IO, self.fd, event, self.connect_co) -- 让出执行权 return co_wait() end function TCP:ssl_handshake(domain) -- 如果设置了NPN/ALPN, 则需要在握手协商中指定. if self.alpn then tcp_ssl_set_alpn(self.ssl, self.ssl_ctx, spack(">B", #self.alpn) .. self.alpn) end -- 如果是服务端模式, 需要等待客户端先返送hello信息. -- 如果是客户端模式, 需要先发送hello信息. if self.mode == "server" then local ok, err = event_wait(self, EVENT_READ) if not ok then return nil, err end else if not self.ssl_ctx and not self.ssl then self.ssl, self.ssl_ctx = tcp_ssl_new_fd(self.fd) else tcp_ssl_set_fd(self.ssl, self.fd) end -- 如果有必要的话, 增加TLS的SNI特性支持. ssl_set_connect_server(self.ssl, domain or "localhost") end -- 开始握手 :: CONTINUE :: local successe, event = tcp_ssl_do_handshake(self.ssl) if not successe then -- 握手失败无需继续尝试 if not event then return nil, "ssl handshake failed." end -- 获取下次握手的等待事件: `READ` 或 `WRITE` local ok, errinfo = event_wait(self, event) if ok then -- 如果本次尝试成功则继续握手流程 goto CONTINUE end -- 握手超时、连接超时或连接中断 return nil, errinfo end -- 握手成功 return true end function TCP:count() return #POOL end function TCP:close() if self.timer then self.timer:stop() self.timer = nil end if self.READ_IO then tcp_stop(self.READ_IO) tcp_push(self.READ_IO) self.READ_IO = nil self.read_co = nil end if self.SEND_IO then tcp_stop(self.SEND_IO) tcp_push(self.SEND_IO) self.SEND_IO = nil self.send_co = nil self.sendfile_co = nil end if self.CONNECT_IO then tcp_stop(self.CONNECT_IO) tcp_push(self.CONNECT_IO) self.CONNECT_IO = nil self.connect_co = nil end if self.LISTEN_IO then tcp_stop(self.LISTEN_IO) tcp_push(self.LISTEN_IO) self.LISTEN_IO = nil self.listen_co = nil end if self.LISTEN_EX_IO then tcp_stop(self.LISTEN_EX_IO) tcp_push(self.LISTEN_EX_IO) self.LISTEN_EX_IO = nil self.listen_ex_co = nil end if self.LISTEN_SSL_IO then tcp_stop(self.LISTEN_SSL_IO) tcp_push(self.LISTEN_SSL_IO) self.LISTEN_SSL_IO = nil self.listen_ssl_co = nil end if self.connect_current_co then co_wakeup(self.connect_current_co) self.connect_current_co = nil end if self.send_current_co then co_wakeup(self.send_current_co) self.send_current_co = nil end if self.read_current_co then co_wakeup(self.read_current_co) self.read_current_co = nil end if self.sendfile_current_co then co_wakeup(self.sendfile_current_co) self.sendfile_current_co = nil end if self._timeout then self._timeout = nil end if self.ssl and self.ssl_ctx then tcp_free_ssl(self.ssl, self.ssl_ctx) self.ssl_ctx = nil self.ssl = nil end if self.fd then tcp_close(self.fd) self.fd = nil end if self.ufd then tcp_close(self.ufd) self.ufd = nil end if self.sfd then tcp_close(self.sfd) self.sfd = nil end end return TCP
local source_doc_root=[[j:\BM\E66230_01\]] local target_doc_root=[[j:\BM\newdoc12\]] --[[--FOR 11g local source_doc_root='j:\\BM\\E11882_01\\' local target_doc_root='j:\\BM\\newdoc11\\' --]] --[[ (c)2016-2017 by hyee, MIT license, https://github.com/hyee/Oracle-DB-Document-CHM-builder .hhc/.hhk/.hhp files are all created under the root path .hhc => Content rules(buildJson): target.db/target.json .hhk => Index rules(buildIdx): 1. Common books => index.htm: <dl> -> <dd[class='*ix']>content,<a[href]> <div> -> <ul> -> <li> -> <[ul|a]> 2. Javadoc books(contains 'allclasses-frame.html') => index-all.html, index-files\index-[1-30].html: <a (href="*.html#<id>" | href="*.html" title=)>content</a> 3. nav\[sql-keywords|catalog_views]*.htm -> key.json: <span> -> <b><a> 4. Glossary => glossary.htm <p[class="glossterm"]>[content]<a[name|id])>[content]</a></p> 5. Book Oracle Error messages(self.errmsg): <dt> -> (<span>->)? <a[name|id]> 6. Book PL/SQL Packages Reference and APLEX API: target.json -> First word in upper-case .hhp => Project rules(buildHhp): 1. Include all files 2. Enable options: Create binary TOC/Create binary indexes/Compile full-text search/show MSDN menu HTML file substitution rules(processHTML): 1. For javadoc, only replace all &lt/gt/amp as >/</& in javascript due to running into errors 2. For others: 1). Remove all <script>/<a[href="#BEGIN"]>/<header>/<footer> elements, used customized header instead 2). For all 'a' element, remove all 'onclick' and 'target' attributes 3). For all links that point to the top 'index.htm', replace as 'MS-ITS:index.chm::/index.htm' 4). For all links that point to other books: a. Replace '.htm?<parameters>' as '.htm' b. Caculate the <relative_path> based on the root path and replace '\' as '.', assign as the <file_name> c. Final address is 'MS-ITS:<file_name>.chm::/<relative_path>/<html_file(#...)?>' 5). For all links from 'a' that starts with 'http', set attribute target="_blank" 6). For the content inside "<footer></footer>", if contains the prev/next navigation, then add the bottom bar 7). For sections that after p="part", move as the children; for sections that p="appendix", move into appendix part Book list rules: all directories that contains 'toc.htm' Pattern for replace html5.css: (\.IND[^\{]+\{[^\}]+\swidth:\s*)(\d{1,2})% => \197% body: padding:20px --]] source_doc_root=source_doc_root:gsub('[\\/]+','\\'):gsub("\\$","")..'\\' target_doc_root=target_doc_root:gsub('[\\/]+','\\'):gsub("\\$","")..'\\' local sub_books={ E18476_01='Exalogic', E65319_01='Key Vault', E69292_01='Audit Vault', E72944_01='Airlines', E80920_01='Exadata', E83411_01='R', E83817_01='Utilities Data Model', E88198_01='Zero Data Loss Recovery', E89798_01='Big Data', ['E88198_01.DBMSG']='REMOVE', ['E89798_01.DBMSG']='REMOVE', ['E80920_01.DBMSG']='REMOVE', ['SQLQR']='REMOVE', ['E89798_01.DBLIC']='REMOVE', ['E88198_01.DBLIC']='REMOVE', ['E18476_01.doc.220.e26417']='REMOVE', ['E88198_01.OBLIC']='REMOVE', ['server.112.e41085']='REMOVE', } local all_books local book_file=target_doc_root..'book_list.json' local chm_builder=[[C:\Program Files (x86)\HTML Help Workshop\hhc.exe]] local plsql_package_ref={ARPLS=1,AEAPI=1,['appdev.112\\e40758']=1,['appdev.112\\e12510']=1} local errmsg_book={ERRMG=1,['server.112\\e17766']=1} local html=require("htmlparser") local json=require("json") local io,pairs,ipairs,math=io,pairs,ipairs,math local global_keys,global_key_file=nil,target_doc_root..'key.json' local ver=source_doc_root:find('E11882_01') and '11.2' or source_doc_root:find('121') and '12.1' or '12.2' local reps={ ['&acute;']='´', ['&copy;']='©', ['&gt;']='>', ['&micro;']='µ', ['&reg;']='®', ['&amp;']='&', ['&deg;']='°', ['&iexcl;']='¡', ['&nbsp;']=' ', ['&raquo;']='>>', ['&brvbar;']='¦', ['&divide;']='÷', ['&iquest;']='¿', ['&not;']='¬', ['&sect;']='§', ['&bull;']='•', ['&frac12;']='½', ['&laquo;']='<<', ['&para;']='¶', ['&uml;']='¨', ['&cedil;']='¸', ['&frac14;']='¼', ['&lt;']='<', ['&plusmn;']='±', ['&times;']='×', ['&cent;']='¢', ['&frac34;']='¾', ['&macr;']='¯', ['&quot;']='"', ['&trade;']='™', ['&euro;']='€', ['&pound;']='£', ['&yen;']='¥', ['&bdquo;']='„', ['&hellip;']='…', ['&middot;']='·', ['&rsaquo;']='>', ['&ordf;']='ª', ['&circ;']='ˆ', ['&ldquo;']='"', ['&mdash;']='—', ['&rsquo;']="'", ['&ordm;']='º', ['&dagger;']='†', ['&lsaquo;']='<', ['&ndash;']='–', ['&sbquo;']='‚', ['&rdquo;']='"', ['&Dagger;']='‡', ['&lsquo;']="'", ['&permil;']='‰', ['&shy;']='', ['&tilde;']='˜', ['&asymp;']='≈', ['&frasl;']='⁄', ['&larr;']='←', ['&part;']='∂', ['&spades;']='♠', ['&cap;']='∩', ['&ge;']='≥', ['&le;']='≤', ['&Prime;']='″', ['&sum;']='∑', ['&clubs;']='♣', ['&harr;']='↔', ['&loz;']='◊', ['&prime;']='′', ['&uarr;']='↑', ['&darr;']='↓', ['&hearts;']='♥', ['&minus;']='−', ['&prod;']='∏', ['&diams;']='♦', ['&infin;']='∞', ['&ne;']='≠', ['&radic;']='√', ['&equiv;']='≡', ['&int;']='∫', ['&oline;']='‾', ['&rarr;']='→', ['&alpha;']='α', ['&eta;']='η', ['&mu;']='μ', ['&pi;']='π', ['&theta;']='θ', ['&beta;']='β', ['&gamma;']='γ', ['&nu;']='ν', ['&psi;']='ψ', ['&upsilon;']='υ', ['&chi;']='χ', ['&iota;']='ι', ['&omega;']='ω', ['&rho;']='ρ', ['&xi;']='ξ', ['&delta;']='δ', ['&kappa;']='κ', ['&omicron;']='ο', ['&sigma;']='σ', ['&zeta;']='ζ', ['&epsilon;']='ε', ['&lambda;']='λ', ['&phi;']='φ', ['&tau;']='τ', ['&Alpha;']='Α', ['&Eta;']='Η', ['&Mu;']='Μ', ['&Pi;']='Π', ['&Theta;']='Θ', ['&Beta;']='Β', ['&Gamma;']='Γ', ['&Nu;']='Ν', ['&Psi;']='Ψ', ['&Upsilon;']='Υ', ['&Chi;']='Χ', ['&Iota;']='Ι', ['&Omega;']='Ω', ['&Rho;']='Ρ', ['&Xi;']='Ξ', ['&Delta;']='Δ', ['&Kappa;']='Κ', ['&Omicron;']='Ο', ['&Sigma;']='Σ', ['&Zeta;']='Ζ', ['&Epsilon;']='Ε', ['&Lambda;']='Λ', ['&Phi;']='Φ', ['&Tau;']='Τ', ['&sigmaf;']='ς' } local function rp(s) if reps[s] then return reps[s] end local asc=s:match('&#(%d+)') if asc and tonumber(asc)<=127 then return string.char(tonumber(asc)) end return s end local jcount={} local builder={} local is_build_global_keys=true local book_list function builder.load_books(toc) if not book_list then local txt=builder.read(source_doc_root.."nav\\portal_booklist.htm") if txt then book_list={} for url,name in txt:gmatch('<a href="%.%.[\\/]([^"]+[\\/]toc.html?)"[^>]*>%s*([^<]+)</a>') do url=source_doc_root..(url:gsub('[\\/]+','\\')) book_list[url]=name --print(url,name) end end end if toc then return book_list[toc] end return book_list end function builder.get_topic(toc,default,name) local topic=builder.load_books(toc) or default topic=topic:gsub('^%s+',' '):gsub('%s+$',' '):gsub('^[Oo]racle%S*%s+','') local found for k,v in pairs(sub_books) do found=name and name:find(k,1,true)==1 if found then if not topic:find(v,1,true) then topic=v..' '..topic end break end end if not found and topic~=default then default=default:gsub('^%s+',' '):gsub('%s+$',' '):gsub('^[Oo]racle%S*%s+','') if default:find('^Database ') and not topic:find('^Database ') then topic='Database '..topic end end return topic end function builder.new(dir,build,copy) dir=dir:gsub('[\\/]+','\\'):gsub("\\$","") if dir:find(target_doc_root,1,true)==1 then dir=dir:sub(#target_doc_root+1) end local depth,parent,folder local dirs={} for d in dir:gmatch('([^\\/]+)') do dirs[#dirs+1]=d end depth=#dirs if depth>1 then parent,folder=dir:match('^(.+)\\([^\\]+)$') else folder=dir end local full_dir=target_doc_root..dir..'\\' local sourceroot=source_doc_root..dir.."\\" local o={ ver=ver, toc=full_dir..'toc.htm', source_toc=sourceroot..'toc.htm', json=sourceroot..'target.json', db=sourceroot..'target.db', idx=full_dir..'index.htm', hhc="", hhk="", depth=depth, root=target_doc_root, dir=dir, full_dir=full_dir, dirs=dirs, parent=parent, folder=folder, name=dir:gsub("[\\/]+",".")} if sub_books[o.name]=='REMOVE' then return end if copy then local targetroot='"'..full_dir..'"' local lst={"toc.htm","index.htm","title.htm"} for j=1,3 do builder.exists(sourceroot..lst[j]) end local exec=io.popen("mkdir "..targetroot..' 2>nul & xcopy "'..sourceroot..'*" '..targetroot.." /E/Y/Q /EXCLUDE:exclude.txt") exec:close() end if builder.exists(full_dir.."title.htm",true) then o.title="title.htm" else o.title="toc.htm" end if not global_keys then global_keys={} end if not all_books then book_text=builder.read(book_file) all_books=book_text and json.decode(book_text) or {} end --[[ if is_build_global_keys and not global_keys then global_keys=builder.read(global_key_file) if global_keys then global_keys=json.decode(global_keys) else global_keys={} end elseif not global_keys then global_keys={} end--]] if builder.exists(full_dir..'allclasses-frame.html') then o.is_javadoc=true end setmetatable(o,builder) builder.__index=builder if build then o:startBuild() end return o end function builder.read(file) local f,err=io.open(file,'r') if not f then return nil,err else local text=f:read('*a') f:close() return text end end function builder.exists(file,silent) local text,err=builder.read(file) return text end function builder.save(path,text) if type(path)=="table" then print(debug.traceback()) end local f=io.open(path,"w") f:write(text) f:close() end function builder:getContent(file) local txt=self.exists(file) if not txt then return end local title=txt:match([[<meta name="doctitle" content="([^"]+)"]]) if not title then title=txt:match("<title>(.-)</title>") end if title then title=title:gsub("%s*&reg;?%s*"," "):gsub("([\1-\127\194-\244][\128-\193])", ''):gsub('%s*|+%s*',''):gsub('&.-;','') end local root=html.parse(txt,1000000):select("div[class^='IND']") return root and root[1] or nil,title end function builder:buildGlossary(tree) local text=self.read(self.full_dir..'glossary.htm') if not text then return end local nodes=html.parse(text,1000000):select('p[class="glossterm"]') for _,p in ipairs(nodes) do local a=p.nodes[1] local ref=a.attributes.id or a.attributes.name if a.name=="a" and ref then local content=a:getcontent():gsub('%s+$','') if content=="" then content=p:getcontent():gsub('<.->',''):gsub('%s+$','') end tree[#tree+1]={name=content,ref={'glossary.htm#'..ref}} end end end function builder:buildIdx() local hhk={[[<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML><HEAD> <meta content="Microsoft HTML Help Workshop 4.1" name="GENERATOR"> <!-- Sitemap 1.0 --> </HEAD> <BODY><UL>]]} local c=self:getContent(self.idx) if not c and not self.errmsg and not self.is_javadoc and (is_build_global_keys and not global_keys[self.name]) then return end local function append(level,txt) hhk[#hhk+1]='\n '..string.rep(" ",level).. txt end local tree,sql_keys={},global_keys[self.name] or {} if self.errmsg then tree=self.errmsg print(#tree..' Error codes are indexed.') elseif self.is_javadoc then --process java-doc api local text=self.read(self.full_dir..'index-all.html') if not text then local f=io.popen('dir /s/b "'..self.full_dir..'index-*.htm*"') local files={} for path in f:lines() do files[#files+1]=self.read(path) end text=table.concat(files,'') if text=='' then text=nil end end if text then local nodes=html.parse(text,1000000):select("a") local addrs={} for idx,a in ipairs(nodes) do if a.attributes.href and a.attributes.href:find('.htm',1,true) then local content=a:getcontent():gsub('<.->',''):gsub('%s+$','') local ref=a.attributes.href:gsub('^%.[\\/]?',''):gsub('/','\\') if ((ref:find('#',1,true) or 0)> 2 or a.attributes.title) and content~="" and not addrs[content..ref] then addrs[content..ref]=1 tree[#tree+1]={name=content,ref={ref}} end end end end elseif c then local nodes=c:select("dd[class*='ix']") local treenode={} for _,node in ipairs(nodes) do local level=tonumber(node.attributes.class:match('l(%d+)ix')) if level then local content=node:getcontent():gsub('%s+$','') local n={name=content:gsub('[%s,%.]*<.*>.*$','') ,ref={}} for _,a in ipairs(node:select("a")) do n.ref[#n.ref+1]=a.attributes.href end treenode[level]=n if level>1 then table.insert(treenode[level-1],n) if #n.ref>0 then for lv=1,level-1 do if #treenode[lv].ref==0 then treenode[lv].ref=n.ref end end elseif content:lower():find('>see<',1,true) and #treenode[level-1].ref==0 then treenode[level-1].ref[1]='#SEE#'..content:gsub('<.->',''):gsub('^%s*See%s*','') end else tree[#tree+1],sql_keys[n.name:upper()]=n,nil end end end if #nodes==0 then local uls=c:select("div > ul") local function access_childs(li,level) if li.name~="li" or not li.nodes[1] then return end local content=li:getcontent():gsub('^%s+','') local n={name=content:gsub('[%s,]+<.+>.*$',''),ref={}} if n.name=="" then return end if level==1 then tree[#tree+1],sql_keys[n.name:upper()]=n,nil elseif n.name=="about" then level,n=level-1,treenode[level-1] else table.insert(treenode[level-1],n) end treenode[level]=n local lis=li:select("li") if li.nodes[1].name~="ul" then for _,a in ipairs(li:select("a")) do if a.parent==li or (a.parent and a.parent.name=="span" and a.parent.parent==li) then n.ref[#n.ref+1]=a.attributes.href end end if level>1 and #n.ref==0 and #treenode[level-1].ref==0 then if content:lower():find('see.*:') then treenode[level-1].ref[1]='#SEE#'..n.name:gsub('<.->',''):gsub('^.-:%s*','') end else for lv=1,level-1 do if #treenode[lv].ref==0 then treenode[lv].ref=n.ref end end end else for _,child in ipairs(li.nodes[1].nodes) do access_childs(child,level+1) end end end for _,ul in ipairs(uls) do for _,li in ipairs(ul.nodes) do access_childs(li,1) end end end end local counter=#tree self:buildGlossary(tree) if #tree>counter then print((#tree-counter)..' glossaries are indexed.') counter=#tree end for name,ref in pairs(sql_keys) do tree[#tree+1]={name=ref[1],ref={ref[2]}} end if #tree>counter then print((#tree-counter)..' additional keywords are indexed.') counter=#tree end counter=0 local function travel(level,node,parent) if not parent then for i=1,#node do travel(level,node[i],node) end return end if node.name~="" then for i=1,#node.ref do counter=counter+1 append(level+1,"<LI><OBJECT type=\"text/sitemap\">") if node.ref[i]:find("^#SEE#")==1 then append(level+2,([[<param name="Name" value="%s">]]):format(node.name)) append(level+2,([[<param name="See Also" value="%s">]]):format(node.ref[i]:sub(6))) else append(level+2,([[<param name="Name" value="%s">]]):format(node.name)) append(level+2,([[<param name="Local" value="%s">]]):format(self.dir..'\\'..node.ref[i])) end if i==#node.ref and #node>0 then append(level+1,'</OBJECT><UL>') for i=1,#node do travel(level+1,node[i],node) end append(level+1,'</UL>') else append(level,'</OBJECT>') end end end end travel(0,tree) append(0,"</UL></BODY></HTML>") self.hhk=self.name..".hhk" self.save(self.root..self.hhk,table.concat(hhk)) self.index_count=#tree..'/'..counter print('Totally '..self.index_count..' items are indexed.') end function builder:buildJson() self.hhc=self.name..".hhc" local hhc={ [[<HTML><HEAD> <meta content="Microsoft HTML Help Workshop 4.1" name="GENERATOR"> <!-- Sitemap 1.0 --> </HEAD> <BODY> <OBJECT type="text/site properties"> <param name="Window Styles" value="0x800225"> <param name="comment" value="title:Online Help"> <param name="comment" value="base:toc.htm"> </OBJECT><UL>]]} local function append(level,txt) hhc[#hhc+1]='\n '..string.rep(" ",level*2).. txt end local txt,typ=self.read(self.db),'db' if not txt then txt,typ=self.read(self.json),'json' end if not txt then local title,href if self.name:lower()=="nav" then self.topic='All Books for Oracle Database Online Documentation Library' self.topic_count='5/5' href='portal_booklist.htm' self.toc=self.full_dir..href self.title=href append(1,[[<LI><OBJECT type="text/sitemap"> <param name="Name" value="All Books for Oracle Database Online Documentation Library"> <param name="Local" value="nav\portal_booklist.htm"> <param name="ImageNumber" value="21"> </OBJECT> <LI><OBJECT type="text/sitemap"> <param name="Name" value="All Data Dictionary Views"> <param name="Local" value="nav\catalog_views.htm"> <param name="ImageNumber" value="21"> </OBJECT> <LI><OBJECT type="text/sitemap"> <param name="Name" value="All SQL, PL/SQL and SQL*Plus Keywords"> <param name="Local" value="nav\sql_keywords.htm"> <param name="ImageNumber" value="21"> </OBJECT> <LI><OBJECT type="text/sitemap"> <param name="Name" value="Master Glossary"> <param name="Local" value="nav\mgloss.htm"> <param name="ImageNumber" value="21"> </OBJECT> <LI><OBJECT type="text/sitemap"> <param name="Name" value="Master Index"> <param name="Local" value="nav\mindx.htm"> <param name="ImageNumber" value="21"> </OBJECT>]]) else local _,title=self:getContent(self.toc) href='toc.htm' self.topic=self.get_topic(self.source_toc,title or "All Book List",self.name) append(1,"<LI><OBJECT type=\"text/sitemap\">") append(2,([[<param name="Name" value="%s">]]):format(self.topic)) append(2,([[<param name="Local" value="%s">]]):format(self.dir..'\\'..href)) append(1,"</OBJECT>") end append(0,"</UL></BODY></HTML>") self.save(self.root..self.hhc,table.concat(hhc)) print('Book:',self.topic) return end local root if typ=='db' then txt=txt:gsub('<%?xml.-%?>','') txt=txt:gsub('<xreftext>.-</xreftext>','') local doc=html.parse(txt,1000000) root={docs={}} local appendix="appendix" local function travel(node,parent,depth) local attrs=node.attributes attrs.targetptr=attrs.targetptr~="" and attrs.targetptr or nil local u=attrs.href and (attrs.href..(attrs.targetptr and ('#'..attrs.targetptr) or '')) local n=attrs.number~="" and attrs.number or nil if n then n=n:gsub("^%s+",""):gsub("%s+$","") end local e=attrs.element and attrs.element:lower() or nil u={h=u,n=node.name,p=e,c={n=node.name,p=e},seq=n} if e==appendix and parent.p~=appendix and node.name=="div" and parent.n=="div" then local prev=parent[#parent] if prev and prev.c and prev.c.n=="div" and (prev.c.p==appendix and #prev.c>0 or prev.c.p=="part") then if prev.t==prev.seq then prev.t=prev.seq.." Appendixes" end parent=prev.c else local apx={n=node.name,p=e,t="Appendix",h=u.h,c={n=node.name,p=e}} --print(string.rep(' ',4*depth)..apx.t) parent[#parent+1]=apx parent=apx.c end depth=depth+1 end parent[#parent+1]=u u.d=depth for idx,child in ipairs(node.nodes) do local p=child.name=="obj" and u.c or child.name=="div" and u.c if p then travel(child,p,depth+1) elseif not u.t and child.name=="ttl" then u.t=((n and (n.." "):gsub("%%s"," ") or "")..child:getcontent()):gsub("%s+"," ") --print(string.rep(' ',4*depth)..u.t.." => "..(u.h or "")) end end if not u.t and n then u.t=n end end travel(doc.nodes[1],root.docs,0) else root=json.decode(txt) end local last=#root.docs[1].c for i=last,1,-1 do local node=root.docs[1].c[i] local p=node.p if (node.t==node.seq or not node.t) and node.h then local url=(self.full_dir..node.h):gsub("(html?)#.+$","%1") txt=self.read(url) if txt then local title=txt:match("<title>(.-)</title>") if title then node.t=(node.seq and (node.seq.." ") or "")..title end end end local t=node.t and node.t:lower() if t and p=="part" and (not node.c or #node.c==0) and last then node.c={p=node.p,n=node.n} for j=last,i+1,-1 do local child=table.remove(root.docs[1].c,j) --print(node.t,child.t) table.insert(node.c,1,child) end last=nil elseif p=="part" or p=="appendix" or p=="index" or p=="glossary" or node.t=="index" or node.t=="glossary" then last=nil elseif not last then last=i end end txt=self.read(self.toc) if txt then for v,item in ipairs{ {'"(title.html?)"','Title and Copyright Information'}, {'"(loe.html?)"','List of Examples'}, {'"(lot.html?)"','List of Tables'}, {'"(lof.html?)"','List of Figures'}, } do local url=txt:match(item[1]) if url then table.insert(root.docs[1].c,1,{t=item[2],h=url}) end end end root.docs[1].t=self.get_topic(self.source_toc,root.docs[1].t,self.name) local counter,last_node,sql_keys=0 if plsql_package_ref[self.dir] then print('Found PL/SQL API and indexing the content.') end local partin=false local function travel(node,level) if node.t then node.t=node.t:gsub("([\1-\127\194-\244][\128-\193])", ''):gsub('%s*|+%s*',''):gsub('(&.-;)',rp):gsub('\153',"'"):gsub("^%s+",""):gsub("%s+"," ") last_node=node.h counter=counter+1 append(level+1,"<LI><OBJECT type=\"text/sitemap\">") append(level+2,([[<param name="Name" value="%s">]]):format(node.t)) append(level+2,([[<param name="Local" value="%s">]]):format(self.dir..'\\'..node.h)) if plsql_package_ref[self.dir] then local first=node.t:match('^[^%s]+') if not sql_keys then sql_keys=global_keys[self.name] or {} global_keys[self.name]=sql_keys end if first:upper()==first and level<4 then --index package name and method sql_keys[node.t:upper()]={node.t,node.h} end end if node.c and #node.c>0 then append(level+1,"</OBJECT><UL>") for index,child in ipairs(node.c) do travel(child,level+1) end if level==0 and last_node and not last_node:lower():find('^index%.htm') then if self.exists(self.idx,true) then counter=counter+1 append(1,"<LI><OBJECT type=\"text/sitemap\">") append(2,[[<param name="Name" value="Index">]]) append(2,([[<param name="Local" value="%s">]]):format(self.dir..'\\index.htm')) append(1,"</OBJECT>") end end append(level+1,"</UL>") else append(level+1,"</OBJECT>") end elseif #node>0 then for index,child in ipairs(node) do travel(child,level+1) end end end travel(root.docs[1],0) append(0,"</UL></BODY></HTML>") self.save(self.root..self.hhc,table.concat(hhc)) self.topic=root.docs[1].t self.topic_count=#root.docs[1].c..'/'..counter print('Book:',self.topic) print('Totally '..self.topic_count..' topics are created.') return self.topic end function builder:processHTML(file,level) if not file:lower():find("%.html?$") then return end local prefix=string.rep("%.%.[\\/]",level) local txt=self.read(file) if not txt then error('error on opening file: '..file) end local fmt='<a href=%s%s%s %s>%s</a>' local subs={} self.dirs=self.dirs or {} txt=txt:gsub([[<a ([^>]*)href=(['"])([^'">]+)%2([^>]*)>(.-)</a>]], function(pre,q,url,sux,content) if url=='#BEGIN' then return '' end pre=pre..sux if url:find('dcommon',1,true) or url:find('^javascript') or url:find('^#') or url:find('MS-ITS:',1,true) then return fmt:format(q,url,q,pre,content) end local pre1=pre:gsub([[target=(['"]).-%1]],''):gsub([[onclick=(['"]).-%1]],''):gsub([[onload=(['"]).-%1]],'') if url:find('^http') or url:find('^www') then return fmt:format(q,url,q,pre1..' target='..q..'_blank'..q,content) end if not self.is_javadoc then pre=pre1 end url=url:gsub('%?[^#]+','') if level>0 then url=url:gsub('^'..prefix,'') end local s,e=url:match('^(.-)([^\\/]+%.[^\\/]+)$') --if not s then print(url) end if s=='' or not s then return fmt:format(q,url,q,pre,content) end subs[#subs]=nil for i=1,#self.dirs do subs[i]=self.dirs[i] end while s:find('^%.%.[\\/]') do subs[#subs]=nil s=s:sub(4) end subs[#subs+1]=s s=table.concat(subs,'/'):gsub('\\','/') local book=s:gsub("/",".") if s:find('%.pdf$') then return fmt:format(q,[[javascript:location.href='file:///'+location.href.match(/\:((\w\:)?[^:]+[\\/])[^:\\/]+\:/)[1]+']]..s:gsub("/",".")..e..".chm'",pre1,'CHM') elseif s:find('^index.html?$') then return fmt:format(q,'MS-ITS:index.chm::/index.htm',q,pre,content) elseif #subs>#self.dirs and #self.dirs>0 then return fmt:format(q,url,q,pre,content) elseif self.name and self.name:find(book,1,true) then return fmt:format(q,e,q,pre,content) else if not all_books[s:upper()] and s:find('/',1,true) then local u,found=(s..e):upper(),false for k,v in ipairs(all_books) do if type(k)=="string" then if u:find(k,1,true)==1 then u,found=s..e,true s,e=u:sub(1,#k),u:sub(#k+1) end end end if not found then print(string.format('Cannot not find chm for link %s, folder: %s, file:%s',url,s,e)) return fmt:format(q,url,q,pre,content) end end return fmt:format(q,'MS-ITS:'..book.."chm::/"..s..e,q,pre,content) end end) if self.is_javadoc then txt=txt:gsub('(<script)(.-)(</script>)',function(a,b,c) return a..b:gsub('&lt;','>'):gsub('&amp;','&'):gsub('&gt;','<')..c end) self.save(file,txt) return elseif self.dir and errmsg_book[self.dir] then --deal with the error message book if not self.errmsg then self.errmsg={} end local doc=html.parse(txt,1000000):select("dt") local name=file:match("[^\\/]+$") for idx,node in ipairs(doc) do local a=node.nodes[1] if a.name~='a' and a.nodes[1] then node,a=a,a.nodes[1] end local ref=a.attributes.id or a.attributes.name if a.name=='a' and ref and not a.attributes.href then local content=node:getcontent():gsub('.*</a>%s*',''):gsub('<.->',''):gsub('%s+$',''):gsub('%s+',' ') if content:find(':') then self.errmsg[#self.errmsg+1]={name=content:match('[^%s:]+'),ref={name..'#'..ref}} end end end end local count=0 self.topic=self.topic or "" local dcommon_path=string.rep('../',level+#self.dirs)..'dcommon' local header=[[<table summary="" cellspacing="0" cellpadding="0" style="width:100%%"> <tr> <td nowrap="nowrap" align="left" valign="top"><b style="color:#326598;font-size:12px">%s<br/><i style="color:black">%s Release %s</i></b></td> <td nowrap="nowrap" style="font-size:10px" width=70 align="center" valign="top"><a href="index.htm"><img width="30" height="30" src="%s/gifs/index.gif" alt="Go to Index" /><br />Index</a></td> <td nowrap="nowrap" style="font-size:10px" width=80 align="center" valign="top"><a style="font-size:10px" href="toc.htm"><img width="30" height="30" src="%s/gifs/doclib.gif" alt="Go to Documentation Home" /><br />Content</a></td> <td nowrap="nowrap" style="font-size:10px" width=90 align="center" valign="top"><a style="font-size:10px" href="MS-ITS:nav.chm::/nav/portal_booklist.htm"><img width="30" height="30" src="%s/gifs/booklist.gif" alt="Go to Book List" /><br />Book List</a></td> <td nowrap="nowrap" style="font-size:10px" width=100 align="center" valign="top"><a style="font-size:10px" href="MS-ITS:nav.chm::/nav/mindx.htm"><img width="30" height="30" src="%s/gifs/masterix.gif" alt="Go to Master Index" /><br />Master Index</a></td> </tr> </table>]] local big,small=ver:match("(%d+)%.(%d+)") header=header:format('Oracle&reg; '..self.topic:gsub("^[Oo]racle%s+",""), big..(big=='11' and 'g' or 'c'), small, dcommon_path,dcommon_path,dcommon_path,dcommon_path) txt,count=txt:gsub("\n(%s+parent%.document%.title)","\n//%1"):gsub("&amp;&amp;","&&") txt,count=txt:gsub('%s*<header>.-</header>%s*','') txt=txt:gsub('%s*<meta http%-equiv="X%-UA%-Compatible"[^>]+>%s*','') txt=txt:gsub('<head>','<head><meta http-equiv="X-UA-Compatible" content="IE=9"/>',1) txt=txt:gsub('%s*<footer>(.-)</footer>%s*',function(s) if not s:find("nav%.gif") then return "" end local left,right,copy='#','#','' for url,dir in s:gmatch('<a%s+href="([^"]+)"[^>]*><img%s+[^>]+src="(.-/(%w+)nav.gif)"') do if dir=='left' then left=url else right=url end end copy=s:match("(Copyright[^<]+)") or ""; return ([[ <hr/><table><tr> <td style="width:80px"><a href="%s"><img width="24" height="24" src="%s/gifs/leftnav.gif" alt="Go to previous page" /></a></td> <td style="text-align:center;vertical-align:middle;font-size:9px"><img width="144" height="18" src="%s/gifs/oracle.gif" alt="Oracle" /><br/>%s</td> <td style="width:80px;text-align:right"><a href="%s"><img width="24" height="24" src="%s/gifs/rightnav.gif" alt="Go to next page" /></a></td> </tr></table>]]):format(left,dcommon_path,dcommon_path,copy,right,dcommon_path) end) txt=txt:gsub([[(%s*<script.-<%/script>%s*)]],'') txt=txt:gsub('(<[^>]*) onload=".-"','%1') if count>0 then txt=txt:gsub('(<div class="IND .->)','%1'..header,1) end if self.name and self.name:lower()=="nav" and (file:find('sql_keywords',1,true) or file:find('catalog_views',1,true)) then for _,span in ipairs(html.parse(txt):select("span")) do local b,a=span.nodes[1],span.nodes[2] if a and b.name=='b' and a.name=='a' and (a.attributes.href or ""):find('MS-ITS',1,true) then local index_name=b:getcontent():gsub('[:%s]+$','') local book,href=a.attributes.href:match('MS%-ITS:(.+)%.chm::/(.+)') if not global_keys[book] then global_keys[book]={} end global_keys[book][index_name:upper()]={index_name,href:sub(#book+2):gsub('/','\\')} end end end if not txt then print("file",file,"miss matched!") end self.save(file,txt) end function builder:listdir(base,level,callback) local root=target_doc_root..base local f=io.popen(([[dir /b/s %s*.htm]]):format(root)) for file in f:lines() do local _,depth=file:sub(#root+1):gsub('[\\/]','') self:processHTML(file,depth) if callback then callback(file:sub(#target_doc_root+1),root,level+depth) end end f:close() --if self.errmsg then self:buildIdx() end end function builder:buildHhp() local title='Oracle '..self.topic local hhp=string.format([[[OPTIONS] Binary TOC=No Binary Index=Yes Topics=%s Indexes=%s Compiled File=%s.chm Contents File=%s Index File=%s Default Window=main Default Topic=%s\%s Default Font= Full-text search=Yes Auto Index=Yes Enhanced decompilation=Yes Language= Title=%s Create CHI file=No Compatibility=1.1 or later Error log file=%s_errorlog.txt Full text search stop list file= Display compile progress=Yes Display compile notes=Yes [WINDOWS] main="%s","%s","%s","%s\%s","%s\%s",,,,,0x33520,222,0x70384E,[10,10,800,600],0xB0000,,,,,,0 [FILES] ]], self.topic_count or '1/1',self.index_count or '0/0',self.name,self.hhc,self.hhk,self.dir,self.title,title,self.name, title,self.hhc,self.hhk,self.dir,self.title,self.dir,self.title,self.name) hhp=hhp..table.concat(self.filelist,'\n') local _,depth=self.dir:gsub('[\\/]','') self.save(self.root..self.name..".hhp",hhp:gsub('[\n\r]+%s+','\n')) if self.name:lower()=='nav' and is_build_global_keys then os.execute('copy /Y html5.css '..target_doc_root..'nav\\css') self.save(global_key_file,json.encode(global_keys)) end end function builder:startBuild() print(string.rep('=',100).."\nBuilding "..self.dir..'...') self.filelist={} if not self.dir:find('dcommon') then self:buildJson() end self:listdir(self.dir..'\\',self.depth,function(item) table.insert(self.filelist,item) end) if not (self.dir:find('dcommon') or self.name:find("%.nav$")) then self:buildIdx() self:buildHhp() end end function builder.BuildAll(parallel) os.execute(string.format("del %s*.hh* & del %s*.chm",target_doc_root,target_doc_root)) local tasks={} local fd all_books={} fd=io.popen(([[dir /s/b "%slookup.htm" & dir /s/b "%stoc.htm"]]):format(source_doc_root,source_doc_root)) for dir in fd:lines() do local name,file=dir:sub(#source_doc_root+1):match('^(.+)[\\/]([^\\/]+)$') local isnav=name=="nav" or name:find('\\nav$') if file=='lookup.htm' and isnav then builder.new(name:gsub('nav$','dcommon'),true,true) all_books[#all_books+1]=name elseif file=='toc.htm' and not isnav then all_books[#all_books+1]=name end all_books[name:upper():gsub('\\','/')..'/']=all_books[#all_books] end fd:close() os.remove(global_key_file) builder.save(book_file,json.encode(all_books)) for i,book in ipairs(all_books) do local this=builder.new(book,true,true) if this then local idx=math.fmod(i-1,parallel)+1 if i==1 then-- for nav idx=parallel+1 end if not tasks[idx] then tasks[idx]={} end local obj='"'..chm_builder..'" "'..target_doc_root..this.name..'.hhp"' if errmsg_book[book] then tasks[idx][#tasks[idx]+1]=obj else table.insert(tasks[idx],1,obj) end end end table.insert(tasks[#tasks],'"'..chm_builder..'" "'..target_doc_root..'index.hhp"') for i=1,#tasks do builder.save(i..".bat",table.concat(tasks[i],"\n")..'\nexit\n') if i<=parallel then os.execute('start "Compiling CHMS '..i..'" '..i..'.bat') end end print('Since compiling nav.chm takes longer time, please execute '..(parallel+1)..'.bat separately if necessary.') builder.BuildBatch() end function builder.BuildBatch() local dir=target_doc_root builder.topic='Oracle '..ver..' Documentations' builder.save(dir..'index.htm',builder.read(source_doc_root..'index.htm')) builder.processHTML(builder,dir..'index.htm',0) local hhc=[[<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML> <HEAD> <meta name="generator" content="Microsoft&reg; HTML Help Workshop 4.1"> <!-- Sitemap 1.0 --> </head> <body> <OBJECT type="text/site properties"> <param name="Window Styles" value="0x800225"> <param name="comment" value="title:Online Help"> <param name="comment" value="base:index.htm"> </OBJECT> <UL> <LI><OBJECT type="text/sitemap"> <param name="Name" value="Portal"> <param name="Local" value="index.htm"> <param name="ImageNumber" value="13"> </OBJECT> <LI><OBJECT type="text/sitemap"> <param name="Name" value="CHM File Overview"> <param name="Local" value="chm.htm"> <param name="ImageNumber" value="39"> </OBJECT> </UL> ]] local hhk=[[ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <HTML> <HEAD> <meta name="generator" content="Microsoft&reg; HTML Help Workshop 4.1"> <!-- Sitemap 1.0 --> <BODY> <OBJECT type="text/site properties"> <param name="Window Styles" value="0x800025"> <param name="comment" value="title:Online Help"> <param name="comment" value="base:index.htm"> </OBJECT> <OBJECT type="text/site properties"> <param name="FrameName" value="right"> </OBJECT> <UL> <LI> <OBJECT type="text/sitemap"> <param name="Name" value="copyright"> <param name="Local" value="dcommon\html\cpyr.htm"> </OBJECT> </UL> </BODY> </HTML> ]] local hhp=[[ [OPTIONS] Binary TOC=No Binary Index=Yes Compiled File=index.chm Contents File=index.hhc Index File=index.hhk Default Window=main Default Topic=index.htm Default Font= Full-text search=Yes Auto Index=Yes Enhanced decompilation=Yes Language= Title=]]..builder.topic..[[ Create CHI file=No Compatibility=1.1 or later Error log file=..\_errorlog.txt Full text search stop list file= Display compile progress=Yes Display compile notes=Yes [WINDOWS] main="]]..builder.topic..[[","index.hhc","index.hhk","index.htm","index.htm",,,,,0x33520,222,0x101846,[10,10,800,600],0xB0000,,,,,,0 [FILES] index.htm chm.htm [MERGE FILES] ]] local hhclist={} local f=io.popen(([[dir /b "%s*.hhc"]]):format(dir)) for name in f:lines() do local n=name:sub(-4) local c=name:sub(1,-5) if n==".hhc" and name~="index.hhc" then local txt=builder.read(dir..c..".hhp") if txt then local title=txt:match("Title=([^\n]+)") hhclist[#hhclist+1]={file=c,title=title,chm=c..".chm",topic_count=txt:match("Topics=([^\n]+)"),index_count=txt:match("Indexes=([^\n]+)")} end end end f:close() table.sort(hhclist,function(a,b) if a.file:find('nav$') then return true end if b.file:find('nav$') then return false end return a.title<b.title end) local html={'<table border><tr><th align="left">CHM File Name</th><th>Topics</th><th>Indexes</th><th align="left">Book Name</th></tr>'} local row=[[<tr><td><a href="javascript:location.href='file:///'+location.href.match(/\:((\w\:)?[^:]+[\\/])[^:\\/]+\:/)[1]+'%s'">%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>]] local item=' <OBJECT type="text/sitemap">\n <param name="Merge" value="%s.chm::/%s.hhc">\n </OBJECT>\n' for i,book in ipairs(hhclist) do html[#html+1]=row:format(book.chm,book.chm,book.topic_count or 'N/A',book.index_count or 'N/A',book.title) hhc=hhc..(item):format(book.file, book.file) hhp=hhp..book.chm.."\n" end html=table.concat(html,'\n')..'</table><br/><p style="font-size:12px">&copy;2016 hyee https://github.com/hyee/Oracle-DB-Document-CHM-builder</p>' hhc=hhc..'</BODY></HTML>' builder.save(dir.."chm.htm",html) builder.save(dir.."index.hhp",hhp:gsub('[\n\r]+%s+','\n')) builder.save(dir.."index.hhc",hhc) builder.save(dir.."index.hhk",hhk) end function builder.scanInvalidLinks() local max_books=3 local f=io.popen('dir /s/b "'..target_doc_root..'*errorlog.txt"') for file in f:lines() do local filelist={} local txt,err=builder.read(file) if txt then local book=txt:match("[\\/]([^\\/]+)%.chm") for link in txt:gmatch('[\n\r](%S+\\%S+)') do if not link:match(book) and not link:find('nav\\',1,true) and not link:find('dcommon\\') then print('Detected link '..link..' on book: '..book) end end else print(err) end end end local arg={...} if arg[1] then local p=tonumber(arg[1]) if p==0 then builder.BuildBatch() elseif p==-1 then builder.scanInvalidLinks() elseif p==-2 then builder.processHTML(builder,target_doc_root..'index.htm',0) elseif p and p>0 then builder.BuildAll(p) else is_build_global_keys=false builder.new(arg[1],true,true) os.execute('"'..chm_builder..'" '..target_doc_root..(arg[1]:gsub("[\\/]",'.'))..'.hhp') end end
--[[ TheNexusAvenger Tests the yxpcall method. --]] local NexusUnitTesting = require("NexusUnitTesting") local NexusUnitTestingProject = require(game:GetService("ReplicatedStorage"):WaitForChild("NexusUnitTesting"):WaitForChild("NexusUnitTestingProject")) local yxpcall = NexusUnitTestingProject:GetResource("UnitTest.yxpcall") --[[ Tests no error being thrown. --]] NexusUnitTesting:RegisterUnitTest("NoErrorThrown",function(UnitTest) --Call yxpcall. local ErrorThrown = false local Worked,Return1,Return2 = yxpcall(function() return "Test1","Test2" end,function() ErrorThrown = true end) --Assert the results are correct. UnitTest:AssertFalse(ErrorThrown,"Error was thrown.") UnitTest:AssertTrue(Worked,"Worked result is incorrect.") UnitTest:AssertEquals(Return1,"Test1","First return is incorrect.") UnitTest:AssertEquals(Return2,"Test2","Second return is incorrect.") end) --[[ Tests calling with arguments. --]] NexusUnitTesting:RegisterUnitTest("NoErrorThrownArgumentsPassed",function(UnitTest) --Call yxpcall with arguments. local ErrorThrown = false local Worked,Return1,Return2 = yxpcall(function(Argument1,Argument2) return Argument1,Argument2 end,function() ErrorThrown = true end,"Test1","Test2") --Assert the results are correct. UnitTest:AssertFalse(ErrorThrown,"Error was thrown.") UnitTest:AssertTrue(Worked,"Worked result is incorrect.") UnitTest:AssertEquals(Return1,"Test1","First return is incorrect.") UnitTest:AssertEquals(Return2,"Test2","Second return is incorrect.") end) --[[ Tests an error being thrown. --]] NexusUnitTesting:RegisterUnitTest("ErrorThrown",function(UnitTest) --Call yxpcall with arguments. local CalledError,CalledStackTrace local Worked = yxpcall(function() error("Test error") end,function(Error,StackTrace) CalledError,CalledStackTrace = Error,StackTrace end) --Assert the results are correct. UnitTest:AssertFalse(Worked,"Worked result is incorrect.") UnitTest:AssertNotNil(string.find(CalledError,"Test error"),"Error message doesn't contain the thrown error.") UnitTest:AssertNotNil(string.find(CalledStackTrace,"yxpcallTests"),"Error stack trace doesn't contain the script.") end) --[[ Tests an error being thrown. --]] NexusUnitTesting:RegisterUnitTest("ErrorThrown",function(UnitTest) --Call yxpcall with arguments. local CalledError,CalledStackTrace local Worked = yxpcall(function() error("Test error") end,function(Error,StackTrace) CalledError,CalledStackTrace = Error,StackTrace end) --Assert the results are correct. UnitTest:AssertFalse(Worked,"Worked result is incorrect.") UnitTest:AssertNotNil(string.find(CalledError,"Test error"),"Error message doesn't contain the thrown error.") UnitTest:AssertNotNil(string.find(CalledStackTrace,"yxpcallTests"),"Error stack trace doesn't contain the script.") end) --[[ Tests an 2 errors being thrown concurrently. --]] NexusUnitTesting:RegisterUnitTest("ConcurrentErrorThrown",function(UnitTest) --Call yxpcall with arguments. local Worked1,Worked2 local CalledError1,CalledStackTrace1 local CalledError2,CalledStackTrace2 spawn(function() Worked1 = yxpcall(function() wait(0.1) error("Test error 1") end,function(Error,StackTrace) CalledError1,CalledStackTrace1 = Error,StackTrace end) end) spawn(function() Worked2 = yxpcall(function() wait(0.1) error("Test error 2") end,function(Error,StackTrace) CalledError2,CalledStackTrace2 = Error,StackTrace end) end) --Assert the results are correct. wait(0.2) UnitTest:AssertFalse(Worked1,"Worked result is incorrect.") UnitTest:AssertFalse(Worked2,"Worked result is incorrect.") UnitTest:AssertNotNil(string.find(CalledError1,"Test error 1"),"Error message doesn't contain the thrown error.") UnitTest:AssertNotNil(string.find(CalledStackTrace1,"yxpcallTests"),"Error stack trace doesn't contain the script.") UnitTest:AssertNotNil(string.find(CalledError2,"Test error 2"),"Error message doesn't contain the thrown error.") UnitTest:AssertNotNil(string.find(CalledStackTrace2,"yxpcallTests"),"Error stack trace doesn't contain the script.") end) --[[ Tests a stack overflow error being thrown. --]] --[[ --Test is disabled for performance reasons NexusUnitTesting:RegisterUnitTest("StackOverflow",function(UnitTest) --Method that throws stack overflow. local function StackOverflow() StackOverflow() end --Call yxpcall with arguments. local CalledError,CalledStackTrace local Worked = yxpcall(function() StackOverflow() end,function(Error,StackTrace) CalledError,CalledStackTrace = Error,StackTrace end) --Assert the results are correct. UnitTest:AssertFalse(Worked,"Worked result is incorrect.") UnitTest:AssertNotNil(string.find(CalledError,"stack overflow"),"Error message doesn't contain stack overflow.") UnitTest:AssertNotNil(string.find(CalledStackTrace,"yxpcallTests"),"Error stack trace doesn't contain the script.") UnitTest:AssertNotNil(string.find(CalledStackTrace,"StackOverflow"),"Error stack trace doesn't contain the function name.") UnitTest:AssertTrue(#CalledStackTrace > 50000,"Stack trace isn't \"long\" ("..tostring(#CalledStackTrace).." < 50000 characters).") end) ]] return true
module_version("java/1.8.0-A","1.8")
ESX = nil local CopsConnected = 0 TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterServerEvent('force_transportrobberyReward') AddEventHandler('force_transportrobberyReward', function() local player = ESX.GetPlayerFromId(source) local money = math.random(Config.MoneyRewardMin, Config.MoneyReward) player.addMoney(money) TriggerClientEvent('esx:showNotification', source, 'You got ' .. money .. '$ in reward, get yourself new from here before the cop comes!') end) function CountCops() local players = ESX.GetPlayers() CopsConnected = 0 for i=1, #players, 1 do local xPlayer = ESX.GetPlayerFromId(players[i]) if xPlayer.job.name == 'police' then CopsConnected = CopsConnected + 1 end end SetTimeout(120 * 1000, CountCops) end CountCops() ESX.RegisterServerCallback('force_robberyrobberyCops', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) cb(CopsConnected) end) RegisterServerEvent('force_transportrobberyAlertPolice') AddEventHandler('force_transportrobberyAlertPolice', function() local player = ESX.GetPlayerFromId(source) local players = ESX.GetPlayers() for i=1, #players, 1 do local player = ESX.GetPlayerFromId(players[i]) if player.job.name == 'police' then TriggerClientEvent('esx:showNotification', players[i], 'Alarm: A cash-in-transit robbery is ongoing, check GPS for position!') TriggerClientEvent('force_transportrobberySetBlip', players[i]) end end end)
table_Months = {EVT_JAN, EVT_FEB, EVT_MAR, EVT_APR, EVT_MAY, EVT_JUN, EVT_JUL, EVT_AUG, EVT_SEP, EVT_OCT, EVT_NOV, EVT_DEC}; table_Dotw = {EVT_SUN, EVT_MON, EVT_TUE, EVT_WED, EVT_THU, EVT_FRI, EVT_SAT}; local epochYear = 2016; local epochMonth = 1; --whichever month your epoch is local epochDay = 5; --whichever day your epoch is function currentDay() return date("%d") + 0 end function currentMonth() return date("%m") + 0 end function currentYear() return date("%Y") + 0 end function isLeapYear(year) local naiveLeap = (mod(year, 4) == 0); local centuryClause = (mod(year, 100) ~= 0); local centuryClauseException = (mod(year, 400) == 0); return naiveLeap and (centuryClause or centuryException); end function DaysInMonth(year, month) if ((month == 2) and isLeapYear(year)) then return 29; end local daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; return daysPerMonth[month] end --[[ implementation found online. see https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Implementation-dependent_methods works for any year above 1752 --]] function GetDayofWeek(year, month, day) local t = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; if month < 3 then year = year - 1; end return mod(year + floor(year/4) - floor(year/100) + floor(year/400) + t[month] + day, 7) + 1; end -----------------Communications Functions------------------ --addon message handler functions, function EVTIncMessage(msgStr, fromWho, channel) if fromWho ~= UnitName("player") then local s1, s2, s3, s4 = strSplit(msgStr, "¿"); --from, toOff, header, msg local b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12 = strSplit(s4, "¡"); --varies per message, each segment separated by ¡ symbol if (((tonumber(s2) == 1) and player_Info["officer"]) or (tonumber(s2) == 0)) and (s1 == UnitName("player") or s1 == "All ") and (s3 == "Invite") then --if message has invite header, parse and add to invite queue if TableIndexExists(CalendarData, b12) == false then if CalendarOptions["acceptEvents"] then StringToTable(s4); else table.insert(invite_Queue, {fromWho, s4}); EVTButton_StartPulse(); end DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] "..fromWho.." has invited you to an event!", 0.1, 1, 0.1); elseif TableFindDupe(CalendarData[b12], b1) == false then if CalendarOptions["acceptEvents"] then StringToTable(s4); else table.insert(invite_Queue, {fromWho, s4}); EVTButton_StartPulse(); end DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] "..fromWho.." has invited you to an event!", 0.1, 1, 0.1); end end if s3 == "VersionCheck" then if tonumber(s4) > tonumber(EVT_VERSION) then DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] Your version of EVTCalendar is out of date! Please download the newest version at: https://github.com/TheOneReed/EVTCalendar", 0.1, 1, 0.1); PlaySoundFile("Sound\\interface\\iTellMessage.wav"); end end if s1 == UnitName("player") and s3 == "ConfirmEvent" then DEFAULT_CHAT_FRAME:AddMessage("[EVTCalendar] "..fromWho.." has signed up for "..b2.." on "..convertDate(b1)..".", 0.1, 1, 0.1); local t = { [1] = fromWho, [2] = b3, [3] = b4, [4] = b5, [5] = (table.getn(CalendarData[b1][TableFindIndex(CalendarData[b1], b2)][12]) + 1), [6] = "10", [7] = b6, [8] = b7 }; table.insert(CalendarData[b1][TableFindIndex(CalendarData[b1], b2)][12], t); EVT_UpdateConfirmedScrollBar(); PlaySoundFile("Sound\\interface\\iTellMessage.wav"); local rtnMsgStr = string.format("%s¿%s¿%s¿%s¿", fromWho, 0, "ConfirmAck", s4); SendAddonMessage("EVTCalendar", rtnMsgStr, channel); end if s1 == UnitName("player") and s3 == "ConfirmAck" then CalendarData[b1][TableFindIndex(CalendarData[b1], b2)][13] = 1; if selectedButton ~= nil then EVT_UpdateDetailList(); end end end end ------- Helper Functions---------- function TableIndexExists(t, i) --does table t contain index i for index,value in pairs(t) do if (index == i) then return true; end end return false; end function TableFindIndex(t, name) --returns index i of associated name local n = table.getn(t); for i = 1, n do getName = t[i][1]; if ( getName == name) then return i; end end return false; end function TableFindDupe(t, name) -- checks if table t contains duplicate entry to name local n = table.getn(t); for i = 1, n do getName = t[i][1]; if ( getName == name) then return true; end end return false; end function EVT_TableSort(t, index, critReverse) local t2 = {}; table.insert(t2, t[1]); table.remove(t, 1); local tSize = table.getn(t); if tSize > 0 then for x = 1, tSize do local t2Size = table.getn(t2); for y = 1, t2Size do if y < t2Size then if critReverse then if (t[1][index] >= t2[y][index]) then table.insert(t2, y, t[1]); table.remove(t, 1); break; elseif (t[1][index] < t2[y][index]) and (t[1][index] >= t2[(y + 1)][index]) then table.insert(t2, (y + 1), t[1]); table.remove(t, 1); break; end else if (t[1][index] <= t2[y][index]) then table.insert(t2, y, t[1]); table.remove(t, 1); break; elseif (t[1][index] > t2[y][index]) and (t[1][index] <= t2[(y + 1)][index]) then table.insert(t2, (y + 1), t[1]); table.remove(t, 1); break; end end elseif y == t2Size then if critReverse then if t[1][index] > t2[y][index] then table.insert(t2, y, t[1]); table.remove(t, 1); else table.insert(t2, t[1]); table.remove(t, 1); end else if t[1][index] < t2[y][index] then table.insert(t2, y, t[1]); table.remove(t, 1); else table.insert(t2, t[1]); table.remove(t, 1); end end end end end end return t2; end function strSplit(msgStr, c) -- separate a string msgStr based on a seperator character c local table_str = {}; local capture = string.format("(.-)%s", c); for v in string.gfind(msgStr, capture) do table.insert(table_str, v); end return unpack(table_str); --returns all table elements as arguments end function TableToString(t, lock) -- builds a string from a table for transfer via addon message strTable = string.format("%s¡%s¡%s¡%s¡%s¡%s¡%s¡%s¡%s¡%s¡%s¡%s¡", t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], lock, createDate); return strTable; end function StringToTable(str) --builds a table from a string recieved from an addon message local s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12 = strSplit(str, "¡"); local t = CalendarData; if TableIndexExists(t, s12) == false then t[s12] = {}; end if TableFindDupe(t[s12], s1) == false then table.insert( t[s12], {s1, s2, tonumber(s3), tonumber(s4), tonumber(s5), tonumber(s6), tonumber(s7), tonumber(s8), tonumber(s9), s10, tonumber(s11), nil, 0}); EVT_UpdateCalendar(); else DEFAULT_CHAT_FRAME:AddMessage("Duplicate Exists!", 1, 0.1, 1); end if CalendarOptions["confirmEvents"] then EVT_EventConfirm(s12, s1, s2); end end function checkIllegal(str) --SANITIZE YOUR CODE TO PREVENT UNINTENDED OPERATION str = string.gsub(str, "¿", "?"); str = string.gsub(str, "¡", "!"); return str; end function EVT_CopyTable(t) -- duplicates a table t local new = {}; local index, value = next(t, nil); while index do if type(value)=="table" then value=EVT_CopyTable(value); end new[index] = value; index, value = next(t, index); end return new; end
local ADDONNAME, ns = ... ns.ARDENWEALD_UIMAPID = 1565 ns.TREASURES = { -- Ardenweald: Lunarpods LARGE = "large", DREAMSHRINE = "Dreamshrine", GLITTERFALL_HEIGHTS_EAST = "Glitterfall Heights (East)", GLITTERFALL_HEIGHTS_WEST = "Glitterfall Heights (West)", GARDEN_OF_NIGHT = "Garden of Night", EVENTIDE_GROVE = "Eventide Grove", } ns.PODS = { LARGE = "large", DREAMSHRINE = "Dreamshrine", GLITTERFALL_HEIGHTS_EAST = "Glitterfall Heights (East)", GLITTERFALL_HEIGHTS_WEST = "Glitterfall Heights (West)", GARDEN_OF_NIGHT = "Garden of Night", EVENTIDE_GROVE = "Eventide Grove", } ns.TREASURE_MAP = { [ns.TREASURES.LARGE] = ns.ARDENWEALD_UIMAPID, [ns.TREASURES.DREAMSHRINE] = ns.ARDENWEALD_UIMAPID, [ns.TREASURES.GLITTERFALL_HEIGHTS_EAST] = ns.ARDENWEALD_UIMAPID, [ns.TREASURES.GLITTERFALL_HEIGHTS_WEST] = ns.ARDENWEALD_UIMAPID, [ns.TREASURES.GARDEN_OF_NIGHT] = ns.ARDENWEALD_UIMAPID, [ns.TREASURES.EVENTIDE_GROVE] = ns.ARDENWEALD_UIMAPID, } local ARDENWEALD_ICON do local ICON_PATH = "Interface/AddOns/" .. ADDONNAME .. "/icons/minimap_icon_ardenweald.blp" ARDENWEALD_ICON = GetFileIDFromPath(ICON_PATH) or ICON_PATH end ns.TREASURE_ICON = { [ns.TREASURES.LARGE] = ARDENWEALD_ICON, [ns.TREASURES.DREAMSHRINE] = ARDENWEALD_ICON, [ns.TREASURES.GLITTERFALL_HEIGHTS_EAST] = ARDENWEALD_ICON, [ns.TREASURES.GLITTERFALL_HEIGHTS_WEST] = ARDENWEALD_ICON, [ns.TREASURES.GARDEN_OF_NIGHT] = ARDENWEALD_ICON, [ns.TREASURES.EVENTIDE_GROVE] = ARDENWEALD_ICON, } ns.TREASURE_DATA = {} ns.POD_DATA = {} ns.ACTIVE_TREASURES = { -- Ardenweald: Lunarpods ["356821"] = ns.TREASURES.LARGE, ["353769"] = ns.TREASURES.EVENTIDE_GROVE, ["353770"] = ns.TREASURES.GARDEN_OF_NIGHT, ["353771"] = ns.TREASURES.GLITTERFALL_HEIGHTS_WEST, ["353772"] = ns.TREASURES.GLITTERFALL_HEIGHTS_EAST, ["353773"] = ns.TREASURES.DREAMSHRINE, } ns.ACTIVE_PODS = { -- ["objectID"] = ns.PODS.NAME, ["356821"] = ns.PODS.LARGE, ["353769"] = ns.PODS.EVENTIDE_GROVE, ["353770"] = ns.PODS.GARDEN_OF_NIGHT, ["353771"] = ns.PODS.GLITTERFALL_HEIGHTS_WEST, ["353772"] = ns.PODS.GLITTERFALL_HEIGHTS_EAST, ["353773"] = ns.PODS.DREAMSHRINE, } ns.FINISHED_TREASURES = { -- Ardenweald: Lunarpods ["356820"] = ns.TREASURES.LARGE, ["353681"] = ns.TREASURES.EVENTIDE_GROVE, ["353683"] = ns.TREASURES.GARDEN_OF_NIGHT, ["353684"] = ns.TREASURES.GLITTERFALL_HEIGHTS_WEST, ["353686"] = ns.TREASURES.DREAMSHRINE, ["353685"] = ns.TREASURES.GLITTERFALL_HEIGHTS_EAST, } ns.FINISHED_PODS = { -- ["objectID"] = ns.PODS.NAME, ["356820"] = ns.PODS.LARGE, ["353681"] = ns.PODS.EVENTIDE_GROVE, ["353683"] = ns.PODS.GARDEN_OF_NIGHT, ["353684"] = ns.PODS.GLITTERFALL_HEIGHTS_WEST, ["353686"] = ns.PODS.DREAMSHRINE, ["353685"] = ns.PODS.GLITTERFALL_HEIGHTS_EAST, } local SET = { ONE = "one", TWO = "two", THREE = "three", FOUR = "four", FIVE = "five", } local LARGE_LUNAR_POD_QUEST_SET_POSISTIONS = { [61692] = { [51183249] = SET.ONE, [49943206] = SET.TWO, [50523181] = SET.THREE, [51013227] = SET.FOUR, [50253163] = SET.FIVE, }, [61693] = { [50863301] = SET.ONE, [50323271] = SET.TWO, [50373295] = SET.THREE, [50593357] = SET.FOUR, [50033325] = SET.FIVE, }, [61694] = { [51423329] = SET.ONE, [51883337] = SET.TWO, [51463408] = SET.THREE, [51813383] = SET.FOUR, [51003438] = SET.FIVE, }, [61695] = { [51793235] = SET.ONE, [52003200] = SET.TWO, [51873145] = SET.THREE, [52323168] = SET.FOUR, [51983091] = SET.FIVE, }, [61696] = { [52513374] = SET.ONE, [52903320] = SET.TWO, [52253243] = SET.THREE, [53093299] = SET.FOUR, [52463340] = SET.FIVE, }, } ns.POD_DATA[ns.PODS.LARGE] = LARGE_LUNAR_POD_QUEST_SET_POSISTIONS ns.TREASURE_DATA[ns.PODS.LARGE] = LARGE_LUNAR_POD_QUEST_SET_POSISTIONS -- Dreamshrine Basin local DREAMSHRINE_QUEST_POSITIONS = { [60820] = { [60515642] = SET.ONE, }, [60821] = { [60405734] = SET.ONE, }, [60822] = { [61895684] = SET.ONE, }, [60823] = { [61455626] = SET.ONE, }, [60824] = { [61415754] = SET.ONE, }, } ns.POD_DATA[ns.PODS.DREAMSHRINE] = DREAMSHRINE_QUEST_POSITIONS ns.TREASURE_DATA[ns.PODS.DREAMSHRINE] = DREAMSHRINE_QUEST_POSITIONS -- Glitterfall Heights local GLITTERFALL_HEIGHTS_EAST_QUEST_POSITIONS = { [60815] = { [55683962] = SET.ONE, }, [60816] = { [56043870] = SET.ONE, }, [60817] = { [55283815] = SET.ONE, }, [60818] = { [56143941] = SET.ONE, }, [60819] = { [55173918] = SET.ONE, }, } ns.POD_DATA[ns.PODS.GLITTERFALL_HEIGHTS_EAST] = GLITTERFALL_HEIGHTS_EAST_QUEST_POSITIONS ns.TREASURE_DATA[ns.PODS.GLITTERFALL_HEIGHTS_EAST] = GLITTERFALL_HEIGHTS_EAST_QUEST_POSITIONS local GLITTERFALL_HEIGHTS_WEST_QUEST_POSITIONS = { [60810] = { [48123582] = true, }, [60811] = { [47643433] = true, }, [60812] = { [48283372] = true, }, [60813] = { [48963447] = true, }, [60814] = { [48503463] = true, }, } ns.POD_DATA[ns.PODS.GLITTERFALL_HEIGHTS_WEST] = GLITTERFALL_HEIGHTS_WEST_QUEST_POSITIONS ns.TREASURE_DATA[ns.PODS.GLITTERFALL_HEIGHTS_WEST] = GLITTERFALL_HEIGHTS_WEST_QUEST_POSITIONS local GARDEN_OF_NIGHT_QUEST_POSITIONS = { [60805] = { [39665351] = SET.ONE, }, [60806] = { [38855363] = SET.ONE, }, [60807] = { [39185366] = SET.ONE, }, [60808] = { [39485444] = SET.ONE, }, [60809] = { [38795424] = SET.ONE, }, } ns.POD_DATA[ns.PODS.GARDEN_OF_NIGHT] = GARDEN_OF_NIGHT_QUEST_POSITIONS ns.TREASURE_DATA[ns.PODS.GARDEN_OF_NIGHT] = GARDEN_OF_NIGHT_QUEST_POSITIONS -- Eventide Grove local EVENTIDE_GROVE_QUEST_POSITIONS = { [60800] = { [47787097] = SET.ONE, }, [60801] = { [48307120] = SET.ONE, }, [60802] = { [48307152] = SET.ONE, }, [60803] = { [48027019] = SET.ONE, }, [60804] = { [48396998] = SET.ONE, }, } ns.POD_DATA[ns.PODS.EVENTIDE_GROVE] = EVENTIDE_GROVE_QUEST_POSITIONS ns.TREASURE_DATA[ns.PODS.EVENTIDE_GROVE] = EVENTIDE_GROVE_QUEST_POSITIONS
-- Import this library local g = require("gachLib") -------------------------------------------------------------------------------- -- Create new application local application = g.gui.application() local label = g.gui.label(10,10,20,20,"TEST") application:addChild(label) application:start()
--[[-------------------------------------------------------------------]]--[[ Copyright wiltOS Technologies LLC, 2020 Contact: www.wiltostech.com ----------------------------------------]]-- wOS = wOS or {} wOS.ALCS = wOS.ALCS or {} wOS.ALCS.Config = wOS.ALCS.Config or {} wOS.ALCS.Config.ExecSys = wOS.ALCS.Config.ExecSys or {} /* Should all kills made by a lightsaber perform the SLICING animation? WARNING: THIS SHIT IS BAD ASS, BUT IT MAY DROP PERFORMANCE DUE TO THE GORE. YOU HAVE BEEN WARNED */ wOS.ALCS.Config.ExecSys.AlwaysSlice = false /* Should we perform the players execution ( IF AVAILABLE ) on killing blows instead of just killing them? Ruins combat flow but once again: bad ass */ wOS.ALCS.Config.ExecSys.FinalBlowExecutions = false
-- -- tests/test_keywords.lua -- Automated test suite for configuration block keyword filtering. -- Copyright (c) 2008, 2009 Jason Perkins and the Premake project -- T.keywords = { } local suite = T.keywords -- -- Keyword escaping tests -- function suite.escapes_special_chars() test.isequal("%.%-", path.wildcards(".-")) end function suite.escapes_star() test.isequal("vs[^/]*", path.wildcards("vs*")) end function suite.escapes_star_star() test.isequal("Images/.*%.bmp", path.wildcards("Images/**.bmp")) end -- -- Keyword matching tests -- function T.keywords.matches_simple_strings() test.istrue(premake.iskeywordmatch("debug", { "debug", "windows", "vs2005" })) end function T.keywords.match_files_with_simple_strings() test.isfalse(premake.iskeywordmatch("release", { "debug", "windows", "vs2005" })) end function T.keywords.matches_with_patterns() test.istrue(premake.iskeywordmatch("vs20.*", { "debug", "windows", "vs2005" })) end function T.keywords.match_fails_with_not_term() test.isfalse(premake.iskeywordmatch("not windows", { "debug", "windows", "vs2005" })) end function T.keywords.match_ok_with_not_term() test.istrue(premake.iskeywordmatch("not linux", { "debug", "windows", "vs2005" })) end function T.keywords.match_ok_with_first_or() test.istrue(premake.iskeywordmatch("windows or linux", { "debug", "windows", "vs2005" })) end function T.keywords.match_ok_with_first_or() test.istrue(premake.iskeywordmatch("windows or linux", { "debug", "linux", "vs2005" })) end function T.keywords.match_ok_with_not_and_or() test.istrue(premake.iskeywordmatch("not macosx or linux", { "debug", "windows", "vs2005" })) end function T.keywords.match_fail_with_not_and_or() test.isfalse(premake.iskeywordmatch("not macosx or windows", { "debug", "windows", "vs2005" })) end function T.keywords.match_ok_required_term() test.istrue(premake.iskeywordsmatch({ "debug", "hello.c" }, { "debug", "windows", "vs2005", required="hello.c" })) end function T.keywords.match_fail_required_term() test.isfalse(premake.iskeywordsmatch({ "debug" }, { "debug", "windows", "vs2005", required="hello.c" })) end
--[[ name : biginfo.lua version: 1.0 description: useful information updated every day. Return: create global variables (variables named BI_*) Based on today's date and longitude/latitude recorded in Domoticz $BI_ISHOLIDAYS ==> true/false $BI_GEOLATITUDE ==> number $BI_HOLIDAYS ==> text (for country code = fr) $BI_SCHOOLZONE ==> text (for country code = fr) $BI_ISWE ==> true/false $BI_ISLEAPYEAR ==> true/false $BI_GEOLONGITUDE ==> number $BI_GEOMUNICIPALITY ==> text $BI_GEOCOUNTRY ==> text $BI_GEONAME ==> text $BI_ISPUBHOLIDAYS ==> true/false (for country code = fr) $BI_GEONUMDEPT ==> number $BI_JULIANDATE ==> number $BI_MOONAGE ==> number $BI_GEOCOUNTRYCODE ==> text $BI_MOON ==> text $BI_GEOPOSTCODE ==> number $BI_GEOSTATE ==> text $BI_SEASON ==> text $BI_PUBHOLIDAYS ==> text (for country code = fr) $BI_GEOCOUNTY ==> text $BI_SCHOOLYEAR ==> text (for country code = fr) author : casanoe creation : 16/04/2021 update : 05/05/2021 --]] -- Script description local scriptName = 'biginfo' local scriptVersion = '1.0' -- Dzvents return { on = { customEvents = { 'onstart_dzBasic', 'biginfo' }, timer = { '00:01' }, }, logging = { -- level = domoticz.LOG_DEBUG, -- level = domoticz.LOG_INFO, -- level = domoticz.LOG_ERROR, -- level = domoticz.LOG_MODULE_EXEC_INFO, marker = scriptName..' v'..scriptVersion }, execute = function(dz, triggeredItem, info) dz.helpers.load_dzBasicLibs(dz) local dayOfYear, year, month, day, geo, TIMEOUT, context local args = {} if triggeredItem.trigger == 'biginfo' then context = dzBasicCall_getData('biginfo') args = context['args'] TIMEOUT = 60 * 60 geo = geoLoc(args['addr'], args['lat'], args['lon']) else geo = geoLoc() end year = args['year'] or tonumber(os.date("%Y")) month = args['month'] or tonumber(os.date("%m")) day = args['day'] or tonumber(os.date("%d")) dayOfYear = tonumber(os.date("%j", os.time{year = year, month = month, day = day})) ---------------------- DZ_LANG = DZ_LANG or geo['address']['country_code'] or 'fr' local lang = DZ_LANG local countrycode = geo['address']['country_code'] local isLeapYear = function(y) if ( y % 4 == 0) then if (y % 100 == 0)then if ( y % 400 == 0) then return true end else return true end end return false end local season = function(d, m, y) local s = { fr = { 'Eté', 'Printemps', 'Automne', 'Hiver' }, en = {'Summer', 'Spring', 'Autumn', 'Winter'} } local dy = tonumber(os.date("%j", os.time{year = y, month = m, day = d})) local ly = isLeapYear(y) and 1 or 0 return (dy > 354 + ly or dy < 80 + ly) and s[lang][4] or (dy >= 80 + ly and dy <= 171 + ly) and s[lang][2] or (dy >= 172 + ly and dy <= 263 + ly) and s[lang][1] or (dy >= 264 + ly and dy <= 354 + ly) and s[lang][3] end local julianDate = function(d, m, y) local mm, yy, k1, k2, k3, j yy = y - math.floor((12 - m) / 10) mm = m + 9 if (mm >= 12) then mm = mm - 12 end k1 = math.floor(365.25 * (yy + 4712)) k2 = math.floor(30.6001 * mm + 0.5) k3 = math.floor(math.floor((yy / 100) + 49) * 0.75) - 38 j = k1 + k2 + d + 59 if (j > 2299160) then j = j - k3 end return j end local moonAge = function(d, m, y) local j, ip, ag j = julianDate(d, m, y) ip = (j + 4.867) / 29.53059 ip = ip - math.floor(ip) if (ip < 0.5) then ag = ip * 29.53059 + 29.53059 / 2 else ag = ip * 29.53059 - 29.53059 / 2 end return ag end local theMoon = function(d, m, y) local mo = { fr = { 'Dernier croissant', 'Dernier quartier', 'Gibbeuse décroisssante', 'Pleine lune', 'Gibbeuse croissante', 'Premier quartier', 'Premier croissant'}, en = {'Waning crescent', 'Third quarter', 'Waning gibbous', 'Full moon', 'Waxing gibbous', 'First quarter', 'Waxing crescent'} } local a = moonAge(d, m, y) return a > 23 and mo[lang][1] or a > 22 and mo[lang][2] or a > 15 and mo[lang][3] or a > 13 and mo[lang][4] or a > 8 and mo[lang][5] or a > 6 and mo[lang][6] or a > 1 and mo[lang][7] end local easterDate = function(y) local a = math.floor(y / 100) local b = math.fmod(y, 100) local c = math.floor((3 * (a + 25)) / 4) local d = math.fmod((3 * (a + 25)), 4) local e = math.floor((8 * (a + 11)) / 25) local f = math.fmod((5 * a + b), 19) local g = math.fmod((19 * f + c - e), 30) local h = math.floor((f + 11 * g) / 319) local j = math.floor((60 * (5 - d) + b) / 4) local k = math.fmod((60 * (5 - d) + b), 4) local m = math.fmod((2 * j - k-g + h), 7) local n = math.floor((g - h + m + 114) / 31) local p = math.fmod((g - h + m + 114), 31) local day = p + 1 local month = n return os.time{year = year, month = month, day = day, hour = 12, min = 0} end local globals = { BI_ISWE = os.date('%w') == '6' or os.date('%w') == '0', BI_ISLEAPYEAR = isLeapYear(year), BI_JULIANDATE = julianDate(day, month, year), BI_SEASON = season(day, month, year), BI_MOON = theMoon(day, month, year), BI_MOONAGE = moonAge(day, month, year), BI_GEOLATITUDE = geo['lat'], BI_GEOLONGITUDE = geo['lon'], BI_GEOCOUNTRY = geo['address']['country'], BI_GEOCOUNTY = geo['address']['county'], -- fr: departement BI_GEONAME = geo['name'], BI_GEOSTATE = geo['address']['state'], -- fr: region BI_GEOPOSTCODE = geo['address']['postcode'], BI_GEOCOUNTRYCODE = geo['address']['country_code'], BI_GEOMUNICIPALITY = geo['address']['municipality'] } ---- FRANCE if countrycode == 'fr' then local pubHolidays = function(d, m, y) local today = tostring(d)..'-'..tostring(m) local epochPaques = easterDate(y) local ph = { ['Vendredi Saint'] = os.date("%d-%m", epochPaques - 172800), ['Pâques'] = os.date("%d-%m", epochPaques + 86400), ['Ascension'] = os.date("%d-%m", epochPaques + 3369600), ['Pentecôte'] = os.date("%d-%m", epochPaques + 4233600), ['Nouvel an'] = '1-1', ['Fête du travail'] = '1-5', ['Fin de la 2nde Guerre'] = '8-5', ['Fête nationale'] = '14-7', ['Assomption'] = '15-8', ['Toussaint'] = '1-11', ['Armistice 1918'] = '11-11', ['Noël'] = '25-12' } for k, v in pairs(ph) do if today == v then return true, k end end return false, '' end local getSchoolZone = function(dc) local schoolZone = { A = {"1", "3", "7", "15", "16", "17", "19", "21", "23", "24", "25", "26", "33", "38", "39", "40", "42", "43", "47", "58", "63", "64", "69D", "69M", "70", "71", "73", "74", "79", "86", "87", "89", "90"}, B = {"2", "4", "5", "6", "8", "10", "13", "14", "18", "22", "27", "28", "29", "35", "36", "37", "41", "44", "45", "49", "50", "51", "52", "53", "54", "55", "56", "57", "59", "60", "61", "62", "67", "68", "72", "76", "80", "83", "84", "85", "88"}, C = {"11", "12", "30", "31", "32", "34", "46", "48", "65", "66", "75", "77", "78", "81", "82", "91", "92", "93", "94", "95"}, Corse = {}, -- TODO Outremer = {} -- TODO } for k, v in pairs(schoolZone) do for _, x in pairs(v) do if dc == x then return k end end end return '?' end local getHolidays = function(d, m, y, z) local u = simpleCurl(string.format('"http://domogeek.entropialux.com/schoolholiday/%s/%0.2d-%0.2d-%d"', z, d, m, y)) return u ~= 'False', u end globals['BI_GEONUMDEPT'] = string.sub(globals['BI_GEOPOSTCODE'] or '', 1, 2) globals['BI_SCHOOLZONE'] = getSchoolZone(globals['BI_GEONUMDEPT']) globals['BI_SCHOOLYEAR'] = dayOfYear > 244 and (year..'-'..(year + 1)) or ((year - 1)..'-'..year) globals['BI_ISPUBHOLIDAYS'], globals['BI_PUBHOLIDAYS'] = pubHolidays(day, month, year) globals['BI_ISHOLIDAYS'], globals['BI_HOLIDAYS'] = getHolidays(day, month, year, globals['BI_SCHOOLZONE']) end ---- if triggeredItem.trigger == 'biginfo' then dzBasicCall_return('biginfo', globals, TIMEOUT) else for k, v in pairs(globals) do set_globalvars(k, v) end end end }
-- -- (C) 2019 Kriss@XIXs.com -- local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require local wstring=require("wetgenes.string") local wutf=require("wetgenes.txt.utf") local wtxtundo=require("wetgenes.txt.undo") local wtxtdiff=require("wetgenes.txt.diff") local wtxtlex =require("wetgenes.txt.lex") local wpath=require("wetgenes.path") -- manage the text data part of a text editor --module local M={ modname=(...) } ; package.loaded[M.modname]=M M.construct=function(txt) txt = txt or {} txt.lexer="text" txt.tabsize=4 txt.hooks={} -- user call backs local hook=function(name) local f=txt.hooks[name] if f then return f(txt) end end txt.strings={} -- a table of strings per line inclusive of any \n at the end txt.cx=1 -- cursor location txt.cy=1 txt.hx=0 -- widest string txt.hy=0 -- number of strings txt.get_string=function(idx) return txt.strings[idx] end -- code based string sub txt.get_string_sub=function(idx,i,j) local cache=txt.get_cache(idx) if not cache then return "" end i=i or 1 j=j or -1 local l=#cache.codes -- length of codes if i<0 then i=l+i end -- deal with negative values if j<0 then j=l+1+j end if i<1 then i=1 end -- clamp values if j<0 then j=0 end if i>l then i=l end if j>l then j=l end if j==0 then return "" end i=cache.cb[i] or 0 -- convert to byte offset j=(cache.cb[j+1] or 1)-1 return cache.string:sub(i,j) -- finally return string end txt.set_string=function(idx,str) txt.strings[idx]=str txt.clear_caches() end txt.add_string=function(idx,str) table.insert( txt.strings , idx , str) txt.hy=txt.hy+1 txt.clear_caches() end txt.del_string=function(idx) table.remove( txt.strings , idx ) txt.hy=txt.hy-1 txt.clear_caches() end txt.del_cache=function(idx) txt.caches[idx]=nil end txt.get_cache=function(idx) local cache=txt.caches[idx] if cache then return cache end cache=txt.build_cache(idx) txt.caches[idx]=cache if (idx-1)%txt.permacache_ratio == 0 then txt.permacaches[1+math.floor((idx-1)/txt.permacache_ratio)]=cache -- do not forget every X caches end return cache end -- just one meta for the caches txt.caches_meta={} txt.caches_meta.__mode="v" txt.permacache_ratio=128 txt.clear_caches=function() txt.permacaches={} txt.caches={} setmetatable(txt.caches, txt.caches_meta) txt.permastart={} -- recalculate start indexs of each perma string local start=0 for i,v in ipairs(txt.strings or {} ) do if (i-1)%txt.permacache_ratio == 0 then -- a perma string so remember start txt.permastart[1+math.floor((i-1)/txt.permacache_ratio)]=start end start=start+#v -- next index end txt.permastart[#txt.permastart+1]=start -- end of text end txt.clear_caches() --[[ Find byte offset into the text from a given line and character. ]] txt.location_to_ptr=function(y,x) local cache=txt.get_cache(y) local ptr=cache.cb[x] or 0 -- convert to byte offset ptr=cache.start+ptr-1 return ptr end --[[ Find the line number and column number of the given byte offset into the text. ]] txt.ptr_to_location=function(ptr) local mh=#txt.permastart local c=math.ceil(mh/2) local y=1 repeat local a=txt.permastart[y] local b=txt.permastart[y+1] or a if not a or not b then y=nil break end -- failed if a>ptr then y=y-c elseif b<ptr then y=y+c end if y<1 then y=1 end -- clamp if y>mh-1 then y=mh-1 end c=math.ceil(c/2) -- half the jump until a<=ptr and b>ptr -- in range if not y then return end -- failed to find line local a=txt.permastart[y] y=1+(y-1)*txt.permacache_ratio -- y back into full range local b=a+#txt.strings[y] while b<=ptr do -- step forward y=y+1 local s=txt.strings[y] if not s then break end -- fail a=b b=a+#s end if a<=ptr and b>ptr then local cache=txt.get_cache(y) local x=cache.bc[1+ptr-a] or #cache.string+1 return y,x -- found line end end --[[ Fill the editor up with text, the filename is used to set the lexer used for highlighting ]] txt.set_text=function(text,filename) if text then -- set new text txt.strings=wstring.split_lines(text) txt.clear_caches() txt.hx=0 txt.hy=#txt.strings for i,v in ipairs(txt.strings) do local cache=txt.get_cache(i) local lv=#cache.codes -- wutf.length(v) if lv > txt.hx then txt.hx=lv end end if filename then -- set new filename ( can help us guess the format ) txt.filename=filename end hook("changed") end end txt.append_text=function(text) txt.clip(txt.hy+1,0) txt.insert(text) end txt.get_text=function() return table.concat(txt.strings) or "" end --[[ mostly this deals with the visible width of a character, eg tab, compared to its byte width, but it is also necessary for utf8 encoding or japanese double glyphs. Its a complicated mapping so it is precalculated ]] txt.build_cache=function(idx) local s=txt.get_string(idx) if not s then return nil end local cache={} cache.string=s local perma=math.floor((idx-1)/txt.permacache_ratio) cache.start=txt.permastart[1+perma] -- get start from sparse array perma=1+(perma*txt.permacache_ratio) -- find start for this chunk while perma<idx do -- find precise start cache.start=cache.start+#txt.strings[perma] perma=perma+1 end cache.codes={} -- x xpos is the screen space offset, so a tab would be 8 and a space 1. -- b byte is the byte offset into the string -- c code is the code offset into the string (unicode character) -- these arrays map one space to another cache.bx={} -- map byte to xpos cache.bc={} -- map byte to code cache.xb={} -- map xpos to byte cache.xc={} -- map xpos to code cache.cx={} -- map code to xpos cache.cb={} -- map code to byte local b=1 local x=0 local c=1 for char in s:gmatch(wutf.charpattern) do local code=wutf.code(char) local size=#char local width=1 cache.codes[c]=code if code==9 then --tab width=math.ceil((x+1)/txt.tabsize)*txt.tabsize-x end cache.cb[c]=b cache.cx[c]=x for i=0,width-1 do cache.xb[x+i]=b cache.xc[x+i]=c end for i=0,size-1 do cache.bx[b+i]=x cache.bc[b+i]=c end c=c+1 x=x+width b=b+size cache.cb[c]=b cache.cx[c]=x end return cache end --[[ auto select an entire word or line depending on number of clicks ]] txt.markauto=function(fy,fx,clicks) txt.mark(fy,fx,fy,fx) local s=txt.get_string(txt.cy) or "" if clicks==2 then -- select word local sl=wutf.length(s) local lx=txt.cx-1 local hx=txt.cx-1 local c = wutf.ncode( s , lx ) if c and c > 32 then -- solid while ( (wutf.ncode( s , lx-1 ) or 0) > 32 ) do lx=lx-1 end while ( (wutf.ncode( s , hx+1 ) or 0) > 32 ) do hx=hx+1 end txt.mark(fy,lx,fy,hx+1) elseif c and c <= 32 then -- White while ( (wutf.ncode( s , lx-1 ) or 33) <= 32 ) do lx=lx-1 end while ( (wutf.ncode( s , hx+1 ) or 33) <= 32 ) do hx=hx+1 end txt.mark(fy,lx,fy,hx+1) end elseif clicks>=3 then -- select line txt.mark(fy,0,fy+1,0) end end --[[ get current selected area / cursor position ]] txt.markget=function() return txt.fy,txt.fx,txt.ty,txt.tx end --[[ are one or more glyphs currently selected, returns true or false ]] txt.marked=function() if txt.fy and txt.fx and txt.ty and txt.tx then if txt.fy==txt.ty and txt.fx==txt.tx then return false end return true end return false end --[[ merge two marked areas into one ]] txt.markmerge=function( fya,fxa,tya,txa, fyb,fxb,tyb,txb ) if not fxa and fxb then return txt.mark(fyb,fxb,tyb,txb) end -- nothing to merge if not fxb and fxa then return txt.mark(fya,fxa,tya,txa) end -- nothing to merge if not fxb and not fxa then return end -- nothing to do local fx,fy,tx,ty if fya < fyb then fy=fya fx=fxa elseif fya > fyb then fy=fyb fx=fxb else if fxa < fxb then fy=fya fx=fxa else fy=fyb fx=fxb end end if tya > tyb then ty=tya tx=txa elseif tya < tyb then ty=tyb tx=txb else if txa > txb then ty=tya tx=txa else ty=tyb tx=txb end end txt.mark(fy,fx,ty,tx) end --[[ mark or unmark an area ]] txt.mark=function(fy,fx,ty,tx) if not fx then -- unmark txt.fx=nil txt.fy=nil txt.tx=nil txt.ty=nil return end txt.fy,txt.fx=txt.clip(fy,fx) txt.ty,txt.tx=txt.clip(ty,tx) txt.cy,txt.cx=txt.ty,txt.tx local flip=false if txt.fy==txt.ty and txt.fx>txt.tx then flip=true elseif txt.fy>txt.ty then flip=true end if flip then txt.fx,txt.tx=txt.tx,txt.fx txt.fy,txt.ty=txt.ty,txt.fy end end --[[ get fy,fx,ty,tx range given a start and a glyph offset ( probably +1 or -1 ) ]] txt.rangeget=function(fy,fx,length) local tx=fx local ty=fy if length<0 then -- backward search local cache=txt.get_cache(fy) while length<0 do if fx <= -length then -- full line length=length+1+fx fy=fy-1 cache=txt.get_cache(fy) if not cache then return fy+1,fx,ty,tx end -- start of file fx=#cache.codes -- end of line else -- partial line fx=fx+length length=0 end end elseif length>0 then -- forward search local cache=txt.get_cache(ty) while length>0 and cache do if ( #cache.codes - tx ) < length then -- full line length=length-( #cache.codes + 1 - tx ) -- include line end ty=ty+1 cache=txt.get_cache(ty) if not cache then return fy,fx,ty-1,tx end -- end of file tx=1 -- start of line else -- partial line tx=tx+length length=0 end end end return fy,fx,ty,tx end --[[ cut out the text in the marked area (if marked) and set the cursor to this location ]] txt.cut=function(fy,fx,ty,tx) local setcursor=not fx fx=fx or txt.fx fy=fy or txt.fy tx=tx or txt.tx ty=ty or txt.ty if fx and fy then local s="" if tx and ty then for idx=fy,ty do if idx==fy then -- first line if ty==fy then -- single line -- local sa=txt.get_string(fy) or "" local sb=txt.get_string_sub(fy,1,fx-1) local sc=txt.get_string_sub(fy,fx,tx-1) local sd=txt.get_string_sub(fy,tx) s=s..sc txt.set_string(fy,sb..sd) else -- multiple lines -- local sa=txt.get_string(fy) or "" local sb=txt.get_string_sub(fy,1,fx-1) local sc=txt.get_string_sub(fy,fx) s=s..sc txt.set_string(fy,sb) end elseif idx==ty then -- last line -- local sa=txt.get_string(fy+1) or "" local sb=txt.get_string_sub(fy+1,1,tx-1) local sc=txt.get_string_sub(fy+1,tx) s=s..sb txt.set_string(fy+1,sc) local sa=txt.get_string(fy) or "" local sb=txt.get_string(fy+1) or "" txt.set_string(fy,sa..sb) txt.del_string(fy+1) else -- middle line local sa=txt.get_string(fy+1) or "" s=s..sa txt.del_string(fy+1) end end end if setcursor then txt.cx=txt.fx txt.cy=txt.fy txt.tx=txt.fx txt.ty=txt.fy txt.mark() end if s=="" then s=nil end return s end end --[[ copy text from the marked area (if marked) or return nil ]] txt.copy=function(fy,fx,ty,tx) fx=fx or txt.fx fy=fy or txt.fy tx=tx or txt.tx ty=ty or txt.ty if fx and fy then local s="" if tx and ty then for idx=fy,ty do if idx==fy then -- first line if ty==fy then -- single line s=s..txt.get_string_sub(idx,fx,tx-1) else -- multiple lines s=s..txt.get_string_sub(idx,fx) end elseif idx==ty then -- last line s=s..txt.get_string_sub(idx,1,tx-1) else -- middle line s=s..txt.get_string(idx) or "" end end end if s=="" then s=nil end return s end end --[[ get length of currently selected text in bytes txt.copy_length=function() local s=txt.copy() -- expensive hax, we should not bother building a string if s then return #s end return 0 end ]] --[[ get length of line in glyphs ]] txt.get_hx=function(y) y=y or txt.cy -- local s=txt.get_string(y) local cache=txt.get_cache(y) if not cache then return 0 end local hx=#cache.codes while hx>0 do local endswith=cache.codes[hx] if endswith==10 or endswith==13 then hx=hx-1 else break end -- ignore any combination of CR or LF at end of line end if hx > txt.hx then txt.hx=hx end -- fix max return hx end --[[ clip this location so it is within the text. eg too the end of a line ]] txt.clip=function(y,x) if not x then txt.cy,txt.cx=txt.clip(txt.cy,txt.cx) return end if y>txt.hy then y=txt.hy end if y<1 then y=1 end local hx=txt.get_hx(y) if x>hx+1 then x=hx+1 end if x<1 then x=1 end return y,x end --[[ move a cursor one character left and clip it ]] txt.clip_left=function(y,x) if x<=1 and y>1 then y=y-1 x=txt.get_hx(y)+1 else x=x-1 end return txt.clip(y,x) end --[[ move a cursor one character right and clip it ]] txt.clip_right=function(y,x) local hx=txt.get_hx(y)+1 if x>=hx and y<txt.hy then y=y+1 x=1 else x=x+1 end return txt.clip(y,x) end --[[ move a cursor one character up and clip it ]] txt.clip_up=function(y,x) return txt.clip(y-1,x) end --[[ move a cursor one character down and clip it ]] txt.clip_down=function(y,x) return txt.clip(y+1,x) end --[[ insert a character, eg user typing ]] txt.insert_char=function(s) local sb=txt.get_string_sub(txt.cy,1,txt.cx-1) local sc=txt.get_string_sub(txt.cy,txt.cx) txt.set_string(txt.cy,sb..s..sc) txt.cx=txt.cx+1 txt.clip() hook("changed") end --[[ insert a new line ]] txt.insert_newline=function() local sb=txt.get_string_sub(txt.cy,1,txt.cx-1) local sc=txt.get_string_sub(txt.cy,txt.cx) txt.set_string(txt.cy,sb.."\n") txt.cy=txt.cy+1 txt.cx=1 txt.add_string(txt.cy,sc) txt.clip() hook("changed") end --[[ insert any string, which will be broken down by newlines ]] txt.insert=function(s) local split=function(s,d) d=d or "\n" local ss={} -- output table local ti=1 -- table index local si=1 -- string index while true do local fa,fb=string.find(s,d,si) -- find delimiter if fa then ss[ti]=string.sub(s,si,fb) -- add string to table, including delimiter ti=ti+1 si=fb+1 else break end -- no more delimiters end ss[ti]=string.sub(s,si) -- we want empty string after a final new line return ss end local lines=split(s,"\n") for idx,line in ipairs(lines) do if idx==1 then -- first line if #lines>1 then -- inserting multiple lines -- local sa=txt.get_string(txt.cy) or "" local sb=txt.get_string_sub(txt.cy,0,txt.cx-1) local sc=txt.get_string_sub(txt.cy,txt.cx) txt.set_string(txt.cy,sb..line) txt.cy=txt.cy+1 txt.cx=1 txt.add_string(txt.cy,sc) -- put remainder on new line else -- inserting a single line -- local sa=txt.get_string(txt.cy) or "" local sb=txt.get_string_sub(txt.cy,0,txt.cx-1) local sc=txt.get_string_sub(txt.cy,txt.cx) txt.set_string(txt.cy,sb..line..sc) txt.cx=txt.cx+wutf.length(line) end elseif idx==#lines then -- last line txt.set_string(txt.cy,line..(txt.get_string(txt.cy) or "")) txt.cx=wutf.length(line)+1 else -- middle txt.add_string(txt.cy,line) txt.cy=txt.cy+1 txt.cx=1 end end txt.clip() hook("changed") end --[[ remove the new line delimiter between this line and the next eg delete the \n at the end of the line ]] local merge_lines=function() local sa=txt.get_string(txt.cy) or "" txt.cy=txt.cy-1 local hx=txt.get_hx() -- local sb=txt.get_string(txt.cy) or "" txt.cx=hx+1 txt.set_string(txt.cy,txt.get_string_sub(txt.cy,1,hx)..sa) txt.del_string(txt.cy+1) txt.clip() end --[[ delete one glyph from the left of the cursor ]] txt.backspace=function() if txt.cx==1 then if txt.cy==1 then return end merge_lines() return end -- local sa=txt.get_string(txt.cy) or "" local sb=txt.get_string_sub(txt.cy,1,txt.cx-2) local sc=txt.get_string_sub(txt.cy,txt.cx) txt.set_string(txt.cy,sb..sc) txt.cx=txt.cx-1 txt.clip() hook("changed") end --[[ delete one glyph from the right of the cursor ]] txt.delete=function() local hx=txt.get_hx() if txt.cx==hx+1 and txt.cy<txt.hy then txt.cy=txt.cy+1 merge_lines() return end -- local sa=txt.get_string(txt.cy) or "" local sb=txt.get_string_sub(txt.cy,1,txt.cx-1) local sc=txt.get_string_sub(txt.cy,txt.cx+1) txt.set_string(txt.cy,sb..sc) txt.clip() hook("changed") end --[[ assign the lexxer code in charge of highlights ]] txt.set_lexer=function(lexer) if lexer then -- force txt.lexer=lexer else -- guess txt.lexer="text" -- generic if txt.filename then local p=wpath.parse(txt.filename) if p.ext then txt.lexer=string.lower( string.sub(p.ext,2) )-- skip the . at the start end end end txt.lex=wtxtlex.list[txt.lexer] -- the lex to use (if any) txt.clear_caches() end --[[ get the lexxer cache for the given line ]] txt.get_cache_lex=function(idx) if not txt.lex then return txt.get_cache(idx) end -- no lex available local cache=txt.get_cache(idx) if not cache then return cache end -- no cache if cache.lex then -- already done return cache end --print("newlex",idx) local state if idx>1 then -- get last local last_cache=txt.get_cache(idx-1) if not last_cache.lex then -- build for i=1,idx-1 do -- dumb auto loop from start, should be moved --print("lex",i) txt.get_cache_lex(i) end end if last_cache.lex then state=wtxtlex.load(last_cache.lex) end end if not state then state=txt.lex.create() end --print("tokens",cache.string) local tokens=txt.lex.parse(state,cache.string,{}) cache.lex=wtxtlex.save(state) cache.tokens=table.concat(tokens) --print("tokens",cache.tokens) return cache end -- bind to an undo state wtxtundo.construct({},txt) txt.set_text("\n","") txt.set_lexer() return txt end
slot0 = class("CommonBuff", import(".BaseVO")) slot0.Ctor = function (slot0, slot1) slot0.id = slot1.id slot0.configId = slot0.id slot0.timestamp = slot1.timestamp end slot0.IsActiveType = function (slot0) return false end slot0.bindConfigTable = function (slot0) return pg.benefit_buff_template end slot0.checkShow = function (slot0) return slot0:getConfig("hide") ~= 1 end slot0.BackYardExpUsage = function (slot0) return slot0:getConfig("benefit_type") == BuffUsageConst.DORM_EXP end slot0.BattleUsage = function (slot0) return slot0:getConfig("benefit_type") == BuffUsageConst.BATTLE end slot0.RookieBattleExpUsage = function (slot0) return slot0:getConfig("benefit_type") == BuffUsageConst.ROOKIEBATTLEEXP end slot0.GetRookieBattleExpMaxLevel = function (slot0) return slot0:getConfig("benefit_condition")[3] end slot0.isActivate = function (slot0) return pg.TimeMgr.GetInstance():GetServerTime() <= slot0.timestamp end slot0.getLeftTime = function (slot0) return slot0.timestamp - pg.TimeMgr.GetInstance():GetServerTime() end return slot0
fx_version 'adamant' game 'gta5' description 'ESX Menu Dialog' version '1.1.0' shared_script '@DiamondCasino/shared.lua' client_script 'client/main.lua' ui_page 'html/ui.html' files { 'html/ui.html', 'html/css/app.css', 'html/js/mustache.min.js', 'html/js/app.js', 'html/fonts/pdown.ttf', 'html/fonts/bankgothic.ttf' } dependency 'es_extended'
-- Profile settings for G402 -- ========================= -- Use these parameters to assign keyboard-keys to mouse buttons G3,G4,G5,G7,G8 -- Type in your in-game key bindings to select which signs should be mapped to a mouse button. -- Also type in what key you're using to cast a sign. -- E.g. the default key mappings for Igni and Quen, which are "5" and "6" as well as "q" for casting. sign1 = "3"; -- G8 sign2 = "4"; -- G7 sign3 = "5"; -- G5 sign4 = "6"; -- G4 sign5 = "7"; -- G6 cast = "q"; function OnEvent(event, arg) -- Check if mouse button G8 is pressed if event == "MOUSE_BUTTON_PRESSED" and arg == 8 then mbG8_pressed = true elseif event == "MOUSE_BUTTON_RELEASED" and arg == 8 then mbG8_pressed = false ReleaseKey(cast); ReleaseKey(sign1); end -- Check if mouse button G7 is pressed if event == "MOUSE_BUTTON_PRESSED" and arg == 7 then mbG7_pressed = true elseif event == "MOUSE_BUTTON_RELEASED" and arg == 7 then mbG7_pressed = false ReleaseKey(cast); ReleaseKey(sign2); end -- Check if mouse button G5 is pressed if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then mbG5_pressed = true elseif event == "MOUSE_BUTTON_RELEASED" and arg == 5 then mbG5_pressed = false ReleaseKey(cast); ReleaseKey(sign3); end -- Check if mouse button G4 is pressed if event == "MOUSE_BUTTON_PRESSED" and arg == 4 then mbG4_pressed = true elseif event == "MOUSE_BUTTON_RELEASED" and arg == 4 then mbG4_pressed = false ReleaseKey(cast); ReleaseKey(sign4); end -- Check if mouse button G3 is pressed if event == "MOUSE_BUTTON_PRESSED" and arg == 6 then mbG6_pressed = true elseif event == "MOUSE_BUTTON_RELEASED" and arg == 6 then mbG6_pressed = false ReleaseKey(cast); ReleaseKey(sign5); end -- Action for mouse Button G8: Sign1 if mbG8_pressed then PressKey(sign1); PressKey(cast); end -- Action for mouse Button G7: Sign2 if mbG7_pressed then PressKey(sign2); PressKey(cast); end -- Action for mouse Button G5: Sign3 if mbG5_pressed then PressKey(sign3); PressKey(cast); end -- Action for mouse Button G4: Sign4 if mbG4_pressed then PressKey(sign4); PressKey(cast); end -- Action for mouse Button G6: Sign5 if mbG6_pressed then PressKey(sign5); PressKey(cast); end end