content stringlengths 5 1.05M |
|---|
position = {x = 47.3906326293945, y = 0.947854518890381, z = 14.9340381622314}
rotation = {x = 2.68935082203825E-07, y = 270.004608154297, z = -1.25960523291724E-05}
|
--
-- tiledmaphandler.lua
-- lua-astar
--
-- Created by Jay Roberts on 2011-01-12.
-- Copyright 2011 GloryFish.org. All rights reserved.
--
require 'middleclass'
TiledMapHandler = class('TiledMapHandler')
function TiledMapHandler:initialize()
self.tiles = {
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
}
end
function TiledMapHandler:getNode(location)
-- Here you make sure the requested node is valid (i.e. on the map, not blocked)
if location.x > #self.tiles[1] or location.y > #self.tiles then
-- print 'location is outside of map on right or bottom'
return nil
end
if location.x < 1 or location.y < 1 then
-- print 'location is outside of map on left or top'
return nil
end
if self.tiles[location.y][location.x] == 1 then
-- print(string.format('location is solid: (%i, %i)', location.x, location.y))
return nil
end
return Node(location, 1, location.y * #self.tiles[1] + location.x)
end
function TiledMapHandler:getAdjacentNodes(curnode, dest)
-- Given a node, return a table containing all adjacent nodes
-- The code here works for a 2d tile-based game but could be modified
-- for other types of node graphs
local result = {}
local cl = curnode.location
local dl = dest
local n = false
n = self:_handleNode(cl.x + 1, cl.y, curnode, dl.x, dl.y)
if n then
table.insert(result, n)
end
n = self:_handleNode(cl.x - 1, cl.y, curnode, dl.x, dl.y)
if n then
table.insert(result, n)
end
n = self:_handleNode(cl.x, cl.y + 1, curnode, dl.x, dl.y)
if n then
table.insert(result, n)
end
n = self:_handleNode(cl.x, cl.y - 1, curnode, dl.x, dl.y)
if n then
table.insert(result, n)
end
return result
end
function TiledMapHandler:locationsAreEqual(a, b)
return a.x == b.x and a.y == b.y
end
function TiledMapHandler:_handleNode(x, y, fromnode, destx, desty)
-- Fetch a Node for the given location and set its parameters
local loc = {
x = x,
y = y
}
local n = self:getNode(loc)
if n ~= nil then
local dx = math.max(x, destx) - math.min(x, destx)
local dy = math.max(y, desty) - math.min(y, desty)
local emCost = dx + dy
n.mCost = n.mCost + fromnode.mCost
n.score = n.mCost + emCost
n.parent = fromnode
return n
end
return nil
end |
-- SPI PinAssign Table
-- PIO[0]: MOSI(Out) : FlashAir Pin2 CMD
-- PIO[1]: SCLK(Out) : FlashAir Pin7 DAT0
-- PIO[2]: /SS(Out) : FlashAir Pin8 DAT1
-- PIO[3]: MISO(In) : FlashAir Pin9 DAT2
-- PIO[4]: INT(In) : FlashAir Pin1 CD/DAT3
-- g_spi_cs: SPI CS IO state(0,1)
-- g_spi_mode: SPI mode (0,1,2,3)
g_spi_mode=2
g_spi_cs=1
g_contrast=35
function spi_cs(cs,verbosity)
g_spi_cs=cs
local s=0
local r=0
s,r = fa.pio (0x07, (bit32.lshift(g_spi_cs,2)+2+1) )
if (verbosity == 1) then
print (r)
end
end
function spi_write(data,verbosity)
local s=0
local r=0
for i=7, 0,-1 do
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 2 + bit32.band(bit32.rshift(data,i),1)))
if (verbosity == 1) then
print (r)
end
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 0 + bit32.band(bit32.rshift(data,i),1)))
if (verbosity == 1) then
print (r)
end
end
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 2 + bit32.band(data,1)))
if (verbosity == 1) then
print (r)
end
end
function spi_read(data,verbosity)
local s=0
local r=0
local ret_val=""
local tmp
for i=7, 0,-1 do
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 2 + bit32.band(bit32.rshift(data,i),1)))
if (verbosity == 1) then
print (r)
end
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 0 + bit32.band(bit32.rshift(data,i),1)))
tmp = bit32.band(r, 0x8)
ret_val = ret_val..tmp/8
if (verbosity == 1) then
print (r)
end
end
s,r = fa.pio (0x07,(bit32.lshift(g_spi_cs,2) + 2 + bit32.band(data,1)))
if (verbosity == 1) then
print (r)
end
ret_val=tonumber(ret_val,2)
return ret_val
end
function write_reg(addr,data)
spi_cs(0,0)
spi_write(0x20,0)
spi_write(addr,0)
spi_write(data,0)
spi_cs(1,0)
end
function lcd_cmd(data)
spi_cs(0,0)
spi_write(0x00,0) -- command 0x00
spi_write(0x02,0) -- number of bytes: 2
spi_write(0x7c,0) -- slave address+W
spi_write(0x00,0) -- O = 0,RS = 0
spi_write(data,0)
spi_cs(1,0)
end
function lcd_contdata(data)
spi_cs(0,0)
spi_write(0x00,0) -- command 0x00
spi_write(0x02,0) -- number of bytes: 2
spi_write(0x7c,0) -- slave address+W
spi_write(0xC0,0) -- CO = 1, RS = 1
spi_write(data,0)
spi_cs(1,0)
end
function read_reg(addr)
local tmp
spi_cs(0,0)
spi_write(0x21,0)
spi_write(addr,0)
spi_write(0x00,0) -- Don't Care
tmp = spi_read(0x00,0)
lcd_printStr(tmp)
spi_cs(1,0)
end
function lcd_printStr(text)
local tmp
for i=1, string.len(text) do
tmp = string.sub(text, i, i)
tmp = string.byte(tmp)
lcd_contdata(tmp)
end
end
function lcd_setCursor(x, y)
lcd_cmd(bit32.bor(0x80 , y * 0x40 + x))
end
function lcd_init()
lcd_cmd(0x38) -- function set
lcd_cmd(0x39) -- function set
lcd_cmd(0x04) -- EntryModeSet
lcd_cmd(0x14) -- interval osc
lcd_cmd(0x73) -- contrast Low
lcd_cmd(0x5E) -- contast High/icon/power
lcd_cmd(0x6C) -- follower control
lcd_cmd(0x38) -- function set
lcd_cmd(0x0C) -- Display On
lcd_cmd(0x01) -- Clear Display
end
function lcd_init2()
lcd_cmd(0x38) -- function set
lcd_cmd(0x39) -- function set
--lcd_cmd(0x04) -- EntryModeSet
--lcd_cmd(0x14) -- interval osc
--lcd_cmd(0x73) -- contrast Low
--lcd_cmd(0x5E) -- contast High/icon/power
--lcd_cmd(0x6C) -- follower control
--lcd_cmd(0x38) -- function set
--lcd_cmd(0x0C) -- Display On
lcd_cmd(0x01) -- Clear Display
end
function LM75B_init()
spi_cs(0,0)
spi_write(0x00,0) -- command 0x00
spi_write(0x01,0) -- number of bytes: 1
spi_write(0x90,0) -- slave address+W
spi_write(0x00,0)
spi_cs(1,0)
end
function LM75B_read()
local tmp=0
local tmp2=0
spi_cs(0,0)
spi_write(0x01,0) -- command 0x01
spi_write(0x02,0) -- number of bytes: 2
spi_write(0x91,0) -- slave address+R
spi_cs(1,0)
spi_cs(0,0)
spi_write(0x06,0) -- command 0x06
spi_write(0x00,0) -- Dont't Care
tmp = spi_read(0x00,0) -- Read
tmp2 = spi_read(0x00,0) -- Read
spi_cs(1,0)
tmp = bit32.bor(bit32.lshift(tmp,8), tmp2)
tmp = string.format("%3.2f",tmp/256)
return(tmp)
end
function lcd_clear()
lcd_cmd(0x01)
sleep(1000)
end
lcd_init()
--lcd_setCursor(0, 1)
--lcd_printStr("FlashAir")
--LM75B_init()
--write_reg(0x06,0x02)
cnt=1
lcd_printStr("cnt:"..cnt)
lcd_setCursor(0, 1)
lcd_printStr("t:")
f = io.open("test.txt","w+")
f:close()
while(1) do
LM75B_init()
tmp3 = LM75B_read()
--lcd_setCursor(0, 1)
--lcd_cmd(0x80)
lcd_init2()
lcd_setCursor(4, 0)
lcd_printStr(cnt)
lcd_setCursor(2, 1)
lcd_printStr(tmp3)
cnt = cnt+1
f = io.open("test.txt","a")
tmp3 = string.format("%f\n", tmp3)
f:write(tmp3)
f:close()
sleep(1000)
collectgarbage("collect")
end
--read_reg(0x02)
--[[
cnt=1
while(1) do
lcd_setCursor(0,1)
lcd_printStr("cnt:"..cnt)
write_reg(0x01,cnt%2)
cnt = cnt + 1
end
while(1) do
--write_reg(0x01,0x00)
write_reg(0x01,0x01)
write_reg(0x01,0x02)
write_reg(0x01,0x04)
write_reg(0x01,0x08)
write_reg(0x01,0x10)
write_reg(0x01,0x20)
write_reg(0x01,0x40)
write_reg(0x01,0x80)
end
]] |
-----------------------------------
-- Area: Inner Horutoto Ruins (192)
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[tpz.zone.INNER_HORUTOTO_RUINS] =
{
text =
{
PORTAL_SEALED_BY_3_MAGIC = 8, -- The Sealed Portal is sealed by three kinds of magic.
PORTAL_NOT_OPEN_THAT_SIDE = 9, -- The Sealed Portal cannot be opened from this side.
CONQUEST_BASE = 10, -- Tallying conquest results...
ITEM_CANNOT_BE_OBTAINED = 6551, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6557, -- Obtained: <item>.
GIL_OBTAINED = 6558, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6560, -- Obtained key item: <keyitem>.
FELLOW_MESSAGE_OFFSET = 6586, -- I'm ready. I suppose.
GEOMAGNETRON_ATTUNED = 7179, -- Your <keyitem> has been attuned to a geomagnetic fount in the corresponding locale.
NOT_BROKEN_ORB = 7234, -- The Mana Orb in this receptacle is not broken.
EXAMINED_RECEPTACLE = 7235, -- You have already examined this receptacle.
DOOR_FIRMLY_CLOSED = 7262, -- The door is firmly closed.
CHEST_UNLOCKED = 7338, -- You unlock the chest!
PLAYER_OBTAINS_ITEM = 7401, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 7402, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 7403, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 7404, -- You already possess that temporary item.
NO_COMBINATION = 7409, -- You were unable to enter a combination.
REGIME_REGISTERED = 9487, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 10535, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
SLENDLIX_SPINDLETHUMB_PH =
{
[17563758] = 17563785, -- -238.315 -0.002 -179.249
},
NOCUOUS_WEAPON_PH =
{
[17563798] = 17563801, -- -236.855 0.476 -51.263
[17563799] = 17563801, -- -237.426 0.5 -23.412
[17563800] = 17563801, -- -230.732 -0.025 -52.324
},
},
npc =
{
CASKET_BASE = 17563838,
PORTAL_CIRCLE_BASE = 17563861,
TREASURE_CHEST = 17563914,
},
}
return zones[tpz.zone.INNER_HORUTOTO_RUINS]
|
local detectives = {};
local detective_color = Color(0, 0, 255);
net.Receive("Detectives", function()
table.Empty(detectives);
detectives = net.ReadTable();
end);
hook.Add("PreDrawHalos", "DetectiveHalos", function()
local ply_role = LocalPlayer():GetRole();
if (ply_role == ROLE_DETECTIVE and LocalPlayer():Alive() and table.Count(detectives) > 0) then
halo.Add(detectives, detective_color, 1, 1, 10, true, true);
end
end);
|
require 'class'
require 'sprite'
class 'gui'
gui.children = {}
gui.atlas = Sprite( 'data/sprites', 'gui' )
function gui:addChild( child )
-- should check all the methods are present ...
table.insert( self.children, child )
end
function mouseMoved(b,time,x,y)
for _,child in pairs( gui.children ) do
if child:mouseMoved(time, x, y, b) then
break
end
end
end
function mouseClick(b,time,x,y)
for _,child in pairs( gui.children ) do
if child:mouseClick(time, x, y, b) then
break
end
end
end
function mouseUp(b,time,x,y)
for _,child in pairs( gui.children ) do
if child:mouseUp(time, x, y, b) then
break
end
end
end
function mouseDown(b,time,x,y)
for _,child in pairs( gui.children ) do
if child:mouseDown(time, x, y, b) then
break
end
end
end
|
-- test_journal_cursor.lua
--[[
Test using SDJournal as a cursor over the journal entries
In this case, we want to try the various cursor positioning
operations to ensure the work correctly.
--]]
package.path = package.path..";../src/?.lua"
local SDJournal = require("SDJournal")
local sysd = require("systemd_ffi")
local jnl = SDJournal()
-- move forward a few times
for i=1,10 do
jnl:next();
end
-- get the cursor label for this position
local label10 = jnl:positionLabel()
print("Label 10: ", label10)
-- seek to the beginning, print that label
jnl:seekHead();
jnl:next();
local label1 = jnl:positionLabel();
print("Label 1: ", label1);
-- seek to label 10 again
jnl:seekLabel(label10)
jnl:next();
local label3 = jnl:positionLabel();
print("Label 3: ", label3)
print("label 3 == label 10: ", label3 == label10) |
local view = {}
view.__index = view
local player = game.Players.LocalPlayer
local RunService = game:GetService("RunService")
view.DistanceFromCharacter = 5
local offsets = setmetatable({}, {
__call = function(_, mode, Chrt, distance)
distance = distance or view.DistanceFromCharacter
if mode:lower() == "front" then
return CFrame.new((Chrt.CFrame * CFrame.new(0, 0, -distance)).Position, Chrt.Position)
elseif mode:lower() == "back" then
return CFrame.new((Chrt.CFrame * CFrame.new(0, 0, distance )).Position, Chrt.Position)
elseif mode:lower() == "freecam" then
return Chrt.CFrame * player.Character.HumanoidRootPart.CFrame:ToObjectSpace(workspace.CurrentCamera.CFrame)
end
end
})
local rendered_bodyparts = {
--R6 Characters
["Torso"] = true;
["Head"] = true;
["HumanoidRootPart"] = true;
["Left Arm"] = true;
["Left Leg"] = true;
["Right Arm"] = true;
["Right Leg"] = true;
--R15 Characters
["LeftFoot"] = true;
["LeftHand"] = true;
["LeftLowerArm"] = true;
["LeftLowerLeg"] = true;
["LeftUpperArm"] = true;
["LeftUpperLeg"] = true;
["LowerTorso"] = true;
["RightFoot"] = true;
["RightHand"] = true;
["RightLowerArm"] = true;
["RightLowerLeg"] = true;
["RightUpperArm"] = true;
["RightUpperLeg"] = true;
["UpperTorso"] = true;
}
--These are children instances that will not be cloned.
local function rename_similars(model)
for _, v in ipairs(model:GetChildren()) do
local equivalent = model:FindFirstChild(v.Name)
if equivalent and v ~= equivalent then
print("Renamed!")
model[v.Name].Name = v.Name..math.random(1, 100000000)..string.rep(math.random(1, 100), math.random(1, 5))
end
end
end
local function camera_render(camera, cloned_char, mode)
return RunService.RenderStepped:Connect(function(step)
camera.CFrame = offsets(mode, cloned_char["HumanoidRootPart"])
end)
end
local function clean_up(object)
for _, v in ipairs(object:GetDescendants()) do
if v:IsA("BaseScript") or v:IsA("GuiObject") or v:IsA("GuiBase2d") or v:IsA("ParticleEmitter") or v:IsA("Camera") or v:IsA("ValueBase") or v:IsA("Camera") or v:IsA("Motor") or v:IsA("Weld") then
v:Destroy()
end
end
end
local function view_ui(viewport_frame, data)
if data:IsA("ViewportFrame") then
viewport_frame.Visible = true
data.Visible = true
else
viewport_frame.BackgroundTransparency = 1
viewport_frame.Position = data.Position
viewport_frame.Size = data.Size
viewport_frame.Parent.Enabled = true
viewport_frame.Visible = true
end
end
function view.new(data, char)
if not data:IsA("ViewportFrame") then --If not passed already-made viewport frame, checks if you instead passed the Position and Size parameters in the data list
assert(data.Size and typeof(data.Size) == "UDim2", "Data type error!")
assert(data.Position and typeof(data.Position) == "UDim2", "Data type error!")
end
local self = setmetatable({}, view)
if data:IsA("ViewportFrame") then
self._viewport = data
else
local screenGui = Instance.new("ScreenGui")
screenGui.Name = "ViewCharacter.fr"
screenGui.Parent = player:WaitForChild("PlayerGui")
local viewPortFrame = Instance.new("ViewportFrame")
viewPortFrame.Parent = screenGui
self._viewport = viewPortFrame
end
self._backups = {}
self._character = char
self._data = data
self._clonedchar = {}
self._updatechar = {}
self._events = {}
self._accessorypool = {}
self._vehicle = {}
return self
end
local function disconnectAllEvents(tabl)
for _, v in ipairs(tabl) do
v:Disconnect()
end
pcall(function()
tabl["Cam"]:Disconnect()
end)
return {}
end
function view:Enable(Mode)
Mode = self._previousmode or Mode or "Front"
self._viewport:ClearAllChildren()
self._events = disconnectAllEvents(self._events)
self._clonedchar = {}
self._updatechar = {}
if self._camera then self._camera:Destroy() end
self._camera = Instance.new("Camera", self._viewport)
self:InitAddition()
self:_TrackChanges()
view_ui(self._viewport, self._data)
self._viewport.CurrentCamera = self._camera
self._events["Cam"] = camera_render(self._camera, self._clonedchar, Mode)
self._previousmode = Mode
local added
added = self._character.ChildAdded:Connect(function(child)
self._clonedchar[child.Name] = child
local clone = child:Clone()
clean_up(clone)
clone.Parent = self._clonedchar["HumanoidRootPart"].Parent
local event
event = RunService.Stepped:Connect(function()
if child then
for _, v in ipairs(clone:GetChildren()) do
if v:IsA("BasePart") then
v.CFrame = child[v.Name].CFrame
end
end
else
event:Disconnect()
end
end)
self._events[child] = event
end)
local removed
removed = self._character.ChildRemoved:Connect(function(child)
if self._events[child] then self._events[child]:Disconnect(); self._events[child] = nil end
self._clonedchar[child.Name] = nil
local model = self._clonedchar["HumanoidRootPart"].Parent
local child_viewport = model:FindFirstChild(child.Name)
if child_viewport then
child_viewport:Destroy()
end
end)
local died
died = self._character:WaitForChild("Humanoid").Died:Connect(function()
self:Freeze()
removed:Disconnect()
added:Disconnect()
end)
table.insert(self._events, died)
--Minor support for vehicles
self._character:WaitForChild("Humanoid").StateChanged:Connect(function(old, new)
if new == Enum.HumanoidStateType.Seated then
local ray = Ray.new(self._character.HumanoidRootPart.Position, -self._character.HumanoidRootPart.CFrame.UpVector * 2)
local part = workspace:FindPartOnRay(ray, self._character)
if part then
local parent = part:FindFirstAncestorWhichIsA("Model", true);
if parent then
rename_similars(parent)
self._vehicle = parent:GetChildren()
if not self._backups[parent.Parent.Name..parent.Name] then
self._backups[parent.Parent.Name..parent.Name] = parent
end
self:LoadOnToView(self._vehicle)
end
end
elseif old == Enum.HumanoidStateType.Seated then
self:UnLoadFromView(self._vehicle)
self._vehicle = {}
end
end)
end
function view:SwitchMode(mode)
self._events["Cam"]:Disconnect()
self._events["Cam"] = camera_render(self._camera, self._clonedchar, mode)
end
function view:Disable()
self._viewport:ClearAllChildren()
disconnectAllEvents(self._events)
end
function view:Freeze()
disconnectAllEvents(self._events)
end
function view:Unfreeze()
coroutine.wrap(function()
self:Enable(self._previousmode)
end)()
end
function view:InitAddition() -- Internal use
self._character.Archivable=true
local clonedModel = Instance.new("Model")
for _, v in ipairs(self._character:GetChildren()) do
if v:IsA("Accessory") then
repeat wait() until v:FindFirstChild("Handle") ~= nil
end
local archivable = v.Archivable
v.Archivable = true
local clone = v:Clone()
clean_up(clone)
clone.Parent = clonedModel
self._clonedchar[v.Name] = clone
v.Archivable = archivable
end
clonedModel.Parent = self._viewport
end
function view:_TrackChanges() --Internal use
for _, v in ipairs(self._character:GetChildren()) do
if (v:IsA("BasePart") and rendered_bodyparts[v.Name]) or v:IsA("Tool") or v:IsA("Humanoid") then
table.insert(self._updatechar, v)
print("added", v)
end
end
if self._character:FindFirstChildWhichIsA("Accessory") then
self:ReloadAccessories()
print("Loading accessories!")
else
print("No accessories to load!")
end
for i = 1, #self._updatechar do
local object = self._updatechar[i]
if object:IsA("BasePart") or object:IsA("UnionOperation") then
local event
event = RunService.Stepped:Connect(function()
if object then
self:Update(object, "CFrame")
else
event:Disconnect()
end
end)
table.insert(self._events, event)
elseif object:IsA("Humanoid") then
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.FallingDown, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Running, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.RunningNoPhysics, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Climbing, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.StrafingNoPhysics, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Ragdoll, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.GettingUp, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Jumping, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Landed, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Flying, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Freefall, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Seated, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.PlatformStanding, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Dead, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Swimming, false)
self._clonedchar[object.Name]:SetStateEnabled(Enum.HumanoidStateType.Physics, false)
self._clonedchar[object.Name].HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
self._clonedchar[object.Name].DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
elseif object:IsA("Accessory") or object:IsA("Tool") then
local event
if object:IsA("Accessory") then
event = RunService.Stepped:Connect(function()
if object then
self:Update(object, "CFrame")
else
event:Disconnect()
end
end)
elseif object:IsA("Tool") then
event = RunService.Stepped:Connect(function()
if object then
self:Update(object, "CFrame")
else
event:Disconnect()
end
end)
end
table.insert(self._events, event)
end
end
end
function view:Update(object, property) --Internal use
if object:IsA("Humanoid") then return end
if object:IsA("Accoutrement") then
self._clonedchar[object.Name].Handle[property] = object.Handle[property]
else
self._clonedchar[object.Name][property] = object[property]
end
end
function view:UpdateCustomLoaded(OriginalObject, ClonedObject, Property)
if OriginalObject:IsA("BasePart") or OriginalObject:IsA("UnionOperation") then
ClonedObject[Property] = OriginalObject[Property]
end
end
function view:ReloadAccessories()
local accessories = {}
local char_children = self._character:GetChildren()
for i = 1, #char_children do
if char_children[i]:IsA("Accessory") then
table.insert(accessories, char_children[i])
table.insert(self._updatechar, char_children[i])
end
end
end
function view:LoadOnToView(tabl)
local index = tabl[1].Parent.Parent.Name..tabl[1].Parent.Name
local backed_up = self._backups[index]
if typeof(backed_up) == "table" then
for i = 1, #backed_up do
if backed_up[i]:IsA("BasePart") or backed_up[i]:IsA("Decal") or backed_up[i]:IsA("UnionOperation") then
local new_transparency = (backed_up[i].Transparency == 0 and 1) or 0
backed_up[i].Transparency = new_transparency
end
end
return
end
self._backups[index] = {}
spawn(function()
for _, object in ipairs(tabl) do
for _, obj in ipairs(object:GetDescendants()) do
if obj:IsA("Model") then
obj:Destroy()
end
end
end
end)
for _, object in ipairs(tabl) do
if object:IsA("Light") then
continue
end
if (object:IsA("BasePart") or object:IsA("Decal") or object:IsA("UnionOperation")) and object.Transparency == 1 then
continue
end
local clone = object:Clone()
clean_up(clone)
clone.Parent = self._viewport
table.insert(self._backups[index], clone)
local event
event = RunService.Stepped:Connect(function()
if object then
self:UpdateCustomLoaded(object, clone,"CFrame")
else
clone:Destroy()
event:Disconnect()
end
end)
table.insert(self._events, event)
end
end
function view:UnLoadFromView(tabl)
local table_rel = self._backups[tabl[1].Parent.Parent.Name..tabl[1].Parent.Name]
if typeof(table_rel) == "table" then
for _, object in ipairs(table_rel) do
if object:IsA("BasePart") or object:IsA("UnionOperation") or object:IsA("Decal") then
object.Transparency = 1
end
end
return
end
end
function view:Destroy()
self:Disable()
self._viewport = nil
self._data = nil
self._clonedchar = nil
self._updatechar = nil
self._events = nil
self._camera = nil
self._previousmode = nil
self._vehicle = nil
self._backups = nil
end
return view
|
object_tangible_component_reverse_engineering_power_bit = object_tangible_component_reverse_engineering_shared_power_bit:new {
}
ObjectTemplates:addTemplate(object_tangible_component_reverse_engineering_power_bit, "object/tangible/component/reverse_engineering/power_bit.iff")
|
if not loadStatFile then
dofile("statdesc.lua")
end
loadStatFile("stat_descriptions.txt")
local itemClassMap = {
["LifeFlask"] = "Flask",
["ManaFlask"] = "Flask",
["HybridFlask"] = "Flask",
["Amulet"] = "Amulet",
["Ring"] = "Ring",
["Claw"] = "Claw",
["Dagger"] = "Dagger",
["Wand"] = "Wand",
["One Hand Sword"] = "One Handed Sword",
["Thrusting One Hand Sword"] = "Thrusting One Handed Sword",
["One Hand Axe"] = "One Handed Axe",
["One Hand Mace"] = "One Handed Mace",
["Bow"] = "Bow",
["Staff"] = "Staff",
["Two Hand Sword"] = "Two Handed Sword",
["Two Hand Axe"] = "Two Handed Axe",
["Two Hand Mace"] = "Two Handed Mace",
["Quiver"] = "Quiver",
["Belt"] = "Belt",
["Gloves"] = "Gloves",
["Boots"] = "Boots",
["Body Armour"] = "Body Armour",
["Helmet"] = "Helmet",
["Shield"] = "Shield",
["Sceptre"] = "Sceptre",
["UtilityFlask"] = "Flask",
["UtilityFlaskCritical"] = "Flask",
["Map"] = "Map",
["Jewel"] = "Jewel",
["Rune Dagger"] = "Dagger",
["Warstaff"] = "Staff",
}
local out = io.open("../Data/ModMaster.lua", "w")
out:write('-- This file is automatically generated, do not edit!\n')
out:write('-- Item data (c) Grinding Gear Games\n\nreturn {\n')
for _, craft in ipairs(dat("CraftingBenchOptions"):GetRowList("IsDisabled", false)) do
if craft.Mod then
out:write('\t{ ')
if craft.Mod.GenerationType == 1 then
out:write('type = "Prefix", ')
elseif craft.Mod.GenerationType == 2 then
out:write('type = "Suffix", ')
end
out:write('affix = "', craft.Mod.Name, '", ')
local stats, orders = describeMod(craft.Mod)
out:write('modTags = { ', stats.modTags, ' }, ')
out:write('"', table.concat(stats, '", "'), '", ')
out:write('statOrder = { ', table.concat(orders, ', '), ' }, ')
out:write('level = ', craft.Mod.Level, ', group = "', craft.Mod.Family, '", ')
out:write('types = { ')
for _, category in ipairs(craft.ItemCategories) do
for _, itemClass in ipairs(category.ItemClasses) do
out:write('["', itemClassMap[itemClass.Id], '"] = true, ')
end
end
out:write('}, ')
out:write('},\n')
end
end
out:write('}')
out:close()
print("Master mods exported.") |
return {'acacia','acaciahout','acacialaan','academica','academicus','academie','academiegebouw','academiejaar','academiestad','academietijd','academievergadering','academievriend','academisch','academisme','acajou','acajouboom','acanthus','acanthusblad','academielid','academieopleiding','academieburger','acacias','acacialanen','academici','academiegebouwen','academiejaren','academies','academiesteden','academievrienden','academische','academischer','academien','acanthussen','acaciaatje','acajoubomen','acanthusbladeren','academieleden'} |
-----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Miuseloir B Enchelles
-- !pos 120 0 104 80
-----------------------------------
------------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(154);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
--[[
Workstealing architecture
**************************************** PUC-RIO 2014 ****************************************
Implemented by:
- Breno Riba
Implemented on October 2014
**********************************************************************************************
]]--
local workstealing = {}
local stages = {}
local lstage = require 'lstage'
local pool = require 'lstage.pool'
function workstealing.compare(a,b)
local aRate = a:getInputCount()
local bRate = b:getInputCount()
if (aRate ~= 0) then
aRate = (a:getProcessedCount() * 100) / aRate
end
if (bRate ~= 0) then
bRate = (b:getProcessedCount() * 100) / bRate
end
return aRate < bRate
end
--[[
<summary>
Used to refresh stage's rate
</summary>
<param name="id">Timer ID</param>
]]--
function workstealing.on_timer(id)
-- Validate ID number
if (id ~= 100) then
return
end
table.sort(stages,workstealing.compare)
if (#stages >= 4) then
local first = 1
local last = #stages
for i=1,2,1 do
local firstPool = stages[first]:pool()
local lastPool = stages[last]:pool()
local lastPoolSize = lastPool:size()
if (lastPoolSize > 1 and stages[first]:instances() >= (firstPool:size() + 1)) then
print(first.." roubou do estágio "..last)
stages[first]:steal(stages[last],1)
end
first = first + 1
last = last - 1
end
end
-- Reset statistics
for i,stage in ipairs(stages) do
stage:resetStatistics()
end
end
--[[
<summary>
Workstealing configure method
</summary>
<param name="stagesTable">LEDA stages table</param>
<param name="threadsPerPool">Number of threads to be created per pool</param>
<param name="refreshSeconds">Time (in seconds) to refresh stage's rate</param>
]]--
function workstealing.configure (stagesTable, threadsPerPool, refreshSeconds)
-- Creating a pool per stage
for i,stage in ipairs(stagesTable) do
-- New pool
local currentPool=pool.new(0)
currentPool:add(threadsPerPool)
-- Set this pool to stage
stage:setpool(currentPool)
end
stages = stagesTable
-- Every "refreshSeconds" with ID = 100
while true do
lstage.event.sleep(refreshSeconds)
workstealing.on_timer(100)
end
end
return workstealing
|
local update_formspec = function(meta)
local text = meta:get_string("text")
meta:set_string("infotext", "Dialogue block: '" .. text .. "'")
meta:set_string("formspec", "size[8,2;]" ..
"field[0.2,0.5;8,1;text;Text;" .. text .. "]" ..
"button_exit[0.1,1.5;8,1;save;Save]" ..
"")
end
-- player -> {}
local active_dialogues = {}
-- formspec name
local FORMNAME = "epic_dialogue"
-- create the dialogue formspec
local function show_formspec(player_name)
local player_dialogue = active_dialogues[player_name]
local buttons = ""
local i = 0
for pos_str, text in pairs(player_dialogue.targets) do
buttons = buttons ..
"button_exit[0," .. (i+0) .. ";2,1;" .. pos_str .. ";Choose]" ..
"label[2.5," .. (i+0.2) .. ";" .. text .. "]"
i = i + 1
end
minetest.show_formspec(player_name,
FORMNAME,
"size[8," .. (i) .. ";]" ..
buttons
)
end
-- callback
minetest.register_on_player_receive_fields(function(player, formname, fields)
local parts = formname:split(";")
local name = parts[1]
if name ~= FORMNAME then
return
end
print("epic_dialogue", player:get_player_name(), dump(fields))
local player_name = player:get_player_name()
local player_dialogue = active_dialogues[player_name]
if not player_dialogue then
-- dialogue not active
return
end
for pos_str in pairs(player_dialogue.targets) do
if fields[pos_str] then
player_dialogue.selected = pos_str
return true
end
end
-- no choice = quit
player_dialogue.quit = true
return true
end)
minetest.register_node("epic:dialogue", {
description = "Epic dialogue block: show one or more questions in a formspec",
tiles = epic.create_texture("condition", "epic_bubble.png"),
paramtype2 = "facedir",
groups = {cracky=3,oddly_breakable_by_hand=3,epic=1},
on_rotate = epic.on_rotate,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("text", "Example text")
update_formspec(meta, pos)
end,
on_receive_fields = function(pos, _, fields, sender)
local meta = minetest.get_meta(pos);
if not sender or minetest.is_protected(pos, sender:get_player_name()) then
-- not allowed
return
end
if fields.save then
local text = fields.text or "<no text>"
meta:set_string("text", text)
update_formspec(meta, pos)
end
end,
epic = {
on_enter = function(pos, meta, player)
local player_name = player:get_player_name()
local player_dialogue = active_dialogues[player_name]
if not player_dialogue then
-- create dialogue entry
player_dialogue = {
active = false,
quit = false,
selected = nil,
-- pos-str -> bool(selected)
targets = {}
}
-- save
active_dialogues[player_name] = player_dialogue
end
-- mark dialogue as not selected yet
player_dialogue.targets[minetest.pos_to_string(pos)] = meta:get_string("text")
end,
on_check = function(pos, _, player, ctx)
local player_name = player:get_player_name()
local player_dialogue = active_dialogues[player_name]
if player_dialogue then
-- show formspec if not alredy active
if not player_dialogue.active then
show_formspec(player_name)
player_dialogue.active = true
end
if player_dialogue.quit then
-- player quit the formname, abort epic execution
ctx.abort("dialogue-exit")
return
end
-- check if current dialogue node is selected
if player_dialogue.selected and player_dialogue.selected == minetest.pos_to_string(pos) then
-- position matches proceed
ctx.next()
end
end
end,
on_exit = function(_, _, player)
-- clear current dialogue
local player_name = player:get_player_name()
active_dialogues[player_name] = nil
end
}
})
|
--------------------------------
-- @module CheckBox
-- @extend AbstractCheckButton
-- @parent_module ccui
--------------------------------
-- Add a callback function which would be called when checkbox is selected or unselected.<br>
-- param callback A std::function with type @see `ccCheckBoxCallback`
-- @function [parent=#CheckBox] addEventListener
-- @param self
-- @param #function callback
-- @return CheckBox#CheckBox self (return value: ccui.CheckBox)
--------------------------------
-- @overload self, string, string, string, string, string, int
-- @overload self
-- @overload self, string, string, int
-- @function [parent=#CheckBox] create
-- @param self
-- @param #string backGround
-- @param #string backGroundSelected
-- @param #string cross
-- @param #string backGroundDisabled
-- @param #string frontCrossDisabled
-- @param #int texType
-- @return CheckBox#CheckBox ret (return value: ccui.CheckBox)
--------------------------------
--
-- @function [parent=#CheckBox] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
--
-- @function [parent=#CheckBox] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- Default constructor.<br>
-- lua new
-- @function [parent=#CheckBox] CheckBox
-- @param self
-- @return CheckBox#CheckBox self (return value: ccui.CheckBox)
return nil
|
local Events = require "scripts/ToolKit/events"
local Utilities = require "scripts/ToolKit/utilities"
local PlayerAnimationController = {
Properties = {
Debug = true,
Animations = {
Right = EntityId(),
Left = EntityId(),
Up = EntityId(),
Down = EntityId(),
WalkDown = EntityId(),
WalkUp = EntityId(),
WalkRight = EntityId(),
WalkLeft = EntityId(),
AttackRightSword = EntityId(),
AttackLeftSword = EntityId(),
AttackUpSword = EntityId(),
AttackDownSword = EntityId(),
}
},
Events = {
[Events.OnPlayAnimation] = {global=true}
}
}
function PlayerAnimationController:OnActivate()
Utilities:InitLogging(self, "PlayerAnimationController")
Utilities:BindEvents(self, self.Events)
end
function PlayerAnimationController.Events.OnPlayAnimation:OnEventBegin(animation)
for animName,entityId in pairs(self.Component.Properties.Animations) do
if animName == animation then
UiElementBus.Event.SetIsEnabled(entityId, true)
else
UiElementBus.Event.SetIsEnabled(entityId, false)
end
end
end
function PlayerAnimationController:OnDeactivate()
Utilities:UnBindEvents(self.Events)
end
return PlayerAnimationController |
local Prop = {}
Prop.Name = "Mesa 3-315 Grif Dr"
Prop.Cat = "Apartments"
Prop.Price = 750
Prop.Doors = {
Vector( 254, 8190, 804 ),
Vector( -78, 7938, 804 ),
Vector( -198, 7982, 804 ),
Vector( -78, 8066, 804 ),
Vector( -50, 8446, 804 ),
}
GM.Property:Register( Prop ) |
fx_version "cerulean"
games { "gta5" }
ui_page "html/index.html"
files {
"html/index.html",
"html/script.js",
"html/style.css",
"html/doorL1.png",
"html/doorL2.png",
"html/doorR1.png",
"html/doorR2.png",
"html/hood.png",
"html/trunk.png",
"html/seat.png",
"html/windowL1.png",
"html/windowL2.png",
"html/windowR1.png",
"html/windowR2.png",
"html/buttonOff.png",
"html/buttonOn.png",
"html/buttonHover.png",
"html/engine.png",
}
shared_scripts {
"shared/*",
}
server_scripts {
"server/*",
}
client_scripts {
"@caue-sync/client/cl_lib.lua",
"client/*",
} |
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
local beautiful = require("beautiful")
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup")
require("awful.hotkeys_popup.keys")
--local mymainmenu = require("widgets.startmenu")
-- Return this
local keys = {}
-- Apps
terminal = "st"
modkey = "Mod4"
editor = os.getenv("EDITOR") or "vi"
editor_cmd = terminal .. " -e " .. editor
mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon,
menu = mymainmenu })
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}
-- {{{ Key bindings
-- i'll fix this eventually
function toggle_systray()
local s = awful.screen.focused()
s.systray.visible = not s.systray.visible
end
-- General Awesome keys
awful.keyboard.append_global_keybindings({
awful.key({ "Control" }, "`", function() naughty.destroy_all_notifications(nil, 1) end,
{description="kills all notifications", group="awesome"}),
awful.key({ modkey, }, "=", toggle_systray,
{description="show help", group="awesome"}),
awful.key({ modkey, }, "s", hotkeys_popup.show_help,
{description="show help", group="awesome"}),
awful.key({ modkey, }, "w", function () mymainmenu:show() end,
{description = "show main menu", group = "awesome"}),
awful.key({ modkey, "Shift" }, "r", awesome.restart,
{description = "reload awesome", group = "awesome"}),
awful.key({ modkey, "Shift" }, "q", awesome.quit,
{description = "quit awesome", group = "awesome"}),
awful.key({ modkey }, "x",
function ()
awful.prompt.run {
prompt = "Run Lua code: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = awful.util.eval,
history_path = awful.util.get_cache_dir() .. "/history_eval"
}
end,
{description = "lua execute prompt", group = "awesome"}),
awful.key({ modkey, }, "Return", function () awful.spawn(terminal) end,
{description = "open a terminal", group = "launcher"}),
awful.key({ modkey }, "r", function () awful.spawn.with_shell("rofi -show drun") end,
{description = "run prompt", group = "launcher"}),
awful.key({ modkey }, "p", function() menubar.show() end,
{description = "show the menubar", group = "launcher"}),
})
-- Tags related keybindings
awful.keyboard.append_global_keybindings({
awful.key({ modkey, }, "Left", awful.tag.viewprev,
{description = "view previous", group = "tag"}),
awful.key({ modkey, }, "Right", awful.tag.viewnext,
{description = "view next", group = "tag"}),
awful.key({ modkey, }, "Escape", awful.tag.history.restore,
{description = "go back", group = "tag"}),
})
-- Focus related keybindings
awful.keyboard.append_global_keybindings({
awful.key({ modkey, }, "j",
function ()
awful.client.focus.byidx( 1)
end,
{description = "focus next by index", group = "client"}
),
awful.key({ modkey, }, "k",
function ()
awful.client.focus.byidx(-1)
end,
{description = "focus previous by index", group = "client"}
),
awful.key({ modkey, }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{description = "go back", group = "client"}),
awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end,
{description = "focus the next screen", group = "screen"}),
awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end,
{description = "focus the previous screen", group = "screen"}),
awful.key({ modkey, "Control" }, "n",
function ()
local c = awful.client.restore()
-- Focus restored client
if c then
c:activate { raise = true, context = "key.unminimize" }
end
end,
{description = "restore minimized", group = "client"}),
})
-- Audio related keybindings
local volume_notif
local vol = function(step)
if step < 0 then
step = -step
signal = "-"
not_icon = os.getenv("HOME") .. "/.config/bin/icons/volume-down.svg"
elseif step > 0 then
signal = "+"
not_icon = os.getenv("HOME") .. "/.config/bin/icons/volume-up.svg"
else
step = "toggle"
signal = ""
not_icon = os.getenv("HOME") .. "/.config/bin/icons/volume-muted.svg"
end
local muted = "amixer sget 'Master' | grep -m 1 'Left:' | awk '{print$6}'"
local cmd = "amixer sset 'Master' " .. step .. "%" .. signal
local vol_cmd = "amixer sget 'Master' | grep -o '.*%]' | cut -d '[' -f 2 | head -n 1 | cut -d% -f1"
awful.spawn.easy_async_with_shell(muted, function(out)
if signal == "+" and out == "[off]\n" then
-- unmute and change volume
cmd = "amixer sset 'Master' toggle && " .. cmd
awful.spawn.easy_async_with_shell(cmd, function(vol)
awful.spawn.easy_async_with_shell(vol_cmd, function(vol)
awful.spawn.easy_async_with_shell("getprogressstring 20 '━' '┄' " .. vol, function(bar)
if volume_notif and not volume_notif.is_expired then
volume_notif.message = cmd
volume_notif.icon = not_icon
else
volume_notif = naughty.notification({ title = "Volume", message = cmd, icon = not_icon, timeout = 2 })
end
end)
end)
end)
else
if step == "toggle" then
if out == "[off]\n" then
not_icon = os.getenv("HOME") .. "/.config/bin/icons/volume-on.svg"
elseif out == "[on]\n" then
not_icon = os.getenv("HOME") .. "/.config/bin/icons/volume-muted.svg"
end
end
-- change volume
awful.spawn.easy_async_with_shell(cmd, function()
awful.spawn.easy_async_with_shell(vol_cmd, function(vol)
awful.spawn.easy_async_with_shell("getprogressstring 20 '━' '┄' " .. vol, function(bar)
if volume_notif and not volume_notif.is_expired then
volume_notif.message = bar
volume_notif.icon = not_icon
else
volume_notif = naughty.notification({ title = "Volume", message = bar, icon = not_icon, timeout = 2 })
end
end)
end)
end)
end
end)
end
awful.keyboard.append_global_keybindings({
awful.key({ }, "XF86AudioLowerVolume", function () vol(-5) end,
{description = "decreases volume by 1", group = "audio"}),
awful.key({ }, "XF86AudioRaiseVolume", function () vol(5) end,
{description = "increases volume by 1", group = "audio"}),
awful.key({ }, "XF86AudioMute", function () vol(0) end,
{description = "toggle audio mute", group = "audio"}),
-- Music Volume
awful.key({ modkey }, "XF86AudioLowerVolume", function () awful.spawn.with_shell("mpc volume -1") end,
{description = "decreases music volume by 1", group = "audio"}),
awful.key({ modkey }, "XF86AudioRaiseVolume", function () awful.spawn.with_shell("mpc volume +1") end,
{description = "increases music volume by 1", group = "audio"}),
-- Music
awful.key({ }, "XF86AudioPlay", function () awful.spawn.with_shell("controlmusic toggle") end,
{description = "play/pause music", group = "audio"}),
awful.key({ }, "XF86AudioPause", function () awful.spawn.with_shell("controlmusic toggle") end,
{description = "play/pause music", group = "audio"}),
awful.key({ }, "XF86AudioNext", function () awful.spawn.with_shell("controlmusic next") end,
{description = "plays next song", group = "audio"}),
awful.key({ }, "XF86AudioPrev", function () awful.spawn.with_shell("controlmusic prev") end,
{description = "plays previous song", group = "audio"}),
})
-- Print
awful.keyboard.append_global_keybindings({
awful.key({ }, "Print", function () awful.spawn.with_shell("screenshot.sh") end,
{description = "screenshot the entire screen", group = "screenshot"}),
awful.key({ "Shift" }, "Print", function () awful.spawn.with_shell("screenshot.sh -c") end,
{description = "select area to capture", group = "screenshot"}),
awful.key({ "Control", "Shift" }, "Print", function () awful.spawn.with_shell("screenshot.sh -s") end,
{description = "select area to take a screenshot", group = "screenshot"}),
})
-- Layout related keybindings
awful.keyboard.append_global_keybindings({
awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end,
{description = "swap with next client by index", group = "client"}),
awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end,
{description = "swap with previous client by index", group = "client"}),
awful.key({ modkey, }, "u", awful.client.urgent.jumpto,
{description = "jump to urgent client", group = "client"}),
awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end,
{description = "increase master width factor", group = "layout"}),
awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end,
{description = "decrease master width factor", group = "layout"}),
awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1, nil, true) end,
{description = "increase the number of master clients", group = "layout"}),
awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1, nil, true) end,
{description = "decrease the number of master clients", group = "layout"}),
awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1, nil, true) end,
{description = "increase the number of columns", group = "layout"}),
awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1, nil, true) end,
{description = "decrease the number of columns", group = "layout"}),
awful.key({ modkey, }, "space", function () awful.layout.inc( 1) end,
{description = "select next", group = "layout"}),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(-1) end,
{description = "select previous", group = "layout"}),
})
awful.keyboard.append_global_keybindings({
awful.key {
modifiers = { modkey },
keygroup = "numrow",
description = "only view tag",
group = "tag",
on_press = function (index)
awesome.emit_signal("t")
local screen = awful.screen.focused()
local tag = screen.tags[index]
if tag then
tag:view_only()
end
end,
},
awful.key {
modifiers = { modkey, "Control" },
keygroup = "numrow",
description = "toggle tag",
group = "tag",
on_press = function (index)
local screen = awful.screen.focused()
local tag = screen.tags[index]
if tag then
awful.tag.viewtoggle(tag)
end
end,
},
awful.key {
modifiers = { modkey, "Shift" },
keygroup = "numrow",
description = "move focused client to tag",
group = "tag",
on_press = function (index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
},
awful.key {
modifiers = { modkey, "Control", "Shift" },
keygroup = "numrow",
description = "toggle focused client on tag",
group = "tag",
on_press = function (index)
if client.focus then
local tag = client.focus.screen.tags[index]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
},
awful.key {
modifiers = { modkey },
keygroup = "numpad",
description = "select layout directly",
group = "layout",
on_press = function (index)
local t = awful.screen.focused().selected_tag
if t then
t.layout = t.layouts[index] or t.layout
end
end,
}
})
client.connect_signal("request::default_mousebindings", function()
awful.mouse.append_client_mousebindings({
awful.button({ }, 1, function (c)
c:activate { context = "mouse_click" }
end),
awful.button({ modkey }, 1, function (c)
c:activate { context = "mouse_click", action = "mouse_move" }
end),
awful.button({ modkey }, 3, function (c)
c:activate { context = "mouse_click", action = "mouse_resize"}
end),
})
end)
client.connect_signal("request::default_keybindings", function()
awful.keyboard.append_client_keybindings({
awful.key({ modkey, }, "f",
function (c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{description = "toggle fullscreen", group = "client"}),
awful.key({ modkey }, "q",
function (c)
c:kill()
end,
{description = "close", group = "client"}),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ,
{description = "toggle floating", group = "client"}),
awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end,
{description = "move to master", group = "client"}),
awful.key({ modkey, }, "o", function (c) c:move_to_screen() end,
{description = "move to screen", group = "client"}),
awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end,
{description = "toggle keep on top", group = "client"}),
awful.key({ modkey, }, "n",
function (c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end ,
{description = "minimize", group = "client"}),
awful.key({ modkey, }, "m",
function (c)
c.maximized = not c.maximized
c:raise()
end ,
{description = "(un)maximize", group = "client"}),
awful.key({ modkey, "Control" }, "m",
function (c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end ,
{description = "(un)maximize vertically", group = "client"}),
awful.key({ modkey, "Shift" }, "m",
function (c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end ,
{description = "(un)maximize horizontally", group = "client"}),
})
end)
-- }}}
-- {{{ Mouse bindings
-- mouse wheel speed fix
aux = 0
awful.mouse.append_global_mousebindings({
awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({ }, 4,
function ()
aux = aux + 1
if aux > 2 then
awful.tag.viewnext()
aux = 0
end
end),
awful.button({ }, 5,
function ()
aux = aux + 1
if aux > 2 then
awful.tag.viewprev()
aux = 0
end
end),
})
-- }}}
return keys
|
-- Start this file with a command like:
-- >lua launchPlotServer.lua "PARENT PORT" portNum
local args = {...} -- arguments given by parent
-- Search for PARENT PORT number and store it in parentPort global variable
for i=1,#args,2 do
--print(args[i],args[i+1],args[i]=="PARENT PORT",#args[i])
if args[i] == "PARENT PORT" and args[i+1] then
--print("Set parentPort = ",tonumber(args[i+1]))
parentPort = args[i+1]
end
end
--print("plotserver is launched")
require("lua-plot.plotserver")
|
function SpawnPoints()
return {
constructionworker = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
},
fireofficer = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
},
parkranger = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
},
policeofficer = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
},
securityguard = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
},
unemployed = {
{ worldX = 30, worldY = 21, posX = 297, posY = 177, posZ = 0 },
{ worldX = 30, worldY = 21, posX = 297, posY = 123, posZ = 0 }
}
}
end
|
local utils = require "utils"
-- For debugging purposes
_G.dump = function(...)
print(vim.inspect(...))
end
_G.warn= function(msg, name)
utils.log(msg, name, "DiagnosticWarn")
end
_G.error = function(msg, name)
utils.log(msg, name, "DiagnosticError")
end
_G.info = function(msg, name)
utils.log(msg, name, "DiagnosticInfo")
end
utils.map("n", "gn", "<cmd>lua info(vim.api.nvim_buf_get_name(0), 'Filename')<CR>")
|
return function()
local ScreenSize = require(script.Parent.ScreenSize)
local AvatarEditorPrompts = script.Parent.Parent
local Actions = AvatarEditorPrompts.Actions
local ScreenSizeUpdated = require(Actions.ScreenSizeUpdated)
it("should have the correct default value", function()
local defaultState = ScreenSize(nil, {})
expect(defaultState).to.equal(Vector2.new(0, 0))
end)
describe("ScreenSizeUpdated", function()
it("should change the value screenSize", function()
local oldState = ScreenSize(nil, {})
local newState = ScreenSize(oldState, ScreenSizeUpdated(Vector2.new(1500, 1200)))
expect(oldState).to.never.equal(newState)
expect(newState).to.equal(Vector2.new(1500, 1200))
end)
end)
end |
local bin = require "bin"
local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
description = [[
Enumerates Siemens S7 PLC Devices and collects their device information. This
script is based off PLCScan that was developed by Positive Research and
Scadastrangelove (https://code.google.com/p/plcscan/). This script is meant to
provide the same functionality as PLCScan inside of Nmap. Some of the
information that is collected by PLCScan was not ported over; this
information can be parsed out of the packets that are received.
Thanks to Positive Research, and Dmitry Efanov for creating PLCScan
]]
author = "Stephen Hilt (Digital Bond)"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery", "version"}
---
-- @usage
-- nmap --script s7-info.nse -p 102 <host/s>
--
-- @output
--102/tcp open Siemens S7 PLC
--| s7-info:
--| Basic Hardware: 6ES7 315-2AG10-0AB0
--| System Name: SIMATIC 300(1)
--| Copyright: Original Siemens Equipment
--| Version: 2.6.9
--| Module Type: CPU 315-2 DP
--| Module: 6ES7 315-2AG10-0AB0
--|_ Serial Number: S C-X4U421302009
--
--
-- @xmloutput
--<elem key="Basic Hardware">6ES7 315-2AG10-0AB0</elem>
--<elem key="System Name">SIMATIC 300(1)</elem>
--<elem key="Copyright">Original Siemens Equipment</elem>
--<elem key="Version">2.6.9</elem>
--<elem key="Object Name">SimpleServer</elem>
--<elem key="Module Type">CPU 315-2 DP</elem>
--<elem key="Module">6ES7 315-2AG10-0AB0</elem>
--<elem key="Serial Number">S C-X4U421302009</elem>
--<elm key="Plant Identification"></elem>
-- port rule for devices running on TCP/102
portrule = shortport.port_or_service(102, "iso-tsap", "tcp")
---
-- Function to send and receive the S7COMM Packet
--
-- First argument is the socket that was created inside of the main Action
-- this will be utilized to send and receive the packets from the host.
-- the second argument is the query to be sent, this is passed in and is created
-- inside of the main action.
-- @param socket the socket that was created in Action.
-- @param query the specific query that you want to send/receive on.
local function send_receive(socket, query)
local sendstatus, senderr = socket:send(query)
if(sendstatus == false) then
return "Error Sending S7COMM"
end
-- receive response
local rcvstatus, response = socket:receive()
if(rcvstatus == false) then
return "Error Reading S7COMM"
end
return response
end
---
-- Function to parse the first SZL Request response that was received from the S7 PLCC
--
-- First argument is the socket that was created inside of the main Action
-- this will be utilized to send and receive the packets from the host.
-- the second argument is the query to be sent, this is passed in and is created
-- inside of the main action.
-- @param response Packet response that was received from S7 host.
-- @param host The host hat was passed in via Nmap, this is to change output of host/port
-- @param port The port that was passed in via Nmap, this is to change output of host/port
-- @param output Table used for output for return to Nmap
local function parse_response(response, host, port, output)
-- unpack the protocol ID
local pos, value = bin.unpack("C", response, 8)
-- unpack the second byte of the SZL-ID
local pos, szl_id = bin.unpack("C", response, 31)
-- set the offset to 0
local offset = 0
-- if the protocol ID is 0x32
if (value == 0x32) then
local pos
-- unpack the module information
pos, output["Module"] = bin.unpack("z", response, 44)
-- unpack the basic hardware information
pos, output["Basic Hardware"] = bin.unpack("z", response, 72)
-- set version number to 0
local version = 0
-- parse version number
local pos, char1, char2, char3 = bin.unpack("CCC", response, 123)
-- concatenate string, or if string is nil make version number 0.0
output["Version"] = table.concat({char1 or "0.0", char2, char3}, ".")
-- return the output table
return output
else
return nil
end
end
---
-- Function to parse the second SZL Request response that was received from the S7 PLC
--
-- First argument is the socket that was created inside of the main Action
-- this will be utilized to send and receive the packets from the host.
-- the second argument is the query to be sent, this is passed in and is created
-- inside of the main action.
-- @param response Packet response that was received from S7 host.
-- @param output Table used for output for return to Nmap
local function second_parse_response(response, output)
local offset = 0
-- unpack the protocol ID
local pos, value = bin.unpack("C", response, 8)
-- unpack the second byte of the SZL-ID
local pos, szl_id = bin.unpack("C", response, 31)
-- if the protocol ID is 0x32
if (value == 0x32) then
-- if the szl-ID is not 0x1c
if( szl_id ~= 0x1c ) then
-- change offset to 4, this is where most of valid PLCs will fall
offset = 4
end
-- parse system name
pos, output["System Name"] = bin.unpack("z", response, 40 + offset)
-- parse module type
pos, output["Module Type"] = bin.unpack("z", response, 74 + offset)
-- parse serial number
pos, output["Serial Number"] = bin.unpack("z", response, 176 + offset)
-- parse plant identification
pos, output["Plant Identification"] = bin.unpack("z", response, 108 + offset)
-- parse copyright
pos, output["Copyright"] = bin.unpack("z", response, 142 + offset)
-- for each element in the table, if it is nil, then remove the information from the table
for key, value in pairs(output) do
if(string.len(output[key]) == 0) then
output[key] = nil
end
end
-- return output
return output
else
return nil
end
end
---
-- Function to set the nmap output for the host, if a valid S7COMM packet
-- is received then the output will show that the port is open
-- and change the output to reflect an S7 PLC
--
-- @param host Host that was passed in via nmap
-- @param port port that S7COMM is running on
local function set_nmap(host, port)
--set port Open
port.state = "open"
-- set that detected an Siemens S7
port.version.name = "iso-tsap"
port.version.devicetype = "specialized"
port.version.product = "Siemens S7 PLC"
nmap.set_port_version(host, port)
nmap.set_port_state(host, port, "open")
end
---
-- Action Function that is used to run the NSE. This function will send the initial query to the
-- host and port that were passed in via nmap. The initial response is parsed to determine if host
-- is a S7COMM device. If it is then more actions are taken to gather extra information.
--
-- @param host Host that was scanned via nmap
-- @param port port that was scanned via nmap
action = function(host, port)
-- COTP packet with a dst of 102
local COTP = bin.pack("H", "0300001611e00000001400c1020100c2020" .. "102" .. "c0010a")
-- COTP packet with a dst of 200
local alt_COTP = bin.pack("H", "0300001611e00000000500c1020100c2020" .. "200" .. "c0010a")
-- setup the ROSCTR Packet
local ROSCTR_Setup = bin.pack("H", "0300001902f08032010000000000080000f0000001000101e0")
-- setup the Read SZL information packet
local Read_SZL = bin.pack("H", "0300002102f080320700000000000800080001120411440100ff09000400110001")
-- setup the first SZL request (gather the basic hardware and version number)
local first_SZL_Request = bin.pack("H", "0300002102f080320700000000000800080001120411440100ff09000400110001")
-- setup the second SZL request
local second_SZL_Request = bin.pack("H", "0300002102f080320700000000000800080001120411440100ff090004001c0001")
-- response is used to collect the packet responses
local response
-- output table for Nmap
local output = stdnse.output_table()
-- create socket for communications
local sock = nmap.new_socket()
-- connect to host
local constatus, conerr = sock:connect(host, port)
if not constatus then
stdnse.debug1('Error establishing connection for %s - %s', host, conerr)
return nil
end
-- send and receive the COTP Packet
response = send_receive(sock, COTP)
-- unpack the PDU Type
local pos, CC_connect_confirm = bin.unpack("C", response, 6)
-- if PDU type is not 0xd0, then not a successful COTP connection
if ( CC_connect_confirm ~= 0xd0) then
sock:close()
-- create socket for communications
stdnse.debug1('S7INFO:: CREATING NEW SOCKET')
sock = nmap.new_socket()
-- connect to host
local constatus, conerr = sock:connect(host, port)
if not constatus then
stdnse.debug1('Error establishing connection for %s - %s', host, conerr)
return nil
end
response = send_receive(sock, alt_COTP)
local pos, CC_connect_confirm = bin.unpack("C", response, 6)
if ( CC_connect_confirm ~= 0xd0) then
stdnse.debug1('S7 INFO:: Could not negotiate COTP')
return nil
end
end
-- send and receive the ROSCTR Setup Packet
response = send_receive(sock, ROSCTR_Setup)
-- unpack the protocol ID
local pos, protocol_id = bin.unpack("C", response, 8)
-- if protocol ID is not 0x32 then return nil
if ( protocol_id ~= 0x32) then
return nil
end
-- send and receive the READ_SZL packet
response = send_receive(sock, Read_SZL)
local pos, protocol_id = bin.unpack("C", response, 8)
-- if protocol ID is not 0x32 then return nil
if ( protocol_id ~= 0x32) then
return nil
end
-- send and receive the first SZL Request packet
response = send_receive(sock, first_SZL_Request)
-- parse the response for basic hardware information
output = parse_response(response, host, port, output)
-- send and receive the second SZL Request packet
response = send_receive(sock, second_SZL_Request)
-- parse the response for more information
output = second_parse_response(response, output)
-- close the socket
sock:close()
-- If we parsed anything, then set the version info for Nmap
if #output > 0 then
set_nmap(host, port)
end
-- return output to Nmap
return output
end
|
#!/usr/bin/env lua5.3
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local easing = require("modules.libraries.backend.easing")
local naughty = require("naughty")
local animation = {
mt = {},
}
local function create_animation(args)
if type(args) ~= "table" then
raise_error("Type of 'args' must be table!")
end
args = args or {}
args = {
fps = args.fps or 60,
start = args.start or 0,
stop = args.stop or 100,
step = args.step or 1,
loop = args.loop or false,
easing = args.easing or easing.easeInOutCubic,
callback = args.callback, -- Needs to be defined, because it's just a resource waste otherwise.
}
local current_step = 0
local current_step_invert = 1
local timer
local timer_callback
if args.loop == true or args.loop == "forward" or args.loop == "f" then
timer_callback = function()
current_step = current_step + args.step
if current_step >= args.stop then
current_step = 0
end
local current_step_eased = args.easing(current_step / args.stop) * args.stop
args.callback(current_step_eased)
end
elseif args.loop == "forward-backward" or args.loop == "fb" then
timer_callback = function()
if current_step <= args.start then
current_step_invert = 1
elseif current_step >= args.stop then
current_step_invert = -1
end
current_step = current_step + (args.step * current_step_invert)
local current_step_eased = args.easing(current_step / args.stop) * args.stop
args.callback(current_step_eased)
end
else
timer_callback = function()
current_step = current_step + args.step
if current_step >= args.stop then
current_step = 0
timer:stop()
end
local current_step_eased = args.easing(current_step / args.stop) * args.stop
args.callback(current_step_eased)
end
end
timer = gears.timer {
timeout = 1 / args.fps,
autostart = true,
callback = timer_callback
}
end
local function new(args)
create_animation(args)
local new_instance = setmetatable({}, animation)
animation.__index = animation
return new_instance
end
function animation.mt:__call(...)
return new(...)
end
return setmetatable(animation, animation.mt)
|
//________________________________
//
// NS2 Combat Mod
// Made by JimWest and MCMLXXXIV, 2012
//
//________________________________
// combat_Utility.lua
// Used to send messages to all players.
function SendGlobalChatMessage(message)
local allPlayers = Shared.GetEntitiesWithClassname("Player")
if (allPlayers:GetSize() > 0) then
for index, player in ientitylist(allPlayers) do
player:SendDirectMessage(message)
end
end
// Also output to the console for admins.
Shared.Message(message)
end
// Gets the time in the format "[m minutes,] s seconds"
function GetTimeText(timeInSeconds)
local timeLeftText = ""
timeNumericSeconds = math.abs(tonumber(timeInSeconds))
ASSERT(timeNumericSeconds >= 0)
if (timeNumericSeconds > 60) then
timeLeftText = math.floor(timeNumericSeconds/60) .." minutes"
elseif (timeNumericSeconds == 60) then
timeLeftText = "1 minute"
end
if (timeNumericSeconds > 60 and timeNumericSeconds % 60 ~= 0) then
timeLeftText = timeLeftText .. ", "
end
if (timeNumericSeconds % 60 ~= 0) then
if (timeNumericSeconds % 60 == 1) then
timeLeftText = timeLeftText .. "1 second"
else
timeLeftText = timeLeftText .. (timeNumericSeconds % 60) .." seconds"
end
end
return timeLeftText
end
// Gets the time in the format "mm:ss:ms"
function GetTimeDigital(timeInSeconds, showMinutes, showMilliseconds)
local timeLeftText = ""
timeNumericSeconds = tonumber(timeInSeconds)
if (timeNumericSeconds < 0) then
timeLeftText = "- "
end
timeNumericSeconds = math.abs(tonumber(timeInSeconds))
if showMinutes then
local timeLeftMinutes = math.floor(timeNumericSeconds/60)
if (timeLeftMinutes < 10) then
timeLeftText = timeLeftText .. "0" .. timeLeftMinutes
else
timeLeftText = timeLeftText .. timeLeftMinutes
end
timeLeftText = timeLeftText .. ":"
end
timeLeftSeconds = math.floor(timeNumericSeconds % 60)
if (timeLeftSeconds < 10) then
timeLeftText = timeLeftText .. "0" .. timeLeftSeconds
else
timeLeftText = timeLeftText .. timeLeftSeconds
end
// Disable milliseconds by default. They are *really* annoying.
if showMilliseconds then
timeLeftText = timeLeftText .. ":"
local timeLeftMilliseconds = math.ceil((timeNumericSeconds * 100) % 100)
if (timeLeftMilliseconds < 10) then
timeLeftText = timeLeftText .. "0" .. timeLeftMilliseconds
else
timeLeftText = timeLeftText .. timeLeftMilliseconds
end
end
return timeLeftText
end
function GetHasTimelimitPassed()
if Server then
return GetGamerules():GetHasTimelimitPassed()
else
return PlayerUI_GetHasTimelimitPassed()
end
end |
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
local Node = cc.Node
function Node:add(child, zorder, tag)
if tag then
self:addChild(child, zorder, tag)
elseif zorder then
self:addChild(child, zorder)
else
self:addChild(child)
end
return self
end
function Node:addTo(parent, zorder, tag)
if tag then
parent:addChild(self, zorder, tag)
elseif zorder then
parent:addChild(self, zorder)
else
parent:addChild(self)
end
return self
end
function Node:removeSelf()
self:removeFromParent()
return self
end
function Node:align(anchorPoint, x, y)
self:setAnchorPoint(anchorPoint)
return self:move(x, y)
end
function Node:show()
self:setVisible(true)
return self
end
function Node:hide()
self:setVisible(false)
return self
end
function Node:move(x, y)
if y then
self:setPosition(x, y)
else
self:setPosition(x)
end
return self
end
function Node:moveTo(args)
transition.moveTo(self, args)
return self
end
function Node:moveBy(args)
transition.moveBy(self, args)
return self
end
function Node:fadeIn(args)
transition.fadeIn(self, args)
return self
end
function Node:fadeOut(args)
transition.fadeOut(self, args)
return self
end
function Node:fadeTo(args)
transition.fadeTo(self, args)
return self
end
function Node:rotate(rotation)
self:setRotation(rotation)
return self
end
function Node:rotateTo(args)
transition.rotateTo(self, args)
return self
end
function Node:rotateBy(args)
transition.rotateBy(self, args)
return self
end
function Node:scaleTo(args)
transition.scaleTo(self, args)
return self
end
function Node:onUpdate(callback)
self:scheduleUpdateWithPriorityLua(callback, 0)
return self
end
Node.scheduleUpdate = Node.onUpdate
function Node:onNodeEvent(eventName, callback)
if "enter" == eventName then
self.onEnterCallback_ = callback
elseif "exit" == eventName then
self.onExitCallback_ = callback
elseif "enterTransitionFinish" == eventName then
self.onEnterTransitionFinishCallback_ = callback
elseif "exitTransitionStart" == eventName then
self.onExitTransitionStartCallback_ = callback
elseif "cleanup" == eventName then
self.onCleanupCallback_ = callback
end
self:enableNodeEvents()
end
function Node:enableNodeEvents()
if self.isNodeEventEnabled_ then
return self
end
self:registerScriptHandler(function(state)
if state == "enter" then
self:onEnter_()
elseif state == "exit" then
self:onExit_()
elseif state == "enterTransitionFinish" then
self:onEnterTransitionFinish_()
elseif state == "exitTransitionStart" then
self:onExitTransitionStart_()
elseif state == "cleanup" then
self:onCleanup_()
end
end)
self.isNodeEventEnabled_ = true
return self
end
function Node:disableNodeEvents()
self:unregisterScriptHandler()
self.isNodeEventEnabled_ = false
return self
end
function Node:onEnter()
end
function Node:onExit()
end
function Node:onEnterTransitionFinish()
end
function Node:onExitTransitionStart()
end
function Node:onCleanup()
end
function Node:onEnter_()
self:onEnter()
if not self.onEnterCallback_ then
return
end
self:onEnterCallback_()
end
function Node:onExit_()
self:onExit()
if not self.onExitCallback_ then
return
end
self:onExitCallback_()
end
function Node:onEnterTransitionFinish_()
self:onEnterTransitionFinish()
if not self.onEnterTransitionFinishCallback_ then
return
end
self:onEnterTransitionFinishCallback_()
end
function Node:onExitTransitionStart_()
self:onExitTransitionStart()
if not self.onExitTransitionStartCallback_ then
return
end
self:onExitTransitionStartCallback_()
end
function Node:onCleanup_()
self:onCleanup()
if not self.onCleanupCallback_ then
return
end
self:onCleanupCallback_()
end
|
return {'hysop','hysterica','hystericus','hysterie','hysterisch','hystericae','hysterici','hysterische','hysterischer'} |
local linkBodyToBone = {
[3] = 4,
[4] = 1,
[5] = 23,
[6] = 33,
[7] = 52,
[8] = 42,
[9] = 5,
}
local linkBodyToFly = {
[3] = 0,
[4] = 1,
[5] = 1,
[6] = 0,
[7] = 1,
[8] = 0,
[9] = 1,
}
-- 1 = Text flows Left side
-- 0 = Text flows Right Side
local drawTextQueue = {}
local font = dxCreateFont("font.otf", 16)
if (not font) then
font = "arial"
end
function getRGBFromObject(v)
if (v[2] == 9) then
return 210, 117, 7
end
if (v[10] == 0) then
return 0, 0, 255
end
return 255, 255, 255
end
function drawDamageText()
for i, v in pairs(drawTextQueue) do
if (getTickCount() - v[6] > 500) then
drawTextQueue[i] = nil
else
if (v[1] and isElementOnScreen(v[1])) then
if (not v[7]) then
local boneX, boneY, boneZ = getPedBonePosition(v[1], v[5])
local screenX, screenY = getScreenFromWorldPosition(boneX, boneY, boneZ)
drawTextQueue[i][7] = true
if (screenX) then
drawTextQueue[i][8] = {0, 0}
local r, g, b = getRGBFromObject(v)
dxDrawText(tostring(v[3]), screenX, screenY, screenX, screenY, tocolor(r, g, b, 255), 1, font, "left", "top", false, false, true)
else
drawTextQueue[i] = nil
end
else
local boneX, boneY, boneZ = getPedBonePosition(v[1], v[5])
local screenX, screenY = getScreenFromWorldPosition(boneX, boneY, boneZ)
if (screenX) then
local alterX, alterY = unpack(drawTextQueue[i][8])
local screenX, screenY = screenX + alterX, screenY + alterY
local moveTo = v[4]
screenY = screenY - 1
alterY = alterY - 1
if (moveTo == 0) then
screenX = screenX - 1
alterX = alterX - 1
else
screenX = screenX + 1
alterX = alterX + 1
end
drawTextQueue[i][8] = {alterX , alterY}
local r, g, b = getRGBFromObject(v)
dxDrawText(tostring(v[3]), screenX, screenY, screenX, screenY, tocolor(r, g, b, (500 - (getTickCount() - v[6]) / 500) * 255), 1, font, "left", "top", false, false, true)
end
end
end
end
end
end
addEventHandler("onClientRender", root, drawDamageText)
function drawDamageNumbers(attacker, weapon, bodypart, loss)
if (wasEventCancelled()) then
return false
end
if (loss < 5) then
return false
end
if (localPlayer ~= attacker) then
return false
end
if (bodypart == 9) then
setSoundVolume(playSound("sound.mp3", false), 1.5)
end
drawTextQueue[#drawTextQueue + 1] = {source, bodypart, math.floor(loss), linkBodyToFly[bodypart], linkBodyToBone[bodypart], getTickCount(), false, 0, 0, getPedArmor(source) > 0 and 0 or 1}
end
addEvent("onClientLocalPlayerDamage", true)
addEventHandler("onClientLocalPlayerDamage", root, drawDamageNumbers, true, "low-5") |
--[[ =================================================================
Description:
All strings (German) used by MailTips.
================================================================= --]]
-- Strings used within MailTips
if (GetLocale()=="deDE") then
MT_STARTUP_MESSAGE = MT_NAME.." ("..C_GREEN..MT_VERSION..C_CLOSE..") geladen.";
MT_ENCLOSED_ITEMS = "Beiliegende Gegenst\195\164nde";
end;
|
--[[
A very simple wrapper for the DataStore methods.
Do you ever find yourself typing the word "Async" over and over again every
time you work with DataStores? There's got to be a better way!
Well now there is! With this simple module you will never need to type the
word "Async" again. Thaaat's right, for the low price of FREE you can save
yourself from the pain of remembering the correct sequence of letters to type
that horrible word.
Also with Crazyman32's MockDataStoreService module, all data store operations
can be handled offline. Now your game won't break down and cry when testing
locally.
--]]
local dataStoreService = game:GetService("DataStoreService")
if game.PlaceId == 0 then
dataStoreService = require(script.Parent.MockDataStoreService)
end
local DataStore = {}
DataStore.__index = DataStore
function DataStore.new(name, scope)
local self = {}
self.DataStore = dataStoreService:GetDataStore(name, scope)
return setmetatable(self, DataStore)
end
function DataStore:Get(key)
self.DataStore:GetAsync(key)
end
function DataStore:Set(key, value)
self.DataStore:SetAsync(key, value)
end
function DataStore:Update(key, callback)
self.DataStore:UpdateAsync(key, callback)
end
function DataStore:Increment(key, delta)
self.DataStore:IncrementAsync(key, delta)
end
return DataStore
|
slot2 = "DdzRoomBgAutoAdaptWidthCcsPane"
DdzRoomBgAutoAdaptWidthCcsPane = class(slot1)
DdzRoomBgAutoAdaptWidthCcsPane.onCreationComplete = function (slot0)
slot4 = BgAutoAdaptWidthCcsPane
ClassUtil.extends(slot2, slot0)
BgAutoAdaptWidthCcsPane.onCreationComplete(slot2)
slot4 = slot0._newTxt
slot0._newTxt._posX = slot0._newTxt.getPositionX(slot0)
end
DdzRoomBgAutoAdaptWidthCcsPane.onStrTxt = function (slot0)
slot3 = slot0
BgAutoAdaptWidthCcsPane.onStrTxt(slot2)
slot3 = slot0._newTxt
if slot0._newTxt.getTextWidth(slot2) < slot0._strBaseWidth then
slot5 = slot0._newTxt._posX + (slot0._strBaseWidth - slot1) / 2
slot0._newTxt.setPositionX(slot3, slot0._newTxt)
else
slot5 = slot0._newTxt._posX
slot0._newTxt.setPositionX(slot3, slot0._newTxt)
end
end
return
|
------------------------------
local a,b; return 1,a,b
------------------------------
success compiling learn.lua
; source chunk: learn.lua
; x86 standard (32-bit, little endian, doubles)
; function [0] definition (level 1) 0
; 0 upvalues, 0 params, is_vararg = 2, 5 stacks
.function 0 0 2 5
.local "a" ; 0
.local "b" ; 1
.const 1 ; 0
[1] loadk 2 0 ; R2 := 1
[2] move 3 0 ; R3 := R0
[3] move 4 1 ; R4 := R1
[4] return 2 4 ; return R2 to R4
[5] return 0 1 ; return
; end of function 0
; source chunk: luac.out
; x86 standard (32-bit, little endian, doubles)
; function [0] definition (level 1) 0
; 0 upvalues, 0 params, is_vararg = 2, 5 stacks
.function 0 0 2 5
.local "a" ; 0
.local "b" ; 1
.const 1 ; 0
[1] loadk 2 0 ; R2 := 1
[2] move 3 0 ; R3 := R0
[3] move 4 1 ; R4 := R1
[4] return 2 4 ; return R2 to R4
[5] return 0 1 ; return
; end of function 0
------------------------------
success compiling learn.lua
Pos Hex Data Description or Code
------------------------------------------------------------------------
0000 ** source chunk: learn.lua
** global header start **
0000 1B4C7561 header signature: "\27Lua"
0004 51 version (major:minor hex digits)
0005 00 format (0=official)
0006 01 endianness (1=little endian)
0007 04 size of int (bytes)
0008 08 size of size_t (bytes)
0009 04 size of Instruction (bytes)
000A 08 size of number (bytes)
000B 00 integral (1=integral)
* number type: double
* x86 standard (32-bit, little endian, doubles)
** global header end **
000C ** function [0] definition (level 1) 0
** start of function 0 **
000C 0B00000000000000 string size (11)
0014 406C6561726E2E6C+ "@learn.l"
001C 756100 "ua\0"
source name: @learn.lua
001F 00000000 line defined (0)
0023 00000000 last line defined (0)
0027 00 nups (0)
0028 00 numparams (0)
0029 02 is_vararg (2)
002A 05 maxstacksize (5)
* code:
002B 05000000 sizecode (5)
002F 81000000 [1] loadk 2 0 ; R2 := 1
0033 C0000000 [2] move 3 0 ; R3 := R0
0037 00018000 [3] move 4 1 ; R4 := R1
003B 9E000002 [4] return 2 4 ; return R2 to R4
003F 1E008000 [5] return 0 1 ; return
* constants:
0043 01000000 sizek (1)
0047 03 const type 3
0048 000000000000F03F const [0]: (1)
* functions:
0050 00000000 sizep (0)
* lines:
0054 05000000 sizelineinfo (5)
[pc] (line)
0058 01000000 [1] (1)
005C 01000000 [2] (1)
0060 01000000 [3] (1)
0064 01000000 [4] (1)
0068 01000000 [5] (1)
* locals:
006C 02000000 sizelocvars (2)
0070 0200000000000000 string size (2)
0078 6100 "a\0"
local [0]: a
007A 00000000 startpc (0)
007E 04000000 endpc (4)
0082 0200000000000000 string size (2)
008A 6200 "b\0"
local [1]: b
008C 00000000 startpc (0)
0090 04000000 endpc (4)
* upvalues:
0094 00000000 sizeupvalues (0)
** end of function 0 **
0098 ** end of chunk **
Pos Hex Data Description or Code
------------------------------------------------------------------------
0000 ** source chunk: luac.out
** global header start **
0000 1B4C7561 header signature: "\27Lua"
0004 51 version (major:minor hex digits)
0005 00 format (0=official)
0006 01 endianness (1=little endian)
0007 04 size of int (bytes)
0008 08 size of size_t (bytes)
0009 04 size of Instruction (bytes)
000A 08 size of number (bytes)
000B 00 integral (1=integral)
* number type: double
* x86 standard (32-bit, little endian, doubles)
** global header end **
000C ** function [0] definition (level 1) 0
** start of function 0 **
000C 0B00000000000000 string size (11)
0014 406C6561726E2E6C+ "@learn.l"
001C 756100 "ua\0"
source name: @learn.lua
001F 00000000 line defined (0)
0023 00000000 last line defined (0)
0027 00 nups (0)
0028 00 numparams (0)
0029 02 is_vararg (2)
002A 05 maxstacksize (5)
* code:
002B 05000000 sizecode (5)
002F 81000000 [1] loadk 2 0 ; R2 := 1
0033 C0000000 [2] move 3 0 ; R3 := R0
0037 00018000 [3] move 4 1 ; R4 := R1
003B 9E000002 [4] return 2 4 ; return R2 to R4
003F 1E008000 [5] return 0 1 ; return
* constants:
0043 01000000 sizek (1)
0047 03 const type 3
0048 000000000000F03F const [0]: (1)
* functions:
0050 00000000 sizep (0)
* lines:
0054 05000000 sizelineinfo (5)
[pc] (line)
0058 01000000 [1] (1)
005C 01000000 [2] (1)
0060 01000000 [3] (1)
0064 01000000 [4] (1)
0068 01000000 [5] (1)
* locals:
006C 02000000 sizelocvars (2)
0070 0200000000000000 string size (2)
0078 6100 "a\0"
local [0]: a
007A 00000000 startpc (0)
007E 04000000 endpc (4)
0082 0200000000000000 string size (2)
008A 6200 "b\0"
local [1]: b
008C 00000000 startpc (0)
0090 04000000 endpc (4)
* upvalues:
0094 00000000 sizeupvalues (0)
** end of function 0 **
0098 ** end of chunk **
|
--[[
Author: Miqueas Martinez (miqueas2020@yahoo.com)
Date: 2020/04/30
Git repository: https://github.com/Miqueas/Self
zlib License
Copyright (c) 2020 - 2022 Miqueas Martinez
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
]]
local unp = unpack or table.unpack
local getmt = getmetatable
local setmt = setmetatable
local get = rawget
local set = rawset
--[[ Private stuff ]]
--- A simple custom version of `assert()` with built-in
--- `string.format()` support
--- @generic Expr
--- @param exp Expr Expression to evaluate
--- @param msg string Error message to print
--- @vararg any Additional arguments to format for `msg`
--- @return Expr
local function err(exp, msg, ...)
local msg = msg:format(...)
if not (exp) then
return error(msg)
end
return exp
end
--- Argument type checking function
--- @generic Any
--- @generic Type
--- @param argn number The argument position in function
--- @param arg_ Any The argument to check
--- @param expected Type The type expected (`string`)
--- @return nil
local function check_arg(argn, arg_, expected)
local argt = type(arg_)
local msg = "Bad argument #%d, `%s` expected, got `%s`."
if argt ~= expected then
error(msg:format(argn, expected, argt))
end
end
--- Same as `check_arg()`, except that this don't throw
--- and error if the argument is `nil`
--- @generic Any
--- @generic Type
--- @param argn number The argument position in function
--- @param arg_ Any The argument to check
--- @param expected Type The type expected (`string`)
--- @return nil
local function opt_arg(argn, arg_, expected)
local argt = type(arg_)
local msg = "Bad argument #%d, `%s` or `nil` expected, got `%s`."
if argt ~= expected and argt ~= "nil" then
error(msg:format(argn, expected, argt))
end
end
--[[ Public stuff ]]
--- Parent class for all classes
--- @class Object
local Object = {}
--- Creates a class
--- @param def table Class "template"
--- @return table
function Class(def)
check_arg(1, def, "table")
local class = setmt(def, Object)
return class
end
--- Return `true` if `instance` is type of `class`,
--- otherwise returns false. If `class` is `nil`,
--- then returns "Object".
--- @param instance table The object
--- @param class table The class
--- @return table|string
function Object.is(instance, class)
check_arg(1, instance, "table")
opt_arg(2, class, "table")
local mt = getmt(instance)
if not class then
return "Object"
end
return mt == class or getmt(mt) == Object
end
--- Implements all functions from one or more classes/tables given.
--- Can't use this from an instance.
--- @param class table The class where implement functions
--- @param ... table Tables/classes with functions to import from
--- @return nil
function Object.implements(class, ...)
check_arg(1, class, "table")
-- Prevent using this method from an instance
err(
getmt(class) == Object,
"Trying to call 'implements' method from an instance"
)
for iface_index, iface in ipairs({ ... }) do
check_arg(iface_index, iface, "table")
for name, func in pairs(iface) do
if not get(class, name) then
set(class, name, func)
end
end
end
end
--- Global constructor
--- @param class table The class to use to create the object
--- @param ... any Additional arguments to pass to the class constructor
--- @return table
function Object.__call(class, ...)
check_arg(1, class, "table")
-- At the moment, these two meta-fields aren't writables
set(class, "__index", class)
set(class, "__newindex", Object.__newindex)
local o = setmt({}, class)
o:new(...)
return o
end
--- Getter
--- @param class table The object
--- @param key string The key
--- @return any
function Object.__index(class, key)
return get(class, key) or get(Object, key)
end
--- Setter
--- @param class table The object
--- @param key string The key
--- @param val any The value
--- @return nil
function Object.__newindex(class, key, val)
local mt = getmt(class)
local _val = get(class, key) or get(mt, key)
if mt == Object then
-- From a class
set(class, key, val)
else
-- From an instance
err(_val, "Field '%s' doesn't exists.", key)
err(type(_val) ~= "function", "Trying to overwrite method '%s'.", key)
set(class, key, val)
end
end
Object.new = Object.__call
--- Handles what will be returned when "require()" this library.
--- See the documentation for more details.
--- @param g_constructor boolean Enable/disable global constructor
--- @param g_object boolean Enable/disable global `Object`
--- @return function, Object|nil
return function (g_constructor, g_object)
opt_arg(1, g_constructor, "boolean")
opt_arg(2, g_object, "boolean")
if g_constructor then
if not _G.New then
_G.New = Object.new
end
end
if g_object then
return Class, Object
end
return Class
end |
fio = require('fio')
net = require('net.box')
fiber = require('fiber')
ext = (jit.os == "OSX" and "dylib" or "so")
build_path = os.getenv("BUILDDIR")
reload1_path = build_path..'/test/box/reload1.'..ext
reload2_path = build_path..'/test/box/reload2.'..ext
reload_path = "reload."..ext
_ = fio.unlink(reload_path)
c = net.connect(os.getenv("LISTEN"))
box.schema.func.create('reload.foo', {language = "C"})
box.schema.user.grant('guest', 'execute', 'function', 'reload.foo')
_ = box.schema.space.create('test')
_ = box.space.test:create_index('primary', {parts = {1, "integer"}})
box.schema.user.grant('guest', 'read,write', 'space', 'test')
_ = fio.unlink(reload_path)
fio.copyfile(reload1_path, reload_path)
--check not fail on non-load func
box.schema.func.reload("reload")
-- test of usual case reload. No hanging calls
box.space.test:insert{0}
c:call("reload.foo", {1})
box.space.test:delete{0}
fio.copyfile(reload2_path, reload_path)
box.schema.func.reload("reload")
c:call("reload.foo")
box.space.test:select{}
box.space.test:truncate()
-- test case with hanging calls
fio.copyfile(reload1_path, reload_path)
box.schema.func.reload("reload")
fibers = 10
for i = 1, fibers do fiber.create(function() c:call("reload.foo", {i}) end) end
while box.space.test:count() < fibers do fiber.sleep(0.001) end
-- double reload doesn't fail waiting functions
box.schema.func.reload("reload")
fio.copyfile(reload2_path, reload_path)
box.schema.func.reload("reload")
c:call("reload.foo")
while box.space.test:count() < 2 * fibers + 1 do fiber.sleep(0.001) end
box.space.test:select{}
box.schema.func.drop("reload.foo")
box.space.test:drop()
fio.copyfile(reload1_path, reload_path)
box.schema.func.create('reload.test_reload', {language = "C"})
box.schema.user.grant('guest', 'execute', 'function', 'reload.test_reload')
s = box.schema.space.create('test_reload')
_ = s:create_index('pk')
box.schema.user.grant('guest', 'read,write', 'space', 'test_reload')
ch = fiber.channel(2)
-- call first time to load function
c:call("reload.test_reload")
s:delete({1})
fio.copyfile(reload2_path, reload_path)
_ = fiber.create(function() ch:put(c:call("reload.test_reload")) end)
while s:get({1}) == nil do fiber.yield(0.0001) end
box.schema.func.reload("reload")
_ = fiber.create(function() ch:put(c:call("reload.test_reload")) end)
_ = ch:get()
_ = ch:get()
s:drop()
box.schema.func.create('reload.test_reload_fail', {language = "C"})
box.schema.user.grant('guest', 'execute', 'function', 'reload.test_reload_fail')
c:call("reload.test_reload_fail")
fio.copyfile(reload1_path, reload_path)
c:call("reload.test_reload")
c:call("reload.test_reload_fail")
box.schema.func.reload()
box.schema.func.reload("non-existing")
-- Make sure that $TMPDIR env variable is used to generate temporary
-- path for DSO copy
os.setenv("TMPDIR", "/dev/null")
_, err = pcall(box.schema.func.reload, "reload")
tostring(err):gsub(': [/%w]+:', ':')
os.setenv("TMPDIR", nil)
box.schema.func.drop("reload.test_reload")
box.schema.func.drop("reload.test_reload_fail")
_ = fio.unlink(reload_path)
|
--------------------------------
---- Created by Cheglalw83 -----
--------------------------------
Locales['fr'] = {
['vending'] = 'Attend un peu.',
['machine'] = 'Machine à boissons',
['machines'] = 'Machine à boissons',
['press_context'] = 'Appuyez sur ~INPUT_CONTEXT~ pour acheter dans la machine',
['bought'] = 'Merci de ton achat (-1$)',
['not_enough'] = 'Tu n\'a pas assez d\'argent',
['player_cannot_hold'] = 'vous n'avez ~r~pas~s~ assez d'~y~espace libre~s~ dans votre inventaire !',
['refreshment'] = 'Vous avez apprécié un bon rafraîchissement',
['broken'] = 'Machine cassé',
['out_of_product'] = 'Plus aucun produit',
['other_problem'] = 'La machine c'est coincée et a pris votre argent.',
} |
local beautiful = require('beautiful')
local gears = require('gears')
local icons = require('theme.icons')
local theme_dir = gears.filesystem.get_configuration_dir() .. 'theme/'
local xresources = beautiful.xresources
local colors = xresources.get_current_theme()
local dpi = xresources.apply_dpi
local theme = {
--#region Directories
dir = theme_dir,
icons_dir = theme_dir .. 'icons/',
--#endregion
--#region Wallpaper & Icons
icons = icons,
--#endregion
--#region Colors
background = colors.background,
foreground = colors.foreground,
transparent = colors.background .. '00',
opacity = '66',
black = colors.color0,
dark_gray = colors.color8,
dark_red = colors.color1,
light_red = colors.color9,
dark_green = colors.color2,
light_green = colors.color10,
dark_yellow = colors.color3,
light_yellow = colors.color11,
dark_blue = colors.color4,
light_blue = colors.color12,
dark_magenta = colors.color5,
light_magenta = colors.color13,
dark_cyan = colors.color6,
light_cyan = colors.color14,
light_gray = colors.color7,
white = colors.color15,
--#endregion
}
--#region Color Theme
theme.primary = theme.dark_blue
theme.success = theme.dark_green
theme.danger = theme.dark_red
theme.warning = theme.dark_yellow
theme.disabled = theme.foreground .. theme.opacity
theme.highlight = theme.light_gray .. 28
theme.bg_focus = theme.background
theme.bg_minimize = theme.background
theme.bg_normal = theme.background
theme.bg_urgent = theme.dark_red
theme.fg_focus = theme.foreground
theme.fg_minimize = theme.foreground
theme.fg_normal = theme.foreground
theme.fg_urgent = theme.foreground
--#endregion
--#region UI events
theme.leave_event = theme.transparent
theme.hover_event = theme.white .. '10'
theme.press_event = theme.white .. '15'
--#endregion
--#region Fonts
theme.base_font = 'Roboto Regular'
theme.font = theme.base_font .. ' 10'
theme.base_font_bold = 'Roboto Bold'
theme.nerd_font = 'FiraCode Nerd Font Mono'
--#endregion
--#region Borders
theme.border_focus = theme.primary
theme.border_marked = theme.background
theme.border_normal = theme.background
theme.border_radius = dpi(9)
theme.border_width = dpi(3)
theme.useless_gap = dpi(4)
theme.separator_color = theme.foreground
--#endregion
--#region Taglist
theme.taglist_spacing = dpi(3)
theme.taglist_font = theme.nerd_font .. ' 20'
theme.taglist_bg_empty = theme.transparent
theme.taglist_bg_focus = theme.primary
theme.taglist_bg_occupied = theme.transparent
theme.taglist_bg_urgent = theme.transparent
theme.taglist_bg_volatile = theme.transparent
theme.taglist_fg_empty = theme.foreground
theme.taglist_fg_focus = theme.background
theme.taglist_fg_occupied = theme.primary
theme.taglist_fg_urgent = theme.danger
theme.taglist_fg_volatile = theme.foreground
--#endregion
--#region Tasklist
theme.tasklist_font = theme.font
theme.tasklist_plain_task_name = true
theme.tasklist_bg_focus = theme.background
theme.tasklist_fg_focus = theme.foreground
theme.tasklist_fg_urgent = theme.foreground
--#endregion
--#region System tray
theme.bg_systray = '#242c39'
theme.systray_icon_spacing = dpi(10)
--#endregion
--#endregion
--#region Shapes
theme.rounded_rect = function(cr, w, h)
return gears.shape.rounded_rect(cr, w, h, dpi(12))
end
--#endregion
--#region Tooltips
theme.tooltip_align = 'bottom'
theme.tooltip_bg_color = theme.background
theme.tooltip_border_color = theme.highlight
theme.tooltip_border_width = dpi(2)
theme.tooltip_delay = 1
theme.tooltip_fg_color = theme.foreground
theme.tooltip_font = theme.nerd_font .. ' 10'
theme.tooltip_margins = dpi(8)
theme.tooltip_shape = theme.rounded_rect
--#endregion
--#region Hotkeys
theme.hotkeys_bg = theme.background
theme.hotkeys_border_color = theme.primary
theme.hotkeys_border_width = dpi(2)
theme.hotkeys_description_font = theme.font
theme.hotkeys_fg = theme.foreground
theme.hotkeys_font = theme.font_bold
theme.hotkeys_modifiers_fg = theme.foreground
theme.hotkeys_group_margin = dpi(20)
theme.hotkeys_opacity = theme.opacity
theme.hotkeys_shape = theme.rounded_rect
--#endregion
--#region Notifications
theme.notification_bg = theme.transparent
theme.notification_border_color = theme.primary
theme.notification_border_width = dpi(0)
theme.notification_fg = theme.foreground
theme.notification_font = theme.font
theme.notification_icon_resize_strategy = 'center'
theme.notification_icon_size = dpi(32)
theme.notification_margin = dpi(6)
theme.notification_position = 'top_right'
theme.notification_shape = theme.rect
theme.notification_spacing = dpi(12)
--#endregion
--#region Menu
theme.menu_bg_normal = theme.background
theme.menu_bg_focus = theme.background
theme.menu_fg_normal = theme.foreground
theme.menu_fg_focus = theme.foreground
theme.menu_border_color = theme.primary
theme.menu_border_width = dpi(1)
theme.menu_height = dpi(34)
theme.menu_width = dpi(200)
--#endregion
--#region Layout
theme.layout_floating = theme.icons.layout_floating
theme.layout_fullscreen = theme.icons.layout_max
theme.layout_max = theme.icons.layout_max
theme.layout_dwindle = theme.icons.layout_tiled
theme.layout_tile = theme.icons.layout_tiled
theme.layout_tileleft = theme.icons.layout_tiled
theme.layout_tileright = theme.icons.layout_tiled
theme.layout_tilebottom = theme.icons.layout_tiled
theme.layout_tiletop = theme.icons.layout_tiled
theme.layout_fairv = theme.icons.layout_tiled
theme.layout_fairh = theme.icons.layout_tiled
theme.layout_spiral = theme.icons.layout_tiled
theme.layout_magnifier = theme.icons.layout_tiled
theme.layout_cornernw = theme.icons.layout_tiled
theme.layout_cornerne = theme.icons.layout_tiled
theme.layout_cornersw = theme.icons.layout_tiled
theme.layout_cornerse = theme.icons.layout_tiled
--#endregion
--#region Widgets
theme.widget_spacing = dpi(3)
theme.icon_spacing = dpi(7)
--#endregion
return theme
|
--[[
actionBar.lua
the code for Dominos action bars and buttons
--]]
--[[ globals ]]--
local Dominos = _G['Dominos']
local ActionButton = Dominos.ActionButton
local HiddenFrame = CreateFrame('Frame'); HiddenFrame:Hide()
local MAX_BUTTONS = 120
local ceil = math.ceil
local min = math.min
local format = string.format
--[[ Action Bar ]]--
local ActionBar = Dominos:CreateClass('Frame', Dominos.Frame); Dominos.ActionBar = ActionBar
--metatable magic. Basically this says, 'create a new table for this index'
--I do this so that I only create page tables for classes the user is actually playing
ActionBar.defaultOffsets = {
__index = function(t, i)
t[i] = {}
return t[i]
end
}
--metatable magic. Basically this says, 'create a new table for this index, with these defaults'
--I do this so that I only create page tables for classes the user is actually playing
ActionBar.mainbarOffsets = {
__index = function(t, i)
local pages = {
page2 = 1,
page3 = 2,
page4 = 3,
page5 = 4,
page6 = 5,
}
if i == 'DRUID' then
pages.cat = 6
pages.bear = 8
pages.moonkin = 9
pages.tree = 7
elseif i == 'WARRIOR' then
pages.battle = 6
pages.defensive = 7
-- pages.berserker = 8
elseif i == 'PRIEST' then
pages.shadow = 6
elseif i == 'ROGUE' then
pages.stealth = 6
pages.shadowdance = 6
elseif i == 'MONK' then
pages.tiger = 6
pages.ox = 7
pages.serpent = 8
end
t[i] = pages
return pages
end
}
ActionBar.class = select(2, UnitClass('player'))
local active = {}
function ActionBar:New(id)
local f = self.super.New(self, id)
f.sets.pages = setmetatable(f.sets.pages, f.id == 1 and self.mainbarOffsets or self.defaultOffsets)
f.pages = f.sets.pages[f.class]
f.baseID = f:MaxLength() * (id-1)
f:LoadButtons()
f:LoadStateController()
f:UpdateClickThrough()
f:UpdateStateDriver()
f:Layout()
f:UpdateGrid()
f:UpdateRightClickUnit()
f:SetScript('OnSizeChanged', self.OnSizeChanged)
f:UpdateFlyoutDirection()
active[id] = f
return f
end
function ActionBar:OnSizeChanged()
if not InCombatLockdown() then
self:UpdateFlyoutDirection()
end
end
--TODO: change the position code to be based more on the number of action bars
function ActionBar:GetDefaults()
local defaults = {}
defaults.point = 'BOTTOM'
defaults.x = 0
defaults.y = 40*(self.id-1)
defaults.pages = {}
defaults.spacing = 4
defaults.padW = 2
defaults.padH = 2
defaults.numButtons = self:MaxLength()
return defaults
end
function ActionBar:Free()
active[self.id] = nil
self.super.Free(self)
end
--returns the maximum possible size for a given bar
function ActionBar:MaxLength()
return floor(MAX_BUTTONS / Dominos:NumBars())
end
--[[ button stuff]]--
function ActionBar:LoadButtons()
for i = 1, self:NumButtons() do
local b = ActionButton:New(self.baseID + i)
if b then
b:SetParent(self.header)
b:SetFlyoutDirection(self:GetFlyoutDirection())
self.buttons[i] = b
else
break
end
end
self:UpdateActions()
end
function ActionBar:AddButton(i)
local b = ActionButton:New(self.baseID + i)
if b then
self.buttons[i] = b
b:SetParent(self.header)
b:SetFlyoutDirection(self:GetFlyoutDirection())
b:LoadAction()
self:UpdateAction(i)
self:UpdateGrid()
end
end
function ActionBar:RemoveButton(i)
local b = self.buttons[i]
self.buttons[i] = nil
b:Free()
end
--[[ Paging Code ]]--
function ActionBar:SetOffset(stateId, page)
self.pages[stateId] = page
self:UpdateStateDriver()
end
function ActionBar:GetOffset(stateId)
return self.pages[stateId]
end
-- note to self:
-- if you leave a ; on the end of a statebutton string, it causes evaluation issues,
-- especially if you're doing right click selfcast on the base state
function ActionBar:UpdateStateDriver()
UnregisterStateDriver(self.header, 'page', 0)
local header = ''
for i, state in Dominos.BarStates:getAll() do
local stateId = state.id
local condition
if type(state.value) == 'function' then
condition = state.value()
else
condition = state.value
end
if self:GetOffset(stateId) then
header = header .. condition .. 'S' .. i .. ';'
end
end
if header ~= '' then
RegisterStateDriver(self.header, 'page', header .. 0)
end
self:UpdateActions()
self:RefreshActions()
end
do
local function ToValidID(id)
return (id - 1) % MAX_BUTTONS + 1
end
--updates the actionID of a given button for all states
function ActionBar:UpdateAction(i)
local b = self.buttons[i]
local maxSize = self:MaxLength()
b:SetAttribute('button--index', i)
for i, state in Dominos.BarStates:getAll() do
local offset = self:GetOffset(state.id)
local actionId = nil
if offset then
actionId = ToValidID(b:GetAttribute('action--base') + offset * maxSize)
end
b:SetAttribute('action--S' .. i, actionId)
end
end
end
--updates the actionID of all buttons for all states
function ActionBar:UpdateActions()
for i = 1, #self.buttons do
self:UpdateAction(i)
end
end
function ActionBar:LoadStateController()
self.header:SetAttribute('_onstate-overridebar', [[
self:RunAttribute('updateState')
]])
self.header:SetAttribute('_onstate-overridepage', [[
self:RunAttribute('updateState')
]])
self.header:SetAttribute('_onstate-page', [[
self:RunAttribute('updateState')
]])
self.header:SetAttribute('updateState', [[
local state
if self:GetAttribute('state-overridepage') > 10 and self:GetAttribute('state-overridebar') then
state = 'override'
else
state = self:GetAttribute('state-page')
end
control:ChildUpdate('action', state)
]])
self:UpdateOverrideBar()
end
function ActionBar:RefreshActions()
self.header:Execute([[ self:RunAttribute('updateState') ]])
end
function ActionBar:UpdateOverrideBar()
local isOverrideBar = self:IsOverrideBar()
self.header:SetAttribute('state-overridebar', isOverrideBar)
end
--returns true if the possess bar, false otherwise
function ActionBar:IsOverrideBar()
return self == Dominos:GetOverrideBar()
end
--Empty button display
function ActionBar:ShowGrid()
for _,b in pairs(self.buttons) do
b:SetAttribute('showgrid', b:GetAttribute('showgrid') + 1)
b:UpdateGrid()
end
end
function ActionBar:HideGrid()
for _,b in pairs(self.buttons) do
b:SetAttribute('showgrid', max(b:GetAttribute('showgrid') - 1, 0))
b:UpdateGrid()
end
end
function ActionBar:UpdateGrid()
if Dominos:ShowGrid() then
self:ShowGrid()
else
self:HideGrid()
end
end
---keybound support
function ActionBar:KEYBOUND_ENABLED()
self:ShowGrid()
end
function ActionBar:KEYBOUND_DISABLED()
self:HideGrid()
end
--right click targeting support
function ActionBar:UpdateRightClickUnit()
self.header:SetAttribute('*unit2', Dominos:GetRightClickUnit())
end
--utility functions
function ActionBar:ForAll(method, ...)
for _,f in pairs(active) do
f[method](f, ...)
end
end
function ActionBar:OnSetAlpha(alpha)
if not self.buttons then return end
local transparent = alpha <= 0
if self.transparent ~= transparent then
self.transparent = transparent
self:UpdateCooldownOpacities()
end
end
function ActionBar:UpdateCooldownOpacities()
if self.transparent then
-- hide cooldown frames on transparent buttons by sticking them onto a different parent
for i, button in pairs(self.buttons) do
button.cooldown:SetParent(HiddenFrame)
end
else
-- show cooldown frames on non transparent buttons
for i, button in pairs(self.buttons) do
if button.cooldown:GetParent() ~= button then
button.cooldown:SetParent(button)
ActionButton_UpdateCooldown(button)
end
end
end
end
--[[ flyout direction updating ]]--
function ActionBar:GetFlyoutDirection()
local w, h = self:GetSize()
local isVertical = w < h
local anchor = self:GetPoint()
if isVertical then
if anchor and anchor:match('LEFT') then
return 'RIGHT'
end
return 'LEFT'
end
if anchor and anchor:match('TOP') then
return 'DOWN'
end
return 'UP'
end
function ActionBar:UpdateFlyoutDirection()
if self.buttons then
local direction = self:GetFlyoutDirection()
--dear blizzard, I'd like to be able to use the useparent-* attribute stuff for this
for _,b in pairs(self.buttons) do
b:SetFlyoutDirection(direction)
end
end
end
function ActionBar:SavePosition()
Dominos.Frame.SavePosition(self)
self:UpdateFlyoutDirection()
end
--right click menu code for action bars
--TODO: Probably enable the showstate stuff for other bars, since every bar basically has showstate functionality for 'free'
do
local L
--state slider template
local function ConditionSlider_OnShow(self)
self:SetMinMaxValues(-1, Dominos:NumBars() - 1)
self:SetValue(self:GetParent().owner:GetOffset(self.stateId) or -1)
self:UpdateText(self:GetValue())
if self.stateTextFunc then
_G[self:GetName() .. 'Text']:SetText(self.stateTextFunc())
end
end
local function ConditionSlider_UpdateValue(self, value)
self:GetParent().owner:SetOffset(self.stateId, (value > -1 and value) or nil)
end
local function ConditionSlider_UpdateText(self, value)
if value > -1 then
local page = (self:GetParent().owner.id + value - 1) % Dominos:NumBars() + 1
self.valText:SetFormattedText(L.Bar, page)
else
self.valText:SetText(DISABLE)
end
end
local function ConditionSlider_New(panel, stateId, text)
local s = panel:NewSlider(stateId, 0, 1, 1)
s.OnShow = ConditionSlider_OnShow
s.UpdateValue = ConditionSlider_UpdateValue
s.UpdateText = ConditionSlider_UpdateText
s.stateId = stateId
s:SetWidth(s:GetWidth() + 28)
local title = _G[s:GetName() .. 'Text']
title:ClearAllPoints()
title:SetPoint('BOTTOMLEFT', s, 'TOPLEFT')
title:SetJustifyH('LEFT')
if type(text) == 'function' then
s.stateTextFunc = text
else
title:SetText(text or L['State_' .. stateId:upper()])
end
local value = s.valText
value:ClearAllPoints()
value:SetPoint('BOTTOMRIGHT', s, 'TOPRIGHT')
value:SetJustifyH('RIGHT')
return s
end
local function AddLayout(self)
local p = self:AddLayoutPanel()
local size = p:NewSlider(L.Size, 1, 1, 1)
size.OnShow = function(self)
self:SetMinMaxValues(1, self:GetParent().owner:MaxLength())
self:SetValue(self:GetParent().owner:NumButtons())
end
size.UpdateValue = function(self, value)
self:GetParent().owner:SetNumButtons(value)
_G[self:GetParent():GetName() .. L.Columns]:OnShow()
end
end
local function AddAdvancedLayout(self)
self:AddAdvancedPanel()
end
--GetSpellInfo(spellID) is awesome for localization
local function addStatePanel(self, name, type)
local states = Dominos.BarStates:map(function(s) return s.type == type end)
if #states > 0 then
local p = self:NewPanel(name)
--HACK: Make the state panel wider for monks
-- since their stances have long names
local playerClass = select(2, UnitClass('player'))
local hasLongStanceNames = playerClass == 'MONK' or playerClass == 'ROGUE' or playerClass == 'DRUID'
for i = #states, 1, -1 do
local state = states[i]
local slider = ConditionSlider_New(p, state.id, state.text)
if hasLongStanceNames then
slider:SetWidth(slider:GetWidth() + 48)
end
end
if hasLongStanceNames then
p.width = 228
end
end
end
local function AddClass(self)
addStatePanel(self, UnitClass('player'), 'class')
end
local function AddPaging(self)
addStatePanel(self, L.QuickPaging, 'page')
end
local function AddModifier(self)
addStatePanel(self, L.Modifiers, 'modifier')
end
local function AddTargeting(self)
addStatePanel(self, L.Targeting, 'target')
end
local function AddShowState(self)
local p = self:NewPanel(L.ShowStates)
p.height = 56
local editBox = CreateFrame('EditBox', p:GetName() .. 'StateText', p, 'InputBoxTemplate')
editBox:SetWidth(148) editBox:SetHeight(20)
editBox:SetPoint('TOPLEFT', 12, -10)
editBox:SetAutoFocus(false)
editBox:SetScript('OnShow', function(self)
self:SetText(self:GetParent().owner:GetShowStates() or '')
end)
editBox:SetScript('OnEnterPressed', function(self)
local text = self:GetText()
self:GetParent().owner:SetShowStates(text ~= '' and text or nil)
end)
editBox:SetScript('OnEditFocusLost', function(self) self:HighlightText(0, 0) end)
editBox:SetScript('OnEditFocusGained', function(self) self:HighlightText() end)
local set = CreateFrame('Button', p:GetName() .. 'Set', p, 'UIPanelButtonTemplate')
set:SetWidth(30) set:SetHeight(20)
set:SetText(L.Set)
set:SetScript('OnClick', function(self)
local text = editBox:GetText()
self:GetParent().owner:SetShowStates(text ~= '' and text or nil)
editBox:SetText(self:GetParent().owner:GetShowStates() or '')
end)
set:SetPoint('BOTTOMRIGHT', -8, 2)
return p
end
function ActionBar:CreateMenu()
local menu = Dominos:NewMenu(self.id)
L = LibStub('AceLocale-3.0'):GetLocale('Dominos-Config')
AddLayout(menu)
AddClass(menu)
AddPaging(menu)
AddModifier(menu)
AddTargeting(menu)
AddShowState(menu)
AddAdvancedLayout(menu)
ActionBar.menu = menu
end
end
--[[ Action Bar Controller ]]--
local ActionBarController = Dominos:NewModule('ActionBars', 'AceEvent-3.0')
function ActionBarController:Load()
self:RegisterEvent('UPDATE_BONUS_ACTIONBAR', 'UpdateOverrideBar')
self:RegisterEvent('UPDATE_VEHICLE_ACTIONBAR', 'UpdateOverrideBar')
self:RegisterEvent('UPDATE_OVERRIDE_ACTIONBAR', 'UpdateOverrideBar')
for i = 1, Dominos:NumBars() do
ActionBar:New(i)
end
end
function ActionBarController:Unload()
self:UnregisterAllEvents()
for i = 1, Dominos:NumBars() do
Dominos.Frame:ForFrame(i, 'Free')
end
end
function ActionBarController:UpdateOverrideBar()
if InCombatLockdown() or (not Dominos.OverrideController:OverrideBarActive()) then
return
end
local overrideBar = Dominos:GetOverrideBar()
for _, button in pairs(overrideBar.buttons) do
ActionButton_Update(button)
end
end
|
-- scaffolding entry point for EASTL
return dofile("EASTL.lua")
|
return {'zich','zicht','zichtas','zichtbaar','zichtbaarheid','zichten','zichter','zichtlijn','zichtlocatie','zichtlocaties','zichtrekening','zichtzending','zichzelf','zichttermijn','zichtveld','zichtdekking','zichtvermogen','zichtzijde','zichtbeton','zichem','zico','zichtbaarder','zichtbaars','zichtbaarst','zichtbare','zichters','zichthouders','zichtlijnen','zichtte','zichtzendingen','zichtrekeningen','zicos'} |
package 'gluon-web-mesh-vpn-fastd'
entry({"admin", "mesh_vpn_fastd"}, model("admin/mesh_vpn_fastd"), _("Mesh VPN"), 50)
|
fx_version "cerulean"
games {"gta5"}
dependencies {
'yarn',
'PolyZone'
}
files {
'nui/ui.html',
'nui/ui.css',
'nui/ui.js'
}
ui_page "nui/ui.html"
-- Common Scripts
client_scripts {
'@PolyZone/client.lua',
'@PolyZone/BoxZone.lua',
'@PolyZone/EntityZone.lua',
'@PolyZone/CircleZone.lua',
'@PolyZone/ComboZone.lua'
}
client_script 'client.lua'
server_script 'server.lua' |
describe("TestAttacks", function()
before_each(function()
newBuild()
end)
teardown(function()
-- newBuild() takes care of resetting everything in setup()
end)
it("adds envy, ensures +1 level keeps level 25 Envy", function()
build.itemsTab:CreateDisplayItemFromRaw("New Item\nAssassin Bow\nGrants Level 1 Summon Raging Spirit\nGrants Level 25 Envy Skill")
build.itemsTab:AddDisplayItem()
runCallback("OnFrame")
assert.are.equals(205, build.calcsTab.mainEnv.minion.modDB:Sum("BASE", build.calcsTab.mainEnv.minion.mainSkill.skillCfg, "ChaosMin"))
build.skillsTab:PasteSocketGroup("Slot: Weapon 1\nAwakened Generosity 4/0 Default 1\n")
runCallback("OnFrame")
assert.are.equals(round(205 * 1.43), build.calcsTab.mainEnv.minion.modDB:Sum("BASE", build.calcsTab.mainEnv.minion.mainSkill.skillCfg, "ChaosMin"))
build.skillsTab:PasteSocketGroup("Slot: Weapon 1\nAwakened Generosity 5/0 Default 1\n")
runCallback("OnFrame")
-- No Envy level increase, so base should still be 205
assert.are.equals(round(205 * 1.44), build.calcsTab.mainEnv.minion.modDB:Sum("BASE", build.calcsTab.mainEnv.minion.mainSkill.skillCfg, "ChaosMin"))
end)
end) |
qtun = {
log = {
syslog = function (level, fmt, ...)
_syslog(level, string.format(fmt, ...))
end
}
}
function trim(s)
return s:gsub('^%s*(.-)%s*$', '%1')
end
function is_numeric(s)
return tonumber(s) ~= nil
end
function is_string(s)
return not is_numeric(s)
end |
SetSunLightingCommand = Command:extends{}
SetSunLightingCommand.className = "SetSunLightingCommand"
function SetSunLightingCommand:init(opts)
self.opts = opts
self._execute_unsynced = true
self.mergeCommand = "MergedCommand"
end
function SetSunLightingCommand:execute()
if not self.old then
self.old = {
groundDiffuseColor = {gl.GetSun("diffuse")},
groundAmbientColor = {gl.GetSun("ambient")},
groundSpecularColor = {gl.GetSun("specular")},
groundShadowDensity = gl.GetSun("shadowDensity"),
unitDiffuseColor = {gl.GetSun("diffuse", "unit")},
unitAmbientColor = {gl.GetSun("ambient", "unit")},
unitSpecularColor = {gl.GetSun("specular", "unit")},
modelShadowDensity = gl.GetSun("shadowDensity", "unit"),
}
end
Spring.SetSunLighting(self.opts)
end
function SetSunLightingCommand:unexecute()
Spring.SetSunLighting(self.old)
end
|
require "string_helper"
local M = {}
--print((" asd sad a dsa "):trim() .. ',')
M.escape = function ( data , doTrim)
if data and type(data) == 'string' then
return data:gsub("[<>&\"]",
{
["&"]="&", --特殊符号必须用[]
["<"]="<",
[">"]=">",
["\""]="""
}
):trim(doTrim)
end
return data
end
M.buildTag = function ( tagName, attribs , subtags, inline, indents)
if inline == nil then
inline = false
end
if indents == nil then
indents = 0
end
local tag = {}
tag[#tag+1] = string.rep('\t', indents)
tag[#tag+1] = "<"
tag[#tag+1] = tagName
for k,v in pairs(attribs) do
tag[#tag+1] = " "
tag[#tag+1] = k
tag[#tag+1] = "="
tag[#tag+1] = "\""
tag[#tag+1] = M.escape(v)
tag[#tag+1] = "\""
end
tag[#tag+1] = ">"
if inline == false then
tag[#tag+1] = "\n"
end
if subtags then
tag[#tag+1] = subtags --M.escape (subtags)
if inline == false then
tag[#tag+1] = "\n"
end
end
if not inline then
tag[#tag+1] = string.rep('\t', indents)
end
tag[#tag+1] = "</"
tag[#tag+1] = tagName
tag[#tag+1] = ">"
return table.concat( tag )
end
--[[
options:{ 1=male ,2=female,...}
]]
M.buildSelectTag = function ( attribs , options , indents)
local optionTags = {}
if indents == nil then
indents = 0
end
local selectedValue = attribs.value
for k,v in pairs(options) do
if selectedValue == k then
optionTags[#optionTags + 1] = M.buildTag( "option", {value=M.escape(v), selected="selected"} , M.escape(v), true, indents+1 )
else
optionTags[#optionTags + 1] = M.buildTag( "option", {value=M.escape(v)} , M.escape(v), true, indents+1 )
end
end
return M.buildTag( "select", attribs , table.concat( optionTags, "\n"), false, indents)
end
M.buildInputTag = function ( type, attribs ,indents)
attribs.type=type
return M.buildTag( "input", attribs , nil, true, indents)
end
M.createTableFromText = function ( tsv , firstLineAsTitle, attribs)
end
M.createTable = function ( t , attribs)
local tb = {}
local trs = {}
local indents = 1
for k,v in pairs(t) do
local tdk = M.buildTag("td",{} , M.escape(k) , true, indents + 2)
local tdv = M.buildTag("td",{} , M.escape(v) , true, indents + 2)
trs[#trs+1] = M.buildTag("tr",{} ,tdk .. '\n' .. tdv , false, indents + 1)
end
tb[#tb+1] = M.buildTag("tbody",{} ,table.concat( trs, "\n") , false, indents)
return M.buildTag("table",attribs ,table.concat( tb, "\n") , false)
end
M.createList = function ( list , attribs )
--[[
if delim == nil then
delim = "\n"
end
]]
local lis = {}
for v in list:gmatch("[^\n]+") do
v = v:trim()
if v ~= '' then
lis[#lis+1] = M.buildTag("li",{} , M.escape(v) , true, 1)
end
end
return M.buildTag("ul" ,attribs, table.concat( lis, "\n") , false)
end
--[[
M.test = function( )
local tag = M.buildTag('input',
{id="order_id",name="order_name", type="text", value="1232321313"},
M.escape("测试<abc\"de&f> ") ,
true)
return tag
end
--]]
--print(M.buildSelectTag({name="test",id="sel" }, {M="male", F="female"}))
print(
M.createList([[
接入间名称
交接箱编码
主干
直列
]] , { class="menu"} )
)
print(
M.createTable( {server="tomcat", version=" 1.3 "} , { class="form_table", border=1} )
)
return M
|
hook.Add("Initialize", "gmod_tool_override", function()
local SWEP = weapons.GetStored("gmod_tool")
function SWEP:DoShootEffect(hitpos, hitnormal, entity, physbone, bFirstTimePredicted)
local left = math.random(1, 2) == 1
local snd
if left then
snd = "npc/stalker/stalker_footstep_left" .. math.random(1, 2) .. ".wav"
else
snd = "npc/stalker/stalker_footstep_right" .. math.random(1, 2) .. ".wav"
end
self:EmitSound(snd, 75, math.random(96, 104), 1)
self:SendWeaponAnim(ACT_VM_PRIMARYATTACK) -- View model animation
-- There's a bug with the model that's causing a muzzle to
-- appear on everyone's screen when we fire this animation.
self.Owner:SetAnimation(PLAYER_ATTACK1) -- 3rd Person Animation
if not bFirstTimePredicted then return end
local effectdata = EffectData()
effectdata:SetOrigin(hitpos)
effectdata:SetNormal(hitnormal)
effectdata:SetEntity(entity)
effectdata:SetAttachment(physbone)
util.Effect("selection_indicator", effectdata)
local effectdata = EffectData()
effectdata:SetOrigin(hitpos)
effectdata:SetStart(self.Owner:GetShootPos())
effectdata:SetAttachment(1)
effectdata:SetEntity(self)
util.Effect("ToolTracer", effectdata)
end
end)
if GAMEMODE then
hook.GetTable().Initialize.gmod_tool_override()
end
|
tigris.mobs.register("tigris_mobs_monsters:wolf", {
description = "Wolf",
collision = {-0.4, -0.4, -0.4, 0.4, 0.4, 0.4},
box = {
{-0.25, 0, -0.5, 0.25, 0.6, 0.5},
{-0.25, -0.5, -0.5, -0.1, 0, -0.35},
{0.1, -0.5, -0.5, 0.25, 0, -0.35},
{-0.25, -0.5, 0.35, -0.1, 0, 0.5},
{0.1, -0.5, 0.35, 0.25, 0, 0.5},
{-0.25, 0, -0.5, 0.25, 0.5, -0.75},
{-0.25, 0, -0.5, 0.25, 0.25, -1.2},
{-0.1, 0.4, 0.5, 0.1, 0.5, 0.75},
},
textures = {
"wool_dark_grey.png",
"wool_dark_grey.png",
"wool_dark_grey.png",
"wool_dark_grey.png",
"wool_dark_grey.png",
"wool_dark_grey.png^tigris_mobs_wolf_face.png",
},
group = "hunters",
level = 2,
drops = {
{100, "mobs:meat_raw"},
{100, "tigris_mobs:bone"},
{100, "tigris_mobs:fang"},
{25, "tigris_mobs:fang"},
{25, "tigris_mobs:eye"},
{15, "tigris_mobs:eye"},
},
habitat_nodes = {"group:soil"},
on_init = function(self, data)
self.hp_max = 6
data.jump = 5
data.speed = 3.5
data.fast_speed = 4
data.damage = {fleshy = 2}
data.regen = 5
end,
start = "wander",
script = tigris.mobs.common.hunter(),
})
tigris.mobs.register_spawn("tigris_mobs_monsters:wolf", {
ymax = tigris.world_limits.max.y,
ymin = -24,
light_min = 0,
light_max = minetest.LIGHT_MAX,
chance = 20000,
nodes = {"group:soil"},
})
|
local kAddonName, addon = ...
addon.actions = {}
local L = LibStub('AceLocale-3.0'):GetLocale(kAddonName)
addon.actions.commandExecutor = _G.ChatEdit_SendText
addon.actions.delayedCommandExecutor = _G.C_Timer.After
local actionEditbox = _G.CreateFrame('EditBox', kAddonName .. '_ActionEditBox')
actionEditbox:Hide()
local function getLanguageID(target)
target = target:lower()
for i = 1, _G.GetNumLanguages() do
local language, languageID = _G.GetLanguageByIndex(i)
if language:lower() == target then
return languageID
end
end
return nil
end
local function execCommand(command)
local normalizedCommand = command
local language, rest = command:match('^%[(.-)%]%s*(.+)')
actionEditbox.languageID = nil
if language and rest then
actionEditbox.languageID = getLanguageID(language)
normalizedCommand = rest
end
actionEditbox:SetText(normalizedCommand)
local success, err = pcall(addon.actions.commandExecutor, actionEditbox)
if not success then
addon.utils.softerror('Failed to run command\nCommand: %s\nError: %s', command, err)
end
end
local function execDelayedCommand(command, delay)
local function exec()
execCommand(command)
end
addon.actions.delayedCommandExecutor(delay, exec)
end
local function normalizeFieldName(name)
return name:gsub('%s', ''):lower()
end
local function normalizeFields(fields)
local normalized = {}
for name, value in pairs(fields) do
local normalizedName = normalizeFieldName(name)
normalized[normalizedName] = value
end
return normalized
end
local function fillCommandFields(command, fields)
local function replaceToken(match, fieldName)
local normalizedName = normalizeFieldName(fieldName)
return tostring(fields[normalizedName] or match)
end
return (command:gsub('({(.-)})', replaceToken))
end
local function runGroup(group, fields)
for _, action in ipairs(group.actions) do
local command = fillCommandFields(action.command, fields)
if #command > 0 then
execDelayedCommand(command, action.delay)
end
end
end
local function compareByAllowedTime(left, right)
if left.group.allowedTime == right.group.allowedTime then
return left.index < right.index
end
return left.group.allowedTime < right.group.allowedTime
end
local function sortGroupsByOldestAllowedTime(groups)
local sortable = {}
for i, group in ipairs(groups) do
table.insert(sortable, {index = i, group = group})
end
table.sort(sortable, compareByAllowedTime)
return sortable
end
local function runGroups(groups, fields, globalAllowedTime)
local now = addon.utils.now()
local sorted = sortGroupsByOldestAllowedTime(groups)
local alwaysIndexes = {}
local cooldownIndex = nil
for _, item in ipairs(sorted) do
if item.group.ignoreGlobalCooldown or now > globalAllowedTime then
if item.group.cooldown == '0' then
table.insert(alwaysIndexes, item.index)
runGroup(item.group, fields)
elseif not cooldownIndex then
if now > item.group.allowedTime then
cooldownIndex = item.index
runGroup(item.group, fields)
end
end
end
end
return alwaysIndexes, cooldownIndex
end
function addon.actions.runEntry(entryIndex, fields)
local state = addon.store.getState()
local entry = state.entries[entryIndex]
local normalizedFields = normalizeFields(fields)
local alwaysIndexes, cooldownIndex = runGroups(
entry.actionGroups, normalizedFields, state.globalAllowedTime)
local didSomething = #alwaysIndexes > 0 or not not cooldownIndex
if didSomething then
addon.store.dispatch({
name = 'updateAllowedTime',
entryIndex = entryIndex,
actionGroupIndexes = {cooldownIndex},
})
end
return alwaysIndexes, cooldownIndex
end
function addon.actions.describe(groups)
if #groups == 0 then
return ('[%s]'):format(L['no actions configured'])
end
local fullDescription = {}
for _, group in ipairs(groups) do
local description = {}
for _, action in ipairs(group.actions) do
table.insert(description, action.command)
end
table.insert(fullDescription, table.concat(description, ' ' .. L['AND'] .. ' '))
end
return table.concat(fullDescription, ' ;; ')
end
function addon.actions.iterateExamples()
return ipairs({
{
name = 'Delayed speech',
group = {
actions = {
{delay = 0, command = '/say You...'},
{delay = 1, command = '/say ...shall not...'},
{delay = 2, command = '/say PASS!'},
},
},
},
})
end
|
local FunctionNode = require("luasnip.nodes.node").Node:new()
local util = require("luasnip.util.util")
local types = require("luasnip.util.types")
local function F(fn, args, ...)
return FunctionNode:new({
fn = fn,
args = util.wrap_value(args),
type = types.functionNode,
mark = nil,
user_args = { ... },
})
end
function FunctionNode:get_args()
local args = {}
for i, node in ipairs(self.args) do
args[i] = util.dedent(node:get_text(), self.parent.indentstr)
end
args[#args + 1] = self.parent
return args
end
function FunctionNode:input_enter()
vim.api.nvim_feedkeys(
vim.api.nvim_replace_termcodes("<Esc>", true, false, true),
"n",
true
)
util.normal_move_on_mark_insert(self.mark.id)
end
function FunctionNode:update()
local text = util.wrap_value(
self.fn(self:get_args(), unpack(self.user_args))
)
if vim.o.expandtab then
util.expand_tabs(text)
end
-- don't expand tabs in parent.indentstr, use it as-is.
self.parent:set_text(self, util.indent(text, self.parent.indentstr))
end
return {
F = F,
}
|
--This bot is heavily dependent on file operations, therefore this library exists.
local file = {}
local json
if pcall(import,"json") then
json = import("json")
elseif pcall(require,"json") then
json = require("json")
end
file.safe = true
file.read = function(filename,mode)
assert(type(filename) == "string","string expected, got "..type(filename))
local mode = mode or "*a"
local temp_file,err = io.open(filename,r)
if err then
if not file.safe then error(err) else
ret_string = ""
end
else
ret_string = temp_file:read(mode)
temp_file:close()
end
return ret_string,err
end
file.write = function(filename,write)
assert(type(filename) == "string", "string expected, got "..type(filename))
assert(type(write) == "string", "string expected for argument #2, got "..type(write))
local temp_file,err = io.open(filename,"w+")
local status = false
if err then
if not file.safe then error(err) else
status = false
end
else
temp_file:write(write)
temp_file:close()
status = true
end
return status,err
end
file.exists = function(filename)
local file = io.open(filename,"r")
if file then
file:close()
return true
else
return false
end
end
file.existsDir = function(filename)
local file = io.open(filename.."/stuff","w")
if file then
file:close()
os.remove(filename.."/stuff")
return true
else
return false
end
end
file.ls = function(path)
if file.existsDir(path) then
local ls_handle = io.popen("ls -1 "..path,"r")
local ls_data = ls_handle:read("*a")
ls_handle:close()
return ls_data
else
return false, "No such file or directory"
end
end
if json then
file.readJSON = function(filename,default)
assert(type(filename) == "string","string expected, got "..type(filename))
local json_data,err = file.read(filename,"*a")
local table_data, status
if err then
if not file.safe then error(err) else
status = err
table_data = default or {}
end
else
table_data,_,err = json.decode(json_data)
if not table_data then
if not file.safe then error(err) else
status = err
table_data = default or {}
end
end
end
return table_data, status
end
file.writeJSON = function(filename,table_data)
assert(type(filename) == "string","string expected, got "..type(filename))
assert(type(table_data) == "table","table expected, got "..type(table_data))
local status = false
local status,json_object,_,err = pcall(function() return json.encode(table_data) end)
if not status then
if not file.safe then error(err) else
status = false
err = json_object
end
else
if json_object then
status,err = file.write(filename,json_object)
end
end
return status, err
end
end
return file
|
Ship = require "game/Ship"
-- Ship MODEL: WD-1
local WD1 = {}
WD1.__index = WD1
function WD1:create(world, player)
local ship = Ship:create(world, player)
-- Load ship image
ship.image = love.graphics.newImage("asset/ship1.png")
-- Create animation properties
ship.sprite = newAnimation(ship.image, 32, 32, 3.0)
-- Ship weapon
ship.weapon = Weapon:create(16, ship)
return ship
end
return WD1
|
-----------------------------------
-- Area: Port Bastok
-- NPC: Latifah
-- Involved in Quest: Stamp Hunt
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local StampHunt = player:getQuestStatus(BASTOK, tpz.quest.id.bastok.STAMP_HUNT)
if (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getCharVar("StampHunt_Mask"), 6) == false) then
player:startEvent(120)
else
player:startEvent(13)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 120) then
player:setMaskBit(player:getCharVar("StampHunt_Mask"), "StampHunt_Mask", 6, true)
end
end
|
local tArgs = { ... }
if not commands then
printError("Requires a Command Computer.")
return
end
if #tArgs == 0 then
local programName = arg[0] or fs.getName(shell.getRunningProgram())
printError("Usage: " .. programName .. " <command>")
return
end
local function printSuccess(text)
if term.isColor() then
term.setTextColor(colors.green)
end
print(text)
term.setTextColor(colors.white)
end
local sCommand = string.lower(tArgs[1])
for n = 2, #tArgs do
sCommand = sCommand .. " " .. tArgs[n]
end
local bResult, tOutput = commands.exec(sCommand)
if bResult then
printSuccess("Success")
if #tOutput > 0 then
for n = 1, #tOutput do
print(tOutput[n])
end
end
else
printError("Failed")
if #tOutput > 0 then
for n = 1, #tOutput do
print(tOutput[n])
end
end
end
|
me = game.Players.luxulux
char = me.Character
selected = false
attacking = false
hurt = false
DERPTRAIN = false
ULTRADURPMODE = false
if ULTRADURPMODE == true then
normaldmg = 1234567891011121314151617181920
normaldmg = 0
else
normaldmg = 1000
end
splashdmg = normaldmg * 2
dmg = normaldmg
function moo1()
local moan1=Instance.new("Sound")
moan1.Parent=workspace
moan1.SoundId="http://www.roblox.com/asset/?id=24902268"
moan1.Name="Moan1"
moan1.Pitch = math.random(1,10)*math.random()
moan1.PlayOnRemove = true
wait(0)
moan1.Parent = nil
local moan2=Instance.new("Sound")
moan2.Parent=script.Parent
moan2.SoundId="http://www.roblox.com/asset/?id=25495733"
moan2.Name="Moan2"
moan2.Pitch = 1
moan2.PlayOnRemove = true
wait(0)
moan2.Parent = nil
end
function moo2()
end
function screem()
local scream=Instance.new("Sound")
scream.Parent=script.Parent
scream.SoundId="http://www.roblox.com/asset/?id=25495733"
scream.Name="Scream"
scream.Pitch = 2.5
scream.PlayOnRemove = true
wait(0)
scream.Parent = nil
end
function getnoobs(pos,dist)
local stoof = {}
for _,v in pairs(workspace:children()) do
local h,t = v:findFirstChild("Humanoid"), v:findFirstChild("Torso")
if h ~= nil and t ~= nil and v:IsA("Model") and v ~= char then
if (t.Position - pos).magnitude < dist then
table.insert(stoof,v)
end
end
end
return stoof
end
function prop(part, parent, collide, tran, ref, x, y, z, color, anchor, form)
part.Parent = parent
part.formFactor = form
part.CanCollide = collide
part.Transparency = tran
part.Reflectance = ref
part.Size = Vector3.new(x,y,z)
part.BrickColor = BrickColor.new(color)
part.TopSurface = 0
part.BottomSurface = 0
part.Anchored = anchor
part.Locked = true
part:BreakJoints()
end
function weld(w, p, p1, a, b, c, x, y, z)
w.Parent = p
w.Part0 = p
w.Part1 = p1
w.C1 = CFrame.fromEulerAnglesXYZ(a,b,c) * CFrame.new(x,y,z)
end
rarm = char:findFirstChild("Right Arm")
larm = char:findFirstChild("Left Arm")
torso = char:findFirstChild("Torso")
hum = char:findFirstChild("Humanoid")
pcall(function() char.Lightsaber:remove() end)
mod = Instance.new("Model",char)
mod.Name = "Lightsaber"
hold = Instance.new("Part")
prop(hold,mod,false,1,0,0.5,0.5,0.5,1,false,"Custom")
hw = Instance.new("Weld")
weld(hw,rarm,hold,0,0,0,0,1,0)
main = Instance.new("Part")
prop(main,mod,false,0,0.04,0.44,2.1,0.44,"Really black",false,"Custom")
Instance.new("CylinderMesh",main)
wewe = Instance.new("Weld")
weld(wewe,hold,nil,math.pi/2,0,math.pi/2,0,0,0)
torsohold = Instance.new("Weld")
weld(torsohold,torso,main,0,0,math.rad(36)+math.pi,-1.1,-1.65,-0.8)
sp = Instance.new("Part")
prop(sp,mod,false,0,0,0.6,0.4,0.6,"Really red",false,"Custom")
Instance.new("CylinderMesh",sp)
w1 = Instance.new("Weld")
weld(w1,main,sp,0,0,0,0,0.8,0)
heh = Instance.new("Part")
prop(heh,mod,false,0,0,1,0.3,0.5,"Really red",false,"Custom")
w2 = Instance.new("Weld")
weld(w2,main,heh,0,0,0,0,-0.9,0)
Instance.new("CylinderMesh",heh)
blade = Instance.new("Part")
prop(blade,mod,false,0.5,0.5,0.44,3.50,0.50,"Toothpaste",false,"Custom")
w3 = Instance.new("Weld")
weld(w3,heh,blade,0,0,0,0,-blade.Size.Y/2,0)
blah = Instance.new("CylinderMesh",blade)
coroutine.resume(coroutine.create(function()
while true do
wait()
if ULTRADURPMODE == true then
blade.Reflectance = 0.5
blade.BrickColor = BrickColor.new(Color3.new(math.random(),math.random(),math.random()))
else
blade.BrickColor = BrickColor.new("Toothpaste")
end
end
end))
lols = {}
touchs = {}
table.insert(lols,blade)
table.insert(touchs,blade)
for i=blade.Size.Y/2,-blade.Size.Y/2,-0.2 do
local pf = Instance.new("Part")
prop(pf,mod,false,1,0,0.65,0.1,0.15,1,false,"Custom")
local wa = Instance.new("Weld")
weld(wa,blade,pf,0,0,0,0,i,0)
table.insert(touchs,pf)
end
rb = Instance.new("Part")
prop(rb,mod,false,1,0,0.5,0.5,0.5,1,false,"Custom")
rbw = Instance.new("Weld")
weld(rbw,torso,rb,0,0,0,-1.5,-0.5,0)
lb = Instance.new("Part")
prop(lb,mod,false,1,0,0.5,0.5,0.5,1,false,"Custom")
lbw = Instance.new("Weld")
weld(lbw,torso,lb,0,0,0,1.5,-0.5,0)
rw = Instance.new("Weld")
weld(rw,rb,nil,0,0,0,0,0.5,0)
lw = Instance.new("Weld")
weld(lw,lb,nil,0,0,0,0,0.5,0)
function showdmg(d)
local pa = Instance.new("Part")
prop(pa,mod,false,1,0,1,1,1,1,true,"Symmetric")
pa.CFrame = CFrame.new(blade.Position)
local bill = Instance.new("BillboardGui",pa)
bill.Size = UDim2.new(0,50,0,35)
bill.Adornee = pa
local tx = Instance.new("TextLabel",bill)
tx.Size = bill.Size
tx.Position = UDim2.new(0,0,0,-30)
tx.BackgroundTransparency = 1
tx.Text = d
tx.FontSize = "Size24"
tx.TextColor3 = Color3.new(0,0,0)
if ULTRADURPMODE == true then
if tx.Text ~= "TURDULATOR WAS HERE" or tx.Text ~= "LORD OF DARKNESS OLOL" then
coroutine.resume(coroutine.create(function()
while true do
wait()
tx.TextColor3 = Color3.new(math.random(),math.random(),math.random())
end
end))
end
end
local poz = pa.Position
for i=0,7,0.4 do
wait()
if ULTRADURPMODE == true then
pa.CFrame = CFrame.new(poz.X+math.random(-5,5), poz.Y+i+math.random(-5,5), poz.Z+math.random(-5,5))
else
pa.CFrame = CFrame.new(poz.X, poz.Y+i, poz.Z)
end
end
pa:remove()
end
function durpmsg(d)
local pa = Instance.new("Part")
prop(pa,mod,false,1,0,1,1,1,1,true,"Symmetric")
pa.CFrame = CFrame.new(blade.Position)
local bill = Instance.new("BillboardGui",pa)
bill.Size = UDim2.new(0,50,0,35)
bill.Adornee = pa
local tx = Instance.new("TextLabel",bill)
tx.Size = bill.Size
tx.Position = UDim2.new(0,0,0,-30)
tx.BackgroundTransparency = 1
tx.Text = d
tx.FontSize = "Size24"
tx.TextColor3 = Color3.new(0,0,0)
if ULTRADURPMODE == true then
coroutine.resume(coroutine.create(function()
while true do
wait()
tx.TextColor3 = Color3.new(math.random(),math.random(),math.random())
end
end))
end
local poz = pa.Position
for i=0,8,0.1 do
wait()
if ULTRADURPMODE == true then
pa.CFrame = CFrame.new(poz.X, poz.Y+i, poz.Z)
else
pa.CFrame = CFrame.new(poz.X, poz.Y+i, poz.Z)
end
end
pa:remove()
end
function derpmsg(d)
local pa = Instance.new("Part")
prop(pa,mod,false,1,0,1,1,1,1,true,"Symmetric")
pa.CFrame = CFrame.new(blade.Position)
local bill = Instance.new("BillboardGui",pa)
bill.Size = UDim2.new(0,50,0,35)
bill.Adornee = pa
local tx = Instance.new("TextLabel",bill)
tx.Size = bill.Size
tx.Position = UDim2.new(0,0,0,-30)
tx.BackgroundTransparency = 1
tx.Text = d
tx.FontSize = "Size24"
tx.TextColor3 = Color3.new(0,0,0)
local poz = pa.Position
for i=0,8,0.1 do
wait()
if ULTRADURPMODE == true then
pa.CFrame = CFrame.new(poz.X, poz.Y+i, poz.Z)
else
pa.CFrame = CFrame.new(poz.X, poz.Y+i, poz.Z)
end
end
pa:remove()
end
deb = true
function kill(h)
if hurt and deb then
local hu, to = h.Parent:findFirstChild("Humanoid"), h.Parent:findFirstChild("Torso")
if hu ~= nil and to ~= nil and h.Parent ~= char then
if hu.Health > 0 then
deb = false
local damg = math.random(dmg/4,dmg)
local chance = math.random(1,5)
if chance > 2 then
hu.PlatformStand = true
coroutine.resume(coroutine.create(function()
wait()
to.Velocity = CFrame.new(torso.Position, to.Position).lookVector * damg*2
wait(0.1)
hu.PlatformStand = false
end))
else
damg = 0
end
hu.Health = hu.Health - damg
coroutine.resume(coroutine.create(function()
-- showdmg("OVAR NINE THOUSAAAAAAND!!!")
-- showdmg(damg)
if ULTRADURPMODE == true then
moo1()
moo2()
-- screem()
for i = 0,5 do
coroutine.resume(coroutine.create(function()
LOLOL = math.random(1,101)
if LOLOL == 1 then
showdmg("OVAR NINE THOUSAAAAAAND!!!")
elseif LOLOL == 2 then
showdmg("ULTRADURP SLASH!")
elseif LOLOL == 3 then
showdmg("DINNUR")
elseif LOLOL == 4 then
showdmg("HERP DE DURP")
elseif LOLOL == 5 then
showdmg("IT'Z A BAGEL!")
elseif LOLOL == 6 then
showdmg("DERPDERPDERPDERPDERPDERPDERPDERP")
elseif LOLOL == 7 then
showdmg("BAGEL")
elseif LOLOL == 8 then
showdmg("IMMA FIRIN' MAH LAZOR")
elseif LOLOL == 9 then
showdmg("BLAAAAAARGH!")
elseif LOLOL == 10 then
showdmg("UMAD")
elseif LOLOL == 11 then
showdmg(math.huge)
elseif LOLOL == 12 then
showdmg("math.huge")
elseif LOLOL == 13 then
showdmg("ME BOTTOL O SCRUMPY")
elseif LOLOL == 14 then
showdmg("NEED A DISPENSER HERE")
elseif LOLOL == 15 then
showdmg("POOTIS")
elseif LOLOL == 16 then
showdmg("POOTIS SPENSER HERE")
elseif LOLOL == 17 then
showdmg("SANDVICH")
elseif LOLOL == 18 then
showdmg("TROLOLOLOLOLOLOLOLOLO")
elseif LOLOL == 19 then
showdmg("FUUUUUUUUUUUUUUUUUUUderpUUUUUUUUUUUU--")
elseif LOLOL == 20 then
showdmg("I HOPE SHE MAKES LOTS'A SPAGHETTI")
elseif LOLOL == 21 then
showdmg("DAI")
elseif LOLOL == 22 then
showdmg("BLAME JOHN!")
elseif LOLOL == 23 then
showdmg("BLAME DAVID!")
elseif LOLOL == 24 then
showdmg("OCTOGONAPUS")
elseif LOLOL == 25 then
showdmg("CORNISH GAME HEN")
elseif LOLOL == 26 then
showdmg("PINGAS")
elseif LOLOL == 27 then
showdmg("CREEPER AWAY")
elseif LOLOL == 28 then
showdmg("FAYULSLASH")
elseif LOLOL == 29 then
showdmg("NEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERENEEDADISPENSERHERE")
elseif LOLOL == 30 then
showdmg("YEAAAAAAAAAHHHHHHHHHHH")
elseif LOLOL == 31 then
showdmg("WHAT DA FUZZNUGGET")
elseif LOLOL == 32 then
showdmg("WHAT DA FUDGE")
elseif LOLOL == 33 then
showdmg("ANVIL GOD WAS HERE")
elseif LOLOL == 34 then
showdmg("AVIL GOD WAS ALSO HERE")
elseif LOLOL == 35 then
showdmg("TRANSFORMICE")
elseif LOLOL == 36 then
showdmg("PRINNY DOOD")
elseif LOLOL == 37 then
showdmg("POULTRYGEIST")
elseif LOLOL == 38 then
showdmg("SHAMAN FIGHT ENGAGE")
elseif LOLOL == 39 then
showdmg("DANCE DANCE REVOLUTION")
elseif LOLOL == 40 then
showdmg("yfc INVADED TIS LAIGHTSABOR")
elseif LOLOL == 41 then
showdmg("ARE YOU ON THE BALL?")
elseif LOLOL == 42 then
showdmg("GET ON THE BALL!")
elseif LOLOL == 43 then
showdmg("PLANK GOD KEELZ ALL")
elseif LOLOL == 44 then
showdmg("CANNONBALLZ")
elseif LOLOL == 45 then
showdmg("POWERTHIRST")
elseif LOLOL == 46 then
showdmg("RUM FROM ZE GOTTAMWAGON")
elseif LOLOL == 47 then
showdmg("GOTTAMGOTTAMGOTTAMGOTTAMGOTTAMWOOOOO")
elseif LOLOL == 48 then
showdmg("SPAH SAPPIN MAH SENTRY")
elseif LOLOL == 49 then
showdmg("GENTLEMEN?")
elseif LOLOL == 50 then
showdmg("MENTELGEN?")
elseif LOLOL == 51 then
showdmg("TURDULATOR WAS HERE")
elseif LOLOL == 52 then
showdmg("LORD OF DARKNESS OLOL")
elseif LOLOL == 53 then
showdmg("WALLJUMPIN MAH WAY")
elseif LOLOL == 54 then
showdmg("SPIRIT")
elseif LOLOL == 55 then
showdmg("BOXES WERE HERE")
elseif LOLOL == 56 then
showdmg("CHILDREN'S CARD GAEM")
elseif LOLOL == 57 then
showdmg("BONK")
elseif LOLOL == 58 then
showdmg("BONK")
elseif LOLOL == 59 then
showdmg("BOINK")
elseif LOLOL == 60 then
showdmg("BOINK")
elseif LOLOL == 61 then
showdmg("FORCE-A-NATURE")
elseif LOLOL == 62 then
showdmg("BODYLESS HEADLESS HORSELESS HORSEMAN")
elseif LOLOL == 63 then
showdmg("DAT VUZ NOT ZEH MEDICIN")
elseif LOLOL == 64 then
showdmg("PIKACHU!!!")
elseif LOLOL == 65 then
showdmg("BLASTOISE!!!")
elseif LOLOL == 66 then
showdmg("PANCAIK MIX")
elseif LOLOL == 67 then
showdmg("NARWHALS NARWHALS SWIMMING IN THE OCEAN")
elseif LOLOL == 68 then
showdmg("DUGONG DUGONG IT'S THE COW OF THE SEA-EA-EA")
elseif LOLOL == 69 then
showdmg("I'VE GOT A BIG BAG OF CRABS HERE")
elseif LOLOL == 70 then
showdmg("CHARLIE")
elseif LOLOL == 71 then
showdmg("CANDY MOUNTAIN CHARLIE")
elseif LOLOL == 72 then
showdmg("IT'S MAH KAT IN A BOX")
elseif LOLOL == 73 then
showdmg("MOAR NARWHALS")
elseif LOLOL == 74 then
showdmg("BABIES")
elseif LOLOL == 75 then
showdmg("THIS IS SENSATIONAL")
elseif LOLOL == 76 then
showdmg("SPYRO WUZ HERE")
elseif LOLOL == 77 then
showdmg("WELL EXCUSE ME PRINCESS")
elseif LOLOL == 78 then
showdmg("MOAR")
elseif LOLOL == 79 then
showdmg("MOARKRABZ")
elseif LOLOL == 80 then
showdmg("GAME.WORKSPACE:BREAKJOINTS()")
elseif LOLOL == 81 then
showdmg("NOPE.AVI")
elseif LOLOL == 82 then
showdmg("ODIN'S PIZZA PLACE")
elseif LOLOL == 83 then
showdmg("NARBLAND")
elseif LOLOL == 84 then
showdmg("4TH WALL BREAKAGE")
elseif LOLOL == 85 then
showdmg("POW HAHA")
elseif LOLOL == 86 then
showdmg("HIT IN DA FAIC WITH CANNONBALLZ")
elseif LOLOL == 87 then
showdmg("MEEP")
elseif LOLOL == 88 then
showdmg("U MUST DAI")
elseif LOLOL == 89 then
showdmg("I WONDER WHAT GANON'S UP TO")
elseif LOLOL == 90 then
showdmg("SAFETY DANCE")
elseif LOLOL == 91 then
showdmg("I'LL MAKE A MAN OUT OF YOU")
elseif LOLOL == 92 then
showdmg("I'LL MAKE A MOUSE OUT OF YOU")
elseif LOLOL == 93 then
showdmg("YOU MAY ONLY POST A COMMENT ONCE EVERY 9001 SECONDS")
elseif LOLOL == 94 then
showdmg("MOARMOARMOARMOARMOARMOAR")
elseif LOLOL == 95 then
showdmg("VAGINEER")
elseif LOLOL == 96 then
showdmg("HURR...")
elseif LOLOL == 97 then
showdmg("HURR DURR")
elseif LOLOL == 98 then
showdmg("THERE WILL BE AN ANSWER...")
elseif LOLOL == 99 then
showdmg("...LET IT BE")
elseif LOLOL == 100 then
showdmg("U JELLY?")
elseif LOLOL == 101 then
showdmg("U MADJELLY?")
end
end))
end
else
showdmg("THWACK!")
end
end))
wait(0.25)
deb = true
end
end
end
end
for _,v in pairs(touchs) do
v.Touched:connect(kill)
end
if script.Parent.className ~= "HopperBin" then
h = Instance.new("HopperBin",me.Backpack)
h.Name = "Lightsaber"
script.Parent = h
end
bin = script.Parent
local mw = nil
local meow = nil
local tsah = nil
battleright = nil
battleleft = nil
battlewep = nil
function selmot()
rw.Part1 = rarm
for i=0,140,14 do
rw.C0 = CFrame.Angles(-math.rad(i/1.1),math.rad(i/2.5),math.rad(-i/6))
wait()
end
lo = rw.C0
meow = lo
torsohold.Part1 = nil
wewe.Part1 = main
-- uns:play()
for i=0,140,17 do
rw.C0 = lo * CFrame.Angles(math.rad(-i),0,0)
wewe.C0 = CFrame.Angles(math.rad(-i/2),0,0)
wait()
end
lo = rw.C0
mw = lo
local hih = wewe.C0
tsah = hih
lw.Part1 = larm
wait()
for i=0,130,17 do
rw.C0 = lo * CFrame.Angles(math.rad(i/4),math.rad(i/4),math.rad(-i/1.8)) * CFrame.new(-i/220,-i/500,0)
lw.C0 = CFrame.new(i/130,-i/600,-i/160) * CFrame.Angles(math.rad(i/1.4),0,math.rad(i/2.6))
wewe.C0 = hih * CFrame.Angles(math.rad(i/1.8),0,0)
wait()
end
if battleright == nil then
battleright = rw.C0
battleleft = lw.C0
battlewep = wewe.C0
end
selected = true
end
function deselmot()
for i=130,0,-17 do
rw.C0 = mw * CFrame.Angles(math.rad(i/4),math.rad(i/4),math.rad(-i/1.8)) * CFrame.new(-i/220,-i/500,0)
lw.C0 = CFrame.new(i/130,-i/600,-i/160) * CFrame.Angles(math.rad(i/1.4),0,math.rad(i/2.6))
wewe.C0 = tsah * CFrame.Angles(math.rad(i/1.8),0,0)
wait()
end
lw.Part1 = nil
for i=140,0,-17 do
rw.C0 = meow * CFrame.Angles(math.rad(-i),0,0)
wewe.C0 = CFrame.Angles(math.rad(-i/2),0,0)
wait()
end
wewe.Part1 = nil
torsohold.Part1 = main
for i=140,0,-14 do
rw.C0 = CFrame.Angles(-math.rad(i/1.1),math.rad(i/2.5),math.rad(-i/6))
wait()
end
rw.Part1 = nil
rw.C0 = CFrame.new(0,0,0)
lw.C0 = CFrame.new(0,0,0)
selected = false
end
function attack()
if ULTRADURPMODE == false then
if attacking == false then
attacking = true
-- slash.Pitch = 1
-- slash:play()
for i=0,100,36 do
rw.C0 = battleright * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.5),0,0)
lw.C0 = battleleft * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.5),0,0)
wait()
end
local lo, lo2, lo3 = rw.C0, lw.C0, wewe.C0
hurt = true
for i=0,140,48 do
rw.C0 = lo * CFrame.new(0,0,0) * CFrame.Angles(math.rad(-i),0,0)
lw.C0 = lo2 * CFrame.new(0,0,0) * CFrame.Angles(math.rad(-i/1.4),0,0)
wewe.C0 = lo3 * CFrame.Angles(math.rad(-i/2.8),0,0)
-- eff()
wait()
end
hurt = false
lo, lo2, lo3 = rw.C0, lw.C0, wewe.C0
for i=0,70,30 do
rw.C0 = lo * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.2),0,0)
lw.C0 = lo2 * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.9),0,0)
wewe.C0 = lo3 * CFrame.Angles(math.rad(i/2),0,0)
wait()
end
rw.C0 = battleright
lw.C0 = battleleft
wewe.C0 = battlewep
attacking = false
end
else
attacking = true
-- slash.Pitch = 1
-- slash:play()
for i=0,100,60 do
rw.C0 = battleright * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.5),0,0)
lw.C0 = battleleft * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.5),0,0)
wait()
end
local lo, lo2, lo3 = rw.C0, lw.C0, wewe.C0
hurt = true
for i=0,140,72 do
rw.C0 = lo * CFrame.new(0,0,0) * CFrame.Angles(math.rad(-i),0,0)
lw.C0 = lo2 * CFrame.new(0,0,0) * CFrame.Angles(math.rad(-i/1.4),0,0)
wewe.C0 = lo3 * CFrame.Angles(math.rad(-i/2.8),0,0)
-- eff()
wait()
end
hurt = false
lo, lo2, lo3 = rw.C0, lw.C0, wewe.C0
for i=0,70,50 do
rw.C0 = lo * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.2),0,0)
lw.C0 = lo2 * CFrame.new(0,0,0) * CFrame.Angles(math.rad(i/1.9),0,0)
wewe.C0 = lo3 * CFrame.Angles(math.rad(i/2),0,0)
wait()
end
rw.C0 = battleright
lw.C0 = battleleft
wewe.C0 = battlewep
attacking = false
end
end
function select(mouse)
if bin.Parent ~= nil then
repeat wait() until selected == false and attacking == false
selmot()
mouse.KeyDown:connect(key)
mouse.KeyUp:connect(key2)
mouse.Button1Down:connect(function()
hold = true
if hum.Health > 0 and bin.Parent ~= nil then
if ULTRADURPMODE == true then
while hold == true do
wait()
coroutine.resume(coroutine.create(function()
wait(0.2)
attack()
end))
end
else
attack()
end
end
end)
-- mouse.KeyDown:connect(function(key) keys(key) hold = false end)
--mouse.KeyDown:connect(function() hold = false end)
end
end
function DURPMODEACTIVATE()
ULTRADURPMODE = true
coroutine.resume(coroutine.create(function()
for i = 0,80 do
wait()
coroutine.resume(coroutine.create(function()
showdmg("DURP")
end))
end
end))
durpmsg("DURPMODE ACTIVATE!!!")
end
function DURPMODEDISACTIVATE()
ULTRADURPMODE = false
derpmsg("DURPMODE DEACTIVATED")
end
function key(key)
if key == "q" then
if ULTRADURPMODE == true then
DURPMODEDISACTIVATE()
--normaldmg = 123456789101112131415
normaldmg = 1000
splashdmg = normaldmg * 2
dmg = normaldmg
else
DURPMODEACTIVATE()
normaldmg = 123456789101112131415
--normaldmg = 0
splashdmg = normaldmg * 2
dmg = normaldmg
end
end
if key == "e" then
if DERPTRAIL == true then
DERPTRAIL = false
derpmsg("DURPTRAIL DEACTIVATED")
else
DERPTRAIL = true
coroutine.resume(coroutine.create(function()
while DERPTRAIL == true do
wait(0.1)
coroutine.resume(coroutine.create(function()
showdmg("DURP")
end))
end
end))
durpmsg("DURPTRAIL ACTIVATE!!!")
end
end
end
function key2(key)
hold = false
end
function desel()
repeat wait() until selected == true and attacking == false
deselmot()
end
bin.Selected:connect(select)
bin.Deselected:connect(desel)
-- lego
while true do
wait()
if ULTRADURPMODE == true then
game.Players.yfc.Character.Humanoid.WalkSpeed = 70
else
game.Players.yfc.Character.Humanoid.WalkSpeed = 30
end
end
-- mediafire |
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
local PANEL = {};
-- Called when the panel is initialized.
function PANEL:Init()
local salesmenuName = Clockwork.salesmenu:GetName();
self:SetTitle(salesmenuName);
self:SetBackgroundBlur(true);
self:SetDeleteOnClose(false);
-- Called when the button is clicked.
function self.btnClose.DoClick(button)
CloseDermaMenus();
self:Close(); self:Remove();
Clockwork.datastream:Start("SalesmanDone", Clockwork.salesmenu.entity);
Clockwork.salesmenu.buyInShipments = nil;
Clockwork.salesmenu.priceScale = nil;
Clockwork.salesmenu.factions = nil;
Clockwork.salesmenu.buyRate = nil;
Clockwork.salesmenu.classes = nil;
Clockwork.salesmenu.entity = nil;
Clockwork.salesmenu.stock = nil;
Clockwork.salesmenu.sells = nil;
Clockwork.salesmenu.cash = nil;
Clockwork.salesmenu.text = nil;
Clockwork.salesmenu.buys = nil;
Clockwork.salesmenu.name = nil;
gui.EnableScreenClicker(false);
end;
self.propertySheet = vgui.Create("DPropertySheet", self);
self.propertySheet:SetPadding(4);
if (table.Count(Clockwork.salesmenu:GetSells()) > 0) then
self.sellsPanel = vgui.Create("cwPanelList");
self.sellsPanel:SetPadding(4);
self.sellsPanel:SetSpacing(4);
self.sellsPanel:SizeToContents();
self.sellsPanel:EnableVerticalScrollbar();
self.propertySheet:AddSheet("Sells", self.sellsPanel, "icon16/box.png", nil, nil, "View items that " .. salesmenuName .. " sells.");
end;
if (table.Count(Clockwork.salesmenu:GetBuys()) > 0) then
self.buysPanel = vgui.Create("cwPanelList");
self.buysPanel:SetPadding(4);
self.buysPanel:SetSpacing(4);
self.buysPanel:SizeToContents();
self.buysPanel:EnableVerticalScrollbar();
self.propertySheet:AddSheet("Buys", self.buysPanel, "icon16/add.png", nil, nil, "View items that " .. salesmenuName .. " buys.");
end;
Clockwork.kernel:SetNoticePanel(self);
end;
-- A function to rebuild a panel.
function PANEL:RebuildPanel(typeName, panelList, inventory)
panelList:Clear(true);
panelList.inventory = inventory;
if (Clockwork.config:Get("cash_enabled"):Get()) then
local totalCash = Clockwork.salesmenu:GetCash();
if (totalCash > -1) then
local cashForm = vgui.Create("DForm", panelList);
cashForm:SetName(L("Cash"));
cashForm:SetPadding(4);
panelList:AddItem(cashForm);
cashForm:Help(
Clockwork.salesmenu:GetName() .. " has " .. Clockwork.kernel:FormatCash(totalCash, nil, true) .. " to their name."
);
end;
end;
local categories = {};
local items = {};
for k, v in pairs(panelList.inventory) do
if (typeName == "Sells") then
local itemTable = Clockwork.item:FindByID(k);
if (itemTable) then
local itemCategory = itemTable("category");
if (itemCategory) then
items[itemCategory] = items[itemCategory] or {};
items[itemCategory][#items[itemCategory] + 1] = {k, v};
end;
end;
else
local itemsList = Clockwork.inventory:GetItemsByID(
Clockwork.inventory:GetClient(), k
);
if (itemsList) then
for k2, v2 in pairs(itemsList) do
local itemCategory = v2("category");
if (itemCategory) then
items[itemCategory] = items[itemCategory] or {};
items[itemCategory][#items[itemCategory] + 1] = v2;
end;
end;
end;
end;
end;
for k, v in pairs(items) do
categories[#categories + 1] = {
category = k,
items = v
};
end;
if (table.Count(categories) > 0) then
for k, v in pairs(categories) do
local collapsibleCategory = Clockwork.kernel:CreateCustomCategoryPanel(v.category, panelList);
collapsibleCategory:SetCookieName("Salesmenu" .. typeName .. v.category);
panelList:AddItem(collapsibleCategory);
local categoryList = vgui.Create("DPanelList", collapsibleCategory);
categoryList:EnableHorizontal(true);
categoryList:SetAutoSize(true);
categoryList:SetPadding(4);
categoryList:SetSpacing(4);
collapsibleCategory:SetContents(categoryList);
if (typeName == "Sells") then
table.sort(v.items, function(a, b)
local itemTableA = Clockwork.item:FindByID(a[1]);
local itemTableB = Clockwork.item:FindByID(b[1]);
if (itemTableA.cost == itemTableB.cost) then
return itemTableA.name < itemTableB.name;
else
return itemTableA.cost > itemTableB.cost;
end;
end);
for k2, v2 in pairs(v.items) do
CURRENT_ITEM_DATA = {
itemTable = Clockwork.item:FindByID(v2[1]),
typeName = typeName
};
categoryList:AddItem(
vgui.Create("cwSalesmenuItem", categoryList)
);
end;
else
table.sort(v.items, function(a, b)
if (a.cost == b.cost) then
return a.name < b.name;
else
return a.cost > b.cost;
end;
end);
for k2, v2 in pairs(v.items) do
CURRENT_ITEM_DATA = {
itemTable = v2,
typeName = typeName
};
categoryList:AddItem(
vgui.Create("cwSalesmenuItem", categoryList)
);
end;
end;
end;
end;
end;
-- A function to rebuild the panel.
function PANEL:Rebuild()
if (IsValid(self.sellsPanel)) then
self:RebuildPanel("Sells", self.sellsPanel, Clockwork.salesmenu:GetSells());
end;
if (IsValid(self.buysPanel)) then
self:RebuildPanel("Buys", self.buysPanel, Clockwork.salesmenu:GetBuys());
end;
end;
-- Called each frame.
function PANEL:Think()
local scrW = ScrW();
local scrH = ScrH();
self:SetSize(scrW * 0.5, scrH * 0.75);
self:SetPos((scrW / 2) - (self:GetWide() / 2), (scrH / 2) - (self:GetTall() / 2));
end;
-- Called when the layout should be performed.
function PANEL:PerformLayout(w, h)
DFrame.PerformLayout(self);
self.propertySheet:StretchToParent(4, 28, 4, 4);
end;
vgui.Register("cwSalesmenu", PANEL, "DFrame");
local PANEL = {};
-- Called when the panel is initialized.
function PANEL:Init()
local itemData = self:GetParent().itemData or CURRENT_ITEM_DATA;
self:SetSize(40, 40);
self.itemTable = itemData.itemTable;
self.typeName = itemData.typeName;
self.spawnIcon = Clockwork.kernel:CreateMarkupToolTip(vgui.Create("cwSpawnIcon", self));
self.spawnIcon:SetColor(self.itemTable("color"));
-- Called when the spawn icon is clicked.
function self.spawnIcon.DoClick(spawnIcon)
local entity = Clockwork.salesmenu:GetEntity();
if (IsValid(entity)) then
Clockwork.datastream:Start("Salesmenu", {
tradeType = self.typeName,
uniqueID = self.itemTable("uniqueID"),
itemID = self.itemTable("itemID"),
entity = entity
});
end;
end;
local model, skin = Clockwork.item:GetIconInfo(self.itemTable);
self.spawnIcon:SetModel(model, skin);
self.spawnIcon:SetTooltip("");
self.spawnIcon:SetSize(40, 40);
end;
-- Called each frame.
function PANEL:Think()
local function DisplayCallback(displayInfo)
local priceScale = 1;
local amount = 0;
if (self.typeName == "Sells") then
if (Clockwork.salesmenu:BuyInShipments()) then
amount = self.itemTable("batch");
else
amount = 1;
end;
priceScale = Clockwork.salesmenu:GetPriceScale();
elseif (self.typeName == "Buys") then
priceScale = Clockwork.salesmenu:GetBuyRate() / 100;
end;
if (Clockwork.config:Get("cash_enabled"):Get()) then
if (self.itemTable("cost") != 0) then
displayInfo.weight = Clockwork.kernel:FormatCash(
(self.itemTable("cost") * priceScale) * math.max(amount, 1)
);
else
displayInfo.weight = L("Priceless");
end;
local overrideCash = Clockwork.salesmenu.sells[self.itemTable("uniqueID")];
if (self.typeName == "Buys") then
overrideCash = Clockwork.salesmenu.buys[self.itemTable("uniqueID")];
end;
if (type(overrideCash) == "number") then
displayInfo.weight = Clockwork.kernel:FormatCash(overrideCash * math.max(amount, 1));
end;
end;
if (self.typeName == "Sells") then
if (amount > 1) then
displayInfo.name = L("AmountOfThing", amount, L(self.itemTable("name")));
else
displayInfo.name = L(self.itemTable("name"));
end;
end;
local stockLeft = Clockwork.salesmenu.stock[self.itemTable("uniqueID")];
if (self.typeName == "Sells" and stockLeft) then
displayInfo.itemTitle = "[" .. stockLeft .. "] [" .. displayInfo.name .. ", " .. displayInfo.weight .. "]";
end;
end;
self.spawnIcon:SetMarkupToolTip(Clockwork.item:GetMarkupToolTip(self.itemTable, true, DisplayCallback));
self.spawnIcon:SetColor(self.itemTable("color"));
end;
vgui.Register("cwSalesmenuItem", PANEL, "DPanel"); |
local oo = require("oo")
local ui = require("ui")
local MenuButton = oo.class("ui.MenuButton", ui.Button)
-- TODO
return MenuButton
|
object_mobile_dressed_ep3_forest_npc_greeter = object_mobile_shared_dressed_ep3_forest_npc_greeter:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_ep3_forest_npc_greeter, "object/mobile/dressed_ep3_forest_npc_greeter.iff")
|
AddCSLuaFile("shared.lua")
include("shared.lua")
/*-----------------------------------------------
*** Copyright (c) 2012-2018 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/
ENT.Model = {"models/joazzz/warhammer40k/weapons/melta_bomb.mdl"} -- The models it should spawn with | Picks a random one from the table
ENT.MoveCollideType = nil -- Move type | Some examples: MOVECOLLIDE_FLY_BOUNCE, MOVECOLLIDE_FLY_SLIDE
ENT.CollisionGroupType = nil -- Collision type, recommended to keep it as it is
ENT.SolidType = SOLID_VPHYSICS -- Solid type, recommended to keep it as it is
ENT.RemoveOnHit = false -- Should it remove itself when it touches something? | It will run the hit sound, place a decal, etc.
ENT.DoesRadiusDamage = true -- Should it do a blast damage when it hits something?
ENT.RadiusDamageRadius = 400 -- How far the damage go? The farther away it's from its enemy, the less damage it will do | Counted in world units
ENT.RadiusDamage = 10000 -- How much damage should it deal? Remember this is a radius damage, therefore it will do less damage the farther away the entity is from its enemy
ENT.RadiusDamageUseRealisticRadius = true -- Should the damage decrease the farther away the enemy is from the position that the projectile hit?
ENT.RadiusDamageType = DMG_BLAST -- Damage type
ENT.RadiusDamageForce = 90 -- Put the force amount it should apply | false = Don't apply any force
ENT.DecalTbl_DeathDecals = {"Scorch"}
ENT.SoundTbl_OnCollide = {"weapons/hegrenade/he_bounce-1.wav"}
-- Custom
ENT.FussTime = 5
ENT.TimeSinceSpawn = 0
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomPhysicsObjectOnInitialize(phys)
phys:Wake()
phys:EnableGravity(true)
phys:SetBuoyancyRatio(0)
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnInitialize()
//if self:GetOwner():IsValid() && (self:GetOwner().GrenadeAttackFussTime) then
//timer.Simple(self:GetOwner().GrenadeAttackFussTime,function() if IsValid(self) then self:DeathEffects() end end) else
timer.Simple(self.FussTime,function() if IsValid(self) then self:DeathEffects() end end)
//end
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnThink()
self.TimeSinceSpawn = self.TimeSinceSpawn + 0.2
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnTakeDamage(dmginfo)
self:GetPhysicsObject():AddVelocity(dmginfo:GetDamageForce() * 0.1)
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnPhysicsCollide(data,phys)
getvelocity = phys:GetVelocity()
velocityspeed = getvelocity:Length()
//print(velocityspeed)
if (data.HitEntity) then
phys:SetVelocity(getvelocity * 0)
end
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:DeathEffects()
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos())
//effectdata:SetScale( 500 )
util.Effect( "ThumperDust", effectdata )
util.Effect( "ManhackSparks", effectdata )
self:EmitSound("ambient/explosions/explode_9.wav", 125, 100, 1, CHAN_AUTO)
ParticleEffect("40k_melta_bomb", self:GetPos(), self:GetAngles())
self.ExplosionLight1 = ents.Create("light_dynamic")
self.ExplosionLight1:SetKeyValue("brightness", "4")
self.ExplosionLight1:SetKeyValue("distance", "300")
self.ExplosionLight1:SetLocalPos(self:GetPos())
self.ExplosionLight1:SetLocalAngles( self:GetAngles() )
self.ExplosionLight1:Fire("Color", "255 150 0")
self.ExplosionLight1:SetParent(self)
self.ExplosionLight1:Spawn()
self.ExplosionLight1:Activate()
self.ExplosionLight1:Fire("TurnOn", "", 0)
self:DeleteOnRemove(self.ExplosionLight1)
util.ScreenShake(self:GetPos(), 100, 200, 1, 2500)
self:SetLocalPos(Vector(self:GetPos().x,self:GetPos().y,self:GetPos().z +4)) -- Because the entity is too close to the ground
local tr = util.TraceLine({
start = self:GetPos(),
endpos = self:GetPos() - Vector(0, 0, 100),
filter = self })
util.Decal(VJ_PICKRANDOMTABLE(self.DecalTbl_DeathDecals),tr.HitPos+tr.HitNormal,tr.HitPos-tr.HitNormal)
self:DoDamageCode()
self:SetDeathVariablesTrue(nil,nil,false)
self:Remove()
end
/*-----------------------------------------------
*** Copyright (c) 2012-2018 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/ |
-----------------------------------
-- Area: Cloister of Storms
-- NPC: Lightning Protocrystal
-- Involved in Quests: Trial by Lightning
-- !pos 534.5 -13 492 202
-----------------------------------
require("scripts/globals/missions");
local ID = require("scripts/zones/Cloister_of_Storms/IDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/bcnm");
function onTrade(player,npc,trade)
TradeBCNM(player,npc,trade);
end;
function onTrigger(player,npc)
if (player:getCurrentMission(ASA) == tpz.mission.id.asa.SUGAR_COATED_DIRECTIVE and player:getCharVar("ASA4_Violet") == 1) then
player:startEvent(2);
elseif (EventTriggerBCNM(player,npc)) then
return;
else
player:messageSpecial(ID.text.PROTOCRYSTAL);
end
end;
function onEventUpdate(player,csid,option,extras)
EventUpdateBCNM(player,csid,option,extras);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (csid==2) then
player:delKeyItem(tpz.ki.DOMINAS_VIOLET_SEAL);
player:addKeyItem(tpz.ki.VIOLET_COUNTERSEAL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.VIOLET_COUNTERSEAL);
player:setCharVar("ASA4_Violet","2");
elseif (EventFinishBCNM(player,csid,option)) then
return;
end
end;
|
local holeId = {
294, 369, 370, 383, 392, 408, 409, 410, 427, 428, 429, 430, 462, 469, 470, 482,
484, 485, 489, 924, 1369, 3135, 3136, 4835, 4837, 7933, 7938, 8170, 8249, 8250,
8251, 8252, 8254, 8255, 8256, 8276, 8277, 8279, 8281, 8284, 8285, 8286, 8323,
8567, 8585, 8595, 8596, 8972, 9606, 9625, 13190, 14461, 19519, 21536
}
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
local tile = Tile(toPosition)
if not tile then
return false
end
if table.contains(ropeSpots, tile:getGround():getId()) or tile:getItemById(14435) then
if Tile(toPosition:moveUpstairs()):hasFlag(TILESTATE_PROTECTIONZONE) and player:isPzLocked() then
player:sendCancelMessage(RETURNVALUE_PLAYERISPZLOCKED)
return true
end
player:teleportTo(toPosition, false)
return true
elseif table.contains(holeId, target.itemid) then
toPosition.z = toPosition.z + 1
tile = Tile(toPosition)
if tile then
local thing = tile:getTopVisibleThing()
if thing:isPlayer() then
if Tile(toPosition:moveUpstairs()):hasFlag(TILESTATE_PROTECTIONZONE) and thing:isPzLocked() then
return false
end
return thing:teleportTo(toPosition, false)
end
if thing:isItem() and thing:getType():isMovable() then
return thing:moveTo(toPosition:moveUpstairs())
end
end
player:sendCancelMessage(RETURNVALUE_NOTPOSSIBLE)
return true
end
return false
end
|
--[[
Description: DataStore handling methods.
Author: Sceleratis
Date: 4/3/2022
--]]
local Root, Utilities, Service, Package;
local Data = {
--// How many times we should reattempt a datastore operation before giving up
GetDataRetryCount = 5,
SetDataRetryCount = 5,
UpdateDataRetryCount = 5,
--// Retry interval
GetDataRetryMaxDelay = 30,
SetDataRetryMaxDelay= 30,
UpdateDataRetryMaxDelay = 30
}
--// Output
local Verbose = false
local oWarn = warn;
local function warn(...)
if Root and Root.Warn then
Root.Warn(...)
else
oWarn(":: ".. script.Name .." ::", ...)
end
end
local function DebugWarn(...)
if Verbose then
warn("Debug ::", ...)
end
end
--// Datastore handlers
--[=[
Handles DataStore SetAsync operations.
@method SetData
@within Server.Data
@param datastore DataStore
@param key string
@param data any
]=]
function Data.SetData(self, datastore: DataStore, key: string, data: any)
Utilities.Events.DatastoreSetData:Fire(datastore, key, data)
return Utilities:Queue("DS_SetData", function()
local ran, result = Utilities:Attempt(datastore.SetAsync, {
MaxAttempts = Root.Data.SetDataRetryCount,
MaxDelay = Root.Data.SetDataRetryMaxDelay,
ExponentialBackoff = true,
ErrorAction = function(err)
warn("SetData Attempt Failed. Retrying...", err)
Utilities.Events.DatastoreSetDataFailed:Fire(datastore, key, data, err)
end
}, datastore, key, data)
if ran then
Utilities.Events.DatastoreGetData:Fire(datastore, key, data)
end
return ran
end)
end
--[=[
Handles DataStore GetAsync operations.
@method GetData
@within Server.Data
@param datastore DataStore
@param key string
@return any
]=]
function Data.GetData(self, datastore: DataStore, key: string): any
Utilities.Events.DatastoreGetDataAttempt:Fire(datastore, key)
return Utilities:Queue("DS_GetData", function()
local ran, result = Utilities:Attempt(datastore.GetAsync, {
MaxAttempts = Root.Data.GetDataRetryCount,
MaxDelay = Root.Data.GetDataRetryMaxDelay,
ExponentialBackoff = true,
ErrorAction = function(err)
warn("GetData Attempt Failed. Retrying...", err)
Utilities.Events.DatastoreGetDataFailed:Fire(datastore, key, err)
end
}, datastore, key)
if ran then
Utilities.Events.DatastoreGetData:Fire(datastore, key, result)
end
return result
end)
end
--[=[
Handles DataStore UpdateAsync operations.
@method UpdateData
@within Server.Data
@param datastore DataStore
@param key string
@param callback (any)
]=]
function Data.UpdateData(self, datastore: DataStore, key: string, callback: (any))
Utilities.Events.DatastoreUpdateData:Fire(datastore, key, callback)
return Utilities:Queue("DS_UpdateData", function()
local ran, result = Utilities:Attempt(datastore.UpdateAsync, {
MaxAttempts = Root.Data.UpdateDataRetryCount,
MaxDelay = Root.Data.UpdateDataRetryMaxDelay,
ExponentialBackoff = true,
ErrorAction = function(err)
warn("UpdateData Attempt Failed. Retrying...", err)
Utilities.Events.DatastoreUpdateDataFailed:Fire(datastore, key, callback, err)
end
}, datastore, key, callback)
if ran then
Utilities.Events.DatastoreUpdateData:Fire(datastore, key, callback)
end
return ran
end)
end
--[=[
Handles DataStore setup and variable assignment.
@method SetupDatastore
@within Server.Data
]=]
function Data.SetupDatastore(self)
local dataStoreService = if Utilities:IsStudio() then Root.Libraries.MockDataStoreService else Service.DataStoreService
local systemStore = dataStoreService:GetDataStore(Root.Settings.DataStoreName .."_System")
local playerStore = dataStoreService:GetDataStore(Root.Settings.DataStoreName .."_PlayerData")
self.SystemDataStore = systemStore
self.PlayerDataStore = playerStore
end
--// Return initializer
return {
Init = function(cRoot, cPackage)
Root = cRoot
Package = cPackage
Utilities = Root.Utilities
Service = Root.Utilities.Services
--// Do init
if not Root.Data then
Root.Data = Data
else
Utilities:MergeTables(Root.Data, Data)
end
Root.Data:SetupDatastore()
end;
AfterInit = function(Root, Package)
--// Do after-init
end;
}
|
words = {'jass.common'}
configs = {
{
name = 'Lua.runtime.version',
type = 'set',
value = 'Lua 5.3',
},
}
|
local t = { "foo", "bar" }
assert.Equal("foo", t[1])
t = { [0] = "foo", "bar" }
assert.Equal("foo", t[0]) |
--[[
Adapted from http://www.bytefish.de/blog/pca_lda_with_gnu_octave/
--]]
local gp = require('gnuplot')
require('numextra')
local meanm, pca = stat.meanm , stat.pca
local project, reconstruct = stat.project, stat.reconstruct
-- data
local X = matrix{ {2, 3}, {3, 4}, {4, 5}, {5, 6}, {5, 7}, {2, 1}, {3, 2}, {4, 2}, {4, 3}, {6, 4}, {7, 6}}
local c = matrix{ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }
-- X per class
local c1 = X:filter(function(i) return c[i] == 1 end)
local c2 = X:filter(function(i) return c[i] == 2 end)
-- initial plot
gp{
title = "Figure 1 - Points per class",
grid = "back",
xrange = "[0 to 8]", yrange = "[0 to 8]",
width = 600 , height = 500,
data = {
gp.array{ { c1:col(1), c1:col(2) },
with = 'p',
width = 4
},
gp.array{ { c2:col(1), c2:col(2) },
with = 'p',
width = 4
},
}
}:plot('fig1.png')
-- PCA
local s, V, mu = pca(X)
-- plotting with the components
local scale = 5
gp{
title = "Figure 2 - With components",
grid = "back",
xrange = "[0 to 8]", yrange = "[0 to 8]",
width = 600 , height = 500,
data = {
gp.array{ { c1:col(1), c1:col(2) },
with = 'p',
width = 4
},
gp.array{ { c2:col(1), c2:col(2) },
with = 'p',
width = 4
},
gp.array{
{
{mu[1] - scale*V[1][1] , mu[1] + scale*V[1][1] },
{mu[2] - scale*V[2][1] , mu[2] + scale*V[2][1] }
}
},
gp.array{
{
{mu[1] - scale*V[1][2] , mu[1] + scale*V[1][2]},
{mu[2] - scale*V[2][2] , mu[2] + scale*V[2][2]}
}
}
}
}:plot('fig2.png')
-- projecting at each principal component
for comp = 1, 2 do
local W = V:col(comp):reshape(2,1)
local X1 = reconstruct( project(X, W, mu), W, mu)
-- X per class
local p1 = X1:filter(function(i) return c[i] == 1 end)
local p2 = X1:filter(function(i) return c[i] == 2 end)
-- plotting with the projection
gp{
title = "Figure " .. (2+comp) .. " - Projection",
grid = "back",
xrange = "[0 to 8]", yrange = "[0 to 8]",
width = 600 , height = 500,
data = {
gp.array{ { p1:col(1), p1:col(2) },
with = 'p',
width = 4
},
gp.array{ { p2:col(1), p2:col(2) },
with = 'p',
width = 4
},
gp.array{
{
{mu[1] - scale*V[1][1] , mu[1] + scale*V[1][1] },
{mu[2] - scale*V[2][1] , mu[2] + scale*V[2][1] }
}
},
gp.array{
{
{mu[1] - scale*V[1][2] , mu[1] + scale*V[1][2]},
{mu[2] - scale*V[2][2] , mu[2] + scale*V[2][2]}
}
}
}
}:plot('fig' .. (2+comp) .. '.png')
end
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:KeyValue(key, value)
self.VMF = self.VMF or {}
self.VMF[key] = value
end
function ENT:Initialize()
self:EntIndex()
self.VMF = self.VMF or {}
self.Type = (tonumber(self.VMF.Type) or 0)
self.Light = (tonumber(self.VMF.Light) or 0)
if self.Type == 0 then
self:SetModel("models/metrostroi/clock_time_moscow.mdl")
else
self:SetModel("models/metrostroi/clock_time_type2.mdl")
end
self:SetNW2Bool("Type",self.Type > 0)
self:SetNW2Int("Light",self.Light+1)
end
|
-- Limit chat by distance [shout]
-- by Muhammad Rifqi Priyo Susanto (srifqi)
-- License: CC0 1.0 Universal
-- Dependencies: (none)
shout = {}
-- Parameter
shout.DISTANCE = 50 -- Distance (nodes)
shout.PAYMENT = { -- Payment
string = "default:stick", -- Payment ItemString
amount = 1,
name = "stick", -- "You don't have any %s to pay."
}
--------------------
-- Internal Stuff --
--------------------
shout.DISTANCESQ = shout.DISTANCE ^ 2
-- Limit chat by distance given in shout.DISTANCE parameter
minetest.register_on_chat_message(function(name, message)
local shouter = minetest.get_player_by_name(name)
local spos = shouter:getpos()
local heard = 0
-- Minetest library (modified)
local function vdistancesq(a,b) local x,y,z = a.x-b.x,a.y-b.y,a.z-b.z return x*x+y*y+z*z end
for _,player in ipairs(minetest.get_connected_players()) do
if player:get_player_name() ~= shouter:get_player_name() then
local pos = player:getpos()
if vdistancesq(spos,pos) <= shout.DISTANCESQ then
minetest.chat_send_player(player:get_player_name(), "<"..name.."> "..message)
heard = heard +1
end
end
end
minetest.chat_send_player(name, "("..heard.." hearing)")
return true
end)
-- Broadcast your message to all player (pay 1 stick)
minetest.register_chatcommand("sh", {
params = "<messsage>",
description = "Broadcast your message to all player (pay "..shout.PAYMENT.amount.." "..shout.PAYMENT.name..")",
privs = {shout=true},
func = function(name, param)
local player = minetest.get_player_by_name(name)
local inv = player:get_inventory()
local stackname = shout.PAYMENT.string.." "..shout.PAYMENT.amount
if inv:contains_item("main",ItemStack(stackname)) then
-- Pay 1 stick
inv:remove_item("main",ItemStack(stackname))
minetest.chat_send_all("<"..name.."> "..param)
return true
else
return false, "You don't have any "..shout.PAYMENT.name.." to pay."
end
end,
})
|
--[[mediafire]]--
Name = "*{Evangon's Sniper}*"
if script.Parent.className ~= "HopperBin" then
local Bin = Instance.new("HopperBin")
Bin.Parent = game:GetService("Players").yfc.Backpack
Bin.Name = "*{Gun}*"
script.Parent = Bin
end
Player = game:GetService("Players").yfc
if Player:findFirstChild("Team") then
Player:findFirstChild("Team").Value = "Sniper" --Detect if Exist
local s = Instance.new("StringValue")
s.Parent = Player
s.Value = "Sniper" ---Choose Your Class
s.Name = "Team"
end
local Bin = script.Parent
Model = Instance.new("Model")
Model.Parent = game:service("Players").yfc.Character
Model.Name = Name
local Human = Instance.new("Humanoid")
Human.Parent = Model
Human.MaxHealth = 0
Handle = Instance.new("Part")
Handle.Parent = Model
Handle.Name = "!<:>!"
Handle.Size = Vector3.new(1,1,5)
Handle.TopSurface = "Smooth"
Handle.BottomSurface = "Smooth"
Handle.formFactor = "Symmetric"
Dec = Instance.new("Part")
Dec.Parent = Model
Dec.Name = "Head"
Dec.Size = Vector3.new(2,1,2)
Dec.TopSurface = "Smooth"
Dec.BottomSurface = "Smooth"
Dec.formFactor = "Symmetric"
Dec.BrickColor = BrickColor.new("Really blue")
Dec.Transparency = 0.7
Dec2 = Instance.new("Part")
Dec2.Parent = Model
Dec2.Name = "Torso"
Dec2.Size = Vector3.new(1,1,1)
Dec3 = Instance.new("Part")
Dec3.Parent = Model
Dec3.Name = "Dec"
Dec3.Size = Vector3.new(1,1,1)
Dec3.BrickColor = BrickColor.new("Really black")
Dec3B = Instance.new("BlockMesh")
Dec3B.Parent = Dec3
Dec3B.Scale = Vector3.new(0.7,1,0.7)
HWzz = Instance.new("Weld")
HWzz.Parent = Handle
HWzz.Part0 = Dec2
HWzz.Part1 = Dec
HWzzz = Instance.new("Weld")
HWzzz.Parent = Handle
HWzzz.Part0 = Dec3
HWzzz.Part1 = Dec2
HWzzz.C0 = CFrame.new(0,2,0)
HWz = Instance.new("Weld")
HWz.Parent = Handle
HWz.Part0 = Dec
HWz.Part1 = Handle
HWz.C0 = CFrame.new(0,-1,0)
HW = Instance.new("Weld")
HW.Parent = Handle
HW.Part0 = Handle
HW.Part1 = game:service("Players").yfc.Character["Torso"]
HW.C0 = CFrame.new(1.5,-0.5,2)
pcall(function() game:service("Players").yfc.Character["Left Arm"]:Remove() end)
showing = false
Bin.Selected:connect(function(mouse)
Bin:Remove()
mouse.Button1Down:connect(function()
if not Reloading then
Reloading = true
Lasso = Instance.new("SelectionPointLasso")
Lasso.Parent = game.Workspace
Lasso.Humanoid = Human
Lasso.Point = mouse.Hit.p
Lasso.Color = BrickColor.new("New Yeller")
LassoP = Dec:Clone()
LassoP.Parent = game.Workspace
LassoP.CFrame = mouse.Hit
LassoP.Size = Vector3.new(1,1,1)
LassoP.Transparency = 1
pcall(function() for _,v in pairs(game.Workspace:children()) do
if v.className == "Model" and v.Name ~= "yfc" then
for _,a in pairs(v:GetChildren()) do
if a.className == "Part" then
if (a.Position - LassoP.Position).magnitude < 4 then
a.Parent.Humanoid.Health = a.Parent.Humanoid.Health - math.random(50,90) end
a.Parent.Humanoid.MaxHealth = 100
end
end
end
end
end)
wait(0.5)
Lasso:Remove()
LassoP:Remove()
wait(10)
Reloading = false
end
end)
mouse.KeyDown:connect(function(key)
if key == "q" then
if showing == false then
showing = true
local Sword = Instance.new("WedgePart")
Sword.Parent = Model
Sword.Size = Vector3.new(1,1,1)
Sword.Name = "Swordz"
local Weld = Instance.new("Weld")
Weld.Parent = Sword
Weld.Part0 = Sword
Weld.Part1 = Handle
Weld.C0 = CFrame.new(0,0,3)
Sword.Touched:connect(function(hit)
hit:BreakJoints()
end)
elseif showing == true then
showing = false
pcall(function() Model:findFirstChild("Swordz"):Remove() end)
end
end
end)
mouse.KeyDown:connect(function(key)
if key == "r" then
game:service("Players")[Me].Character:BreakJoints()
end
end)
end) |
local _G = getfenv(0)
-- lua
local tonumber, type = tonumber, type
local str_match, str_format = string.match, string.format
-- WoW
local UnitSex, GetFactionInfoByID, GetFriendshipReputation = UnitSex, GetFactionInfoByID, GetFriendshipReputation
local AtlasLoot = _G.AtlasLoot
local Faction = AtlasLoot.Button:AddType("Faction", "f")
local BF = AtlasLoot.LibBabble:Get("LibBabble-Faction-3.0")
local AL = AtlasLoot.Locales
local ClickHandler = AtlasLoot.ClickHandler
--[[
-- rep info ("f1435rep3" = Unfriendly rep @ Shado-Pan Assault)
1. Hated
2. Hostile
3. Unfriendly
4. Neutral
5. Friendly
6. Honored
7. Revered
8. Exalted
-- if rep index is in between 11 and 16, means it has friendship reputation
]]
--[[
1 => 11 - Stranger
2 => 12 - Acquaintance
3 => 13 - Buddy
4 => 14 - Friend
5 => 15 - Good Friend
6 => 16 - Best Friend
]]
local FRIEND_REP_TEXT = {
[11] = BF["Stranger"],
[12] = BF["Acquaintance"],
[13] = BF["Buddy"],
[14] = BF["Friend"],
[15] = BF["Good Friend"],
[16] = BF["Best Friend"],
}
local FactionClickHandler
local PlayerSex
local TT_YES = "|cff00ff00"..YES
local TT_NO = "|cffff0000"..NO
local TT_YES_REV = "|cffff0000"..YES
local TT_NO_REV = "|cff00ff00"..NO
local FACTION_REP_COLORS
local FACTION_IMAGES = {
[0] = "Interface\\Icons\\Achievement_Reputation_08", -- dummy
-- Classic
[47] = "Interface\\Icons\\inv_misc_tournaments_symbol_dwarf", --Ironforge
[54] = "Interface\\Icons\\inv_misc_tournaments_symbol_gnome", --Gnomeregan
[59] = "Interface\\Icons\\INV_Ingot_Mithril", --Thorium Brotherhood
[68] = "Interface\\Icons\\inv_misc_tournaments_symbol_scourge", --Undercity
[69] = "Interface\\Icons\\inv_misc_tournaments_banner_nightelf", --Darnassus
[72] = "Interface\\Icons\\inv_misc_tournaments_symbol_human", --Stormwind
[76] = "Interface\\Icons\\inv_misc_tournaments_symbol_orc", --Orgrimmar
[81] = "Interface\\Icons\\inv_misc_tournaments_symbol_tauren", --Thunder Bluff
[87] = "Interface\\Icons\\INV_Helmet_66", --Bloodsail Buccaneers
[529] = "Interface\\Icons\\inv_jewelry_talisman_07", --Argent Dawn
[530] = "Interface\\Icons\\inv_misc_tournaments_symbol_troll", --Darkspear Trolls
[576] = "Interface\\Icons\\achievement_reputation_timbermaw", --Timbermaw Hold
[589] = "Interface\\Icons\\Achievement_Zone_Winterspring", --Wintersaber Trainers
[609] = "Interface\\Icons\\ability_racial_ultravision", --Cenarion Circle
[910] = "Interface\\Icons\\inv_misc_head_dragon_bronze", --Brood of Nozdormu
-- BC
[911] = "Interface\\Icons\\inv_misc_tournaments_symbol_bloodelf", --Silvermoon City
[922] = "Interface\\Icons\\INV_Misc_Bandana_03", --Tranquillien
[930] = "Interface\\Icons\\inv_misc_tournaments_symbol_draenei", --Exodar
[932] = "Interface\\Icons\\spell_arcane_portalshattrath", --The Aldor
[933] = "Interface\\Icons\\inv_enchant_shardprismaticlarge", --The Consortium
[934] = "Interface\\Icons\\spell_arcane_portalshattrath", --The Scryers
[935] = "Interface\\Icons\\Spell_Nature_LightningOverload", --The Sha'tar
[941] = "Interface\\Icons\\inv_misc_foot_centaur", --The Mag'har
[942] = "Interface\\Icons\\ability_racial_ultravision", --Cenarion Expedition
[946] = "Interface\\Icons\\INV_BannerPVP_02", --Honor Hold
[947] = "Interface\\Icons\\INV_BannerPVP_01", --Thrallmar
[967] = "Interface\\Icons\\spell_holy_mindsooth", --The Violet Eye
[970] = "Interface\\Icons\\inv_mushroom_11", --Sporeggar
[978] = "Interface\\Icons\\inv_misc_foot_centaur", --Kurenai
[989] = "Interface\\Icons\\Ability_Warrior_VictoryRush", --Keepers of Time
[990] = "Interface\\Icons\\inv_enchant_dustillusion", --The Scale of the Sands
[1011] = "Interface\\Icons\\Ability_Rogue_MasterOfSubtlety", --Lower City
[1012] = "Interface\\Icons\\achievement_reputation_ashtonguedeathsworn", --Ashtongue Deathsworn
[1015] = "Interface\\Icons\\ability_mount_netherdrakepurple", --Netherwing
[1031] = "Interface\\Icons\\ability_hunter_pet_netherray", --Sha'tari Skyguard
[1038] = "Interface\\Icons\\inv_misc_apexis_crystal", --Ogri'la
[1077] = "Interface\\Icons\\inv_shield_48", --Shattered Sun Offensive
-- WotLK
[1037] = "Interface\\Icons\\spell_misc_hellifrepvphonorholdfavor", --Alliance Vanguard
[1052] = "Interface\\Icons\\spell_misc_hellifrepvpthrallmarfavor", --Horde Expedition
[1073] = "Interface\\Icons\\achievement_reputation_tuskarr", --The Kalu'ak
[1090] = "Interface\\Icons\\achievement_reputation_kirintor", --Kirin Tor
[1091] = "Interface\\Icons\\achievement_reputation_wyrmresttemple", --The Wyrmrest Accord
[1094] = "Interface\\Icons\\inv_elemental_primal_mana", --The Silver Covenant
[1098] = "Interface\\Icons\\achievement_reputation_knightsoftheebonblade", --Knights of the Ebon Blade
[1104] = "Interface\\Icons\\ability_mount_whitedirewolf", --Frenzyheart Tribe
[1105] = "Interface\\Icons\\inv_misc_head_murloc_01", --The Oracles
[1106] = "Interface\\Icons\\inv_jewelry_talisman_08", --Argent Crusade
[1119] = "Interface\\Icons\\spell_frost_wizardmark", --The Sons of Hodir
[1124] = "Interface\\Icons\\inv_elemental_primal_nether", --The Sunreavers
[1156] = "Interface\\Icons\\inv_jewelry_talisman_08", --The Ashen Verdict
-- Cata
[1133] = "Interface\\Icons\\inv_misc_tabard_kezan", --Bilgewater Cartel
[1134] = "Interface\\Icons\\inv_misc_tabard_gilneas", --Gilneas
[1135] = "Interface\\Icons\\inv_misc_tabard_earthenring", --The Earthen Ring
[1158] = "Interface\\Icons\\inv_misc_tabard_guardiansofhyjal", --Guardians of Hyjal
[1171] = "Interface\\Icons\\inv_misc_tabard_therazane", --Therazane
[1172] = "Interface\\Icons\\inv_misc_tabard_dragonmawclan", --Dragonmaw Clan
[1173] = "Interface\\Icons\\inv_misc_tabard_tolvir", --Ramkahen
[1174] = "Interface\\Icons\\inv_misc_tabard_wildhammerclan", --Wildhammer Clan
[1177] = "Interface\\Icons\\inv_misc_tabard_baradinwardens", --Baradin's Wardens
[1178] = "Interface\\Icons\\inv_misc_tabard_hellscream", --Hellscream's Reach
[1204] = "Interface\\Icons\\inv_neck_hyjaldaily_04", --Avengers of Hyjal
-- MoP
[1269] = "Interface\\Icons\\achievement_faction_goldenlotus", --Golden Lotus
[1270] = "Interface\\Icons\\achievement_faction_shadopan", --Shado Pan
[1271] = "Interface\\Icons\\achievement_faction_serpentriders", --Order of the Cloud Serpent
[1272] = "Interface\\Icons\\achievement_faction_tillers", --The Tillers
[1302] = "Interface\\Icons\\achievement_faction_anglers", --The Anglers
[1337] = "Interface\\Icons\\achievement_faction_klaxxi", --The Klaxxi
[1341] = "Interface\\Icons\\achievement_faction_celestials", --The August Celestials
[1345] = "Interface\\Icons\\achievement_faction_lorewalkers", --The Lorewalkers
[1352] = "Interface\\Icons\\inv_misc_tournaments_symbol_orc", --Huojin Pandaren
[1353] = "Interface\\Icons\\inv_misc_tournaments_symbol_human", --Tushui Pandaren
[1358] = "Interface\\Icons\\INV_Misc_Fishing_Raft", --Nat Pagle
[1375] = "Interface\\Icons\\achievement_general_hordeslayer", --Dominance Offensive
[1376] = "Interface\\Icons\\achievement_general_allianceslayer", --Operation: Shieldwall
[1387] = "Interface\\Icons\\achievement_reputation_kirintor_offensive", --Kirin Tor Offensive
[1388] = "Interface\\Icons\\achievement_faction_sunreaveronslaught", --Sunreaver Onslaught
[1435] = "Interface\\Icons\\achievement_faction_shadopan", --Shado-Pan Assault
[1492] = "Interface\\Icons\\ability_monk_quipunch", --Emperor Shaohao
-- WoD
[1445] = "Interface\\Icons\\inv_tabard_a_01frostwolfclan", --Frostwolf Orcs
[1515] = "Interface\\Icons\\inv_tabard_a_76arakkoaoutcast", --Arakkoa Outcasts
[1681] = "Interface\\Icons\\inv_tabard_a_77voljinsspear", --Vol'jin's Spear
[1682] = "Interface\\Icons\\inv_tabard_a_78wrynnvanguard", --Wrynn's Vanguard
[1708] = "Interface\\Icons\\inv_tabard_a_80laughingskull", --Laughing Skull Orcs
[1710] = "Interface\\Icons\\inv_tabard_a_shataridefense", --Sha'tari Defense
[1711] = "Interface\\Icons\\achievement_goblinhead", --Steamwheedle Perservation Society
[1731] = "Interface\\Icons\\inv_tabard_a_81exarchs", --Council of Exarchs
[1847] = "Interface\\Icons\\Achievement_Leader_Prophet_Velen", -- Hand of the Prophet
[1848] = "Interface\\Icons\\INV_Misc_VoljinsShatteredTusk", -- Vol'jin's Headhunters
[1849] = "Interface\\Icons\\INV_Tabard_A_82AwakenedOrder", -- Order of the Awakened
[1850] = "Interface\\Icons\\INV_Tabard_A_83SaberStalkers", -- The Saberstalkers
-- Legion
[1828] = "Interface\\Icons\\INV_Legion_Faction_HightmountainTribes", -- Highmountain Tribe
[1859] = "Interface\\Icons\\INV_Legion_Faction_NightFallen", -- The Nightfallen
[1883] = "Interface\\Icons\\INV_Legion_Faction_DreamWeavers", -- Dreamweavers
[1894] = "Interface\\Icons\\INV_Legion_Faction_Warden", -- The Wardens
[1900] = "Interface\\Icons\\INV_Legion_Faction_CourtofFarnodis", -- Court Of Farondis
[1948] = "Interface\\Icons\\INV_Legion_Faction_Valarjar", -- Valarjar
[2045] = "Interface\\Icons\\INV_Legion_Faction_LegionFall", -- Armies of Legionfall
[2165] = "Interface\\Icons\\INV_Legion_Faction_ArmyoftheLight", -- Army of the Light
[2170] = "Interface\\Icons\\INV_legion_Faction_ArgussianReach", -- Argussian Reach
}
local FACTION_KEY = {
-- Classic
[47] = "Ironforge",
[54] = "Gnomeregan",
[59] = "Thorium Brotherhood",
[68] = "Undercity",
[69] = "Darnassus",
[72] = "Stormwind",
[76] = "Orgrimmar",
[81] = "Thunder Bluff",
[87] = "Bloodsail Buccaneers",
[529] = "Argent Dawn",
[530] = "Darkspear Trolls",
[576] = "Timbermaw Hold",
[589] = "Wintersaber Trainers",
[609] = "Cenarion Circle",
[910] = "Brood of Nozdormu",
-- BC
[911] = "Silvermoon City",
[922] = "Tranquillien",
[930] = "Exodar",
[932] = "The Aldor",
[933] = "The Consortium",
[934] = "The Scryers",
[935] = "The Sha'tar",
[941] = "The Mag'har",
[942] = "Cenarion Expedition",
[946] = "Honor Hold",
[947] = "Thrallmar",
[967] = "The Violet Eye",
[970] = "Sporeggar",
[978] = "Kurenai",
[989] = "Keepers of Time",
[990] = "The Scale of the Sands",
[1011] = "Lower City",
[1012] = "Ashtongue Deathsworn",
[1015] = "Netherwing",
[1031] = "Sha'tari Skyguard",
[1038] = "Ogri'la",
[1077] = "Shattered Sun Offensive",
-- WotLK
[1037] = "Alliance Vanguard",
[1052] = "Horde Expedition",
[1073] = "The Kalu'ak",
[1090] = "Kirin Tor",
[1091] = "The Wyrmrest Accord",
[1094] = "The Silver Covenant",
[1098] = "Knights of the Ebon Blade",
[1104] = "Frenzyheart Tribe",
[1105] = "The Oracles",
[1106] = "Argent Crusade",
[1119] = "The Sons of Hodir",
[1124] = "The Sunreavers",
[1156] = "The Ashen Verdict",
-- Cata
[1133] = "Bilgewater Cartel",
[1134] = "Gilneas",
[1135] = "The Earthen Ring",
[1158] = "Guardians of Hyjal",
[1171] = "Therazane",
[1172] = "Dragonmaw Clan",
[1173] = "Ramkahen",
[1174] = "Wildhammer Clan",
[1177] = "Baradin's Wardens",
[1178] = "Hellscream's Reach",
[1204] = "Avengers of Hyjal",
-- MoP
[1269] = "Golden Lotus",
[1270] = "Shado-Pan",
[1271] = "Order of the Cloud Serpent",
[1272] = "The Tillers",
[1302] = "The Anglers",
[1337] = "The Klaxxi",
[1341] = "The August Celestials",
[1345] = "The Lorewalkers",
[1352] = "Huojin Pandaren",
[1353] = "Tushui Pandaren",
[1358] = "Nat Pagle",
[1375] = "Dominance Offensive",
[1376] = "Operation: Shieldwall",
[1387] = "Kirin Tor Offensive",
[1388] = "Sunreaver Onslaught",
[1435] = "Shado-Pan Assault",
[1492] = "Emperor Shaohao",
-- WoD
[1445] = "Frostwolf Orcs",
[1515] = "Arakkoa Outcasts",
[1681] = "Vol'jin's Spear",
[1682] = "Wrynn's Vanguard",
[1708] = "Laughing Skull Orcs",
[1710] = "Sha'tari Defense",
[1711] = "Steamwheedle Preservation Society",
[1731] = "Council of Exarchs",
[1847] = "Hand of the Prophet",
[1848] = "Vol'jin's Headhunters",
[1849] = "Order of the Awakened",
[1850] = "The Saberstalkers",
-- Legion
[1828] = "Highmountain Tribe",
[1859] = "The Nightfallen",
[1883] = "Dreamweavers",
[1894] = "The Wardens",
[1900] = "Court of Farondis",
[1948] = "Valarjar",
[2045] = "Armies of Legionfall",
[2165] = "Army of the Light",
[2170] = "Argussian Reach",
-- Bfa
--- Alliance
[2159] = "7th Legion",
[2160] = "Proudmoore Admiralty",
[2161] = "Order of Embers",
[2162] = "Storm's Wake",
--- Horde
[2157] = "The Honorbound",
[2103] = "Zandalari Empire",
[2156] = "Talanji's Expedition",
[2158] = "Voldunai",
--- All
[2163] = "Tortollan Seekers",
[2164] = "Champions of Azeroth",
}
local function GetLocRepStanding(id)
if (id > 10) then
return FRIEND_REP_TEXT[id] or FACTION_STANDING_LABEL4_FEMALE
else
return PlayerSex==3 and _G["FACTION_STANDING_LABEL"..(id or 4).."_FEMALE"] or _G["FACTION_STANDING_LABEL"..(id or 4)]
end
end
local function RGBToHex(t)
local r,g,b = t.r*255,t.g*255,t.b*255
r = r <= 255 and r >= 0 and r or 0
g = g <= 255 and g >= 0 and g or 0
b = b <= 255 and b >= 0 and b or 0
return str_format("%02x%02x%02x", r, g, b)
end
function Faction.OnSet(button, second)
if not FactionClickHandler then
FactionClickHandler = ClickHandler:Add(
"Faction",
{
--ChatLink = { "LeftButton", "Shift" },
types = {
--ChatLink = true,
},
},
AtlasLoot.db.Button.Faction.ClickHandler,
{
--{ "ChatLink", AL["Chat Link"], AL["Add item into chat"] },
}
)
PlayerSex = UnitSex("player")
FACTION_REP_COLORS = {}
for i = 1, #FACTION_BAR_COLORS do
FACTION_REP_COLORS[i] = RGBToHex(FACTION_BAR_COLORS[i])
end
RGBToHex = nil
end
if not button then return end
if second and button.__atlaslootinfo.secType then
if type(button.__atlaslootinfo.secType[2]) == "table" then
button.secButton.FactionID = button.__atlaslootinfo.secType[2][1]
button.secButton.RepID = button.__atlaslootinfo.secType[2][2]
else
button.secButton.FactionID = button.__atlaslootinfo.secType[2]
end
Faction.Refresh(button.secButton)
else
if type(button.__atlaslootinfo.type[2]) == "table" then
button.FactionID = button.__atlaslootinfo.type[2][1]
button.RepID = button.__atlaslootinfo.type[2][2]
else
button.FactionID = button.__atlaslootinfo.type[2]
end
Faction.Refresh(button)
end
end
function Faction.OnMouseAction(button, mouseButton)
if not mouseButton then return end
mouseButton = FactionClickHandler:Get(mouseButton)
--if mouseButton == "ChatLink" then
--end
end
function Faction.OnEnter(button, owner)
if not button.FactionID then return end
--[[
local tooltip = AtlasLoot.Tooltip:GetTooltip()
tooltip:ClearLines()
if owner and type(owner) == "table" then
tooltip:SetOwner(unpack(owner))
else
tooltip:SetOwner(button, "ANCHOR_RIGHT", -(button:GetWidth() * 0.5), 24)
end
local name, description, standingID, barMin, barMax, barValue, atWarWith, canToggleAtWar = GetFactionInfoByID(button.FactionID)
tooltip:AddLine(name)
tooltip:AddLine(description, 1, 1, 1, 1)
tooltip:AddLine(" ")
tooltip:AddLine(UnitName("player")..":")
tooltip:AddDoubleLine(COMBAT_FACTION_CHANGE, string.format("|cFF%s%s ( %d / %d )", FACTION_REP_COLORS[standingID], GetLocRepStanding(standingID), barValue-barMin, barMax-barMin) )
if canToggleAtWar then
tooltip:AddDoubleLine(AT_WAR, atWarWith and TT_YES_REV or TT_NO_REV)
end
tooltip:Show()
]]--
Faction.ShowToolTipFrame(button)
end
function Faction.OnLeave(button)
if Faction.tooltipFrame then
Faction.tooltipFrame:Hide()
end
end
function Faction.OnClear(button)
button.FactionID = nil
button.secButton.FactionID = nil
button.RepID = nil
button.secButton.RepID = nil
button.icon:SetDesaturated(false)
button.secButton.icon:SetDesaturated(false)
end
function Faction.GetStringContent(str)
if tonumber(str) then
return tonumber(str)
else
return {
tonumber(str_match(str, "(%d+)")),
tonumber(str_match(str, "rep(%d+)")), -- required rep (1-8)
}
end
end
function Faction.Refresh(button)
if not button.FactionID then return end
--friendID, friendRep, friendMaxRep, friendName, friendText, friendTexture, friendTextLevel, friendThreshold, nextFriendThreshold = GetFriendshipReputation(factionID)
local friendID = GetFriendshipReputation(button.FactionID)
-- name, description, standingID, barMin, barMax, barValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild = GetFactionInfoByID(factionID)
local name, _, standingID = GetFactionInfoByID(button.FactionID)
local color
if friendID and button.RepID then
color = "|cFF"..FACTION_REP_COLORS[button.RepID > 12 and 5 or 4]
else
color = "|cFF"..FACTION_REP_COLORS[button.RepID or standingID]
end
if button.type == "secButton" then
button:SetNormalTexture(FACTION_IMAGES[button.FactionID] or FACTION_IMAGES[0])
else
-- ##################
-- name
-- ##################
name = name or BF[FACTION_KEY[button.FactionID]] or FACTION.." "..button.FactionID
button.name:SetText(color..name)
--button.extra:SetText("|cFF"..FACTION_REP_COLORS[button.RepID or standingID]..GetLocRepStanding(button.RepID or standingID))
-- ##################
-- icon
-- ##################
button.icon:SetTexture(FACTION_IMAGES[button.FactionID] or FACTION_IMAGES[0])
local reqRepText = friendID and FRIEND_REP_TEXT[button.RepID] or GetLocRepStanding(button.RepID or standingID) or ""
if button.RepID and standingID and button.RepID > standingID then
button.icon:SetDesaturated(true)
button.extra:SetText("|cffff0000"..reqRepText)
elseif not standingID then
button.extra:SetText("|cffff0000"..reqRepText)
else
button.extra:SetText(color..reqRepText)
end
end
return true
end
function Faction.ShowToolTipFrame(button)
if not Faction.tooltipFrame then
local WIDTH = 200
local name = "AtlasLoot-FactionToolTip"
local frame = CreateFrame("Frame", name)
frame:SetClampedToScreen(true)
frame:SetWidth(WIDTH)
frame:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background",
edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 }})
frame:SetBackdropColor(0,0,0,1)
frame.icon = frame:CreateTexture(name.."-icon", frame)
frame.icon:SetPoint("TOPLEFT", frame, "TOPLEFT", 5, -5)
frame.icon:SetHeight(15)
frame.icon:SetWidth(15)
frame.icon:SetTexture(FACTION_IMAGES[0])
frame.name = frame:CreateFontString(name.."-name", "ARTWORK", "GameFontNormal")
frame.name:SetPoint("TOPLEFT", frame.icon, "TOPRIGHT", 3, 0)
frame.name:SetJustifyH("LEFT")
frame.name:SetWidth(WIDTH-25)
frame.name:SetHeight(15)
--frame.name:SetTextColor(1, 1, 1, 1)
frame.standing = CreateFrame("FRAME", name.."-standing", frame)
frame.standing:SetWidth(WIDTH-10)
frame.standing:SetHeight(20)
frame.standing:SetPoint("TOPLEFT", frame.icon, "BOTTOMLEFT", 0, -1)
frame.standing:SetBackdrop({bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 12,
insets = { left = 3, right = 3, top = 3, bottom = 3 }})
frame.standing:SetBackdropColor(0, 0, 0, 1)
frame.standing.bar = CreateFrame("StatusBar", name.."-standingBar", frame.standing)
frame.standing.bar:SetStatusBarTexture("Interface\\TARGETINGFRAME\\UI-StatusBar")
frame.standing.bar:SetPoint("TOPLEFT", 3, -3)
frame.standing.bar:SetPoint("BOTTOMRIGHT", -4, 3)
frame.standing.bar:GetStatusBarTexture():SetHorizTile(false)
frame.standing.bar:GetStatusBarTexture():SetVertTile(false)
frame.standing.text = frame.standing.bar:CreateFontString(name.."-standingText", "ARTWORK", "GameFontNormalSmall")
frame.standing.text:SetPoint("TOPLEFT", 3, -3)
frame.standing.text:SetPoint("BOTTOMRIGHT", -4, 3)
frame.standing.text:SetJustifyH("CENTER")
frame.standing.text:SetJustifyV("CENTER")
frame.standing.text:SetTextColor(1, 1, 1, 1)
frame.desc = frame:CreateFontString(name.."-desc", "ARTWORK", "GameFontNormalSmall")
frame.desc:SetPoint("TOPLEFT", frame.standing, "BOTTOMLEFT", 0, -1)
frame.desc:SetJustifyH("LEFT")
frame.desc:SetJustifyV("TOP")
frame.desc:SetWidth(WIDTH-10)
frame.desc:SetTextColor(1, 1, 1, 1)
Faction.tooltipFrame = frame
end
local frame = Faction.tooltipFrame
local name, description, standingID, barMin, barMax, barValue = GetFactionInfoByID(button.FactionID)
standingID = standingID or 1
local colorIndex = standingID
local factionStandingtext
local friendID, friendRep, _, _, _, _, friendTextLevel, friendThreshold, nextFriendThreshold = GetFriendshipReputation(button.FactionID)
if friendID then
factionStandingtext = friendTextLevel
if ( nextFriendThreshold ) then
barMin, barMax, barValue = friendThreshold, nextFriendThreshold, friendRep
else
-- max rank, make it look like a full bar
barMin, barMax, barValue = 0, 1, 1;
end
colorIndex = 5
else
barMin, barMax, barValue = barMin or 0, barMax or 1, barValue or 0
factionStandingtext = GetLocRepStanding(standingID)
end
frame:ClearAllPoints()
frame:SetParent(button:GetParent():GetParent())
frame:SetFrameStrata("TOOLTIP")
frame:SetPoint("BOTTOMLEFT", button, "TOPRIGHT")
frame.icon:SetTexture(FACTION_IMAGES[button.FactionID] or FACTION_IMAGES[0])
frame.name:SetText(name or "Faction "..button.FactionID)
frame.desc:SetText(description)
frame.standing.bar:SetMinMaxValues(barMin, barMax)
frame.standing.bar:SetValue(barValue)
local color = FACTION_BAR_COLORS[colorIndex]
frame.standing.bar:SetStatusBarColor(color.r, color.g, color.b)
frame.standing.text:SetText(str_format("%s ( %d / %d )", factionStandingtext, barValue - barMin, barMax - barMin))
frame:SetHeight(20+21+frame.desc:GetHeight()+5)
frame:Show()
end
|
local factory = require("items/factory_sange_yasha_kaya")
DeclarePassiveAbility("item_sange_and_yasha_and_kaya", "modifier_item_sange_and_yasha_and_kaya")
LinkLuaModifier("modifier_item_sange_and_yasha_and_kaya", "items/item_sange_and_yasha_and_kaya.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_sange_and_yasha_and_kaya_maim", "items/item_sange_and_yasha_and_kaya.lua", LUA_MODIFIER_MOTION_NONE)
modifier_item_sange_and_yasha_and_kaya, modifier_item_sange_and_yasha_and_kaya_maim = factory(
{ sange = "modifier_item_sange_and_yasha_and_kaya_maim", yasha = true, kaya = true }
)
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP")
--[ CONEXÃO ]----------------------------------------------------------------------------------------------------------------------------
banK = {}
Tunnel.bindInterface("vrp_banco",banK)
Proxy.addInterface("vrp_banco",banK)
--[ VARIÁVEIS ]--------------------------------------------------------------------------------------------------------------------------
local recompensa = 0
local andamento = false
local dinheirosujo = {}
--[ LOCAIS ]-----------------------------------------------------------------------------------------------------------------------------
local caixas = {
[1] = { ['seconds'] = 25 },
[2] = { ['seconds'] = 39 },
[3] = { ['seconds'] = 39 },
[4] = { ['seconds'] = 35 },
[5] = { ['seconds'] = 33 },
[6] = { ['seconds'] = 33 },
[7] = { ['seconds'] = 55 },
[8] = { ['seconds'] = 39 },
[9] = { ['seconds'] = 35 },
[10] = { ['seconds'] = 60 },
[11] = { ['seconds'] = 43 },
[12] = { ['seconds'] = 27 },
[13] = { ['seconds'] = 45 },
[14] = { ['seconds'] = 120 }
}
--[ WEBHOOKS ]---------------------------------------------------------------------------------------------------------------------------
local webhookDepositar = ""
local webhookSacar = ""
local webhookPTrans = ""
local webhookPSacar = ""
local webhookRCaixaEletronico = ""
--[ PAGAR MULTAS ]-----------------------------------------------------------------------------------------------------------------------
RegisterCommand('multas',function(source,args,rawCommand)
local source = source
local user_id = vRP.getUserId(source)
local value = vRP.getUData(parseInt(user_id),"vRP:multas")
local multas = json.decode(value) or 0
local banco = vRP.getBankMoney(user_id)
if user_id then
if args[1] == nil then
if multas >= 1 then
TriggerClientEvent("Notify",source,"aviso","Você possuí <b>$"..multas.." dólares em multas</b> para pagar.",8000)
else
TriggerClientEvent("Notify",source,"aviso","Você <b>não possuí</b> multas para pagar.",8000)
end
elseif args[1] == "pagar" then
local valorpay = vRP.prompt(source,"Saldo de multas: $"..multas.." - Valor de multas a pagar:","")
if banco >= parseInt(valorpay) then
if parseInt(valorpay) <= parseInt(multas) then
vRP.setBankMoney(user_id,parseInt(banco-valorpay))
vRP.setUData(user_id,"vRP:multas",json.encode(parseInt(multas)-parseInt(valorpay)))
TriggerClientEvent("Notify",source,"sucesso","Você pagou <b>$"..valorpay.." dólares</b> em multas.",8000)
else
TriggerClientEvent("Notify",source,"negado","Você não pode pagar mais multas do que deve.",8000)
end
else
TriggerClientEvent("Notify",source,"negado","Você não tem dinheiro em sua conta suficiente para isso.",8000)
end
end
end
end)
--[ DEPOSITAR ]--------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('banco:depositar')
AddEventHandler('banco:depositar', function(amount)
local _source = source
local user_id = vRP.getUserId(_source)
if amount == nil or amount <= 0 or amount > vRP.getMoney(user_id) then
TriggerClientEvent("Notify",_source,"negado","Valor inválido")
else
vRP.tryDeposit(user_id, tonumber(amount))
TriggerClientEvent("Notify",_source,"sucesso","Você depositou <b>$"..amount.." dólares</b>.")
end
end)
--[ SACAR ]------------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('banco:sacar')
AddEventHandler('banco:sacar', function(amount)
local _source = source
local user_id = vRP.getUserId(_source)
amount = tonumber(amount)
local getbankmoney = vRP.getBankMoney(user_id)
if amount == nil or amount <= 0 or amount > getbankmoney then
TriggerClientEvent("Notify",_source,"negado","Valor inválido")
else
vRP.tryWithdraw(user_id,amount)
TriggerClientEvent("Notify",_source,"sucesso","Você sacou <b>$"..amount.." dólares</b>.")
end
end)
--[ PAGAR ]------------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('banco:pagar')
AddEventHandler('banco:pagar', function(amount)
local _source = source
local user_id = vRP.getUserId(_source)
local banco = vRP.getBankMoney(user_id)
local valor = tonumber(amount)
if banco >= tonumber(amount) then
local multas = vRP.getUData(user_id,"vRP:multas")
local int = parseInt(multas)
if int >= valor then
if valor > 999 then
local rounded = math.ceil(valor)
local novamulta = int - rounded
vRP.setUData(user_id,"vRP:multas",json.encode(novamulta))
vRP.setBankMoney(user_id,banco-tonumber(valor))
TriggerClientEvent("Notify",_source,"sucesso","Você pagou $"..valor.." em multas.")
TriggerClientEvent("currentbalance2",_source)
else
TriggerClientEvent("Notify",_source,"negado","Você só pode pagar multas acima de <b>$1.000</b> dólares")
end
else
TriggerClientEvent("Notify",_source,"negado","Você não pode pagar mais multas do que possuí.")
end
else
TriggerClientEvent("Notify",_source,"negado","Saldo inválido.")
end
end)
--[ SALDO ]------------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('banco:balance')
AddEventHandler('banco:balance', function()
local _source = source
local user_id = vRP.getUserId(_source)
local getbankmoney = vRP.getBankMoney(user_id)
local multasbalance = vRP.getUData(user_id,"vRP:multas")
TriggerClientEvent("currentbalance1",_source,addComma(math.floor(getbankmoney)),multasbalance)
end)
--[ TRANSFERENCIAS ]---------------------------------------------------------------------------------------------------------------------
RegisterServerEvent('banco:transferir')
AddEventHandler('banco:transferir', function(to,amountt)
local _source = source
local user_id = vRP.getUserId(_source)
local identity = vRP.getUserIdentity(user_id)
local _nplayer = vRP.getUserSource(parseInt(to))
local nuser_id = vRP.getUserId(_nplayer)
local identitynu = vRP.getUserIdentity(nuser_id)
local banco = 0
if nuser_id == nil then
TriggerClientEvent("Notify",_source,"negado","Passaporte inválido ou indisponível.")
else
if nuser_id == user_id then
TriggerClientEvent("Notify",_source,"negado","Você não pode transferir dinheiro para sí mesmo.")
else
local banco = vRP.getBankMoney(user_id)
local banconu = vRP.getBankMoney(nuser_id)
if banco <= 0 or banco < tonumber(amountt) or tonumber(amountt) <= 0 then
TriggerClientEvent("Notify",_source,"negado","Dinheiro Insuficiente")
else
vRP.setBankMoney(user_id,banco-tonumber(amountt))
vRP.setBankMoney(nuser_id,banconu+tonumber(amountt))
TriggerClientEvent("Notify",_nplayer,"sucesso","<b>"..identity.name.." "..identity.firstname.."</b> depositou <b>$"..amountt.." dólares</b> na sua conta.")
TriggerClientEvent("Notify",_source,"sucesso","Você transferiu <b>$"..amountt.." dólares</b> para conta de <b>"..identitynu.name.." "..identitynu.firstname.."</b>.")
end
end
end
end)
--[ TEMPO ]------------------------------------------------------------------------------------------------------------------------------
local timers = {}
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
for k,v in pairs(timers) do
if v > 0 then
timers[k] = v - 1
end
end
end
end)
--[ CHECKROBBERY ]-----------------------------------------------------------------------------------------------------------------------
function banK.checkRobbery(id,x,y,z,head)
local source = source
local user_id = vRP.getUserId(source)
local policia = vRP.getUsersByPermission("policia-ptr.permissao")
local identity = vRP.getUserIdentity(user_id)
if user_id then
if #policia <= 2 then
TriggerClientEvent("Notify",source,"aviso","Número insuficiente de policiais em patrulha no momento.",8000)
else
if timers[id] == 0 or not timers[id] then
timers[id] = 600
andamento = true
dinheirosujo = {}
dinheirosujo[user_id] = caixas[id].seconds
vRPclient.setStandBY(source,parseInt(800))
recompensa = parseInt(math.random(2000,8000)/caixas[id].seconds)
TriggerClientEvent('iniciandocaixaeletronico',source,x,y,z,caixas[id].seconds,head)
vRPclient._playAnim(source,false,{{"anim@heists@ornate_bank@grab_cash_heels","grab"}},true)
for l,w in pairs(policia) do
local player = vRP.getUserSource(parseInt(w))
if player then
async(function()
TriggerClientEvent('blip:criar:caixaeletronico',player,x,y,z)
vRPclient.playSound(player,"Oneshot_Final","MP_MISSION_COUNTDOWN_SOUNDSET")
TriggerClientEvent('chatMessage',player,"911",{64,64,255},"O roubo começou no ^1Caixa Eletrônico^0, dirija-se até o local e intercepte os assaltantes.")
end)
end
end
PerformHttpRequest(webhookRCaixaEletronico, function(err, text, headers) end, 'POST', json.encode({
embeds = {
{
title = "REGISTRO DE ASSALTO:",
thumbnail = {
url = "https://i.imgur.com/5ydYKZg.png"
},
fields = {
{
name = "**IDENTIFICAÇÃO DO PLAYER:**",
value = "**"..identity.name.." "..identity.firstname.."** [**"..user_id.."**] \n⠀"
},
{
name = "**LUCRO DO ASSALTO:**",
value = "**$"..parseInt(recompensa).." dólares**\n⠀"
},
},
footer = {
text = os.date("\n[Data]: %d/%m/%Y [Hora]: %H:%M:%S"),
icon_url = "https://i.imgur.com/5ydYKZg.png"
},
color = 15906321
}
}
}), { ['Content-Type'] = 'application/json' })
SetTimeout(caixas[id].seconds*1000,function()
if andamento then
andamento = false
for l,w in pairs(policia) do
local player = vRP.getUserSource(parseInt(w))
if player then
async(function()
TriggerClientEvent('blip:remover:caixaeletronico',player)
TriggerClientEvent('chatMessage',player,"911",{64,64,255},"O roubo terminou, os assaltantes estão correndo antes que vocês cheguem.")
end)
end
end
end
end)
else
TriggerClientEvent("Notify",source,"aviso","O caixa eletrônico está vazio, aguarde <b>"..timers[id].." segundos</b> até que tenha dinheiro novamente.",8000)
end
end
end
end
--[ CANCELROBBERY ]----------------------------------------------------------------------------------------------------------------------
function banK.cancelRobbery()
if andamento then
andamento = false
local policia = vRP.getUsersByPermission("dpla-ptr.permissao")
for l,w in pairs(policia) do
local player = vRP.getUserSource(parseInt(w))
if player then
async(function()
TriggerClientEvent('blip:remover:caixaeletronico',player)
TriggerClientEvent('chatMessage',player,"911",{64,64,255},"O assaltante saiu correndo e deixou tudo para trás.")
end)
end
end
end
end
--[ PAYMENTROBBERY ]---------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
if andamento then
for k,v in pairs(dinheirosujo) do
if v > 0 then
dinheirosujo[k] = v - 1
vRP._giveInventoryItem(k,"dinheiro-sujo",recompensa)
end
end
end
end
end)
--[ CHECK PERMISSIONS ]------------------------------------------------------------------------------------------------------------------
function banK.checkPermission()
local source = source
local user_id = vRP.getUserId(source)
return not (vRP.hasPermission(user_id,"policia-ptr.permissao") or vRP.hasPermission(user_id,"policia.permissao") or vRP.hasPermission(user_id,"ems.permissao") or vRP.hasPermission(user_id,"paisana-ems.permissao"))
end
function banK.giveDebitCard()
local source = source
local user_id = vRP.getUserId(source)
if vRP.getInventoryWeight(user_id) + vRP.getItemWeight("cartao-debito") <= vRP.getInventoryMaxWeight(user_id) then
if vRP.getInventoryItemAmount(user_id,"cartao-debito") > 0 then
TriggerClientEvent("Notify",source,"negado","Você já possui um cartão de débito em sua mochila.")
else
local bank = vRP.getBankMoney(user_id)
if bank >= 170 then
vRP.setBankMoney(user_id,bank-170)
vRP.giveInventoryItem(user_id,"cartao-debito",1)
TriggerClientEvent("Notify",source,"sucesso","Sucesso, você adquiriu o seu cartão de débito por <b>$170 dólares</b>.")
else
TriggerClientEvent("Notify",source,"negado","Saldo insuficiente para contratar o seu cartão de débito.")
end
end
else
TriggerClientEvent("Notify",source,"negado","Sua mochila está cheia.")
end
end
--[ TESTE ]------------------------------------------------------------------------------------------------------------------------------
function round(num, numDecimalPlaces)
local mult = 5^(numDecimalPlaces or 0)
if num and type(num) == "number" then
return math.floor(num * mult + 0.5) / mult
end
end
function addComma(amount)
local formatted = amount
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1.%2')
if (k==0) then
break
end
end
return formatted
end
|
local settings_prefix= "/" .. THEME:GetThemeDisplayName() .. "_settings/"
global_cur_game= GAMESTATE:GetCurrentGame():GetName():lower()
function force_table_elements_to_match_type(candidate, must_match, depth_remaining)
for k, v in pairs(candidate) do
if type(must_match[k]) ~= type(v) then
candidate[k]= nil
elseif type(v) == "table" and depth_remaining ~= 0 then
force_table_elements_to_match_type(v, must_match[k], depth_remaining-1)
end
end
for k, v in pairs(must_match) do
if type(candidate[k]) == "nil" then
if type(v) == "table" then
candidate[k]= DeepCopy(v)
else
candidate[k]= v
end
end
end
end
local function slot_to_prof_dir(slot, reason)
local prof_dir= "Save"
if slot and slot ~= "ProfileSlot_Invalid" then
prof_dir= PROFILEMAN:GetProfileDir(slot)
if not prof_dir or prof_dir == "" then
--Warn("Could not fetch profile dir to " .. reason .. ".")
return
end
end
return prof_dir
end
local function load_conf_file(fname)
local file= RageFileUtil.CreateRageFile()
local ret= {}
if file:Open(fname, 1) then
local data= loadstring(file:Read())
setfenv(data, {})
local success, data_ret= pcall(data)
if success then
ret= data_ret
end
file:Close()
end
file:destroy()
return ret
end
local setting_mt= {
__index= {
init= function(self, name, file, default, match_depth)
assert(type(default) == "table", "default for setting must be a table.")
self.name= name
self.file= file
self.default= default
self.match_depth= match_depth
self.dirty_table= {}
self.data_set= {}
return self
end,
load= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
local prof_dir= slot_to_prof_dir(slot, "read " .. self.name)
if not prof_dir then
self.data_set[slot]= DeepCopy(self.default)
else
local fname= prof_dir .. settings_prefix .. self.file
if not FILEMAN:DoesFileExist(fname) then
self.data_set[slot]= DeepCopy(self.default)
else
local from_file= load_conf_file(fname)
if type(from_file) == "table" then
if self.match_depth and self.match_depth ~= 0 then
force_table_elements_to_match_type(
from_file, self.default, self.match_depth-1)
end
self.data_set[slot]= from_file
else
self.data_set[slot]= DeepCopy(self.default)
end
end
end
return self.data_set[slot]
end,
get_data= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
return self.data_set[slot] or self.default
end,
set_data= function(self, slot, data)
slot= slot or "ProfileSlot_Invalid"
self.data_set[slot]= data
end,
set_dirty= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
self.dirty_table[slot]= true
end,
check_dirty= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
return self.dirty_table[slot]
end,
clear_slot= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
self.dirty_table[slot]= nil
self.data_set[slot]= nil
end,
save= function(self, slot)
slot= slot or "ProfileSlot_Invalid"
if not self:check_dirty(slot) then return end
local prof_dir= slot_to_prof_dir(slot, "write " .. self.name)
if not prof_dir then return end
local fname= prof_dir .. settings_prefix .. self.file
local file_handle= RageFileUtil.CreateRageFile()
if not file_handle:Open(fname, 2) then
Warn("Could not open '" .. fname .. "' to write " .. self.name .. ".")
else
local output= "return " .. lua_table_to_string(self.data_set[slot])
file_handle:Write(output)
file_handle:Close()
file_handle:destroy()
end
end,
save_all= function(self)
for slot, data in pairs(self.data_set) do
self:save(slot)
end
end
}}
function create_setting(name, file, default, match_depth)
return setmetatable({}, setting_mt):init(name, file, default, match_depth)
end
function write_str_to_file(str, fname, str_name)
local file_handle= RageFileUtil.CreateRageFile()
if not file_handle:Open(fname, 2) then
Warn("Could not open '" .. fname .. "' to write " .. str_name .. ".")
else
file_handle:Write(str)
file_handle:Close()
file_handle:destroy()
end
end
function string_needs_escape(str)
if str:match("^[a-zA-Z_][a-zA-Z_0-9]*$") then
return false
else
return true
end
end
function lua_table_to_string(t, indent, line_pos)
indent= indent or ""
line_pos= (line_pos or #indent) + 1
local internal_indent= indent .. " "
local ret= "{"
local has_table= false
for k, v in pairs(t) do if type(v) == "table" then has_table= true end
end
if has_table then
ret= "{\n" .. internal_indent
line_pos= #internal_indent
end
local separator= ""
local function do_value_for_key(k, v, need_key_str)
if type(v) == "nil" then return end
local k_str= k
if type(k) == "number" then
k_str= "[" .. k .. "]"
else
if string_needs_escape(k) then
k_str= "[" .. ("%q"):format(k) .. "]"
else
k_str= k
end
end
if need_key_str then
k_str= k_str .. "= "
else
k_str= ""
end
local v_str= ""
if type(v) == "table" then
v_str= lua_table_to_string(v, internal_indent, line_pos + #k_str)
elseif type(v) == "string" then
v_str= ("%q"):format(v)
elseif type(v) == "number" then
if v ~= math.floor(v) then
v_str= ("%.6f"):format(v)
local last_nonz= v_str:reverse():find("[^0]")
if last_nonz then
v_str= v_str:sub(1, -last_nonz)
end
else
v_str= tostring(v)
end
else
v_str= tostring(v)
end
local to_add= k_str .. v_str
if type(v) == "table" then
if separator == "" then
to_add= separator .. to_add
else
to_add= separator .."\n" .. internal_indent .. to_add
end
else
if line_pos + #separator + #to_add > 80 then
line_pos= #internal_indent + #to_add
to_add= separator .. "\n" .. internal_indent .. to_add
else
to_add= separator .. to_add
line_pos= line_pos + #to_add
end
end
ret= ret .. to_add
separator= ", "
end
-- do the integer indices from 0 to n first, in order.
do_value_for_key(0, t[0], true)
for n= 1, #t do
do_value_for_key(n, t[n], false)
end
for k, v in pairs(t) do
local is_integer_key= (type(k) == "number") and (k == math.floor(k)) and k >= 0 and k <= #t
if not is_integer_key then
do_value_for_key(k, v, true)
end
end
ret= ret .. "}"
return ret
end
local slot_conversion= {
[PLAYER_1]= "ProfileSlot_Player1", [PLAYER_2]= "ProfileSlot_Player2",}
function pn_to_profile_slot(pn)
return slot_conversion[pn] or "ProfileSlot_Invalid"
end |
local app = require 'app'
local Gamestate = require 'vendor/gamestate'
local window = require 'window'
local fonts = require 'fonts'
local TunnelParticles = require "tunnelparticles"
local flyin = Gamestate.new()
local sound = require 'vendor/TEsound'
local Timer = require 'vendor/timer'
local Character = require 'character'
function flyin:init( )
TunnelParticles:init()
end
function flyin:enter( prev )
self.flying = {}
self.characterorder = {}
for i,c in pairs(Character.characters) do
if c.name ~= Character.name then
table.insert(self.characterorder, c.name)
end
end
self.characterorder = table.shuffle( self.characterorder, 5 )
table.insert( self.characterorder, Character.name )
local time = 0
for _,name in pairs( self.characterorder ) do
Timer.add(time, function()
table.insert( self.flying, {
n = name,
c = name == Character.name and Character.costume or Character:findRelatedCostume(name),
x = window.width / 2,
y = window.height / 2,
t = math.random( ( math.pi * 2 ) * 10000 ) / 10000,
r = n == Character.name and 0 or ( math.random( 4 ) - 1 ) * ( math.pi / 2 ),
s = 0.1,
show = true
})
end)
time = time + 0.4
end
end
function flyin:draw()
TunnelParticles.draw()
love.graphics.circle( 'fill', window.width / 2, window.height / 2, 30 )
--draw in reverse order, so the older ones get drawn on top of the newer ones
for i = #flyin.flying, 1, -1 do
local v = flyin.flying[i]
if v.show then
love.graphics.setColor( 255, 255, 255, 255 )
Character.characters[v.n].animations.flyin:draw( Character:getSheet(v.n,v.c), v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 )
-- black mask while coming out of 'tunnel'
if v.s <= 1 then
love.graphics.setColor( 0, 0, 0, 255 * ( 1 - v.s ) )
Character.characters[v.n].animations.flyin:draw( Character:getSheet(v.n,v.c), v.x, v.y, v.r - ( v.r % ( math.pi / 2 ) ), math.min(v.s,5), math.min(v.s,5), 22, 32 )
end
end
end
end
function flyin:startGame(dt)
local gamesave = app.gamesaves:active()
local point = gamesave:get('savepoint', {level='studyroom', name='main'})
Gamestate.switch(point.level, point.name)
end
function flyin:keypressed(button)
Timer.clear()
self:startGame()
end
function flyin:update(dt)
TunnelParticles.update(dt)
for k,v in pairs(flyin.flying) do
if v.n ~= Character.name then
v.x = v.x + ( math.cos( v.t ) * dt * v.s * 90 )
v.y = v.y + ( math.sin( v.t ) * dt * v.s * 90 )
end
v.s = v.s + dt * 4
v.r = v.r + dt * 5
if v.s >= 6 then
v.show = false
end
end
if not flyin.flying[ #flyin.flying ].show then
Timer.clear()
self:startGame()
end
end
return flyin
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {},
Category = "Tick_FounderStageDone",
Effects = {},
Enabled = true,
Image = "UI/Messages/Events/06_space_suit.tga",
Prerequisites = {
PlaceObj('CheckObjectCount', {
'Label', "Colonist",
'Filters', {},
'Condition', ">=",
'Amount', 50,
}),
PlaceObj('CheckObjectCount', {
'Label', "ShuttleHub",
'Filters', {},
'Condition', ">=",
'Amount', 1,
}),
PlaceObj('PickFromLabel', {
'Label', "Colonist",
'Conditions', {
PlaceObj('HasTrait', {
'Trait', "Child",
'Negate', true,
}),
},
}),
},
ScriptDone = true,
Text = T(268319532855, --[[StoryBit WatcherInTheSky Text]] "The signal seems harmless but can very well be a spying device.\n\nDo we ignore it? "),
TextReadyForValidation = true,
TextsDone = true,
Title = T(348128839780, --[[StoryBit WatcherInTheSky Title]] "The Watcher"),
VoicedText = T(284947371309, --[[voice:narrator]] "A faint signal was traced to originate from the high mountains just outside our Colony's vicinity."),
group = "Colonists",
id = "WatcherInTheSky",
PlaceObj('StoryBitReply', {
'Text', T(982697491816, --[[StoryBit WatcherInTheSky Text]] "Send a Colonist in a Shuttle to investigate."),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('ActivateStoryBit', {
'Id', "WatcherInTheSky_2",
'ForcePopup', false,
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(567951828202, --[[StoryBit WatcherInTheSky Text]] "Jam the signal and carry on."),
}),
})
|
{{$gEmoji:=`<:yag:277569741932068864>`}}
{{/*Code*/}}
{{ $data:=sdict}}
{{$compareEmoji:=.Reaction.Emoji.Name}}
{{with reFindAllSubmatches `(\d+)>\z` $gEmoji}}{{$gEmoji =index . 0 1}}{{$compareEmoji =str $.Reaction.Emoji.ID}}{{end}}
{{if and (eq $compareEmoji $gEmoji) (not .User.Bot)}}
{{with (dbGet 7777 "giveaway_active").Value}}{{$data =sdict .}}{{end}}
{{$giveawayData := $data.Get (joinStr "" .Reaction.ChannelID .Reaction.MessageID)}}
{{if $giveawayData}}
{{$giveawayData =sdict $giveawayData}}
{{$IDregex:=print .User.ID ","}}
{{if .ReactionAdded}}{{$amount:=1}}{{if reFind $IDregex $giveawayData.listID}}{{$giveawayData.Set "listID" (reReplace $IDregex $giveawayData.listID "")}}{{$amount =0}}{{end}}{{$giveawayData.Set "listID" (print $giveawayData.listID $IDregex)}}{{$giveawayData.Set "count" (add $giveawayData.count $amount)}}
{{else}}{{if reFind $IDregex $giveawayData.listID}}{{$giveawayData.Set "listID" (reReplace $IDregex $giveawayData.listID "")}}{{$giveawayData.Set "count" (add $giveawayData.count -1)}}{{end}}
{{end}}
{{$data.Set (joinStr "" .Reaction.ChannelID .Reaction.MessageID) $giveawayData}}{{dbSet 7777 "giveaway_active" $data}}
{{end}}
{{end}}
|
local M = {}
local ADDR = 0x23 -- Addr L
local COMMAND = 0x20 -- One time H-resolution mode
local i2c = i2c
local ID = 0 -- Always sero
function M.init(sda, scl)
i2c.setup(ID, sda, scl, i2c.SLOW)
end
local function read_data_from_bh1750(address)
i2c.start(ID)
i2c.address(ID, address, i2c.TRANSMITTER)
i2c.write(ID, COMMAND)
i2c.stop(ID)
i2c.start(ID)
i2c.address(ID, address,i2c.RECEIVER)
tmr.delay(185000) -- Wait to complete H-resolution mode measurement max. 180 ms
data = i2c.read(ID, 2)
i2c.stop(ID)
return data
end
function M.read_lux()
data_string = read_data_from_bh1750(ADDR)
data = data_string:byte(1) * 256 + data_string:byte(2)
lux = (data / 1.2) -- H-reslution mode : Illuminance per 1 count ( lx / count ) = 1 / 1.2
return(lux)
end
return M
|
runer=loadfile("./ldoc/ldoc.lua")
runer() |
---@type cc.Sprite
local Sprite = cc.Sprite
---
---@param path string
---@param size size_table
---@return cc.Sprite
function Sprite:createWithSVGFile(path, size)
local img = cc.Image()
img:initWithSVGFile(unpack({ path, size }))
local tex = cc.Texture2D()
tex:initWithImage(img)
return cc.Sprite:createWithTexture(tex)
end
---
---@param b lstg.Buffer buffer which holds the image data.
---@return boolean true if loaded correctly.
function Sprite:createWithImageData(b)
local img = cc.Image()
img:initWithImageData(b)
local tex = cc.Texture2D()
tex:initWithImage(img)
return cc.Sprite:createWithTexture(tex)
end
--- warning: only support RGBA8888
---@param b lstg.Buffer
---@param width number
---@param height number
---@param bitsPerComponent number
---@param preMulti boolean
---@return boolean
function Sprite:createWithRawData(b, width, height, bitsPerComponent, preMulti)
local img = cc.Image()
img:initWithRawData(unpack({ b, width, height, bitsPerComponent, preMulti }))
local tex = cc.Texture2D()
tex:initWithImage(img)
return cc.Sprite:createWithTexture(tex)
end
--- clone sprite
---@return cc.Sprite
function Sprite:clone()
return cc.Sprite:createWithSpriteFrame(self:getSpriteFrame())
end
|
local M = {}
local usage = [[
Usage: check-republic SUBCOMMAND
Example: check-republic install
CLI helper for the check-republic daemon
Options:
-h, --help Display this help
Available commands:
help Display this help
install Install the check-republic service and daemon
list List all checks
run Run all checks]]
function M.process()
print(usage)
end
return M
|
local module = ...
local mqtt = require('mqtt_ws')
local settings = require('settings')
local device_id = wifi.sta.getmac():lower():gsub(':','')
local c = mqtt.Client(settings.aws)
local topics = settings.aws.topics
local sendTimer = tmr.create()
local timeout = tmr.create()
local heartbeat = tmr.create()
timeout:register(3000, tmr.ALARM_SEMI, function()
sensorPut[1].retry = (sensorPut[1].retry or 0) + 1
sensorPut[1].message_id = nil
sendTimer:start()
end)
sendTimer:register(200, tmr.ALARM_AUTO, function(t)
local sensor = sensorPut[1]
if sensor then
t:stop()
if sensor.retry and sensor.retry > 0 then
print("Heap:", node.heap(), "Retry:", sensor.retry)
end
if sensor.retry and sensor.retry > 10 then
print("Heap:", node.heap(), "Retried 10 times and failed. Rebooting in 30 seconds.")
for k, v in pairs(sensorPut) do sensorPut[k] = nil end -- remove all pending sensor updates
tmr.create():alarm(30000, tmr.ALARM_SINGLE, function() node.restart() end) -- reboot in 30 sec
else
local message_id = c.msg_id
local topic = sensor.topic or topics.sensor
sensor.device_id = device_id
print("Heap:", node.heap(), "PUBLISH", "Message ID:", message_id, "Topic:", topic, "Payload:", sjson.encode(sensor))
timeout:start()
c:publish(topic, sensor)
sensor.message_id = message_id
end
end
end)
heartbeat:register(200, tmr.ALARM_AUTO, function(t)
local hb = require('server_status')()
hb.topic = topics.heartbeat
hb.timestamp = rtctime.get()
table.insert(sensorPut, hb)
t:interval(300000) -- 5 minutes
end)
local function startLoop()
print("Heap:", node.heap(), 'Connecting to AWS IoT Endpoint:', settings.endpoint)
c:on('offline', function()
print("Heap:", node.heap(), "mqtt: offline")
sendTimer:stop()
c:connect(settings.endpoint)
end)
c:connect(settings.endpoint)
end
c:on('puback', function(_, message_id)
print("Heap:", node.heap(), 'PUBACK', 'Message ID:', message_id)
local sensor = sensorPut[1]
if sensor and sensor.message_id == message_id then
table.remove(sensorPut, 1)
blinktimer:start()
timeout:stop()
sendTimer:start()
end
end)
c:on('message', function(_, topic, message)
print("Heap:", node.heap(), 'topic:', topic, 'msg:', message)
local payload = sjson.decode(message)
require("switch")(payload)
-- publish the new state after actuating switch
table.insert(sensorPut, { pin = payload.pin, state = gpio.read(payload.pin) })
end)
c:on('connect', function()
print("Heap:", node.heap(), "mqtt: connected")
print("Heap:", node.heap(), "Subscribing to topic:", topics.switch)
c:subscribe(topics.switch)
-- update current state of actuators upon boot
for i, actuator in pairs(actuatorGet) do
table.insert(sensorPut, { pin = actuator.pin, state = gpio.read(actuator.pin) })
end
heartbeat:start()
sendTimer:start()
end)
return function()
package.loaded[module] = nil
module = nil
return startLoop()
end |
return function()
clr_timers()
local tt = tmr.create()
table.insert(timers, tt)
local r, g ,b = 0, 0, 0
tt:alarm(30, tmr.ALARM_AUTO, function()
buf:fill(0, 0, 0)
if math.random(1,6) >= 4 then
for i = 1,3 do
g, r, b = leds.hsv2grb(0, 0, val)
buf:set(math.random(1,101), r, g, b)
end
end
buf:set(1, 0, 0, 0)
ws2812.write(buf)
end)
end
|
function write_doc(parsed_data, file_name)
-- Set the general anchor
local anchor = "__" .. parsed_data.title .. "__"
local title = parsed_data.title
if (title:match("^[A-Z][a-z]") and
not title:match("^Data") and
not title:match("^Df") and
not title:match("^Batc")) then
title = title:sub(1,1):lower() .. title:sub(2)
end
local header = ("# API documentation for [%s](#%s)"):
format(title, anchor)
for i=1,#parsed_data.anchors.tags do
header = header .. get_anchor_link(parsed_data.anchors.titles[i], nil, parsed_data.anchors.tags[i], "")
end
local docfile = io.open(file_name, "w")
docfile:write(header)
docfile:write(("\n\n<a name=\"%s\">\n%s"):format(anchor, parsed_data.content))
docfile:close()
end
|
Camera = {
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
--Initialize the x and y coordinates of Camera to a starter value
x = 0,
y = 0
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
function Camera.update(dt)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[CODE 5 LINES] Make the camera move to the left and right with the left and right arrow keys. Exactly the same as Quiddtich
if love.keyboard.isDown("right") then --RIGHT ARROW BUTTON IS DOWN then
Camera.x = Camera.x + 5
elseif love.keyboard.isDown("left") then
Camera.x = Camera.x - 5
end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[CODE 5 LINES] Make the camera move to the up and down with the up and down arrow keys. Exactly the same as Quiddtich
if love.keyboard.isDown("up") then
Camera.y = Camera.y - 5
elseif love.keyboard.isDown("down") then
Camera.y = Camera.y + 5
end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
end
function Camera:follow(dt, rider)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Make Camera.x and Camera.y follow the rider. Exactly the same as Quidditch
Camera.x = rider.body:getX() - love.graphics.getWidth()/2
Camera.y = rider.body:getY() - love.graphics.getHeight()/2
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
end
|
local errors = require('errors')
errors.deprecate(
"Module `cartridge.graphql.schema` is deprecated." ..
" Use `require('graphql.schema')` instead."
)
return require('graphql.schema')
|
data:extend
{
{
type = "equipment-grid",
name = "electric-vehicles-electric-car",
width = 10,
height = 5,
equipment_categories = {"armor", "electric-vehicles-equipment"},
},
{
type = "equipment-grid",
name = "electric-vehicles-electric-locomotive",
width = 10,
height = 10,
equipment_categories = {"armor", "electric-vehicles-equipment"},
},
{
type = "equipment-grid",
name = "electric-vehicles-electric-tank",
width = 10,
height = 10,
equipment_categories = {"armor", "electric-vehicles-equipment"},
},
{
type = "battery-equipment",
name = "electric-vehicles-lo-voltage-transformer",
sprite =
{
filename = "__Laser_Tanks_kr__/graphics/equipment/lo-voltage-transformer.png",
width = 32,
height = 64,
priority = "medium"
},
shape =
{
width = 1,
height = 2,
type = "full"
},
energy_source =
{
type = "electric",
buffer_capacity = math.ceil(300 / 60) .. "kJ",
input_flow_limit = 300 .. "kW",
output_flow_limit = "0W",
usage_priority = "primary-input"
},
categories = {"electric-vehicles-equipment"},
},
{
type = "battery-equipment",
name = "electric-vehicles-hi-voltage-transformer",
sprite =
{
filename = "__Laser_Tanks_kr__/graphics/equipment/hi-voltage-transformer.png",
width = 64,
height = 64,
priority = "medium"
},
shape =
{
width = 2,
height = 2,
type = "full"
},
energy_source =
{
type = "electric",
buffer_capacity = math.ceil(5 / 60) .. "MJ",
input_flow_limit = 5 .. "MW",
output_flow_limit = "0W",
usage_priority = "primary-input"
},
categories = {"electric-vehicles-equipment"},
},
{
type = "battery-equipment",
name = "electric-vehicles-regen-brake-controller",
sprite =
{
filename = "__Laser_Tanks_kr__/graphics/equipment/regen-brake-controller.png",
width = 64,
height = 64,
priority = "medium"
},
shape =
{
width = 2,
height = 2,
type = "full"
},
energy_source =
{
type = "electric",
buffer_capacity = math.ceil(10 / 60) .. "MJ",
input_flow_limit = "0MW",
output_flow_limit = 10 .. "MW",
usage_priority = "primary-output"
},
categories = {"electric-vehicles-equipment"},
},
}
--if mods["vtk-armor-plating"] then
-- table.insert(data.raw["equipment-grid"]["electric-vehicles-electric-locomotive"].equipment_categories,"vtk-armor-plating")
-- table.insert(data.raw["equipment-grid"]["electric-vehicles-electric-car"].equipment_categories,"vtk-armor-plating")
-- table.insert(data.raw["equipment-grid"]["electric-vehicles-electric-tank"].equipment_categories,"vtk-armor-plating")
--end |
function foo()
function bar() end
-- body
end |
local moon = require("moon")
local test_assert = require("test_assert")
moon.start(
function()
moon.async(
function()
local receiverid =
moon.co_new_service(
"lua",
{
name = "call_example_receiver",
file = "call_example_receiver.lua"
}
)
print(moon.co_call("lua", receiverid, "SUB", 1000, 2000))
local res = moon.co_call("lua", receiverid, "SUB", 1000, 2000)
test_assert.equal(res, -1000)
res = moon.co_call("lua", receiverid, "ACCUM", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
test_assert.equal(res, 136)
--This call will got error message:
res = moon.co_call("lua", receiverid, "ADD", 100, 99)
test_assert.equal(res, false)
res = moon.co_call("lua", receiverid, "SUB", 100, 99)
test_assert.equal(res, 1)
--Let receiver exit:
moon.co_call("lua", receiverid, "EXIT")
test_assert.success()
end
)
end
)
|
local playsession = {
{"Menander", {1618689}},
{"ohmygodism", {3683}},
{"MetonymicalInsanity", {1573433}},
{"ultrajer", {1473774}},
{"Kokori", {144964}},
{"Duchesko", {675244}},
{"lemarkiz", {437624}},
{"Nikkichu", {862196}},
{"rlidwka", {1476443}},
{"Gerkiz", {412141}},
{"foggyliziouz", {934385}},
{"VB11", {718118}},
{"marklinCZ", {338651}},
{"Wesoly1234", {11606}},
{"pfd", {265683}},
{"toddrofls", {604314}},
{"bigoz72", {89816}},
{"Zillo7", {302680}},
{"Bartell", {28604}},
{"Nagrom_17", {7344}},
{"Hiero", {757538}},
{"ausmister", {476568}},
{"realDonaldTrump", {881411}},
{"Mullacs", {310954}},
{"helic99", {1066}},
{"Spelling_A", {175914}},
{"Frosty1098", {159118}},
{"Troubletime", {372733}},
{"zopieux", {302431}},
{"CustomSocks", {585099}},
{"ksb4145", {303270}},
{"fractaldelic", {822}},
{"sixtothegrave", {38703}},
{"bdgray02", {272052}},
{"Jularen", {257272}},
{"StormBreaker", {8026}},
{"NicolaasZA", {3582}},
{"Keo_nix", {167951}},
{"MECH4NIKER", {6698}},
{"RebuffedBrute44", {257300}},
{"Tracolix", {256512}},
{"Mselvage1231", {1284}},
{"jagger23", {115410}},
{"mars_precision", {6049}},
{"DrunkBoxer", {244955}},
{"marathonman", {5260}},
{"seirjgkemn", {26467}},
{"Bryce940", {22119}},
{"Miguel724", {4453}}
}
return playsession |
local palette_data = {}
local GetColorFromHexStr = function(str)
local color = {
a = 0,
r = 0,
g = 0,
b = 0
}
local tmp = {}
for cc in string.gmatch(str, "..") do
table.insert(tmp, tonumber(cc, 16))
end
color.a = tmp[1] / 255
color.r = tmp[2] / 255
color.g = tmp[3] / 255
color.b = tmp[4] / 255
return color
end
-- https://lospec.com/palette-list/summers-past-16
local _colors = {'FF320011', 'FF5f3a60', 'FF876672', 'FFb7a39d', 'FFece8c2', 'FF6db7c3', 'FF5e80b2', 'FF627057',
'FF8da24e', 'FFd2cb3e', 'FFf7d554', 'FFe8bf92', 'FFe78c5b', 'FFc66f5e', 'FFc33846', 'FF933942'}
local colors = {}
for _, c in ipairs(_colors) do
table.insert(colors, GetColorFromHexStr(c))
end
palette_data.colors = colors
palette_data.black = colors[1]
palette_data.white = colors[5]
palette_data.blue = colors[6]
palette_data.green = colors[10]
palette_data.red = colors[14]
palette_data.main_colors = {palette_data.black, palette_data.white, palette_data.blue, palette_data.green,
palette_data.red}
palette_data.foreground_color = colors[5]
palette_data.background_color = colors[16]
palette_data.border_color = colors[1]
return palette_data
|
local seafoam_islands_0 = DoorSlot("seafoam_islands","0")
local seafoam_islands_0_hub = DoorSlotHub("seafoam_islands","0",seafoam_islands_0)
seafoam_islands_0:setHubIcon(seafoam_islands_0_hub)
local seafoam_islands_1 = DoorSlot("seafoam_islands","1")
local seafoam_islands_1_hub = DoorSlotHub("seafoam_islands","1",seafoam_islands_1)
seafoam_islands_1:setHubIcon(seafoam_islands_1_hub)
local seafoam_islands_2 = DoorSlot("seafoam_islands","2")
local seafoam_islands_2_hub = DoorSlotHub("seafoam_islands","2",seafoam_islands_2)
seafoam_islands_2:setHubIcon(seafoam_islands_2_hub)
local seafoam_islands_3 = DoorSlot("seafoam_islands","3")
local seafoam_islands_3_hub = DoorSlotHub("seafoam_islands","3",seafoam_islands_3)
seafoam_islands_3:setHubIcon(seafoam_islands_3_hub)
local seafoam_islands_4 = DoorSlot("seafoam_islands","4")
local seafoam_islands_4_hub = DoorSlotHub("seafoam_islands","4",seafoam_islands_4)
seafoam_islands_4:setHubIcon(seafoam_islands_4_hub)
local seafoam_islands_5 = DoorSlot("seafoam_islands","5")
local seafoam_islands_5_hub = DoorSlotHub("seafoam_islands","5",seafoam_islands_5)
seafoam_islands_5:setHubIcon(seafoam_islands_5_hub)
local seafoam_islands_6 = DoorSlot("seafoam_islands","6")
local seafoam_islands_6_hub = DoorSlotHub("seafoam_islands","6",seafoam_islands_6)
seafoam_islands_6:setHubIcon(seafoam_islands_6_hub)
local seafoam_islands_7 = DoorSlot("seafoam_islands","7")
local seafoam_islands_7_hub = DoorSlotHub("seafoam_islands","7",seafoam_islands_7)
seafoam_islands_7:setHubIcon(seafoam_islands_7_hub)
local seafoam_islands_8 = DoorSlot("seafoam_islands","8")
local seafoam_islands_8_hub = DoorSlotHub("seafoam_islands","8",seafoam_islands_8)
seafoam_islands_8:setHubIcon(seafoam_islands_8_hub)
local seafoam_islands_9 = DoorSlot("seafoam_islands","9")
local seafoam_islands_9_hub = DoorSlotHub("seafoam_islands","9",seafoam_islands_9)
seafoam_islands_9:setHubIcon(seafoam_islands_9_hub)
local seafoam_islands_10 = DoorSlot("seafoam_islands","10")
local seafoam_islands_10_hub = DoorSlotHub("seafoam_islands","10",seafoam_islands_10)
seafoam_islands_10:setHubIcon(seafoam_islands_10_hub)
local seafoam_islands_11 = DoorSlot("seafoam_islands","11")
local seafoam_islands_11_hub = DoorSlotHub("seafoam_islands","11",seafoam_islands_11)
seafoam_islands_11:setHubIcon(seafoam_islands_11_hub)
local seafoam_islands_12 = DoorSlot("seafoam_islands","12")
local seafoam_islands_12_hub = DoorSlotHub("seafoam_islands","12",seafoam_islands_12)
seafoam_islands_12:setHubIcon(seafoam_islands_12_hub)
local seafoam_islands_13 = DoorSlot("seafoam_islands","13")
local seafoam_islands_13_hub = DoorSlotHub("seafoam_islands","13",seafoam_islands_13)
seafoam_islands_13:setHubIcon(seafoam_islands_13_hub)
local seafoam_islands_14 = DoorSlot("seafoam_islands","14")
local seafoam_islands_14_hub = DoorSlotHub("seafoam_islands","14",seafoam_islands_14)
seafoam_islands_14:setHubIcon(seafoam_islands_14_hub)
local seafoam_islands_15 = DoorSlot("seafoam_islands","15")
local seafoam_islands_15_hub = DoorSlotHub("seafoam_islands","15",seafoam_islands_15)
seafoam_islands_15:setHubIcon(seafoam_islands_15_hub)
local seafoam_islands_16 = DoorSlot("seafoam_islands","16")
local seafoam_islands_16_hub = DoorSlotHub("seafoam_islands","16",seafoam_islands_16)
seafoam_islands_16:setHubIcon(seafoam_islands_16_hub)
local seafoam_islands_17 = DoorSlot("seafoam_islands","17")
local seafoam_islands_17_hub = DoorSlotHub("seafoam_islands","17",seafoam_islands_17)
seafoam_islands_17:setHubIcon(seafoam_islands_17_hub)
local seafoam_islands_18 = DoorSlot("seafoam_islands","18")
local seafoam_islands_18_hub = DoorSlotHub("seafoam_islands","18",seafoam_islands_18)
seafoam_islands_18:setHubIcon(seafoam_islands_18_hub)
|
DefineClass.CargoTransporter = {
__parents = { "Object", "TaskRequester" },
properties = {
{ category = "CargoTransporter", id = "name", name = T(1000037, "Name"), editor = "text", default = ""},
{ template = true, category = "CargoTransporter", name = T(757, "Cargo Capacity (kg)"), id = "cargo_capacity", editor = "number", default = 10000, min = 0, max = 1000000, modifiable = true, help = "The amount of available cargo capacity." },
},
keep_cargo_in_labels = false,
cargo = false,
demand = false,
supply = false,
}
function CargoTransporter:GameInit()
self.cargo = self.cargo or {}
self.drones_entering = {}
self.drones_exiting = {}
end
function CargoTransporter:HasAutoMode()
return false
end
function CreateEmptyManifest()
local manifest = {}
manifest.drones = 0
manifest.rovers = {}
manifest.passengers = {}
manifest.prefabs = {}
return manifest
end
function CreateManifest(cargo)
local manifest = CreateEmptyManifest()
local transportable_rovers = table.filter(cargo, function(k, v) return IsKindOf(g_Classes[k], "BaseRover") end)
for _,entry in pairs(transportable_rovers) do
local count = entry.requested or 0
manifest.rovers[entry.class] = count > 0 and count or nil
end
manifest.drones = cargo["Drone"] and cargo["Drone"].requested or nil
for _,specialization in ipairs(GetSortedColonistSpecializationTable()) do
local count = cargo[specialization] and cargo[specialization].requested or 0
manifest.passengers[specialization] = count > 0 and count or nil
end
local prefabs = table.filter(cargo, function(k, v) return BuildingTemplates[k] end)
for _,entry in pairs(prefabs) do
local count = entry.requested or 0
manifest.prefabs[entry.class] = count > 0 and count or nil
end
return manifest
end
function CargoTransporter:SetCargoAmount(class_id, amount)
if not self.cargo[class_id] then
self.cargo[class_id] = {
class = class_id,
requested = 0,
amount = 0,
}
end
self.cargo[class_id].amount = amount
end
function CargoTransporter:GetCargoAmount(class_id)
return self.cargo[class_id] and self.cargo[class_id].amount or 0
end
function CargoTransporter:GetCargoRequested(class_id)
return self.cargo[class_id] and self.cargo[class_id].requested or 0
end
function CargoTransporter:GetCargoRemaining(class_id)
local cargo = self.cargo[class_id]
if cargo then
return cargo.requested - cargo.amount
else
return 0
end
end
function CargoTransporter:GetCargoItemStatus(item)
local remaining = (item.requested or 0) - item.amount
local cargo_type = GetCargoType(item.class)
local total_pending = GetTotalCargoPending(self.city, item.class)
local available = GetTotalCargoAvailable(self.city, cargo_type, item.class)
return GetAvailabilityStatus(remaining, total_pending, available)
end
function CargoTransporter:GetCargoStatus(class_id)
local cargo = self.cargo[class_id]
if cargo then
return self:GetCargoItemStatus(cargo)
else
return AvailabilityStatus.None
end
end
function CargoTransporter:AddCargoAmount(class_id, amount)
self:SetCargoAmount(class_id, self:GetCargoAmount(class_id) + amount)
end
function CargoTransporter:UnitDropCargoOnLoad()
return false
end
function CargoTransporter:Load(manifest, quick_load, transfer_available)
assert(manifest)
self.boarding = {}
self.departures = {}
self.cargo = self.cargo or {}
local succeed, rovers, drones, crew, prefabs = self:GatherAvailableCargo(manifest, quick_load, transfer_available)
if not transfer_available then
while not succeed do
Sleep(1000)
succeed, rovers, drones, crew, prefabs = self:GatherAvailableCargo(manifest, quick_load, transfer_available)
end
end
self:ExpeditionLoadDrones(drones)
self:AddCargoAmount("Drone", #drones)
for _,rover in pairs(rovers) do
if self:UnitDropCargoOnLoad() and IsKindOf(rover, "RCTransport") then
rover:ReturnStockpiledResources()
end
rover:SetCommand("EnterTransporter", self)
self:AddCargoAmount(rover.class, 1)
end
self:ExpeditionLoadCrew(crew)
for _,member in pairs(crew) do
if member.traits.Tourist then
self:AddCargoAmount("Tourist", 1)
else
self:AddCargoAmount(member.specialist, 1)
end
end
for _,prefab in pairs(prefabs) do
self:AddCargoAmount(prefab.class, prefab.amount)
self.city:AddPrefabs(prefab.class, -prefab.amount, false)
end
return rovers, drones, crew, prefabs
end
-- This is an alias for a function that was renamed
function CargoTransporter:Find(...) return self:GatherAvailableCargo(...) end
function CargoTransporter:GatherAvailableCargo(manifest, quick_load, transfer_available)
-- find vehicles
local rovers = {}
for rover_type, count in pairs(manifest.rovers) do
local new_rovers = self:GatherAvailableRovers(rover_type, count, quick_load, transfer_available) or empty_table
if not quick_load and not transfer_available and #new_rovers < count then
return false
end
table.iappend(rovers, new_rovers)
end
-- pick the required number of drones uniformly from hubs in range
local drones = {}
if manifest.drones and manifest.drones > 0 then
drones = self:GatherAvailableDrones(manifest.drones, quick_load)
if not quick_load and not transfer_available and #drones < manifest.drones then
return false
end
end
-- wait to have enough potential crew, set command, wait them to board
local crew = {}
for specialization, count in pairs(manifest.passengers) do
local new_crew = self:GatherAvailableColonists(count, specialization, quick_load, transfer_available) or empty_table
if not quick_load and not transfer_available and #new_crew < count then
return false
end
table.iappend(crew, new_crew)
end
-- wait till all prefabs are available to be loaded
local prefabs = {}
local manifest_prefabs = table.filter(manifest.prefabs, function(k, v) return v > 0 end)
for prefab,count in pairs(manifest_prefabs) do
local available_count = self:GatherAvailablePrefabs(count, prefab)
if not quick_load and not transfer_available and available_count < count then
return false
end
table.insert(prefabs, {class = prefab, amount = available_count})
end
return true, rovers, drones, crew, prefabs
end
local function FilterColonists(colonists, label, amount)
local all_filter = function(i, col)
return (label == "Colonist" or col.traits[label])
end
local adult_filter = function(i, col)
return not col.traits.Child and all_filter(i, col)
end
local list = table.ifilter(colonists or empty_table, adult_filter)
if #list < amount then
list = table.ifilter(colonists or empty_table, all_filter)
end
return list
end
function CargoTransporter:GatherAvailableColonists(amount, label, quick_load, transfer_available)
label = label or "Colonist"
local colonists = self.city.labels.Colonist or empty_table
colonists = quick_load and colonists or table.ifilter(colonists, function(_, unit) return not unit.thread_running_destructors end)
local idle_colonists = table.ifilter(colonists, function(_, unit) return table.find({"Idle", "Abandoned"}, unit.command) end)
local list = FilterColonists(idle_colonists, label, amount)
if #list < amount then
local busy_colonists = table.ifilter(colonists, function(_, unit) return not table.find(idle_colonists, unit) end)
local remaining = amount - #list
local remainder = FilterColonists(busy_colonists, label, amount)
for i = 1, #remainder do list[#list + 1] = remainder[i] end
end
if #list >= amount or quick_load or transfer_available then
local crew = {}
while #list > 0 and #crew < amount do
local unit = table.rand(list, InteractionRand("PickCrew"))
table.remove_value(list, unit)
table.insert(crew, unit)
end
return crew
else
return {}
end
end
function CargoTransporter:ExpeditionLoadCrew(crew)
for _,unit in pairs(crew) do
unit:SetCommand("EnterTransporter", self)
end
end
function CargoTransporter:GatherAvailablePrefabs(amount, prefab)
local city = self.city or MainCity
local available_prefabs = city:GetPrefabs(prefab)
if available_prefabs >= amount then
return amount
else
return available_prefabs
end
end
function CargoTransporter:WaitToFinishDisembarking(crew)
while #crew > 0 do
for _,unit in ipairs(crew) do
if unit.command~="ReturnFromExpedition" then
table.remove_value(crew, unit)
end
end
Sleep(1000)
end
end
function GetBestAvailableDroneFrom(controller, picked, filter)
local drone = nil
for _, d in ipairs(controller.drones or empty_table) do
if d:CanBeControlled() and not table.find(picked, d) then
if (not filter or filter(d)) then
if not drone or (drone.command ~= "Idle" and d.command == "Idle") then -- prefer idling drones
drone = d
end
end
end
end
return drone
end
function GatherBestAvailableDrones(drones, amount, city, filter)
local list = table.copy(city.labels.DroneControl or empty_table)
local idx = 1
while #drones < amount and #list > 0 do
local drone = GetBestAvailableDroneFrom(list[idx], drones, filter)
if drone then
table.insert(drones, drone)
idx = idx + 1
else
table.remove(list, idx)
end
if idx > #list then
idx = 1
end
end
end
local function GatherAvailableDronesWithFilter(drones, amount, obj, filter)
-- prefer own drones first
while #drones < amount and #(obj:HasMember("drones") and obj.drones or empty_table) > 0 do
local drone = GetBestAvailableDroneFrom(obj, drones, filter)
if not drone then
break
end
table.insert(drones, drone)
end
-- pick orphaned drones
GatherAvailableOrphanedDrones(drones, amount, obj, filter)
-- pick from other drone controllers
GatherBestAvailableDrones(drones, amount, obj.city, filter)
end
function GatherAvailableOrphanedDrones(drones, amount, obj, filter)
local available_orphaned_drones = table.copy(g_OrphanedDrones[obj:GetMapID()] or empty_table)
while #drones < amount do
local drone = FindClosest(available_orphaned_drones, obj)
if not drone then return end
if (not filter or filter(drone)) then
table.insert(drones, drone)
table.remove_value(available_orphaned_drones, drone)
end
end
end
local function DroneApproachingRocket(drone)
if drone.s_request then
local target_building = drone.s_request:GetBuilding()
if IsKindOf(target_building, "RocketBase") and table.find(target_building.drones_entering, drone) then
return true
end
end
return false
end
local function GetAvailableDronesFilter(drone)
local available = not drone.resource and drone.command ~= "Deliver" and not drone.holder and not drone.thread_running_destructors
available = available and drone.command ~= "Charge"
available = available and not DroneApproachingRocket(drone)
return available
end
function CargoTransporter:GatherAvailableDrones(amount, quick_load)
local found_drones = {}
GatherAvailableDronesWithFilter(found_drones, amount, self, GetAvailableDronesFilter)
-- Check if it's an availability issue
if #found_drones < amount then
-- Try finding all drones available drones
local available_drones = table.copy(found_drones)
GatherAvailableDronesWithFilter(available_drones, amount, self, nil)
if quick_load then
found_drones = table.copy(available_drones)
end
end
return found_drones
end
function CargoTransporter:ExpeditionLoadRover(rover) -- backwards compatibility
rover:SetCommand("EnterTransporter", self)
end
function CargoTransporter:ExpeditionLoadDrones(found_drones)
for idx, d in ipairs(found_drones or empty_table) do
if not GetAvailableDronesFilter(d) then
-- Filter failed, but we have to load the drones
-- Check if drone needs to be removed from approaching rocket
if DroneApproachingRocket(d) then
local rocket = d.s_request:GetBuilding()
table.remove_entry(rocket.drones_entering, d)
end
-- Kill current drone and respawn it so it can be loaded safely
d:DespawnNow()
d = self.city:CreateDrone()
d.init_with_command = false
d:SetCommandCenter(self)
found_drones[idx] = d
end
end
for _, drone in ipairs(found_drones) do
drone:SetCommand("EnterTransporter", self)
end
end
function CargoTransporter:GatherAvailableRovers(class, amount, quick_load, transfer_available)
local list = self:ListAvailableRovers(class, quick_load)
if #list < amount then
return (quick_load or transfer_available) and list or empty_table
end
local candidates = {}
for _, unit in ipairs(list) do
local d = self:GetDist2D(unit)
table.insert(candidates, {
rover = unit,
distance = d,
})
end
table.sortby_field(candidates, "distance")
local rovers = {}
for i = 1, amount do
rovers[i] = candidates[i].rover
end
return rovers
end
function CargoTransporter:ListAvailableRovers(class, quick_load)
local filter = function(index, unit)
return unit.class == class and unit:CanBeControlled() and not unit.holder and (quick_load or unit:IsIdle())
end
local rovers_list = self.city.labels[class] or empty_table
local available_list = table.ifilter(rovers_list, filter)
return available_list
end
function CargoTransporter:AttachRovers(rovers)
for n,rover in ipairs(rovers) do
if n > 2 then break end
self:Attach(rover, self:GetSpotBeginIndex("Roverdock"..n))
if n == 1 then
rover:ClearGameFlags(const.gofSpecialOrientMode)
end
if rover:HasState("idleRocket") then
rover:SetState("idleRocket")
end
end
end
function CargoTransporter:SpawnRovers()
local rovers = { transports = {} }
local map_id = self:GetMapID()
for _,item in pairs(self.cargo or emptry_table) do
if IsKindOf(g_Classes[item.class], "BaseRover") and item.amount > 0 then
while item.amount > 0 do
local rover = PlaceObjectIn(item.class, map_id, {city = self.city, override_ui_status = "Disembarking"})
rover:SetHolder(self)
rovers[#rovers + 1] = rover
item.amount = item.amount - 1
if IsKindOf(rover, "RCRover") then
rover.sieged_state = false
end
end
end
end
return rovers
end
function CargoTransporter:PlaceAdjacent(obj, def_pt, set_pos, move)
local placement = self.placement
local radius = obj:HasMember("GetDestlockRadius") and obj:GetDestlockRadius() or obj:GetRadius()
local target_pt
local adjacent
local my_rad = self:GetRadius()
my_rad = my_rad * my_rad
-- artificially increase the radius for a sparser placement
radius = MulDivRound(radius, 150, 100)
if #placement == 0 then
-- no objects placed, pick the default pt
target_pt = def_pt
adjacent = {}
elseif #placement == 1 then
-- only one object placed, pick a point in the direction of default
local dir = (def_pt - placement[1].center):SetZ(0)
target_pt = placement[1].center + SetLen(dir, placement[1].radius + radius)
adjacent = { 1 }
else
-- two or more objects: pick an object at random and one adjacent to it, then
-- try the centers of the two circles touching the two picked ones (one on each side)
local objs = table.copy(placement, "deep") -- code below modifies adjacency structures, using a copy
local valid = {}
-- build a list of indices of valid starting objecets
for i = 1, #objs do
valid[i] = i
end
local terrain = GetTerrain(self)
while not target_pt and #valid > 0 do
local obj_idx, idx = table.rand(valid, InteractionRand("RocketUnload"))
local obj = objs[obj_idx]
if #obj.adjacent == 0 then
-- obj is no longer a valid pick, remove from valid (not from objs, as it would invalidate adjacencies)
table.remove(valid, idx)
else
local obj_idx2, idx2 = table.rand(obj.adjacent, InteractionRand("RocketUnload"))
local obj2 = objs[obj_idx2]
local d1 = obj.radius + obj2.radius
local d2 = obj.radius + radius
local d3 = obj2.radius + radius
assert(d1 > 0 and d2 > 0 and d3 > 0)
-- the centers of the 3 circles form a triangle with sides of length d1, d2 and d3
-- calculate the angle at 'obj' using cosine theorem
local cos_alpha = MulDivRound(4096, (-d3 * d3 + d1 * d1 + d2 * d2), (2 * d1 * d2)) -- scale 4096
local angle = acos(cos_alpha)
-- align a vector to the known side of the triangle, resize it to match the desired length
local v = SetLen((obj2.center - obj.center):SetZ(0), d2)
for i = 1, 2 do
if not target_pt then
-- rotate the vector using the calculated angle to get the 3rd point of the triangle
target_pt = obj.center + Rotate(v, angle)
-- check if valid
if not terrain:IsPassable(target_pt) or target_pt:Dist2(self:GetPos()) < my_rad then --2 close 2 rocket or not passable.
target_pt = false
else
for j = 1, #placement do
if j ~= obj_idx2 and j ~= obj_idx and placement[j].center:Dist2D(target_pt) < placement[j].radius + radius then
--DbgAddCircle(target_pt, radius, const.clrRed)
target_pt = false
break
end
end
end
end
if target_pt then
assert(target_pt:Dist2D(obj.center) < d2 + 10*guic and target_pt:Dist2D(obj2.center) < d3 + 10*guic)
break
end
-- invert angle and try placing on the opposite side
angle = -angle
end
-- if both points aren't valid remove adjacency between obj and obj2 for this placement
if not target_pt then
table.remove_entry(obj.adjacent, obj_idx2)
table.remove_entry(obj2.adjacent, obj_idx)
else
adjacent = { obj_idx, obj_idx2 }
end
end
end
end
local realm = GetRealm(self)
target_pt = realm:SnapToTerrain(target_pt or def_pt)
adjacent = adjacent or ""
placement[#placement + 1] = {
--obj = obj,
center = target_pt,
x = target_pt:x(),
y = target_pt:y(),
radius = radius,
adjacent = adjacent,
}
if move then
Movable.Goto(obj, target_pt) -- Unit.Goto is a command, use this instead for direct control
end
if set_pos then
obj:SetPos(target_pt)
end
--DbgAddCircle(target_pt, radius, const.clrGreen)
for i = 1, #adjacent do
local idx = adjacent[i]
local tbl = placement[idx].adjacent
tbl[#tbl + 1] = #placement
--DbgAddVector(placement[idx].center, target_pt - placement[idx].center, const.clrBlue)
end
return target_pt
end
function CargoTransporter:UnloadRovers(rovers, out)
local rc_rovers = {}
local angle = self:GetAngle()
if #rovers > 0 then
local first_rover = rovers[1]
if IsKindOf(first_rover, "RCRover") then
rc_rovers[1] = first_rover
end
local realm = GetRealm(self)
local def_out_1 = out + SetLen((out - self:GetPos()):SetZ(0), 25*guim)
local out_1 = realm:GetPassablePointNearby(def_out_1, first_rover.pfclass)
out_1 = self:PlaceAdjacent(first_rover, out_1 or def_out_1)
out = realm:GetPassablePointNearby(out, first_rover.pfclass) or out
self:PlaceAdjacent(first_rover, out) --block out so they don't park right @ the ramp exit.
first_rover:Detach()
first_rover:SetGameFlags(const.gofSpecialOrientMode)
first_rover:SetAngle(angle)
first_rover:SetPos(out)
first_rover:SetAnim(1, "disembarkUnload", const.eDontCrossfade)
Sleep(first_rover:TimeToAnimEnd())
first_rover:SetHolder(false)
first_rover.override_ui_status = nil
first_rover:SetCommand("Goto", out_1)
Sleep(1000) --disembark 2 anim is kinda quick so give it a sec
if #rovers > 1 then
--generate positions
local positions = {}
for i = #rovers, 2, -1 do
if IsKindOf(rovers[i], "RCRover") then
rc_rovers[#rc_rovers + 1] = rovers[i]
end
positions[i] = self:PlaceAdjacent(rovers[i], out_1)
end
for i = 2, #rovers do
local rover = rovers[i]
rover:Detach()
rover:SetAngle(angle)
rover:SetPos(out)
rover:SetAnim(1, "disembarkUnload2", const.eDontCrossfade)
Sleep(rover:TimeToAnimEnd())
rover:SetHolder(false)
rover.override_ui_status = nil
rover:SetCommand("Goto", positions[i])
Sleep(1000) --disembark 2 anim is kinda quick so give it a sec
end
end
end
--re enable auto siege mode on RC Commanders
for i = 1, #rc_rovers do
local rc_rover = rc_rovers[i]
rc_rover.sieged_state = true
if rc_rover.command == "Idle" then --otherwise player is touching it.
rc_rover:SetCommand("Idle")
end
end
end
function CargoTransporter:PickArrivalPos(center, dir, max_radius, min_radius, max_angle, min_angle)
min_radius = min_radius or 0
if not dir or not center then
local spot = self:GetSpotBeginIndex("Colonistout")
local pos, angle = self:GetSpotLoc(spot)
center = center or pos
dir = dir or (pos - self:GetPos()):SetZ(0)
end
local terrain = GetTerrain(self)
local mw, mh = terrain:GetMapSize()
if center == InvalidPos() then
center = point(mw / 2, mh / 2)
end
--DbgClearVectors()
--DbgAddVector(center, dir, const.clrWhite)
for j = 1, 25 do
local r = SetLen(dir, Random(min_radius, max_radius))
local v = Rotate(r, Random(min_angle, max_angle))
local pt = v + center
local x, y = pt:x(), pt:y()
x = Clamp(x, guim, mw - guim)
y = Clamp(y, guim, mh - guim)
if terrain:IsPassable(x, y) then
--DbgAddVector(center, v, const.clrGreen)
local pos = point(x, y)
return pos
end
--DbgAddVector(center, v, const.clrYellow)
end
return center
end
function CargoTransporter:OnWaypointStartGoto(drone, pos, next_pos)
local z = pos:z()
local a = z and (z - (next_pos:z() or z)) or 0
if a ~= 0 then
local b = pos:Dist2D(next_pos)
local axis, angle = ComposeRotation(axis_y, atan(a, b), drone:GetAxis(), drone:GetAngle())
drone:SetAxisAngle(axis, angle)
else
drone:SetAxis(axis_z)
end
end
function CargoTransporter:GetEntrancePoint()
local entrance = nil
if not self.waypoint_chains then return entrance end
if self.waypoint_chains.entrance then
entrance = self.waypoint_chains.entrance[1]
end
if self.waypoint_chains.rocket_exit then
entrance = self.waypoint_chains.rocket_exit[1]
end
return entrance
end
function CargoTransporter:LeadOut(unit)
if IsKindOf(unit, "Drone") then
if self:HasMember("drone_charged") and self.drone_charged == unit then
self.drone_charged = false
unit.force_go_home = true
end
if unit.command == "Embark" then --cant move in embark
unit:SetCommand(false)
while unit.command_destructors and unit.command_destructors[1] > 0 do --wait while unit's destructor cleans up
Sleep(1)
end
unit.command_thread = CurrentThread() --hack, so that PopAndCallDestructor in Goto doesn't halt this thread.
end
table.insert_unique(self.drones_exiting, unit)
unit:ClearGameFlags(const.gofSpecialOrientMode)
end
unit:PushDestructor(function(unit)
-- uninterruptible code:
if not IsValid(unit) then return end
unit:SetOutside(true)
unit:SetState(unit:GetMoveAnim()) --fix for drones sometimes exiting in weird animation
local entrance = self:GetEntrancePoint()
if entrance then
local open = entrance.openInside
unit:SetPos(entrance[1])
local speed = unit:GetSpeed()
for i = 2, #entrance do
if not IsValid(self) or not IsValid(unit) then
return
end
local p1 = entrance[i - 1]
local p2 = entrance[i]
unit:Face(p2)
self:OnWaypointStartGoto(unit, p1, p2)
local t = p1:Dist(p2) * 1000 / speed
unit:SetPos(p2, t)
Sleep(t)
end
else
unit:SetPos(self:GetPos())
end
if IsValid(unit) then
unit:SetHolder(false)
self:OnExitUnit(unit)
end
if IsKindOf(unit, "Drone") then
table.remove_entry(self.drones_exiting, unit)
if IsValid(unit) then
unit:SetGameFlags(const.gofSpecialOrientMode)
unit:SetAxis(axis_z)
end
if self == SelectedObj and self:HasMember("drones") and table.find(self.drones, unit) then
SelectionArrowAdd(unit)
end
end
end)
unit:PopAndCallDestructor()
end
function CargoTransporter:UnloadDrones(drones)
for i = 1, #drones do
CreateGameTimeThread(function()
local drone = drones[i]
Sleep( (i - 1) * 1000 )
if IsValid(drone) then
self:LeadOut(drone)
if not IsValid(drone) then return end
local pt
if IsValid(self) then
pt = self:PickArrivalPos(false, false, 30*guim, 10*guim, 90*60, -90*60)
else
pt = self:PickArrivalPos(drone:GetPos(), point(guim, 0, 0), 30*guim, 10*guim, 180*60, -180*60)
end
Movable.Goto(drone, pt) -- Unit.Goto is a command, use this instead for direct control
drone:SetCommand("Idle")
end
end, self, i)
end
end
function CargoTransporter:UnloadCargoObjects(cargo, out)
local refreshBM = false
local map_id = self:GetMapID()
local specializations = GetSortedColonistSpecializationTable()
for _,item in pairs(cargo) do
local amount = item.amount or 0
if amount > 0 then
local classdef = g_Classes[item.class]
if GetResourceInfo(item.class) then
self:AddResource(item.amount*const.ResourceScale, item.class)
elseif item.class == "Passengers" then
self:GenerateArrivals(item.amount, item.applicants_data)
elseif IsKindOf(classdef, "Vehicle") then
for j = 1, item.amount do
local obj = PlaceObjectIn(item.class, map_id, {city = self.city})
self:PlaceAdjacent(obj, out, true)
end
elseif BuildingTemplates[item.class] then
refreshBM = true
self.city:AddPrefabs(item.class, item.amount, false)
elseif not table.find(specializations, item.class) then
print("unexpected cargo type", item.class, "ignored")
end
end
end
if refreshBM then
RefreshXBuildMenu()
end
end
local function ExtractCargo(cargo)
local new_cargo = {}
for _,entry in ipairs(cargo) do
entry.requested = 0
new_cargo[entry.class] = entry
end
return new_cargo
end
function NormalizeCargo(cargo)
if #cargo > 0 then
return ExtractCargo(cargo)
else
return cargo
end
end
function FixPayloadToCargoObject(payload_request)
local flying_idx = table.find(payload_request, "class", "FlyingDrone")
if flying_idx then
local drone_idx = table.find(payload_request, "class", "Drone")
payload_request[drone_idx].amount = payload_request[drone_idx].amount + payload_request[flying_idx].amount
payload_request[flying_idx].amount = 0
end
end
function FixCargoToPayloadObject(payload_request)
if GetMissionSponsor().id == "Japan" then
local flying_amount = RocketPayload_GetAmount("FlyingDrone")
local drone_amount = RocketPayload_GetAmount("Drone")
payload_request:SetItem("FlyingDrone", flying_amount + drone_amount)
payload_request:SetItem("Drone", 0)
end
end
local function AddPayloadToCargo(payload_request, cargo)
cargo = NormalizeCargo(cargo)
payload_request = NormalizeCargo(payload_request)
local classes = table.keys(payload_request)
for class,_ in pairs(cargo) do
table.insert_unique(classes, class)
end
local new_cargo = {}
for _,class in ipairs(classes) do
local entry = cargo[class]
local amount = entry and Max(0, entry.amount) or 0
local requested = payload_request[class] and Max(0, payload_request[class].amount) or 0
if amount > 0 or requested > 0 then
new_cargo[class] = {
class = class,
amount = amount,
requested = requested
}
end
end
return new_cargo
end
local function AddPassengerManifestToCargo(passenger_manifest, cargo)
cargo = NormalizeCargo(cargo)
for class,amount in pairs(passenger_manifest) do
cargo[class] = {
class = class,
amount = 0,
requested = amount
}
end
return cargo
end
function CreateCargoListFromPayload(payload_object, passenger_manifest, old_cargo)
FixPayloadToCargoObject(payload_object)
local cargo = AddPayloadToCargo(payload_object, old_cargo or empty_table)
cargo = AddPassengerManifestToCargo(passenger_manifest, cargo)
return cargo
end
function CargoTransporter:HasCargoRequestsOutstanding()
for key,_ in pairs(self.cargo) do
if self.cargo[key].requested > 0 then
return true
end
end
return false
end
function CargoTransporter:GetRequestUnitCount(max_storage)
return 3 + (max_storage / (const.ResourceScale * 5)) -- 1 per 5 + 3
end
function CargoTransporter:GetCargoLoadingStatus()
local resources = table.filter(self.cargo, function(k, v) return GetResourceInfo(k) end)
for _,entry in pairs(resources) do
if entry.amount > entry.requested then
return "unloading"
end
if entry.amount < entry.requested then
return "loading"
end
end
return false
end
function CargoTransporter:GetRollover(id)
local item = GetResupplyItem(id)
if not item then
return
end
local display_name, description = item.name, item.description
if not display_name or display_name == "" then
display_name, description = ResolveDisplayName(id)
end
description = (description and description ~= "" and description .. "<newline><newline>") or ""
local icon = item.icon and Untranslated("<image "..item.icon.." 2000><newline><newline>") or ""
local item_weight = RocketPayload_GetItemWeight(item)
local building_cost = ""
if ClassTemplates.Building[id] then
building_cost = FormatBuildingCostInfo(id, false)
end
description = icon..description .. T{13730, "Weight: <value> kg<newline><newline><cost>", value = item_weight, cost = building_cost}
return {
title = display_name,
descr = description,
gamepad_hint = T(7580, "<DPadLeft> Change value <DPadRight>"),
}
end
function CargoTransporter:AddCargoDemandRequest(resource, amount, flags, max_units, desired_amount)
assert(not self.demand[resource])
local demand = self:AddDemandRequest(resource, amount, flags, max_units, desired_amount)
self.demand[resource] = demand
return demand
end
function CargoTransporter:GetCargoDemandRequest(resource)
return self.demand[resource]
end
function CargoTransporter:RemoveCargoDemandRequest(resource)
local demand = self.demand[resource]
assert(demand)
if demand then
demand:SetAmount(0)
table.remove_entry(self.task_requests, demand)
self.demand[resource] = nil
end
end
function CargoTransporter:AddCargoSupplyRequest(resource, amount, flags, max_units, desired_amount)
assert(not self.supply[resource])
local supply = self:AddSupplyRequest(resource, amount, flags, max_units, desired_amount)
self.supply[resource] = supply
return supply
end
function CargoTransporter:GetCargoSupplyRequest(resource)
return self.supply[resource]
end
function CargoTransporter:RemoveCargoSupplyRequest(resource)
local supply = self.supply[resource]
assert(supply)
if supply then
supply:SetAmount(0)
table.remove_entry(self.task_requests, supply)
self.supply[resource] = nil
end
end
function CargoTransporter:UpdateCargoResourceRequests(resources)
self:DisconnectFromCommandCenters()
for _,entry in pairs(resources) do
if not self.demand[entry.class] then
local unit_count = g_Consts.CargoRequestDroneAmount
self:AddCargoDemandRequest(entry.class, 0, self.demand_r_flags, unit_count)
self:AddCargoSupplyRequest(entry.class, 0, self.supply_r_flags, unit_count)
end
if entry.amount <= entry.requested then
local amount_to_request = (entry.requested - entry.amount) * const.ResourceScale
self:GetCargoSupplyRequest(entry.class):SetAmount(0)
self:GetCargoDemandRequest(entry.class):SetAmount(amount_to_request)
end
if entry.amount > entry.requested then
local amount_to_supply = (entry.amount - entry.requested) * const.ResourceScale
self:GetCargoSupplyRequest(entry.class):SetAmount(amount_to_supply)
self:GetCargoDemandRequest(entry.class):SetAmount(0)
end
end
self:ConnectToCommandCenters()
end
local function ContainsActiveRequests(requests)
for _,request in pairs(requests) do
if request:GetActualAmount() > 0 then
return true
end
end
return false
end
function CargoTransporter:HasActiveDemandRequests()
return ContainsActiveRequests(self.demand)
end
function CargoTransporter:SetCargoRequest(payload_object, passenger_manifest)
self.cargo = CreateCargoListFromPayload(payload_object, passenger_manifest, self.cargo)
local resources = table.filter(self.cargo, function(k, v) return GetResourceInfo(k) end)
self:UpdateCargoResourceRequests(resources)
end
function CargoTransporter:DroneLoadResource(drone, request, resource, amount)
if self.supply[resource] == request then
local unscaled_amount = amount / const.ResourceScale
assert(self.cargo[resource].amount >= 0)
self.cargo[resource].amount = self.cargo[resource].amount - unscaled_amount
end
end
function CargoTransporter:DroneUnloadResource(drone, request, resource, amount)
if self.demand[resource] == request then
local unscaled_amount = amount / const.ResourceScale
self.cargo[resource].amount = self.cargo[resource].amount + unscaled_amount
end
end
function CargoTransporter:BuildCargoInfo(cargo, skip_completed)
local cargo_info = {}
local table_copy = table.copy(cargo)
table_copy["rocket_name"] = nil
for _,entry in pairs(table_copy) do
if not skip_completed or entry.requested > entry.amount then
table.insert(cargo_info, {
class = entry.class,
amount = entry.amount,
requested = entry.requested,
status = self:GetCargoItemStatus(entry),
})
end
end
return cargo_info
end
local function FormatCargoManifestLine(name, amount, requested, status, type, status_level, show_remaining_only)
local show_status = status_level and status <= status_level
local status_description = show_status and AvailabilityStatusDescription[status] or T("")
local resource_format = T{13942, "<resource(amount,max_amount,type)>", amount = amount, max_amount = requested, type = type }
if show_remaining_only then
local remaining = requested - amount
resource_format = T{13943, "<resource(amount,type)>", amount = remaining, type = type}
end
return T{13780, "<left><name><right><status> <amount_str>", name = name, status = status_description, amount_str = resource_format}
end
ShowAllCargoStatusLevels = {
Resource = AvailabilityStatus.Loaded,
Drone = AvailabilityStatus.Loaded,
Rover = AvailabilityStatus.Loaded,
Colonist = AvailabilityStatus.Loaded,
Prefab = AvailabilityStatus.Loaded,
}
function FormatRequestedCargoManifest(cargo, status_levels, collapse_groups, only_collapsed, show_remaining_only)
show_remaining_only = show_remaining_only or false
if not cargo or #cargo == 0 then
return T(720, "Nothing")
end
status_levels = status_levels or ShowAllCargoStatusLevels
local prefabs = {loaded = 0, requested = 0, status = AvailabilityStatus.Ready, texts = {}, }
local passengers = {loaded = 0, requested = 0, status = AvailabilityStatus.Ready, texts = {}, }
local other_texts = {}
local resource_texts = {}
for i = 1, #cargo do
local item = cargo[i]
if item.requested and item.requested > 0 then
if item.class == "Passengers" then
local resource_format = T{13592, "<left>Passengers<right><amount>/<requested>", number = item.amount, requested = item.requested}
if show_remaining_only then
resource_format = T{13880, "<left>Passengers<right><amount>", number = item.requested-item.amount}
end
other_texts[#other_texts + 1] = resource_format
elseif GetResourceInfo(item.class) then
local requested = item.requested * const.ResourceScale
local amount = item.amount * const.ResourceScale
table.insert(resource_texts, FormatCargoManifestLine(GetResourceTranslation(item.class), amount, requested, item.status, item.class, status_levels.Resource, show_remaining_only))
elseif BuildingTemplates[item.class] then
prefabs.loaded = prefabs.loaded + item.amount
prefabs.requested = prefabs.requested + item.requested
local status = item.status
prefabs.status = GetHighestAvailabilityStatus(prefabs.status, status)
if not collapse_groups then
local def = BuildingTemplates[item.class]
local name = item.amount > 1 and def.display_name_pl or def.display_name
table.insert(prefabs.texts, FormatCargoManifestLine(name, item.amount, item.requested, status, "Prefab", status_levels.Prefab, show_remaining_only))
end
elseif table.find(GetSortedColonistSpecializationTable(), item.class) then
passengers.loaded = passengers.loaded + item.amount
passengers.requested = passengers.requested + item.requested
local status = item.status
passengers.status = GetHighestAvailabilityStatus(passengers.status, status)
if not collapse_groups then
local name = const.ColonistSpecialization[item.class].display_name
table.insert(passengers.texts, FormatCargoManifestLine(name, item.amount, item.requested, status, "Colonist", status_levels.Colonist, show_remaining_only))
end
else
local def = g_Classes[item.class]
if def then
local status = item.status
local type = item.class == "Drone" and "Drone" or "Rover"
local status_level = status_levels[type]
table.insert(other_texts, FormatCargoManifestLine(def.display_name, item.amount, item.requested, status, type, status_level, show_remaining_only))
else
assert(false, "invalid class (" .. tostring(item.class) .. ") in rocket cargo")
end
end
end
end
local texts = {}
if prefabs.requested > 0 then
if collapse_groups then
table.insert(texts, FormatCargoManifestLine(T(13784, "Prefabs"), prefabs.loaded, prefabs.requested, prefabs.status, "Prefab", status_levels.Prefab, show_remaining_only))
else
table.insert(texts, T(13785, "<left><em>Prefabs</em>"))
table.iappend(texts, prefabs.texts)
table.insert(texts, "<newline>")
end
end
if passengers.requested > 0 then
if collapse_groups then
table.insert(texts, FormatCargoManifestLine(T(547, "Colonists"), passengers.loaded, passengers.requested, passengers.status, "Colonist", status_levels.Colonist, show_remaining_only))
else
table.insert(texts, T(13786, "<left><em>Colonists</em>"))
table.iappend(texts, passengers.texts)
table.insert(texts, "<newline>")
end
end
if not only_collapsed then
other_texts = table.map(other_texts, _InternalTranslate)
table.sort(other_texts)
table.iappend(texts, other_texts)
resource_texts = table.map(resource_texts, _InternalTranslate)
table.sort(resource_texts)
table.iappend(texts, resource_texts)
end
texts = table.map(texts, Untranslated)
if #texts == 0 then
return nil
end
return table.concat(texts, "<newline>")
end
function FormatInlineCargoManifest(cargo)
if not cargo or #cargo == 0 then
return T(720, "Nothing")
end
local texts, resources = {}, {}
local num_prefabs = 0
local num_rovers = 0
local num_drones = 0
local num_colonists = 0
for i = 1, #cargo do
local item = cargo[i]
if item.amount and item.amount > 0 then
if BuildingTemplates[item.class] then
num_prefabs = num_prefabs + item.amount
elseif item.class == "Drone" or item.class == "FlyingDrone" then
num_drones = num_drones + item.amount
elseif GetResourceInfo(item.class) then
resources[#resources + 1] = T{722, "<resource(amount,res)>", amount = item.amount*const.ResourceScale, res = item.class}
elseif table.find(GetSortedColonistSpecializationTable(), item.class) then
num_colonists = num_colonists + item.amount
else
local def = g_Classes[item.class]
if def then
num_rovers = num_rovers + item.amount
else
assert(false, "invalid class (" .. tostring(item.class) .. ") in cargo")
end
end
end
end
if num_prefabs > 0 then
resources[#resources + 1] = T{13944, "<prefab(amount)>", amount = num_prefabs}
end
if num_drones > 0 then
resources[#resources + 1] = T{13945, "<drone(amount)>", amount = num_drones}
end
if num_rovers > 0 then
resources[#resources + 1] = T{13946, "<rover(amount)>", amount = num_rovers}
end
if num_colonists > 0 then
resources[#resources + 1] = T{13947, "<colonist(amount)>", amount = num_colonists}
end
if #resources > 0 then
texts[#texts + 1] = table.concat(resources, " ")
end
if #texts == 0 then
return T(10887, "No Cargo")
end
return table.concat(texts, "<newline>")
end
function GetAdditionalResources(cargo)
local array = {}
local table_copy = table.copy(cargo)
table_copy["rocket_name"] = nil
for _,entry in pairs(table_copy) do
local requested = entry.requested or 0
local extra = entry.amount - requested
if extra > 0 then
table.insert(array, {
class = entry.class,
amount = extra,
})
end
end
return array
end
function GetRemainingResources(cargo)
local array = {}
local table_copy = table.copy(cargo)
table_copy["rocket_name"] = nil
for _,entry in pairs(table_copy) do
local requested = entry.requested or 0
local remaining = Max(0, requested - entry.amount)
if remaining > 0 then
table.insert(array, {
class = entry.class,
amount = remaining,
})
end
end
return array
end
function CargoTransporter:GetRequestedCrew()
local passengers = CreateManifest(self.cargo).passengers
local total = 0
for k,v in pairs(passengers) do
total = total + v
end
return total
end
function CargoTransporter:GetAdditionalResources()
return GetAdditionalResources(self.cargo)
end
function CargoTransporter:GetUnloadingCargoManifest()
return FormatCargoManifest(GetAdditionalResources(self.cargo))
end
function CargoTransporter:GetCargoManifest()
return FormatRequestedCargoManifest(self:BuildCargoInfo(self.cargo), empty_table, true, false) or T(10887, "No Cargo")
end
function CargoTransporter:GetCargoRolloverText()
return FormatRequestedCargoManifest(self:BuildCargoInfo(self.cargo), empty_table, false, true) or T("")
end
function CargoTransporter:CanRequestPayload()
return true
end
function CargoTransporter:OpenPayloadDialog(name, context)
local dlg = GetDialog(name)
if dlg then
if not dlg.context or dlg.context.transporter ~= context.transporter then
CloseDialog(name)
else
return
end
end
return OpenDialog(name, nil, context)
end
function CargoTransporter:UIEditPayloadRequest()
if self:CanRequestPayload() then
self:OpenPayloadDialog("PayloadRequest", CargoRequest:new{transporter = self})
end
end
function CargoTransporter:UIEditPayloadRequest_Update(button)
button:SetEnabled(self:CanRequestPayload())
end
function CargoTransporter:GetLaunchIssue(skip_flight_ban)
return self:GetCargoLoadingStatus()
end
function CargoTransporter:CanTransportCargoType(cargo_type)
return true
end
function CargoTransporter:RestorePayloadRequest(payload)
local specializations = GetSortedColonistSpecializationTable()
for _,entry in pairs(self.cargo) do
if table.find(specializations, entry.class) then
payload.traits_object.approved_per_trait = payload.traits_object.approved_per_trait or {}
payload.traits_object.approved_per_trait[entry.class] = entry.requested
else
local amount = entry.requested - entry.amount
if amount > 0 then
payload:SetItem(entry.class, amount)
end
end
end
FixCargoToPayloadObject(payload)
end
function CargoTransporter:SetDefaultPayload(payload)
end
function CargoTransporter:GetCargoWeightCapacity()
return self.cargo_capacity
end
function CargoTransporter:GetPassengerCapacity()
return -1
end
function CargoTransporter:GetPayloadWarning()
local colonists_missing = false
local drones_missing = false
local rovers_missing = false
local prefabs_missing = false
local busy_rovers = false
local busy_drones = false
for _,item in pairs(self.cargo) do
if item.requested and item.requested > 0 then
if GetCargoType(item.class) == CargoType.Rover then
local available_rovers_list = self:ListAvailableRovers(item.class)
local total_rovers_list = self.city.labels[item.class] or empty_table
if item.requested <= #total_rovers_list and item.requested > #available_rovers_list then busy_rovers = true end
end
if GetCargoType(item.class) == CargoType.Drone then
local available_drones_list = self:GatherAvailableDrones(item.requested)
local total_drones_list = self.city.labels.Drone or empty_table
if item.requested <= #total_drones_list and item.requested > #available_drones_list then busy_drones = true end
end
local status = self:GetCargoItemStatus(item)
if status ~= AvailabilityStatus.Ready then
if not colonists_missing and table.find(GetSortedColonistSpecializationTable(), item.class) then
colonists_missing = true
elseif not drones_missing and IsKindOf(g_Classes[item.class], "Drone") then
drones_missing = true
elseif not rovers_missing and IsKindOf(g_Classes[item.class], "BaseRover") then
rovers_missing = true
elseif not prefabs_missing then
local is_resource = Resources[item.class] or false
if not is_resource then
prefabs_missing = true
end
end
end
end
end
if colonists_missing then return T(11473, "Not enough Colonists") end
if drones_missing then return T(11472, "Not enough Drones") end
if rovers_missing then return T(13882, "Not enough Rovers") end
if prefabs_missing then return T(13883, "Not enough Prefabs") end
if busy_rovers then return T(14355, "Rovers are busy") end
if busy_drones then return T(14363, "Drones are busy") end
end
function CargoTransporter:GetCargoEnvironments()
return empty_table
end
function CargoTransporter:GetTransportableVehicles(excluded)
local vehicles = {}
for _,def in ipairs(ResupplyItemDefinitions) do
local class = g_Classes[def.id]
local item = GetResupplyItem(def.id)
if IsKindOf(class, "BaseRover") and not IsKindOfClasses(class, excluded) and IsResupplyItemAvailable(item.id) then
table.insert(vehicles, def)
end
end
return vehicles
end
function CargoTransporter:GetTransportablePrefabs(environments)
return GetAccessiblePrefabs({ self.city }, self:GetCargoEnvironments())
end
function SavegameFixups.AddMissingResupplyItemDefs()
if IsDlcAccessible("picard") then
ResupplyItemsInit(true)
end
end
|
---
-- unit_factory.lua
local class = require "middleclass"
local json = require "json.json"
local Unit = require "repositories.units.dto.unit"
local Stats = require "repositories.units.dto.stats"
local Position = require "utils.position"
local IdGenerator = require "utils.id_generator"
local UnitFactory = class("UnitFactory")
function UnitFactory:initialize(data)
if not data.map_settings_repository then
error("UnitFactory:initialize(): no data.map_settings_repository argument!")
end
self.map_settings_repository = data.map_settings_repository
local file = assert(io.open("res/data/units.json", "rb"))
local content = file:read("*all")
file:close()
self.units_data = json.decode(content)
end
function UnitFactory:get_trooper(unit_data)
local tile_size = self.map_settings_repository:get_tile_size()
local raw_x, raw_y = unit_data:get_position():get()
local x_pos = (raw_x - 1) * tile_size
local y_pos = (raw_y - 1) * tile_size
local trooper = Unit({
id = IdGenerator:get_new_id(),
type = unit_data:get_type(),
team = unit_data:get_team(),
position = Position(x_pos, y_pos),
stats = Stats({
movement_range = self.units_data["trooper"].move
})
})
return trooper
end
return UnitFactory
|
local config = require("aerial.config")
local data = require("aerial.data")
local util = require("aerial.util")
local M = {}
M.add_fold_mappings = function(bufnr)
if config.link_folds_to_tree then
local function map(key, cmd)
vim.api.nvim_buf_set_keymap(bufnr or 0, "n", key, cmd, { silent = true, noremap = true })
end
map("za", [[<cmd>AerialTreeToggle<CR>]])
map("zA", [[<cmd>AerialTreeToggle!<CR>]])
map("zo", [[<cmd>AerialTreeOpen<CR>]])
map("zO", [[<cmd>AerialTreeOpen!<CR>]])
map("zc", [[<cmd>AerialTreeClose<CR>]])
map("zC", [[<cmd>AerialTreeClose!<CR>]])
map("zM", [[<cmd>AerialTreeCloseAll<CR>]])
map("zR", [[<cmd>AerialTreeOpenAll<CR>]])
map("zx", [[<cmd>AerialTreeSyncFolds<CR>]])
map("zX", [[<cmd>AerialTreeSyncFolds<CR>]])
end
end
M.foldexpr = function(lnum, debug)
if util.is_aerial_buffer() then
return "0"
end
if not data:has_symbols(0) then
return "0"
end
local bufdata = data[0]
local lastItem = {}
local foldItem = { level = -1 }
bufdata:visit(function(item)
lastItem = item
if item.lnum > lnum then
return true
elseif bufdata:is_collapsable(item) then
foldItem = item
end
end, {
incl_hidden = true,
})
local levelstr = string.format("%d", foldItem.level + 1)
if lnum == foldItem.lnum then
levelstr = ">" .. levelstr
elseif vim.api.nvim_buf_get_lines(0, lnum - 1, lnum, true)[1] == "" then
levelstr = "-1"
end
if debug then
levelstr = string.format("%s %s:%d:%d", levelstr, lastItem.name, lastItem.level, lastItem.lnum)
end
return levelstr
end
local prev_fdm = "_aerial_prev_foldmethod"
local prev_fde = "_aerial_prev_foldexpr"
M.restore_foldmethod = function()
local ok, prev_foldmethod = pcall(vim.api.nvim_win_get_var, 0, prev_fdm)
if ok and prev_foldmethod then
vim.api.nvim_win_del_var(0, prev_fdm)
vim.wo.foldmethod = prev_foldmethod
end
local ok2, prev_foldexpr = pcall(vim.api.nvim_win_get_var, 0, prev_fde)
if ok2 and prev_foldexpr then
vim.api.nvim_win_del_var(0, prev_fde)
vim.wo.foldexpr = prev_foldexpr
end
end
M.maybe_set_foldmethod = function(bufnr)
local manage_folds = config.manage_folds
if not manage_folds then
return
end
if not data:has_symbols(bufnr) then
return
end
local winids
if bufnr then
winids = util.get_fixed_wins(bufnr)
else
winids = { vim.api.nvim_get_current_win() }
end
for _, winid in ipairs(winids) do
local fdm = vim.api.nvim_win_get_option(winid, "foldmethod")
local fde = vim.api.nvim_win_get_option(winid, "foldexpr")
if
not util.is_managing_folds(winid)
and (manage_folds == true or (manage_folds == "auto" and fdm == "manual"))
then
vim.api.nvim_win_set_var(winid, prev_fdm, fdm)
vim.api.nvim_win_set_var(winid, prev_fde, fde)
vim.api.nvim_win_set_option(winid, "foldmethod", "expr")
vim.api.nvim_win_set_option(winid, "foldexpr", "aerial#foldexpr()")
if config.link_tree_to_folds then
vim.api.nvim_win_set_option(winid, "foldlevel", 99)
end
end
end
end
M.sync_tree_folds = function(winid)
if not util.is_managing_folds(winid) then
return
end
util.go_win_no_au(winid)
local view = vim.fn.winsaveview()
vim.cmd("normal! zxzR")
local bufdata = data[0]
local items = bufdata:flatten(nil, { incl_hidden = true })
table.sort(items, function(a, b)
return a.level > b.level
end)
for _, item in ipairs(items) do
if bufdata:is_collapsed(item) then
vim.api.nvim_win_set_cursor(0, { item.lnum, 0 })
vim.cmd("normal! zc")
end
end
vim.fn.winrestview(view)
end
local function win_do_action(winid, action, lnum, recurse)
util.go_win_no_au(winid)
if vim.fn.foldlevel(lnum) == 0 then
M.sync_tree_folds(winid)
end
if vim.fn.foldlevel(lnum) == 0 then
return
end
local view = vim.fn.winsaveview()
vim.api.nvim_win_set_cursor(0, { lnum, 0 })
local key
if action == "open" then
key = "o"
elseif action == "close" then
key = "c"
elseif action == "toggle" then
key = "a"
end
if key and recurse then
key = string.upper(key)
end
if key then
vim.cmd("normal! z" .. key)
end
vim.fn.winrestview(view)
end
M.fold_action = function(action, lnum, opts)
opts = vim.tbl_extend("keep", opts or {}, {
recurse = false,
})
local my_winid = vim.api.nvim_get_current_win()
local wins
local bufnr, _ = util.get_buffers()
wins = util.get_fixed_wins(bufnr)
for _, winid in ipairs(wins) do
if util.is_managing_folds(winid) then
win_do_action(winid, action, lnum, opts.recurse)
end
end
util.go_win_no_au(my_winid)
end
return M
|
--[[? if (!ctx.test) out(]]
__source 'lua/api_io.cpp'
__namespace 'io'
--[[) ?]]
ffi.cdef[[
typedef struct {
int64_t fileSize;
int64_t creationTime;
int64_t lastAccessTime;
int64_t lastWriteTime;
bool exists;
bool isDirectory;
bool isHidden;
bool isReadOnly;
bool isEncrypted;
bool isCompressed;
bool isReparsePoint;
} lua_file_attributes;
typedef struct {
lua_string_ref name__;
int64_t fileSize;
int64_t creationTime;
int64_t lastAccessTime;
int64_t lastWriteTime;
bool exists;
bool isDirectory;
bool isHidden;
bool isReadOnly;
bool isEncrypted;
bool isCompressed;
bool isReparsePoint;
} lua_dir_scan;
]]
---Scan directory and call callback function for each of files, passing file name (not full name, but only name of the file) and attributes. If callback function would return
---a non-nil value, iteration will stop and value returned by callback would return from this function. This could be used to
---find a certain file without going through all files in the directory. Optionally, a mask can be used to pre-filter received files
---entries.
---
---If callback function is not provided, it’ll return list of files instead (file names only).
---
---System entries “.” and “..” will not be included in the list of files. Accessing attributes does not add extra cost.
---@generic TCallbackData
---@generic TReturn
---@param directory string @Directory to look for files in. Note: directory is relative to current directory, not to script directory. For AC in general it’s an AC root directory, but do not rely on it, instead use `ac.getFolder(ac.FolderID.Root)`.
---@param mask string @Mask in a form of usual “*.*”. Default value: '*'.
---@param callback fun(fileName: string, fileAttributes: io.FileAttributes, callbackData: TCallbackData): TReturn @Callback which will be ran for every file in directory fitting mask until it would return a non-nil value.
---@param callbackData TCallbackData @Callback data that will be passed to callback as third argument, to avoid creating a capture.
---@return TReturn @First non-nil value returned by callback.
---@overload fun(directory: string, callback: fun(fileName: string, fileAttributes: io.FileAttributes, callbackData: any), callbackData: any): any
---@overload fun(directory: string, mask: string|nil): string[]
function io.scanDir(directory, mask, callback, callbackData)
if type(directory) ~= 'string' then error('First argument has to be a string with path to a directory', 2) end
if type(mask) == 'function' then mask, callback, callbackData = nil, mask, callback end
local s, r = ffi.C.lj_dirscan_start__io(__util.str(directory), __util.str_opt(mask)), nil
if not callback then
r = {}
local n = 1
while s.exists do
r[n], n = __util.strref_ref(s.name__), n + 1
ffi.C.lj_dirscan_next__io(s)
end
else
r = nil
while s.exists do
r = callback(__util.strref_ref(s.name__), s, callbackData)
if r ~= nil then break end
ffi.C.lj_dirscan_next__io(s)
end
end
ffi.C.lj_dirscan_end__io(s)
return r
end
|
ATTRIBUTE.name = "Ballistic Skill (BAL)"
ATTRIBUTE.description = "Ability to attack with ranged weapons accurately."
ATTRIBUTE.shortname = "BAL" |
-- Copyright (c) 2021 Kirazy
-- Part of Prismatic Belts
--
-- See LICENSE.md in the project directory for license information.
if not mods["boblogistics"] then return end
local tiers = {
["basic-"] = {tint = util.color("7d7d7dd1") , variant = 1, loader = "basic-", technology = "logistics-0"},
["turbo-"] = {tint = util.color("a510e5d1"), variant = 2, loader = "purple-", technology = "logistics-4"},
["ultimate-"] = {tint = util.color("16f263d1"), variant = 2, loader = "green-", technology = "logistics-5"},
}
-- Compatibility with Bob's Logistics Belt Reskin
if mods["boblogistics-belt-reskin"] then
tiers["basic-"].tint = util.color("e7e7e7d1")
tiers["turbo-"].tint = util.color("df1ee5d1")
end
-- Compatibility with Artisanal Reskins 1.1.3+
if mods["reskins-library"] and not (reskins.bobs and (reskins.bobs.triggers.logistics.entities == false)) then
-- Setup standard properties
tiers["basic-"].tier = 0
tiers["turbo-"].tier = 4
tiers["ultimate-"].tier = 5
tiers["basic-"].tint = reskins.lib.belt_tint_index[0]
tiers["turbo-"].tint = reskins.lib.belt_tint_index[4]
tiers["ultimate-"].tint = reskins.lib.belt_tint_index[5]
-- Check for custom colors, update tint and tier information if so
if reskins.lib.setting("reskins-lib-customize-tier-colors") then
tiers[""] = {tint = reskins.lib.belt_tint_index[1], variant = 1, loader = "", tier = 1, technology = "logistics"}
tiers["fast-"] = {tint = reskins.lib.belt_tint_index[2], variant = 2, loader = "fast-", tier = 2, technology = "logistics-2"}
tiers["express-"] = {tint = reskins.lib.belt_tint_index[3], variant = 2, loader = "express-", tier = 3, technology = "logistics-3"}
end
-- Compatibility with Artisanal Reskins 2.0.0+
if prismatic_belts.migration.is_version_or_newer(mods["reskins-library"], "2.0.0") then
for _, properties in pairs(tiers) do
properties.use_reskin_process = true
end
end
end
-- Setup all the entities to use the updated belt animation sets
for prefix, properties in pairs(tiers) do
-- Fetch entities
local entities = {
belt = data.raw["transport-belt"][prefix.."transport-belt"],
splitter = data.raw["splitter"][prefix.."splitter"],
underground = data.raw["underground-belt"][prefix.."underground-belt"],
loader = data.raw["loader"][properties.loader.."loader"],
-- Miniloader
miniloader = data.raw["loader-1x1"][prefix.."miniloader-loader"],
filter_miniloader = data.raw["loader-1x1"][prefix.."filter-miniloader-loader"],
-- Deadlock Stacking Beltboxes and Compact loaders
deadlock_loader = data.raw["loader-1x1"][prefix.."transport-belt-loader"]
}
-- Reskin the belt item
local belt_item = data.raw["item"][prefix.."transport-belt"]
if belt_item then
local icons = prismatic_belts.transport_belt_icon(properties.tint, properties.use_reskin_process)
-- Append tier labels for reskins-library
if mods["reskins-library"] and not (reskins.bobs and (reskins.bobs.triggers.logistics.entities == false)) then
reskins.lib.append_tier_labels(properties.tier, {icon = icons, tier_labels = reskins.lib.setting("reskins-bobs-do-belt-entity-tier-labeling") and true or false})
reskins.lib.assign_icons(prefix.."transport-belt", {icon = icons, icon_picture = prismatic_belts.transport_belt_picture(properties.tint, properties.use_reskin_process), make_icon_pictures = true})
else
belt_item.icons = icons
end
-- Update entity icon to match
if entities.belt then
entities.belt.icons = belt_item.icons
end
end
-- Reskin all related entity types
for _, entity in pairs(entities) do
if entity then
entity.belt_animation_set = prismatic_belts.transport_belt_animation_set({mask_tint = properties.tint, variant = properties.variant, use_reskin_process = properties.use_reskin_process})
end
end
-- Setup remnants
if entities.belt then
prismatic_belts.create_remnant(prefix.."transport-belt", {mask_tint = properties.tint})
end
-- Setup logistics technologies
local technology = data.raw["technology"][properties.technology]
if technology then
technology.icons = prismatic_belts.logistics_technology_icon({mask_tint = properties.tint, use_reskin_process = properties.use_reskin_process})
end
end |
-- core_file_l2_1_0.lua
-- api-ms-win-core-file-l2-1-0.dll
local ffi = require("ffi");
local k32Lib = ffi.load("kernel32");
local WTypes = require("WTypes");
local WinBase = require("WinBase");
ffi.cdef[[
typedef
DWORD ( *LPPROGRESS_ROUTINE)(
LARGE_INTEGER TotalFileSize,
LARGE_INTEGER TotalBytesTransferred,
LARGE_INTEGER StreamSize,
LARGE_INTEGER StreamBytesTransferred,
DWORD dwStreamNumber,
DWORD dwCallbackReason,
HANDLE hSourceFile,
HANDLE hDestinationFile,
LPVOID lpData
);
]]
ffi.cdef[[
BOOL
CopyFileExW(
LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
LPPROGRESS_ROUTINE lpProgressRoutine,
LPVOID lpData,
LPBOOL pbCancel,
DWORD dwCopyFlags
);
BOOL
CreateDirectoryExW(
LPCWSTR lpTemplateDirectory,
LPCWSTR lpNewDirectory,
LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
BOOL
CreateHardLinkW(
LPCWSTR lpFileName,
LPCWSTR lpExistingFileName,
LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
BOOLEAN
CreateSymbolicLinkW (
LPCWSTR lpSymlinkFileName,
LPCWSTR lpTargetFileName,
DWORD dwFlags
);
BOOL
GetFileInformationByHandleEx(
HANDLE hFile,
FILE_INFO_BY_HANDLE_CLASS FileInformationClass,
LPVOID lpFileInformation,
DWORD dwBufferSize
);
BOOL
MoveFileExW(
LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
DWORD dwFlags
);
BOOL
MoveFileWithProgressW(
LPCWSTR lpExistingFileName,
LPCWSTR lpNewFileName,
LPPROGRESS_ROUTINE lpProgressRoutine,
LPVOID lpData,
DWORD dwFlags
);
BOOL
ReadDirectoryChangesW(
HANDLE hDirectory,
LPVOID lpBuffer,
DWORD nBufferLength,
BOOL bWatchSubtree,
DWORD dwNotifyFilter,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
HANDLE
ReOpenFile(
HANDLE hOriginalFile,
DWORD dwDesiredAccess,
DWORD dwShareMode,
DWORD dwFlagsAndAttributes
);
BOOL
ReplaceFileW(
LPCWSTR lpReplacedFileName,
LPCWSTR lpReplacementFileName,
LPCWSTR lpBackupFileName,
DWORD dwReplaceFlags,
LPVOID lpExclude,
LPVOID lpReserved
);
]]
return {
Lib = k32Lib,
--CopyFile2
CopyFileExW = k32Lib.CopyFileExW,
CreateDirectoryExW = k32Lib.CreateDirectoryExW,
CreateHardLinkW = k32Lib.CreateHardLinkW,
CreateSymbolicLinkW = k32Lib.CreateSymbolicLinkW,
GetFileInformationByHandleEx = k32Lib.GetFileInformationByHandleEx,
MoveFileExW = k32Lib.MoveFileExW,
MoveFileWithProgressW = k32Lib.MoveFileWithProgressW,
ReadDirectoryChangesW = k32Lib.ReadDirectoryChangesW,
ReOpenFile = k32Lib.ReOpenFile,
ReplaceFileW = k32Lib.ReplaceFileW,
}
|
-- nvim-cmp
-- A completion plugin for neovim coded in Lua.
-- https://github.com/hrsh7th/nvim-cmp
local cmp = require("cmp")
-- local autopairs = require("nvim-autopairs")
-- local cmp_autopairs = require("nvim-autopairs.completion.cmp")
local lspkind = require("lspkind")
vim.opt.completeopt = "menuone,noselect"
cmp.setup {
mapping = {
["<C-n>"] = cmp.mapping.select_next_item(),
["<C-p>"] = cmp.mapping.select_prev_item(),
["<C-f>"] = cmp.mapping.scroll_docs(-4),
["<C-d>"] = cmp.mapping.scroll_docs(4),
["<C-Space>"] = cmp.mapping.complete(),
["<CR>"] = cmp.mapping.confirm({
behaviour = cmp.ConfirmBehavior.Replace,
select = false
})
},
window = {
completion = {
border = _G.defaults.borders
},
documentation = {
border = _G.defaults.borders,
max_width = 50
-- max_height = 50
}
},
sources = {
{ name = "luasnip" },
{ name = "nvim_lua" },
{ name = "nvim_lsp" },
{ name = "path" },
{ name = "buffer" }
},
experimental = { ghost_text = true },
formatting = {
format = lspkind.cmp_format({
mode = "symbol_text",
maxwidth = 50,
before = function(entrey, vim_item)
return vim_item
end
})
},
snippet = {
expand = function(args)
require("luasnip").lsp_expand(args.body)
end
}
}
-- autopairs.setup {}
-- cmp.event:on("confirm_done", cmp_autopairs.on_confirm_done {
-- map_char = { tex = "" }
-- })
|
-- Circuit break if this plugin has already completed
if vim.b.did_local_ftplugin == true then
return 0
end
-- Create an augroup for this module
vim.api.nvim_define_augroup("Markdown", true)
-- Align Github-flavored markdown tables
vim.api.nvim_set_keymap("v", "<bar>", ":EasyAlign *<bar><CR>", { noremap = true })
-- Signal that the plugin has completed
vim.b.did_local_ftplugin = true
|
--
-- tek.ui.class.meter
-- Written by Timm S. Mueller <tmueller at schulze-mueller.de>
-- See copyright notice in COPYRIGHT
--
local db = require "tek.lib.debug"
local ui = require "tek.ui".checkVersion(112)
local Text = ui.Text
local Region = require "tek.lib.region"
local floor = math.floor
local insert = table.insert
local ipairs = ipairs
local max = math.max
local min = math.min
local pi = math.pi
local remove = table.remove
local sin = math.sin
local sort = table.sort
local tonumber = tonumber
local unpack = unpack or table.unpack
local Meter = Text.module("tek.ui.class.meter", "tek.ui.class.text")
Meter._VERSION = "Meter 8.3"
-------------------------------------------------------------------------------
-- Class style properties:
-------------------------------------------------------------------------------
Meter.Properties = {
["padding-top"] = 0,
["padding-right"] = 0,
["padding-bottom"] = 0,
["padding-left"] = 0,
}
-------------------------------------------------------------------------------
-- Class implementation:
-------------------------------------------------------------------------------
function Meter.new(class, self)
self = self or { }
self.NumSamples = self.NumSamples or 256
self.GraphBGColor = self.GraphBGColor or "dark"
self.GraphColor = self.GraphColor or "bright"
self.GraphColor2 = self.GraphColor2 or self.GraphColor
self.GraphColor3 = self.GraphColor3 or self.GraphColor
self.GraphColor4 = self.GraphColor4 or self.GraphColor
self.GraphPens = { self.GraphColor, self.GraphColor2, self.GraphColor3,
self.GraphColor4 }
self.CaptionsX = self.CaptionsX or
{
{ pri = 100, text = "-1.0" },
{ pri = 25, text = "-0.5" },
{ pri = 50, text = "0.0" },
{ pri = 25, text = "0.5" },
{ pri = 100, text = "1.0" },
}
self.CaptionsY = self.CaptionsY or
{
{ pri = 100, text = "-1.0" },
{ pri = 25, text = "-0.5" },
{ pri = 50, text = "0.0" },
{ pri = 25, text = "0.5" },
{ pri = 100, text = "1.0" },
}
self.Curves = self.Curves or { { } }
self.Font = "ui-small"
self.GraphRect = false
self.MaxHeight = self.MaxHeight or "none"
self.MaxWidth = self.MaxWidth or "none"
self.Mode = self.Mode or "line" -- or "rect"
self.RedrawGraph = false
self.TextRecordsX = false
self.TextRecordsY = false
self.TextRegion = false
return Text.new(class, self)
end
-------------------------------------------------------------------------------
-- layout: overrides
-------------------------------------------------------------------------------
function Meter:layout(x0, y0, x1, y1, markdamage)
local res = Text.layout(self, x0, y0, x1, y1, markdamage)
if res then
local font = self.Application.Display:openFont(self.Font)
local r1, r2, r3, r4 = self:getRect()
local captionheight, captionwidth, _ = 0, 0
if #self.CaptionsX > 0 then
_, captionheight = font:getTextSize("")
end
-- flush text records:
self.TextRecords = { }
-- generate text records on Y axis:
local height = r4 - r2 - captionheight
local cy = 0
local dy = height * 0x10000 / (#self.CaptionsY - 1)
local tr = { }
local pris = { }
for i, c in ipairs(self.CaptionsY) do
insert(pris, c)
local tw, th = font:getTextSize(c.text)
local y0 = floor(cy / 0x10000)
y0 = y0 - floor(th / 2)
y0 = max(0, min(y0, height - 1 - th)) + captionheight
c.y0 = y0
c.y1 = y0 + th - 1
c.tw = tw
cy = cy + dy
end
sort(pris, function(a, b) return a.pri > b.pri end)
local final = { }
for i, c in ipairs(pris) do
local found
for j = 1, i - 1 do
if c.y1 >= pris[j].y0 and c.y0 <= pris[j].y1 then
found = true
break
end
end
if not found then
insert(final, c)
captionwidth = max(captionwidth, c.tw)
end
end
for _, c in ipairs(final) do
local t = self:newTextRecord(c.text, font, "left", "bottom",
captionwidth - c.tw, 0, 0, c.y0)
insert(tr, t)
insert(self.TextRecords, t)
end
self.TextRecordsY = tr
-- generate text records on X axis:
local width = r3 - r1 - captionwidth
local cx = 0
local dx = width * 0x10000 / (#self.CaptionsX - 1)
tr = { }
local pris = { }
for i, c in ipairs(self.CaptionsX) do
insert(pris, c)
local tw, th = font:getTextSize(c.text)
local x0 = floor(cx / 0x10000)
x0 = x0 - floor(tw / 2)
x0 = max(0, min(x0, width - 1 - tw)) + captionwidth
c.x0 = x0
c.x1 = x0 + tw - 1
cx = cx + dx
end
sort(pris, function(a, b) return a.pri > b.pri end)
for i, c in ipairs(pris) do
local found
for j = 1, i - 1 do
if c.x1 >= pris[j].x0 and c.x0 <= pris[j].x1 then
found = true
break
end
end
if not found then
local t = self:newTextRecord(c.text, font, "left", "bottom",
c.x0, 0, 0, 0)
insert(tr, t)
insert(self.TextRecords, t)
end
end
self.TextRecordsX = tr
-- layout all text records:
self:layoutText()
-- create regions for areas used by captions and graph:
self.TextRegion = Region.new()
self.GraphRect = { r1, r2, r3, r4 }
local tr = self.TextRecordsX
local tw, th, x0, y0 = ui.Text:getTextSize(tr)
if x0 then
local x1 = x0 + tw - 1
local y1 = y0 + th - 1
self.TextRegion:orRect(x0, y0, x1, y1)
self.GraphRect[4] = y0 - 1
end
local tr = self.TextRecordsY
local tw, th, x0, y0 = ui.Text:getTextSize(tr)
if x0 then
local x1 = x0 + tw - 1
local y1 = y0 + th - 1
self.TextRegion:orRect(x0, y0, x1, y1)
self.GraphRect[1] = x1 + 1
end
self.TextRegion:andRect(r1, r2, r3, r4)
self.RedrawGraph = true
return true
end
end
-------------------------------------------------------------------------------
-- drawGraph:
-------------------------------------------------------------------------------
function Meter:drawGraph()
local d = self.Window.Drawable
local r1, r2, r3, r4 = self:getRect()
for cnr, c in ipairs(self.Curves) do
local pen = self.GraphPens[cnr]
local x0, y0, x1, y1 = unpack(self.GraphRect)
local gw = x1 - x0
local gh = y1 - y0
local n = self.NumSamples - 1
local dx = gw * 0x10000 / n
local y = r2 + gh
local v0
for i = 0, n do
local v = c[i + 1]
if not v then
break
end
v = max(min(0xffff, v), 0)
if i == 0 then
v0 = v * gh / 0x10000
x0 = x0 * 0x10000
else
local v1 = v * gh / 0x10000
local x1 = x0 + dx
local x = x0 / 0x10000
if x >= r3 then
break
end
if self.Mode == "rect" then
local x1 = min(x1 / 0x10000, r3)
d:drawLine(floor(x), floor(y - v0), floor(x1),
floor(y - v0), pen)
d:drawLine(floor(x1), floor(y - v0), floor(x1),
floor(y - v1), pen)
else
d:drawLine(floor(x), floor(y - v0),
floor(min(x1 / 0x10000, r3)), floor(y - v1), pen)
end
x0 = x1
v0 = v1
end
end
end
end
-------------------------------------------------------------------------------
-- eraseGraphBG:
-------------------------------------------------------------------------------
function Meter:eraseGraphBG()
local x0, y0, x1, y1 = unpack(self.GraphRect)
self.Window.Drawable:fillRect(x0, y0, x1, y1, self.GraphBGColor)
end
-------------------------------------------------------------------------------
-- erase: overrides
-------------------------------------------------------------------------------
function Meter:erase()
local d = self.Window.Drawable
d:setBGPen(self:getBG())
self.TextRegion:forEach(d.fillRect, d)
end
-------------------------------------------------------------------------------
-- draw: overrides
-------------------------------------------------------------------------------
function Meter:draw()
local res = Text.draw(self)
if res or self.RedrawGraph then
self:eraseGraphBG()
self:drawGraph()
self.RedrawGraph = false
end
return res
end
return Meter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.