content
stringlengths 5
1.05M
|
|---|
local character
local game
local lib
character = {
world = nil,
alive = true,
life_time = 0,
life_elapsed = 0,
sort = 0,
x = 0,
y = 0,
offset_x = 0,
offset_y = 0,
source = nil,
draw = function(self, event)
if (self.alive) then
love.graphics.draw(self.source,
(game.tile_size * game.scale * self.x + self.offset_x),
(game.tile_size * game.scale * self.y + self.offset_y),
0, game.scale, game.scale, 0, 0)
end
end,
tick = function(self, event)
self.life_elapsed = self.life_elapsed + event.delta
if (self.life_elapsed >= self.life_time) then
self.alive = false
end
end,
_new = function(base, new, world, source)
new.world = world
new.source = source
return new
end,
init = function(self, engine)
lib = engine.lib
game = lib.tsr.game
lib.oop:objectify(self)
end
}
return character
|
--[[
MTA Role Play (mta-rp.pl)
Autorzy poniższego kodu:
- Patryk Adamowicz <patrykadam.dev@gmail.com>
Discord: PatrykAdam#1293
Link do githuba: https://github.com/PatrykAdam/mtarp
--]]
local doors = {}
function loadDoors()
local count = 0
local doorsData = exports.sarp_mysql:mysql_result("SELECT * FROM `sarp_doors`")
for id, v in ipairs(doorsData) do
local door = createMarker( doorsData[id].posX, doorsData[id].posY, doorsData[id].posZ, "corona", 1.0, 0, 255, 0, 0 )
local exit = createMarker( doorsData[id].exitX, doorsData[id].exitY, doorsData[id].exitZ, "corona", 1.0, 255, 255, 255, 0 )
setElementDimension( door, doorsData[id].dimension )
setElementInterior( door, doorsData[id].interior )
setElementDimension( exit, doorsData[id].exitdimension )
setElementInterior( exit, doorsData[id].exitinterior )
setElementData( exit, "type:doors", true )
setElementData( exit, "doors:exit", true )
setElementData( exit, "doors:parent", door)
setElementData( door, "type:doors", true )
setElementData( door, "doors:id", doorsData[id].id )
setElementData( door, "doors:name", doorsData[id].name )
setElementData( door, "doors:description", doorsData[id].description )
setElementData( door, "doors:lock", doorsData[id].lock )
setElementData( door, "doors:entry", doorsData[id].entry )
setElementData( door, "doors:posRot", doorsData[id].posRot )
setElementData( door, "doors:exitRot", doorsData[id].exitRot )
setElementData( door, "doors:ownerType", doorsData[id].ownerType )
setElementData( door, "doors:accessGroup", doorsData[id].accessGroup )
setElementData( door, "doors:ownerID", doorsData[id].ownerID )
setElementData( door, "doors:garage", doorsData[id].garage )
setElementData( door, "doors:arrest", doorsData[id].arrest )
setElementData( door, "doors:objects", doorsData[id].objects )
setElementData( door, "doors:equipment", doorsData[id].equipment )
setElementData( door, "doors:parent", exit)
local ownerName = false
if doorsData[id].ownerType == 1 then
local query = exports.sarp_mysql:mysql_result("SELECT `name`, `surname` FROM `sarp_characters` WHERE `player_id` = ?", doorsData[id].ownerID)
if not query[1] then
ownerName = "Nie przypisano"
else
ownerName = query[1].name.." "..query[1].surname
end
elseif doorsData[id].ownerType == 2 then
local query = exports.sarp_mysql:mysql_result("SELECT `name`, `type` FROM `sarp_groups` WHERE `id` = ?", doorsData[id].ownerID)
if not query[1] then
ownerName = "Nie przypisano"
else
ownerName = query[1].name
doorsData[id].subType = query[1].type
end
else
ownerName = "Nie przypisano"
end
setElementData( door, "doors:ownerName", ownerName)
if haveDoorEquipment(id, 1) then
setElementData( door, "doors:url", doorsData[id].url )
end
end
outputDebugString( "Wczytano ".. #doorsData .." drzwi z bazy danych." )
end
addEventHandler( "onResourceStart", resourceRoot, loadDoors )
function doorTeleport(playerid)
if not exports.sarp_main:isPlayerLogged( playerid ) then return end
for i, v in ipairs(getElementsByType( "marker" )) do
if getElementData(v, "type:doors") then
local dX, dY, dZ = getElementPosition( v )
local parent = getElementData( v, "doors:parent")
local eX, eY, eZ = getElementPosition( parent )
if getDistanceBetweenPoints3D( dX, dY, dZ, getElementPosition( playerid ) ) <= 1.0 and getElementDimension( v ) == getElementDimension( playerid ) and getElementInterior( v ) == getElementInterior( playerid ) then
if getElementData( v, "doors:lock") == 1 or getElementData( parent, "doors:lock") == 1 then
return exports.sarp_notify:addNotify(playerid, "Drzwi w tym budynku są zamknięte.")
end
if getElementData( playerid, "player:arrestTime") then
return exports.sarp_notify:addNotify(playerid, "Przechodzenie przez drzwi wyłączone podczas aresztu.")
end
if not getElementData( v, "doors:exit") and getElementData( v, "doors:entry") > 0 then
local cash = getElementData( playerid, "player:money")
if cash < getElementData( v, "doors:entry") then
return exports.sarp_notify:addNotify(playerid, "Nie posiadasz wystarczającej ilości gotówki aby wejść do tego budynku.")
end
exports.sarp_main:givePlayerCash(playerid, -cash)
end
local vehicle = getPedOccupiedVehicle( playerid )
if vehicle then
local driver = getVehicleOccupant(vehicle)
if getElementData( v, "doors:garage") == 0 and driver == playerid then
return
end
if driver and driver == playerid then
removePedFromVehicle( playerid )
setElementPosition( vehicle, eX, eY, eZ + 1)
setElementDimension( vehicle, getElementDimension( parent ) )
setElementInterior( vehicle, getElementInterior( parent ) )
warpPedIntoVehicle( playerid, vehicle )
end
end
setElementPosition( playerid, eX, eY, eZ )
setElementDimension( playerid, getElementDimension( parent ) )
setElementInterior( playerid, getElementInterior( parent ) )
if not getElementData( v, "doors:exit") then
setElementData( playerid, "player:door", v )
if haveDoorEquipment(getElementData( v, "doors:id"), 1) and getElementData( v, "doors:url") then
triggerClientEvent( playerid, "doorSound", playerid, getElementData( v, "doors:url") )
end
else
setElementData( playerid, "player:door", false)
triggerClientEvent( playerid, "doorSoundOff", root )
end
triggerEvent( "objects:load", root, playerid, getElementDimension( parent ), getElementInterior( parent ) )
return true
end
end
end
end
addEventHandler( "onPlayerJoin", root, function ()
bindKey(source, "E", "down", doorTeleport)
end)
addEventHandler( "onResourceStart", resourceRoot, function ()
for i, v in ipairs(getElementsByType( "player" )) do
unbindKey( v, "E", "both" )
bindKey(v, "E", "down", doorTeleport)
end
end)
addEventHandler( "onResourceStop", resourceRoot, function ()
for i, v in ipairs(getElementsByType( "player" )) do
unbindKey(v, "E", "down", doorTeleport)
end
end)
|
Menu = {}
--[[ Functions: Menu ]]--
function Menu:Init()
self.isLoaded = true
self:Invoke(false, "loadConfig", {
effects = Config.Effects,
bones = Config.Bones,
})
end
function Menu:Invoke(target, method, ...)
SendNUIMessage({
invoke = {
target = target,
method = method,
args = {...},
}
})
end
function Menu:Focus()
if GetGameTimer() - (self.lastFocus or 0) < 20 then
return
end
self.lastFocus = GetGameTimer()
self:Invoke("main", "focus", 1000, 8000)
end
--[[ Events ]]--
AddEventHandler("interact:onNavigate_healthStatus", function()
Menu:Focus()
end)
--[[ Commands ]]--
exports.chat:RegisterCommand("status", function()
Menu:Focus()
end, {
description = "Show your health buddy for a few seconds!",
})
|
--------------------------------
-- @module sp
--------------------------------------------------------
-- the sp Skeleton
-- @field [parent=#sp] Skeleton#Skeleton Skeleton preloaded module
--------------------------------------------------------
-- the sp SkeletonAnimation
-- @field [parent=#sp] SkeletonAnimation#SkeletonAnimation SkeletonAnimation preloaded module
return nil
|
local Buffer = require("lib/buffer")
local BackWord = require("lib/motions/back_word")
describe("BackWord", function()
it("has a name", function()
assert.are.equals("back_word", BackWord:new().name)
end)
describe("#getRange", function()
it("handles simple words", function()
local buffer = Buffer:new()
buffer:setValue("cat dog mouse")
buffer:setSelectionRange(3, 0)
local backWord = BackWord:new()
assert.are.same(
{
start = 0,
finish = 3,
mode = "exclusive",
direction = "characterwise"
},
backWord:getRange(buffer)
)
end)
it("handles starting on the next word", function()
local buffer = Buffer:new()
buffer:setValue("cat dog mouse") -- cat dog (m)ouse
buffer:setSelectionRange(8, 0)
local backWord = BackWord:new()
local result = backWord:getRange(buffer)
assert.are.same(
{
start = 4, -- cat (d)og mouse
finish = 8,
mode = "exclusive",
direction = "characterwise"
},
result
)
end)
it("crosses the new line boundary", function()
local buffer = Buffer:new()
buffer:setValue("ab cd\n ef")
buffer:setSelectionRange(8, 0) -- (e)f
local backWord = BackWord:new()
assert.are.same(
{
start = 3,
finish = 8,
mode = "exclusive",
direction = "characterwise"
},
backWord:getRange(buffer)
)
end)
it("handles punctuation stops", function()
local buffer = Buffer:new()
buffer:setValue("www.test.com")
buffer:setSelectionRange(11, 0) -- .co(m)
local backWord = BackWord:new()
assert.are.same(
{
start = 9,
finish = 11,
mode = "exclusive",
direction = "characterwise"
},
backWord:getRange(buffer)
)
end)
it("handles jumping across punctuation sequences", function()
local buffer = Buffer:new()
buffer:setValue("www.test..com")
buffer:setSelectionRange(10, 0) -- ..(c)om
local backWord = BackWord:new()
assert.are.same(
{
start = 8,
finish = 10,
mode = "exclusive",
direction = "characterwise"
},
backWord:getRange(buffer)
)
end)
it("handles jumping from punctuation thru words", function()
local buffer = Buffer:new()
buffer:setValue("www.test.com")
buffer:setSelectionRange(8, 0) -- www.test(.)com
local backWord = BackWord:new()
assert.are.same(
{
start = 4,
finish = 8,
mode = "exclusive",
direction = "characterwise"
},
backWord:getRange(buffer)
)
end)
end)
end)
|
require 'dp'
--[[parse command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('PostgreSQL MLP Training/Optimization')
cmd:text('Example:')
cmd:text('$> th pgnn.lua --collection "MnistMLP1" --batchSize 128 --momentum 0.5')
cmd:text('$> th pgnn.lua --collection "Mnist-MLP-baseline1" --batchSize 128 --learningRate 0.1 --momentum 0.995 --modelWidth 1024 --widthScales "{1,0.37109375,0.043945312}" --modelDept 4 --progress')
cmd:text('Options:')
cmd:option('--learningRate', 0.1, 'learning rate at t=0')
cmd:option('--decayPoints', '{400,600,700}', 'epochs at which learning rate is decayed')
cmd:option('--decayFactor', 0.1, 'factor by which learning rate is decayed at each point')
cmd:option('--linearDecay', false, 'linear decay from first to second from second to third point, etc')
cmd:option('--maxOutNorm', 1, 'max norm each layers output neuron weights')
cmd:option('--maxNormPeriod', 2, 'Applies MaxNorm Visitor every maxNormPeriod batches')
cmd:option('--weightDecay', 0, 'weight decay factor')
cmd:option('--momentum', 0, 'momentum')
cmd:option('--nesterov', false, 'use nesterov momentum')
cmd:option('--modelWidth', 1024, 'width of the model in hidden neurons')
cmd:option('--widthScales', '{1,1,1}', 'scales the width of different layers')
cmd:option('--modelDept', 2, 'number of Neural layers (affine transform followed by transfer function) to use')
cmd:option('--activation', 'Tanh', 'activation function')
cmd:option('--batchSize', 128, 'number of examples per batch')
cmd:option('--type', 'double', 'type: double | float | cuda')
cmd:option('--useDevice', 1, 'sets the device (GPU) to use')
cmd:option('--maxEpoch', 2000, 'maximum number of epochs to run')
cmd:option('--maxTries', 200, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--dropoutProbs', '{0}', 'probability of dropout on inputs to each layer')
cmd:option('--datasource', 'Mnist', 'datasource to use : Mnist | NotMnist | Cifar10')
cmd:option('--zca_gcn', false, 'apply GCN followed by ZCA input preprocessing')
cmd:option('--standardize', false, 'apply Standardize input preprocessing')
cmd:option('--lecunLCN', false, 'apply LeCunLCN preprocessing to datasource inputs')
cmd:option('--collection', 'MLP-1', 'identifies a collection of related experiments')
cmd:option('--validRatio', 1/6, 'proportion of train set used for cross-validation')
cmd:option('--progress', false, 'display progress bar')
cmd:option('--pg', false, 'use postgresql')
cmd:option('--minAccuracy', 0.1, 'minimum accuracy that must be maintained after 10 epochs')
cmd:option('--accUpdate', false, 'accumulate updates inplace using accUpdateGradParameters')
cmd:text()
opt = cmd:parse(arg or {})
if opt.type == 'cuda' then
require "cutorch"
cutorch.setDevice(opt.useDevice)
end
--[[ hyperparameter sampling distribution ]]--
local hp = {
version = 1,
max_tries = opt.maxTries,
max_epoch = opt.maxEpoch,
model_type = opt.type,
datasource = opt.datasource,
random_seed = dp.TimeChoose(),
batch_size = opt.batchSize,
model_dept = opt.modelDept,
learning_rate = opt.learningRate,
decay_points = table.fromString(opt.decayPoints),
decay_factor = opt.decayFactor,
linear_decay = opt.linearDecay,
max_out_norm = opt.maxOutNorm,
max_norm_period = opt.maxNormPeriod,
weight_decay = opt.weightDecay,
momentum = opt.momentum,
nesterov = opt.nesterov,
model_width = opt.modelWidth,
width_scales = table.fromString(opt.widthScales),
activation = opt.activation,
dropout_probs = table.fromString(opt.dropoutProbs),
valid_ratio = opt.validRatio,
collection = opt.collection,
progress = opt.progress,
zca_gcn = opt.zca_gcn,
standardize = opt.standardize,
lecunlcn = opt.lecunLCN,
max_error = opt.minAccuracy,
acc_update = opt.accUpdate
}
if not opt.pg then
local logger = dp.FileLogger()
hyperopt = dp.HyperOptimizer{
collection_name=opt.collection,
hyperparam_sampler = dp.PriorSampler{--only samples random_seed
name='MLP+'..opt.datasource..':user_dist', dist=hp
},
experiment_factory = dp.MLPFactory{
logger=logger,
save_strategy=dp.SaveToFile()
},
datasource_factory=dp.ImageClassFactory(),
logger=logger
}
hyperopt:run()
end
local pg = dp.Postgres()
local logger = dp.PGLogger{pg=pg}
hyperopt = dp.PGHyperOptimizer{
collection_name=opt.collection,
hyperparam_sampler = dp.PriorSampler{--only samples random_seed
name='MLP+'..opt.datasource..':user_dist', dist=hp
},
experiment_factory = dp.PGMLPFactory{
logger=logger, pg=pg,
save_strategy=dp.PGSaveToFile{pg=pg}
},
datasource_factory=dp.ImageClassFactory(),
logger=logger
}
hyperopt:run()
|
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
|
_tile = _{
new = function(this, args)
merge(
this,
{
id = 1,
sprite = 16,
x = 1,
y = 1
}
)
merge(this,args)
if this.id == 1 then
this.passable = true
end
end,
to_string = function(this)
return this.x..", "..this.y..": "..this.id
end,
draw = function(this)
local tx = this.x*tile_size-tile_size
local ty = this.y*tile_size-tile_size
spr(this.sprite,tx,ty)
end
}
|
-- Triangle wave.
local SoundUnit = require((...):gsub('[^.]*$', '') .. 'soundunit')
local function process (t, v)
return math.abs(2 * v) - 1
end
return function (t)
t = SoundUnit(t)
t.process = process
return t
end
|
format_version = "3.0"
function linearType()
return jbox.ui_linear {
min=0,
max=1,
units = {
min_text = jbox.ui_text("zero"),
max_text = jbox.ui_text("one"),
{
decimals=2,
unit = { template = jbox.ui_text("linear_template") }
}
}
}
end
function rangeType(n)
return jbox.ui_linear {
min=0,
max=n-1,
units = {
min_text = jbox.ui_text("linear_template"),
max_text = jbox.ui_text("linear_template"),
{
decimals=0,
unit = { template = jbox.ui_text("linear_template") }
}
}
}
end
function seedType()
return jbox.ui_nonlinear {
data_to_gui = function(value)
return value+1
end,
gui_to_data = function(value)
return value-1
end,
units = {
{
decimals=0,
unit = { template = jbox.ui_text("linear_template") }
}
}
}
end
function bendRangeType()
return jbox.ui_nonlinear {
data_to_gui = function(value)
return value+1
end,
gui_to_data = function(value)
return value-1
end,
units = {
{
decimals=0,
unit = { template = jbox.ui_text("linear_template") }
}
}
}
end
local mutateValues = {5,10,25,50,75,100}
function mutateRangeType()
return jbox.ui_nonlinear {
data_to_gui = function(value)
return mutateValues[value+1]
end,
gui_to_data = function(value)
for k, v in pairs(mutateValues) do
if v==value then
return k-1
end
end
return 0
end,
units = {
{
decimals=0,
unit = { template = jbox.ui_text("linear_template") }
}
}
}
end
function labelType(tags)
local items={}
for _, value in pairs(tags) do
table.insert(items,jbox.ui_text(value))
end
return jbox.ui_selector(items)
end
function append(to,extras)
for k,v in pairs(extras) do
to[k]=v
end
return to
end
local shapeNames = {
"normal",
"poisson",
"triangleDown",
"triangleUp",
"triangle",
"delta",
"expHard",
"expSoft",
"square"
}
local uiShapeNames={}
for _,name in pairs(shapeNames) do
table.insert(uiShapeNames,jbox.ui_text(name))
end
-- Some range properties
PITCH_MIN = 20
PITCH_MAX = 10000
LENGTH_MIN = 1
LENGTH_MAX = 500
LIMITER_MIN = -12
LIMITER_MAX = 0
-- The property tags
local SHAPE_TAG = 1
local PITCH_TAG = 2
local LENGTH_TAG = 3
local PAN_TAG = 4
local AMPLITUDE_TAG = 5
local TRIGGER_TAG = 6
local TRIGGER_MODE_TAG = 7
local LIMITER_TAG = 8
local LIMITER_ONOFF_TAG = 9
local LIMITER_HARD_SOFT_TAG = 10
local LFO_FREQUENCY_TAG = 11
local LFO_HOLD_TAG = 12
local LFO_MODULATOR_ONOFF_TAG = 13
local EXT_TRIGGER_THRESHOLD_TAG = 14
local EXT_TRIGGER_DEBOUNCE_TAG = 15
local TRIGGERED_TAG = 20
local Props = {
PropertiesTable = {
[SHAPE_TAG] = "shape",
[PITCH_TAG] = "pitch",
[LENGTH_TAG] = "length",
[PAN_TAG] = "pan",
[AMPLITUDE_TAG] = "amplitude",
[TRIGGER_TAG] = "trigger",
[TRIGGER_MODE_TAG] = "triggerMode",
[LIMITER_TAG] = "limiter",
[LIMITER_ONOFF_TAG] = "limiterOnOff",
[LIMITER_HARD_SOFT_TAG] = "limiterHardSoft",
[LFO_FREQUENCY_TAG] = "vcoFrequency",
[LFO_HOLD_TAG] = "vcoHold",
[LFO_MODULATOR_ONOFF_TAG] = "vcoModulatorActive",
[EXT_TRIGGER_THRESHOLD_TAG] = "externalTriggerThreshold",
[EXT_TRIGGER_DEBOUNCE_TAG] = "externalTriggerDebounce"
},
name = function(tag) return Props.PropertiesTable[tag] end,
path = function(tag) return "/custom_properties" .. Props.name(tag) end
}
custom_properties = jbox.property_set{
document_owner = {
properties = {
["shape"] = jbox.number {
default=0,
steps=9,
ui_name = jbox.ui_text("shape"),
property_tag=SHAPE_TAG,
ui_type = jbox.ui_selector(uiShapeNames)
},
["pitch"] = jbox.number {
default=20,
steps = 10001,
ui_name = jbox.ui_text("pitch"),
property_tag=PITCH_TAG,
ui_type = jbox.ui_linear{
min = 0,
max = 10000,
units = {{ decimals=0, unit = { template = jbox.ui_text("hertz") }}}
}
},
["length"] = jbox.number {
default=100,
steps=500,
ui_name = jbox.ui_text("length"),
property_tag=LENGTH_TAG,
ui_type = jbox.ui_linear{
min=LENGTH_MIN,
max=LENGTH_MAX,
units = {{ decimals=0, unit = { template = jbox.ui_text("samples" )}}}
}
},
["pan"] = jbox.number {
default=0.5,
ui_name = jbox.ui_text("pan"),
property_tag=PAN_TAG,
ui_type = jbox.ui_linear{
min = -90,
max = 90,
units = {
min_text=jbox.ui_text("left"),
max_text=jbox.ui_text("right"),
{
decimals=2,
unit={ template = jbox.ui_text("degrees") }
}
}
}
},
["amplitude"] = jbox.number {
default=1,
ui_name = jbox.ui_text("amplitude"),
property_tag=AMPLITUDE_TAG,
ui_type = jbox.ui_percent{decimals=1}
},
["trigger"] = jbox.number {
default=0,
steps=2,
ui_name = jbox.ui_text("trigger"),
property_tag=TRIGGER_TAG,
ui_type = jbox.ui_selector({jbox.UI_TEXT_OFF,jbox.UI_TEXT_ON})
},
["triggerMode"] = jbox.number {
default=0,
steps=3,
ui_name = jbox.ui_text("trigger"),
property_tag=TRIGGER_MODE_TAG,
ui_type = labelType({"external","clocked","manual"})
},
["externalTriggerThreshold"] = jbox.number {
default=0.5,
ui_name=jbox.ui_text("extTriggerThreshold"),
property_tag = EXT_TRIGGER_THRESHOLD_TAG,
ui_type = jbox.ui_percent{decimals=2}
},
["externalTriggerDebounce"] = jbox.number {
default=1,
steps=64,
ui_name=jbox.ui_text("extTriggerDebounce"),
property_tag = EXT_TRIGGER_DEBOUNCE_TAG,
ui_type = jbox.ui_linear{
min=0,
max=63,
units = {{ decimals=0, unit = { template = jbox.ui_text("samples" )}}}
}
},
["limiter"] = jbox.number {
default=1,
ui_name = jbox.ui_text("limiter"),
property_tag=LIMITER_TAG,
ui_type = jbox.ui_linear{
min=LIMITER_MIN,
max=LIMITER_MAX,
units = {{ decimals=1, unit = { template = jbox.ui_text("decibels" )}}}
}
},
["limiterOnOff"] = jbox.number {
default=1,
steps=2,
ui_name = jbox.ui_text("limiter"),
property_tag=LIMITER_ONOFF_TAG,
ui_type = jbox.ui_selector({jbox.UI_TEXT_OFF,jbox.UI_TEXT_ON})
},
["limiterHardSoft"] = jbox.number {
default=0,
steps=2,
ui_name = jbox.ui_text("limiter"),
property_tag=LIMITER_HARD_SOFT_TAG,
ui_type = jbox.ui_selector({jbox.UI_TEXT_OFF,jbox.UI_TEXT_ON})
},
["vcoFrequency"] = jbox.number {
default=1,
steps=7501,
ui_name = jbox.ui_text("frequency"),
property_tag = LFO_FREQUENCY_TAG,
ui_type = jbox.ui_linear{
min = 0,
max = 750,
units = {
{
decimals=1,
unit={ template = jbox.ui_text("hertz") }
}
}
}},
["vcoHold"] =jbox.number {
default=0,
steps=2,
ui_name = jbox.ui_text("hold"),
property_tag=LFO_HOLD_TAG,
ui_type = jbox.ui_selector({jbox.UI_TEXT_OFF,jbox.UI_TEXT_ON})
}
}},
rtc_owner = {
properties = {
instance = jbox.native_object{},
extEnabled = jbox.boolean {
default = false,
ui_name = jbox.ui_text("trigger"),
ui_type = jbox.ui_selector({jbox.UI_TEXT_OFF,jbox.UI_TEXT_ON})
}
}
},
rt_owner = {
properties = {
triggered = jbox.number {
default = 0,
steps = 2,
ui_name = jbox.ui_text("trigger"),
property_tag = TRIGGERED_TAG,
ui_type = jbox.ui_selector{ jbox.UI_TEXT_OFF, jbox.UI_TEXT_ON }
}
}
}
}
local midi_cc = {}
for tag, name in pairs(Props.PropertiesTable) do
midi_cc[101+tag] = "/custom_properties/"..name
end
midi_implementation_chart = {
midi_cc_chart = {} -- midi_cc
}
function remote(name)
return {
internal_name = name,
short_ui_name = jbox.ui_text(name.."_short"),
shortest_ui_name = jbox.ui_text(name.."_shortest")
}
end
remote_implementation_chart = {
-- ["/custom_properties/triggerMode"] = remote("triggerMode"),
-- ["/custom_properties/trigger"] = remote("trigger"),
-- ["/custom_properties/shape"] = remote("shape"),
}
ui_groups = {}
cv_inputs = {
externalTrigger = jbox.cv_input{ ui_name = jbox.ui_text("trigger") }
}
cv_outputs = {}
audio_inputs = {}
audio_outputs = {
audioOutLeft = jbox.audio_output{ ui_name = jbox.ui_text("audioOutput") },
audioOutRight = jbox.audio_output{ ui_name = jbox.ui_text("audioOutput") }
}
jbox.add_stereo_instrument_routing_hint{
left_output = "/audio_outputs/audioOutLeft",
right_output = "/audio_outputs/audioOutRight",
}
jbox.add_stereo_audio_routing_target{
signal_type = "send",
left = "/audio_outputs/audioOutLeft",
right = "/audio_outputs/audioOutRight",
auto_route_enable = true
}
jbox.add_stereo_audio_routing_pair{
left = "/audio_outputs/audioOutLeft",
right = "/audio_outputs/audioOutRight"
}
|
local g_InitCallbacks = {}
local g_PreInitFuncs = {}
local _addEventHandler
local g_Co, g_CoTicks
local g_ScoreBoardRes
#DBG_START_PERF = false
local function setupDatabase()
if (not DbInit()) then
return false
end
if (not Settings.init()) then
return false
end
if (not Updater.run()) then
return false
end
return true
end
local function cleanUpDatabase()
if (not Settings.cleanup_done) then
Debug.warn('Cleaning database!')
DbQuery('UPDATE '..DbPrefix..'players SET online=0')
end
Settings.cleanup_done = false
end
local function LoadCountries()
local node = xmlLoadFile('conf/countries.xml')
if(not node) then return false end
for i, subnode in ipairs(xmlNodeGetChildren(node)) do
local code = xmlNodeGetAttribute(subnode, 'code')
local name = xmlNodeGetAttribute(subnode, 'name')
assert(code and name)
code = code:upper()
name = upperCaseWords(name:lower())
g_Countries[code] = name
end
xmlUnloadFile(node)
return true
end
local function LoadLanguages()
local node = xmlLoadFile('conf/iso_langs.xml')
if(not node) then return false end
for i, subnode in ipairs(xmlNodeGetChildren(node)) do
local code = xmlNodeGetAttribute(subnode, 'code')
local name = xmlNodeGetValue(subnode)
assert(code and name)
g_IsoLangs[code:upper()] = name
end
xmlUnloadFile(node)
return true
end
local function setupScoreboard()
if (g_ScoreBoardRes:isReady()) then
g_ScoreBoardRes:call('scoreboardAddColumn', 'country', g_Root, 50, 'Country', false, 'country_img')
if (AvtSetupScoreboard) then
AvtSetupScoreboard(g_ScoreBoardRes.res)
end
if (StSetupScoreboard) then
StSetupScoreboard(g_ScoreBoardRes.res)
end
end
end
local function initPlayers()
for i, playerEl in ipairs (getElementsByType('player')) do
if (NbCheckPlayerAndFix) then
NbCheckPlayerAndFix(playerEl)
end
Player.create(playerEl)
end
local consoles = getElementsByType('console')
assert(#consoles == 1)
Player.create(consoles[1])
end
local function initRountine()
table.sort(g_InitCallbacks, function(a, b)
return a[2] < b[2]
end)
local prof = DbgPerf(300)
for i, data in ipairs(g_InitCallbacks) do
local func = data[1]
#if(DBG_START_PERF) then
local name = data[3]
local prof2 = DbgPerf()
func()
prof2:cp(name)
#else
func()
#end
end
prof:cp('init')
Debug.info('rafalh script has started!')
#if(TEST) then
Debug.warn('Script compiled with test support')
#end
end
function continueCoRountine(notFirst)
while(getTickCount() - g_CoTicks < 2000 and coroutine.status(g_Co) ~= 'dead') do
local success, msg = coroutine.resume(g_Co)
if(not success) then
Debug.warn('Worker failed: '..msg)
if(not notFirst) then
cancelEvent()
end
return false
end
end
if(coroutine.status(g_Co) ~= 'dead') then
if(not notFirst) then
Debug.info('Please wait while script is initializing...')
else
Debug.info('Still working... Please wait.')
end
g_CoTicks = getTickCount()
setTimer(continueCoRountine, 50, 1, true)
end
return true
end
local function init()
-- Init random generator
math.randomseed(getTickCount())
-- Create a unique element used for verification
createElement('TXC413b9d90', 'TXC413b9d90')
-- Enable addEventHandler function
addEventHandler = _addEventHandler
-- Start initialization in thread in case it gets long to start
-- (for example database upgrade has to be done)
g_Co = coroutine.create(initRountine)
g_CoTicks = getTickCount()
continueCoRountine()
end
function addInitFunc(func, prio)
assert(func)
#if(DBG_START_PERF) then
local name = Debug.getStackTrace(1, 1)[1]
table.insert(g_InitCallbacks, {func, prio or 0, name})
#else
table.insert(g_InitCallbacks, {func, prio or 0})
#end
end
addEventHandler('onResourceStart', resourceRoot, init)
-- Disable addEventHandler for loading
_addEventHandler = addEventHandler
function addEventHandler(...)
Debug.warn('addEventHandler is not recommended at startup! Use addInitFunc instead.')
Debug.printStackTrace()
return _addEventHandler(...)
end
addInitFunc(setupDatabase, -195)
addInitFunc(cleanUpDatabase, -190)
addInitFunc(initPlayers, -100)
addInitFunc(LoadCountries, -10)
addInitFunc(LoadLanguages, -10)
addInitFunc(function()
g_ScoreBoardRes = Resource('scoreboard')
setupScoreboard()
g_ScoreBoardRes:addReadyHandler(function()
setTimer(setupScoreboard, 1000, 1)
end)
end)
|
--[[
You can modify speeds via the main folder in this template.
]]
local containerFolder = script.parent.parent
local function CanRun()
-- any condition you want (stamina checking etc)
return true
end
local function UpdateWalkSpeed(player, states)
local prefix = states.Crouched and "Crouch" or ""
local speedType = states.Running and "Run" or "Walk"
if speedType == "Run" then
if not CanRun() then
speedType = "Walk"
end
end
local speed = containerFolder:GetCustomProperty(prefix..speedType.."Speed")
if states.Slow then
speed = speed * containerFolder:GetCustomProperty("SlowWalkModifier")
end
player.maxWalkSpeed = speed
player.maxSwimSpeed = speed
end
Events.ConnectForPlayer("changeMovementType", UpdateWalkSpeed)
|
PLUGIN.commands = {}
local times = {
{1,"1 Год","1г"},
{2,"1 Месяц","1м"},
{3,"1 Неделя","1н"},
{4,"1 День","1д"},
{5,"30 Минут","30м"},
{6,"1 Минута","1м"},
}
local reasons = {
"Неуважение администрации.",
"Некорректный RolePlay.",
"Метагейм.",
"Пауэргейм.",
"Неуважительный RP.",
"Нечестная игра.",
"Нарушение авторских прав.",
"Пошел нахуй.",
}
function PLUGIN:GetTimeByString(data)
if (!data) then
return 0
end
data = string.lower(data)
local time = 0
for i = 1, 5 do
local info = self.timeData[i]
data = string.gsub(data, "(%d+)"..info[1], function(match)
local amount = tonumber(match)
if (amount) then
time = time + (amount * info[2])
end
return ""
end)
end
local seconds = tonumber(string.match(data, "(%d+)")) or 0
time = time + seconds
return math.max(time, 0)
end
function PLUGIN:CreateCommand(data, command)
if (!data or !command) then
return
end
local callback = data.onRun
local group = data.group
local syntax = data.syntax or "[none]"
local hasTarget = data.hasTarget
local allowDead = data.allowDead
if (hasTarget == nil) then
hasTarget = true
end
if (allowDead == nil) then
allowDead = true
end
data.onMenu = data.onMenu or function( menu, icon, client, command )
menu:AddOption(client:Name(), function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'"' )
end):SetImage(icon)--nut.schema.Call("GetUserIcon", client) or icon)
end
self.commands[command] = data
nut.command.add(command, {
syntax = "<string target> "..syntax,
allowDead = allowDead,
hasPermission = function(client)
return self:IsAllowed(client, group)
end,
silent = (data.silent or false),
onRun = function(client, arguments)
local target
if (hasTarget) then
target = nut.command.findPlayer(client, arguments[1])
if (!IsValid(target)) then
return
end
end
if (IsValid(target) and !self:IsAllowed(client, target)) then
client:notify("Цель выше Вас по рангу.")
return
end
if (hasTarget) then
table.remove(arguments, 1)
end
callback(client, arguments, target)
end
})
end
local PLUGIN = PLUGIN
PLUGIN:CreateCommand({
text = "Создать Ранг",
desc = "Создать новый ранг." ,
group = "owner",
syntax = "<string name> [number immunity]",
hasTarget = false,
onMenu = function( menu, icon, client, command )
end,
onRun = function(client, arguments)
local name = arguments[1]
local immunity = tonumber(arguments[2] or "0") or 0
if (!name) then
client:notify("Вы не привели название группы.")
return
end
name = string.lower(name)
PLUGIN:CreateRank(name, immunity)
client:notify(client:Name().." создал ранг '"..name.."' с иммунитетом "..immunity..".")
end
}, "newrank")
PLUGIN:CreateCommand({
text = "Удалить ранг",
desc = "Удалить существующий ранг." ,
group = "owner",
syntax = "<string name>",
hasTarget = false,
onMenu = function( menu, icon, client, command )
end,
onRun = function(client, arguments)
local name = arguments[1]
if (!name) then
client:notify("Вы должны привести ранг.")
return
end
name = string.lower(name)
local removed, realName = PLUGIN:RemoveRank(name)
if (removed) then
client:notify(client:Name().." удалил ранг '"..realName.."'.")
else
client:notify("Этот ранг не существует.", client)
end
end
}, "delrank")
PLUGIN:CreateCommand({
text = "Толкнуть игрока",
desc = "Толкнуть игрока с заданными силой и уроном." ,
group = "operator",
syntax = "[number force]",
onRun = function(client, arguments, target)
local power = math.Clamp(tonumber(arguments[1] or "128"), 0, 1000)
local direction = VectorRand() * power
direction.z = math.max(power, 128)
target:SetGroundEntity(NULL)
target:SetVelocity(direction)
target:EmitSound("physics/body/body_medium_impact_hard"..math.random(1, 6)..".wav")
target:ViewPunch(direction:Angle() * (power / 10000))
client:notify(client:Name().." толкнул "..target:Name().." с силой "..power..".")
end
}, "slap")
PLUGIN:CreateCommand({
text = "Убить игрока",
desc = "Убить игрока именем Модератора.",
group = "operator",
onRun = function(client, arguments, target)
target:Kill()
client:notify(client:Name().." убил "..target:Name()..".")
end
}, "slay")
PLUGIN:CreateCommand({
text = "Заморозить игрока",
desc = "Игрок теряет контроль над персонажем.",
group = "operator",
onRun = function(client, arguments, target)
target:Lock()
client:notify(client:Name().." заморозил "..target:Name()..".")
end
}, "freeze")
PLUGIN:CreateCommand({
text = "Разморозить игрока",
desc = "Возвращает игроку контроль над персонажем.",
group = "operator",
onRun = function(client, arguments, target)
target:UnLock()
client:notify(client:Name().." разморозил "..target:Name()..".")
end
}, "unfreeze")
PLUGIN:CreateCommand({
text = "Поджечь игрока",
desc = "Игрок воспламеняется.",
group = "admin",
syntax = "[number time]",
onRun = function(client, arguments, target)
local time = math.max(tonumber(arguments[1] or "5"), 1)
target:Ignite(time)
client:notify(client:Name().." поджег "..target:Name().." на "..time.." секунд.")
end
}, "ignite")
PLUGIN:CreateCommand({
text = "Потушить игрока",
desc = "Потушить огонь на игроке.",
group = "admin",
syntax = "[number time]",
onRun = function(client, arguments, target)
target:Extinguish()
client:notify(client:Name().." потушил "..target:Name()..".")
end
}, "unignite")
PLUGIN:CreateCommand({
text = "Установить здоровье",
desc = "Установить уровень здоровья игрока.",
group = "operator",
syntax = "[number health]",
onMenu = function( menu, icon, client, command )
local submenu = menu:AddSubMenu( client:Name() )
for i = 1, 10 do
submenu:AddOption(i*10, function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'" '.. i*10 )
end):SetImage(icon)--nut.schema.Call("GetUserIcon", client) or icon)
end
end,
onRun = function(client, arguments, target)
-- No point of 0 HP, might as well just slay.
local health = math.max(tonumber(arguments[1] or "100"), 1)
target:SetHealth(health)
client:notify(client:Name().." установил здоровье "..target:Name().." на "..health..".")
end
}, "hp")
PLUGIN:CreateCommand({
text = "Изъять оружие",
desc = "Удалить все оружие игрока.",
group = "admin",
onRun = function(client, arguments, target)
target:StripWeapons()
client:notify(client:Name().." удалил оружие "..target:Name()..".")
end
}, "strip")
PLUGIN:CreateCommand({
text = "Выдать стандартное оружие",
desc = "Выдать игроку оружие по умолчанию.",
group = "admin",
onRun = function(client, arguments, target)
--target:SetMainBar()
target:StripWeapons()
client:SetModel(client:getChar():getModel())
target:Give("nut_hands")
target:SetWalkSpeed(nut.config.get("walkSpeed"))
target:SetRunSpeed(nut.config.get("runSpeed"))
target:setWepRaised(false)
nut.flag.onSpawn(target)
nut.attribs.setup(target)
client:notify(client:Name().." выдал оружие по умолчанию "..target:Name()..".")
end
}, "arm")
PLUGIN:CreateCommand({
text = "Установить броню",
desc = "Установить уровень брони игрока.",
group = "operator",
syntax = "[number armor]",
onMenu = function( menu, icon, client, command )
local submenu = menu:AddSubMenu( client:Name() )
for i = 1, 10 do
submenu:AddOption(i*10, function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'" '.. i*10 )
end):SetImage(icon)--nut.schema.Call("GetUserIcon", client) or icon)
end
end,
onRun = function(client, arguments, target)
local armor = math.max(tonumber(arguments[1] or "100"), 0)
target:SetArmor(armor)
client:notify(client:Name().." установил уровень брони персонажа "..target:Name().." на "..armor..".")
end
}, "armor")
PLUGIN:CreateCommand({
text = "Телепортировать игрока",
desc = "Телепортировать игрока А к игроку Б.",
group = "admin",
syntax = "[bool toAimPos]",
onRun = function(client, arguments, target)
local position = client:GetEyeTraceNoCursor().HitPos
local toAimPos = util.tobool(arguments[1])
if (!toAimPos) then
local data = {}
data.start = client:GetShootPos() + client:GetAimVector() * 32
data.endpos = client:GetShootPos() + client:GetAimVector() * 72
data.filter = client
local trace = util.TraceLine(data)
position = trace.HitPos
end
if (position) then
target:SetPos(position)
client:notify(client:Name().." телепортировал "..target:Name().." к "..(toAimPos and "к себе" or "его позиции")..".")
else
client:notify(target:Name().." не может быть телепортирован.")
end
end
}, "tp")
PLUGIN:CreateCommand({
text = "Телепортироваться к игроку",
desc = "Телепортироваться к игроку.",
group = "admin",
syntax = "[bool toAimPos]",
onRun = function(client, arguments, target)
local position = target:GetEyeTraceNoCursor().HitPos
local toAimPos = util.tobool(arguments[1])
if (!toAimPos) then
local data = {}
data.start = target:GetShootPos() + target:GetAimVector() * 32
data.endpos = target:GetShootPos() + target:GetAimVector() * 72
data.filter = target
local trace = util.TraceLine(data)
position = trace.HitPos
end
if (position) then
client:SetPos(position)
client:notify(client:Name().." телепортировался к позиции "..target:Name()".")
else
client:notify("Позиция для Вас не найдена.", client)
end
end
}, "goto")
PLUGIN:CreateCommand({
text = "Отключить игрока",
desc = "Отключить игрока от сервера.",
group = "admin",
syntax = "[string reason]",
onMenu = function( menu, icon, client, command )
local submenu = menu:AddSubMenu( client:Name() )
for _, why in pairs( reasons ) do
submenu:AddOption(why, function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'" '.. why )
end):SetImage(icon)--nut.schema.Call("GetUserIcon", client) or icon)
end
end,
onRun = function(client, arguments, target)
local reason = "без причины"
if (#arguments > 0) then
reason = table.concat(arguments, " ")
end
local name = target:Name()
target:Kick("Отключен "..client:Name().." ("..client:SteamID()..") по причине: "..reason)
client:notify(client:Name().." отключил "..name.." за "..reason..".")
end
}, "kick")
PLUGIN:CreateCommand({
text = "Заблокировать игрока",
desc = "Отключить игрока и запретить ему подключаться к серверу.",
group = "admin",
hasTarget = false,
syntax = "[string time] [string reason]",
onMenu = function( menu, icon, client, command )
local submenu = menu:AddSubMenu( client:Name() )
for _, why in pairs( reasons ) do
local reasonmenu = submenu:AddSubMenu( why )
for _, tdat in SortedPairsByMemberValue( times, 1 ) do
reasonmenu:AddOption(tdat[2], function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'" "'.. tdat[3] .. '" "'.. why .. '"' )
end):SetImage(icon)--nut.schema.Call("GetUserIcon", client) or icon)
end
end
end,
onRun = function(client, arguments)
local target = nut.command.findPlayer(client, arguments[1], true)
local targetname
if (!target or !target:IsValid()) then
if (string.StartWith(arguments[1], "STEAM_0")) then
targetname = arguments[1]
table.remove(arguments, 1)
else
client:notify(nut.lang.Get("no_ply"))
return
end
else
if (target == client) then
client:notify("Вы попытались заблокировать себя. Введите другое имя.")
return
end
targetname = target:Name()
table.remove(arguments, 1)
end
local time = PLUGIN:GetTimeByString(arguments[1])
table.remove(arguments, 1)
local reason = "без причины"
if (#arguments > 0) then
reason = table.concat(arguments, " ")
end
local timetext
if time == 0 then
timetext = "перманентно"
else
timetext = PLUGIN:SecondsToFormattedString(time)
end
local bantext = Format("%s заблокирован на %s (%s)", targetname, timetext, reason)
nut.util.AddLog(bantext, LOG_FILTER_MAJOR)
nut.util.Notify(bantext, unpack(player.GetAll()))
local steamid
if target and target:IsValid() then
steamid = target:SteamID()
else
steamid = targetname
end
PLUGIN:BanPlayer(steamid, time, reason)
end
}, "ban")
PLUGIN:CreateCommand({
text = "Изменить карту сервера",
desc = "Изменить серверную карту.",
group = "superadmin",
syntax = "<string map> [number time]",
hasTarget = false,
onMenu = function( menu, icon, client, command )
end,
onRun = function(client, arguments)
local map = arguments[1]
local time = math.Clamp(tonumber(arguments[2] or "5"), 5, 60)
if (!map) then
client:notify("Вы должны представить карту.")
return
end
map = string.lower(map)
if (!file.Exists("maps/"..map..".bsp", "GAME")) then
client:notify("Карта недействительна.")
return
end
client:notify(client:Name().." изменил карту на "..map..". Смена карты произойдет через "..time.." секунд.")
timer.Create("nut_ChangeMap", time, 1, function()
game.ConsoleCommand("changelevel "..map.."\n")
end)
end
}, "map")
PLUGIN:CreateCommand({
text = "Разблокировать игрока",
desc = "Позволить заблокированному игроку подключаться к серверу.",
group = "admin",
hasTarget = false,
syntax = "<string steamID>",
onMenu = function( menu, icon, client, command )
end,
onRun = function(client, arguments, target)
local steamID = arguments[1]
if (!steamID) then
client:notify(nut.lang.Get("missing_arg", 1))
return
end
local result = PLUGIN:UnbanPlayer(steamID)
if (result) then
local bantext = Format("%s разблокировал %s ", client:Name(), steamID)
nut.util.AddLog(bantext, LOG_FILTER_MAJOR)
nut.util.Notify(bantext, unpack(player.GetAll()))
else
client:notify("Блокировка по данному SteamID не найдена.")
end
end
}, "unban")
PLUGIN:CreateCommand({
text = "Установить ранг",
desc = "Установить ранг игроку.",
group = "owner",
syntax = "<string name/steamID> [string group]",
hasTarget = false,
onMenu = function( menu, icon, client, command )
local submenu = menu:AddSubMenu( client:Name() )
for uid, power in pairs( PLUGIN.ranks ) do
submenu:AddOption(uid, function()
LocalPlayer():ConCommand( 'say /'..command..' "'..client:Name()..'" '.. uid )
end):SetImage(icon)--.schema.Call("GetUserIcon", client) or icon)
end
end,
onRun = function(client, arguments)
local steamID = arguments[1]
local group = arguments[2] or "user"
if (!steamID) then
client:notify(L("invalidArg", client, 1))
return
end
local target
-- If a player's name is passed since it is not a valid SteamID.
if (!string.find(steamID, "STEAM_0:[01]:[0-9]+")) then
target = nut.command.findPlayer(client, steamID)
if (!IsValid(target)) then
return
end
steamID = target:SteamID()
end
PLUGIN:SetUserGroup(steamID, group, target)
client:notify(client:Name().." изменил группу "..(IsValid(target) and target:Name() or steamID).." на "..group..".")
end
}, "rank")
if (SERVER) then
concommand.Add("nut_setowner", function(client, command, arguments)
if (!IsValid(client) or (IsValid(client) and client:IsListenServerHost())) then
local steamID = arguments[1]
if (!steamID) then
print("You did not provide a valid player or SteamID.")
return
end
local target
-- If a player's name is passed since it is not a valid SteamID.
if (!string.find(steamID, "STEAM_0:[01]:[0-9]+")) then
target = nut.util.findPlayer(steamID)
if (!IsValid(target)) then
print("You did not provide a valid player.")
return
end
steamID = target:SteamID()
end
PLUGIN:SetUserGroup(steamID, "owner", target)
print("You have made "..(IsValid(target) and target:Name() or steamID).." an owner.")
if (IsValid(target)) then
target:notify("Вы были назначены владельцем сервера.")
end
else
client:ChatPrint("Эту команду нужно вводить в консоль сервера.")
end
end)
end
|
local ShakeAction = {}
function ShakeAction.create(node,call,is)
local ts = 1.05
if is then
ts = is
end
local os = node:getScale()
local s0 = cc.ScaleTo:create(0.05,os * ts)
local s1 = cc.ScaleTo:create(0.1,os)
local action
if call then
action = cc.Sequence:create(s0,s1,cc.CallFunc:create(call))
else
action = cc.Sequence:create(s0,s1)
end
return action
end
return ShakeAction
|
function _hack_prime_log() -- this seems to make it update the data much quicker
for i=1,GetNumQuestLogEntries()+1 do
GetQuestLogTitle(i)
QuestieQuest:GetRawLeaderBoardDetails(i)
end
end
--- GLOBAL ---
--This is needed for functions around the addon, due to UnitLevel("player") not returning actual level PLAYER_LEVEL_UP unless this is used.
QuestieEventHandler = {}
qPlayerLevel = -1
__UPDATEFIX_IDX = 1; -- temporary bad fix
--- LOCAL ---
local QuestWatchTimers = {
cancelTimer = nil,
repeatTimer = nil
}
local lastState = {}
--False -> true -> nil
local playerEntered = false;
local hasFirstQLU = false;
local questWatchFrames = {}
for i = 1, 35 do
questWatchFrames[i] = CreateFrame("Frame", "QuestWatchFrame"..i)
questWatchFrames[i].questLogIndex = i;
questWatchFrames[i].refresh = false;
questWatchFrames[i].accept = false;
questWatchFrames[i].objectives = {}
questWatchFrames[i]:RegisterEvent("QUEST_LOG_UPDATE")--, QUEST_LOG_UPDATE
questWatchFrames[i]:SetScript("OnEvent", function(self, event, ...)
if (event == "QUEST_LOG_UPDATE") then
if(self.refresh) then
--Get quest info
local QuestInfo = QuestieQuest:GetRawLeaderBoardDetails(self.questLogIndex)
--No need to run this unless we have to.
if(Questie.db.global.debugEnabled) then
Questie:Debug(DEBUG_DEVELOP, event, "Updating index", self.questLogIndex, "Title:", QuestInfo.title, "Id:", QuestInfo.Id)
for index, objective in pairs(QuestInfo.Objectives) do
Questie:Debug(DEBUG_DEVELOP, "-------->", objective.description);
end
end
--Update the quest
C_Timer.After(1, function ()
QuestieQuest:UpdateQuest(QuestInfo.Id)
end)
--QuestieQuest:UpdateQuest(QuestInfo.Id);
self.refresh = false;
end
if(self.accept) then
local QuestInfo = QuestieQuest:GetRawLeaderBoardDetails(self.questLogIndex)
Questie:Debug(DEBUG_DEVELOP, event, "Accepted quest", self.questLogIndex, "Title:", QuestInfo.title, "Id:", QuestInfo.Id)
--Accept the quest.
QuestieQuest:AcceptQuest(QuestInfo.Id)
--Delay the update by 1 second to let everything propagate, should not be needed...
C_Timer.After(1, function ()
Questie:Debug(DEBUG_DEVELOP, event, "Updated quest", self.questLogIndex, "Title:", QuestInfo.title, "Id:", QuestInfo.Id)
QuestieQuest:UpdateQuest(QuestInfo.Id)
end)
-- deferred update (possible desync fix)
C_Timer.After(3, function()
QuestieQuest:PopulateObjectiveNotes(QuestieDB:GetQuest(QuestInfo.Id))
QuestieQuest:UpdateQuest(QuestInfo.Id)
end)
self.accept = false;
end
end
end)
end
function QuestieEventHandler:PLAYER_ENTERING_WORLD()
C_Timer.After(4, function()
_hack_prime_log()
qPlayerLevel = UnitLevel("player")
QuestieDB:Initialize()
QuestieQuest:Initialize()
QuestieQuest:GetAllQuestIdsNoObjectives()
QuestieQuest:CalculateAvailableQuests()
QuestieQuest:DrawAllAvailableQuests()
QuestieNameplate:Initialize();
QuestieTracker:Initialize()
Questie:Debug(DEBUG_ELEVATED, "PLAYER_ENTERED_WORLD")
playerEntered = true
-- manually fire QLU since enter has been delayed past the first QLU
if hasFirstQLU then
QuestieEventHandler:QUEST_LOG_UPDATE()
end
end)
--[[C_Timer.After(2, function ()
Questie:Debug(DEBUG_ELEVATED, "Player entered world")
QuestieQuest:GetAllQuestIds()
end)
C_Timer.After(5, function ()
Questie:Debug(DEBUG_ELEVATED, "Player entered world (deferred update)")
QuestieQuest:GetAllQuestIds()
end)]]--
-- periodically update the objectives of quests, temporary hold-over until we can properly fix the event based logic
--[[Questie:ScheduleRepeatingTimer(function()
if (GetNumQuestLogEntries()+1 == __UPDATEFIX_IDX) then
__UPDATEFIX_IDX = 1;
end
title, level, _, isHeader, _, isComplete, _, _questId, _, displayQuestId, _, _, _, _, _, _, _ = GetQuestLogTitle(__UPDATEFIX_IDX)
if (not isHeader) and _questId ~= nil and _questId > 0 then
QuestieQuest:UpdateQuest(_questId);
end
__UPDATEFIX_IDX = __UPDATEFIX_IDX + 1
end, 3);]]--
--local Note = QuestieFramePool:GetFrame();
--THIS WILL BE MOVED!!!
--Note.data.QuestID = 1337
--Note.data.data..NoteType = NoteType --MiniMapNote or WorldMapNote, Will be moved!
--Note.data.IconType = type;
--Note.data.questHash = questHash;
--Note.data.objectiveid = objectiveid;
--HBDPins:AddMinimapIconWorld(Questie, Note, 0, x, y, true)
--HBDPins:AddWorldMapIconWorld(Questie, Note, 0, x, y, HBD_PINS_WORLDMAP_SHOW_WORLD)
end
--Fires when a quest is accepted in anyway.
function QuestieEventHandler:QUEST_ACCEPTED(QuestLogIndex, QuestId)
Questie:Debug(DEBUG_DEVELOP, "EVENT: QUEST_ACCEPTED", "QLogIndex: "..QuestLogIndex, "QuestID: "..QuestId);
_hack_prime_log()
--Update the information on next QUEST_LOG_UPDATE
questWatchFrames[QuestLogIndex].accept = true;
--[[C_Timer.After(2, function ()
QuestieQuest:AcceptQuest(QuestId) -- is it safe to pass params to virtual functions like this?
end)
-- this needs to use a repeating timer maybe? Often times when quest is accepted, it has the same trouble as the other events
C_Timer.After(5, function()
QuestieQuest:UpdateQuest(QuestId);
end)]]--
-- Add quest accept journey note.
local data = {};
data.Event = "Quest";
data.SubType = "Accept";
data.Quest = QuestId;
data.Level = UnitLevel("player");
data.Timestamp = time();
data.Party = {};
if GetHomePartyInfo() then
data.Party = {};
local p = {};
for i, v in pairs(GetHomePartyInfo()) do
p.Name = v;
p.Class,_ ,_ = UnitClass(v);
p.Level = UnitLevel(v);
table.insert(data.Party, p);
end
end
table.insert(Questie.db.char.journey, data);
end
--Fires when a quest is removed from the questlog, this includes turning it in!
function QuestieEventHandler:QUEST_REMOVED(QuestId)
_hack_prime_log()
Questie:Debug(DEBUG_DEVELOP, "EVENT: QUEST_REMOVED", QuestId);
QuestieQuest:AbandonedQuest(QuestId)
-- Abandon Quest added to Journey
-- first check to see if the quest has been completed already or not
local skipAbandon = false;
for i in ipairs(Questie.db.char.journey) do
local entry = Questie.db.char.journey[i];
if entry.Event == "Quest" then
if entry.Quest == QuestId then
if entry.SubType == "Complete" then
skipAbandon = true;
end
end
end
end
if not skipAbandon then
local data = {};
data.Event = "Quest";
data.SubType = "Abandon";
data.Quest = QuestId;
data.Level = UnitLevel("player");
data.Timestamp = time()
data.Party = {};
if GetHomePartyInfo() then
local p = {};
for i, v in pairs(GetHomePartyInfo()) do
p.Name = v;
p.Class, _, _ = UnitClass(v);
p.Level = UnitLevel(v);
table.insert(data.Party, p);
end
end
table.insert(Questie.db.char.journey, data);
end
-- deferred update (possible desync fix?)
--C_Timer.After(3, function()
-- QuestieQuest:GetAllQuestIdsNoObjectives();
-- QuestieQuest:CalculateAvailableQuests();
-- QuestieQuest:DrawAllAvailableQuests();
--end)
end
--Fires when a quest is turned in.
function QuestieEventHandler:QUEST_TURNED_IN(questID, xpReward, moneyReward)
_hack_prime_log()
Questie:Debug(DEBUG_DEVELOP, "EVENT: QUEST_TURNED_IN", questID, xpReward, moneyReward);
QuestieQuest:CompleteQuest(questID)
-- deferred update (possible desync fix?)
--C_Timer.After(3, function()
-- QuestieQuest:GetAllQuestIdsNoObjectives()
-- QuestieQuest:CalculateAvailableQuests();
-- QuestieQuest:DrawAllAvailableQuests();
--end)
-- Complete Quest added to Journey
local data = {};
data.Event = "Quest";
data.SubType = "Complete";
data.Quest = questID;
data.Level = UnitLevel("player");
data.Timestamp = time();
data.Party = {};
if GetHomePartyInfo() then
local p = {};
for i, v in pairs(GetHomePartyInfo()) do
p.Name = v;
p.Class, _, _ = UnitClass(v);
p.Level = UnitLevel(v);
table.insert(data.Party, p);
end
end
table.insert(Questie.db.char.journey, data);
end
function QuestieEventHandler:QUEST_LOG_UPDATE()
Questie:Debug(DEBUG_DEVELOP, "QUEST_LOG_UPDATE")
hasFirstQLU = true
if(playerEntered)then
Questie:Debug(DEBUG_DEVELOP, "---> Player entered world, START.")
C_Timer.After(1, function ()
Questie:Debug(DEBUG_DEVELOP, "---> Player entered world, DONE.")
QuestieQuest:GetAllQuestIds()
end)
playerEntered = nil;
end
end
function QuestieEventHandler:QUEST_WATCH_UPDATE(QuestLogIndex)
Questie:Debug(DEBUG_INFO, "QUEST_WATCH_UPDATE", QuestLogIndex)
--When a quest gets updated, wait until next QUEST_LOG_UPDATE before updating.
questWatchFrames[QuestLogIndex].refresh = true
--[[_hack_prime_log()
title, level, _, isHeader, _, isComplete, _, questId, _, displayQuestId, _, _, _, _, _, _, _ = GetQuestLogTitle(QuestLogIndex)
Questie:Debug(DEBUG_DEVELOP, "EVENT: QUEST_WATCH_UPDATE", "QLogIndex: "..QuestLogIndex, "QuestID: "..questId);
--If a timer exists from previous upda
if(QuestWatchTimers.cancelTimer) then
Questie:CancelTimer(QuestWatchTimers.cancelTimer)
QuestWatchTimers.cancelTimer = nil;
Questie:Debug(DEBUG_DEVELOP, "[QuestieEventHandler] Cancel timer exists, canceled!")
end
if(QuestWatchTimers.repeatTimer) then
Questie:CancelTimer(QuestWatchTimers.repeatTimer)
QuestWatchTimers.repeatTimer = nil;
Questie:Debug(DEBUG_DEVELOP, "[QuestieEventHandler] Repeat timer exists, canceled!")
end
local _QuestLogIndexFinal = tonumber(QuestLogIndex)
local _questIdFinal = tonumber(questId);
QuestWatchTimers.cancelTimer = Questie:ScheduleTimer(function()
if QuestWatchTimers.repeatTimer ~= nil then
Questie:CancelTimer(QuestWatchTimers.repeatTimer)
QuestWatchTimers.repeatTimer = nil;
QuestWatchTimers.cancelTimer = nil;
Questie:Debug(DEBUG_DEVELOP, "[QuestieEventHandler] Repeat timer took to long, cancel it!")
--if _questIdFinal ~= nil and _questIdFinal > 0 then
-- QuestieQuest:UpdateQuest(_questIdFinal);
--end
end
-- always double-update
if _questIdFinal ~= nil and _questIdFinal > 0 then
QuestieQuest:UpdateQuest(_questIdFinal);
end
end, 6)
C_Timer.After(1, function() -- start repeating after 1 sec, first update was incorrectly being detected as a change because this bug is super annoying
QuestWatchTimers.repeatTimer = Questie:ScheduleRepeatingTimer(function()
local QuestInfo = QuestieQuest:GetRawLeaderBoardDetails(_QuestLogIndexFinal)
if(lastState[QuestInfo.Id] == nil or lastState[QuestInfo.Id].compareString ~= QuestInfo.compareString) then
Questie:Debug(DEBUG_DEVELOP, "[QuestieEventHandler] QUEST_WATCH_UPDATE found a change!")
lastState[QuestInfo.Id] = QuestInfo;
Questie:CancelTimer(QuestWatchTimers.repeatTimer)
Questie:CancelTimer(QuestWatchTimers.cancelTimer)
QuestWatchTimers.cancelTimer = nil;
QuestWatchTimers.repeatTimer = nil;
QuestieQuest:UpdateQuest(QuestInfo.Id);
end
end, 1)
end)]]--
end
function QuestieEventHandler:QUEST_LOG_CRITERIA_UPDATE(questID, specificTreeID, description, numFulfilled, numRequired)
Questie:Debug(DEBUG_DEVELOP, "EVENT: QUEST_LOG_CRITERIA_UPDATE", questID, specificTreeID, description, numFulfilled, numRequired);
end
function QuestieEventHandler:CUSTOM_QUEST_COMPLETE()
numEntries, numQuests = GetNumQuestLogEntries();
--Questie:Debug(DEBUG_CRITICAL, "CUSTOM_QUEST_COMPLETE", "Quests: "..numQuests);
end
function QuestieEventHandler:PLAYER_LEVEL_UP(level, hitpoints, manapoints, talentpoints, ...)
Questie:Debug(DEBUG_DEVELOP, "EVENT: PLAYER_LEVEL_UP", level);
qPlayerLevel = level;
--QuestieQuest:CalculateAvailableQuests();
--QuestieQuest:DrawAllAvailableQuests();
-- deferred update (possible desync fix?)
C_Timer.After(3, function()
qPlayerLevel = UnitLevel("player")
QuestieQuest:CalculateAvailableQuests();
QuestieQuest:DrawAllAvailableQuests();
end)
-- Complete Quest added to Journey
local data = {};
data.Event = "Level";
data.NewLevel = level;
data.Timestamp = time();
data.Party = {};
if GetHomePartyInfo() then
data.Party = {};
local p = {};
for i, v in pairs(GetHomePartyInfo()) do
p.Name = v;
p.Class, _, _ = UnitClass(v);
p.Level = UnitLevel(v);
table.insert(data.Party, p);
end
end
table.insert(Questie.db.char.journey, data);
end
--Old stuff
--This is used to see if they acually completed the quest or just fucking with us...
local NumberOfQuestInLog = -1
function QuestieEventHandler:QUEST_COMPLETE()
numEntries, numQuests = GetNumQuestLogEntries();
NumberOfQuestInLog = numQuests;
--Questie:Debug(DEBUG_CRITICAL, "EVENT: QUEST_COMPLETE", "Quests: "..numQuests);
end
function QuestieEventHandler:QUEST_FINISHED()
numEntries, numQuests = GetNumQuestLogEntries();
if (NumberOfQuestInLog ~= numQuests) then
--Questie:Debug(DEBUG_CRITICAL, "EVENT: QUEST_FINISHED", "CHANGE");
NumberOfQuestInLog = -1
end
--Questie:Debug(DEBUG_CRITICAL, "EVENT: QUEST_FINISHED", "NO CHANGE");
end
function QuestieEventHandler:MODIFIER_STATE_CHANGED(key, down)
if GameTooltip and GameTooltip:IsShown() and GameTooltip._rebuild then
GameTooltip:Hide()
GameTooltip:ClearLines()
GameTooltip:SetOwner(GameTooltip._owner, "ANCHOR_CURSOR");
GameTooltip:_rebuild() -- rebuild the tooltip
GameTooltip:SetFrameStrata("TOOLTIP");
GameTooltip:Show()
end
end
|
local tPeripherals = peripheral.getNames()
print( "Attached Peripherals:" )
if #tPeripherals > 0 then
for n=1,#tPeripherals do
local sPeripheral = tPeripherals[n]
print( sPeripheral .. " (" .. peripheral.getType( sPeripheral ) .. ")" )
end
else
print( "None" )
end
|
gunslinger = {
__stack = {},
__guns = {},
__types = {},
__automatic = {},
__scopes = {},
__interval = {}
}
local config = {
max_wear = 65534,
projectile_speed = 500,
base_dmg = 1,
base_spread = 0.001,
base_recoil = 0.001,
lite = minetest.settings:get_bool("gunslinger.lite")
}
--
-- Internal API functions
--
local function rangelim(low, val, high, default)
if not val and default then
return default
elseif low and val and high then
return math.max(low, math.min(val, high))
else
error("gunslinger: Invalid rangelim invokation!", 2)
end
end
local function get_eye_pos(player)
if not player then
return
end
local pos = player:get_pos()
pos.y = pos.y + player:get_properties().eye_height
return pos
end
local function get_pointed_thing(pos, dir, def)
if not pos or not dir or not def then
error("gunslinger: Invalid get_pointed_thing invocation" ..
" (missing params)", 2)
end
local pos2 = vector.add(pos, vector.multiply(dir, def.range))
local ray = minetest.raycast(pos, pos2)
return ray:next()
end
local function play_sound(sound, player)
minetest.sound_play(sound, {
object = player,
loop = false
})
end
local function add_auto(name, def, stack)
gunslinger.__automatic[name] = {
def = def,
stack = stack
}
end
local function validate_def(def)
if type(def) ~= "table" then
error("gunslinger.register_gun: Gun definition has to be a table!", 2)
end
if (def.mode == "automatic" or def.mode == "hybrid") and config.lite then
error("gunslinger.register_gun: Attempting to register gun of " ..
"type '" .. def.mode .. "' when lite mode is enabled", 2)
end
if not def.ammo then
def.ammo = "gunslinger:ammo"
end
if def.mode == "burst" then
def.burst = rangelim(2, def.burst, 5, 3)
end
def.dmg_mult = rangelim(1, def.dmg_mult, 100, 1)
def.reload_time = rangelim(1, def.reload_time, 10, 2.5)
def.spread_mult = rangelim(0, def.spread_mult, 500, 0)
def.recoil_mult = rangelim(0, def.recoil_mult, 500, 0)
def.pellets = rangelim(1, def.pellets, 20, 1)
-- Initialize sounds
do
def.sounds = def.sounds or {}
def.sounds.fire = def.sounds.fire or "gunslinger_fire"
def.sounds.reload = def.sounds.reload or "gunslinger_reload"
def.sounds.ooa = def.sounds.ooa or "gunslinger_ooa"
end
return def
end
--------------------------------
local function show_scope(player, scope, zoom)
if not player then
return
end
-- Create HUD overlay element
gunslinger.__scopes[player:get_player_name()] = player:hud_add({
hud_elem_type = "image",
position = {x = 0.5, y = 0.5},
alignment = {x = 0, y = 0},
text = scope
})
end
local function hide_scope(player)
if not player then
return
end
local name = player:get_player_name()
player:hud_remove(gunslinger.__scopes[name])
gunslinger.__scopes[name] = nil
end
--------------------------------
local function reload(stack, player)
-- Check for ammo
local inv = player:get_inventory()
local def = gunslinger.__guns[stack:get_name()]
local meta = stack:get_meta()
if meta:contains("reloading") then
return
end
local taken = inv:remove_item("main", def.ammo .. " " .. def.clip_size)
if taken:is_empty() then
play_sound(def.sounds.ooa, player)
else
local name = player:get_player_name()
gunslinger.__interval[name] = gunslinger.__interval[name] - def.reload_time
play_sound(def.sounds.reload, player)
meta:set_string("reloading")
local wear = math.floor(config.max_wear -
(taken:get_count() / def.clip_size) * config.max_wear)
minetest.after(def.reload_time, function(obj, rstack, twear, s_meta)
rstack:set_wear(twear)
s_meta:set_string("reloading", "")
player:set_wielded_item(rstack)
end, player, stack, wear, meta)
end
return stack
end
local function fire(stack, player)
if not stack then
return
end
local def = gunslinger.__guns[stack:get_name()]
if not def then
return stack
end
local wear = stack:get_wear()
if wear == config.max_wear then
gunslinger.__automatic[player:get_player_name()] = nil
return reload(stack, player)
end
-- Play gunshot sound
play_sound(def.sounds.fire, player)
--[[
Perform "deferred raycasting" to mimic projectile entities, without
actually using entities:
- Perform initial raycast to get position of target if it exists
- Calculate time taken for projectile to travel from gun to target
- Perform actual raycast after the calculated time
This process throws in a couple more calculations and an extra raycast,
but the vastly improved realism at the cost of a negligible performance
hit is always great to have.
]]
local time = 0.1 -- Default to 0.1s
local dir = player:get_look_dir()
local pos1 = get_eye_pos(player)
pos1 = vector.add(pos1, dir)
local initial_pthing = get_pointed_thing(pos1, dir, def)
if initial_pthing then
local pos2 = minetest.get_pointed_thing_position(initial_pthing)
time = vector.distance(pos1, pos2) / config.projectile_speed
end
local random = PcgRandom(os.time())
for i = 1, def.pellets do
-- Mimic inaccuracy by applying randomised miniscule deviations
if def.spread_mult ~= 0 then
dir = vector.apply(dir, function(n)
return n + random:next(-def.spread_mult, def.spread_mult) * config.base_spread
end)
end
minetest.after(time, function(obj, pos, look_dir, gun_def)
local pointed = get_pointed_thing(pos, look_dir, gun_def)
if pointed and pointed.type == "object" then
local target = pointed.ref
if target:get_player_name() ~= obj:get_player_name() then
local point = pointed.intersection_point
local dmg = config.base_dmg * gun_def.dmg_mult
-- Add 50% damage if headshot
if point.y > target:get_pos().y + 1.2 then
dmg = dmg * 1.5
end
-- Add 20% more damage if player using scope
if gunslinger.__scopes[obj:get_player_name()] then
dmg = dmg * 1.2
end
target:punch(obj, nil, {damage_groups = {fleshy = dmg}})
end
end
end, player, pos1, dir, def)
-- Projectile particle
minetest.add_particle({
pos = pos1,
velocity = vector.multiply(dir, config.projectile_speed),
acceleration = {x = 0, y = 0, z = 0},
expirationtime = 3,
size = 3,
collisiondetection = true,
collision_removal = true,
object_collision = true,
glow = 10
})
end
-- Simulate recoil
local offset = config.base_recoil * def.recoil_mult
local look_vertical = player:get_look_vertical() - offset
look_vertical = rangelim(-math.pi / 2, look_vertical, math.pi / 2)
player:set_look_vertical(look_vertical)
-- Update wear
wear = stack:get_wear() + def.unit_wear
if wear > config.max_wear then
wear = config.max_wear
end
stack:set_wear(wear)
return stack
end
local function burst_fire(stack, player)
local def = gunslinger.__guns[stack:get_name()]
for i = 1, def.burst do
minetest.after(i / def.fire_rate, function(...)
-- Use global var to store stack, because the stack
-- can't be directly accessed outside minetest.after
gunslinger.__stack[arg[2]:get_player_name()] = fire(arg[1], arg[2])
end, stack, player)
end
return gunslinger.__stack[player:get_player_name()]
end
--------------------------------
local function on_lclick(stack, player)
if not stack or not player then
return
end
local def = gunslinger.__guns[stack:get_name()]
if not def then
return
end
local name = player:get_player_name()
if gunslinger.__interval[name] and gunslinger.__interval[name] < def.unit_time then
return
end
gunslinger.__interval[name] = 0
if def.mode == "automatic" and not gunslinger.__automatic[name] then
stack = fire(stack, player)
add_auto(name, def, stack)
elseif def.mode == "hybrid"
and not gunslinger.__automatic[name] then
if gunslinger.__scopes[name] then
stack = burst_fire(stack, player)
else
add_auto(name, def)
end
elseif def.mode == "burst" then
stack = burst_fire(stack, player)
elseif def.mode == "semi-automatic" then
stack = fire(stack, player)
elseif def.mode == "manual" then
local meta = stack:get_meta()
local loaded = meta:get("loaded")
if not loaded then
if def.sounds.load then
play_sound(def.sounds.load, player)
end
meta:set_string("loaded", "true")
stack = reload(stack, player)
else
meta:set_string("loaded", "")
stack = fire(stack, player)
end
end
return stack
end
local function on_rclick(stack, player)
local def = gunslinger.__guns[stack:get_name()]
if gunslinger.__scopes[player:get_player_name()] then
hide_scope(player)
else
if def.scope then
show_scope(player, def.scope, def.gunslinger.__scopes)
end
end
end
--------------------------------
minetest.register_globalstep(function(dtime)
for name in pairs(gunslinger.__interval) do
gunslinger.__interval[name] = gunslinger.__interval[name] + dtime
end
if not config.lite then
for name, info in pairs(gunslinger.__automatic) do
local player = minetest.get_player_by_name(name)
if not player or player:get_hp() <= 0 then
gunslinger.__automatic[name] = nil
elseif gunslinger.__interval[name] > info.def.unit_time then
if player:get_player_control().LMB and
player:get_wielded_item():get_name() ==
info.stack:get_name() then
-- If LMB pressed, fire
info.stack = fire(info.stack, player)
player:set_wielded_item(info.stack)
if gunslinger.__automatic[name] then
gunslinger.__automatic[name].stack = info.stack
end
gunslinger.__interval[name] = 0
else
gunslinger.__automatic[name] = nil
end
end
end
end
end)
--
-- External API functions
--
function gunslinger.get_def(name)
return gunslinger.__guns[name]
end
function gunslinger.register_type(name, def)
assert(type(name) == "string" and type(def) == "table",
"gunslinger.register_type: Invalid params!")
assert(not gunslinger.__types[name], "gunslinger.register_type:" ..
" Attempt to register a type with an existing name!")
gunslinger.__types[name] = def
end
function gunslinger.register_gun(name, def)
assert(type(name) == "string" and type(def) == "table",
"gunslinger.register_gun: Invalid params!")
assert(not gunslinger.__guns[name], "gunslinger.register_gun: " ..
"Attempt to register a gun with an existing name!")
-- Import type defaults if def.type specified
if def.type then
assert(gunslinger.__types[def.type], "gunslinger.register_gun: Invalid type!")
for attr, val in pairs(gunslinger.__types[def.type]) do
def[attr] = val
end
end
def = validate_def(def)
-- Add additional helper fields for internal use
def.unit_wear = math.ceil(config.max_wear / def.clip_size)
def.unit_time = 1 / def.fire_rate
-- Register gun
gunslinger.__guns[name] = def
def.itemdef.on_use = on_lclick
def.itemdef.on_secondary_use = on_rclick
def.itemdef.on_place = function(stack, player, pointed)
if pointed.type == "node" then
local node = minetest.get_node_or_nil(pointed.under)
local nodedef = minetest.registered_items[node.name]
return nodedef.on_rightclick or on_rclick(stack, player)
elseif pointed.type == "object" then
local entity = pointed.ref:get_luaentity()
return entity:on_rightclick(player) or on_rclick(stack, player)
end
end
-- Register tool
minetest.register_tool(name, def.itemdef)
end
|
--------------------------------
-- @module EaseQuarticActionInOut
-- @extend ActionEase
-- @parent_module cc
---@class cc.EaseQuarticActionInOut:cc.ActionEase
local EaseQuarticActionInOut = {}
cc.EaseQuarticActionInOut = EaseQuarticActionInOut
--------------------------------
---
---@param action cc.ActionInterval
---@return cc.EaseQuarticActionInOut
function EaseQuarticActionInOut:create(action)
end
--------------------------------
---
---@return cc.EaseQuarticActionInOut
function EaseQuarticActionInOut:clone()
end
--------------------------------
---
---@param time number
---@return cc.EaseQuarticActionInOut
function EaseQuarticActionInOut:update(time)
end
--------------------------------
---
---@return cc.ActionEase
function EaseQuarticActionInOut:reverse()
end
--------------------------------
---
---@return cc.EaseQuarticActionInOut
function EaseQuarticActionInOut:EaseQuarticActionInOut()
end
return nil
|
----------------------------------------------------- WIRELESS DATA TRANSMITTER ---------------------------------
-- Entity --
wdtE = table.deepcopy(data.raw["constant-combinator"]["constant-combinator"])
wdtE.type = "constant-combinator"
wdtE.name = "WirelessDataTransmitter"
wdtE.icon = "__Mobile_Factory_Graphics__/graphics/matter-serialization/WirelessDataTransmitterI.png"
wdtE.icon_size = 64
wdtE.minable = {mining_time = 0.2, result = "WirelessDataTransmitter"}
wdtE.max_health = 200
wdtE.corpse = "big-remnants"
wdtE.collision_box = {{-1.8, -1.8}, {1.8, 1.8}}
wdtE.selection_box = wdtE.collision_box
wdtE.item_slot_count = 999
wdtE.circuit_wire_max_distance = 20
wdtE.circuit_connector_sprites = nil
wdtE.sprites.sheets =
{ {
filename = "__Mobile_Factory_Graphics__/graphics/matter-serialization/WirelessDataTransmitterE.png",
width = 400,
height = 400,
shift = {0,-0.2},
scale = 1/10 * 3.2,
frames = 1
},
{
filename = "__Mobile_Factory_Graphics__/graphics/matter-serialization/WirelessDataTransmitterS.png",
width = 400,
height = 400,
shift = {1.8,0.4},
draw_as_shadow = true,
scale = 1/10 * 3.2,
frames = 1
}
}
wdtE.circuit_wire_connection_points =
{
{
wire = {green={-0.05,0.82}, red={0.05,0.82}},
shadow = {green={-0.05,0.85}, red={0.05,0.85}}
},
{
wire = {green={-0.05,0.82}, red={0.05,0.82}},
shadow = {green={-0.05,0.85}, red={0.05,0.85}}
},
{
wire = {green={-0.05,0.82}, red={0.05,0.82}},
shadow = {green={-0.05,0.85}, red={0.05,0.85}}
},
{
wire = {green={-0.05,0.82}, red={0.05,0.82}},
shadow = {green={-0.05,0.85}, red={0.05,0.85}}
}
}
data:extend{wdtE}
-- Item --
local wdtI = {}
wdtI.type = "item"
wdtI.name = "WirelessDataTransmitter"
wdtI.icon = "__Mobile_Factory_Graphics__/graphics/matter-serialization/WirelessDataTransmitterI.png"
wdtI.icon_size = 64
wdtI.place_result = "WirelessDataTransmitter"
wdtI.subgroup = "DataSerialization"
wdtI.order = "e"
wdtI.stack_size = 10
data:extend{wdtI}
-- Recipe --
local wdtR = {}
wdtR.type = "recipe"
wdtR.name = "WirelessDataTransmitter"
wdtR.energy_required = 6
wdtR.enabled = false
wdtR.ingredients =
{
{"CrystalizedCircuit", 18},
{"MachineFrame3", 6}
}
wdtR.result = "WirelessDataTransmitter"
data:extend{wdtR}
-- Animation --
wdtA = {}
wdtA.name = "WirelessDataTransmitterA"
wdtA.type = "animation"
wdtA.frame_count = 60
wdtA.filename = "__Mobile_Factory_Graphics__/graphics/matter-serialization/WirelessDataTransmitterA.png"
wdtA.size = 500
wdtA.line_length = 10
wdtA.animation_speed = 1/6
wdtA.scale = 1/8 * 3.2
wdtA.flags = {"terrain"}
data:extend{wdtA}
|
local os_ext = require('os_ext')
local str = require('str')
local path = {}
local _windows_invalid_path_chars = {
'"',
'<',
'>',
'|',
'\0'
}
for i = 1, 31 do
table.insert(_windows_invalid_path_chars, string.char(i))
end
-- returns windows specific cmd string to list all files in the root_directory
-- with the option to also include subdirectories
local function _wincmd_listfiles(root_directory, include_subdirectories)
-- /b removes header/extraneous information
-- /a-d defines usage of attribute -d (anything not a directory)
local command = string.format('dir "%s" /b /a-d', root_directory)
if include_subdirectories then
command = command .. ' /s'
end
return command
end
local function _unixcmd_listfiles(root_directory, include_subdirectories)
local depth = ''
if not include_subdirectories then
depth = '-maxdepth 7'
end
local command = string.format('find "%s" %s -type f', root_directory, depth)
return command
end
-- returns windows specific cmd string to list all directories in the root_directory
-- with the option to also include subdirectories
local function _wincmd_listdir(root_directory, include_subdirectories)
-- /b removes header/extraneous information
-- /ad defines usage of attribute directory
local command = string.format('dir "%s" /b /ad', root_directory)
if include_subdirectories then
command = command .. ' /s'
end
return command
end
local function _unixcmd_listdir(root_directory, include_subdirectories)
local depth = ''
if not include_subdirectories then
depth = '-maxdepth 7'
end
local command = string.format('find "%s" "%s" -type d', root_directory, depth)
return command
end
-- returns path string of the current (present) working directory
function path.get_cwd()
local result = false
local output = nil
local err_code = 0
if os_ext.is_windows then
result, output, err_code = os_ext.run_command('cd')
else
result, output, err_code = os_ext.run_command('pwd')
end
return output[1]
end
-- returns whether the target_path exists or not
function path.exists(target_path)
assert(type(target_path) == 'string')
local eval_output = function(result, output)
return result and output[1] == 'true'
end
if os_ext.is_windows then
local result, output, err_code = os_ext.run_command(string.format('if exist "%s" (echo true) else (echo false)', target_path))
return eval_output(result, output)
else
local result, output, err_code = os_ext.run_command(string.format('if test -f "%s"; then echo true; else echo false; fi', target_path))
if eval_output(result, output) then
return true
end
result, output, err_code = os_ext.run_command(string.format('if test -d "%s"; then echo true; else echo false; fi', target_path))
return eval_output(result, output)
end
end
-- need to potentially add filtering
function path.list_files(root_directory, include_subdirectories)
assert(type(root_directory) == 'string')
assert(path.exists(root_directory), string.format('directory "%s" does not exist', root_directory))
local command = nil
if os_ext.is_windows then
local command = _wincmd_listfiles(root_directory, include_subdirectories)
local result, files, err_code = os_ext.run_command(command)
-- when /s (include subdirectories) is not used, dir
-- does not include the directory path in the output
if not include_subdirectories then
local is_path_escaped = root_directory:sub(-1, -1) == os_ext.path_separator
if not is_path_escaped then
root_directory = root_directory .. os_ext.path_separator
end
for k, _ in pairs(files) do
files[k] = root_directory .. files[k]
end
end
return files
else
command = _unixcmd_listfiles(root_directory, include_subdirectories)
local result, files, err_code = os_ext.run_command(command)
return files
end
end
-- need to potentially add filtering
function path.list_dir(root_directory, include_subdirectories)
assert(type(root_directory) == 'string')
assert(path.exists(root_directory), string.format('directory "%s" does not exist', root_directory))
if os_ext.is_windows then
local command = _wincmd_listdir(root_directory, include_subdirectories)
local result, folders, err_code = os_ext.run_command(command)
-- when /s (include subdirectories) is not used, dir
-- does not include the directory path in the output
if not include_subdirectories then
local is_path_escaped = root_directory:sub(-1, -1) == os_ext.path_separator
if not is_path_escaped then
root_directory = root_directory .. os_ext.path_separator
end
for k, _ in pairs(folders) do
folders[k] = root_directory .. folders[k]
end
end
return folders
else
local command = _unixcmd_listdir(root_directory, include_subdirectories)
local result, folders, err_code = os_ext.run_command(command)
return folders
end
end
function path.combine(directory_path, filepath)
assert(type(directory_path) == 'string')
assert(type(filepath) == 'string')
return string.format('%s%s%s', directory_path, os_ext.path_separator, filepath)
end
function path.get_filename(filepath)
assert(type(filepath) == 'string')
local index = str.last_index_of(filepath, os_ext.path_separator)
if index == -1 then
return ''
end
local filename = filepath:sub(index + 1, string.len(filepath))
return filename
end
local function _has_invalid_chars(str)
local char = nil
if os_ext.is_windows then
for i = 1, string.len(str) do
char = str:sub(i, i)
for _, c in pairs(_windows_invalid_path_chars) do
if char == c then
return true
end
end
end
else
-- TODO add linux
assert(true == false)
end
return false
end
return path
|
-- CameraController.singletonInstance.zoomMin = 0.1;
-- UnityEngine.Application.targetFrameRate = 60.0;
-- RenderSettings.fog = false;
if DebugLog == nil then
DebugLog = {};
DebugLog.File = io.open("/data/local/tmp/script/rom.log", "a");
DebugLog.Write = function(data)
DebugLog.File:write(os.date("%x %X") .. ' ' .. data .. "\n");
DebugLog.File:flush();
end;
end;
if Game~=nil and Game.me~=nil then
DebugLog.Write(tostring(Game.me));
end;
function SetFrameRate(fps)
UnityEngine.Application.targetFrameRate = fps;
end;
function ZoomHack(apply)
if apply then
CameraController.singletonInstance.zoomMin = 0.1;
else
CameraController.singletonInstance.zoomMin = 0.7;
end
end;
function RemoveFog()
RenderSettings.fog = false;
end;
ZoomHack(true);
RemoveFog();
SetFrameRate(60.0);
DebugLog.Write("loaded");
|
-- harmograph
local J = require "include/protojuce"
function Harmograph(args)
local bounds = args.bounds or J.Rectangle_int{15,0,480,330};
local pageBack = args.pageBack or J.Colour.white;
local pageFore = args.pageFore or J.Colour.black;
local graphBack = args.graphBack or J.Colour.white;
local graphFore = args.graphFore or J.Colour.black;
local yMax = args.yMax or 500
local pos = args.pos or 0
local frame = J.Rectangle_int(4, 30, bounds.w-50, bounds.h-65)
local outFrame = J.Rectangle_int(2, 28, frame.w+4, frame.h+4)
local backBuffer = J.Image(J.Image.PixelFormat.RGB, bounds.w, bounds.h, true)
-- initialize backbuffer
do
local g = J.Graphics(backBuffer)
g:fillAll(pageBack)
g:setColour(graphFore)
g:drawRect(outFrame, 1)
g:setColour(pageFore)
-- draw the Y axis labels
g:setFont(14)
for pos, label in pairs{0=0; 0.5=50; 1=100} do
local y = self.frame.y+((self.frame.h-10)*(1-pos))-6
g:drawText(tostring(label), self.frame:getR()+3, y, 33, 20)
end
end
local renderGraph = function()
end
renderGraph()
local yfactor = 0.5*frame.h/yMax
return {
draw = function (g)
g:setColour(J.Colour.black)
for x=0,frame.w do
if x==math.floor(pos*frame.w) then
g:setColour(J.Colour.blue)
g:drawLine(x+10, 10, x+10, 410)
end
local ls = makeLengths(x/graphW)
g:setColour(J.Colour(64,64,64))
for k,v in ipairs(ls) do
g:setPixel(x+10, graphH-(v*3)*yfactor)
end
g:setColour(J.Colour(128,128,128))
for k,v in ipairs(ls) do
g:setPixel(x+10, graphH-(v*2)*yfactor)
end
g:setColour(J.Colour.black)
for k,v in ipairs(ls) do
g:setPixel(x+10, graphH-v*yfactor)
end
end
end,
}
end
return Harmograph
|
-----------------------------------
--
-- Zone: Windurst_Waters (238)
--
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters/IDs")
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/conquest")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/zone")
-----------------------------------
function onInitialize(zone)
-- Check if we are on Windurst Mission 1-3
zone:registerRegion(1, 23, -12, -208, 31, -8, -197)
applyHalloweenNpcCostumes(zone:getID())
end
function onZoneIn(player, prevZone)
local cs = -1
if ENABLE_ROV == 1 and player:getCurrentMission(ROV) == tpz.mission.id.rov.RHAPSODIES_OF_VANADIEL and player:getMainLvl()>=3 then
cs = 30035
end
if player:getCurrentMission(ROV) == tpz.mission.id.rov.FATES_CALL and player:getCurrentMission(player:getNation()) > 15 then
cs = 30036
end
-- FIRST LOGIN (START CS)
if player:getPlaytime(false) == 0 then
if NEW_CHARACTER_CUTSCENE == 1 then
cs = 531
end
player:setPos(-40, -5, 80, 64)
player:setHomePoint()
elseif player:getCurrentMission(COP) == tpz.mission.id.cop.THE_ROAD_FORKS and player:getCharVar("MEMORIES_OF_A_MAIDEN_Status") == 1 then -- COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route
player:setCharVar("MEMORIES_OF_A_MAIDEN_Status", 2)
cs = 871
end
-- MOG HOUSE EXIT
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
local position = math.random(1, 5) + 157
player:setPos(position, -5, -62, 192)
end
return cs
end
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end
function onRegionEnter(player, region)
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe
-- If we're on Windurst Mission 1-3
if player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.THE_PRICE_OF_PEACE and player:getCharVar("MissionStatus") == 2 then
player:startEvent(146)
end
end,
}
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 531 then
player:messageSpecial(ID.text.ITEM_OBTAINED, 536)
elseif csid == 146 then -- Returned from Giddeus, Windurst 1-3
player:setCharVar("MissionStatus", 3)
player:setCharVar("ghoo_talk", 0)
player:setCharVar("laa_talk", 0)
elseif csid == 30035 then
player:completeMission(ROV, tpz.mission.id.rov.RHAPSODIES_OF_VANADIEL)
player:addMission(ROV, tpz.mission.id.rov.RESONACE)
elseif csid == 30036 then
player:completeMission(ROV, tpz.mission.id.rov.FATES_CALL)
player:addMission(ROV, tpz.mission.id.rov.WHAT_LIES_BEYOND)
end
end
|
local status_ok, telescope = pcall(require, "telescope")
if not status_ok then
return
end
local mini_fuzzy_sorter = require("mini.fuzzy").get_telescope_sorter
telescope.setup {
defaults = {
vimgrep_arguments = {
"rg",
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case",
},
prompt_prefix = " ",
selection_caret = " ",
path_display = { "smart" },
entry_prefix = " ",
initial_mode = "insert",
generic_sorter = mini_fuzzy_sorter,
file_sorter = mini_fuzzy_sorter,
layout_strategy = "horizontal",
layout_config = {
horizontal = {
preview_width = 0.55,
results_width = 0.8,
},
vertical = {
mirror = false,
prompt_position = "bottom",
},
width = 0.87,
height = 0.80,
preview_cutoff = 120,
},
},
pickers = {
colorscheme = {
enable_preview = true,
},
-- Default configuration for builtin pickers goes here:
-- picker_name = {
-- picker_config_key = value,
-- ...
-- }
-- Now the picker_config_key will be applied every time you call this
-- builtin picker
},
extensions = {
-- Your extension configuration goes here:
-- extension_name = {
-- extension_config_key = value,
-- }
-- please take a look at the readme of the extension you want to configure
},
}
|
-- 3rd party libraries
include("span-lite")
include("spdlog")
include("catch2")
|
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
-- This file is automaticly generated. Don't edit manualy!
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
---@class C_SpellBook
C_SpellBook = {}
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_SpellBook.ContainsAnyDisenchantSpell)
---@return boolean @contains
function C_SpellBook.ContainsAnyDisenchantSpell()
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_SpellBook.GetSkillLineIndexByID)
---@param skillLineID number
---@return number @skillIndex
function C_SpellBook.GetSkillLineIndexByID(skillLineID)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_SpellBook.IsSpellDisabled)
---@param spellID number
---@return boolean @disabled
function C_SpellBook.IsSpellDisabled(spellID)
end
|
--[[
PersistenceXP data file for Flight Factor 757
]]
module(..., package.seeall)
--Modules
local LIP = require("LIP")
local LARM = nil
local RARM = nil
local pxpSwitchData = {}
function pxpCompile()
if (XPLMFindDataRef("anim/armCapt/1") ~= nil) then
LARM = get("anim/armCapt/1")
end
if (XPLMFindDataRef("anim/armFO/1") ~= nil) then
RARM = get("anim/armFO/1")
end
pxpSwitchData = {
PersistenceData = {
LARM = LARM;
RARM = RARM;
}
}
LIP.save(AIRCRAFT_PATH .. "/pxpPersistence757.ini", pxpSwitchData)
print("PersistenceXP 757 Panel State Saved")
end
function pxpRead()
local f = io.open(AIRCRAFT_PATH .. "/pxpPersistence757.ini","r")
if f ~= nil then
io.close(f)
pxpSwitchData = LIP.load(AIRCRAFT_PATH .. "/pxpPersistence757.ini")
if (XPLMFindDataRef("anim/armCapt/1") ~= nil) then
if pxpSwitchData.PersistenceData.LARM ~= nil then
set("anim/armCapt/1", pxpSwitchData.PersistenceData.LARM)
end
end
if (XPLMFindDataRef("anim/armFO/1") ~= nil) then
if pxpSwitchData.PersistenceData.RARM ~= nil then
set("anim/armFO/1", pxpSwitchData.PersistenceData.RARM)
end
end
print("PersistenceXP 757 Panel State Loaded")
end
end
|
local antiSpam = {}
local criminalRanks = {
--Name, Required Points, whatGiveFunctiom
{"L0. Trial", 0, function() return false end},
{"L1. Criminal", 100, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",100 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",100 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",100 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",100 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",100 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",100 )
exports.AURpayments:addMoney(thePlayer, 20000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L2. Criminal", 300, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",100 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",150 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",150 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",150 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",150 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",150 )
exports.AURpayments:addMoney(thePlayer, 40000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L3. Criminal", 600, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",170 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",170 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",170 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",170 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",170 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",170 )
exports.AURpayments:addMoney(thePlayer, 80000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L4. Criminal", 1000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",190 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",190 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",190 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",190 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",190 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",190 )
exports.AURpayments:addMoney(thePlayer, 100000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L5. Criminal", 1500, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",200 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",200 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",200 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",200 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",200 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",200 )
exports.AURpayments:addMoney(thePlayer, 120000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L6. Criminal", 2000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",220 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",220 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",220 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",220 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",220 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",220 )
exports.AURpayments:addMoney(thePlayer, 150000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L7. Criminal", 2500, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",250 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",250 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",250 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",250 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",250 )
exports.csgdrugs:giveDrug(thePlayer, "Weed", 250 )
exports.AURpayments:addMoney(thePlayer, 180000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L8. Criminal", 4000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",280 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",280 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",280 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",280 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",280 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",280 )
exports.AURpayments:addMoney(thePlayer, 200000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L9. Criminal", 6000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",290 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",290 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",290 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",290 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",290 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",290 )
exports.AURpayments:addMoney(thePlayer, 240000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L10. Criminal", 8000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",300 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",300 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",300 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",300 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",300 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",300 )
exports.AURpayments:addMoney(thePlayer, 260000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L11. Criminal", 10000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",320 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",320 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",320 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",320 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",320 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",320 )
exports.AURpayments:addMoney(thePlayer, 280000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L12. Criminal", 50000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",350 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",350 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",350 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",350 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",350 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",350 )
exports.AURpayments:addMoney(thePlayer, 300000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L13. Criminal", 100000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",370 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",370 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",370 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",370 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",370 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",370 )
exports.AURpayments:addMoney(thePlayer, 340000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L14. Criminal", 150000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",390 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",390 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",390 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",390 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",390 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",390 )
exports.AURpayments:addMoney(thePlayer, 360000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L15. Criminal", 300000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",400 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",400 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",400 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",400 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",400 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",400 )
exports.AURpayments:addMoney(thePlayer, 380000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L16. Criminal", 500000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",420 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",420 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",420 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",420 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",420 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",420 )
exports.AURpayments:addMoney(thePlayer, 400000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L17. Criminal", 700000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",500 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",500 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",500 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",500 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",500 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",500 )
exports.AURpayments:addMoney(thePlayer, 500000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L18. Criminal", 1000000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",700 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",700 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",700 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",700 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",700 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",700 )
exports.AURpayments:addMoney(thePlayer, 600000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L18. Criminal", 2000000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",800 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",800 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",800 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",800 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",800 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",800 )
exports.AURpayments:addMoney(thePlayer, 800000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
{"L20. Criminal", 3000000, function(thePlayer)
exports.csgdrugs:giveDrug(thePlayer, "LSD",1000 )
exports.csgdrugs:giveDrug(thePlayer, "Cocaine",1000 )
exports.csgdrugs:giveDrug(thePlayer, "Heroine",1000 )
exports.csgdrugs:giveDrug(thePlayer, "Ritalin",1000 )
exports.csgdrugs:giveDrug(thePlayer, "Ecstasy",1000 )
exports.csgdrugs:giveDrug(thePlayer, "Weed",1000 )
exports.AURpayments:addMoney(thePlayer, 1000000,"Custom","Criminal Promotion",0,"AURcriminalp")
return true
end},
}
function giveCriminalPoints (thePlayer, theReason, points)
local getCurrentPoints = exports.AURcurtmisc:getPlayerAccountData(thePlayer, "criminalpoints")
exports.AURcurtmisc:setPlayerAccountData(thePlayer, "criminalpoints", getCurrentPoints+points)
setElementData(thePlayer, "criminalpoints", getCurrentPoints+points)
checkRankings(thePlayer)
return true
end
function takeCriminalPoints (thePlayer, theReason, points)
local getCurrentPoints = exports.AURcurtmisc:getPlayerAccountData(thePlayer, "criminalpoints")
exports.AURcurtmisc:setPlayerAccountData(thePlayer, "criminalpoints", getCurrentPoints-points)
setElementData(thePlayer, "criminalpoints", getCurrentPoints-points)
checkRankings(thePlayer)
return true
end
function getCriminalPoints (thePlayer)
local getCurrentPoints = exports.AURcurtmisc:getPlayerAccountData(thePlayer, "criminalpoints")
return getCurrentPoints
end
function checkRankings (thePlayer)
if (not isElement(thePlayer)) or (not exports.server:isPlayerLoggedIn(thePlayer)) then return false end
for i=1, #criminalRanks do
if (math.floor(getCriminalPoints(thePlayer)) <= criminalRanks[i][2]) then
if ((getCriminalPoints(thePlayer)-criminalRanks[i][2]) <= 5 and (getCriminalPoints(thePlayer)-criminalRanks[i][2]) >= 0 ) then
local userID = exports.server:getPlayerAccountID(thePlayer)
if (not isTimer(antiSpam[userID])) then
if (criminalRanks[i][3](thePlayer) == true) then
exports.NGCdxmsg:createNewDxMessage(thePlayer, string.format(exports.AURlanguage:getTranslate("You got promoted to %s.", true, thePlayer), criminalRanks[i][1]), 66, 244, 98)
antiSpam[userID] = setTimer(function() killTimer(antiSpam[userID]) end, 60000, 1)
end
end
end
if (i+1 <= #criminalRanks) then
return criminalRanks[i][1], criminalRanks[i+1][1], criminalRanks[i+1][2]
else
return criminalRanks[i][1], 0, "-"
end
end
end
end
addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), function ()
for index, player in pairs(getElementsByType("player")) do
if (exports.server:isPlayerLoggedIn(player)) then
setElementData(player, "criminalpoints", getCriminalPoints(player))
local theRank, theNextRank, theNextRankP = checkRankings(player)
setElementData(player, "criminalrank", theRank)
setElementData(player, "criminalnextrank", theNextRank.." ("..theNextRankP.." points)")
end
end
end)
addEventHandler("onPlayerLogin", getRootElement(), function()
setElementData(source, "criminalpoints", getCriminalPoints(source))
local theRank, theNextRank, theNextRankP = checkRankings(source)
setElementData(source, "criminalrank", theRank)
setElementData(source, "criminalnextrank", theNextRank.." ("..theNextRankP.." points)")
end)
|
--[[
author: Aussiemon
-----
Copyright 2021 Aussiemon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
local mod = get_mod("CreatureSpawner")
mod.regular_units = {}
mod.dummy_units = {}
mod.misc_units = {}
mod.special_units = {}
mod.boss_units = {}
mod.all_units = {}
mod.unit_category_names = {
"regular",
"dummy",
"misc",
"special",
"boss",
"all"
}
mod.unit_categories = {
beastmen_bestigor = {
"regular",
"special",
},
beastmen_bestigor_dummy = {
"dummy",
"misc",
},
beastmen_gor = {
"regular",
},
beastmen_gor_dummy = {
"dummy",
"misc",
},
beastmen_minotaur = {
"regular",
"boss",
},
beastmen_standard_bearer = {
"regular",
"special",
},
beastmen_standard_bearer_crater = {
"misc",
},
beastmen_ungor = {
"regular",
},
beastmen_ungor_dummy = {
"dummy",
"misc",
},
beastmen_ungor_archer = {
"regular",
},
chaos_berzerker = {
"regular",
"special",
},
chaos_corruptor_sorcerer = {
"regular",
"special",
},
chaos_dummy_exalted_sorcerer_drachenfels = {
"dummy",
"misc",
},
chaos_dummy_sorcerer = {
"dummy",
"misc",
},
chaos_dummy_troll = {
"dummy",
"misc",
},
chaos_exalted_champion_norsca = {
"boss",
},
chaos_exalted_champion_warcamp = {
"boss",
},
chaos_exalted_sorcerer = {
"boss",
},
chaos_exalted_sorcerer_drachenfels = {
"boss",
},
chaos_fanatic = {
"regular",
},
chaos_greed_pinata = {
"misc",
},
chaos_marauder = {
"regular",
},
chaos_marauder_tutorial = {
"misc",
},
chaos_marauder_with_shield = {
"regular",
},
chaos_mutator_sorcerer = {
"misc",
},
chaos_plague_sorcerer = {
"misc",
},
chaos_plague_wave_spawner = {
"misc",
},
chaos_raider = {
"regular",
"special",
},
chaos_raider_tutorial = {
"misc",
},
chaos_spawn = {
"regular",
"boss",
},
chaos_spawn_exalted_champion_norsca = {
"boss",
},
chaos_tentacle = {
"misc",
},
chaos_tentacle_sorcerer = {
"misc",
},
chaos_troll = {
"regular",
"boss",
},
chaos_vortex = {
"misc",
},
chaos_vortex_sorcerer = {
"regular",
"special",
},
chaos_warrior = {
"regular",
"special",
},
chaos_zombie = {
"misc",
},
critter_pig = {
"regular",
},
critter_rat = {
"regular",
},
curse_mutator_sorcerer = {
"misc",
},
pet_pig = {
"misc",
},
pet_rat = {
"misc",
},
skaven_clan_rat = {
"regular",
},
skaven_clan_rat_tutorial = {
"misc",
},
skaven_clan_rat_with_shield = {
"regular",
},
skaven_dummy_clan_rat = {
"dummy",
"misc",
},
skaven_dummy_slave = {
"dummy",
"misc",
},
skaven_explosive_loot_rat = {
"misc",
},
skaven_grey_seer = {
"boss",
},
skaven_gutter_runner = {
"regular",
"special",
},
skaven_loot_rat = {
"regular",
"special",
},
skaven_pack_master = {
"regular",
"special",
},
skaven_plague_monk = {
"regular",
"special",
},
skaven_poison_wind_globadier = {
"regular",
"special",
},
skaven_rat_ogre = {
"regular",
"boss",
},
skaven_ratling_gunner = {
"regular",
"special",
},
skaven_slave = {
"regular",
},
skaven_storm_vermin = {
"regular",
"special",
},
skaven_storm_vermin_champion = {
"misc",
"boss",
},
skaven_storm_vermin_commander = {
"regular",
"special",
},
skaven_storm_vermin_warlord = {
"boss",
},
skaven_storm_vermin_with_shield = {
"regular",
"special",
},
skaven_stormfiend = {
"regular",
"boss",
},
skaven_stormfiend_boss = {
"boss",
},
skaven_stormfiend_demo = {
"misc",
"boss",
},
skaven_warpfire_thrower = {
"regular",
"special",
}
}
mod.ai_blacklist = {
chaos_exalted_sorcerer_drachenfels = true
}
mod.hub_levels = {
inn_level = true,
inn_level_skulls = true,
inn_level_celebrate = true,
inn_level_halloween = true,
inn_level_sonnstill = true
}
local mod_data = {
name = "Creature Spawner", -- Readable mod name
description = mod:localize("cs_mod_description"), -- Mod description
is_togglable = true, -- If the mod can be enabled/disabled
is_mutator = false, -- If the mod is mutator
mutator_settings = {} -- Extra settings, if it's mutator
}
mod_data.options = {
widgets = { -- Widget settings for the mod options menu
-- { -- Selected spawning unit
-- ["setting_id"] = "cs_selected_unit",
-- ["type"] = "dropdown",
-- ["text"] = "Selected Unit",
-- ["tooltip"] = "This unit is selected for spawning.",
-- ["options"] = {
-- {text = "", value = ""},
-- },
-- ["default_value"] = "skaven_dummy_slave",
-- },
{ -- Selected list of available spawn units
["setting_id"] = "cs_unit_list",
["type"] = "dropdown",
["tooltip"] = "cs_unit_list_tooltip",
["options"] = {
{text = "cs_unit_list_header_regular", value = "regular_units"},
{text = "cs_unit_list_header_dummy", value = "dummy_units"},
{text = "cs_unit_list_header_misc", value = "misc_units"},
{text = "cs_unit_list_header_special", value = "special_units"},
{text = "cs_unit_list_header_boss", value = "boss_units"},
{text = "cs_unit_list_header_all", value = "all_units"},
},
["default_value"] = "regular_units", -- Default first option is enabled. In this case mod.regular_units
},
{ -- Keybind for spawning units
["setting_id"] = "cs_spawn_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_spawn_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_spawn_unit"
},
{ -- Keybind to move to next unit in list
["setting_id"] = "cs_next_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_next_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_next_unit"
},
{ -- Keybind to move to previous unit in list
["setting_id"] = "cs_prev_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_prev_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_previous_unit"
},
{ -- Keybind to destroy all spawned units
["setting_id"] = "cs_destroy_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_destroy_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_despawn_units"
},
-- { -- First slot of saved units
-- ["setting_id"] = "cs_saved_unit_one",
-- ["type"] = "dropdown",
-- ["text"] = "Saved Unit One",
-- ["tooltip"] = "This unit can be spawned with the associated keybind.",
-- ["options"] = {
-- {text = "", value = ""},
-- },
-- ["default_value"] = "",
-- },
{ -- Keybind to spawn first saved unit
["setting_id"] = "cs_spawn_saved_unit_one_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_spawn_saved_unit_one_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_spawn_unit_one"
},
-- { -- Second slot of saved units
-- ["setting_id"] = "cs_saved_unit_two",
-- ["type"] = "dropdown",
-- ["text"] = "Saved Unit Two",
-- ["tooltip"] = "This unit can be spawned with the associated keybind.",
-- ["options"] = {
-- {text = "", value = ""},
-- },
-- ["default_value"] = "",
-- },
{ -- Keybind to spawn second saved unit
["setting_id"] = "cs_spawn_saved_unit_two_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_spawn_saved_unit_two_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_spawn_unit_two"
},
-- { -- Third slot of saved units
-- ["setting_id"] = "cs_saved_unit_three",
-- ["type"] = "dropdown",
-- ["text"] = "Saved Unit Three",
-- ["tooltip"] = "This unit can be spawned with the associated keybind.",
-- ["options"] = {
-- {text = "", value = ""},
-- },
-- ["default_value"] = "",
-- },
{ -- Keybind to spawn third saved unit
["setting_id"] = "cs_spawn_saved_unit_three_keybind",
["type"] = "keybind",
["keybind_trigger"] = "pressed",
["keybind_type"] = "function_call",
["tooltip"] = "cs_spawn_saved_unit_three_keybind_tooltip",
["default_value"] = {},
["function_name"] = "handle_spawn_unit_three"
},
{ -- Toggle AI in missions
["setting_id"] = "cs_enable_mission_ai",
["type"] = "checkbox",
["tooltip"] = "cs_enable_mission_ai_tooltip",
["default_value"] = true -- Default first option is enabled. In this case true
},
{ -- Toggle AI in Keep
["setting_id"] = "cs_enable_keep_ai",
["type"] = "checkbox",
["tooltip"] = "cs_enable_keep_ai_tooltip",
["default_value"] = false -- Default first option is enabled. In this case true
},
{ -- Grudge-Marked spawning types
["setting_id"] = "cs_enable_grudge_marked",
["type"] = "dropdown",
["tooltip"] = "cs_enable_grudge_marked_tooltip",
["options"] = {
{text = "cs_enable_grudge_marked_header_disabled", value = false},
{text = "cs_enable_grudge_marked_header_random", value = "RANDOM", show_widgets = {1}},
{text = "cs_enable_grudge_marked_header_manual", value = "MANUAL", show_widgets = {2,3,4,5,6,7,8,9,10,11}}
},
["default_value"] = false, -- Default first option is enabled. In this case false
["sub_widgets"] =
{
{
["setting_id"] = "cs_grudge_marked_random_modifier_count",
["type"] = "numeric",
["tooltip"] = "cs_grudge_marked_random_modifier_count_tooltip",
["default_value"] = 1,
["range"] = { 0, 10 },
["decimals_number"] = 0
},
{ -- Enable grudge-marked setting: warping
["setting_id"] = "cs_enable_grudge_marked_warping",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_warping_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: intangible
["setting_id"] = "cs_enable_grudge_marked_intangible",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_intangible_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: unstaggerable
["setting_id"] = "cs_enable_grudge_marked_unstaggerable",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_unstaggerable_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: raging
["setting_id"] = "cs_enable_grudge_marked_raging",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_raging_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: vampiric
["setting_id"] = "cs_enable_grudge_marked_vampiric",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_vampiric_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: ranged_immune
["setting_id"] = "cs_enable_grudge_marked_ranged_immune",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_ranged_immune_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: periodic_shield
["setting_id"] = "cs_enable_grudge_marked_periodic_shield",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_periodic_shield_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: crippling
["setting_id"] = "cs_enable_grudge_marked_crippling",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_crippling_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: crushing
["setting_id"] = "cs_enable_grudge_marked_crushing",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_crushing_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
},
{ -- Enable grudge-marked setting: regenerating
["setting_id"] = "cs_enable_grudge_marked_regenerating",
["type"] = "checkbox",
["tooltip"] = "cs_enable_grudge_marked_regenerating_tooltip",
["default_value"] = false -- Default first option is enabled. In this case false
}
}
}
}
}
return mod_data
|
-- add package path for the example
package.path = ";../src/?.lua;"..package.path
-- lib
local Luaoop = require("Luaoop")
class = Luaoop.class
-- DEF OBJECT
Object = class("Object")
Object.color = {
BLACK = 0,
BLUE = 1,
YELLOW = 2,
RED = 3,
GREEN = 4,
WHITE = 5
}
function Object:__construct()
print("new object")
end
function Object:classname()
return class.name(self)
end
-- DEF BOTTLE
Bottle = class("Bottle", Object)
function Bottle:__construct(max)
Object.__construct(self)
self.max = max
self.amount = 0
end
function Bottle:fill()
self.amount = self.max
end
function Bottle:drink()
if self.amount >= 2 then
self.amount = self.amount-2
end
end
function Bottle:__mul_number(rhs)
return self.amount*rhs
end
function Bottle:__mul_Bottle(rhs)
local b = Bottle(self.max*rhs.max)
b.amount = self.amount*rhs.amount
return b
end
function Bottle:__add_Bottle(rhs)
local b = Bottle(self.max+rhs.max)
b.amount = self.amount+rhs.amount
return b
end
function Bottle:__unm()
local b = Bottle(-self.max)
b.amount = -self.amount
return b
end
function Bottle:__tostring()
return self.amount.."/"..self.max
end
function Bottle:__eq_Bottle(rhs)
return self.amount == rhs.amount
end
-- USE
local bottle = Bottle(10)
print(bottle)
bottle:fill()
print(bottle)
bottle:drink()
print(bottle)
bottle:drink()
print(bottle)
if class.instanceof(bottle, "Object") then print("is object") end
if class.instanceof(bottle, "Bottle") then print("is bottle") end
if not class.instanceof(bottle, "Glass") then print("is not glass") end
print(class.type(bottle))
print(class.type(Bottle))
print(class.type(Object))
local types = class.types(bottle)
for k,v in pairs(types) do
print("bottle has type "..k)
end
print(bottle*2)
print(2*bottle)
print("bottle id: "..class.instanceid(bottle))
-- multiply a bottle by the same bottle
local b = bottle*bottle
print(b)
print("b id: "..class.instanceid(b))
-- sub a bottle by itself (0/0 bottle)
b = bottle-bottle
print(b)
print("b id: "..class.instanceid(b))
-- get bottle definition
local cbottle = class.definition("Bottle")
print(cbottle(42)) -- create a bottle
|
local lm = require "luamake"
local fs = require "bee.filesystem"
local Platform_renderers = {
windows = "direct3d11",
ios = "metal",
macos = "metal",
linux = "vulkan",
android = "vulkan",
}
local stage_types = {
fs = "fragment",
vs = "vertex",
cs = "compute",
}
local shader_options = {
windows = {
vs = "vs_5_0",
fs = "ps_5_0",
cs = "cs_5_0",
},
ios = {
vs = "metal",
fs = "metal",
cs = "metal",
},
macos = {
vs = "metal",
fs = "metal",
cs = "metal",
},
linux = {
vs = "spirv",
fs = "spirv",
cs = "spriv",
},
android = {
vs = "spirv",
fs = "spirv",
cs = "spriv",
},
}
local function generate_command(shaderc, cfg)
local stagename = cfg.stage
local commands = {
shaderc,
"-f", "$in", "-o", "$out",
"--platform", lm.os,
"--type", stage_types[stagename],
"-p", shader_options[lm.os][stagename],
input = cfg.input,
output = cfg.output,
}
if cfg.varying_path then
commands[#commands+1] = "--varyingdef"
commands[#commands+1] = cfg.varying_path
end
if cfg.includes then
for _, p in ipairs(cfg.includes) do
if not fs.exists(p) then
error(string.format("include path : %s, but not exist!", p))
end
assert(p:is_absolute(), p:string())
commands[#commands+1] = "-i"
commands[#commands+1] = p:string()
end
end
if cfg.defines then
local t = {}
for _, m in ipairs(cfg.defines) do
t[#t+1] = m
end
if #t > 0 then
local defines = table.concat(t, ';')
commands[#commands+1] = "--define"
commands[#commands+1] = defines
end
end
local level = cfg.optimizelevel
if not level then
if cfg.renderer:match("direct3d") then
level = cfg.stage == "cs" and 1 or 3
end
end
if cfg.debug then
commands[#commands+1] = "--debug"
else
if level then
commands[#commands+1] = "-O"
commands[#commands+1] = tostring(level)
end
end
return commands
end
return {
gen_cmd = generate_command
}
|
Config = {}
Config.Webhook = false
Config.WebhookLink = 'https://discord.com/api/webhooks/'
Config.Strings= {
['playerleft'] = 'Player left',
['sessiontime'] = 'Session time',
['totaltime'] = 'Total time',
['welcome1st'] = 'Welcome To Secret City Battleground',
['welcome'] = 'Welcome back!',
['ptotaltime'] = 'Total time spent on server: ',
['loggedin'] = 'You have logged in ~y~%s~s~ times',
}
|
-- fake "osm2pgsql" table for test, usually created by the main C++ program
osm2pgsql = {}
-- load the init.lua script that is normally run by the main C++ program
package.path = '../src/?.lua'
require('init')
print("Running Lua tests...")
local o = osm2pgsql
-- ---------------------------------------------------------------------------
-- has_prefix()
assert(o.has_prefix('addr:city', 'addr:'))
assert(not o.has_prefix('addr:city', 'foo'))
assert(o.has_prefix('addr:city', ''))
assert(not o.has_prefix('name', 'addr:'))
assert(o.has_prefix('a', 'a'))
assert(not o.has_prefix('a', 'ab'))
assert(o.has_prefix(nil, 'a') == nil)
-- has_suffix()
assert(o.has_suffix('tiger:source', ':source'))
assert(not o.has_suffix('tiger:source', 'foo'))
assert(o.has_suffix('tiger:source', ''))
assert(not o.has_suffix('name', ':source'))
assert(o.has_suffix('a', 'a'))
assert(not o.has_suffix('a', 'ba'))
assert(o.has_suffix(nil, 'a') == nil)
-- ---------------------------------------------------------------------------
-- clamp
do
assert(o.clamp(1, 2, 3) == 2)
assert(o.clamp(3, 1, 4) == 3)
assert(o.clamp(3, -1, 1) == 1)
assert(o.clamp(-3, -1, 1) == -1)
assert(o.clamp(2.718, 0, 3.141) == 2.718)
assert(o.clamp(nil, -1, 1) == nil)
end
-- make_check_values_func without default
do
local if_known_highway_value = o.make_check_values_func{
'motorway', 'trunk', 'primary', 'secondary', 'tertiary'
}
assert(if_known_highway_value('motorway') == 'motorway')
assert(if_known_highway_value('primary') == 'primary')
assert(if_known_highway_value('residential') == nil)
end
-- make_check_values_func with default
do
local highway_value = o.make_check_values_func({
'motorway', 'trunk', 'primary', 'secondary', 'tertiary'
}, 'road')
assert(highway_value('motorway') == 'motorway')
assert(highway_value('primary') == 'primary')
assert(highway_value('residential') == 'road')
end
-- make_clean_tags_func
do
local clean_tags = o.make_clean_tags_func{'source',
'source:*',
'*:source',
'note'}
local tags = {
source = 'foo',
highway = 'residential',
['source:url'] = 'bar',
['tiger:source'] = 'value',
['source:vs:source'] = 'removeme',
['with:source:infix'] = 'keepme',
NOTE = 'x'
}
assert(clean_tags(tags) == false)
assert(tags.highway == 'residential')
assert(tags.NOTE == 'x')
assert(tags.source == nil)
assert(tags['source:url'] == nil)
assert(tags['tiger:source'] == nil)
assert(tags['source:vs:source'] == nil)
assert(tags['with:source:infix'] == 'keepme')
num = 0
for k, v in pairs(tags) do
num = num + 1
end
assert(num == 3)
end
-- trim
assert(osm2pgsql.trim('') == '')
assert(osm2pgsql.trim(' ') == '')
assert(osm2pgsql.trim(' ') == '')
assert(osm2pgsql.trim('a') == 'a')
assert(osm2pgsql.trim(' a') == 'a')
assert(osm2pgsql.trim('a ') == 'a')
assert(osm2pgsql.trim(' a ') == 'a')
assert(osm2pgsql.trim(' a ') == 'a')
assert(osm2pgsql.trim(' ab cd ') == 'ab cd')
assert(osm2pgsql.trim(' \t\r\n\f\va\000b \r\t\n\f\v') == 'a\000b')
assert(osm2pgsql.trim(nil) == nil)
-- split_unit
v, u = o.split_unit('20m', '')
assert(v == 20 and u == 'm')
v, u = o.split_unit('20 m')
assert(v == 20 and u == 'm')
v, u = o.split_unit('20ft', '')
assert(v == 20 and u == 'ft')
v, u = o.split_unit('23.4 ft', '')
assert(v == 23.4 and u == 'ft')
v, u = o.split_unit('20 ft', 'm')
assert(v == 20 and u == 'ft')
v, u = o.split_unit('20km', 'm')
assert(v == 20 and u == 'km')
v, u = o.split_unit('20')
assert(v == 20 and u == nil)
v, u = o.split_unit('20', 'm')
assert(v == 20 and u == 'm')
v, u = o.split_unit('0', 'm')
assert(v == 0 and u == 'm')
v, u = o.split_unit('-20000', 'leagues')
assert(v == -20000 and u == 'leagues')
v, u = o.split_unit('20xx20', '')
assert(v == nil)
v, u = o.split_unit('20-20', '')
assert(v == nil)
v, u = o.split_unit('20xx20', 'foo')
assert(v == nil)
v, u = o.split_unit('abc', 'def')
assert(v == nil)
v, u = o.split_unit(nil)
assert(v == nil and u == nil)
v, u = o.split_unit(nil, 'foo')
assert(v == nil and u == nil)
-- split_string
r = o.split_string('ab c;d;e f;ghi')
assert(#r == 4)
assert(r[1] == 'ab c')
assert(r[2] == 'd')
assert(r[3] == 'e f')
assert(r[4] == 'ghi')
r = o.split_string('ab c;d ; e f; ghi')
assert(#r == 4)
assert(r[1] == 'ab c')
assert(r[2] == 'd')
assert(r[3] == 'e f')
assert(r[4] == 'ghi')
r = o.split_string('ab c ')
assert(#r == 1)
assert(r[1] == 'ab c')
r = o.split_string('')
assert(#r == 0)
r = o.split_string('ab c;d , e f, ghi', ',')
assert(#r == 3)
assert(r[1] == 'ab c;d')
assert(r[2] == 'e f')
assert(r[3] == 'ghi')
r = o.split_string(nil)
assert(#r == 0)
-- ---------------------------------------------------------------------------
print("All tests successful")
|
local read, write = io.read, io.write
local num, nl = '*n', '\n'
while true do
local a = read(num)
if a == 42 then return end
write(a, nl)
end
|
data:extend({
{
type = "recipe",
name = "advanced-combinator",
enabled = false,
energy_required = 20,
ingredients = {
{ "constant-combinator", 24 },
{ "arithmetic-combinator", 48 },
{ "green-wire", 100 },
{ "red-wire", 100 }
},
result = "advanced-combinator"
}
})
|
/*
Addon by Voikanaa
*/
player_manager.AddValidModel( "Snoop Dogg", "models/player/voikanaa/snoop_dogg.mdl" );
player_manager.AddValidHands( "Snoop Dogg", "models/player/voikanaa/snoop_dogg_arms.mdl", 0, "00000000" )
list.Set( "PlayerOptionsModel", "Snoop Dogg", "models/player/voikanaa/snoop_dogg.mdl" );
|
---------------------------
-- Default awesome theme --
---------------------------
local theme_assets = require "beautiful.theme_assets"
local xresources = require "beautiful.xresources"
local rnotification = require "ruled.notification"
local dpi = xresources.apply_dpi
local theme_path = require("gears").filesystem.get_configuration_dir() .. "themes/forest/"
local themes_path = require("gears").filesystem.get_themes_dir()
local gcolor = require("gears").color
local theme = {}
theme.font_name = "JetBrainsMono Nerd Font"
theme.font = theme.font_name .. " 8"
theme.none = "#00000000"
theme.bg_normal = "#1d2021"
theme.bg_focus = "#282828"
theme.bg_dark = "#161819"
theme.bg_urgent = "#1d2021"
theme.bg_minimize = "#1d2021"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#d4be98"
theme.fg_focus = "#d4be98"
theme.fg_urgent = "#d4be98"
theme.fg_minimize = "#d4be98"
theme.fg_dark = "#928374"
theme.fg_bat = "#a9b665"
theme.fg_time = "#e78a4e"
theme.useless_gap = dpi(10)
theme.border_width = dpi(0)
theme.border_color_normal = "#282828"
theme.border_color_active = "#89b482"
theme.border_color_marked = "#c678dd"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- taglist_[bg|fg]_[focus|urgent|occupied|empty|volatile]
-- tasklist_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- prompt_[fg|bg|fg_cursor|bg_cursor|font]
-- hotkeys_[bg|fg|border_width|border_color|shape|opacity|modifiers_fg|label_bg|label_fg|group_margin|font|description_font]
-- Example:
theme.taglist_bg_focus = "#89b482"
theme.taglist_fg_focus = "#1d2021"
theme.taglist_fg_empty = "#928374"
-- Generate taglist squares:
local taglist_square_size = dpi(0)
theme.taglist_squares_sel = theme_assets.taglist_squares_sel(taglist_square_size, theme.bg_focus)
theme.taglist_squares_unsel = theme_assets.taglist_squares_unsel(taglist_square_size, theme.fg_normal)
-- control center
theme.control_center_button_bg = "#89b482"
theme.control_center_button_bg_off = "#3f3f3f"
theme.control_center_mem_used = "#ea6962"
theme.control_center_cpu_active = "#d8a657"
theme.control_center_vol_slider_active = "#a9b665"
theme.control_center_bri_slider_active = "#d3869b"
-- Variables set for theming notifications:
-- notification_font
-- notification_[bg|fg]
-- notification_[width|height|margin]
-- notification_[border_color|border_width|shape|opacity]
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_height = dpi(20)
theme.menu_width = dpi(150)
theme.titlebar_close_button_normal = theme_path .. "close_normal.svg"
theme.wallpaper = theme_path .. "background.png"
theme.layout_floating = gcolor.recolor_image(themes_path .. "default/layouts/floatingw.png", theme.fg_normal)
theme.layout_tile = gcolor.recolor_image(themes_path .. "default/layouts/tile.png", theme.fg_normal)
theme.layout_spiral = gcolor.recolor_image(themes_path .. "default/layouts/spiral.png", theme.fg_normal)
theme.task_preview_widget_border_radius = 5
theme.task_preview_widget_bg = theme.bg_dark
theme.task_preview_widget_border_color = theme.fg_normal
theme.task_preview_widget_border_width = 0
theme.task_preview_widget_margin = 10
theme.tag_preview_widget_border_radius = 5
theme.tag_preview_client_border_radius = 5
theme.tag_preview_client_opacity = 0.5
theme.tag_preview_client_bg = theme.bg_focus
theme.tag_preview_client_border_color = theme.border_color_normal
theme.tag_preview_client_border_width = 3
theme.tag_preview_widget_bg = theme.bg_dark
theme.tag_preview_widget_border_color = theme.border_color_normal
theme.tag_preview_widget_border_width = 0
theme.tag_preview_widget_margin = 10
-- For tabbed only
theme.tabbed_spawn_in_tab = false
-- For tabbar in general
theme.tabbar_ontop = false
theme.tabbar_radius = 5
theme.tabbar_style = "default"
theme.tabbar_font = theme.font
theme.tabbar_size = 40
theme.tabbar_position = "top"
theme.tabbar_bg_normal = theme.bg_normal
theme.tabbar_fg_normal = theme.fg_normal
theme.tabbar_bg_focus = theme.bg_focus
theme.tabbar_fg_focus = theme.fg_focus
theme.tabbar_disable = false
theme.tabbar_color_close = "#f9929b"
theme.tabbar_color_min = "#fbdf90"
theme.tabbar_color_float = "#ccaced"
theme.window_switcher_widget_bg = theme.bg_dark
theme.window_switcher_widget_border_width = 0
theme.window_switcher_widget_border_radius = 5
theme.window_switcher_clients_spacing = 20
theme.window_switcher_client_icon_horizontal_spacing = 5
theme.window_switcher_client_width = 150
theme.window_switcher_client_height = 250
theme.window_switcher_client_margins = 10
theme.window_switcher_thumbnail_margins = 10
theme.window_switcher_name_margins = 10
theme.window_switcher_name_forced_width = 200
theme.window_switcher_name_normal_color = theme.fg_normal
theme.window_switcher_name_focus_color = "#89b482"
theme.window_switcher_icon_width = 40
-- Set different colors for urgent notifications.
rnotification.connect_signal("request::rules", function()
rnotification.append_rule {
rule = { urgency = "critical" },
properties = { bg = "#ff0000", fg = "#ffffff" },
}
end)
return theme
|
module 'mock'
--------------------------------------------------------------------
local storyNodeTypeRegistry = {}
function registerStoryNodeType( tag, clas )
storyNodeTypeRegistry[ tag ] = clas
end
--------------------------------------------------------------------
CLASS: StoryGraph ()
:MODEL{}
function StoryGraph:__init()
self:initRoot()
end
function StoryGraph:initRoot()
self.rootGroup = StoryScopedGroup()
self.rootGroup.id = '__root'
self.rootGroup.text = '__root'
self.rootGroup.actorId = false
end
function StoryGraph:_loadStoryNode( nodeData, group, scope, nodeDict )
local ntype = nodeData[ 'type' ]
local node
local isGroup = false
if ntype == 'REF' then
node = StoryScopedGroup()
node.scope = scope
scope = node
isGroup = true
elseif ntype == 'GROUP' then
node = StoryNodeGroup()
node.scope = scope
isGroup = true
else
local nodeClas = storyNodeTypeRegistry[ ntype ]
if nodeClas then
node = nodeClas()
else
_warn( 'unknown story node type', ntype, nodeData['fullId'] )
node = StoryNode()
end
node.scope = scope
end
node.type = ntype
node.id = nodeData[ 'fullId' ] or 'unknown'
node.text = nodeData[ 'text' ]
-- node.groupId = nodeData [ 'group' ]
if isGroup then
for _, childData in ipairs( nodeData[ 'children' ] ) do
self:_loadStoryNode( childData, node, scope, nodeDict )
end
end
group:addChild( node )
nodeDict[ node.id ] = node --for edge reference
node.graph = self
node.data = nodeData
return node
end
function StoryGraph:load( data )
self:initRoot()
local nodeDict = {}
local root = self.rootGroup
--nodes
for _, nodeData in ipairs( data[ 'rootNodes' ] ) do
self:_loadStoryNode( nodeData, root, root, nodeDict )
end
--edges/routes
for _, edgeData in ipairs( data[ 'edges' ] ) do
if edgeData['type'] == 'COMMENT' then
--PASS
else
local srcId = edgeData[ 'src' ]
local dstId = edgeData[ 'dst' ]
local srcNode = nodeDict[ srcId ]
local dstNode = nodeDict[ dstId ]
if srcNode:isDecorator() then
srcNode:apply( dstNode )
else
local route = StoryRoute( srcNode, dstNode )
route.type = edgeData[ 'type' ]
route.text = edgeData[ 'text' ]
route.graph = self
route:onLoad( edgeData )
end
end
end
root.nodeData = {}
root:loadNodeData()
end
function StoryGraph:getRoot()
return self.rootGroup
end
--------------------------------------------------------------------
CLASS: StoryNode ()
:MODEL{}
function StoryNode:__init()
self.id = false
self.text = ''
self.routesOut = {}
self.routesIn = {}
self.decorators = {}
self.type = 'node'
self.scope = false
self.group = false
self.actorId = false
end
function StoryNode:getActorId()
if self.actorId then return self.actorId end
if self.group then return self.group:getActorId() end
return false
end
function StoryNode:setActorId( id )
self.actorId = id
end
function StoryNode:getScope()
return self.scope
end
function StoryNode:getId()
return self.id
end
function StoryNode:getText()
return self.text
end
function StoryNode:getType()
return self.type
end
function StoryNode:isDecorator()
return false
end
function StoryNode:toString()
return '[' .. self.id .. '<'..self:getType()..'>]\t'.. self.text
end
function StoryNode:calcNextNode( state, prevNodeResult )
local nextNodes = {}
for i, routeOut in ipairs( self.routesOut ) do
local dst = routeOut.nodeDst
if routeOut.type == 'NOT' then
if not prevNodeResult then
table.insert( nextNodes, dst )
end
else
if prevNodeResult ~= false then
table.insert( nextNodes, dst )
end
end
end
return nextNodes
end
function StoryNode:onLoad( nodeData )
end
function StoryNode:onStateEnter( state, prevNode, prevResult )
-- print( '-> ', self:toString() )
end
function StoryNode:onStateUpdate( state )
return 'ok'
end
function StoryNode:onStateExit( state )
end
function StoryNode:loadNodeData()
self:onLoad( self.nodeData )
end
--------------------------------------------------------------------
CLASS: StoryNodeGroup ( StoryNode )
:MODEL{}
function StoryNodeGroup:__init()
self.children = {}
self.startNodes = {}
self.inputNodes = {}
end
function StoryNodeGroup:addChild( node )
node.group = self
table.insert( self.children, node )
end
function StoryNodeGroup:findChildrenByType( typeId )
local found = {}
for i, child in ipairs( self.children ) do
if child:getType() == typeId then
table.insert( found, child )
end
end
return found
end
function StoryNodeGroup:onStateEnter( state, prevNode, prevResult )
--start all START node
--add INPUT node into trigger pool
for startNode in pairs( self.startNodes ) do
state:enterStoryNode( startNode, nil, nil )
end
for inputNode in pairs( self.inputNodes ) do
state:addInputTrigger( inputNode )
end
end
function StoryNodeGroup:onLoad( nodeData )
local startNodes = {}
local inputNodes = {}
for _, child in ipairs( self.children ) do
local t = child:getType()
if t == 'START' then
startNodes[ child ] = true
elseif t == 'INPUT' then
inputNodes[ child ] = true
end
end
self.startNodes = startNodes
self.inputNodes = inputNodes
end
function StoryNodeGroup:onStateUpdate( state )
return 'running'
end
function StoryNodeGroup:loadNodeData()
for i, child in ipairs( self.children ) do
child:loadNodeData()
end
self:onLoad( self.nodeData )
end
--------------------------------------------------------------------
CLASS: StoryScopedGroup ( StoryNodeGroup )
:MODEL{}
function StoryScopedGroup:__init()
end
function StoryScopedGroup:getType()
return 'ScopedGroup'
end
---------------------------------------------------------------------
CLASS: StoryDecoratorNode ( StoryNode )
:MODEL{}
function StoryDecoratorNode:isDecorator()
return true
end
function StoryDecoratorNode:apply( dstNode )
table.insert( dstNode.decorators , self )
self:onApply( dstNode )
end
function StoryDecoratorNode:onApply( dstNode )
end
--------------------------------------------------------------------
CLASS: StoryRoute ()
:MODEL{}
function StoryRoute:__init( nodeSrc, nodeDst )
self.text = ''
self.nodeSrc = nodeSrc
self.nodeDst = nodeDst
self.type = 'NORMAL'
table.insert( nodeSrc.routesOut, self )
table.insert( nodeDst.routesIn, self )
end
function StoryRoute:getType()
return self.type
end
function StoryRoute:onLoad( data )
self.valueNumber = tonumber( self.text ) or false
end
--------------------------------------------------------------------
--ASSET Loader
--------------------------------------------------------------------
local function StoryGraphLoader( node )
local path = node:getObjectFile('def')
local data = loadJSONFile( path )
local graph = StoryGraph()
graph:load( data )
return graph
end
registerAssetLoader ( 'story_graph', StoryGraphLoader )
|
-- Super Monkey Ball (PAL v1.0)
local core = require("games.core")
local game = core.newGame()
local addr = 0x80225E00
local offset = 0x3C
local controllers = {
[1] = addr + offset * 0,
[2] = addr + offset * 1,
[3] = addr + offset * 2,
[4] = addr + offset * 3,
}
local controller_struct = {
[0x0] = { type = "short", name = "controller.%d.buttons.pressed" },
[0x2] = { type = "sbyte", name = "controller.%d.joystick.x" },
[0x3] = { type = "sbyte", name = "controller.%d.joystick.y" },
[0x4] = { type = "sbyte", name = "controller.%d.cstick.x" },
[0x5] = { type = "sbyte", name = "controller.%d.cstick.y" },
[0x6] = { type = "byte", name = "controller.%d.analog.l" },
[0x7] = { type = "byte", name = "controller.%d.analog.r" },
[0xA] = { type = "byte", name = "controller.%d.plugged" },
}
for port, address in ipairs(controllers) do
for offset, info in pairs(controller_struct) do
game.memorymap[address + offset] = {
type = info.type,
debug = info.debug,
name = info.name:format(port),
}
end
end
game.translateJoyStick = core.translateJoyStick
game.translateTriggers = core.translateTriggers
return game
|
Tuple = {
x = 0,
y = 0,
z = 0,
w = 0,
-- https://mathinsight.org/vectors_cartesian_coordinates_2d_3d
magnitude = function (self)
return math.sqrt(self.x^2 + self.y^2 + self.z^2 + self.w^2)
end,
normalize = function (self)
local mag = self:magnitude()
local a = Tuple:new(self.x / mag, self.y / mag, self.z / mag, self.w / mag)
return a
end,
dot = function (self, b)
-- The smaller the dot product, the larger the angle between the vectors
return self.x * b.x +
self.y * b.y +
self.z * b.z +
self.w * b.w
end,
__add = function (a, b)
return Tuple:new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w)
end,
__sub = function (a, b)
local x = a.x - b.x
local y = a.y - b.y
local z = a.z - b.z
local w = a.w - b.w
if w == 0 then
return Vector:new(x, y, z)
elseif w == 1 then
return Point:new(x, y, z)
else
return Tuple:new(x, y, z, w)
end
end,
__unm = function (a)
return Tuple:new(0, 0, 0, 0) - a
end,
__mul = function (a, b)
return Tuple:new(a.x * b, a.y * b, a.z * b, a.w * b)
end,
__div = function (a, b)
return Tuple:new(a.x / b, a.y / b, a.z / b, a.w / b)
end,
__eq = function (a, b)
local epsilon = 0.00001
return math.abs(a.x - b.x) < epsilon
and math.abs(a.y - b.y) < epsilon
and math.abs(a.z - b.z) < epsilon
and math.abs(a.w - b.w) < epsilon
end,
__tostring = function (self)
return "{" .. self.x .. ", " .. self.y .. ", " .. self.z .. ", " .. self.w .."}"
end
}
function Tuple:new(x, y, z, w)
local t = {
x = x or 0,
y = y or 0,
z = z or 0,
w = w or 0
}
setmetatable(t, self)
self.__index = self
return t
end
function Tuple:type()
if self.w == 0 then
return "vector"
elseif self.w == 1 then
return "point"
else
return "tuple"
end
end
Point = {}
function Point:new(x, y, z)
local t = {
x = x or 0,
y = y or 0,
z = z or 0,
w = 1
}
setmetatable(t, Tuple)
self.__index = self
return t
end
Vector = {}
function Vector:new(x, y, z)
local t = {
x = x or 0,
y = y or 0,
z = z or 0,
w = 0,
cross = function (self, b)
-- Returns a new vector that is perpendicular to both input vectors
return Vector:new(
self.y * b.z - self.z * b.y,
self.z * b.x - self.x * b.z,
self.x * b.y - self.y * b.x
)
end
}
setmetatable(t, Tuple)
self.__index = self
return t
end
|
if blight then
client = require 'client.blight.blight-adapter'
require 'client.blight.blight-specific'
else
local mg_lua_dir = os.getenv('MG_LUA_DIR')
package.path = package.path..';'..mg_lua_dir..'/?.lua'
local mg_custom_dir = os.getenv('MG_LUA_CUSTOM_DIR')
if mg_custom_dir ~= nil then
package.path = package.path..';'..mg_custom_dir..'/?.lua'
end
client = require 'client.tf.tf-adapter'
require 'client.tf.tf-specific'
end
local base = require 'base'
require 'battle'
require 'damage'
require 'gmcp-data'
require 'guild.common'
require 'inventory'
require 'itemdb'
require 'pub'
require 'reduce'
require 'report'
require 'room'
require 'timer'
require 'utils.tools'
require 'utils-mg'
require 'ways'
require 'ways-extensions'
local allGuilds = {
'bierschuettler',
'chaos',
'common',
'dunkelelfen',
'kaempfer',
'karate',
'katzenkrieger',
'klerus',
'tanjian',
'urukhai',
'zauberer'
}
local guildClasses = {}
for _,guild in ipairs(allGuilds) do
guildClasses[guild] = require('guild.'..guild)
end
local logger = client.createLogger('base')
base.registerEventHandler(
'base.char.init.done',
function()
local guildName = base.charGuild()
local guildClass = guildClasses[guildName]
if guildClass ~= nil then
local guild = guildClass()
guild.enable()
base.setGuild(guild)
logger.info('Code zur Gilde \''..(guildName or '')..'\' aktiviert')
end
end
)
|
local Util = {}
-- 清空子节点
Util.removeAllChild = function(gameObject)
local len = gameObject.transform.childCount
local obj = nil
for i=0,len-1 do
obj = gameObject.transform:GetChild(i).gameObject
Object.Destroy(obj)
end
end
-- 切割字符串
Util.split = function(s, p)
local rt= {}
string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
return rt
end
-- 用标签获取组件参数
Util.GetComponentWithFlag = function(obj,flag,otype)
if obj == nil then return end
local links = obj:GetComponents(Link)
for v in Slua.iter(links) do
if v.flag == flag then
if otype then
return v.target:GetComponent(otype)
end
return v.target
end
end
return nil
end
Util.FindComponentFlag = function(obj,str)
local links = obj:GetComponents(Link)
for v in Slua.iter(links) do
local a,b = string.find(v.flag,str)
if a ~=nil and b ~=nil then
return string.sub(v.flag,b+1)
end
end
return nil
end
Util.AnimatorIsPlaying = function(animator,name)
local ret = false
if name then
local stateInfo = animator:GetCurrentAnimatorStateInfo(0);
if stateInfo:IsName("Base Layer.".. name) and stateInfo.normalizedTime < 1 then
ret = true
end
end
return ret
end
LDeclare("Util", Util)
return Util
|
return 'Hello World'
|
data:extend({
{type = "bool-setting", name = "diplomacy_tech_tanks_count_switcher", setting_type = "startup", default_value = true},
{type = "bool-setting", name = "diplomacy_hp_rocket_silo_switcher", setting_type = "startup", default_value = true},
{type = "bool-setting", name = "diplomacy_entity_not_on_map", setting_type = "startup", default_value = false},
{type = "bool-setting", name = "diplomacy_visible_all_teams", setting_type = "runtime-global", default_value = false},
{type = "bool-setting", name = "diplomacy_allow_mine_entity", setting_type = "runtime-global", default_value = false},
{
type = "bool-setting",
name = "disable_diplomacy_on_entity_died",
setting_type = "runtime-global",
default_value = false
},
{
type = "int-setting",
name = "diplomacy_hp_rocket_silo",
setting_type = "startup",
default_value = 50000,
minimum_value = 1,
maximum_value = 10000000000
},
{
type = "int-setting",
name = "diplomacy_tech_tanks_count",
setting_type = "startup",
default_value = 1000,
minimum_value = 1,
maximum_value = 10000000000
}, {
type = "bool-setting",
name = "diplomacy_tech_power_armor_2_count_switcher",
setting_type = "startup",
default_value = true
}, {
type = "int-setting",
name = "diplomacy_tech_power_armor_2_count",
setting_type = "startup",
default_value = 1000,
minimum_value = 1,
maximum_value = 10000000000
}, {
type = "bool-setting",
name = "diplomacy_tech_uranium_ammo_count_switcher",
setting_type = "startup",
default_value = true
}, {
type = "int-setting",
name = "diplomacy_tech_uranium_ammo_count",
setting_type = "startup",
default_value = 1800,
minimum_value = 1,
maximum_value = 10000000000
}, {
type = "int-setting",
name = "diplomacy_HP_forbidden_entity_on_killed",
setting_type = "runtime-global",
default_value = 300,
minimum_value = 1,
maximum_value = 100000000000
}, {
type = "int-setting",
name = "diplomacy_HP_forbidden_entity_on_mined",
setting_type = "runtime-global",
default_value = 300,
minimum_value = 0,
maximum_value = 100000000000
}, {
type = "string-setting",
name = "who_decides_diplomacy",
setting_type = "runtime-global",
default_value = "all_players",
allowed_values = {"all_players", "team_leader"}
}
})
|
return {'awara','awari','awacs','awater','awad','awaras','awaris'}
|
malkloc = Creature:new {
objectName = "@mob/creature_names:malkloc",
socialGroup = "malkloc",
faction = "",
level = 22,
chanceHit = 0.33,
damageMin = 190,
damageMax = 200,
baseXp = 2006,
baseHAM = 5400,
baseHAMmax = 6600,
armor = 0,
resists = {115,120,5,-1,-1,-1,5,145,-1},
meatType = "meat_herbivore",
meatAmount = 1000,
hideType = "hide_leathery",
hideAmount = 1000,
boneType = "bone_mammal",
boneAmount = 1000,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/malkloc_hue.iff"},
hues = { 8, 9, 10, 11, 12, 13, 14, 15 },
controlDeviceTemplate = "object/intangible/pet/malkloc_hue.iff",
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"intimidationattack",""}
}
}
CreatureTemplates:addCreatureTemplate(malkloc, "malkloc")
|
local KEY = require 'script.jzslm.key'
local redis = require 'script.redis'
local util = require 'script.utility'
local log = require 'script.log'
local CHEAT_TIME = 14 * 60
local CHEAT_LEVEL = 7
local CHEAT_MAX = 10
local m = {}
function m.checkTime(level, time)
if level < CHEAT_LEVEL then
return false
end
return time <= CHEAT_TIME
end
function m.mark(names)
local rds = redis.get()
for _, name in ipairs(names) do
if #names == 1 then
ngx.log(ngx.WARN, '作弊:', name, ' + 10')
rds:hincrby(KEY.CHEAT, name, 10)
else
ngx.log(ngx.WARN, '作弊:', name, ' + 1')
rds:hincrby(KEY.CHEAT, name, 1)
end
end
end
function m.isBlack(names)
local rds = redis.get()
for _, name in ipairs(names) do
local c = tonumber((rds:hget(KEY.CHEAT, name))) or 0
if c >= CHEAT_MAX then
return true
end
end
return false
end
function m.clear()
local rds = redis.get()
local f = log(('logs\\cheat\\clear-%d.log'):format(os.time()))
local cheats = {}
local uids = util.zrevrange(rds, KEY.GROUP_SCORE, 1, -1)
f:write('=====旧的排行榜一览=====\n')
for rank, uid in ipairs(uids) do
local time = tonumber((rds:hget(KEY.GROUP_TIME, uid))) or -1
local level = tonumber((rds:hget(KEY.GROUP_LEVEL, uid))) or -1
local qClass = rds:hget(KEY.GROUP_CLASS, uid)
if qClass == ngx.null then
qClass = ''
end
local names = util.unpackList(uid)
if m.checkTime(level, time) then
m.mark(names)
end
if m.isBlack(names) or m.checkTime(level, time) then
cheats[#cheats+1] = {
rank = rank,
uid = uid,
time = time,
level = level,
class = qClass,
names = names,
}
end
f:write('Rank:', rank
, '\tUID:', uid
, '\tclass:', qClass
, '\tLevel:', level
, '\tTime:', time
, '\n'
)
end
f:write('=====清理以下用户=====\n')
for _, cheat in ipairs(cheats) do
f:write('Rank:', cheat.rank
, '\tUID:', cheat.uid
, '\tclass:', cheat.class
, '\tLevel:', cheat.level
, '\tTime:', cheat.time
, '\n'
)
rds:zrem(KEY.GROUP_SCORE, cheat.uid)
rds:hdel(KEY.GROUP_CLASS, cheat.uid)
rds:hdel(KEY.GROUP_TIME, cheat.uid)
rds:hdel(KEY.GROUP_LEVEL, cheat.uid)
for _, name in ipairs(cheat.names) do
rds:hdel(KEY.PLAYER_SCORE, name)
rds:hdel(KEY.PLAYER_CLASS, name)
rds:hdel(KEY.PLAYER_TIME, name)
rds:hdel(KEY.PLAYER_LEVEL, name)
end
end
f:write('=====新的排行榜一览=====\n')
local uids = util.zrevrange(rds, KEY.GROUP_SCORE, 1, -1)
local mark = {}
for rank, uid in ipairs(uids) do
local time = tonumber((rds:hget(KEY.GROUP_TIME, uid))) or -1
local level = tonumber((rds:hget(KEY.GROUP_LEVEL, uid))) or -1
local qClass = rds:hget(KEY.GROUP_CLASS, uid)
if qClass == ngx.null then
qClass = ''
end
f:write('Rank:', rank
, '\tUID:', uid
, '\tclass:', qClass
, '\tLevel:', level
, '\tTime:', time
, '\n'
)
local names = util.unpackList(uid)
local class = util.unpackList(qClass)
local score = tonumber((rds:zscore(KEY.GROUP_SCORE, uid))) or -1
for i, name in ipairs(names) do
if not mark[name] then
mark[name] = true
rds:hset(KEY.PLAYER_SCORE, name, score)
rds:hset(KEY.PLAYER_CLASS, name, class[i])
rds:hset(KEY.PLAYER_TIME, name, time)
rds:hset(KEY.PLAYER_LEVEL, name, level)
end
end
end
f:close()
end
function m.view()
local rds = redis.get()
local f = log(('logs\\cheat\\view-%d.log'):format(os.time()))
local t = util.hgetall(rds, 'cheat')
for k, v in pairs(t) do
f:write(k, '\t', v, '\n')
end
f:close()
end
return m
|
ITEM.name = "대형 케비넷"
ITEM.model = Model("models/props_wasteland/controlroom_storagecloset001a.mdl")
ITEM.uniqueID = "stor_closet"
ITEM.maxWeight = 30
ITEM.desc = "녹색의 대형 케비넷입니다."
|
local refactors = require("refactoring.refactor")
local Config = require("refactoring.config")
local get_select_input = require("refactoring.get_select_input")
local async = require("plenary.async")
local M = {}
function M.setup(config)
Config.setup(config)
end
function M.refactor(name, opts)
if opts == nil then
opts = {}
end
-- TODO: We should redo how this selection thing works.
local refactor = refactors.refactor_names[name] or refactors[name] and name
if not refactor then
error(
string.format(
'Could not find refactor %s. You can get a list of all refactors from require("refactoring").get_refactors()',
refactor
)
)
end
-- Remove the calls to vim.fn
-- I just forgot the name of this ;)
local config = Config.get():merge(opts)
refactors[refactor](vim.api.nvim_buf_get_number(0), config)
end
function M.get_refactors()
return vim.tbl_keys(refactors.refactor_names)
end
function M.select_refactor(opts)
local selected_refactor
async.run(function()
selected_refactor = get_select_input(
M.get_refactors(),
"Refactoring: select a refactor to apply:"
)
end)
if selected_refactor then
M.refactor(selected_refactor, opts)
end
end
M.debug = require("refactoring.debug")
return M
|
-- rk4.lua
-- (C) 2015 Lesley De Cruz
-- See LICENSE.txt for license information.
------------------------------------------------------------------------
-- A classical fourth order Runge-Kutta scheme.
-- Butcher tableau:
--
-- 0 |
-- 1/2 | 1/2
-- 1/2 | 0 1/2
-- 1 | 0 0 1
-- +-------------------
-- 1/6 1/3 1/3 1/6
------------------------------------------------------------------------
--- Create an integrator for n-arrays.
-- @function rk4
-- @param n number of variables (length of the array)
-- @return Integrator for n-arrays
return function(n)
local array = require("array")(n)
local buf_kA, buf_kB, buf_y1 = array(), array(), array()
--- Integrator for n-arrays
-- @function integrator
-- @param y variables at time t
-- @param f function to calculate the time derivatives of the variables
-- @param t time
-- @param dt time integration step
-- @param ynew n-array (buffer) to store the new y-value
-- @return t+dt (incremented time)
-- @return ynew array with variables at time t+dt
return function(y,f,t,dt,ynew)
f(t,y,buf_kA) -- k_1 (A) = f(t, y)
buf_kA:nmul(0.5*dt,buf_y1):add(y,buf_y1) -- y_1 = y + 0.5*dt*k_1 (A)
f(t+0.5*dt,buf_y1,buf_kB) -- k_2 (B) = f(t + 0.5*dt, y_1)
buf_kB:nmul(0.5*dt,buf_y1):add(y,buf_y1) -- y_1' = y + 0.5*dt*k_2
buf_kB:nmul(2,buf_kB):add(buf_kA,buf_kA) -- k_S (A) = k_1 (A) + 2 * k_2 (B)
f(t+0.5*dt,buf_y1,buf_kB) -- k_3 (B) = f(t + 0.5*dt, y_1')
buf_kB:nmul(dt,buf_y1):add(y,buf_y1) -- y_1'' = y + dt*k_3 (B)
buf_kB:nmul(2,buf_kB):add(buf_kA,buf_kA) -- k_S (A) = k_S (A) + 2 * k_3 (B)
f(t+dt,buf_y1,buf_kB) -- k_4 (B) = f(t + dt, y_1")
buf_kB:add(buf_kA,buf_kA) -- k_S (A) = k_S (A) + k_4 (B)
-- ynew = y + dt/6 * k_S
return t+dt, buf_kA:nmul(dt/6,buf_kA):add(y,ynew)
end
end
|
great_borgle = Creature:new {
objectName = "@mob/creature_names:great_borgle",
socialGroup = "borgle",
faction = "",
level = 14,
chanceHit = 0.3,
damageMin = 140,
damageMax = 150,
baseXp = 714,
baseHAM = 2400,
baseHAMmax = 3000,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_carnivore",
meatAmount = 11,
hideType = "hide_leathery",
hideAmount = 7,
boneType = "bone_avian",
boneAmount = 11,
milk = 0,
tamingChance = 0.25,
ferocity = 2,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/great_borgle.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
controlDeviceTemplate = "object/intangible/pet/borgle_hue.iff",
scale = 1.2,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(great_borgle, "great_borgle")
|
local api = vim.api
local loop = vim.loop
local sync = vim.schedule_wrap
local function write(window, buffer, data)
if data == nil or not api.nvim_buf_is_valid(buffer) then
return
end
local lines = api.nvim_buf_line_count(buffer) - 1
local value = vim.split(data, '\n')
local offset = #value + lines
api.nvim_buf_set_option(buffer, 'modifiable', true)
api.nvim_buf_set_lines(buffer, lines, offset, false, value)
api.nvim_buf_set_option(buffer, 'modifiable', false)
api.nvim_win_set_cursor(window, {offset, 0})
end
local function cleanup_handle(handle, notify)
if handle and not handle:is_closing() then
handle:close()
if notify then
print('Job killed.')
end
end
end
local function cleanup_job(process, stdout, stderr, notify)
stdout:read_stop()
stderr:read_stop()
cleanup_handle(stdout)
cleanup_handle(stderr)
cleanup_handle(process, notify)
end
local function start_job(args)
local command, arguments = args[1], {unpack(args, 2)}
local window = api.nvim_get_current_win()
local buffer = api.nvim_create_buf(false, true)
api.nvim_set_current_buf(buffer)
api.nvim_buf_set_keymap(buffer, 'n', '<CR>', ':b#<CR>', {
silent = true
})
api.nvim_buf_set_option(buffer, 'modifiable', false)
api.nvim_buf_set_option(buffer, 'buftype', 'nofile')
api.nvim_buf_set_option(buffer, 'bufhidden', 'wipe')
-- Kick off the process after the buffer has been created.
-- This prevents fast processes from finishing before the
-- buffer has a chance to display.
local stdout = loop.new_pipe(false)
local stderr = loop.new_pipe(false)
local process, _ = loop.spawn(command, {
args = arguments,
stdio = {nil, stdout, stderr}
}, sync(function(code, signal)
local message = '>> Press return to close the buffer <<'
write(window, buffer, '\n\n')
write(window, buffer, message)
cleanup_job(process, stdout, stderr)
end))
-- Attach buffer after the process variables are set. This
-- ensures they can be accessed later.
api.nvim_buf_attach(buffer, false, {
on_detach=function(buffer)
cleanup_job(process, stdout, stderr, true)
end
})
loop.read_start(stdout, sync(function(err, data)
write(window, buffer, data)
end))
loop.read_start(stderr, sync(function(err, data)
write(window, buffer, data)
end))
end
return {
start_job = start_job
}
|
local utf8 = require 'utf8'
local defaultHighlight = { 0x80, 0x80, 0xff, 0x80 }
local function getRectangle (self)
return self.x, self.y, self.width, self.height
end
local function setValue (self, value)
local oldValue = self.value
if oldValue == value then return end
self.value = value
self:changed(value, oldValue)
end
-- make sure selection range doesn't extend past EOT
local function trimRange (self)
local max = #self.value
if self.startIndex > max then self.startIndex = max end
if self.endIndex > max then self.endIndex = max end
end
local function updateHighlight (self)
local value = self.value
local font = love.graphics.getFont()
local startIndex, endIndex = self.startIndex, self.endIndex
local offset = self.x - self.scrollX
self.startX = font:getWidth(value:sub(1, startIndex)) + offset
self.endX = font:getWidth(value:sub(1, endIndex)) + offset
end
local function scrollToCaret (self)
updateHighlight(self)
local x1, y1, w, h = getRectangle(self)
local x2, y2 = x1 + w, y1 + h
local oldX = self.endX or x1
if oldX <= x1 then
self.scrollX = self.scrollX - (x1 - oldX)
updateHighlight(self)
elseif oldX >= x2 then
self.scrollX = self.scrollX + (oldX - x2 + 1)
updateHighlight(self)
end
end
local function selectRange (self, startIndex, endIndex)
if startIndex then self.startIndex = startIndex end
if endIndex then self.endIndex = endIndex end
trimRange(self)
scrollToCaret(self)
end
-- return caret index
local function findIndexFromPoint (self, x, y)
local x1 = self.x
local font = love.graphics.getFont()
local width = 0
local lastPosition = 0
local function checkPosition (position)
local text = self.value:sub(1, position - 1)
width = font:getWidth(text)
if width > x + self.scrollX - x1 then
if position == 1 then
return 0
end
return lastPosition
end
lastPosition = position - 1
end
for position in utf8.codes(self.value) do
local index = checkPosition(position)
if index then return index end
end
local index = checkPosition(#self.value + 1)
if index then return index end
return #self.value
end
-- move the caret or end of selection range one character to the left
local function moveCharLeft (self, alterRange)
trimRange(self)
local text, endIndex = self.value, self.endIndex
-- clamp caret to beginning
if endIndex < 1 then endIndex = 1 end
-- move left
local index = (utf8.offset(text, -1, endIndex + 1) or 0) - 1
selectRange(self, not alterRange and index, index)
end
-- move caret or end of selection range one word to the left
local function moveWordLeft (self, alterRange)
trimRange(self)
local text = self.value:sub(1, self.endIndex)
local pos = text:find('%s[^%s]+%s*$') or 0
selectRange(self, not alterRange and pos, pos)
end
-- move the caret or end of selection range to the beginning of the line
local function moveLineLeft (self, alterRange)
trimRange(self)
selectRange(self, not alterRange and 0, 0)
end
-- move caret or end of selection range one character to the right
local function moveCharRight (self, alterRange)
trimRange(self)
local text, endIndex = self.value, self.endIndex
-- clamp caret to end
if endIndex >= #text then endIndex = #text - 1 end
-- move right
local index = (utf8.offset(text, 2, endIndex + 1) or #text) - 1
selectRange(self, not alterRange and index, index)
end
-- move caret or end of selection range one word to the right
local function moveWordRight (self, alterRange)
trimRange(self)
local text = self.value
local _, pos = text:find('^%s*[^%s]+', self.endIndex + 1)
pos = pos or #text + 1
selectRange(self, not alterRange and pos, pos)
end
-- move caret or end of selection range to the end of the line
local function moveLineRight (self, alterRange)
trimRange(self)
local text = self.value
selectRange(self, not alterRange and #text, #text)
end
local function getRange (self)
trimRange(self)
if self.startIndex <= self.endIndex then
return self.startIndex, self.endIndex
end
return self.endIndex, self.startIndex
end
local function deleteRange (self)
trimRange(self)
local text = self.value
local first, last = getRange(self)
-- if expanded range is selected, delete text in range
if first ~= last then
local left = text:sub(1, first)
local index = #left
setValue(self, left .. text:sub(last + 1))
selectRange(self, index, index)
return true
end
end
local function deleteCharacterLeft (self)
trimRange(self)
local text = self.value
local first, last = getRange(self)
-- if cursor is at beginning, do nothing
if first < 1 then
return
end
-- delete character to the left
local offset = utf8.offset(text, -1, last + 1) or 0
local left = text:sub(1, offset - 1)
local index = #left
setValue(self, left .. text:sub(first + 1))
selectRange(self, index, index)
end
local function deleteCharacterRight (self)
trimRange(self)
local text = self.value
local first, last = getRange(self)
-- if cursor is at end, do nothing
if first == #text then
return
end
-- delete character to the right
local offset = utf8.offset(text, 2, last + 1) or 0
local left = text:sub(1, first)
local index = #left
setValue(self, left .. text:sub(offset))
selectRange(self, index, index)
end
local function copyRangeToClipboard (self)
trimRange(self)
local text = self.value
local first, last = getRange(self)
if last >= first + 1 then
love.system.setClipboardText(text:sub(first + 1, last))
end
end
local function pasteFromClipboard (self)
trimRange(self)
local text = self.value
local pasted = love.system.getClipboardText() or ''
local first, last = getRange(self)
local left = text:sub(1, first) .. pasted
local index = #left
setValue(self, left .. text:sub(last + 1))
selectRange(self, index, index)
end
local function insertText (self, newText)
trimRange(self)
local text = self.value
local first, last = getRange(self)
local left = text:sub(1, first) .. newText
local index = #left
setValue(self, left .. text:sub(last + 1))
selectRange(self, index, index)
end
local function isShiftPressed ()
return love.keyboard.isDown('lshift', 'rshift')
end
-- check command (gui) key, only on Mac.
local isCommandPressed
if IS_MAC then
isCommandPressed = function ()
return love.keyboard.isDown('lgui', 'rgui')
end
else
isCommandPressed = function ()
return false
end
end
-- check command (gui) key on Mac and ctrl key everywhere else.
local isCommandOrCtrlPressed
if IS_MAC then
isCommandOrCtrlPressed = function ()
return love.keyboard.isDown('lgui', 'rgui')
end
else
isCommandOrCtrlPressed = function ()
return love.keyboard.isDown('lctrl', 'rctrl')
end
end
-- check option (alt) key on Mac and ctrl key everywhere else.
local isOptionOrCtrlPressed
if IS_MAC then
isOptionOrCtrlPressed = function ()
return love.keyboard.isDown('lalt', 'ralt')
end
else
isOptionOrCtrlPressed = function ()
return love.keyboard.isDown('lctrl', 'rctrl')
end
end
-- Special keys.
local function createDefaultKeyActions (self)
return {
['tab'] = function ()
return false
end,
['return'] = function ()
self:returned(self.value)
end,
['backspace'] = function ()
if isOptionOrCtrlPressed() then
moveWordLeft(self, true)
end
if not deleteRange(self) then
deleteCharacterLeft(self)
end
end,
['delete'] = function ()
if isOptionOrCtrlPressed() then
moveWordRight(self, true)
end
if not deleteRange(self) then
deleteCharacterRight(self)
end
end,
['left'] = function ()
if isOptionOrCtrlPressed() then
moveWordLeft(self, isShiftPressed())
elseif isCommandPressed() then
moveLineLeft(self, isShiftPressed())
else
moveCharLeft(self, isShiftPressed())
end
end,
['right'] = function ()
if isOptionOrCtrlPressed() then
moveWordRight(self, isShiftPressed())
elseif isCommandPressed() then
moveLineRight(self, isShiftPressed())
else
moveCharRight(self, isShiftPressed())
end
end,
['home'] = function ()
moveLineLeft(self, isShiftPressed())
end,
['end'] = function ()
moveLineRight(self, isShiftPressed())
end,
['x'] = function ()
if isCommandOrCtrlPressed() then
copyRangeToClipboard(self)
deleteRange(self)
end
end,
['c'] = function ()
if isCommandOrCtrlPressed() then
copyRangeToClipboard(self)
end
end,
['v'] = function ()
if isCommandOrCtrlPressed() then
pasteFromClipboard(self)
end
end,
['a'] = function ()
if isCommandOrCtrlPressed() then
selectRange(self, 0, #self.value)
end
end,
}
end
local textInputKeys = {
['space'] = true,
['return'] = true,
['kp00'] = true,
['kp000'] = true,
['kp&&'] = true,
['kp||'] = true,
}
local function isKeyTextInput (key)
if textInputKeys[key] or #key == 1
or (#key == 3 and key:sub(1, 2) == "kp") then
return not love.keyboard.isDown(
'lalt', 'ralt', 'lctrl', 'rctrl', 'lgui', 'rgui')
end
return false
end
-- callbacks
local function draw (self)
if self.needsUpdate then
updateHighlight(self)
end
local startX, endX = self.startX, self.endX
local x, y, w, h = getRectangle(self)
local width, height = endX - startX, h
local font = love.graphics.getFont()
local color = self.color or { 0, 0, 0, 255 }
local textTop = math.floor(y + (h - font:getHeight()) / 2)
love.graphics.push('all')
love.graphics.intersectScissor(x, y, w, h)
-- love.graphics.setFont(font)
if self.focused then
-- draw highlighted selection
love.graphics.setColor(self.highlight or defaultHighlight)
love.graphics.rectangle('fill', startX, y, width, height)
-- draw cursor selection
if love.timer.getTime() % 2 < 1.75 then
love.graphics.setColor(color)
love.graphics.rectangle('fill', endX, y, 1, height)
end
else
love.graphics.setColor { color[1], color[2], color[3],
(color[4] or 256) / 8 }
love.graphics.rectangle('fill', startX, y, width, height)
end
-- draw text
love.graphics.setColor(color)
love.graphics.print(self.value, x - self.scrollX, textTop)
love.graphics.pop()
end
local function mousepressed (self, x, y, button)
if button ~= 1 then return end
self.isDragging = true
self.startIndex = findIndexFromPoint(self, x)
self.endIndex = self.startIndex
scrollToCaret(self)
end
local function mousemoved (self, x, y)
if not self.isDragging then return end
self.endIndex = findIndexFromPoint(self, x)
scrollToCaret(self)
end
local function mousereleased (self, x, y)
if button ~= 1 then return end
self.isDragging = false
end
local function textinput (self, text)
insertText(self, text)
end
local function keypressed (self, key)
local act = self.keyActions[key]
if act then
local result = act()
return result == nil and true or result
end
return isKeyTextInput(key)
end
local function resize (self, width, height)
self.needsUpdate = true
end
local function nothing () end
return function (t)
t = t or {}
t.x = x or 0
t.y = y or 0
t.width = t.width or 128
t.height = t.height or 32
t.startIndex, t.endIndex = 0, 0
t.startX, t.endX = -1, -1
t.scrollX = 0
t.value = t.value or ''
t.keyActions = createDefaultKeyActions(t)
t.type = 'textbox'
t.draw = draw
t.mousepressed = mousepressed
t.mousemoved = mousemoved
t.mousereleased = mousereleased
t.keypressed = keypressed
t.textinput = textinput
t.resize = resize
t.changed = t.changed or nothing
t.returned = t.returned or nothing
return t
end
|
require("camerashake")
FollowCamera = Class(function(self, inst)
self.inst = inst
self.target = nil
self.currentpos = Vector3(0,0,0)
self.distance = 30
self:SetDefault()
self:Snap()
self.time_since_zoom = nil
end)
function FollowCamera:SetDefault()
self.targetpos = Vector3(0,0,0)
--self.currentpos = Vector3(0,0,0)
self.targetoffset = Vector3(0,1.5,0)
if self.headingtarget == nil then
self.headingtarget = 45
end
self.fov = 35
self.pangain = 4
self.headinggain = 20
self.distancegain = 1
self.zoomstep = 4
self.distancetarget = 30
self.mindist = 15
self.maxdist = 50 --40
self.mindistpitch = 30
self.maxdistpitch = 60--60
self.paused = false
self.shake = nil
self.controllable = true
self.cutscene = false
if GetWorld() and GetWorld():IsCave() then
self.mindist = 15
self.maxdist = 35
self.mindistpitch = 25
self.maxdistpitch = 40
self.distancetarget = 25
end
if self.target then
self:SetTarget(self.target)
end
end
function FollowCamera:GetRightVec()
return Vector3(math.cos((self.headingtarget + 90)*DEGREES), 0, math.sin((self.headingtarget+ 90)*DEGREES))
end
function FollowCamera:GetDownVec()
return Vector3(math.cos((self.headingtarget)*DEGREES), 0, math.sin((self.headingtarget)*DEGREES))
end
function FollowCamera:SetPaused(val)
self.paused = val
end
function FollowCamera:SetMinDistance(distance)
self.mindist = distance
end
function FollowCamera:SetGains(pan, heading, distance)
self.distancegain = distance
self.pangain = pan
self.headinggain = heading
end
function FollowCamera:IsControllable()
return self.controllable
end
function FollowCamera:SetControllable(val)
self.controllable = val
end
function FollowCamera:CanControl()
return self.controllable
end
function FollowCamera:SetOffset(offset)
self.targetoffset.x, self.targetoffset.y, self.targetoffset.z = offset.x, offset.y, offset.z
end
function FollowCamera:GetDistance()
return self.distancetarget
end
function FollowCamera:SetDistance(dist)
self.distancetarget = dist
end
function FollowCamera:Shake(type, duration, speed, scale)
if Profile:IsScreenShakeEnabled() then
self.shake = CameraShake(type, duration, speed, scale)
end
local shake_scale = math.max(0, math.min(scale/4, 1))
TheInputProxy:AddVibration(VIBRATION_CAMERA_SHAKE, duration, shake_scale, false)
end
function FollowCamera:SetTarget(inst)
self.target = inst
self.targetpos.x, self.targetpos.y, self.targetpos.z = self.target.Transform:GetWorldPosition()
--self.currentpos.x, self.currentpos.y, self.currentpos.z = self.target.Transform:GetWorldPosition()
end
function FollowCamera:Apply()
--dir
local dx = -math.cos(self.pitch*DEGREES)*math.cos(self.heading*DEGREES)
local dy = -math.sin(self.pitch*DEGREES)
local dz = -math.cos(self.pitch*DEGREES)*math.sin(self.heading*DEGREES)
--pos
local px = dx*(-self.distance) + self.currentpos.x
local py = dy*(-self.distance) + self.currentpos.y
local pz = dz*(-self.distance) + self.currentpos.z
--right
local rx = math.cos((self.heading+90)*DEGREES)
local ry = 0
local rz = math.sin((self.heading+90)*DEGREES)
--up
local ux, uy, uz = dy * rz - dz * ry,
dz * rx - dx * rz,
dx * ry - dy * rx
TheSim:SetCameraPos(px,py,pz)
TheSim:SetCameraDir(dx, dy, dz)
TheSim:SetCameraUp(ux, uy, uz)
TheSim:SetCameraFOV(self.fov)
--local listenpos = dir*(-self.distance*.1) + self.currentpos
--listen dist
local lx = dx*(-self.distance*.1) + self.currentpos.x
local ly = dy*(-self.distance*.1) + self.currentpos.y
local lz = dz*(-self.distance*.1) + self.currentpos.z
--print (lx, ly, lz, self.distance)
TheSim:SetListener(lx, ly, lz, dx, dy, dz, ux, uy, uz)
end
local lerp = function(lower, upper, t)
if t > 1 then t = 1 elseif t < 0 then t = 0 end
return lower*(1-t)+upper*t
end
function FollowCamera:GetHeading()
return self.heading
end
function FollowCamera:GetHeadingTarget()
return self.headingtarget
end
function FollowCamera:SetHeadingTarget(r)
self.headingtarget = r
end
function FollowCamera:ZoomIn()
self.distancetarget = self.distancetarget - self.zoomstep
if self.distancetarget < self.mindist then
self.distancetarget = self.mindist
end
self.time_since_zoom = 0
end
function FollowCamera:ZoomOut()
self.distancetarget = self.distancetarget + self.zoomstep
if self.distancetarget > self.maxdist then
self.distancetarget = self.maxdist
end
self.time_since_zoom = 0
end
function FollowCamera:Snap()
if self.target then
self.targetpos = Vector3(self.target.Transform:GetWorldPosition()) + self.targetoffset
else
self.targetpos.x,self.targetpos.y,self.targetpos.z = self.targetoffset.x,self.targetoffset.y,self.targetoffset.z
end
self.currentpos.x, self.currentpos.y, self.currentpos.z = self.targetpos.x, self.targetpos.y, self.targetpos.z
self.heading = self.headingtarget
self.distance = self.distancetarget
local percent_d = (self.distance - self.mindist)/ (self.maxdist - self.mindist)
self.pitch = lerp(self.mindistpitch, self.maxdistpitch, percent_d)
self:Apply()
end
function FollowCamera:CutsceneMode(b)
self.cutscene = b
end
function FollowCamera:SetCustomLocation(loc)
self.targetpos.x,self.targetpos.y,self.targetpos.z = loc.x,loc.y,loc.z
end
function FollowCamera:Update(dt)
if self.paused then
return
end
if self.cutscene then
self.currentpos.x = lerp(self.currentpos.x, self.targetpos.x + self.targetoffset.x, dt*self.pangain)
self.currentpos.y = lerp(self.currentpos.y, self.targetpos.y + self.targetoffset.y, dt*self.pangain)
self.currentpos.z = lerp(self.currentpos.z, self.targetpos.z + self.targetoffset.z, dt*self.pangain)
if self.shake then
local shakeOffset = self.shake:Update(dt)
if shakeOffset then
local upOffset = Vector3(0, shakeOffset.y, 0)
local rightOffset = self:GetRightVec() * shakeOffset.x
self.currentpos.x = self.currentpos.x + upOffset.x + rightOffset.x
self.currentpos.y = self.currentpos.y + upOffset.y + rightOffset.y
self.currentpos.z = self.currentpos.z + upOffset.z + rightOffset.z
else
self.shake = nil
end
end
if math.abs(self.heading - self.headingtarget) > .01 then
self.heading = lerp(self.heading, self.headingtarget, dt*self.headinggain)
end
if math.abs(self.distance - self.distancetarget) > .01 then
self.distance = lerp(self.distance, self.distancetarget, dt*self.distancegain)
end
local percent_d = (self.distance - self.mindist)/ (self.maxdist - self.mindist)
self.pitch = lerp(self.mindistpitch, self.maxdistpitch, percent_d)
else
if self.time_since_zoom then
self.time_since_zoom = self.time_since_zoom + dt
if self.should_push_down and self.time_since_zoom > .25 then
self.distancetarget = self.distance - self.zoomstep
end
end
if self.target then
--self.targetpos = Vector3(self.target.Transform:GetWorldPosition()) + self.targetoffset
local x, y, z = self.target.Transform:GetWorldPosition()
self.targetpos.x = x + self.targetoffset.x
self.targetpos.y = y + self.targetoffset.y
self.targetpos.z = z + self.targetoffset.z
else
self.targetpos.x, self.targetpos.y, self.targetpos.z = self.targetoffset.x, self.targetoffset.y, self.targetoffset.z
end
self.currentpos.x = lerp(self.currentpos.x, self.targetpos.x, dt*self.pangain)
self.currentpos.y = lerp(self.currentpos.y, self.targetpos.y, dt*self.pangain)
self.currentpos.z = lerp(self.currentpos.z, self.targetpos.z, dt*self.pangain)
--self.currentpos = lerp(self.currentpos, self.targetpos, dt*self.pangain)
if self.shake then
local shakeOffset = self.shake:Update(dt)
if shakeOffset then
local upOffset = Vector3(0, shakeOffset.y, 0)
local rightOffset = self:GetRightVec() * shakeOffset.x
self.currentpos.x = self.currentpos.x + upOffset.x + rightOffset.x
self.currentpos.y = self.currentpos.y + upOffset.y + rightOffset.y
self.currentpos.z = self.currentpos.z + upOffset.z + rightOffset.z
else
self.shake = nil
end
end
if math.abs(self.heading - self.headingtarget) > .01 then
self.heading = lerp(self.heading, self.headingtarget, dt*self.headinggain)
else
self.heading = self.headingtarget
end
if math.abs(self.distance - self.distancetarget) > .01 then
self.distance = lerp(self.distance, self.distancetarget, dt*self.distancegain)
else
self.distance = self.distancetarget
end
local percent_d = (self.distance - self.mindist)/ (self.maxdist - self.mindist)
self.pitch = lerp(self.mindistpitch, self.maxdistpitch, percent_d)
end
self:Apply()
end
return FollowCamera
|
-- Simple Spikes
local b = {}
b.Name = "Spikes"
b.Icon = Material("yawd/hud/spikes.png")
b.Health = -1
b.CanBuild = true
b.BuildClass = {CLASS_CONSTRUCTOR, CLASS_JUGGERNAUT, CLASS_HEALER}
b.Cost = 350
local damage = 50 -- This allows to balance traps
b.BuildingSize = {-Vector(95, 95, 12), Vector(95, 95, 12)}
b.TrapArea = {-Vector(95, 95, 1.7), Vector(95, 95, 95)}
b.TrapTriggerTime = 0.5 -- Time it takes to trigger
b.TrapResetTime = 7 -- Time it takes to reset
b.TrapDurationTime = 1 -- Time it takes to stop
function b:OnTrapThink() end
function b:OnTrapTrigger( tListOfEnemies )
if SERVER then
local dm = self:DamageInfo()
dm:SetDamage( damage )
dm:SetDamageType( DMG_SLASH )
for k,v in ipairs( tListOfEnemies ) do
v:TakeDamageInfo( dm )
v:EmitSound("npc/manhack/grind_flesh" .. math.random(1,3) .. ".wav", 100)
end
else
self:EmitSound("npc/strider/strider_skewer1.wav", 100, 100, 0.4)
self.triggered = true
end
end
if CLIENT then
function b:OnTrapEnd()
self:EmitSound("npc/strider/strider_skewer1.wav", 100, 100, 0.4)
self.triggered = nil
end
end
local mat = Material("yawd/spike.png")
local mat2 = Material("yawd/models/trap_spike")
b.retract = 0
local spike_length = 50
function b:DrawSelection( )
self:RenderBase(mat2)
self:RenderTrapArea()
render.SetMaterial(mat)
local ep = EyePos()
local r_t = {}
for x = -3, 3 do
for y = -3, 3 do
local pos = self:LocalToWorld(Vector(x * 19, y * 19, self:OBBMaxs().z))
table.insert(r_t, {pos,ep:DistToSqr(pos)})
end
end
table.sort(r_t, function(a,b) return a[2]>b[2] end)
local n = self:GetAngles():Up()
for k,v in ipairs(r_t) do
render.DrawBeam(v[1],v[1] + n * spike_length, 5, 1, 0, self.CanAfford and Color(0,255,0) or Color(255,0,0))
end
end
function b:Draw()
-- Renders the bottom of the trap
self:RenderBase(mat2)
self:RenderTrapArea()
if self.triggered then
self.retract = math.min(self.retract + FrameTime() * 500, spike_length)
elseif self.retract > 0 then
self.retract = math.max(self.retract - FrameTime() * 300, 0)
end
if self.retract <= 0 then return end
render.SetMaterial(mat)
local ep = EyePos()
local r_t = {}
for x = -3, 3 do
for y = -3, 3 do
local pos = self:LocalToWorld(Vector(x * 19, y * 19, self:OBBMaxs().z))
table.insert(r_t, {pos,ep:DistToSqr(pos)})
end
end
table.sort(r_t, function(a,b) return a[2]>b[2] end)
local r_e = self.retract / spike_length
local n = self:GetAngles():Up()
for k,v in ipairs(r_t) do
render.DrawBeam(v[1],v[1] + n * self.retract, 5, r_e, 0, Color(255,255,255))
end
end
return b
|
object_tangible_loot_creature_loot_collections_dooku_datadisk_05 = object_tangible_loot_creature_loot_collections_shared_dooku_datadisk_05:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_dooku_datadisk_05, "object/tangible/loot/creature/loot/collections/dooku_datadisk_05.iff")
|
object_mobile_outbreak_hum_01 = object_mobile_shared_outbreak_hum_01:new {
}
ObjectTemplates:addTemplate(object_mobile_outbreak_hum_01, "object/mobile/outbreak_hum_01.iff")
|
--This is a rank table
--There could be multiple tables to generate spawns from
local Tsoo_Ranks_01 = {
["Underlings"] = {
--NA
},
["Minions"] = {
"Tsoo_01","Tsoo_04","Tsoo_05",
"Tsoo_06","Tsoo_08","Tsoo_09",
"Tsoo_12","Tsoo_17",
},
["Lieutenants"] = {
"Tsoo_10","Tsoo_14","Tsoo_15","Tsoo_Spirit",
"Mystic_01","Mystic_02","Mystic_03","Mystic_04",
},
["Sniper"] = {
--NA
},
["Boss"] = {
"Tsoo_03","Tsoo_13","Tsoo_16","Tsoo_07","Tsoo_11","Tsoo_02","Tsoo_09",
},
["Elite Boss"] = {
--NA
},
["Victims"] = {
},
["Specials"] = {
},
}
local Warriors_Rumble_01 = {
["Minions"] = {
"Thug_Warrior_01", "Thug_Warrior_02", "Thug_Warrior_03",
"Thug_Warrior_04", "Thug_Warrior_05", "Thug_Warrior_06",
},
["Boss"] = {
"Thug_Warrior_Boss_01", "Thug_Warrior_Boss_02", "Thug_Warrior_Boss_03",
},
}
--== Shady Deal ==---
ShadyDeal_Tsoo_D1_V0 = {
["Markers"] = {
["Encounter_S_30"] = Tsoo_Ranks_01.Minions,
["Encounter_S_32"] = Tsoo_Ranks_01.Minions,
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
},
}
ShadyDeal_Tsoo_D1_V1 = {
["Markers"] = {
["Encounter_S_30"] = Tsoo_Ranks_01.Boss,
["Encounter_S_32"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_E_02"] = Tsoo_Ranks_01.Minions,
["Encounter_E_04"] = Tsoo_Ranks_01.Minions,
},
}
ShadyDeal_Tsoo_D1_V2 = {
["Markers"] = {
["Encounter_S_30"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_S_31"] = Tsoo_Ranks_01.Minions,
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
["Encounter_E_03"] = Tsoo_Ranks_01.Minions,
["Encounter_E_05"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_E_08"] = Tsoo_Ranks_01.Minions,
},
}
ShadyDeal_Tsoo_D1_V3 = {
["Markers"] = {
["Encounter_S_30"] = Tsoo_Ranks_01.Boss,
["Encounter_S_32"] = Tsoo_Ranks_01.Boss,
["Encounter_E_02"] = Tsoo_Ranks_01.Minions,
["Encounter_E_03"] = Tsoo_Ranks_01.Minions,
["Encounter_E_05"] = Tsoo_Ranks_01.Minions,
["Encounter_E_07"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_E_08"] = Tsoo_Ranks_01.Lieutenants,
},
}
ShadyDeal_Tsoo_D1_V4 = {
["Markers"] = {
["Encounter_S_30"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_S_32"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
["Encounter_E_02"] = Tsoo_Ranks_01.Minions,
["Encounter_E_04"] = Tsoo_Ranks_01.Boss,
["Encounter_E_06"] = Tsoo_Ranks_01.Minions,
["Encounter_E_08"] = Tsoo_Ranks_01.Boss,
},
}
ShadyDeal_Tsoo_D5_V0 = ShadyDeal_Tsoo_D1_V0
ShadyDeal_Tsoo_D5_V1 = ShadyDeal_Tsoo_D1_V1
ShadyDeal_Tsoo_D5_V2 = ShadyDeal_Tsoo_D1_V2
ShadyDeal_Tsoo_D5_V3 = ShadyDeal_Tsoo_D1_V3
ShadyDeal_Tsoo_D5_V4 = ShadyDeal_Tsoo_D1_V4
ShadyDeal_Tsoo_D10_V0 = ShadyDeal_Tsoo_D1_V0
ShadyDeal_Tsoo_D10_V1 = ShadyDeal_Tsoo_D1_V1
ShadyDeal_Tsoo_D10_V2 = ShadyDeal_Tsoo_D1_V2
ShadyDeal_Tsoo_D10_V3 = ShadyDeal_Tsoo_D1_V3
ShadyDeal_Tsoo_D10_V4 = ShadyDeal_Tsoo_D1_V4
-- Loiter --
Loiter_Tsoo_D1_V0 = {
["Markers"] = {
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
["Encounter_E_02"] = Tsoo_Ranks_01.Minions,
["Encounter_E_03"] = Tsoo_Ranks_01.Minions,
["Encounter_E_06"] = Tsoo_Ranks_01.Minions,
["Encounter_S_30"] = Tsoo_Ranks_01.Lieutenants,
},
}
Loiter_Tsoo_D1_V1 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D1_V2 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D1_V3 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D1_V4 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D5_V0 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D5_V1 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D5_V2 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D5_V3 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D5_V4 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D10_V0 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D10_V1 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D10_V2 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D10_V3 = Loiter_Tsoo_D1_V0
Loiter_Tsoo_D10_V4 = Loiter_Tsoo_D1_V0
-- Shakedown --
Shakedown_Tsoo_D1_V0 = {
["Markers"] = {
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
["Encounter_E_04"] = Tsoo_Ranks_01.Lieutenants,
["Encounter_E_06"] = Tsoo_Ranks_01.Minions,
["Encounter_S_30"] = Tsoo_Ranks_01.Boss,
},
}
Shakedown_Tsoo_D1_V1 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D1_V2 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D1_V3 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D1_V4 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D5_V0 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D5_V1 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D5_V2 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D5_V3 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D5_V4 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D10_V0 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D10_V1 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D10_V2 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D10_V3 = Shakedown_Tsoo_D1_V0
Shakedown_Tsoo_D10_V4 = Shakedown_Tsoo_D1_V0
-- Rumble --
Rumble_TsooWarriors_D3_V0 = {
["Markers"] = {
["Encounter_E_09"] = Tsoo_Ranks_01.Minions,
["Encounter_E_03"] = Tsoo_Ranks_01.Boss,
["Encounter_E_01"] = Tsoo_Ranks_01.Minions,
["Encounter_E_05"] = Tsoo_Ranks_01.Minions,
["Encounter_S_33"] = Tsoo_Ranks_01.Minions,
["Encounter_S_31"] = Tsoo_Ranks_01.Minions,
["Encounter_E_02"] = Warriors_Rumble_01.Minions,
["Encounter_E_10"] = Warriors_Rumble_01.Minions,
["Encounter_E_04"] = Warriors_Rumble_01.Minions,
["Encounter_E_06"] = Warriors_Rumble_01.Boss,
["Encounter_S_32"] = Warriors_Rumble_01.Minions,
["Encounter_S_30"] = Warriors_Rumble_01.Minions,
},
}
Rumble_TsooWarriors_D3_V1 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D3_V2 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D3_V3 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D3_V4 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D8_V0 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D8_V1 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D8_V2 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D8_V3 = Rumble_TsooWarriors_D3_V0
Rumble_TsooWarriors_D8_V4 = Rumble_TsooWarriors_D3_V0
|
-- Functions:
-------------------------------------------------------
function model.completeDataPartSpecific(data)
if not data.partSpecific then
data.partSpecific={}
end
if not data.partSpecific['width'] then
data.partSpecific['width']=0.3
end
if not data.partSpecific['length'] then
data.partSpecific['length']=0.3
end
if not data.partSpecific['height'] then
data.partSpecific['height']=0.3
end
if not data.partSpecific['bitCoded'] then
data.partSpecific['bitCoded']=0 -- 1,2: free, 4:textured
end
if not data.partSpecific['mass'] then
data.partSpecific['mass']=0.5
end
end
function model.readPartInfo()
local data=simBWF.readPartInfo(model.handle)
-- Additional part data (label specific):
if not data['labelData'] then
data['labelData']={}
end
if not data['labelData']['bitCoded'] then
data['labelData']['bitCoded']=0 -- 1,2,4: free, 8=label1,16=label2,32=label3,64=largeLabel1,128=largeLabel2,256=largeLabel3
end
if not data['labelData']['placementCode'] then
data['labelData']['placementCode']={'{0,0,0},{0,0,0}','{0,0,0},{0,0,0}','{0,0,0},{0,0,0}'}
end
if not data['labelData']['smallLabelSize'] then
data['labelData']['smallLabelSize']={0.075,0.038}
end
if not data['labelData']['largeLabelSize'] then
data['labelData']['largeLabelSize']={0.075,0.1125}
end
if not data['labelData']['boxSize'] then
data['labelData']['boxSize']={0.1,0.1,0.1}
end
return data
end
function model.writePartInfo(data)
return simBWF.writePartInfo(model.handle,data)
end
-- Additional handles:
-------------------------------------------------------
model.specHandles={}
model.specHandles.texture=sim.getObjectHandle('genericShippingBox_texture')
model.specHandles.smallLabel=sim.getObjectHandle('genericShippingBox_smallLabel')
model.specHandles.largeLabel=sim.getObjectHandle('genericShippingBox_largeLabel')
|
-- Helper functions for the marine buy menu
-- headlines for the Buymenu
function CombatMarineBuy_GetHeadlines()
local headlines = {
"Support",
"Weapons",
"Weapon Ups",
"Armor Ups",
"Class Ups",
"Grenades",
}
return headlines
end
-- costum sort function that the ups to look good
function CombatMarineBuy_GUISortUps(upgradeList)
-- max 4 rows per column
local layoutList = {
-- 0, Support
"nextRow",
kTechId.MedPack,
kTechId.AmmoPack,
kTechId.CatPack,
kTechId.Scan,
kTechId.LayMines,
kTechId.Welder,
"nextRow",
-- 1, Weapons
kTechId.Shotgun,
kTechId.GrenadeLauncher,
kTechId.Flamethrower,
kTechId.HeavyMachineGun,
"nextRow",
-- 2, Weapon Upgrades
kTechId.Weapons1,
kTechId.Weapons2,
kTechId.Weapons3,
kTechId.AdvancedWeaponry,
"nextRow",
-- 3, Armor Upgrades
kTechId.Armor1,
kTechId.Armor2,
kTechId.Armor3,
"nextRow",
-- 4, Class Upgrades
kTechId.Jetpack,
kTechId.DualMinigunExosuit,
kTechId.DualRailgunExosuit,
kTechId.PhaseTech,
"nextRow",
-- 5, grenades
kTechId.ClusterGrenade,
kTechId.GasGrenade,
kTechId.PulseGrenade,
}
local sortedList = {}
-- search the techID in the Uplist and copy it to its correct place
for _, entry in ipairs(layoutList) do
if (entry == "nextRow") then
table.insert(sortedList, "nextRow")
else
for _, upgrade in ipairs(upgradeList) do
if upgrade:GetTechId() == entry then
table.insert(sortedList, upgrade)
break
end
end
end
end
return sortedList
end
-- Todo: Move these into the locale file
local combatWeaponDescription
function CombatMarineBuy_GetWeaponDescription(techId)
if not combatWeaponDescription then
combatWeaponDescription = {}
combatWeaponDescription[kTechId.MedPack] ={ "COMBAT_RESUPPLY_DESCRIPTION", kResupplyTimer }
combatWeaponDescription[kTechId.AmmoPack] = {"COMBAT_IMPROVED_RESUPPLY_DESCRIPTION", kImprovedResupplyExtra}
combatWeaponDescription[kTechId.Scan] = { "COMBAT_SCAN_DESCRIPTION", kScanTimer }
combatWeaponDescription[kTechId.Welder] = { "COMBAT_WELDER_DESCRIPTION" }
combatWeaponDescription[kTechId.LayMines] = {"COMBAT_MINES_DESCRIPTION"}
combatWeaponDescription[kTechId.CatPack] = {"COMBAT_CATALYST_DESCRIPTION", kCatalystTimer}
combatWeaponDescription[kTechId.Axe] = {"COMBAT_AXE_DESCRIPTION"}
combatWeaponDescription[kTechId.Pistol] = {"COMBAT_PISTOL_DESCRIPTION"}
combatWeaponDescription[kTechId.Rifle] = {"COMBAT_RIFLE_DESCRIPTION"}
combatWeaponDescription[kTechId.Shotgun] = {"COMBAT_SHOTGUN_DESCRIPTION"}
combatWeaponDescription[kTechId.Flamethrower] = {"COMBAT_FLAMETHROWER_DESCRIPTION"}
combatWeaponDescription[kTechId.GrenadeLauncher] = {"COMBAT_GRENADELAUNCHER_DESCRIPTION" }
combatWeaponDescription[kTechId.HeavyMachineGun] = {"COMBAT_MACHINE_GUN_DESCRIPTION"}
combatWeaponDescription[kTechId.Weapons1] = {"COMBAT_WEAPON1_DESCRIPTION"}
combatWeaponDescription[kTechId.Weapons2] = {"COMBAT_WEAPON2_DESCRIPTION"}
combatWeaponDescription[kTechId.Weapons3] = {"COMBAT_WEAPON3_DESCRIPTION"}
combatWeaponDescription[kTechId.AdvancedWeaponry] = {"COMBAT_RELOAD_DESCRIPTION"}
combatWeaponDescription[kTechId.Armor1] = {"COMBAT_ARMOR1_DESCRIPTION"}
combatWeaponDescription[kTechId.Armor2] = {"COMBAT_ARMOR2_DESCRIPTION"}
combatWeaponDescription[kTechId.Armor3] = {"COMBAT_ARMOR3_DESCRIPTION"}
combatWeaponDescription[kTechId.PhaseTech] = {"COMBAT_SPRINT_DESCRIPTION"}
combatWeaponDescription[kTechId.Jetpack] = {"COMBAT_JETPACK_DESCRIPTION"}
combatWeaponDescription[kTechId.Exosuit] = {"COMBAT_EXOSUIT_DESCRIPTION"}
combatWeaponDescription[kTechId.DualMinigunExosuit] = {"COMBAT_EXOSUIT_DUALMINIGUN_DESCRIPTION"}
combatWeaponDescription[kTechId.ClawRailgunExosuit] = {"COMBAT_EXOSUIT_RAILGUN_DESCRIPTION"}
combatWeaponDescription[kTechId.DualRailgunExosuit] = {"COMBAT_EXOSUIT_DUALRAILGUN_DESCRIPTION"}
combatWeaponDescription[kTechId.ClusterGrenade] = {"COMBAT_CLUSTERGRENADE_DESCRIPTION"}
combatWeaponDescription[kTechId.GasGrenade] = {"COMBAT_GASGRENADE_DESCRIPTION"}
combatWeaponDescription[kTechId.PulseGrenade] = {"COMBAT_PULSEGRENADE_DESCRIPTION"}
end
local description = combatWeaponDescription[techId]
local desc = Combat_ResolveString(description[1])
if description[2] then
desc = string.format(desc, description[2])
end
return desc
end
|
-- this script checks if we processed the whole request, and if so it cleans
-- up all the structures created.
-- If we did not process the whole request, the subrequest we just processed
-- is acknowledged.
--
-- KEYS[1] contains the ID of the request
-- ARGV[1] contains the ID of the request entry in the consumer group
local req_stream = string.format( "sub:{%s}", KEYS[1] )
local counter = string.format( "counter:{%s}",KEYS[1] )
local remaining = redis.call("DECR", counter)
if remaining == 0 then
redis.call("XGROUP", "DESTROY", req_stream, req_stream)
redis.call("DEL", req_stream)
redis.call("DEL", counter)
redis.call("PUBLISH", KEYS[1], "1")
else
redis.call("XACK", req_stream, req_stream, ARGV[1])
end
return redis.status_reply("OK")
|
-----------------------------------
-- Area: Waughroon Shrine
-- Mob: Sa'Nha Soulsaver
-- BCNM mob in Bastok mission 7-2.
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
|
local _M = {}
_M.LOCAL_IP = "127.0.0.1"
_M.LOCAL_HOST = "localhost"
_M.BALANCER_CHASH = "CHASH"
_M.BALANCER_ROUNDROBIN = "ROUNDROBIN"
_M.ENVIRONMENT_PROD = "PROD"
_M.ENVIRONMENT_BETA = "BETA"
_M.ENVIRONMENT_TEST = "TEST"
_M.REQUEST_API_ENV_KEY = "APIOAK-API-ENV"
_M.REQUEST_ADMIN_TOKEN_KEY = "APIOAK-ADMIN-TOKEN"
_M.RESPONSE_MOCK_REQUEST_KEY = "APIOAK-MOCK-REQUEST"
_M.REQUEST_PARAM_POS_QUERY = "QUERY"
_M.REQUEST_PARAM_POS_PATH = "PATH"
_M.REQUEST_PARAM_POS_HEADER = "HEADER"
_M.CONTENT_TYPE = "Content-Type"
_M.CONTENT_TYPE_JSON = "application/json"
_M.CONTENT_TYPE_HTML = "text/html"
_M.CONTENT_TYPE_XML = "text/xml"
return _M
|
ITEM.Name = 'Clock Mask'
ITEM.Price = 50
ITEM.Model = 'models/props_c17/clock01.mdl'
ITEM.Attachment = 'eyes'
function ITEM:OnEquip(ply, modifications)
ply:PS_AddClientsideModel(self.ID)
end
function ITEM:OnHolster(ply)
ply:PS_RemoveClientsideModel(self.ID)
end
function ITEM:ModifyClientsideModel(ply, model, pos, ang)
ang:RotateAroundAxis(ang:Right(), -90)
return model, pos, ang
end
|
function make_model(time_anim, animation)
local model = {}
model["animation"] = animation or {}
model["time_anim"] = time_anim
local function set_animation(self, key, index_anim, sprite)
self.animation[key] = { index_anim, sprite }
end
model["set_animation"] = set_animation
return model
end
function make_model_sprite(path ,x_clips,y_clips)
local sprite = ERPG_Sprite.make_sprite(path, {255,0,255})
sprite:set_clips(x_clips,y_clips)
return sprite
end
|
pg = pg or {}
pg.navalacademy_shoppingstreet_template = {
{
special_goods_num = 3,
lv_up_time = 10,
goods_num = 10,
words_enter = "恩?欢迎光临…|啊…又来了啊…|要来点科技箱吗……?",
words_buy = "呼呼…谢谢惠顾…|再多买一点如何?|眼光不错……",
lv = 1,
words_touch = "呒…|打折?没有的不存在的……|下一个科技箱里就会有好东西的…|再怎么戳我也不会给你好处的…",
lv_up_cost = {
1,
100
}
},
all = {
1
}
}
return
|
-- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Structures\Alien\Harvester\client.lua
-- - Dragon
-- Harvester
local originalHarvesterOnUpdate
originalHarvesterOnUpdate = Class_ReplaceMethod("Harvester", "OnUpdate",
function(self, deltaTime)
originalHarvesterOnUpdate(self, deltaTime)
if self.isTeleporting ~= self.lastisTeleporting then
-- This isnt good coding, but these are all over the place in vanilla
if not self.isTeleporting and self.lastisTeleporting then
-- We are not teleporting, trigger clear, then infest start.
self:CleanupInfestation()
end
self.lastisTeleporting = self.isTeleporting
end
end
)
|
local event = require("__flib__.event")
local gui = require("__flib__.gui-beta")
local mod_gui = require("__core__.lualib.mod-gui")
local migration = require("__flib__.migration")
local mi_gui = require("scripts.gui")
local table = require("__flib__.table")
local lib = require "__ModuleInserterER__/lib_control"
local debugDump = lib.debugDump
local function compare_contents(tbl1, tbl2)
if tbl1 == tbl2 then return true end
for k, value in pairs(tbl1) do
if (value ~= tbl2[k]) then return false end
end
for k, _ in pairs(tbl2) do
if tbl1[k] == nil then return false end
end
return true
end
local function sort_modules(entity, modules, cTable)
--Don't sort empty inventories
if not next(modules) then return end
local inventory = entity.get_module_inventory()
local contents = inventory and inventory.get_contents()
if compare_contents(cTable, contents) then
local status, err = pcall(function()
inventory.clear()
local insert = inventory.insert
for _, module in pairs(modules) do
if module then
insert{name = module, count = 1}
end
end
end)
if not status then
debugDump(err, true)
inventory.clear()
for name, count in pairs(contents) do
inventory.insert{name = name, count = count}
end
end
end
end
local function mi_on_mod_item_opened(e)
if e.item.name == "module-inserter" then
e.player = game.get_player(e.player_index)
e.pdata = global._pdata[e.player_index]
if not e.pdata.gui_open then
mi_gui.open(e)
end
end
end
event.on_mod_item_opened(mi_on_mod_item_opened)
event.register("toggle-module-inserter", function(e)
e.player = game.get_player(e.player_index)
e.pdata = global._pdata[e.player_index]
mi_gui.toggle(e)
end)
local function get_module_inserter(e)
local player = game.get_player(e.player_index)
local inv = player.get_main_inventory()
local mi = inv.find_item_stack("module-inserter")
if mi then
mi.swap_stack(player.cursor_stack)
else
player.clear_cursor()
player.cursor_stack.set_stack{name = "module-inserter", count = 1}
end
end
event.register("get-module-inserter", get_module_inserter)
event.on_lua_shortcut(function(e)
if e.prototype_name == "module-inserter" then
get_module_inserter(e)
end
end)
event.register("mi-confirm-gui", function(e)
local pdata = global._pdata and global._pdata[e.player_index]
if pdata and pdata.gui_open and not pdata.pinned then
e.pdata = pdata
e.player = game.get_player(e.player_index)
mi_gui.handlers.main.apply_changes(e)
end
end)
local function drop_module(entity, name, count, module_inventory, chest, create_entity)
if not (chest and chest.valid) then
chest = create_entity{
name = "module_inserter_pickup",
position = entity.position,
force = entity.force,
create_build_effect_smoke = false
}
if not (chest and chest.valid) then
error("Invalid chest")
end
end
local stack = {name = name, count = count}
stack.count = chest.insert(stack)
if module_inventory.remove(stack) ~= stack.count then
log("Not all modules removed")
end
return chest
end
local function print_planner(planner)--luacheck: ignore
for i = 1, 4 do
log(serpent.line(planner.get_mapper(i, "from")) .. serpent.line(planner.get_mapper(i, "to")))
end
end
--TODO: figure out which modules can be replaced via upgrade item
--only 1 type desired
--multiple module types if:
-- amounts can be matched from contents to desired
local function create_upgrade_planner(contents, desired, desired_count, upgrade_planner)
if desired_count == 0 or table_size(contents) == 0 then return end
if desired_count == 1 then
local from = {type = "item", name = ""}
local to = {type = "item", name = next(desired)}
local i = 0
for name, _ in pairs(contents) do
if name ~= to.name then
i = i + 1
from.name = name
upgrade_planner.set_mapper(i, "from", from)
upgrade_planner.set_mapper(i, "to", to)
end
end
if i > 0 then
return upgrade_planner
end
end
local matches = {}
local assigned = {}
--"upgrading" to the same module
for name, c in pairs(contents) do
if desired[name] and desired[name] == c then
matches[name] = name
assigned[name] = name
end
end
for name, c in pairs(contents) do
for name_d, c_d in pairs(desired) do
if c == c_d and not matches[name] and not assigned[name_d] then
matches[name] = name_d
assigned[name_d] = name
end
end
end
if desired_count == table_size(matches) then
local from = {type = "item", name = ""}
local to = {type = "item", name = next(desired)}
local i = 0
for name, name_d in pairs(matches) do
if name ~= name_d then
from.name = name
to.name = name_d
i = i + 1
upgrade_planner.set_mapper(i, "from", from)
upgrade_planner.set_mapper(i, "to", to)
end
end
if i > 0 then
return upgrade_planner
end
end
end
local function create_request_proxy(entity, modules, desired, proxies, player, create_entity, upgrade_planner)
local module_inventory = entity.get_module_inventory()
if not module_inventory then
return proxies
end
local contents = module_inventory.get_contents()
local same = compare_contents(desired, contents)
local desired_count = table_size(desired)
local needs_sorting = desired_count > 1
if same then
if needs_sorting then
sort_modules(entity, modules, desired)
end
return proxies
end
local planner = create_upgrade_planner(contents, desired, desired_count, upgrade_planner)
if planner then
--print_planner(planner)
entity.surface.upgrade_area{area = entity.bounding_box, force = player.force, player = player, item = planner, skip_fog_of_war = false}
planner.clear_upgrade_item()
--print_planner(planner)
local to_add = table_size(modules) - module_inventory.get_item_count()
local irp
if desired_count > 1 or to_add > 0 then
irp = entity.surface.find_entity("item-request-proxy", entity.position)
end
if to_add > 0 and desired_count == 1 and irp then
--find created proxy and change item requests
local to = {type = "item", name = next(desired)}
local requests = irp.item_requests
requests[to.name] = desired[to.name] - (contents[to.name] or 0)
irp.item_requests = requests
return proxies
end
if to_add == 0 then
if irp and needs_sorting then
script.register_on_entity_destroyed(irp)
proxies[irp.unit_number] = {modules = modules, cTable = desired, target = entity}
end
return proxies
end
end
local missing = {}
--local surplus = {}
local changed
local diff
local chest = false
--Drop all modules and done
if desired_count == 0 then
for name, count in pairs(contents) do
chest = drop_module(entity, name, count, module_inventory, chest, create_entity)
end
if chest and chest.valid then
if player and player.valid then
chest.order_deconstruction(chest.force, player)
else
chest.order_deconstruction(chest.force)
end
end
return proxies
end
--Request all modules and done
if not next(contents) then
missing = desired
local ghost = create_entity{
name = "item-request-proxy",
position = entity.position,
force = entity.force,
target = entity,
modules = missing,
raise_built = true
}
if ghost and needs_sorting then
script.register_on_entity_destroyed(ghost)
proxies[ghost.unit_number] = {modules = modules, cTable = desired, target = entity}
end
return proxies
end
for name, count in pairs(desired) do
diff = (contents[name] or 0) - count -- >0: drop, < 0 missing
contents[name] = nil
if diff < 0 then
missing[name] = -1 * diff
elseif diff > 0 then
chest = drop_module(entity, name, diff, module_inventory, chest, create_entity)
--surplus[name] = diff
end
end
for name, count in pairs(contents) do
diff = count - (desired[name] or 0) -- >0: drop, < 0 missing
--assert(not missing[name] and not surplus[name])
if diff < 0 then
missing[name] = -1 * diff
elseif diff > 0 then
chest = drop_module(entity, name, diff, module_inventory, chest, create_entity)
--surplus[name] = diff
changed = true
end
end
if chest and chest.valid then
if player and player.valid then
chest.order_deconstruction(chest.force, player)
else
chest.order_deconstruction(chest.force)
end
end
if changed then
contents = module_inventory.get_contents()
same = compare_contents(desired, contents)
end
if not same and next(missing) then
local ghost = create_entity{
name = "item-request-proxy",
position = entity.position,
force = entity.force,
target = entity,
modules = missing,
raise_built = true
}
if ghost and needs_sorting then
script.register_on_entity_destroyed(ghost)
proxies[ghost.unit_number] = {modules = modules, cTable = desired, target = entity}
end
end
return proxies
end
local function delayed_creation(e)
local current = global.to_create[e.tick]
if current then
local proxies = global.proxies
local ent
local upgrade_inventory = game.create_inventory(1)
upgrade_inventory.insert{name = "upgrade-planner"}
for _, data in pairs(current) do
ent = data.entity
if ent and ent.valid then
proxies = create_request_proxy(ent, data.modules, data.cTable, proxies, data.player, data.surface.create_entity, upgrade_inventory[1])
end
end
upgrade_inventory.destroy()
global.proxies = proxies
global.to_create[e.tick] = nil
script.on_nth_tick(e.nth_tick, nil)
end
end
local function conditional_events(check)
if check then
for tick, to_create in pairs(global.to_create) do
for id, data in pairs(to_create) do
if not (data.entity and data.entity.valid) then
to_create[id] = nil
end
end
if not next(to_create) then
global.to_create[tick] = nil
end
end
end
for tick in pairs(global.to_create) do
script.on_nth_tick(tick, delayed_creation)
end
end
local function modules_allowed(recipe, modules)
local restricted_modules = global.restricted_modules
for module, _ in pairs(modules) do
if restricted_modules[module] and not restricted_modules[module][recipe] then
return false
end
end
return true
end
local function on_player_selected_area(e)
local status, err = pcall(function()
local player_index = e.player_index
if e.item ~= "module-inserter" or not player_index then return end
local player = game.get_player(player_index)
local pdata = global._pdata[player_index]
local config = pdata.config_by_entity
if not config then
player.print({"module-inserter-config-not-set"})
return
end
local ent_type, ent_name, target
local surface = player.surface
local delay = e.tick
local max_proxies = settings.global["module_inserter_proxies_per_tick"].value
local message = false
for i, entity in pairs(e.entities) do
ent_name = entity.name
--remove existing proxies if we have a config for it's target
if ent_name == "item-request-proxy" then
target = entity.proxy_target
if target and target.valid and config[target.name] then
entity.destroy{raise_destroy = true}
end
goto continue
end
local entity_configs = config[ent_name]
if not entity_configs then
goto continue
end
ent_type = entity.type
local recipe = ent_type == "assembling-machine" and entity.get_recipe()
recipe = recipe and recipe.name
local entity_config = nil
local cTable = nil
if recipe then
for _, e_config in pairs(entity_configs) do
if e_config.limitations then
if modules_allowed(recipe, e_config.cTable) then
entity_config = e_config
cTable = e_config.cTable
break
else
message = "item-limitation.production-module-usable-only-on-intermediates"
end
else
entity_config = e_config
cTable = e_config.cTable
break
end
end
else
entity_config = entity_configs[1]
cTable = entity_config.cTable
end
if entity_config then
if (i % max_proxies == 0) then
delay = delay + 1
end
if not global.to_create[delay] then global.to_create[delay] = {} end
global.to_create[delay][entity.unit_number] = {
entity = entity,
modules = table.shallow_copy(entity_config.to),
cTable = table.shallow_copy(cTable),
player = player,
surface = surface
}
end
::continue::
end
if message then
player.print({message})
end
conditional_events()
end)
if not status then
debugDump(err, true)
conditional_events(true)
end
end
local function on_player_alt_selected_area(e)
local status, err = pcall(function()
if not e.item == "module-inserter" then return end
for _, entity in pairs(e.entities) do
if entity.name == "item-request-proxy" then
entity.destroy{raise_destroy = true}
end
end
conditional_events()
end)
if not status then
debugDump(err, true)
conditional_events(true)
end
end
local function se_grounded_entity(name)
local result = name:sub(-9) == "-grounded" -- -#"grounded"
return result
end
local function create_lookup_tables()
global.nameToSlots = {}
global.module_entities = {}
local i = 1
for name, prototype in pairs(game.entity_prototypes) do
if prototype.module_inventory_size and prototype.module_inventory_size > 0 and not se_grounded_entity(name) then
global.nameToSlots[name] = prototype.module_inventory_size
global.module_entities[i] = name
i = i + 1
end
end
global.restricted_modules = {}
local limitations
for name, module in pairs(game.item_prototypes) do
if module.type == "module" then
limitations = module.limitations
if limitations and next(limitations) then
global.restricted_modules[name] = {}
for _, recipe in pairs(limitations) do
global.restricted_modules[name][recipe] = true
end
end
end
end
end
local function remove_invalid_items()
local items = game.item_prototypes
local entities = game.entity_prototypes
local removed_entities = {}
local removed_modules = {}
local function _remove(tbl)
for _, config in pairs(tbl) do
if (config.from or config.from == false) and not entities[config.from] then
removed_entities[config.from] = true
config.from = nil
config.to = {}
config.cTable = {}
end
config.limitations = nil
for k, m in pairs(config.to) do
if m and not items[m] then
config.to[k] = nil
config.cTable[m] = nil
removed_modules[config.from] = true
end
if global.restricted_modules[m] then
config.limitations = true
end
end
end
end
for _, pdata in pairs(global._pdata) do
_remove(pdata.config)
if pdata.config_tmp then
_remove(pdata.config_tmp)
end
for _, preset in pairs(pdata.storage) do
_remove(preset)
end
end
for k in pairs(removed_entities) do
log("Module Inserter: Removed configuration for " ..k)
end
for k in pairs(removed_modules) do
log("Module Inserter: Removed module " .. k .. " from all configurations")
end
end
local function init_global()
global.proxies = global.proxies or {}
global.to_create = global.to_create or {}
global.nameToSlots = global.nameToSlots or {}
global.restricted_modules = global.restricted_modules or {}
global._pdata = global._pdata or {}
end
local function init_player(i)
init_global()
local pdata = global._pdata[i] or {}
global._pdata[i] = {
last_preset = pdata.last_preset or "",
config = pdata.config or {},
storage = pdata.storage or {},
gui = pdata.gui or {},
}
mi_gui.update_main_button(game.get_player(i))
mi_gui.create(i)
end
local function init_players()
for i, _ in pairs(game.players) do
init_player(i)
end
end
event.on_init(function()
create_lookup_tables()
init_global()
init_players()
end)
event.on_load(function()
conditional_events()
end)
local migrations = {
["4.1.7"] = function()
global = {}
init_global()
init_players()
for _, player in pairs(game.players) do
if player.gui.left.mod_gui_frame_flow and player.gui.left.mod_gui_frame_flow.valid then
for _, egui in pairs(player.gui.left.mod_gui_frame_flow.children) do
if egui.get_mod() == "ModuleInserter" then
egui.destroy()
end
end
end
end
end,
["5.0.9"] = function()
init_players()
local gui_e, pdata
for i, _ in pairs(game.players) do
pdata = global._pdata[i]
gui_e = pdata.gui_elements
if gui_e then
if gui_e.config_frame and gui_e.config_frame.valid then
gui_e.config_frame.destroy()
end
if gui_e.preset_frame and gui_e.preset_frame.valid then
gui_e.preset_frame.destroy()
end
init_player(i)
pdata = global._pdata[i]
if gui_e.main_button and gui_e.main_button.valid then
gui_e.main_button.destroy()
end
end
pdata.last_preset = ""
local config_by_entity = {}
for _, config in pairs(pdata.config) do
if config.from then
config_by_entity[config.from] = config_by_entity[config.from] or {}
config_by_entity[config.from][table_size(config_by_entity[config.from])+1] = {to = config.to, cTable = config.cTable, limitations = config.limitations}
end
end
pdata.config_by_entity = config_by_entity
pdata.gui_elements = nil
pdata.gui_actions = nil
pdata.settings = nil
end
end,
["5.1.5"] = function()
local to_register = {}
for _, proxies in pairs(global.proxies) do
for _, data in pairs(proxies) do
if data.proxy and data.target then
if data.proxy.valid and table_size(data.cTable) > 1 then
script.register_on_entity_destroyed(data.proxy)
to_register[data.proxy.unit_number] = {modules = data.modules, cTable = data.cTable, target = data.target}
end
if not data.proxy.valid then
if data.target and data.target.valid then
sort_modules(data.target, data.modules, data.cTable)
end
end
end
end
end
event.on_tick(nil)
global.proxies = to_register
conditional_events(true)
end,
["5.1.7"] = function()
for id, data in pairs(global.proxies) do
if not (data.target and data.target.valid) then
global.proxies[id] = nil
end
end
end,
["5.1.8"] = function()
for pi, pdata in pairs(global._pdata) do
local player = game.get_player(pi)
if player and pdata.gui.main_button and pdata.gui.main_button.valid then
pdata.gui.main_button = nil
elseif not player then
global._pdata[pi] = nil
end
end
end,
["5.1.9"] = function()
for _, pdata in pairs(global._pdata) do
pdata.pinned = false
end
end,
["5.2.2"] = function()
for i, player in pairs(game.players) do
local pdata = global._pdata[i]
if pdata and pdata.gui then
pdata.gui.main_button = nil
end
local button_flow = mod_gui.get_button_flow(player)
local button = button_flow.module_inserter_config_button
if button then
gui.update_tags(button, {flib = {on_click = {gui = "mod_gui_button", action = "toggle"}}})
end
mi_gui.update_main_button(player)
end
end,
}
event.on_configuration_changed(function(e)
create_lookup_tables()
remove_invalid_items()
if migration.on_config_changed(e, migrations) then
for pi, pdata in pairs(global._pdata) do
mi_gui.destroy(pdata, game.get_player(pi))
mi_gui.create(pi)
end
end
conditional_events(true)
end)
event.on_player_selected_area(on_player_selected_area)
event.on_player_alt_selected_area(on_player_alt_selected_area)
gui.hook_events(function(e)
local msg = gui.read_action(e)
if msg then
e.player = game.get_player(e.player_index)
e.pdata = global._pdata[e.player_index]
local gui_handler = mi_gui.handlers[msg.gui]
local handler = gui_handler and gui_handler[msg.action]
if handler then
handler(e)
else
e.player.print("Unhandled gui event: " .. serpent.line(msg))
end
end
end)
event.on_player_created(function(e)
init_player(e.player_index)
end)
event.on_player_removed(function(e)
global._pdata[e.player_index] = nil
end)
event.on_runtime_mod_setting_changed(function(e)
if not e.player_index then return end
if e.setting == "module_inserter_button_style" or e.setting == "module_inserter_hide_button" then
mi_gui.update_main_button(game.get_player(e.player_index))
end
end)
event.on_entity_destroyed(function(e)
if e.unit_number and global.proxies[e.unit_number] then
local data = global.proxies[e.unit_number]
if data.target and data.target.valid then
sort_modules(data.target, data.modules, data.cTable)
end
global.proxies[e.unit_number] = nil
end
end)
-- event.on_player_cursor_stack_changed(function(e)
-- local player = game.get_player(e.player_index)
-- if player.cursor_stack.valid_for_read and player.cursor_stack.name == "module-inserter" then
-- global._pdata[e.player_index].cursor = true
-- elseif global._pdata[e.player_index].cursor then
-- global._pdata[e.player_index].cursor = false
-- local inv = player.get_main_inventory()
-- local count = inv.get_item_count("module-inserter")
-- if count > 1 then
-- inv.remove{name = "module-inserter", count = count - 1}
-- end
-- end
-- end)
commands.add_command("mi_clean", "", function()
for _, egui in pairs(game.player.gui.screen.children) do
if egui.get_mod() == "ModuleInserter" then
egui.destroy()
end
end
end)
|
fx_version 'cerulean'
game 'gta5'
description 'QB-Multicharacter'
version '1.0.0'
ui_page 'html/index.html'
shared_script '@qb-core/import.lua'
client_script 'client/main.lua'
server_script 'server/main.lua'
files {
'html/index.html',
'html/style.css',
'html/reset.css',
'html/script.js'
}
dependencies {
'qb-core',
'qb-spawn'
}
|
return {
['Ameilia'] = {
['BLU'] = {
['Club'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "realmrazer" <t>'
},
['Hand-to-Hand'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['ws_cmd'] = '/ws "Chant du Cygne" <t>'
},
['Sword'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Chant du Cygne" <t>'
}
},
['BRD'] = {
['Dagger'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '1000',
['ws_cmd'] = '/ws "Aeolian Edge" <t>'
}
},
['COR'] = {
['Dagger'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Last Stand" <t>'
},
['Sword'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Last Stand" <t>'
}
},
['DNC'] = {
['Dagger'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '999',
['ws_cmd'] = '/ws "Rudra\'s Storm" <t>'
}
},
['DRG'] = {
['Polearm'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "stardiver" <t>'
}
},
['DRK'] = {
['Great Sword'] = {
['hps'] = {
['<'] = 99,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '1000',
['ws_cmd'] = '/ws "Resolution" <t>'
},
['Scythe'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Crossreaper" <t>'
}
},
['GEO'] = {
['Club'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Realmrazer" <t>'
}
},
['MNK'] = {
['Hand-to-Hand'] = {
['hps'] = {
['<'] = 99,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '1000',
['ws_cmd'] = '/ws "Victory Smite" <t>'
}
},
['NIN'] = {
['Katana'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Blade: Shun" <t>'
}
},
['RNG'] = {
['Dagger'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '1250',
['ws_cmd'] = '/ws "Trueflight" <t>'
},
['Hand-to-Hand'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Trueflight" <t>'
}
},
['RUN'] = {
['Great Sword'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = '1500',
['ws_cmd'] = '/ws "Resolution" <t>'
}
},
['SAM'] = {
['Great Katana'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Tachi: Shoha" <t>'
}
},
['SMN'] = {
['Staff'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['ws_cmd'] = '/ws "Scourge" <t>'
}
},
['THF'] = {
['Dagger'] = {
['hps'] = {
['<'] = 100,
['>'] = 5
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Rudra\'s Storm" <t>'
}
},
['WAR'] = {
['Great Axe'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Upheaval" <t>'
},
['Great Sword'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['ws_cmd'] = '/ws "resolution" <t>'
},
['Hand-to-Hand'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['ws_cmd'] = '/ws "Scourge" <t>'
},
['Staff'] = {
['hps'] = {
['<'] = 100,
['>'] = 5
},
['mobs'] = {},
['ws_cmd'] = '/ws "Heavy Swing" <t>'
}
},
['WHM'] = {
['Club'] = {
['hps'] = {
['<'] = 50,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "Mystic Boon" <t>'
}
}
},
['Raffi'] = {
['COR'] = {
['Sword'] = {
['hps'] = {
['<'] = 100,
['>'] = 5
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "fast blade" <t>'
}
},
['WHM'] = {
['Club'] = {
['hps'] = {
['<'] = 100,
['>'] = 0
},
['mobs'] = {},
['tpThreshold'] = 999,
['ws_cmd'] = '/ws "judgment" <t>'
}
}
},
['hps'] = {
['<'] = 100,
['>'] = 5
}
}
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local enum = require("enum")
local utils = require("utils")
require("dcmp_variable_length_integer")
--
-- Compressed resource data in `'dcmp' (0)` format,
-- as stored in compressed resources with header type `8` and decompressor ID `0`.
--
-- The `'dcmp' (0)` decompressor resource is included in the System file of System 7.0 and later.
-- This compression format is used for most compressed resources in System 7.0's files.
-- This decompressor is also included with and used by some other Apple applications,
-- such as ResEdit.
--
-- This compression format supports some basic general-purpose compression schemes,
-- including backreferences to previous data,
-- run-length encoding,
-- and delta encoding.
-- It also includes some types of compression tailored specifically to Mac OS resources,
-- including a set of single-byte codes that correspond to entries in a hard-coded lookup table,
-- and a specialized kind of delta encoding for segment loader jump tables.
--
-- Almost all parts of this compression format operate on units of 2 or 4 bytes.
-- As a result,
-- it is nearly impossible to store data with an odd length in this format.
-- To work around this limitation,
-- odd-length resources are padded with an extra byte before compressing them with this format.
-- This extra byte is ignored after decompression,
-- as the real (odd) length of the resource is stored in the compressed resource header.
--
-- The `'dcmp' (1)` compression format (see dcmp_1.ksy) is very similar to this format,
-- with the main difference that it operates mostly on single bytes rather than two-byte units.
-- See also: Source (https://github.com/dgelessus/python-rsrcfork/tree/master/rsrcfork/compress/dcmp0.py)
Dcmp0 = class.class(KaitaiStruct)
function Dcmp0:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0:_read()
self.chunks = {}
local i = 0
while true do
_ = Dcmp0.Chunk(self._io, self, self._root)
self.chunks[i + 1] = _
if _.tag == 255 then
break
end
i = i + 1
end
end
--
-- The sequence of chunks that make up the compressed data.
--
-- A single chunk of compressed data.
-- Each chunk in the compressed data expands to a sequence of bytes in the uncompressed data,
-- except when `tag == 0xff`,
-- which marks the end of the data and does not correspond to any bytes in the uncompressed data.
--
-- Most chunks are stateless and always expand to the same data,
-- regardless of where the chunk appears in the sequence.
-- However,
-- some chunks affect the behavior of future chunks,
-- or expand to different data depending on which chunks came before them.
Dcmp0.Chunk = class.class(KaitaiStruct)
Dcmp0.Chunk.TagKind = enum.Enum {
invalid = -1,
literal = 0,
backreference = 1,
table_lookup = 2,
extended = 3,
end = 4,
}
function Dcmp0.Chunk:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk:_read()
self.tag = self._io:read_u1()
local _on = utils.box_unwrap(( ((self.tag >= 0) and (self.tag <= 31)) ) and utils.box_wrap(Dcmp0.Chunk.TagKind.literal) or (utils.box_unwrap(( ((self.tag >= 32) and (self.tag <= 74)) ) and utils.box_wrap(Dcmp0.Chunk.TagKind.backreference) or (utils.box_unwrap(( ((self.tag >= 75) and (self.tag <= 253)) ) and utils.box_wrap(Dcmp0.Chunk.TagKind.table_lookup) or (utils.box_unwrap((self.tag == 254) and utils.box_wrap(Dcmp0.Chunk.TagKind.extended) or (utils.box_unwrap((self.tag == 255) and utils.box_wrap(Dcmp0.Chunk.TagKind.end) or (Dcmp0.Chunk.TagKind.invalid))))))))))
if _on == Dcmp0.Chunk.TagKind.extended then
self.body = Dcmp0.Chunk.ExtendedBody(self._io, self, self._root)
elseif _on == Dcmp0.Chunk.TagKind.literal then
self.body = Dcmp0.Chunk.LiteralBody(self.tag, self._io, self, self._root)
elseif _on == Dcmp0.Chunk.TagKind.end then
self.body = Dcmp0.Chunk.EndBody(self._io, self, self._root)
elseif _on == Dcmp0.Chunk.TagKind.table_lookup then
self.body = Dcmp0.Chunk.TableLookupBody(self.tag, self._io, self, self._root)
elseif _on == Dcmp0.Chunk.TagKind.backreference then
self.body = Dcmp0.Chunk.BackreferenceBody(self.tag, self._io, self, self._root)
end
end
--
-- The chunk's tag byte.
-- This controls the structure of the body and the meaning of the chunk.
--
-- The chunk's body.
--
-- Certain chunks do not have any data following the tag byte.
-- In this case,
-- the body is a zero-length structure.
--
-- The body of a literal data chunk.
--
-- The data that this chunk expands to is stored literally in the body (`literal`).
-- Optionally,
-- the literal data may also be stored for use by future backreference chunks (`do_store`).
--
-- The length of the literal data is stored as a number of two-byte units.
-- This means that the literal data always has an even length in bytes.
Dcmp0.Chunk.LiteralBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.LiteralBody:_init(tag, io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self.tag = tag
self:_read()
end
function Dcmp0.Chunk.LiteralBody:_read()
if self.is_len_literal_div2_separate then
self.len_literal_div2_separate = self._io:read_u1()
end
self.literal = self._io:read_bytes(self.len_literal)
end
--
-- Whether this literal should be stored for use by future backreference chunks.
--
-- See the documentation of the `backreference_body` type for details about backreference chunks.
Dcmp0.Chunk.LiteralBody.property.do_store = {}
function Dcmp0.Chunk.LiteralBody.property.do_store:get()
if self._m_do_store ~= nil then
return self._m_do_store
end
self._m_do_store = (self.tag & 16) ~= 0
return self._m_do_store
end
--
-- The length of the literal data,
-- in two-byte units.
--
-- In practice,
-- this value is always greater than zero,
-- as there is no use in storing a zero-length literal.
Dcmp0.Chunk.LiteralBody.property.len_literal_div2 = {}
function Dcmp0.Chunk.LiteralBody.property.len_literal_div2:get()
if self._m_len_literal_div2 ~= nil then
return self._m_len_literal_div2
end
self._m_len_literal_div2 = utils.box_unwrap((self.is_len_literal_div2_separate) and utils.box_wrap(self.len_literal_div2_separate) or (self.len_literal_div2_in_tag))
return self._m_len_literal_div2
end
--
-- The length of the literal data,
-- in bytes.
Dcmp0.Chunk.LiteralBody.property.len_literal = {}
function Dcmp0.Chunk.LiteralBody.property.len_literal:get()
if self._m_len_literal ~= nil then
return self._m_len_literal
end
self._m_len_literal = (self.len_literal_div2 * 2)
return self._m_len_literal
end
--
-- The part of the tag byte that indicates the length of the literal data,
-- in two-byte units.
-- If this value is 0,
-- the length is stored in a separate byte after the tag byte and before the literal data.
Dcmp0.Chunk.LiteralBody.property.len_literal_div2_in_tag = {}
function Dcmp0.Chunk.LiteralBody.property.len_literal_div2_in_tag:get()
if self._m_len_literal_div2_in_tag ~= nil then
return self._m_len_literal_div2_in_tag
end
self._m_len_literal_div2_in_tag = (self.tag & 15)
return self._m_len_literal_div2_in_tag
end
--
-- Whether the length of the literal is stored separately from the tag.
Dcmp0.Chunk.LiteralBody.property.is_len_literal_div2_separate = {}
function Dcmp0.Chunk.LiteralBody.property.is_len_literal_div2_separate:get()
if self._m_is_len_literal_div2_separate ~= nil then
return self._m_is_len_literal_div2_separate
end
self._m_is_len_literal_div2_separate = self.len_literal_div2_in_tag == 0
return self._m_is_len_literal_div2_separate
end
--
-- The length of the literal data,
-- in two-byte units.
--
-- This field is only present if the tag byte's low nibble is zero.
-- In practice,
-- this only happens if the length is 0x10 or greater,
-- because smaller lengths can be encoded into the tag byte.
--
-- The literal data.
--
-- The tag byte preceding this chunk body.
--
-- The body of a backreference chunk.
--
-- This chunk expands to the data stored in a preceding literal chunk,
-- indicated by an index number (`index`).
Dcmp0.Chunk.BackreferenceBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.BackreferenceBody:_init(tag, io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self.tag = tag
self:_read()
end
function Dcmp0.Chunk.BackreferenceBody:_read()
if self.is_index_separate then
local _on = self.tag
if _on == 32 then
self.index_separate_minus = self._io:read_u1()
elseif _on == 33 then
self.index_separate_minus = self._io:read_u1()
elseif _on == 34 then
self.index_separate_minus = self._io:read_u2be()
end
end
end
--
-- Whether the index is stored separately from the tag.
Dcmp0.Chunk.BackreferenceBody.property.is_index_separate = {}
function Dcmp0.Chunk.BackreferenceBody.property.is_index_separate:get()
if self._m_is_index_separate ~= nil then
return self._m_is_index_separate
end
self._m_is_index_separate = ((self.tag >= 32) and (self.tag <= 34))
return self._m_is_index_separate
end
--
-- The index of the referenced literal chunk,
-- as stored in the tag byte.
Dcmp0.Chunk.BackreferenceBody.property.index_in_tag = {}
function Dcmp0.Chunk.BackreferenceBody.property.index_in_tag:get()
if self._m_index_in_tag ~= nil then
return self._m_index_in_tag
end
self._m_index_in_tag = (self.tag - 35)
return self._m_index_in_tag
end
--
-- The index of the referenced literal chunk,
-- as stored separately from the tag byte,
-- with the implicit offset corrected for.
Dcmp0.Chunk.BackreferenceBody.property.index_separate = {}
function Dcmp0.Chunk.BackreferenceBody.property.index_separate:get()
if self._m_index_separate ~= nil then
return self._m_index_separate
end
if self.is_index_separate then
self._m_index_separate = ((self.index_separate_minus + 40) + utils.box_unwrap((self.tag == 33) and utils.box_wrap(256) or (0)))
end
return self._m_index_separate
end
--
-- The index of the referenced literal chunk.
--
-- Stored literals are assigned index numbers in the order in which they appear in the compressed data,
-- starting at 0.
-- Non-stored literals are not counted in the numbering and cannot be referenced using backreferences.
-- Once an index is assigned to a stored literal,
-- it is never changed or unassigned for the entire length of the compressed data.
--
-- As the name indicates,
-- a backreference can only reference stored literal chunks found *before* the backreference,
-- not ones that come after it.
Dcmp0.Chunk.BackreferenceBody.property.index = {}
function Dcmp0.Chunk.BackreferenceBody.property.index:get()
if self._m_index ~= nil then
return self._m_index
end
self._m_index = utils.box_unwrap((self.is_index_separate) and utils.box_wrap(self.index_separate) or (self.index_in_tag))
return self._m_index
end
--
-- The index of the referenced literal chunk,
-- stored separately from the tag.
-- The value in this field is stored minus 0x28.
-- If the tag byte is 0x21,
-- the value is also stored minus 0x100,
-- *on top of* the regular offset
-- (i. e. minus 0x128 in total).
--
-- In other words,
-- for tag bytes 0x20 and 0x21,
-- the index is actually 9 bits large,
-- with the low 8 bits stored separately and the highest bit stored in the lowest bit of the tag byte.
--
-- This field is only present if the tag byte is 0x20 through 0x22.
-- For higher tag bytes,
-- the index is encoded in the tag byte.
-- Values smaller than 0x28 cannot be stored in this field,
-- they must always be encoded in the tag byte.
--
-- The tag byte preceding this chunk body.
--
-- The body of a table lookup chunk.
-- This body is always empty.
--
-- This chunk always expands to two bytes (`value`),
-- determined from the tag byte using a fixed lookup table (`lookup_table`).
-- This lookup table is hardcoded in the decompressor and always the same for all compressed data.
Dcmp0.Chunk.TableLookupBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.TableLookupBody:_init(tag, io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self.tag = tag
self:_read()
end
function Dcmp0.Chunk.TableLookupBody:_read()
end
--
-- Fixed lookup table that maps tag byte numbers to two bytes each.
--
-- The entries in the lookup table are offset -
-- index 0 stands for tag 0x4b, 1 for 0x4c, etc.
Dcmp0.Chunk.TableLookupBody.property.lookup_table = {}
function Dcmp0.Chunk.TableLookupBody.property.lookup_table:get()
if self._m_lookup_table ~= nil then
return self._m_lookup_table
end
self._m_lookup_table = {"\000\000", "\078\186", "\000\008", "\078\117", "\000\012", "\078\173", "\032\083", "\047\011", "\097\000", "\000\016", "\112\000", "\047\000", "\072\110", "\032\080", "\032\110", "\047\046", "\255\252", "\072\231", "\063\060", "\000\004", "\255\248", "\047\012", "\032\006", "\078\237", "\078\086", "\032\104", "\078\094", "\000\001", "\088\143", "\079\239", "\000\002", "\000\024", "\096\000", "\255\255", "\080\143", "\078\144", "\000\006", "\038\110", "\000\020", "\255\244", "\076\238", "\000\010", "\000\014", "\065\238", "\076\223", "\072\192", "\255\240", "\045\064", "\000\018", "\048\046", "\112\001", "\047\040", "\032\084", "\103\000", "\000\032", "\000\028", "\032\095", "\024\000", "\038\111", "\072\120", "\000\022", "\065\250", "\048\060", "\040\064", "\114\000", "\040\110", "\032\012", "\102\000", "\032\107", "\047\007", "\085\143", "\000\040", "\255\254", "\255\236", "\034\216", "\032\011", "\000\015", "\089\143", "\047\060", "\255\000", "\001\024", "\129\225", "\074\000", "\078\176", "\255\232", "\072\199", "\000\003", "\000\034", "\000\007", "\000\026", "\103\006", "\103\008", "\078\249", "\000\036", "\032\120", "\008\000", "\102\004", "\000\042", "\078\208", "\048\040", "\038\095", "\103\004", "\000\048", "\067\238", "\063\000", "\032\031", "\000\030", "\255\246", "\032\046", "\066\167", "\032\007", "\255\250", "\096\002", "\061\064", "\012\064", "\102\006", "\000\038", "\045\072", "\047\001", "\112\255", "\096\004", "\024\128", "\074\064", "\000\064", "\000\044", "\047\008", "\000\017", "\255\228", "\033\064", "\038\064", "\255\242", "\066\110", "\078\185", "\061\124", "\000\056", "\000\013", "\096\006", "\066\046", "\032\060", "\103\012", "\045\104", "\102\008", "\074\046", "\074\174", "\000\046", "\072\064", "\034\095", "\034\000", "\103\010", "\048\007", "\066\103", "\000\050", "\032\040", "\000\009", "\072\122", "\002\000", "\047\043", "\000\005", "\034\110", "\102\002", "\229\128", "\103\014", "\102\010", "\000\080", "\062\000", "\102\012", "\046\000", "\255\238", "\032\109", "\032\064", "\255\224", "\083\064", "\096\008", "\004\128", "\000\104", "\011\124", "\068\000", "\065\232", "\072\065"}
return self._m_lookup_table
end
--
-- The two bytes that the tag byte expands to,
-- based on the fixed lookup table.
Dcmp0.Chunk.TableLookupBody.property.value = {}
function Dcmp0.Chunk.TableLookupBody.property.value:get()
if self._m_value ~= nil then
return self._m_value
end
self._m_value = self.lookup_table[(self.tag - 75) + 1]
return self._m_value
end
--
-- The tag byte preceding this chunk body.
--
-- The body of an end chunk.
-- This body is always empty.
--
-- The last chunk in the compressed data must always be an end chunk.
-- An end chunk cannot appear elsewhere in the compressed data.
Dcmp0.Chunk.EndBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.EndBody:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk.EndBody:_read()
end
--
-- The body of an extended chunk.
-- The meaning of this chunk depends on the extended tag byte stored in the chunk data.
Dcmp0.Chunk.ExtendedBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.ExtendedBody:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk.ExtendedBody:_read()
self.tag = self._io:read_u1()
local _on = self.tag
if _on == 0 then
self.body = Dcmp0.Chunk.ExtendedBody.JumpTableBody(self._io, self, self._root)
elseif _on == 4 then
self.body = Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody(self._io, self, self._root)
elseif _on == 6 then
self.body = Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody(self._io, self, self._root)
elseif _on == 3 then
self.body = Dcmp0.Chunk.ExtendedBody.RepeatBody(self.tag, self._io, self, self._root)
elseif _on == 2 then
self.body = Dcmp0.Chunk.ExtendedBody.RepeatBody(self.tag, self._io, self, self._root)
end
end
--
-- The chunk's extended tag byte.
-- This controls the structure of the body and the meaning of the chunk.
--
-- The chunk's body.
--
-- The body of a jump table chunk.
--
-- This chunk generates parts of a segment loader jump table,
-- in the format found in `'CODE' (0)` resources.
-- It expands to the following data,
-- with all non-constant numbers encoded as unsigned 16-bit big-endian integers:
--
-- * `0x3f 0x3c` (push following segment number onto stack)
-- * The segment number
-- * `0xa9 0xf0` (`_LoadSeg` trap)
-- * For each address:
-- * The address
-- * `0x3f 0x3c` (push following segment number onto stack)
-- * The segment number
-- * `0xa9 0xf0` (`_LoadSeg` trap)
--
-- Note that this generates one jump table entry without an address before it,
-- meaning that this address needs to be generated by the preceding chunk.
-- All following jump table entries are generated with the addresses encoded in this chunk.
Dcmp0.Chunk.ExtendedBody.JumpTableBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.ExtendedBody.JumpTableBody:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk.ExtendedBody.JumpTableBody:_read()
self.segment_number_raw = DcmpVariableLengthInteger(self._io)
self.num_addresses_raw = DcmpVariableLengthInteger(self._io)
self.addresses_raw = {}
for i = 0, self.num_addresses - 1 do
self.addresses_raw[i + 1] = DcmpVariableLengthInteger(self._io)
end
end
--
-- The segment number for all of the generated jump table entries.
--
-- Although it is stored as a variable-length integer,
-- the segment number must be in the range `0x0 <= x <= 0xffff`,
-- i. e. an unsigned 16-bit integer.
Dcmp0.Chunk.ExtendedBody.JumpTableBody.property.segment_number = {}
function Dcmp0.Chunk.ExtendedBody.JumpTableBody.property.segment_number:get()
if self._m_segment_number ~= nil then
return self._m_segment_number
end
self._m_segment_number = self.segment_number_raw.value
return self._m_segment_number
end
--
-- The number of addresses stored in this chunk.
--
-- This number must be greater than 0.
Dcmp0.Chunk.ExtendedBody.JumpTableBody.property.num_addresses = {}
function Dcmp0.Chunk.ExtendedBody.JumpTableBody.property.num_addresses:get()
if self._m_num_addresses ~= nil then
return self._m_num_addresses
end
self._m_num_addresses = self.num_addresses_raw.value
return self._m_num_addresses
end
--
-- Raw variable-length integer representation of `segment_number`.
--
-- Raw variable-length integer representation of `num_addresses`.
--
-- The addresses for each generated jump table entry,
-- stored as variable-length integers.
--
-- The first address is stored literally and must be in the range `0x0 <= x <= 0xffff`,
-- i. e. an unsigned 16-bit integer.
--
-- All following addresses are stored as deltas relative to the previous address.
-- Each of these deltas is stored plus 6;
-- this value needs to be subtracted before (or after) adding it to the previous address.
--
-- Each delta (after subtracting 6) should be positive,
-- and adding it to the previous address should not result in a value larger than `0xffff`,
-- i. e. there should be no 16-bit unsigned integer wraparound.
-- These conditions are always met in all known jump table chunks,
-- so it is not known how the original decompressor behaves otherwise.
--
-- The body of a repeat chunk.
--
-- This chunk expands to a 1-byte or 2-byte value repeated a number of times,
-- i. e. it implements a form of run-length encoding.
Dcmp0.Chunk.ExtendedBody.RepeatBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.ExtendedBody.RepeatBody:_init(tag, io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self.tag = tag
self:_read()
end
function Dcmp0.Chunk.ExtendedBody.RepeatBody:_read()
self.to_repeat_raw = DcmpVariableLengthInteger(self._io)
self.repeat_count_m1_raw = DcmpVariableLengthInteger(self._io)
end
--
-- The length in bytes of the value to be repeated.
-- Regardless of the byte count,
-- the value to be repeated is stored as a variable-length integer.
Dcmp0.Chunk.ExtendedBody.RepeatBody.property.byte_count = {}
function Dcmp0.Chunk.ExtendedBody.RepeatBody.property.byte_count:get()
if self._m_byte_count ~= nil then
return self._m_byte_count
end
self._m_byte_count = utils.box_unwrap((self.tag == 2) and utils.box_wrap(1) or (utils.box_unwrap((self.tag == 3) and utils.box_wrap(2) or (-1))))
return self._m_byte_count
end
--
-- The value to repeat.
--
-- Although it is stored as a variable-length integer,
-- this value must fit into an unsigned big-endian integer that is as long as `byte_count`,
-- i. e. either 8 or 16 bits.
Dcmp0.Chunk.ExtendedBody.RepeatBody.property.to_repeat = {}
function Dcmp0.Chunk.ExtendedBody.RepeatBody.property.to_repeat:get()
if self._m_to_repeat ~= nil then
return self._m_to_repeat
end
self._m_to_repeat = self.to_repeat_raw.value
return self._m_to_repeat
end
--
-- The number of times to repeat the value,
-- minus one.
--
-- This value must not be negative.
Dcmp0.Chunk.ExtendedBody.RepeatBody.property.repeat_count_m1 = {}
function Dcmp0.Chunk.ExtendedBody.RepeatBody.property.repeat_count_m1:get()
if self._m_repeat_count_m1 ~= nil then
return self._m_repeat_count_m1
end
self._m_repeat_count_m1 = self.repeat_count_m1_raw.value
return self._m_repeat_count_m1
end
--
-- The number of times to repeat the value.
--
-- This value must be positive.
Dcmp0.Chunk.ExtendedBody.RepeatBody.property.repeat_count = {}
function Dcmp0.Chunk.ExtendedBody.RepeatBody.property.repeat_count:get()
if self._m_repeat_count ~= nil then
return self._m_repeat_count
end
self._m_repeat_count = (self.repeat_count_m1 + 1)
return self._m_repeat_count
end
--
-- Raw variable-length integer representation of `to_repeat`.
--
-- Raw variable-length integer representation of `repeat_count_m1`.
--
-- The extended tag byte preceding this chunk body.
--
-- The body of a 16-bit delta encoding chunk.
--
-- This chunk expands to a sequence of 16-bit big-endian integer values.
-- The first value is stored literally.
-- All following values are stored as deltas relative to the previous value.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody:_read()
self.first_value_raw = DcmpVariableLengthInteger(self._io)
self.num_deltas_raw = DcmpVariableLengthInteger(self._io)
self.deltas = {}
for i = 0, self.num_deltas - 1 do
self.deltas[i + 1] = self._io:read_s1()
end
end
--
-- The first value in the sequence.
--
-- Although it is stored as a variable-length integer,
-- this value must be in the range `-0x8000 <= x <= 0x7fff`,
-- i. e. a signed 16-bit integer.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody.property.first_value = {}
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody.property.first_value:get()
if self._m_first_value ~= nil then
return self._m_first_value
end
self._m_first_value = self.first_value_raw.value
return self._m_first_value
end
--
-- The number of deltas stored in this chunk.
--
-- This number must not be negative.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody.property.num_deltas = {}
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding16BitBody.property.num_deltas:get()
if self._m_num_deltas ~= nil then
return self._m_num_deltas
end
self._m_num_deltas = self.num_deltas_raw.value
return self._m_num_deltas
end
--
-- Raw variable-length integer representation of `first_value`.
--
-- Raw variable-length integer representation of `num_deltas`.
--
-- The deltas for each value relative to the previous value.
--
-- Each of these deltas is a signed 8-bit value.
-- When adding the delta to the previous value,
-- 16-bit integer wraparound is performed if necessary,
-- so that the resulting value always fits into a 16-bit signed integer.
--
-- The body of a 32-bit delta encoding chunk.
--
-- This chunk expands to a sequence of 32-bit big-endian integer values.
-- The first value is stored literally.
-- All following values are stored as deltas relative to the previous value.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody = class.class(KaitaiStruct)
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody:_read()
self.first_value_raw = DcmpVariableLengthInteger(self._io)
self.num_deltas_raw = DcmpVariableLengthInteger(self._io)
self.deltas_raw = {}
for i = 0, self.num_deltas - 1 do
self.deltas_raw[i + 1] = DcmpVariableLengthInteger(self._io)
end
end
--
-- The first value in the sequence.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody.property.first_value = {}
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody.property.first_value:get()
if self._m_first_value ~= nil then
return self._m_first_value
end
self._m_first_value = self.first_value_raw.value
return self._m_first_value
end
--
-- The number of deltas stored in this chunk.
--
-- This number must not be negative.
Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody.property.num_deltas = {}
function Dcmp0.Chunk.ExtendedBody.DeltaEncoding32BitBody.property.num_deltas:get()
if self._m_num_deltas ~= nil then
return self._m_num_deltas
end
self._m_num_deltas = self.num_deltas_raw.value
return self._m_num_deltas
end
--
-- Raw variable-length integer representation of `first_value`.
--
-- Raw variable-length integer representation of `num_deltas`.
--
-- The deltas for each value relative to the previous value,
-- stored as variable-length integers.
--
-- Each of these deltas is a signed value.
-- When adding the delta to the previous value,
-- 32-bit integer wraparound is performed if necessary,
-- so that the resulting value always fits into a 32-bit signed integer.
|
LARGURA_TELA = 320
ALTURA_TELA = 480
MAX_METEOROS = 12
FIM_JOGO = false
METEOROS_ATINGIDOS = 0
NUMERO_METEOROS_OBJETIVO = 100
aviao_14bis = {
src = "imagens/14bis.png",
largura = 55,
altura = 63,
x = LARGURA_TELA/2 - 64/2,
y = ALTURA_TELA - 64/2,
tiros = {}
}
meteoros = {}
function daTiro()
disparo:play()
local tiro = {
x = aviao_14bis.x + aviao_14bis.largura/2,
y = aviao_14bis.y,
largura = 16,
altura = 16
}
table.insert(aviao_14bis.tiros, tiro)
end
function moveTiros()
for i = #aviao_14bis.tiros, 1, -1 do
if aviao_14bis.tiros[i].y > 0 then
aviao_14bis.tiros[i].y = aviao_14bis.tiros[i].y - 1
else
table.remove(aviao_14bis.tiros, i)
end
end
end
function destroiAviao()
destruicao:play()
aviao_14bis.src = "imagens/explosao_nave.png"
aviao_14bis.imagem = love.graphics.newImage(aviao_14bis.src)
aviao_14bis.largura = 67
aviao_14bis.altura = 77
end
function temColisao(X1, Y1, L1, A1, X2, Y2, L2, A2)
return X2 < X1 + L1 and
X1 < X2 + L2 and
Y1 < Y2 + A2 and
Y2 < Y1 + A1
end
function removeMeteoros()
for i = #meteoros, 1, -1 do
if meteoros[i].y > ALTURA_TELA then
table.remove(meteoros, i)
end
end
end
function criaMeteoro()
meteoro = {
x = math.random(LARGURA_TELA),
y = -70,
largura = 50,
altura = 44,
peso = math.random(3),
deslocamento_horizontal = math.random(-1, 1)
}
table.insert(meteoros, meteoro)
end
function moveMeteoros()
for k, meteoro in pairs(meteoros) do
meteoro.y = meteoro.y + meteoro.peso
meteoro.x = meteoro.x + meteoro.deslocamento_horizontal
end
end
function move14bis()
if love.keyboard.isDown('w') then
aviao_14bis.y = aviao_14bis.y - 1
end
if love.keyboard.isDown('s') then
aviao_14bis.y = aviao_14bis.y + 1
end
if love.keyboard.isDown('a') then
aviao_14bis.x = aviao_14bis.x - 1
end
if love.keyboard.isDown('d') then
aviao_14bis.x = aviao_14bis.x + 1
end
end
function trocaMusicaDeFundo()
musica_ambiente:stop()
game_over:play()
end
function checaColisaoComAviao()
for k, meteoro in pairs(meteoros) do
if temColisao(meteoro.x, meteoro.y, meteoro.largura, meteoro.altura,
aviao_14bis.x, aviao_14bis.y, aviao_14bis.largura, aviao_14bis.altura) then
trocaMusicaDeFundo()
destroiAviao()
FIM_JOGO = true
end
end
end
function checaColisaoComTiros()
for i = #aviao_14bis.tiros, 1, -1 do
for j = #meteoros, 1, -1 do
if temColisao(aviao_14bis.tiros[i].x, aviao_14bis.tiros[i].y, aviao_14bis.tiros[i].largura, aviao_14bis.tiros[i].altura,
meteoros[j].x, meteoros[j].y, meteoros[j].largura, meteoros[j].altura) then
METEOROS_ATINGIDOS = METEOROS_ATINGIDOS + 1
table.remove(aviao_14bis.tiros, i)
table.remove(meteoros, j)
break
end
end
end
end
function checaColisoes()
checaColisaoComAviao()
checaColisaoComTiros()
end
function checaObjetivoConcluido()
if METEOROS_ATINGIDOS >= NUMERO_METEOROS_OBJETIVO then
VENCEDOR = true
musica_ambiente:stop()
vencedor_som:play()
end
end
function love.load()
love.window.setMode(LARGURA_TELA, ALTURA_TELA, {resizable = false})
love.window.setTitle("14bis vs Meteoros")
math.randomseed(os.time())
background = love.graphics.newImage("imagens/background.png")
gameover_img = love.graphics.newImage("imagens/gameover.png")
vencedor_img = love.graphics.newImage("imagens/vencedor.png")
aviao_14bis.imagem = love.graphics.newImage(aviao_14bis.src)
meteoro_img = love.graphics.newImage("imagens/meteoro.png")
tiro_img = love.graphics.newImage("imagens/tiro.png")
musica_ambiente = love.audio.newSource("audios/ambiente.wav", "static")
musica_ambiente:setLooping(true)
musica_ambiente:play()
destruicao = love.audio.newSource("audios/destruicao.wav", "static")
game_over = love.audio.newSource("audios/game_over.wav", "static")
vencedor_som = love.audio.newSource("audios/winner.wav", "static")
disparo = love.audio.newSource("audios/disparo.wav", "static")
end
function love.update(dt)
if not FIM_JOGO and not VENCEDOR then
if love.keyboard.isDown('w', 'a', 's', 'd') then
move14bis()
end
removeMeteoros()
if #meteoros < MAX_METEOROS then
criaMeteoro()
end
moveMeteoros()
moveTiros()
checaColisoes()
checaObjetivoConcluido()
end
end
function love.keypressed(tecla)
if tecla == "escape" then
love.event.quit()
elseif tecla == "space" then
daTiro()
end
end
function love.draw()
love.graphics.draw(background, 0, 0)
love.graphics.draw(aviao_14bis.imagem, aviao_14bis.x, aviao_14bis.y)
love.graphics.print("Meteoros restantes "..NUMERO_METEOROS_OBJETIVO - METEOROS_ATINGIDOS, 0, 0)
for k, meteoro in pairs(meteoros) do
love.graphics.draw(meteoro_img, meteoro.x, meteoro.y)
end
for k, tiro in pairs(aviao_14bis.tiros) do
love.graphics.draw(tiro_img, tiro.x, tiro.y)
end
if FIM_JOGO then
love.graphics.draw(gameover_img, LARGURA_TELA/2 - gameover_img:getWidth()/2,
ALTURA_TELA/2 - gameover_img:getHeight()/2)
end
if VENCEDOR then
love.graphics.draw(vencedor_img, LARGURA_TELA/2 - vencedor_img:getWidth()/2,
ALTURA_TELA/2 - vencedor_img:getHeight()/2)
end
end
|
-- luahs, Lua bindings to hyperscan
-- Copyright (C) 2016 Boris Nagaev
-- See the LICENSE file for terms of use.
local luahs = require 'luahs'
describe("compilation", function()
it("compiles simple pattern", function()
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
it("current platform", function()
local platform = luahs.currentPlatform()
assert.truthy(platform.tune)
assert.truthy(platform.cpu_features)
end)
it("specify platform", function()
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = {
tune = luahs.cpu_tuning.HS_TUNE_FAMILY_GENERIC,
},
}
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = {
tune = {
luahs.cpu_tuning.HS_TUNE_FAMILY_GENERIC,
luahs.cpu_tuning.HS_TUNE_FAMILY_SNB,
},
},
}
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = luahs.currentPlatform(),
}
end)
it("throws on incorrect platform structure", function()
assert.has_error(function()
luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = {
tune = 'generic',
},
}
end)
assert.has_error(function()
luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = {
cpu_features = 'generic',
},
}
end)
end)
it("specify flags", function()
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
flags = luahs.pattern_flags.HS_FLAG_CASELESS,
}
end)
it("specify flags as list", function()
local db = luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
flags = {
luahs.pattern_flags.HS_FLAG_CASELESS,
luahs.pattern_flags.HS_FLAG_DOTALL,
},
}
end)
it("specify multiple modes", function()
local db = luahs.compile {
expression = 'aaa',
mode = {
luahs.compile_mode.HS_MODE_STREAM,
luahs.compile_mode.HS_MODE_SOM_HORIZON_LARGE,
},
flags = HS_FLAG_SOM_LEFTMOST,
}
end)
it("compiles multiple patterns", function()
local db = luahs.compile {
expressions = {
'aaa',
'bbb',
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
it("compiles multiple patterns with parameters", function()
local db = luahs.compile {
expressions = {
'aaa',
{
expression = 'bbb',
id = 42,
flags = luahs.pattern_flags.HS_FLAG_CASELESS,
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
it("compiles multiple patterns with multiple flags", function()
local db = luahs.compile {
expressions = {
'aaa',
{
expression = 'bbb',
id = 42,
flags = {
luahs.pattern_flags.HS_FLAG_CASELESS,
luahs.pattern_flags.HS_FLAG_DOTALL,
},
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
it("compiles multiple patterns with extended flags", function()
local db = luahs.compile {
expressions = {
'aaa',
{
expression = 'bbb',
min_offset = 100,
max_offset = 140,
min_length = 1,
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
it("get information about RE", function()
local info = luahs.expressionInfo('aaa?')
assert.equal(2, info.min_width)
assert.equal(3, info.max_width)
end)
it("get information about RE (max_width is inf)", function()
local info = luahs.expressionInfo('aaa*')
assert.equal(2, info.min_width)
assert.equal(luahs.UINT_MAX, info.max_width)
end)
it("get information about RE with flags as integer",
function()
local info = luahs.expressionInfo(
'a?a?a?',
luahs.pattern_flags.HS_FLAG_ALLOWEMPTY
)
assert.equal(0, info.min_width)
assert.equal(3, info.max_width)
end)
it("get information about RE with flags as table",
function()
local info = luahs.expressionInfo(
'a?a?a?',
{luahs.pattern_flags.HS_FLAG_ALLOWEMPTY}
)
assert.equal(0, info.min_width)
assert.equal(3, info.max_width)
end)
it("expressionInfo throws on bad flags", function()
assert.has_error(function()
luahs.expressionInfo('aaa', 'allow_empty')
end)
end)
it("expressionInfo throws on bad pattern", function()
assert.has_error(function()
luahs.expressionInfo('[')
end)
end)
it("throws on bad arguments", function()
assert.has_error(function()
luahs.compile()
end)
assert.has_error(function()
luahs.compile({})
end)
assert.has_error(function()
luahs.compile({expression='aaa'})
end)
assert.has_error(function()
luahs.compile({expression='aaa', mode=42})
end)
assert.has_error(function()
luahs.compile({expression='aaa', mode='block'})
end)
assert.has_error(function()
luahs.compile {
expression = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
platform = 'foo',
}
end)
assert.has_error(function()
luahs.compile {
expressions = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expression = {
'aaa',
'bbb',
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
123,
456,
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{
expression = 'aaa',
flags = 'caseless',
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{
expression = 'aaa',
flags = 10000001,
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{
expression = 'aaa',
id = '',
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{
expression = 'aaa',
min_length = '',
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expressions = {
{
expression = 'aaa',
min_length = 4,
},
},
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
assert.has_error(function()
luahs.compile {
expression = 'aaa',
flags = 'aaa',
mode = luahs.compile_mode.HS_MODE_BLOCK,
}
end)
end)
end)
|
Textbox = {}
Textbox.__index = Textbox
function Textbox:Create(params)
params = params or {}
if type(params.text) == "string" then
params.text = {params.text}
end
local this =
{
-- mText = params.text, Removing this
mChunks = params.text,
mChunkIndex = 1,
mContinueMark = Sprite.Create(),
mTime = 0,
mTextScale = params.textScale or 1,
mPanel = Panel:Create(params.panelArgs),
mSize = params.size,
mBounds = params.textbounds,
mAppearTween = Tween:Create(0, 1, 0.4, Tween.EaseOutCirc),
mWrap = params.wrap or -1,
mChildren = params.children or {},
mSelectionMenu = params.selectionMenu,
mStack = params.stack,
mDoClickCallback = false,
mOnFinish = params.OnFinish or function() end
}
this.mContinueMark:SetTexture(Texture.Find("continue_caret.png"))
-- Calculate center point from mSize
-- We can use this to scale.
this.mX = (this.mSize.right + this.mSize.left) / 2
this.mY = (this.mSize.top + this.mSize.bottom) / 2
this.mWidth = this.mSize.right - this.mSize.left
this.mHeight = this.mSize.top - this.mSize.bottom
setmetatable(this, self)
return this
end
function Textbox:Update(dt)
self.mTime = self.mTime + dt
self.mAppearTween:Update(dt)
if self:IsDead() then
self.mStack:Pop()
end
return true
end
function Textbox:HandleInput()
if Keyboard.JustPressed(KEY_SPACE) then
self:OnClick()
elseif self.mSelectionMenu then
self.mSelectionMenu:HandleInput()
end
end
function Textbox:Enter()
end
function Textbox:Exit()
if self.mDoClickCallback then
self.mSelectionMenu:OnClick()
end
if self.mOnFinish then
self.mOnFinish()
end
end
function Textbox:OnClick()
if self.mSelectionMenu then
self.mDoClickCallback = true
end
if self.mChunkIndex >= #self.mChunks then
--
-- If the dialog is appearing or dissapearing
-- ignore interaction
--
if not (self.mAppearTween:IsFinished()
and self.mAppearTween:Value() == 1) then
return
end
self.mAppearTween = Tween:Create(1, 0, 0.2, Tween.EaseInCirc)
else
self.mChunkIndex = self.mChunkIndex + 1
end
end
function Textbox:IsDead()
return self.mAppearTween:IsFinished()
and self.mAppearTween:Value() == 0
end
function Textbox:Render(renderer)
local scale = self.mAppearTween:Value()
renderer:ScaleText(self.mTextScale * scale)
renderer:AlignText("left", "top")
-- Draw the scale panel
self.mPanel:CenterPosition(
self.mX,
self.mY,
self.mWidth * scale,
self.mHeight * scale)
self.mPanel:Render(renderer)
local left = self.mX - (self.mWidth/2 * scale)
local textLeft = left + (self.mBounds.left * scale)
local top = self.mY + (self.mHeight/2 * scale)
local textTop = top + (self.mBounds.top * scale)
local bottom = self.mY - (self.mHeight/2 * scale)
renderer:DrawText2d(
textLeft,
textTop,
self.mChunks[self.mChunkIndex],
Vector.Create(1,1,1,1),
self.mWrap * scale)
if self.mSelectionMenu then
renderer:AlignText("left", "center")
local menuX = textLeft
local menuY = bottom + self.mSelectionMenu:GetHeight()
menuY = menuY + self.mBounds.bottom
self.mSelectionMenu.mX = menuX
self.mSelectionMenu.mY = menuY
self.mSelectionMenu.mScale = scale
self.mSelectionMenu:Render(renderer)
end
if self.mChunkIndex < #self.mChunks then
-- There are more chunks t come.
local offset = 12 + math.floor(math.sin(self.mTime*10)) * scale
self.mContinueMark:SetScale(scale, scale)
self.mContinueMark:SetPosition(self.mX, bottom + offset)
renderer:DrawSprite(self.mContinueMark)
end
for k, v in ipairs(self.mChildren) do
if v.type == "text" then
renderer:DrawText2d(
textLeft + (v.x * scale),
textTop + (v.y * scale),
v.text,
Vector.Create(1,1,1,1)
)
elseif v.type == "sprite" then
v.sprite:SetPosition(
left + (v.x * scale),
top + (v.y * scale))
v.sprite:SetScale(scale, scale)
renderer:DrawSprite(v.sprite)
end
end
end
|
SDL=require("samplesdlbind")
--sample code from https://wiki.libsdl.org/SDL_CreateRenderer
SDL.Init(SDL.INIT_VIDEO)
--can not bit and on lua5.2
local window = assert(SDL.CreateWindow("test window",SDL.WINDOWPOS_CENTERED,SDL.WINDOWPOS_CENTERED,400,400,SDL.WINDOW_RESIZABLE))
local renderer = SDL.CreateRenderer(window, -1, SDL.RENDERER_ACCELERATED);
local bitmapSurface = SDL.LoadBMP("neko-i.bmp");
local bitmapTex = SDL.CreateTextureFromSurface(renderer, bitmapSurface);
SDL.FreeSurface(bitmapSurface);
while not quit do
event = SDL.Event.new()
if SDL.WaitEvent(event) then
if SDL.QUIT == event:type() then
break;
end
end
SDL.RenderClear(renderer);
SDL.RenderCopy(renderer, bitmapTex, nil, nil);
SDL.RenderPresent(renderer);
end
SDL.DestroyWindow(window)
SDL.Quit()
|
--[[
Project: SA-MP-API
Author: Tim4ukys
My url: vk.com/tim4ukys
]]
local sys = require 'SA-MP API.kernel'
sys.safely_include 'SA-MP API.samp.0_3_7-R4-2.stTextdraw'
sys.ffi.cdef[[
struct stTextdrawPool {
int iIsListed[2048];
int iPlayerTextDraw[256];
stTextdraw *textdraw[2048];
stTextdraw *playerTextdraw[256];
} __attribute__ ((packed));
]]
|
-- Load globals
require './globals'
-- Load libs
local push = require './libs/push'
-- Load states
local Menu = require './menu'
local Play = require './play'
-- Push set up
function love.resize(w, h)
push:resize(w, h)
end
push:setupScreen(GAME_WIDTH, GAME_HEIGHT, 800, 600, {
vsync = true,
fullscreen = false,
resizable = true,
})
-- Set up imputs
function love.keypressed(key)
KEY_TABLE[key] = true
end
-- Set up state machine
local states = {
menu = Menu:new(),
play = Play:new(),
}
local return_value = false;
local current_state = 'menu'
function love.load()
end
function love.update(dt)
if KEY_TABLE['escape'] then
love.event.quit()
end
return_value = states[current_state]:update(dt)
if return_value then
current_state = return_value
states[current_state]:load()
end
KEY_TABLE = {}
end
function love.draw()
push:start()
states[current_state]:draw()
push:finish()
end
|
local class = require('opus.class')
local UI = require('opus.ui')
UI.WizardPage = class(UI.Window)
UI.WizardPage.defaults = {
UIElement = 'WizardPage',
ey = -2,
}
function UI.WizardPage.validate()
return true
end
|
xgui.prepareDataType( "URSRestrictions" )
xgui.prepareDataType( "URSLimits" )
urs = {}
urs.removers = {}
urs.weapons = weapons.GetList()
urs.arg1save = nil
urs.back = xlib.makepanel{ parent = xgui.null }
urs.restrictionlist = xlib.makelistview{ parent = urs.back, x = 5, y = 5, w = 150, h = 71 }
urs.typelist = xlib.makelistview{ parent = urs.back, x = 5, y = 81, w = 150, h = 220 }
urs.itemlist = xlib.makelistview{ parent = urs.back, x = 160, y = 5, w = 425, h = 295, multiselect = true }
urs.addbutton = xlib.makebutton{ parent = urs.back, x = 485, y = 306, w = 100, h = 25, label = "Add", disabled = true }
urs.removebutton = xlib.makebutton{ parent = urs.back, x = 5, y = 306, w = 150, h = 25, label = "Remove Selected Items", disabled = true }
urs.arg1 = xlib.makecombobox{ parent = urs.back, x = 160, y = 306, w = 155, h = 25, disabled = true}
urs.arg2 = xlib.makecombobox{ parent = urs.back, x = 320, y = 306, w = 160, h = 25, disabled = true}
urs.arg3 = xlib.maketextbox{ parent = urs.back, x = 320, y = 306, w = 160, h = 25, disabled = true, visible = false}
urs.arg2Old = urs.arg2
urs.restrictionlist:AddColumn( "Type of Restriction" )
urs.restrictionlist:AddLine( "Restrictions" )
urs.restrictionlist:AddLine( "Limits" )
urs.typelist:AddColumn( " " )
urs.itemlist:AddColumn( " " )
urs.itemlist:AddColumn( " " )
--------------------------------------------------------------------------------------------------------------------------------------------
urs.restrictionlist.OnRowSelected = function( _, _, line )
urs.arg1:Clear()
urs.arg2:Clear()
urs.arg1save = nil
urs.arg2:SetVisible(false)
urs.arg3:SetVisible(true)
urs.arg2 = urs.arg3
urs.addbutton:SetDisabled( true )
urs.arg1:SetDisabled( true )
urs.arg2:SetDisabled( true )
urs.removebutton:SetDisabled( true )
if line:GetValue(1) == "Restrictions" then
urs.arg1:SetText( "Group(s)" )
urs.arg2:SetText( "Target" )
--urs.arg2:AddChoice( "*" )
for _, groups in pairs( xgui.data.groups ) do
urs.arg1:AddChoice( groups )
end
elseif line:GetValue(1) == "Limits" then
urs.arg1:SetText( "Group" )
urs.arg2:SetText( "Limit" )
for _, groups in pairs( xgui.data.groups ) do
urs.arg1:AddChoice( groups )
end
end
urs.itemlist:Clear()
urs.typelist:Clear()
if line:GetValue(1) == "Restrictions" then
urs.typelist.Columns[1]:SetName( "Type" )
urs.itemlist.Columns[1]:SetName( "Target" )
urs.itemlist.Columns[2]:SetName( "Group" )
for type in pairs( xgui.data.URSRestrictions ) do
urs.typelist:AddLine( type )
end
elseif line:GetValue(1) == "Limits" then
urs.typelist.Columns[1]:SetName( " " )
urs.itemlist.Columns[1]:SetName( "Group" )
urs.itemlist.Columns[2]:SetName( "Limit" )
for type in pairs( xgui.data.URSLimits ) do
urs.typelist:AddLine( type )
end
end
end
urs.typelist.OnRowSelected = function( _, _, line )
urs.addbutton:SetDisabled( false )
urs.arg1:SetDisabled( false )
urs.arg2:SetDisabled( false )
urs.removebutton:SetDisabled( true )
urs.itemlist:Clear()
urs.arg1save = nil
if urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" then
for type, types in pairs( xgui.data.URSRestrictions ) do
if type == line:GetValue(1) then
for target, targets in pairs( types ) do
for group in pairs( targets ) do
urs.itemlist:AddLine( target, group )
end
end
end
end
elseif urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Limits" then
for type, types in pairs( xgui.data.URSLimits ) do
if type == line:GetValue(1) then
for group, numericLimit in pairs( types ) do
urs.itemlist:AddLine( group, numericLimit )
end
end
end
end
end
urs.itemlist.OnRowSelected = function( _, _, line )
urs.removebutton:SetDisabled( false )
urs.addbutton:SetDisabled( false )
urs.arg1:SetDisabled( false )
urs.arg2:SetDisabled( false )
if urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" or urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Limits" then
urs.arg2:SetText( line:GetValue(1) )
end
end
--------------------------------------------------------------------------------------------------------------------------------------------
urs.removebutton.DoClick = function()
if urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" then
for _, items in pairs( urs.itemlist:GetSelected() ) do
if not urs.removers[items:GetValue(1)] then urs.removers[items:GetValue(1)] = { } end
table.insert( urs.removers[items:GetValue(1)], items:GetValue(2) )
end
for target, _ in pairs( urs.removers ) do
LocalPlayer():ConCommand( "ulx unrestrict \"" .. urs.typelist:GetSelected()[1]:GetValue(1) .. "\" \"" .. target .. "\" " .. table.concat( urs.removers[target], " " ) )
end
elseif urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Limits" then
for item in pairs( urs.itemlist:GetSelected() ) do
table.insert( urs.removers, urs.itemlist:GetSelected()[item]:GetValue(2) )
end
for group in pairs( urs.removers ) do
RunConsoleCommand( "ulx", "setlimit", urs.typelist:GetSelected()[1]:GetValue(1), urs.itemlist:GetSelected()[group]:GetValue(1), "-1" )
end
end
urs.removebutton:SetDisabled( true )
urs.removers = {}
end
urs.addbutton.DoClick = function()
if urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" or urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Limits" then
local cmd
if urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" then cmd = "restrict" else cmd = "setlimit" end
if urs.arg1:GetValue() and urs.arg2:GetValue() then
LocalPlayer():ConCommand( "ulx " .. cmd .. " \"" .. urs.typelist:GetSelected()[1]:GetValue(1) .. "\" \"" .. (cmd == "restrict" and urs.arg2:GetValue() or urs.arg1:GetValue()) .. "\" " .. (cmd == "restrict" and urs.arg1:GetValue() or urs.arg2:GetValue()) )
else
LocalPlayer():ChatPrint( "Missing Argument(s) ~ Please fill in all text boxes." )
end
else
LocalPlayer():ChatPrint( "Missing Argument(s) ~ Please fill in all text boxes." )
end
end
--------------------------------------------------------------------------------------------------------------------------------------------
function URSRestrictionProcess()
urs.itemlist:Clear()
if urs.restrictionlist:GetSelectedLine() and urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Restrictions" and urs.typelist:GetSelectedLine() then
for item, items in pairs( xgui.data.URSRestrictions[ urs.typelist:GetSelected()[1]:GetValue(1) ] ) do
for group in pairs( items ) do
urs.itemlist:AddLine( item, group )
end
end
end
end
xgui.hookEvent( "URSRestrictions", "process", URSRestrictionProcess )
function URSLimitsProcess()
urs.itemlist:Clear()
if urs.restrictionlist:GetSelectedLine() and urs.restrictionlist:GetSelected()[1]:GetValue(1) == "Limits" and urs.typelist:GetSelectedLine() then
for group, groups in pairs( xgui.data.URSLimits[ urs.typelist:GetSelected()[1]:GetValue(1) ] ) do
urs.itemlist:AddLine( group, groups )
end
end
end
xgui.hookEvent( "URSLimits", "process", URSLimitsProcess )
xgui.addSettingModule( "URS", urs.back, "icon16/shield.png" )
|
-- Code created by Kwik - Copyright: kwiksher.com {{year}}
-- Version: {{vers}}
-- Project: {{ProjName}}
--
local _M = {}
--
local _K = require "Application"
local player = require "extlib.movieclip_player"
--
--
{{#ultimate}}
local imageWidth = {{elW}}/4
local imageHeight = {{elH}}/4
local mX, mY = _K.ultimatePosition({{mX}}, {{mY}}, "{{align}}")
{{#randX}}
local randXStart = _K.ultimatePosition({{randXStart}})
local randXEnd = _K.ultimatePosition({{randXEnd}})
{{/randX}}
{{#randY}}
local dummy, randYStart = _K.ultimatePosition(0, {{randYStart}})
local dummy, randYEnd = _K.ultimatePosition(0, {{randYEnd}})
{{/randY}}
{{/ultimate}}
{{^ultimate}}
local imageWidth = {{elW}}
local imageHeight = {{elH}}
local mX, mY = _K.ultimatePosition({{mX}}, {{mY}}, "{{align}}")
{{#randX}}
local randXStart = {{randXStart}}
local randXEnd = {{randXEnd}}
{{/randX}}
{{#randY}}
local randYStart = {{randYStart}}
local randYEnd = {{randYEnd}}
{{/randY}}
{{/ultimate}}
local oriAlpha = {{oriAlpha}}
local png_prefix = _K.videoDir .. "{{elURL}}/{{prefix}}" -- "img/test_HTML5 Canvas" --test_HTML5 Canvas0001.png
local prefix_num = "{{preNum}}"
local num_of_pngs = {{numOfPngs}}
function _M:localVars(UI)
end
function _M:localPos(UI)
local sceneGroup = UI.scene.view
local layer = UI.layer
layer.{{myLName}} = display.newGroup()
layer.{{myLName}}.player = player
player:init(png_prefix, prefix_num, num_of_pngs, mX, mY, imageWidth, imageHeight, layer.{{myLName}} ) -- group
sceneGroup:insert(layer.{{myLName}})
sceneGroup.{{myLName}} = layer.{{myLName}}
end
--
function _M:didShow(UI)
local sceneGroup = UI.scene.view
local layer = UI.layer
--
{{#randX}}
layer.{{myLName}}.x = math.random( randXStart,randXEnd)
{{/randX}}
{{#randY}}
layer.{{myLName}}.y = math.random( randYStart, {{randYEnd}})
{{/randY}}
{{#scaleW}}
layer.{{myLName}}.xScale = {{scaleW}}
{{/scaleW}}
{{#scaleH}}
layer.{{myLName}}.yScale = {{scaleH}}
{{/scaleH}}
{{#rotate}}
layer.{{myLName}}:rotate( {{rotate)}})
{{/rotate}}
layer.{{myLName}}.oriX = layer.{{myLName}}.x
layer.{{myLName}}.oriY = layer.{{myLName}}.y
layer.{{myLName}}.oriXs = layer.{{myLName}}.xScale
layer.{{myLName}}.oriYs = layer.{{myLName}}.yScale
layer.{{myLName}}.alpha = oriAlpha
layer.{{myLName}}.oldAlpha = oriAlpha
{{#elTriggerElLoop}}
layer.{{myLName}}.videoListener = function(event)
if event.phase == "ended" then
{{#elRewind}}
{{/elRewind}}
{{#elTrigger}}
UI.scene:dispatchEvent({name="action_{{elTrigger}}", layer=layer.{{myLName}} })
{{/elTrigger}}
end
end
{{/elTriggerElLoop}}
{{#elPlay}}
local _loop = 0
{{#elLoop}}
_loop = -1
{{/elLoop}}
layer.{{myLName}}.loop = _loop
player:play({loop=_loop, onComplete = function()
print("completed")
player:stop()
{{#elTriggerElLoop}}
layer.{{myLName}}.videoListener({phase ="ended"})
{{/elTriggerElLoop}}
end
})
{{/elPlay}}
layer.{{myLName}}.name = "{{myLName}}"
end
--
function _M:toDispose(UI)
local sceneGroup = UI.scene.view
local layer = UI.layer
{{#elTriggerElLoop}}
if layer.{{myLName}} then
layer.{{myLName}}.videoListener = nil
end
{{/elTriggerElLoop}}
end
--
function _M:localVars()
end
function _M:toDestroy(UI)
local sceneGroup = UI.scene.view
local layer = UI.layer
end
--
return _M
|
local context = G.botContext
if type(context.UI) ~= "table" then
context.UI = {}
end
local UI = context.UI
UI.SingleScrollItemPanel = function(params, callback, parent) -- callback = function(widget, newParams)
--[[ params:
on - bool,
item - number,
subType - number,
title - string,
min - number,
max - number,
]]
params.title = params.title or "title"
params.item = params.item or 0
params.subType = params.subType or 0
params.min = params.min or 20
local widget = UI.createWidget('SingleScrollItemPanel', parent)
widget.title:setOn(params.on)
widget.title.onClick = function()
params.on = not params.on
widget.title:setOn(params.on)
if callback then
callback(widget, params)
end
end
widget.item:setItem(Item.create(params.item, params.subType))
widget.item.onItemChange = function()
params.item = widget.item:getItemId()
params.subType = widget.item:getItemSubType()
if callback then
callback(widget, params)
end
end
local update = function(dontSignal)
widget.title:setText(" ".. params.min .." ".. params.title .." ")
if callback and not dontSignal then
callback(widget, params)
end
end
widget.scroll:setValue(params.min)
widget.scroll.onValueChange = function(scroll, value)
params.min = value
update()
end
update(true)
end
|
local shell = require("shell")
local _, ops = shell.parse(...)
if ops.help then
print([[Usage: ls [OPTION]... [FILE]...
-a, --all do not ignore entries starting with .
--full-time with -l, print time in full iso format
-h, --human-readable with -l and/or -s, print human readable sizes
--si likewise, but use powers of 1000 not 1024
-l use a long listing format
-r, --reverse reverse order while sorting
-R, --recursive list subdirectories recursively
-S sort by file size
-t sort by modification time, newest first
-X sort alphabetically by entry extension
-1 list one file per line
-p append / indicator to directories
-M display Microsoft-style file and directory count after listing
--no-color Do not colorize the output (default colorized)
--help display this help and exit
For more info run: man ls]])
return 0
end
-- load complex, if we can (might be low on memory)
local full_ls_path = package.searchpath("tools/full-ls", package.path)
assert(full_ls_path, "could not find ls libraries")
local full_ls, reason = loadfile(full_ls_path, "bt", _G)
if not full_ls then
io.stderr:write(tostring(reason).."\nFor low memory systems, try using `list` instead\n")
return 1
end
return full_ls(...)
|
local function filtertab(tab, predicate)
local length = #tab
for i = length, 1, -1 do
if predicate(tab[i]) then table.remove(tab, i) end
end
return tab
end
return filtertab
|
description = [[
Attempts to extract information from HP iLO boards including versions and addresses.
HP iLO boards have an unauthenticated info disclosure at <ip>/xmldata?item=all.
It lists board informations such as server model, firmware version,
MAC addresses, IP addresses, etc. This script uses the slaxml library
to parse the iLO xml file and display the info.
]]
---
--@usage nmap --script hp-ilo-info -p 80 <target>
--
--@usage nmap --script hp-ilo-info -sV <target>
--
--@output
--PORT STATE SERVICE
--80/tcp open http
--| ilo-info:
--| ServerType: ProLiant MicroServer Gen8
--| ProductID: XXXXXX-XXX
--| UUID: XXXXXXXXXXXXXXXX
--| cUUID: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX
--| ILOType: Integrated Lights-Out 4 (iLO 4)
--| ILOFirmware: X.XX
--| SerialNo: ILOXXXXXXXXXX
--| NICs:
--| NIC 1:
--| Description: iLO 4
--| MacAddress: 12:34:56:78:9a:bc
--| IPAddress: 10.10.10.10
--| Status: OK
--| NIC 2:
--| Description: iLo 4
--| MacAddress: 11:22:33:44:55:66
--| IPAddress: Unknown
--|_ Status: Disabled
--
author = "Rajeev R Menon"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"safe","discovery"}
local http = require "http"
local slaxml = require "slaxml"
local stdnse = require "stdnse"
local shortport = require "shortport"
portrule = shortport.http
function getTag(table,tag)
for _,n in ipairs(table.kids) do
if n.type == "element" and n.name == tag then
return n
elseif n.type == "element" then
local ret = getTag(n,tag)
if ret ~= nil then return ret end
end
end
return nil
end
function parseXML(dom)
local response = stdnse.output_table()
local info = stdnse.output_table()
info['ServerType'] = getTag(dom,"SPN")
info['ProductID'] = getTag(dom,"PRODUCTID")
info['UUID'] = getTag(dom,"UUID")
info['cUUID'] = getTag(dom,"cUUID")
info['ILOType'] = getTag(dom,"PN")
info['ILOFirmware'] = getTag(dom,"FWRI")
info['SerialNo'] = getTag(dom,"SN")
for key,_ in pairs(info) do
if info[key] ~= nil then
response[tostring(key)] = info[key].kids[1].value
end
end
response.NICs = stdnse.output_table()
local nicdom = getTag(dom,"NICS")
if nicdom ~= nil then
local count = 1
for _,n in ipairs(nicdom.kids) do
local nic = stdnse.output_table()
info = stdnse.output_table()
for k,m in ipairs(n.kids) do
if #m.kids >= 1 and m.kids[1].type == "text" then
if m.name == "DESCRIPTION" then
info["Description"] = m.kids[1].value
elseif m.name == "MACADDR" then
info["MacAddress"] = m.kids[1].value
elseif m.name == "IPADDR" then
info["IPAddress"] = m.kids[1].value
elseif m.name == "STATUS" then
info["Status"] = m.kids[1].value
end
end
end
for key,_ in pairs(info) do
nic[tostring(key)] = info[key]
end
response.NICs["NIC "..tostring(count)] = nic
count = count + 1
end
end
return response
end
action = function(host,port)
local response = http.get(host,port,"/xmldata?item=all")
if response["status"] ~= 200
or not response.body
or not response.body:match('<RIMP>')
or not response.body:match('iLO')
then
return
end
local domtable = slaxml.parseDOM(response["body"],{stripWhitespace=true})
return parseXML(domtable)
end
|
-- Object for managing Cleanup
-- @README https://github.com/devSparkle/Maid
local Maid = {}
-- Maid[key] = (function) Adds a function to call at cleanup
-- Maid[key] = (Instance) Adds an Object to be Destroyed at cleanup
-- Maid[key] = (RBXScriptConnection) Adds a connection to be Disconnected at cleanup
-- Maid[key] = (Maid) Maids can act as an event connection, allowing a Maid to have other maids to clean up.
-- Maid[key] = nil Removes a named task. This cleans up the previous Maid[key]
--- Generates a new Maid object
-- @return Maid
function Maid.new()
return setmetatable({_Tasks = {}}, Maid)
end
--- Gives the Maid a Task to perform at cleanup, incremented by 1
-- @param Variant Task An object to be Destroyed, a Connection to be Disconnected, or function/callable table to be called
-- @returns the index the Task was placed at
function Maid:GiveTask(Task)
local n = #self._Tasks + 1
self._Tasks[n] = Task
return n
end
--- Makes the Maid clean up when the instance is destroyed
-- @param Instance Instance The Instance the Maid will wait for to be Destroyed
-- @returns Disconnectable table to stop Maid from being cleaned up upon Instance Destroy (automatically cleaned up by Maid, btw)
-- @author Corecii
local Disconnect = {Connected = true}
Disconnect.__index = Disconnect
function Disconnect:Disconnect()
self.Connected = false
self.Connection:Disconnect()
end
function Maid:LinkToInstance(Object)
local Reference = Instance.new("ObjectValue")
Reference.Value = Object
-- ObjectValues have weak-like Instance references
-- If the Instance can no longer be accessed then it can be collected despite
-- the ObjectValue having a reference to it
local ManualDisconnect = setmetatable({}, Disconnect)
local Connection
local function ChangedFunction(Obj, Par)
if not Reference.Value then
ManualDisconnect.Connected = false
return self:DoCleaning()
elseif Obj == Reference.Value and not Par then
Obj = nil
wait() -- Push further execution of this script to the end of the current execution cycle.
-- This is needed because when the event first runs it's always still Connected.
-- The object may have been reparented or the event manually disconnected or disconnected and ran in that time...
if (not Reference.Value or not Reference.Value.Parent) and ManualDisconnect.Connected then
if not Connection.Connected then
ManualDisconnect.Connected = false
return self:DoCleaning()
else
-- Since this event won't fire if the instance is destroyed while in nil, we have to check
-- often to make sure it's not destroyed. Once it's parented outside of nil we can stop doing
-- this. We also must check to make sure it wasn't manually disconnected or disconnected and ran.
while wait(0.2) do
if not ManualDisconnect.Connected then
-- Don't run func, we were disconnected manually
return
elseif not Connection.Connected then
-- Otherwise, if we're disconnected it's because instance was destroyed
ManualDisconnect.Connected = false
return self:DoCleaning()
elseif Reference.Value.Parent then
-- If it's still Connected then it's not destroyed. If it has a parent then
-- we can quit checking if it's destroyed like this.
return
end
end
end
end
end
end
Connection = Object.AncestryChanged:Connect(ChangedFunction)
ManualDisconnect.Connection = Connection
Object = nil
-- If the object is currently in nil then we need to start our destroy checking loop
-- We need to spawn a new Roblox Lua thread right now before any other code runs.
-- spawn() starts it on the next cycle or frame, coroutines don't have ROBLOX's coroutine.yield handler
-- The only option left is BindableEvents, which run as soon as they are called and use ROBLOX's yield
local QuickRobloxThreadSpawner = Instance.new("BindableEvent")
QuickRobloxThreadSpawner.Event:Connect(ChangedFunction)
QuickRobloxThreadSpawner:Fire(Reference.Value, Reference.Value.Parent)
QuickRobloxThreadSpawner:Destroy()
self._Tasks[#self._Tasks + 1] = ManualDisconnect -- Give Task to Maid, cleanup this Connection upon cleanup
return ManualDisconnect
end
--- Cleans up the Tasks assigned to the Maid
-- This Disconnects RBXScriptConnections, Destroys Instances, and calls Functions/callable Tables
function Maid:DoCleaning()
local Tasks = self._Tasks
for Name, Task in next, Tasks do
local Type = typeof(Task)
local IsTable = Type == "table"
if Type == "RBXScriptConnection" or IsTable and Task.Disconnect then
Task:Disconnect()
elseif Type == "Instance" or IsTable and Task.Destroy then
Task:Destroy()
else
Task()
end
Tasks[Name] = nil
end
end
Maid.Disconnect = Maid.DoCleaning
Maid.Destroy = Maid.DoCleaning
--- Internal __index metamethod
function Maid:__index(i)
return Maid[i] or self._Tasks[i]
end
--- Internal __newindex metamethod
function Maid:__newindex(i, v)
local Tasks = self._Tasks
local Task = Tasks[i]
if Task or v == nil then -- Clear previous Task
local Type = typeof(Task)
local IsTable = Type == "table"
if Type == "RBXScriptConnection" or IsTable and Task.Disconnect then
Task:Disconnect()
elseif Type == "Instance" or IsTable and Task.Destroy then
Task:Destroy()
end
end
Tasks[i] = v
end
return Maid
|
-----------------------------------
-- Area: Bostaunieux Obliette
-- NPC: _4n2 (Sewer Lid)
-- !pos -19.000 -17.899 20.000 167
-----------------------------------
local ID = require("scripts/zones/Bostaunieux_Oubliette/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
player:messageSpecial(ID.text.SEEMS_LOCKED)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option, npc)
end
|
local TextMeasureTemporaryPatch = true
local TextService = game:GetService("TextService")
local Text = {}
-- FYI: Any number greater than 2^30 will make TextService:GetTextSize give invalid results
local MAX_BOUND = 10000
-- TODO(CLIPLAYEREX-1633): We can remove this padding patch after fixing TextService:GetTextSize sizing bug
Text._TEMP_PATCHED_PADDING = Vector2.new(0, 0)
if TextMeasureTemporaryPatch then
Text._TEMP_PATCHED_PADDING = Vector2.new(2, 2)
end
-- Wrapper function for GetTextSize
function Text.GetTextBounds(text, font, fontSize, bounds)
return TextService:GetTextSize(text, fontSize, font, bounds) + Text._TEMP_PATCHED_PADDING
end
function Text.GetTextWidth(text, font, fontSize)
return Text.GetTextBounds(text, font, fontSize, Vector2.new(MAX_BOUND, MAX_BOUND)).X
end
function Text.GetTextHeight(text, font, fontSize, widthCap)
return Text.GetTextBounds(text, font, fontSize, Vector2.new(widthCap, MAX_BOUND)).Y
end
-- TODO(CLIPLAYEREX-391): Kill these truncate functions once we have official support for text truncation
function Text.Truncate(text, font, fontSize, widthInPixels, overflowMarker)
overflowMarker = overflowMarker or ""
if Text.GetTextWidth(text, font, fontSize) > widthInPixels then
-- A binary search may be more efficient
local lastText = ""
for _, stopIndex in utf8.graphemes(text) do
local newText = string.sub(text, 1, stopIndex) .. overflowMarker
if Text.GetTextWidth(newText, font, fontSize) > widthInPixels then
return lastText
end
lastText = newText
end
else -- No truncation needed
return text
end
return ""
end
function Text.TruncateTextLabel(textLabel, overflowMarker)
textLabel.Text = Text.Truncate(textLabel.Text, textLabel.Font,
textLabel.TextSize, textLabel.AbsoluteSize.X, overflowMarker)
end
-- Remove whitespace from the beginning and end of the string
function Text.Trim(str)
if type(str) ~= "string" then
error(string.format("Text.Trim called on non-string type %s.", type(str)), 2)
end
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
-- Remove whitespace from the end of the string
function Text.RightTrim(str)
if type(str) ~= "string" then
error(string.format("Text.RightTrim called on non-string type %s.", type(str)), 2)
end
return (str:gsub("%s+$", ""))
end
-- Remove whitespace from the beginning of the string
function Text.LeftTrim(str)
if type(str) ~= "string" then
error(string.format("Text.LeftTrim called on non-string type %s.", type(str)), 2)
end
return (str:gsub("^%s+", ""))
end
-- Replace multiple whitespace with one; remove leading and trailing whitespace
function Text.SpaceNormalize(str)
if type(str) ~= "string" then
error(string.format("Text.SpaceNormalize called on non-string type %s.", type(str)), 2)
end
return (str:gsub("%s+", " "):gsub("^%s+" , ""):gsub("%s+$" , ""))
end
-- Splits a string by the provided pattern into a table. The pattern is interpreted as plain text.
function Text.Split(str, pattern)
if type(str) ~= "string" then
error(string.format("Text.Split called on non-string type %s.", type(str)), 2)
elseif type(pattern) ~= "string" then
error(string.format("Text.Split called with a pattern that is non-string type %s.", type(pattern)), 2)
elseif pattern == "" then
error("Text.Split called with an empty pattern.", 2)
end
local result = {}
local currentPosition = 1
while true do
local patternStart, patternEnd = string.find(str, pattern, currentPosition, true)
if not patternStart or not patternEnd then break end
table.insert(result, string.sub(str, currentPosition, patternStart - 1))
currentPosition = patternEnd + 1
end
table.insert(result, string.sub(str, currentPosition, string.len(str)))
return result
end
return Text
|
#!/usr/bin/env lua
-- In case we want to run tests when library is built but not installed.
local LUA_PATH_SEP = package.config:sub(3, 3)
package.cpath = package.cpath .. LUA_PATH_SEP .. '../src/?.so'
local function maketester(t)
return function(library, name)
assert(type(library[name]) == t, string.format('%s not defined as a %s.', name, t)
end
end
local testFunctionDefined = maketester('function')
local testStringsDefined = maketester('string')
local testNumericDefined = maketester('number')
local lblink = require 'lblink'
local numericvars = {'VID', 'PID' }
local stringvars = { '_VERSION' }
local functions = { 'enumerate', 'list', 'open' }
for _,n in ipairs(numericvars) do
testNumericDefined(lblink, n)
end
for _,s in ipairs(stringvars) do
testStringsDefined(lblink, s)
end
for _,f in ipairs(functions) do
testFunctionDefined(lblink, f)
end
print "Success"
|
local require = require
local find = string.find
local sub = string.sub
local match = string.match
local format = string.format
local reverse = string.reverse
local module = module
local error = error
local parse_prototype = {}
local assert = assert
local print = print
local gfind = string.gfind
local pcall = pcall
if module then
module 'parse_prototype'
end
local pretty = pcall(require, 'pl/pretty')
local _ENV = {}
function parse_prototype.extract_args(str)
local start_of_argument_list, _, function_name, argument_list
= find((str), '([%w_]+)%s*(%b())%s*$')
if not start_of_argument_list then
error(format('No argument list in %q', str), 2)
end
argument_list = argument_list:sub(2)
local return_type
= str:sub(1, start_of_argument_list - 1):gsub('^%s*',''):gsub('%s*$', '')
local count = 0
local start = 1
local args = {}
local argument_names = {}
local argument_types = {}
--print(('[ARGUMENT_LIST] %q'):format(argument_list))
while true do
--print(('[REMAINING ARGUMENT LIST] %q'):format(argument_list:sub(start)))
local start_, end_ = find(argument_list, '[_%w%b()%*][_%w%b()%*%s]-[,%)]',
start)
count = count + 1
if not start_ then
break
end
local this_argument = argument_list:sub(start_, end_ - 1)
args[count] = this_argument
local start_name, end_name, argument_name = assert(find(this_argument,
'%s*([%w_]+)%s*$'))
--print(('[FOUND_ARGUMENT] %q'):format(args[count]))
argument_names[count] = argument_name
argument_types[count] = this_argument:sub(1, end_name)
start = end_ + 1
end
--pretty.dump(args)
return return_type, function_name, args, argument_names, argument_types
end
return parse_prototype
|
-- Model: vgg-face.small1.def.lua
-- Description: Modified VGG Face network. Smaller and with batch normalization.
-- !! In progress, may change.
-- Input size: 3x96x96
-- Number of Parameters from net:getParameters() with embSize=128: TODO
-- Components: Mostly `nn`
-- Devices: CPU and CUDA
--
-- Brandon Amos <http://bamos.github.io>
-- 2016-06-08
--
-- Copyright 2016 Carnegie Mellon University
--
-- 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.
imgDim = 96
local conv = nn.SpatialConvolutionMM
local sbn = nn.SpatialBatchNormalization
local relu = nn.ReLU
local mp = nn.SpatialMaxPooling
function createModel()
local net = nn.Sequential()
net:add(conv(3, 64, 3,3, 1,1, 1,1))
net:add(sbn(64))
net:add(relu(true))
net:add(conv(64, 64, 3,3, 1,1, 1,1))
net:add(sbn(64))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(64, 128, 3,3, 1,1, 1,1))
net:add(sbn(128))
net:add(relu(true))
net:add(conv(128, 128, 3,3, 1,1, 1,1))
net:add(sbn(128))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(128, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(conv(256, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(conv(256, 256, 3,3, 1,1, 1,1))
net:add(sbn(256))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(256, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(mp(2,2, 2,2))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(conv(512, 512, 3,3, 1,1, 1,1))
net:add(sbn(512))
net:add(relu(true))
net:add(mp(2,2, 2,2))
-- Validate shape with:
net:add(nn.Reshape(4608))
net:add(nn.View(4608))
net:add(nn.Linear(4608, 1024))
net:add(relu(true))
net:add(nn.Linear(1024, opt.embSize))
net:add(nn.Normalize(2))
return net
end
|
-- The MIT License (MIT)
--
-- Copyright (c) 2014 Cyril David <cyx@cyx.is>
-- Copyright (c) 2011-2013 Bertrand Mansion <bmansion@mamasam.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
-- == list of known and common scheme ports
--
-- @see http://www.iana.org/assignments/uri-schemes.html
--
local SERVICES = {
acap = 674,
cap = 1026,
dict = 2628,
ftp = 21,
gopher = 70,
http = 80,
https = 443,
iax = 4569,
icap = 1344,
imap = 143,
ipp = 631,
ldap = 389,
mtqp = 1038,
mupdate = 3905,
news = 2009,
nfs = 2049,
nntp = 119,
rtsp = 554,
sip = 5060,
snmp = 161,
telnet = 23,
tftp = 69,
vemmi = 575,
afs = 1483,
jms = 5673,
rsync = 873,
prospero = 191,
videotex = 516
}
local LEGAL = {
["-"] = true, ["_"] = true, ["."] = true, ["!"] = true,
["~"] = true, ["*"] = true, ["'"] = true, ["("] = true,
[")"] = true, [":"] = true, ["@"] = true, ["&"] = true,
["="] = true, ["+"] = true, ["$"] = true, [","] = true,
[";"] = true -- can be used for parameters in path
}
-- aggressive caching of methods
local gsub = string.gsub
local char = string.char
local byte = string.byte
local upper = string.upper
local lower = string.lower
local format = string.format
-- forward declaration of helper utilities
local util = {}
local function decode(str)
local str = gsub(str, "+", " ")
return (gsub(str, "%%(%x%x)", function(c)
return char(tonumber(c, 16))
end))
end
local function encode(str)
return (gsub(str, "([^A-Za-z0-9%_%.%-%~])", function(v)
return upper(format("%%%02x", byte(v)))
end))
end
-- Build a URL given a table with the fields:
--
-- - scheme
-- - user
-- - password
-- - host
-- - port
-- - path
-- - query
-- - fragment
--
-- Example:
--
-- local url = uri.build({
-- scheme = "http",
-- host = "example.com",
-- path = "/some/path"
-- })
--
-- assert(url == "http://example.com/some/path")
--
local function build(uri)
local url = ""
if uri.path then
local path = uri.path
gsub(path, "([^/]+)", function (s) return util.encode_segment(s) end)
url = url .. tostring(path)
end
if uri.query then
local qstring = tostring(uri.query)
if qstring ~= "" then
url = url .. "?" .. qstring
end
end
if uri.host then
local authority = uri.host
if uri.port and uri.scheme and SERVICES[uri.scheme] ~= uri.port then
authority = authority .. ":" .. uri.port
end
local userinfo
if uri.user and uri.user ~= "" then
userinfo = encode(uri.user)
if uri.password then
userinfo = userinfo .. ":" .. encode(uri.password)
end
end
if userinfo and userinfo ~= "" then
authority = userinfo .. "@" .. authority
end
if authority then
if url ~= "" then
url = "//" .. authority .. "/" .. gsub(url, "^/+", "")
else
url = "//" .. authority
end
end
end
if uri.scheme then
url = uri.scheme .. ":" .. url
end
if uri.fragment then
url = url .. "#" .. uri.fragment
end
return url
end
-- Parse the url into the designated parts.
--
-- Depending on the url, the following parts will be available:
--
-- - scheme
-- - userinfo
-- - user
-- - password
-- - authority
-- - host
-- - port
-- - path
-- - query
-- - fragment
--
-- Usage:
--
-- local u = uri.parse("http://john:monkey@example.com/some/path#h1")
--
-- assert(u.host == "example.com")
-- assert(u.scheme == "http")
-- assert(u.user == "john")
-- assert(u.password == "monkey")
-- assert(u.path == "/some/path")
-- assert(u.fragment == "h1")
--
local function parse(url)
local uri = { query = nil }
util.set_authority(uri, "")
local url = tostring(url or "")
url = gsub(url, "#(.*)$", function(v)
uri.fragment = v
return ""
end)
url = gsub(url, "^([%w][%w%+%-%.]*)%:", function(v)
uri.scheme = lower(v)
return ""
end)
url = gsub(url, "%?(.*)", function(v)
uri.query = v
return ""
end)
url = gsub(url, "^//([^/]*)", function(v)
util.set_authority(uri, v)
return ""
end)
uri.path = decode(url)
return uri
end
function util.encode_segment(s)
local function encode_legal(c)
if LEGAL[c] then
return c
end
return encode(c)
end
return gsub(s, "([^a-zA-Z0-9])", encode_legal)
end
-- set the authority part of the url
--
-- The authority is parsed to find the user, password, port and host if available.
-- @param authority The string representing the authority
-- @return a string with what remains after the authority was parsed
function util.set_authority(uri, authority)
uri.authority = authority
uri.port = nil
uri.host = nil
uri.userinfo = nil
uri.user = nil
uri.password = nil
authority = gsub(authority, "^([^@]*)@", function(v)
uri.userinfo = decode(v)
return ""
end)
authority = gsub(authority, "^%[[^%]]+%]", function(v)
-- ipv6
uri.host = v
return ""
end)
authority = gsub(authority, ":([^:]*)$", function(v)
uri.port = tonumber(v)
return ""
end)
if authority ~= "" and not uri.host then
uri.host = lower(authority)
end
if uri.userinfo then
local userinfo = uri.userinfo
userinfo = gsub(userinfo, ":([^:]*)$", function(v)
uri.password = v
return ""
end)
uri.user = userinfo
end
return authority
end
local uri = {
build = build,
parse = parse,
encode = encode,
decode = decode
}
return uri
|
PLUGIN.Title = "Rank and List"
PLUGIN.Description = "Allow Admins to Put Users in Ranks"
PLUGIN.Author = "The Big Wig"
PLUGIN.Version = "1.2.2"
print(PLUGIN.Title .. " (" .. PLUGIN.Version .. ") plugin loaded")
--Things To Add Later:
--ADD STEAM IDS (ADMIN CANT REMOVE USERS AFTER NAME CHANGE UNLESS USING OLD NAME)
--Add time and date stamp reading to stop users from causing errors
--If group the group is deleted, delete all users with that group
-- Called when oxide loads or user types oxide.reload example at F1 console
function PLUGIN:Init()
self:AddChatCommand("createrankname", self.cmdcreaterank)
self:AddChatCommand("removerankname", self.cmdremoverank)
self:AddChatCommand("addrank", self.cmdaddrank)
self:AddChatCommand("removerank", self.cmdremoverank1)
self:AddChatCommand("rankhelp", self.cmdrankhelp)
self:AddChatCommand("ranks", self.cmdviewrank)
self:LoadConfig()
--RANKS LOAD
self.DataFile = util.GetDatafile("Ranks")
local txt = self.DataFile:GetText();
if (txt ~= "") then
self.Ranks = json.decode(txt);
else
self.Ranks ={}
end
--LOADS User Ranks
self.UserRankNameFile = util.GetDatafile("UserRanksNames")
local txt = self.UserRankNameFile:GetText();
if (txt ~= "") then
self.UserRanksNames= json.decode(txt);
else
self.UserRanksNames ={}
end
--LOADS USER RANKS
self.UserRankFile = util.GetDatafile("UserRanks")
local txt = self.UserRankFile:GetText();
if (txt ~= "") then
self.UserRanks = json.decode(txt);
else
self.UserRanks ={}
end
end
-- Called when user types /createrankname
function PLUGIN:cmdcreaterank( netuser, cmd, args )
--TESTING CODE BELOW
--Working
--rust.SendChatToUser( netuser, "Using create rank name" )
--TESTING CODE Above
if not netuser:CanAdmin() then
rust.Notice( netuser, "You are not an admin!" )
return
end
if not args[1] then
rust.SendChatToUser( netuser, "Syntax /createrankname Name")
return
end
local rankName = args[1]
rankName = util.QuoteSafe(rankName)
if self.Ranks == nil then
local arraySize = 0
else
arraySize = #self.Ranks
end
--Checks To See if Rank Name Already Exists
for i=1,arraySize do
if rankName == self.Ranks[i] then
rust.SendChatToUser( netuser, "There Already is a Rank Name Called "..rankName)
return
end
end
arraySize =arraySize +1
self.Ranks[arraySize] = rankName
self:saveRanks()
rust.SendChatToUser( netuser, "You Have Added Rank Named "..self.Ranks[arraySize])
end
-- Called when user types /removerankname
function PLUGIN:cmdremoverank( netuser, cmd, args )
--TESTING CODE BELOW
--Working
--rust.SendChatToUser( netuser, "Using Remove Rank Name" )
--TESTING CODE Above
if not netuser:CanAdmin() then
rust.Notice( netuser, "You are not an admin!" )
return
end
if not args[1] then
rust.SendChatToUser( netuser, "Syntax /removerankname Name")
return
end
local rankName = args[1]
rankName = util.QuoteSafe(rankName)
local arraySize = #self.Ranks
if arraySize == nil then
arraySize = 0
rust.SendChatToUser( netuser, "There Are No Ranks To Remove!" )
return
end
local isThere = false
for i=1,arraySize do
if rankName == self.Ranks[i] then
isThere = true
end
end
if isThere == false then
rust.SendChatToUser( netuser, "Cannont Not Find Rank Name "..rankName)
return
end
--Array Contains Some Rank At the Point
for i=1, arraySize do
local scannedRankName = self.Ranks[i]
if scannedRankName == rankName then
--Remove This Rank Name
table.remove(self.Ranks,i)
self:saveRanks()
end
end
rust.SendChatToUser( netuser, "You Have Removed Rank: "..rankName )
end
-- Called when user types /addrank
function PLUGIN:cmdaddrank( netuser, cmd, args )
--TESTING CODE BELOW
--working
--rust.SendChatToUser( netuser, "You Are Running Add Rank" )
--TESTING CODE ABOVE
if not netuser:CanAdmin() then
rust.Notice( netuser, "You are not an admin!" )
return
end
if not args[1] then
rust.SendChatToUser( netuser, "Syntax /addrank Name Rank")
return
end
if not args[2] then
rust.SendChatToUser( netuser, "Syntax /addrank Name Rank")
return
end
local addToRank = args[2]
addToRank = util.QuoteSafe(addToRank)
--Checks To See if the User is a Valid User
local b, targetuser = rust.FindNetUsersByName( args[1] )
if (not b) then
if (targetuser == 0) then
rust.Notice( netuser, "No players found with that name!" )
else
rust.Notice( netuser, "Multiple players found with that name!" )
end
return
end
local arraySizeRanks = #self.Ranks
if arraySizeRanks == nil or arraySizeRanks==0 then
rust.SendChatToUser( netuser, "You Must Create A Rank Before Adding a User To It!" )
return
end
--Checks To See If The Inputed Value is A Valid Rank Name
for g=1,arraySizeRanks do
if addToRank == self.Ranks[g] then
break
end
if g == arraySizeRanks then
rust.SendChatToUser( netuser, "Can Not Find That Rank Name!" )
end
end
--Checks To See If Either Of The Arrays Is Nil. This Stops Throwing an Error To The User
local arraySizeUserRanksNames = #self.UserRanksNames
if arraySizeUserRanksNames == nil then
arraySizeUserRanksNames = 0
end
local arraySizeUserRanks = #self.UserRanks
if arraySizeUserRanks == nil then
arraySizeUserRanks = 0
end
--ADDS USER TO THE ARRAY BASED ON THEIR STEAM NAME
--local targetuserID = rust.GetUserID(targetuser)
--Inserts Users into User Rank Table
self.UserRanks[arraySizeUserRanks+1]= addToRank
self.UserRanksNames[arraySizeUserRanksNames+1] =targetuser.displayName
self:saveUserRankNames()
self:saveUserRanks()
rust.SendChatToUser( netuser, "You Have Added "..self.UserRanksNames[arraySizeUserRanksNames+1].." To Rank ".. self.UserRanks[arraySizeUserRanks+1])
end
-- Called when user types /removerank
function PLUGIN:cmdremoverank1( netuser, cmd, args )
--TESTING CODE BELOW
--working
--rust.SendChatToUser( netuser, "You are Now Running Remove Rank" )
--TESTING CODE ABOVE
if not netuser:CanAdmin() then
rust.Notice( netuser, "You are not an admin!" )
return
end
if not args[1] then
rust.SendChatToUser( netuser, "Syntax /removerank Name Rank")
return
end
if not args[2] then
rust.SendChatToUser( netuser, "Syntax /removerank Name Rank")
return
end
local b, targetuser = rust.FindNetUsersByName( args[1] )
if (not b) then
if (targetuser == 0) then
rust.Notice( netuser, "No players found with that name!" )
else
rust.Notice( netuser, "Multiple players found with that name!" )
end
return
end
local arraySizeRanksNames = #self.UserRanksNames
local arraySizeUserRanks = #self.UserRanks
--Makes Sure That We Dont Do any Processing On nil or 0 valued Arrays Which Would Cause Errors
if arraySizeRanksNames == nil or arraySizeRanksNames==0 then
rust.SendChatToUser( netuser, "You Must Add a User To a Rank Before You Can Remove Them!" )
return
end
if arraySizeUserRanks == nil or arraySizeUserRanks==0 then
rust.SendChatToUser( netuser, "You Must Add a User To a Rank Before You Can Remove Them!" )
return
end
local someVar = args[2]
someVar = util.QuoteSafe(someVar)
for p=1, arraySizeRanksNames do
if self.UserRanksNames[p] == targetuser.displayName and self.UserRanks[p] == someVar then
table.remove(self.UserRanksNames,p)
table.remove(self.UserRanks,p)
self:saveUserRankNames()
self:saveUserRanks()
end
end
rust.SendChatToUser( netuser, "You Have Removed "..targetuser.displayName.." From ".. someVar)
end
-- Called when user types /viewrank
function PLUGIN:cmdviewrank( netuser, cmd, args )
--TESTING CODE BELOW
--Working
--rust.SendChatToUser( netuser, "NOW Running View Rank" )
--TESTING CODE ABOVE
local rankArray ={}
local arraySub =""
local arraySub2=""
local arraySizeRanks = #self.Ranks
local arraySizeRanksNames = #self.UserRanksNames
local arraySizeUserRanks = #self.UserRanks
if arraySizeRanks ==nil or arraySizeRanks == 0 then
rust.SendChatToUser( netuser, "There Are Currently No Ranks")
return
end
--ADD Checks Here
rust.SendChatToUser( netuser, "Current Server Ranks:" )
--Array Contains Some Rank At the Point
for i=1, arraySizeRanks do
--^ This For Loops Cycles Through All Possible Ranks
--Adds Rank To Position 1 in the Array
--rust.SendChatToUser( netuser, ""..self.Ranks[i])
rankArray[1] = self.Ranks[i]
for p=1, arraySizeUserRanks do
if self.UserRanks[p] == self.Ranks[i] then
--local targetUser =rust.NetUserFromNetPlayer(key)
local userName =self.UserRanksNames[p]
--Adds The UserName To The Array To Be Print Later
--rust.SendChatToUser( netuser, "-"..userName)
rankArray[1+#rankArray] =userName
end
end
--At the end of each rank the plguin prints out each rank and users
for y=1, #rankArray do
arraySub =rankArray[y]
if y==1 or y== #rankArray then
if y==1 then
arraySub2 =arraySub2..""..arraySub..": "
else
arraySub2 =arraySub2..""..arraySub.." "
end
else
arraySub2 =arraySub2..""..arraySub..", "
end
end
rust.SendChatToUser( netuser, ""..arraySub2)
for n=1, #rankArray do
rankArray[n]=nil
end
arraySub2 =""
arraySub=""
end
end
--Allows Admin To Add Group Names To The Chat As Well.
function PLUGIN:OnUserChat(netuser, name, msg)
if (msg:sub(1, 1) == "/") then
return
end
if self.Config.ShowNameinChat == false then
print("Not Showing Name in Chat!")
return
end
--Find NetUser Tag
print("Trying To Find User Tag!")
local UserFound = false
local UserIndex = 0
for j=1, #self.UserRanksNames do
if self.UserRanksNames[j] == netuser.displayName then
UserFound = true
UserIndex = j
print(j)
break
end
end
--If No Tag Is Found Then Display The Message Normally
if UserFound == false then
print("Can't Find UserName")
return
end
--print("User Found: "..UserFound)
--print("User Found: "..toString(UserFound).." User Index: "..toString(UserIndex))
--Takes Index From UserRanksNames and Gets That Users Rank
local ownerTag = self.UserRanks[UserIndex]
-- If Show in Front Is True Then the Chat Shows The Rank In Front of The Name
if (self.Config.ShowinFront == true) then
--Makes The Rank Easier To See In The Chat
if self.Config.UseBrackets then
print("Adding Brackets" )
ownerTag = "["..ownerTag.."] "
else
ownerTag = ""..ownerTag.." "
end
rust.BroadcastChat( ownerTag .. netuser.displayName, msg )
--rust.Notice( netuser, "Show In Front is True" )
return false
else
--Makes The Rank Easier To See In The Chat
if self.Config.UseBrackets then
print("Adding Brackets" )
ownerTag = " ["..ownerTag.."]"
else
ownerTag = " "..ownerTag..""
end
rust.BroadcastChat( netuser.displayName .. ownerTag, msg )
--rust.Notice( netuser, "Show in Front is False" )
return false
end
end
-- Called when user types /rankhelp
function PLUGIN:cmdrankhelp( netuser, cmd, args )
--Working
if not netuser:CanAdmin() then
rust.SendChatToUser( netuser, "User Commands: /ranks" )
else
rust.SendChatToUser( netuser, "User Commands: /ranks" )
rust.SendChatToUser( netuser, "Admin Commands: /createrankname, /removerankname, /addrank, /removerank, /rankhelp" )
end
end
-- Automated Oxide help function (added to /help list)
function PLUGIN:SendHelpText( netuser )
--Working
rust.SendChatToUser( netuser, "Use /rankhelp to view all available commands!" )
end
function PLUGIN:saveRanks()
--Saves All Data Files
self.DataFile:SetText(json.encode(self.Ranks));
self.DataFile:Save();
print("Saved: " .. json.encode(self.Ranks));
end
function PLUGIN:saveUserRankNames()
self.UserRankNameFile:SetText(json.encode(self.UserRanksNames));
self.UserRankNameFile:Save();
print("Saved: " .. json.encode(self.UserRanksNames));
end
function PLUGIN:saveUserRanks()
self.UserRankFile:SetText(json.encode(self.UserRanks));
self.UserRankFile:Save();
print("Saved: " .. json.encode(self.UserRanks));
end
function PLUGIN:LoadDefaultConfig()
self.Config.ShowNameinChat = false
self.Config.ShowinFront = true
self.Config.UseBrackets = true
end
function PLUGIN:LoadConfig()
local b, res = config.Read("RankandList")
self.Config = res or {}
if (not b) then
self:LoadDefaultConfig()
if (res) then config.Save("RankandList") end
end
end
|
local headerHeight = 50;
local function PlayerText(pn)
local pnumber = pn == PLAYER_1 and "1" or "2";
local xpos = pn == PLAYER_1 and 0.5 or 1.5;
return LoadFont("_wendy small")..{
Name="Label"..pname(pn);
Text="Player "..pnumber;
InitCommand=function(self)
self:x(_screen.cx*xpos):y(headerHeight/2): NoStroke():zoom(0.8)
end;
OnCommand=function(self)
self:diffusealpha(0):linear(0.5):diffusealpha(1)
end;
OffCommand=function(self)
self:linear(0.5):diffusealpha(0)
end;
};
end;
local t = Def.ActorFrame{
Def.ActorFrame{
Def.ActorProxy{
Name="Scroller";
InitCommand=function(self)
self:MaskDest()
end;
BeginCommand=function(self)
local scroller = SCREENMAN:GetTopScreen():GetChild("LineScroller");
self:SetTarget(scroller);
end;
};
Def.Quad{
InitCommand=function(self)
self:CenterX():y(SCREEN_TOP):vertalign(top):zoomto(_screen.w,headerHeight):MaskSource()
end;
};
};
Def.ActorFrame{
Def.Quad{
Name="P1bg";
InitCommand=function(self)
self:x(SCREEN_LEFT):y(SCREEN_TOP):horizalign(left):vertalign(top):zoomto(_screen.cx,headerHeight):diffuse(PlayerColor(PLAYER_1))
end;
OnCommand=function(self)
self:diffusealpha(0.75)
end;
};
PlayerText(PLAYER_1);
};
Def.ActorFrame{
Def.Quad{
Name="P2bg";
InitCommand=function(self)
self:x(SCREEN_RIGHT):y(SCREEN_TOP):horizalign(right):vertalign(top):zoomto(_screen.cx,headerHeight):diffuse(PlayerColor(PLAYER_2))
end;
OnCommand=function(self)
self:diffusealpha(0.75)
end;
};
PlayerText(PLAYER_2);
};
Def.Quad{
Name="DevicesBG";
InitCommand=function(self)
self:x(_screen.cx):y(headerHeight/2):zoomto(_screen.w/3.5,headerHeight*0.65):diffuse(color("0.5,0.5,0.5,0.9"))
end;
};
};
return t;
|
local present, telescope = pcall(require, "telescope")
if not present then
return
end
telescope.setup {
defaults = {
file_ignore_patterns = {
"%.jpg",
"%.jpeg",
"%.png",
"%.otf",
"%.ttf",
"node_modules",
".git",
},
prompt_prefix = "│ ",
selection_caret = " ",
entry_prefix = " ",
layout_strategy = "flex",
layout_config = {
horizontal = {
preview_width = 0.6,
},
},
border = {},
borderchars = { " ", " ", " ", " ", " ", " ", " ", " " },
-- borderchars = { "─", "│", "─", "│", "┌", "┐", "┘", "└" },
-- borderchars = { "─", "│", "─", "│", "╭", "╮", "╯", "╰" },
},
}
|
for i, force in pairs(game.forces) do
if force.technologies["electric-energy-accumulators-1"].researched then
force.recipes["alien-accumulator"].enabled = true
end
end
|
#@ SimpleGraphic
-- Path of Building
--
-- Module: Launch
-- Program entry point; loads and runs the Main module within a protected environment
--
SetWindowTitle("Path of Building")
ConExecute("set vid_mode 8")
ConExecute("set vid_resizable 3")
local launch = { }
SetMainObject(launch)
function launch:OnInit()
self.devMode = false
self.versionNumber = "?"
self.versionBranch = "?"
self.versionPlatform = "?"
self.lastUpdateCheck = GetTime()
self.subScripts = { }
local firstRunFile = io.open("first.run", "r")
if firstRunFile then
firstRunFile:close()
os.remove("first.run")
-- This is a fresh installation
-- Perform an immediate update to download the latest version
ConClear()
ConPrintf("Please wait while we complete installation...\n")
local updateMode, errMsg = LoadModule("UpdateCheck")
if not updateMode then
self.updateErrMsg = errMsg
elseif updateMode ~= "none" then
self:ApplyUpdate(updateMode)
return
end
end
local xml = require("xml")
local localManXML = xml.LoadXMLFile("manifest.xml")
if localManXML and localManXML[1].elem == "PoBVersion" then
for _, node in ipairs(localManXML[1]) do
if type(node) == "table" then
if node.elem == "Version" then
self.versionNumber = node.attrib.number
self.versionBranch = node.attrib.branch
self.versionPlatform = node.attrib.platform
end
end
end
end
if localManXML and not self.versionBranch and not self.versionPlatform then
-- Looks like a remote manifest, so we're probably running from a repository
-- Enable dev mode to disable updates and set user path to be the script path
self.devMode = true
end
ConPrintf("Loading main script...")
local errMsg
errMsg, self.main = PLoadModule("Modules/Main", self)
if errMsg then
self:ShowErrMsg("Error loading main script: %s", errMsg)
elseif not self.main then
self:ShowErrMsg("Error loading main script: no object returned")
elseif self.main.Init then
errMsg = PCall(self.main.Init, self.main)
if errMsg then
self:ShowErrMsg("In 'Init': %s", errMsg)
end
end
if not self.devMode and not firstRunFile then
-- Run a background update check if developer mode is off
self:CheckForUpdate(true)
end
end
function launch:CanExit()
if self.main and self.main.CanExit and not self.promptMsg then
local errMsg, ret = PCall(self.main.CanExit, self.main)
if errMsg then
self:ShowErrMsg("In 'CanExit': %s", errMsg)
return false
else
return ret
end
end
return true
end
function launch:OnExit()
if self.main and self.main.Shutdown then
PCall(self.main.Shutdown, self.main)
end
end
function launch:OnFrame()
if self.main then
if self.main.OnFrame then
local errMsg = PCall(self.main.OnFrame, self.main)
if errMsg then
self:ShowErrMsg("In 'OnFrame': %s", errMsg)
end
end
end
self.devModeAlt = self.devMode and IsKeyDown("ALT")
SetDrawLayer(1000)
SetViewport()
if self.promptMsg then
local r, g, b = unpack(self.promptCol)
self:DrawPopup(r, g, b, "^0%s", self.promptMsg)
end
if self.doRestart then
local screenW, screenH = GetScreenSize()
SetDrawColor(0, 0, 0, 0.75)
DrawImage(nil, 0, 0, screenW, screenH)
SetDrawColor(1, 1, 1)
DrawString(0, screenH/2, "CENTER", 24, "FIXED", self.doRestart)
Restart()
end
if not self.devMode and (GetTime() - self.lastUpdateCheck) > 1000*60*60*12 then
-- Do an update check every 12 hours if the user keeps the program open
self:CheckForUpdate(true)
end
end
function launch:OnKeyDown(key, doubleClick)
if key == "F5" and self.devMode then
self.doRestart = "Restarting..."
elseif key == "u" and IsKeyDown("CTRL") then
if not self.devMode then
self:CheckForUpdate()
end
elseif self.promptMsg then
self:RunPromptFunc(key)
else
if self.main and self.main.OnKeyDown then
local errMsg = PCall(self.main.OnKeyDown, self.main, key, doubleClick)
if errMsg then
self:ShowErrMsg("In 'OnKeyDown': %s", errMsg)
end
end
end
end
function launch:OnKeyUp(key)
if not self.promptMsg then
if self.main and self.main.OnKeyUp then
local errMsg = PCall(self.main.OnKeyUp, self.main, key)
if errMsg then
self:ShowErrMsg("In 'OnKeyUp': %s", errMsg)
end
end
end
end
function launch:OnChar(key)
if self.promptMsg then
self:RunPromptFunc(key)
else
if self.main and self.main.OnChar then
local errMsg = PCall(self.main.OnChar, self.main, key)
if errMsg then
self:ShowErrMsg("In 'OnChar': %s", errMsg)
end
end
end
end
function launch:OnSubCall(func, ...)
if func == "UpdateProgress" then
self.updateProgress = string.format(...)
end
if _G[func] then
return _G[func](...)
end
end
function launch:OnSubError(id, errMsg)
if self.subScripts[id].type == "UPDATE" then
self:ShowErrMsg("In update thread: %s", errMsg)
self.updateCheckRunning = false
elseif self.subScripts[id].type == "DOWNLOAD" then
local errMsg = PCall(self.subScripts[id].callback, nil, errMsg)
if errMsg then
self:ShowErrMsg("In download callback: %s", errMsg)
end
end
self.subScripts[id] = nil
end
function launch:OnSubFinished(id, ...)
if self.subScripts[id].type == "UPDATE" then
self.updateAvailable, self.updateErrMsg = ...
self.updateCheckRunning = false
if self.updateCheckBackground and self.updateAvailable == "none" then
self.updateAvailable = nil
end
elseif self.subScripts[id].type == "DOWNLOAD" then
local errMsg = PCall(self.subScripts[id].callback, ...)
if errMsg then
self:ShowErrMsg("In download callback: %s", errMsg)
end
elseif self.subScripts[id].type == "CUSTOM" then
if self.subScripts[id].callback then
local errMsg = PCall(self.subScripts[id].callback, ...)
if errMsg then
self:ShowErrMsg("In subscript callback: %s", errMsg)
end
end
end
self.subScripts[id] = nil
end
function launch:RegisterSubScript(id, callback)
if id then
self.subScripts[id] = {
type = "CUSTOM",
callback = callback,
}
end
end
function launch:DownloadPage(url, callback, cookies)
-- Download the given page in the background, and calls the provided callback function when done:
-- callback(pageText, errMsg)
local id = LaunchSubScript([[
local url, cookies, proxyURL = ...
ConPrintf("Downloading page at: %s", url)
local curl = require("lcurl.safe")
local page = ""
local easy = curl.easy()
easy:setopt_url(url)
easy:setopt(curl.OPT_ACCEPT_ENCODING, "")
if cookies then
easy:setopt(curl.OPT_COOKIE, cookies)
end
if proxyURL then
easy:setopt(curl.OPT_PROXY, proxyURL)
end
easy:setopt_writefunction(function(data)
page = page..data
return true
end)
local _, error = easy:perform()
local code = easy:getinfo(curl.INFO_RESPONSE_CODE)
easy:close()
local errMsg
if error then
errMsg = error:msg()
elseif code ~= 200 then
errMsg = "Response code: "..code
elseif #page == 0 then
errMsg = "No data returned"
end
ConPrintf("Download complete. Status: %s", errMsg or "OK")
if errMsg then
return nil, errMsg
else
return page
end
]], "", "ConPrintf", url, cookies, self.proxyURL)
if id then
self.subScripts[id] = {
type = "DOWNLOAD",
callback = callback
}
end
end
function launch:ApplyUpdate(mode)
if mode == "basic" then
-- Need to revert to the basic environment to fully apply the update
LoadModule("UpdateApply", "Update/opFile.txt")
SpawnProcess(GetRuntimePath()..'/Update', 'UpdateApply.lua Update/opFileRuntime.txt')
Exit()
elseif mode == "normal" then
-- Update can be applied while normal environment is running
LoadModule("UpdateApply", "Update/opFile.txt")
Restart()
self.doRestart = "Updating..."
end
end
function launch:CheckForUpdate(inBackground)
if self.updateCheckRunning then
return
end
self.updateCheckBackground = inBackground
self.updateMsg = "Initialising..."
self.updateProgress = "Checking..."
self.lastUpdateCheck = GetTime()
local update = io.open("UpdateCheck.lua", "r")
local id = LaunchSubScript(update:read("*a"), "GetScriptPath,GetRuntimePath,GetWorkDir,MakeDir", "ConPrintf,UpdateProgress", self.proxyURL)
if id then
self.subScripts[id] = {
type = "UPDATE"
}
self.updateCheckRunning = true
end
update:close()
end
function launch:ShowPrompt(r, g, b, str, func)
self.promptMsg = str
self.promptCol = {r, g, b}
self.promptFunc = func or function(key)
if key == "RETURN" or key == "ESCAPE" then
return true
elseif key == "F5" then
self.doRestart = "Restarting..."
return true
end
end
end
function launch:ShowErrMsg(fmt, ...)
if not self.promptMsg then
self:ShowPrompt(1, 0, 0, "^1Error:\n\n^0" .. string.format(fmt, ...) .. "\n\nPress Enter/Escape to Dismiss, or F5 to restart the application.")
end
end
function launch:RunPromptFunc(key)
local curMsg = self.promptMsg
local errMsg, ret = PCall(self.promptFunc, key)
if errMsg then
self:ShowErrMsg("In prompt func: %s", errMsg)
elseif ret and self.promptMsg == curMsg then
self.promptMsg = nil
end
end
function launch:DrawPopup(r, g, b, fmt, ...)
local screenW, screenH = GetScreenSize()
SetDrawColor(0, 0, 0, 0.5)
DrawImage(nil, 0, 0, screenW, screenH)
local txt = string.format(fmt, ...)
local w = DrawStringWidth(20, "VAR", txt) + 20
local h = (#txt:gsub("[^\n]","") + 2) * 20
local ox = (screenW - w) / 2
local oy = (screenH - h) / 2
SetDrawColor(1, 1, 1)
DrawImage(nil, ox, oy, w, h)
SetDrawColor(r, g, b)
DrawImage(nil, ox + 2, oy + 2, w - 4, h - 4)
SetDrawColor(1, 1, 1)
DrawImage(nil, ox + 4, oy + 4, w - 8, h - 8)
DrawString(0, oy + 10, "CENTER", 20, "VAR", txt)
end
|
local spell = {}
spell["element"] = [[Support]]
spell["cost"] = 6
spell["desc"] = [[Cures panic, fear and distress in all allies]]
spell["target"] = [[All Ally]]
spell["name"] = [[Me Patra]]
spell["costtype"] = [[SP]]
function spell.activate()
state.context.cost(spell.costtype, spell.cost)
if state.party[state.battle.participants[state.battle.open].name] then
targets = state.battle.iparty
else
targets = state.battle.ienemy
end
validStatuses = {"Distress", "Panic", "Fear"}
for _, index in pairs(targets) do
if validStatuses[state.battle.participants[index].status] then
state.battle.participants[index].status = nil
table.insert(state.battle.turns, {{
target=state.battle.participants[index].name,
caster=state.battle.participants[state.battle.open].name,
status=spell.name,
blurb=state.battle.participants[index].name..spell.blurb
}})
end
end
end
return spell
|
-- Gemeinschaft 5 module: user class
-- (c) AMOOMA GmbH 2012-2013
--
module(...,package.seeall)
Tenant = {}
-- Create Tenant object
function Tenant.new(self, arg)
arg = arg or {}
object = arg.object or {}
setmetatable(object, self)
self.__index = self;
self.class = 'tenant';
self.log = arg.log;
self.database = arg.database;
self.record = arg.record;
return object;
end
-- find tenant by id
function Tenant.find_by_id(self, id)
local sql_query = 'SELECT * FROM `tenants` WHERE `id`= ' .. tonumber(id) .. ' LIMIT 1';
local tenant = nil;
self.database:query(sql_query, function(account_entry)
tenant = Tenant:new(self);
tenant.record = account_entry;
tenant.id = tonumber(account_entry.id);
tenant.uuid = account_entry.uuid;
end);
return tenant;
end
-- find tenant by uuid
function Tenant.find_by_uuid(self, uuid)
tenant_id = tonumber(tenant_id)
local sql_query = 'SELECT * FROM `tenants` WHERE `id`= "' .. uuid .. '" LIMIT 1';
local tenant = nil;
self.database:query(sql_query, function(account_entry)
tenant = Tenant:new(self);
tenant.record = account_entry;
tenant.id = tonumber(account_entry.id);
tenant.uuid = account_entry.uuid;
end);
return tenant;
end
|
-- Handle mismatch between homebrew's version of Lua and hammerspoon's version
local lVer = _VERSION:match("Lua (.+)$")
local luarocks = "/opt/homebrew/bin/luarocks"
package.path = package.path .. ";" .. hs.execute(
luarocks .. " --lua-version " .. lVer .. " path --lr-path"
):gsub("\n", "")
package.cpath = package.cpath .. ";" .. hs.execute(
luarocks .. " --lua-version " .. lVer .. " path --lr-cpath"
):gsub("\n", "")
fennel = require "fennel"
table.insert(package.loaders or package.searchers, fennel.searcher)
fennel.dofile("init.fnl", { allowedGlobals = false })
|
-- Copyright 2012 Gabor Varga <vargagab@gmail.com>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.transmission", package.seeall)
function index()
if not nixio.fs.access("/etc/config/transmission") then
return
end
entry({"admin", "nas"}, firstchild(), "NAS", 44).dependent = false
entry({"admin","nas","transmission","status"},call("act_status")).leaf=true
local page = entry({"admin", "nas", "transmission"}, cbi("transmission"), _("Transmission"))
page.dependent = true
end
function act_status()
local e={}
e.running=luci.sys.call("pgrep transmission > /dev/null") == 0
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.