content
stringlengths 5
1.05M
|
|---|
Config = {}
Config.DrawDistance = 100.0
Config.MarkerColor = { r = 120, g = 120, b = 240 }
Config.EnablePlayerManagement = true -- If set to true, you need esx_addonaccount, esx_billing and esx_society
Config.EnablePvCommand = false
Config.MaxInService = -1
Config.EnableOwnedVehicles = true
Config.EnableSocietyOwnedVehicles = true
Config.ResellPercentage = 70
Config.Locale = 'fr'
Config.Zones = {
ShopEntering = {
Pos = { x = -32.1483, y = -1114.4133, z = 26.4537, angle = 82.5456 },------le bureaux pour les civil
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = 1,
},
ShopInside = {
Pos = { x = -44.322, y = -1097.644, z = 26.422, angle = 70.737 },------pour acheté le véhicule pour le megasin et le jeureu
Size = { x = 1.5, y = 1.5, z = 1.0 },
Heading = 73.60,
Type = -1,
},
ShopOutside = {
Pos = { x = -48.093, y = -1078.855, z = 25.771 },
Pos = { x = -47.093, y = -1077.855, z = 25.771 },
Pos = { x = -46.093, y = -1076.855, z = 25.771 },
Pos = { x = -48.668, y = -1079.944, z = 25.771 },
Size = { x = 2.5, y = 2.5, z = 2.0 },
Heading = 73.60,
Type = -1,
},
BossActions = {
Pos = { x = -29.528, y = -1108.426, z = 26.422 },------le buraux pour sont service
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = -1,
},
VehicleSpawnPoint = {
Pos = { x = -49.172927856445, y = -1078.2733154297, z = 26.335163116455 },--------donne votre voiture
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = (Config.EnablePlayerManagement and 1 or -1),
},
GiveBackVehicle = {
Pos = { x = -7.441, y = -1082.621, z = 26.672 },--------donne votre voiture
Size = { x = 1.5, y = 1.5, z = 1.0 },
Type = (Config.EnablePlayerManagement and 1 or -1),
},
ResellVehicle = {
Pos = { x = 0, y = 0, z = 0 },----Revendre le véhicule
Size = { x = 5.0, y = 5.0, z = 3.0 },
Type = 1,
},
}
----14.405086517334, y = -1101.6304931641, z = 26.672071456909 angle = 156.58789
|
--
-- Byte Encoder
--
local bit = assert(foundation.com.bit)
-- Base module
local E = {}
function E:e_i64(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(8, int)
end
function E:e_i56(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(7, int)
end
function E:e_i48(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(6, int)
end
function E:e_i40(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(5, int)
end
function E:e_i32(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(4, int)
end
function E:e_i24(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(3, int)
end
function E:e_i16(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(2, int)
end
function E:e_i8(int)
assert(type(int) == "number", "expected an integer")
return self:e_iv(1, int)
end
function E:e_u64(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(8, int)
end
function E:e_u56(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(7, int)
end
function E:e_u48(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(6, int)
end
function E:e_u40(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(5, int)
end
function E:e_u32(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(4, int)
end
function E:e_u24(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(3, int)
end
function E:e_u16(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(2, int)
end
function E:e_u8(int)
assert(type(int) == "number", "expected an integer")
return self:e_uv(1, int)
end
-- Little Endian - Encoder
local LE = {}
setmetatable(LE, { __index = E })
-- Signed Integers
function LE:e_iv(len, int)
local r = int
local i = 0
local result = {}
for j = 1,(len - 1) do
i = j
local byte = bit.band(r, 255)
result[i] = byte
r = bit.rshift(r, 8)
end
i = i + 1
if int < 0 then
-- set last bit to 1, meaning it's negative
result[i] = bit.bor(bit.band(r, 127), 128)
else
result[i] = bit.band(r, 127)
end
return string.char(unpack(result))
end
-- Unsigned Integers
function LE:e_uv(len, int)
assert(int >= 0, "expected integer to be greater than or equal to 0")
local r = int
local result = {}
for i = 1,len do
local byte = bit.band(r, 255)
result[i] = byte
r = bit.rshift(r, 8)
end
return string.char(unpack(result))
end
-- Little Endian - Encoder
local BE = {}
setmetatable(BE, { __index = E })
-- Signed Integers
function BE:e_iv(len, int)
local r = int
local i = len
local result = {}
for j = 1,(len - 1) do
local byte = bit.band(r, 255)
result[i] = byte
i = i - 1
r = bit.rshift(r, 8)
end
if int < 0 then
-- set last bit to 1, meaning it's negative
result[i] = bit.bor(bit.band(r, 127), 128)
else
result[i] = bit.band(r, 127)
end
return string.char(unpack(result))
end
-- Unsigned Integers
function BE:e_uv(len, int)
assert(int >= 0, "expected integer to be greater than or equal to 0")
local r = int
local result = {}
local j = len
for i = 1,len do
local byte = bit.band(r, 255)
-- 1+ is to compensate for lua's array offset
result[j] = byte
j = j - 1
r = bit.rshift(r, 8)
end
return string.char(unpack(result))
end
foundation.com.ByteEncoder = {
LE = LE,
BE = BE,
}
|
ITEM.name = "Respirator"
ITEM.desc = "A Gas-mask type Respirator that protects you from bad airs."
ITEM.model = "models/barneyhelmet_faceplate.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.gasMask = true
ITEM.price = 250
ITEM.category = "Outfit"
ITEM.iconCam = {
ang = Angle(29.00287437439, 411.06158447266, 0),
fov = 4.2897785277726,
pos = Vector(-111.17874145508, -135.5086517334, 96.315162658691)
}
ITEM.pacData = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Angles"] = Angle(8.4950472228229e-005, -66.922698974609, -89.999969482422),
["UniqueID"] = "3085914138",
["ClassName"] = "model",
["Size"] = 0.95,
["EditorExpand"] = true,
["Model"] = "models/barneyhelmet_faceplate.mdl",
["Position"] = Vector(3.3733520507813, -1.6019897460938, -0.10595703125),
},
},
},
["self"] = {
["EditorExpand"] = true,
["UniqueID"] = "2607460179",
["ClassName"] = "group",
["Name"] = "my outfit",
["Description"] = "add parts to me!",
},
},
}
local defaultDesc = "A Gas-mask type Respirator that protects you from bad airs."
function ITEM:getDesc()
local str
if (!self.entity or !IsValid(self.entity)) then
local health = self:getData("health", DEFAULT_GASMASK_HEALTH)
local filter = self:getData("filter", DEFAULT_GASMASK_HEALTH)
str = defaultDesc
if (health <= 0) then
str = str .. "\nThis mask is broken."
elseif (health < DEFAULT_GASMASK_HEALTH * .2) then
str = str .. "\nThis mask is barely functional."
end
if (filter <= 0) then
str = str .. "\nThis mask's filter is not functional."
elseif (filter < DEFAULT_GASMASK_FILTER * .3) then
str = str .. "\nThis mask's filter is barely functional."
end
return str
else
return defaultDesc
end
end
if (CLIENT) then
function ITEM:paintOver(item, w, h)
if (item:getData("equip")) then
surface.SetDrawColor(110, 255, 110, 100)
surface.DrawRect(w - 14, h - 14, 8, 8)
end
end
else
hook.Add("PlayerDeath", "UnequipGasmasks", function(client)
local char = client:getChar()
if (char) then
client.deadMaskChar = char:getID()
if (char:getInv()) then
for k, v in pairs(char:getInv():getItems()) do
local itemTable = nut.item.instances[v.id]
if (itemTable.gasMask and itemTable:getData("equip")) then
-- SAVE TEMP MASKVARS
itemTable:setData("equip", false)
itemTable:setData("health", char:getVar("gasMaskHealth", DEFAULT_GASMASK_HEALTH))
itemTable:setData("filter", char:getVar("gasMaskFilter", DEFAULT_GASMASK_FILTER))
char:setVar("gasMaskHealth", nil)
char:setVar("gasMaskFilter", nil)
break
end
end
end
end
end)
-- This hook notices you the death penalty that you've got by the server.
hook.Add("PlayerSpawn", "UnequipGasMasks", function(client)
local char = client:getChar()
if (char) then
if (client.deadMaskChar and client.deadMaskChar == char:getID() and char:getVar("gasMask", nil)) then
-- REMOVE TEMP MASKVARS
char:setVar("gasMask", nil)
char:removePart("gasmask")
end
client.deadMaskChar = nil
end
end)
hook.Add("PlayerLoadout", "UnequipGasMasks", function(client)
local char = client:getChar()
if (char) then
local inv = char:getInv()
if (inv) then
for k, v in pairs(inv:getItems()) do
local itemTable = nut.item.instances[v.id]
if (itemTable.gasMask and itemTable:getData("equip")) then
-- INITIALIZE TEMP MASKVARS
char:setVar("gasMask", true)
char:setVar("gasMaskHealth", itemTable:getData("health", DEFAULT_GASMASK_HEALTH))
char:setVar("gasMaskFilter", itemTable:getData("filter", DEFAULT_GASMASK_FILTER))
netstream.Start(client, "mskInit", char:getVar("gasMaskHealth"))
break
end
end
end
end
end)
end
ITEM:hook("drop", function(item)
if (item:getData("equip") == true) then
local char = item.player:getChar()
item:setData("equip", false)
item:setData("health", char:getVar("gasMaskHealth", DEFAULT_GASMASK_HEALTH))
item:setData("filter", char:getVar("gasMaskFilter", DEFAULT_GASMASK_FILTER))
char:setVar("gasMask", nil)
char:setVar("gasMaskHealth", nil)
char:setVar("gasMaskFilter", nil)
item.player:EmitSound("gasmaskoff.wav", 80)
end
end)
ITEM.functions.EquipUn = { -- sorry, for name order.
name = "Unequip",
tip = "unequipTip",
icon = "icon16/cross.png",
onRun = function(item)
local char = item.player:getChar()
-- REMOVE TEMP VARS
-- SAVE TEMP VARS
item.player:EmitSound("gasmaskoff.wav", 80)
item:setData("equip", false)
item:setData("health", char:getVar("gasMaskHealth", DEFAULT_GASMASK_HEALTH))
item:setData("filter", char:getVar("gasMaskFilter", DEFAULT_GASMASK_FILTER))
char:removePart(item.uniqueID)
char:setVar("gasMask", nil)
char:setVar("gasMaskHealth", nil)
char:setVar("gasMaskFilter", nil)
item.player:ScreenFade(1, Color(0, 0, 0, 255), 1, 0)
return false
end,
onCanRun = function(item)
return (!IsValid(item.entity) and item:getData("equip") == true)
end
}
ITEM.functions.Equip = {
name = "Equip",
tip = "equipTip",
icon = "icon16/tick.png",
onRun = function(item)
local char = item.player:getChar()
local inv = char:getInv()
for k, v in pairs(inv:getItems()) do
if (v.id != item.id) then
local itemTable = nut.item.instances[v.id]
if (itemTable.gasMask and itemTable:getData("equip")) then
item.player:notify("You're already wearing mask")
return false
end
end
end
-- INITIALIZE TEMP MASKVARS
item:setData("equip", true)
char:setVar("gasMask", true)
char:setVar("gasMaskHealth", item:getData("health", DEFAULT_GASMASK_HEALTH))
char:setVar("gasMaskFilter", item:getData("filter", DEFAULT_GASMASK_FILTER))
char:addPart(item.uniqueID)
netstream.Start(item.player, "mskInit", char:getVar("gasMaskHealth"))
item.player:EmitSound("gasmaskon.wav", 80)
item.player:ScreenFade(1, Color(0, 0, 0, 255), 1, 0)
return false
end,
onCanRun = function(item)
return (!IsValid(item.entity) and item:getData("equip") != true)
end
}
ITEM.functions.Filter = {
name = "Change Filter",
tip = "filterTip",
icon = "icon16/wrench.png",
onRun = function(item)
local char = item.player:getChar()
local inv = char:getInv()
local filterItem
for k, v in pairs(inv:getItems()) do
if (v.uniqueID == "gasmfilter") then
filterItem = v
end
end
if (filterItem) then
filterItem:remove()
if (item:getData("equip")) then
char:setVar("gasMaskFilter", DEFAULT_GASMASK_FILTER)
end
item:setData("filter", DEFAULT_GASMASK_FILTER)
item.player:notify(L("gmskFilter", item.player))
item.player:EmitSound("gasmaskon.wav", 80)
else
item.player:notify(L("gmskNeedFilter", item.player))
end
return false
end,
onCanRun = function(item)
return (!IsValid(item.entity))
end
}
function ITEM:onCanBeTransfered(oldInventory, newInventory)
return !self:getData("equip")
end
-- Called when a new instance of this item has been made.
function ITEM:onInstanced(invID, x, y)
self:setData("equip", false)
self:setData("health", DEFAULT_GASMASK_HEALTH)
self:setData("filter", DEFAULT_GASMASK_FILTER)
end
|
local MechanicPickup
local vehicleColors = {
black = '000000',
red = 'FF0000',
matallic = 'AAA9AD',
electric_green = '00FF00',
orange = 'FFA500',
yellow = 'FFFF00',
blue = '0000FF',
baby_blue = '89CFF0',
dark_purple = '6A0DAD',
white = 'FFFFFF',
light_purple = 'B19CD9',
dark_red = '8B0000',
pink = 'FFC0CB'
}
AddEvent("OnPackageStart", function()
MechanicPickup = CreatePickup(336, 210791.96875, 175153.03125, 1307.1500244141)
CreateText3D("Mechanic Vehicle Modder" .. "\n" .. "Drive in car" , 18, 210791.96875, 175153.03125, 1307.1500244141, 0, 0, 0)
end)
AddRemoteEvent("StartMechanicJob", function(player)
PlayerData[player].job = 'mechanic'
end)
AddRemoteEvent("StopMechanicJob", function(player)
PlayerData[player].job = ''
end)
AddRemoteEvent("ApplyVehicleMod", function(player, mod, color_name)
local vehicle = GetPlayerVehicle(player)
if vehicle ~= 0 then
if VehicleData[vehicle].player == player then
return CallRemoteEvent(player, 'KNotify:Send', "You cant modify your own vehicle", "#f00")
end
local upgrade_action = {
vehicle_color = function(player, vehicle, color_name)
ApplyColorChange(player, vehicle, color_name)
end,
vehicle_nos = function(player, vehicle)
ApplyNos(player, vehicle, hex)
end,
vehicle_durability = function(player, vehicle)
ApplyVehicleDurability(player, vehicle)
end
}
upgrade_action[mod](player, vehicle, color_name)
end
end)
function ApplyNos(player, vehicle)
local cost = 20000
if GetPlayerCash(player) >= cost then
RemoveBalanceFromAccount(player, 'cash', cost)
AttachVehicleNitro(vehicle, true)
local update_query = mariadb_prepare(sql, "UPDATE player_garage set nos_equipped = 1 WHERE id = '?';", VehicleData[vehicle].garageid)
mariadb_query(sql, update_query)
StartVehicleEngine(vehicle)
CallRemoteEvent(player, 'KNotify:Send', "NOS has been added to this vehicle", "#0f0")
else
CallRemoteEvent(player, 'KNotify:Send', "You dont have enough to add NOS", "#f00")
end
end
function ApplyColorChange(player, vehicle, color_name)
local cost = 500
if GetPlayerCash(player) >= cost then
RemoveBalanceFromAccount(player, 'cash', cost)
SetVehicleColor(vehicle, "0x" .. vehicleColors[color_name])
local update_query = mariadb_prepare(sql, "UPDATE player_garage set color = '?' WHERE id = '?';", vehicleColors[color_name], VehicleData[vehicle].garageid)
mariadb_query(sql, update_query)
StartVehicleEngine(vehicle)
CallRemoteEvent(player, 'KNotify:Send', "The color has been changed on this vehicle", "#0f0")
else
CallRemoteEvent(player, 'KNotify:Send', "You dont have enough to respray", "#f00")
end
end
function ApplyVehicleDurability(player, vehicle)
local cost = 5000
if GetPlayerCash(player) >= cost then
RemoveBalanceFromAccount(player, 'cash', cost)
SetVehicleHealth(vehicle, 10000)
local update_query = mariadb_prepare(sql, "UPDATE player_garage set vehicle_durability = '?' WHERE id = '?';", '1', VehicleData[vehicle].garageid)
mariadb_query(sql, update_query)
StartVehicleEngine(vehicle)
CallRemoteEvent(player, 'KNotify:Send', "Vehicle durability increased", "#0f0")
else
CallRemoteEvent(player, 'KNotify:Send', "You dont have enough to upgrade vehicle durability", "#f00")
end
end
AddEvent("OnPlayerPickupHit", function(player, pickup)
if pickup == MechanicPickup then
local player_vehicle = GetPlayerVehicle(player)
if player_vehicle ~= 0 then
if PlayerData[player].job == 'mechanic' then
if VehicleData[player_vehicle].player == player then
return CallRemoteEvent(player, 'KNotify:Send', "You cant modify your own vehicle", "#f00")
end
StopVehicleEngine(player_vehicle)
SetVehicleLocation(player_vehicle, 211144.015625, 175584.203125, 1307.1500244141)
CallRemoteEvent(player, "ShowVehicleModMenu")
end
end
end
end)
AddRemoteEvent("RepairPlayerVehicle", function(player)
local vehicles = GetAllVehicles()
local nearest_vehicle = GetNearestVehicle(player, vehicles)
if nearest_vehicle then
local vehicle_health = GetVehicleHealth(nearest_vehicle)
if vehicle_health ~= 5000 then
CallRemoteEvent(player, 'KNotify:Send', "Vehicle has been repaired", "#0f0")
SetVehicleHealth(nearest_vehicle, 5000)
for i=1,8 do
SetVehicleDamage(nearest_vehicle, i, 0)
end
else
CallRemoteEvent(player, 'KNotify:Send', "Vehicle is in perfect shape", "#f00")
end
else
CallRemoteEvent(player, 'KNotify:Send', "No vehicle near you", "#f00")
end
end)
function GetNearestVehicle(player, vehicles)
local x, y, z = GetPlayerLocation(player)
for key, vehicle in pairs(vehicles) do
local x2, y2, z2 = GetVehicleLocation(vehicle)
local distance = GetDistance3D(x, y, z, x2, y2, z2)
if distance <= 250 then
return vehicle
end
end
end
AddRemoteEvent("OpenMechanicMenu", function(player)
if PlayerData[player].job == 'mechanic' then
CallRemoteEvent(player, "ShowMechanicMenu")
end
end)
|
Config = {
Prefix = '^9[^1Badger-Tags^9] ^3',
TagsForStaffOnly = false, -- "DiscordTagIDs.Use.Tag-Toggle"
roleList = {
{0, "~g~Member ~w~"},
{"Cert_Civ", "~b~Certified Civilian ~w~"},
{"Police", "~r~Popo ~w~"},
{"Owner", "~o~FOUNDER ~w~"},
},
}
|
local fireutil = require("__base__.prototypes.fire-util")
local nuke_explosions = require("data-nuke-explosions")
local atomic_artillery_recipe = {
type = "recipe",
name = "TN-atomic-artillery-shell",
enabled = false,
energy_required = 120,
ingredients =
{
{"artillery-shell", 1},
{"processing-unit", 20},
{"uranium-235", 100},
{"explosives", 10}
},
result = "TN-atomic-artillery-shell"
}
local atomic_artillery_item = table.deepcopy(data.raw["ammo"]["artillery-shell"])
atomic_artillery_item.name = "TN-atomic-artillery-shell"
if mods["SchallTankPlatoon"] then
atomic_artillery_item.order = "h[artillery]-e[atomic-artillery]"
else
atomic_artillery_item.order = "d[explosive-cannon-shell]-e[atomic-artillery]"
end
atomic_artillery_item.ammo_type.cooldown_modifier = 10
atomic_artillery_item.ammo_type.action.action_delivery.projectile = "TN-atomic-artillery-projectile"
atomic_artillery_item.icon = "__True-Nukes__/graphics/atomic-artillery-shell.png"
atomic_artillery_item.pictures = {
layers =
{
{
size = 64,
filename = "__True-Nukes__/graphics/atomic-artillery-shell.png",
scale = 0.25,
mipmap_count = 4
},
{
draw_as_light = true,
flags = {"light"},
size = 64,
filename = "__True-Nukes__/graphics/atomic-artillery-shell-light.png",
scale = 0.25,
mipmap_count = 1
}
}
}
local atomic_artillery_projectile = table.deepcopy(data.raw["artillery-projectile"]["artillery-projectile"])
atomic_artillery_projectile.name = "TN-atomic-artillery-projectile"
atomic_artillery_projectile.created_effect = {
type = "direct",
action_delivery =
{
type = "instant",
target_effects = {
type = "script",
effect_id = "Nuke firing"
}
}
}
--Hack to fix Make Artillery Great Again's removal of the 'chart_picture'... also just being defensive
if(atomic_artillery_projectile.chart_picture) then
atomic_artillery_projectile.chart_picture.filename = "__True-Nukes__/graphics/atomic-artillery-map-visualization.png"
else
atomic_artillery_projectile.chart_picture = {
filename = "__True-Nukes__/graphics/atomic-artillery-map-visualization.png",
flags = { "icon" },
frame_count = 1,
width = 64,
height = 64,
priority = "high",
scale = 0.25
}
end
atomic_artillery_projectile.action = {
type = "direct",
action_delivery =
{
type = "instant",
target_effects = nuke_explosions.N1kt_detonation
}
}
if(settings.startup["enable-atomic-artillery"].value or settings.startup["enable-big-atomic-artillery"].value or settings.startup["enable-very-big-atomic-artillery"].value) then
data:extend{atomic_artillery_recipe, atomic_artillery_item, atomic_artillery_projectile}
end
if(settings.startup["enable-big-atomic-artillery"].value or settings.startup["enable-very-big-atomic-artillery"].value) then
local big_atomic_artillery_recipe = {
type = "recipe",
name = "TN-big-atomic-artillery-shell",
enabled = false,
energy_required = 300,
ingredients =
{
{"TN-atomic-artillery-shell", 1},
{"processing-unit", 100},
{"uranium-235", 200},
{"explosives", 100}
},
result = "TN-big-atomic-artillery-shell"
}
local big_atomic_artillery_item = table.deepcopy(data.raw["ammo"]["artillery-shell"])
big_atomic_artillery_item.name = "TN-big-atomic-artillery-shell"
if mods["SchallTankPlatoon"] then
big_atomic_artillery_item.order = "h[artillery]-e[big-atomic-artillery]"
else
big_atomic_artillery_item.order = "d[explosive-cannon-shell]-e[big-atomic-artillery]"
end
big_atomic_artillery_item.ammo_type.cooldown_modifier = 15
big_atomic_artillery_item.ammo_type.action.action_delivery.projectile = "TN-big-atomic-artillery-projectile"
big_atomic_artillery_item.icon = "__True-Nukes__/graphics/big-atomic-artillery-shell.png"
big_atomic_artillery_item.pictures = {
layers =
{
{
size = 64,
filename = "__True-Nukes__/graphics/big-atomic-artillery-shell.png",
scale = 0.25,
mipmap_count = 4
},
{
draw_as_light = true,
flags = {"light"},
size = 64,
filename = "__True-Nukes__/graphics/big-atomic-artillery-shell-light.png",
scale = 0.25,
mipmap_count = 1
}
}
}
local big_atomic_artillery_projectile = table.deepcopy(data.raw["artillery-projectile"]["TN-atomic-artillery-projectile"])
big_atomic_artillery_projectile.name = "TN-big-atomic-artillery-projectile"
big_atomic_artillery_projectile.action.action_delivery.target_effects = nuke_explosions.N15kt_detonation
data:extend{big_atomic_artillery_recipe, big_atomic_artillery_item, big_atomic_artillery_projectile}
end
if(settings.startup["enable-very-big-atomic-artillery"].value) then
local very_big_atomic_artillery_recipe = {
type = "recipe",
name = "TN-very-big-atomic-artillery-shell",
enabled = false,
energy_required = 600,
ingredients =
{
{"TN-big-atomic-artillery-shell", 1},
{"processing-unit", 200},
{"FOGBANK", 50},
{"tritium-canister", 5},
{"heat-pipe", 5}
},
result = "TN-very-big-atomic-artillery-shell"
}
local very_big_atomic_artillery_item = table.deepcopy(data.raw["ammo"]["artillery-shell"])
very_big_atomic_artillery_item.name = "TN-very-big-atomic-artillery-shell"
if mods["SchallTankPlatoon"] then
very_big_atomic_artillery_item.order = "h[artillery]-e[very-big-atomic-artillery]"
else
very_big_atomic_artillery_item.order = "d[explosive-cannon-shell]-e[very-big-atomic-artillery]"
end
very_big_atomic_artillery_item.ammo_type.cooldown_modifier = 30
very_big_atomic_artillery_item.ammo_type.action.action_delivery.projectile = "TN-very-big-atomic-artillery-projectile"
very_big_atomic_artillery_item.icon = "__True-Nukes__/graphics/very-big-atomic-artillery-shell.png"
very_big_atomic_artillery_item.pictures = {
layers =
{
{
size = 64,
filename = "__True-Nukes__/graphics/very-big-atomic-artillery-shell.png",
scale = 0.25,
mipmap_count = 4
},
{
draw_as_light = true,
flags = {"light"},
size = 64,
filename = "__True-Nukes__/graphics/big-atomic-artillery-shell-light.png",
scale = 0.25,
mipmap_count = 1
}
}
}
local very_big_atomic_artillery_projectile = table.deepcopy(data.raw["artillery-projectile"]["TN-atomic-artillery-projectile"])
very_big_atomic_artillery_projectile.name = "TN-very-big-atomic-artillery-projectile"
very_big_atomic_artillery_projectile.action.action_delivery.target_effects = nuke_explosions.N100kt_detonation
data:extend{very_big_atomic_artillery_recipe, very_big_atomic_artillery_item, very_big_atomic_artillery_projectile}
end
local small_atomic_artillery_recipe = {
type = "recipe",
name = "TN-small-atomic-artillery-shell",
enabled = false,
energy_required = 90,
ingredients =
{
{"artillery-shell", 1},
{"processing-unit", 10},
{"uranium-235", 75},
{"explosives", 10}
},
result = "TN-small-atomic-artillery-shell"
}
local small_atomic_artillery_item = table.deepcopy(data.raw["ammo"]["artillery-shell"])
small_atomic_artillery_item.name = "TN-small-atomic-artillery-shell"
if mods["SchallTankPlatoon"] then
small_atomic_artillery_item.order = "h[artillery]-d[small-atomic-artillery]"
else
small_atomic_artillery_item.order = "d[explosive-cannon-shell]-d[small-atomic-artillery]"
end
small_atomic_artillery_item.ammo_type.cooldown_modifier = 3
small_atomic_artillery_item.ammo_type.action.action_delivery.projectile = "TN-small-atomic-artillery-projectile"
small_atomic_artillery_item.icon = "__True-Nukes__/graphics/small-atomic-artillery-shell.png"
small_atomic_artillery_item.pictures = {
layers =
{
{
size = 64,
filename = "__True-Nukes__/graphics/small-atomic-artillery-shell.png",
scale = 0.25,
mipmap_count = 4
},
{
draw_as_light = true,
flags = {"light"},
size = 64,
filename = "__True-Nukes__/graphics/atomic-artillery-shell-light.png",
scale = 0.25,
mipmap_count = 1
}
}
}
local small_atomic_artillery_projectile = table.deepcopy(atomic_artillery_projectile)
small_atomic_artillery_projectile.name = "TN-small-atomic-artillery-projectile"
small_atomic_artillery_projectile.action.action_delivery.target_effects = nuke_explosions.N500t_detonation
if(settings.startup["enable-small-atomic-artillery"].value) then
data:extend{small_atomic_artillery_recipe, small_atomic_artillery_item, small_atomic_artillery_projectile}
end
local very_small_atomic_artillery_recipe = {
type = "recipe",
name = "TN-very-small-atomic-artillery-shell",
enabled = false,
energy_required = 60,
ingredients =
{
{"artillery-shell", 1},
{"processing-unit", 5},
{"uranium-235", 30},
{"explosives", 10}
},
result = "TN-very-small-atomic-artillery-shell"
}
local very_small_atomic_artillery_item = table.deepcopy(data.raw["ammo"]["artillery-shell"])
very_small_atomic_artillery_item.name = "TN-very-small-atomic-artillery-shell"
if mods["SchallTankPlatoon"] then
very_small_atomic_artillery_item.order = "h[artillery]-d[atomic-artillery]"
else
very_small_atomic_artillery_item.order = "d[explosive-cannon-shell]-d[atomic-artillery]"
end
very_small_atomic_artillery_item.ammo_type.cooldown_modifier = 1.5
very_small_atomic_artillery_item.ammo_type.action.action_delivery.projectile = "TN-very-small-atomic-artillery-projectile"
very_small_atomic_artillery_item.icon = "__True-Nukes__/graphics/very-small-atomic-artillery-shell.png"
very_small_atomic_artillery_item.icon_mipmaps = 1
very_small_atomic_artillery_item.pictures = {
layers =
{
{
size = 64,
filename = "__True-Nukes__/graphics/very-small-atomic-artillery-shell.png",
scale = 0.25,
mipmap_count = 1
},
{
draw_as_light = true,
flags = {"light"},
size = 64,
filename = "__True-Nukes__/graphics/atomic-artillery-shell-light.png",
scale = 0.25,
mipmap_count = 1
}
}
}
local very_small_atomic_artillery_projectile = table.deepcopy(atomic_artillery_projectile)
very_small_atomic_artillery_projectile.name = "TN-very-small-atomic-artillery-projectile"
very_small_atomic_artillery_projectile.action.action_delivery.target_effects = nuke_explosions.N20t_detonation
if(settings.startup["enable-very-small-atomic-artillery"].value) then
data:extend{very_small_atomic_artillery_recipe, very_small_atomic_artillery_item, very_small_atomic_artillery_projectile}
end
local artillery_nuke_tech = table.deepcopy(data.raw["technology"]["atomic-bomb"])
artillery_nuke_tech.name = "atomic-artillery-shells"
artillery_nuke_tech.effects = {}
if(settings.startup["enable-very-small-atomic-artillery"].value) then
table.insert(artillery_nuke_tech.effects,
{
type = "unlock-recipe",
recipe = "TN-very-small-atomic-artillery-shell"
})
end
if(settings.startup["enable-small-atomic-artillery"].value) then
table.insert(artillery_nuke_tech.effects,
{
type = "unlock-recipe",
recipe = "TN-small-atomic-artillery-shell"
})
end
if(settings.startup["enable-atomic-artillery"].value or settings.startup["enable-big-atomic-artillery"].value or settings.startup["enable-very-big-atomic-artillery"].value) then
table.insert(artillery_nuke_tech.effects,
{
type = "unlock-recipe",
recipe = "TN-atomic-artillery-shell"
})
end
artillery_nuke_tech.unit.count=2000
artillery_nuke_tech.prerequisites = {"atomic-bomb", "artillery"}
artillery_nuke_tech.order = "e-a-c"
artillery_nuke_tech.icon = "__True-Nukes__/graphics/atomic-artillery-tech.png"
artillery_nuke_tech.icon_mipmaps = 1
data:extend{artillery_nuke_tech}
|
local PANEL = {}
function PANEL:Init()
self:SetSize(500, 700)
self:MakePopup()
self:Center()
self:SetTitle("Paper")
self.controls = self:Add("DPanel")
self.controls:Dock(BOTTOM)
self.controls:SetTall(30)
self.controls:DockMargin(0, 5, 0, 0)
self.contents = self:Add("DTextEntry")
self.contents:Dock(FILL)
self.contents:SetMultiline(true)
self.contents:SetEditable(true)
self.test = self.controls:Add("DTextEntry")
self.test:SetMultiline(true)
self.test:SetSize(0,0)
self.test:SetEditable(false)
self.confirm = self.controls:Add("DButton")
self.confirm:Dock(RIGHT)
self.confirm:SetDisabled(false)
self.confirm:SetText(L("Terminer"))
self.controls.Paint = function(this, w, h)
local text = self.contents:GetValue()
draw.SimpleText(Format("Number of characters: %s/3000", string.len(text)), "DermaDefault", 10, h/2, color_white, TEXT_ALIGN_LEFT, 1)
end
self.confirm.DoClick = function(this)
local text = self.contents:GetValue()
netstream.Start("paperSendText", itemID, text)
self:Close()
end
end
function PANEL:setText(text, id)
self.contents:SetValue(text or "")
itemID = id
end
vgui.Register("paperRead", PANEL, "DFrame")
|
--- === hs.canvas.matrix ===
---
--- A sub module to `hs.canvas` which provides support for basic matrix manipulations which can be used as the values for `transformation` attributes in the `hs.canvas` module.
---
--- For mathematical reasons that are beyond the scope of this document, a 3x3 matrix can be used to represent a series of manipulations to be applied to the coordinates of a 2 dimensional drawing object. These manipulations can include one or more of a combination of translations, rotations, shearing and scaling. Within the 3x3 matrix, only 6 numbers are actually required, and this module represents them as the following keys in a Lua table: `m11`, `m12`, `m21`, `m22`, `tX`, and `tY`. For those of a mathematical bent, the 3x3 matrix used within this module can be visualized as follows:
---
--- [ m11, m12, 0 ]
--- [ m21, m22, 0 ]
--- [ tX, tY, 1 ]
---
--- This module allows you to generate the table which can represent one or more of the recognized transformations without having to understand the math behind the manipulations or specify the matrix values directly.
---
--- Many of the methods defined in this module can be used both as constructors and as methods chained to a previous method or constructor. Chaining the methods in this manner allows you to combine multiple transformations into one combined table which can then be assigned to an element in your canvas.
---.
---
--- For more information on the mathematics behind these, you can check the web. One site I used for reference (but there are many more which go into much more detail) can be found at http://www.cs.trinity.edu/~jhowland/cs2322/2d/2d/.
local USERDATA_TAG = "hs.canvas.matrix"
local module = require("hs.libcanvasmatrix")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
-- store this in the registry so we can easily set it both from Lua and from C functions
debug.getregistry()[USERDATA_TAG] = {
__type = USERDATA_TAG,
__index = module,
__tostring = function(_)
return string.format("[ % 10.4f % 10.4f 0 ]\n[ % 10.4f % 10.4f 0 ]\n[ % 10.4f % 10.4f 1 ]",
_.m11, _.m12, _.m21, _.m22, _.tX, _.tY)
end,
}
-- Return Module Object --------------------------------------------------
return module
|
local AttackRange = Component.create("AttackRange")
function AttackRange:initialize(max, min)
self.max = max
self.min = min or -1
end
function AttackRange:setRange(max, min)
self.max = max
self.min = min or -1
end
|
local name = "mesecar_yellow"
local definition = ...
definition.description = "Yellow Mesecar"
definition.inventory_image = "mesecar_car4front.png"
definition.wield_image = "mesecar_car4front.png"
definition.textures = {
"mesecar_car4top.png",
"mesecar_carbase.png",
"mesecar_car4rightside.png",
"mesecar_car4leftside.png",
"mesecar_car4front.png",
"mesecar_car4back.png"
}
vehicle_mash.register_vehicle("vehicle_mash:"..name, definition)
|
SPECIAL_MSGTYPE_ADDTOKEN = "addtoken";
function onInit()
-- if the user is the host
if User.isHost() then
-- create the token node
local tokensnode = DB.createNode("tokens");
-- clean the current tokens
cleanTokens();
-- subscrive to the user login event
--User.onLogin = onLogin;
end
-- register special messages
ChatManager.registerSpecialMessageHandler(SPECIAL_MSGTYPE_ADDTOKEN, handleAddToken);
end
function onLogin(username, activated)
if User.isHost() and activated then
DB.findNode("tokens").addHolder(username);
end
end
function cleanTokens(containernode, tokens)
if User.isHost() then
local tokensnode = DB.findNode("tokens");
for k1, v1 in pairs(tokensnode.getChildren()) do
local currentcontainernode = DB.findNode(v1.getChild("container").getValue());
if currentcontainernode then
if containernode and containernode.getNodeName() == currentcontainernode.getNodeName() and tokens then
local exists = false;
for k2, v2 in ipairs(tokens) do
if v2.getId() == v1.getChild("id").getValue() then
exists = true;
end
end
if not exists then
v1.delete();
end
end
else
v1.delete();
end
end
end
end
function addToken(token, classname, recordname)
return ChatManager.sendSpecialMessage(SPECIAL_MSGTYPE_ADDTOKEN, {token.getContainerNode().getNodeName(), token.getId(), classname, recordname});
end
function handleAddToken(msguser, msgidentity, msgparams)
if User.isHost() then
-- get the tokens node
local tokensnode = DB.findNode("tokens");
-- get the message parameters
local containername = msgparams[1];
local tokenid = tonumber(msgparams[2]);
local classname = msgparams[3];
local recordname = msgparams[4];
-- determine if node already exists for this token
local tokennode = nil;
for k, v in pairs(tokensnode.getChildren()) do
if v.getChild("container").getValue() == containername and v.getChild("id").getValue == tokenid then
tokennode = v;
end
end
-- create the token node if required
if not tokennode then
tokennode = tokensnode.createChild();
tokennode.createChild("container", "string").setValue(containername);
tokennode.createChild("id", "number").setValue(tokenid);
end
-- update the token details
tokennode.createChild("classname", "string").setValue(classname);
tokennode.createChild("recordname", "string").setValue(recordname);
-- make the token targetable
local containernode = DB.findNode(containername);
if containernode then
local windownode = containernode.getParent();
if windownode then
local imagewindow = Interface.findWindow("image", windownode);
if imagewindow then
local tokens = imagewindow.image.getTokens();
if tokens then
for k, v in pairs(tokens) do
if v.getId() == tokenid then
if not v.isTargetable() then
v.setTargetable(true);
end
end
end
end
local viewers = imagewindow.getViewers();
if viewers then
for k, v in pairs(viewers) do
imagewindow.share(v);
end
end
end
end
end
end
return true;
end
function getTokenNode(token)
local tokensnode = DB.findNode("tokens");
for k, v in pairs(tokensnode.getChildren()) do
local container = v.getChild("container").getValue();
local id = v.getChild("id").getValue();
if token.getContainerNode().getNodeName() == container and token.getId() == id then
return v;
end
end
end
function openTokenSheet(token)
local tokennode = getTokenNode(token);
if tokennode then
local classname = tokennode.getChild("classname").getValue();
local recordnode = DB.findNode(tokennode.getChild("recordname").getValue());
if recordnode then
if classname == "charsheet" then
CharacterManager.openCharacterSheet(recordnode);
elseif classname == "npc" then
NpcManager.openNpcSheet(recordnode);
elseif classname == "partysheet" then
PartySheetManager.openPartySheet();
elseif classname == "location" then
LocationManager.openLocation(recordnode);
elseif classname == "pet" then
PetManager.openPetSheet(recordnode);
elseif classname == "horse" then
HorseManager.openHorseSheet(recordnode);
elseif classname == "retainer" then
RetainerManager.openRetainerSheet(recordnode);
end
end
return true;
end
end
function onDrop(token, draginfo)
local tokennode = getTokenNode(token);
Debug.console("tokenmanager.lua: on Drop. Drop type = " .. draginfo.getType());
if tokennode then
local classname = tokennode.getChild("classname").getValue();
local recordnode = DB.findNode(tokennode.getChild("recordname").getValue());
--Debug.console("tokenmanager.lua: on Drop. classname = " .. classname);
if recordnode then
if classname == "charsheet" then
return CharacterManager.onDrop(recordnode, 0, 0, draginfo);
elseif classname == "npc" then
return NpcManager.onDrop(recordnode, 0, 0, draginfo);
elseif classname == "partysheet" then
return PartySheetManager.onDrop(0, 0, draginfo);
end
end
end
end
function onWheel(token, notches)
if Input.isControlPressed() then
if not token then
return ;
end
local scale = token.getScale();
if Input.isShiftPressed() then
scale = math.floor(scale + notches);
if scale < 1 then
scale = 1;
end
else
scale = scale + (notches * 0.1);
if scale < 0.1 then
scale = 0.1;
end
end
token.setScale(scale);
return true;
end
end
function targetToken(token)
if not User.isHost() and User.getCurrentIdentity() then
token.setTarget(not token.isTargetedByIdentity());
end
return true;
end
|
local M = {}
local sign_define_cache = {}
local function sign_get(name)
if not sign_define_cache[name] then
local s = vim.fn.sign_getdefined(name)
if not vim.tbl_isempty(s) then
sign_define_cache[name] = s
end
end
return sign_define_cache[name]
end
function M.sign_define(name, opts, redefine)
if redefine then
sign_define_cache[name] = nil
vim.fn.sign_undefine(name)
vim.fn.sign_define(name, opts)
elseif not sign_get(name) then
vim.fn.sign_define(name, opts)
end
end
return M
|
---------------------------------------------------------------------------
--- Text clock widget.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @classmod wibox.widget.textclock
---------------------------------------------------------------------------
local setmetatable = setmetatable
local os = os
local textbox = require("wibox.widget.textbox")
local timer = require("gears.timer")
local gtable = require("gears.table")
local glib = require("lgi").GLib
local DateTime = glib.DateTime
local TimeZone = glib.TimeZone
local textclock = { mt = {} }
--- Set the clock's format
-- @property format
-- @tparam string format The new time format. This can contain pango markup
function textclock:set_format(format)
self._private.format = format
self:force_update()
end
function textclock:get_format()
return self._private.format
end
--- Set the clock's timezone
-- @property timezone
-- @tparam string timezone
function textclock:set_timezone(tzid)
self._private.tzid = tzid
self._private.timezone = tzid and TimeZone.new(tzid)
self:force_update()
end
function textclock:get_timezone()
return self._private.tzid
end
--- Set the clock's refresh rate
-- @property refresh
-- @tparam number How often the clock is updated, in seconds
function textclock:set_refresh(refresh)
self._private.refresh = refresh or self._private.refresh
self:force_update()
end
function textclock:get_refresh()
return self._private.refresh
end
--- Force a textclock to update now.
function textclock:force_update()
self._timer:emit_signal("timeout")
end
--- This lowers the timeout so that it occurs "correctly". For example, a timeout
-- of 60 is rounded so that it occurs the next time the clock reads ":00 seconds".
local function calc_timeout(real_timeout)
return real_timeout - os.time() % real_timeout
end
--- Create a textclock widget. It draws the time it is in a textbox.
--
-- @tparam[opt=" %a %b %d, %H:%M "] string format The time format.
-- @tparam[opt=60] number refresh How often to update the time (in seconds).
-- @tparam[opt=local timezone] string timezone The timezone to use,
-- e.g. "Z" for UTC, "±hh:mm" or "Europe/Amsterdam". See
-- https://developer.gnome.org/glib/stable/glib-GTimeZone.html#g-time-zone-new.
-- @treturn table A textbox widget.
-- @function wibox.widget.textclock
local function new(format, refresh, tzid)
local w = textbox()
gtable.crush(w, textclock, true)
w._private.format = format or " %a %b %d, %H:%M "
w._private.refresh = refresh or 60
w._private.tzid = tzid
w._private.timezone = tzid and TimeZone.new(tzid)
function w._private.textclock_update_cb()
local str = DateTime.new_now(w._private.timezone or TimeZone.new_local()):format(w._private.format)
if str == nil then
require("gears.debug").print_warning("textclock: "
.. "g_date_time_format() failed for format "
.. "'" .. w._private.format .. "'")
end
w:set_markup(str)
w._timer.timeout = calc_timeout(w._private.refresh)
w._timer:again()
return true -- Continue the timer
end
w._timer = timer.weak_start_new(refresh, w._private.textclock_update_cb)
w:force_update()
return w
end
function textclock.mt:__call(...)
return new(...)
end
--
--
return setmetatable(textclock, textclock.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
module("Loader", package.seeall)
BaseGamemode = GM.FolderName
local function GetFileList(strDirectory, strGamemode)
local files = {}
local realDirectory = strGamemode .. "/gamemode/" .. strDirectory .. "/*"
local findFiles, findFolders = file.Find(realDirectory, "LUA")
for k, v in pairs(table.Add(findFiles, findFolders)) do
if (v == "." or v == ".." or v == ".svn") then continue end
table.insert(files, v)
end
return files
end
local function IsLuaFile(strFile)
return (string.sub(strFile, -4) == ".lua")
end
local function IsDirectory(strDir)
return (string.GetExtensionFromFilename(strDir) == nil)
end
local function LoadFile(strDirectory, strGamemode, strFile)
local prefix = string.sub(strFile, 0, 3)
local realFile = strGamemode .. "/gamemode/" .. strDirectory .. "/" .. strFile
if (prefix == "cl_") then
if SERVER then
AddCSLuaFile(realFile)
else
include(realFile)
end
elseif (prefix == "sh_") then
if SERVER then
AddCSLuaFile(realFile)
end
include(realFile)
elseif (prefix == "sv_" or strFile == "init.lua") then
if SERVER then
include(realFile)
end
end
end
function LoadAction(strDirectory, strGamemode, funcAction)
local entList = GetFileList(strDirectory, strGamemode)
for _, v in pairs(entList) do
local entDir = strDirectory .. "/" .. v
local entFiles = GetFileList(entDir, strGamemode)
funcAction(entDir, entFiles, v, strGamemode)
end
end
function LoadEntities(entDir, entFiles, entName, strGamemode)
_G.ENT = {}
for _, entFile in pairs(entFiles) do
LoadFile(entDir, strGamemode, entFile)
end
if _G.ENT.Type then
scripted_ents.Register(_G.ENT, entName, false)
end
_G.ENT = nil
end
function LoadEnts(strDirectory, strGamemode)
local strDirectory = strDirectory .. "/ents"
local fileList = GetFileList(strDirectory, strGamemode)
for _, v in pairs(fileList) do
local entFolder = strDirectory .. "/" .. v
if (v == "entities") then
LoadAction(entFolder, strGamemode, LoadEntities)
end
end
end
function Load(strDirectory, strGamemode)
if (not strGamemode) then
strGamemode = BaseGamemode
end
local fileList = GetFileList(strDirectory, strGamemode)
if table.HasValue(fileList, "ents") then
LoadEnts(strDirectory, strGamemode)
end
for k, v in pairs(fileList) do
if (IsLuaFile(v)) then
LoadFile(strDirectory, strGamemode, v)
elseif (v ~= "ents") then
local strNextDir = strDirectory .. "/" .. v
if IsDirectory(strNextDir) then
Load(strNextDir, strGamemode) -- go deeper. BWOOOOOONG!!
end
end
end
end
|
--[[
Core.lua is intended to store all core functions and variables to be used throughout the addon.
Don't put anything in here that you don't want to be loaded immediately after the Libs but before initialization.
--]]
local _, core = ...;
local _G = _G;
local L = core.L;
core.MonDKP = {}; -- UI Frames global
local MonDKP = core.MonDKP;
local tc_colors = {
["Druid"] = { r = 1, g = 0.49, b = 0.04, hex = "FF7D0A" },
["Hunter"] = { r = 0.67, g = 0.83, b = 0.45, hex = "ABD473" },
["Mage"] = { r = 0.25, g = 0.78, b = 0.92, hex = "40C7EB" },
["Priest"] = { r = 1, g = 1, b = 1, hex = "FFFFFF" },
["Rogue"] = { r = 1, g = 0.96, b = 0.41, hex = "FFF569" },
["Shaman"] = { r = 0.96, g = 0.55, b = 0.73, hex = "F58CBA" },
["Paladin"] = { r = 0.96, g = 0.55, b = 0.73, hex = "F58CBA" },
["Warlock"] = { r = 0.53, g = 0.53, b = 0.93, hex = "8787ED" },
["Warrior"] = { r = 0.78, g = 0.61, b = 0.43, hex = "C79C6E" }
}
local tc_classes = {}
core.faction = UnitFactionGroup("player")
if core.faction == "Horde" then
tc_classes = { "Druid", "Hunter", "Mage", "Priest", "Rogue", "Shaman", "Warlock", "Warrior" }
elseif core.faction == "Alliance" then
tc_classes = { "Druid", "Hunter", "Mage", "Paladin", "Priest", "Rogue", "Warlock", "Warrior" }
end
core.CColors = {
["UNKNOWN"] = { r = 0.627, g = 0.627, b = 0.627, hex = "A0A0A0" }
}
core.classes = {}
for i = 1, #tc_classes do
local cname = tc_classes[i]
local lname = string.upper(cname)
core.CColors[lname] = tc_colors[cname]
table.insert(core.classes, lname)
end
--------------------------------------
-- Addon Defaults
--------------------------------------
local defaults = {
theme = { r = 0.6823, g = 0.6823, b = 0.8666, hex = "aeaedd" },
theme2 = { r = 1, g = 0.37, b = 0.37, hex = "ff6060" }
}
core.WorkingTable = {}; -- table of all entries from MonDKP_DKPTable that are currently visible in the window. From MonDKP_DKPTable
core.EncounterList = { -- Event IDs must be in the exact same order as core.BossList declared in localization files
MC = {
663, 664, 665,
666, 668, 667, 669,
670, 671, 672
},
BWL = {
610, 611, 612,
613, 614, 615, 616,
617
},
AQ = {
709, 711, 712,
714, 715, 717,
710, 713, 716
},
NAXX = {
1107, 1110, 1116,
1117, 1112, 1115,
1113, 1109, 1121,
1118, 1111, 1108, 1120,
1119, 1114
},
ZG = {
787, 790, 793, 789, 784, 791,
785, 792, 786, 788
},
AQ20 = {
722, 721, 719, 718, 720, 723
},
ONYXIA = {1084},
WORLD = { -- No encounter IDs have been identified for these world bosses yet
"Azuregos", "Lord Kazzak", "Emeriss", "Lethon", "Ysondre", "Taerar"
}
}
core.MonDKPUI = {} -- global storing entire Configuration UI to hide/show UI
core.MonVersion = "v2.1.2 custom";
core.BuildNumber = 20102;
core.TableWidth, core.TableRowHeight, core.TableNumRows = 500, 18, 27; -- width, row height, number of rows
core.SelectedData = { player="none"}; -- stores data of clicked row for manipulation.
core.classFiltered = {}; -- tracks classes filtered out with checkboxes
core.IsOfficer = nil;
core.ShowState = false;
core.StandbyActive = false;
core.currentSort = "class" -- stores current sort selection
core.BidInProgress = false; -- flagged true if bidding in progress. else; false.
core.RaidInProgress = false;
core.NumLootItems = 0; -- updates on LOOT_OPENED event
core.Initialized = false
core.InitStart = false
core.CurrentRaidZone = ""
core.LastKilledBoss = ""
core.ArchiveActive = false
core.CurView = "all"
core.CurSubView = "all"
core.LastVerCheck = 0
core.CenterSort = "class";
core.OOD = false
function MonDKP:GetCColors(class)
if core.CColors then
local c
if class then
c = core.CColors[class] or core.CColors["UNKNOWN"];
else
c = core.CColors
end
return c;
else
return false;
end
end
function MonDKP_round(number, decimals)
return tonumber((("%%.%df"):format(decimals)):format(number))
end
function MonDKP:ResetPosition()
MonDKP.UIConfig:ClearAllPoints();
MonDKP.UIConfig:SetPoint("CENTER", UIParent, "CENTER", -250, 100);
MonDKP.UIConfig:SetSize(550, 590);
MonDKP.UIConfig.TabMenu:Hide()
MonDKP.UIConfig.expandtab:SetTexture("Interface\\AddOns\\MonolithDKP\\Media\\Textures\\expand-arrow");
core.ShowState = false;
MonDKP.BidTimer:ClearAllPoints()
MonDKP.BidTimer:SetPoint("CENTER", UIParent)
MonDKP:Print(L["POSITIONRESET"])
end
function MonDKP:GetGuildRank(player)
local name, rank, rankIndex;
local guildSize;
if IsInGuild() then
guildSize = GetNumGuildMembers();
for i=1, guildSize do
name, rank, rankIndex = GetGuildRosterInfo(i)
name = strsub(name, 1, string.find(name, "-")-1) -- required to remove server name from player (can remove in classic if this is not an issue)
if name == player then
return rank, rankIndex;
end
end
return L["NOTINGUILD"];
end
return L["NOGUILD"]
end
function MonDKP:GetGuildRankIndex(player)
local name, rank;
local guildSize,_,_ = GetNumGuildMembers();
if IsInGuild() then
for i=1, tonumber(guildSize) do
name,_,rank = GetGuildRosterInfo(i)
name = strsub(name, 1, string.find(name, "-")-1) -- required to remove server name from player (can remove in classic if this is not an issue)
if name == player then
return rank+1;
end
end
return false;
end
end
function MonDKP:CheckOfficer() -- checks if user is an officer IF core.IsOfficer is empty. Use before checks against core.IsOfficer
if not core.InitStart then return end
if core.IsOfficer == nil then -- used as a redundency as it should be set on load in init.lua GUILD_ROSTER_UPDATE event
if MonDKP:GetGuildRankIndex(UnitName("player")) == 1 then -- automatically gives permissions above all settings if player is guild leader
core.IsOfficer = true
MonDKP.ConfigTab3.WhitelistContainer:Show()
return;
end
if IsInGuild() then
if #MonDKP_Whitelist > 0 then
core.IsOfficer = false;
for i=1, #MonDKP_Whitelist do
if MonDKP_Whitelist[i] == UnitName("player") then
core.IsOfficer = true;
end
end
else
local curPlayerRank = MonDKP:GetGuildRankIndex(UnitName("player"))
if curPlayerRank then
core.IsOfficer = C_GuildInfo.GuildControlGetRankFlags(curPlayerRank)[12]
end
end
else
core.IsOfficer = false;
end
end
end
function MonDKP:GetGuildRankGroup(index) -- returns all members within a specific rank index as well as their index in the guild list (for use with GuildRosterSetPublicNote(index, "msg") and GuildRosterSetOfficerNote)
local name, rank --, seed; -- local temp = MonDKP:GetGuildRankGroup(1)
local group = {} -- print(temp[1]["name"])
local guildSize,_,_ = GetNumGuildMembers();
if IsInGuild() then
for i=1, tonumber(guildSize) do
name,_,rank = GetGuildRosterInfo(i)
--seed = MonDKP:RosterSeedExtract(i)
rank = rank+1;
name = strsub(name, 1, string.find(name, "-")-1) -- required to remove server name from player (can remove in classic if this is not an issue)
if rank == index then
--tinsert(group, { name = name, index = i, seed = seed })
tinsert(group, { name = name, index = i })
end
end
return group;
end
end
function MonDKP:CheckRaidLeader()
local tempName,tempRank;
for i=1, 40 do
tempName, tempRank = GetRaidRosterInfo(i)
if tempName == UnitName("player") and tempRank == 2 then
return true
end
end
return false;
end
function MonDKP:GetThemeColor()
local c = {defaults.theme, defaults.theme2};
return c;
end
function MonDKP:GetPlayerDKP(player)
local search = MonDKP:Table_Search(MonDKP_DKPTable, player)
if search then
return MonDKP_DKPTable[search[1][1]].dkp
else
return false;
end
end
function MonDKP:PurgeLootHistory() -- cleans old loot history beyond history limit to reduce native system load
local limit = MonDKP_DB.defaults.HistoryLimit
if #MonDKP_Loot > limit then
while #MonDKP_Loot > limit do
MonDKP:SortLootTable()
local path = MonDKP_Loot[#MonDKP_Loot]
if not MonDKP_Archive[path.player] then
MonDKP_Archive[path.player] = { dkp=path.cost, lifetime_spent=path.cost, lifetime_gained=0 }
else
MonDKP_Archive[path.player].dkp = MonDKP_Archive[path.player].dkp + path.cost
MonDKP_Archive[path.player].lifetime_spent = MonDKP_Archive[path.player].lifetime_spent + path.cost
end
if not MonDKP_Archive.LootMeta or MonDKP_Archive.LootMeta < path.date then
MonDKP_Archive.LootMeta = path.date
end
tremove(MonDKP_Loot, #MonDKP_Loot)
end
end
end
function MonDKP:PurgeDKPHistory() -- purges old entries and stores relevant data in each users MonDKP_Archive entry (dkp, lifetime spent, and lifetime gained)
local limit = MonDKP_DB.defaults.DKPHistoryLimit
if #MonDKP_DKPHistory > limit then
while #MonDKP_DKPHistory > limit do
MonDKP:SortDKPHistoryTable()
local path = MonDKP_DKPHistory[#MonDKP_DKPHistory]
local players = {strsplit(",", strsub(path.players, 1, -2))}
local dkp = {strsplit(",", path.dkp)}
if #dkp == 1 then
for i=1, #players do
dkp[i] = tonumber(dkp[1])
end
else
for i=1, #dkp do
dkp[i] = tonumber(dkp[i])
end
end
for i=1, #players do
if not MonDKP_Archive[players[i]] then
if ((dkp[i] > 0 and not path.deletes) or (dkp[i] < 0 and path.deletes)) and not strfind(path.dkp, "%-%d*%.?%d+%%") then
MonDKP_Archive[players[i]] = { dkp=dkp[i], lifetime_spent=0, lifetime_gained=dkp[i] }
else
MonDKP_Archive[players[i]] = { dkp=dkp[i], lifetime_spent=0, lifetime_gained=0 }
end
else
MonDKP_Archive[players[i]].dkp = MonDKP_Archive[players[i]].dkp + dkp[i]
if ((dkp[i] > 0 and not path.deletes) or (dkp[i] < 0 and path.deletes)) and not strfind(path.dkp, "%-%d*%.?%d+%%") then --lifetime gained if dkp addition and not a delete entry, dkp decrease and IS a delete entry
MonDKP_Archive[players[i]].lifetime_gained = MonDKP_Archive[players[i]].lifetime_gained + path.dkp --or is NOT a decay
end
end
end
if not MonDKP_Archive.DKPMeta or MonDKP_Archive.DKPMeta < path.date then
MonDKP_Archive.DKPMeta = path.date
end
tremove(MonDKP_DKPHistory, #MonDKP_DKPHistory)
end
end
end
function MonDKP:FormatTime(time)
local str = date("%y/%m/%d %H:%M:%S", time)
return str;
end
function MonDKP:Print(...) --print function to add "MonolithDKP:" to the beginning of print() outputs.
if not MonDKP_DB.defaults.supressNotifications then
local defaults = MonDKP:GetThemeColor();
local prefix = string.format("|cff%s%s|r|cff%s", defaults[1].hex:upper(), "ValaDKP:", defaults[2].hex:upper());
local suffix = "|r";
for i = 1, NUM_CHAT_WINDOWS do
local name = GetChatWindowInfo(i)
if MonDKP_DB.defaults.ChatFrames[name] then
_G["ChatFrame"..i]:AddMessage(string.join(" ", prefix, ..., suffix));
end
end
end
end
function MonDKP:CreateButton(point, relativeFrame, relativePoint, xOffset, yOffset, text)
local btn = CreateFrame("Button", nil, relativeFrame, "MonolithDKPButtonTemplate")
btn:SetPoint(point, relativeFrame, relativePoint, xOffset, yOffset);
btn:SetSize(100, 30);
btn:SetText(text);
btn:GetFontString():SetTextColor(1, 1, 1, 1)
btn:SetNormalFontObject("MonDKPSmallCenter");
btn:SetHighlightFontObject("MonDKPSmallCenter");
return btn;
end
function MonDKP:BroadcastTimer(seconds, ...) -- broadcasts timer and starts it natively
if IsInRaid() and core.IsOfficer == true then
local title = ...;
if not tonumber(seconds) then -- cancels the function if the command was entered improperly (eg. no number for time)
MonDKP:Print(L["INVALIDTIMER"]);
return;
end
MonDKP:StartTimer(seconds, ...)
MonDKP.Sync:SendData("MonDKPCommand", "StartTimer,"..seconds..","..title)
end
end
function MonDKP:CreateContainer(parent, name, header)
local f = CreateFrame("Frame", "MonDKP"..name, parent);
f:SetBackdrop( {
edgeFile = "Interface\\AddOns\\MonolithDKP\\Media\\Textures\\edgefile.tga", tile = true, tileSize = 1, edgeSize = 2,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
});
f:SetBackdropColor(0,0,0,0.9);
f:SetBackdropBorderColor(1,1,1,0.5)
f.header = CreateFrame("Frame", "MonDKP"..name.."Header", f)
f.header:SetBackdrop( {
bgFile = "Textures\\white.blp", tile = true, -- White backdrop allows for black background with 1.0 alpha on low alpha containers
insets = { left = 0, right = 0, top = 0, bottom = 0 }
});
f.header:SetBackdropColor(0,0,0,1)
f.header:SetBackdropBorderColor(0,0,0,1)
f.header:SetPoint("LEFT", f, "TOPLEFT", 20, 0)
f.header.text = f.header:CreateFontString(nil, "OVERLAY")
f.header.text:SetFontObject("MonDKPSmallCenter");
f.header.text:SetPoint("CENTER", f.header, "CENTER", 0, 0);
f.header.text:SetText(header);
f.header:SetWidth(f.header.text:GetWidth() + 10)
f.header:SetHeight(f.header.text:GetHeight() + 4)
return f;
end
function MonDKP:StartTimer(seconds, ...)
local duration = tonumber(seconds)
local alpha = 1;
if not tonumber(seconds) then -- cancels the function if the command was entered improperly (eg. no number for time)
MonDKP:Print(L["INVALIDTIMER"]);
return;
end
MonDKP.BidTimer = MonDKP.BidTimer or MonDKP:CreateTimer(); -- recycles timer frame so multiple instances aren't created
MonDKP.BidTimer:SetShown(not MonDKP.BidTimer:IsShown()) -- shows if not shown
if MonDKP.BidTimer:IsShown() == false then -- terminates function if hiding timer
return;
end
MonDKP.BidTimer:SetMinMaxValues(0, duration)
MonDKP.BidTimer.timerTitle:SetText(...)
PlaySound(8959)
if MonDKP_DB.timerpos then
local a = MonDKP_DB["timerpos"] -- retrieves timer's saved position from SavedVariables
MonDKP.BidTimer:SetPoint(a.point, a.relativeTo, a.relativePoint, a.x, a.y)
else
MonDKP.BidTimer:SetPoint("CENTER") -- sets to center if no position has been saved
end
local timer = 0 -- timer starts at 0
local timerText; -- count down when below 1 minute
local modulo -- remainder after divided by 60
local timerMinute -- timerText / 60 to get minutes.
local audioPlayed = false; -- so audio only plays once
local expiring; -- determines when red blinking bar starts. @ 30 sec if timer > 120 seconds, @ 10 sec if below 120 seconds
MonDKP.BidTimer:SetScript("OnUpdate", function(self, elapsed) -- timer loop
timer = timer + elapsed
timerText = MonDKP_round(duration - timer, 1)
if tonumber(timerText) > 60 then
timerMinute = math.floor(tonumber(timerText) / 60, 0);
modulo = bit.mod(tonumber(timerText), 60);
if tonumber(modulo) < 10 then modulo = "0"..modulo end
MonDKP.BidTimer.timertext:SetText(timerMinute..":"..modulo)
else
MonDKP.BidTimer.timertext:SetText(timerText)
end
if duration >= 120 then
expiring = 30;
else
expiring = 10;
end
if tonumber(timerText) < expiring then
if audioPlayed == false then
PlaySound(23639);
end
if tonumber(timerText) < 10 then
audioPlayed = true
StopSound(23639)
end
MonDKP.BidTimer:SetStatusBarColor(0.8, 0.1, 0, alpha)
if alpha > 0 then
alpha = alpha - 0.005
elseif alpha <= 0 then
alpha = 1
end
else
MonDKP.BidTimer:SetStatusBarColor(0, 0.8, 0)
end
self:SetValue(timer)
if timer >= duration then
MonDKP.BidTimer:SetScript("OnUpdate", nil)
MonDKP.BidTimer:Hide();
end
end)
end
function MonDKP:StatusVerify_Update()
if (MonDKP.UIConfig and not MonDKP.UIConfig:IsShown()) or (#MonDKP_DKPHistory == 0 and #MonDKP_Loot == 0) then -- blocks update if dkp window is closed. Updated when window is opened anyway
return;
end
if IsInGuild() and core.Initialized then
core.OOD = false
local missing = {}
if MonDKP_Loot.seed and MonDKP_DKPHistory.seed and strfind(MonDKP_Loot.seed, "-") and strfind(MonDKP_DKPHistory.seed, "-") then
local search_dkp = MonDKP:Table_Search(MonDKP_DKPHistory, MonDKP_DKPHistory.seed, "index")
local search_loot = MonDKP:Table_Search(MonDKP_Loot, MonDKP_Loot.seed, "index")
if not search_dkp then
core.OOD = true
local officer1, date1 = strsplit("-", MonDKP_DKPHistory.seed)
if (date1 and tonumber(date1) < (time() - 1209600)) or not MonDKP:ValidateSender(officer1) then -- does not consider if claimed entry was made more than two weeks ago or name is not an officer
core.OOD = false
else
date1 = date("%m/%d/%y %H:%M:%S", tonumber(date1))
missing[officer1] = date1 -- if both missing seeds identify the same officer, it'll only list once
end
end
if not search_loot then
core.OOD = true
local officer2, date2 = strsplit("-", MonDKP_Loot.seed)
if (date2 and tonumber(date2) < (time() - 1209600)) or not MonDKP:ValidateSender(officer2) then -- does not consider if claimed entry was made more than two weeks ago or name is not an officer
core.OOD = false
else
date2 = date("%m/%d/%y %H:%M:%S", tonumber(date2))
missing[officer2] = date2
end
end
end
if not core.OOD then
MonDKP.DKPTable.SeedVerifyIcon:SetTexture("Interface\\AddOns\\MonolithDKP\\Media\\Textures\\up-to-date")
MonDKP.DKPTable.SeedVerify:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
GameTooltip:SetText(L["DKPSTATUS"], 0.25, 0.75, 0.90, 1, true);
GameTooltip:AddLine(L["ALLTABLES"].." |cff00ff00"..L["UPTODATE"].."|r.", 1.0, 1.0, 1.0, false);
if core.IsOfficer then
GameTooltip:AddLine(" ")
GameTooltip:AddLine("|cffff0000"..L["CLICKQUERYGUILD"].."|r", 1.0, 1.0, 1.0, true);
end
GameTooltip:Show()
end)
MonDKP.DKPTable.SeedVerify:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
return true;
else
MonDKP.DKPTable.SeedVerifyIcon:SetTexture("Interface\\AddOns\\MonolithDKP\\Media\\Textures\\out-of-date")
MonDKP.DKPTable.SeedVerify:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
GameTooltip:SetText(L["DKPSTATUS"], 0.25, 0.75, 0.90, 1, true);
if #MonDKP_Loot == 0 and #MonDKP_DKPHistory == 0 then
GameTooltip:AddLine(L["TABLESAREEMPTY"], 1.0, 1.0, 1.0, false);
else
GameTooltip:AddLine(L["ONETABLEOOD"].." |cffff0000"..L["OUTOFDATE"].."|r.", 1.0, 1.0, 1.0, false);
end
GameTooltip:AddLine(" ")
GameTooltip:AddLine(L["MISSINGENT"]..":", 0.25, 0.75, 0.90, 1, true);
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(L["PLAYER"], L["CREATED"],1,1,1,1,1,1)
for k,v in pairs(missing) do
local classSearch = MonDKP:Table_Search(MonDKP_DKPTable, k)
if classSearch then
c = MonDKP:GetCColors(MonDKP_DKPTable[classSearch[1][1]].class)
else
c = { hex="ffffff" }
end
GameTooltip:AddDoubleLine("|cff"..c.hex..k.."|r",v,1,1,1,1,1,1);
end
if core.IsOfficer then
GameTooltip:AddLine(" ")
GameTooltip:AddLine("|cffff0000"..L["CLICKQUERYGUILD"].."|r", 1.0, 1.0, 1.0, true);
end
GameTooltip:Show()
end)
MonDKP.DKPTable.SeedVerify:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
return false;
end
elseif core.Initialized then
MonDKP.DKPTable.SeedVerify:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT", 0, 0);
GameTooltip:SetText(L["DKPSTATUS"], 0.25, 0.75, 0.90, 1, true);
GameTooltip:AddLine(L["CURRNOTINGUILD"], 1.0, 1.0, 1.0, true);
GameTooltip:Show()
end)
MonDKP.DKPTable.SeedVerify:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
return false;
end
end
-------------------------------------
-- Recursively searches tar (table) for val (string) as far as 4 nests deep (use field only if you wish to search a specific key IE: MonDKP_DKPTable, "Roeshambo", "player" would only search for Roeshambo in the player key)
-- returns an indexed array of the keys to get to searched value
-- First key is the result (ie if it's found 8 times, it will return 8 tables containing results).
-- Second key holds the path to the value searched. So to get to a player searched on DKPTable that returned 1 result, MonDKP_DKPTable[search[1][1]][search[1][2]] would point at the "player" field
-- if the result is 1 level deeper, it would be MonDKP_DKPTable[search[1][1]][search[1][2]][search[1][3]]. MonDKP_DKPTable[search[2][1]][search[2][2]][search[2][3]] would locate the second return, if there is one.
-- use to search for players in SavedVariables. Only two possible returns is the table or false.
-------------------------------------
function MonDKP:Table_Search(tar, val, field)
local value = string.upper(tostring(val));
local location = {}
for k,v in pairs(tar) do
if(type(v) == "table") then
local temp1 = k
for k,v in pairs(v) do
if(type(v) == "table") then
local temp2 = k;
for k,v in pairs(v) do
if(type(v) == "table") then
local temp3 = k
for k,v in pairs(v) do
if string.upper(tostring(v)) == value then
if field then
if k == field then
tinsert(location, {temp1, temp2, temp3, k} )
end
else
tinsert(location, {temp1, temp2, temp3, k} )
end
end;
end
end
if string.upper(tostring(v)) == value then
if field then
if k == field then
tinsert(location, {temp1, temp2, k} )
end
else
tinsert(location, {temp1, temp2, k} )
end
end;
end
end
if string.upper(tostring(v)) == value then
if field then
if k == field then
tinsert(location, {temp1, k} )
end
else
tinsert(location, {temp1, k} )
end
end;
end
end
if string.upper(tostring(v)) == value then
if field then
if k == field then
tinsert(location, k)
end
else
tinsert(location, k)
end
end;
end
if (#location > 0) then
return location;
else
return false;
end
end
function MonDKP:TableStrFind(tar, val, field) -- same function as above, but searches values that contain the searched string rather than exact string matches
local value = string.upper(tostring(val)); -- ex. MonDKP:TableStrFind(MonDKP_DKPHistory, "Roeshambo") will return the path to any table element that contains "Roeshambo"
local location = {}
for k,v in pairs(tar) do
if(type(v) == "table") then
local temp1 = k
for k,v in pairs(v) do
if(type(v) == "table") then
local temp2 = k;
for k,v in pairs(v) do
if(type(v) == "table") then
local temp3 = k
for k,v in pairs(v) do
if (field ~= "players" and field ~= "player" and strfind(string.upper(tostring(v)), value)) or ((field == "players" or field == "player") and (strfind(string.upper(tostring(v)), ","..value..",") or strfind(string.upper(tostring(v)), value..",") == 1)) then
if field then
if k == field then
tinsert(location, {temp1, temp2, temp3, k} )
end
else
tinsert(location, {temp1, temp2, temp3, k} )
end
end;
end
end
if (field ~= "players" and field ~= "player" and strfind(string.upper(tostring(v)), value)) or ((field == "players" or field == "player") and (strfind(string.upper(tostring(v)), ","..value..",") or strfind(string.upper(tostring(v)), value..",") == 1)) then
if field then
if k == field then
tinsert(location, {temp1, temp2, k} )
end
else
tinsert(location, {temp1, temp2, k} )
end
end;
end
end
if (field ~= "players" and field ~= "player" and strfind(string.upper(tostring(v)), value)) or ((field == "players" or field == "player") and (strfind(string.upper(tostring(v)), ","..value..",") or strfind(string.upper(tostring(v)), value..",") == 1)) then
if field then
if k == field then
tinsert(location, {temp1, k} )
end
else
tinsert(location, {temp1, k} )
end
end;
end
end
if (field ~= "players" and field ~= "player" and strfind(string.upper(tostring(v)), value)) or ((field == "players" or field == "player") and (strfind(string.upper(tostring(v)), ","..value..",") or strfind(string.upper(tostring(v)), value..",") == 1)) then
if field then
if k == field then
tinsert(location, k)
end
else
tinsert(location, k)
end
end;
end
if (#location > 0) then
return location;
else
return false;
end
end
function MonDKP:DKPTable_Set(tar, field, value, loot) -- updates field with value where tar is found (IE: MonDKP:DKPTable_Set("Roeshambo", "dkp", 10) adds 10 dkp to user Roeshambo). loot = true/false if it's to alter lifetime_spent
local result = MonDKP:Table_Search(MonDKP_DKPTable, tar);
for i=1, #result do
local current = MonDKP_DKPTable[result[i][1]][field];
if(field == "dkp") then
MonDKP_DKPTable[result[i][1]][field] = MonDKP_round(tonumber(current + value), MonDKP_DB.modes.rounding)
if value > 0 and loot == false then
MonDKP_DKPTable[result[i][1]]["lifetime_gained"] = MonDKP_round(tonumber(MonDKP_DKPTable[result[i][1]]["lifetime_gained"] + value), MonDKP_DB.modes.rounding)
elseif value < 0 and loot == true then
MonDKP_DKPTable[result[i][1]]["lifetime_spent"] = MonDKP_round(tonumber(MonDKP_DKPTable[result[i][1]]["lifetime_spent"] + value), MonDKP_DB.modes.rounding)
end
else
MonDKP_DKPTable[result[i][1]][field] = value
end
end
DKPTable_Update()
end
|
return {
summary = 'Encode the TextureData as png.',
description = 'Encodes the TextureData to a png.',
arguments = {},
returns = {
{
name = 'blob',
type = 'Blob',
description = 'A new Blob containing the PNG image data.'
}
},
related = {
'lovr.filesystem.write'
}
}
|
local internet = require("internet")
-- ##############################
-- TCP
-- ##############################
local function on_tcp_connection(connection, s)
print("tcp connection connected")
local hello_timer = tmr.create()
hello_timer:alarm(1000, tmr.ALARM_AUTO, function ()
connection:send("testing = chip\n")
end)
end
local function on_tcp_disconnection(connection, error_code)
print("tcp connection disconnected or failed to connect, reason: " .. error_code)
end
local skip_headers
local chunk
local buffering
local buf
local function on_tcp_receive(connection, data)
print("data recieved " .. data)
if skip_headers then
-- simple logic to filter the HTTP headers
chunk = chunk..data
local i, j = string.find(chunk, '\r\n\r\n')
if i then
skip_headers = false
data = string.sub(chunk, j+1, -1)
chunk = nil
end
end
if not skip_headers then
buf[#buf+1] = data
if #buf > 5 then
-- throttle server to avoid buffer overrun
connection:hold()
if buffering then
buffering = false
print(chunk)
end
end
end
end
-- ##############################
-- TCP END
-- ##############################
-- ##############################
-- Internet
-- ##############################
local tcp_client = nil
local function on_internet_connected(data)
print("station connected, getting ip address: " .. data.SSID)
end
local function on_internet_got_ip()
print("station ip address gathered: " .. internet.get_station_ip())
print("station mac address: " .. internet.get_station_mac())
print("station status: " .. internet.get_station_status())
tcp_client = net.createConnection(net.TCP, 0)
tcp_client:on("connection", on_tcp_connection)
tcp_client:on("disconnection", on_tcp_disconnection)
tcp_client:on("receive", on_tcp_receive)
print("attempting tcp connection to: 192.168.1.65:80")
tcp_client:connect(80, "192.168.1.65")
end
local function on_internet_disconnected(callback)
print("internet disconnected, reason: " .. callback.reason)
end
-- ##############################
-- Internet END
-- ##############################
local function main()
internet.configure_station("The Promise Lan", "DangerZone2018", nil)
internet.connect_station(on_internet_connected, on_internet_got_ip, on_internet_disconnected)
end
main()
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local MAX_SCROLL_SPEED_MODIFIER = 5
local MIN_SCROLL_SPEED_MODIFIER = 1
local CreditsScreen_Gamepad = CreditsScreen_Base:Subclass()
function CreditsScreen_Gamepad:New(...)
return CreditsScreen_Base.New(self, ...)
end
function CreditsScreen_Gamepad:Initialize(control)
CreditsScreen_Base.Initialize(self, control)
self.creditDescriptor =
{
{
name = GetString(SI_CANCEL),
keybind = "UI_SHORTCUT_NEGATIVE",
callback = function()
self:Exit()
end,
},
{
--Ethereal binds show no text, the name field is used to help identify the keybind when debugging. This text does not have to be localized.
name = "Gamepad Game Credits Faster",
keybind = "UI_SHORTCUT_RIGHT_TRIGGER",
ethereal = true,
callback = function()
local speedMultiplier = self:GetScrollSpeedMultiplier()
if speedMultiplier < MAX_SCROLL_SPEED_MODIFIER then
self:SetScrollSpeedMultiplier(speedMultiplier + 1)
end
end,
},
{
--Ethereal binds show no text, the name field is used to help identify the keybind when debugging. This text does not have to be localized.
name = "Gamepad Game Credits Slower",
keybind = "UI_SHORTCUT_LEFT_TRIGGER",
ethereal = true,
callback = function()
local speedMultiplier = self:GetScrollSpeedMultiplier()
if speedMultiplier > MIN_SCROLL_SPEED_MODIFIER then
self:SetScrollSpeedMultiplier(speedMultiplier - 1)
end
end,
},
}
GAME_CREDITS_GAMEPAD_FRAGMENT = ZO_FadeSceneFragment:New(control)
GAME_CREDITS_GAMEPAD_FRAGMENT:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
self.keybindState = KEYBIND_STRIP:PushKeybindGroupState()
KEYBIND_STRIP:RemoveDefaultExit(self.keybindState)
KEYBIND_STRIP:AddKeybindButtonGroup(self.creditDescriptor, self.keybindState)
ShowCredits()
elseif newState == SCENE_FRAGMENT_HIDDEN then
self:StopCredits()
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.creditDescriptor, self.keybindState)
KEYBIND_STRIP:RestoreDefaultExit(self.keybindState)
KEYBIND_STRIP:PopKeybindGroupState()
end
end)
-- NOTE: Templates must be unique due to how the object pools name controls as they're created.
self:AddPool(GAME_CREDITS_ENTRY_TYPE_DEPARTMENT_HEADER, "ZO_GameCreditsDepartmentGamepad", function(textControl, text) return self:SetupTextControl(textControl, text) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_SECTION_HEADER, "ZO_GameCreditsSectionGamepad", function(textControl, text) return self:SetupTextControl(textControl, text) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_SECTION_TEXT, "ZO_GameCreditsNamesGamepad", function(textControl, text) return self:SetupTextControl(textControl, text) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_SECTION_TEXT_BLOCK, "ZO_GameCreditsTextBlockGamepad", function(textControl, text) return self:SetupTextControl(textControl, text) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_COMPANY_LOGO, "ZO_GameCreditsLogoGamepad", function(logoControl, texture, height) return self:SetupLogoControl(logoControl, texture, height) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_BACKGROUND_SWITCH, "ZO_GameCreditsBGSwitchGamepad", function(backgroundControl, texture) return self:SetupBackgroundSwitch(backgroundControl, texture) end)
self:AddPool(GAME_CREDITS_ENTRY_TYPE_PADDING_SECTION, "ZO_GameCreditsPaddingGamepad", function(paddingControl, unused, height) return self:SetupPaddingSection(paddingControl, unused, height) end)
EVENT_MANAGER:RegisterForEvent("GameCreditsGamepad", EVENT_GAME_CREDITS_READY, function() self:BeginCredits() end)
end
function CreditsScreen_Gamepad:Exit()
SCENE_MANAGER:HideCurrentScene()
end
function CreditsScreen_Gamepad:IsPreferredScreen()
return IsInGamepadPreferredMode()
end
function ZO_GameCredits_Gamepad_Initialize(control)
GAME_CREDITS_GAMEPAD = CreditsScreen_Gamepad:New(control)
end
|
-- 删除一个延迟任务
local jobs_key_ht = KEYS[1];
local bucket_key_zset = KEYS[2];
local topic_id = ARGV[1];
redis.call('HDEL',jobs_key_ht,topic_id) ;
redis.call('ZREM',bucket_key_zset,topic_id) ;
|
require("prototypes.engineering.add_effects_script")
require("prototypes.turrets.data")
|
--[[----------------------------------------------------------------------------
Info.lua
metaExportFilter Sample
Summary information for Metadata Export Filter plugin sample plugin
--------------------------------------------------------------------------------
ADOBE SYSTEMS INCORPORATED
Copyright 2008 Adobe Systems Incorporated
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
with the terms of the Adobe license agreement accompanying it. If you have received
this file from a source other than Adobe, then your use, modification, or distribution
of it requires the prior written permission of Adobe.
------------------------------------------------------------------------------]]
return {
LrSdkVersion = 3.0,
LrSdkMinimumVersion = 1.3, -- minimum SDK version required by this plugin
LrPluginName = LOC "$$$/SDK/MetaExportFilter/Sample=Metadata Post Process Sample",
LrToolkitIdentifier = 'com.adobe.lightroom.sdk.export.metaexportfilter',
LrExportFilterProvider = {
title = LOC "$$$/SDK/MetaExportFilter/Sample=Metadata Post Process", -- the string that appears in the export filter section of the export dialog in LR
file = 'MetadataExportFilterProvider.lua', -- name of the file containing the filter definition script
id = "metadata", -- unique identifier for export filter
},
VERSION = { major=8, minor=0, revision=0, build=1193777, },
}
|
---------------------------------------------------------------------------------
-- Simple cursor script by Infinite Rain, based on a sample by Unreal Software --
---------------------------------------------------------------------------------
if not CSample then
require("sys/lua/CS2D-AmplifiedScripting")
CSample = {}
end
CSample.cursor = {
updateRate = 150,
player = {}
}
--------------------------------------
-- Timer which requests client data --
--------------------------------------
CSample.cursor.timer = cas.timer.new(function()
for _, player in pairs(cas.player.getPlayers()) do
player:requestClientData("cursoronmap")
end
end):startConstantly(CSample.cursor.updateRate)
-----------------------------------------------------
-- Table which holds functions, later to be hooked --
-----------------------------------------------------
CSample.cursor.hook = {
-- On join, creating a data table for this player.
join = function(player)
CSample.cursor.player[player] = {
cursor = cas.mapImage.new("gfx/sprites/flare2.bmp", "supertop")
:setColor(cas.color.yellow)
:setBlend("light")
:setAlpha(0.5)
:setScale(0.3, 0.3)
}
end,
-- On leave, removing the data table of this player.
leave = function(player)
CSample.cursor.player[player] = nil
end,
-- On startround, since all the images are removed, re-drawing them.
startround = function(mode)
for key, value in pairs(cas.player.getPlayers()) do
CSample.cursor.player[value].cursor = cas.mapImage.new("gfx/sprites/flare2.bmp", "supertop")
:setColor(cas.color.yellow)
:setBlend("light")
:setAlpha(0.5)
:setScale(0.3, 0.3)
end
end,
clientdata = function(player, mode, data1, data2)
if mode == "cursoronmap" then
if not player:isBot() then
if CSample.cursor.player[player].cursor:isTweenMove() then
CSample.cursor.player[player].cursor:stopTweenMove()
end
CSample.cursor.player[player].cursor:tweenMove(CSample.cursor.updateRate, data1, data2)
end
end
end
}
------------------------------------
-- Hooking the declared functions --
------------------------------------
CSample.cursor.hook.joinHook = cas.hook.new("join", CSample.cursor.hook.join)
CSample.cursor.hook.leaveHook = cas.hook.new("leave", CSample.cursor.hook.leave)
CSample.cursor.hook.startroundHook = cas.hook.new("startround", CSample.cursor.hook.startround)
CSample.cursor.hook.clientdataHook = cas.hook.new("clientdata", CSample.cursor.hook.clientdata)
|
--[[
args={
text={
{content="hello",color={r=255,g=222,b=123}},
{content="wahahhasd",color={r=255,g=222,b=0}},
{content="c喔喔",color={r=255,g=2,b=1}}
},
font='Microsoft YaHei',
size=23
}
]]
local tools = require('app.helpers.tools')
local BIAS = 30
local CONTENT_FORMAT = "[color=%X]%s[/color]"
local RollWidget = class("RollWidget", function()
return display.newNode()
end)
function RollWidget:ctor()
-- data
self.messageList = {}
self.curMsgIndex = 1
self.start = false
self.totalWidth = 0
self.rollSize = nil
self.layer = display.newNode()
self:addChild(self.layer)
self.myLbal = display.newNode():addTo(self.layer)
self:registerScriptHandler(function(event)
if "enter" == event then
tools.schedule(self, function() self:step() end, 0.01)
end
end)
-- 吞掉区域外的所有事件
-- local function onTouched(eventType, x, y)
-- if eventType == "began" then
-- local wpos = self:convertToWorldSpace(cc.p(0, 0))
-- print('wx_, wy_',wpos.x, wpos.y,x,y)
-- print(self.rollSize.width,self.rollSize.height)
-- if (x > wpos.x) and (x < wpos.x + self.rollSize.width) and
-- (y < wpos.y) and (y > wpos.y - self.rollSize.height) then
-- print("in")
-- return false
-- else
-- print('out')
-- end
-- elseif eventType == "moved" then
-- elseif eventType == "ended" then
-- end
-- return true
-- end
-- local touchLayer = cc.Layer:create()
-- self:addChild(touchLayer)
-- touchLayer:setTouchEnabled(true)
-- touchLayer:registerScriptTouchHandler(onTouched, false, 0, false)
end
function RollWidget:step()
if self.start then
local x = self.myLbal:getPositionX() - 1
if x <= -self.totalWidth - BIAS then
self:showNextMessage()
else
self.myLbal:setPositionX(x)
end
end
end
function RollWidget:showNextMessage()
self.myLbal:removeAllChildren()
self.curMsgIndex = self.curMsgIndex + 1
if self.curMsgIndex > #self.messageList then
self.curMsgIndex = 1
end
local msg = self.messageList[self.curMsgIndex]
if msg == nil then
print("msg == nil")
return
end
-- 创建label
local label_ = require('app.widgets.nRichLabel').new(msg, true, self.callBack)
self.myLbal:addChild(label_)
label_:setAnchorPoint(cc.p(0,0.5))
self.myLbal:setPosition(self.rollSize.width + BIAS, 0)
self.totalWidth = label_.size.width
self.start = true
end
-- 设置滚动区域
function RollWidget:setRollSize(size)
self.rollSize = size
end
-- 添加消息
function RollWidget:setMsg(messages)
self.curMsgIndex = 0
self.messageList = messages
self:beginRoll()
end
-- 开始滚动
function RollWidget:beginRoll()
-- self:stopAllActions()
self:showNextMessage()
end
-- 开始滚动
function RollWidget:registerClickCallBack(callBack_)
self.callBack = callBack_
end
return RollWidget
|
local wk = require("which-key")
wk.register({
m = {
name = "plugins",
s = { "<cmd>PackerSync<cr>", "packer-sync" },
c = { "<cmd>PackerCompile<cr>", "packer-compile" },
i = { "<cmd>PackerInstall<cr>", "packer-install" },
u = { "<cmd>PackerUpdate<cr>", "packer-update" },
},
}, { prefix = "<leader>" })
|
local function test1()
collectgarbage("collect") -- 先清理一次
-- "count": 以 K 字节数为单位返回 Lua 使用的总内存数。 这个值有小数部分,所以只需要乘上 1024 就能得到 Lua 使用的准确字节数(除非溢出)。
local c1 = collectgarbage("count")
print("t1 memory:", c1)
-- collen 插入 50000个对象
local collen = {} -- 将local去掉, 会导致内存泄漏
for i = 1, 50000 do
table.insert(collen, {})
end
local c2 = collectgarbage("count")
print("t2 memory:", c2)
end
local function mem()
local c1 = collectgarbage("count")
print("gc before:", c1)
print("gc...")
collectgarbage("collect")
local c2 = collectgarbage("count")
print("gc after:", c2)
end
local function main()
test1()
mem()
end
main()
|
local function curl(payload)
local cmd = {
'curl',
'--header', 'Content-Type: application/json',
'--header', 'X-API-Token: ' .. CODESTATS_API_KEY,
'--user-agent', 'codestats.nvim/' .. CODESTATS_VERSION,
'--data', payload,
'--request', 'POST',
'--silent',
'--output', '/dev/null',
'--write-out', '%{http_code}',
CODESTATS_API_URL .. '/my/pulses'
}
return vim.fn.system(cmd)
end
return curl
|
tree_bark = {
-- Exactly same spell as Chongun Invincibility (harden body) but this one has longer duration but long aethers. Also has a higher fail rate (just keeping the same for now).
cast = function(player)
local duration = 12000
-- 12s duration
local aether = 300000
-- 300s aethers
local magicCost = 1500
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magicCost) then
player:sendMinitext("Your will is too weak.")
return
end
if player:checkIfCast(hardBodies) then
player:sendMinitext("You already cast that spell.")
return
end
local armor = 0
if player.armor < -80 then
armor = -80
elseif player.armor > 70 then
armor = 70
else
armor = player.armor
end
player:sendAction(6, 20)
player.magic = player.magic - magicCost
player:sendStatus()
local successRate = (140 + armor) / 2
local random = math.random(1, 100)
if random < successRate then
player:sendMinitext("Something went wrong.")
return
end
player:playSound(5)
player:sendMinitext("Harden body spell")
player:sendMinitext("You cast Tree bark.")
player:setDuration("tree_bark", duration)
player:setAether("tree_bark", aether)
player:sendAnimation(11, 3)
end,
uncast = function(player)
player:sendMinitext("Your skin turns back to flesh.")
end,
requirements = function(player)
local level = 99
local items = {"moon_helm", "tigers_heart", "charm"}
local itemAmounts = {1, 20, 1}
local desc = "Makes you invincible briefly."
return level, items, itemAmounts, desc
end
}
|
--
-- SOFTCUT
--
-- -------------------------------------------------------------------------
-- STATE
local state = {
recording = false,
rec_time = 0,
}
function sofcut_get_record_duration()
return state.rec_time
end
-- -------------------------------------------------------------------------
-- INIT / CLEANUP
--- Softcut init phase
function softcut_init()
softcut.reset()
audio.level_cut(1.0)
audio.level_adc_cut(1.0) -- listen analog input
audio.level_eng_cut(0.0) -- don't listen engine / sc
for i=1, 2 do
softcut.level(i, 1.0)
softcut.level_slew_time(i, 0.1)
softcut.play(i, 0)
softcut.rate(i, 1)
softcut.rate_slew_time(i, 0.1)
softcut.loop_start(i, 0)
softcut.loop_end(i, 350)
softcut.loop(i, 1)
softcut.fade_time(i, 0.1)
softcut.rec(i, 0)
softcut.rec_level(i, 1)
softcut.pre_level(i, 1)
softcut.position(i, 0)
softcut.buffer(i, i)
softcut.enable(i, 1)
softcut.filter_dry(i, 1)
softcut.phase_quant(i, .01)
end
softcut.level_input_cut(1, 1, 1.0)
softcut.level_input_cut(2, 1, 0.0)
softcut.level_input_cut(1, 2, 0.0)
softcut.level_input_cut(2, 2, 1.0)
softcut.pan(1, -1.0)
softcut.pan(2, 1.0)
softcut.event_phase(softcut_event_phase)
softcut.poll_start_phase()
end
--- Softcut event phase
-- @param voice current softcut voice
-- @param x time since record / playback
softcut_event_phase = function(voice, x)
if state.recording then state.rec_time = x end
end
-- -------------------------------------------------------------------------
-- RECORD
--- Predicate, is curently recorded
function softcut_is_recording()
return state.recording
end
--- Predicate, has something recorded
function softcut_has_recording()
return state.rec_time ~= 0
end
--- Toggle Softcut record start / stop
function softcut_toggle_record()
state.recording = not state.recording
if state.recording then
print("record on")
softcut_record_on()
else
print("record off")
softcut_record_off()
cut_to_engine()
end
end
--- Start Softcut record in buffer
function softcut_record_on()
timber_free_up_sample()
softcut_clear_buffers()
for i=1, 2 do
softcut.rec(i, 1)
end
end
--- Stop Softcut record in buffer
function softcut_record_off()
for i=1, 2 do
softcut.rec(i, 0)
softcut.position(i, 0)
end
end
--- Clear Softcut buffers
function softcut_clear_buffers()
for i=1, 2 do
softcut.buffer_clear(i)
softcut.position(i, 0)
state.rec_time = 0
end
end
-- -------------------------------------------------------------------------
-- PLAYBACK
--- Play Softcut voices (mapped to buffers)
-- unused
function softcut_play()
for i=1, 2 do
softcut.position(i, 0)
softcut.play(i, 1)
end
end
--- Stop playing Softcut voices (mapped to buffers)
-- unused
function softcut_stop()
for i=1, 2 do
softcut.position(i, 0)
softcut.play(i, 0)
end
end
-- -------------------------------------------------------------------------
-- PLAYBACK OPTIONS
--- Update current Softcut buffer playback speed
-- unused
sofcut_update_current_playback_rate = function()
local n = rpmate.current_playback_ratio()
for i=1, 2 do
softcut.rate(0, n)
end
end
-- -------------------------------------------------------------------------
-- SAVE TO DISK
function sofcut_write_to_file(filepath)
softcut.buffer_write_stereo(filepath, 0, state.rec_time)
-- softcut.buffer_write_stereo(filepath, 0, -1)
end
|
module(..., package.seeall)
local ffi = require("ffi")
require "terravox.api" -- This loads FFI definition
api = ffi.cast("struct TerravoxApi*", __terravoxApi)
|
local Game = require("Game")
function love.load()
love.window.setTitle("Platform Hero")
love.window.setMode(800, 600, {
fullscreentype = "desktop",
resizable = true,
highdpi = true,
})
love.physics.setMeter(1)
love.graphics.setDefaultFilter("nearest")
local music =
love.audio.newSource("resources/music/platformHero.ogg", "stream")
music:setLooping(true)
music:play()
game = Game.new({})
end
function love.update(...)
game:update(...)
if game.complete then
game = Game.new({
level = game.level + 1,
})
end
end
function love.draw(...)
game:draw(...)
end
function love.resize(...)
game:resize(...)
end
function love.keypressed(key, scancode, isrepeat)
if key == "f1" then
love.graphics.captureScreenshot("screenshot.png")
end
end
|
module 'mock'
local insert = table.insert
local index = table.index
local remove = table.remove
CLASS: DeckCanvas ( GraphicsPropComponent )
:MODEL{
Field 'index' :no_edit();
--'----';
--Field 'size' :type('vec2') :getset('Size');
Field 'serializedData' :getset( 'SerializedData' ) :no_edit();
'----';
Field 'edit' :action('editPen') :meta{ icon='edit', style='tool'};
Field 'clear' :action('editClear') :meta{ icon='clear' };
}
registerComponent( 'DeckCanvas', DeckCanvas )
--mock.registerEntityWithComponent( 'DeckCanvas', DeckCanvas )
function DeckCanvas:__init()
self.props = {}
--self.size = { 500, 500 }
self:getMoaiProp().inside = function()
return self:inside( x,y,z, pad )
end
end
function DeckCanvas:inside( x,y,z, pad )
for i, prop in ipairs( self.props ) do
if prop:inside( x,y,z, pad ) then return true end
end
return false
end
-- function DeckCanvas:setSize( w, h )
-- self.size = { w, h }
-- self:getMoaiProp():setBounds( -w/2, -h/2, 0, w/2, h/2, 0 )
-- end
-- function DeckCanvas:getSize()
-- return unpack( self.size )
-- end
function DeckCanvas:getSerializedData()
local deckset = {}
local decklist = {}
local id0 = 0
local function affirmDeckId( path )
local id = deckset[ path ]
if not id then
id0 = id0 + 1
id = id0
deckset[ path ] = id
decklist[ id ] = path
end
return id
end
local propDatas = {}
for i, prop in ipairs( self.props ) do
local deckPath = prop.deckPath
if deckPath then
-- assert( deckPath, tostring(prop) )
-- if deckPath then
local deckId = affirmDeckId( deckPath )
local x, y, z = prop:getLoc()
local rx, ry, rz = prop:getRot()
local sx, sy, sz = prop:getScl()
local r,g,b,a = prop:getColor()
table.insert( propDatas, {
deck = deckId,
transform = { x,y,z, rx,ry,rz, sx,sy,sz },
color = { r,g,b,a },
})
end
end
local output = {
props = propDatas,
decks = decklist
}
return output
end
function DeckCanvas:setSerializedData( data )
if not data then return end
local decks = data.decks
for i, propData in ipairs( data.props ) do
local deckId = propData.deck
local x,y,z, rx,ry,rz, sx,sy,sz = unpack( propData.transform )
local r,g,b,a = unpack( propData.color )
local deckPath = decks[ deckId ]
local prop = self:createProp( deckPath )
prop:setLoc( x,y,z )
prop:setRot( rx,ry,rz )
prop:setScl( sx,sy,sz )
prop:setColor( r,g,b,a )
self:_addProp( prop )
end
end
function DeckCanvas:createProp( deckPath )
local deck = loadAsset( deckPath )
if deck then
local prop = MOAIProp.new()
prop:setDeck( deck:getMoaiDeck() )
prop.deckPath = deckPath
return prop
end
end
function DeckCanvas:clear()
for i, prop in ipairs( self.props ) do
self:_removeProp( prop, false )
end
self.props = {}
end
--x,y = local coords
local defaultSortMode = MOAILayer.SORT_Z_ASCENDING
function DeckCanvas:findProps( x, y, radius )
local radius = radius or 1
local ent = self:getEntity()
local x, y, z = ent:getProp( 'render' ):modelToWorld( x, y )
--TODO: use some spatial graph
local partition = ent:getPartition()
local propsInPartition = {
-- partition:propListForRay( x, y, -1000000, 0, 0, 1, defaultSortMode )
partition:propListForBox( x-radius, y-radius, -100000, x+radius, y+radius, 100000, defaultSortMode )
}
local result = {}
for i, prop in ipairs( propsInPartition ) do
if prop.__deckCanvas == self then
insert( result, prop )
end
end
return result
end
function DeckCanvas:findTopProp( x, y )
local props = self:findProps( x, y )
local count = #props
if count > 0 then
return props[ count ]
else
return nil
end
end
function DeckCanvas:removeProps( x, y )
local found = self:findProps( x, y )
for i, prop in ipairs( found ) do
self:_removeProp( prop )
end
end
function DeckCanvas:removeTopProp( x, y )
local found = self:findTopProp( x, y )
if found then
self:_removeProp( found )
end
end
function DeckCanvas:addProp( deckPath )
local prop = self:createProp( deckPath )
if prop then
return self:_addProp( prop )
end
end
local linkPartition = linkPartition
local linkIndex = linkIndex
local linkBlendMode = linkBlendMode
local inheritTransformColorVisible = inheritTransformColorVisible
local linkShader = linkShader
function DeckCanvas:_addProp( prop )
local material = self:getMaterialObject()
local prop0 = self:getMoaiProp()
insert( self.props, prop )
linkPartition( prop, prop0 )
linkIndex( prop, prop0 )
linkBlendMode( prop, prop0 )
inheritTransformColorVisible( prop, prop0 )
linkShader( prop, prop0 )
material:applyToMoaiProp( prop )
prop:forceUpdate()
prop.__deckCanvas = self
return prop
end
function DeckCanvas:_addBoundsProps()
end
local clearLinkPartition = clearLinkPartition
local clearLinkIndex = clearLinkIndex
local clearInheritTransform = clearInheritTransform
local clearInheritColor = clearInheritColor
local clearLinkShader = clearLinkShader
local clearLinkBlendMode = clearLinkBlendMode
function DeckCanvas:_removeProp( prop, removeFromTable )
clearLinkPartition( prop )
clearLinkIndex( prop )
clearInheritTransform( prop )
clearInheritColor( prop )
clearLinkShader( prop )
clearLinkBlendMode( prop )
prop:setPartition( nil )
prop:forceUpdate()
if removeFromTable ~= false then
local props = self.props
local idx = index( props, prop )
if idx then
return remove( props, idx )
end
end
end
function DeckCanvas:applyMaterial( mat )
mat:applyToMoaiProp( self.prop )
for i, prop in ipairs( self.props ) do
mat:applyToMoaiProp( prop )
end
end
-- function DeckCanvas:insideCanvas( x, y, z, pads )
-- x, y = self.prop:worldToModel( x, y, z )
-- local w, h = self:getSize()
-- return x > -w/2 and h > -h/2 and x < w/2 and y < h/2
-- end
--------------------------------------------------------------------
--Editor support
function DeckCanvas:onBuildSelectedGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
return giz
end
local deckCanvasItemBoundsVisible = true
function setDeckCanvasItemBoundsVisible( vis )
deckCanvasItemBoundsVisible = vis
end
function isDeckCanvasItemBoundsVisible()
return deckCanvasItemBoundsVisible
end
local drawRect = MOAIDraw.drawRect
function DeckCanvas:drawBounds()
if not self._entity then return end
if deckCanvasItemBoundsVisible then
mock_edit.applyColor( 'deckcanvas-item' )
for i, prop in ipairs( self.props ) do
local x,y,z,x1,y1,z1 = prop:getWorldBounds()
drawRect( x,y,x1,y1 )
end
end
-- GIIHelper.setVertexTransform( self._entity:getProp() )
-- local w, h = self:getSize()
-- mock_edit.applyColor( 'deckcanvas-bound' )
-- drawRect( -w/2, -h/2, w/2, h/2 )
end
function DeckCanvas:editPen()
mock_edit.startAdhocSceneTool( 'deckcanvas_pen', { target = self } )
end
function DeckCanvas:editClear()
self:clear()
mock_edit.getCurrentSceneView():updateCanvas()
markProtoInstanceOverrided( self, 'serializedData' )
end
|
--[[
--=====================================================================================================--
Script Name: Troll, for SAPP (PC & CE)
Description: A unique mod designed to troll your whole server (or specific players)
Features:
* Silent Kill Random inexplicable deaths (no death message).
* Damage Modifier Randomly change damage multipliers.
* Chat Text Randomizer Randomly jumbles up characters in some sentences.
* Teleport Under Map Randomly teleports a player under the map.
* Flag Dropper Randomly force a player to drop the flag.
* Vehicle Exit Randomly eject a player from their vehicle.
* Ammo Changer Randomly change weapon ammo, battery and grenade count.
* Silent Kick Randomly force a player to disconnect (no kick message output).
* Random Color Change Randomly change a player's colour when they spawn.
* Client Crasher Randomly crash a player's game client.
* Name Changer Randomly change newly joined player's name to a random pre-defined name.
* Inverted Controls Randomly invert player controls.
* Roasty Toasty Randomly burn a player.
* Fake Kill Messages Randomly show the player fake kill messages.
* Glitched Grenades Randomly glitch out grenades.
No grenade projectiles will be thrown but the throw animation will still play.
* Fake Join/Quit Messages Randomly show fake player join/quit messages to the target or
manually fake join/quit a player with a custom command.
* Force Chat Randomly force a player to say something from a list of pre-defined sentences
or manually force a player to say something with a custom command:
* SPECIAL COMMANDS (see settings table in config section):
Manually add a player to the troll list (bypassing "ignore_admins" settings and "specific_users" settings)
or manually prevent a player from being trolled by this script.
* ENABLE or DISABLE any feature at any time with two simple commands (see config section)
Credits to Kavawuvi and Devieth for functions at bottom of script.
Copyright (c) 2020, Jericho Crosby <jericho.crosby227@gmail.com>
* Notice: You can use this document subject to the following conditions:
https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE
--=====================================================================================================--
]]--
api_version = "1.12.0.0"
-- Configuration [STARTS] ------------------------------------------------------
local Troll = {
-------- [ S E T T I N G S ] ----------
-- Base command syntax: /troll <command> <params>
--===================================--
settings = {
base_command = "troll",
--------------------------------------------------------
-- Use these commands to ENABLE or DISABLE specific features:
-- Command Syntax: /base_command features
feature_list_command = "features",
-- Command Syntax: /base_command enable_command <feature id>
enable_command = "enable",
-- Command Syntax: /base_command disable_command <feature id>
disable_command = "disable",
-- Minimum permission level needed to execute any of the above three commands:
enable_disable_list_perm = 1,
--------------------------------------------------------
-- This command lets you manually add a player to the
-- troll list (bypassing "ignore_admins" settings and "specific_users" settings).
-- Command Syntax: /base_command add_troll_command <player id>
add_troll_command = "add",
add_troll_permission = 1,
--------------
-- This command will prevent a player from being trolled by this script.
-- Command Syntax: /base_command remove_troll_command <player id>
remove_troll_command = "remove",
remove_troll_permission = 1,
--------------
-- Several functions temporarily remove the server prefix when certain messages are broadcast.
-- The prefix will be restored to 'server_prefix' when the relay has finished.
-- Enter your server prefix here:
server_prefix = "**SAPP**",
--[[
If "specific_users_only" is true, then only players whose IP addresses
are in this list will be affected by this script.
If "specific_users_only" is false then all players will be affected,
excluding Admins under special circumstances (see below):
If a player is an admin, they will be affected unless
"ignore_admins" is "true" for each specific feature
and their level is >= "ignore_admin_level" level.
]]
specific_users_only = false,
specific_users = {
"127.0.0.1", -- Local Host
"108.5.107.145" -- DeathBringR
},
print_feature_state = false,
-- Do Not Touch this.
script_version = 1.5
},
-------- [ F E A T U R E S ] ----------
--===================================--
features = {
["Damage Modifier"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
multipliers = {
-- I wanted to give the end user the opportunity to change
-- the min/max damage multipliers on a per-damage-type basis,
-- as well as the chances of applied damage being effected by this script.
-- EXAMPLE 1:
-- Will generate random number between (1) and (10) units with a (3 in 6) chance of this happening.
-- The damage dealt will have a reduced number of units by the random number generated above.
-- { "weapons\\assault rifle\\melee", 8, 10, { 3, 6 } },
-- Additionally, the chance of a players damage multiplier being affected
-- is randomized every application of damage.
melee = {
{ "weapons\\assault rifle\\melee", 8, 10, { 1, 2 } },
{ "weapons\\ball\\melee", 8, 10, { 1, 2 } },
{ "weapons\\flag\\melee", 8, 10, { 1, 2 } },
{ "weapons\\flamethrower\\melee", 8, 10, { 1, 2 } },
{ "weapons\\needler\\melee", 8, 10, { 1, 3 } },
{ "weapons\\pistol\\melee", 8, 10, { 1, 2 } },
{ "weapons\\plasma pistol\\melee", 8, 10, { 1, 2 } },
{ "weapons\\plasma rifle\\melee", 8, 10, { 1, 4 } },
{ "weapons\\rocket launcher\\melee", 8, 10, { 1, 2 } },
{ "weapons\\shotgun\\melee", 8, 10, { 1, 3 } },
{ "weapons\\sniper rifle\\melee", 8, 10, { 1, 2 } },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", 8, 10, { 1, 2 } },
},
grenades = {
-- EXAMPLE 2:
-- There are separate damage multipliers for causers, and victims.
-- For example, you will lose a minimum of 7 and maximum of 10 units of damage dealt to your victims
-- with a 1 in 2 chance of this happening.
-- If you grenade yourself, you will receive 10x normal damage
{ "weapons\\frag grenade\\explosion", others = { 7, 10 }, you = { 10, 10 }, { 1, 2 } },
{ "weapons\\plasma grenade\\explosion", others = { 6, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\plasma grenade\\attached", others = { 8, 10 }, you = { 10, 10 }, { 1, 2 } },
},
vehicles = {
{ "vehicles\\ghost\\ghost bolt", 6, 10, { 1, 3 } },
{ "vehicles\\scorpion\\bullet", 5, 10, { 1, 6 } },
{ "vehicles\\warthog\\bullet", 7, 10, { 1, 5 } },
{ "vehicles\\c gun turret\\mp bolt", 7, 10, { 1, 6 } },
{ "vehicles\\banshee\\banshee bolt", 6, 10, { 1, 3 } },
{ "vehicles\\scorpion\\shell explosion", 8, 10, { 1, 2 } },
{ "vehicles\\banshee\\mp_fuel rod explosion", 8, 10, { 1, 2 } },
},
projectiles = {
{ "weapons\\pistol\\bullet", others = { 7, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\plasma rifle\\bolt", others = { 6, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\shotgun\\pellet", others = { 5, 10 }, you = { 10, 10 }, { 1, 4 } },
{ "weapons\\plasma pistol\\bolt", others = { 8, 10 }, you = { 10, 10 }, { 1, 6 } },
{ "weapons\\needler\\explosion", others = { 7, 10 }, you = { 10, 10 }, { 1, 4 } },
{ "weapons\\assault rifle\\bullet", others = { 6, 10 }, you = { 10, 10 }, { 1, 2 } },
{ "weapons\\needler\\impact damage", others = { 6, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\flamethrower\\explosion", others = { 7, 10 }, you = { 10, 10 }, { 1, 2 } },
{ "weapons\\sniper rifle\\sniper bullet", others = { 8, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\rocket launcher\\explosion", others = { 7, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\needler\\detonation damage", others = { 7, 10 }, you = { 10, 10 }, { 1, 2 } },
{ "weapons\\plasma rifle\\charged bolt", others = { 5, 10 }, you = { 10, 10 }, { 1, 3 } },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", others = { 8, 10 }, you = { 10, 10 }, { 1, 2 } },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_explosion", others = { 7, 10 }, you = { 10, 10 }, { 1, 2 } },
},
fall_damage = {
{ "globals\\falling", you = { 10, 10 }, chance = { 1, 3 } },
{ "globals\\distance", you = { 10, 10 }, chance = { 1, 3 } },
},
vehicle_collision = {
"globals\\vehicle_collision", others = { 7, 10 }, you = { 10, 10 }, { 1, 3 }
}
}
},
["Chat Text Randomizer"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
min_chances = 1, -- 1 in 6 chance of your messages being randomized every time you chat.
max_chances = 6,
format = {
--[[ Custom Variables:
%name% - will output the players name
%msg% - will output message
-- Add this if you're using my ChatID script! (or because reasons)
"%id% - will output the Player Index ID
--]]
global = "%name%: %msg%",
team = "[%name%]: %msg%",
vehicle = "[%name%]: %msg%"
}
},
["Silent Kill"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- When a player spawns, the interval until they are killed is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 35, -- in seconds
max = 300, -- in seconds
},
["Roasty Toasty"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
projectile = { "proj", "weapons\\flamethrower\\flame" },
-- Min/Max time until a player is burnt to a crisp.
min = 35, -- in seconds
max = 225, -- in seconds
},
["Fake Kill Messages"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
--[[
Only the player being trolled will see these messages:
Example:
Type 1: mrSands001 was killed by Chalwk
Type 2: You killed mrSands001
]]
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Min/Max time until a fake kill message appears.
min = 45, -- in seconds
max = 200, -- in seconds
messages = {
[1] = "You killed %fake_victim%",
[2] = "%troll_victim% was killed by %fake_victim%",
}
},
["Teleport Under Map"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Players will be teleported a random number of world units under the map.
-- The value of W/Units is a random number between minZ, maxZ
minZ = 0.3, -- in world units
maxZ = 0.4, -- in world units
-- Players will be teleported under the map at a random time between min/max seconds.
min = 60, -- in seconds
max = 280, -- in seconds
},
["Inverted Controls"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Min/Max Interval until players controls are inverted.
untilMin = 25, -- in seconds
untilMax = 180, -- in seconds
inverted_time = 10, -- in seconds
},
["Flag Dropper"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- When a player pick up the flag, the interval until they drop it is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 5, -- in seconds
max = 120, -- in seconds
},
["Vehicle Exit"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- When a player enters a vehicle, the interval until they are forced to exit is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 5, -- in seconds
max = 140, -- in seconds
},
["Name Changer"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- When a player joins, their new name will be randomly selected from this list.
names = { -- Max 11 Characters only!
{ "iLoveAG" },
{ "iLoveV3" },
{ "loser4Eva" },
{ "iLoveChalwk" },
{ "iLoveSe7en" },
{ "iLoveAussie" },
{ "benDover" },
{ "clitEruss" },
{ "tinyDick" },
{ "cumShot" },
{ "PonyGirl" },
{ "iAmGroot" },
{ "twi$t3d" },
{ "maiBahd" },
{ "frown" },
{ "Laugh@me" },
{ "imaDick" },
{ "facePuncher" },
{ "TEN" },
{ "whatElse" },
-- Repeat the structure to add more entries!
}
},
["Nuke"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
projectile = { "proj", "weapons\\rocket launcher\\rocket" },
-- Quantity of projectiles spawned:
min_projectiles = 1,
max_projectiles = 10,
-- The interval until they are nuked.
-- The interval itself is an amount of seconds between "min" and "max".
min = 55, -- in seconds
max = 175, -- in seconds
},
["Ammo Changer"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Min/Max time until ammo count is modified:
minAmmoTime = 15,
maxAmmoTime = 300,
-- Min/Max time until grenade count is modified:
minNadeTime = 45,
maxNadeTime = 250,
weapons = {
-- If battery powered weapon, set to true!
{ "weapons\\plasma rifle\\plasma rifle", true },
{ "weapons\\plasma_cannon\\plasma_cannon", true },
{ "weapons\\plasma pistol\\plasma pistol", true },
{ "weapons\\pistol\\pistol", false },
{ "weapons\\shotgun\\shotgun", false },
{ "weapons\\needler\\mp_needler", false },
{ "weapons\\sniper rifle\\sniper rifle", false },
{ "weapons\\assault rifle\\assault rifle", false },
{ "weapons\\flamethrower\\flamethrower", false },
{ "weapons\\rocket launcher\\rocket launcher", false },
},
},
["Glitched Grenades"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Interval until grenades are glitched is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 25, -- in seconds
max = 270, -- in seconds
},
["Silent Kick"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
announcements = {
enabled = false,
msg = "%name% was silently disconnected from the server!"
},
-- When a player joins, the interval until they are kicked is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 20, -- in seconds
max = 360, -- in seconds
},
["Random Color Change"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Chance that someone's color will be changed when they spawn:
chance = { 1, 6 },
-- COLOR ID, Enabled/Disabled
colors = {
{ 0, true }, --white
{ 1, true }, --black
{ 2, true }, --red
{ 3, true }, --blue
{ 4, true }, --gray
{ 5, true }, --yellow
{ 6, true }, --green
{ 7, true }, --pink
{ 8, true }, --purple
{ 9, true }, --cyan
{ 10, true }, --cobalt
{ 11, true }, --orange
{ 12, true }, --teal
{ 13, true }, --sage
{ 14, true }, --brown
{ 15, true }, --tan
{ 16, true }, --maroon
{ 17, true } --salmon
}
},
["Client Crasher"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- When a player joins, the interval until they are crashed is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 45, -- in seconds
max = 270, -- in seconds
},
["Fake Join-Quit"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Command Syntax: /base_command fake_join_command [player name] (max 11 characters)
fake_join_command = "fakejoin",
-- Command Syntax: /base_command fake_quit_command [player name] (max 11 characters)
fake_quit_command = "fakequit",
fake_join_message = "Welcome %fakename%",
fake_quit_message = "%fakename% quit",
permission_level = 1,
names = {
{ "ILoveRock" },
{ "leila water" },
{ "LilTuGfa" },
{ "Nuevo001" },
{ "Jass" },
{ "Crypt®" },
{ "Carbono980" },
{ "shagnemite" },
{ "DA-n00b1n8R" },
{ "i- XTuAnuel" },
},
-- Interval until fake join/quit message is broadcast to the target player.
-- The interval itself is an amount of seconds between "min" and "max".
min = 65, -- in seconds
max = 255, -- in seconds
},
["Force Chat"] = {
-- Set this to "false" to disable this feature on start up:
enabled = true,
ignore_admins = true,
-- Admins who are this level (or higher) will be ignored:
ignore_admin_level = 1,
-- Command Syntax: /base_command command [player id] {message}
command = "fchat",
-- Minimum permission level the player must be in order to execute /command:
permission_level = 1,
-- The interval until a player is forced to say something is randomized.
-- The interval itself is an amount of seconds between "min" and "max".
min = 60, -- in seconds
max = 300, -- in seconds
-- Players message output format:
-- %name% is replaced with the players name
-- %msg% is replaced with a random message from the list of sentences.
chat_format = "%name%: %msg%",
sentences = {
"I suck at this game!",
"I want my mommy!",
"Momma always said life is like a box of chocolates",
"I'm horny",
"I like turtles",
"I like eating human hotdogs",
"I was born a bastard",
"You can fuck my sister",
"I am the reason the gene pool needs a lifeguard",
"My only chance of getting laid is to crawl up the chicken's butt and wait!",
"Warthogs are gay",
"My favourite game type is CTF",
"Race game types suck balls",
"I ate some dirt out of the garden earlier",
"I'm wearing lipstick",
"Oh ouh! I shit myself. Be right back. Gotta clean up!",
"I'm a little school girl",
"I want to guzzle some gasoline",
"My brother just spat in my face",
"My mom said it's bed time. Bye fuckers",
"My nana is sitting next to me and asked what I'm doing",
"God damn my clothes smell",
"Time to take a rip off my bowl",
"I have to see my probation officer tomorrow",
-- repeat the structure to add more entries
},
},
}
}
-- Configuration [ENDS] ------------------------------------------------------
local game_over
local players = { }
local format = string.format
local gsub, sub, gmatch = string.gsub, string.sub, string.gmatch
local time_scale = 1 / 30
local flag, globals, ls, network_struct = { }, nil
function OnScriptLoad()
-- Register needed event callbacks:
register_callback(cb["EVENT_TICK"], "OnTick")
register_callback(cb['EVENT_PREJOIN'], "OnPlayerPreJoin")
register_callback(cb["EVENT_LEAVE"], "OnPlayerDisconnect")
register_callback(cb["EVENT_CHAT"], "OnPlayerChat")
register_callback(cb["EVENT_PRESPAWN"], "OnPreSpawn")
register_callback(cb["EVENT_COMMAND"], "OnServerCommand")
register_callback(cb["EVENT_GAME_END"], "OnGameEnd")
register_callback(cb["EVENT_GAME_START"], "OnGameStart")
register_callback(cb["EVENT_VEHICLE_ENTER"], "OnVehicleEntry")
register_callback(cb["EVENT_DAMAGE_APPLICATION"], "OnDamageApplication")
local gp = sig_scan("8B3C85????????3BF9741FE8????????8B8E2C0200008B4610") + 3
if (gp == 3) then
return
end
globals = read_dword(gp)
network_struct = read_dword(sig_scan("F3ABA1????????BA????????C740??????????E8????????668B0D") + 3)
if (Troll.features["Random Color Change"].enabled) then
LSS(true)
end
if (get_var(0, "$gt") ~= "n/a") then
game_over, players = false, { }
for i = 1, 16 do
if player_present(i) then
InitPlayer(i, false)
end
end
end
end
function OnScriptUnload()
if (Troll.features["Random Color Change"].enabled) then
LSS(false)
end
end
function OnGameStart()
if (get_var(0, "$gt") ~= "n/a") then
game_over, players = false, { }
flag = { read_word(globals + 0x8), read_word(globals + 0xc) }
local nc = Troll.features["Name Changer"]
if (nc.enabled) then
for i = 1, #nc.names do
nc.names[i].used = false
end
end
local fjq = Troll.features["Fake Join-Quit"]
if (fjq.enabled) then
for i = 1, #fjq.names do
fjq.names[i].joined = false
end
end
local feature_id = 1
for _, v in pairs(Troll.features) do
v.feature_id = feature_id
feature_id = feature_id + 1
end
if (Troll.settings.print_feature_state) then
PrintFeatureState()
end
end
end
function OnGameEnd()
game_over = true
end
function OnTick()
if (not gameover) then
for player, ply in pairs(players) do
if (player) and player_present(player) then
for Feature, V1 in pairs(Troll.features) do
for B, t in pairs(ply) do
if (Feature == B) then
if (V1.enabled) and TrollPlayer(player, V1) then
math.randomseed(os.time())
if player_alive(player) then
local DynamicPlayer = get_dynamic_player(player)
if (Feature == "Silent Kill") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_kill) then
KillSilently(player)
end
elseif (Feature == "Teleport Under Map") then
if (not InVehicle(DynamicPlayer)) then
t.timer = t.timer + time_scale
if (math.floor(t.timer) >= t.time_until_tp) then
t.timer = 0
t.time_until_tp = math.random(V1.min, V1.max)
local x, y, z = read_vector3d(DynamicPlayer + 0x5c)
write_vector3d(DynamicPlayer + 0x5c, x, y, z - t.zaxis)
cprint("[TROLL] " .. ply.name .. " was teleported under the map", 5 + 8)
end
end
elseif (Feature == "Inverted Controls") then
t.timer = t.timer + time_scale
if (t.timer > t.time_until_invert) then
local speed = read_float(DynamicPlayer + 0x6C)
if (t.getspeed) then
t.getspeed = false
t.old_speed = speed
execute_command("s " .. player .. " " .. speed - 2)
cprint("[TROLL] " .. ply.name .. " had their controls inverted", 5 + 8)
end
if (t.timer > (t.time_until_invert + V1.inverted_time)) then
t.timer = 0
execute_command("s " .. player .. " " .. speed + 1)
end
end
elseif (Feature == "Roasty Toasty") then
if (not InVehicle(DynamicPlayer)) then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_burn) then
t.timer = 0
t.time_until_burn = math.random(V1.min, V1.max)
SpawnFlames(DynamicPlayer)
cprint("[TROLL] " .. ply.name .. " is being burnt to a crisp!", 5 + 8)
end
end
elseif (Feature == "Fake Kill Messages") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_say) then
t.timer = 0
t.time_until_say = math.random(V1.min, V1.max)
local candidates = { }
for i = 1, 16 do
if player_present(i) and (i ~= player) then
candidates[#candidates + 1] = get_var(i, "$name")
end
end
local name = candidates[math.random(#candidates)]
if (name) then
local type = math.random(1, 2)
local message = V1.messages[type]
message = gsub(gsub(message, "%%fake_victim%%", name), "%%troll_victim%%", ply.name)
execute_command("msg_prefix \"\"")
say(player, message)
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
cprint("[TROLL] " .. ply.name .. " was sent a fake kill message", 5 + 8)
end
end
elseif (Feature == "Flag Dropper") then
if (not InVehicle(DynamicPlayer)) then
if hasObjective(DynamicPlayer) then
t.hasflag = true
t.timer = t.timer + time_scale
if (math.floor(t.timer) >= t.time_until_drop) then
drop_weapon(player)
cprint("[TROLL] " .. ply.name .. " was forced to drop the flag", 5 + 8)
end
elseif (t.hasflag) then
t.hasflag = false
t.time_until_drop = math.random(V1.min, V1.max)
t.timer = 0
else
t.timer = 0
end
end
elseif (Feature == "Vehicle Exit") then
if InVehicle(DynamicPlayer) then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_exit) then
t.timer = 0
exit_vehicle(player)
cprint("[TROLL] " .. ply.name .. " was forced to exit their vehicle", 5 + 8)
end
end
elseif (Feature == "Ammo Changer") then
if (not InVehicle(DynamicPlayer)) then
t.nade_timer = t.nade_timer + time_scale
t.weapon_timer = t.weapon_timer + time_scale
if (t.weapon_timer >= t.time_until_take_ammo) then
t.weapon_timer = 0
t.time_until_take_ammo = math.random(V1.minAmmoTime, V1.maxAmmoTime)
local weapon = read_dword(DynamicPlayer + 0x118)
local Object = get_object_memory(weapon)
if (Object ~= 0) then
local weapons = V1.weapons
for i = 1, #weapons do
local tag_name = read_string(read_dword(read_word(Object) * 32 + 0x40440038))
if (tag_name == weapons[i][1]) then
local battery_powered = weapons[i][2]
if (battery_powered) then
local energy = read_float(Object + 0x240)
execute_command("battery " .. player .. " " .. math.random(0, energy) .. " 0")
else
local ammo = read_word(Object + 0x2B8)
safe_write(true)
write_dword(Object + 0x2B8, math.random(0, ammo))
safe_write(false)
sync_ammo(weapon)
end
cprint("[TROLL] " .. ply.name .. " had their ammo count modified", 5 + 8)
end
end
end
elseif (t.nade_timer >= t.time_until_take_nades) then
t.nade_timer = 0
t.time_until_take_nades = math.random(V1.minNadeTime, V1.maxNadeTime)
local nade_type = math.random(1, 2)
if (nade_type == 1) then
local current = read_byte(DynamicPlayer + 0x31E)
local amount_to_take = math.random(0, current)
execute_command("nades " .. player .. " " .. current - amount_to_take)
elseif (nade_type == 2) then
local current = read_byte(DynamicPlayer + 0x31F)
local amount_to_take = math.random(0, current)
execute_command("plasmas " .. player .. " " .. current - amount_to_take)
end
cprint("[TROLL] " .. ply.name .. " had their grenade count modified", 5 + 8)
end
end
elseif (Feature == "Glitched Grenades") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_glitch) then
t.time_until_glitch = math.random(V1.min, V1.max)
execute_command("nades " .. player .. " -2")
cprint("[TROLL] " .. ply.name .. " had their grenades glitched", 5 + 8)
end
elseif (Feature == "Client Crasher") then
if not (t.delay) then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_crash) then
t.timer = 0
if hasObjective(DynamicPlayer) or InVehicle(DynamicPlayer) then
KillSilently(player)
t.delay = true
else
CrashClient(player, DynamicPlayer)
end
end
elseif player_alive(player) and (DynamicPlayer ~= 0) then
CrashClient(player, DynamicPlayer)
end
elseif (Feature == "Nuke") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_nuke) then
t.timer = 0
t.time_until_nuke = math.random(V1.min, V1.max)
Nuke(DynamicPlayer, V1)
cprint("[TROLL] " .. ply.name .. " was nuked!", 5 + 8)
end
end
end
-- Player does not need to be alive to execute blocks of code below this line:
if (Feature == "Silent Kick") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_kick) and (t.broadcast) then
SilentKick(player, V1)
end
elseif (Feature == "Force Chat") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_say) then
t.timer = 0
t.time_until_say = math.random(V1.min, V1.max)
local message = V1.sentences[math.random(#V1.sentences)]
local str = V1.chat_format
message = gsub(gsub(str, "%%name%%", ply.name), "%%msg%%", message)
execute_command("msg_prefix \"\"")
say_all(message)
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
cprint("[TROLL] " .. ply.name .. " was forced to say random message!", 5 + 8)
end
elseif (Feature == "Fake Join-Quit") then
t.timer = t.timer + time_scale
if (t.timer >= t.time_until_say) then
t.timer = 0
t.time_until_say = math.random(V1.min, V1.max)
local n = math.random(#V1.names)
local joined = V1.names[n].joined
local name = V1.names[n][1]
execute_command("msg_prefix \"\"")
if (joined) then
V1.names[n].joined = false
local msg = gsub(V1.fake_quit_message, "%%fakename%%", name)
say_all(msg)
cprint("[TROLL] FAKE QUIT - " .. msg, 5 + 8)
else
V1.names[n].joined = true
local msg = gsub(V1.fake_join_message, "%%fakename%%", name)
say_all(msg)
cprint("[TROLL] FAKE QUIT - " .. msg, 5 + 8)
end
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
end
end
end
end
end
end
end
end
end
end
function OnPlayerPreJoin(P)
InitPlayer(P, false)
end
function OnPlayerDisconnect(P)
local nc = Troll.features["Name Changer"]
if (nc.enabled) and TrollPlayer(P, nc) then
local id = players[P]["Name Changer"].name_id
if (nc.names[id] ~= nil) then
nc.names[id].used = false
end
end
InitPlayer(P, true)
end
function OnPreSpawn(P, OnEnable, EnableFeat)
local t = players[P]
if (t ~= nil) then
for Feature, V1 in pairs(Troll.features) do
for B, V2 in pairs(t) do
if (Feature == B) then
if (V1.enabled) and TrollPlayer(P, V1) then
math.randomseed(os.time())
if (not OnEnable) or (OnEnable and EnableFeat == Feature) then
if (Feature == "Silent Kill") then
V2.timer = 0
V2.time_until_kill = math.random(V1.min, V1.max)
elseif (Feature == "Silent Kick") then
V2.timer = 0
V2.broadcast = true
V2.time_until_kick = math.random(V1.min, V1.max)
elseif (Feature == "Teleport Under Map") then
V2.timer = 0
V2.zaxis = math.random(V1.minZ, V1.maxZ)
V2.time_until_tp = math.random(V1.min, V1.max)
V2.time_until_kick = math.random(V1.min, V1.max)
elseif (Feature == "Inverted Controls") then
V2.timer = 0
V2.getspeed = true
V2.time_until_invert = math.random(V1.untilMin, V1.untilMax)
elseif (Feature == "Roasty Toasty") then
V2.timer = 0
V2.time_until_burn = math.random(V1.min, V1.max)
elseif (Feature == "Fake Kill Messages") then
V2.timer = 0
V2.time_until_say = math.random(V1.min, V1.max)
elseif (Feature == "Flag Dropper") then
V2.hasflag = false
V2.timer = 0
V2.time_until_drop = math.random(V1.min, V1.max)
elseif (Feature == "Ammo Changer") then
V2.weapon_timer = 0
V2.time_until_take_ammo = math.random(V1.minAmmoTime, V1.maxAmmoTime)
V2.nade_timer = 0
V2.time_until_take_nades = math.random(V1.minNadeTime, V1.maxNadeTime)
elseif (Feature == "Glitched Grenades") then
V2.timer = 0
V2.time_until_glitch = math.random(V1.min, V1.max)
elseif (Feature == "Nuke") then
V2.timer = 0
V2.time_until_nuke = math.random(V1.min, V1.max)
elseif (Feature == "Force Chat") then
V2.timer = 0
V2.time_until_say = math.random(V1.min, V1.max)
elseif (Feature == "Fake Join-Quit") then
V2.timer = 0
V2.time_until_say = math.random(V1.min, V1.max)
elseif (Feature == "Client Crasher") then
V2.timer = 0
V2.delay = false
V2.time_until_crash = math.random(V1.min, V1.max)
elseif (Feature == "Random Color Change") then
local chance = V1.chance[math.random(#V1.chance)]
if (chance == 1) then
local player = get_player(P)
if (player ~= 0) then
local NewColor = function()
local temp = { }
for i = 1, #V1.colors do
if (V1.colors[i][2]) then
temp[#temp + 1] = V1.colors[i][1]
end
end
if (#temp > 0) then
return math.random(#temp)
end
return 0
end
write_byte(player + 0x60, NewColor())
cprint("[TROLL] " .. t.name .. " had their armor colour changed!", 5 + 8)
end
end
elseif (Feature == "Chat Text Randomizer") then
V2.chance = function()
return math.random(V1.min_chances, V1.max_chances)
end
end
end
end
end
end
end
end
end
function OnServerCommand(P, Command, _, _)
local CMD = CmdSplit(Command)
if (CMD == nil or CMD == "") then
return
else
CMD[1] = string.lower(CMD[1]) or string.upper(CMD[1])
if (CMD[1] == Troll.settings.base_command) then
if (CMD[2] ~= nil) then
local set = Troll.settings
local fc = Troll.features["Force Chat"]
local FJQ = Troll.features["Fake Join-Quit"]
if (CMD[2] == fc.command) then
local access = hasAccess(P, fc.permission_level)
if access then
local enabled = IsEnabled(P, fc)
if (enabled) then
local TargetID, String = tonumber(CMD[3]), tostring(CMD[4])
if (TargetID ~= nil and String ~= nil) then
if player_present(TargetID) then
if (P ~= TargetID) then
local msg = ConcatSplitString(CMD, 4)
msg = gsub(msg, '"', "")
local name = get_var(TargetID, "$name")
local str = fc.chat_format
local StringFormat = gsub(gsub(str, "%%name%%", name), "%%msg%%", msg)
execute_command("msg_prefix \"\"")
say_all(StringFormat)
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
local EName = get_var(P, "$name")
if (P == 0) then
EName = "THE SERVER"
end
cprint("[TROLL] " .. name .. " was forced to say something by " .. EName, 5 + 8)
else
Respond(P, "You cannot execute this command on yourself!", 4 + 8)
end
else
Respond(P, "Invalid Player ID or Player Not Online!", 4 + 8)
end
else
Respond(P, "Invalid Syntax. Usage: /" .. CMD[1] .. " " .. CMD[2] .. " [player id] {message}", 4 + 8)
end
end
end
elseif (CMD[2] == FJQ.fake_join_command) then
local access = hasAccess(P, FJQ.permission_level)
if access then
local enabled = IsEnabled(P, FJQ)
if (enabled) then
local fake_name = ConcatSplitString(CMD, 3)
fake_name = gsub(fake_name, '"', "")
if (string.len(fake_name) > 0 and string.len(fake_name) < 12) then
execute_command("msg_prefix \"\"")
say_all(gsub(FJQ.fake_join_message, "%%fakename%%", fake_name))
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
Respond(P, "Broadcasting JOIN message", 2 + 8)
else
Respond(P, "Sorry, player names can only be 1-11 characters", 4 + 8)
end
end
end
elseif (CMD[2] == FJQ.fake_quit_command) then
local access = hasAccess(P, FJQ.permission_level)
if access then
local enabled = IsEnabled(P, FJQ)
if (enabled) then
local fake_name = ConcatSplitString(CMD, 3)
fake_name = gsub(fake_name, '"', "")
if (string.len(fake_name) > 0 and string.len(fake_name) < 12) then
execute_command("msg_prefix \"\"")
say_all(gsub(FJQ.fake_quit_message, "%%fakename%%", fake_name))
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
Respond(P, "Broadcasting QUIT message", 2 + 8)
else
Respond(P, "Sorry, player names can only be 1-11 characters", 4 + 8)
end
end
end
elseif (CMD[2] == set.add_troll_command) then
local access = hasAccess(P, set.add_troll_permission)
if access then
local pl = GetPlayers(P, CMD)
if (pl) then
for i = 1, #pl do
local TargetID = tonumber(pl[i])
if (TargetID ~= 0) then
if (players[TargetID] == nil) then
InitPlayer(TargetID, false, true)
players[TargetID].ignore_status = true
OnPreSpawn(TargetID)
if (TargetID == P) then
Respond(P, "Successfully added yourself to troll list!", 2 + 8)
else
local name = get_var(TargetID, "$name")
Respond(P, "Temporarily adding " .. name .. " to the list of players to troll!", 2 + 8)
end
else
if (TargetID == P) then
Respond(P, "You are already on the troll list", 4 + 8)
else
Respond(P, "This player is already on the troll List!", 4 + 8)
end
end
else
Respond(P, "Server cannot be on troll list!", 4 + 8)
end
end
end
end
elseif (CMD[2] == set.remove_troll_command) then
local access = hasAccess(P, set.remove_troll_permission)
if access then
local pl = GetPlayers(P, CMD)
if (pl) then
for i = 1, #pl do
local TargetID = tonumber(pl[i])
if (TargetID ~= 0) then
if (players[TargetID] ~= nil) then
players[TargetID] = nil
if (TargetID == P) then
Respond(P, "Successfully removed yourself from troll list!", 2 + 8)
else
local name = get_var(TargetID, "$name")
Respond(P, "Successfully removed " .. name .. " from the list of players to troll!", 2 + 8)
end
else
if (TargetID == P) then
Respond(P, "You are not on the troll list", 4 + 8)
else
Respond(P, "This player is not on the troll list", 4 + 8)
end
end
else
Respond(P, "Server cannot be on troll list!", 4 + 8)
end
end
end
end
elseif (CMD[2] == set.feature_list_command) then
local access = hasAccess(P, set.enable_disable_list_perm)
if access then
Respond(P, "----- [ FEATURES ] -----")
for k, v in pairs(Troll.features) do
if (v.enabled) then
Respond(P, "[" .. v.feature_id .. "] " .. k .. "|rEnabled", 2 + 8)
else
Respond(P, "[" .. v.feature_id .. "] " .. k .. "|rDisabled", 4 + 8)
end
end
end
elseif (CMD[2] == set.enable_command) then
local access = hasAccess(P, set.enable_disable_list_perm)
if access then
EnableDisable(P, tonumber(CMD[3]), true)
end
elseif (CMD[2] == set.disable_command) then
local access = hasAccess(P, set.enable_disable_list_perm)
if access then
EnableDisable(P, tonumber(CMD[3]), false)
end
else
Respond(P, "Invalid command parameters!", 4 + 8)
end
else
Respond(P, "Please specify command parameters!", 4 + 8)
end
return false
end
end
end
function EnableDisable(P, ID, Enable)
local valid_id
for k, v in pairs(Troll.features) do
if (v.feature_id == ID) then
valid_id = true
if (Enable) then
if (not v.enabled) then
v.enabled = true
OnPreSpawn(P, true, k)
Respond(P, k .. " is now enabled!", 2 + 8)
else
Respond(P, k .. " is already enabled!", 4 + 8)
end
else
if (v.enabled) then
v.enabled = false
Respond(P, k .. " is now disabled!", 2 + 8)
else
Respond(P, k .. " is already disabled!", 4 + 8)
end
end
end
end
if (not valid_id) then
Respond(P, "Invalid Feature ID!", 4 + 8)
Respond(P, "Type /" .. Troll.settings.feature_list_command .. " to view feature ID", 4 + 8)
end
end
function OnPlayerChat(P, Message, Type)
if (Type ~= 6) then
local Msg = CmdSplit(Message)
if (Msg == nil or Msg == "") then
return
elseif (not isChatCmd(Msg)) then
local p = players[P]
if (p ~= nil) then
local t = p["Chat Text Randomizer"]
if (t.chance) then
local chance = t.chance()
if (chance and chance == 1) then
local new_message = ShuffleWords(Message)
local formatMsg = function(Str)
local patterns = {
{ "%%name%%", p.name },
{ "%%msg%%", new_message },
{ "%%id%%", P }
}
for i = 1, #patterns do
Str = (gsub(Str, patterns[i][1], patterns[i][2]))
end
return Str
end
execute_command("msg_prefix \"\"")
local F = Troll.features["Chat Text Randomizer"].format
if (Type == 0) then
say_all(formatMsg(F.global))
elseif (Type == 1) then
SayTeam(P, formatMsg(F.team))
elseif (Type == 2) then
SayTeam(P, formatMsg(F.vehicle))
execute_command("msg_prefix \" " .. Troll.settings.server_prefix .. "\"")
cprint("[TROLL] " .. players[P].name .. " chat message was scrambled!", 5 + 8)
return false
end
end
end
end
end
end
end
function OnVehicleEntry(P, _)
local t = players[P]
if (t ~= nil) then
local VE = Troll.features["Vehicle Exit"]
if (VE.enabled) and TrollPlayer(P, VE) then
math.randomseed(os.time())
t["Vehicle Exit"].timer = 0
t["Vehicle Exit"].time_until_exit = math.random(VE.min, VE.max)
end
end
end
function ChangeName(P)
local nc = Troll.features["Name Changer"]
if (nc.enabled) and TrollPlayer(P, nc) then
local name = GetRandomName(P, nc)
players[P].name = name
local client_network_struct = network_struct + 0x1AA + 0x40 + to_real_index(P) * 0x20
cprint("[TROLL] " .. get_var(P, "$name") .. " had their name changed to " .. name, 5 + 8)
write_widestring(client_network_struct, string.sub(name, 1, 11), 12)
end
end
function SayTeam(P, Message)
for i = 1, 16 do
if player_present(i) then
if get_var(i, "$team") == get_var(P, "$team") then
say(i, Message)
end
end
end
end
function InitPlayer(P, Reset, Bypass)
if (Reset) then
players[P] = nil
else
local Case = function()
local ip = get_var(P, "$ip"):match("%d+.%d+.%d+.%d+")
for i = 1, #Troll.settings.specific_users do
if (ip == Troll.settings.specific_users[i] or (not Troll.settings.specific_users_only)) or (Bypass) then
return true
end
end
return false
end
if Case() then
math.randomseed(os.time())
players[P] = {
name = get_var(P, "$name"),
ignore_status = false,
["Nuke"] = {},
["Force Chat"] = {},
["Silent Kick"] = {},
["Silent Kill"] = {},
["Flag Dropper"] = {},
["Vehicle Exit"] = {},
["Ammo Changer"] = {},
["Name Changer"] = {},
["Roasty Toasty"] = {},
["Fake Join-Quit"] = {},
["Client Crasher"] = {},
["Glitched Grenades"] = {},
["Inverted Controls"] = {},
["Teleport Under Map"] = {},
["Random Color Change"] = {},
["Fake Kill Messages"] = {},
["Chat Text Randomizer"] = {},
}
cprint("[TROLL] " .. get_var(P, "$name") .. " has been added to the list of players to troll", 5 + 8)
OnPreSpawn(P)
ChangeName(P)
return true
end
end
return false
end
function SilentKick(P, SK)
for _ = 1, 9999 do
rprint(P, " ")
end
local t = players[P]
if (t["Silent Kick"].broadcast) then
t["Silent Kick"].broadcast = false
if (SK.announcements.enabled) then
for i = 1, 6 do
if player_present(i) and (i ~= P) then
say(i, gsub(SK.announcements.msg, "%%name%%", t.name))
end
end
end
end
cprint("[TROLL] " .. t.name .. " was auto-kicked silently", 5 + 8)
end
function OnDamageApplication(VictimIndex, CauserIndex, MetaID, Damage, _, _)
if (tonumber(CauserIndex) > 0) then
local t = Troll.features["Damage Modifier"]
if (t.enabled) then
if (players[CauserIndex] ~= nil and players[VictimIndex] ~= nil) then
for Table, _ in pairs(t.multipliers) do
for _, Tag in pairs(t.multipliers[Table]) do
if (Tag[1] ~= nil) then
if (MetaID == GetTag("jpt!", Tag[1])) then
local SelfHarm = (VictimIndex == CauserIndex)
math.randomseed(os.clock())
if (SelfHarm) and TrollPlayer(VictimIndex, t) then
Damage = (Damage + math.random(Tag.you[1], Tag.you[2]))
cprint("[TROLL] " .. players[VictimIndex].name .. " units of damage was modified!", 5 + 8)
elseif (not SelfHarm) and TrollPlayer(CauserIndex, t) then
cprint("[TROLL] " .. players[CauserIndex].name .. " units of damage was modified!", 5 + 8)
if (Table == "vehicle_collision" or Table == "grenades" or Table == "projectiles") then
Damage = Damage - math.random(Tag.others[1], Tag.others[2])
else
Damage = -math.random(Tag[2], Tag[3])
end
end
return true, Damage
end
end
end
end
end
end
end
end
function Nuke(DynamicPlayer, N)
local coords = GetXYZ(DynamicPlayer)
local projectile_object = N.projectile
local object = GetTag(projectile_object[1], projectile_object[2])
if (object) then
for _ = N.min_projectiles, N.max_projectiles do
local payload = spawn_object(projectile_object[1], projectile_object[2], coords.x, coords.y, coords.z + 0.5)
local projectile = get_object_memory(payload)
if (projectile ~= 0) then
write_float(projectile + 0x68, 0)
write_float(projectile + 0x6C, 0)
write_float(projectile + 0x70, -1)
end
end
else
cprint("[TROLL] Nuke() | Projectile Tag Address Error", 4 + 8)
end
end
function CrashClient(Player, DynamicPlayer)
local Coords = GetXYZ(DynamicPlayer)
local TagType, TagName = "vehi", "vehicles\\rwarthog\\rwarthog"
if GetTag(TagType, TagName) then
local Vehicle = spawn_object(TagType, TagName, Coords.x, Coords.y, Coords.z)
local VehicleObject = get_object_memory(Vehicle)
if (VehicleObject ~= 0) then
for j = 0, 20 do
enter_vehicle(Vehicle, Player, j)
exit_vehicle(Player)
end
destroy_object(Vehicle)
cprint(" [TROLL] " .. players[Player].name .. " had their game crashed", 5 + 8)
end
else
cprint("[TROLL] CrashClient() | Vehicle Tag Address Error", 4 + 8)
end
end
function SpawnFlames(DynamicPlayer)
local t = Troll.features["Roasty Toasty"]
local flames = t.projectile
local object = GetTag(flames[1], flames[2])
if (object) then
for _ = 1, 1 do
local coords = GetXYZ(DynamicPlayer)
if (coords) then
spawn_object(flames[1], flames[2], coords.x, coords.y, coords.z + 0.2)
end
end
else
cprint("[TROLL] SpawnFlames() | Projectile Tag Address Error", 4 + 8)
end
end
function GetTag(obj_type, obj_name)
local tag = lookup_tag(obj_type, obj_name)
return tag ~= 0 and read_dword(tag + 0xC) or nil
end
function GetXYZ(DynamicPlayer)
local coordinates, x, y, z = {}
local VehicleID = read_dword(DynamicPlayer + 0x11C)
if (VehicleID == 0xFFFFFFFF) then
x, y, z = read_vector3d(DynamicPlayer + 0x5c)
else
x, y, z = read_vector3d(get_object_memory(VehicleID) + 0x5c)
end
coordinates.x, coordinates.y, coordinates.z = x, y, z
return coordinates
end
function hasObjective(DynamicPlayer)
for i = 0, 3 do
local WeaponID = read_dword(DynamicPlayer + 0x2F8 + 0x4 * i)
if (WeaponID ~= 0xFFFFFFFF) then
local Weapon = get_object_memory(WeaponID)
if (Weapon ~= 0) then
local tag_address = read_word(Weapon)
local tag_data = read_dword(read_dword(0x40440000) + tag_address * 0x20 + 0x14)
if (read_bit(tag_data + 0x308, 3) == 1) then
return true
end
end
end
end
return false
end
function ConcatSplitString(Msg, StartPoint)
local msg = ""
for i = 1, #Msg do
if (i >= StartPoint) then
msg = msg .. Msg[i] .. " "
end
end
return msg
end
function GetPlayers(P, Args)
local pl = { }
if (Args[2] == nil or Args[2] == "me") then
pl[#pl + 1] = P
elseif (Args[2]:match("%d+")) and player_present(Args[2]) then
pl[#pl + 1] = Args[2]
elseif (Args[2] == "all" or Args[2] == "*") then
for i = 1, 16 do
if player_present(i) then
pl[#pl + 1] = i
end
end
else
Respond(P, "Invalid Player ID or Player not Online", 4 + 8)
Respond(P, "Command Usage: " .. Args[1] .. " [number: 1-16] | */all | me", 4 + 8)
end
return pl
end
function IsEnabled(P, Feature)
if (not Feature.enabled) then
return Respond(P, "Sorry! This feature is disabled!", 4 + 8)
end
return true
end
function InVehicle(DynamicPlayer)
if (DynamicPlayer ~= 0) then
local VehicleID = read_dword(DynamicPlayer + 0x11C)
if (VehicleID ~= 0xFFFFFFFF) then
return true
end
end
return false
end
function TrollPlayer(P, Feature)
local lvl = tonumber(get_var(P, "$lvl"))
local ignore_status = (players[P].ignore_status == true)
return (lvl == -1) or ((Feature.ignore_admins == false) or (lvl <= Feature.ignore_admin_level)) or (ignore_status)
end
function KillSilently(P)
local kma = sig_scan("8B42348A8C28D500000084C9") + 3
local original = read_dword(kma)
safe_write(true)
write_dword(kma, 0x03EB01B1)
safe_write(false)
execute_command("kill " .. tonumber(P))
safe_write(true)
write_dword(kma, original)
safe_write(false)
write_dword(get_player(P) + 0x2C, 0 * 33)
local deaths = tonumber(get_var(P, "$deaths"))
execute_command("deaths " .. tonumber(P) .. " " .. deaths - 1)
cprint("[TROLL] " .. get_var(P, "$name") .. " was auto-killed silently", 5 + 8)
end
function GetRandomName(P, NC)
local ply = players[P]["Name Changer"]
ply.name_id = ply.name_id or 0
local t = { }
for i = 1, #NC.names do
if (string.len(NC.names[i][1]) < 12) then
if (not NC.names[i].used) then
t[#t + 1] = { NC.names[i][1], i }
end
end
end
if (#t > 0) then
math.randomseed(os.time())
local rand = math.random(#t)
local name = t[rand][1]
local n_id = t[rand][2]
NC.names[n_id].used = true
ply.name_id = n_id
return name
end
return "no name"
end
function isChatCmd(Msg)
if (sub(Msg[1], 1, 1) == "/" or sub(Msg[1], 1, 1) == "\\") then
return true
end
end
function CmdSplit(Message)
local Args, index = { }, 1
for Params in gmatch(Message, "([^%s]+)") do
Args[index] = Params
index = index + 1
end
return Args
end
function Respond(PlayerIndex, Message, Color)
if (PlayerIndex == 0) then
Color = Color or 2 + 8
cprint(Message, Color)
else
rprint(PlayerIndex, Message)
end
end
function ShuffleWords(String)
math.randomseed(os.time())
local letters = { }
for letter in String:gmatch '.[\128-\191]*' do
letters[#letters + 1] = { letter = letter, rnd = math.random() }
end
table.sort(letters, function(a, b)
return a.rnd < b.rnd
end)
for i, v in ipairs(letters) do
letters[i] = v.letter
end
return table.concat(letters)
end
function hasAccess(P, RequiredLevel)
local lvl = tonumber(get_var(P, "$lvl"))
local case = (lvl >= RequiredLevel) or (P == 0)
if (case) then
return true
else
Respond(P, "You do not have permission to execute this command", 4 + 8)
end
end
function PrintFeatureState()
cprint(" ")
cprint("---- TROLL FEATURES ----", 5 + 8)
for k, v in pairs(Troll.features) do
if (v.enabled) then
cprint("[" .. k .. '] is enabled', 2 + 8)
else
cprint("[" .. k .. '] is disabled', 4 + 8)
end
end
cprint(" ")
end
function report()
local script_version = format("%0.2f", Troll.settings.script_version)
cprint("--------------------------------------------------------", 5 + 8)
cprint("Please report this error on github:", 7 + 8)
cprint("https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/issues", 7 + 8)
cprint("Script Version: " .. script_version, 7 + 8)
cprint("--------------------------------------------------------", 5 + 8)
end
function OnError()
cprint(debug.traceback(), 4 + 8)
timer(50, "report")
end
------------ CREDITS BELOW --------------------------------------:
-- Credits to Kavawuvi for this chunk of code:
function LSS(state)
if (state) then
ls = sig_scan("741F8B482085C9750C")
if (ls == 0) then
ls = sig_scan("EB1F8B482085C9750C")
end
safe_write(true)
write_char(ls, 235)
safe_write(false)
else
if (ls == 0) then
return
end
safe_write(true)
write_char(ls, 116)
safe_write(false)
end
end
-----------------------------------------------------------------------
-- Credits to Devieth for these functions:
function write_widestring(address, str, len)
local Count = 0
for _ = 1, len do
write_byte(address + Count, 0)
Count = Count + 2
end
local count = 0
local length = string.len(str)
for i = 1, length do
local newbyte = string.byte(string.sub(str, i, i))
write_byte(address + count, newbyte)
count = count + 2
end
end
function read_widestring(Address, Size)
local str = ""
for i = 0, Size - 1 do
if read_byte(Address + i * 2) ~= 00 then
str = str .. string.char(read_byte(Address + i * 2))
end
end
if str ~= "" then
return str
end
return nil
end
-----------------------------------------------------------------------
return Troll
|
local parsers = require'nvim-treesitter.parsers'
local queries = require'nvim-treesitter.query'
local utils = require'nvim-treesitter.ts_utils'
local M = {}
local function get_node_at_line(root, lnum)
for node in root:iter_children() do
local srow, _, erow = node:range()
if srow == lnum then return node end
if node:child_count() > 0 and srow < lnum and lnum <= erow then
return get_node_at_line(node, lnum)
end
end
local wrapper = root:descendant_for_range(lnum, 0, lnum, -1)
local child = wrapper:child(0)
return child or wrapper
end
local get_indents = utils.memoize_by_buf_tick(function(bufnr)
local indents = queries.get_capture_matches(bufnr, '@indent.node', 'indents') or {}
local branches = queries.get_capture_matches(bufnr, '@branch.node', 'indents') or {}
local indents_map = {}
for _, node in ipairs(indents) do
indents_map[tostring(node)] = true
end
local branches_map = {}
for _, node in ipairs(branches) do
branches_map[tostring(node)] = true
end
return { indents = indents_map, branches = branches_map }
end)
function M.get_indent(lnum)
local parser = parsers.get_parser()
if not parser or not lnum then return -1 end
local node = get_node_at_line(parser:parse()[1]:root(), lnum-1)
local indent_queries = get_indents(vim.api.nvim_get_current_buf())
local indents = indent_queries.indents
local branches = indent_queries.branches
if not indents then return 0 end
while node and branches[tostring(node)] do
node = node:parent()
end
local ind_size = vim.bo.softtabstop < 0 and vim.bo.shiftwidth or vim.bo.tabstop
local ind = 0
while node do
node = node:parent()
if indents[tostring(node)] then
ind = ind + ind_size
end
end
return ind
end
local indent_funcs = {}
function M.attach(bufnr)
indent_funcs[bufnr] = vim.bo.indentexpr
vim.bo.indentexpr = 'nvim_treesitter#indent()'
end
function M.detach(bufnr)
vim.bo.indentexpr = indent_funcs[bufnr]
end
return M
|
function getNA11Actions(no)
if(no < 0)then return {};
elseif(no == 0)then
return {'5185','18562','8936','774','99','22812','22842','61336','192081','6795','164812','77758','33917','6807','213764'};
elseif(no == 1)then
return {'106951','1079','106832','5217','22568','164812','1822','5221','213764','61336','5185','5215','106839'};
elseif(no == 2)then
return {'8921','93402','197626','197628','5176','22812','208253','102342','197721','740','18562','774','48438','8936','5185'};
elseif(no == 3)then
return {'108238','22812','8921','93402','194223','202767','194153','78674','190984','191034'};
end
return {};
end
NA11ProfileNames = {[0]='熊德',[1]='貓德',[2]='恢复德',[3]='平衡德',};
NA11ProfileDescriptions = {[0]='天赋:3131131--属性:',[1]='天赋:--属性:',[2]='天赋:--属性:精神>急速≥精通>暴击=溅射>全能',[3]='天赋:3123122--属性:急速>精通>暴击=全能',};
function NA11Dps()
W_Log(1,"德鲁伊 dps");
local inBear = W_FormInfo(1);
local notTanking=not NA_IsSolo and not W_isTanking();
local inCat = W_FormInfo(2);
local inBird = W_FormInfo(4);
if(W_IsInCombat())then
if(NA_ProfileNo < 0)then return false; --保命施法
elseif(NA_ProfileNo == 0)then --熊德
if(false
)then return true; end
elseif(NA_ProfileNo == 1)then --貓德
if(false
or NA_Fire(NA_checkHP(0), '61336', NA_Player) --生存本能
or NA_Fire(NA_checkHP(2) and W_HasBuff(NA_Player, 69369, true), '5185', NA_Player) --治疗之触
)then return true; end
elseif(NA_ProfileNo == 2)then --恢复德
if(false
)then return true; end
elseif(NA_ProfileNo == 3)then --平衡德
if(false
)then return true; end
end
if(W_TargetCanAttack()) then --攻击施法
if(NA_ProfileNo < 0)then return false;
elseif(NA_ProfileNo == 0)then --熊德
if(not NA_IsAOE and (false
or NA_Fire(NA_checkHP(0), '5185', NA_Player) --治疗之触
or NA_Fire(NA_checkHP(0), '18562', NA_Player) --18562
or NA_Fire(NA_checkHP(0) and not W_RetainBuff(NA_Player, 8936, true), '8936', NA_Player) --8936
or NA_Fire(NA_checkHP(0) and not W_RetainBuff(NA_Player, 774, true), '774', NA_Player) --774
or NA_Fire(NA_checkHP(1), '99', NA_Target) --夺魂咆哮
or NA_Fire(NA_checkHP(1), '22812', NA_Player) --树皮术
or NA_Fire(NA_checkHP(1), '22842', NA_Player) --狂暴回复
or NA_Fire(NA_checkHP(1), '61336', NA_Player) --生存本能
or NA_Fire(NA_checkHP(3) and W_BuffCount(NA_Player, 192081, true)<1, '192081', NA_Player) --铁鬃
or NA_Fire(notTanking, '6795', NA_Target) --低吼
or NA_Fire(not W_RetainBuff(NA_Target, -164812, true), '164812', NA_Target) --月火术
or NA_Fire(true, '77758', NA_Player) --77758
or NA_Fire(W_HasBuff(NA_Player, 93622, true), '33917', NA_Target) --裂伤
or NA_Fire(UnitPower(NA_Player)>50, '6807', NA_Target) --重殴
or NA_Fire(true, '33917', NA_Target) --裂伤
))then return true; end
if(NA_IsAOE and (false
or NA_Fire(NA_checkHP(0), '61336', NA_Player) --生存本能
or NA_Fire(NA_checkHP(0), '5185', NA_Player) --治疗之触
or NA_Fire(NA_checkHP(0), '18562', NA_Player) --18562
or NA_Fire(NA_checkHP(0) and not W_RetainBuff(NA_Player, 8936, true), '8936', NA_Player) --8936
or NA_Fire(NA_checkHP(0) and not W_RetainBuff(NA_Player, 774, true), '774', NA_Player) --774
or NA_Fire(NA_checkHP(1), '99', NA_Target) --夺魂咆哮
or NA_Fire(NA_checkHP(1), '22812', NA_Player) --树皮术
or NA_Fire(NA_checkHP(1), '22842', NA_Player) --狂暴回复
or NA_Fire(NA_checkHP(3) and W_BuffCount(NA_Player, 192081, true)<1, '192081', NA_Player) --铁鬃
or NA_Fire(notTanking, '6795', NA_Target) --低吼
or NA_Fire(not W_RetainBuff(NA_Target, -164812, true), '164812', NA_Target) --月火术
or NA_Fire(true, '77758', NA_Player) --77758
or NA_Fire(W_HasBuff(NA_Player, 93622, true), '33917', NA_Target) --裂伤
or NA_Fire(true, '213764', NA_Nil) --横扫
or NA_Fire(true, '33917', NA_Target) --裂伤
))then return true; end
elseif(NA_ProfileNo == 1)then --貓德
local hasgl = W_RetainBuff(NA_Target, -1079, true); --割裂
local hasqxyz = W_RetainBuff(NA_Player, 16864, true); --清晰预兆
local hasComboPoints = UnitPower(NA_Player,4)>4 or (NA_IsSolo and not NA_IsMaxDps and UnitPower(NA_Player,4)>2)
if(not NA_IsAOE and (false
or NA_Fire(NA_IsMaxDps, '106951', NA_Player) --狂暴
or NA_Fire(not hasgl and hasComboPoints, '1079', NA_Target) --割裂
or NA_Fire(hasqxyz, '106832', NA_Target) --痛击
or NA_Fire(W_PowerLevel(NA_Player)<0.6, '5217', NA_Player) --猛虎之怒
or NA_Fire(hasComboPoints, '22568', NA_Target) --凶猛撕咬
or NA_Fire(NA_isUsableTalentSpell(7,1) and not W_RetainBuff(NA_Target, -155625, true), '164812', NA_Target) --月火术
or NA_Fire(not W_RetainBuff(NA_Target, -5215, true), '1822', NA_Target) --斜掠
or NA_Fire(true, '5221', NA_Target) --撕碎
))then return true; end
if(NA_IsAOE and (false
or NA_Fire(UnitPower(NA_Player,4)<5, '213764', NA_Target) --横扫
or NA_Fire(not hasgl and hasComboPoints, '1079', NA_Target) --割裂
or NA_Fire(hasComboPoints, '22568', NA_Target) --凶猛撕咬
or NA_Fire(NA_isUsableTalentSpell(7,1) and not W_RetainBuff(NA_Target, -155625, true), '164812', NA_Target) --月火术
or NA_Fire(not W_RetainBuff(NA_Target, -5215, true), '1822', NA_Target) --斜掠
or NA_Fire(UnitPower(NA_Player,4)<5 or W_RetainBuff(NA_Player, 58984, true), '5221', NA_Target) --撕碎
))then return true; end
elseif(NA_ProfileNo == 2)then --恢复德
if(not NA_IsAOE and (false
or NA_Fire(not W_RetainBuff(NA_Target, -164812, true), '8921', NA_Target) --8921
or NA_Fire(not W_RetainBuff(NA_Target, -164815, true), '93402', NA_Target) --阳炎术
or NA_Fire(W_FormInfo(4) and not W_HasBuff(NA_Player, 164545, true) and not W_HasBuff(NA_Player, 164547, true), '197626', NA_Target) --197626
or NA_Fire(W_FormInfo(4) and W_HasBuff(NA_Player, 164547, true), '197628', NA_Target) --197628
or NA_Fire(true, '5176', NA_Target) --阳炎之怒
))then return true; end
if(NA_IsAOE and (false
))then return true; end
elseif(NA_ProfileNo == 3)then --平衡德
if(not NA_IsAOE and (false
or NA_Fire(W_HPlevel(NA_Player) < 0.6, '108238', NA_Player) --新生
or NA_Fire(W_HPlevel(NA_Player) < 0.9, '22812', NA_Player) --树皮术
or NA_Fire(not W_HasBuff(NA_Target, -164812, true), '8921', NA_Target) --8921
or NA_Fire(not W_RetainBuff(NA_Target, -164815, true), '93402', NA_Target) --阳炎术
or NA_Fire(inBird and NA_IsMaxDps, '194223', NA_Player) --超凡之盟
or NA_Fire(UnitPower(NA_Player,8)<80, '202767', NA_Target) --新月
or NA_Fire(inBird and W_HasBuff(NA_Player, 202425, true), '194153', NA_Target) --明月打击
or NA_Fire(inBird and not W_HasBuff(NA_Player, 164545, true) and not W_HasBuff(NA_Player, 164547, true), '78674', NA_Target) --星涌术
or NA_Fire(inBird and W_HasBuff(NA_Player, 164545, true), '190984', NA_Target) --阳炎之怒
or NA_Fire(inBird and W_HasBuff(NA_Player, 164547, true), '194153', NA_Target) --明月打击
or NA_Fire(true, '190984', NA_Target) --阳炎之怒
))then return true; end
if(NA_IsAOE and (false
or NA_Fire(W_HPlevel(NA_Player) < 0.6, '108238', NA_Player) --新生
or NA_Fire(W_HPlevel(NA_Player) < 0.9, '22812', NA_Player) --树皮术
or NA_Fire(UnitPower(NA_Player,8)<80, '202767', NA_Target) --新月
or NA_Fire(not W_HasBuff(NA_Target, -164812, true), '8921', NA_Target) --8921
or NA_Fire(not W_RetainBuff(NA_Target, -164815, true), '93402', NA_Target) --阳炎术
or NA_Fire(true, '191034', NA_Target) --星辰坠落
or NA_Fire(inBird, '194153', NA_Target) --明月打击
))then return true; end
end
elseif(UnitCanAssist(NA_Player, NA_Target))then --辅助施法
if(NA_ProfileNo < 0)then return false;
elseif(NA_ProfileNo == 0)then --熊德
if(false
)then return true; end
elseif(NA_ProfileNo == 1)then --貓德
if(false
)then return true; end
elseif(NA_ProfileNo == 2)then --恢复德
local hcs = W_RetainBuff(NA_Target, 774, true); --回春术
local yh = W_RetainBuff(NA_Target, 8936, true); --愈合
local jnsf = W_RetainBuff(NA_Player, 16870, true); --节能施法
if(false
or NA_Fire(NA_checkHP(1), '22812', NA_Player) --树皮术
or NA_Fire(W_HPlevel(NA_Target)<0.3, '208253', NA_Target) --加尼尔的精华
or NA_Fire(W_HPlevel(NA_Target)<0.5, '102342', NA_Target) --铁木树皮
or NA_Fire(W_HPlevel(NA_Target)<0.5, '197721', NA_Target) --繁盛
or NA_Fire(NA_IsMaxDps and W_HPlevel(NA_Target)<0.5, '740', NA_Player) --宁静
or NA_Fire(W_HPlevel(NA_Target)<0.7, '18562', NA_Target) --迅捷治愈
or NA_Fire(W_HPlevel(NA_Target)<1 and not hcs, '774', NA_Target) --回春术
or NA_Fire(W_HPlevel(NA_Target)<0.9, '48438', NA_Target) --野性成长
or NA_Fire(W_HPlevel(NA_Target)<1 and jnsf and not yh, '8936', NA_Target) --愈合
or NA_Fire(W_HPlevel(NA_Target)<0.7 and not yh, '8936', NA_Target) --愈合
or NA_Fire(W_HPlevel(NA_Target)<0.7, '5185', NA_Target) --治疗之触
)then return true; end
elseif(NA_ProfileNo == 3)then --平衡德
if(false
)then return true; end
end
end
else --不在战斗中
if(NA_ProfileNo < 0)then return false; --脱战后补buff,开怪等
elseif(NA_ProfileNo == 0)then --熊德
if(false
or NA_Fire(NA_IsSolo and W_TargetCanAttack(), '164812', NA_Target) --月火术
)then return true; end
elseif(NA_ProfileNo == 1)then --貓德
if(false
or NA_Fire(not W_HasBuff(NA_Player, 5215, true) and W_TargetCanAttack(), '5215', NA_Player) --潜行
or NA_Fire(true and W_TargetCanAttack(), '106839', NA_Target) --迎头痛击
or NA_Fire(true and W_TargetCanAttack(), '1822', NA_Target) --斜掠
)then return true; end
elseif(NA_ProfileNo == 2)then --恢复德
if(false
)then return true; end
elseif(NA_ProfileNo == 3)then --平衡德
if(false
or NA_Fire(NA_IsSolo and W_TargetCanAttack(), '93402', NA_Target) --阳炎术
or NA_Fire(W_TargetCanAttack(), '190984', NA_Target) --阳炎之怒
)then return true; end
end
end
return false;
end
|
require "lib.classes.class"
local Menu = require "Menu.model.menues.Menu"
--------------------------------------------------------------------------------------------------------
-- class: MenuBuilder
-- Builder class to create a menu
local MenuBuilder = class(function(self)
self.menu = Menu.new()
self.state_number = 0
end)
-- addState: MenuState -> self
-- Adds a menu state to the menu
function MenuBuilder.addState(self,state)
self.menu.options[self.state_number+1] = state
if self.state_number == 0 then
self:setCurrentState(0)
end
self.state_number = self.state_number + 1
return self
end
-- addTransition: int int key -> self
-- Adds a transition to the menu
function MenuBuilder.addTransition(self,i, j, key)
self.menu.options[i+1]:setTransition(key, self.menu.options[j+1])
return self
end
-- setCurrentState: int -> self
-- Sets the current option of the menu (if the option number exceeds the amount of options y corrects to the last option)
function MenuBuilder.setCurrentState(self, i)
self.menu:setCurrentState(self.menu.options[math.min(i+1, self.menu:getOptionNumber())])
return self
end
-- getMenu: None -> Menu
-- Gets the builder's menu
function MenuBuilder.getMenu(self)
return self.menu
end
return MenuBuilder
|
local log = require('nvim-completor/log')
local manager = require("nvim-completor/src-manager")
local completor = require("nvim-completor/completor")
local ncp_lsp = require("nvim-completor/lsp")
local private = {}
function private.filter_items(ctx, items)
if not items or #items == 0 then
return {}
end
local new_items = items
local prefix = ctx:typed_to_cursor()
prefix = prefix:match("[%w_]+$")
if prefix and #prefix > 0 then
new_items = vim.tbl_filter(function(item)
local word = item.filterText or item.insertText or item.label
return vim.startswith(word, prefix)
end, items)
end
log.trace("new items num: ", #new_items, " old items num: ", #items)
return new_items
end
function private.request_src(ctx)
if not ctx then
return
end
local bufno = vim.api.nvim_get_current_buf()
log.trace("builtin_lsp complete request")
params = {
textDocument = { uri = vim.uri_from_bufnr(0) },
position = {
line = ctx.pos[1];
character = vim.str_utfindex(ctx.typed, ctx.pos[2]);
-- character = ctx.pos[2];
}
}
vim.lsp.buf_request(
bufno,
'textDocument/completion',
params,
function(err, _, result)
if err or not result then
log.warn("lsp complete err ", err)
return
end
log.trace("builtin lsp response")
local items = result.items or result
local incomplete = result.incomplete
if incomplete then
incomplete = "builtin_lsp"
end
log.trace(items)
items = private.filter_items(ctx, items)
log.debug(items)
items = ncp_lsp.lsp_items2vim(ctx, items)
if not items or #items == 0 then
return
end
completor.add_complete_items(ctx, items, incomplete)
end
)
end
manager:add_src("builtin_lsp", private.request_src)
log.info("add builtin lsp complete source finish")
|
-- clear statistics
env = require('test_run')
test_run = env.new()
test_run:cmd('restart server default with cleanup=1')
box.stat.INSERT.total
box.stat.DELETE.total
box.stat.UPDATE.total
box.stat.REPLACE.total
box.stat.SELECT.total
box.stat.ERROR.total
space = box.schema.space.create('tweedledum')
index = space:create_index('primary', { type = 'hash' })
-- check stat_cleanup
-- add several tuples
for i=1,10 do space:insert{i, 'tuple'..tostring(i)} end
box.stat.INSERT.total
box.stat.DELETE.total
box.stat.UPDATE.total
box.stat.REPLACE.total
box.stat.SELECT.total
-- check exceptions
space:get('Impossible value')
box.stat.ERROR.total
-- select, get, and pairs
space:get(1)
box.stat.SELECT.total
space:get(11)
box.stat.SELECT.total
space:select(5)
box.stat.SELECT.total
space:select(15)
box.stat.SELECT.total
for _ in space:pairs() do end
box.stat.SELECT.total
-- reset
box.stat.reset()
box.stat.INSERT.total
box.stat.DELETE.total
box.stat.UPDATE.total
box.stat.REPLACE.total
box.stat.SELECT.total
box.stat.ERROR.total
test_run:cmd('restart server default')
-- statistics must be zero
box.stat.INSERT.total
box.stat.DELETE.total
box.stat.UPDATE.total
box.stat.REPLACE.total
box.stat.SELECT.total
box.stat.ERROR.total
-- cleanup
box.space.tweedledum:drop()
|
local libraryUtil = {}
function libraryUtil.checkType( name, argIdx, arg, expectType, nilOk )
if arg == nil and nilOk then
return
end
if type( arg ) ~= expectType then
local msg = string.format( "bad argument #%d to '%s' (%s expected, got %s)",
argIdx, name, expectType, type( arg )
)
error( msg, 3 )
end
end
function libraryUtil.checkTypeForIndex( index, value, expectType )
if type( value ) ~= expectType then
local msg = string.format( "value for index '%s' must be %s, %s given",
index, expectType, type( value )
)
error( msg, 3 )
end
end
function libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc )
return function ( self, method )
if self ~= selfObj then
error( string.format(
"%s: invalid %s. Did you call %s with a dot instead of a colon, i.e. " ..
"%s.%s() instead of %s:%s()?",
libraryName, selfObjDesc, method, varName, method, varName, method
), 3 )
end
end
end
return libraryUtil
|
local ECS = require('wacky-ecs.wacky-ecs')
ECS.Component.new('animation',
function(texture, quads, current, animations)
return {
texture = texture,
quads = quads,
animations = animations,
current = current or 'default',
time = 0,
frame = 1
}
end)
local animation = ECS.System.new('animation', {'drawable', 'animation'})
function animation:update(entities, dt)
-- local time = love.timer.getTime()
for _,e in ipairs(entities) do
local a = e.animation
local d = e.drawable
local current = a.animations[a.current]
-- if time - a.time > current.time then
-- a.time = time + ((time - a.time) % current.time)
-- if a.frame < #current.frames or current.loop then
-- a.frame = 1 + (a.frame % #current.frames)
-- end
-- end
a.time = a.time + dt
if a.time > current.time then
if a.frame < #current.frames or current.loop then
a.frame = 1 + (a.frame % #current.frames)
end
a.time = a.time - current.time
end
d.texture = a.texture
d.quad = a.quads[current.frames[a.frame]]
end
end
|
return {'inhaalactie','inhaalbeweging','inhaalcursus','inhaaldag','inhaaleffect','inhaalmanoeuvre','inhaalmatch','inhaaloperatie','inhaalpoging','inhaalpremie','inhaalprogramma','inhaalrace','inhaalsituatie','inhaalslag','inhaalstrook','inhaalverbod','inhaalvraag','inhaalwedstrijd','inhaken','inhakken','inhalatie','inhalatieapparaat','inhalatietoestel','inhalator','inhalen','inhaleren','inhalers','inhalig','inhaligheid','inhaling','inham','inhameren','inhangen','inhebben','inhechtenisneming','inheems','inheemse','inheemsen','inheien','inherent','inhibitie','inhomogeen','inhoud','inhoudelijk','inhoudelijkheid','inhouden','inhouding','inhoudsanalyse','inhoudsbepaling','inhoudsloos','inhoudsmaat','inhoudsniveau','inhoudsopgaaf','inhoudsopgave','inhoudssamenvatting','inhoudstafel','inhoudsweergave','inhout','inhouwen','inhuldigen','inhuldiging','inhuldigingsfeest','inhumaan','inhuren','inhumatie','inhoudsvol','inhoudingsplichtige','inhaalrust','inhaalgroei','inhoudingsplicht','inhaalregeling','inhaalruimte','inhaak','inhaakt','inhaakte','inhaakten','inhaal','inhaaldagen','inhaalde','inhaalden','inhaalmanoeuvres','inhaalpremies','inhaalt','inhak','inhakt','inhakte','inhakten','inhalaties','inhalatietoestellen','inhaleer','inhaleerde','inhaleerden','inhaleert','inhalerend','inhalerende','inhalige','inhaliger','inhaligste','inhalingen','inhammen','inhangt','inhechtenisnemingen','inhei','inheiden','inheit','inhelp','inhelpt','inherente','inhield','inhielp','inhielpen','inhieuwen','inhomogene','inhoudelijke','inhoudelijks','inhoudend','inhoudende','inhoudingen','inhoudsbepalingen','inhoudsloze','inhoudsmaten','inhoudsopgaven','inhoudstafels','inhoudsvolle','inhoudt','inhouw','inhouwt','inhuldig','inhuldigde','inhuldigden','inhuldigingen','inhuldigingsfeesten','inhuldigt','inhumane','inhumaner','inhuur','inhuurde','inhuurden','inhuurt','inhaalmatchen','inhaalmatches','inhaalstroken','inhaalwedstrijden','inhakend','inhalators','inhalend','inhalende','inhangende','inhielden','inhumaanst','inhammetje','inhalatoren','inhibities','inhumaties','inhaalacties','inhaalverboden','inhoudingsplichtigen','inhaalbewegingen','inhaalpogingen'}
|
return function(catagory)
return {
type = script.Name,
catagory = catagory,
}
end
|
--[[
Copyright (c) 2015 gameboxcloud.com
Permission is hereby granted, free of chargse, 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 Online = cc.import("#online")
local Session = cc.import("#session")
local gbc = cc.import("#gbc")
local UserAction = cc.class("UserAction", gbc.ActionBase)
local _opensession
function UserAction:signinAction(args)
local username = args.username
if not username then
cc.throw("not set argsument: \"username\"")
end
-- start session
local session = Session:new(self:getInstance():getRedis())
session:start()
session:set("username", username)
session:set("count", 0)
session:save()
-- return result
return {sid = session:getSid(), count = 0}
end
function UserAction:signoutAction(args)
-- remove user from online list
local session = _opensession(self:getInstance(), args)
local online = Online:new(self:getInstance())
online:remove(session:get("username"))
-- delete session
session:destroy()
return {ok = "ok"}
end
function UserAction:countAction(args)
-- update count value in session
local session = _opensession(self:getInstance(), args)
local count = session:get("count")
count = count + 1
session:set("count", count)
session:save()
return {count = count}
end
function UserAction:addjobAction(args)
local sid = args.sid
if not sid then
cc.throw("not set argsument: \"sid\"")
end
local instance = self:getInstance()
local redis = instance:getRedis()
local session = Session:new(redis)
if not session:start(sid) then
cc.throw("session is expired, or invalid session id")
end
local delay = cc.checkint(args.delay)
if delay <= 0 then
delay = 1
end
local message = args.message
if not message then
cc.throw("not set argument: \"message\"")
end
-- send message to job
local jobs = instance:getJobs()
local job = {
action = "/jobs/jobs.echo",
delay = delay,
data = {
username = session:get("username"),
message = message,
}
}
local ok, err = jobs:add(job)
if not ok then
return {err = err}
else
return {ok = "ok"}
end
end
-- private
_opensession = function(instance, args)
local sid = args.sid
if not sid then
cc.throw("not set argsument: \"sid\"")
end
local session = Session:new(instance:getRedis())
if not session:start(sid) then
cc.throw("session is expired, or invalid session id")
end
return session
end
return UserAction
|
-- This file is generated by pcode_autog-1.19.5
-- Copyright(c) Lake.Deal, ALL RIGHTS RESERVED.
--
-- Purpose: contains some constants defininations
--
--
proto = proto or {}
proto.numbers = {
CID_SIMPLE1 = 101,
}
|
local MAJOR="AceConsole-3.0"
dofile("wow_api.lua")
dofile("LibStub.lua")
dofile("../"..MAJOR.."/"..MAJOR..".lua")
local AC = assert(LibStub(MAJOR))
----------------------------------------------------------
-- Simple tests
-- (no need to explicitly test startpos; if multi-arg tests work, it works)
local a1,a2 = AC:GetArgs("") -- no arg
assert(a1==nil and a2==1e9)
local a1,a2 = AC:GetArgs(" ") -- still no arg
assert(a1==nil and a2==1e9)
local a1,a2 = AC:GetArgs("a1") -- simple
assert(a1=="a1" and a2==1e9)
local a1 = AC:GetArgs("a1", 0) -- fetch 0 args
assert(a1==1)
local a1 = AC:GetArgs(" a1", 0) -- fetch 0 args, leading space
assert(a1==3)
local a1,a2 = AC:GetArgs("a1 a2") -- args remaining, check nextpos
assert(a1=="a1" and a2==4)
local a1,a2 = AC:GetArgs("a1 a2") -- args remaining, check nextpos
assert(a1=="a1" and a2==6, dump(a1,a2))
local a1,a2,a3 = AC:GetArgs("a1 a2", 2) -- 2 args
assert(a1=="a1" and a2=="a2" and a3==1e9)
local a1,a2,a3 = AC:GetArgs(" a1 a2 ", 2) -- surplous space
assert(a1=="a1" and a2=="a2" and a3==1e9, dump(a1,a2,a3))
local a1,a2,a3 = AC:GetArgs(" a1 a2 ", 2) -- one more space at end
assert(a1=="a1" and a2=="a2" and a3==1e9, dump(a1,a2,a3))
local a1,a2,a3 = AC:GetArgs(" a1 ", 2) -- missing arg2
assert(a1=="a1" and a2==nil and a3==1e9, dump(a1,a2,a3))
----------------------------------------------------------
-- Test quoting
local a1,a2 = AC:GetArgs([["a1"]]) -- simple quote
assert(a1=="a1" and a2==1e9, dump(a1,a2))
local a1,a2 = AC:GetArgs([["a 1"]]) -- quote with space in it
assert(a1=="a 1" and a2==1e9, dump(a1,a2))
local a1,a2 = AC:GetArgs([[" a 1 "]]) -- quote with space at beginning and end
assert(a1==" a 1 " and a2==1e9, dump(a1,a2))
local a1,a2 = AC:GetArgs([['a 1']]) -- single quote
assert(a1=="a 1" and a2==1e9, dump(a1,a2))
local a1,a2,a3 = AC:GetArgs([["a 1" "a 2"]], 2) -- 2 args
assert(a1=="a 1" and a2=="a 2" and a3==1e9, dump(a1,a2,a3))
local a1,a2,a3 = AC:GetArgs([["a 1" 'a 2']], 2) -- mixed quoting
assert(a1=="a 1" and a2=="a 2" and a3==1e9, dump(a1,a2,a3))
local a1,a2,a3 = AC:GetArgs([[ "a 1" 'a 2' ]], 2) -- surplous spacing between quotes
assert(a1=="a 1" and a2=="a 2" and a3==1e9, dump(a1,a2,a3))
local a1,a2,a3 = AC:GetArgs([["foo'bar" 'foo"bar']], 2) -- don't break on nonmatching quote
assert(a1=="foo'bar" and a2=='foo"bar' and a3==1e9, dump(a1,a2,a3))
local a1,a2 = AC:GetArgs([[ "unfinished quote]], 1) -- missing " at end
assert(a1=="unfinished quote" and a2==1e9, dump(a1,a2))
------------------------------------------------------------
-- Hyperlinks and combos
local a1,a2,a3,a4 = AC:GetArgs("simple |Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r", 3)
assert(a1=="simple" and a2=="|Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r" and a3==nil and a4==1e9, dump(a1,a2,a3,a4))
local a1,a2,a3,a4 = AC:GetArgs("simple '|Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r'", 3)
assert(a1=="simple" and a2=="|Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r" and a3==nil and a4==1e9, dump(a1,a2,a3,a4))
local a1,a2,a3,a4 = AC:GetArgs("simple \"|Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r\" 'bar'", 3)
assert(a1=="simple" and a2=="|Cff112233|Hitem:0:0:0:0|hand here's a text with \"s and stuff|h|r" and a3=="bar" and a4==1e9, dump(a1,a2,a3,a4))
local a1,a2,a3,a4 = AC:GetArgs("simple |H|ha 1|h|H|ha 1|h", 3)
assert(a1=="simple" and a2=="|H|ha 1|h|H|ha 1|h" and a3==nil and a4==1e9, dump(a1,a2,a3,a4))
local a1,a2,a3,a4 = AC:GetArgs("simple ||H|ha 1|h|H|ha 1|h", 3) -- note double ||
assert(a1=="simple" and a2=="||H|ha" and a3=="1|h|H|ha 1|h" and a4==1e9, dump(a1,a2,a3,a4))
local a1,a2,a3,a4 = AC:GetArgs("simple |||H|ha 1|h|H|ha 1|h", 3) -- note double || followed by |H
assert(a1=="simple" and a2=="|||H|ha 1|h|H|ha 1|h" and a3==nil and a4==1e9, dump(a1,a2,a3,a4))
------------------------------------------------------------
print "OK"
|
local diffview = require 'diffview'
diffview.setup {
enhanced_diff_hl = true
}
|
local fs = require("filesystem")
local shell = require("shell")
if not fs.exists("/tmp/update-tmp.cfg") then
u = io.open("/etc/update.cfg", "r")
textu = u:read()
u:close()
else
u = io.open("/tmp/update-tmp.cfg", "r")
textu = u:read()
u:close()
end
local function dirs()
local env = {}
local config = loadfile("/tmp/dirs.dat", nil, env)
if config then
pcall(config)
end
return env.dirs
end
local dirs = dirs()
if dirs then
for i = 1, #dirs do
local files = fs.makeDirectory(shell.resolve(dirs[i]))
if files ~= nil then
print("Made missing directory: " .. dirs[i])
end
end
print("Finished\n")
end
shell.execute("wget -f https://raw.githubusercontent.com/Shuudoushi/SecureOS/" .. textu .. "/sbin/update.lua /sbin/update.lua \n")
shell.execute("wget -f https://raw.githubusercontent.com/Shuudoushi/SecureOS/" .. textu .. "/root/login.lua /root/login.lua \n")
shell.execute("wget -f https://raw.githubusercontent.com/Shuudoushi/SecureOS/" .. textu .. "/init.lua /init.lua \n")
shell.execute("wget -f https://raw.githubusercontent.com/Shuudoushi/SecureOS/" .. textu .. "/boot/kernel/SecureOS /boot/kernel/SecureOS \n")
local v = io.open("/.version", "w")
v:write("myversions = { bin = '0', boot = '0', etc = '0', lib = '0', root = '0', sbin = '0', system = '0', usr = '0' }")
v:close()
print("The updater has changed, please run it again after reboot")
if not require("event").pull() == "key_down" then os.sleep(30) end
os.remove("/tmp/depreciated.dat")
os.sleep(1.5)
|
object_tangible_loot_npc_loot_dye_set_generic = object_tangible_loot_npc_loot_shared_dye_set_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_dye_set_generic, "object/tangible/loot/npc/loot/dye_set_generic.iff")
|
object_tangible_storyteller_story_token_generic = object_tangible_storyteller_shared_story_token_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_storyteller_story_token_generic, "object/tangible/storyteller/story_token_generic.iff")
|
function CreateSprite(image)
local imageSize = image:GetSize()
local size = Vector2(imageSize.x / imageSize.y, 1) / 2
local uv1, uv2 = image:GetUV()
local sprite = Model.Create({
Vertex(Vector2(-size.x, size.y), Vector2(uv1.x, uv1.y)),
Vertex(Vector2(-size.x,-size.y), Vector2(uv1.x, uv2.y)),
Vertex(Vector2( size.x,-size.y), Vector2(uv2.x, uv2.y)),
Vertex(Vector2( size.x,-size.y), Vector2(uv2.x, uv2.y)),
Vertex(Vector2( size.x, size.y), Vector2(uv2.x, uv1.y)),
Vertex(Vector2(-size.x, size.y), Vector2(uv1.x, uv1.y))
})
sprite:SetTexture(image)
sprite:SetTopology(Topology.TriangleList)
return sprite
end
sprites = {
}
LightsaberColors = { -- Define an easy reference of lightsaber colours
["anakin"] = Color(80, 80, 255), -- keys = filenames
["darth vader"] = Color(255, 25, 25),
["luke skywalker"] = Color(25, 255, 25),
}
ModelData = {
}
lightsabersNeeded = {
}
initiallyLoading = true
function CacheModelData(table, name, player)
ModelData[name] = table
-- If this is part 2 of a request:
if string.find(name, "_hilt") != nil then
for i, v in pairs(lightsabersNeeded) do
lastPlayer = v
end
if player == LocalPlayer then
StartMakingDemands(player, true, true)
else
if lastPlayer == player and initiallyLoading then
initiallyLoading = false
Events:Subscribe("EntitySpawn", ForceSense)
end
ForceSensePart2(player)
end
end
end
function CallbackForChange(table, name, player)
ModelData[name] = table
if string.find(name, "_hilt") != nil then--if it's a secondary request
name = player:GetValue("Jedi")
local model = Model.Create(ModelData[name])
local hilt = Model.Create(ModelData[name .. "_hilt"])
local sprite = sprites[name]
Lightsabers[player:GetId()]:SetModel(
model, sprite
)
Lightsabers[player:GetId()]:SetHilt(
hilt
)
Lightsabers[player:GetId()]:SetLightColor(
LightsaberColors[name]
)
end
end
function ModulesLoad()
if IsValid(LocalPlayer) then
pValue = LocalPlayer:GetValue("HasLightsaber") or false
if pValue then
RequestModelData(LocalPlayer:GetValue("Jedi") or "anakin", LocalPlayer) -- LocalPlayer first and foremost
else
StartMakingDemands(LocalPlayer, true, false)
end
end
Events:Subscribe("Render", MoveLightsabers) -- Once everything is initialized, start fixing the lightsabers to bones
Events:Subscribe("PreTick", MoveLightsabers) -- Subscribing to three events ensures that they don't drift about at high speeds
Events:Subscribe("PostTick", MoveLightsabers)
Events:Subscribe("NetworkObjectValueChange", DetectLightsaberChange)
end
function StartMakingDemands(p, initial, makeForLP) -- For localplayer
initial = initial or true
p = p or LocalPlayer -- weird shit happens
if makeForLP then
pValue = p:GetValue("Jedi")
if Lightsabers[p:GetId()] then return end
Lightsabers[p:GetId()] = Lightsaber(
Model.Create(ModelData[pValue]),
LightsaberColors[pValue],
pValue,
p,
Model.Create(ModelData[pValue .. "_hilt"]),
sprites[pValue]
)
if p:GetValue("ScaleUnfucked") != nil then Lightsabers[p:GetId()]:UnfuckScale() end
end
if initial then MakeDemands() end
end
function MakeDemands() -- Find out how many lightsabers we initially need
for p in Client:GetPlayers() do
if Lightsabers[p:GetId()] then return end
if p:GetValue("HasLightsaber") then
if lightsabersNeeded[p:GetValue("Jedi")] == nil then
lightsabersNeeded[p:GetValue("Jedi")] = p
end
end
end
for i, v in pairs(lightsabersNeeded) do
RequestModelData(i, v)
end
end
Network:Subscribe("BEGIN", ModulesLoad)
function ForceSense(args)
if args.entity.__type != "Player" then return end
if not args.entity:GetValue("HasLightsaber") then return end
local p = args.entity
if Lightsabers[p:GetId()] != nil then return end -- if they already have a lightsaber from a previous encounter
pValue = p:GetValue("Jedi") or "anakin"
if ModelData[pValue] and ModelData[pValue .. "_hilt"] and sprites[pValue] then
Lightsabers[p:GetId()] = Lightsaber(
Model.Create(ModelData[pValue]),
LightsaberColors[pValue],
pValue,
p,
Model.Create(ModelData[pValue .. "_hilt"]),
sprites[pValue]
)
else
RequestModelData(pValue, p)
end
end
Events:Subscribe("EntitySpawn", ForceSense)
function ucantcme(args)
if args.entity.__type == "Player" then
if args.entity:GetValue("HasLightsaber") then
if Lightsabers[args.entity:GetId()] then
Lightsabers[args.entity:GetId()].model = nil
Lightsabers[args.entity:GetId()].sprite = nil
Lightsabers[args.entity:GetId()].hilt = nil
Lightsabers[args.entity:GetId()]:Remove()
Lightsabers[args.entity:GetId()] = nil
end
end
end
end
Events:Subscribe("EntityDespawn", ucantcme)
function ForceSensePart2(p)
if p == LocalPlayer then return end -- localplayer has a seperate function
if not IsValid(p) then return end
if Lightsabers[p:GetId()] then return end -- no duplicates
pValue = p:GetValue("Jedi")
Lightsabers[p:GetId()] = Lightsaber(
Model.Create(ModelData[pValue]),
LightsaberColors[pValue],
pValue,
p,
Model.Create(ModelData[pValue .. "_hilt"]),
sprites[pValue]
)
end
function RequestModelData(name, p, callback)
if not IsValid(p) then return end
if Lightsabers[p:GetId()] then
if Lightsabers[p:GetId()].name == name then return end
end
callback = callback or CacheModelData
if ModelData[name] == nil then
OBJLoader.Request({path = name}, p, callback)
else
callback(ModelData[name], name, p)
end
if ModelData[name .. "_hilt"] == nil then
OBJLoader.Request({path = name .. "_hilt"}, p, callback)
else
callback(ModelData[name .. "_hilt"], name .. "_hilt", p)
end
sprites[name] = CreateSprite(Image.Create(AssetLocation.Resource, name))
end
function DetectLightsaberChange(args)
if IsValid(args.object) then
if args.object.__type == "Player" or args.object.__type == "LocalPlayer" then -- If network value change was on a Player object...
if args.key == "Jedi" then -- If it concerns our script#
if ModelData[args.value] and ModelData[args.value .. "_hilt"] and sprites[args.value] then
local model = Model.Create(ModelData[args.value])
local hilt = Model.Create(ModelData[args.value .. "_hilt"])
local sprite = sprites[args.value]
model:SetTopology(Topology.TriangleList)
hilt:SetTopology(Topology.TriangleList)
Lightsabers[args.object:GetId()]:SetModel(
model, sprite
)
Lightsabers[args.object:GetId()]:SetHilt(
hilt
)
Lightsabers[args.object:GetId()]:SetLightColor(
LightsaberColors[args.value])
else
RequestModelData(args.value, args.object, CallbackForChange)
end
elseif args.key == "HasLightsaber" then
if args.value then
pValue = args.object:GetValue("Jedi")
if ModelData[pValue] and ModelData[pValue .. "_hilt"] and sprites[pValue] then
Lightsabers[args.object:GetId()] = Lightsaber(
Model.Create(ModelData[pValue]),
LightsaberColors[pValue],
pValue,
args.object,
Model.Create(ModelData[pValue .. "_hilt"]),
sprites[pValue]
)
else
RequestModelData(pValue, args.object, CacheModelData)
end
else
if Lightsabers[args.object:GetId()] then
Lightsabers[args.object:GetId()]:Remove()
Lightsabers[args.object:GetId()].model = nil
Lightsabers[args.object:GetId()].sprite = nil
Lightsabers[args.object:GetId()].hilt = nil
Lightsabers[args.object:GetId()]:Remove()
Lightsabers[args.object:GetId()] = nil
end
end
end
end
end
end
function MoveLightsabers()
for p in Client:GetPlayers() do
if Lightsabers[p:GetId()] then
Lightsabers[p:GetId()]:SetPosition(p:GetBonePosition("ragdoll_LeftHand")) -- Set to hand every frame
Lightsabers[p:GetId()]:SetAngle(p:GetBoneAngle("ragdoll_LeftHand"))
Lightsabers[p:GetId()]:SetPosition_s(p:GetBonePosition("ragdoll_LeftUpLeg")) -- Set to hip every frame
Lightsabers[p:GetId()]:SetAngle_s(p:GetBoneAngle("ragdoll_LeftUpLeg"))
end
end
if Lightsabers[LocalPlayer:GetId()] then
Lightsabers[LocalPlayer:GetId()]:SetPosition(LocalPlayer:GetBonePosition("ragdoll_LeftHand"))
Lightsabers[LocalPlayer:GetId()]:SetAngle(LocalPlayer:GetBoneAngle("ragdoll_LeftHand")) -- Again, Client:GetPlayers() does not include LocalPlayer
Lightsabers[LocalPlayer:GetId()]:SetPosition_s(LocalPlayer:GetBonePosition("ragdoll_LeftUpLeg"))
Lightsabers[LocalPlayer:GetId()]:SetAngle_s(LocalPlayer:GetBoneAngle("ragdoll_LeftUpLeg"))
end
end
function DeleteLightsaberQuit(args)
if Lightsabers[args.player:GetId()] then
Lightsabers[args.player:GetId()]:Remove()
end
end
Events:Subscribe("PlayerQuit", DeleteLightsaberQuit)
function SheathUnsheathKeys(args)
if LocalPlayer:GetValue("HasLightsaber") then
if args.key == string.byte("G") and not LocalPlayer:InVehicle() then
Network:Send("KeyPressSheath", not LocalPlayer:GetValue("sheathed"))
end
end
end
Events:Subscribe("KeyUp", SheathUnsheathKeys)
function ForceSheath() -- use the force, heh
if LocalPlayer:GetValue("HasLightsaber") then
if LocalPlayer:InVehicle() then
Network:Send("KeyPressSheath", true) -- It looks really weird if you have a lightsaber out while flying a plane. And it's irresponsible.
end
end
end
Events:Subscribe("PostTick", ForceSheath)
function InputPoll(args)
if not LocalPlayer:GetValue("sheathed") then
Input:SetValue(Action.Kick, Input:GetValue(Action.FireRight))
Input:SetValue(Action.FireRight, 0)
end
end
Events:Subscribe("InputPoll", InputPoll)
|
local iter = function(state, cur)
local ret
if cur == nil then
ret = state[1] -- 起点
else
ret = cur + (state[3] and state[3] or 1) -- 有步长加步长没步长加1
end
if ret > state[2] then
ret = nil -- 超出终点
end
return ret
end
local fromto = function(n, m, p) -- 左边界n,右边界m,步长p
local state = {n, m, p}
return iter, state, nil -- 返回迭代器iter, 不可变状态,控制变量
end
for i in fromto(1, 5, 2) do
print(i)
end
|
--[[
Based on code from:
http://www.redblobgames.com/pathfinding/a-star/introduction.html
http://www.redblobgames.com/pathfinding/a-star/implementation.html
Depends on a Graph class, providing the following methods:
getNeighbours( node ): return a list of neighbouring points
getCost( from_node, to_node ): return the actual cost of moving from first node to second
getHeuristic( from_node, goal ): return an estimate of cost to goal.
]]
local PathFinder = {}
-- get the folder that we're in.
local IRO_PATH = (...):match("(.+)%.[^%.]+$") or (...)
local PriorityQueue = require( IRO_PATH .. '.priorityqueue' )
function PathFinder:new( ... )
local instance = {}
setmetatable( instance, self )
self.__index = self
self._init( instance, ... )
return instance
end
function PathFinder:_init( graph )
self.graph = graph
end
function PathFinder:getKey( point )
return point[ 1 ] .. ":" .. point[ 2 ]
end
function PathFinder:astarSearch( start, goal )
local frontier = PriorityQueue:new( function( a, b ) return a > b end )
local came_from = {}
local cost_so_far = {}
local start_key = self:getKey( start )
frontier:push( start, 0 )
cost_so_far[ start_key ] = 0 -- cost for going from start to start is 0
while not frontier:isEmpty() do
local current = frontier:pop() -- get node with lowest score
local current_key = self:getKey( current )
local current_cost = cost_so_far[ current_key ]
-- got there. quit trying
if current[ 1 ] == goal[ 1 ] and current[ 2 ] == goal[ 2 ] then
break
end
local neighbours = self.graph:getNeighbours( current )
for _, neighbour in ipairs( neighbours ) do
local neighbour_key = self:getKey( neighbour )
local new_cost = current_cost + self.graph:getCost( current, neighbour )
-- no cost yet, or cost is cheaper than previous best
if not cost_so_far[ neighbour_key ] or new_cost < cost_so_far[ neighbour_key ] then
cost_so_far[ neighbour_key ] = new_cost
local h = self.graph:getHeuristic( neighbour, goal )
local priority = new_cost + h
frontier:push( neighbour, priority )
came_from[ neighbour_key ] = current
end
end
end
return came_from, cost_so_far
end
-- return the path
function PathFinder:reconstructPath( came_from, goal )
local current = goal
local back_path = { current }
while current do
-- advance a step
local current_key = self:getKey( current )
current = came_from[ current_key ]
table.insert( back_path, current )
end
-- reverse that path so it goes from start to end.
local path = {}
for i, node in ipairs( back_path ) do
path[ #back_path - i + 1 ] = node
end
return path
end
-- the meat and potatoes function! Call this one.
function PathFinder:getPath( start, goal )
local came_from, costs = self:astarSearch( start, goal )
local path = self:reconstructPath( came_from, goal )
local start_key = self:getKey( start )
local total_cost = costs[ start_key ]
return path, total_cost
end
return PathFinder
|
local vim = vim
local M = {}
function M.is_buf_attached_to_lsp(bufnr)
local clients = vim.lsp.buf_get_clients(bufnr or 0)
return clients ~= nil and #clients > 0
end
function M.is_buf_markdown(bufnr)
return vim.api.nvim_buf_get_option(bufnr, 'ft') == 'markdown'
end
---@param bufnr number
---@return boolean
function M.should_not_refresh(bufnr)
if (not M.is_buf_markdown(bufnr)) and (not M.is_buf_attached_to_lsp(bufnr)) then
return true
end
return false
end
return M
|
workspace "SchoolProject"
architecture "x64"
configurations {"Debug", "Release"}
systemversion "latest"
project "SchoolProject"
location "SchoolProject"
files {"%{prj.location}/**.cpp", "%{prj.location}/**.h","%{prj.location}/**.hlsl", "%{prj.location}/**.hlsli"}
kind "WindowedApp"
language "C++"
cppdialect "C++14"
targetdir "bin/%{cfg.buildcfg}"
objdir "objects/%{cfg.buildcfg}"
includedirs{"DirectXTK/include/"}
links{
"d3d11",
}
vpaths{["Shaders"] = "**.hlsl", ["Headers"] = "**.h", ["Sources"] = {"**.c", "**.cpp"}, ["Buffers"] = {"**Buffer"}, ["PreCompiledHeaders"] = "**pch", ["Main"] = "**main.cpp", ["ECS"] = {"**Component", "**System","**Factory","**ECS"}, ["Core"] = {"**Render","**Core"},["imGUI"] = {"**imgui","**imstb","**imconfig"}}
filter "configurations:Debug"
libdirs{"DirectXTK/bin/x64/Debug_lib/"}
links{"DirectXTK"}
defines{"_DEBUG", "_UNICODE", "UNICODE"}
symbols "On"
filter "configurations:Release"
libdirs{"DirectXTK/bin/x64/Release_lib/"}
links{"DirectXTK"}
defines{"NDEBUG", "_UNICODE", "UNICODE"}
optimize "On"
filter "*"
local ws = "$(ProjectDir)%%(Filename).cso"
files("*.hlsl")
shadermodel("5.0")
shaderobjectfileoutput(ws)
filter("files:**_vs.hlsl")
shadertype("Vertex")
filter("files:**_ps.hlsl")
shadertype("Pixel")
filter("files:**_gs.hlsl")
shadertype("Geometry")
filter("files:**_cs.hlsl")
shadertype("Compute")
|
local FriendUtils = {
getOnlineFriendsList = require(script.getOnlineFriendsList),
getFriendsList = require(script.getFriendsList),
}
table.freeze(FriendUtils)
return FriendUtils
|
---@class UnityEngine.Behaviour : UnityEngine.Component
---@field enabled bool
---@field isActiveAndEnabled bool
local m = {}
UnityEngine = {}
UnityEngine.Behaviour = m
return m
|
-- this file is generated by xresloader, please don't edit it.
return {
[1] = {
count = 4,
data_source = {
{
file = "./资源转换示例.xlsx",
sheet = "keep_or_strip_empty_list",
},
},
data_ver = "1.0.0.0",
hash_code = "sha256:bef5c76679b43b65aec7906f42010530fadae99f0e386d94e3a77e94a7d12e8e",
xres_ver = "2.11.0-rc2",
},
[2] = "keep_or_strip_empty_list_cfg",
keep_or_strip_empty_list_cfg = {
{
array_int32 = {
711,
712,
713,
},
array_int64 = {
811,
812,
813,
},
array_msg = {
{
id = 511,
level = "L-511",
},
{
id = 512,
level = "L-512",
},
{
id = 513,
level = "L-513",
},
},
array_plain_msg = {
{
id = 611,
level = "L-611",
},
{
id = 612,
level = "L-612",
},
{
id = 613,
level = "L-613",
},
},
id = 50001,
},
{
array_int32 = {
721,
722,
},
array_int64 = {
821,
822,
},
array_msg = {
{
id = 521,
level = "L-521",
},
{
id = 522,
level = "L-522",
},
},
array_plain_msg = {
{
id = 621,
level = "L-621",
},
{
id = 622,
level = "L-622",
},
},
id = 50002,
},
{
array_int32 = {
0,
732,
733,
},
array_int64 = {
0,
832,
833,
},
array_msg = {
{
},
{
id = 532,
level = "L-532",
},
{
id = 533,
level = "L-533",
},
},
array_plain_msg = {
{
},
{
id = 632,
level = "L-632",
},
{
id = 633,
level = "L-633",
},
},
id = 50003,
},
{
array_int32 = {
741,
0,
743,
},
array_int64 = {
841,
0,
843,
},
array_msg = {
{
id = 541,
level = "L-541",
},
{
},
{
id = 543,
level = "L-543",
},
},
array_plain_msg = {
{
id = 641,
level = "L-641",
},
{
},
{
id = 643,
level = "L-643",
},
},
id = 50004,
},
},
}
|
-- (c)ontrolled player
e.cplayer = {
"position", "size", "player", "sprite", "controller", "pointer", "hearts"
}
s.cplayer = {"position", "size", "pointer", "hearts", "player", "controller"}
s.cplayer.update = function(i, position, size, pointer, hearts, player)
move_camera(position.x, position.y)
local x, y = game.input:get("move")
if x ~= 0 or y ~= 0 then
game.queue[#game.queue + 1] = {type = 'move', x = x, y = y}
game.audio.move[love.math.random(#game.audio.move)]:play()
end
local mx, my = game.camera:mousePosition()
local cx, cy = position.x + size.w / 2, position.y + size.h / 2
pointer.angle = math.atan2(my - cy, mx - cx)
if game.input:pressed("punch") then
local dx = math.cos(pointer.angle) * 16
local dy = math.sin(pointer.angle) * 16
game.queue[#game.queue + 1] = {
type = 'punch',
dx = dx,
dy = dy,
angle = pointer.angle
}
e.punch({
position = {
x = position.x + size.w / 2,
y = position.y + size.h / 2
},
size = {w = 16, h = 16},
punch = {angle = pointer.angle, scale = 1}
})
game.audio.woosh[love.math.random(#game.audio.woosh)]:play()
end
if game.hit then game.hit = false end
end
function move_camera(x, y)
local speed = 10
local radius_to_player = 0
local cx, cy = game.camera.x, game.camera.y
if math.distance(x, y, cx, y) > radius_to_player then
cx = math.cerp(cx, x, game.dt * speed)
cy = math.cerp(cy, y, game.dt * speed)
end
game.camera.x, game.camera.y = cx, cy
end
|
---@class mx.symbol.symbol
local M = {}
local ctypes = require('ctypes')
local AttrScope = require('mx.attribute').AttrScope
local base = require('mx.base')
local _LIB, numeric_types, c_array, c_array_buf, c_str, c_str_array, c_handle_array
, mx_uint, py_str, string_types, integer_types, mx_int
, NDArrayHandle, ExecutorHandle, SymbolHandle
, check_call, MXNetError, NotImplementedForSymbol = base._LIB, base.numeric_types, base.c_array, base.c_array_buf, base.c_str, base.c_str_array, base.c_handle_array
, base.mx_uint, base.py_str, base.string_types, base.integer_types, base.mx_int
, base.NDArrayHandle, base.ExecutorHandle, base.SymbolHandle
, base.check_call, base.MXNetError, base.NotImplementedForSymbol
local Context, current_context = require('mx.context').Context, require('mx.context').current_context
local __nd = require('mx.ndarray.__init__')
local NDArray, _DTYPE_NP_TO_MX, _DTYPE_MX_TO_NP, _GRAD_REQ_MAP, _ndarray_cls = __nd.NDArray, __nd._DTYPE_NP_TO_MX, __nd._DTYPE_MX_TO_NP, __nd._GRAD_REQ_MAP, __nd._ndarray_cls
local _STORAGE_TYPE_STR_TO_ID = require('mx.ndarray.ndarray')._STORAGE_TYPE_STR_TO_ID
local Executor = require('mx.executor').Executor
local _internal = require('mx.symbol._internal')
local op = require('mx.symbol.op')
local SymbolBase, _set_symbol_class = _internal.SymbolBase, _internal._set_symbol_class
local is_np_shape = require('mx.util').is_np_shape
---@class mx.symbol.Symbol:mx._ctypes.symbol.SymbolBase
---@field name string
local Symbol = class('mx.symbol.Symbol', SymbolBase)
M.Symbol = Symbol
function Symbol:__tostring()
local name = self.name
if isnone(name) then
name = {}
for i in self:__iter() do
table.insert(name, i.name)
end
name = table.concat(name, ', ')
return ('<%s group [%s]>'):format('Symbol', name)
else
return ('<%s %s>'):format('Symbol', name)
end
end
function Symbol:__iter()
local sz = #self
local function f(t, i)
i = i + 1
if i >= sz then
return
end
return self:__getitem(i)
end
return f, self, -1
end
local function _op_helper(lhs, rhs, f1, f2, f3)
if isinstance(lhs, Symbol) then
if isinstance(rhs, Symbol) then
return f1(lhs, rhs)
elseif type(rhs) == 'number' then
return f2(lhs, rhs)
else
raise('TypeError', ('type %s not supported'):format(gettypename(rhs)))
end
else
if type(lhs) == 'number' then
return f3(rhs, lhs)
else
raise('TypeError', ('type %s not supported'):format(gettypename(lhs)))
end
end
end
function Symbol:__add(other)
return _op_helper(self, other, _internal._Plus, _internal._PlusScalar, Symbol.__add)
end
function Symbol:__bool()
raise('NotImplementedForSymbol')
end
function Symbol:iadd(other)
raise('NotImplementedForSymbol')
end
function Symbol:__sub(other)
return _op_helper(self, other, _internal._Minus, _internal._MinusScalar, _internal._RMinusScalar)
end
function Symbol:isub(other)
raise('NotImplementedForSymbol')
end
function Symbol:__mul(other)
return _op_helper(self, other, _internal._Mul, _internal._MulScalar, Symbol.__mul)
end
function Symbol:imul(other)
raise('NotImplementedForSymbol')
end
function Symbol:__div(other)
return _op_helper(self, other, _internal._Div, _internal._DivScalar, _internal._RDivScalar)
end
function Symbol:idiv(other)
raise('NotImplementedForSymbol')
end
function Symbol:__mod(other)
return _op_helper(self, other, _internal._Mod, _internal._ModScalar, _internal._RModScalar)
end
function Symbol:__pow(other)
return _op_helper(self, other, _internal._Power, _internal._PowerScalar, _internal._RPowerScalar)
end
function Symbol:__unm()
return self:__mul(-1.0)
end
function Symbol:__copy()
return self:__deepcopy()
end
function Symbol:__deepcopy()
local handle = SymbolHandle()
check_call(_LIB.MXSymbolCopy(self.handle,
ctypes.byref(handle)))
return Symbol(handle)
end
local function _cmp_helper(lhs, rhs, f1, f2)
if isinstance(rhs, Symbol) then
return f1(lhs, rhs)
elseif type(rhs) == 'number' then
return f2(lhs, rhs)
else
raise('TypeError', ('type %s not supported'):format(gettypename(rhs)))
end
end
function Symbol:eq(other)
return _cmp_helper(self, other, _internal._equal, _internal._equal_scalar)
end
function Symbol:ne(other)
return _cmp_helper(self, other, _internal._not_equal, _internal._not_equal_scalar)
end
function Symbol:gt(other)
return _cmp_helper(self, other, _internal._greater, _internal._greater_scalar)
end
function Symbol:ge(other)
return _cmp_helper(self, other, _internal._greater_equal, _internal._greater_equal_scalar)
end
function Symbol:lt(other)
return _cmp_helper(self, other, _internal._lesser, _internal._lesser_scalar)
end
function Symbol:le(other)
return _cmp_helper(self, other, _internal._lesser_equal, _internal._lesser_equal_scalar)
end
function Symbol:__getstate()
if not isnone(self.handle) then
return { handle = self:tojson() }
else
return { handle = None }
end
end
function Symbol:__setstate(state)
local handle = state.handle
if not isnone(handle) then
local json_str = handle
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
self.handle = handle
else
self.handle = None
end
end
function Symbol:__call(...)
local s = self:__copy()
s:_compose(...)
return s
end
function Symbol:_compose(...)
local args, kwargs = arg_kw(...)
local name = arg_pop(kwargs, 'name', None)
if name then
name = c_str(name)
end
if #args ~= 0 and not table.empty(kwargs) then
raise('TypeError', 'compose only accept input Symbols either as positional or keyword arguments, not both')
end
for i, arg in ipairs(args) do
if not isinstance(arg, Symbol) then
raise('TypeError', ('Compose expect `Symbol` as arguments, but got `%s` at %d'):format(gettypename(arg, i)))
end
end
for k, val in pairs(kwargs) do
if not isinstance(val, Symbol) then
raise('TypeError', ('Compose expect `Symbol` as arguments, but got `%s` at `%s`'):format(gettypename(val), k))
end
end
local num_args = len(args) + table.len(kwargs)
local keys
if not table.empty(kwargs) then
keys = c_str_array(table.keys(kwargs))
args = c_handle_array(table.values(kwargs))
else
keys = None
args = c_handle_array(table.values(kwargs))
end
check_call(_LIB.NNSymbolCompose(
self.handle, name, num_args, keys, args))
end
function Symbol:__getitem(index)
local output_count = #self
if islist(index) then
local start, stop, step = index[1] or 0, index[2] or output_count, index[3] or 1
local function f(i)
return self[i]
end
return M.Group(table.arange(f, start, stop - 1, step))
end
if type(index) == 'string' then
local output_names = self:list_outputs()
local idx
for i, name in ipairs(output_names) do
if name == index then
if idx then
raise('ValueError', 'There are multiple outputs with name ' .. index)
end
idx = i - 1
end
end
if not idx then
raise('ValueError', 'Cannot find output that matches name ' .. index)
end
index = idx
end
if type(index) ~= 'number' then
raise('TypeError', 'Symbol only support integer index to fetch i-th output')
end
if index >= output_count then
raise('IndexError')
end
local handle = SymbolHandle()
check_call(_LIB.MXSymbolGetOutput(
self.handle, mx_uint(index), ctypes.byref(handle)))
return Symbol(handle)
end
function Symbol:_name()
local ret = ctypes.c_char_p()
local success = ctypes.c_int()
check_call(_LIB.MXSymbolGetName(
self.handle, ctypes.byref(ret), ctypes.byref(success)))
if success.value ~= 0 then
return py_str(ret.value)
else
return None
end
end
function Symbol:attr(key)
local ret = ctypes.c_char_p()
local success = ctypes.c_int()
check_call(_LIB.MXSymbolGetAttr(
self.handle, ctypes.byref(ret), ctypes.byref(success)))
if success.value ~= 0 then
return py_str(ret.value)
else
return None
end
end
function Symbol:list_attr(recursive)
recursive = default(recursive, false)
if recursive then
raise('DeprecationWarning', 'Please use attr_dict instead')
end
local size = mx_uint()
local pairs = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListAttrShallow(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
local ret = {}
for i = 0, size.value - 1 do
ret[py_str(pairs[i * 2])] = py_str(pairs[i * 2 + 1])
end
return ret
end
function Symbol:attr_dict()
local size = mx_uint()
local pairs = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListAttr(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
local ret = {}
for i = 0, size.value - 1 do
local name, key = unpack(py_str(pairs[i * 2]):split('$'))
local val = py_str(pairs[i * 2 + 1])
if not ret[name] then
ret[name] = {}
end
ret[name][key] = val
end
return ret
end
function Symbol:_set_attr(kwargs)
for key, value in pairs(kwargs) do
if type(value) ~= 'string' then
raise('ValueError', 'Set Attr only accepts string values')
end
check_call(_LIB.MXSymbolSetAttr(
self.handle, c_str(key), c_str(value)))
end
end
function Symbol:get_internals()
local handle = SymbolHandle()
check_call(_LIB.MXSymbolGetInternals(
self.handle, ctypes.byref(handle)))
return Symbol(handle)
end
function Symbol:get_children()
local handle = SymbolHandle()
check_call(_LIB.MXSymbolGetChildren(
self.handle, ctypes.byref(handle)))
local ret = Symbol(handle)
if #ret:list_outputs() == 0 then
return None
end
return ret
end
local function _list_helper(hdl, f)
local size = ctypes.c_uint()
local sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(f(
hdl, ctypes.byref(size), ctypes.byref(sarr)))
return table.arange(function(i)
return py_str(sarr[i - 1])
end, size.value)
end
function Symbol:list_arguments()
return _list_helper(self.handle, _LIB.MXSymbolListArguments)
end
function Symbol:list_outputs()
return _list_helper(self.handle, _LIB.MXSymbolListOutputs)
end
function Symbol:__len()
local output_count = mx_uint()
check_call(_LIB.MXSymbolGetNumOutputs(self.handle, ctypes.byref(output_count)))
return tonumber(output_count.value)
end
function Symbol:list_auxiliary_states()
return _list_helper(self.handle, _LIB.MXSymbolListAuxiliaryStates)
end
function Symbol:list_inputs()
local size = ctypes.c_uint()
local sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.NNSymbolListInputNames(
self.handle, 0, ctypes.byref(size), ctypes.byref(sarr)))
return table.arange(function(i)
return py_str(sarr[i - 1])
end, size.value)
end
function Symbol:infer_type(...)
local try = function(...)
local res = self:_infer_type_impl(false, ...)
if isnone(res[2]) then
local arg_types = self:_infer_type_impl(true, ...)[1]
local arg_names = self:list_arguments()
local unknowns = {}
for i = 1, #arg_names do
local name, dtype = arg_names[i], arg_types[i]
if not dtype then
if #unknowns > 10 then
table.insert(unknowns, '...')
break
end
table.insert(unknowns, ('%s: %s'):format(name, tostring(dtype)))
end
end
print('Cannot decide type for the following arguments.',
'Consider providing them as input:\n\t',
table.concat(unknowns, '\n\t'))
end
return res
end
local ok, ret = pcall(try, ...)
if ok then
return unpack(ret)
else
local args, kwargs = arg_kw(...)
print("infer_type error. Arguments:")
for i, arg in ipairs(args) do
print((' #%d: %s'):format(i, tostring(arg)))
end
for k, v in pairs(kwargs) do
print((' %s: %s'):format(k, tostring(v)))
end
raise()
end
end
function Symbol:infer_type_partial(...)
return unpack(self:_infer_type_impl(true, ...))
end
function Symbol:_infer_type_impl(partial, ...)
local args, kwargs = arg_kw(...)
if #args ~= 0 and not table.empty(kwargs) then
raise('ValueError', 'Can only specify known argument types either by positional or kwargs way.')
end
local sdata = {}
local keys
if #args ~= 0 then
keys = c_array(ctypes.c_char_p, {})
for _, s in ipairs(args) do
if not isnone(s) then
s = _DTYPE_NP_TO_MX[s]
if not s then
raise('TypeError')
end
table.insert(sdata, s)
else
table.insert(sdata, -1)
end
end
else
local str_keys = {}
for k, v in pairs(kwargs) do
if _DTYPE_NP_TO_MX[v] then
table.insert(str_keys, k)
table.insert(sdata, _DTYPE_NP_TO_MX[v])
end
end
keys = c_str_array(str_keys)
end
local arg_type_size = mx_uint()
local arg_type_data = ctypes.POINTER(ctypes.c_int)()
local out_type_size = mx_uint()
local out_type_data = ctypes.POINTER(ctypes.c_int)()
local aux_type_size = mx_uint()
local aux_type_data = ctypes.POINTER(ctypes.c_int)()
local complete = ctypes.c_int()
local infer_func = partial and _LIB.MXSymbolInferTypePartial or _LIB.MXSymbolInferType
check_call(infer_func(
self.handle,
mx_uint(len(sdata)),
keys,
c_array_buf(ctypes.c_int, sdata),
ctypes.byref(arg_type_size),
ctypes.byref(arg_type_data),
ctypes.byref(out_type_size),
ctypes.byref(out_type_data),
ctypes.byref(aux_type_size),
ctypes.byref(aux_type_data),
ctypes.byref(complete)))
if complete.value ~= 0 then
local arg_types = table.arange(function(i)
return _DTYPE_MX_TO_NP[tonumber(arg_type_data[i - 1])]
end, arg_type_size.value)
local out_types = table.arange(function(i)
return _DTYPE_MX_TO_NP[tonumber(out_type_data[i - 1])]
end, out_type_size.value)
local aux_types = table.arange(function(i)
return _DTYPE_MX_TO_NP[tonumber(aux_type_data[i - 1])]
end, aux_type_size.value)
return { arg_types, out_types, aux_types }
else
return { None, None, None }
end
end
function Symbol:infer_shape(...)
local try = function(...)
local res = self:_infer_shape_impl(false, ...)
if isnone(res[2]) then
local arg_shapes = self:_infer_shape_impl(true, ...)[1]
local arg_names = self:list_arguments()
local unknowns = {}
for i = 1, #arg_names do
local name, shape = arg_names[i], arg_shapes[i]
local shape_is_none = isnone(shape)
if not shape_is_none then
if is_np_shape() then
shape_is_none = table.has_value(shape, -1)
else
shape_is_none = table.has_value(shape, 0)
end
end
if shape_is_none then
if #unknowns > 10 then
table.insert(unknowns, '...')
break
end
table.insert(unknowns, ('%s: %s'):format(name, base.tostring(shape)))
end
end
print('Cannot decide shape for the following arguments ',
'(0s in shape means unknown dimensions).',
'Consider providing them as input:\n\t',
table.concat(unknowns, '\n\t'))
end
return res
end
local ok, ret = pcall(try, ...)
if ok then
return unpack(ret)
else
local args, kwargs = arg_kw(...)
print("infer_shape error. Arguments:")
for i, arg in ipairs(args) do
print((' #%d: %s'):format(i, tostring(arg)))
end
for k, v in pairs(kwargs) do
print((' %s: %s'):format(k, tostring(v)))
end
raise()
end
end
function Symbol:infer_shape_partial(...)
return unpack(self:_infer_shape_impl(true, ...))
end
function Symbol:_infer_shape_impl(partial, ...)
local args, kwargs = arg_kw(...)
if #args ~= 0 and not table.empty(kwargs) then
raise('ValueError', 'Can only specify known argument types either by positional or kwargs way.')
end
local sdata = {}
local indptr = { 0 }
local keys
if #args ~= 0 then
keys = c_array(ctypes.c_char_p, {})
for _, s in ipairs(args) do
if not isnone(s) then
if not islist(s) then
raise('TypeError', 'Arguments need to be shapes')
end
table.append(sdata, s)
end
table.insert(indptr, #sdata)
end
else
local str_keys = {}
for k, v in pairs(kwargs) do
if not islist(v) then
raise('TypeError', 'Arguments need to be shapes')
end
table.insert(str_keys, k)
table.append(sdata, v)
table.insert(indptr, #sdata)
end
keys = c_str_array(str_keys)
end
local arg_shape_size = mx_uint()
local arg_shape_ndim = ctypes.POINTER(mx_int)()
local arg_shape_data = ctypes.POINTER(ctypes.POINTER(mx_int))()
local out_shape_size = mx_uint()
local out_shape_ndim = ctypes.POINTER(mx_int)()
local out_shape_data = ctypes.POINTER(ctypes.POINTER(mx_int))()
local aux_shape_size = mx_uint()
local aux_shape_ndim = ctypes.POINTER(mx_int)()
local aux_shape_data = ctypes.POINTER(ctypes.POINTER(mx_int))()
local complete = ctypes.c_int()
local infer_func = partial and _LIB.MXSymbolInferShapePartialEx or _LIB.MXSymbolInferShapeEx
check_call(infer_func(
self.handle,
mx_uint(#indptr - 1),
keys,
c_array_buf(mx_uint, indptr),
c_array_buf(mx_int, sdata),
ctypes.byref(arg_shape_size),
ctypes.byref(arg_shape_ndim),
ctypes.byref(arg_shape_data),
ctypes.byref(out_shape_size),
ctypes.byref(out_shape_ndim),
ctypes.byref(out_shape_data),
ctypes.byref(aux_shape_size),
ctypes.byref(aux_shape_ndim),
ctypes.byref(aux_shape_data),
ctypes.byref(complete)))
if complete.value ~= 0 then
local function make(a1, a2, a3)
return table.arange(function(i)
if a2[i - 1] >= 0 then
return table.arange(function(j)
return a1[i - 1][j - 1]
end, a2[i - 1])
else
return None
end
end, a3)
end
local arg_shapes = make(arg_shape_data, arg_shape_ndim, arg_shape_size.value)
local out_shapes = make(out_shape_data, out_shape_ndim, out_shape_size.value)
local aux_shapes = make(aux_shape_data, aux_shape_ndim, aux_shape_size.value)
return { arg_shapes, out_shapes, aux_shapes }
else
return { None, None, None }
end
end
function Symbol:debug_str()
local debug_str = ctypes.c_char_p()
check_call(_LIB.MXSymbolPrint(
self.handle, ctypes.byref(debug_str)))
return py_str(debug_str.value)
end
function Symbol:save(fname, remove_amp_cast)
remove_amp_cast = default(remove_amp_cast, true)
if type(fname) ~= 'string' then
raise('TypeError', 'fname need to be string')
end
if remove_amp_cast then
local handle = SymbolHandle()
check_call(_LIB.MXSymbolRemoveAmpCast(self.handle, ctypes.byref(handle)))
check_call(_LIB.MXSymbolSaveToFile(handle, c_str(fname)))
else
check_call(_LIB.MXSymbolSaveToFile(self.handle, c_str(fname)))
end
end
function Symbol:tojson()
local json_str = ctypes.c_char_p()
check_call(_LIB.MXSymbolSaveToJSON(self.handle, ctypes.byref(json_str)))
return py_str(json_str.value)
end
function Symbol._get_ndarray_inputs(arg_key, args, arg_names, allow_missing)
local arg_handles = {}
local arg_arrays = {}
if #args > 0 then
if #args ~= #arg_names then
raise('ValueError', ('Length of %s does not match the number of arguments'):format(arg_key))
end
for _, narr in ipairs(args) do
if isnone(narr) and allow_missing then
table.insert(arg_handles, None)
elseif not isinstance(narr, NDArray) then
raise('TypeError', 'Only accept list of NDArrays or dict of str to NDArray')
else
table.insert(arg_handles, narr.handle)
end
end
arg_arrays = args
else
for _, name in ipairs(arg_names) do
if args[name] then
local narr = args[name]
if not isinstance(narr, NDArray) then
raise('TypeError', 'Only accept list of NDArrays or dict of str to NDArray')
end
table.insert(arg_handles, narr.handle)
table.insert(arg_arrays, narr.handle)
else
if allow_missing then
table.insert(arg_handles, None)
table.insert(arg_arrays, None)
else
raise('ValueError', ('key %q is missing in %q'):format(name, arg_key))
end
end
end
end
return c_array(NDArrayHandle, arg_handles), arg_arrays
end
function Symbol:_gen_atomic_symbol()
local handle = SymbolHandle()
check_call(_LIB.MXGenAtomicSymbolFromSymbol(self.handle, ctypes.byref(handle)))
return Symbol(handle)
end
function Symbol:simple_bind(ctx, grad_req, type_dict, stype_dict,
group2ctx, shared_arg_names, shared_exec,
shared_buffer, kwargs)
grad_req, kwargs = default(grad_req, 'write', kwargs, {})
-- data types
local num_provided_arg_types = 0
local provided_arg_type_names = ctypes.POINTER(ctypes.c_char_p)() -- provided type argument names
local provided_arg_type_data = ctypes.POINTER(mx_uint)() -- provided types
if not isnone(type_dict) then
provided_arg_type_names = {}
provided_arg_type_data = {}
for k, v in pairs(type_dict) do
if _DTYPE_NP_TO_MX[v] then
table.insert(provided_arg_type_names, k)
table.insert(provided_arg_type_data, _DTYPE_NP_TO_MX[v])
end
end
num_provided_arg_types = mx_uint(#provided_arg_type_names)
provided_arg_type_names = c_str_array(provided_arg_type_names)
provided_arg_type_data = c_array_buf(ctypes.c_int, provided_arg_type_data)
end
-- storage types
local num_provided_arg_stypes = 0
-- provided storage type argument names
local provided_arg_stype_names = ctypes.POINTER(ctypes.c_char_p)()
local provided_arg_stype_data = ctypes.POINTER(mx_uint)() -- provided storage types
if not isnone(stype_dict) then
provided_arg_stype_names = {}
provided_arg_stype_data = {}
for k, v in pairs(stype_dict) do
if _STORAGE_TYPE_STR_TO_ID[v] then
table.insert(provided_arg_stype_names, k)
table.insert(provided_arg_stype_data, _STORAGE_TYPE_STR_TO_ID[v])
end
end
num_provided_arg_stypes = mx_uint(#provided_arg_stype_names)
provided_arg_stype_names = c_str_array(provided_arg_stype_names)
provided_arg_stype_data = c_array_buf(ctypes.c_int, provided_arg_stype_data)
end
local provided_arg_shape_data = {} -- shape data
-- argument shape index in sdata,
-- e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg
local provided_arg_shape_idx = { 0 }
local provided_arg_shape_names = {} -- provided argument names
for k, v in pairs(kwargs) do
-- if k not in listed_arguments and k not in listed_aux_states:
-- raise ValueError('arg name %s is not valid', k)
if islist(v) then
table.insert(provided_arg_shape_names, k)
table.append(provided_arg_shape_data, v)
table.insert(provided_arg_shape_idx, #provided_arg_shape_data)
end
end
local provided_req_type_list_len = 0
local provided_grad_req_types = ctypes.POINTER(ctypes.c_char_p)()
local provided_grad_req_names = ctypes.POINTER(ctypes.c_char_p)()
if not isnone(grad_req) then
if type(grad_req) == 'string' then
-- use provided_req_type_list_len = 0 to indicate this situation
provided_req_type_list_len = 0
provided_grad_req_types = { grad_req }
elseif #grad_req > 0 then
provided_grad_req_types = grad_req
provided_req_type_list_len = #grad_req
else
if table.empty(grad_req) then
raise('RuntimeError', 'grad_req in simple_bind cannot be empty')
end
provided_grad_req_names = {}
provided_grad_req_types = {}
for k, v in pairs(grad_req) do
table.insert(provided_grad_req_names, k)
table.append(provided_grad_req_types, v)
end
provided_grad_req_names = c_str_array(provided_grad_req_names)
provided_req_type_list_len = #provided_grad_req_types
end
provided_grad_req_types = c_str_array(provided_grad_req_types)
end
local num_ctx_map_keys = mx_uint(0)
local ctx_map_keys = ctypes.POINTER(ctypes.c_char_p)()
local ctx_map_dev_types = ctypes.POINTER(ctypes.c_int)()
local ctx_map_dev_ids = ctypes.POINTER(ctypes.c_int)()
if not isnone(group2ctx) then
ctx_map_keys = {}
ctx_map_dev_types = {}
ctx_map_dev_ids = {}
for k, v in pairs(group2ctx) do
table.insert(ctx_map_keys, k)
table.insert(ctx_map_dev_types, v.device_typeid)
table.insert(ctx_map_dev_ids, v.device_id)
end
num_ctx_map_keys = mx_uint(#ctx_map_keys)
ctx_map_keys = c_str_array(ctx_map_keys)
ctx_map_dev_types = c_array(ctypes.c_int, ctx_map_dev_types)
ctx_map_dev_ids = c_array(ctypes.c_int, ctx_map_dev_ids)
end
-- prepare param names
local shared_arg_name_list = {}
if not isnone(shared_arg_names) then
if not islist(shared_arg_names) then
raise('ValueError', 'shared_arg_names in simple_bind must be a list or None')
end
shared_arg_name_list = shared_arg_names
end
-- prepare shared_buffer
local shared_buffer_len, shared_buffer_names, shared_buffer_handles
if isnone(shared_buffer) then
shared_buffer_len = ctypes.c_int(-1)
shared_buffer_names = ctypes.POINTER(ctypes.c_char_p)()
shared_buffer_handles = ctypes.POINTER(NDArrayHandle)()
else
if type(shared_buffer) ~= 'table' then
raise('ValueError', 'shared_buffer in simple_bind must be dict or None')
end
local buffer_names, buffer_arrays = table.kv(shared_buffer)
for _, v in ipairs(buffer_arrays) do
assert(v.stype == 'default',
'shared_buffer is expected to only contain NDArrays with default storage')
end
shared_buffer_names = c_str_array(buffer_names)
shared_buffer_len = ctypes.c_int(#buffer_arrays)
shared_buffer_handles = c_handle_array(buffer_arrays)
end
local updated_shared_buffer_names = ctypes.POINTER(ctypes.c_char_p)()
local updated_shared_buffer_handles = ctypes.POINTER(NDArrayHandle)()
-- prepare shared_exec_handle
local shared_exec_handle = isnone(shared_exec) and ExecutorHandle() or shared_exec.handle
-- prepare current executor handle
local exe_handle = ExecutorHandle()
-- prepare current executor's in_args, arg_grads, and aux_states
local num_in_args = ctypes.c_uint()
local in_arg_handles = ctypes.POINTER(NDArrayHandle)()
local arg_grad_handles = ctypes.POINTER(NDArrayHandle)()
local num_aux_states = ctypes.c_uint()
local aux_state_handles = ctypes.POINTER(NDArrayHandle)()
local try = function()
check_call(_LIB.MXExecutorSimpleBindEx(
self.handle,
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
num_ctx_map_keys,
ctx_map_keys,
ctx_map_dev_types,
ctx_map_dev_ids,
mx_uint(provided_req_type_list_len),
provided_grad_req_names,
provided_grad_req_types,
mx_uint(#provided_arg_shape_names),
c_str_array(provided_arg_shape_names),
c_array_buf(mx_int,
provided_arg_shape_data),
c_array_buf(mx_uint,
provided_arg_shape_idx),
num_provided_arg_types,
provided_arg_type_names,
provided_arg_type_data,
num_provided_arg_stypes,
provided_arg_stype_names,
provided_arg_stype_data,
mx_uint(len(shared_arg_name_list)),
c_str_array(shared_arg_name_list),
ctypes.byref(shared_buffer_len),
shared_buffer_names,
shared_buffer_handles,
ctypes.byref(updated_shared_buffer_names),
ctypes.byref(updated_shared_buffer_handles),
ctypes.byref(num_in_args),
ctypes.byref(in_arg_handles),
ctypes.byref(arg_grad_handles),
ctypes.byref(num_aux_states),
ctypes.byref(aux_state_handles),
shared_exec_handle,
ctypes.byref(exe_handle)))
end
local ok, ret = pcall(try)
if not ok then
local error_msg = ret .. "\nsimple_bind error. Arguments:\n"
for k, v in pairs(kwargs) do
error_msg = error_msg .. ('%s: %s\n'):format(k, tostring(v))
end
raise('RuntimeError', error_msg)
end
-- update shared_buffer
if not isnone(shared_buffer) then
for i = 1, shared_buffer_len.value do
local k = py_str(updated_shared_buffer_names[i - 1])
local v = NDArray(NDArrayHandle(updated_shared_buffer_handles[i - 1]))
shared_buffer[k] = v
end
end
-- create in_args, arg_grads, and aux_states for the current executor
local arg_arrays = table.arange(function(i)
return _ndarray_cls(NDArrayHandle(in_arg_handles[i - 1]))
end, num_in_args.value)
local grad_arrays = table.arange(function(i)
local hdl = arg_grad_handles[i - 1]
if ffi.isnullptr(hdl) then
return None
else
return _ndarray_cls(NDArrayHandle(hdl))
end
end, num_in_args.value)
local aux_arrays = table.arange(function(i)
return _ndarray_cls(NDArrayHandle(aux_state_handles[i - 1]))
end, num_aux_states.value)
local executor = Executor(exe_handle, self, ctx, grad_req, group2ctx)
executor.arg_arrays = arg_arrays
executor.grad_arrays = grad_arrays
executor.aux_arrays = aux_arrays
return executor
end
function Symbol:bind(ctx, args, args_grad, grad_req, aux_states, group2ctx, shared_exec)
grad_req = default(grad_req, 'write')
if not isinstance(ctx, Context) then
raise('TypeError', 'Context type error')
end
local listed_arguments = self:list_arguments()
local args_handle, args_grad_handle
args_handle, args = self:_get_ndarray_inputs('args', args, listed_arguments, false)
-- setup args gradient
if isnone(args_grad) then
args_grad_handle = c_array(NDArrayHandle, table.replicate(None, #args))
else
args_grad_handle, args_grad = self:_get_ndarray_inputs(
'args_grad', args_grad, listed_arguments, true)
end
if isnone(aux_states) then
aux_states = {}
end
local aux_args_handle
aux_args_handle, aux_states = self:_get_ndarray_inputs(
'aux_states', aux_states, self:list_auxiliary_states(), false)
-- setup requirements
local reqs_array
if type(grad_req) == 'string' then
if not _GRAD_REQ_MAP[grad_req] then
raise('ValueError', 'invalid grad_req: ' .. grad_req)
end
reqs_array = c_array_buf(mx_uint,
table.replicate(_GRAD_REQ_MAP[grad_req], len(listed_arguments)))
elseif #grad_req > 0 then
reqs_array = c_array_buf(mx_uint,
table.map(grad_req, function(v)
return _GRAD_REQ_MAP[v]
end))
else
local req_array = {}
for _, name in ipairs(listed_arguments) do
if grad_req[name] then
table.insert(req_array, _GRAD_REQ_MAP[grad_req[name]])
else
table.insert(req_array, 0)
end
end
reqs_array = c_array_buf(mx_uint, req_array)
end
local ctx_map_keys = {}
local ctx_map_dev_types = {}
local ctx_map_dev_ids = {}
if group2ctx then
for k, v in pairs(group2ctx) do
table.insert(ctx_map_keys, k)
table.insert(ctx_map_dev_types, v.device_typeid)
table.insert(ctx_map_dev_ids, v.device_id)
end
end
local handle = ExecutorHandle()
local shared_handle = isnone(shared_exec) and ExecutorHandle() or shared_exec.handle
check_call(_LIB.MXExecutorBindEX(self.handle,
ctypes.c_int(ctx.device_typeid),
ctypes.c_int(ctx.device_id),
mx_uint(len(ctx_map_keys)),
c_str_array(ctx_map_keys),
c_array_buf(ctypes.c_int, ctx_map_dev_types),
c_array_buf(ctypes.c_int, ctx_map_dev_ids),
mx_uint(len(args)),
args_handle,
args_grad_handle,
reqs_array,
mx_uint(len(aux_states)),
aux_args_handle,
shared_handle,
ctypes.byref(handle)))
local executor = Executor(handle, self, ctx, grad_req, group2ctx)
executor.arg_arrays = args
executor.grad_arrays = args_grad
executor.aux_arrays = aux_states
return executor
end
function Symbol:gradient(wrt)
local handle = SymbolHandle()
local c_wrt = c_str_array(wrt)
check_call(_LIB.MXSymbolGrad(self.handle,
mx_uint(#wrt),
c_wrt,
ctypes.byref(handle)))
return Symbol(handle)
end
function Symbol:eval(ctx, kwargs)
if isnone(ctx) then
ctx = current_context()
end
return self:bind(ctx, kwargs):forward()
end
local function __register()
Symbol.reshape = op.reshape
Symbol.reshape_like = op.reshape_like
Symbol.astype = op.cast
Symbol.zeros_like = op.zeros_like
Symbol.ones_like = op.ones_like
Symbol.broadcast_axes = op.broadcast_axes
Symbol.repeat_ = op.repeat_
Symbol.pad = op.pad
Symbol.swapaxes = op.swapaxes
Symbol.split = op.split
Symbol.split_v2 = M.split_v2
Symbol.slice = op.slice
Symbol.slice_axis = op.slice_axis
Symbol.slice_like = op.slice_like
Symbol.take = op.take
Symbol.one_hot = op.one_hot
Symbol.pick = op.pick
Symbol.sort = op.sort
Symbol.topk = op.topk
Symbol.argsort = op.argsort
Symbol.argmax = op.argmax
Symbol.argmax_channel = op.argmax_channel
Symbol.argmin = op.argmin
Symbol.clip = op.clip
Symbol.abs = op.abs
Symbol.sign = op.sign
Symbol.flatten = op.flatten
Symbol.shape_array = op.shape_array
Symbol.size_array = op.size_array
Symbol.expand_dims = op.expand_dims
Symbol.broadcast_to = op.broadcast_to
Symbol.broadcast_like = op.broadcast_like
Symbol.tile = op.tile
Symbol.transpose = op.transpose
Symbol.flip = op.flip
Symbol.depth_to_space = op.depth_to_space
Symbol.space_to_depth = op.space_to_depth
Symbol.sum = op.sum
Symbol.nansum = op.nansum
Symbol.prod = op.prod
Symbol.nanprod = op.nanprod
Symbol.mean = op.mean
Symbol.max = op.max
Symbol.min = op.min
Symbol.norm = op.norm
Symbol.round = op.round
Symbol.rint = op.rint
Symbol.fix = op.fix
Symbol.floor = op.floor
Symbol.ceil = op.ceil
Symbol.trunc = op.trunc
Symbol.sin = op.sin
Symbol.cos = op.cos
Symbol.tan = op.tan
Symbol.arcsin = op.arcsin
Symbol.arccos = op.arccos
Symbol.arctan = op.arctan
Symbol.degrees = op.degrees
Symbol.radians = op.radians
Symbol.sinh = op.sinh
Symbol.cosh = op.cosh
Symbol.tanh = op.tanh
Symbol.arcsinh = op.arcsinh
Symbol.arccosh = op.arccosh
Symbol.arctanh = op.arctanh
Symbol.exp = op.exp
Symbol.expm1 = op.expm1
Symbol.log = op.log
Symbol.log10 = op.log10
Symbol.log2 = op.log2
Symbol.log1p = op.log1p
Symbol.sqrt = op.sqrt
Symbol.rsqrt = op.rsqrt
Symbol.cbrt = op.cbrt
Symbol.rcbrt = op.rcbrt
Symbol.square = op.square
Symbol.reciprocal = op.reciprocal
Symbol.relu = op.relu
Symbol.sigmoid = op.sigmoid
Symbol.softmax = op.softmax
Symbol.log_softmax = op.log_softmax
Symbol.softmin = op.softmin
Symbol.squeeze = op.squeeze
end
function Symbol:diag(k, kwargs)
return op.diag(self, default(k, 0), kwargs)
end
Symbol.__register = __register
function Symbol:get_backend_symbol(backend)
local out = SymbolHandle()
check_call(_LIB.MXGenBackendSubgraph(self.handle, c_str(backend), ctypes.byref(out)))
return Symbol(out)
end
function Symbol:wait_to_read()
raise('NotImplementedForSymbol')
end
function Symbol:asnumpy()
raise('NotImplementedForSymbol')
end
function Symbol:asscalar()
raise('NotImplementedForSymbol')
end
function Symbol:copy()
raise('NotImplementedForSymbol')
end
function Symbol:as_in_context()
raise('NotImplementedForSymbol')
end
function Symbol:detach()
raise('NotImplementedForSymbol')
end
function Symbol:backward()
raise('NotImplementedForSymbol')
end
--
local _Symbol_field = {
name = Symbol._name,
}
function Symbol:__index(k)
local tk = type(k)
if tk == 'string' then
if _Symbol_field[k] then
return _Symbol_field[k](self)
elseif not isnone(Symbol[k]) then
return Symbol[k]
end
end
return self:__getitem(k)
end
--
function M.var(name, attr, shape, lr_mult, wd_mult, dtype,
init, stype, kwargs)
kwargs = default(kwargs, {})
if type(name) ~= 'string' then
raise('TypeError', 'Expect a string for variable `name`')
end
local handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateVariable(c_str(name), ctypes.byref(handle)))
local ret = Symbol(handle)
if not AttrScope._current.value then
AttrScope._current.value = AttrScope()
end
attr = AttrScope._current.value:get(attr)
if isnone(attr) then
attr = {}
end
local str = base.tostring
if not isnone(shape) then
attr['__shape__'] = str(shape)
end
if not isnone(lr_mult) then
attr['__lr_mult__'] = str(lr_mult)
end
if not isnone(wd_mult) then
attr['__wd_mult__'] = str(wd_mult)
end
if not isnone(dtype) then
attr['__dtype__'] = str(_DTYPE_NP_TO_MX[dtype])
end
if not isnone(init) then
if type(init) ~= 'string' then
init = init:dumps()
end
attr['__init__'] = init
end
if not isnone(stype) then
attr['__storage_type__'] = str(_STORAGE_TYPE_STR_TO_ID[stype])
end
for k, v in pairs(kwargs) do
if k:starts_with('__') and k:ends_with('__') then
attr[k] = str(v)
else
raise('ValueError', ('Attribute name=%s is not supported.'):format(k))
end
end
ret:_set_attr(attr)
return ret
end
-- for back compatibility
M.Variable = M.var
function M.Group(symbols)
local function check(v)
return not isinstance(v, Symbol)
end
if not symbols or table.any(symbols, check) then
raise('TypeError', 'Expected a list of symbols as input')
end
local handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateGroup(
mx_uint(len(symbols)),
c_handle_array(symbols), ctypes.byref(handle)))
return Symbol(handle)
end
function M.load(fname)
if type(fname) ~= 'string' then
raise('TypeError', 'fname need to be string')
end
local handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromFile(c_str(fname), ctypes.byref(handle)))
return Symbol(handle)
end
function M.load_json(json_str)
if type(json_str) ~= 'string' then
raise('TypeError', 'json_str need to be string')
end
local handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
return Symbol(handle)
end
local function _sym_helper(lhs, rhs, f1, f2, f3, f4)
local a1 = isinstance(lhs, Symbol)
local a2 = isinstance(rhs, Symbol)
local b1 = not a1 and type(lhs) == 'number'
local b2 = not a2 and type(rhs) == 'number'
if a1 and a2 then
return f1(lhs, rhs)
elseif a1 and b2 then
return f2(lhs, rhs)
elseif b1 and a2 then
return f3(rhs, lhs)
elseif b1 and b2 then
return f4(lhs, rhs)
else
raise('TypeError', 'type not supported')
end
end
function M.power(base_, exp)
return _sym_helper(
base_, exp, _internal._Power, _internal._PowerScalar, _internal._RPowerScalar,
function(a, b)
return a ^ b
end)
end
M.pow = M.power
function M.maximum(left, right)
return _sym_helper(
left, right, _internal._Maximum, _internal._MaximumScalar, _internal._MaximumScalar,
function(a, b)
if a > b then
return a
end
return b
end)
end
function M.minimum(left, right)
return _sym_helper(
left, right, _internal._Minimum, _internal._MinimumScalar, _internal._MinimumScalar,
function(a, b)
if a < b then
return a
end
return b
end)
end
function M.hypot(left, right)
return _sym_helper(
left, right, _internal._Hypot, _internal._HypotScalar, _internal._HypotScalar,
function(a, b)
return math.sqrt(a * a + b * b)
end)
end
local function check_dtype(dtype)
if isnone(dtype) then
dtype = 'float32'
end
return dtype
end
function M.eye(N, M_, k, dtype, kwargs)
M_, k = default(M_, 0, k, 0)
dtype = check_dtype(dtype)
return _internal._eye(N, M_, k, nil, dtype, nil, nil, nil, kwargs)
end
function M.zeros(shape, dtype, kwargs)
dtype = check_dtype(dtype)
return _internal._zeros(shape, nil, dtype, nil, nil, nil, kwargs)
end
function M.ones(shape, dtype, kwargs)
dtype = check_dtype(dtype)
return _internal._ones(shape, nil, dtype, nil, nil, nil, kwargs)
end
function M.full(shape, val, dtype, kwargs)
dtype = check_dtype(dtype)
return _internal._full(shape, nil, dtype, val, nil, nil, nil, kwargs)
end
function M.arange(start, stop, step, repeat_, infer_range, name, dtype)
step, repeat_, infer_range = default(step, 1, repeat_, 1, infer_range, false)
dtype = check_dtype(dtype)
return _internal._arange(start, stop, step, repeat_, infer_range, nil, dtype, name)
end
function M.linspace(start, stop, num, endpoint, name, dtype)
endpoint = default(endpoint, true)
dtype = check_dtype(dtype)
return _internal._linspace(start, stop, nil, nil, nil, nil, dtype, name, nil, nil, {
num = num,
stop = stop,
})
end
function M.histogram(a, bins, range, kwargs)
if isinstance(bins, Symbol) then
return _internal._histogram(a, bins, nil, nil, nil, nil, nil, kwargs)
elseif type(bins) == 'number' then
if isnone(range) then
raise('ValueError', 'null range is not supported in symbol mode')
end
return _internal._histogram(a, nil, bins, range, nil, nil, nil, kwargs)
end
raise('ValueError', 'bins argument should be either an integer or an NDArray')
end
function M.split_v2(ary, indices_or_sections, axis, squeeze_axis)
axis, squeeze_axis = default(axis, 0, squeeze_axis, false)
local indices = {}
local sections = 0
if type(indices_or_sections) == 'number' then
sections = indices_or_sections
elseif islist(indices_or_sections) then
indices = table.sequence({ 0 }, indices_or_sections)
else
raise('ValueError', 'indices_or_sections must either int or tuple of ints')
end
return _internal._split_v2(ary, indices, axis, squeeze_axis, sections)
end
_set_symbol_class(Symbol)
return M
|
PluginInfo = {
Name = "My Plugins~Playlist Maker",
Version = "1.0",
BuildVersion = "1.0.0.1",
Id = "5783e46f-c180-4a81-961a-21f605ff5e5f",
Author = "Maxx Sanner",
Description = "A simple plugin that allows you to create a playlist out of a single audio file"
}
|
class("U73SkinRePage", import(".TemplatePage.SkinTemplatePage")).OnUpdateFlush = function (slot0)
slot0.super.OnUpdateFlush(slot0)
setText(slot0.dayTF, setColorStr(slot0.nday, COLOR_GREEN) .. "/" .. #slot0.taskGroup)
end
return class("U73SkinRePage", import(".TemplatePage.SkinTemplatePage"))
|
object_tangible_saga_system_rewards_shared_decal_pgc_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s01.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s01, "object/tangible/saga_system/rewards/shared_decal_pgc_s01.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_decal_pgc_s02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s02, "object/tangible/saga_system/rewards/shared_decal_pgc_s02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_decal_pgc_s03 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s03.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s03, "object/tangible/saga_system/rewards/shared_decal_pgc_s03.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_decal_pgc_s04 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s04.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s04, "object/tangible/saga_system/rewards/shared_decal_pgc_s04.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_decal_pgc_s05 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s05.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s05, "object/tangible/saga_system/rewards/shared_decal_pgc_s05.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_decal_pgc_s06 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_decal_pgc_s06.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_decal_pgc_s06, "object/tangible/saga_system/rewards/shared_decal_pgc_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_frn_fireplace = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_frn_fireplace.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_frn_fireplace, "object/tangible/saga_system/rewards/shared_frn_fireplace.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_chandelier = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_chandelier.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_chandelier, "object/tangible/saga_system/rewards/shared_jabba_chandelier.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_drapes = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_drapes.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_drapes, "object/tangible/saga_system/rewards/shared_jabba_drapes.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_fancyrug = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_fancyrug.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_fancyrug, "object/tangible/saga_system/rewards/shared_jabba_fancyrug.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_gargoyle = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_gargoyle.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_gargoyle, "object/tangible/saga_system/rewards/shared_jabba_gargoyle.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_generator = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_generator.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_generator, "object/tangible/saga_system/rewards/shared_jabba_generator.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_table = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_table.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_table, "object/tangible/saga_system/rewards/shared_jabba_table.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_tassels = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_tassels.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_tassels, "object/tangible/saga_system/rewards/shared_jabba_tassels.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_jabba_windchime = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_jabba_windchime.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_jabba_windchime, "object/tangible/saga_system/rewards/shared_jabba_windchime.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_pgc_glass_pane_01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_pgc_glass_pane_01.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_pgc_glass_pane_01, "object/tangible/saga_system/rewards/shared_pgc_glass_pane_01.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_pgc_glass_pane_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_pgc_glass_pane_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_pgc_glass_pane_02, "object/tangible/saga_system/rewards/shared_pgc_glass_pane_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_pgc_monitorscreen = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_pgc_monitorscreen.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_pgc_monitorscreen, "object/tangible/saga_system/rewards/shared_pgc_monitorscreen.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_pgc_monitorscreen_small = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_pgc_monitorscreen_small.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_pgc_monitorscreen_small, "object/tangible/saga_system/rewards/shared_pgc_monitorscreen_small.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_pgc_robe_statue = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_pgc_robe_statue.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_pgc_robe_statue, "object/tangible/saga_system/rewards/shared_pgc_robe_statue.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_corellia = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_corellia.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_corellia, "object/tangible/saga_system/rewards/shared_planet_hologram_corellia.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_corellia_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_corellia_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_corellia_02, "object/tangible/saga_system/rewards/shared_planet_hologram_corellia_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_dantooine = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_dantooine.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_dantooine, "object/tangible/saga_system/rewards/shared_planet_hologram_dantooine.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_dantooine_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_dantooine_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_dantooine_02, "object/tangible/saga_system/rewards/shared_planet_hologram_dantooine_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_dathomir = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_dathomir.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_dathomir, "object/tangible/saga_system/rewards/shared_planet_hologram_dathomir.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_dathomir_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_dathomir_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_dathomir_02, "object/tangible/saga_system/rewards/shared_planet_hologram_dathomir_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_endor = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_endor.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_endor, "object/tangible/saga_system/rewards/shared_planet_hologram_endor.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_endor_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_endor_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_endor_02, "object/tangible/saga_system/rewards/shared_planet_hologram_endor_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_lok = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_lok.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_lok, "object/tangible/saga_system/rewards/shared_planet_hologram_lok.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_lok_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_lok_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_lok_02, "object/tangible/saga_system/rewards/shared_planet_hologram_lok_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_naboo = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_naboo.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_naboo, "object/tangible/saga_system/rewards/shared_planet_hologram_naboo.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_naboo_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_naboo_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_naboo_02, "object/tangible/saga_system/rewards/shared_planet_hologram_naboo_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_rori = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_rori.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_rori, "object/tangible/saga_system/rewards/shared_planet_hologram_rori.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_rori_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_rori_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_rori_02, "object/tangible/saga_system/rewards/shared_planet_hologram_rori_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_talus = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_talus.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_talus, "object/tangible/saga_system/rewards/shared_planet_hologram_talus.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_talus_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_talus_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_talus_02, "object/tangible/saga_system/rewards/shared_planet_hologram_talus_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_tatooine = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_tatooine.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_tatooine, "object/tangible/saga_system/rewards/shared_planet_hologram_tatooine.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_tatooine_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_tatooine_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_tatooine_02, "object/tangible/saga_system/rewards/shared_planet_hologram_tatooine_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_yavin4 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_yavin4.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_yavin4, "object/tangible/saga_system/rewards/shared_planet_hologram_yavin4.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_planet_hologram_yavin4_02 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_planet_hologram_yavin4_02.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_planet_hologram_yavin4_02, "object/tangible/saga_system/rewards/shared_planet_hologram_yavin4_02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_starship_storage_device = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_starship_storage_device.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_starship_storage_device, "object/tangible/saga_system/rewards/shared_starship_storage_device.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_structure_deed_player_house_sandcrawler = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_structure_deed_player_house_sandcrawler.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_structure_deed_player_house_sandcrawler, "object/tangible/saga_system/rewards/shared_structure_deed_player_house_sandcrawler.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_saga_system_rewards_shared_structure_deed_player_tent_chronicler = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/saga_system/rewards/shared_structure_deed_player_tent_chronicler.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_saga_system_rewards_shared_structure_deed_player_tent_chronicler, "object/tangible/saga_system/rewards/shared_structure_deed_player_tent_chronicler.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
package.path = "../../?/init.lua;../../?.lua;"..package.path
print = require("klib.utils.debug").trace
local classes = require "klib.classes"
local Application = require("klib.app").Application
local gui = require "klib.gui"
local MainWindow = classes.class("MainWindow", gui.Window)
function MainWindow:init()
gui.Window.init(self, "Hello", gui.Label("World!"))
end
local HelloApp = classes.class("HelloApp", Application)
HelloApp.title = "Hello, World! from KLib"
function HelloApp:init()
Application.init(self)
local wnd = MainWindow()
self.desktop:insert(wnd)
end
function love.load(arg)
HelloApp():set_as_foreground()
end
|
local CBM = CALLBACK_MANAGER
local CreateString = ZO_CreateStringId
local PSBT_EVENTS = PSBT.EVENTS
local PSBT_STRINGS = PSBT.STRINGS
--[[
FALL_DAMAGE = 'SI_PSBT_EVENT_FALL_DAMAGE',
CANNOT_SEE = 'SI_PSBT_EVENT_CANNOT_SEE',
DAMAGE_CRIT = 'SI_PSBT_EVENT_DAMAGE_CRIT',
DAMAGE = 'SI_PSBT_EVENT_DAMAGE',
HEALING_CRIT = 'SI_PSBT_EVENT_HEAL_CRIT',
HEALING = 'SI_PSBT_EVENT_HEAL',
KILLING_BLOW = 'SI_PSBT_EVENT_KILLING_BLOW',
FALLING = 'SI_PSBT_EVENT_FALLING',
INTERCEPTED = 'SI_PSBT_EVENT_INTERCEPTED',
BUSY = 'SI_PSBT_EVENT_BUSY',
IMMUNE = 'SI_PSBT_EVENT_IMMUNE',
INTERRUPT = 'SI_PSBT_EVENT_INTERRUPT',
ULTIMATE_GAIN = 'SI_PSBT_EVENT_ULTIMATE_GAIN',
ULTIMATE_READY = 'SI_PSBT_EVENT_ULTIMATE_READY',
LOW_SOMETHING = 'SI_PSBT_EVENT_LOW_SOMETHING',
AURA_GAINED = 'SI_PSBT_EVENT_AURA_GAINED',
AURA_FADES = 'SI_PSBT_EVENT_AURA_FADES',
ENERGIZE = 'SI_PSBT_EVENT_ENERGIZE',
DRAIN = 'SI_PSBT_EVENT_DRAIN',
]]
CBM:RegisterCallback( PSBT_EVENTS.INITIALIZE, function()
print( 'PSBT Locale: FR' )
CreateString( PSBT_STRINGS.FALL_DAMAGE, '<<1>> en baisse' )
CreateString( PSBT_STRINGS.CANNOT_SEE, 'Vous ne pouvez pas voir la cible' )
CreateString( PSBT_STRINGS.DAMAGE_CRIT, '<<1>> !' )
CreateString( PSBT_STRINGS.DAMAGE, '<<1>>')
CreateString( PSBT_STRINGS.HEALING_CRIT, '+<<1>> !')
CreateString( PSBT_STRINGS.HEALING, '+<<1>>')
CreateString( PSBT_STRINGS.KILLING_BLOW, '|cCC7D5E<<1>>|r mort !')
CreateString( PSBT_STRINGS.FALLING, 'Chute')
CreateString( PSBT_STRINGS.INTERCEPTED, 'Intercepté')
CreateString( PSBT_STRINGS.BUSY, 'Occupé')
CreateString( PSBT_STRINGS.IMMUNE, 'Immunitaire')
CreateString( PSBT_STRINGS.INTERRUPT, 'Interrompre')
CreateString( PSBT_STRINGS.ULTIMATE_GAIN, '<<1>> Ultime')
CreateString( PSBT_STRINGS.ULTIMATE_READY, 'Ultime prêt !')
CreateString( PSBT_STRINGS.LOW_SOMETHING, '<<1>> faible ! ( <<2>> )')
CreateString( PSBT_STRINGS.AURA_GAINED, '<<1>> acquise')
CreateString( PSBT_STRINGS.AURA_FADES, '<<1>> se faner')
CreateString( PSBT_STRINGS.ENERGIZE, '+<<1>> ( <<2>> )')
CreateString( PSBT_STRINGS.DRAIN, '-<<1>> ( <<2>> )')
end )
|
return {'eeg','eega','eegs','eegas','eegaatje'}
|
---------------------------------------------
-- Chainspell
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
MobBuffMove(mob, tpz.effect.CHAINSPELL, 1, 0, 60)
skill:setMsg(tpz.msg.basic.USES)
return tpz.effect.CHAINSPELL
end
|
local tinyurl = {}
local kk = require("kk")
local conf = require("conf/tinyurl")
local table = require("table")
return function(uri,data)
ngx.log(ngx.ALERT,'[HTTP] '..conf.baseURL .. uri)
ngx.log(ngx.ALERT,'[HTTP] '.. kk.json.encode(data))
return kk.http.json(conf.baseURL .. uri,data)
end
|
local Element = require "lattice.element"
local op = {}
op["^"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 ^ n2)
else return Element:InitWithBottom() end
end
op[".."] = function(e1, e2)
local b1, s1 = e1:getString()
local b2, s2 = e2:getString()
if b1 and b2 then return Element:InitWithString(s1 .. s2)
else return Element:InitWithBottom() end
end
op["*"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 * n2)
else return Element:InitWithBottom() end
end
op["/"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 / n2)
else return Element:InitWithBottom() end
end
op["//"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 // n2)
else return Element:InitWithBottom() end
end
op["%"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 % n2)
else return Element:InitWithBottom() end
end
op["+"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 + n2)
else return Element:InitWithBottom() end
end
op["-"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 - n2)
else return Element:InitWithBottom() end
end
op["<<"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 << n2)
else return Element:InitWithBottom() end
end
op[">>"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 >> n2)
else return Element:InitWithBottom() end
end
op["&"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 & n2)
else return Element:InitWithBottom() end
end
op["~"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 ~ n2)
else return Element:InitWithBottom() end
end
op["|"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithNumber(n1 | n2)
else return Element:InitWithBottom() end
end
-- Unops
op["not"] = function(e)
local isNil = e:isNil()
local isBool, bool = e:getBool()
if isNil then
return Element:InitWithBool(true)
elseif isBool then
return Element:InitWithBool(not bool)
elseif e:isBottom() then
return Element:InitWithBottom()
else
return Element:InitWithBool(false)
end
end
op["#"] = function()
return Element:InitWithBottom()
end
op["u-"] = function(e)
local b, n = e:getNumber()
if b then return Element:InitWithNumber(-n)
else return Element:InitWithBottom() end
end
op["u~"] = function(e)
local b, n = e:getNumber()
if b then return Element:InitWithNumber(~n)
else return Element:InitWithBottom() end
end
-- LogBinOps
op["and"] = function(e1, e2)
local isConstant1, constant1 = e1:test()
if not isConstant1 then
return Element:InitWithBottom()
elseif not constant1 then
return e1:copy()
else
return e2:copy()
end
end
op["or"] = function(e1, e2)
local isConstant1, constant1 = e1:test()
if not isConstant1 then
return Element:InitWithBottom()
elseif constant1 then
return e1:copy()
else
return e2:copy()
end
end
-- Compare ops
op["<"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithBool(n1 < n2)
else return Element:InitWithBottom() end
end
op["<="] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithBool(n1 <= n2)
else return Element:InitWithBottom() end
end
op[">"] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithBool(n1 > n2)
else return Element:InitWithBottom() end
end
op[">="] = function(e1, e2)
local b1, n1 = e1:getNumber()
local b2, n2 = e2:getNumber()
if b1 and b2 then return Element:InitWithBool(n1 >= n2)
else return Element:InitWithBottom() end
end
op["=="] = function(e1, e2)
if e1:isBottom() or e2:isBottom()
or e1:isTop() or e2:isTop() then
return Element:InitWithBottom()
else
return Element:InitWithBool(e1:compare(e2))
end
end
op["~="] = function(e1, e2)
if e1:isBottom() or e2:isBottom()
or e1:isTop() or e2:isTop() then
return Element:InitWithBottom()
else
return Element:InitWithBool(not e1:compare(e2))
end
end
return op
|
--ティアラメンツ・ルルカロス
--
--Script by Trishula9
function c101110039.initial_effect(c)
c:EnableReviveLimit()
--fusion material
aux.AddFusionProcCodeFun(c,92731385,aux.FilterBoolFunction(Card.IsSetCard,0x181),1,true,true)
--indestructable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(c101110039.indtg)
e1:SetValue(1)
c:RegisterEffect(e1)
--negate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(101110039,0))
e2:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY+CATEGORY_TOGRAVE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,101110039)
e2:SetCondition(c101110039.discon)
e2:SetTarget(c101110039.distg)
e2:SetOperation(c101110039.disop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(101110039,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCountLimit(1,101110039+100)
e3:SetCondition(c101110039.spcon)
e3:SetTarget(c101110039.sptg)
e3:SetOperation(c101110039.spop)
c:RegisterEffect(e3)
end
function c101110039.indtg(e,c)
return c:IsRace(RACE_AQUA) and c~=e:GetHandler()
end
function c101110039.discon(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) or not Duel.IsChainNegatable(ev) then return false end
return re:IsHasCategory(CATEGORY_SPECIAL_SUMMON) and ep~=tp
end
function c101110039.tgfilter(c)
return c:IsSetCard(0x181) and (c:IsLocation(LOCATION_HAND) or c:IsFaceup()) and c:IsAbleToGrave()
end
function c101110039.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101110039.tgfilter,tp,LOCATION_HAND+LOCATION_ONFIELD,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND+LOCATION_ONFIELD)
end
function c101110039.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) and Duel.Destroy(eg,REASON_EFFECT)~=0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c101110039.tgfilter,tp,LOCATION_HAND+LOCATION_ONFIELD,0,1,1,nil)
if #g>0 then
Duel.BreakEffect()
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
end
function c101110039.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_EFFECT) and c:IsPreviousLocation(LOCATION_MZONE) and c:IsSummonType(SUMMON_TYPE_FUSION)
end
function c101110039.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c101110039.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
|
local function GetAllFiles( tab, folder, extension, path )
local files, folders = file.Find( folder .. "/*", path )
for k, v in pairs( files ) do
if ( v:EndsWith( extension ) ) then
table.insert( tab, (folder .. v):lower() )
end
end
for k, v in pairs( folders ) do
timer.Simple( k * 0.1, function()
GetAllFiles( tab, folder .. v .. "/", extension, path )
end )
end
if ( folder == "models/" ) then
hook.Run( "SearchUpdate" )
end
end
local model_list = nil
--
-- Model Search
--
search.AddProvider( function( str )
if ( model_list == nil ) then
model_list = {}
GetAllFiles( model_list, "models/", ".mdl", "GAME" )
timer.Simple( 1, function() hook.Run( "SearchUpdate" ) end )
end
local list = {}
for k, v in pairs( model_list ) do
if ( v:find( str ) ) then
if ( UTIL_IsUselessModel( v ) ) then continue end
local entry =
{
text = v:GetFileFromFilename(),
func = function() RunConsoleCommand( "gm_spawn", v ) end,
icon = spawnmenu.CreateContentIcon( "model", nil, { model = v } ),
words = { v }
}
table.insert( list, entry )
end
if ( #list >= 128 ) then break end
end
return list
end );
--
-- Entity, vehicles
--
search.AddProvider( function( str )
local results = {}
local ents = {}
table.Add( ents, scripted_ents.GetSpawnable() );
table.Add( ents, list.Get( "SpawnableEntities" ) );
for k, v in pairs( list.Get( "Vehicles" ) ) do
v.ClassName = k
v.PrintName = v.Name
v.ScriptedEntityType = 'vehicle'
table.insert( ents, v )
end
for k, v in pairs( list.Get( "NPC" ) ) do
v.ClassName = k
v.PrintName = v.Name
v.ScriptedEntityType = 'npc'
table.insert( ents, v )
end
for k, v in pairs( ents ) do
local name = v.ClassName or v.PrintName
if ( !name ) then continue end
if ( name:lower():find( str ) ) then
local entry =
{
text = v.PrintName or v.ClassName,
icon = spawnmenu.CreateContentIcon( v.ScriptedEntityType or "entity", nil,
{
nicename = v.PrintName or v.ClassName,
spawnname = v.ClassName,
material = "entities/"..v.ClassName..".png",
admin = v.AdminOnly
}),
words = { v }
}
table.insert( results, entry )
end
if ( #results >= 128 ) then break end
end
return results
end );
|
-----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Stone Picture Frame
-- Notes: Opens door to Den of Rancor using Painbrush of Souls
-- !pos -52.239 -2.089 10.000 159
-----------------------------------
local ID = require("scripts/zones/Temple_of_Uggalepih/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/status")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local X = player:getXPos()
local Z = player:getZPos()
if X < -60 then
if Z < -6 then -- SW frame
if player:hasKeyItem(tpz.ki.FINAL_FANTASY) then
player:startEvent(50, tpz.ki.FINAL_FANTASY)
else
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 31) -- This is a frame for a painting.
end
elseif Z < 5 then
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 14) -- It is a picture of an old mage carrying a staff.
else
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 13) -- It is a picture of a small group of three men and women.
end
else
if Z <-5 then -- SE picture
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 12) -- It is a painting of a beautiful landscape.
elseif Z > -5 and Z < 5 then
if GetNPCByID(ID.npc.DOOR_TO_RANCOR):getAnimation() == tpz.anim.OPEN_DOOR then
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 23, tpz.ki.PAINTBRUSH_OF_SOULS) -- The <KEY_ITEM> begins to twitch. The canvas is graced with the image from your soul.
elseif player:hasKeyItem(tpz.ki.PAINTBRUSH_OF_SOULS) and X >= -53.2 and Z <= 0.1 and Z >= -0.1 then -- has paintbrush of souls + close enough
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 17, tpz.ki.PAINTBRUSH_OF_SOULS)
player:setCharVar("started_painting", os.time())
player:startEvent(60, tpz.ki.PAINTBRUSH_OF_SOULS)
elseif player:hasKeyItem(tpz.ki.PAINTBRUSH_OF_SOULS) then
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 15, tpz.ki.PAINTBRUSH_OF_SOULS)
else
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET, tpz.ki.PAINTBRUSH_OF_SOULS) -- When the paintbrush of souls projects the deepest, darkest corner of your soul...
end
else
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 11) -- It is a painting of a sublime-looking woman.
end
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 50 then
-- Soon !
elseif csid == 60 then
local time_elapsed = os.time() - player:getCharVar("started_painting")
if time_elapsed >= 30 then
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 22) -- You succeeded in projecting the image in your soul to the blank canvas. The door to the Rancor Den has opened!<Prompt>
GetNPCByID(ID.npc.DOOR_TO_RANCOR):openDoor(45) -- Open the door to Den of Rancor for 45 sec
else
player:messageSpecial(ID.text.PAINTBRUSH_OFFSET + 21) -- You were unable to fill the canvas with an image from your soul.
end
player:setCharVar("started_painting", 0)
end
end
|
require "luaClass.init"
require "test.containerTest.timeTest"
_ENV=namespace "test"
using_namespace "container"
local q=queue(50)
q:push_back(998)
print(q:front())
print(q:pop_front())
print(q:empty())
q:push_back(7766)
q:push_back(8877)
print(q:pop_front())
print(q:pop_front())
print(q:empty())
for i=1,50 do
q:push_back(i)
end
print(q:full())
print(q:empty())
print("-------性能测试----------")
local count=1000000
testTime(function()
for i=1,count do
if i%1==1 then
q:push_back(i)
else
q:pop_front()
end
end
end)
print(q:empty())
----------其实这个性能非常高,虽然跟前面的测试时间上似乎差不多,循环队列的设计先天保证了没有rehash开销----------------
|
-- This script needs to be loaded before other scripts that use it.
local PlayerDefaults = {
__index = {
initialize = function(self)
self.ActiveModifiers = {
JudgmentGraphic = "Love",
Mini = "0%",
BackgroundFilter = "Off",
SpeedModType = "x",
SpeedMod = 1.00,
Vocalization = "None",
NoteSkin = nil,
HideTargets = false,
HideSongBG = false,
HideCombo = false,
HideLifebar = false,
HideScore = false,
ColumnFlashOnMiss = false,
SubtractiveScoring = false,
MeasureCounterPosition = "Left",
MeasureCounter = "None",
TargetStatus = "Disabled",
TargetBar = 11,
TargetScore = false,
ReceptorArrowsPosition = "StomperZ",
LifeMeterType = "Standard",
DensityGraph = "Disabled",
LaneCover = "0%"
}
self.Streams = {
SongDir = nil,
StepsType = nil,
Difficulty = nil,
Measures = nil
}
self.HighScores = {
EnteringName = false,
Name = ""
}
self.Stages = {
Stats = {}
}
self.CurrentPlayerOptions = {
String = nil
}
end
}
}
local GlobalDefaults = {
__index = {
-- since the initialize() function is called every game cycle, the idea
-- is to define variables we want to reset every game cycle inside
initialize = function(self)
self.ActiveModifiers = {
MusicRate = 1.0,
DecentsWayOffs = "Decents Only"
}
self.Stages = {
PlayedThisGame = 0,
Remaining = PREFSMAN:GetPreference("SongsPerPlay"),
Stats = {}
}
self.ScreenAfter = {
PlayAgain = SL.IsEtterna and "ScreenTitleMenu" or "ScreenEvaluationSummary",
PlayerOptions = "ScreenGameplay",
PlayerOptions2 = "ScreenGameplay"
}
self.ContinuesRemaining = ThemePrefs.Get("NumberOfContinuesAllowed") or 0
self.Gamestate = {
Style = "single"
}
self.GameMode = ThemePrefs.Get("DefaultGameMode") or "Competitive"
self.ScreenshotTexture = nil
self.MenuTimer = {
ScreenSelectMusic = ThemePrefs.Get("ScreenSelectMusicMenuTimer"),
ScreenSelectMusicCasual = ThemePrefs.Get("ScreenSelectMusicCasualMenuTimer"),
ScreenPlayerOptions = ThemePrefs.Get("ScreenPlayerOptionsMenuTimer"),
ScreenEvaluation = ThemePrefs.Get("ScreenEvaluationMenuTimer"),
ScreenEvaluationSummary = ThemePrefs.Get("ScreenEvaluationSummaryMenuTimer"),
ScreenNameEntry = ThemePrefs.Get("ScreenNameEntryMenuTimer")
}
self.TimeAtSessionStart = nil
end,
-- These values outside initialize() won't be reset each game cycle,
-- but are rather manipulated as needed by the theme.
ActiveColorIndex = ThemePrefs.Get("SimplyLoveColor") or 1
}
}
-- "SL" is a general-purpose table that can be accessed from anywhere
-- within the theme and stores info that needs to be passed between screens
SL = {
P1 = setmetatable({}, PlayerDefaults),
P2 = setmetatable({}, PlayerDefaults),
Global = setmetatable({}, GlobalDefaults),
IsEtterna = not (not GAMESTATE.GetEtternaVersion),
-- Colors that Simply Love's background can be
Colors = {
"#FF3C23",
"#FF003C",
"#C1006F",
"#8200A1",
"#413AD0",
"#0073FF",
"#00ADC0",
"#5CE087",
"#AEFA44",
"#FFFF00",
"#FFBE00",
"#FF7D00"
},
JudgmentColors = {
Casual = {
color("#21CCE8"), -- blue
color("#e29c18"), -- gold
color("#66c955"), -- green
color("#5b2b8e"), -- purple
color("#c9855e"), -- peach?
color("#ff0000") -- red
},
Competitive = {
color("#21CCE8"), -- blue
color("#e29c18"), -- gold
color("#66c955"), -- green
color("#5b2b8e"), -- purple
color("#c9855e"), -- peach?
color("#ff0000") -- red
},
ECFA = {
color("#21CCE8"), -- blue
color("#ffffff"), -- white
color("#e29c18"), -- gold
color("#66c955"), -- green
color("#5b2b8e"), -- purple
color("#ff0000") -- red
},
StomperZ = {
color("#5b2b8e"), -- purple
color("#0073ff"), -- dark blue
color("#66c955"), -- green
color("#e29c18"), -- gold
color("#dddddd"), -- grey
color("#ff0000") -- red
}
},
Preferences = {
Casual = {
TimingWindowAdd = ThemePrefs.Get("TimingWindowAdd"),
RegenComboAfterMiss = 0,
MaxRegenComboAfterMiss = 0,
MinTNSToHideNotes = "TapNoteScore_W3",
HarshHotLifePenalty = 1,
TimingWindowSecondsW1 = 0.021500,
TimingWindowSecondsW2 = 0.043000,
TimingWindowSecondsW3 = 0.102000,
TimingWindowSecondsW4 = 0.102000,
TimingWindowSecondsW5 = 0.102000,
TimingWindowSecondsHold = 0.320000,
TimingWindowSecondsMine = 0.070000,
TimingWindowSecondsRoll = 0.350000
},
Competitive = {
TimingWindowAdd = ThemePrefs.Get("TimingWindowAdd"),
RegenComboAfterMiss = 5,
MaxRegenComboAfterMiss = 10,
MinTNSToHideNotes = "TapNoteScore_W3",
HarshHotLifePenalty = 1,
TimingWindowSecondsW1 = 0.021500,
TimingWindowSecondsW2 = 0.043000,
TimingWindowSecondsW3 = 0.102000,
TimingWindowSecondsW4 = 0.135000,
TimingWindowSecondsW5 = 0.180000,
TimingWindowSecondsHold = 0.320000,
TimingWindowSecondsMine = 0.070000,
TimingWindowSecondsRoll = 0.350000
},
ECFA = {
TimingWindowAdd = 0.0015,
RegenComboAfterMiss = 5,
MaxRegenComboAfterMiss = 10,
MinTNSToHideNotes = "TapNoteScore_W4",
HarshHotLifePenalty = 1,
TimingWindowSecondsW1 = 0.011000,
TimingWindowSecondsW2 = 0.021500,
TimingWindowSecondsW3 = 0.043000,
TimingWindowSecondsW4 = 0.102000,
TimingWindowSecondsW5 = 0.135000,
TimingWindowSecondsHold = 0.320000,
TimingWindowSecondsMine = 0.065000,
TimingWindowSecondsRoll = 0.350000
},
StomperZ = {
TimingWindowAdd = 0,
RegenComboAfterMiss = 0,
MaxRegenComboAfterMiss = 0,
MinTNSToHideNotes = "TapNoteScore_W4",
HarshHotLifePenalty = 0,
TimingWindowSecondsW1 = 0.012500,
TimingWindowSecondsW2 = 0.025000,
TimingWindowSecondsW3 = 0.050000,
TimingWindowSecondsW4 = 0.100000,
TimingWindowSecondsW5 = 0.10000,
TimingWindowSecondsHold = 0.20000,
TimingWindowSecondsMine = 0.070000,
TimingWindowSecondsRoll = 0.350000
}
},
Metrics = {
Casual = {
PercentScoreWeightW1 = 3,
PercentScoreWeightW2 = 2,
PercentScoreWeightW3 = 1,
PercentScoreWeightW4 = 0,
PercentScoreWeightW5 = 0,
PercentScoreWeightMiss = 0,
PercentScoreWeightLetGo = 0,
PercentScoreWeightHeld = 3,
PercentScoreWeightHitMine = -1,
GradeWeightW1 = 3,
GradeWeightW2 = 2,
GradeWeightW3 = 1,
GradeWeightW4 = 0,
GradeWeightW5 = 0,
GradeWeightMiss = 0,
GradeWeightLetGo = 0,
GradeWeightHeld = 3,
GradeWeightHitMine = -1,
LifePercentChangeW1 = 0,
LifePercentChangeW2 = 0,
LifePercentChangeW3 = 0,
LifePercentChangeW4 = 0,
LifePercentChangeW5 = 0,
LifePercentChangeMiss = 0,
LifePercentChangeLetGo = 0,
LifePercentChangeHeld = 0,
LifePercentChangeHitMine = 0
},
Competitive = {
PercentScoreWeightW1 = 5,
PercentScoreWeightW2 = 4,
PercentScoreWeightW3 = 2,
PercentScoreWeightW4 = 0,
PercentScoreWeightW5 = -6,
PercentScoreWeightMiss = -12,
PercentScoreWeightLetGo = 0,
PercentScoreWeightHeld = 5,
PercentScoreWeightHitMine = -6,
GradeWeightW1 = 5,
GradeWeightW2 = 4,
GradeWeightW3 = 2,
GradeWeightW4 = 0,
GradeWeightW5 = -6,
GradeWeightMiss = -12,
GradeWeightLetGo = 0,
GradeWeightHeld = 5,
GradeWeightHitMine = -6,
LifePercentChangeW1 = 0.008,
LifePercentChangeW2 = 0.008,
LifePercentChangeW3 = 0.004,
LifePercentChangeW4 = 0.000,
LifePercentChangeW5 = -0.050,
LifePercentChangeMiss = -0.100,
LifePercentChangeLetGo = IsGame("pump") and 0.000 or -0.080,
LifePercentChangeHeld = IsGame("pump") and 0.000 or 0.008,
LifePercentChangeHitMine = -0.050
},
ECFA = {
PercentScoreWeightW1 = 5,
PercentScoreWeightW2 = 5,
PercentScoreWeightW3 = 4,
PercentScoreWeightW4 = 2,
PercentScoreWeightW5 = 0,
PercentScoreWeightMiss = -12,
PercentScoreWeightLetGo = 0,
PercentScoreWeightHeld = 5,
PercentScoreWeightHitMine = -6,
GradeWeightW1 = 5,
GradeWeightW2 = 5,
GradeWeightW3 = 4,
GradeWeightW4 = 2,
GradeWeightW5 = 0,
GradeWeightMiss = -12,
GradeWeightLetGo = 0,
GradeWeightHeld = 5,
GradeWeightHitMine = -6,
LifePercentChangeW1 = 0.008,
LifePercentChangeW2 = 0.008,
LifePercentChangeW3 = 0.008,
LifePercentChangeW4 = 0.004,
LifePercentChangeW5 = 0,
LifePercentChangeMiss = -0.1,
LifePercentChangeLetGo = -0.08,
LifePercentChangeHeld = 0.008,
LifePercentChangeHitMine = -0.05
},
StomperZ = {
PercentScoreWeightW1 = 10,
PercentScoreWeightW2 = 9,
PercentScoreWeightW3 = 8,
PercentScoreWeightW4 = 5,
PercentScoreWeightW5 = 0,
PercentScoreWeightMiss = 0,
PercentScoreWeightLetGo = 0,
PercentScoreWeightHeld = 10,
PercentScoreWeightHitMine = -5,
GradeWeightW1 = 10,
GradeWeightW2 = 9,
GradeWeightW3 = 8,
GradeWeightW4 = 5,
GradeWeightW5 = 0,
GradeWeightMiss = 0,
GradeWeightLetGo = 0,
GradeWeightHeld = 10,
GradeWeightHitMine = -5,
LifePercentChangeW1 = 0.004,
LifePercentChangeW2 = 0.004,
LifePercentChangeW3 = 0.004,
LifePercentChangeW4 = 0.004,
LifePercentChangeW5 = 0,
LifePercentChangeMiss = -0.04,
LifePercentChangeLetGo = -0.04,
LifePercentChangeHeld = 0,
LifePercentChangeHitMine = -0.04
}
},
TitleMenuChoices = function()
return SL.IsEtterna and "1,Multi,3,4" or "1,2,3,4"
end
}
-- Initialize preferences by calling this method.
-- We typically do this from ./BGAnimations/ScreenTitleMenu underlay.lua
-- so that preferences reset between each game cycle.
function InitializeSimplyLove()
SL.P1:initialize()
SL.P2:initialize()
SL.Global:initialize()
end
-- TODO: remove this; it's for debugging purposes (Control+F2 to reload scripts) only
InitializeSimplyLove()
|
local trigger = {}
trigger.name = "ExtendedVariantMode/ColorGradeTrigger"
trigger.placements = {
name = "trigger",
data = {
colorGrade = "none",
revertOnLeave = false,
revertOnDeath = true,
delayRevertOnDeath = false,
withTeleport = false,
coversScreen = false,
flag = "",
flagInverted = false,
onlyOnce = false
}
}
trigger.fieldInformation = {
colorGrade = {
options = {
"none",
"oldsite",
"panicattack",
"templevoid",
"reflection",
"credits",
"cold",
"hot",
"feelingdown",
"golden",
"max480/extendedvariants/celsius/tetris",
"max480/extendedvariants/greyscale",
"max480/extendedvariants/sepia",
"max480/extendedvariants/inverted",
"max480/extendedvariants/rgbshift1",
"max480/extendedvariants/rgbshift2",
"max480/extendedvariants/hollys_randomnoise"
}
}
}
return trigger
|
require "mods.my_first_mod.files.scripts.test_module"
-- ffi = require("ffi")
module = {}
module.test = 1
function module.HelloWorld()
print("hello world" .. module.test)
test_module.fooFun1()
-- ffi.cdef[[
-- int printf(const char* fmt, ...);
-- ]]
-- ffi.C.printf()
end
return module
|
-- Support for visual mode.
local M = {}
local vi_motion = require('textadept-vi.vi_motion')
local vi_ops = require('textadept-vi.vi_ops')
local state -- This will be vi_mode.state later (but import time is too early)
local function visual_update(pos)
local s = state.visual.s
local e = pos or state.visual.pos
state.visual.pos = e
-- Adjust one end to make it inclusive
if s < e then
e = e+1
end
buffer.set_selection(s, e)
end
M.VISUAL = 'visual'
local function exit_visual()
enter_mode(mode_command)
end
local function visual_range()
local s, e = state.visual.s, state.visual.pos
if s>e then
s, e = e, s
end
return s, e+1
end
-- Take an operator function (which takes startpos, endpos, movtype)
-- and return a key sym for visual mode.
local function wrap_op(opfunc)
return function()
local s, e = visual_range()
local movement = {
s=s,
e=e,
movtype=state.visual.movtype,
}
opfunc(movement)
exit_visual()
end
end
local function wrap_op_linewise(opfunc)
return function()
local s, e = visual_range()
local movement = {
s=s,
e=e,
movtype='linewise',
raws=s,
rawe=e,
}
opfunc(movement)
exit_visual()
end
end
local handle_v_r = setmetatable({}, {
__index = function(t, sym)
if string.match(sym, "^.$") then
return wrap_op(function(s, e, t) vi_ops.replace_char(sym, s, e, t) end)
end
end,
})
local mode_visual = {
name = M.VISUAL,
bindings = {
esc = function()
exit_visual()
end,
v = function()
exit_visual()
end,
x = wrap_op(vi_ops.cut),
d = wrap_op(vi_ops.cut),
['~'] = wrap_op(vi_ops.revcase),
u = wrap_op(vi_ops.lowercase),
U = wrap_op(vi_ops.uppercase),
y = wrap_op(vi_ops.yank),
r = handle_v_r,
g = {
q = wrap_op(vi_ops.wrap),
},
--[[ Vim operators not yet implemented here:
c, <, >, !, =
other commands:
:, s, C, S, R, D, X, Y, p, J, ^], I, A
]]
},
init = function()
state = vi_mode.state
local pos = buffer.current_pos
state.visual.pos = pos -- current location
state.visual.s = pos -- other end.
state.visual.movtype = MOV_INC -- Possible linewise support later
visual_update()
end,
}
local function motion2visualkey(m)
return function()
local f = vi_mode.motion2key(m)
buffer.goto_pos(state.visual.pos)
f()
visual_update(buffer.current_pos)
end
end
setmetatable(mode_visual.bindings, {
__index = function(t,k)
local m = vi_motion.motions[k]
if type(m) == 'table' and m[1] then
return motion2visualkey(m)
elseif type(m) == 'table' then
return vi_motion.wrap_table(m, motion2visualkey)
end
end
})
local function set_default_visual_key(k)
if mode_visual.bindings[k] == nil then
mode_visual.bindings[k] = function()
vi_mode.err("Unbound visual key: <" .. tostring(k) .. ">")
end
end
end
for i = 0,25 do
k = string.char(i + string.byte("a"))
set_default_visual_key(k)
set_default_visual_key(string.upper(k))
end
M.mode_visual = mode_visual
return M
|
--
-- System module that runs under the energy cluster to resolve the energy generation and
-- distribution.
--
-- @namespace yatm_cluster_energy
local EnergyDevices = assert(yatm.energy.EnergyDevices)
local get_node_or_nil = minetest.get_node_or_nil
-- @class EnergySystem
local EnergySystem = foundation.com.Class:extends("EnergySystem")
local ic = EnergySystem.instance_class
--local LOG_GROUP = 'yatm.cluster.energy:energy_system'
-- @spec #initialize(): void
function ic:initialize()
ic._super.initialize(self)
end
-- @spec #calc_energy_produced(Cluster, dtime: Float, trace: Trace): Integer
function ic:calc_energy_produced(cluster, dtime, trace)
local span
if trace then
span = trace:span_start("produce_energy")
end
local node
local amount_produced
local energy_produced =
cluster:reduce_nodes_of_groups("energy_producer", 0, function (node_entry, acc)
node = get_node_or_nil(node_entry.pos)
--print(LOG_GROUP, "produce energy", node_entry.pos.x, node_entry.pos.y, node_entry.pos.z, node.name)
if node then
amount_produced = EnergyDevices.produce_energy(node_entry.pos, node, dtime, span)
if amount_produced then
acc = acc + amount_produced
end
end
return true, acc
end)
if span then
span:span_end()
end
return energy_produced
end
-- @spec #calc_energy_stored(cluster: Cluster, dtime: Float, trace: Trace): Integer
function ic:calc_energy_stored(cluster, dtime, trace)
local span
if trace then
span = trace:span_start("calc_energy_stored")
end
local node
local amount_stored
local energy_stored =
cluster:reduce_nodes_of_groups("energy_storage", 0, function (node_entry, accumulated_energy_stored)
node = get_node_or_nil(node_entry.pos)
if node then
amount_stored = EnergyDevices.get_usable_stored_energy(node_entry.pos, node, dtime, span)
if amount_stored then
accumulated_energy_stored = accumulated_energy_stored + amount_stored
end
end
return true, accumulated_energy_stored
end)
if span then
span:span_end()
end
return energy_stored
end
-- @spec #calc_energy_stored(
-- energy_available: Integer,
-- cluster: Cluster,
-- dtime: Float,
-- trace: Trace
-- ): (energy_consumed: Integer, energy_available: Integer)
function ic:run_consume_energy(energy_available, cluster, dtime, trace)
local span
if trace then
span = trace:span_start("consume_energy")
end
local energy_consumed = 0
if energy_available > 0 then
--print(LOG_GROUP, "energy_available", energy_available, "=", energy_stored, " + ", energy_produced)
-- Consumers are different from receivers, they use energy without any intention of storing it
local amount_consumed
local node
energy_consumed =
cluster:reduce_nodes_of_groups("energy_consumer", energy_consumed, function (node_entry, acc)
node = get_node_or_nil(node_entry.pos)
if node then
amount_consumed = EnergyDevices.consume_energy(node_entry.pos, node, energy_available, dtime, span)
if amount_consumed then
energy_available = energy_available - amount_consumed
acc = acc + amount_consumed
end
end
-- can't continue if we have no energy available
return energy_available > 0, acc
end)
end
if span then
span:span_end()
end
return energy_consumed, energy_available
end
-- @spec #run_use_stored_energy(
-- energy_available: Integer,
-- cluster: Cluster,
-- dtime: Float,
-- trace: Trace
-- ): void
function ic:run_use_stored_energy(energy_storage_consumed, cluster, dtime, trace)
local span
if trace then
span = trace:span_start("use_stored_energy")
end
-- if we went over the produced, then the rest must be taken from the storage
if energy_storage_consumed > 0 then
local used
local node
cluster:reduce_nodes_of_groups("energy_storage", 0, function (node_entry, acc)
node = get_node_or_nil(node_entry.pos)
if node then
used = EnergyDevices.use_stored_energy(node_entry.pos, node, energy_storage_consumed, dtime, span)
if used then
energy_storage_consumed = energy_storage_consumed + used
end
end
-- only continue if the energy_storage_consumed is still greater than 0
return energy_storage_consumed > 0, acc + 1
end)
end
if span then
span:span_end()
end
end
-- @spec #run_receive_energy(
-- energy_left: Integer,
-- cluster: Cluster,
-- dtime: Float,
-- trace: Trace
-- ): void
function ic:run_receive_energy(energy_left, cluster, dtime, trace)
local span
if trace then
span = trace:span_start("receive_energy")
end
if energy_left > 0 then
local node
--print(LOG_GROUP, "energy_left", energy_left)
-- Receivers are the lowest priority, they accept any left over energy from the production
-- Incidentally, storage nodes tend to be also receivers
local energy_received
cluster:reduce_nodes_of_groups("energy_receiver", 0, function (node_entry, acc)
node = get_node_or_nil(node_entry.pos)
if node then
energy_received = EnergyDevices.receive_energy(node_entry.pos, node, energy_left, dtime, span)
if energy_received then
energy_left = energy_left - energy_received
end
end
return energy_left > 0, acc + 1
end)
end
if span then
span:span_end()
end
end
function ic:run_has_update(cluster, dtime, trace)
local span
if trace then
span = trace:span_start("has_update")
end
local pos
local node
local tc
local nodedef
cluster:reduce_nodes_of_groups("has_update", 0, function (node_entry, acc)
pos = node_entry.pos
node = get_node_or_nil(pos)
if node then
nodedef = minetest.registered_nodes[node.name]
if nodedef.yatm_network and nodedef.yatm_network.update then
if span then
tc = span:span_start(node.name)
end
nodedef.yatm_network.update(pos, node, dtime, tc)
if tc then
tc:span_end()
end
else
print("energy_system", "INVALID UPDATABLE DEVICE", pos.x, pos.y, pos.z, node.name)
end
end
return true, acc + 1
end)
if span then
span:span_end()
end
end
function ic:update(cls, cluster, dtime, trace)
local sys_trace
local step_trace
if trace then
sys_trace = trace:span_start("energy_system")
end
if sys_trace then
step_trace = sys_trace:span_start(cluster.id)
end
--print(LOG_GROUP, "dtime=" .. dtime, "cluster_id=" .. cluster.id, "size=" .. cluster:size(), "updating energy")
--print(cluster:inspect())
-- Highest priority, produce energy
-- It's up to the node how it wants to deal with the energy, whether it's buffered, or just burst
local energy_produced = self:calc_energy_produced(cluster, dtime, step_trace)
-- Second highest priority, how much energy is stored in the network right now
-- This is combined with the produced to determine how much is available
-- The node is allowed to lie about it's contents, to cause energy trickle or gating
local energy_stored = self:calc_energy_stored(cluster, dtime, step_trace)
local total_energy_available = energy_stored + energy_produced
local energy_available = total_energy_available
local energy_consumed
energy_consumed, energy_available = self:run_consume_energy(energy_available, cluster, dtime, step_trace)
--print(LOG_GROUP, "energy_consumed", energy_consumed)
self:run_use_stored_energy(energy_consumed - energy_produced, cluster, dtime, step_trace)
-- how much extra energy is left, note the stored is subtracted from the available
-- if it falls below 0 then there is no extra energy.
local energy_left = energy_available - energy_consumed
self:run_receive_energy(energy_left, cluster, dtime, step_trace)
self:run_has_update(cluster, dtime, step_trace)
if step_trace then
step_trace:span_end()
end
if sys_trace then
sys_trace:span_end()
end
end
yatm_cluster_energy.EnergySystem = EnergySystem
|
function Physic_Standart_Workbench(Map_ID, X, Y, Z)
Player_Number = Map_Block_Get_Player_Last(Map_ID, X, Y, Z)
Table = {}
for i = 0, 3 do
if i == 0 then dx, dy = 1, 0
elseif i == 1 then dx, dy = 0, 1
elseif i == 2 then dx, dy = -1, 0
elseif i == 3 then dx, dy = 0, -1
end
for ix = 0, 2 do
for iz = 0, 2 do
ax = ix-1
Table[1 + ix + iz*3] = Map_Block_Get_Type(Map_ID, X+ax*dx, Y+ax*dy, Z+3-iz)
end
end
Amount = 0
--System_Message_Network_Send_2_All(Map_ID, tostring(unpack(Table)))
-- Workbench
if Table[1]==5 and Table[2]==5 and Table[3]==0 and Table[4]==5 and Table[5]==5 and Table[6]==0 and Table[7]==0 and Table[8]==0 and Table[9]==0 then
Material = 58
Amount = 1
end
-- Furnace
if Table[1]==4 and Table[2]==4 and Table[3]==4 and Table[4]==4 and Table[5]==0 and Table[6]==4 and Table[7]==4 and Table[8]==4 and Table[9]==4 then
Material = 61
Amount = 1
end
-- Steps
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==4 and Table[8]==4 and Table[9]==4 then
Material = 44
Amount = 3
end
-- Bookcase
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==5 and Table[8]==23 and Table[9]==5 then
Material = 47
Amount = 1
end
-- Gravel
if Table[1]==4 and Table[2]==4 and Table[3]==0 and Table[4]==3 and Table[5]==3 and Table[6]==0 and Table[7]==0 and Table[8]==0 and Table[9]==0 then
Material = 13
Amount = 3
end
-- Mossy Cobblestone
if Table[1]==6 and Table[2]==6 and Table[3]==6 and Table[4]==6 and Table[5]==4 and Table[6]==6 and Table[7]==6 and Table[8]==6 and Table[9]==6 then
Material = 48
Amount = 1
end
-- Yellow Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==37 and Table[8]==37 and Table[9]==37 then
Material = 23
Amount = 1
end
-- Orange Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==38 and Table[8]==37 and Table[9]==38 then
Material = 22
Amount = 1
end
-- Red Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==38 and Table[8]==38 and Table[9]==38 then
Material = 21
Amount = 1
end
-- Light Green Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==6 and Table[8]==37 and Table[9]==6 then
Material = 24
Amount = 1
end
-- Green Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==6 and Table[8]==6 and Table[9]==6 then
Material = 25
Amount = 1
end
-- Dark Grey Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==16 and Table[8]==6 and Table[9]==16 then
Material = 34
Amount = 3
end
-- Light Grey Cloth
if Table[1]==0 and Table[2]==0 and Table[3]==0 and Table[4]==0 and Table[5]==0 and Table[6]==0 and Table[7]==6 and Table[8]==16 and Table[9]==6 then
Material = 35
Amount = 2
end
-- Sponge
if Table[1]==23 and Table[2]==0 and Table[3]==23 and Table[4]==0 and Table[5]==23 and Table[6]==0 and Table[7]==23 and Table[8]==0 and Table[9]==23 then
Material = 19
Amount = 1
end
if Amount ~= 0 then
for ix = 0, 2 do
for iz = 0, 2 do
ax = ix-1
Map_Block_Change(-1, Map_ID, X+ax*dx, Y+ax*dy, Z+3-iz, 0, 1, 1, 1, 5)
end
end
for i = 1, Amount do
ax = -2+i
Map_Block_Change(-1, Map_ID, X+ax*dx, Y+ax*dy, Z+1, Material, 1, 1, 1, 5)
end
end
end
end
|
module(..., package.seeall)
local ffi = require("ffi")
local tlv = subClass(nil)
ffi.cdef[[
typedef struct {
uint8_t type;
uint8_t length;
} tlv_t __attribute__((packed))
]]
local tlv_t = ffi.typeof("tlv_t")
local tlv_ptr_t = ffi.typeof("$ *", tlv_t)
tlv._types = {
[1] = {
name = "src_ll_addr",
class = "lib.protocol.icmp.nd.options.lladdr"
},
[2] = {
name = "tgt_ll_addr",
class = "lib.protocol.icmp.nd.options.lladdr"
},
}
-- Will be overriden for known types
tlv._name = "unkown"
function tlv:new (type, data)
assert(tlv._types[type], "tlv: unsupported type")
local size = ffi.sizeof(tlv_t)+ffi.sizeof(data)
assert(size%8 == 0)
local o = tlv:superClass().new(self)
local tlv = ffi.typeof("struct { tlv_t tlv; uint8_t data[$]; }", ffi.sizeof(data))()
tlv.tlv.type = type
tlv.tlv.length = size/8
ffi.copy(tlv.data, data, ffi.sizeof(data))
o._tlv = tlv
o._option = require(o._types[type].class):new_from_mem(tlv.data, ffi.sizeof(data))
return o
end
function tlv:new_from_mem (mem, size)
local o = tlv:superClass().new(self)
local tlv_t_size = ffi.sizeof(tlv_t)
assert(tlv_t_size <= size)
local tlv = ffi.cast(tlv_ptr_t, mem)
assert(o._types[tlv.type], "tlv: unsupported type")
o._name = o._types[tlv.type].name
local class = o._types[tlv.type].class
o._option = require(class):new_from_mem(mem + tlv_t_size,
size - tlv_t_size)
local t = ffi.typeof("struct { tlv_t tlv; uint8_t data[$]; }", size-tlv_t_size)
o._tlv = ffi.cast(ffi.typeof("$*", t), mem)
return o
end
function tlv:name ()
return self._name
end
function tlv:type (type)
if type ~= nil then
assert(self._types[type])
self._tlv.tlv.type = type
end
return self._tlv.tlv.type
end
-- This is in units of 8 bytes
function tlv:length ()
return self._tlv.tlv.length
end
function tlv:data ()
return self._tlv.data
end
function tlv:tlv ()
return self._tlv
end
function tlv:option ()
return self._option
end
return tlv
|
require "common"
--[[
TODO:
* add oversample
* add MAX Over T for some T
* multi scale turing patterns: https://faculty.ac/image-story/a-machine-in-motion/
* https://elifesciences.org/articles/14022
* https://examples.pyviz.org/attractors/attractors.html
]]
config=make_config({
{"pause",false,type="boolean"},
{"clamp_edges",false,type="boolean"},
{"do_sum",false,type="boolean"},
{"do_norm",false,type="boolean"},
{"diff_a",1,type="float",min=0,max=1},
{"diff_b",0.5,type="float",min=0,max=1},
{"diff_c",0.25,type="float",min=0,max=1},
{"diff_d",0.125,type="float",min=0,max=1},
{"k1",0.5,type="float",min=0,max=1},
{"k2",0.5,type="float",min=0,max=1},
{"k3",0.5,type="float",min=0,max=1},
{"k4",0.5,type="float",min=0,max=1},
{"region_size",0.5,type="float",min=0.01,max=1},
{"gamma",1,type="float",min=0.01,max=5},
{"gain",1,type="float",min=-5,max=5},
{"draw_comp",0,type="int",min=0,max=3},
{"animate",false,type="boolean"},
},config)
mapping_parameters={1,2}
local oversample=0.25 --TODO: not working correctly
function update_size()
local trg_w=1024
local trg_h=1024
--this is a workaround because if everytime you save
-- you do __set_window_size it starts sending mouse through windows. SPOOKY
if win_w~=trg_w or win_h~=trg_h or (img_buf==nil or img_buf.w~=trg_w) then
win_w=trg_w
win_h=trg_h
aspect_ratio=win_w/win_h
__set_window_size(win_w,win_h)
end
end
update_size()
local size=STATE.size
img_buf=img_buf or make_image_buffer(size[1],size[2])
react_buffer=react_buffer or multi_texture(size[1],size[2],2,1)
collect_buffer=collect_buffer or multi_texture(size[1],size[2],2,1)
io_buffer=io_buffer or make_flt_buffer(size[1],size[2])
map_region=map_region or {-1,0,0,0}
thingy_string=thingy_string or "-c.x*c.y*c.y,0,0,+c.x*c.y*c.y"
--feed_kill_string=feed_kill_string or "feed_rate*(1-c.x),-(kill_rate)*c.y,-(kill_rate)*(c.z),-(kill_rate)*c.w"
feed_kill_string="-k.y,-k.y,-k.y,k.x"
--cos(c.z),cos((k.z)-(((c.z)*((k.w)-(k.x)))-(c.x))),cos((c.y)-((c.w)+((k.y)*(c.x)))),cos((c.w)*(c.x))
function resize( w,h )
local ww=w*oversample
local hh=h*oversample
img_buf=make_image_buffer(w,h)
size=STATE.size
react_buffer:update_size(ww,hh)
collect_buffer:update_size(ww,hh)
io_buffer=make_flt_buffer(ww,hh);
end
if react_buffer.w~=win_w*oversample then
resize(win_w,win_h)
end
function count_lines( s )
local n=0
for i in s:gmatch("\n") do n=n+1 end
return n
end
function shader_make( s_in )
local sl=count_lines(s_in)
s="#version 330\n#line "..(debug.getinfo(2, 'l').currentline-sl).."\n"
s=s..s_in
return shaders.Make(s)
end
local react_diffuse
function update_diffuse( )
react_diffuse=shaders.Make(string.format([==[
#version 330
#line 85
out vec4 color;
in vec3 pos;
uniform vec4 diffusion;
uniform vec4 kill_feed;
uniform sampler2D tex_main;
uniform float dt;
uniform vec4 map_region;
vec4 laplace(vec2 pos) //with laplacian kernel (cnt -1,near .2,diag 0.05)
{
vec4 ret=vec4(0);
ret+=textureOffset(tex_main,pos,ivec2(-1,-1))*0.05;
ret+=textureOffset(tex_main,pos,ivec2(-1,1))*0.05;
ret+=textureOffset(tex_main,pos,ivec2(1,-1))*0.05;
ret+=textureOffset(tex_main,pos,ivec2(1,1))*0.05;
ret+=textureOffset(tex_main,pos,ivec2(0,-1))*.2;
ret+=textureOffset(tex_main,pos,ivec2(-1,0))*.2;
ret+=textureOffset(tex_main,pos,ivec2(1,0))*.2;
ret+=textureOffset(tex_main,pos,ivec2(0,1))*.2;
ret+=textureOffset(tex_main,pos,ivec2(0,0))*(-1);
return ret;
}
vec4 laplace_h(vec2 pos)
{
vec4 ret=vec4(0);
ret+=textureOffset(tex_main,pos,ivec2(0,-1))*.25;
ret+=textureOffset(tex_main,pos,ivec2(-1,0))*.25;
ret+=textureOffset(tex_main,pos,ivec2(1,0))*.25;
ret+=textureOffset(tex_main,pos,ivec2(0,1))*.25;
ret+=textureOffset(tex_main,pos,ivec2(0,0))*(-1);
return ret;
}
#define MAPPING
vec4 gray_scott(vec4 c,vec2 normed)
{
//NOTE: can increase the dt somewhat generally...
//x=0;0.5
//y=0;0.25
/*
X+2Y=3Y
*/
vec4 scale=vec4(0.07,0.1,0,0);
vec4 offset=vec4(0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
#if 0
vec2 kcenter=vec2(0.861682,0.439294);
float w=0.0625;
//0.861682,0.439294), width:0.0625
//0.694565,0.190942
//0.697397,0.19309), width:0.03125
float dist=1-clamp(length(normed-vec2(0.5))*2,0,1);
kill_rate=(kcenter.x-w*0.5+dist*w)*0.07;
feed_rate=(kcenter.y-w*0.5+dist*w)*0.1;
#endif
float abb=c.x*c.y*c.y;
return vec4(-abb,abb,0,0)+vec4(k.x*(1-c.x),-(k.y+k.x)*c.y,0,0);
}
vec4 schnakenberk_reaction_kinetics(vec4 cnt,vec2 normed)
{
#if 0
float k1=kill_feed.x;
float k2=kill_feed.y;
float k3=kill_feed.z;
float k4=kill_feed.w;
#ifdef MAPPING
if (map_region.x>=0)
{
k3=mix(map_region.x,map_region.y,normed.x);
k4=mix(map_region.z,map_region.w,normed.y);
}
#endif
float aab=cnt.x*cnt.x*cnt.y;
return vec2(k1,k4)-vec2(k2*cnt.x,0)+vec2(k3*aab,-k3*aab);
#endif
vec4 k=kill_feed;
vec4 scale=vec4(4,4,4,4);
vec4 offset=vec4(0,0,0,0);
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return k.z*vec4(k.x-cnt.x-cnt.x*cnt.x*cnt.y,k.y-cnt.x*cnt.x*cnt.y,0,0);
}
vec4 gierer_meinhard(vec4 cnt,vec2 normed)
{
//not dimensional
float k1=kill_feed.x;
float k2=kill_feed.y;
float k3=kill_feed.z;
#ifdef MAPPING
if (map_region.x>=0)
{
k1=mix(map_region.x,map_region.y,normed.x);
k2=mix(map_region.z,map_region.w,normed.y);
}
#endif
return k3*vec4(k1-k2*cnt.x+cnt.x*cnt.x/cnt.y,cnt.x*cnt.x-cnt.y,0,0);
}
vec4 ruijgrok(vec4 cnt,vec2 normed)
{
/*
X+Y=>2X
Y+Z=>2Y
Z+X=>2Z
X+2Y=>3Y
Y+2Z=>3Z
Z+2X=>3X
*/
float kill_rate=kill_feed.x;
float feed_rate=kill_feed.y;
#ifdef MAPPING
kill_rate=mix(map_region.x,map_region.y,normed.x);
feed_rate=mix(map_region.z,map_region.w,normed.y);
#endif
float pos_x1=cnt.y*cnt.x;
float pos_x2=cnt.z*cnt.x*cnt.x;
float pos_y1=cnt.z*cnt.y;
float pos_y2=cnt.x*cnt.y*cnt.y;
float pos_z1=cnt.z*cnt.x;
float pos_z2=cnt.z*cnt.y*cnt.y;
float neg_x1=pos_y2;
float neg_x2=pos_z1;
float neg_y1=pos_x1;
float neg_y2=pos_z2;
float neg_z1=pos_x2;
float neg_z2=pos_y1;
return vec4(
pos_x1+pos_x2-neg_x1-neg_x2+feed_rate*(1-cnt.x),
pos_y1+pos_y2-neg_y1-neg_y2-(kill_rate+feed_rate)*cnt.y,
pos_z1+pos_z2-neg_z1-neg_z2,
0);
}
vec4 rossler(vec4 cnt,vec2 normed)
{
//k1=0.2
//k2=0.2
//k3=5.7
//k1=0.1
//k2=0.1
//k3=14
float k1=kill_feed.x*0.2+0.1;
float k2=kill_feed.y*0.2+0.1;
float k3=kill_feed.z*20+4;
float k4=kill_feed.w;
#ifdef MAPPING
if (map_region.x>=0)
{
//k1=mix(map_region.x,map_region.y,normed.x)*0.2+0.1;
k2=mix(map_region.z,map_region.w,normed.y)*0.2+0.1;
//k3=mix(map_region.x,map_region.y,normed.x)*20+4;
}
#endif
return vec4(
-(cnt.y+cnt.z),
cnt.x+k1*cnt.y,
cnt.x*cnt.z-k2*cnt.z+k3,
0
)*k4;
}
vec4 rossler4(vec4 c,vec2 normed)
{
//http://www.scholarpedia.org/article/Hyperchaos
//explodes very fast
vec4 scale=vec4(0.125,1.5,0.25,0.025);
vec4 offset=vec4(0.25,3,0.5,0.05);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
-c.y-c.z,
c.x+k.x*c.y+c.w,
k.y+c.x*c.z,
-k.z*c.z+k.w*c.w
);
}
vec4 two_reacts(vec4 cnt,vec2 normed)
{
/*
X+2Y=3Y
Z+X=2Z
*/
float kill_rate=kill_feed.x;
float feed_rate=kill_feed.y;
#ifdef MAPPING
vec2 c=vec2(0.5,0.5);
vec2 cs=vec2(0.5,0.5);
kill_rate=mix(c.x-cs.x,c.x+cs.x,normed.x);
feed_rate=mix(c.y-cs.y,c.y+cs.y,normed.y);
#endif
float pos_y1=cnt.x*cnt.y*cnt.y;
float pos_z1=cnt.z*cnt.x;
float neg_x1=pos_y1;
float neg_x2=pos_z1;
return vec4(
-neg_x2-neg_x1+feed_rate*(1-cnt.x),
pos_y1,
pos_z1-(kill_rate+feed_rate)*cnt.z,
0);
}
vec4 thingy_formulas(vec4 c,vec2 normed)
{
vec4 scale=vec4(20);
vec4 offset=vec4(-10);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
float max_len=1;
float l=length(c);
float nl=clamp(l/max_len,0,1);
vec4 r=mix(vec4(%s),-c,nl);
//r=r/(l);
//return r*exp(-l*l/100);
//*k.y+vec4(%s)*k.w;
return r;
}
vec4 hyper_chaos(vec4 c,vec2 normed)
{
//BROKEN SOURCE?
vec4 scale=vec4(1);
vec4 offset=vec4(0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
c.x*(1-c.y)+k.x*c.z,
k.y*(c.x*c.x-1)*c.y,
k.z*(1-c.y)*c.w,
k.w*c.z
);
}
vec4 lorenz_system(vec4 c,vec2 normed)
{
//k1=10
//k2=28
//k3=8/3
vec4 scale=vec4(6,6,1,0);
vec4 offset=vec4(7,22,8/3-0.5,0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
k.x*(c.y-c.x),
c.x*(k.y-c.z)-c.y,
c.x*c.y-k.z*c.z,
0
);
}
vec4 chen_attractor(vec4 c,vec2 normed)
{
//BROKEN?
//chaos at: a = 40, b = 3, c = 28
//k.x=36,k.y=20,k.z=0 (and k.z=3)
//float k1=kill_feed.x*40+20;
//float k2=kill_feed.y*6;
//float k3=kill_feed.z*56;
vec4 scale=vec4(2,2,3,0);
vec4 offset=vec4(35,19,0,0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
//k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
k.z=mix(map_region.x,map_region.y,normed.x);
}
#endif
k=k*scale+offset;
return vec4(
k.x*(c.y-c.x),
(k.z-k.x)*c.x-c.x*c.z+k.z*c.y,
c.x*c.y-k.y*c.z,
0
);
}
vec4 clifford_attractor(vec4 c, vec2 normed)
{
vec4 scale=vec4(2,2,2,2);
vec4 offset=vec4(0,0,-1,-1);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.x);
//k.z=mix(map_region.z,map_region.w,normed.y);
//k.w=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
sin(k.x*c.y)+k.z*cos(k.x*c.x),
sin(k.y*c.x)+k.w*cos(k.y*c.y),
0,
0
);
}
vec4 hopalong_attractor1(vec4 c,vec2 normed)
{
vec4 k=kill_feed*8-vec4(4);
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x)*4-2;
k.y=mix(map_region.z,map_region.w,normed.y)*4-2;
}
#endif
return vec4(
c.y-sqrt(abs(k.y*c.x-k.z))*sign(c.x),
k.x-c.x,
0,
0
);
}
vec4 hopalong_attractor2(vec4 c,vec2 normed)
{
vec4 k=kill_feed*8-vec4(4);
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
//k=k*scale+offset;
return vec4(
c.y-1.0-sqrt(abs(k.y*c.x-1.0-k.z))*sign(c.x-1.0),
k.x-c.x-1.0,
0,
0
);
}
vec4 coullet_attractor(vec4 c, vec2 normed)
{
vec4 scale=vec4(2,2,2,2);
vec4 offset=vec4(0.8,-1.1,-0.45,-1);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.x);
//k.z=mix(map_region.z,map_region.w,normed.y);
//k.w=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
c.y,
c.z,
dot(vec4(c.x,c.y,c.z,c.x*c.x*c.x),k),
0
);
}
vec4 chaos_4d(vec4 c, vec2 normed)
{
//https://www.sciencedirect.com/science/article/pii/S209044791730014X
//EXPLODES VERY FAST
vec4 scale=vec4(4,4,0,0);
vec4 offset=vec4(21,7,0,0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
return vec4(
k.x*(c.x-c.w),
k.y*c.w-c.w*c.y,
c.w*c.x-c.x*c.z,
c.y*(c.x-1)
);
}
float GM_helper(float x,float mu)
{
return mu*x+2*(1-mu)*x*x/(1+x*x);
}
vec4 gumowski_mira_attractor(vec4 c,vec2 normed)
{
//NB: probably broken
//http://kgdawiec.bplaced.net/badania/pdf/cacs_2010.pdf
//3 param
vec4 scale=vec4(0.001,1,0.05,0);
vec4 offset=vec4(0.001,-.5,0,0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.z=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
float xn=c.y+k.x*(1-k.y*c.y*c.y)*c.y+GM_helper(c.x,k.z);
return vec4(
xn,
-c.x+GM_helper(xn,k.z),
0,
0
);
}
vec4 rampe1_modded(vec4 c,vec2 normed)
{
//https://softologyblog.wordpress.com/2009/10/19/3d-strange-attractors/
vec4 scale=vec4(2,2,2,2);
vec4 offset=vec4(-1,-1,-1,-1);
vec4 k=kill_feed;
float ke=-0.8;
float kf=0.7;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
k.y=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
vec4 r=vec4(
cos(k.x*c.x)+cos(k.y*c.y),
cos(k.z*c.y)+cos(k.w*c.z),
cos(ke*c.z)+cos(kf*c.x),
0
);
float l=length(r);
l=max(l,0.00001);
return r/l;
}
vec4 coupled_attractors(vec4 c,vec2 normed)
{
//AGiga-StableOscillatorwithHiddenandSelf-ExcitedAttractorsAMegastableOscillatorForcedbyHisTwin.pdf
vec4 scale=vec4(0.2,0.5,0.75,0);
vec4 offset=vec4(0.1,2.77,0,0);
vec4 k=kill_feed;
#ifdef MAPPING
if (map_region.x>=0)
{
k.x=mix(map_region.x,map_region.y,normed.x);
//k.y=mix(map_region.z,map_region.w,normed.y);
k.z=mix(map_region.z,map_region.w,normed.y);
}
#endif
k=k*scale+offset;
vec4 r=vec4(
c.y,
-k.x*k.x*c.x+c.y*cos(c.x)+k.z*c.z,
k.y*c.w,
k.y*(-k.x*k.x*c.z+c.w*cos(c.z))
);
return r;
}
vec4 actual_function(vec4 c,vec2 normed)
{
return
//gray_scott(c,normed)
//ruijgrok(c,normed)
//two_reacts(c,normed)
thingy_formulas(c,normed)
//schnakenberk_reaction_kinetics(c,normed)
//gierer_meinhard(c,normed)
//rossler(c,normed)
//rossler4(c,normed)
//hyper_chaos(c,normed)
//lorenz_system(c,normed)
//chen_attractor(c,normed)
//clifford_attractor(c,normed)
//hopalong_attractor1(c,normed)
//hopalong_attractor2(c,normed)
//gumowski_mira_attractor(c,normed)
//chaos_4d(c,normed)
//coullet_attractor(c,normed)
//rampe1_modded(c,normed)
//coupled_attractors(c,normed)
;
}
vec4 runge_kutta_4(vec4 c,vec2 normed,float step_dt)
{
vec4 k1=step_dt*actual_function(c,normed);
vec4 k2=step_dt*actual_function(c+0.5*k1,normed);
vec4 k3=step_dt*actual_function(c+0.5*k2,normed);
vec4 k4=step_dt*actual_function(c+k3,normed);
return c+(k1+2*k2+2*k3+k4)/6.0;
}
void main(){
vec4 diffusion_value=diffusion;
vec2 normed=(pos.xy+vec2(1,1))/2;
float dist=clamp(length(pos.xy)+0.5,0.5,1.5);
//diffusion_value.xy*=dist;
vec4 L=laplace(normed);
vec4 cnt=texture(tex_main,normed);
#if 1
vec4 ret=cnt+(diffusion_value*L
+actual_function(cnt,normed)
)*dt;
#elif 0
int step_count=10;
float step_dt=dt/float(step_count);
vec4 ret=cnt;
for(int i=0;i<step_count;i++)
{
ret+=actual_function(ret,normed)*step_dt;
}
ret+=diffusion_value*L*dt;
#elif 1
vec4 ret=diffusion_value*L*dt+runge_kutta_4(cnt,normed,dt);
#else
int step_count=10;
float step_dt=dt/float(step_count);
vec4 ret=vec4(cnt);
for(int i=0;i<step_count;i++)
{
ret=runge_kutta_4(ret,normed,step_dt);
}
ret+=diffusion_value*L*dt;
#endif
//ret=clamp(ret,0,1);
//float l=length(ret);
//l=max(l,0.0001);
color=ret;///l;
}
]==],thingy_string,feed_kill_string))
end
update_diffuse()
local draw_shader = shader_make[==[
out vec4 color;
in vec3 pos;
uniform sampler2D tex_main;
uniform float v_gamma;
uniform float v_gain;
uniform int draw_comp;
uniform vec4 value_scale;
uniform vec4 value_offset;
float gain(float x, float k)
{
float a = 0.5*pow(2.0*((x<0.5)?x:1.0-x), k);
return (x<0.5)?a:1.0-a;
}
vec3 palette( in float t, in vec3 a, in vec3 b, in vec3 c, in vec3 d )
{
return a + b*cos( 6.28318*(c*t+d) );
}
void main(){
vec2 normed=(pos.xy+vec2(1,1))/2;
vec4 cnt=texture(tex_main,normed);
cnt+=value_offset;
cnt*=value_scale;
//cnt=clamp(cnt,0,1);
float lv=cnt.x;
if(draw_comp==1)
lv=cnt.y;
else if(draw_comp==2)
lv=cnt.z;
else if(draw_comp==3)
lv=cnt.w;
//lv+=value_offset;
//lv*=value_scale;
lv=gain(lv,v_gain);
lv=pow(lv,v_gamma);
//color=vec4(cnt.xyz,1);
color=vec4(lv,lv,lv,1);
//color=vec4(palette(lv,vec3(0.5,0.5,0.5),vec3(0.5,0.5,0.5),vec3(1.5,1.5,1.25),vec3(1.0,1.05,1.4)),1);
//color=vec4(palette(lv,vec3(0.6,0,0.3),vec3(.4,0,0.7),vec3(1,1,1),vec3(0,0.33,0.66)),1);
/* accent
float accent_const=0.5;
if(lv<accent_const)
color=vec4(vec3(1)*(lv/accent_const),1);
else
color=mix(vec4(1),vec4(0.05,0.1,0.3,1),(lv-accent_const)/(1-accent_const));
//*/
/*
if(lv>0)
color.xyz=vec3(lv,0,0);
else
color.xyz=vec3(0,0,lv);
color.w=1;
*/
}
]==]
local sum_texture = shader_make[==[
out vec4 color;
in vec3 pos;
uniform sampler2D tex_main;
uniform sampler2D tex_old;
vec4 smooth_max_p_norm(vec4 a,vec4 b,float alpha)
{
return pow(pow(a,vec4(alpha))+pow(b,vec4(alpha)),vec4(1/alpha));
}
vec4 smooth_max_2(vec4 a,vec4 b,float alpha)
{
return ((a+b)+sqrt((a+b)*(a+b)+alpha))/2;
}
vec4 smooth_max(vec4 a,vec4 b,float alpha)
{
return (a*exp(alpha*a)+b*exp(alpha*b))/(exp(alpha*a)+exp(alpha*b));
}
void main(){
vec2 normed=(pos.xy+vec2(1,1))/2;
vec4 cnt=texture(tex_main,normed);
vec4 cnt_old=texture(tex_old,normed);
//color=max(abs(cnt),abs(cnt_old));
color=max(cnt,cnt_old);
//color=max(cnt,cnt_old)-min(cnt,cnt_old);
//color=(abs(cnt)+abs(cnt_old))/2;
//color=cnt+cnt_old;
//color=smooth_max(cnt,cnt_old,5);
//color=smooth_max_p_norm(cnt,cnt_old,5);
//color.a=1;
}
]==]
local terminal_symbols={["c.x"]=10,["c.y"]=10,["c.z"]=10,["c.w"]=10,["1.0"]=0.1,["0.0"]=0.1}
local normal_symbols={
["max(R,R)"]=0.05,["min(R,R)"]=0.05,["mod(R,R)"]=0.1,["fract(R)"]=0.1,["floor(R)"]=0.1,["abs(R)"]=0.1,
["sqrt(R)"]=0.1,["exp(R)"]=0.01,["atan(R,R)"]=1,["acos(R)"]=0.1,["asin(R)"]=0.1,["tan(R)"]=1,["sin(R)"]=1,
["cos(R)"]=1,
["log(R+1.0)"]=1,
["(R)/(R+1)"]=0.1,["(R)*(R)"]=20,["(R)-(R)"]=20,["(R)+(R)"]=20}
function normalize( tbl )
local sum=0
for i,v in pairs(tbl) do
sum=sum+v
end
for i,v in pairs(tbl) do
tbl[i]=tbl[i]/sum
end
end
normalize(terminal_symbols)
normalize(normal_symbols)
function rand_weighted(tbl)
local r=math.random()
local sum=0
for i,v in pairs(tbl) do
sum=sum+v
if sum>= r then
return i
end
end
end
function replace_random( s,substr,rep )
local num_match=0
local function count( )
num_match=num_match+1
return false
end
string.gsub(s,substr,count)
num_rep=math.random(0,num_match-1)
function rep_one( )
if num_rep==0 then
num_rep=num_rep-1
if type(rep)=="function" then
return rep()
else
return rep
end
else
num_rep=num_rep-1
return false
end
end
local ret=string.gsub(s,substr,rep_one)
return ret
end
function make_rand_math(def_seed, normal_s,terminal_s,forced_s )
forced_s=forced_s or {}
return function ( steps,seed,force_values)
local cur_string=seed or def_seed
force_values=force_values or forced_s
function M( )
return rand_weighted(normal_s)
end
function MT( )
return rand_weighted(terminal_s)
end
for i=1,steps do
cur_string=replace_random(cur_string,"R",M)
end
for i,v in ipairs(force_values) do
cur_string=replace_random(cur_string,"R",v)
end
cur_string=string.gsub(cur_string,"R",MT)
return cur_string
end
end
random_math=make_rand_math("R,R,R,R",normal_symbols,terminal_symbols)
random_math_cos=make_rand_math("cos(R),cos(R),cos(R),cos(R)",normal_symbols,terminal_symbols)
function random_math_balanced( steps,seed )
function M( )
return rand_weighted(normal_symbols)
end
function MT( )
return rand_weighted(terminal_symbols)
end
local ret=""
for i=1,4 do
local cur_string=seed or "R"
for i=1,steps do
cur_string=replace_random(cur_string,"R",M)
end
cur_string=string.gsub(cur_string,"R",MT)
if i==1 then
ret=cur_string
else
ret=ret..","..cur_string
end
end
return ret
end
function random_math_poly( )
local rf=function ( )
return math.random()*2-1
end
local ret=string.format("dot(c,vec4(%g,%g,%g,%g)),dot(c,vec4(%g,%g,%g,%g)),dot(c,vec4(%g,%g,%g,%g)),dot(c,vec4(%g,%g,%g,%g))",
rf(),rf(),rf(),rf(),
rf(),rf(),rf(),rf(),
rf(),rf(),rf(),rf(),
rf(),rf(),rf(),rf())
return ret
end
function random_math_transfers( steps,seed,count_transfers )
count_transfers=count_transfers or 3
function M( )
return rand_weighted(normal_symbols)
end
function MT( )
return rand_weighted(terminal_symbols)
end
local ret={"0","0","0","0"}
for i=1,count_transfers do
local cur_string=seed or "R"
for i=1,steps do
cur_string=replace_random(cur_string,"R",M)
end
cur_string=string.gsub(cur_string,"R",MT)
local remove=math.random(1,4)
local add=math.random(1,4)
while add==remove do
add=math.random(1,4)
end
ret[remove]=ret[remove].."-"..cur_string
ret[add]=ret[add].."+"..cur_string
end
local rstr=table.concat(ret,",")
return rstr
end
function sim_tick( )
local dt=0.05
react_diffuse:use()
-- react_diffuse:blend_disable()
react_diffuse:blend_default()
react_diffuse:set("diffusion",config.diff_a,config.diff_b,config.diff_c,config.diff_d)
react_diffuse:set("kill_feed",config.k1,config.k2,config.k3,config.k4)
react_diffuse:set("dt",dt)
react_diffuse:set("map_region",map_region[1],map_region[2],map_region[3],map_region[4])
local cur_buff=react_buffer:get()
local do_clamp
if config.clamp_edges then
do_clamp=1
else
do_clamp=0
end
cur_buff:use(0,1,do_clamp)
react_diffuse:set_i("tex_main",0)
local next_buff=react_buffer:get_next()
next_buff:use(1,1,do_clamp)
if not next_buff:render_to(react_buffer.w,react_buffer.h) then
error("failed to set framebuffer up")
end
react_diffuse:draw_quad()
__render_to_window()
react_buffer:advance()
end
init_size=1
function reset_buffers(rnd,do_rand)
local b=io_buffer
local center=1
local scale=1
local min_value=center-scale/2
local max_value=center+scale/2
--[[
local min_value=-1
local max_value=1
]]
do_rand=false
local v = {math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value}
for x=0,b.w-1 do
for y=0,b.h-1 do
local dx=x-b.w/2
local dy=y-b.h/2
local dist=math.sqrt(dx*dx+dy*dy)
-- [[
if rnd=="circle" then
if dist<b.w/4 then
if do_rand then
b:set(x,y,{
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value})
else
b:set(x,y,v)
end
else
b:set(x,y,{1,0,0,0})
end
elseif rnd=="noise" then
b:set(x,y,{
math.random()*(max_value-min_value)+min_value,math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,math.random()*(max_value-min_value)+min_value})
elseif rnd=="chaos" then
local v=(x+y)/(b.w+b.h-2)
b:set(x,y,{
(x/(b.w-1)+0.1)*(max_value-min_value)+min_value,
(1-y/(b.h-1)-0.1)*(max_value-min_value)+min_value,
--dist/10,
--dist/10,
--dist/10,
(x/(b.w-1)+0.1)*(max_value-min_value)+min_value,
(y/(b.w-1)+0.1)*(max_value-min_value)+min_value})
else
b:set(x,y,{1,0,0,0})
end
--]]
end
end
if rnd=="square" then
local cx=math.floor(b.w/2)
local cy=math.floor(b.h/2)
local s=math.random(1,b.w*0.25)
for x=cx-s,cx+s do
for y=cy-s,cy+s do
local dx=x-cx
local dy=y-cy
--if math.sqrt(dx*dx+dy*dy)<s then
if do_rand then
b:set(x,y,{
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value,
math.random()*(max_value-min_value)+min_value
})
else
b:set(x,y,v)
end
--end
end
end
end
local buf=react_buffer:get()
buf:use(0)
b:write_texture(buf)
react_buffer:advance()
buf=react_buffer:get()
buf:use(0)
b:write_texture(buf)
reset_collect()
end
function reset_collect()
local b=io_buffer
for x=0,b.w-1 do
for y=0,b.h-1 do
b:set(x,y,{0,0,0,0})
end
end
local buf=collect_buffer:get()
buf:use(0)
b:write_texture(buf)
collect_buffer:advance()
buf=collect_buffer:get()
buf:use(0)
b:write_texture(buf)
end
function is_inf( v )
if v==math.huge or v==-math.huge then
return true
end
return false
end
function clip_maxmin( tbl1,tbl2,id )
if is_inf(tbl1[id]) or is_inf(tbl2[id]) then
print("clip",id)
tbl1[id]=0
tbl2[id]=1
elseif math.abs(tbl1[id]-tbl2[id])<0.0001 then
tbl1[id]=0
tbl2[id]=1
end
end
function eval_thingy_string()
local MAX_DIFF_VALUE=0.25
local env={
max=math.max,
min=math.min,
mod=math.modf,
fract=function ( x )
return select(2,math.modf(x))
end,
floor=math.floor,
abs=math.abs,
sqrt=math.sqrt,
exp=math.exp,
atan=math.atan,
acos=math.acos,
asin=math.asin,
tan=math.tan,
sin=math.sin,
cos=math.cos,
log=math.log,
math=math,
dot=function ( a,b )
return a.x*b.x+a.y*b.y+a.z*b.z+a.w*b.w
end,
vec4=function ( x,y,z,w )
return {x=x,y=y,z=z,w=w}
end
}
local f=load(string.format(
[==[
local inf=math.huge
local val_min={inf,inf,inf,inf}
local val_max={-inf,-inf,-inf,-inf}
local step_size=0.05
local itg={0,0,0,0}
for x=0,1,step_size do
for y=0,1,step_size do
for z=0,1,step_size do
for w=0,1,step_size do
local c={x=x,y=y,z=z,w=w}
local tx,ty,tz,tw=%s
if tx>val_max[1] then val_max[1]=tx end
if ty>val_max[2] then val_max[2]=ty end
if tz>val_max[3] then val_max[3]=tz end
if tw>val_max[4] then val_max[4]=tw end
if tx<val_min[1] then val_min[1]=tx end
if ty<val_min[2] then val_min[2]=ty end
if tz<val_min[3] then val_min[3]=tz end
if tw<val_min[4] then val_min[4]=tw end
itg[1]=itg[1]+tx*step_size*step_size*step_size
itg[2]=itg[2]+ty*step_size*step_size*step_size
itg[3]=itg[3]+tz*step_size*step_size*step_size
itg[4]=itg[4]+tw*step_size*step_size*step_size
end
end
end
end
return val_min,val_max,itg
]==],thingy_string),"thingy","t",env)
local ret,vmin,vmax,itg=pcall(f)
if ret then
print("Min:",vmin[1],vmin[2],vmin[3],vmin[4])
print("Max:",vmax[1],vmax[2],vmax[3],vmax[4])
print("Integral:",itg[1],itg[2],itg[3],itg[4])
local swing={}
for i=1,4 do
clip_maxmin(vmin,vmax,i)
if itg[i]==0 then itg[i]=1 end
if math.abs(itg[i])==math.huge then itg[i]=1 end
if itg[i]~=itg[i] then itg[i]=1 end
swing[i]=vmax[i]-vmin[i]
--swing[i]=math.abs(vmax[i]-vmin[i])
end
thingy_string=string.format("(vec4(%s)+vec4(%g,%g,%g,%g))*vec4(%g,%g,%g,%g)"
,thingy_string,
-vmin[1],-vmin[2],-vmin[3],-vmin[4],
--itg[1],-itg[2],-itg[3],-itg[4],
MAX_DIFF_VALUE/swing[1],MAX_DIFF_VALUE/swing[2],-MAX_DIFF_VALUE/swing[3],-MAX_DIFF_VALUE/swing[4]
--MAX_DIFF_VALUE/itg[1],MAX_DIFF_VALUE/itg[2],-MAX_DIFF_VALUE/itg[3],-MAX_DIFF_VALUE/itg[4]
--1,1,1,1
)
print(thingy_string)
else
print("ERR:",vmin)
end
end
anim_state={
current_frame=0,
frame_skip=10,
max_frame=12000,
}
local do_normalize=false
function gui( )
imgui.Begin("GrayScott")
draw_config(config)
if imgui.Button("Reset") then
reset_buffers("noise")
end
imgui.SameLine()
if imgui.Button("Reset Square") then
reset_buffers("square")
end
imgui.SameLine()
if imgui.Button("Reset Circle") then
reset_buffers("circle")
end
imgui.SameLine()
if imgui.Button("Reset Chaos") then
reset_buffers("chaos")
end
if imgui.Button("RandMath") then
thingy_string=random_math(12,nil,{"c.x","c.y","c.z","c.w","k.x","k.y","k.z","k.w"})
print(thingy_string)
--eval_thingy_string()
update_diffuse()
reset_buffers("chaos")
end
imgui.SameLine()
if imgui.Button("ClearCollec") then
reset_collect()
end
if imgui.Button("NotMapping") then
if map_region[1]>=0 then
map_region={-1,0,0,0}
else
local cx=config["k"..mapping_parameters[1]]
local cy=config["k"..mapping_parameters[2]]
local low_x=math.max(0,cx-config.region_size)
local low_y=math.max(0,cy-config.region_size)
local high_x=math.min(1,cx+config.region_size)
local high_y=math.min(1,cy+config.region_size)
map_region={low_x,high_x,low_y,high_y}
end
end
imgui.SameLine()
if imgui.Button("FullMap") then
map_region={0,1,0,1}
config.region_size=0.5
reset_buffers("noise")
end
imgui.SameLine()
if imgui.Button("Zoom in") then
config.region_size=config.region_size/2
local cx=(map_region[2]-map_region[1])/2
local cy=(map_region[4]-map_region[3])/2
local low_x=math.max(0,cx-config.region_size)
local low_y=math.max(0,cy-config.region_size)
local high_x=math.min(1,cx+config.region_size)
local high_y=math.min(1,cy+config.region_size)
map_region={low_x,high_x,low_y,high_y}
reset_buffers("noise")
end
imgui.SameLine()
if imgui.Button("Zoom out") then
config.region_size=config.region_size*2
local cx=(map_region[2]-map_region[1])/2
local cy=(map_region[4]-map_region[3])/2
local low_x=math.max(0,cx-config.region_size)
local low_y=math.max(0,cy-config.region_size)
local high_x=math.min(1,cx+config.region_size)
local high_y=math.min(1,cy+config.region_size)
map_region={low_x,high_x,low_y,high_y}
reset_buffers("noise")
end
if imgui.Button("Save image") then
need_save=true
end
imgui.SameLine()
if imgui.Button("Save Gif") then
print(img_buf.w,img_buf.h)
if giffer~=nil then
giffer:stop()
end
giffer=gif_saver(string.format("saved_%d.gif",os.time(os.date("!*t"))),
img_buf,500,15)
end
imgui.SameLine()
if imgui.Button("Stop Gif") then
if giffer then
giffer:stop()
giffer=nil
end
end
imgui.SameLine()
if imgui.Button("Print math") then
print(thingy_string)
end
if imgui.Button("norm") then
do_normalize="single"
end
if imgui.Button("Start animate") then
anim_state.current_frame=0
config.animate=true
end
imgui.End()
end
function save_img( id )
--make_image_buffer()
--img_buf=make_image_buffer(size[1],size[2])
local config_serial=__get_source().."\n--AUTO SAVED CONFIG:\n"
for k,v in pairs(config) do
if type(v)~="table" then
config_serial=config_serial..string.format("config[%q]=%s\n",k,v)
end
end
config_serial=config_serial.."\n"..string.format("thingy_string=%q",thingy_string)
config_serial=config_serial.."\n"..string.format("feed_kill_string=%q",feed_kill_string)
img_buf:read_frame()
if id then
img_buf:save(string.format("video/saved (%d).png",id),config_serial)
else
img_buf:save(string.format("saved_%d.png",os.time(os.date("!*t"))),config_serial)
end
end
function find_min_max( buf )
buf:use(0,0,0)
local lmin={math.huge,math.huge,math.huge,math.huge}
local lmax={-math.huge,-math.huge,-math.huge,-math.huge}
io_buffer:read_texture(buf)
local count=0
for x=0,io_buffer.w-1 do
for y=0,io_buffer.h-1 do
local v=io_buffer:get(x,y)
if v.r<lmin[1] then lmin[1]=v.r end
if v.g<lmin[2] then lmin[2]=v.g end
if v.b<lmin[3] then lmin[3]=v.b end
if v.a<lmin[4] then lmin[4]=v.a end
if v.r>lmax[1] then lmax[1]=v.r end
if v.g>lmax[2] then lmax[2]=v.g end
if v.b>lmax[3] then lmax[3]=v.b end
if v.a>lmax[4] then lmax[4]=v.a end
end
end
return lmin,lmax
end
function draw_texture( id )
draw_shader:use()
local buf=react_buffer:get()
if config.do_sum then
buf=collect_buffer:get()
end
local need_normalize=
do_normalize or
(global_mm==nil) or
(config.do_norm) or
(giffer and giffer:want_frame() and not config.pause)
if need_normalize then
global_mm,global_mx=find_min_max(buf)
if do_normalize=="single" then
do_normalize=false
-- [[
print("=======================")
for i,v in ipairs(global_mm) do
print(i,v)
end
for i,v in ipairs(global_mx) do
print(i,v)
end
--]]
end
end
buf:use(0,0,0)
draw_shader:set_i('tex_main',0)
draw_shader:set("v_gamma",config.gamma)
draw_shader:set("v_gain",config.gain)
draw_shader:set_i("draw_comp",config.draw_comp)
local mm=global_mm
local mx=global_mx
-- [[
local mmin=math.min(mm[1],mm[2])
mmin=math.min(mmin,mm[3])
mmin=math.min(mmin,mm[4])
local mmax=math.max(mx[1],mm[2])
mmax=math.max(mmax,mm[3])
mmax=math.max(mmax,mm[4])
--]]
--[[
local mmin=mm[config.draw_comp+1]
local mmax=mx[config.draw_comp+1]
--]]
draw_shader:set("value_offset",-mm[1],-mm[2],-mm[3],-mm[4])
draw_shader:set("value_scale",1/(mx[1]-mm[1]),1/(mx[2]-mm[2]),1/(mx[3]-mm[3]),1/(mx[4]-mm[4]))
draw_shader:blend_disable()
draw_shader:draw_quad()
if need_save or id then
save_img(id)
if need_save=="r" then
reset_buffers("noise")
end
need_save=nil
end
if giffer and not config.pause then
if giffer:want_frame() then
img_buf:read_frame()
end
giffer:frame(img_buf)
end
end
function apply_sum_texture()
sum_texture:use()
local buf=react_buffer:get()
buf:use(0,0,0)
sum_texture:set_i('tex_main',0)
local cur_buff=collect_buffer:get()
local do_clamp
if config.clamp_edges then
do_clamp=1
else
do_clamp=0
end
cur_buff:use(1,0,do_clamp)
sum_texture:set_i("tex_old",1)
local next_buff=collect_buffer:get_next()
next_buff:use(2,0,do_clamp)
if not next_buff:render_to(collect_buffer.w,collect_buffer.h) then
error("failed to set framebuffer up")
end
--sum_texture:blend_disable()
sum_texture:blend_default()
sum_texture:draw_quad()
__render_to_window()
collect_buffer:advance()
end
function is_mouse_down( )
return __mouse.clicked1 and not __mouse.owned1, __mouse.x,__mouse.y
end
function is_mouse_down_0( ... )
return __mouse.clicked0 and not __mouse.owned0, __mouse.x,__mouse.y
end
function update( )
__no_redraw()
__clear()
__render_to_window()
gui()
if config.pause then
draw_texture()
else
sim_tick()
apply_sum_texture()
local save_id
if config.animate then
anim_state.current_frame=anim_state.current_frame+1
if anim_state.current_frame>anim_state.max_frame then
config.animate=false
end
if anim_state.current_frame % anim_state.frame_skip ==0 then
save_id=anim_state.current_frame/anim_state.frame_skip
end
end
draw_texture(save_id)
end
local c0
local c,x,y= is_mouse_down()
c0,x,y= is_mouse_down_0()
if c or c0 then
local scale_x
local scale_y
local offset_x=map_region[1]
local offset_y=map_region[3]
if map_region[1]>=0 then
scale_x=map_region[2]-map_region[1]
scale_y=map_region[4]-map_region[3]
else
scale_x=1
scale_y=1
offset_x=0
offset_y=0
end
local xx=(x/size[1])*scale_x+offset_x
local yy=(1-y/size[2])*scale_y+offset_y
print(string.format("Center(%g,%g), width:%g",xx,yy,config.region_size))
if c then
config["k"..mapping_parameters[1]]=xx
config["k"..mapping_parameters[2]]=yy
--config.k3=xx
-- [[
local low_x=math.max(0,xx-config.region_size)
local low_y=math.max(0,yy-config.region_size)
local high_x=math.min(1,xx+config.region_size)
local high_y=math.min(1,yy+config.region_size)
--]]
--[[
local low_x=xx-config.region_size
local low_y=yy-config.region_size
local high_x=xx+config.region_size
local high_y=yy+config.region_size
--]]
map_region={low_x,high_x,low_y,high_y}
reset_buffers("noise")
config.region_size=config.region_size/2
end
end
end
|
function help()
print('Usage: wh workbit {<network file path> | namespace <namespace>}')
end
if arg[2] == 'help' then
return help()
end
local conf
local idx
if arg[2] and arg[2] ~= "namespace" then
local err
conf, err = openconf(arg[2])
if not conf then
printf("error: %s", err)
return -1
end
idx = 3
else
idx = 2
end
if not conf then
conf = parsearg(idx, {
namespace=tostring,
})
if not conf.namespace then
conf.namespace = wh.DEFAULT_NAMESPACE
end
end
local k = io.stdin:read()
local ok, value = pcall(wh.fromb64, k)
if not ok then
printf("Invalid name: %s", value)
return
end
k = value
local wb = wh.workbit(k, conf.namespace or 'public')
print(wb)
|
-- Copyright 2015 Google Inc. All rights reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- Write stats to stdout in CSV format, for simpler parsing by PKB.
function done(summary, latency, requests)
io.write("==CSV==\n")
io.write("variable,value,unit\n")
for _, p in pairs({ 5, 25, 50, 75, 90, 99, 99.9 }) do
n = latency:percentile(p)
io.write(string.format("p%g latency,%g,ms\n", p, n / 1000))
end
local errors = summary.errors.connect + summary.errors.read +
summary.errors.write + summary.errors.timeout
local data = {
{'bytes transferred', summary.bytes, 'bytes'},
{'errors', errors, 'n'},
{'requests', summary.requests, 'n'},
{'throughput',
summary.requests / summary.duration * 1e6,
'requests/sec'}
}
for _, p in pairs(data) do
io.write(string.format("%s,%g,%s\n", p[1], p[2], p[3]))
end
end
|
--[[
MIT License
Copyright (c) 2020 DekuJuice
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.
]]--
-- An interface to a scene file.
local binser = require("enginelib.binser")
local Resource = require("class.engine.resource.Resource")
local PackedScene = Resource:subclass("PackedScene")
PackedScene.static.extensions = {"scene"}
PackedScene.static.dontlist = true
PackedScene:export_var("data", "data")
function PackedScene:instance()
local node_list = binser.deserialize(self.data)[1]
local root
if node_list[1].filepath then
root = resource.get_resource(node_list[1].filepath):instance()
else
root = node_list[1].class()
end
for k,v in pairs(node_list[1].properties) do
local setter = ("set_%s"):format(k)
root[setter](root, v)
end
for i = 2, #node_list do
local info = node_list[i]
if info.class then
info.node = info.class()
elseif info.filepath then
info.node = resource.get_resource(info.filepath):instance()
else
info.node = root:get_node(info.path)
end
local node = info.node
if not node then
log.warn("Missing node, inherited scene was changed?")
goto CONTINUE
end
for k,v in pairs(info.properties) do
local setter = ("set_%s"):format(k)
node[setter](node, v)
end
if not info.path then
root:get_node(info.parent):add_child(node)
end
node:set_owner(root)
::CONTINUE::
end
-- Do second pass to connect signals
for _, info in ipairs(node_list) do
local node = info.node
for _,connection in ipairs(info.signals) do
node:connect(connection.signal, root:get_node(connection.target_path), connection.method)
end
end
root:set_filepath( self:get_filepath() )
return root
end
-- Packs the given root node into scene data
-- Only nodes owned by the root (+ the root itself) are saved
-- Only signals between children of root or to autoload nodes are preserved
function PackedScene:pack(root)
-- Idea: Keep a list of all resources referenced for preloading purposes?
-- Nodes are listed in preorder to make reconstruction of
-- the tree easier
local instance_defaults = {}
local node_list = {}
-- Serialize nodes
local stack = { root }
while #stack > 0 do
local top = table.remove(stack)
-- Ignore children of instanced nodes that aren't part of an inherited scene
if top ~= root and top:get_owner() ~= root then goto CONTINUE end
local instanced = top:get_filepath() ~= nil
local inherited = top:get_is_inherited_scene()
-- Node was instanced from a file, load the default values for comparison
if instanced then
instance_defaults[top:get_filepath()] = resource.get_resource( top:get_filepath() ):instance()
end
local exported_vars = top.class:get_exported_vars()
local node_info = {
properties = {},
signals = {}
}
-- Create list of outgoing signals
-- Signals pointing to things outside the tree are discarded
for signal in pairs(top.class:get_signals()) do
for _, connection in ipairs(top:get_connections(signal)) do
if connection.target:get_tree() == top:get_tree() then
table.insert(node_info.signals, {
signal = signal,
target_path = connection.target:get_relative_path(root),
method = connection.method
})
end
end
end
-- Non root nodes are given the path of their parent
-- Since we're traversing in preorder if we add children back
-- when instancing the children will still be in the same order
if top ~= root then
node_info.parent = top:get_parent():get_relative_path(root)
end
-- Cases:
-- Node is root node of instanced scene
-- Node is part of inherited scene
-- Normal node
if instanced then
node_info.filepath = top:get_filepath()
elseif not inherited then
node_info.class = top.class
else
node_info.path = top:get_relative_path(root)
end
-- If node is instanced or inherited, only save properties that were modified from the default
if instanced or inherited then
local base
if instanced then
base = instance_defaults[top:get_filepath()]
else
local owner = top:get_owner()
base = instance_defaults[owner:get_filepath()]:get_node( top:get_relative_path(owner) )
end
for name in pairs(exported_vars) do
local getter = ("get_%s"):format(name)
local v = top[getter](top)
local bv = base[getter](base)
if v ~= bv then
node_info.properties[name] = v
end
end
else -- Otherwise save properties that differ from class defaults
for name, ep in pairs(exported_vars) do
local getter = ("get_%s"):format(name)
local v = top[getter](top)
if v ~= ep.default then
node_info.properties[name] = v
end
end
end
table.insert(node_list, node_info)
-- Include children only if owner is root node
for _,c in ipairs(top:get_children()) do
if c:get_owner() == root then
table.insert(stack, c)
end
end
::CONTINUE::
end
-- Do second pass for
self.data = binser.serialize(node_list)
end
return PackedScene
|
return {
require('routing.routes.plain').new,
require('routing.routes.choice').new,
require('routing.routes.curly').new,
require('routing.routes.pattern').new
}
|
cfg = {}
-----------------------------------------------------------------------------------------------------------------------------------------
-- START FARM
-----------------------------------------------------------------------------------------------------------------------------------------
cfg.StartCoords = {
{ type = "Roxos", perm = "PurplePermission", coords = vector3(104.03,6329.56,31.38), blipname = "Coletar Adubo" },
{ type = "Amarelos", perm = "YellowPermission", coords = vector3(-1103.18,4953.34,218.65), blipname = "Coletar Folha de Coca" },
{ type = "Vermelhos", perm = "RedPermission", coords = vector3(1491.02,6396.32,20.79), blipname = "Coletar Acido de Bateria" },
{ type = "Mafia", perm = "mafia.permissao", coords = vector3(-2674.45,1335.87,144.25), blipname = "Coletar Pecas de Armas" },
{ type = "Serpentes", perm = "serpentes.permissao", coords = vector3(1401.59,1139.27,109.75), blipname = "Coletar Pecas de Armas" },
{ type = "Motoclub", perm = "motoclub.permissao", coords = vector3(885.16,-3203.38,-98.19), blipname = "Coletar Capsulas" },
{ type = "Yakuza", perm = "yakuza.permissao", coords = vector3(2335.04,3057.49,48.16), blipname = "Coletar Pendrive com Informacoes" },
}
-----------------------------------------------------------------------------------------------------------------------------------------
-- FARM LOCATION
-----------------------------------------------------------------------------------------------------------------------------------------
cfg.FarmLocs = {
Roxos = {
[1] = { coords = vector3(-354.24,4825.14,144.3) },
[2] = { coords = vector3(0.73,3727.41,39.76) },
[3] = { coords = vector3(113.6,3701.28,39.76) },
[4] = { coords = vector3(898.74,3561.91,33.81) },
[5] = { coords = vector3(1428.12,3646.45,37.89) },
[6] = { coords = vector3(1789.22,3896.34,34.39) },
[7] = { coords = vector3(1753.38,3338.97,41.16) },
[8] = { coords = vector3(2523.9,4099.45,38.64) },
[9] = { coords = vector3(2141.75,4788.99,40.98) },
[10] = { coords = vector3(2442.86,4985.11,46.82) },
[11] = { coords = vector3(2191.89,5598.8,53.71) },
[12] = { coords = vector3(1743.89,6412.28,35.05) },
[13] = { coords = vector3(-149.89,6416.17,31.92) },
[14] = { coords = vector3(-312.68,6303.96,32.49) },
[15] = { coords = vector3(-779.23,5397.78,34.07), final = true },
},
Amarelos = {
[1] = { coords = vector3(-354.24,4825.14,144.3) },
[2] = { coords = vector3(0.73,3727.41,39.76) },
[3] = { coords = vector3(113.6,3701.28,39.76) },
[4] = { coords = vector3(898.74,3561.91,33.81) },
[5] = { coords = vector3(1428.12,3646.45,37.89) },
[6] = { coords = vector3(1789.22,3896.34,34.39) },
[7] = { coords = vector3(1753.38,3338.97,41.16) },
[8] = { coords = vector3(2523.9,4099.45,38.64) },
[9] = { coords = vector3(2141.75,4788.99,40.98) },
[10] = { coords = vector3(2442.86,4985.11,46.82) },
[11] = { coords = vector3(2191.89,5598.8,53.71) },
[12] = { coords = vector3(1743.89,6412.28,35.05) },
[13] = { coords = vector3(-149.89,6416.17,31.92) },
[14] = { coords = vector3(-312.68,6303.96,32.49) },
[15] = { coords = vector3(-779.23,5397.78,34.07), final = true },
},
Vermelhos = {
[1] = { coords = vector3(-354.24,4825.14,144.3) },
[2] = { coords = vector3(0.73,3727.41,39.76) },
[3] = { coords = vector3(113.6,3701.28,39.76) },
[4] = { coords = vector3(898.74,3561.91,33.81) },
[5] = { coords = vector3(1428.12,3646.45,37.89) },
[6] = { coords = vector3(1789.22,3896.34,34.39) },
[7] = { coords = vector3(1753.38,3338.97,41.16) },
[8] = { coords = vector3(2523.9,4099.45,38.64) },
[9] = { coords = vector3(2141.75,4788.99,40.98) },
[10] = { coords = vector3(2442.86,4985.11,46.82) },
[11] = { coords = vector3(2191.89,5598.8,53.71) },
[12] = { coords = vector3(1743.89,6412.28,35.05) },
[13] = { coords = vector3(-149.89,6416.17,31.92) },
[14] = { coords = vector3(-312.68,6303.96,32.49) },
[15] = { coords = vector3(-779.23,5397.78,34.07), final = true },
},
Mafia = {
[1] = { coords = vector3(-174.42,6548.54,11.14) },
[2] = { coords = vector3(-2174.40,4287.76,49.08) },
[3] = { coords = vector3(1738.06,3325.96,41.22) },
[4] = { coords = vector3(1388.46,3612.56,38.94) },
[5] = { coords = vector3(912.70,3555.37,33.86) },
[6] = { coords = vector3(914.14,3657.31,32.50) },
[7] = { coords = vector3(-1055.16,4921.26,211.81) },
[8] = { coords = vector3(-1150.40,4940.95,222.26) },
[9] = { coords = vector3(-2294.30,3191.87,32.81) },
[10] = { coords = vector3(-2542.07,2300.32,33.21) },
[11] = { coords = vector3(-3187.55,1050.45,20.88) },
[12] = { coords = vector3(529.31,-1940.16,24.98), final = true },
},
Serpentes = {
[1] = { coords = vector3(-174.42,6548.54,11.14) },
[2] = { coords = vector3(-2174.40,4287.76,49.08) },
[3] = { coords = vector3(1738.06,3325.96,41.22) },
[4] = { coords = vector3(1388.46,3612.56,38.94) },
[5] = { coords = vector3(912.70,3555.37,33.86) },
[6] = { coords = vector3(914.14,3657.31,32.50) },
[7] = { coords = vector3(-1055.16,4921.26,211.81) },
[8] = { coords = vector3(-1150.40,4940.95,222.26) },
[9] = { coords = vector3(-2294.30,3191.87,32.81) },
[10] = { coords = vector3(-2542.07,2300.32,33.21) },
[11] = { coords = vector3(-3187.55,1050.45,20.88) },
[12] = { coords = vector3(529.31,-1940.16,24.98), final = true },
},
Motoclub = {
[1] = { coords = vector3(-3068.87,3328.0,8.8) },
[2] = { coords = vector3(439.38,3561.53,33.240) },
[3] = { coords = vector3(1601.67,3562.69,35.37) },
[4] = { coords = vector3(1310.24,4386.92,41.23) },
[5] = { coords = vector3(1943.85,4647.04,40.63) },
[6] = { coords = vector3(1736.61,6423.25,34.39) },
[7] = { coords = vector3(-758.16,5600.44,33.83) },
[8] = { coords = vector3(264.26,3096.01,42.79) },
[9] = { coords = vector3(2867.29,1506.66,24.57) },
[10] = { coords = vector3(2544.2,377.0,108.62) },
[11] = { coords = vector3(2505.42,-333.5,93.0) },
[12] = { coords = vector3(1126.87,-1302.52,34.73), final = true },
},
Yakuza = {
[1] = { coords = vector3(-1063.08,-249.14,44.03), heading = 306.79 },
[2] = { coords = vector3(30.26,-1339.43,29.5), heading = 24.06 },
[3] = { coords = vector3(1076.26,-1978.89,31.48), heading = 141.88 },
[4] = { coords = vector3(1324.12,-1649.6,52.28), heading = 118.96 },
[5] = { coords = vector3(1272.33,-1711.51,54.78), heading = 49.72 },
[6] = { coords = vector3(319.61,180.37,103.59), heading = 234.89 },
[7] = { coords = vector3(-560.7,281.9,85.68), heading = 255.1 },
[8] = { coords = vector3(-1448.71,-237.95,49.82), heading = 52.84 },
[9] = { coords = vector3(-3048.1,587.64,7.91), heading = 135.54 },
[10] = { coords = vector3(544.32,2662.76,42.21), heading = 228.62, final = true },
},
}
-----------------------------------------------------------------------------------------------------------------------------------------
-- FARM ITEMS
-----------------------------------------------------------------------------------------------------------------------------------------
cfg.FarmItems = {
Roxos = {
item = { item = "adubo", a1 = 4, a2 = 7, times = 1 },
},
Amarelos = {
item = { item = "folhadecoca", a1 = 4, a2 = 7, times = 1 },
},
Vermelhos = {
item = { item = "acidobateria", a1 = 4, a2 = 7, times = 1 },
},
Mafia = {
item = { item = "pecadearma", a1 = 3, a2 = 5, item2 = "dinheirosujo", a3 = 150, a4 = 200, times = 2 },
},
Serpentes = {
item = { item = "pecadearma", a1 = 3, a2 = 5, item2 = "dinheirosujo", a3 = 150, a4 = 200, times = 2 },
},
Motoclub = {
item = { item = "polvora", a1 = 100, a2 = 120, times = 1 },
},
Yakuza = {
item = { item = "pendriveinformacoes", a1 = 20, a2 = 25, times = 1 },
},
}
|
local args = { ... }
local version = args[1] or '1.1.0'
local installDir = ''
local repoOwner = 'imevul'
local repoName = 'imevul-ui'
---@class Installer
local Installer = {}
---Download a single file to a target folder
---@param url string URL of item to download
---@param target string Target path
function Installer:downloadItem(url, target)
local request = http.get(url)
if request == nil then
error(('Failed to download %s to %s'):format(url, target))
end
local file = fs.open(target, 'w')
file.write(request.readAll())
file.close()
request.close()
end
---Recursively download items into their correct target path
---@param items table Table containing items to download
---@param path string Target path to download them to
function Installer:downloadItems(items, path)
for _, v in ipairs(items) do
if v.url == nil then
self:downloadItems(v.items, path .. '/' .. v.path)
else
print(('Downloading %s to %s'):format(v.path, path))
self:downloadItem(v.url, path .. '/' .. v.path)
end
end
end
---Fetches downloadable items from a GitHub repository and then downloads them
---@param owner string Name of the repository owner
---@param repo string Name of the repository
---@param sha string sha hash, or name of branch or tag
---@param filters table List of folders to download. All others will be skipped
function Installer:downloadGitHubRepo(owner, repo, sha, filters)
local items = self:getGitHubTree(owner, repo, sha, filters)
self:downloadItems(items, installDir)
end
---Recursively fetch a specific GitHub tree (files+folders)
---@param owner string Name of the repository owner
---@param repo string Name of the repository
---@param sha string sha hash, or name of branch or tag
---@param filters table A list of folders to download. All others will be skipped
function Installer:getGitHubTree(owner, repo, sha, filters)
local url = ('https://api.github.com/repos/%s/%s/git/trees/%s'):format(owner, repo, sha)
local request = http.get(url, {
Accept = 'application/vnd.github.v3+json'
})
if request == nil then
error(('Could not reach GitHub API for %s/%s (%s). Either the version does not exist, or the API limit has been reached'):format(owner, repo, sha))
end
local response = textutils.unserializeJSON(request.readAll())
local items = {}
for _, v in ipairs(response.tree) do
local found = true
if type(filters) == 'table' then
found = false
for _, v2 in ipairs(filters) do
if v2 == v.path then
found = true
break
end
end
end
if found then
if v.type == 'tree' then
local subTree = self:getGitHubTree(owner, repo, v.sha)
table.insert(items, {
path = v.path,
url = nil,
items = subTree
})
elseif v.type == 'blob' then
table.insert(items, {
path = v.path,
url = v.url,
items = {}
})
end
end
end
return items
end
---Installs the library to the default location
function Installer:install()
print('Installing imevul/ui')
print('Removing old files')
fs.delete(installDir .. 'imevul/ui')
print(('Downloading GitHub repo %s/%s (%s) to %s'):format(repoOwner, repoName, version, installDir))
self:downloadGitHubRepo(repoOwner, repoName, version, { 'imevul' })
print('Done')
end
---Uninstalls from the default location
function Installer:uninstall()
print('Uninstalling imevul/ui')
fs.delete(installDir .. 'imevul/ui')
print('Done')
end
if version == 'remove' then
Installer:uninstall()
else
Installer:install()
end
|
--[[
# Element: Status Indicator
Combines the combat and resting indicators.
## Widget
StatusIndicator - A texture.
## Notes
Custom Textures are not supported
## Examples
-- Position and size
local StatusIndicator = self:CreateTexture(nil, 'OVERLAY')
StatusIndicator:SetSize(16, 16)
StatusIndicator:SetPoint('TOPLEFT', self)
-- Register it with oUF
self.StatusIndicator = StatusIndicator
--]]
local _, ns = ...
local oUF = _G.oUF or ns.oUF
local function Update(self, event)
local element = self.StatusIndicator
local unit = self.unit
--[[ Callback: StatusIndicator:PreUpdate()
Called before the element has been updated.
* self - the StatusIndicator element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local inCombat = UnitAffectingCombat(unit)
local isResting = IsResting()
if(inCombat) then
element:Show()
if(element:IsObjectType("Texture")) then
element:SetTexCoord(.5, 1, 0, .49)
end
elseif(isResting and unit == "player") then
element:Show()
if(element:IsObjectType("Texture")) then
element:SetTexCoord(0, 0.5, 0, 0.421875)
end
else
element:Hide()
end
--[[ Callback: StatusIndicator:PostUpdate(inCombat, isResting)
Called after the element has been updated.
* self - the StatusIndicator element
* inCombat - indicates whether the unit is currently in combat (boolean)
* isResting - indicates whether the unit is currently resting (boolean)
--]]
if(element.PostUpdate) then
return element:PostUpdate(inCombat, isResting)
end
end
local function Path(self, ...)
--[[ Override: StatusIndicator.Override(self, event, ...)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* ... - the arguments accompanying the event
--]]
return (self.StatusIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, "ForceUpdate")
end
local function Enable(self)
local element = self.StatusIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('UNIT_COMBAT', Path)
self:RegisterEvent('UNIT_FLAGS', Path)
self:RegisterEvent('PLAYER_REGEN_DISABLED', Path, true)
self:RegisterEvent('PLAYER_REGEN_ENABLED', Path, true)
self:RegisterEvent("PLAYER_UPDATE_RESTING", Path, true)
if(element:IsObjectType("Texture") and not element:GetTexture()) then
element:SetTexture([[Interface\CharacterFrame\UI-StateIcon]])
end
return true
end
end
local function Disable(self)
local element = self.StatusIndicator
if(element) then
element:Hide()
self:UnregisterEvent('UNIT_COMBAT', Path)
self:UnregisterEvent('UNIT_FLAGS', Path)
self:UnregisterEvent('PLAYER_REGEN_DISABLED', Path)
self:UnregisterEvent('PLAYER_REGEN_ENABLED', Path)
self:UnregisterEvent("PLAYER_UPDATE_RESTING", Path)
end
end
oUF:AddElement("StatusIndicator", Path, Enable, Disable)
|
require ("libluaauto")
some_funs.add(3.3, 4.2)
some_funs.sub(3.3,2.1)
t=Tesla.create()
t:music("don't break my heart.")
t:navi("beijing")
t:fuel(3332)
t:drive("moto", 321, 2.4)
t:charge(3.3, 2)
t:bluetooth("apple")
t=nil
collectgarbage()
|
local WeightedSmoothL1Criterion, parent = torch.class("detection.WeightedSmoothL1Criterion", "nn.Criterion")
function WeightedSmoothL1Criterion:__init(sizeAverage)
parent.__init(self)
-- Local SmoothL1Loss
self._smoothL1Loss = nn.SmoothL1Criterion():cuda()
self._smoothL1Loss.sizeAverage = false
end
function WeightedSmoothL1Criterion:updateOutput(input, target)
-- input contains the output of the network
-- target has the labels as the first element and loss weights as the second element
local repeat_size = input:size(2) / target[1]:size(2)
local targets = target[1]:repeatTensor(1, repeat_size)
local weights = target[2]
local n_row = targets:size(1)
local cur_input = input[weights]
local cur_target = targets[weights]
if cur_input:numel() == 0 then
-- This sample does not have any gts
return 0.0
end
self.output = self._smoothL1Loss:forward(cur_input, cur_target)
self.output = self.output / n_row
return self.output
end
function WeightedSmoothL1Criterion:updateGradInput(input, target)
local repeat_size = input:size(2) / target[1]:size(2)
local targets = target[1]:repeatTensor(1, repeat_size)
local weights = target[2]
local n_row = targets:size(1)
self.gradInput:resizeAs(input):zero()
local cur_input = input[weights]
local cur_target = targets[weights]
if cur_input:numel() > 0 then
local smoothL1grad = self._smoothL1Loss:backward(cur_input, cur_target) / n_row
self.gradInput[weights] = smoothL1grad
end
return self.gradInput
end
|
--[[By: @V3N0M_Z]]
local inheritance = require(script.Parent.Node)
local node = {}
node.__index = node
setmetatable(node, inheritance)
function node.new(plugin, pluginDisplay, id)
local self = setmetatable(inheritance.new("SelectionNode", plugin, pluginDisplay, id), node)
self._settings = {
title = function(txt) self._frame.Title.Text = txt end;
placeholder = function(txt) self._input.PlaceholderText = txt end;
ignoreCase = function(enabled)
if not enabled then
self._frame.IgnoreCase:Destroy()
self._frame.IgnoreCaseLabel:Destroy()
self._frame.Size = self._frame.Size + UDim2.new(0, 0, 0, -25)
self._ignoreCase = nil
end
end;
}
self:SetSelectionComponents()
self:Transition(1, true, nil, true)
self._frame.Parent = pluginDisplay
self:Forge({
self._input:GetPropertyChangedSignal("Text"):Connect(function()
self._selectionIndex = nil
self:UpdateSelection()
end)
})
return self
end
function node:UpdateSelection()
if not self._selectionIndex then
self._currentSelection.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
else
self._currentSelection.BackgroundColor3 = Color3.fromRGB(180, 180, 180)
end
end
local selectionService = game:GetService("Selection")
function node:ParseInput(enterPressed)
if enterPressed and not self._selectionIndex then
local children = {}
for _, obj in ipairs(game:GetDescendants()) do
if obj.Name == self._input.Text or (self._ignoreCase and self._ignoreCase.Visible and string.lower(obj.Name) == string.lower(self._input.Text)) then
table.insert(children, obj)
end
end
selectionService:Set(children)
local selection = selectionService:Get()
return {selectionService:Get(), (self._ignoreCase and self._ignoreCase.Visible)}
elseif enterPressed and self._selectionIndex then
return {selectionService:Get(), (self._ignoreCase and self._ignoreCase.Visible)}
end
return {}
end
function node:SetSelectionComponents()
self._selection = true
self._currentSelection = self._frame.FromSelection
self._frame.FromSelection.MouseButton1Click:Connect(function()
self._selectionIndex = 1
self:Destroy(true)
end)
end
return node
|
data:extend(
{
{
type = "car",
name = "land-robot",
icon = "__base__/graphics/icons/logistic-robot.png",
icon_size = 32,
flags = {"placeable-neutral", "player-creation"},
minable = {mining_time = 1, result = "land-robot"},
mined_sound = {filename = "__core__/sound/deconstruct-medium.ogg"},
max_health = 50,
corpse = "small-remnants",
alert_icon_shift = util.by_pixel(0, -13),
energy_per_hit_point = 1,
crash_trigger = crash_trigger(),
resistances =
{
{
type = "fire",
percent = 50
},
{
type = "impact",
percent = 30,
decrease = 50
}
},
collision_box = {{-0.5, -0.5}, {0.5, 0.5}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
effectivity = 0.5,
braking_power = "200kW",
burner =
{
fuel_category = "chemical",
effectivity = 0.6,
fuel_inventory_size = 1,
smoke =
{
{
name = "smoke",
deviation = {0.1, 0.1},
frequency = 9
}
}
},
consumption = "10kW",
friction = 1e-3,
light =
{
{
type = "oriented",
minimum_darkness = 0.3,
picture =
{
filename = "__core__/graphics/light-cone.png",
priority = "extra-high",
flags = { "light" },
scale = 2,
width = 200,
height = 200
},
shift = {0, -10},
size = 2,
intensity = 0.6,
color = {r = 0.92, g = 0.77, b = 0.3}
}
},
render_layer = "object",
animation =
{
layers =
{
{
filename = "__base__/graphics/entity/logistic-robot/logistic-robot.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
hr_version = {
filename = "__base__/graphics/entity/logistic-robot/hr-logistic-robot.png",
priority = "high",
line_length = 16,
width = 80,
height = 84,
frame_count = 1,
shift = util.by_pixel(0, -3),
direction_count = 16,
scale = 0.5
}
}
}
},
sound_no_fuel =
{
{
filename = "__base__/sound/fight/car-no-fuel-1.ogg",
volume = 0.2
}
},
stop_trigger_speed = 0.2,
stop_trigger =
{
{
type = "play-sound",
sound =
{
{
filename = "__base__/sound/car-breaks.ogg",
volume = 0.2
}
}
}
},
sound_minimum_speed = 0.2;
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound =
{
filename = "__base__/sound/car-engine.ogg",
volume = 0.2
},
activate_sound =
{
filename = "__base__/sound/car-engine-start.ogg",
volume = 0.2
},
deactivate_sound =
{
filename = "__base__/sound/car-engine-stop.ogg",
volume = 0.2
},
match_speed_to_activity = true,
},
open_sound = { filename = "__base__/sound/car-door-open.ogg", volume=0.7 },
close_sound = { filename = "__base__/sound/car-door-close.ogg", volume = 0.7 },
rotation_speed = 0.01,
weight = 100,
guns = { },
inventory_size = 10,
tank_driving = true
}
})
|
local Class = require "Base.Class"
local ControlBranch = require "Unit.ControlBranch"
local Pitch = require "Unit.ViewControl.Pitch"
local PitchBranch = Class {
classType = "Pitch",
classDescription = "Pitch",
classPrefix = "tune"
}
PitchBranch:include(ControlBranch)
function PitchBranch:init(args)
local id = args.id or app.logError("%s:init: id is missing.", self)
local tune = app.ConstantOffset()
tune:setName(id)
local range = app.MinMax()
range:setName(id)
connect(tune, "Out", range, "In")
args.leftDestination = tune:getInput("In")
args.leftOutObject = tune
args.leftOutletName = "Out"
args.channelCount = 1
args.objects = {
tune,
range
}
ControlBranch.init(self, args)
self:setClassName("Unit.ControlBranch.Pitch")
self.control = Pitch {
button = id,
description = args.description or PitchBranch.classDescription,
branch = self,
offset = tune,
range = range
}
end
return PitchBranch
|
if SILE.outputter ~= SILE.outputters.libtexpdf then
SU.error("pdf package requires libtexpdf backend")
end
local pdf = require("justenoughlibtexpdf")
SILE.registerCommand("pdf:destination", function (options, content)
local name = SU.required(options, "name", "pdf:bookmark")
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
pdf.destination(name, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY)
end
})
end)
SILE.registerCommand("pdf:bookmark", function (options, content)
local dest = SU.required(options, "dest", "pdf:bookmark")
local title = SU.required(options, "title", "pdf:bookmark")
local level = options.level or 1
-- Added UTF8 to UTF16-BE conversion
-- For annotations and bookmarks, text strings must be encoded using
-- either PDFDocEncoding or UTF16-BE with a leading byte-order marker.
-- As PDFDocEncoding supports only limited character repertoire for
-- European languages, we use UTF-16BE for internationalization.
local ustr = SU.utf8_to_utf16be_hexencoded(title)
SILE.typesetter:pushHbox({
value = nil, height = 0, width = 0, depth = 0,
outputYourself = function ()
local d = "<</Title<" .. ustr .. ">/A<</S/GoTo/D(" .. dest .. ")>>>>"
pdf.bookmark(d, level)
end
})
end)
if SILE.Commands.tocentry then
SILE.scratch.pdf = { dests = {}, dc = 1 }
local oldtoc = SILE.Commands.tocentry
SILE.Commands.tocentry = function (options, content)
SILE.call("pdf:destination", { name = "dest" .. SILE.scratch.pdf.dc } )
local title = SU.contentToString(content)
SILE.call("pdf:bookmark", { title = title, dest = "dest" .. SILE.scratch.pdf.dc, level = options.level })
oldtoc(options, content)
SILE.scratch.pdf.dc = SILE.scratch.pdf.dc + 1
end
end
SILE.registerCommand("pdf:literal", function (options, content)
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self, typesetter)
pdf.add_content(content[1])
end
})
end)
SILE.registerCommand("pdf:link", function (options, content)
local dest = SU.required(options, "dest", "pdf:link")
local target = options.external and "/Type/Action/S/URI/URI" or "/S/GoTo/D"
local llx, lly
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
llx = typesetter.frame.state.cursorX
lly = SILE.documentState.paperSize[2] - typesetter.frame.state.cursorY
pdf.begin_annotation()
end
})
local hbox = SILE.Commands["hbox"]({}, content) -- hack
SILE.typesetter:pushHbox({
value = nil,
height = 0,
width = 0,
depth = 0,
outputYourself = function (self,typesetter)
local d = "<</Type/Annot/Subtype/Link/C [ 1 0 0 ]/A<<" .. target .. "(" .. dest .. ")>>>>"
pdf.end_annotation(d, llx, lly, typesetter.frame.state.cursorX, SILE.documentState.paperSize[2] -typesetter.frame.state.cursorY + hbox.height)
end
})
end)
return { documentation = [[\begin{document}
The \code{pdf} package enables (basic) support for PDF links and table-of-contents
entries. It provides the three commands \command{\\pdf:destination}, \command{\\pdf:link}
and \command{\\pdf:bookmark}.
The \command{\\pdf:destination} parameter creates a link target; it expects a
parameter called \code{name} to uniquely identify the target. To create a link to
that location in the document, use \code{\\pdf:link[dest=\goodbreak{}name]\{link content\}}.
If the \code{pdf} package is loaded after the \code{tableofcontents} package (e.g.
in a document with the \code{book} class), then a PDF document outline will be generated.
\end{document}]] }
|
AssetLoader = AssetLoader or BaseClass()
function AssetLoader.GetInstance()
if AssetLoader._instance == nil then
AssetLoader._instance = AssetLoader.New()
end
return AssetLoader._instance
end
function AssetLoader:__init()
end
function AssetLoader:Load(path)
local result = Resources.Load(path)
return result
end
|
WIN_WIDTH = 800
WIN_HEIGHT = 800
V_SYNC = false
TITLE = "graphique"
|
bonemeal = {}
-- Load support for intllib.
local MP = minetest.get_modpath(minetest.get_current_modname())
local S, NS = dofile(MP .. "/intllib.lua")
-- creative check
local creative_mode_cache = minetest.settings:get_bool("creative_mode")
function is_creative(name)
return creative_mode_cache or minetest.check_player_privs(name, {creative = true})
end
-- default crops
local crops = {
{"farming:cotton_", 8, "farming:seed_cotton"},
{"farming:wheat_", 8, "farming:seed_wheat"},
}
-- special pine check for nearby snow
local function pine_grow(pos)
if minetest.find_node_near(pos, 1,
{"default:snow", "default:snowblock", "default:dirt_with_snow"}) then
default.grow_new_snowy_pine_tree(pos)
else
default.grow_new_pine_tree(pos)
end
end
-- default saplings
local saplings = {
{"default:sapling", default.grow_new_apple_tree, "soil"},
{"default:junglesapling", default.grow_new_jungle_tree, "soil"},
{"default:acacia_sapling", default.grow_new_acacia_tree, "soil"},
{"default:aspen_sapling", default.grow_new_aspen_tree, "soil"},
{"default:pine_sapling", pine_grow, "soil"},
{"default:bush_sapling", default.grow_bush, "soil"},
{"default:acacia_bush_sapling", default.grow_acacia_bush, "soil"},
}
-- helper tables ( "" denotes a blank item )
local green_grass = {
"default:grass_2", "default:grass_3", "default:grass_4",
"default:grass_5", "", ""
}
local dry_grass = {
"default:dry_grass_2", "default:dry_grass_3", "default:dry_grass_4",
"default:dry_grass_5", "", ""
}
local flowers = {
"flowers:dandelion_white", "flowers:dandelion_yellow", "flowers:geranium",
"flowers:rose", "flowers:tulip", "flowers:viola", ""
}
-- add additional bakedclay flowers if enabled
if minetest.get_modpath("bakedclay") then
flowers[7] = "bakedclay:delphinium"
flowers[8] = "bakedclay:thistle"
flowers[9] = "bakedclay:lazarus"
flowers[10] = "bakedclay:mannagrass"
flowers[11] = ""
end
-- default biomes deco
local deco = {
{"default:dirt_with_dry_grass", dry_grass, flowers},
{"default:sand", {}, {"default:dry_shrub", "", "", ""} },
{"default:desert_sand", {}, {"default:dry_shrub", "", "", ""} },
{"default:silver_sand", {}, {"default:dry_shrub", "", "", ""} },
}
----- local functions
-- particles
local function particle_effect(pos)
minetest.add_particlespawner({
amount = 4,
time = 0.15,
minpos = pos,
maxpos = pos,
minvel = {x = -1, y = 2, z = -1},
maxvel = {x = 1, y = 4, z = 1},
minacc = {x = -1, y = -1, z = -1},
maxacc = {x = 1, y = 1, z = 1},
minexptime = 1,
maxexptime = 1,
minsize = 1,
maxsize = 3,
texture = "bonemeal_particle.png",
})
end
-- tree type check
local function grow_tree(pos, object)
if type(object) == "table" and object.axiom then
-- grow L-system tree
minetest.remove_node(pos)
minetest.spawn_tree(pos, object)
elseif type(object) == "string" and minetest.registered_nodes[object] then
-- place node
minetest.set_node(pos, {name = object})
elseif type(object) == "function" then
-- function
object(pos)
end
end
-- sapling check
local function check_sapling(pos, nodename)
-- what is sapling placed on?
local under = minetest.get_node({
x = pos.x,
y = pos.y - 1,
z = pos.z
})
local can_grow, grow_on
-- check list for sapling and function
for n = 1, #saplings do
if saplings[n][1] == nodename then
grow_on = saplings[n][3]
-- sapling grows on top of specific node
if grow_on
and grow_on ~= "soil"
and grow_on ~= "sand"
and grow_on == under.name then
can_grow = true
end
-- sapling grows on top of soil (default)
if can_grow == nil
and (grow_on == nil or grow_on == "soil")
and minetest.get_item_group(under.name, "soil") > 0 then
can_grow = true
end
-- sapling grows on top of sand
if can_grow == nil
and grow_on == "sand"
and minetest.get_item_group(under.name, "sand") > 0 then
can_grow = true
end
-- check if we can grow sapling
if can_grow then
particle_effect(pos)
grow_tree(pos, saplings[n][2])
return
end
end
end
end
-- crops check
local function check_crops(pos, nodename, strength)
local stage, nod, def
-- grow registered crops
for n = 1, #crops do
if string.find(nodename, crops[n][1])
or nodename == crops[n][3] then
-- get stage number or set to 0 for seed
stage = tonumber( nodename:split("_")[2] ) or 0
stage = math.min(stage + strength, crops[n][2])
-- check for place_param setting
nod = crops[n][1] .. stage
def = minetest.registered_nodes[nod]
def = def and def.place_param2 or 0
minetest.set_node(pos, {name = nod, param2 = def})
particle_effect(pos)
return
end
end
end
-- check soil for specific decoration placement
local function check_soil(pos, nodename, strength)
-- set radius according to strength
local side = strength - 1
local tall = math.max(strength - 2, 0)
-- get area of land with free space above
local dirt = minetest.find_nodes_in_area_under_air(
{x = pos.x - side, y = pos.y - tall, z = pos.z - side},
{x = pos.x + side, y = pos.y + tall, z = pos.z + side},
{"group:soil", "group:sand"})
-- set default grass and decoration
local grass = green_grass
local decor = flowers
-- choose grass and decoration to use on dirt patch
for n = 1, #deco do
-- do we have a grass match?
if nodename == deco[n][1] then
grass = deco[n][2] or {}
decor = deco[n][3] or {}
end
end
local pos2, nod, def
-- loop through soil
for _,n in pairs(dirt) do
pos2 = n
pos2.y = pos2.y + 1
if math.random(1, 5) == 5 then
-- place random decoration (rare)
nod = decor[math.random(1, #decor)] or ""
else
-- place random grass (common)
nod = #grass > 0 and grass[math.random(1, #grass)] or ""
end
if nod and nod ~= "" then
def = minetest.registered_nodes[nod]
def = def and def.place_param2 or 0
minetest.set_node(pos2, {name = nod, param2 = def})
end
particle_effect(pos2)
end
end
-- global functions
-- add to sapling list
-- {sapling node, schematic or function name, "soil"|"sand"|specific_node}
--e.g. {"default:sapling", default.grow_new_apple_tree, "soil"}
function bonemeal:add_sapling(list)
for n = 1, #list do
table.insert(saplings, list[n])
end
end
-- add to crop list to force grow
-- {crop name start_, growth steps, seed node (if required)}
-- e.g. {"farming:wheat_", 8, "farming:seed_wheat"}
function bonemeal:add_crop(list)
for n = 1, #list do
table.insert(crops, list[n])
end
end
-- add grass and flower/plant decoration for specific dirt types
-- {dirt_node, {grass_nodes}, {flower_nodes}
-- e.g. {"default:dirt_with_dry_grass", dry_grass, flowers}
-- if an entry already exists for a given dirt type, it will add new entries and all empty
-- entries, allowing to both add decorations and decrease their frequency.
function bonemeal:add_deco(list)
for l = 1, #list do
for n = 1, #deco do
-- update existing entry
if list[l][1] == deco[n][1] then
-- adding grass types
for _,extra in ipairs(list[l][2]) do
if extra ~= "" then
for __,entry in ipairs(deco[n][2]) do
if extra == entry then
extra = false
break
end
end
end
if extra then
table.insert(deco[n][2], extra)
end
end
-- adding decoration types
for _,extra in ipairs(list[l][3]) do
if extra ~= "" then
for __,entry in ipairs(deco[n][3]) do
if extra == entry then
extra = false
break
end
end
end
if extra then
table.insert(deco[n][3], extra)
end
end
list[l] = false
break
end
end
if list[l] then
table.insert(deco, list[l])
end
end
end
-- definitively set a decration scheme
-- this function will either add a new entry as is, or replace the existing one
function bonemeal:set_deco(list)
for l = 1, #list do
for n = 1, #deco do
-- replace existing entry
if list[l][1] == deco[n][1] then
deco[n][2] = list[l][2]
deco[n][3] = list[l][3]
list[l] = false
break
end
end
if list[l] then
table.insert(deco, list[l])
end
end
end
-- global on_use function for bonemeal
function bonemeal:on_use(pos, strength, node)
-- get node pointed at
local node = node or minetest.get_node(pos)
-- return if nothing there
if node.name == "ignore" then
return
end
-- make sure strength is between 1 and 4
strength = strength or 1
strength = math.max(strength, 1)
strength = math.min(strength, 4)
-- papyrus and cactus
if node.name == "default:papyrus" then
default.grow_papyrus(pos, node)
particle_effect(pos)
return
elseif node.name == "default:cactus" then
default.grow_cactus(pos, node)
particle_effect(pos)
return
end
-- grow grass and flowers
if minetest.get_item_group(node.name, "soil") > 0
or minetest.get_item_group(node.name, "sand") > 0 then
check_soil(pos, node.name, strength)
return
end
-- light check depending on strength (strength of 4 = no light needed)
if (minetest.get_node_light(pos) or 0) < (12 - (strength * 3)) then
return
end
-- check for tree growth if pointing at sapling
if minetest.get_item_group(node.name, "sapling") > 0
and math.random(1, (5 - strength)) == 1 then
check_sapling(pos, node.name)
return
end
-- check for crop growth
check_crops(pos, node.name, strength)
end
----- items
-- mulch (strength 1)
minetest.register_craftitem("bonemeal:mulch", {
description = S("Mulch"),
inventory_image = "bonemeal_mulch.png",
on_use = function(itemstack, user, pointed_thing)
-- did we point at a node?
if pointed_thing.type ~= "node" then
return
end
-- is area protected?
if minetest.is_protected(pointed_thing.under, user:get_player_name()) then
return
end
-- take item if not in creative
if not is_creative(user:get_player_name()) then
itemstack:take_item()
end
-- call global on_use function with strength of 1
bonemeal:on_use(pointed_thing.under, 1)
return itemstack
end,
})
-- bonemeal (strength 2)
minetest.register_craftitem("bonemeal:bonemeal", {
description = S("Bone Meal"),
inventory_image = "bonemeal_item.png",
on_use = function(itemstack, user, pointed_thing)
-- did we point at a node?
if pointed_thing.type ~= "node" then
return
end
-- is area protected?
if minetest.is_protected(pointed_thing.under, user:get_player_name()) then
return
end
-- take item if not in creative
if not is_creative(user:get_player_name()) then
itemstack:take_item()
end
-- call global on_use function with strength of 2
bonemeal:on_use(pointed_thing.under, 2)
return itemstack
end,
})
-- fertiliser (strength 3)
minetest.register_craftitem("bonemeal:fertiliser", {
description = S("Fertiliser"),
inventory_image = "bonemeal_fertiliser.png",
on_use = function(itemstack, user, pointed_thing)
-- did we point at a node?
if pointed_thing.type ~= "node" then
return
end
-- is area protected?
if minetest.is_protected(pointed_thing.under, user:get_player_name()) then
return
end
-- take item if not in creative
if not is_creative(user:get_player_name()) then
itemstack:take_item()
end
-- call global on_use function with strength of 3
bonemeal:on_use(pointed_thing.under, 3)
return itemstack
end,
})
-- bone
minetest.register_craftitem("bonemeal:bone", {
description = S("Bone"),
inventory_image = "bonemeal_bone.png",
})
--- crafting recipes
-- bonemeal (from bone)
minetest.register_craft({
type = "shapeless",
output = "bonemeal:bonemeal 2",
recipe = {"bonemeal:bone"},
})
-- bonemeal (from player bones)
minetest.register_craft({
type = "shapeless",
output = "bonemeal:bonemeal 4",
recipe = {"bones:bones"},
})
-- bonemeal (from coral skeleton)
minetest.register_craft({
type = "shapeless",
output = "bonemeal:bonemeal 2",
recipe = {"default:coral_skeleton"},
})
-- mulch
minetest.register_craft({
type = "shapeless",
output = "bonemeal:mulch 4",
recipe = {
"group:tree", "group:leaves", "group:leaves",
"group:leaves", "group:leaves", "group:leaves",
"group:leaves", "group:leaves", "group:leaves"
},
})
-- fertiliser
minetest.register_craft({
type = "shapeless",
output = "bonemeal:fertiliser 2",
recipe = {"bonemeal:bonemeal", "bonemeal:mulch"},
})
-- add bones to dirt
minetest.override_item("default:dirt", {
drop = {
max_items = 1,
items = {
{
items = {"bonemeal:bone"},
rarity = 30,
},
{
items = {"default:dirt"},
}
}
},
})
-- add support for other mods
local path = minetest.get_modpath("bonemeal")
dofile(path .. "/mods.lua")
dofile(path .. "/lucky_block.lua")
print (S("[bonemeal] loaded"))
|
-- #############################################################################
-- # Battery Monitor - Lua application for JETI DC/DS transmitters
-- # Inspired by LI-xx BATTCHECK (Developped by Heisenberg, debugged by Sacre100)
-- #
-- # Copyright (c) 2016, JETI model s.r.o.
-- # All rights reserved.
-- #
-- # License: Share alike
-- # Can be used and changed non commercial
-- #
-- # V1.0 - Initial release
-- # V1.1 - Displayed voltage values for the graph axes
-- # V1.2 - The readFile() function has been replaced by internal io.readall() (DC/DS FW V4.22)
-- # Better displayed on DC/DS-16/14. Detection of inactive sensor.
-- # V1.3 - Improved translations to different languages
-- #############################################################################
--Configuration
local sensorId=0
--Local variables
local sensorsAvailable = {}
local lang
local options={}
local cellfull, cellempty = 4.2, 3.00
-- Lipo discharge table
local myArrayPercentList =
{
{3.000, 0},
{3.380, 5},
{3.580, 10},
{3.715, 15},
{3.747, 20},
{3.769, 25},
{3.791, 30},
{3.802, 35},
{3.812, 40},
{3.826, 45},
{3.839, 50},
{3.861, 55},
{3.883, 60},
{3.910, 65},
{3.936, 70},
{3.986, 75},
{3.999, 80},
{4.042, 85},
{4.085, 90},
{4.142, 95},
{4.170, 97},
{4.200, 100}
}
-- Minimum voltage
local cellminima = {cellfull, cellfull, cellfull, cellfull, cellfull, cellfull}
-- Maximum voltage
local cellmaxima = {0, 0, 0, 0, 0 ,0}
local cell = {0, 0, 0, 0, 0 ,0}
-- Statistics
local cellsumfull, cellsumempty, cellsumtype, cellsum = 0, 0, 0, 0
-- Icon positions - large window
local positions = {{170,90}, {170, 115}, {170, 140}, {250,90}, {250, 115}, {250, 140}}
-- Icon positions - small window
local positionsSmall = {{10,5}, {10, 27}, {10, 49}, {80,5}, {80, 27}, {80, 49}}
-- Local variables
local cellsumfull, cellsumempty, cellsumtype, cellsum = 0, 0, 0, 0
--X,Y coordinates
local echX, ech100Y, ech0Y = 210, 4, 70
local echH = (ech0Y-ech100Y)
-- Space between gauges
local gaugeW, gaugeGap = 12, 3
local i, cellmin, cellmax, cellresult = 0, cellfull, 0, 0
local cellsumpercent, precision, blink = 0, 0, 0
local cellsumpercentminima, cellsumpercentmaxima = 100, 0
local percentDelta
local sensorValid=false
--------------------------------------------------------------------
---- Calculate percentage voltage
--------------------------------------------------------------------
local function percentcell(targetVoltage)
local result = 0
if targetVoltage > cellfull or targetVoltage < cellempty then
if targetVoltage >= cellfull then
result = 100
end
if targetVoltage <= cellempty then
result = 0
end
else
for i, v in ipairs( myArrayPercentList ) do
-- Interpolate values
if v[ 1 ] >= targetVoltage and i > 1 then
local lastVal = myArrayPercentList[i-1]
result = (targetVoltage - lastVal[1]) / (v[1] - lastVal[1])
result = result * (v[2] - lastVal[2]) + lastVal[2]
break
end
end --for
end --if
return result
end
--------------------------------------------------------------------
-- Configure language settings
--------------------------------------------------------------------
local function setLanguage()
-- Set language
local lng=system.getLocale();
local file = io.readall("Apps/BattMon/locale.jsn")
local obj = json.decode(file)
if(obj) then
lang = obj[lng] or obj[obj.default]
end
end
--------------------------------------------------------------------
-- Get current voltage from sensor - return array of 6 values
--------------------------------------------------------------------
-- local values = {3.9, 3.85, 3.9, 4.0,4.1,4.2}
local function getVoltages()
sensorValid=false
if(sensorId==0) then
return
end
local values ={}
-- values[1] = values[1] - 0.0005 -- + math.random(-100,100)*0.0005
-- values[2] = values[2] - 0.0005
-- values[3] = values[3] - 0.0005
-- values[4] = values[4] - 0.0005
-- values[5] = values[5] - 0.0005
-- values[6] = values[6] - 0.0005
local sensor
for i = 1,6 do
sensor = system.getSensorByID(sensorId,i)
if sensor and sensor.valid then
values[#values+1] = sensor.value
sensorValid=true
end
end
cellmin = cellfull
cellmax = 0
cellsum = 0
for i = 1, #cell do cell[i] = 0 end
cellsumtype = #values
for i, v in pairs(values) do
cellsum = cellsum + v
cell[i] = v
if cellmaxima[i] < v then
cellmaxima[i] = v
end
if cellminima[i] > v then
cellminima[i] = v
end
if cellmin > v then
cellmin = v
end
if cellmax < v then
cellmax = v
end
end
cellsumpercent = percentcell(cellsum/cellsumtype)
if cellsumpercentmaxima < cellsumpercent then
cellsumpercentmaxima = cellsumpercent
end
if cell[1]>0 then
if cellsumpercentminima > cellsumpercent then
cellsumpercentminima = cellsumpercent
end
end
end
--------------------------------------------------------------------
-- Print batt values
--------------------------------------------------------------------
local function printBattery(w,h)
local txtr,txtg,txtb
local bgr,bgg,bgb = lcd.getBgColor()
if (bgr+bgg+bgb)/3 >128 then
txtr,txtg,txtb = 0,0,0
else
txtr,txtg,txtb = 255,255,255
end
-- Separator line
lcd.setColor(130,130,130)
lcd.drawLine(235, 80, 235, 158)
local label
-- Maximum charged
lcd.setColor(txtr,txtg, txtb , 100)
lcd.drawFilledRectangle(6, 11, cellsumpercentmaxima*44/100,18,FONT_GRAYED)
lcd.setColor(lcd.getFgColor())
-- Current value
lcd.drawFilledRectangle(6, 11, cellsumpercent*44/100, 18 )
-- Minimum
if cellsumpercentminima < cellsumpercent and cellsumpercentminima > 0 then
lcd.setColor(130,130,130)
lcd.drawLine(6+(cellsumpercentminima*44/100), 11, 6+(cellsumpercentminima*44/100), 28)
end
-- Battery shape
lcd.setColor(txtr,txtg, txtb)
lcd.drawRectangle(5, 10, 46, 20)
lcd.drawFilledRectangle (51,15,2,10)
label = string.format("%d%%",cellsumpercent)
lcd.drawText(50-lcd.getTextWidth(FONT_BIG,label),30,label,FONT_BIG)
for i = 1, 6 do
blink = (cell[i] ~= 0 and (cell[i] < cellempty or not sensorValid) ) and true or false
if blink then
lcd.setColor(lcd.getFgColor())
else
lcd.setColor(txtr,txtg, txtb , 200)
end
local t = lcd.getTextWidth(FONT_BOLD,i)
lcd.drawLine(positions[i][1] + 2, positions[i][2] - 3, positions[i][1] - 2 + t, positions[i][2] - 3)
lcd.drawFilledRectangle(positions[i][1]-1,positions[i][2] - 2,t+3,20)
lcd.setColor(255-txtr,255-txtg,255-txtb)
lcd.drawNumber(positions[i][1], positions[i][2]-1, i, FONT_NORMAL | FONT_XOR)
t = positions[i][1] + t + 8
if cell[i] ~= 0 then
if(not blink or (system.getTime()%2 == 1)) then
label = string.format("%.2fV",cell[i])
lcd.setColor(txtr,txtg, txtb)
lcd.drawText(t, positions[i][2],label, FONT_NORMAL)
end
percent = math.floor(percentcell(cell[i]) * (echH/100))
percentminima = math.floor(percentcell(cellminima[i]) * (echH/100))
percentmaxima = math.floor(percentcell(cellmaxima[i]) * (echH/100))
lcd.setColor(lcd.getFgColor())
lcd.drawFilledRectangle(echX + 2 + (i - 1) * (gaugeW + gaugeGap), (ech100Y + echH - percentmaxima), gaugeW, percentmaxima,FONT_GRAYED)
lcd.setColor(txtr,txtg, txtb)
lcd.drawFilledRectangle(echX + 2 + (i - 1) * (gaugeW + gaugeGap), (ech100Y + echH - percent), gaugeW, percent)
if percentminima < percent and percentminima > 0 then
lcd.setColor(lcd.getFgColor())
lcd.drawLine(echX + 2 + (i - 1) * (gaugeW + gaugeGap), ech100Y + echH - percentminima, (echX + 2 + (i - 1) * (gaugeW + gaugeGap)) + gaugeW-1, ech100Y + echH - percentminima)
end
else
lcd.setColor(txtr,txtg, txtb)
lcd.drawText(t, positions[i][2],"...",FONT_BOLD)
lcd.drawText (echX + 5 + (i - 1)*(gaugeW + gaugeGap), ech0Y-17, "*", FONT_NORMAL)
end
end
-- Graph axis
lcd.drawLine(echX, ech100Y, echX, ech0Y)
lcd.drawLine(echX+1, ech0Y, echX + gaugeGap + 5*(gaugeW + gaugeGap) + gaugeW, ech0Y)
lcd.drawText(echX-25,0,"4.2V",FONT_MINI)
lcd.drawText(echX-25,ech0Y-5,"3.0V",FONT_MINI)
i = 6
while (i >= 0) do
lcd.drawLine(echX-2, (ech100Y+echH)-((echH/6)*i), echX-1, (ech100Y+echH)-((echH/6)*i))
i= i-1
end
-- Draw values - average, sum, ...
lcd.drawText (60,4, string.format(lang.pack,cellsumtype),FONT_NORMAL)
lcd.drawText (60,22, lang.voltage, FONT_NORMAL)
label = string.format
if cellsum > 10 then
label = string.format("%.1fV",cellsum)
else
label = string.format("%.2fV",cellsum)
end
lcd.drawText (echX-20-lcd.getTextWidth(FONT_NORMAL,label),22, label, FONT_NORMAL)
lcd.drawText (60,40, lang.average, FONT_NORMAL)
if cellsum > 0 then
label = string.format("%.2fV",(cellsum / cellsumtype))
else
label = "0V"
end
lcd.drawText (echX-20-lcd.getTextWidth(FONT_NORMAL,label),40, label, FONT_NORMAL)
if cell[1] > 0 then
percentDelta = math.floor(100 - (percentcell(cellmax) - percentcell(cellmin)))
else
percentDelta = "-"
end
label = string.format(lang.delta,(cell[1] > 0 and (cellmax * 1000) - (cellmin * 1000) or 0), percentDelta)
lcd.drawText (5,58,label,FONT_MINI)
end
--------------------------------------------------------------------
-- Print batt values - Small Window
--------------------------------------------------------------------
local function printBatterySmall(w,h)
local label
local txtr,txtg,txtb
local bgr,bgg,bgb = lcd.getBgColor()
if (bgr+bgg+bgb)/3 >128 then
txtr,txtg,txtb = 0,0,0
else
txtr,txtg,txtb = 255,255,255
end
-- Print battery icon and voltages
for i = 1, 6 do
blink = (cell[i] ~= 0 and (cell[i] < cellempty or not sensorValid) ) and true or false
if blink then
lcd.setColor(lcd.getFgColor())
else
lcd.setColor(txtr,txtg, txtb , 200)
end
local t = lcd.getTextWidth(FONT_BOLD,i)
lcd.drawLine(positionsSmall[i][1] + 2, positionsSmall[i][2] - 3, positionsSmall[i][1] - 2 + t, positionsSmall[i][2] - 3)
lcd.drawFilledRectangle(positionsSmall[i][1]-1,positionsSmall[i][2] - 2,t+3,20)
lcd.setColor(255-txtr,255-txtg,255-txtb)
lcd.drawNumber(positionsSmall[i][1], positionsSmall[i][2]-1, i, FONT_NORMAL | FONT_XOR)
t = positionsSmall[i][1] + t + 8
if cell[i] ~= 0 then
if(not blink or (system.getTime()%2 == 1)) then
label = string.format("%.2fV",cell[i])
lcd.setColor(txtr,txtg, txtb )
lcd.drawText(t, positionsSmall[i][2],label, FONT_NORMAL)
end
else
lcd.setColor(txtr,txtg, txtb )
lcd.drawText(t, positionsSmall[i][2],"...",FONT_BOLD)
end
end
end
--------------------------------------------------------------------
-- Form functions
--------------------------------------------------------------------
--------------------------------------------------------------------
local function sensorChanged(value)
if(value and value >=0) then
sensorId=sensorsAvailable[value].id
else
sensorId = 0
end
system.pSave("sensor",sensorId)
end
--------------------------------------------------------------------
local function initForm(formID)
sensorsAvailable = {}
local available = system.getSensors();
local list={}
local curIndex=-1
local descr = ""
for index,sensor in ipairs(available) do
if(sensor.param == 0) then
list[#list+1] = sensor.label
sensorsAvailable[#sensorsAvailable+1] = sensor
if(sensor.id==sensorId ) then
curIndex=#sensorsAvailable
end
end
end
form.addSpacer(100,10)
form.addLabel({label=lang.sensor,font=FONT_BOLD})
form.addRow(2)
form.addLabel({label=lang.selectSensor,width=120})
form.addSelectbox (list, curIndex,true,sensorChanged,{width=190})
end
--------------------------------------------------------------------
-- Initialization
--------------------------------------------------------------------
-- Init function
local function init()
-- registers a whole-size window
sensorId = system.pLoad("sensor",0)
if sensorId == 0 then
-- Fill default sensors ID - MULi6
local available = system.getSensors();
for index,sensor in ipairs(available) do
if((sensor.id & 0xFFFF) >= 43185 and (sensor.id & 0xFFFF) <= 43188) then
sensorId = sensor.id
break
end
end
end
system.registerTelemetry(1,lang.appName,3,printBattery)
system.registerTelemetry(2,lang.windowSmall,2,printBatterySmall)
system.registerForm(1,MENU_TELEMETRY,lang.appName,initForm,nil,printForm)
end
--------------------------------------------------------------------
-- Loop function
local function loop()
getVoltages()
end
--------------------------------------------------------------------
setLanguage()
return { init=init, loop=loop, author="JETI model", version="1.3",name=lang.appName}
|
-- load options
require("ape.options")
-- load global options
require("ape.globals")
-- load global utils
require("ape.util.globals")
-- don't load any plugins if packer is not installed
if require("ape.first_load")() then
return
end
-- speed up starup, must be loaded before any plugins are loaded
--require("impatient")
-- setup colors
require("ape.colors")
-- load plugins file
require("ape.plugins")
-- setup completion
require("ape.completion")
-- statusline
-- require("ape.statusline")
-- load lsp config
require("ape.lsp").setup()
-- setup nvim-dap for debugging
require("ape.dap")
-- setup treesitter
require("ape.treesitter")
-- load snippets
require("ape.snips")
|
--[=[
@within PageCursor
@prop Client Client
@readonly
A reference back to the client that owns this object.
]=]
--[=[
@within PageCursor
@prop Endpoint string
@readonly
The URL to send requests to.
]=]
--[=[
@within PageCursor
@prop Tags {[string]=any}
@readonly
The URL to send requests to.
]=]
--[=[
@within PageCursor
@prop Interpret function
@readonly
The function that parses return data to turn it into a usable form.
]=]
--[=[
@within PageCursor
@prop SortOrder "Asc"|"Desc"
@readonly
The sort order sent with the request.
]=]
--[=[
@within PageCursor
@prop Limit number
@readonly
The number of items that should be sent with each page.
]=]
--[=[
@within PageCursor
@prop PageDataLocation string
@readonly
The location where data is found for non-standard pages.
]=]
--[=[
@within PageCursor
@prop PageNextLocation string
@readonly
The location where the next page cursor is found for non-standard pages.
]=]
--[=[
@within PageCursor
@prop PageNextLocation string
@readonly
The location where the next page cursor is found for non-standard pages.
]=]
--[=[
@within PageCursor
@prop PagePreviousLocation string
@readonly
The location where the previous page cursor is found for non-standard pages.
]=]
--[=[
@within PageCursor
@prop CursorTag string
@readonly
The querystring name of the cursor for non-standard pages.
]=]
--[=[
@within PageCursor
@prop LimitTag string
@readonly
The querystring name of the limit for non-standard pages.
]=]
--[=[
@within PageCursor
@prop SortOrderTag string
@readonly
The querystring name of the sort order for non-standard pages.
]=]
--[=[
@within PageCursor
@prop LastPage boolean
@readonly
If the page you are currently on is the last page.
]=]
--[=[
@within PageCursor
@prop FirstPage boolean
@readonly
If the page you are currently on is the first page.
]=]
--[=[
@within PageCursor
@prop NextCursor string?
@readonly
The cursor for the next page.
]=]
--[=[
@within PageCursor
@prop PreviousCursor string?
@readonly
The cursor for the previous page.
]=]
--[=[
The object represents roblox pagination, many endpoints have thousands of data points,
and it would be too expensive to send them all in one document, so they are sent in
managable clusters called pages.
This class manages cursor-based pagination.
@class PageCursor
]=]
local PageCursor = {}
--[=[
Constructs a PageCursor object.
@param _ PageCursor
@param Client Client -- The client to make requests with.
@param Endpoint string -- The endpoint to get pages from.
@param Tags {[string]=any} -- Optional list of tags to add on to the request.
@param Interpret function -- The function that interprets recieved data, to turn it into a useable format.
@param SortOrder string? -- The sort order to use when requesting for pages. Can be "Asc" or "Desc".
@param Limit number? -- The page item limit to use when requesting pages.
@param PageDataLocation string? -- The location where page data is located for non-standard pages.
@param PageNextLocation string? -- The location where the next page cursor is found for non-standard pages.
@param PagePreviousLocation string? -- The location where the previous page cursor is found for non-standard pages.
@param CursorTag string? -- The name of the tag to send the cursor for non-standard pages.
@param LimitTag string? -- The name of the tag to send the limit for non-standard pages.
@param SortOrderTag string? -- The name of the tag to send the sort order for non-standard pages.
@return PageCursor
]=]
function PageCursor.__call (_,Client,Endpoint,Tags,Interpret,SortOrder,Limit,PageDataLocation,PageNextLocation,PagePreviousLocation,CursorTag,LimitTag,SortOrderTag)
local self = {}
setmetatable(self,{__index=PageCursor})
self.Client = Client
self.Endpoint = Endpoint
self.Tags = Tags
self.Interpret = Interpret
self.SortOrder = SortOrder or "Asc"
self.Limit = Limit or 10
self.PageDataLocation = PageDataLocation or "data"
self.PageNextLocation = PageNextLocation or "nextPageCursor"
self.PagePreviousLocation = PagePreviousLocation or "previousPageCursor"
self.CursorTag = CursorTag or "cursor"
self.LimitTag = LimitTag or "limit"
self.SortOrderTag = SortOrderTag or "sortOrder"
self.LastPage = false
self.FirstPage = true
return self
end
--[=[
This gets the next page and returns it.
@return {<T>}
]=]
function PageCursor:Next ()
if self.LastPage then
error("Lublox: You cannot use method 'Next' when you are on the last page!")
end
local Tags = self.Tags or {}
if self.NextCursor then
Tags[self.CursorTag] = self.NextCursor
end
Tags[self.SortOrderTag] = self.SortOrder
Tags[self.LimitTag] = self.Limit
local Success,Body = self.Client:Request ("GET",self.Endpoint,Tags)
if Success then
self.LastPage = Body[self.PageNextLocation] == nil
self.FirstPage = Body[self.PagePreviousLocation] == nil
self.NextCursor = Body[self.PageNextLocation]
self.PreviousCursor = Body[self.PagePreviousLocation]
local Data = {}
for _,v in pairs(Body[self.PageDataLocation]) do
Data[#Data+1] = self.Interpret(v)
end
return Data
end
end
--[=[
This gets the previous page and returns it.
@return {<T>}
]=]
function PageCursor:Previous ()
if self.FirstPage then
error("Lublox: You cannot use method 'Previous' when you are on the first page!")
end
local Tags = self.Tags or {}
if self.PreviousCursor then
Tags[self.CursorTag] = self.PreviousCursor
end
Tags[self.SortOrderTag] = self.SortOrder
Tags[self.LimitTag] = self.Limit
local Success,Body = self.Client:Request ("GET",self.Endpoint,Tags)
if Success then
self.LastPage = Body[self.PageNextLocation] ~= nil
self.FirstPage = Body[self.PagePreviousLocation] ~= nil
self.NextCursor = Body[self.PageNextLocation]
self.PreviousCursor = Body[self.PagePreviousLocation]
local Data = {}
for _,v in pairs(Body[self.PageDataLocation]) do
Data[#Data+1] = self.Interpret(v)
end
return Data
end
end
setmetatable(PageCursor,PageCursor)
return {PageCursor=PageCursor}
|
local function has_locked_chest_privilege(meta, player)
if player:get_player_name() ~= meta:get_string("owner") then
return false
end
return true
end
local open = "size[8,10]"..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[current_name;main;0,0.3;8,4;]"..
"list[current_player;main;0,4.85;8,1;]" ..
"list[current_player;main;0,6.08;8,3;8]" ..
"listring[current_name;main]" ..
"listring[current_player;main]" ..
"button[3,9;2,1;open;close]" ..
default.get_hotbar_bg(0,4.85)
local closed = "size[2,1]"..
"button[0,0;2,1;open;open]"
minetest.register_node("more_chests:secret", {
description = "Secret Chest",
tiles = {"secret_top.png", "secret_top.png", "secret_side.png",
"secret_side.png", "secret_side.png", "secret_front.png"},
paramtype2 = "facedir",
groups = {snappy=2, choppy=2, oddly_breakable_by_hand=2, tubedevice = 1, tubedevice_receiver = 1},
-- Pipeworks
tube = {
insert_object = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:add_item("main", stack)
end,
can_insert = function(pos, node, stack, direction)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:room_for_item("main", stack)
end,
input_inventory = "main",
connect_sides = {left = 1, right = 1, back = 1, front = 1, bottom = 1, top = 1}
},
legacy_facedir_simple = true,
sounds = default.node_sound_wood_defaults(),
after_place_node = function(pos, placer)
local meta = minetest.get_meta(pos)
meta:set_string("owner", placer:get_player_name() or "")
meta:set_string("infotext", "Secret Chest (owned by "..
meta:get_string("owner")..")")
end,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", open)
meta:set_string("infotext", "Secret Chest")
meta:set_string("owner", "")
local inv = meta:get_inventory()
inv:set_size("main", 8*4)
end,
can_dig = function(pos,player)
local meta = minetest.get_meta(pos);
local inv = meta:get_inventory()
return inv:is_empty("main")
end,
allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.get_meta(pos)
if not has_locked_chest_privilege(meta, player) then
minetest.log("action", player:get_player_name()..
" tried to access a secret chest belonging to "..
meta:get_string("owner").." at "..
minetest.pos_to_string(pos))
return 0
end
return count
end,
allow_metadata_inventory_put = function(pos, listname, index, stack, player)
local meta = minetest.get_meta(pos)
if not has_locked_chest_privilege(meta, player) then
minetest.log("action", player:get_player_name()..
" tried to access a secret chest belonging to "..
meta:get_string("owner").." at "..
minetest.pos_to_string(pos))
return 0
end
return stack:get_count()
end,
allow_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta = minetest.get_meta(pos)
if not has_locked_chest_privilege(meta, player) then
minetest.log("action", player:get_player_name()..
" tried to access a secret chest belonging to "..
meta:get_string("owner").." at "..
minetest.pos_to_string(pos))
return 0
end
return stack:get_count()
end,
on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
minetest.log("action", player:get_player_name()..
" moves stuff in secret chest at "..minetest.pos_to_string(pos))
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name()..
" moves stuff to secret chest at "..minetest.pos_to_string(pos))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name()..
" takes stuff from secret chest at "..minetest.pos_to_string(pos))
end,
on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
if has_locked_chest_privilege(meta, sender) then
if fields.open == "open" then
meta:set_string("formspec", open)
else
meta:set_string("formspec", closed)
end
end
end,
})
minetest.register_craft({
output = 'more_chests:secret',
recipe = {
{'default:wood','default:cobble','default:wood'},
{'default:wood','default:steel_ingot','default:wood'},
{'default:wood','default:wood','default:wood'}
}
})
|
local class = require("pl.class")
local sfmt = string.format
local uuid = require("core.lib.uuid")
local tablex = require("pl.tablex")
local GameEntity = require("core.GameEntity")
local ItemType = require("core.ItemType")
local Logger = require("core.Logger")
local Inventory = require("core.Inventory")
---@class Item : GameEntity
---@field area Area
---@field behaviors string[]
---@field defaultItems Item[]
---@field description string
---@field entityReference string #areaId:itemId
---@field id string
---@field maxItems number
---@field isEquipped boolean
---@field keywords string[]
---@field name string
---@field room Room
---@field roomDesc string
---@field script string
---@field uuid string|number
---@field closeable boolean
---@field closed boolean
---@field locked boolean
---@field lockedBy string
---@field carriedBy Character | Item
---@field equippedBy Character
local M = class(GameEntity)
function M:_init(area, item)
self:super()
local validate = { "keywords", "name", "id" }
for _, prop in ipairs(validate) do
if not item[prop] then
error(sfmt("Item in area [%s] missing required property [%s]", area.name,
prop))
end
end
self.area = area
self.metadata = item.metadata or {}
self.behaviors = tablex.copy(item.behaviors or {})
self.defaultItems = item.items or {}
self.description = item.description or "Nothing special."
self.entityReference = item.entityReference
self.id = item.id
self.maxItems = item.maxItems or math.maxinteger
self:initializeInventory(item.inventory)
self.isEquipped = item.isEquipped or false
self.keywords = item.keywords
self.name = item.name
self.room = item.room
self.roomDesc = item.roomDesc or ""
self.script = item.script
if type(item.type) == "string" then
self.type = ItemType[item.type] or item.type
else
self.type = item.type or ItemType.OBJECT
end
self.uuid = item.uuid or uuid()
self.closeable = item.closeable or item.closed or item.locked or false
self.closed = item.closed or false
self.locked = item.locked or false
self.lockedBy = item.lockedBy
self.carriedBy = nil
self.equippedBy = nil
end
function M:initializeInventory(inventory)
if inventory then
self.inventory = Inventory(inventory)
self.inventory:setMax(self.maxItems)
else
self.inventory = nil
end
end
function M:hasKeyword(keyword) return self.keywords:find(keyword) end
function M:addItem(item)
self:_setupInventory()
self.inventory:addItem(item)
item.carriedBy = self
end
function M:removeItem(item)
self.inventory:removeItem(item)
if not self.inventory.size then self.inventory = nil end
item.carriedBy = nil
end
function M:isInventoryFull()
self:_setupInventory()
return self.inventory:isFull()
end
function M:_setupInventory()
if not self.inventory then
self.inventory = Inventory({ items = {}, max = self.maxItems })
end
end
function M:findCarrier()
local owner = self.carriedBy
while owner do
if not owner.carriedBy then return owner end
owner = owner.carriedBy
end
end
function M:open()
if not self.closed then return end
self.closed = false
end
function M:close()
if self.close or not self.closeable then return end
self.closed = true
end
function M:lock()
if self.locked or not self.closeable then return end
self:close()
self.locked = true
end
function M:unlock()
if not self.locked then return end
self.locked = false
end
function M:hydrate(state, serialized)
serialized = serialized or {}
if self.__hydrated then
Logger.warn("Attempted to hydrate already hydrated item.")
return false
end
if serialized.behaviors then
self.behaviors = tablex.copy(serialized.behaviors)
end
self:setupBehaviors(state.ItemBehaviorManager)
self.description = serialized.description or self.description
self.keywords = serialized.keywords or self.keywords
self.name = serialized.name or self.name
self.roomDesc = serialized.roomDesc or self.roomDesc
self.metadata = serialized.metadata or self.metadata
self.closed = serialized["closed"] and serialized.closed or self.closed
self.locked = serialized["locked"] and serialized.locked or self.locked
if type(self.area) == "string" then
self.area = state.AreaManager:getArea(self.area)
end
if self.inventory then
self.inventory:hydrate(state, self)
else
for _, defaultItemId in ipairs(self.defaultItems) do
Logger.verbose("\tDIST: Adding item [%s] to item [%s] [%s]",
defaultItemId, self.name, self.entityReference)
local newItem = state.ItemFactory:create(self.area, defaultItemId)
newItem:hydrate(state)
state.ItemManager:add(newItem)
self:addItem(newItem)
end
end
self.__hydrated = true
end
function M:serialize()
local behaviors = tablex.copy(self.behaviors)
return {
entityReference = self.entityReference,
inventory = self.inventory and self.inventory:serialize(),
-- metadata is serialized/hydrated to save the state of the item during gameplay
-- example= the players a food that is poisoned, or a sword that is enchanted
metadata = self.metadata,
description = self.description,
keywords = self.keywords,
name = self.name,
roomDesc = self.roomDesc,
closed = self.closed,
locked = self.locked,
-- behaviors are serialized in case their config was modified during gameplay
-- and that state needs to persist (charges of a scroll remaining, etc)
behaviors = behaviors,
}
end
return M
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.