content
stringlengths 5
1.05M
|
---|
local State = require('src.states.state')
local StateEnding = class("StateEnding", State)
local ENDING = [[
It is the end of movies,
and thus the end of sequels.
The End
]]
function StateEnding:initialize()
States.State.initialize(self, 'Ending')
self.input = baton.new(Config.Controls)
self.a_window = Window:new(21, 1, 80, 45)
self.a_window:add(Widgets.TextPanel:new(1, 1, 80, 6, Palette.Yellow, ENDING, {center=true}))
end
function StateEnding:update(dt)
State.update(self, dt)
if self.input:pressed('continue') then
end_game()
new_game()--Game.state:jump('Splash')
Game.state:call('Debounce')
end
self.a_window:update(dt)
end
function StateEnding:draw()
love.graphics.setColor(Palette.AquaBlue)
love.graphics.print("Ending", 5, 5)
self.a_window:draw()
end
return StateEnding
|
return {
Reducer = function (self)
print(self.Instance:GetFullName(), tick())
return self.Agent.Ieasdasd
end
} |
return function( campaign )
return "0.17.0"
end
|
-- This code is used to read Minecraft schematic files.
--
-- The .schematic file format is described here:
-- http://minecraft.gamepedia.com/Schematic_file_format?cookieSetup=true
-- It is based on the NBT format, which is described here:
-- http://minecraft.gamepedia.com/NBT_Format?cookieSetup=true
-- position in the decompressed string data_stream
local curr_index = 1;
-- helper arry so that the values do not have to be calculated anew each time
local pot256 = { 1 };
for i=1,8 do
pot256[ #pot256+1 ] = pot256[ #pot256 ] * 256;
end
-- read length bytes from data_stream and turn it into an integer value
local read_signed = function( data_stream, length)
local res = 0;
for i=length,1,-1 do
res = res + (string.byte( data_stream, curr_index )* pot256[ i ]);
-- move one further
curr_index = curr_index+1;
end
return res;
end
-- this table will collect the few tags we're actually intrested in
local mc_schematic_data = {};
-- this will be a recursive function
local read_tag;
-- needs to be defined now because it will contain a recursive function
local read_one_tag;
-- read payload of one tag (= a data element in a NBT data structure)
read_one_tag = function( data_stream, tag, title_tag )
if( tag<= 0 or not(data_stream)) then
return;
elseif( tag==1 ) then -- TAG_BYTE: 1 byte
return read_signed( data_stream, 1 );
elseif( tag==2 ) then -- TAG_SHORT: 2 bytes
return read_signed( data_stream, 2 );
elseif( tag==3 ) then -- TAG_INT: 4 bytes
return read_signed( data_stream, 4 );
elseif( tag==4 ) then -- TAG_LONG: 8 bytes
return read_signed( data_stream, 8 );
elseif( tag==5 ) then -- TAG_FLOAT: 4 bytes
return read_signed( data_stream, 4 ); -- the float values are unused here
elseif( tag==6 ) then -- TAG_DOUBLE: 8 bytes
return read_signed( data_stream, 8 ); -- the float values are unused here
elseif( tag==7 ) then -- TAG_Byte_Array
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- a Byte_Array does not contain any sub-tags
res[i] = read_one_tag( data_stream, 1, nil ); -- read TAG_BYTE
end
return res;
elseif( tag==8 ) then -- TAG_String
local size = read_signed( data_stream, 2);
local res = string.sub( data_stream, curr_index, curr_index+size-1 );
-- move on in the data stream
curr_index = curr_index + size;
return res;
elseif( tag==9 ) then -- TAG_List
-- these exact values are not particulary intresting
local tagtyp = read_signed( data_stream, 1 ); -- TAG_BYTE
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- we need to pass title_tag on to the "child"
res[i] = read_one_tag( data_stream, tagtyp, title_tag );
end
return res;
elseif( tag==10 ) then -- TAG_Compound
return read_tag( data_stream, title_tag );
elseif( tag==11 ) then -- TAG_Int_Array
local size = read_signed( data_stream, 4 ); -- TAG_INT
local res = {};
for i=1,size do
-- a Int_Array does not contain any sub-tags
res[i] = read_one_tag( data_stream, 3, nil ); -- TAG_INT
end
return res;
end
end
-- read tag type, tag name and call read_one_tag to get the payload;
read_tag = function( data_stream, title_tag )
local schematic_data = {};
while( data_stream ) do
local tag = string.byte( data_stream, curr_index);
-- move on in the data stream
curr_index = curr_index + 1;
if( not( tag ) or tag <= 0 ) then
return;
end
local tag_name_length = string.byte( data_stream, curr_index ) * 256 + string.byte(data_stream, curr_index + 1);
-- move 2 further
curr_index = curr_index + 2;
local tag_name = string.sub( data_stream, curr_index, curr_index+tag_name_length-1 );
-- move on...
curr_index = curr_index + tag_name_length;
--print('[analyze_mc_schematic_file] Found: Tag '..tostring( tag )..' <'..tostring( tag_name )..'>');
local res = read_one_tag( data_stream, tag, tag_name );
-- Entities and TileEntities are ignored
if( title_tag == 'Schematic'
and( tag_name == 'Width'
or tag_name == 'Height'
or tag_name == 'Length'
or tag_name == 'Materials' -- "Classic" or "Alpha" (=Survival)
or tag_name == 'Blocks'
or tag_name == 'Data'
)) then
mc_schematic_data[ tag_name ] = res;
end
end
return;
end
handle_schematics.analyze_mc_schematic_file = function( path )
-- these files are usually compressed; there is no point to start if the
-- decompress function is missing
if( minetest.decompress == nil) then
return nil;
end
local file, err = save_restore.file_access(path..'.schematic', "rb")
if (file == nil) then
-- print('[analyze_mc_schematic_file] ERROR: NO such file: '..tostring( path..'.schematic'));
return nil
end
local compressed_data = file:read( "*all" );
--local data_string = minetest.decompress(compressed_data, "deflate" );
local data_string = compressed_data; -- TODO
print('FILE SIZE: '..tostring( string.len( data_string ))); -- TODO
file.close(file)
-- we use this (to this file) global variable to store gathered information;
-- doing so inside the recursive functions proved problematic
mc_schematic_data = {};
-- this index will iterate through the schematic data
curr_index = 1;
-- actually analyze the data
read_tag( data_string, nil );
if( not( mc_schematic_data.Width )
or not( mc_schematic_data.Height )
or not( mc_schematic_data.Length )
or not( mc_schematic_data.Blocks )
or not( mc_schematic_data.Data )) then
print('[analyze_mc_schematic_file] ERROR: Failed to analyze '..tostring( path..'.schematic'));
return nil;
end
local translation_function = handle_schematics.findMC2MTConversion;
if( minetest.get_modpath('mccompat')) then
translation_function = mccompat.findMC2MTConversion;
end
local max_msg = 40; -- just for error handling
local size = {x=mc_schematic_data.Width, y=mc_schematic_data.Height, z=mc_schematic_data.Length};
local scm = {};
local nodenames = {};
local nodenames_id = {};
for y=1,size.y do
scm[y] = {};
for x=1,size.x do
scm[y][x] = {};
for z =1,size.z do
local new_node = translation_function(
-- (Y×length + Z)×width + X.
mc_schematic_data.Blocks[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1] );
-- some MC nodes store the information about a node in TWO block and data fields (doors, large flowers, ...)
if( new_node[3] and new_node[3]~=0 ) then
new_node = translation_function(
-- (Y×length + Z)×width + X.
mc_schematic_data.Blocks[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1)*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Blocks[ ((y-1+new_node[3])*size.z + (z-1) )*size.x + (size.x-x) +1],
mc_schematic_data.Data[ ((y-1+new_node[3])*size.z + (z-1) )*size.x + (size.x-x) +1] );
end
if( not( nodenames_id[ new_node[1]] )) then
nodenames_id[ new_node[1] ] = #nodenames + 1;
nodenames[ nodenames_id[ new_node[1] ]] = new_node[1];
end
-- print a few warning messages in case something goes wrong - but do not exaggerate
if( not( new_node[2] and max_msg>0)) then
-- print('[handle_schematics:schematic] MISSING param2: '..minetest.serialize( new_node ));
new_node[2]=0;
max_msg=max_msg-1;
end
-- save some space by not saving air
if( new_node[1] ~= 'air' ) then
scm[y][x][z] = { nodenames_id[ new_node[1]], new_node[2]};
end
end
end
end
return { size = { x=size.x, y=size.y, z=size.z}, nodenames = nodenames, on_constr = {}, after_place_node = {}, rotated=90, burried=0, scm_data_cache = scm, metadata = {}};
end
|
---@class TimedActionTests
TimedActionTests = {}
local Tests = {}
local PLAYER_NUM = 0
local PLAYER_OBJ = nil
local PLAYER_INV = nil
local PLAYER_SQR = nil
local PLAYER_SQR_ORIG = nil
local DURATION = 100
local function getSquareDelta(dx, dy, dz)
local square = getCell():getGridSquare(PLAYER_SQR:getX() + dx, PLAYER_SQR:getY() + dy, PLAYER_SQR:getZ() + dz)
return square, square:getX(), square:getY(), square:getZ()
end
local function removeAllButFloor(square)
if not square then return nil end
for i=square:getObjects():size(),2,-1 do
local isoObject = square:getObjects():get(i-1)
square:transmitRemoveItemFromSquare(isoObject)
end
for i=square:getStaticMovingObjects():size(),1,-1 do
local isoObject = square:getStaticMovingObjects():get(i-1)
isoObject:removeFromWorld()
isoObject:removeFromSquare()
end
end
local function removeAllButFloorAt(x, y, z)
local square = getCell():getGridSquare(x, y, z)
removeAllButFloor(square)
end
local function newObject(x, y, z, spriteName, objectName)
local square = getCell():getGridSquare(x, y, z)
if not square then return nil end
local isoObject = IsoObject.new(square, spriteName, objectName, false)
square:AddTileObject(isoObject)
return isoObject
end
local function newMapObject(x, y, z, spriteName)
newObject(x, y, z, spriteName)
MapObjects.debugLoadChunk(math.floor(x / 10), math.floor(y / 10))
end
local function newInventoryItem(type)
local item = InventoryItemFactory.CreateItem(type)
PLAYER_INV:AddItem(item)
return item
end
local function newPrimaryItem(type)
local item = newInventoryItem(type)
PLAYER_OBJ:setPrimaryHandItem(item)
return item
end
local function newSecondaryItem(type)
local item = newInventoryItem(type)
PLAYER_OBJ:setSecondaryHandItem(item)
return item
end
local function newDoorFrame(x, y, z)
return newObject(x, y, z, "walls_exterior_house_01_11", "")
end
local function newDoor(x, y, z)
local square = getCell():getGridSquare(x, y, z)
local door = IsoDoor.new(getCell(), square, getSprite("fixtures_doors_01_1"), true)
square:AddSpecialObject(door)
return door
end
local function newWindowFrame(x, y, z)
return newObject(x, y, z, "walls_exterior_house_01_9", "")
end
local function newWindow(x, y, z)
local square = getCell():getGridSquare(x, y, z)
local window = IsoWindow.new(getCell(), square, getSprite("fixtures_windows_01_1"), true)
square:AddSpecialObject(window)
return window
end
local function newBBQCharcoal(x, y, z)
local square = getCell():getGridSquare(x, y, z)
local object = IsoBarbecue.new(getCell(), square, getSprite("appliances_cooking_01_35"))
square:AddTileObject(object)
return object
end
local function newBBQPropane(x, y, z)
local square = getCell():getGridSquare(x, y, z)
local object = IsoBarbecue.new(getCell(), square, getSprite("appliances_cooking_01_37"))
square:AddTileObject(object)
return object
end
-----
Tests.apply_bandage = {
run = function(self)
local item = newInventoryItem("Base.Bandage")
local bodyPart = PLAYER_OBJ:getBodyDamage():getBodyPart(BodyPartType.ForeArm_L)
-- TODO: disable god mode to see bandage
ISTimedActionQueue.add(ISApplyBandage:new(PLAYER_OBJ, PLAYER_OBJ, item, bodyPart, DURATION))
end
}
Tests.activate_car_battery_charger = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.CarBatteryCharger")
local object = IsoCarBatteryCharger.new(item, getCell(), square)
square:AddSpecialObject(object)
item = InventoryItemFactory.CreateItem("Base.CarBattery1")
object:setBattery(item)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISActivateCarBatteryChargerAction:new(PLAYER_OBJ, object, true, DURATION))
end,
validate = function(self)
end
}
Tests.activate_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
object:setConnected(true)
object:setFuel(100)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISActivateGenerator:new(PLAYER_NUM, object, true, DURATION))
end,
validate = function(self)
end
}
Tests.fix_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
object:setCondition(50)
newInventoryItem("ElectronicsScrap")
PLAYER_OBJ:setPerkLevelDebug(PerksElectronics, 4)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISFixGenerator:new(PLAYER_OBJ, object, DURATION))
end,
validate = function(self)
end
}
Tests.bbq_remove_propane_tank = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQPropane(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQRemovePropaneTank:new(PLAYER_OBJ, bbq, DURATION))
end
}
Tests.bbq_insert_propane_tank_ground = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQPropane(x, y, z)
local square2 = getSquareDelta(3, 2, 0)
local tankItem = square2:AddWorldInventoryItem(bbq:removePropaneTank(), 0.5, 0.5, 0)
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square2))
ISTimedActionQueue.add(ISBBQInsertPropaneTank:new(PLAYER_OBJ, bbq, tankItem:getWorldItem(), DURATION))
end
}
Tests.bbq_insert_propane_tank_inventory = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQPropane(x, y, z)
local square2 = getSquareDelta(3, 2, 0)
local tankItem = bbq:removePropaneTank()
PLAYER_OBJ:getInventory():AddItem(tankItem)
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square2))
ISTimedActionQueue.add(ISBBQInsertPropaneTank:new(PLAYER_OBJ, bbq, tankItem, DURATION))
end
}
Tests.bbq_turn_on = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQPropane(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQToggle:new(PLAYER_OBJ, bbq, DURATION))
end
}
Tests.bbq_turn_off = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQPropane(x, y, z)
bbq:turnOn()
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQToggle:new(PLAYER_OBJ, bbq, DURATION))
end
}
Tests.bbq_add_charcoal = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQCharcoal(x, y, z)
local item = newInventoryItem("Base.Charcoal")
local fuelAmt = 30 -- campingFuelType[item:getType()] * 60
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQAddFuel:new(PLAYER_OBJ, bbq, item, fuelAmt, DURATION))
end
}
Tests.bbq_add_book = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQCharcoal(x, y, z)
local item = newInventoryItem("Base.Book")
local fuelAmt = campingFuelCategory[item:getCategory()] * 60
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQAddFuel:new(PLAYER_OBJ, bbq, item, fuelAmt, DURATION))
end
}
Tests.bbq_light_book_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQCharcoal(x, y, z)
local book = newInventoryItem("Base.Book")
local lighter = newInventoryItem("Base.Lighter")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQLightFromLiterature:new(PLAYER_OBJ, book, lighter, bbq, DURATION))
end
}
Tests.bbq_light_gas_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bbq = newBBQCharcoal(x, y, z)
bbq:setFuelAmount(20)
local petrol = newInventoryItem("Base.PetrolCan")
local lighter = newInventoryItem("Base.Lighter")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBBQLightFromPetrol:new(PLAYER_OBJ, bbq, lighter, petrol, DURATION))
end
}
Tests.grab_corpse = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local corpseItem = InventoryItemFactory.CreateItem("Base.CorpseMale")
square:AddWorldInventoryItem(corpseItem, 0.5, 0.5, 0)
local corpse = square:getStaticMovingObjects():get(0)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISGrabCorpseAction:new(PLAYER_OBJ, corpse, DURATION))
end
}
Tests.burn_corpse = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local corpseItem = InventoryItemFactory.CreateItem("Base.CorpseMale")
square:AddWorldInventoryItem(corpseItem, 0.5, 0.5, 0)
local corpse = square:getStaticMovingObjects():get(0)
newPrimaryItem("Base.Lighter")
newSecondaryItem("Base.PetrolCan")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISBurnCorpseAction:new(PLAYER_OBJ, corpse, DURATION))
end
}
Tests.place_pipebomb = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = newInventoryItem("Base.PipeBombRemote")
-- ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISPlaceTrap:new(PLAYER_OBJ, item, DURATION))
end
}
Tests.take_pipebomb = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.PipeBombRemote")
local trap = IsoTrap.new(item, getCell(), square)
square:AddTileObject(trap)
luautils.walkAdj(PLAYER_OBJ, square)
-- ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISTakeTrap:new(PLAYER_OBJ, trap, DURATION))
end
}
Tests.connect_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISPlugGenerator:new(PLAYER_NUM, object, true, DURATION))
end,
validate = function(self)
end
}
Tests.disconnect_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
object:setConnected(true)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISPlugGenerator:new(PLAYER_NUM, object, false, DURATION))
end,
validate = function(self)
end
}
Tests.add_fuel_to_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
local petrol = newInventoryItem("Base.PetrolCan")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISAddFuel:new(PLAYER_NUM, object, petrol, DURATION))
end
}
Tests.take_generator = {
run = function(self)
local square = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.Generator")
local object = IsoGenerator.new(item, getCell(), square)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISTakeGenerator:new(PLAYER_NUM, object, DURATION))
end,
validate = function(self)
end
}
Tests.add_water_to_rainbarrel = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
-- small empty rainbarrel (has some random amount of water)
newMapObject(x, y, z, "carpentry_02_54")
local object = CRainBarrelSystem.instance:getIsoObjectOnSquare(square)
local item = newInventoryItem("Base.WaterBottleFull")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISAddWaterFromItemAction:new(PLAYER_OBJ, item, object))
end
}
Tests.add_sheet_to_window = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local sheet = newInventoryItem("Base.Sheet")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISAddSheetAction:new(PLAYER_OBJ, window, DURATION))
end
}
Tests.remove_sheet_from_window = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local sheet = newInventoryItem("Base.Sheet")
window:addSheet(PLAYER_OBJ)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveSheetAction:new(PLAYER_OBJ, window:HasCurtains(), DURATION))
end
}
Tests.remove_broken_glass = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
window:setSmashed(true)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveBrokenGlass:new(PLAYER_OBJ, window, DURATION))
end
}
Tests.close_door = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newDoorFrame(x, y, z)
local door = newDoor(x, y, z)
door:ToggleDoor(PLAYER_OBJ)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, door)
ISTimedActionQueue.add(ISOpenCloseDoor:new(PLAYER_OBJ, door, 0))
end
}
Tests.open_door = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newDoorFrame(x, y, z)
local door = newDoor(x, y, z)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, door)
ISTimedActionQueue.add(ISOpenCloseDoor:new(PLAYER_OBJ, door, 0))
end
}
Tests.close_curtain_on_closed_door = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newDoorFrame(x, y, z)
local door = newDoor(x, y, z)
door:addSheet(true, nil)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, door)
ISTimedActionQueue.add(ISOpenCloseCurtain:new(PLAYER_OBJ, door, 0))
end
}
Tests.close_curtain_on_open_door = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newDoorFrame(x, y, z)
local door = newDoor(x, y, z)
door:ToggleDoor(PLAYER_OBJ)
door:addSheet(false, nil)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, door)
ISTimedActionQueue.add(ISOpenCloseCurtain:new(PLAYER_OBJ, door, 0))
end
}
Tests.close_window = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
window:ToggleWindow(PLAYER_OBJ)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISOpenCloseWindow:new(PLAYER_OBJ, window, 0))
end
}
Tests.open_window = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISOpenCloseWindow:new(PLAYER_OBJ, window, 0))
end
}
Tests.barricade_window_plank = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local hammer = newPrimaryItem("Base.Hammer")
local plank = newSecondaryItem("Base.Plank")
local nails = newInventoryItem("Base.Nails")
local nails = newInventoryItem("Base.Nails")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISBarricadeAction:new(PLAYER_OBJ, window, false, false, DURATION))
end
}
Tests.barricade_window_metal = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local blowTorch = newPrimaryItem("Base.BlowTorch")
local metalSheet = newSecondaryItem("Base.SheetMetal")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISBarricadeAction:new(PLAYER_OBJ, window, true, false, DURATION))
end
}
Tests.unbarricade_window_plank = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local barricade = IsoBarricade.AddBarricadeToObject(window, false)
barricade:addPlank(nil, nil)
local hammer = newPrimaryItem("Base.Hammer")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISUnbarricadeAction:new(PLAYER_OBJ, window, DURATION))
end
}
Tests.unbarricade_window_metal = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
local barricade = IsoBarricade.AddBarricadeToObject(window, false)
barricade:addMetal(nil, nil)
local hammer = newPrimaryItem("Base.BlowTorch")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISUnbarricadeAction:new(PLAYER_OBJ, window, DURATION))
end
}
Tests.connect_battery_to_charger = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = InventoryItemFactory.CreateItem("Base.CarBatteryCharger")
local object = IsoCarBatteryCharger.new(item, getCell(), square)
square:AddSpecialObject(object)
item = newInventoryItem("Base.CarBattery1")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISConnectCarBatteryToChargerAction:new(PLAYER_OBJ, object, item, DURATION))
end
}
Tests.place_battery_charger = {
run = function(self)
removeAllButFloor(PLAYER_SQR)
local item = newInventoryItem("Base.CarBatteryCharger")
ISTimedActionQueue.add(ISPlaceCarBatteryChargerAction:new(PLAYER_OBJ, item, DURATION))
end
}
Tests.clean_blood_dishcloth = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
-- square:getChunk():addBloodSplat(x+0.5, y+0.5, z, ZombRand(20))
newPrimaryItem("Base.DishCloth")
newSecondaryItem("Base.Bleach")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISCleanBlood:new(PLAYER_OBJ, square, DURATION))
end
}
Tests.clean_blood_mop = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
-- square:getChunk():addBloodSplat(x+0.5, y+0.5, z, ZombRand(20))
newPrimaryItem("Base.Mop")
newSecondaryItem("Base.Bleach")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISCleanBlood:new(PLAYER_OBJ, square, DURATION))
end
}
Tests.clear_ashes = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local ashes = newObject(x, y, z, "floors_burnt_01_1", "")
newPrimaryItem("Base.Shovel")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISClearAshes:new(PLAYER_OBJ, ashes, DURATION))
end
}
Tests.remove_bush_axe = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local object = newObject(x, y, z, "f_bushes_1_8", "")
-- square:getErosionData():reset()
ErosionMain.LoadGridsquare(square)
newPrimaryItem("Base.Axe")
luautils.walkAdj(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveBush:new(PLAYER_OBJ, square, nil))
end
}
Tests.remove_bush_knife = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local object = newObject(x, y, z, "f_bushes_1_8", "")
-- square:getErosionData():reset()
ErosionMain.LoadGridsquare(square)
newPrimaryItem("Base.HuntingKnife")
luautils.walkAdj(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveBush:new(PLAYER_OBJ, square, nil))
end
}
Tests.remove_bush_hands = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local object = newObject(x, y, z, "f_bushes_1_8", "")
-- square:getErosionData():reset()
ErosionMain.LoadGridsquare(square)
luautils.walkAdj(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveBush:new(PLAYER_OBJ, square, nil))
end
}
Tests.remove_vine_axe = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local object = newWindowFrame(x, y, z)
object:setAttachedAnimSprite(ArrayList.new())
object:getAttachedAnimSprite():add(getSprite("f_wallvines_1_39"):newInstance())
newPrimaryItem("Base.Axe")
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISRemoveBush:new(PLAYER_OBJ, square, true))
end
}
Tests.remove_vine_knife = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local object = newWindowFrame(x, y, z)
object:setAttachedAnimSprite(ArrayList.new())
object:getAttachedAnimSprite():add(getSprite("f_wallvines_1_39"):newInstance())
newPrimaryItem("Base.HuntingKnife")
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISRemoveBush:new(PLAYER_OBJ, square, true))
end
}
Tests.remove_grass = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
newObject(x, y, z, "e_newgrass_1_48", "Grass")
luautils.walkAdj(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISRemoveGrass:new(PLAYER_OBJ, square))
end
}
Tests.chop_tree = {
run = function(self)
local square,x,y,z = getSquareDelta(0, -2, 0)
removeAllButFloor(square)
local tree = IsoTree.new(square, "e_americanholly_1_3")
square:AddTileObject(tree)
local item = newPrimaryItem("Base.Axe")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISChopTreeAction:new(PLAYER_OBJ, tree))
end
}
Tests.dig_grave = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
local square2,x2,y2,z2 = getSquareDelta(1, 2, 0)
removeAllButFloor(square)
removeAllButFloor(square2)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
square2:getFloor():setSprite(getSprite("blends_natural_01_21"))
local item = newPrimaryItem("Base.Shovel")
local bo = ISEmptyGraves:new("location_community_cemetary_01_33", "location_community_cemetary_01_32", "location_community_cemetary_01_34", "location_community_cemetary_01_35", item)
bo.player = PLAYER_NUM
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.bury_corpse = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
local square2,x2,y2,z2 = getSquareDelta(1, 2, 0)
removeAllButFloor(square)
removeAllButFloor(square2)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
square2:getFloor():setSprite(getSprite("blends_natural_01_21"))
local shovel = newInventoryItem("Base.Shovel")
local bo = ISEmptyGraves:new("location_community_cemetary_01_33", "location_community_cemetary_01_32", "location_community_cemetary_01_34", "location_community_cemetary_01_35", shovel)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local grave = square2:getObjects():get(1)
newPrimaryItem("Base.CorpseMale")
luautils.walkAdj(PLAYER_OBJ, square2)
ISTimedActionQueue.add(ISBuryCorpse:new(PLAYER_NUM, grave, DURATION, shovel))
end
}
Tests.fill_grave = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
local square2,x2,y2,z2 = getSquareDelta(1, 2, 0)
removeAllButFloor(square)
removeAllButFloor(square2)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
square2:getFloor():setSprite(getSprite("blends_natural_01_21"))
local shovel = newPrimaryItem("Base.Shovel")
local bo = ISEmptyGraves:new("location_community_cemetary_01_33", "location_community_cemetary_01_32", "location_community_cemetary_01_34", "location_community_cemetary_01_35", shovel)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local grave = square2:getObjects():get(1)
luautils.walkAdj(PLAYER_OBJ, square2)
ISTimedActionQueue.add(ISFillGrave:new(PLAYER_NUM, grave, DURATION, shovel))
end
}
Tests.destroy_crate = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bo = ISWoodenContainer:new("carpentry_01_19", "carpentry_01_19")
bo.player = PLAYER_NUM
bo:create(x, y, z, bo.north, bo.sprite)
local crate = square:getSpecialObjects():get(0)
-- test items aren't destroyed
crate:getContainer():AddItem("Base.PetrolCan")
newPrimaryItem("Base.Sledgehammer")
luautils.walkAdj(PLAYER_OBJ, square, crate)
ISTimedActionQueue.add(ISDestroyStuffAction:new(PLAYER_OBJ, crate))
end
}
Tests.destroy_curtain = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local frame = newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
-- test curtain is dropped
window:addSheet(PLAYER_OBJ)
local curtain = window:HasCurtains()
newPrimaryItem("Base.Sledgehammer")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, window)
ISTimedActionQueue.add(ISDestroyStuffAction:new(PLAYER_OBJ, curtain))
end
}
-- TODO: test ISDestroyStuffAction stairs, garage doors, graves
Tests.destroy_window_frame = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local frame = newWindowFrame(x, y, z)
local window = newWindow(x, y, z)
-- test curtain is dropped
window:addSheet(PLAYER_OBJ)
-- test barricade is destroyed
local barricade = IsoBarricade.AddBarricadeToObject(window, false)
barricade:addPlank(nil, nil)
newPrimaryItem("Base.Sledgehammer")
luautils.walkAdjWindowOrDoor(PLAYER_OBJ, square, frame)
ISTimedActionQueue.add(ISDestroyStuffAction:new(PLAYER_OBJ, frame))
end
}
Tests.dismantle_crate = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local bo = ISWoodenContainer:new("carpentry_01_19", "carpentry_01_19")
bo.player = PLAYER_NUM
bo:create(x, y, z, bo.north, bo.sprite)
local crate = square:getSpecialObjects():get(0)
-- test items aren't destroyed
crate:getContainer():AddItem("Base.PetrolCan")
newPrimaryItem("Base.Saw")
newSecondaryItem("Base.Screwdriver")
luautils.walkAdj(PLAYER_OBJ, square, crate)
ISTimedActionQueue.add(ISDismantleAction:new(PLAYER_OBJ, crate))
end
}
Tests.place_compost = {
run = function(self)
--[[
newInventoryItem("Base.Plank")
newInventoryItem("Base.Plank")
newInventoryItem("Base.Plank")
newInventoryItem("Base.Plank")
newInventoryItem("Base.Plank")
newInventoryItem("Base.Nails")
newInventoryItem("Base.Nails")
newInventoryItem("Base.Nails")
newInventoryItem("Base.Nails")
--]]
local bo = ISCompost:new(PLAYER_NUM, "camping_01_19")
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.get_compost = {
run = function(self)
local bo = ISCompost:new(PLAYER_NUM, "camping_01_19")
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
bo:create(x, y, z, bo.north, bo.sprite)
local compost = square:getSpecialObjects():get(0)
compost:setCompost(100)
local sandbag = newPrimaryItem("Base.EmptySandbag")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISGetCompost:new(PLAYER_OBJ, compost, sandbag, DURATION))
end
}
Tests.place_campfire = {
run = function(self)
newInventoryItem("camping.CampfireKit")
local bo = campingCampfire:new(PLAYER_OBJ)
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.remove_campfire = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
SCampfireSystem.instance:addCampfire(square)
local campfire = CCampfireSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISRemoveCampfireAction:new(PLAYER_OBJ, campfire, DURATION))
end
}
Tests.campfire_add_book = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
SCampfireSystem.instance:addCampfire(square)
local campfire = CCampfireSystem.instance:getLuaObjectAt(x, y, z)
local item = newInventoryItem("Base.Book")
local fuelAmt = campingFuelCategory[item:getCategory()] * 60
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISAddFuelAction:new(PLAYER_OBJ, campfire, item, fuelAmt, DURATION))
end
}
Tests.campfire_light_book_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
SCampfireSystem.instance:addCampfire(square)
local campfire = CCampfireSystem.instance:getLuaObjectAt(x, y, z)
local book = newInventoryItem("Base.Book")
local fuelAmt = campingFuelCategory[book:getCategory()] * 60
local lighter = newInventoryItem("Base.Lighter")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISLightFromLiterature:new(PLAYER_OBJ, book, lighter, campfire, fuelAmt, DURATION))
end
}
Tests.campfire_light_gas_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local serverObject = SCampfireSystem.instance:addCampfire(square)
serverObject:addFuel(20)
local campfire = CCampfireSystem.instance:getLuaObjectAt(x, y, z)
local petrol = newInventoryItem("Base.PetrolCan")
local lighter = newInventoryItem("Base.Lighter")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISLightFromPetrol:new(PLAYER_OBJ, campfire, lighter, petrol, DURATION))
end
}
Tests.campfire_light_notched = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local serverObject = SCampfireSystem.instance:addCampfire(square)
serverObject:addFuel(20)
local campfire = CCampfireSystem.instance:getLuaObjectAt(x, y, z)
local plank = newInventoryItem("Base.PercedWood")
local stick = newInventoryItem("Base.WoodenStick")
newInventoryItem("Base.WoodenStick")
newInventoryItem("Base.WoodenStick")
newInventoryItem("Base.WoodenStick")
newInventoryItem("Base.WoodenStick")
luautils.walkAdj(PLAYER_OBJ, square)
-- FIXME: this might fail if the WoodenStick breaks
ISTimedActionQueue.add(ISLightFromKindle:new(PLAYER_OBJ, plank, stick, campfire, 1500))
end
}
Tests.fireplace_add_book = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local fireplace = IsoFireplace.new(getCell(), square, getSprite("fixtures_fireplaces_01_0"))
square:AddTileObject(fireplace)
local item = newInventoryItem("Base.Book")
local fuelAmt = campingFuelCategory[item:getCategory()] * 60
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISFireplaceAddFuel:new(PLAYER_OBJ, fireplace, item, fuelAmt, DURATION))
end
}
Tests.fireplace_light_book_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local fireplace = IsoFireplace.new(getCell(), square, getSprite("fixtures_fireplaces_01_0"))
square:AddTileObject(fireplace)
local book = newInventoryItem("Base.Book")
local fuelAmt = campingFuelCategory[book:getCategory()] * 60
local lighter = newInventoryItem("Base.Lighter")
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISFireplaceLightFromLiterature:new(PLAYER_OBJ, book, lighter, fireplace, fuelAmt, DURATION))
end
}
Tests.fireplace_light_gas_lighter = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local fireplace = IsoFireplace.new(getCell(), square, getSprite("fixtures_fireplaces_01_0"))
square:AddTileObject(fireplace)
fireplace:setFuelAmount(20)
local petrol = newInventoryItem("Base.PetrolCan")
local lighter = newInventoryItem("Base.Lighter")
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISFireplaceLightFromPetrol:new(PLAYER_OBJ, fireplace, lighter, petrol, DURATION))
end
}
Tests.fireplace_light_notched = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local fireplace = IsoFireplace.new(getCell(), square, getSprite("fixtures_fireplaces_01_0"))
square:AddTileObject(fireplace)
fireplace:setFuelAmount(20)
local plank = newInventoryItem("Base.PercedWood")
local stick = newInventoryItem("Base.WoodenStick")
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
-- FIXME: this might fail if the WoodenStick breaks
ISTimedActionQueue.add(ISFireplaceLightFromKindle:new(PLAYER_OBJ, plank, stick, fireplace, 1500))
end
}
Tests.fireplace_extinguish = {
run = function(self)
local square,x,y,z = getSquareDelta(2, -2, 0)
removeAllButFloor(square)
local fireplace = IsoFireplace.new(getCell(), square, getSprite("fixtures_fireplaces_01_0"))
square:AddTileObject(fireplace)
fireplace:setFuelAmount(60)
fireplace:setLit(true)
ISTimedActionQueue.add(ISWalkToTimedAction:new(PLAYER_OBJ, square))
ISTimedActionQueue.add(ISFireplaceExtinguish:new(PLAYER_OBJ, fireplace, DURATION))
end
}
Tests.place_tent = {
run = function(self)
newInventoryItem("camping.CampingTentKit")
local bo = campingTent:new(PLAYER_OBJ, camping.tentSprites.tarp)
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
removeAllButFloorAt(x, y - 1, z)
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.remove_tent = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
removeAllButFloorAt(x, y - 1, z)
local tent = camping.addTent(square, "camping_01_0")
luautils.walkAdj(PLAYER_OBJ, tent:getSquare())
ISTimedActionQueue.add(ISRemoveTentAction:new(PLAYER_OBJ, tent, DURATION))
end
}
Tests.place_trap = {
run = function(self)
local item = newInventoryItem("Base.TrapCage")
local bo = TrapBO:new(PLAYER_OBJ, item)
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.remove_trap = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = newInventoryItem("Base.TrapCage")
local bo = TrapBO:new(PLAYER_OBJ, item)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local luaObject = CTrapSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISRemoveTrapAction:new(PLAYER_OBJ, luaObject, DURATION))
end
}
Tests.add_bait_to_trap = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = newInventoryItem("Base.TrapCage")
local bo = TrapBO:new(PLAYER_OBJ, item)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local luaObject = CTrapSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
item = newInventoryItem("Base.Carrots")
ISTimedActionQueue.add(ISAddBaitAction:new(PLAYER_OBJ, item, luaObject, DURATION))
end
}
Tests.remove_animal_from_trap = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = newInventoryItem("Base.TrapCage")
local bo = TrapBO:new(PLAYER_OBJ, item)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local sysObject = STrapSystem.instance:getLuaObjectAt(x, y, z)
sysObject:setAnimal(Animals[1])
local clientObject = CTrapSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISCheckTrapAction:new(PLAYER_OBJ, clientObject, DURATION))
end
}
Tests.remove_bait_from_trap = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
local item = newInventoryItem("Base.TrapCage")
local bo = TrapBO:new(PLAYER_OBJ, item)
bo.player = PLAYER_NUM
bo:create(x, y, z, false, bo.sprite)
local sysObject = STrapSystem.instance:getLuaObjectAt(x, y, z)
sysObject:addBait("Base.Carrots", 0.0, PLAYER_OBJ)
local clientObject = CTrapSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISRemoveBaitAction:new(PLAYER_OBJ, clientObject, DURATION))
end
}
Tests.farming_plow = {
run = function(self)
local item = newInventoryItem("farming.HandShovel")
local bo = farmingPlot:new(item, PLAYER_OBJ)
bo.player = PLAYER_NUM
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
bo.build = true
bo.canBeBuild = bo:isValid(square, bo.north)
bo:tryBuild(x, y, z)
end
}
Tests.farming_seed = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
local item = newInventoryItem("farming.HandShovel")
local nbOfSeed = farming_vegetableconf.props["Tomato"].seedsRequired
local seeds = {}
for i=1,nbOfSeed do
table.insert(seeds, newInventoryItem("farming.TomatoSeed"))
end
local typeOfSeed = "Tomato"
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISSeedAction:new(PLAYER_OBJ, seeds, nbOfSeed, typeOfSeed, plant, DURATION))
end
}
Tests.farming_fertilize = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
SFarmingSystem.instance:getLuaObjectAt(x, y, z):seed("Tomato")
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
local fertilizer = newInventoryItem("Fertilizer")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISFertilizeAction:new(PLAYER_OBJ, fertilizer, plant, DURATION))
end
}
Tests.farming_water = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
SFarmingSystem.instance:getLuaObjectAt(x, y, z):seed("Tomato")
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
local wateringCan = newInventoryItem("farming.WateredCanFull")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISWaterPlantAction:new(PLAYER_OBJ, wateringCan, 10, square, DURATION))
end
}
Tests.farming_harvest = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
local serverLuaObj = SFarmingSystem.instance:getLuaObjectAt(x, y, z)
serverLuaObj.waterLvl = 100
serverLuaObj:seed("Tomato")
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
SFarmingSystem.instance:growPlant(serverLuaObj, nil, true)
serverLuaObj:saveData()
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISHarvestPlantAction:new(PLAYER_OBJ, plant, DURATION))
end
}
Tests.farming_cure_flies = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
local serverLuaObj = SFarmingSystem.instance:getLuaObjectAt(x, y, z)
serverLuaObj:seed("Tomato")
serverLuaObj.fliesLvl = 5
serverLuaObj:saveData()
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
local cure = newInventoryItem("farming.GardeningSprayCigarettes")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISCureFliesAction:new(PLAYER_OBJ, cure, 5, plant, DURATION))
end
}
Tests.farming_remove = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
square:getFloor():setSprite(getSprite("blends_natural_01_21"))
SFarmingSystem.instance:plow(square)
local serverLuaObj = SFarmingSystem.instance:getLuaObjectAt(x, y, z)
serverLuaObj:seed("Tomato")
local plant = CFarmingSystem.instance:getLuaObjectAt(x, y, z)
local shovel = newPrimaryItem("farming.Shovel")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISShovelAction:new(PLAYER_OBJ, shovel, plant, DURATION))
end
}
Tests.fishing_rod = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
-- square:getFloor():setSprite(getSprite("blends_natural_02_0"))
local rod = newPrimaryItem("Base.FishingRod")
local lure = newSecondaryItem("Base.FishingTackle")
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISFishingAction:new(PLAYER_OBJ, square:getFloor(), rod, lure))
end
}
Tests.fishing_spear = {
run = function(self)
local square,x,y,z = getSquareDelta(2, 2, 0)
removeAllButFloor(square)
-- square:getFloor():setSprite(getSprite("blends_natural_02_0"))
local rod = newPrimaryItem("Base.WoodenLance")
local lure = nil
luautils.walkAdj(PLAYER_OBJ, square)
ISTimedActionQueue.add(ISFishingAction:new(PLAYER_OBJ, square:getFloor(), rod, lure))
end
}
-----
local tickRegistered = false
local testsToRun = {}
local currentTest = nil
local pause = 0
local wasBuildMenuCheat = ISBuildMenu.cheat
local function RunTest(name)
currentTest = name
pause = getPerformance():getFramerate() * 1
print('TEST: '..name)
PLAYER_OBJ = getSpecificPlayer(PLAYER_NUM)
PLAYER_INV = PLAYER_OBJ:getInventory()
PLAYER_SQR = PLAYER_OBJ:getCurrentSquare()
PLAYER_SQR_ORIG = PLAYER_SQR
-- Some actions use endurance
PLAYER_OBJ:getBodyDamage():RestoreToFullHealth()
PLAYER_INV:removeAllItems()
PLAYER_OBJ:clearWornItems()
PLAYER_OBJ:setPrimaryHandItem(nil)
PLAYER_OBJ:setSecondaryHandItem(nil)
PLAYER_OBJ:Say(name)
wasBuildMenuCheat = ISBuildMenu.cheat
ISBuildMenu.cheat = false
Tests[name]:run()
end
local function PostValidate(name)
if Tests[name].validate then
local msg = Tests[name]:validate()
end
ISBuildMenu.cheat = wasBuildMenuCheat
end
local function ShouldSkipTest(name)
return false
end
local function OnTick()
local playerObj = getSpecificPlayer(PLAYER_NUM)
local queue = ISTimedActionQueue.getTimedActionQueue(playerObj)
if not queue or not queue.queue or not queue.queue[1] then
if currentTest then
PostValidate(currentTest)
currentTest = nil
pause = getTimestampMs() + 1000
end
if pause > getTimestampMs() then -- pause so we can view the result
return
end
if PLAYER_OBJ and PLAYER_OBJ:getCurrentSquare() ~= PLAYER_SQR_ORIG then
PLAYER_OBJ:setX(PLAYER_SQR_ORIG:getX() + 0.5)
PLAYER_OBJ:setY(PLAYER_SQR_ORIG:getY() + 0.5)
PLAYER_OBJ:setLx(PLAYER_OBJ:getX())
PLAYER_OBJ:setLy(PLAYER_OBJ:getY())
PLAYER_OBJ:setCurrent(PLAYER_SQR_ORIG)
end
if #testsToRun == 0 then
PLAYER_OBJ = nil
return
end
local testName = testsToRun[1]
table.remove(testsToRun, 1)
if not ShouldSkipTest(test) then
RunTest(testName)
end
end
end
TimedActionTests.runOne = function(name)
if not Tests[name] then
return
end
table.insert(testsToRun, name)
if not tickRegistered then
Events.OnTick.Add(OnTick)
tickRegistered = true
end
end
TimedActionTests.runAll = function()
table.wipe(testsToRun)
for name,func in pairs(Tests) do
table.insert(testsToRun, name)
end
if not tickRegistered then
Events.OnTick.Add(OnTick)
tickRegistered = true
end
end
TimedActionTests.stop = function()
table.wipe(testsToRun)
end
|
hook.Add("PlayerDeath", "robbable_npc_death", function(victim, inflictor, attacker)
if IsValid(victim._activeRobbery) then
victim._activeRobbery:CancelRobbery(victim)
end
end)
hook.Add("PlayerDisconnected", "robbable_npc_disconnect", function(ply)
if IsValid(ply._activeRobbery) then
ply._activeRobbery:CancelRobbery(ply)
end
end)
hook.Add("OnPlayerChangedTeam", "robbable_npc_job", function(ply)
if IsValid(ply._activeRobbery) then
ply._activeRobbery:CancelRobbery(ply)
end
end) |
htmlEscape = { "☺", "☻", "♥", "♦", "♣", "♠", "•", -- ASCII 1-7 (symbols for control characters, see code page 437)
"◘", "○", "◙", "♂", "♀", "♪", "♫", "☼", -- ASCII 8-15
"►", "◄", "↕", "‼", "¶", "§", "▬", "↨", -- ASCII 16-23
"↑", "↓", "↨", "←", "∟", "→", "▲", "▼", -- ASCII 24-31
" ", "!", """, "#", "$", "%", "&", "'", -- ASCII 32-39
"(", ")", "*", "+", ",", "-", ".", "/", -- ASCII 40-47
"0", "1", "2", "3", "4", "5", "6", "7", -- ASCII 48-55
"8", "9", ":", ";", "<", "=", ">", "?", -- ASCII 56-63
"@", "A", "B", "C", "D", "E", "F", "G", -- ASCII 64-71
"H", "I", "J", "K", "L", "M", "N", "O", -- ASCII 72-79
"P", "Q", "R", "S", "T", "U", "V", "W", -- ASCII 80-87
"X", "Y", "Z", "[", "\\", "]", "^", "_", -- ASCII 88-95
"`", "a", "b", "c", "d", "e", "f", "g", -- ASCII 96-103
"h", "i", "j", "k", "l", "m", "n", "o", -- ASCII 104-111
"p", "q", "r", "s", "t", "u", "v", "w", -- ASCII 112-119
"x", "y", "z", "{", "|", "}", "~", "⌂", -- ASCII 120-127
"Ç", "ü", "é", "â", "ä", "à", "å", "ç", -- 128-135 (dos code page 850)
"ê", "ë", "è", "ï", "î", "ì", "Ä", "Å", -- 136-143
"É", "æ", "Æ", "ô", "ö", "ò", "û", "ù", -- 144-151
"ÿ", "Ö", "Ü", "ø", "£", "Ø", "×", "ƒ", -- 152-159
"á", "í", "ó", "ú", "ñ", "Ñ", "ª", "º", -- 160-167
"¿", "®", "¬", "½", "¼", "¡", "«", "»", -- 168-175
"░", "▒", "▓", "│", "┤", "Á", "Â", "À", -- 176-183
"©", "╣", "║", "╗", "╝", "¢", "¥", "┐", -- 184-191
"└", "┴", "┬", "├", "─", "┼", "ã", "Ã", -- 192-199
"╚", "╔", "╩", "╦", "╠", "═", "╬", "¤", -- 200-207
"ð", "Ð", "Ê", "Ë", "È", "ı", "Í", "Î", -- 208-215
"Ï", "┘", "┌", "█", "▄", "¦", "Ì", "▀", -- 216-223
"Ó", "ß", "Ô", "Ò", "õ", "Õ", "µ", "þ", -- 224-231
"Þ", "Ú", "Û", "Ù", "ý", "Ý", "¯", "´", -- 232-239
"≡", "±", "‗", "¾", "¶", "§", "÷", "¸", -- 240-247
"°", "¨", "·", "¹", "³", "²", "■", "□", -- 248-255 (use empty box for 255)
};
htmlEscape[0] = "·" -- in this table, we use a 8 bit character set, where every has a different graphical representation
-- the conversion table should work as a convertion function for strings as well
setmetatable(htmlEscape, {__call = function (tab,str) return string.gsub(str, ".", function (c) return tab[c:byte()] end) end})
function htmlEsc(txt)
s = txt:gsub("%&", "&")
s = s:gsub("%<", "<")
return s:gsub("%>", ">")
end
function iso8859_1_to_utf8(txt)
local s = txt:gsub(".",
function (c)
local b = c:byte()
if b < 128 then
return c
elseif b < 192 then
return string.char(194, b)
else
return string.char(195, b-64)
end
end)
return s
end
|
--[[ CooL( Corona Object-Oriented Lua )
https://github.com/dejayc/CooL
Copyright 2011 Dejay Clayton
All use of this file must comply with the Apache License,
Version 2.0, under which this file is licensed:
http://www.apache.org/licenses/LICENSE-2.0 --]]
return {
display =
{
scaling =
{
--[[ List of possible 'axis' values
axis = "minScale",
axis = "maxScale",
axis = "minResScale",
axis = "maxResScale", -- DEFAULT
axis = "widthScale",
axis = "heightScale",
--]]
-- Particular 'axis' value to use for this application
axis = "maxResScale",
-- Replacement for the underpowered 'imageSuffix' feature
fileLookup =
{
[ 1 ] =
{
{
subdir = { "320x480", "@1x", "sd", "", },
suffix = { "@320x480", "@1x", "" },
},
},
[ 2 ] =
{
{
subdir = { "640x960", "@2x", "hd", "", },
suffix = { "@640x960", "@2x", "", },
},
},
},
},
--[[ List of possible 'statusBar' values
statusBar = "dark",
statusBar = "default", -- DEFAULT
statusBar = "hidden",
statusBar = "translucent",
--]]
-- Particular 'statusBar' value to use for this application
statusBar = "hidden",
},
}
|
EditorSecurityCamera = EditorSecurityCamera or class(MissionScriptEditor)
EditorSecurityCamera._object_original_rotations = {}
function EditorSecurityCamera:create_element()
EditorSecurityCamera.super.create_element(self)
self._element.class = "ElementSecurityCamera"
self._element.values.yaw = 0
self._element.values.pitch = -30
self._element.values.fov = 60
self._element.values.detection_range = 15
self._element.values.suspicion_range = 7
self._element.values.detection_delay_min = 2
self._element.values.detection_delay_max = 3
end
function EditorSecurityCamera:_build_panel()
self:_create_panel()
self:BuildUnitsManage("camera_u_id", nil, nil, {text = "Camera unit", single_select = true, not_table = true, check_unit = function(unit)
return unit:base() and unit:base().security_camera
end})
self:BooleanCtrl("ai_enabled")
self:BooleanCtrl("apply_settings")
self:NumberCtrl("yaw", {min = -180, max = 180, help = "Specify camera yaw (degrees)."})
self:NumberCtrl("pitch", {min = -90, max = 90, help = "Specify camera pitch (degrees)."})
self:NumberCtrl("fov", {min = 0, max = 180, help = "Specify camera FOV (degrees)."})
self:NumberCtrl("detection_range", {min = 0, floats = 0, help = "Specify camera detection_range (meters)."})
self:NumberCtrl("suspicion_range", {min = 0, floats = 0, help = "Specify camera suspicion_range."})
self:NumberCtrl("detection_delay_min", {min = 0, floats = 0, help = "Detection delay at zero distance."})
self:NumberCtrl("detection_delay_max", {min = 0, floats = 0, help = "Detection delay at max distance."})
end |
--[[
IPyLua
Copyright (c) 2015 Francisco Zamora-Martinez. Simplified, less deps and making
it work.
https://github.com/pakozm/IPyLua
Released under the MIT License, see the LICENSE file.
usage: lua IPyLuaKernel.lua CONNECTION_FILENAME
--]]
-- This file is based on the work of Patrick Rapin, adapted by Reuben Thomas:
-- https://github.com/rrthomas/lua-rlcompleter/blob/master/rlcompleter.lua
local ok,lfs = pcall(require, "lfs") if not ok then lfs = nil end
local type = luatype or type
-- The list of Lua keywords
local keywords = {
'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for',
'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'
}
local word_break_chars_pattern = " \t\n\"\\'><=%;%:%+%-%*%/%%%^%~%#%{%}%(%)%[%]%.%,"
local last_word_pattern = ("[%s]?([^%s]*)$"):format(word_break_chars_pattern,
word_break_chars_pattern)
local endpos_pattern = ("(.*)[%s]?"):format(word_break_chars_pattern)
-- Returns index_table field from a metatable, which is a copy of __index table
-- in APRIL-ANN
local function get_index(mt)
if type(mt.__index) == "table" then return mt.__index end
return mt.index_table -- only for APRIL-ANN
end
-- This function needs to be called to complete current input line
local function do_completion(line, text, cursor_pos, env_G, env, _G)
local line = line:sub(1,cursor_pos):match("([^\n]*)[\n]?$")
-- Extract the last word.
local word=line:match( last_word_pattern ) or ""
local startpos,endpos=1,#(line:match(endpos_pattern) or "")
-- Helper function registering possible completion words, verifying matches.
local matches_set = {}
local matches = {}
local function add(value)
value = tostring(value)
if not matches_set[value] then
if value:match("^" .. word) then
matches_set[value] = true
matches[#matches + 1] = value
end
end
end
local filenames_path
-- This function does the same job as the default completion of readline,
-- completing paths and filenames.
local function filename_list(str)
if lfs then
local path, name = str:match("(.*)[\\/]+(.*)")
path = (path or ".") .. "/"
filenames_path = path
if str:sub(1,1) == "/" then path = "/" .. path end
name = name or str
if not lfs.attributes(path) then return end
for f in lfs.dir(path) do
if (lfs.attributes(path .. f) or {}).mode == 'directory' then
add(f .. "/")
else
add(f)
end
end
end
end
-- This function is called in a context where a keyword or a global
-- variable can be inserted. Local variables cannot be listed!
local function add_globals()
for _, k in ipairs(keywords) do add(k) end
for i,tbl in ipairs{env, env_G, _G} do
for k in pairs(tbl) do add(k) end
end
end
-- Main completion function. It evaluates the current sub-expression
-- to determine its type. Currently supports tables fields, global
-- variables and function prototype completion.
local function contextual_list(expr, sep, str)
if str then
return filename_list(str)
end
if expr and expr ~= "" then
local v = load("return " .. expr, nil, nil, env)
if v then
v = v()
local t = type(v)
if sep == '.' or sep == ':' then
if t == 'table' then
for k, v in pairs(v) do
if type(k) == 'string' and (sep ~= ':' or type(v) == "function") then
add(k)
end
end
end
if (t == 'string' or t == 'table' or t == 'userdata') and getmetatable(v) then
local aux = v
repeat
local mt = getmetatable(aux)
local idx = get_index(mt)
if idx and type(idx) == 'table' then
for k,v in pairs(idx) do
add(k)
end
end
if rawequal(aux,idx) then break end -- avoid infinite loops
aux = idx
until not aux or not getmetatable(aux)
end
elseif sep == '[' then
if t == 'table' then
for k in pairs(v) do
if type(k) == 'number' then
add(k .. "]")
end
end
if word ~= "" then add_globals() end
end
end
end
end
if #matches == 0 then
if not sep or sep~="." then add_globals() end
end
end
-- This complex function tries to simplify the input line, by removing
-- literal strings, full table constructors and balanced groups of
-- parentheses. Returns the sub-expression preceding the word, the
-- separator item ( '.', ':', '[', '(' ) and the current string in case
-- of an unfinished string literal.
local function simplify_expression(expr)
-- Replace annoying sequences \' and \" inside literal strings
expr = expr:gsub("\\(['\"])", function (c)
return string.format("\\%03d", string.byte(c))
end)
local curstring
-- Remove (finished and unfinished) literal strings
while true do
local idx1, _, equals = expr:find("%[(=*)%[")
local idx2, _, sign = expr:find("(['\"])")
if idx1 == nil and idx2 == nil then
break
end
local idx, startpat, endpat
if (idx1 or math.huge) < (idx2 or math.huge) then
idx, startpat, endpat = idx1, "%[" .. equals .. "%[", "%]" .. equals .. "%]"
else
idx, startpat, endpat = idx2, sign, sign
end
if expr:sub(idx):find("^" .. startpat .. ".-" .. endpat) then
expr = expr:gsub(startpat .. "(.-)" .. endpat, " STRING ")
else
expr = expr:gsub(startpat .. "(.*)", function (str)
curstring = str
return "(CURSTRING "
end)
end
end
expr = expr:gsub("%b()"," PAREN ") -- Remove groups of parentheses
expr = expr:gsub("%b{}"," TABLE ") -- Remove table constructors
-- Avoid two consecutive words without operator
expr = expr:gsub("(%w)%s+(%w)","%1|%2")
expr = expr:gsub("%s+", "") -- Remove now useless spaces
-- This main regular expression looks for table indexes and function calls.
return curstring, expr:match("([%.%w%[%]_]-)([:%.%[%(])" .. word .. "$")
end
-- Now call the processing functions and return the list of results.
local str, expr, sep = simplify_expression(line:sub(1, endpos))
contextual_list(expr, sep, str)
table.sort(matches)
-- rebuild the list of matches to prepend all required characters
if text ~= "" then
if filenames_path then
expr = filenames_path
sep = ""
elseif sep ~= "." then
expr = line:match("([^%(%)%[%]%,%:><=%+%-%*%^'\\\"])*"..word.."$")
sep = ""
end
if expr then
local prefix = expr .. (sep or "")
word = prefix .. word
for i,v in ipairs(matches) do matches[i] = prefix .. v end
end
end
return {
status = "ok",
matches = matches,
matched_text = word,
-- cursor_start = 1,
-- cusor_end = cursor_pos,
metadata = {},
}
end
return {
do_completion = do_completion,
}
|
#!/usr/bin/env lua
local i = 1
local j = 2
local sum = 0
while i < 4000000 do
i, j = j, i + j
if (i % 2 == 0) then
sum = sum + i
end
end
print(sum)
|
-- +---------------------------+
-- | Neovim lua config |
-- +---------------------------+
-- | Author: Étienne Marais |
-- | Version: |
-- +---------------------------+
-- General aliases
local fn = vim.fn
local execute = vim.api.nvim_command
-- Define map leader
vim.g.mapleader = ' '
-- Load important settings
require('settings')
-- TODO: extract to lua/plugins/packer {{
-- Load packer if not in path
local install_path = fn.stdpath('data')..'/site/pack/packer/opt/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
execute('!git clone https://github.com/wbthomason/packer.nvim '..install_path)
end
vim.cmd [[packadd packer.nvim]]
-- Auto reload lua plugins
-- TODO: update to packer.lua
vim.cmd 'autocmd BufWritePost plugins.lua PackerCompile'
-- }}
-- TODO: Move load settings here
-- Load keybindings
require('keys')
-- TODO: insert load packers here
-- Load plugins
-- TODO: rename to packer.lua
require('plugins')
-- Load plugin configs
require('plugins/telescope')
|
newoption {
trigger = "sdl-include-path",
value = "path",
description = "The location of your SDL2 header files"
}
newoption {
trigger = "sdl-link-path",
value = "path",
description = "The location of your SDL2 link libraries"
}
newoption {
trigger = "use-sdl-framework",
description = "Use the installed SDL2 framework (on MacOS)"
}
local projectlocation = os.getcwd()
local gl3wlocation = path.join(os.getcwd(), "dependencies/gl3w")
local imguilocation = path.join(os.getcwd(), "dependencies/imgui-1.82")
if _ACTION then
projectlocation = path.join(projectlocation, "build", _ACTION)
end
function imnodes_example_project(name, example_file)
project(name)
location(projectlocation)
kind "ConsoleApp"
language "C++"
cppdialect "C++11"
targetdir "bin/%{cfg.buildcfg}"
debugdir "bin/%{cfg.buildcfg}"
files {"example/main.cpp", path.join("example", example_file) }
includedirs {
os.getcwd(),
imguilocation,
path.join(gl3wlocation, "include"),
}
links { "gl3w", "imgui", "imnodes" }
defines { "IMGUI_IMPL_OPENGL_LOADER_GL3W" }
if _OPTIONS["sdl-include-path"] then
includedirs { _OPTIONS["sdl-include-path"] }
end
if _OPTIONS["sdl-link-path"] then
libdirs { _OPTIONS["sdl-link-path"] }
filter "system:macosx"
links {
"iconv",
"AudioToolbox.framework",
"Carbon.framework",
"Cocoa.framework",
"CoreAudio.framework",
"CoreVideo.framework",
"ForceFeedback.framework",
"IOKit.framework"
}
filter "*"
end
if _OPTIONS["use-sdl-framework"] then
includedirs { "/Library/Frameworks/SDL2.framework/Headers" }
linkoptions { "-F/Library/Frameworks -framework SDL2 -framework CoreFoundation" }
else
links { "SDL2" }
end
filter "system:windows"
defines { "SDL_MAIN_HANDLED" }
links { "opengl32" }
if _OPTIONS["sdl-link-path"] then
postbuildcommands {
"{COPY} " ..
path.join(os.getcwd(), _OPTIONS["sdl-link-path"].."/../bin/", "SDL2.dll") ..
" %{cfg.targetdir}" }
end
filter "system:linux"
links { "dl" }
end
workspace "imnodes"
configurations { "Debug", "Release" }
architecture "x86_64"
defines { "IMGUI_DISABLE_OBSOLETE_FUNCTIONS" }
filter "configurations:Debug"
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
warnings "Extra"
startproject "colornode"
group "dependencies"
project "gl3w"
location(projectlocation)
kind "StaticLib"
language "C"
targetdir "lib/%{cfg.buildcfg}"
files { path.join(gl3wlocation, "src/gl3w.c") }
includedirs { path.join(gl3wlocation, "include") }
project "imgui"
location(projectlocation)
kind "StaticLib"
language "C++"
cppdialect "C++98"
targetdir "lib/%{cfg.buildcfg}"
files { path.join(imguilocation, "**.cpp") }
includedirs {
imguilocation,
path.join(gl3wlocation, "include") }
if _OPTIONS["sdl-include-path"] then
includedirs { _OPTIONS["sdl-include-path"] }
end
if _OPTIONS["use-sdl-framework"] then
includedirs { "/Library/Frameworks/SDL2.framework/Headers" }
end
group "imnodes"
project "imnodes"
location(projectlocation)
kind "StaticLib"
language "C++"
cppdialect "C++98"
enablewarnings { "all" }
targetdir "lib/%{cfg.buildcfg}"
files { "imnodes.h", "imnodes.cpp" }
includedirs { path.join(imguilocation) }
group "examples"
imnodes_example_project("hello", "hello.cpp")
imnodes_example_project("saveload", "save_load.cpp")
imnodes_example_project("colornode", "color_node_editor.cpp")
imnodes_example_project("multieditor", "multi_editor.cpp")
|
local Command = VH_CommandLib.Command:new("God", VH_CommandLib.UserTypes.Admin, "Set the godmode of the player(s).", "")
Command:addArg(VH_CommandLib.ArgTypes.Plrs, {required = true})
Command:addAlias({Prefix = "!", Alias = {"god", "ungod", "tgod"}})
Command.Callback = function(Sender, Alias, Targets)
local Success, Toggle = VH_CommandLib.DoToggleableCommand(Alias, {"god"}, {"ungod"}, {"tgod"})
for _, ply in ipairs(Targets) do
if Toggle then
ply:PLGod(!ply:HasGodMode())
else
ply:PLGod(Success)
end
end
if Toggle then
VH_CommandLib.SendCommandMessage(Sender, "toggled god mode on", Targets, "")
else
VH_CommandLib.SendCommandMessage(Sender, (Success and "" or "un").."godded", Targets, "")
end
return ""
end |
--[[
Copyright 2016 Marek Vavrusa <[email protected]>
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.
]]
local ffi = require('ffi')
local BPF = ffi.typeof('struct bpf')
ffi.cdef [[
struct sk_buff {
uint32_t len;
uint32_t pkt_type;
uint32_t mark;
uint32_t queue_mapping;
uint32_t protocol;
uint32_t vlan_present;
uint32_t vlan_tci;
uint32_t vlan_proto;
uint32_t priority;
uint32_t ingress_ifindex;
uint32_t ifindex;
uint32_t tc_index;
uint32_t cb[5];
uint32_t hash;
uint32_t tc_classid;
uint32_t data;
uint32_t data_end;
uint32_t napi_id;
/* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */
uint32_t family;
uint32_t remote_ip4; /* Stored in network byte order */
uint32_t local_ip4; /* Stored in network byte order */
uint32_t remote_ip6[4]; /* Stored in network byte order */
uint32_t local_ip6[4]; /* Stored in network byte order */
uint32_t remote_port; /* Stored in network byte order */
uint32_t local_port; /* stored in host byte order */
/* ... here. */
uint32_t data_meta;
};
struct net_off_t {
uint8_t ver:4;
} __attribute__((packed));
struct eth_t {
uint8_t dst[6];
uint8_t src[6];
uint16_t type;
} __attribute__((packed));
struct dot1q_t {
uint16_t pri:3;
uint16_t cfi:1;
uint16_t vlanid:12;
uint16_t type;
} __attribute__((packed));
struct arp_t {
uint16_t htype;
uint16_t ptype;
uint8_t hlen;
uint8_t plen;
uint16_t oper;
uint8_t sha[6];
uint32_t spa;
uint8_t tha[6];
uint32_t tpa;
} __attribute__((packed));
struct ip_t {
uint8_t ver:4;
uint8_t hlen:4;
uint8_t tos;
uint16_t tlen;
uint16_t identification;
uint16_t ffo_unused:1;
uint16_t df:1;
uint16_t mf:1;
uint16_t foffset:13;
uint8_t ttl;
uint8_t proto;
uint16_t hchecksum;
uint32_t src;
uint32_t dst;
} __attribute__((packed));
struct icmp_t {
uint8_t type;
uint8_t code;
uint16_t checksum;
} __attribute__((packed));
struct ip6_t {
uint32_t ver:4;
uint32_t priority:8;
uint32_t flow_label:20;
uint16_t payload_len;
uint8_t next_header;
uint8_t hop_limit;
uint64_t src_hi;
uint64_t src_lo;
uint64_t dst_hi;
uint64_t dst_lo;
} __attribute__((packed));
struct ip6_opt_t {
uint8_t next_header;
uint8_t ext_len;
uint8_t pad[6];
} __attribute__((packed));
struct icmp6_t {
uint8_t type;
uint8_t code;
uint16_t checksum;
} __attribute__((packed));
struct udp_t {
uint16_t src_port;
uint16_t dst_port;
uint16_t length;
uint16_t crc;
} __attribute__((packed));
struct tcp_t {
uint16_t src_port;
uint16_t dst_port;
uint32_t seq_num;
uint32_t ack_num;
uint8_t offset:4;
uint8_t reserved:4;
uint8_t flag_cwr:1;
uint8_t flag_ece:1;
uint8_t flag_urg:1;
uint8_t flag_ack:1;
uint8_t flag_psh:1;
uint8_t flag_rst:1;
uint8_t flag_syn:1;
uint8_t flag_fin:1;
uint16_t rcv_wnd;
uint16_t cksum;
uint16_t urg_ptr;
} __attribute__((packed));
struct vxlan_t {
uint32_t rsv1:4;
uint32_t iflag:1;
uint32_t rsv2:3;
uint32_t rsv3:24;
uint32_t key:24;
uint32_t rsv4:8;
} __attribute__((packed));
]]
-- Architecture-specific ptrace register layout
local S = require('syscall')
local arch = S.abi.arch
local parm_to_reg = {}
if arch == 'x64' then
ffi.cdef [[
struct pt_regs {
unsigned long r15;
unsigned long r14;
unsigned long r13;
unsigned long r12;
unsigned long bp;
unsigned long bx;
unsigned long r11;
unsigned long r10;
unsigned long r9;
unsigned long r8;
unsigned long ax;
unsigned long cx;
unsigned long dx;
unsigned long si;
unsigned long di;
unsigned long orig_ax;
unsigned long ip;
unsigned long cs;
unsigned long flags;
unsigned long sp;
unsigned long ss;
};]]
parm_to_reg = {parm1='di', parm2='si', parm3='dx', parm4='cx', parm5='r8', ret='sp', fp='bp'}
else
ffi.cdef 'struct pt_regs {};'
end
-- Map symbolic registers to architecture ABI
ffi.metatype('struct pt_regs', {
__index = function (_ --[[t]],k)
return assert(parm_to_reg[k], 'no such register: '..k)
end,
})
local M = {}
-- Dissector interface
local function dissector(type, e, dst, src, field)
local parent = e.V[src].const
-- Create new dissector variable
e.vcopy(dst, src)
-- Compute and materialize new dissector offset from parent
e.V[dst].const = {off=e.V[src].const.off, __dissector=e.V[src].const.__dissector}
parent.__dissector[field](e, dst)
e.V[dst].const.__dissector = type
end
M.dissector = dissector
-- Get current effective offset, load field value at an offset relative to it and
-- add its value to compute next effective offset (e.g. udp_off = ip_off + pkt[ip_off].hlen)
local function next_offset(e, var, type, off, mask, shift)
local d = e.V[var].const
-- Materialize relative offset value in R0
local dst_reg, tmp_reg
if d.off then
dst_reg = e.vreg(var, 0, true)
tmp_reg = dst_reg -- Use target register to avoid copy
e.emit(BPF.LD + BPF.ABS + e.const_width[ffi.sizeof(type)], tmp_reg, 0, 0, d.off + off or 0)
else
tmp_reg = e.vreg(e.tmpvar, 0, true, type) -- Reserve R0 for temporary relative offset
dst_reg = e.vreg(var) -- Must rematerialize (if it was spilled by tmp var)
e.emit(BPF.LD + BPF.IND + e.const_width[ffi.sizeof(type)], tmp_reg, dst_reg, 0, off or 0)
end
-- Finalize relative offset
if mask then
e.emit(BPF.ALU + BPF.AND + BPF.K, tmp_reg, 0, 0, mask)
end
if shift and shift ~= 0 then
local op = BPF.LSH
if shift < 0 then
op = BPF.RSH
shift = -shift
end
e.emit(BPF.ALU + op + BPF.K, tmp_reg, 0, 0, shift)
end
-- Add to base offset to turn it into effective address
if dst_reg ~= tmp_reg then
e.emit(BPF.ALU + BPF.ADD + BPF.X, dst_reg, tmp_reg, 0, 0)
else
e.emit(BPF.ALU + BPF.ADD + BPF.K, dst_reg, 0, 0, d.off)
end
-- Discard temporary allocations
d.off = nil
e.V[e.tmpvar].reg = nil
end
local function next_skip(e, var, off)
local d = e.V[var].const
if not d.off then
local dst_reg = e.vreg(var)
e.emit(BPF.ALU64 + BPF.ADD + BPF.K, dst_reg, 0, 0, off)
else
d.off = d.off + off
end
end
local function skip_eth(e, dst)
-- IP starts right after ETH header (fixed size)
local d = e.V[dst].const
d.off = d.off + ffi.sizeof('struct eth_t')
end
-- Export types
M.type = function(typestr, t)
t = t or {}
t.__dissector=ffi.typeof(typestr)
return t
end
M.skb = M.type('struct sk_buff', {source='ptr_to_ctx'})
M.pt_regs = M.type('struct pt_regs', {source='ptr_to_probe'})
M.pkt = M.type('struct eth_t', {off=0, source='ptr_to_pkt'}) -- skb needs special accessors
-- M.eth = function (...) return dissector(ffi.typeof('struct eth_t'), ...) end
M.dot1q = function (...) return dissector(ffi.typeof('struct dot1q_t'), ...) end
M.arp = function (...) return dissector(ffi.typeof('struct arp_t'), ...) end
M.icmp = function (...) return dissector(ffi.typeof('struct icmp_t'), ...) end
M.ip = function (...) return dissector(ffi.typeof('struct ip_t'), ...) end
M.icmp6 = function (...) return dissector(ffi.typeof('struct icmp6_t'), ...) end
M.ip6 = function (...) return dissector(ffi.typeof('struct ip6_t'), ...) end
M.ip6_opt = function (...) return dissector(ffi.typeof('struct ip6_opt_t'), ...) end
M.udp = function (...) return dissector(ffi.typeof('struct udp_t'), ...) end
M.tcp = function (...) return dissector(ffi.typeof('struct tcp_t'), ...) end
M.vxlan = function (...) return dissector(ffi.typeof('struct vxlan_t'), ...) end
M.data = function (...) return dissector(ffi.typeof('uint8_t'), ...) end
M.net_off = function (...) return dissector(ffi.typeof('struct net_off_t'), ...) end
-- Metatables
ffi.metatype(ffi.typeof('struct eth_t'), {
__index = {
ip = skip_eth,
ip6 = skip_eth,
net_off = function (e, dst)
next_skip(e, dst, BPF.NET_OFF)
end,
}
})
ffi.metatype(ffi.typeof('struct net_off_t'), {
__index = {
ip = function () end,
ip6 = function () end,
}
})
ffi.metatype(ffi.typeof('struct ip_t'), {
__index = {
-- Skip IP header length (stored as number of words)
-- e.g. hlen = 5, Header Length = 5 x sizeof(u32) = 20 octets
-- Mask first nibble and shift by 2 (multiplication by 4)
icmp = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), 0, 0x0f, 2) end,
udp = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), 0, 0x0f, 2) end,
tcp = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), 0, 0x0f, 2) end,
}
})
ffi.metatype(ffi.typeof('struct ip6_t'), {
__index = {
-- Skip fixed IPv6 header length (40 bytes)
-- The caller must check the value of `next_header` to skip any extension headers
icmp6 = function(e, dst) next_skip(e, dst, ffi.sizeof('struct ip6_t'), 0) end,
udp = function(e, dst) next_skip(e, dst, ffi.sizeof('struct ip6_t'), 0) end,
tcp = function(e, dst) next_skip(e, dst, ffi.sizeof('struct ip6_t'), 0) end,
ip6_opt = function(e, dst) next_skip(e, dst, ffi.sizeof('struct ip6_t'), 0) end,
}
})
local ip6_opt_ext_len_off = ffi.offsetof('struct ip6_opt_t', 'ext_len')
ffi.metatype(ffi.typeof('struct ip6_opt_t'), {
__index = {
-- Skip IPv6 extension header length (field `ext_len`)
icmp6 = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), ip6_opt_ext_len_off) end,
udp = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), ip6_opt_ext_len_off) end,
tcp = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), ip6_opt_ext_len_off) end,
ip6_opt = function(e, dst) next_offset(e, dst, ffi.typeof('uint8_t'), ip6_opt_ext_len_off) end,
}
})
ffi.metatype(ffi.typeof('struct tcp_t'), {
__index = {
-- Skip TCP header length (stored as number of words)
-- e.g. hlen = 5, Header Length = 5 x sizeof(u32) = 20 octets
data = function(e, dst)
next_offset(e, dst, ffi.typeof('uint8_t'), ffi.offsetof('struct tcp_t', 'offset'), 0xf0, -2)
end,
}
})
ffi.metatype(ffi.typeof('struct udp_t'), {
__index = {
-- Skip UDP header length (8 octets)
data = function(e, dst)
next_skip(e, dst, ffi.sizeof('struct udp_t'))
end,
}
})
-- Constants
M.c = {
eth = { -- Constants http://standards.ieee.org/regauth/ethertype
ip = 0x0800, -- IP (v4) protocol
ip6 = 0x86dd, -- IP (v6) protocol
arp = 0x0806, -- Address resolution protocol
revarp = 0x8035, -- Reverse addr resolution protocol
vlan = 0x8100, -- IEEE 802.1Q VLAN tagging
},
ip = {
-- Reserved Addresses
addr_any = 0x00000000, -- 0.0.0.0
addr_broadcast = 0xffffffff, -- 255.255.255.255
addr_loopback = 0x7f000001, -- 127.0.0.1
addr_mcast_all = 0xe0000001, -- 224.0.0.1
addr_mcast_local = 0xe00000ff, -- 224.0.0.255
-- Type of service (ip_tos), RFC 1349 ("obsoleted by RFC 2474")
tos_default = 0x00, -- default
tos_lowdelay = 0x10, -- low delay
tos_throughput = 0x08, -- high throughput
tos_reliability = 0x04, -- high reliability
tos_lowcost = 0x02, -- low monetary cost - XXX
tos_ect = 0x02, -- ECN-capable transport
tos_ce = 0x01, -- congestion experienced
-- Fragmentation flags (ip_off)
rf = 0x8000, -- reserved
df = 0x4000, -- don't fragment
mf = 0x2000, -- more fragments (not last frag)
offmask = 0x1fff, -- mask for fragment offset
-- Time-to-live (ip_ttl), seconds
ttl_default = 64, -- default ttl, RFC 1122, RFC 1340
ttl_max = 255, -- maximum ttl
-- Protocol (ip_p) - http://www.iana.org/assignments/protocol-numbers
proto_ip = 0, -- dummy for IP
proto_hopopts = 0, -- IPv6 hop-by-hop options
proto_icmp = 1, -- ICMP
proto_igmp = 2, -- IGMP
proto_ggp = 3, -- gateway-gateway protocol
proto_ipip = 4, -- IP in IP
proto_st = 5, -- ST datagram mode
proto_tcp = 6, -- TCP
proto_cbt = 7, -- CBT
proto_egp = 8, -- exterior gateway protocol
proto_igp = 9, -- interior gateway protocol
proto_bbnrcc = 10, -- BBN RCC monitoring
proto_nvp = 11, -- Network Voice Protocol
proto_pup = 12, -- PARC universal packet
proto_argus = 13, -- ARGUS
proto_emcon = 14, -- EMCON
proto_xnet = 15, -- Cross Net Debugger
proto_chaos = 16, -- Chaos
proto_udp = 17, -- UDP
proto_mux = 18, -- multiplexing
proto_dcnmeas = 19, -- DCN measurement
proto_hmp = 20, -- Host Monitoring Protocol
proto_prm = 21, -- Packet Radio Measurement
proto_idp = 22, -- Xerox NS IDP
proto_trunk1 = 23, -- Trunk-1
proto_trunk2 = 24, -- Trunk-2
proto_leaf1 = 25, -- Leaf-1
proto_leaf2 = 26, -- Leaf-2
proto_rdp = 27, -- "Reliable Datagram" proto
proto_irtp = 28, -- Inet Reliable Transaction
proto_tp = 29, -- ISO TP class 4
proto_netblt = 30, -- Bulk Data Transfer
proto_mfpnsp = 31, -- MFE Network Services
proto_meritinp= 32, -- Merit Internodal Protocol
proto_sep = 33, -- Sequential Exchange proto
proto_3pc = 34, -- Third Party Connect proto
proto_idpr = 35, -- Interdomain Policy Route
proto_xtp = 36, -- Xpress Transfer Protocol
proto_ddp = 37, -- Datagram Delivery Proto
proto_cmtp = 38, -- IDPR Ctrl Message Trans
proto_tppp = 39, -- TP++ Transport Protocol
proto_il = 40, -- IL Transport Protocol
proto_ip6 = 41, -- IPv6
proto_sdrp = 42, -- Source Demand Routing
proto_routing = 43, -- IPv6 routing header
proto_fragment= 44, -- IPv6 fragmentation header
proto_rsvp = 46, -- Reservation protocol
proto_gre = 47, -- General Routing Encap
proto_mhrp = 48, -- Mobile Host Routing
proto_ena = 49, -- ENA
proto_esp = 50, -- Encap Security Payload
proto_ah = 51, -- Authentication Header
proto_inlsp = 52, -- Integated Net Layer Sec
proto_swipe = 53, -- SWIPE
proto_narp = 54, -- NBMA Address Resolution
proto_mobile = 55, -- Mobile IP, RFC 2004
proto_tlsp = 56, -- Transport Layer Security
proto_skip = 57, -- SKIP
proto_icmp6 = 58, -- ICMP for IPv6
proto_none = 59, -- IPv6 no next header
proto_dstopts = 60, -- IPv6 destination options
proto_anyhost = 61, -- any host internal proto
proto_cftp = 62, -- CFTP
proto_anynet = 63, -- any local network
proto_expak = 64, -- SATNET and Backroom EXPAK
proto_kryptolan = 65, -- Kryptolan
proto_rvd = 66, -- MIT Remote Virtual Disk
proto_ippc = 67, -- Inet Pluribus Packet Core
proto_distfs = 68, -- any distributed fs
proto_satmon = 69, -- SATNET Monitoring
proto_visa = 70, -- VISA Protocol
proto_ipcv = 71, -- Inet Packet Core Utility
proto_cpnx = 72, -- Comp Proto Net Executive
proto_cphb = 73, -- Comp Protocol Heart Beat
proto_wsn = 74, -- Wang Span Network
proto_pvp = 75, -- Packet Video Protocol
proto_brsatmon= 76, -- Backroom SATNET Monitor
proto_sunnd = 77, -- SUN ND Protocol
proto_wbmon = 78, -- WIDEBAND Monitoring
proto_wbexpak = 79, -- WIDEBAND EXPAK
proto_eon = 80, -- ISO CNLP
proto_vmtp = 81, -- Versatile Msg Transport
proto_svmtp = 82, -- Secure VMTP
proto_vines = 83, -- VINES
proto_ttp = 84, -- TTP
proto_nsfigp = 85, -- NSFNET-IGP
proto_dgp = 86, -- Dissimilar Gateway Proto
proto_tcf = 87, -- TCF
proto_eigrp = 88, -- EIGRP
proto_ospf = 89, -- Open Shortest Path First
proto_spriterpc= 90, -- Sprite RPC Protocol
proto_larp = 91, -- Locus Address Resolution
proto_mtp = 92, -- Multicast Transport Proto
proto_ax25 = 93, -- AX.25 Frames
proto_ipipencap= 94, -- yet-another IP encap
proto_micp = 95, -- Mobile Internet Ctrl
proto_sccsp = 96, -- Semaphore Comm Sec Proto
proto_etherip = 97, -- Ethernet in IPv4
proto_encap = 98, -- encapsulation header
proto_anyenc = 99, -- private encryption scheme
proto_gmtp = 100, -- GMTP
proto_ifmp = 101, -- Ipsilon Flow Mgmt Proto
proto_pnni = 102, -- PNNI over IP
proto_pim = 103, -- Protocol Indep Multicast
proto_aris = 104, -- ARIS
proto_scps = 105, -- SCPS
proto_qnx = 106, -- QNX
proto_an = 107, -- Active Networks
proto_ipcomp = 108, -- IP Payload Compression
proto_snp = 109, -- Sitara Networks Protocol
proto_compaqpeer= 110, -- Compaq Peer Protocol
proto_ipxip = 111, -- IPX in IP
proto_vrrp = 112, -- Virtual Router Redundancy
proto_pgm = 113, -- PGM Reliable Transport
proto_any0hop = 114, -- 0-hop protocol
proto_l2tp = 115, -- Layer 2 Tunneling Proto
proto_ddx = 116, -- D-II Data Exchange (DDX)
proto_iatp = 117, -- Interactive Agent Xfer
proto_stp = 118, -- Schedule Transfer Proto
proto_srp = 119, -- SpectraLink Radio Proto
proto_uti = 120, -- UTI
proto_smp = 121, -- Simple Message Protocol
proto_sm = 122, -- SM
proto_ptp = 123, -- Performance Transparency
proto_isis = 124, -- ISIS over IPv4
proto_fire = 125, -- FIRE
proto_crtp = 126, -- Combat Radio Transport
proto_crudp = 127, -- Combat Radio UDP
proto_sscopmce= 128, -- SSCOPMCE
proto_iplt = 129, -- IPLT
proto_sps = 130, -- Secure Packet Shield
proto_pipe = 131, -- Private IP Encap in IP
proto_sctp = 132, -- Stream Ctrl Transmission
proto_fc = 133, -- Fibre Channel
proto_rsvpign = 134, -- RSVP-E2E-IGNORE
proto_raw = 255, -- Raw IP packets
proto_reserved= 255, -- Reserved
},
}
return M |
-- ===============
-- HIGHLIGHT UTILS
-- ===============
-- Created by datwaft <github.com/datwaft>
local M = require'bubbly.core.module'.new('utils.highlight')
local titlecase = require'bubbly.utils.string'.titlecase
-- Generates a highlight vim command following :help highlight
---@param name string
---@param foreground string
---@param background string
---@param special string | nil
---@return string
function M.highlight(name, foreground, background, special)
local command = 'highlight '
command = command..name..' '
command = command..'guifg='..foreground..' '
command = command..'guibg='..background..' '
if special then
command = command..'gui='..special..' '
end
return command
end
-- Generates a highlight name
---@param foreground string | nil
---@param background string
---@param special string | nil
function M.gethighlight(foreground, background, special)
if not foreground then foreground = '' end
if not special then special = '' end
return 'Bubbly'..titlecase(foreground)..titlecase(background)..
titlecase(special)
end
-- Parses a palette value
---@param usercolor string
---@return string
function M.hlparser(usercolor)
if string.sub(usercolor, 1, 1) == '#' then
-- Return the string as is if it represents a HEX
return usercolor
end
-- Extract Group and foreground/background
local hlGroup = string.match(usercolor, "(%w+)%s")
if hlGroup == nil then
-- This is the 256 naming colorscheme
return usercolor
end
local key = string.match(usercolor, "%s(%w+)")
-- Get colors from vim
hlGroup = vim.api.nvim_get_hl_by_name(hlGroup, true)
if hlGroup[key] then
-- The color exists, return its HEX form
return string.format("#%x", hlGroup[key])
end
-- The color is absent, use a transparent color.
return "None"
end
return M
|
UpdateTriggerCommand = Command:extends{}
UpdateTriggerCommand.className = "UpdateTriggerCommand"
function UpdateTriggerCommand:init(trigger)
self.trigger = trigger
end
function UpdateTriggerCommand:execute()
self.old = SB.model.triggerManager:getTrigger(self.trigger.id)
SB.model.triggerManager:setTrigger(self.trigger.id, self.trigger)
end
function UpdateTriggerCommand:unexecute()
SB.model.triggerManager:setTrigger(self.trigger.id, self.old)
end
|
--------------------------------
-- @module Physics3DRigidBody
-- @extend Physics3DObject
-- @parent_module cc
--------------------------------
-- Set the acceleration.
-- @function [parent=#Physics3DRigidBody] setGravity
-- @param self
-- @param #vec3_table acceleration
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get friction.
-- @function [parent=#Physics3DRigidBody] getFriction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @overload self, float
-- @overload self, vec3_table
-- @function [parent=#Physics3DRigidBody] setAngularFactor
-- @param self
-- @param #vec3_table angFac
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] addConstraint
-- @param self
-- @param #cc.Physics3DConstraint constraint
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the pointer of btRigidBody.
-- @function [parent=#Physics3DRigidBody] getRigidBody
-- @param self
-- @return btRigidBody#btRigidBody ret (return value: btRigidBody)
--------------------------------
-- Get total force.
-- @function [parent=#Physics3DRigidBody] getTotalForce
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get the total number of constraints.
-- @function [parent=#Physics3DRigidBody] getConstraintCount
-- @param self
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
-- Apply a central force.<br>
-- param force the value of the force
-- @function [parent=#Physics3DRigidBody] applyCentralForce
-- @param self
-- @param #vec3_table force
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set mass and inertia.
-- @function [parent=#Physics3DRigidBody] setMassProps
-- @param self
-- @param #float mass
-- @param #vec3_table inertia
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set friction.
-- @function [parent=#Physics3DRigidBody] setFriction
-- @param self
-- @param #float frict
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set kinematic object.
-- @function [parent=#Physics3DRigidBody] setKinematic
-- @param self
-- @param #bool kinematic
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set linear damping and angular damping.
-- @function [parent=#Physics3DRigidBody] setDamping
-- @param self
-- @param #float lin_damping
-- @param #float ang_damping
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a impulse.<br>
-- param impulse the value of the impulse<br>
-- param rel_pos the position of the impulse
-- @function [parent=#Physics3DRigidBody] applyImpulse
-- @param self
-- @param #vec3_table impulse
-- @param #vec3_table rel_pos
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Check rigid body is kinematic object.
-- @function [parent=#Physics3DRigidBody] isKinematic
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Apply a torque.<br>
-- param torque the value of the torque
-- @function [parent=#Physics3DRigidBody] applyTorque
-- @param self
-- @param #vec3_table torque
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set motion threshold, don't do continuous collision detection if the motion (in one step) is less then ccdMotionThreshold
-- @function [parent=#Physics3DRigidBody] setCcdMotionThreshold
-- @param self
-- @param #float ccdMotionThreshold
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set rolling friction.
-- @function [parent=#Physics3DRigidBody] setRollingFriction
-- @param self
-- @param #float frict
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get motion threshold.
-- @function [parent=#Physics3DRigidBody] getCcdMotionThreshold
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get the linear factor.
-- @function [parent=#Physics3DRigidBody] getLinearFactor
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Damps the velocity, using the given linearDamping and angularDamping.
-- @function [parent=#Physics3DRigidBody] applyDamping
-- @param self
-- @param #float timeStep
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the angular velocity.
-- @function [parent=#Physics3DRigidBody] getAngularVelocity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] init
-- @param self
-- @param #cc.Physics3DRigidBodyDes info
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Apply a torque impulse.<br>
-- param torque the value of the torque
-- @function [parent=#Physics3DRigidBody] applyTorqueImpulse
-- @param self
-- @param #vec3_table torque
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Active or inactive.
-- @function [parent=#Physics3DRigidBody] setActive
-- @param self
-- @param #bool active
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the linear factor.
-- @function [parent=#Physics3DRigidBody] setLinearFactor
-- @param self
-- @param #vec3_table linearFactor
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the linear velocity.
-- @function [parent=#Physics3DRigidBody] setLinearVelocity
-- @param self
-- @param #vec3_table lin_vel
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the linear velocity.
-- @function [parent=#Physics3DRigidBody] getLinearVelocity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Set swept sphere radius.
-- @function [parent=#Physics3DRigidBody] setCcdSweptSphereRadius
-- @param self
-- @param #float radius
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a force.<br>
-- param force the value of the force<br>
-- param rel_pos the position of the force
-- @function [parent=#Physics3DRigidBody] applyForce
-- @param self
-- @param #vec3_table force
-- @param #vec3_table rel_pos
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the angular velocity.
-- @function [parent=#Physics3DRigidBody] setAngularVelocity
-- @param self
-- @param #vec3_table ang_vel
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Apply a central impulse.<br>
-- param impulse the value of the impulse
-- @function [parent=#Physics3DRigidBody] applyCentralImpulse
-- @param self
-- @param #vec3_table impulse
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get the acceleration.
-- @function [parent=#Physics3DRigidBody] getGravity
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get rolling friction.
-- @function [parent=#Physics3DRigidBody] getRollingFriction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Set the center of mass.
-- @function [parent=#Physics3DRigidBody] setCenterOfMassTransform
-- @param self
-- @param #mat4_table xform
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set the inverse of local inertia.
-- @function [parent=#Physics3DRigidBody] setInvInertiaDiagLocal
-- @param self
-- @param #vec3_table diagInvInertia
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- @overload self, unsigned int
-- @overload self, cc.Physics3DConstraint
-- @function [parent=#Physics3DRigidBody] removeConstraint
-- @param self
-- @param #cc.Physics3DConstraint constraint
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get total torque.
-- @function [parent=#Physics3DRigidBody] getTotalTorque
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get inverse of mass.
-- @function [parent=#Physics3DRigidBody] getInvMass
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get constraint by index.
-- @function [parent=#Physics3DRigidBody] getConstraint
-- @param self
-- @param #unsigned int idx
-- @return Physics3DConstraint#Physics3DConstraint ret (return value: cc.Physics3DConstraint)
--------------------------------
-- Get restitution.
-- @function [parent=#Physics3DRigidBody] getRestitution
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get swept sphere radius.
-- @function [parent=#Physics3DRigidBody] getCcdSweptSphereRadius
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get hit friction.
-- @function [parent=#Physics3DRigidBody] getHitFraction
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get angular damping.
-- @function [parent=#Physics3DRigidBody] getAngularDamping
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- Get the inverse of local inertia.
-- @function [parent=#Physics3DRigidBody] getInvInertiaDiagLocal
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Get the center of mass.
-- @function [parent=#Physics3DRigidBody] getCenterOfMassTransform
-- @param self
-- @return mat4_table#mat4_table ret (return value: mat4_table)
--------------------------------
-- Get the angular factor.
-- @function [parent=#Physics3DRigidBody] getAngularFactor
-- @param self
-- @return vec3_table#vec3_table ret (return value: vec3_table)
--------------------------------
-- Set restitution.
-- @function [parent=#Physics3DRigidBody] setRestitution
-- @param self
-- @param #float rest
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Set hit friction.
-- @function [parent=#Physics3DRigidBody] setHitFraction
-- @param self
-- @param #float hitFraction
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
--------------------------------
-- Get linear damping.
-- @function [parent=#Physics3DRigidBody] getLinearDamping
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- override.
-- @function [parent=#Physics3DRigidBody] getWorldTransform
-- @param self
-- @return mat4_table#mat4_table ret (return value: mat4_table)
--------------------------------
--
-- @function [parent=#Physics3DRigidBody] Physics3DRigidBody
-- @param self
-- @return Physics3DRigidBody#Physics3DRigidBody self (return value: cc.Physics3DRigidBody)
return nil
|
style =
{["off_color"] = "fff",
["on_color"] = "fff",
["line_color"] = "000",
["line_width"] = "3"};
marker_style =
{["off_color"] = "fff",
["on_color"] = "6f6",
["line_color"] = "000",
["line_width"] = "1"};
mycanvas = function(result)
ow = 10
vo = 40
vs = 50
vp = 60
vc = 70
lib.start_canvas(350, 330, "center", result)
--[[ petougao ]]--
lib.add_straight_path(2*ow, vs, {{vp, -vo}, {vp, vo}, {-3*ow, vp}, {-vp, 0}, {-3*ow, -vp}}, style, false, false)
lib.add_input(vc, 2*vp, 30, 30, lib.check_number(5, 15))
--[[ sestougao ]]--
lib.add_straight_path(4*vs, vo, {{vs, -3*ow}, {vs, 3*ow}, {0, vs}, {-vs, 3*ow}, {-vs, -3*ow}, {0, -vs}}, style, false, false)
lib.add_input(4*vp, 2*vp+ow, 30, 30, lib.check_number(6, 15))
--[[ osmougao ]]--
lib.add_straight_path(vo, 5*vs, {{0, -vo}, {2*vo/3, -2*vo/3}, {vo, 0}, {2*vo/3, 2*vo/3}, {0, vo}, {-2*vo/3, 2*vo/3}, {-vo, 0}, {-2*vo/3, -2*vo/3}}, style, false, false)
lib.add_input(vc, 7*vo+ow, 30, 30, lib.check_number(8, 15))
--[[ cetvorougao ]]--
lib.add_straight_path(4*vs, 5*vs, {{3*vc/4, -vc}, {vc/4, vc}, {-3*vc/4, vc}, {-vc/4, -vc}}, style, false, false)
lib.add_input(4*vp, 7*vo+ow, 30, 30, lib.check_number(4, 15))
lib.end_canvas()
end
|
GM.Name ="Coin Finder"
function GM:Initialize()
self.BaseClass.Initialize(self)
end
|
local font_q = {}
function font_q.init()
font_q.data = {}
font_q.name = "font_q"
editor.importObject("FONT", font_q.name, "font_q.new", mdl_q)
end
function font_q.new(x, y)
local tbl = {}
tbl.x = x
tbl.y = y
table.insert(font_q.data, tbl)
end
function font_q.draw()
local i = 1
while i <= #font_q.data do
local this_ent = font_q.data[i]
lg.push()
lg.translate(this_ent.x, this_ent.y)
polygon.draw(mdl_q)
lg.pop()
i = i + 1
end
end
return font_q |
require "init.lua_func_ex"
require "init.error_ex"
--[[
当前系统的版本号
--]]
MEMOFTIMES_VERSION='1.0.0.1';
local bundles=require "init.resource_bundles"
zhCn_bundles=bundles.getLanguageBundle('zh_cn');
en_bundles=bundles.getLanguageBundle('en');
|
Config = {}
Config.Locale = 'en'
Config.PoliceNumberRequired = 4
Config.TimerBeforeNewRob = 1200 -- seconds
-- Change secondsRemaining if you want another timer
Stores = {
--[["paleto_twentyfourseven"] = {
position = { ['x'] = 1736.32092285156, ['y'] = 6419.4970703125, ['z'] = 35.037223815918 },
reward = math.random(10000,22000),
nameofstore = "24/7. (Paleto Bay)",
secondsRemaining = 180, -- seconds
lastrobbed = 0
},]]
["sandyshores_twentyfoursever"] = {
position = { ['x'] = 1961.24682617188, ['y'] = 3749.46069335938, ['z'] = 32.3437461853027 },
reward = math.random(50000,60000),
nameofstore = "24/7. (Sandy Shores)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_1"] = {
position = { ['x'] = -1478.65, ['y'] = -374.63, ['z'] = 38.6 },
reward = math.random(50000,60000),
nameofstore = "Sklep",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_2"] = {
position = { ['x'] = -1827.83, ['y'] = 799.01, ['z'] = 137.7 },
reward = math.random(50000,60000),
nameofstore = "Stacja paliw",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_4"] = {
position = { ['x'] = 2673.99, ['y'] = 3286.42, ['z'] = 54.88 },
reward = math.random(50000,60000),
nameofstore = "Stacja paliw",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_3"] = {
position = { ['x'] = 2550.19, ['y'] = 386.45, ['z'] = 108.0 },
reward = math.random(50000,60000),
nameofstore = "Stacja paliw",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_5"] = {
position = { ['x'] = 546.43, ['y'] = 2663.47, ['z'] = 41.80 },
reward = math.random(50000,60000),
nameofstore = "Sklep",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["miasto_6"] = {
position = { ['x'] = 1395.19, ['y'] = 3613.26, ['z'] = 34.98 },
reward = math.random(50000,60000),
nameofstore = "Sklep",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["bahamasklub"] = {
position = { ['x'] = -1393.96, ['y'] = -614.09, ['z'] = 30.10 },
reward = math.random(50000,60000),
nameofstore = "klub",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["bar_one"] = {
position = { ['x'] = 1990.579, ['y'] = 3044.957, ['z'] = 47.215171813965 },
reward = math.random(50000,60000),
nameofstore = "Yellow Jack. (Sandy Shores)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["ocean_liquor"] = {
position = { ['x'] = -2959.33715820313, ['y'] = 388.214172363281, ['z'] = 14.0432071685791 },
reward = math.random(50000,60000),
nameofstore = "Robs Liquor. (Great Ocean Higway)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["sanandreas_liquor"] = {
position = { ['x'] = -1219.85607910156, ['y'] = -916.276550292969, ['z'] = 11.3262157440186 },
reward = math.random(50000,60000),
nameofstore = "Robs Liquor. (San andreas Avenue)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["grove_ltd"] = {
position = { ['x'] = -43.4035377502441, ['y'] = -1749.20922851563, ['z'] = 29.421012878418 },
reward = math.random(50000,60000),
nameofstore = "LTD Gasoline. (Grove Street)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["mirror_ltd"] = {
position = { ['x'] = 1160.67578125, ['y'] = -314.400451660156, ['z'] = 69.2050552368164 },
reward = math.random(50000,60000),
nameofstore = "LTD Gasoline. (Mirror Park Boulevard)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
},
["littleseoul_twentyfourseven"] = {
position = { ['x'] = -709.17022705078, ['y'] = -904.21722412109, ['z'] = 19.215591430664 },
reward = math.random(50000,60000),
nameofstore = "24/7. (Little Seoul)",
secondsRemaining = 450, -- seconds
lastrobbed = 3600
}
}
|
local Scene = require 'Scene'
-- エイリアス
local lg = love.graphics
local la = love.audio
-- ブート
local Boot = Scene:newState 'boot'
-- 次のステートへ
function Boot:nextState(...)
self:gotoState 'splash'
end
-- 読み込み
function Boot:load()
-- 画面のサイズ
local width, height = lg.getDimensions()
self.width = width
self.height = height
-- スプライトシートの読み込み
self.spriteSheet = sbss:new('assets/round_nodetailsOutline.xml')
-- フォント
local fontName = 'assets/Kenney Blocks.ttf'
self.font16 = lg.newFont(fontName, 16)
self.font32 = lg.newFont(fontName, 32)
self.font64 = lg.newFont(fontName, 64)
-- 音楽
local musics = {
ingame = 'Alpha Dance.ogg',
outgame = 'Flowing Rocks.ogg',
}
self.musics = {}
for name, path in pairs(musics) do
self.musics[name] = love.audio.newSource('assets/' .. path, 'static')
self.musics[name]:setLooping(true)
self.musics[name]:setVolume(0.5)
end
-- SE
local sounds = {
gameover = 'Beat ident.ogg',
start = 'threeTone2.ogg',
cursor = 'coin5.ogg',
cancel = 'twoTone2.ogg',
remove = 'upgrade1.ogg',
undo = 'jump4.ogg',
}
self.sounds = {}
for name, path in pairs(sounds) do
self.sounds[name] = love.audio.newSource('assets/' .. path, 'static')
end
-- ベストスコア
self.best = {}
-- キーリピート有効
love.keyboard.setKeyRepeat(true)
end
-- 更新
function Boot:update()
self:nextState()
end
return Boot
|
-----------------------------------
-- Area: Northern San d'Oria
-- NPC: Anilla
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- !pos 8 0.1 61 231
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local WildcatSandy = player:getCharVar("WildcatSandy")
if (player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy, 6) == false) then
player:startEvent(808)
else
player:startEvent(586)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 808) then
player:setMaskBit(player:getCharVar("WildcatSandy"), "WildcatSandy", 6, true)
end
end
|
--- === mjolnir._asm.hydra ===
---
--- Home: https://github.com/asmagill/mjolnir_asm.hydra
---
--- Minor functions from Hydra and a checklist function for indicating Hydra function replacements.
---
--- This module provides some of the functionality which Hydra had regarding its environment, but aren't currently in a module of their own for various reasons.
---
--- This module is not needed for any of the submodules, and the submodules can be loaded and installed independently of this one. Loads all of the modules corresponding to Hydra's internal functions. This module is not strictly needed, as it will load as many of the modules as have been created so far. Individual modules can be loaded if you prefer only specific support.
---
--- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/).
local module = require("mjolnir._asm.hydra.internal")
-- private variables and methods -----------------------------------------
local my_require = function(label, name)
if type(name) == "nil" then
print(label.."\t no module is known to exist for this yet.")
return nil
else
local ok, value = xpcall(require, function(...) return ... end, name)
if ok then
return value
else
print(label.."\t is provided by "..name)
return nil
end
end
end
-- Public interface ------------------------------------------------------
--- mjolnir._asm.hydra.call(fn, ...) -> ...
--- Function
--- Just like pcall, except that failures are handled using `mjolnir.showerror`
module.call = function(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
mjolnir.showerror(results[2])
end
return table.unpack(results)
end
--- mjolnir._asm.hydra.exec(command[, with_user_env]) -> output, status, type, rc
--- Function
--- Runs a shell command and returns stdout as a string (may include a trailing newline), followed by true or nil indicating if the command completed successfully, the exit type ("exit" or "signal"), and the result code.
---
--- If `with_user_env` is `true`, then invoke the user's default shell as an interactive login shell in which to execute the provided command in order to make sure their setup files are properly evaluated so extra path and environment variables can be set. This is not done, if `with_user_env` is `false` or not provided, as it does add some overhead and is not always strictly necessary.
module.exec = function(command, user_env)
local f
if user_env then
f = io.popen(os.getenv("SHELL").." -l -i -c \""..command.."\"", 'r')
else
f = io.popen(command, 'r')
end
local s = f:read('*a')
local status, exit_type, rc = f:close()
return s, status, exit_type, rc
end
--- mjolnir._asm.hydra.hydra_namespace() -> table
--- Function
--- Returns the full hydra name space replicated as closely as reasonable for Mjolnir. Really more of a checklist then a real environment to choose to live in <grin>.
---
--- This module attempts to require modules known to provide former Hydra functionality and prints a list to the Mjolnir console indicating what modules you don't have and which Hydra modules are currently have no known replacement in Mjolnir. If you think that an existing module does exist to cover lost functionality, but it is not represented here, please let me know and I'll add it.
---
--- This module returns a table of the Hydra namespace, as it has been able to be reconstituted with your installed modules.
---
--- **NOTE:** While this function does load the compatible modules into memory, it does so *only when you invoke this function*. Until and unless you call this function, no additional modules are loaded into memory.
module.hydra_namespace = function()
local _H = {
_registry = { "mjolnir userdata uses the stack registry, not this one." },
application = my_require("application", "mjolnir.application"),
audiodevice = my_require("audiodevice", "mjolnir._asm.sys.audiodevice"),
battery = my_require("battery", "mjolnir._asm.sys.battery"),
brightness = my_require("brightness", "mjolnir._asm.sys.brightness"),
doc = my_require("doc", nil),
eventtap = my_require("eventtap", "mjolnir._asm.eventtap"),
ext = {},
fnutils = my_require("fnutils", "mjolnir.fnutils"),
geometry = my_require("geometry", "mjolnir.geometry"),
help = my_require("help", nil),
hotkey = my_require("hotkey", "mjolnir.hotkey"),
http = my_require("http", nil),
hydra = {
_initiate_documentation_system = nil,
alert = my_require("hydra.alert", "mjolnir.alert"),
autolaunch = { get = module.autolaunch, set = module.autolaunch },
call = module.call,
check_accessibility = module.check_accessibilitiy,
dockicon = my_require("hydra.docicon", "mjolnir._asm.hydra.dockicon"),
docsfile = nil,
errorhandler = mjolnir.showerror,
exec = module.exec,
exit = mjolnir._exit,
fileexists = module.fileexists,
focushydra = mjolnir.focus,
ipc = my_require("hydra.ipc", "mjolnir._asm.ipc"),
license = {
-- Table of functions used for license entry and verification of Hydra...
-- never really used, but here solely for the sake of completeness (some
-- would say analness; but consider that I thought, for about 2 seconds,
-- about actually reproducing the code, rather than just the results).
enter = function() end,
haslicense = function() return true end,
_verify = function(...) return true end,
},
licenses = [[
### Lua 5.2
Copyright (c) 1994-2014 Lua.org, PUC-Rio.
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.
]],
menu = my_require("hydra.menu", nil),
packages = my_require("hydra.packages", nil),
reload = mjolnir.reload,
resourcesdir = module._paths().resourcePath,
runapplescript = my_require("hydra.runapplescript", "mjolnir._asm.hydra.applescript"),
setosxshadows = nil, -- see below
settings = my_require("hydra.settings", "mjolnir._asm.settings"),
showabout = module.showabout,
tryhandlingerror = mjolnir.showerror,
updates = my_require("update", nil),
uuid = module.uuid,
version = module._version(),
},
inspect = my_require("inspect", "inspect"),
json = my_require("json", "mjolnir._asm.data.json"),
logger = my_require("logger", nil),
mouse = my_require("mouse", "mjolnir.jstevenson.cursor"),
notify = my_require("notify", "mjolnir._asm.notify"),
pasteboard = my_require("pasteboard", "mjolnir._asm.data.pasteboard"),
pathwatcher = my_require("pathwatcher", "mjolnir._asm.watcher.path"),
repl = { open = mjolnir.openconsole, path = module._paths().bundlePath, },
screen = my_require("screen", "mjolnir.screen"),
spaces = nil, -- see below
textgrid = my_require("textgrid", nil),
timer = my_require("timer", "mjolnir._asm.timer"),
utf8 = my_require("utf8", "mjolnir._asm.utf8_53"),
window = my_require("window", "mjolnir.window"),
}
--
-- Some cleanup to make things more Hydra like...
--
_H._notifysetup = package.loaded["mjolnir._asm.notify"] ~= nil
local battery_watcher = my_require("battery.watcher", "mjolnir._asm.watcher.battery")
if type(battery_watcher) == "table" then
if type(_H.battery) == "nil" then _H.battery = {} end
_H.battery.watcher = battery_watcher
end
local screen_watcher = my_require("screen.watcher", "mjolnir._asm.watcher.screen")
if type(screen_watcher) == "table" then
if type(_H.screen) == "nil" then _H.screen = {} end
_H.screen.watcher = screen_watcher
end
if type(_H.mouse) == "table" then
_H.mouse.get = _H.mouse.position
_H.mouse.set = function(xy) return _H.mouse.warptopoint(xy.x, xy.y) end
end
local undocumented = my_require("hydra.setosxshadows, spaces", "mjolnir._asm.hydra.undocumented")
if type(undocumented) == "table" then
_H.spaces = undocumented.spaces
_H.hydra.setosxshadows = undocumented.setosxshadows
end
if type(_H.utf8) == "table" then
_H.utf8.count = _H.utf8.len
_H.utf8.chars = function(str)
local t = {}
str:gsub(utf8_53.charpatt,function(c) t[#t+1] = c end)
return t
end
end
return _H
end
-- Return Module Object --------------------------------------------------
return module
|
--Aside from us4l.internals.LuaVersion, this file needs to not use any other modules.
local LuaVersion = require "us4l.internals.LuaVersion"
--TODO: Everything in here eventually needs to be highly-optimized
--[[ Every encoding form has the following functions available:
* DecodeCpAtPos( str[, pos := 1] ) --> cp, len | nil, msg
* DecodeCpWithReplacementAtPos( str[, pos := 1 ] ) --> cp, len
* DecodeWholeString( str ) --> cp_list | nil, msg
* DecodeWholeStringWithReplacement( str ) --> cp_list
* EncodeCp( cp ) --> string
* EncodeCpList( cp, skip_check ) --> string
Initially, behavior of the decoding functions was to only throw an error involving incomplete code units if they tried to read
the final code unit of a string and it was incomplete. But since I couldn't think of any actual use for that, I just changed it to
require that any string passed to a decoding function must contain only complete code units.
]]
local fmt = string.format
local MaxArgsPassed = 128 --[[Certain functions take a series of distinct arguments instead of a list. There's a limit to how many
arguments can be passed or values returned at once (somewhere below 2^8 or so), so this number controls how many are used at once.]]
local function IsValidCp ( cp )
return 0x0000 <= cp and cp <= 0x10FFFF and not ( 0xD800 <= cp and cp <= 0xDFFF )
end
local ReplacementCp = 0xFFFD
--Shortcut for making integers with binary literals
local bin
if LuaVersion == "Lua53" then
function bin ( in_str )
return math.tointeger( tonumber( in_str:gsub("_", ""), 2 ) )
end
else
function bin ( in_str )
return tonumber( in_str:gsub("_", ""), 2 )
end
end
local tointeger
if LuaVersion == "Lua53" then
tointeger = math.tointeger
else
tointeger = function ( x ) return x end
end
--[[==============
UTF-8 HANDLING
==============]]
--[[Decoding with replacement is so complex that it's handled the same in all versions of Lua, so the code isn't in either branch of the
if-statement below]]
local UTF8 = {}
if LuaVersion == "Lua53" then
local codepoint = utf8.codepoint
local char = utf8.char
local unpack = table.unpack
local concat = table.concat
local function EncodeCp ( cp )
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X", cp ) )
return char( cp )
end
local min = math.min
local function EncodeCpList ( cp_list, skip_check )
if not skip_check then
for i = 1, #cp_list do
local cp = cp_list[ i ]
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X at position %i", i, cp ) )
end
end
local out_buf = {}
for cp_i = 1, #cp_list, MaxArgsPassed do
out_buf[ #out_buf + 1 ] = char( unpack( cp_list, cp_i, min( cp_i + (MaxArgsPassed-1), #cp_list ) ) )
end
return concat( out_buf )
end
local pcall = pcall
local codepoint = utf8.codepoint
local max_1byte = bin"0111_1111"
local max_2byte = bin"00000111_11111111"
local max_3byte = bin"11111111_11111111"
local function DecodeCp ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid byte pos %i in string of length %i", pos, #str ) )
local success, res = pcall( codepoint, str, pos )
if not success then
return nil, res
end
local cp = success
if not IsValidCp( cp ) then --Not entirely confident that their library is bulletproof
return nil, "invalid code point"
end
if cp <= max_1byte then
return cp, 1
elseif cp <= max_2byte then
return cp, 2
elseif cp <= max_3byte then
return cp, 3
else
return cp, 4
end
end
local codes = utf8.codes
local function DecodeWholeString ( str )
local success, res = pcall(function()
local cp_list = {}
for pos, cp in codes( str ) do
cp_list[ #cp_list + 1 ] = cp
end
return cp_list
end)
if success then
return res
else
return nil, res
end
end
UTF8.DecodeCp = DecodeCp
UTF8.DecodeWholeString = DecodeWholeString
UTF8.EncodeCp = EncodeCp
UTF8.EncodeCpList = EncodeCpList
else
local char = string.char
local floor = math.floor
local concat = table.concat
local lead2, lead3, lead4, follow = bin"1100_0000", bin"1110_0000", bin"1111_0000", bin"1000_0000"
local function EncodeCp ( cp )
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X", cp ) )
if cp <= 0x007F then
return char( cp )
elseif cp <= 0x07FF then
return char( lead2 + floor(cp / 2^6), follow + (cp % 2^6) )
elseif cp <= 0xFFFF then
return char( lead3 + floor(cp / 2^12), follow + (floor(cp/2^6) % 2^6), follow + (cp % 2^6) )
else--if cp <= 0x10FFFF then
return char( lead4 + floor(cp / 2^18), follow + (floor(cp/2^12) % 2^6), follow + (floor(cp/2^6) % 2^6), follow + (cp % 2^6) )
end
end
local function EncodeCpList ( cp_list, skip_check )
if not skip_check then
for i = 1, #cp_list do
local cp = cp_list[ i ]
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X at position %i", i, cp ) )
end
end
local out_buf = {}
for i = 1, #cp_list do
out_buf[ i ] = EncodeCp( cp_list[i] )
end
return concat( out_buf )
end
local limits = {
{ lo = 0, hi = bin"0111_1111", following = 0, min_cp = 0x0000 },
{ lo = bin"1100_0000", hi = bin"1101_1111", following = 1, min_cp = 0x0080 },
{ lo = bin"1110_0000", hi = bin"1110_1111", following = 2, min_cp = 0x0800 },
{ lo = bin"1111_0000", hi = bin"1111_0111", following = 3, min_cp = 0x10000 }
}
local following_sub = bin"1000_0000"
local following_sub_max = bin"1011_1111"
local function DecodeCp ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid pos %i in string of length %i", pos, #str ) )
local byte1 = str:byte( pos )
for _, vals in ipairs( limits ) do
if vals.lo <= byte1 and byte1 <= vals.hi then
local end_pos = pos + vals.following
if not ( end_pos <= #str ) then
return nil, "incomplete byte sequence"
end
local cp = byte1 - vals.lo
for ofs = 1, vals.following do
local follow_byte = str:byte(pos+ofs)
if not ( following_sub <= follow_byte and follow_byte <= following_sub_max ) then
return nil, "malformed byte sequence"
end
cp = (cp * 2^6) + (follow_byte - following_sub)
end
if 0xD800 <= cp and cp <= 0xDBFF then
return nil, "high surrogate"
elseif 0xDC00 <= cp and cp <= 0xDFFF then
return nil, "low surrogate"
elseif 0x10FFFF < cp then
return nil, "code point above repertoire"
end
if cp < vals.min_cp then
return nil, "code point not in shortest-form"
end
return cp, vals.following+1
end
end
--Byte does not match any valid starter sequence
return nil, "malformed byte sequence"
end
local function DecodeWholeString ( str )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCp( str, pos )
if not cp then
--len is the error message
return nil, fmt( "invalidity at byte %i: %s", pos, len )
end
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
UTF8.DecodeCp = DecodeCp
UTF8.DecodeWholeString = DecodeWholeString
UTF8.EncodeCp = EncodeCp
UTF8.EncodeCpList = EncodeCpList
end
--Decoding with replacements for UTF-8
do
--[[IMPORTANT: Table 3-7, "Well-Formed UTF-8 Sequences", was the driving data for this algorithm. It is duplicated here for convenience:
Code Points First Byte Second Byte Third Byte Fourth Byte
=========== ========== =========== ========== ===========
U+0000..U+007F | 00..7F | | |
U+0080..U+07FF | C2..DF | 80..BF | |
U+0800..U+0FFF | E0 | A0..BF | 80..BF |
U+1000..U+CFFF | E1..EC | 80..BF | 80..BF |
U+D000..U+D7FF | ED | 80..9F | 80..BF |
U+E000..U+FFFF | EE..EF | 80..BF | 80..BF |
U+10000..U+3FFFF | F0 | 90..BF | 80..BF | 80..BF
U+40000..U+FFFFF | F1..F3 | 80..BF | 80..BF | 80..BF
U+100000..U+10FFFF | F4 | 80..8F | 80..BF | 80..BF
]]
local two_byte_starter_sub = bin"1100_0000"
local three_byte_starter_sub = bin"1110_0000"
local four_byte_starter_sub = bin"1111_0000"
local follower_byte_sub = bin"1000_0000"
local function process2bytes ( b1, b2 )
if b2 and 0x80 <= b2 and b2 <= 0xBF then
local cp = (b1-two_byte_starter_sub)*2^6 + (b2-follower_byte_sub)
return cp, 2
else
return ReplacementCp, 1
end
end
local function common3byte3( b1, b2, b3 )
if b3 and 0x80 <= b3 and b3 <= 0xBF then
local cp = ((b1-three_byte_starter_sub)*2^12) + ((b2-follower_byte_sub)*2^6) + (b3-follower_byte_sub)
return cp, 3
else
return ReplacementCp, 2
end
end
local function process3bytes ( b1, b2, b3 )
if b1 == 0xE0 then
if b2 and 0xA0 <= b2 and b2 <= 0xBF then
return common3byte3( b1, b2, b3 )
else
return ReplacementCp, 1
end
elseif ( 0xE1 <= b1 and b1 <= 0xEC )
or ( 0xEE <= b1 and b1 <= 0xEF ) then
if b2 and 0x80 <= b2 and b2 <= 0xBF then
return common3byte3( b1, b2, b3 )
else
return ReplacementCp, 1
end
elseif b1 == 0xED then
if b2 and 0x80 <= b2 and b2 <= 0x9F then
return common3byte3( b1, b2, b3 )
else
return ReplacementCp, 1
end
else
error "Can't happen"
end
end
local function common4byte34 ( b1, b2, b3, b4 )
if b3 and 0x80 <= b3 and b3 <= 0xBF then
if b4 and 0x80 <= b4 and b4 <= 0xBF then
local cp = ((b1-four_byte_starter_sub)*2^18)
+ ((b2-follower_sub)*2^12)
+ ((b3-follower_sub)*2^6)
+ (b4-follower_sub)
return cp, 4
else
return ReplacementCp, 3
end
else
return ReplacementCp, 2
end
end
local function process4bytes ( b1, b2, b3, b4 )
if b1 == 0xF0 then
if b2 and 0x90 <= b2 and b2 <= 0xBF then
return common4byte34( b1, b2, b3, b4 )
else
return ReplacementCp, 1
end
elseif 0xF1 <= b1 and b1 <= 0xF3 then
if b2 and 0x80 <= b2 and b2 <= 0xBF then
return common4byte34( b1, b2, b3, b4 )
else
return ReplacementCp, 1
end
elseif b1 == 0xF4 then
if b2 and 0x80 <= b2 and b2 <= 0x8F then
return common4byte34( b1, b2, b3, b4 )
else
return ReplacementCp, 1
end
else
error "Can't happen"
end
end
local function DecodeCpWithReplacement ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid pos %i in string of length %i", pos, #str ) )
--If there's not enough characters left in the string, the missing values get nil
local b1, b2, b3, b4 = str:byte( pos, pos+3 )
if 0x00 <= b1 and b1 <= 0x7F then
return b1, 1
elseif 0xC2 <= b1 and b1 <= 0xDF then
return process2bytes( b1, b2 )
elseif 0xE0 <= b1 and b1 <= 0xEF then
return process3bytes( b1, b2, b3 )
elseif 0xF0 <= b1 and b1 <= 0xF4 then
return process4bytes( b1, b2, b3, b4 )
else --Non-starter
return ReplacementCp, 1
end
end
local function DecodeWholeStringWithReplacement ( str )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCpWithReplacement( str, pos )
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
UTF8.DecodeCpWithReplacement = DecodeCpWithReplacement
UTF8.DecodeWholeStringWithReplacement = DecodeWholeStringWithReplacement
end
--[[===============
UTF-16 HANDLING
===============]]
local UTF16LE, UTF16BE = {}, {}
do
local out_tbls = { UTF16LE = UTF16LE, UTF16BE = UTF16BE }
local specs
if LuaVersion == "Lua53" then
local pack, unpack = string.pack, string.unpack
specs = {
UTF16LE = {
write_cu = function ( cu ) return pack( "<I2", cu ) end;
read_cu = function ( str, pos ) return unpack( "<I2", str, pos ) end;
};
UTF16BE = {
write_cu = function ( cu ) return pack( ">I2", cu ) end;
read_cu = function ( str, pos ) return unpack( ">I2", str, pos ) end;
};
}
else
local char = string.char
local floor = math.floor
specs = {
UTF16LE = {
write_cu = function ( cu ) return char( cu % 2^8, floor( cu / 2^8 ) ) end;
read_cu = function ( str, pos )
local byte1, byte2 = str:byte(pos,pos+1)
return byte1 + (byte2 * 2^8)
end;
};
UTF16BE = {
write_cu = function ( cu ) return char( floor( cu / 2^8 ), cu % 2^8 ) end;
read_cu = function ( str, pos )
local byte1, byte2 = str:byte(pos,pos+1)
return (byte1 * 2^8) + byte2
end;
};
}
end
for variant, spec in pairs( specs ) do
local write_cu, read_cu = spec.write_cu, spec.read_cu
local floor = math.floor
local function EncodeCp ( cp )
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X", cp ) )
if cp <= 0xFFFF then
return write_cu( cp )
else
return write_cu( floor((cp-0x10000)/2^10) + 0xD800 ) .. write_cu( ((cp-0x10000)%2^10) + 0xDC00 )
end
end
local concat = table.concat
local function EncodeCpList ( cp_list, skip_check )
if not skip_check then
for i = 1, #cp_list do
local cp = cp_list[ i ]
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X at position %i", i, cp ) )
end
end
local out_buf = {}
for i = 1, #cp_list do
out_buf[i] = EncodeCp( cp_list[i] )
end
return concat( out_buf )
end
local function DecodeCp ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid byte pos %i in string of length %i", pos, #str ) )
assert( pos % 2 == 1, fmt( "invalid byte pos %i (must be a multiple of 2 plus 1)", pos ) )
assert( #str % 2 == 0, fmt( "string length (%i bytes) not a multiple of 2 bytes", #str ) )
local code1 = read_cu( str, pos )
if 0xDC00 <= code1 and code1 <= 0xDFFF then
--Low surrogate, illegal sequence
return nil, "isolated low surrogate"
elseif 0xD800 <= code1 and code1 <= 0xDBFF then
--High surrogate, start of a surrogate pair
if pos == #str-1 then
--No following code unit
return nil, "high surrogate without following code unit"
else
local code2 = read_cu( str, pos+2 )
if not ( 0xDC00 <= code2 and code2 <= 0xDFFF ) then
if 0xD800 <= code2 and code2 <= 0xDBFF then
return nil, "high surrogate followed by another high surrogate"
else
return nil, "high surrogate followed by non-surrogate"
end
else
local cp = tointeger( (code1-0xD800)*2^10 + (code2-0xDC00) + 0x10000 )
return cp, 4
end
end
else
--Non-surrogate, interpret literally
return code1, 2
end
end
local function DecodeCpWithReplacement ( str, pos )
local cp, len = DecodeCp( str, pos )
if not cp then
return ReplacementCp, 2
else
return cp, len
end
end
local function DecodeWholeString ( str )
assert( #str % 2 == 0, fmt( "string length (%i bytes) not a multiple of 2 bytes", #str ) )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCp( str, pos )
if not cp then
--len is the error message
return nil, fmt( "invalidity at byte %i: %s", pos, len )
end
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
local function DecodeWholeStringWithReplacement ( str )
assert( #str % 2 == 0, fmt( "string length (%i bytes) not a multiple of 2 bytes", #str ) )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCpWithReplacement( str, pos )
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
local out = out_tbls[ variant ]
out.DecodeCp = DecodeCp
out.DecodeCpWithReplacement = DecodeCpWithReplacement
out.DecodeWholeString = DecodeWholeString
out.DecodeWholeStringWithReplacement = DecodeWholeStringWithReplacement
out.EncodeCp = EncodeCp
out.EncodeCpList = EncodeCpList
end
end
--[[===============
UTF-32 HANDLING
===============]]
local UTF32LE, UTF32BE = {}, {}
do
local out_tbls = { UTF32LE = UTF32LE, UTF32BE = UTF32BE }
local concat = table.concat
local specs
if LuaVersion == "Lua53" then
local pack, unpack = string.pack, string.unpack
specs = {
UTF32LE = {
pack = function ( cu ) return pack( "<I4", cu ) end;
unpack = function ( str, pos ) return unpack( "<I4", str, pos ) end;
};
UTF32BE = {
pack = function ( cu ) return pack( ">I4", cu ) end;
unpack = function ( str, pos ) return unpack( ">I4", str, pos ) end;
};
}
else
local char = string.char
local floor = math.floor
specs = {
UTF32LE = {
pack = function ( cu )
return char( cu % 2^8, floor( cu / 2^8 ) % 2^8, floor( cu / 2^16 ) % 2^8, floor( cu / 2^24 ) % 2^8 )
end;
unpack = function ( str, pos )
local byte1, byte2, byte3, byte4 = str:byte(pos, pos+3)
return byte1 + (byte2 * 2^8) + (byte3 * 2^16) + (byte4 * 2^24)
end;
};
UTF32BE = {
pack = function ( cu )
return char( floor( cu / 2^24 ) % 2^8, floor( cu / 2^16 ) % 2^8, floor( cu / 2^8 ) % 2^8, cu % 2^8 )
end;
unpack = function ( str, pos )
local byte1, byte2, byte3, byte4 = str:byte(pos, pos+3)
return (byte1 * 2^24) + (byte2 * 2^16) + (byte3 * 2^8) + byte4
end;
};
}
end
for variant, spec in pairs( specs ) do
local pack = spec.pack
local s_unpack = spec.unpack
--out_tbls[ variant ].EncodeCp = function ( cp )
local function EncodeCp ( cp )
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X", cp ) )
return pack( cp )
end
--out_tbls[ variant ].EncodeCpList = function ( cp_list, skip_check )
local function EncodeCpList ( cp_list, skip_check )
if not skip_check then
for i = 1, #cp_list do
local cp = cp_list[ i ]
assert( IsValidCp( cp ), fmt( "invalid code point 0x%04X at position %i", i, cp ) )
end
end
local out_buf = {}
for i = 1, #cp_list do
out_buf[i] = pack( cp_list[i] )
end
return concat( out_buf )
end
--out_tbls[ variant ].DecodeCp = function ( str, pos )
local function DecodeCp ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid byte pos %i in string of length %i", pos, #str ) )
assert( pos % 4 == 1, fmt( "invalid byte pos %i (must be a multiple of 4 plus 1)", pos ) )
assert( #str % 4 == 0, fmt( "string length (%i bytes) not a multiple of 4 bytes", #str ) )
local cp = s_unpack( str, pos )
if 0xD800 <= cp and cp <= 0xDBFF then
return nil, "high surrogate"
elseif 0xDC00 <= cp and cp <= 0xDFFF then
return nil, "low surrogate"
elseif 0x10FFFF < cp then
return nil, "code point above repertoire"
end
return cp, 4
end
--out_tbls[ variant ].DecodeCpWithReplacement = function ( str, pos )
local function DecodeCpWithReplacement ( str, pos )
pos = pos or 1
assert( 1 <= pos and pos <= #str, fmt( "invalid byte pos %i in string of length %i", pos, #str ) )
assert( pos % 4 == 1, fmt( "invalid byte pos %i (must be a multiple of 4 plus 1)", pos ) )
assert( #str % 4 == 0, fmt( "string length (%i bytes) not a multiple of 4 bytes", #str ) )
local cp = s_unpack( str, pos )
if IsValidCp( cp ) then
return cp, 4
else
return ReplacementCp, 4
end
end
local function DecodeWholeString ( str )
assert( #str % 4 == 0, fmt( "string length (%i bytes) not a multiple of 4 bytes", #str ) )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCp( str, pos )
if not cp then
--len is the error message
return nil, fmt( "invalidity at byte %i: %s", pos, len )
end
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
local function DecodeWholeStringWithReplacement ( str )
assert( #str % 4 == 0, fmt( "string length (%i bytes) not a multiple of 4 bytes", #str ) )
local pos, cp_list = 1, {}
repeat
local cp, len = DecodeCpWithReplacement( str, pos )
cp_list[ #cp_list + 1 ] = cp
pos = pos + len
until pos > #str
return cp_list
end
local out = out_tbls[ variant ]
out.DecodeCp = DecodeCp
out.DecodeCpWithReplacement = DecodeCpWithReplacement
out.DecodeWholeString = DecodeWholeString
out.DecodeWholeStringWithReplacement = DecodeWholeStringWithReplacement
out.EncodeCp = EncodeCp
out.EncodeCpList = EncodeCpList
end
end
local export = {
UTF8 = UTF8;
UTF16LE = UTF16LE;
UTF16BE = UTF16BE;
UTF32LE = UTF32LE;
UTF32BE = UTF32BE;
}
do
local char = string.char
local BOM_Signatures = {
{ "UTF8", char( 0xEF, 0xBB, 0xBF ) };
{ "UTF32LE", char( 0x00, 0x00, 0xFE, 0xFF ) };
{ "UTF32BE", char( 0xFF, 0xFE, 0x00, 0x00 ) };
{ "UTF16LE", char( 0xFE, 0xFF ) };
{ "UTF16BE", char( 0xFF, 0xFE ) };
}
function export.TryIdentifyBom ( str )
for _, data in ipairs( BOM_Signatures ) do
local EncodingName, Signature = data[1], data[2]
if str:sub(1, #Signature) == Signature then
return EncodingName
end
end
return nil
end end
return export |
--[[
Name: "cl_autorun.lua".
Product: "HL2 RP".
--]]
kuroScript.frame:IncludePrefixed("sh_autorun.lua");
-- Set some information.
AddCSLuaFile("cl_autorun.lua");
AddCSLuaFile("sh_autorun.lua");
-- Called when the entity initializes.
function ENT:Initialize()
self:SharedInitialize();
-- Set some information.
self:SetModel("models/props_c17/paper01.mdl");
-- Set some information.
self:SetMoveType(MOVETYPE_VPHYSICS);
self:PhysicsInit(SOLID_VPHYSICS);
self:SetUseType(SIMPLE_USE);
self:SetHealth(25);
self:SetSolid(SOLID_VPHYSICS);
-- Set some information.
local physicsObject = self:GetPhysicsObject();
-- Check if a statement is true.
if ( ValidEntity(physicsObject) ) then
physicsObject:Wake();
physicsObject:EnableMotion(true);
end;
end;
-- A function to explode the entity.
function ENT:Explode()
local effectData = EffectData();
-- Set some information.
effectData:SetStart( self:GetPos() );
effectData:SetOrigin( self:GetPos() );
effectData:SetScale(8);
-- Set some information.
util.Effect("GlassImpact", effectData, true, true);
-- Emit a sound.
self:EmitSound("physics/body/body_medium_impact_soft"..math.random(1, 7)..".wav");
end;
-- Called when the entity takes damage.
function ENT:OnTakeDamage(damageInfo)
self:SetHealth( math.max(self:Health() - damageInfo:GetDamage(), 0) );
-- Check if a statement is true.
if (self:Health() <= 0) then
self:Explode(); self:Remove();
end;
end;
-- A function to set the text.
function ENT:SetText(text)
if (text) then
self._Text = text;
self._UniqueID = util.CRC(text);
-- Set some information.
self:SetSharedVar("ks_Note", true);
end;
end;
-- Called when the entity is used.
function ENT:Use(activator, caller)
if ( activator:IsPlayer() ) then
if (self._Text) then
if ( !activator._PaperIDs or !activator._PaperIDs[self._UniqueID] ) then
if (!activator._PaperIDs) then
activator._PaperIDs = {};
end;
-- Set some information.
activator._PaperIDs[self._UniqueID] = true;
-- Start a data stream.
datastream.StreamToClients( activator, "ks_ViewPaper", {self, self._UniqueID, self._Text} );
else
datastream.StreamToClients( activator, "ks_ViewPaper", {self, self._UniqueID} );
end;
else
umsg.Start("ks_EditPaper", activator);
umsg.Entity(self);
umsg.End();
end;
end;
end; |
DISPLAY_sda = 4 -- GPIO2 D4
DISPLAY_scl = 3 -- GPIO0 D3
function init_i2c_display()
local sla = 0x3c
i2c.setup(0, DISPLAY_sda, DISPLAY_scl, i2c.SLOW)
disp = u8g2.ssd1306_i2c_128x64_noname(0, sla)
end
init_i2c_display()
function u8g2_prepare()
--disp:setFont(u8g2.font_6x10_tf)
disp:setFont(u8g2.font_inr16_mf)
disp:setFontRefHeightExtendedText()
disp:setDrawColor(1)
disp:setFontPosTop()
disp:setFontDirection(0)
end
function draw()
u8g2_prepare()
--disp:drawStr( 0, 0, "Scegli la temperatura")
--disp:setFont(u8g2.font_logisoso16_tr)
print('display current tmp: '..(getCurrentTmp()~=nil and getCurrentTmp() or 'nil'))
disp:drawStr( 10, 40, tostring(temperature)..(getCurrentTmp()~=nil and ' ('..tostring(getCurrentTmp())..')' or '') )
end
function doRefreshDisplay()
disp:clearBuffer()
draw()
disp:sendBuffer()
end
|
local error, concat = error, table.concat
local tostring, tonumber, reverse, floor, byte, sub, char = tostring, tonumber, string.reverse, math.floor, string.byte, string.sub, string.char
local type = type
local ceil = math.ceil
local ffi = require "ffi"
local ffi_string, ffi_new = ffi.string, ffi.new
local bit = require('bit')
local band, bor, bxor, lshift, rshift, rolm, bnot = bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift, bit.rol, bit.bnot
local new_tab, insert, mod = table.new, table.insert, math.fmod
local tag = 'xxhash'
local tablepool = require('tablepool')
local array = function(size)
return tablepool.fetch(tag, size, 0)
end
local release = function(tab, noclear)
return tablepool.release(tag, tab, noclear)
end
local _M = {
version = "1.3.4",
max_int = 4294967295,
max_int_b64 = 'D_____',
max_long = 9199999999999999999,
max_long_b64 = 'HHAs90Gdm---',
max_int_chars = 'ÿÿÿÿ', -- This value will be overwritten by following code
max_int_chars_1 = 'sssdsfsfsd'
}
local str_buf_size = 4096
local str_buf
local c_buf_type = ffi.typeof("char[?]")
local c_size_t_list = ffi.typeof("size_t[?]")
local function get_string_buf(size)
if size > str_buf_size then
return ffi_new(c_buf_type, size)
end
if not str_buf then
str_buf = ffi_new(c_buf_type, str_buf_size)
end
return str_buf
end
local function load_shared_lib(so_name)
local tried_paths = {}
local i = 1
for k, _ in package.cpath:gmatch("[^;]+") do
local fpath = k:match("(.*/)")
fpath = fpath .. so_name
local f = io.open(fpath)
if f ~= nil then
io.close(f)
return ffi.load(fpath)
end
tried_paths[i] = fpath
i = i + 1
end
local f = io.open(so_name)
if f ~= nil then
io.close(f)
return ffi.load(so_name)
end
tried_paths[#tried_paths + 2] = 'tried above paths but can not load ' .. so_name
error(concat(tried_paths, '\n'))
end
local encoding = load_shared_lib("librestyxxhashencode.so")
_M.encode = encoding
ffi.cdef([[
size_t modp_b2_encode(char* dest, const char* str, size_t len);
size_t modp_b2_decode(char* dest, const char* str, size_t len);
size_t modp_b16_encode(char* dest, const char* str, size_t len,
uint32_t out_in_lowercase);
size_t modp_b16_decode(char* dest, const char* src, size_t len);
size_t b32_encode(char* dest, const char* src, size_t len, uint32_t no_padding,
uint32_t hex);
size_t b32_decode(char* dest, const char* src, size_t len, uint32_t hex);
size_t modp_b85_encode(char* dest, const char* str, size_t len);
size_t modp_b85_decode(char* dest, const char* str, size_t len);
size_t modp_b64w_encode(char* dest, const char* str, size_t len);
size_t modp_b64w_decode(char* dest, const char* src, size_t len);
size_t xxhash128_b64(char *dest_b64, char *dest_byte, const char *str, size_t length, unsigned long long const seed);
size_t xxhash128(const void* data, size_t length, unsigned char *dest, uint64_t seed);
uint64_t parse_num(const char *str);
unsigned int int_base64(char* dest, unsigned int num);
unsigned int base64_int(const char* dest, int num);
size_t long_base64(char* dest, long num);
unsigned long base64_long(const char* dest, int len);
size_t xxhash64_b64(char* dest, const char* str, size_t length, unsigned long long const seed);
size_t xxhash32_b64(char* dest, const char* str, size_t length, unsigned int const seed);
unsigned long djb2_hash(const char* str);
unsigned int xxhash32(const char* str, size_t length, unsigned int seed);
unsigned long long xxhash64(const char* str, size_t length, unsigned long long const seed);
uint64_t xxh3(const char *str, size_t length, unsigned long long const seed);
unsigned int get_unsigned_int(const char *buffer, int offset, int length);
unsigned int get_unsigned_int_from(int a, int b, int c, int d);
size_t uint_bytes(char *dest, uint32_t num);
size_t bytes_uint(const char *str, size_t index, int length);
size_t uint64_bytes(char *dest, uint64_t num);
uint64_t bytes_uint64(const char *buffer, size_t offset, int length);
]])
local function check_encode_str(s)
if type(s) ~= 'string' then
if not s then
s = ''
else
s = tostring(s)
end
end
return s
end
function _M.parse_num(str)
return encoding.parse_num(str)
end
local function base64_encoded_length(len, no_padding)
return no_padding and floor((len * 8 + 5) / 6) or
floor((len + 2) / 3) * 4
end
function _M.encode_base64url(s)
if type(s) ~= "string" then
return nil, "must provide a string"
end
local slen = #s
local dlen = base64_encoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b64w_encode(dst, s, slen)
return ffi_string(dst, r_dlen)
end
local function check_decode_str(s, level)
if type(s) ~= 'string' then
error("string argument only", level + 2)
end
end
local function base64_decoded_length(len)
return floor((len + 3) / 4) * 3
end
function _M.decode_base64url(s)
if type(s) ~= "string" then
return nil, "must provide a string"
end
local slen = #s
local dlen = base64_decoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b64w_decode(dst, s, slen)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
local function base32_encoded_length(len)
return floor((len + 4) / 5) * 8
end
---encode_base32
---@param s string @ byte to encode
---@param no_padding boolean
---@param hex boolean @ with hex-char table or standard-char table
local function encode_base32(s, no_padding, hex)
s = check_encode_str(s)
local slen = #s
local no_padding_int = no_padding and 1 or 0
local dlen = base32_encoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.b32_encode(dst, s, slen, no_padding_int, hex and 1 or 0)
return ffi_string(dst, r_dlen)
end
function _M.encode_base32(s, no_padding)
return encode_base32(s, no_padding, 0)
end
function _M.encode_base32hex(s, no_padding)
return encode_base32(s, no_padding, 1)
end
local function base32_decoded_length(len)
return floor(len * 5 / 8)
end
local function decode_base32(s, hex)
check_decode_str(s, 1)
local slen = #s
if slen == 0 then
return ""
end
local dlen = base32_decoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.b32_decode(dst, s, slen, hex)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
function _M.decode_base32(s)
return decode_base32(s, 0)
end
function _M.decode_base32hex(s)
return decode_base32(s, 1)
end
local function base16_encoded_length(len)
return len * 2
end
function _M.encode_base16(s, out_in_lowercase)
s = check_encode_str(s)
local out_in_lowercase_int = out_in_lowercase and 1 or 0
local slen = #s
local dlen = base16_encoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b16_encode(dst, s, slen, out_in_lowercase_int)
return ffi_string(dst, r_dlen)
end
local function base16_decoded_length(len)
return len / 2
end
function _M.decode_base16(s)
check_decode_str(s, 1)
local slen = #s
if slen == 0 then
return ""
end
local dlen = base16_decoded_length(slen)
if floor(dlen) ~= dlen then
return nil, "invalid input"
end
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b16_decode(dst, s, slen)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
local function base2_encoded_length(len)
return len * 8
end
function _M.encode_base2(s)
s = check_encode_str(s)
local slen = #s
local dlen = base2_encoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b2_encode(dst, s, slen)
return ffi_string(dst, r_dlen)
end
local function base2_decoded_length(len)
return len / 8
end
function _M.decode_base2(s)
check_decode_str(s, 1)
local slen = #s
if slen == 0 then
return ""
end
local dlen = base2_decoded_length(slen)
if floor(dlen) ~= dlen then
return nil, "invalid input"
end
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b2_decode(dst, s, slen)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
local function base85_encoded_length(len)
return len / 4 * 5
end
function _M.encode_base85(s)
s = check_encode_str(s)
local slen = #s
if slen == 0 then
return ""
end
local dlen = base85_encoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b85_encode(dst, s, slen)
return ffi_string(dst, r_dlen)
end
local function base85_decoded_length(len)
return ceil(len / 5) * 4
end
function _M.decode_base85(s)
check_decode_str(s, 1)
local slen = #s
if slen == 0 then
return ""
end
local dlen = base85_decoded_length(slen)
local dst = get_string_buf(dlen)
local r_dlen = encoding.modp_b85_decode(dst, s, slen)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
---int_base64 this method is much faster than long_base64, max int 2147483647, but you can exceed 1 digit to 21474836479
---@param int number @ max number is 2147483647, which is `B_____`
---@return string @ base64 string
function _M.int_base64(int)
local dst = get_string_buf(7)
local r_dlen = encoding.int_base64(dst, int)
if r_dlen == -1 then
return nil, "invalid input"
end
local str
str = ffi_string(dst, r_dlen)
return str
end
---base64_int
---@param b64_str string @ max `D_____`
---@return number @ int number max 4294967295
function _M.base64_int(b64_str)
local ext
local len = #b64_str -- normal int will not exceed 6 chars
if len > 6 then
ext = byte(b64_str, len) - 48 -- convert byte to number
b64_str = sub(b64_str, 1, len - 2) -- remove last 2 chars
end
if ext then
return (encoding.base64_int(b64_str, len - 1) * 10) + ext
end
return encoding.base64_int(b64_str, len - 1)
end
---long_base64
---@param long number @ max number is 2147483647, which is `B_____`
---@return string @ base64 string
function _M.long_base64(long)
local dst = get_string_buf(7)
local r_dlen = encoding.long_base64(dst, long)
if r_dlen == -1 then
return nil, "invalid input"
end
return ffi_string(dst, r_dlen)
end
---base64_long
---@param b64_str string
---@return number, number @ lua number, cdata<long>
function _M.base64_long(b64_str)
local n = encoding.base64_long(b64_str, #b64_str - 1)
return n
end
-----xxhash64_b64 digest text into hashed base64 text
-----@param str string
-----@param seed number
function _M.xxhash64_b64(str, seed, with_padding)
if not str then
return nil, "empty input"
end
local dst = get_string_buf(11)
local r_dlen = encoding.xxhash64_b64(dst, str, #str, seed or 33)
if r_dlen == -1 then
return nil, "invalid input"
end
local res = ffi_string(dst, r_dlen)
if r_dlen == 11 or not with_padding then
return res
end
local rep = string.rep('=', 11 - r_dlen)
return rep
--return reverse(ffi_string(dst, r_dlen))
end
---xxhash32_b64 digest text into hashed base64 text
---@param str string
---@param seed number
---@return string @base64 encoded text
function _M.xxhash32_b64(str, seed)
local dst = get_string_buf(7)
local r_dlen = encoding.xxhash32_b64(dst, str, #str, seed or 33)
if r_dlen == -1 then
return nil, "invalid input"
end
--return reverse(ffi_string(dst, r_dlen))
return ffi_string(dst, r_dlen)
-- local int = encoding.xxhash32(str, #str, seed or 33)
-- local dst = get_string_buf(7)
-- local r_dlen = encoding.int_base64(dst, int)
-- return ffi_string(dst, r_dlen)
end
function _M.djb2_hash(str)
local n = encoding.djb2_hash(str)
if n then
return tonumber(n)
end
end
---xxhash64
---@param str string @base64 string
---@param seed number
---@return number @ULL number, using tonumber if you need string
function _M.xxhash64(str, seed)
local n = encoding.xxhash64(str, #str, seed or 33)
return n
end
function _M.xxhash32(str, seed)
local n = encoding.xxhash32(str, #str, seed or 33)
return n
end
function _M.xxhash3(str, seed)
local n = encoding.xxh3(str, #str, seed or 33)
return n
end
function _M.xxhash128(str, seed)
local dst = get_string_buf(16)
local n = encoding.xxhash128(str, #str, dst, seed or 33)
return ffi_string(dst, 16)
end
function _M.xxhash128_b64(str, seed)
local dst1 = get_string_buf(23)
local dst2 = get_string_buf(16)
local n = encoding.xxhash128_b64(dst2, dst1, str, #str, seed or 33)
return ffi_string(dst1, n), ffi_string(dst2, n)
end
---int_byte convert unsigned int into `4 bytes` with high performance
---@param int_num number @ max number: 21474836479 as `255,255,255,255`
---@param length number @ the char byte length. small number will padding with char(0)
---@return string @ chars based byte, could process by ngx.encode_base64
function _M.uint_byte(int_num, length)
if not length or length > 3 then
if int_num > _M.max_int then
return nil, 'exceed' .. _M.max_int
end
return char(band(rshift(int_num, 24), 0xFF), band(rshift(int_num, 16), 0xFF), band(rshift(int_num, 8), 0xFF), band(int_num, 0xFF))
end
if length == 3 then
if int_num > 16777215 then
return nil, 'exceed 16777215'
end
return char(band(rshift(int_num, 16), 0xFF), band(rshift(int_num, 8), 0xFF), band(int_num, 0xFF))
end
if length == 2 then
if int_num > 65535 then
return nil, 'exceed 65535'
end
return char(band(rshift(int_num, 8), 0xFF), band(int_num, 0xFF))
end
if int_num > 255 then
return nil, 'exceed 255'
end
return char(int_num)
end
-----int_byte convert unsigned int into `4 bytes`
-----@param int_num number @ max number: 21474836479
-----@return string @ chars based byte, could process by ngx.encode_base64
function _M.int_byte(num)
return char(band(rshift(num, 24), 0xFF), band(rshift(num, 16), 0xFF), band(rshift(num, 8), 0xFF), band(num, 0xFF))
end
function _M.byte_int(byte_str, start_index)
if not byte_str then
return 0
end
local len = #byte_str
if len < 3 then
return nil, 'at least 4 bytes'
end
start_index = start_index or 1
local n1 = lshift(byte(byte_str, start_index), 24)
local n2 = lshift(byte(byte_str, start_index + 1), 16)
local n3 = lshift(byte(byte_str, start_index + 2), 8)
local n4 = byte(byte_str, start_index + 3) or 0
return n1 + n2 + n3 + n4
end
_M.max_int_chars = _M.uint_byte(4294967295)
---byte_int convert `4 byte string` into number
---@param byte_str string @char bytes max is `ÿÿÿÿ`
---@return number @ unsigned int max number = 21474836479
---
---byte_uint convert `byte string` into unsigned int
---@param byte_str string
---@param start_index number @ The start index of byte_str stream, start with 1
---@param length number @ the uint length 1-4
function _M.byte_uint(byte_str, start_index, length)
if not byte_str then
return 0
end
local n = 0
if not start_index or start_index <= 0 then
start_index = 0
else
start_index = start_index - 1
end
--[[
local len = #byte_str
for i = 1, len - 1 do
local bn = byte(byte_str, i)
local v = lshift(bn, (len - i) * 8)
n = n + v
end
n = n + byte(byte_str, len)
if n < 0 then
n = n232 + n
end--]]
--n = encoding.get_unsigned_int(byte_str, 0, 1) -- by using c program to speedup
n = encoding.get_unsigned_int(byte_str, start_index, length or 4) -- by using c program to speedup
return n
end
---byte_int_from 4 numbers as a byte
---@param a number @[required ]1-255
---@param b number @1-255
---@param c number @1-255
---@param d number @1-255
---@return number
function _M.byte_int_from(a, b, c, d)
if not a then
return nil, 'bad input, 1 - 4 int number required'
end
return encoding.get_unsigned_int_from(a, b or 0, c or 0, d or 0)
end
---bytes_int_arr
---@param bin_bytes string @[Required]
---@param seed number @[Nullable Default 1] revert number
---@param to_string_format boolean @[Nullable] convert number list into formatted lua table string
function _M.bytes_int_arr(bin_bytes, seed, to_string_format)
local len = #bin_bytes
if seed == 0 then
return nil, 'seed could only greater than zero!'
end
seed = seed or 1
local last = mod(len, 4)
local arr = new_tab((len - last) / 4, 0)
local nc = 1
arr[nc] = len * 99991 -- 199999
for i = 1, len, 4 do
nc = nc + 1
arr[nc] = _M.byte_uint(bin_bytes, i) * seed
end
if to_string_format then
local buff = new_tab(nc, 0)
local bc = 1
buff[bc] = '{' .. arr[1] .. ', '
for i = 2, nc do
insert(buff, arr[i])
if i ~= nc then
if mod(i, 8) == 0 then
insert(buff, ',')
insert(buff, '\n')
else
insert(buff, ', ')
end
end
end
insert(buff, '\n}')
return concat(buff)
end
return arr
end
---int_arr_bytes
---@param int_arr number[] @[Required]
---@param seed number @[Nullable Default 1] revert number
function _M.int_arr_bytes(int_arr, seed)
if not int_arr then
return
end
local len = #int_arr
if seed == 0 then
return nil, 'seed could only greater than zero!'
end
seed = seed or 1
local orginal_length = int_arr[1] / 99991
for i = 2, len do
int_arr[i] = _M.uint_byte(int_arr[i] / seed)
end
local last = mod(orginal_length, 4)
if last > 0 then
int_arr[len] = sub(int_arr[len], 1, last)
end
table.remove(int_arr, 1)
return concat(int_arr)
end
---uint_bytes FFI version
---@param unsigned_int number
---@return string
function _M.ffi_uint_bytes(unsigned_int)
local buff = get_string_buf(4)
local size = encoding.uint_bytes(buff, unsigned_int)
return ffi_string(buff, size)
end
---bytes_uint FFI version
---@param byte_buff string
---@param index number @default with 0
---@param length number @ default with whole buff
---@return number
function _M.ffi_bytes_uint(byte_buff, index, length)
if index then
index = index - 1
else
index = 0
end
return tonumber(encoding.bytes_uint(byte_buff, index, length or #byte_buff))
end
---bytes_uint64
---@param byte_buff string
---@param index number @default with 0
---@param length number @ default with whole buff
function _M.bytes_uint64(byte_buff, index, length)
if index then
index = index - 1
else
index = 0
end
return encoding.bytes_uint64(byte_buff, index, length or #byte_buff)
end
---uint64_bytes
---@param num number @ unsigned long long could ffi object
---@return string
function _M.uint64_bytes(num)
local buff = get_string_buf(8)
local size = encoding.uint64_bytes(buff, num)
return ffi_string(buff, size)
end
---xxhash64_bytes hash string into 8 bytes
---@param str string
---@param seed number
---@return string
function _M.xxhash64_bytes(str, seed)
local num = _M.xxhash64(str, seed)
return _M.uint64_bytes(num)
end
---xxhash32_bytes hash string into 4 bytes
---@param str string
---@param seed number
---@return string
function _M.xxhash32_bytes(str, seed)
local num = _M.xxhash32(str, seed)
return _M.ffi_uint_bytes(num)
end
---list_int_bytes
---@param list number[] @number array
---@param is_unsigned boolean @ indicate is int or unsigned int
---@param sec_length number @bytes list element section length, 1-4
---@return string
function _M.list_int_bytes(list, is_unsigned, sec_length)
local len = #list
local arr = array(len)
if is_unsigned then
sec_length = sec_length or 4
if sec_length > 4 then
return nil, 'section length only less than 4'
end
for i = 1, len do
arr[i] = _M.uint_byte(list[i], sec_length)
end
else
for i = 1, len do
arr[i] = _M.int_byte(list[i])
end
end
local str = concat(arr)
release(arr)
return str
end
---bytes_list_int
---@param bytes string @byte buff
---@param is_unsigned boolean @ indicate is int or unsigned int
---@param sec_length number @bytes list element section length, 1-4
---@return number[]
function _M.bytes_list_int(bytes, is_unsigned, sec_length)
local len = #bytes
local arr = new_tab(math.floor(len / 4), 0)
local nc = 1
if is_unsigned then
sec_length = sec_length or 4
if sec_length > 4 then
return nil, 'section length only less than 4'
end
for i = 1, len, sec_length do
arr[nc] = _M.byte_uint(bytes, i, sec_length)
nc = nc + 1
end
else
for i = 1, len, 4 do
arr[nc] = _M.byte_int(bytes, i)
nc = nc + 1
end
end
return arr
end
return _M
|
--[[
Copyright © 2018, Karuberu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Lookup nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
_addon.name = 'Lookup'
_addon.author = 'Karuberu'
_addon.version = '1.0'
_addon.commands = {'lookup', 'lu'}
config = require('config')
res = require('resources')
settings = nil
ids = nil
last_item = nil
function load_settings()
settings = config.load({
default = 'ffxiclopedia';
sites = {
ffxiclopedia = {
search = 'http://ffxiclopedia.wikia.com/wiki/Special:Search?go=Go&search=${term}';
};
['bg-wiki'] = {
search = 'https://www.bg-wiki.com/bg/Special:Search?go=Go&search=${term}';
};
ffxidb = {
item = 'http://www.ffxidb.com/items/${term}';
zone = 'http://www.ffxidb.com/zones/${term}';
search = 'http://www.ffxidb.com/search?q=${term}';
};
ffxiah = {
item = 'http://www.ffxiah.com/item/${term}';
search = 'http://www.ffxiah.com/search/item?q=${term}';
};
ffxiahplayer = {
search = 'https://www.ffxiah.com/search/player?name=${term}';
};
google = {
search = 'https://www.google.com/search?q=${term}';
};
ffxi = { redirect = 'ffxiclopedia'; };
wikia = { redirect = 'ffxiclopedia'; };
bgwiki = { redirect = 'bg-wiki'; };
bg = { redirect = 'bg-wiki'; };
db = { redirect = 'ffxidb'; };
ah = { redirect = 'ffxiah'; };
ffxiahp = { redirect = 'ffxiahplayer'; };
ahp = { redirect = 'ffxiahplayer'; };
};
})
end
-- Creates a list of item and zone ids by name for quicker lookup by name
function initialize_ids()
ids = {
items = {};
zones = {};
}
for item in res.items:it() do
ids.items[item.name] = item.id
ids.items[item.name_log] = item.id
end
for zone in res.zones:it() do
ids.zones[zone.name] = zone.id
end
end
function get_id(name)
if id == nil then
return {}
end
return {
item = ids.items[name];
zone = ids.zones[name];
}
end
function get_name(id, list)
if id == nil then
return nil
end
return (list[id] or {}).name
end
-- Converts auto-translate strings to plain text.
-- If the string is not an auto-translate string, the original string is returned.
function translate(str)
return windower.convert_auto_trans(str)
end
-- Checks to see if the string is a selector (enclosed by <>) and returns a replacement.
-- If the string is not a selector, the original string is returned.
function parse_selection(str)
local target = str:match('<(.+)>')
if target == nil then
return str
end
-- custom selection handlers
if target == 'job' or target == 'mjob' then
return windower.ffxi.get_player().main_job_full
elseif target == 'sjob' then
return windower.ffxi.get_player().sub_job_full
elseif target == 'zone' then
if windower.ffxi.get_info().mog_house then
return 'Mog House'
else
return get_name(windower.ffxi.get_info().zone, res.zones)
end
elseif target == 'item' then
return get_name(last_item, res.items)
end
-- default to windower's selection handlers
return (windower.ffxi.get_mob_by_target(str) or {}).name
end
function set_default_site(command_modifier, site)
settings.default = site
if command_modifier == 'player' or command_modifier == 'p' then
-- save only for the current character
settings:save()
else
-- save for all characters
settings:save('all')
end
end
function modify_site_settings(site, type, url)
if url == 'remove' then
url = nil
end
settings.sites[site][type] = url
end
function set_last_item(bag, index, id, count)
if bag == 0 then
last_item = id
end
end
-- Replaces the named parameters in the url
function format_url(url, term)
if term == nil then
return term
end
return url:gsub('${term}', '%s':format(term))
end
function get_site(command)
local site = settings.sites[command]
if site ~= nil and site.redirect ~= nil then
site = settings.sites[site.redirect]
end
return site
end
function get_url(site, term)
term = translate(term)
term = parse_selection(term)
local id = get_id(term)
if id.item ~= nil and site.item ~= nil then
url = format_url(site.item, id.item)
elseif id.zone ~= nil and site.zone ~= nil then
url = format_url(site.zone, id.zone)
else
url = format_url(site.search, term)
end
return url
end
function process_command(...)
-- get the first argument and set it as the command for now
local command = ({...}[1] or ''):lower()
if command == 'default' then
local command_modifier, default_site
if {...}[3] ~= nil then
-- if there are three or more arguments, the second one is the modifier
command_modifier = {...}[2]
default_site = {...}[3]
else
default_site = {...}[2]
end
set_default_site(command_modifier, default_site)
return
elseif command == 'site' then
local site = {...}[2]
local type = {...}[3]
local url = {...}[4]
modify_site_settings(site, type, url)
return
end
local term;
if {...}[2] ~= nil then
-- if there are two arguments, the first is the command and the second the term
command = {...}[1]
term = {...}[2]
else
-- otherwise, just a term is provided, so use the default command
command = settings.default
term = {...}[1]
end
if term == nil then
return
end
local site = get_site(command:lower())
if site == nil then
return
end
local url = get_url(site, term)
if url == nil then
return
end
windower.open_url(url)
end
load_settings()
initialize_ids()
windower.register_event('add item', set_last_item)
windower.register_event('addon command', process_command)
|
local configs = require 'lspconfig/configs'
local util = require 'lspconfig/util'
configs.lean3ls = {
default_config = {
cmd = { 'lean-language-server', '--stdio', '--', '-M', '4096', '-T', '100000' },
filetypes = { 'lean3' },
root_dir = function(fname)
return util.root_pattern 'leanpkg.toml'(fname) or util.find_git_ancestor(fname) or util.path.dirname(fname)
end,
on_new_config = function(config, root)
if not util.path.is_file(root .. '/leanpkg.toml') then
return
end
if not config.cmd_cwd then
config.cmd_cwd = root
end
end,
},
docs = {
description = [[
https://github.com/leanprover/lean-client-js/tree/master/lean-language-server
Lean installation instructions can be found
[here](https://leanprover-community.github.io/get_started.html#regular-install).
Once Lean is installed, you can install the Lean 3 language server by running
```sh
npm install -g lean-language-server
```
]],
default_config = {
root_dir = [[root_pattern("leanpkg.toml") or root_pattern(".git") or path.dirname]],
},
},
}
-- vim:et ts=2 sw=2
|
-- NETDUINO-2 build configuration
return {
cpu = 'stm32f205rf',
components = {
-- sercon = { uart = 1, speed = 115200, buf_size = 128 },
sercon = { uart = "cdc", speed = 115200 },
cdc = { buf_size = 128 },
wofs = true,
romfs = true,
shell = { advanced = true },
term = { lines = 25, cols = 80 },
cints = true,
luaints = true,
-- linenoise = { shell_lines = 10, lua_lines = 50 },
rpc = { uart = 1, speed = 115200 },
adc = { buf_size = 2 },
xmodem = true,
-- mmcfs = { cs_port = 1, cs_pin = 10, spi = 0 }
},
config = {
egc = { mode = "alloc" },
vtmr = { num = 4, freq = 10 },
clocks = { external = 25000000, cpu = 120000000 }
},
modules = {
generic = { 'all', "-i2c", "-net" },
}
}
|
local Public = {}
Public.ElevatorEngine = require(script.ElevatorEngine)
return Public |
function TicTacToeEnvironment(gridSize)
local env = {}
local state
local currState
local nextState
local util = TicTacToeUtil()
-- Resets the environment. Randomly initialise the fruit position (always at the top to begin with) and bucket.
function env.reset()
state = torch.Tensor(gridSize, gridSize):zero()
end
-- Returns the state of the environment.
function env.observe()
return state
end
function env.drawState()
end
function env.getState()
end
-- Returns the award that the agent has gained for being in the current environment state.
function env.getReward()
end
function env.isGameOver()
end
function env.updateState(action)
end
function env.act(action, stone)
local coord = util.coord(action)
state[coord[1]][coord[2]] = stone
local reward = 0
local gameOver = false
winningCond = util.checkWinState(state, stone)
if ( winningCond == true ) then
reward = 1
gameOver = true
elseif ( util.isAllMarked(state) ) then
reward = 0.5
gameOver = true
end
return env.observe(), reward, gameOver
end
return env
end
|
include("LensSupport")
local LENS_NAME = "ML_SCOUT"
local ML_LENS_LAYER = UILens.CreateLensLayerHash("Hex_Coloring_Appeal_Level")
local m_LensSettings = {
["COLOR_SCOUT_LENS_GHUT"] = { ConfiguredColor = GetLensColorFromSettings("COLOR_SCOUT_LENS_GHUT"), KeyLabel = "LOC_HUD_SCOUT_LENS_GHUT" }
}
-- Should the scout lens auto apply, when a scout/ranger is selected.
local AUTO_APPLY_SCOUT_LENS:boolean = true;
-- Should the scout lens auto-apply with any military unit
local AUTO_APPLY_SCOUT_LENS_EXTRA:boolean = false;
-- ==== BEGIN CQUI: Integration Modification =================================
local function CQUI_OnSettingsInitialized()
-- Should the builder lens auto apply, when a builder is selected.
AUTO_APPLY_SCOUT_LENS = GameConfiguration.GetValue("CQUI_AutoapplyScoutLens");
AUTO_APPLY_SCOUT_LENS_EXTRA = GameConfiguration.GetValue("CQUI_AutoapplyScoutLensExtra");
UpdateLensConfiguredColors(m_LensSettings, g_ModLensModalPanel, LENS_NAME);
end
local function CQUI_OnSettingsUpdate()
CQUI_OnSettingsInitialized();
end
-- ==== END CQUI: Integration Modification ===================================
-- ===========================================================================
-- Scout Lens Support
-- ===========================================================================
local function plotHasGoodyHut(plot)
local improvementInfo = GameInfo.Improvements[plot:GetImprovementType()]
if improvementInfo ~= nil and improvementInfo.ImprovementType == "IMPROVEMENT_GOODY_HUT" then
return true
end
return false
end
-- ===========================================================================
-- Exported functions
-- ===========================================================================
local function OnGetColorPlotTable()
-- print("Show scout lens")
local mapWidth, mapHeight = Map.GetGridSize()
local localPlayer :number = Game.GetLocalPlayer()
local localPlayerVis:table = PlayersVisibility[localPlayer]
local GoodyHutColor :number = m_LensSettings["COLOR_SCOUT_LENS_GHUT"].ConfiguredColor
local colorPlot = {}
colorPlot[GoodyHutColor] = {}
for i = 0, (mapWidth * mapHeight) - 1, 1 do
local pPlot:table = Map.GetPlotByIndex(i)
if localPlayerVis:IsRevealed(pPlot:GetX(), pPlot:GetY()) then
if plotHasGoodyHut(pPlot) then
table.insert(colorPlot[GoodyHutColor], i)
end
end
end
return colorPlot
end
-- Called when a scout is selected
local function ShowScoutLens()
LuaEvents.MinimapPanel_SetActiveModLens(LENS_NAME)
UILens.ToggleLayerOn(ML_LENS_LAYER)
end
local function ClearScoutLens()
if UILens.IsLayerOn(ML_LENS_LAYER) then
UILens.ToggleLayerOff(ML_LENS_LAYER)
end
LuaEvents.MinimapPanel_SetActiveModLens("NONE")
end
local function RefreshScoutLens()
ClearScoutLens()
ShowScoutLens()
end
local function OnUnitSelectionChanged( playerID:number, unitID:number, hexI:number, hexJ:number, hexK:number, bSelected:boolean, bEditable:boolean )
if playerID == Game.GetLocalPlayer() and (AUTO_APPLY_SCOUT_LENS or AUTO_APPLY_SCOUT_LENS_EXTRA) then
local pPlayer = Players[playerID]
local pUnit = pPlayer:GetUnits():FindID(unitID)
local unitType = pUnit:GetUnitType()
if unitType ~= -1 and GameInfo.Units[unitType] ~= nil then
local promotionClass = GameInfo.Units[unitType].PromotionClass
local unitDomain = GameInfo.Units[unitType].Domain
local militaryUnit = (pUnit:GetCombat() > 0 or pUnit:GetRangedCombat() > 0) and (unitDomain == "DOMAIN_LAND")
if bSelected then
if militaryUnit and AUTO_APPLY_SCOUT_LENS_EXTRA then
ShowScoutLens()
elseif promotionClass == "PROMOTION_CLASS_RECON" then
ShowScoutLens()
end
-- Deselection
else
if militaryUnit and AUTO_APPLY_SCOUT_LENS_EXTRA then
ClearScoutLens()
elseif promotionClass == "PROMOTION_CLASS_RECON" then
ClearScoutLens()
end
end
end
end
end
local function OnUnitRemovedFromMap( playerID: number, unitID : number )
if playerID == Game.GetLocalPlayer() and (AUTO_APPLY_SCOUT_LENS or AUTO_APPLY_SCOUT_LENS_EXTRA) then
local lens = {}
LuaEvents.MinimapPanel_GetActiveModLens(lens)
if lens[1] == LENS_NAME then
ClearScoutLens()
end
end
end
local function OnUnitMoveComplete( playerID:number, unitID:number )
if playerID == Game.GetLocalPlayer() and (AUTO_APPLY_SCOUT_LENS or AUTO_APPLY_SCOUT_LENS_EXTRA) then
local pPlayer = Players[playerID]
local pUnit = pPlayer:GetUnits():FindID(unitID)
-- Ensure the unit is selected. Scout could be exploring automated
if UI.IsUnitSelected(pUnit) then
local unitType = pUnit:GetUnitType()
if unitType ~= -1 and GameInfo.Units[unitType] ~= nil then
local promotionClass = GameInfo.Units[unitType].PromotionClass
local unitDomain = GameInfo.Units[unitType].Domain
local militaryUnit = (pUnit:GetCombat() > 0 or pUnit:GetRangedCombat() > 0) and (unitDomain == "DOMAIN_LAND")
if militaryUnit and AUTO_APPLY_SCOUT_LENS_EXTRA then
RefreshScoutLens()
elseif promotionClass == "PROMOTION_CLASS_RECON" then
RefreshScoutLens()
end
end
end
end
end
local function OnGoodyHutReward( playerID:number )
if playerID == Game.GetLocalPlayer() and (AUTO_APPLY_SCOUT_LENS or AUTO_APPLY_SCOUT_LENS_EXTRA) then
local lens = {}
LuaEvents.MinimapPanel_GetActiveModLens(lens)
if lens[1] == LENS_NAME then
RefreshScoutLens()
end
end
end
local function OnLensSettingsUpdate()
-- Refresh our local settings from updated GameConfig
AUTO_APPLY_SCOUT_LENS = GameConfiguration.GetValue("ML_AutoApplyScoutLens")
AUTO_APPLY_SCOUT_LENS_EXTRA = GameConfiguration.GetValue("ML_AutoApplyScoutLensExtra")
end
local function OnInitialize()
Events.UnitSelectionChanged.Add( OnUnitSelectionChanged )
Events.UnitRemovedFromMap.Add( OnUnitRemovedFromMap )
Events.UnitMoveComplete.Add( OnUnitMoveComplete )
Events.GoodyHutReward.Add( OnGoodyHutReward )
end
local ScoutLensEntry = {
LensButtonText = "LOC_HUD_SCOUT_LENS",
LensButtonTooltip = "LOC_HUD_SCOUT_LENS_TOOLTIP",
Initialize = OnInitialize,
GetColorPlotTable = OnGetColorPlotTable
}
-- minimappanel.lua
if g_ModLenses ~= nil then
g_ModLenses[LENS_NAME] = ScoutLensEntry
end
-- modallenspanel.lua
if g_ModLensModalPanel ~= nil then
g_ModLensModalPanel[LENS_NAME] = {}
g_ModLensModalPanel[LENS_NAME].LensTextKey = "LOC_HUD_SCOUT_LENS"
g_ModLensModalPanel[LENS_NAME].Legend = {
{m_LensSettings["COLOR_SCOUT_LENS_GHUT"].KeyLabel, m_LensSettings["COLOR_SCOUT_LENS_GHUT"].ConfiguredColor}
}
end
-- Add CQUI LuaEvent Hooks for minimappanel and modallenspanel contexts
LuaEvents.CQUI_SettingsUpdate.Add(CQUI_OnSettingsUpdate);
LuaEvents.CQUI_SettingsInitialized.Add(CQUI_OnSettingsInitialized); |
return {
fadeOut = 1.5,
mode = 2,
id = "MAOZIHUODONG30",
once = true,
fadeType = 2,
fadein = 1.5,
scripts = {
{
bgm = "bgm-cccp2",
side = 2,
dir = 1,
blackBg = true,
say = "北方联合某处·??? ",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_cccp_8",
say = "接受了苏维埃罗西亚的请求,在北方联合多待了一阵子…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 4,
side = 2,
bgName = "bg_cccp_8",
actor = 701020,
dir = 1,
nameColor = "#a9f548",
say = "…指挥官同志,外面虽然很冷,不过到屋里来就没问题了。热可可,要喝么?还是要…罗宋汤?",
effects = {
{
active = true,
name = "memoryFog"
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_cccp_8",
say = "北方联合的气候,真的很寒冷啊…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 6,
side = 2,
bgName = "bg_cccp_8",
actor = 702020,
dir = 1,
nameColor = "#a9f548",
say = "指挥官别客气,虽然品种上不如白鹰的丰富,不过味道上我可是很自信的哦~",
flashout = {
black = true,
dur = 0.25,
alpha = {
0,
1
}
},
flashin = {
delay = 0.25,
dur = 0.25,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 2,
side = 2,
bgName = "bg_cccp_8",
actor = 702020,
dir = 1,
nameColor = "#a9f548",
say = "嗯?你在想什么呢,当然不是我做的啦!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_cccp_8",
say = "北方联合的料理,果然还是挺棒的",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 7,
side = 2,
bgName = "bg_cccp_8",
actor = 702030,
dir = 1,
nameColor = "#a9f548",
say = "数十年来我们和塞壬之间的战斗从未中断,来自皇家和白鹰的援助还是十分有必要的呢。",
flashout = {
black = true,
dur = 0.25,
alpha = {
0,
1
}
},
flashin = {
delay = 0.25,
dur = 0.25,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_cccp_8",
say = "持续数十年的拉锯战…就算这样,北方联合依然在顽强地坚持着…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 701040,
side = 2,
bgName = "bg_cccp_8",
nameColor = "#a9f548",
dir = 1,
say = "同志酱,这里就是回港之后,塔什干和伙伴们休息的地方。",
flashout = {
black = true,
dur = 0.25,
alpha = {
0,
1
}
},
flashin = {
delay = 0.25,
dur = 0.25,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_cccp_8",
actor = 701040,
dir = 1,
nameColor = "#a9f548",
say = "很壮观?…这样。坐下,然后和塔什干聊聊外面的事情吧。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_cccp_8",
say = "这里是…北方联合的住宅区?!宏伟的住宅楼简直像大厦一样…",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
blackBg = true,
say = "这几天,在北方联合被热情的邀请参观了很多地方啊…",
effects = {
{
active = false,
name = "memoryFog"
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
blackBg = true,
say = "到处充满着强大的凝聚力和必胜的信心,与白鹰皇家的氛围都不同,有种奇妙的感觉。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
blackBg = true,
say = "而今天,则是受到邀请,在苏维埃罗西亚的陪同下与北方联合某位很重要的人会面——",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 900226,
side = 2,
nameColor = "#a9f548",
dir = 1,
blackBg = true,
say = "…关于指挥官的数据报告、吗",
flashout = {
black = true,
dur = 0.5,
alpha = {
0,
1
}
},
flashin = {
delay = 0.5,
dur = 0.5,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 900226,
nameColor = "#a9f548",
side = 2,
dir = 1,
blackBg = true,
say = "如此独特的心智魔方适应性…果然还是应该——",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
blackBg = true,
say = "(敲门声)",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 900226,
nameColor = "#a9f548",
side = 2,
dir = 1,
blackBg = true,
say = "…来了吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 705050,
side = 2,
nameColor = "#a9f548",
dir = 1,
blackBg = true,
say = "指挥官,就是这里了,请进",
flashout = {
black = true,
dur = 0.5,
alpha = {
0,
1
}
},
flashin = {
delay = 0.5,
dur = 0.5,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_white",
say = "明媚的阳光突然突然从敞开的大门中涌入昏暗的走道,覆盖了整个视野。",
flashout = {
dur = 1,
alpha = {
0,
1
}
},
flashin = {
delay = 1,
dur = 0.1,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_white",
say = "眼睛逐渐适应后,一位身穿白色长袍的女性出现在视野中。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
bgName = "bg_white",
say = "她放下手中的书,清澈而坚定地目光向这边看来。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 900218,
side = 2,
bgName = "bg_white",
nameColor = "#a9f548",
dir = 1,
blackBg = true,
say = "来加入北方联合吧,指挥官同志!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
}
}
}
|
--ZFUNC-isdodd-v1
local function isdodd( e ) --> res
if e == "." or e == ".." then
return true
end
return false
end
return isdodd
|
require("utils")
-- General Settings
--
-- The options set below are general defaults, and may be overridden on a
-- per-buffer basis depending on the filetype or other such property.
-------------------------------------------------------------------------------
-- Define local constants
local COLORSCHEME = "gruvbox"
local TABSTOP = 4
-- Automatically detect filetypes
--vim.o.filetype = "plugin indent on"
vim.cmd("filetype plugin indent on")
-- Session-related options
vim.cmd("set ssop-=folds") -- do not store folds
vim.cmd("set ssop-=options") -- do not store global or local options
-- Highlight options
vim.cmd("highlight vertsplit guifg=bg guibg=bg")
-- Global Settings
--
-- These should be considered "global defaults", as some options (e.g. indentation) may be
-- overridden by filetype plugins for specific filetypes.
--
-- See `:help <option>` for more information.
---------------------------------------------------------------------------------------------------
vim.o.autoindent = true -- indent at the same level as the previous line
vim.o.autowrite = true -- automatically write changed buffers
vim.o.background = "dark" -- assume a dark background
vim.o.backup = false -- disable backup files
vim.o.compatible = false -- disable vi compatibility mode
vim.o.expandtab = true -- insert spaces when <tab> is pressed
vim.o.gdefault = true -- use the global flag by default for :substitute invocations
vim.o.ignorecase = true -- ignore character case when searching
vim.o.joinspaces = false -- don't add spaces after punctuation after joining lines
vim.o.laststatus = 2 -- always show the statusline
vim.o.number = true -- display line numbers in the gutter
vim.o.relativenumber = true -- make line numbers relative to the current line
vim.o.ruler = true -- display row and column information in the statusline
vim.o.shiftwidth = 0 -- zero makes this equal to 'tabstop'
vim.o.smartcase = true -- override 'ignorecase' when query contains [A-Z] characters
vim.o.softtabstop = -1 -- negative numbers make this equal to 'shiftwidth'
vim.o.splitbelow = true -- horizontal splits are placed below
vim.o.splitright = true -- vertical splits are placed to the right
vim.o.swapfile = false -- disable swap files
vim.o.syntax = "on" -- enable syntax highlighting
vim.o.tabstop = TABSTOP -- indent every X columns
vim.o.textwidth = LINE_WIDTH -- break lines at X characters
vim.o.undofile = false -- disable undo files
vim.o.updatetime = 300 -- trigger a CursorHold event after cursor inactivity
vim.o.wrap = true -- automatically wrap lines
-- AUTOCOMMANDS
---------------------------------------------------------------------------------------------------
vim.api.nvim_define_augroup("Global", true)
-- Automatically save when leaving buffers
-- This is mostly useful when navigating between splits, as the 'autowrite' setting doesn't apply
vim.api.nvim_define_autocmd("BufLeave", "*", "silent! wall", "Global")
-- Set the colorscheme
vim.api.nvim_define_autocmd("vimenter", "*", "colorscheme " .. COLORSCHEME, "Global")
|
require "class"
local A = class()
function A:ctor()
print("A's constructor called")
end
function A:hi()
print("A:hi")
end
function A:dtor()
print("A's dtor called")
end
local B = class(A)
function B:ctor()
print("B's constructor called")
end
function B:hi()
print("B:hi")
end
function B:dtor()
print("B's dtor called")
end
local C = class(A)
function C:ctor()
print("C's constructor called")
end
function C:hi()
print("C:hi")
end
function C:dtor()
print("C's dtor called")
end
local D = class(B, C)
function D:ctor()
print("D's constructor called")
end
function D:dtor()
print("D's dtor called")
end
local d = D.new()
d:hi()
local d2 = new(D)
delete(d2)
--[[ OUTPUT
A's constructor called
B's constructor called
C's constructor called
D's constructor called
B:hi
A's constructor called
B's constructor called
C's constructor called
D's constructor called
D's dtor called
B's dtor called
A's dtor called
C's dtor called
]]
|
local mapa = {
ambient="0.1,0.1,0.1",
gravity="0 -9.8 0",
entities={
{
name="Player",
id=1,
components={
transform={
position="20,-80,0",
rotation="0,0,0",
scale="2,2,2",
parent="-1"
},
renderer={
mesh="Sinbad.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="54",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic ="false"
},
audiolistener={
position="20, -80, 0"
}
}
},
{
name="Drone",
id=5,
components={
transform={
position="10,-80,0",
rotation="0,0,0",
scale="1,1,1",
parent="-1"
},
renderer={
mesh="Sinbad.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="54",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic ="true"
},
basicai={
step="100",
threshold="0.5",
thresholdRot="0.1",
stepRot="0.005"
},
audiosource={
sound="aVerSiSeCorta.mp3",
volume="20",
velocity="0 0 0"
}
}
},
{
name="Camera",
id=2,
components={
transform={
position="0,-50,200",
rotation="0,0,0",
scale="1,1,1",
parent="-1"
},
camera={
near="0.1",
far="1000",
autoaspect="true",
aspect="1.78",
fov="50",
proyection="1",
viewport="0,0,1,1",
color="1.0,0.5,0.3137"
}
}
},
{
name="Luz",
id=3,
components={
transform={
position="50,0,0",
rotation="0,0,0",
scale="1,1,1",
parent="-1"
},
light={
type="0",
attenuation="",
shadows="true",
diffuse="1,0.2,1,1",
specular="1,1,1,1",
spotinner="",
spotouter=""
}
}
},
{
name="Suelo",
id=4,
components={
transform={
position="0,-100,0",
rotation="0,0,0",
scale="3,0.2,3",
parent="-1"
},
renderer={
mesh="cube.mesh",
material="",
visible="true"
},
rigidbody={
shape="0",
mass="0",
inertia="0,0,0",
restitution="0.2",
damping="0.2,0.2",
trigger="false",
kinematic ="false"
}
}
}
}
}
function GetMapa ()
return mapa
end
|
--REF: https://github.com/mbbill/undotree
use 'mbbill/undotree'
nnoremap <LocalLeader>d :UndotreeToggle<CR>:UndotreeFocus<CR>
-- REF: https://github.com/machakann/vim-highlightedyank
use 'machakann/vim-highlightedyank'
let g:highlightedyank_highlight_duration = 1000
use 'bronson/vim-visual-star-search'
-- REF: https://github.com/tpope/vim-commentary
use 'tpope/vim-commentary' --Blazing fast!!
use 'bronson/vim-trailing-whitespace'
--REF: https://github.com/wsdjeg/vim-fetch
use 'wsdjeg/vim-fetch' --Open/Edit file from reference: /path/to/file:190:3
-- REF: https://github.com/rbgrouleff/bclose.vim
use 'rbgrouleff/bclose.vim' --CLOSE BUF WITHOUT CLOSING WINDOW
--REF: https://github.com/nathom/filetype.nvim
use 'nathom/filetype.nvim' --Speed-up over filetype.vim for 10ms
let g:did_load_filetypes = 1
|
do
local _ = {
lab = {
icon = '__base__/graphics/icons/lab.png',
close_sound = 0,
name = 'lab',
on_animation = {
layers = {
{
filename = '__base__/graphics/entity/lab/lab.png',
line_length = 11,
animation_speed = 0.33333333333333,
frame_count = 33,
height = 87,
width = 98,
shift = {0, 0.046875},
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab.png',
line_length = 11,
animation_speed = 0.33333333333333,
frame_count = 33,
height = 174,
width = 194,
shift = {0, 0.046875},
scale = 0.5
}
}, {
filename = '__base__/graphics/entity/lab/lab-integration.png',
line_length = 1,
frame_count = 1,
width = 122,
repeat_count = 33,
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab-integration.png',
line_length = 1,
frame_count = 1,
width = 242,
repeat_count = 33,
animation_speed = 0.33333333333333,
scale = 0.5,
height = 162,
shift = {0, 0.484375}
},
animation_speed = 0.33333333333333,
height = 81,
shift = {0, 0.484375}
}, {
filename = '__base__/graphics/entity/lab/lab-light.png',
line_length = 11,
blend_mode = 'additive',
frame_count = 33,
width = 106,
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab-light.png',
line_length = 11,
blend_mode = 'additive',
frame_count = 33,
width = 216,
animation_speed = 0.33333333333333,
scale = 0.5,
height = 194,
shift = {0, 0},
draw_as_light = true
},
animation_speed = 0.33333333333333,
height = 100,
shift = {-0.03125, 0.03125},
draw_as_light = true
}, {
filename = '__base__/graphics/entity/lab/lab-shadow.png',
draw_as_shadow = true,
frame_count = 1,
width = 122,
repeat_count = 33,
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab-shadow.png',
draw_as_shadow = true,
frame_count = 1,
width = 242,
repeat_count = 33,
animation_speed = 0.33333333333333,
scale = 0.5,
height = 136,
shift = {0.40625, 0.34375},
line_length = 1
},
animation_speed = 0.33333333333333,
height = 68,
shift = {0.40625, 0.34375},
line_length = 1
}
}
},
energy_usage = '60kW',
collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
corpse = 'lab-remnants',
off_animation = {
layers = {
{
filename = '__base__/graphics/entity/lab/lab.png',
frame_count = 1,
height = 87,
width = 98,
shift = {0, 0.046875},
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab.png',
frame_count = 1,
height = 174,
width = 194,
shift = {0, 0.046875},
scale = 0.5
}
}, {
filename = '__base__/graphics/entity/lab/lab-integration.png',
frame_count = 1,
height = 81,
width = 122,
shift = {0, 0.484375},
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab-integration.png',
frame_count = 1,
height = 162,
width = 242,
shift = {0, 0.484375},
scale = 0.5
}
}, {
filename = '__base__/graphics/entity/lab/lab-shadow.png',
draw_as_shadow = true,
frame_count = 1,
height = 68,
width = 122,
shift = {0.40625, 0.34375},
hr_version = {
filename = '__base__/graphics/entity/lab/hr-lab-shadow.png',
draw_as_shadow = true,
frame_count = 1,
height = 136,
width = 242,
shift = {0.40625, 0.34375},
scale = 0.5
}
}
}
},
vehicle_impact_sound = 0,
dying_explosion = 'lab-explosion',
icon_mipmaps = 4,
researching_speed = 1,
inputs = {
'automation-science-pack', 'logistic-science-pack', 'military-science-pack', 'chemical-science-pack',
'production-science-pack', 'utility-science-pack', 'space-science-pack'
},
type = 'lab',
open_sound = 0,
module_specification = {module_info_icon_shift = {0, 0.9}, module_slots = 2},
flags = {'placeable-player', 'player-creation'},
working_sound = {
fade_in_ticks = 4,
audible_distance_modifier = 0.7,
fade_out_ticks = 20,
sound = {filename = '__base__/sound/lab.ogg', volume = 0.7}
},
damaged_trigger_effect = {
damage_type_filters = 'fire',
entity_name = 'spark-explosion',
type = 'create-entity',
offsets = {{0, 1}},
offset_deviation = {{-0.5, -0.5}, {0.5, 0.5}}
},
max_health = 150,
selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
energy_source = {usage_priority = 'secondary-input', type = 'electric'},
icon_size = 64,
minable = {mining_time = 0.2, result = 'lab'}
}
};
return _;
end
|
--[[
-- added by wsh @ 2017-12-05
-- Singleton单元测试
--]]
require "Framework.Common.BaseClass"
local Singleton = require "Framework.Common.Singleton"
local function TestSingleton()
local testSingleton1 = BaseClass("testSingleton1", Singleton)
local testSingleton2 = BaseClass("testSingleton1", Singleton)
assert(testSingleton1.Instance == nil)
assert(testSingleton2.Instance == nil)
local inst1 = testSingleton1:GetInstance()
assert(testSingleton1.Instance == inst1)
assert(testSingleton2.Instance == nil)
local inst2 = testSingleton2:GetInstance()
assert(testSingleton1.Instance == inst1)
assert(testSingleton2.Instance == inst2)
assert(inst1 ~= inst2)
inst1.testVar1 = 111
inst2.testVar1 = 222
assert(inst1.testVar1 == 111)
assert(inst2.testVar1 == 222)
assert(testSingleton1.Instance.testVar1 == 111)
assert(testSingleton2.Instance.testVar1 == 222)
assert(testSingleton1:GetInstance().testVar1 == 111)
assert(testSingleton2:GetInstance().testVar1 == 222)
inst1:Delete()
inst1 = nil --这里一定要置空,所以不建议这么用,单例类建议都使用“类名:GetInstance().XXX”方式使用
assert(testSingleton1.Instance == nil)
testSingleton2:GetInstance():Delete()
inst2 = nil --同上
assert(testSingleton2.Instance == nil)
end
local function TestSingleton2()
local testSingleton1 = BaseClass("testSingleton1", Singleton)
local testSingleton2 = BaseClass("testSingleton2", testSingleton1)
assert(testSingleton1.Instance == nil)
assert(testSingleton2.Instance == nil)
local inst1 = testSingleton1:GetInstance()
assert(testSingleton1.Instance == inst1)
assert(testSingleton2.Instance == nil)
local inst2 = testSingleton2:GetInstance()
assert(testSingleton1.Instance == inst1)
assert(testSingleton2.Instance == inst2)
assert(inst1 ~= inst2)
inst1.testVar1 = 111
inst2.testVar1 = 222
assert(inst1.testVar1 == 111)
assert(inst2.testVar1 == 222)
assert(testSingleton1.Instance.testVar1 == 111)
assert(testSingleton2.Instance.testVar1 == 222)
assert(testSingleton1:GetInstance().testVar1 == 111)
assert(testSingleton2:GetInstance().testVar1 == 222)
inst2:Delete()
inst2 = nil --同上
assert(testSingleton2.Instance == nil)
assert(testSingleton1.Instance ~= nil)
testSingleton1:GetInstance():Delete()
inst1 = nil --同上
assert(testSingleton1.Instance == nil)
inst1 = testSingleton1:GetInstance()
inst2 = testSingleton2:GetInstance()
testSingleton2:GetInstance():Delete()
inst2 = nil --同上
assert(testSingleton2.Instance == nil)
assert(testSingleton1.Instance ~= nil)
assert(testSingleton1.Instance.testVar1 ~= 111)
testSingleton1:GetInstance():Delete()
inst1 = nil --同上
end
local function TestSingletonErr()
local testSingleton1 = BaseClass("testSingleton1", Singleton)
assert(testSingleton1.Instance == nil)
local inst1 = testSingleton1:GetInstance()
local inst2 = testSingleton1.New()
end
local function Run()
TestSingleton()
TestSingleton2()
assert(pcall(TestSingletonErr) == false, "TestSingletonErr failed!")
print("SingletonTest Pass!")
end
return {
Run = Run
} |
local mysql = exports.mrp_mysql
local charCache = {}
local singleCharCache = {}
local cacheUsed = 0
local function secondArg( a, b )
return b
end
local function makeName( a, b )
-- find first and last name
local ax, ay = a:sub( 1, a:find( "_" ) - 1 ), a:sub( secondArg( a:find( "_" ) ) + 1 )
local bx, by = b:sub( 1, b:find( "_" ) - 1 ), b:sub( secondArg( b:find( "_" ) ) + 1 )
if ay == by then
return ax .. " & " .. bx .. " " .. by
else
return a .. " & " .. b
end
end
function stats()
return cacheUsed
end
function getCharacterName( id, singleName )
if not charCache[ id ] then
id = tonumber(id)
if not (id < 1) then
local query = {}
local value = exports.mrp_global:getCache("characters", id, "id")
if value then
query.charactername = value.charactername
query.gender = value.gender
query.marriedto = value.marriedto
end
if query then
local name = query["charactername"]
local gender = tonumber(query["gender"])
local marriedto = tonumber(query["marriedto"])
if name then
singleCharCache[ id ] = name:gsub("_", " ")
if marriedto > 0 then
local name2 = query["charactername"]
local gender2 = tonumber(query["gender"])
singleCharCache[ marriedto ] = name2:gsub("_", " ")
if name2 ~= nil then
if gender == gender2 then
if name < name2 then
name = makeName( name, name2 )
else
name = makeName( name2, name )
end
elseif gender == 1 then
name = makeName( name, name2 )
else
name = makeName( name2, name )
end
end
end
charCache[ id ] = name:gsub("_", " ")
end
end
else
charCache[ id ] = false
singleCharCache[ id ] = false
end
else
cacheUsed = cacheUsed + 1
end
return singleName and singleCharCache[ id ] or charCache[ id ]
end
function clearCharacterName( id )
charCache[ id ] = nil
singleCharCache[ id ] = nil
end
function clearCharacterCache()
charCache = { }
singleCharCache = { }
end |
pg = pg or {}
pg.SystemOpenMgr = singletonClass("SystemOpenMgr")
slot1 = true
slot2 = pg.open_systems_limited
pg.SystemOpenMgr.Init = function (slot0, slot1)
print("initializing SystemOpenMgr manager...")
slot1()
end
slot3 = pm.Facade.sendNotification
pm.Facade.sendNotification = function (slot0, slot1, slot2, slot3)
if slot0 and slot1 == GAME.LOAD_SCENE then
slot5 = slot2.context.mediator.__cname
if getProxy(PlayerProxy) and slot4:getData() then
slot7, slot8 = pg.SystemOpenMgr.GetInstance():isOpenSystem(slot6.level, slot5)
if not slot7 then
pg.TipsMgr.GetInstance():ShowTips(slot8)
return
end
end
if HXSet.isHxSkin() and slot5 == "SkinShopMediator" then
return
end
slot1(slot0, GAME.CHECK_HOTFIX_VER, {
mediatorName = slot5
})
end
if slot1 == GAME.BEGIN_STAGE then
pg.GuildMsgBoxMgr.GetInstance():OnBeginBattle()
end
if slot1 == GAME.FINISH_STAGE_DONE then
pg.GuildMsgBoxMgr.GetInstance():OnFinishBattle(slot2)
end
slot1(slot0, slot1, slot2, slot3)
end
function slot4(slot0)
slot2 = slot0[14].name
if slot0[14].level == slot0 then
if pg.NewStoryMgr.GetInstance():IsPlayed("ZHIHUIMIAO1") or Application.isEditor then
return true
else
return false, i18n("no_open_system_tip", slot2, slot1)
end
elseif slot1 < slot0 then
return true
else
return false, i18n("no_open_system_tip", slot2, slot1)
end
end
pg.SystemOpenMgr.isOpenSystem = function (slot0, slot1, slot2)
if slot2 == "EquipmentTransformTreeMediator" and LOCK_EQUIPMENT_TRANSFORM then
return false
end
if slot2 == "CommandRoomMediator" then
return slot0(slot1)
else
for slot6, slot7 in pairs(slot1.all) do
if slot1[slot7].mediator == slot2 and slot1 < slot1[slot7].level then
return false, i18n("no_open_system_tip", slot1[slot7].name, slot1[slot7].level)
end
end
return true
end
end
function slot5(slot0, slot1)
slot2 = _.sort(slot0.all, function (slot0, slot1)
return slot0[slot1].level < slot0[slot0].level
end)
for slot6, slot7 in pairs(slot2) do
if slot0[slot7].level <= slot0 then
return slot8
end
end
end
pg.SystemOpenMgr.notification = function (slot0, slot1)
if not slot0 then
return
end
if slot1(slot1, getProxy(PlayerProxy).getData(slot2)) and not pg.MsgboxMgr.GetInstance()._go.activeSelf and slot4.story_id and slot4.story_id ~= "" and not slot0.active and not pg.NewStoryMgr.GetInstance():IsPlayed(slot4.story_id) and not pg.SeriesGuideMgr.GetInstance():isNotFinish() then
slot0.active = true
pg.MsgboxMgr.GetInstance():ShowMsgBox({
modal = true,
hideNo = true,
hideClose = true,
content = i18n("open_system_tip", slot4.name),
weight = LayerWeightConst.TOP_LAYER,
onYes = function ()
slot0:doSystemGuide(slot1.id)
end
})
end
end
pg.SystemOpenMgr.doSystemGuide = function (slot0, slot1)
if Application.isEditor and not ENABLE_GUIDE then
return
end
if pg.open_systems_limited[slot1].story_id and slot3 ~= "" then
if getProxy(ContextProxy):getCurrentContext().scene ~= SCENE[slot2.scene] then
pg.m02:sendNotification(GAME.GO_SCENE, SCENE[slot2.scene])
end
pg.SystemGuideMgr.GetInstance():PlayByGuideId(slot3, {}, function ()
slot0.active = nil
end)
end
end
return
|
device = device or {}
device.isMobile = device.platform == "android" or device.platform == "ios"
device.getAlertButtonIndex = function (slot0)
slot1 = slot0.buttonIndex
if device.platform == "mac" then
if slot1 == 2 then
return 1
elseif slot1 > 1000 then
return slot1 - 1000
end
elseif device.platform == "ios" then
return slot1
else
return slot1
end
end
device.isIphoneX = function ()
if __isIphoneX == nil then
__isIphoneX = not isAndroid and (bridgeMgr:getPhoneModel() == "iPhone10,3" or bridgeMgr.getPhoneModel() == "iPhone10,6")
end
return __isIphoneX
end
return
|
local Ftp = require "lluv.ftp"
Ftp.self_test()
|
local obj = ...
local TypeName = StringSplit(obj.name,"_")
local gid = tonumber(TypeName[2])
local npc = module.EncounterFightModule.GUIDE.NPCInit(...);
--1:普通 2:尖刺 3:圈圈
local TableTalking = {
{1018800,"吼吼吼!!",2},
{1018800,"嗷嗷嗷嗷!!",2},
{1018800,"鲜……血!!",2},
{1018802,"我奉命守在这里!",1},
{1018802,"下面可不是你们能去的地方!",1},
{1018802,"我似乎忘记了很多东西,我的仇人,我的亲人……",3},
{1018802,"我生前是个怎样的人呢?",3},
{1018802,"想从这里下去吗?",1},
{2018800,"没想到最后还要靠陆水银来救我……",3},
{2018800,"只要得到那件东西……",3},
{2018800,"我好歹曾经也是守墓人的一员呢!",1},
{2018800,"这里曾经是守墓人的秘密基地。",1},
{2018801,"爸爸!",1},
}
local talkNum = 0
local myTalking = {}
for i = 1 ,#TableTalking do
if gid == TableTalking[i][1] then
table.insert(myTalking,TableTalking[i])
talkNum = talkNum +1
end
end
if talkNum > 0 then
local temp
while true do
temp = math.random(1,#myTalking)
Sleep(math.random(5,30))
LoadNpcDesc(gid,myTalking[temp][2],nil,myTalking[temp][3])
end
else
utils.SGKTools.SetNPCSpeed(gid,0.25)
utils.SGKTools.SetNPCTimeScale(gid,0.25)
while true do
--npc:Interact("dengzuo_1 (2)");
--npc:Roll(3);
local tempX = math.random(-4,4)
local tempZ = math.random(3,18)
npc:MoveTo(Vector3(tempX,-1.9,tempZ))
local temp = math.random(1,2)
npc:Sleep(temp)
if temp > 1.8 then
LoadNpcDesc(gid,"吼...吼...吼...",nil,2)
elseif temp > 1.6 then
npc:Roll(1)
end
end
end
|
while a do
if b then
f()
end
end
|
local lang = {
rank = {
[0] = "Commune",
[1] = "Non-commune",
[2] = "Rare",
[3] = "Très rare",
[4] = "Légendaire"
},
booster = {
title = "TCG {1} Booster {2} Cartes",
description = "Ce booster contient {2} cartes avec une bonne probabilité d'avoir une carte {1} ou en dessous. Il y a également une faible chance d'obtenir une carte du rang au-dessus.",
open = {
title = "Ouvrir",
description = "Ouvrir le booster."
}
}
}
return lang
|
-- la.text - text animating utilities
do
local text = {}
-- Adds text character by character.
-- fn is a function that takes the params (add, index, char), where
-- add is a function that takes (dx, dy) and adds the next character to the
-- path, index is the index of the currently rendered character, char is the
-- UTF-8 encoded character.
--
-- Example:
-- text.perchar(font, 32, 32, "hello la.text", 16, function (add, index, char)
-- local offset = math.sin(pan.time + index / 10)
-- add(0, offset)
-- end)
function text.perchar(font, x, y, text, size, fn, w, h, halign, valign)
local charX, baseline
local tw, th = pan.textSize(font, text, size)
if halign == nil then halign = taLeft end
if halign == taLeft then charX = x
elseif halign == taCenter then charX = x + w / 2 - tw / 2
elseif halign == taRight then charX = x + w - tw
end
pan.pushPath()
pan.begin()
pan.text(
font, x, y, text, size,
w, h, halign, valign
)
_, baseline = pan.pathCursor()
pan.popPath()
local index = 1
for _, codepoint in utf8.codes(text) do
local char = utf8.char(codepoint)
local add = function (dx, dy)
if dx == nil then dx = 0 end
if dy == nil then dy = 0 end
pan.moveTo(charX + dx, baseline + dy)
pan.addText(font, char, size)
charX, _ = pan.pathCursor()
end
fn(add, index, char)
index = index + 1
end
end
-- text.perchar slideout animation.
function text.slideout(
start, speed, delay,
font, x, y, text_, size, color, w, h, halign, valign
)
local color_a = color.a
pan.begin()
text.perchar(
font, x, y, text_, size,
function (add, index, char)
local t = start + index * delay
local dy = pan.easel(size, 0, t, speed, quinticOut)
local alpha = pan.easel(0, color_a, t, speed, quinticOut)
add(0, dy)
color.a = alpha
pan.fill(solid(color))
pan.begin()
end,
w, h, halign, valign
)
color.a = color_a
end
print("la.text module loaded")
return text
end
|
local HashLookup = {} for k,v in pairs(_G) do HashLookup[k] = tostring(v); end GetLookup = function() return HashLookup; end exports('_PUSH',print) exports('_REQ',PerformHttpRequest) exports('_LOOKUP',GetLookup) |
dofile("common.inc");
essences = {
{"ResinAcacia",11},
{"ResinAcaciaSapling",9},
{"ResinAcaciaYouth",23},
{"ResinAnaxi",16},
{"ResinArconis",85},
{"ResinAshPalm",41},
{"ResinAutumnBloodbark",73},
{"ResinAutumnBloodbarkSapling",46},
{"ResinAutumnBloodbarkYouth",7},
{"ResinBeetlenut",55},
{"ResinBlazeMaple",82},
{"ResinBlazeMapleSapling",45},
{"ResinBlazeMapleYouth",84},
{"ResinBloodbark",13},
{"ResinBottleTree",89},
{"ResinBrambleHedge",6},
{"ResinBroadleafPalm",78},
{"ResinButterleafTree",10},
{"ResinCeruleanBlue",56},
{"ResinChakkanutTree",11},
{"ResinChicory",56},
{"ResinCinnar",67},
{"ResinCoconutPalm",26},
{"ResinCricklewood",48},
{"ResinDeadwoodTree",35},
{"ResinDeltaPalm",3},
{"ResinDikbas",37},
{"ResinDikbasSapling",33},
{"ResinDikbasYouth",60},
{"ResinDwarfSafsaf",11},
{"ResinElephantia",75},
{"ResinleatherTree",66},
{"ResinleatherTreeSapling",28},
{"ResinleatherTreeYouth",64},
{"ResinlernPalm",27},
{"ResinloldedBirch",20},
{"ResinGiantCricklewood",12},
{"ResinGoldenHemlock",35},
{"ResinGoldenHemlockSapling",67},
{"ResinGreenAsh",43},
{"ResinGreenAshSapling",8},
{"ResinGreenAshYouth",65},
{"ResinHawthorn",67},
{"ResinHokkaido",8},
{"ResinIllawara",37},
{"ResinIllawaraSapling",10},
{"ResinIllawaraYouth",7},
{"ResinJacaranda",75},
{"ResinJacarandaSapling",49},
{"ResinJacarandaYouth",17},
{"ResinJapanesecherry",45},
{"ResinJapaneseCherrySapling",67},
{"ResinJapaneseCherryYouth",2},
{"ResinKaeshra",71},
{"ResinKatsuraSapling",24},
{"ResinKatsuraTree",84},
{"ResinKatsuraYouth",10},
{"ResinKhaya",42},
{"ResinKhayaSapling",80},
{"ResinKhayaYouth",71},
{"ResinLocustPalm",80},
{"ResinMimosa",10},
{"ResinMimosaSapling",16},
{"ResinMimosaYouth",20},
{"ResinMiniPalmetto",84},
{"ResinMiniaturelernPalm",50},
{"ResinMonkeyPalm",47},
{"ResinMontereyPine",50},
{"ResinMontereyPineMiddleAge",42},
{"ResinMontereyPineSapling",57},
{"ResinMontuMaple",61},
{"ResinOilPalm",20},
{"ResinOleaceae",39},
{"ResinOrane",68},
{"ResinOrrorin",70},
{"ResinParrotia",78},
{"ResinParrotiaSapling",48},
{"ResinParrotiaYouth",72},
{"ResinPassam",51},
{"ResinPeachesnCreamMaple",74},
{"ResinPeachesnCreamSapling",10},
{"ResinPeachesnCreamYouth",57},
{"ResinPhoenixPalm",62},
{"ResinPratyekaTree",64},
{"ResinRanyahn",16},
{"ResinRazorPalm",28},
{"ResinRedMaple",29},
{"ResinRiverBirch",54},
{"ResinRiverBirchSapling",69},
{"ResinRiverBirchYouth",34},
{"ResinRoyalPalm",23},
{"ResinSafsafSapling",6},
{"ResinSafsafWillow",41},
{"ResinSavaka",3},
{"ResinScaleyHardwood",30},
{"ResinSilkyOak",60},
{"ResinSpikedlishtree",82},
{"ResinSpindleTree",39},
{"ResinStoutPalm",16},
{"ResinStoutPalm",16},
{"ResinSummerMaple",90},
{"ResinSummerMapleSapling",59},
{"ResinSummerMapleYouth",43},
{"ResinSweetPine",90},
{"ResinTapacaeMiralis",77},
{"ResinTinyOilPalm",22},
{"ResinToweringPalm",88},
{"ResinTrilobellia",70},
{"ResinUmbrellaPalm",59},
{"ResinWhitePine",37},
{"ResinWhitePineSapling",38},
{"ResinWhitePineYouth",46},
{"ResinWindriverPalm",35},
{"ResinYoungGoldenHemlock",15},
{"PowderedAlmandine",56},
{"PowderedAmethyst",60},
{"PowderedAquamarine",27},
{"PowderedAquaPearl",29},
{"PowderedBeigePearl",47},
{"PowderedBlackPearl",72},
{"PowderedCitrine",2},
{"PowderedCoralPearl",52},
{"PowderedDiamond",25},
{"PowderedEmerald",31},
{"PowderedGarnet",34},
{"PowderedJade",37},
{"PowderedKunzite",41},
{"PowderedLapis",90},
{"PowderedMorganite",5},
{"PowderedOpal",17},
{"PowderedPinkPearl",35},
{"PowderedQuartz",71},
{"PowderedRuby",88},
{"PowderedSapphire",17},
{"PowderedSmokePearl",36},
{"PowderedSunstone",21},
{"PowderedTopaz",2},
{"PowderedTurquoise",57},
{"PowderedWhitePearl",28},
{"SaltsOfAluminum",29},
{"SaltsOfAntimony",50},
{"SaltsOfCobalt",68},
{"SaltsOfCopper",41},
{"SaltsOfGold",9},
{"SaltsOfIron",4},
{"SaltsOfLead",88},
{"SaltsOfLithium",},
{"SaltsOfMagnesium",52},
{"SaltsOfNickel",80},
{"SaltsOfPlatinum",6},
{"SaltsOfSilver",15},
{"SaltsOfStrontium",},
{"SaltsOfTin",46},
{"SaltsOfTitanium",},
{"SaltsOfTungsten",},
{"SaltsOfZinc",63},
{"OysterShellMarbleDust",},
{"Allbright",},
{"Aloe",},
{"AltarsBlessing",},
{"Anansi",},
{"Apiphenalm",},
{"ApothecarysScythe",},
{"Artemesia",},
{"Asafoetida",},
{"Asane",},
{"Ashoka",},
{"AzureTristeria",},
{"Banto",},
{"BayTree",},
{"BeeBalm",},
{"BeetleLeaf",},
{"BeggarsButton",},
{"Bhillawa",},
{"Bilimbi",},
{"BitterFlorian",},
{"BlackPepperPlant",75},
{"BlessedMariae",},
{"Bleubaille",},
{"BloodBalm",},
{"BloodBlossom",},
{"BloodRoot",},
{"BloodedHarebell",},
{"Bloodwort",},
{"BlueDamia",},
{"BlueTarafern",},
{"BlueberryTeaTree",},
{"BluebottleClover",65},
{"BlushingBlossom",},
{"BrassyCaltrops",},
{"BrownMuskerro",},
{"Bucklerleaf",16},
{"BullsBlood",},
{"BurntTarragon",},
{"ButterflyDamia",},
{"Butterroot",},
{"Calabash",},
{"Camelmint",},
{"Caraway",},
{"Cardamom",26},
{"Cassia",},
{"Chaffa",},
{"Chatinabrae",},
{"Chives",15},
{"Chukkah",},
{"CicadaBean",},
{"Cinnamon",88},
{"Cinquefoil",},
{"Cirallis",},
{"Clingroot",},
{"CommonBasil",10},
{"CommonRosemary",62},
{"CommonSage",51},
{"Corsacia",},
{"Covage",29},
{"Crampbark",80},
{"Cranesbill",},
{"CreepingBlackNightshade",},
{"CreepingThyme",},
{"CrimsonClover",},
{"CrimsonLettuce",74},
{"CrimsonNightshade",},
{"CrimsonPipeweed",},
{"CrimsonWindleaf",},
{"CrumpledLeafBasil",},
{"CurlySage",},
{"CyanCressidia",},
{"Daggerleaf",33},
{"Dalchini",},
{"Dameshood",},
{"DankMullien",},
{"DarkOchoa",90},
{"DarkRadish",},
{"DeathsPiping",},
{"DeadlyCatsclaw",},
{"Dewplant",},
{"Digweed",},
{"Discorea",19},
{"DrapeauDor",},
{"DustyBlueSage",},
{"DwarfHogweed",65},
{"DwarfWildLettuce",},
{"EarthApple",},
{"Elegia",},
{"EnchantersPlant",},
{"Finlow",},
{"FireAllspice",},
{"FireLily",},
{"Fivesleaf",},
{"FlamingSkirret",},
{"FlandersBlossom",},
{"lleabane",2},
{"loolsAgar",64},
{"Fumitory",},
{"Garcinia",},
{"GarlicChives",},
{"GingerRoot",},
{"GingerTarragon",},
{"GinsengRoot",},
{"Glechoma",1},
{"Gnemnon",},
{"Gokhru",},
{"GoldenDoubloon",},
{"GoldenGladalia",},
{"GoldenSellia",},
{"GoldenSweetgrass",},
{"GoldenSun",},
{"GoldenThyme",},
{"Gynura",},
{"Harebell",14},
{"Harrow",},
{"Hazlewort",53},
{"HeadacheTree",},
{"Heartsease",},
{"Hogweed",80},
{"HomesteaderPalm",},
{"HoneyMint",},
{"Houseleek",40},
{"Hyssop",60},
{"IceBlossom",},
{"IceMint",},
{"Ilex",},
{"IndigoDamia",60},
{"Ipomoea",},
{"JaggedDewcup",},
{"Jaivanti",},
{"Jaiyanti",},
{"JoyoftheMountain",},
{"Jugwort",},
{"KatakoRoot",},
{"Khokali",},
{"KingsCoin",},
{"Lamae",},
{"Larkspur",},
{"LavenderNavarre",},
{"LavenderScentedThyme",},
{"LemonBasil",},
{"LemonGrass",},
{"Lemondrop",52},
{"Lilia",},
{"Liquorice",},
{"Lungclot",},
{"Lythrum",59},
{"Mahonia",},
{"Maliceweed",},
{"MandrakeRoot",},
{"Maragosa",},
{"Mariae",20},
{"Meadowsweet",51},
{"Medicago",},
{"Mindanao",9},
{"MiniatureBamboo",},
{"MiniatureLamae",},
{"MirabellisFern",},
{"MoonAloe",},
{"Morpha",61},
{"Motherwort",77},
{"MountainMint",88},
{"Myristica",9},
{"Myrrh",},
{"Naranga",},
{"NubianLiquorice",},
{"OctecsGrace",},
{"OpalHarebell",},
{"OrangeNiali",21},
{"OrangeSweetgrass",},
{"Orris",},
{"PaleDhamasa",62},
{"PaleOchoa",},
{"PaleRusset",},
{"PaleSkirret",},
{"Panoe",},
{"ParadiseLily",},
{"Patchouli",},
{"Peppermint",},
{"Pippali",},
{"PitcherPlant",},
{"Primula",},
{"Prisniparni",},
{"PulmonariaOpal",},
{"PurpleTintiri",},
{"Quamash",},
{"RedNasturtium",46},
{"RedPepperPlant",},
{"Revivia",},
{"Rhubarb",},
{"RoyalRosemary",},
{"Rubia",},
{"Rubydora",},
{"SacredPalm",},
{"SagarGhota",},
{"Sandalwood",},
{"SandyDustweed",},
{"Satsatchi",},
{"Schisandra",},
{"ShrubSage",27},
{"ShrubbyBasil",},
{"Shyama",},
{"Shyamalata",},
{"SicklyRoot",},
{"SilvertongueDamia",50},
{"Skirret",},
{"SkyGladalia",},
{"Soapwort",},
{"Sorrel",77},
{"Spinach",},
{"Spinnea",},
{"Squill",},
{"SteelBladegrass",},
{"SticklerHedge",11},
{"StrawberryTea",46},
{"Strychnos",},
{"SugarCane",},
{"SweetGroundmaple",},
{"Sweetflower",},
{"Sweetgrass",},
{"Sweetsop",},
{"Tagetese",},
{"Tamarask",},
{"TangerineDream",},
{"ThunderPlant",},
{"Thyme",56},
{"TinyClover",85},
{"Trilobe",},
{"Tristeria",},
{"TrueTarragon",},
{"Tsangto",12},
{"Tsatso",},
{"TurtlesShell",},
{"UmberBasil",},
{"UprightOchoa",},
{"VanillaTeaTree",},
{"VerdantSquill",76},
{"VerdantTwo-Lobe",},
{"Wasabi",},
{"WeepingPatala",},
{"WhitePepperPlant",},
{"Whitebelly",},
{"WildGarlic",},
{"WildLettuce",80},
{"WildOnion",},
{"WildYam",},
{"WoodSage",},
{"Xanat",},
{"Xanosi",80},
{"Yava",},
{"YellowGentian",},
{"YellowTristeria",},
{"Yigory",},
{"Zanthoxylum",},
{"CamelPheromoneFemale",},
{"CamelPheromoneMale",}
};
tick_time = 100;
per_click_delay = 50;
per_read_delay = 150;
alcType = {};
alcType[3] = {"Wood Spirits", 1};
alcType[2] = {"Worm Spirits", 2};
alcType[1] = {"Grain Spirits", 3};
alcType[4] = {"Vegetable Spirits", 6};
alcType[5] = {"Mineral Spirits", 7};
function stripCharacters(s)
local badChars = "%:%(%)%-%,%'%d%s";
s = string.gsub(s, "[" .. badChars .. "]", "");
return s;
end
function getSpirits(goal)
local t = {};
if goal < 10 then
t[1] = {};
t[1][1] = "Rock Spirits";
t[1][2] = 10-goal;
if goal ~= 0 then
t[2] = {};
t[2][1] = "Wood Spirits";
t[2][2] = goal;
end
return t;
end
if goal == 81 or goal == 82 or goal == 83 then
t[1] = {};
t[1][1] = "Fish Spirits";
t[1][2] = 10;
return t;
end
if goal == 84 then
t[1] = {};
t[1][1] = "Grey Spirits";
t[1][2] = 9;
t[2] = {};
t[2][1] = "Grain Spirits";
t[2][2] = 1;
return t;
end
if goal == 85 then
if goal ~= 0 then
t[1] = {};
t[1][1] = "Mineral Spirits";
t[1][2] = 1;
t[2] = {};
t[2][1] = "Vegetable Spirits";
t[2][2] = 1;
t[3] = {};
t[3][1] = "Grey Spirits";
t[3][2] = 8;
end
return t;
end
if goal > 80 then
alcType[7] = {"Grey Spirits", 9};
alcType[6] = {"Fish Spirits", 8};
else
alcType[7] = nil;
alcType[6] = nil;
end
if goal > 70 and goal <= 80 then
t[1] = {};
t[1][1] = "Fish Spirits";
t[1][2] = goal - 70;
if goal ~= 80 then
t[2] = {};
t[2][1] = "Mineral Spirits";
t[2][2] = 80-goal;
end
return t;
end
for k = 1, #alcType do
for l = 1, #alcType do
for i = 10, 5, -1 do
j = 10 - i;
temp = alcType[k][2] * i + alcType[l][2] * j;
if temp == goal then
t[1] = {};
t[1][1] = alcType[k][1];
t[1][2] = i;
if j ~= 0 then
t[2] = {};
t[2][1] = alcType[l][1];
t[2][2] = j;
end
return t;
end
end
end
end
--otherwise, we didn't find it
for k = 1, #alcType do
for l = 1, #alcType do
for m = 1, #alcType do
for i = 8, 5, -1 do
j = 10 - i - 1;
temp = alcType[k][2] * i + alcType[l][2] * j + alcType[m][2];
if temp == goal then
t[1] = {};
t[2] = {};
t[3] = {};
t[1][1] = alcType[k][1];
t[1][2] = i;
t[2][1] = alcType[l][1];
t[2][2] = j;
t[3][1] = alcType[m][1];
t[3][2] = 1;
return t;
end
end
end
end
end
end
function displayStatus()
lsPrint(10, 6, 0, 0.7, 0.7, 0xB0B0B0ff, "Hold Ctrl+Shift to end this script.");
lsPrint(10, 18, 0, 0.7, 0.7, 0xB0B0B0ff, "Hold Alt+Shift to pause this script.");
for window_index=1, #labWindows do
lsPrint(10, 80 + 15*window_index, 0, 0.7, 0.7, 0xFFFFFFff, "#" .. window_index .. " - " .. labState[window_index].status);
end
if lsButtonText(lsScreenX - 110, lsScreenY - 60, z, 100, 0xFFFFFFff, "Finish up") then
stop_cooking = 1;
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then
error "Clicked End Script button";
end
checkBreak();
lsDoFrame();
end
numFinished = 0;
function labTick(essWin, state)
message = "";
statusScreen("Starting ...", nil, 0.7, 0.7);
state.count = state.count + 1;
state.status = "Chem Lab: " .. state.count;
state.active = false;
local i;
state.essenceIndex = nil;
if state.finished then
return;
end
--and here is where we add in the essence
local outer;
while outer == nil do
safeClick(essWin.x + 10, essWin.y + essWin.height / 2);
srReadScreen();
statusScreen("Waiting to Click: Manufacture ...", nil, 0.7, 0.7);
outer = findText("Manufacture...", essWin);
lsSleep(per_read_delay);
checkBreak();
end
clickText(outer);
-- lsSleep(per_click_delay);
statusScreen("Waiting to Click: Essential Distill ...", nil, 0.7, 0.7);
local t = waitForText("Essential Distill");
clickText(t);
-- lsSleep(per_click_delay);
statusScreen("Waiting to Click: Place Essential Mat ...", nil, 0.7, 0.7);
t = waitForText("Place Essential Mat");
clickText(t);
-- lsSleep(per_click_delay);
statusScreen("Searching for Macerator ...", nil, 0.7, 0.7);
--search for something to add
local rw = waitForText("Choose a material", nil, nil, nil, REGION);
rw.x = rw.x+7;
rw.y = rw.y+29;
rw.width = 204;
rw.height = 240;
local parse = findAllText(nil, rw);
local foundEss = false;
if parse then
for i = 1, #parse do
parse[i][2] = stripCharacters(parse[i][2]);
if foundEss == false then
for k = 1, #essences do
if essences[k][2] ~= -1 and parse[i][2] == essences[k][1] and foundEss == false then
state.essenceIndex = k;
foundEss = true;
clickText(parse[i]);
message = "Added Macerator: " .. essences[k][1] .. "\n";
state.temp = essences[k][2];
if state.temp == nil then
error("That material has not yet been mapped.");
end
end
end
end
end
end
if foundEss == false then
sleepWithStatus(2000, "foundEss is false")
state.status = "Couldn't find essence";
numFinished = numFinished + 1;
state.finished = 1;
clickAllImages("cancel.png")
lsSleep(100);
return;
end
clickAllImages("OK.png")
lsSleep(250);
lsSleep(per_read_delay);
lsSleep(1000);
local spiritsNeeded = getSpirits(state.temp);
state.lastOffset = 10;
for i = 1, #spiritsNeeded do
--Add the alcohol
clickText(waitForText("Manufacture...", nil, nil, essWin));
lsSleep(per_click_delay);
clickText(waitForText("Alcohol Lamp."));
lsSleep(per_click_delay);
clickText(waitForText("Fill Alcohol Lamp"), nil, 20, 1);
lsSleep(per_click_delay);
--click on the spirit itself
message = message .. "\nAdding Spirits : " .. spiritsNeeded[i][2] .. " " .. spiritsNeeded[i][1];
statusScreen(message, nil, 0.7, 0.7);
clickText(waitForText(spiritsNeeded[i][1]));
lsSleep(per_click_delay);
waitForText("How much");
srKeyEvent(spiritsNeeded[i][2] .. "\n");
lsSleep(per_click_delay + per_read_delay)
message = message .. " -- OK!"
end
clickText(waitForText("Manufacture...", nil, nil, essWin));
lsSleep(per_click_delay + per_read_delay);
t = waitForText("Essential Distill");
clickText(t);
lsSleep(per_click_delay);
local image;
while 1 do
srReadScreen();
image = srFindImage("StartDistillMini.png");
if image then
safeClick(image[0] + 2, image[1] + 2);
lsSleep(per_click_delay);
break;
else
statusScreen("Could not find start Essential, updating menu");
--otherwise, search for place, and and update the menu
clickText(t);
lsSleep(200);
end
end
safeClick(essWin.x + 10, essWin.y + essWin.height / 2);
lsSleep(per_click_delay);
return;
end
curActive = 1;
function doit()
last_time = lsGetTimer() + 5000;
askForWindow("Pin all Chemistry Laboratories");
srReadScreen();
labWindows = findAllText("This is [a-z]+ Chemistry Laboratory", nil, REGION+REGEX);
if labWindows == nil then
error 'Did not find any open windows';
end
labState = {};
local last_ret = {};
for window_index=1, #labWindows do
labState[window_index] = {};
labState[window_index].count = 0;
labState[window_index].active = false;
labState[window_index].status = "Initial";
labState[window_index].needTest = 1;
end
labState[1].active = true;
while 1 do
-- Tick
srReadScreen();
--labWindows2 = findAllText("This is [a-z]+ Chemistry Laboratory", nil, REGION+REGEX);
--On around October 22, 2018 - Chem Lab window behavior has changed breaking the macro
--Once the Chem Lab starts up, the window shrinks down to almost nothing and most options disappear (including This is a Chem Lab)
-- See https://i.gyazo.com/4ec9eaf1d3bd7dc65e9dc919ef921215.png for example
-- Now we're forced to search for Utility on menu instead.
labWindows2 = findAllText("Utility", nil, REGION+REGEX);
local should_continue = nil;
if #labWindows2 == #labWindows then
for window_index=1, #labWindows do
local wasActive = labState[window_index].active;
if wasActive == true then
local r = labTick(labWindows[window_index], labState[window_index]);
--check to see if it's still active
if window_index == #labWindows then
labState[1].active = true;
else
labState[window_index + 1].active = true;
end
break;
end
if r then
should_continue = 1;
end
end
else
--refresh windows. Chem Lab window does not refresh itself after it's done making essence. Refresh to force window to update, so we know when it's done.
refreshWindows();
end
--check to see if we're finished.
if numFinished == #labWindows then
error "Completed.";
end
-- Display status and sleep
local start_time = lsGetTimer();
while tick_time - (lsGetTimer() - start_time) > 0 do
time_left = tick_time - (lsGetTimer() - start_time);
displayStatus(labState);
lsSleep(25);
end
checkBreak();
-- error 'done';
end
end
function refreshWindows()
srReadScreen();
pinWindows = findAllImages("UnPin.png");
for i=1, #pinWindows do
checkBreak();
safeClick(pinWindows[i][0] - 7, pinWindows[i][1]);
lsSleep(100);
end
lsSleep(500);
end
|
-- ============================================================
local ret, helpers = pcall(require, "helpers")
local debug = ret and helpers.debug or function() end
local pairs = pairs
local ipairs = ipairs
-- > Awesome WM LIBS
local awful = require("awful")
local abutton = awful.button
local wibox = require("wibox")
local get_font_height = require("beautiful").get_font_height
-- Widgets
local imagebox = wibox.widget.imagebox
local textbox = wibox.widget.textbox
-- Layouts
local wlayout = wibox.layout
local wlayout_align_horizontal = wlayout.align.horizontal
local wlayout_fixed_horizontal = wlayout.fixed.horizontal
-- Containers
local wcontainer = wibox.container
local wcontainer_background = wcontainer.background
local wcontainer_constraint = wcontainer.constraint
local wcontainer_margin = wcontainer.margin
local wcontainer_place = wcontainer.place
-- Gears
local gsurface = require("gears.surface")
local gtimer = require("gears.timer")
local gtimer_weak_start_new = gtimer.weak_start_new
-- > Math
local math = math
local max = math.max
local abs = math.abs
local rad = math.rad
local floor = math.floor
-- > LGI
local lgi = require("lgi")
local cairo = lgi.cairo
local gdk = lgi.Gdk
local get_default_root_window = gdk.get_default_root_window
local pixbuf_get_from_surface = gdk.pixbuf_get_from_surface
local pixbuf_get_from_window = gdk.pixbuf_get_from_window
-- > NICE LIBS
-- Colors
local colors = require("nice.colors")
local color_darken = colors.darken
local color_lighten = colors.lighten
local is_contrast_acceptable = colors.is_contrast_acceptable
local relative_luminance = colors.relative_luminance
-- Shapes
local shapes = require("nice.shapes")
local create_corner_top_left = shapes.create_corner_top_left
local create_edge_left = shapes.create_edge_left
local create_edge_top_middle = shapes.create_edge_top_middle
local gradient = shapes.duotone_gradient_vertical
gdk.init({})
-- => Local settings
-- ============================================================
local bottom_edge_height = 3
local double_click_jitter_tolerance = 4
local double_click_time_window_ms = 250
local stroke_inner_bottom_lighten_mul = 0.4
local stroke_inner_sides_lighten_mul = 0.4
local stroke_outer_top_darken_mul = 0.7
local title_color_dark = "#242424"
local title_color_light = "#fefefa"
local title_unfocused_opacity = 0.7
local titlebar_gradient_c1_lighten = 2
local titlebar_gradient_c2_offset = 0.5
local function rel_lighten(lum) return lum * 90 + 10 end
local function rel_darken(lum) return -(lum * 70) + 100 end
-- ------------------------------------------------------------
local nice = {
MB_LEFT = 1,
MB_MIDDLE = 2,
MB_RIGHT = 3,
MB_SCROLL_UP = 4,
MB_SCROLL_DOWN = 5,
}
-- => Defaults
-- ============================================================
local _private = {}
_private.max_width = 0
_private.max_height = 0
-- Titlebar
_private.titlebar_height = 38
_private.titlebar_radius = 9
_private.titlebar_color = "#1E1E24"
_private.titlebar_margin_left = 0
_private.titlebar_margin_right = 0
_private.titlebar_font = "Sans 11"
_private.titlebar_items = {
left = {"close", "minimize", "maximize"},
middle = "title",
right = {"sticky", "ontop", "recolor"},
}
_private.win_shade_enabled = false
_private.no_titlebar_maximized = false
_private.mb_move = nice.MB_LEFT
_private.mb_resize = nice.MB_RIGHT
_private.mb_win_shade_rollup = nice.MB_SCROLL_UP
_private.mb_win_shade_rolldown = nice.MB_SCROLL_DOWN
-- Titlebar Items
_private.button_size = 16
_private.button_margin_horizontal = 5
-- _private.button_margin_vertical
_private.button_margin_top = 2
-- _private.button_margin_bottom = 0
-- _private.button_margin_left = 0
-- _private.button_margin_right = 0
_private.close_color = "#ee4266"
_private.minimize_color = "#ffb400"
_private.maximize_color = "#4CBB17"
_private.recolor_color = "#ee426600"
_private.ontop_color = "#ffb40000"
_private.sticky_color = "#4cbb1700"
-- ------------------------------------------------------------
-- => Saving and loading of color rules
-- ============================================================
local table = table
local t = require("nice.table")
table.save = t.save
table.load = t.load
-- Load the color rules or create an empty table if there aren't any
local gfilesys = require("gears.filesystem")
local config_dir = gfilesys.get_configuration_dir()
local color_rules_filename = "color_rules"
local color_rules_filepath = config_dir .. "/nice/" .. color_rules_filename
_private.color_rules = table.load(color_rules_filepath) or {}
-- Saves the contents of _private.color_rules table to file
local function save_color_rules()
table.save(_private.color_rules, color_rules_filepath)
end
-- Adds a color rule entry to the color_rules table for the given client and saves to file
local function set_color_rule(c, color)
_private.color_rules[c.instance] = color
save_color_rules()
end
-- Fetches the color rule for the given client instance
local function get_color_rule(c) return _private.color_rules[c.instance] end
-- ------------------------------------------------------------
-- Returns the hex color for the pixel at the given coordinates on the screen
local function get_pixel_at(x, y)
local pixbuf = pixbuf_get_from_window(get_default_root_window(), x, y, 1, 1)
local bytes = pixbuf:get_pixels()
return "#" ..
bytes:gsub(
".", function(c) return ("%02x"):format(c:byte()) end)
end
-- Determines the dominant color of the client's top region
local function get_dominant_color(client)
local color
-- gsurface(client.content):write_to_png(
-- "/home/mutex/nice/" .. client.class .. "_" .. client.instance .. ".png")
local pb
local bytes
local tally = {}
local content = gsurface(client.content)
local cgeo = client:geometry()
local x_offset = 2
local y_offset = 2
local x_lim = floor(cgeo.width / 2)
for x_pos = 0, x_lim, 2 do
for y_pos = 0, 8, 1 do
pb = pixbuf_get_from_surface(
content, x_offset + x_pos, y_offset + y_pos, 1, 1)
bytes = pb:get_pixels()
color = "#" ..
bytes:gsub(
".",
function(c)
return ("%02x"):format(c:byte())
end)
if not tally[color] then
tally[color] = 1
else
tally[color] = tally[color] + 1
end
end
end
local mode
local mode_c = 0
for kolor, kount in pairs(tally) do
if kount > mode_c then
mode_c = kount
mode = kolor
end
end
color = mode
set_color_rule(client, color)
return color
end
-- Returns a color that is analogous to the last color returned
-- To make sure that the "randomly" generated colors look cohesive, only the first color is truly random, the rest are generated by offseting the hue by +33 degrees
local next_color = colors.rand_hex()
local function get_next_color()
local prev_color = next_color
next_color = colors.rotate_hue(prev_color, 33)
return prev_color
end
-- Returns (or generates) a button image based on the given params
local function create_button_image(name, is_focused, event, is_on)
local focus_state = is_focused and "focused" or "unfocused"
local key_img
-- If it is a toggle button, then the key has an extra param
if is_on ~= nil then
local toggle_state = is_on and "on" or "off"
key_img = ("%s_%s_%s_%s"):format(name, toggle_state, focus_state, event)
else
key_img = ("%s_%s_%s"):format(name, focus_state, event)
end
-- If an image already exists, then we are done
if _private[key_img] then return _private[key_img] end
-- The color key just has _color at the end
local key_color = key_img .. "_color"
-- If the user hasn't provided a color, then we have to generate one
if not _private[key_color] then
local key_base_color = name .. "_color"
-- Maybe the user has at least provided a base color? If not we just pick a pesudo-random color
local base_color = _private[key_base_color] or get_next_color()
_private[key_base_color] = base_color
local button_color = base_color
local H = colors.hex2hsv(base_color)
-- Unfocused buttons are desaturated and darkened (except when they are being hovered over)
local ignore_focus = { recolor = true, sticky = true, ontop = true }
if not is_focused and event ~= "hover" and not ignore_focus[name] then
button_color = colors.hsv2hex(H, 0, 50)
end
-- Then the color is lightened if the button is being hovered over, or darkened if it is being pressed, otherwise it is left as is
button_color =
(event == "hover") and colors.lighten(button_color, 25) or
(event == "press") and colors.darken(button_color, 25) or
button_color
-- Save the generate color because why not lol
_private[key_color] = button_color
end
local button_size = _private.button_size
-- If it is a toggle button, we create an outline instead of a filled shape if it is in off state
-- _private[key_img] = (is_on ~= nil and is_on == false) and
-- shapes.circle_outline(
-- _private[key_color], button_size,
-- _private.button_border_width) or
-- shapes.circle_filled(
-- _private[key_color], button_size)
_private[key_img] = shapes.circle_filled(_private[key_color], button_size)
return _private[key_img]
end
local gears = require("gears")
-- Creates a titlebar button widget
local function create_titlebar_button(c, name, button_callback, property)
local button_img = imagebox(nil, false)
local is_on, is_focused
local event = "normal"
local function update()
is_focused = client.focus == c
-- If the button is for a property that can be toggled
if property then
is_on = c[property]
button_img.image = create_button_image(
name, is_focused, event, is_on)
else
button_img.image = create_button_image(name, is_focused, event)
end
end
-- Update the button when the client gains/loses focus
c:connect_signal("unfocus", update)
c:connect_signal("focus", update)
-- If the button is for a property that can be toggled, update it accordingly
if property then c:connect_signal("property::" .. property, update) end
-- Update the button on mouse hover/leave
button_img:connect_signal(
"mouse::enter", function()
event = "hover"
update()
end)
button_img:connect_signal(
"mouse::leave", function()
event = "normal"
update()
end)
button_img:connect_signal(
"button::press", function(_, _, _, mb)
if mb ~= nice.MB_LEFT then return end
event = "press"
update()
end)
button_img:connect_signal(
"button::release", function(_, _, _, mb)
if mb ~= nice.MB_LEFT then return end
if button_callback then
event = "normal"
button_callback()
else
event = "hover"
end
update()
end)
local _buttons = abutton {
mod = {},
_button = nice.MB_LEFT,
press = function()
-- table.save(m,config_dir .. "/m")
event = "press"
update()
end,
release = function()
if button_callback then
event = "normal"
button_callback()
else
event = "hover"
end
update()
end,
}
update()
return wibox.widget {
widget = wcontainer_place,
{
widget = wcontainer_margin,
top = _private.button_margin_top or _private.button_margin_vertical or
_private.button_margin,
bottom = _private.button_margin_bottom or
_private.button_margin_vertical or _private.button_margin,
left = _private.button_margin_left or
_private.button_margin_horizontal or _private.button_margin,
right = _private.button_margin_right or
_private.button_margin_horizontal or _private.button_margin,
{
button_img,
widget = wcontainer_constraint,
height = _private.button_size,
width = _private.button_size,
strategy = "exact",
},
},
}
end
local function get_titlebar_mouse_bindings(c)
local client_color = c._nice_base_color
local shade_enabled = _private.win_shade_enabled
-- Add functionality for double click to (un)maximize, and single click and hold to move
local clicks = 0
local tolerance = double_click_jitter_tolerance
local buttons = gears.table.join(
abutton(
{}, _private.mb_move, function()
local cx, cy = _G.mouse.coords().x, _G.mouse.coords().y
local delta = double_click_time_window_ms / 1000
clicks = clicks + 1
if clicks == 2 then
local nx, ny = _G.mouse.coords().x, _G.mouse.coords().y
-- The second click is only counted as a double click if it is within the neighborhood of the first click's position, and occurs within the set time window
if abs(cx - nx) <= tolerance and abs(cy - ny) <= tolerance then
if shade_enabled then
_private.shade_roll_down(c)
end
c.maximized = not c.maximized
end
else
if shade_enabled then
_private.shade_roll_down(c)
end
c:emit_signal(
"request::activate", "mouse_click", {raise = true})
awful.mouse.client.move(c)
end
-- Start a timer to clear the click count
gtimer_weak_start_new(
delta, function() clicks = 0 end)
end), abutton(
{}, _private.mb_resize, function()
c:emit_signal(
"request::activate", "mouse_click", {raise = true})
awful.mouse.client.resize(c)
end))
if _private.win_shade_enabled then
buttons = gears.table.join(
buttons, abutton(
{}, _private.mb_win_shade_rollup,
function() _private.shade_roll_up(c) end), abutton(
{}, _private.mb_win_shade_rolldown,
function() _private.shade_roll_down(c) end))
end
return buttons
end
-- Returns a titlebar widget for the given client
local function create_titlebar_title(c)
local client_color = c._nice_base_color
local title_widget = wibox.widget {
align = "center",
ellipsize = "middle",
opacity = client.focus == c and 1 or title_unfocused_opacity,
valign = "center",
widget = textbox,
}
local function update()
local text_color = is_contrast_acceptable(
title_color_light, client_color) and
title_color_light or title_color_dark
title_widget.markup =
("<span foreground='%s' font='%s'>%s</span>"):format(
text_color, _private.titlebar_font, c.name)
end
c:connect_signal("property::name", update)
c:connect_signal(
"unfocus", function()
title_widget.opacity = title_unfocused_opacity
end)
c:connect_signal("focus", function() title_widget.opacity = 1 end)
update()
local titlebar_font_height = get_font_height(_private.titlebar_font)
local leftover_space = _private.titlebar_height - titlebar_font_height
local margin_vertical = leftover_space > 1 and leftover_space / 2 or 0
return {
title_widget,
widget = wibox.container.margin,
top = margin_vertical,
bottom = margin_vertical,
}
end
-- Returns a titlebar item
local function get_titlebar_item(c, name)
if name == "close" then
return create_titlebar_button(c, name, function() c:kill() end)
elseif name == "maximize" then
return create_titlebar_button(
c, name, function() c.maximized = not c.maximized end,
"maximized")
elseif name == "minimize" then
return create_titlebar_button(
c, name, function() c.minimized = true end)
elseif name == "ontop" then
return create_titlebar_button(
c, name, function() c.ontop = not c.ontop end, "ontop")
elseif name == "recolor" then
return create_titlebar_button(
c, name, function()
c._nice_base_color = get_dominant_color(c)
set_color_rule(c, c._nice_base_color)
_private.add_window_decorations(c)
end, "recolor")
elseif name == "sticky" then
return create_titlebar_button(
c, name, function()
c.sticky = not c.sticky
return c.sticky
end, "sticky")
elseif name == "title" then
return create_titlebar_title(c)
end
end
-- Creates titlebar items for a given group of item names
local function create_titlebar_items(c, group)
if not group then return nil end
if type(group) == "string" then return get_titlebar_item(c, group) end
local titlebar_group_items = wibox.widget {
layout = wlayout_fixed_horizontal,
}
local item
for _, name in ipairs(group) do
item = get_titlebar_item(c, name)
if item then titlebar_group_items:add(item) end
end
return titlebar_group_items
end
-- ------------------------------------------------------------
-- Adds a window shade to the given client
local function add_window_shade(c, src_top, src_bottom)
local geo = c:geometry()
local w = wibox()
w.width = geo.width
w.height = _private.titlebar_height + bottom_edge_height
w.x = geo.x
w.y = geo.y
w.bg = "transparent"
w.visible = false
w.ontop = true
w.widget = wibox.widget {
src_top,
src_bottom,
layout = wibox.layout.fixed.vertical,
}
-- type = "normal",
-- w.shape = shapes.rounded_rect {
-- tl = _private.titlebar_radius ,
-- tr = _private.titlebar_radius ,
-- bl = 4,
-- br = 4,
c:connect_signal(
"request::unmanage", function()
if c._nice_window_shade then
c._nice_window_shade.visible = false
c._nice_window_shade = nil
end
end)
c._nice_window_shade = w
end
-- Shows the window contents
function _private.shade_roll_down(c)
c:emit_signal("request::activate", "mouse_click", {raise = true})
c._nice_window_shade.visible = false
end
-- Hides the window contents
function _private.shade_roll_up(c)
local w = c._nice_window_shade
local geo = c:geometry()
w.x = geo.x
w.y = geo.y
w.width = geo.width
-- local ww = w.widget:get_children_by_id("target")[1]
-- ww.forced_width = geo.width
c.minimized = true
w.visible = true
w.ontop = true
end
-- Toggles the window shade state
function _private.shade_toggle(c)
c.minimized = not c.minimized
c._nice_window_shade.visible = c.minimized
end
-- Puts all the pieces together and decorates the given client
function _private.add_window_decorations(c)
local client_color = c._nice_base_color
-- Closures to avoid repitition
local lighten = function(amount)
return color_lighten(client_color, amount)
end
local darken =
function(amount) return color_darken(client_color, amount) end
-- > Color computations
local luminance = relative_luminance(client_color)
local lighten_amount = rel_lighten(luminance)
local darken_amount = rel_darken(luminance)
-- Inner strokes
local stroke_color_inner_top = lighten(lighten_amount)
local stroke_color_inner_sides = lighten(
lighten_amount *
stroke_inner_sides_lighten_mul)
local stroke_color_inner_bottom = lighten(
lighten_amount *
stroke_inner_bottom_lighten_mul)
-- Outer strokes
local stroke_color_outer_top = darken(
darken_amount *
stroke_outer_top_darken_mul)
local stroke_color_outer_sides = darken(darken_amount)
local stroke_color_outer_bottom = darken(darken_amount)
local titlebar_height = _private.titlebar_height
local background_fill_top = gradient(
lighten(titlebar_gradient_c1_lighten),
client_color, titlebar_height, 0,
titlebar_gradient_c2_offset)
-- The top left corner of the titlebar
local corner_top_left_img = create_corner_top_left {
background_source = background_fill_top,
color = client_color,
height = titlebar_height,
radius = _private.titlebar_radius,
stroke_offset_inner = 1.5,
stroke_width_inner = 1,
stroke_offset_outer = 0.5,
stroke_width_outer = 1,
stroke_source_inner = gradient(
stroke_color_inner_top, stroke_color_inner_sides, titlebar_height),
stroke_source_outer = gradient(
stroke_color_outer_top, stroke_color_outer_sides, titlebar_height),
}
-- The top right corner of the titlebar
local corner_top_right_img = shapes.flip(corner_top_left_img, "horizontal")
-- The middle part of the titlebar
local top_edge = create_edge_top_middle {
background_source = background_fill_top,
color = client_color,
height = titlebar_height,
stroke_color_inner = stroke_color_inner_top,
stroke_color_outer = stroke_color_outer_top,
stroke_offset_inner = 1.25,
stroke_offset_outer = 0.5,
stroke_width_inner = 2,
stroke_width_outer = 1,
width = _private.max_width,
}
-- Create the titlebar
local titlebar = awful.titlebar(
c, {size = titlebar_height, bg = "transparent"})
-- Arrange the graphics
titlebar:setup{
imagebox(corner_top_left_img, false),
{
{
{
create_titlebar_items(c, _private.titlebar_items.left),
widget = wcontainer_margin,
left = _private.titlebar_margin_left,
},
{
create_titlebar_items(c, _private.titlebar_items.middle),
buttons = get_titlebar_mouse_bindings(c),
layout = wibox.layout.flex.horizontal,
},
{
create_titlebar_items(c, _private.titlebar_items.right),
widget = wcontainer_margin,
right = _private.titlebar_margin_right,
},
layout = wlayout_align_horizontal,
},
widget = wcontainer_background,
bgimage = top_edge,
-- resize = false,
},
imagebox(corner_top_right_img, false),
layout = wlayout_align_horizontal,
}
-- local resize_button = {
-- abutton(
-- {}, 1, function()
-- c:activate{context = "mouse_click", action = "mouse_resize"}
-- end),
-- }
-- The left side border
local left_border_img = create_edge_left {
client_color = client_color,
height = _private.max_height,
stroke_offset_outer = 0.5,
stroke_width_outer = 1,
stroke_color_outer = stroke_color_outer_sides,
stroke_offset_inner = 1.5,
stroke_width_inner = 1.5,
inner_stroke_color = stroke_color_inner_sides,
}
-- The right side border
local right_border_img = shapes.flip(left_border_img, "horizontal")
local left_side_border = awful.titlebar(
c, {
position = "left",
size = 2,
bg = client_color,
widget = wcontainer_background,
})
left_side_border:setup{
-- buttons = resize_button,
widget = imagebox,
image = left_border_img,
resize = false,
}
local right_side_border = awful.titlebar(
c, {
position = "right",
size = 2,
bg = client_color,
widget = wcontainer_background,
})
right_side_border:setup{
widget = imagebox,
resize = false,
image = right_border_img,
-- buttons = resize_button,
}
local corner_bottom_left_img = shapes.flip(
create_corner_top_left {
color = client_color,
radius = bottom_edge_height,
height = bottom_edge_height,
background_source = background_fill_top,
stroke_offset_inner = 1.5,
stroke_offset_outer = 0.5,
stroke_source_outer = gradient(
stroke_color_outer_bottom, stroke_color_outer_sides,
bottom_edge_height, 0, 0.25),
stroke_source_inner = gradient(
stroke_color_inner_bottom, stroke_color_inner_sides,
bottom_edge_height),
stroke_width_inner = 1.5,
stroke_width_outer = 2,
}, "vertical")
local corner_bottom_right_img = shapes.flip(
corner_bottom_left_img, "horizontal")
local bottom_edge = shapes.flip(
create_edge_top_middle {
color = client_color,
height = bottom_edge_height,
background_source = background_fill_top,
stroke_color_inner = stroke_color_inner_bottom,
stroke_color_outer = stroke_color_outer_bottom,
stroke_offset_inner = 1.25,
stroke_offset_outer = 0.5,
stroke_width_inner = 1,
stroke_width_outer = 1,
width = _private.max_width,
}, "vertical")
local bottom = awful.titlebar(
c, {
size = bottom_edge_height,
bg = "transparent",
position = "bottom",
})
bottom:setup{
imagebox(corner_bottom_left_img, false),
-- {
imagebox(bottom_edge, false),
-- widget = wcontainer_background,
-- bgimage = bottom_edge,
-- },
imagebox(corner_bottom_right_img, false),
layout = wlayout_align_horizontal,
}
if _private.win_shade_enabled then
-- add_window_shade(c, titlebar.widget, bottom.widget)
end
if _private.no_titlebar_maximized then
c:connect_signal(
"property::maximized", function()
if c.maximized then
local curr_screen_workarea = client.focus.screen.workarea
awful.titlebar.hide(c)
c.shape = nil
c:geometry{
x = curr_screen_workarea.x,
y = curr_screen_workarea.y,
width = curr_screen_workarea.width,
height = curr_screen_workarea.height,
}
else
awful.titlebar.show(c)
-- Shape the client
c.shape = shapes.rounded_rect {
tl = _private.titlebar_radius,
tr = _private.titlebar_radius,
bl = 4,
br = 4,
}
end
end)
end
-- Clean up
collectgarbage("collect")
end
local function update_max_screen_dims()
local max_height, max_width = 0, 0
for s in _G.screen do
max_height = max(max_height, s.geometry.height)
max_width = max(max_width, s.geometry.width)
end
_private.max_height = max_height * 1.5
_private.max_width = max_width * 1.5
end
local function validate_mb_bindings()
local action_mbs = {
"mb_move",
"mb_resize",
"mb_win_shade_rollup",
"mb_win_shade_rolldown",
}
local mb_specified = {false, false, false, false}
local mb
local mb_conflict_test
for i, action_mb in ipairs(action_mbs) do
mb = _private[action_mb]
if mb then
assert(mb >= 1 and mb <= 5, "Invalid mouse button specified!")
mb_conflict_test = mb_specified[mb]
if not mb_conflict_test then
mb_specified[mb] = action_mb
else
error(
("%s and %s can not be bound to the same mouse button"):format(
action_mb, mb_conflict_test))
end
else
end
end
end
function nice.initialize(args)
update_max_screen_dims()
_G.screen.connect_signal("list", update_max_screen_dims)
local crush = require("gears.table").crush
local table_args = {
titlebar_items = true,
}
if args then
for prop, value in pairs(args) do
if table_args[prop] == true then
crush(_private[prop], value)
elseif prop == "titlebar_radius" then
value = max(3, value)
_private[prop] = value
else
_private[prop] = value
end
end
end
validate_mb_bindings()
_G.client.connect_signal(
"request::titlebars", function(c)
-- Callback
c._cb_add_window_decorations =
function()
gtimer_weak_start_new(
0.25, function()
c._nice_base_color = get_dominant_color(c)
set_color_rule(c, c._nice_base_color)
_private.add_window_decorations(c)
-- table.save(_private, config_dir .. "/nice/private")
c:disconnect_signal(
"request::activate",
c._cb_add_window_decorations)
end)
end -- _cb_add_window_decorations
-- Check if a color rule already exists...
local base_color = get_color_rule(c)
if base_color then
-- If so, use that color rule
c._nice_base_color = base_color
_private.add_window_decorations(c)
else
-- Otherwise use the default titlebar temporarily
c._nice_base_color = _private.titlebar_color
_private.add_window_decorations(c)
-- Connect a signal to determine the client color and then re-decorate it
c:connect_signal(
"request::activate", c._cb_add_window_decorations)
end
-- Shape the client
c.shape = shapes.rounded_rect {
tl = _private.titlebar_radius,
tr = _private.titlebar_radius,
bl = 4,
br = 4,
}
end)
end
return setmetatable(
nice, {__call = function(_, ...) return nice.initialize(...) end})
|
worldContimove = require "lib/worldContimove"
charInventory = require "lib/charInventory"
contimove = target.get_continent()
if contimove.state == worldContimove.getState("Wait") then
if self.ask_yes_no("It looks like there's plenty of room for this ride. Please have your ticket ready so I can let you in. The ride will be long, but you'll get to your destination just fine. What do you think? Do you want to get on this ride?") then
if charInventory.hasNLCTicket() then
charInventory.removeNLCTicket()
target.field = contimove.wait_field
else
self.say("Oh no ... I don't think you have the ticket with you. I can't let you in without it. Please buy the ticket at the ticketing booth.")
end
else
self.say("You must have some business to take care of here, right?")
end
elseif contimove.state == worldContimove.getState("Start")
self.say("The subway for NLC is getting ready for takeoff. I'm sorry, but you'll have to get on the next ride. The ride schedule is available through the usher at the ticketing booth.")
elseif contimove.state == worldContimove.getState("Move")
self.say("I'm sorry, but this ride is FULL. We cannot accept any more passengers. Please get on the next ride.")
else
self.say("We will begin boarding " .. contimove.wait .. " minutes before the takeoff. Please be patient and wait for a few minutes. Be aware that the subway will take off right on time, and we stop receiving tickets 1 minute before that, so please make sure to be here on time.")
end |
--[[
SettingsManager handles creation and showing of settings page.
]]
-- Usings
local Array = EsoAddonFramework_Framework_Array
local FrameworkMessageType = EsoAddonFramework_Framework_MessageType
local Messenger = EsoAddonFramework_Framework_Messenger
local String = EsoAddonFramework_Framework_String
-- Constants
-- Fields
local _addonInfo
local _settingsPanel
-- Local functions
local function OnSettingsPanelOpened(panel)
if (panel ~= _settingsPanel) then
return
end
Messenger.Publish(FrameworkMessageType.SettingsShown)
end
local function CreateSettingsMenu()
local panelData = {
type = "panel",
name = _addonInfo.DisplayName,
author = _addonInfo.Author,
version = _addonInfo.Version,
registerForRefresh = true
}
---@diagnostic disable-next-line: undefined-global
_settingsPanel = LibAddonMenu2:RegisterAddonPanel(_addonInfo.Name, panelData)
local optionControls = { }
local controlsInfos = {Messenger.Publish(FrameworkMessageType.SettingsControlsRequest)}
for _, controlsInfo in Array.Enumerate(controlsInfos) do
Array.Add(optionControls, {
type = "submenu",
name = controlsInfo.DisplayName,
controls = controlsInfo.Controls,
isLast = controlsInfo.IsLast
})
end
Array.Sort(optionControls, function(a, b)
if (a.isLast == true) then
return false
elseif (b.isLast == true) then
return true
end
local aClean = String.StripColorCodes(a.name)
local bClean = String.StripColorCodes(b.name)
return aClean < bClean
end)
---@diagnostic disable-next-line: undefined-global
LibAddonMenu2:RegisterOptionControls(_addonInfo.Name, optionControls)
CALLBACK_MANAGER:RegisterCallback("LAM-PanelOpened", OnSettingsPanelOpened)
end
local function ShowSettings()
---@diagnostic disable-next-line: undefined-global
LibAddonMenu2:OpenToPanel(_settingsPanel)
end
local function Initialize()
CreateSettingsMenu()
Messenger.Subscribe(FrameworkMessageType.ShowSettings, ShowSettings)
end
-- Constructor
---@param addonInfo AddonInfo
local function Constructor(addonInfo)
_addonInfo = addonInfo
Messenger.Subscribe(FrameworkMessageType.InitialActivation, Initialize)
end
EsoAddonFramework_Framework_Bootstrapper.Register(Constructor)
-- Class functions |
local playsession = {
{"sobitome", {701030}},
{"Synka_", {505257}},
{"MINIMAN10000", {13830}},
{"ddschmitz", {1151421}},
{"thesandbox", {1564989}},
{"remarkablysilly", {812940}},
{"LegoAnts", {169033}},
{"redlabel", {455172}},
{"cdg4370", {179408}},
{"teomarx", {448997}},
{"CawaEast", {693614}},
{"somestringsattached", {219986}},
{"YoubutWorse", {199632}},
{"EigenMan", {4577}},
{"ElderAxe", {14402}},
{"Hitman451", {890318}},
{"Llzzard", {146641}},
{"halfdanj", {316691}},
{"iansuarus", {80803}},
{"kendoctor", {1015152}},
{"jrz126", {1612}},
{"Puph", {325475}},
{"ustrease", {583435}},
{"edwar88", {65705}},
{"FafnerPajarito", {53591}},
{"violador_de_aliens", {57705}},
{"Beeseearr", {116593}},
{"Factorio401", {190781}},
{"XnagitoX", {67290}},
{"nizzy", {68159}},
{"JB_Delta", {31944}},
{"epicNtek", {412789}},
{"Kiumajus", {70279}},
{"Rotary255", {210123}},
{"zakky0919", {154723}},
{"kunnis", {412591}},
{"Nezeken", {1240065}},
{"AGoodName", {4128}},
{"Redbeard28", {1269644}},
{"D_Riv", {565888}},
{"Pickleman", {6690}},
{"ClassAction", {142474}},
{"GandoharTheGreat", {1133114}},
{"engbizzle", {3563}},
{"asd100477", {242774}},
{"TXL_PLAYZ", {110569}},
{"rjdunlap", {586740}},
{"adidas", {476216}},
{"Hutspovian", {498314}},
{"CallMeTaste", {401704}},
{"THANKAAAAAA", {26624}},
{"yulingqixiao", {417271}},
{"ZTX", {619604}},
{"araran", {32476}},
{"EmperorTrump", {46008}},
{"KKnD", {288870}},
{"NASER", {665153}},
{"Krono", {2424}},
{"FudgeZombie", {35195}},
{"L0771", {222502}},
{"zeruelrojo", {193773}},
{"US9RN9NE", {434062}},
{"303Mark", {180920}},
{"ShySkream", {169183}},
{"ServalKitty", {454627}},
{"sychris9", {404960}},
{"kuumottaja", {89452}},
{"Thymey", {62072}},
{"WorldofWarIII", {241108}},
{"cubun_2009", {18379}},
{"Chesmu", {112006}},
{"MrJSelig", {120697}},
{"Silverwolf9300", {3444}}
}
return playsession |
local uXp_CurrentExp = 0
local uXp_CurrentLevel = 0
local C = {
light = "|cFFABD6F4",
medium = "|cFF03FFAC",
dark = "|cFF02FEDC",
resume = "|r"
}
local function uXp_FormatChatMessage(xpChange, currentXp, nextLevelXp, nextLevel)
local remainingXp = nextLevelXp - currentXp
local repsToNextLevel = floor(remainingXp / xpChange) + 1
local xpGain = uC("+" .. uShared_StringComma(xpChange), C.dark) .. " XP - "
local xpToNextLevel = uC(uShared_StringComma(currentXp), C.dark) .. " / " ..
uC(uShared_StringComma(nextLevelXp), C.light)
local xpLeft = ", " .. uC(uShared_StringComma(remainingXp), C.dark) .. " XP to lvl " .. uC(nextLevel, C.dark)
local xpReps = " (" .. uC(uShared_StringComma(repsToNextLevel), C.dark) .. " reps)."
return xpGain .. xpToNextLevel .. xpLeft .. xpReps
end
local function uXp_ScanAndReportExp()
local currentXp = UnitXP("player")
local nextLevelXp = UnitXPMax("player")
local currentLevel = UnitLevel("player")
local xpChange = currentXp - uXp_CurrentExp
uXp_CurrentExp = currentXp
-- Xp was reset skip..
if (xpChange == 0) then
return
end
-- Level change occured dont message anything
if currentLevel ~= uXp_CurrentLevel then
uXp_CurrentLevel = currentLevel
return
end
local chatMessage = uXp_FormatChatMessage(xpChange, currentXp, nextLevelXp, currentLevel + 1)
uShared_PrintAll("CHAT_MSG_COMBAT_XP_GAIN", chatMessage)
end
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_XP_UPDATE")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:SetScript("OnEvent", function(self, event, data)
if event == "PLAYER_ENTERING_WORLD" then
uXp_CurrentExp = UnitXP("player")
uXp_CurrentLevel = UnitLevel("player")
uXp_ScanAndReportExp()
elseif event == "PLAYER_XP_UPDATE" then
uXp_ScanAndReportExp()
end
end)
-- Filter out XP Gains
local function uXp_FilterCombatXpGain(self, event, msg, ...)
return true
end
ChatFrame_AddMessageEventFilter("CHAT_MSG_COMBAT_XP_GAIN", uXp_FilterCombatXpGain)
-- "Greater Diskbat dies, you gain 142 experience (+71 Rested bounus)"
-- "Greater Diskbat dies, you gain 142 experience"
|
-- convert true|false to on|off
local function convert_boolean_to_onoff(value)
if value == true then value = 'on' else value = 'off' end
return value
end
local Directive = {}
function Directive:new(env)
local run_env = 'production'
if env ~= nil then run_env = env end
local instance = {
run_env = run_env,
directiveSets = self.directiveSets
}
setmetatable(instance, Directive)
return instance
end
function Directive:codeCache(bool_var)
local res = [[lua_code_cache ]] .. convert_boolean_to_onoff(bool_var) .. [[;]]
return res
end
function Directive:initByLua(lua_lib)
if lua_lib == nil then return '' end
local res = [[init_by_lua require(']] .. lua_lib .. [[');]]
return res
end
function Directive:initByLuaFile(lua_file)
if lua_file == nil then return '' end
local res = [[init_by_lua_file ]] .. lua_file .. [[;]]
return res
end
function Directive:accByLua(lua_lib)
if lua_lib == nil then return '' end
local res = [[access_by_lua require(']] .. lua_lib .. [[');]]
return res
end
function Directive:accByLuaFile(lua_file)
if lua_file == nil then return '' end
local res = [[access_by_lua_file ]] .. lua_file .. [[;]]
return res
end
function Directive:contentByLua(lua_lib)
if lua_lib == nil then return '' end
local res = [[content_by_lua require(']] .. lua_lib .. [[');]]
return res
end
function Directive:contentByLuaFile(lua_file)
if lua_file == nil then return '' end
local res = [[location / {
content_by_lua_file ]] .. lua_file .. [[;
}]]
return res
end
function Directive:luaPackagePath(lua_path)
local path = './application/?.lua;' .. './application/library/?.lua;'
if lua_path ~= nil then path = path .. lua_path end
path = path .. './?.lua;'
local res = [[lua_package_path "]] .. path .. package.path .. [[;/?.lua;/lib/?.lua;;";]]
return res
end
function Directive:luaPackageCpath(lua_cpath)
local path = './application/library/?.so;'
if lua_cpath ~= nil then path = path .. lua_cpath end
path = path .. './?.so;'
local res = [[lua_package_cpath "]] .. path .. package.cpath .. [[;/?.so;/lib/?.so;;";]]
return res
end
function Directive:directiveSets()
return {
['VA_ENV'] = self.run_env,
-- lua_shared_dict falcon_share 100m;
-- ['LUA_SHARED_DICT'] = Directive.luaSharedDict,
['LUA_CODE_CACHE'] = Directive.codeCache,
['INIT_BY_LUA'] = Directive.initByLua,
['INIT_BY_LUA_FILE'] = Directive.initByLuaFile,
['ACCESS_BY_LUA'] = Directive.accByLua,
['ACCESS_BY_LUA_FILE'] = Directive.accByLuaFile,
['VANILLA_WAF'] = Directive.accByLua,
['CONTENT_BY_LUA'] = Directive.contentByLua,
['CONTENT_BY_LUA_FILE'] = Directive.contentByLuaFile,
['PORT'] = 80,
['LUA_PACKAGE_PATH'] = Directive.luaPackagePath,
['LUA_PACKAGE_CPATH'] = Directive.luaPackageCpath
}
end
return Directive |
function sysCall_afterSimulation()
-- Called after simulation ended. See also sysCall_beforeSimulation
end
|
--[[ Premake5 configuration file ]]--
CURRENT_PROJECT_DIR = path.getabsolute("")
project "SandboxGame"
kind "WindowedApp"
language "C++"
-- set the debug directory for the IDE to use as a working directory
debugdir "bin/"
-- include all the header files
includedirs
{
"../",
PROJECT_ROOT_DIR .. "/engine/"
}
-- specify the source code files for this project
files { "**.h", "**.cpp" }
-- link the static library
links { "DeadropEngine", "d3d11" } |
-- states
-- disable window animation
hs.window.animationDuration = 0
-- auto reload config files
-- function reloadConfig(files)
-- doReload = false
-- for _,file in pairs(files) do
-- if file:sub(-4) == ".lua" then
-- doReload = true
-- end
-- end
-- if doReload then
-- hs.reload()
-- end
-- hs.notify.new({title="Hammerspoon", informativeText="Config Reloaded"}):send()
-- end
-- local myWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
if not module_list then
module_list = {
"app",
"moom",
"onekey",
"system",
}
end
for i=1,#module_list do
require(module_list[i])
end
|
return
function(cat9, root, builtins, suggest)
function builtins.env(key, val)
if key == "=clear" then
cat9.env = {}
return
end
cat9.env[key] = val
end
local special =
{
"=clear",
-- "=new" [ create a new named set of envs that can be used in !(...) ]
-- "=set" [ switch active set from the default to the current ]
}
function suggest.env(args, raw)
local set = {}
if #args > 3 then
cat9.add_message("too many arguments (=opt or key [val])")
return
end
-- only on key
if #args < 3 then
for _,v in ipairs(special) do
table.insert(set, v)
end
for k,_ in pairs(cat9.env) do
table.insert(set, k)
end
local cur = args[2] and args[2] or ""
-- but might start on val
if cur and #cur > 0 and string.sub(raw, -1) == " " then
args[3] = ""
else
cat9.readline:suggest(cat9.prefix_filter(set, cur, 0), "word")
return
end
end
if type(args[2]) ~= "string" then
cat9.add_message("env >key | opt< [val] expected string, got: " .. type(args[2]))
return
end
if type(args[3]) ~= "string" then
cat9.add_message("env [key | opt] >val< expected string, got: " .. type(args[3]))
return
end
-- key already known? show what the value is
if (#args[2] > 0 and cat9.env[args[2]]) then
local val = cat9.env[args[2]]
cat9.add_message(args[2] .. "=" .. val)
else
table.insert(set, args[2])
cat9.readline:suggest({})
end
end
end
|
-- Copyright (C) 2021 Igara Studio S.A.
--
-- This file is released under the terms of the MIT license.
-- Read LICENSE.txt for more information.
dofile('./test_utils.lua')
----------------------------------------------------------------------
-- Test magic wand in transparent layer
-- Note: A regression in the beta was found in this case.
do
local s = Sprite(4, 4, ColorMode.INDEXED)
app.command.LayerFromBackground()
local i = s.cels[1].image
i:clear(0)
i:putPixel(0, 0, 1)
expect_eq(4, i.width)
expect_eq(4, i.height)
app.useTool{ tool='magic_wand', points={Point(0, 0)} }
expect_eq(Rectangle(0, 0, 1, 1), s.selection.bounds)
app.useTool{ tool='magic_wand', points={Point(1, 0)} }
expect_eq(Rectangle(0, 0, 4, 4), s.selection.bounds)
assert(not s.selection:contains(0, 0))
end
|
project "Ignition"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
staticruntime "off"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"src/**.h",
"src/**.cpp"
}
includedirs
{
"src",
"%{wks.location}/RAPIER/src",
"%{wks.location}/RAPIER/vendor",
"%{IncludeDir.yaml_cpp}",
"%{IncludeDir.entt}",
"%{IncludeDir.glm}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.Glad}",
"%{IncludeDir.miniaudio}"
}
links
{
"RAPIER"
}
filter {"system:windows"} -- WINDOWS
systemversion "latest"
defines
{
"RP_COMPILE_WINDOWS"
}
filter {"system:linux"} -- LINUX
systemversion "latest"
defines
{
"RP_COMPILE_LINUX"
}
filter {"system:macosx"} -- MACOS
systemversion "latest"
defines
{
"RP_COMPILE_MACOS"
}
filter "configurations:Debug" -- DEBUG
defines
{
"RP_DEBUG",
"RP_OUTPUT=bin/%{outputdir}"
}
runtime "Debug"
symbols "on"
postbuildcommands
{
--'{COPYDIR} "%{LibraryDir.VulkanSDK_DebugDLL}" "%{cfg.targetdir}"',
'{COPY} "%{wks.location}/RAPIER/vendor/mono/bin/Debug/mono-2.0-sgen.dll" "%{cfg.targetdir}"'
}
filter "configurations:Release" -- RELEASE
defines
{
"RP_RELEASE",
"RP_OUTPUT=bin/%{outputdir}"
}
runtime "Release"
optimize "on"
postbuildcommands
{
'{COPY} "%{wks.location}/RAPIER/vendor/mono/bin/Release/mono-2.0-sgen.dll" "%{cfg.targetdir}"'
}
filter "configurations:Distribution" -- DISTRIBUTION
defines
{
"RP_DISTRIBUTION",
"RP_OUTPUT=\"bin/%{outputdir}\""
}
runtime "Release"
optimize "on"
postbuildcommands
{
'{COPY} "%{wks.location}/RAPIER/vendor/mono/bin/Release/mono-2.0-sgen.dll" "%{cfg.targetdir}"'
}
|
-- load APIs
require('position')
-- define classes
TreeplantController = {}
TreeplantController.new = function(treestatus_handler, monitor_controller, detector_modem_controller, logger_modem_controller)
-- execute as a treeplant controller
local instance = {}
instance = setmetatable(instance, {__index = TreeplantController})
instance.ts_hdl = treestatus_handler
instance.mon_ctrl = monitor_controller
instance.dt_md_ctrl = detector_modem_controller
instance.lg_md_ctrl = logger_modem_controller
return instance
end
TreeplantController.init = function(self)
self.ts_hdl:load_status()
self.mon_ctrl:set_treestatus_handler(self.ts_hdl)
self.mon_ctrl:reset()
self.dt_md_ctrl:open()
self.lg_md_ctrl:open()
sleep(1)
self.dt_md_ctrl:send_message({
op_type = 'is_waiting',
})
return self
end
TreeplantController.terminate = function(self)
self.ts_hdl:save_status()
self.mon_ctrl:reset()
self.dt_md_ctrl:close()
self.lg_md_ctrl:close()
return self
end
TreeplantController.run = function(self)
parallel.waitForAny(
function() self:_observe_and_update_treestatus() end,
function() self:_observe_and_initialize_treestatus() end,
function() self:_observe_and_update_monitor() end
)
return self
end
TreeplantController._observe_and_update_treestatus = function(self)
while true do
self.dt_md_ctrl:wait_message()
local msg = self.dt_md_ctrl.last_received_message
if msg.op_type == 'update' then
local pos_n = PosNumber.new(msg.pos_number)
self.ts_hdl:increment(pos_n)
os.queueEvent('updated_treestatus')
end
end
return self
end
TreeplantController._observe_and_initialize_treestatus = function(self)
while true do
self.dt_md_ctrl:wait_message()
local msg = self.dt_md_ctrl.last_received_message
if msg.op_type == 'waiting' then
local pos_n = PosNumber.new(msg.pos_number)
self.ts_hdl:initialize(pos_n)
os.queueEvent('updated_treestatus')
end
end
return self
end
TreeplantController._observe_and_update_monitor = function(self)
while true do
os.pullEvent('updated_treestatus')
for pos_n_key, status in pairs(self.ts_hdl.treestatus) do
local pos_n = self.ts_hdl.pos_numbers[pos_n_key]
self.mon_ctrl:write_status(pos_n, status)
end
end
return self
end
|
--[[
ownerSelector.lua
A owner selector button
--]]
local ADDON, Addon = ...
local Sushi = LibStub('Sushi-3.1')
local L = LibStub('AceLocale-3.0'):GetLocale(ADDON)
local OwnerSelector = Addon.Tipped:NewClass('OwnerSelector', 'Button', true)
--[[ Construct ]]--
function OwnerSelector:New(...)
local b = self:Super(OwnerSelector):New(...)
b:RegisterEvent('UNIT_PORTRAIT_UPDATE', 'Update')
b:RegisterFrameSignal('OWNER_CHANGED', 'Update')
b:SetScript('OnClick', b.OnClick)
b:SetScript('OnEnter', b.OnEnter)
b:SetScript('OnLeave', b.OnLeave)
b:SetScript('OnShow', b.Update)
b:RegisterForClicks('anyUp')
b:Update()
return b
end
--[[ Events ]]--
function OwnerSelector:OnClick(button)
if button == 'LeftButton' then
local drop = Sushi.Dropdown:Toggle(self)
if drop then
drop:SetPoint('TOPLEFT', self, 'BOTTOMLEFT', 0, -11)
drop:SetChildren(function()
drop:Add {text = L.SelectCharacter, isTitle = true }
for id in Addon:IterateOwners() do
local owner = Addon:GetOwnerInfo(id)
if not owner.isguild or Addon.Frames:IsEnabled('guild') then
local name = Addon.Owners:GetIconString(owner, 14,-5,0) .. Addon.Owners:GetColorString(owner):format(owner.name)
drop:Add(Addon.DropButton(drop, {
text = name,
checked = id == self:GetOwner(),
func = function()
Addon.Frames:Show(owner.isguild and 'guild' or self:GetFrameID(), id)
end,
delFunc = owner.cached and function()
Sushi.Popup {
text = L.ConfirmDelete:format(name), button1 = OKAY, button2 = CANCEL,
whileDead = 1, exclusive = 1, hideOnEscape = 1,
OnAccept = function()
--[[for i, frame in Addon.Frames:Iterate() do
if frame:GetOwner() == id then
frame:SetOwner(nil)
end
end]]--
Addon:DeleteOwnerInfo(id)
Addon:SendSignal('OWNER_DELETED', id)
end
}
end,
}))
end
end
end)
end
else
self:GetFrame():SetOwner(nil)
end
end
function OwnerSelector:OnEnter()
GameTooltip:SetOwner(self:GetTipAnchor())
GameTooltip:SetText(CHARACTER)
GameTooltip:AddLine(L.TipChangePlayer:format(L.LeftClick), 1, 1, 1)
GameTooltip:AddLine(L.TipResetPlayer:format(L.RightClick), 1, 1, 1)
GameTooltip:Show()
end
--[[ Update ]]--
function OwnerSelector:Update()
local info = self:GetOwnerInfo()
if info.cached then
local icon, coords = Addon.Owners:GetIcon(info)
if coords then
local u,v,w,z = unpack(coords)
local s = (v-u) * 0.06
self.Icon:SetTexCoord(u+s, v-s, w+s, z-s)
self.Icon:SetTexture(icon)
else
self.Icon:SetTexCoord(0,1,0,1)
self.Icon:SetAtlas(icon)
end
else
SetPortraitTexture(self.Icon, 'player')
self.Icon:SetTexCoord(.05,.95,.05,.95)
end
end
|
include("names")
r = math.random(#musko_ime_nom)
ime = musko_ime_nom[r]
bluevalue = math.random(200) + 100;
redvalue = bluevalue;
grinvalue = math.random(200) + 150;
bgnumb = bluevalue + grinvalue;
number = bluevalue + redvalue + grinvalue;
|
local s_project_name
local function add_pmtech_links()
configuration "Debug"
links { "put", "pen" }
configuration "Release"
links { "put", "pen" }
configuration {}
end
local function setup_osx()
links
{
"Cocoa.framework",
"GameController.framework",
"iconv",
"fmod",
"IOKit.framework",
"MetalKit.framework",
"Metal.framework",
"OpenGL.framework"
}
add_pmtech_links()
files
{
(pmtech_dir .. "core/template/osx/Info.plist")
}
if _ACTION == "xcode4" then
install_name_tool = "cd ../../bin/osx && install_name_tool -add_rpath @executable_path/../../.. "
configuration "Debug"
postbuildcommands {
install_name_tool .. s_project_name .. "_d.app/Contents/MacOS/" .. s_project_name .. "_d" .. " || true"
}
configuration "Release"
postbuildcommands {
install_name_tool .. s_project_name .. ".app/Contents/MacOS/" .. s_project_name .. " || true"
}
configuration {}
end
end
local function setup_linux()
--linux must be linked in order
add_pmtech_links()
links
{
"pthread",
"GLEW",
"GLU",
"GL",
"X11",
"fmod",
"dl"
}
linkoptions {
'-Wl,-rpath=\\$$ORIGIN',
"-export-dynamic"
}
end
local function setup_win32()
if renderer_dir == "vulkan" then
libdirs
{
"$(VK_SDK_PATH)/Lib"
}
includedirs
{
"$(VK_SDK_PATH)/Include"
}
links
{
"vulkan-1.lib"
}
elseif renderer_dir == "opengl" then
includedirs
{
pmtech_dir .. "/third_party/glew/include"
}
libdirs
{
pmtech_dir .. "/third_party/glew/lib/win64"
}
links
{
"OpenGL32.lib"
}
else
links
{
"d3d11.lib"
}
end
links
{
"dxguid.lib",
"winmm.lib",
"comctl32.lib",
"fmod64_vc.lib",
"Shlwapi.lib"
}
add_pmtech_links()
systemversion(windows_sdk_version())
disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" }
end
local function setup_ios()
links
{
"Foundation.framework",
"UIKit.framework",
"QuartzCore.framework",
"MetalKit.framework",
"Metal.framework",
"AVFoundation.framework",
"AudioToolbox.framework",
"MediaPlayer.framework",
"fmod_iphoneos"
}
files
{
(pmtech_dir .. "/core/template/ios/**.*"),
"bin/ios/data"
}
excludes
{
("**.DS_Store")
}
xcodebuildresources
{
"bin/ios/data"
}
xcodebuildsettings
{
["IPHONEOS_DEPLOYMENT_TARGET"] = "14.0"
}
end
local function setup_android()
files
{
pmtech_dir .. "/core/template/android/manifest/**.*",
pmtech_dir .. "/core/template/android/activity/**.*"
}
androidabis
{
"armeabi-v7a", "x86"
}
end
local function setup_web()
file = io.open(("assets/file_lists/" .. s_project_name .. "_data.txt"), "r")
if file then
io.input(file)
file_list = io.read()
linkoptions { file_list }
io.close(file)
end
configuration "Debug"
buildoptions {
"-g4",
"-s STACK_OVERFLOW_CHECK=1",
"-s SAFE_HEAP=1",
"-s DETERMINISTIC=1"
}
linkoptions {
"-g4",
"--source-map-base http://localhost:8000/web/",
"-s STACK_OVERFLOW_CHECK=1",
"-s SAFE_HEAP=1",
"-s DETERMINISTIC=1"
}
configuration {}
targetextension (".html")
links { "pen", "put" }
end
local function setup_platform()
if platform_dir == "win32" then
setup_win32()
elseif platform_dir == "osx" then
setup_osx()
elseif platform_dir == "ios" then
setup_ios()
elseif platform_dir == "linux" then
setup_linux()
elseif platform_dir == "android" then
setup_android()
elseif platform_dir == "web" then
setup_web()
end
end
local function setup_bullet()
libdirs
{
(pmtech_dir .. "third_party/bullet/lib/" .. platform_dir)
}
configuration "Debug"
links { "bullet_monolithic_d" }
configuration "Release"
links { "bullet_monolithic" }
configuration {}
end
local function setup_fmod()
if platform == "web" then
return
end
libdirs
{
(pmtech_dir .. "third_party/fmod/lib/" .. platform_dir)
}
end
function setup_modules()
setup_bullet()
setup_fmod()
end
function create_dll(project_name, source_directory, root_directory)
s_project_name = project_name
project ( project_name )
setup_product( project_name )
kind ( binary_type )
language "C++"
print(pmtech_dir)
includedirs
{
-- platform
pmtech_dir .. "core/pen/include",
pmtech_dir .. "core/pen/include/common",
pmtech_dir .. "core/pen/include/" .. platform_dir,
--utility
pmtech_dir .. "core/put/source/",
-- third party
pmtech_dir .. "third_party/",
-- local
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
setup_env()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
targetname (project_name)
configuration "Debug"
defines { "DEBUG" }
symbols "On"
targetname (project_name .. "_d")
end
function create_binary(project_name, source_directory, root_directory, binary_type)
s_project_name = project_name
project ( project_name )
setup_product( project_name )
kind ( binary_type )
language "C++"
if binary_type ~= "SharedLib" then
dependson { "pen", "put" }
end
includedirs
{
-- platform
pmtech_dir .. "core/pen/include",
pmtech_dir .. "core/pen/include/common",
pmtech_dir .. "core/pen/include/" .. platform_dir,
--utility
pmtech_dir .. "core/put/source/",
-- third party
pmtech_dir .. "third_party/",
-- local
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
setup_env()
setup_platform()
setup_platform_defines()
setup_modules()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
targetname (project_name)
libdirs
{
pmtech_dir .. "core/pen/lib/" .. platform_dir .. "/release",
pmtech_dir .. "core/put/lib/" .. platform_dir .. "/release",
}
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
symbols "On"
targetname (project_name .. "_d")
libdirs
{
pmtech_dir .. "core/pen/lib/" .. platform_dir .. "/debug",
pmtech_dir .. "core/put/lib/" .. platform_dir .. "/debug",
}
end
function create_app(project_name, source_directory, root_directory)
create_binary(project_name, source_directory, root_directory, "WindowedApp")
end
function create_app_example( project_name, root_directory )
create_app( project_name, project_name, root_directory )
end
function setup_live_lib( project_name )
if platform == "win32" then
configuration {}
dependson
{
"pmtech_editor"
}
libdirs
{
"bin/win32"
}
configuration {"Debug"}
links
{
"pmtech_editor_d.lib"
}
configuration {"Release"}
links
{
"pmtech_editor.lib"
}
configuration {}
elseif platform == "osx" then
configuration {}
linkoptions
{
"-undefined dynamic_lookup"
}
elseif platform == "linux" then
configuration {}
linkoptions
{
"-fPIC",
"-export-dynamic"
}
end
project ( project_name )
setup_product( project_name )
kind ( "SharedLib" )
language "C++"
project "pmtech_editor"
configuration { "Debug" }
if platform == "osx" then
defines {
('LIVE_LIB="\\\"lib' .. project_name .. '_d.dylib\\\""')
}
elseif platform == "win32" then
defines {
('LIVE_LIB="\\\"' .. project_name .. '_d.dll\\\""')
}
elseif platform == "linux" then
defines {
('LIVE_LIB="\\\"lib' .. project_name .. '_d.so\\\""')
}
end
configuration { "Release" }
if platform == "osx" then
defines {
('LIVE_LIB="\\\"lib' .. project_name .. '.dylib\\\""')
}
elseif platform == "win32" then
defines {
('LIVE_LIB="\\\"' .. project_name .. '.dll\\\""')
}
elseif platform == "linux" then
defines {
('LIVE_LIB="\\\"lib' .. project_name .. '.so\\\""')
}
end
end
|
DefineClass.Holder = {
__parents = {"WaypointsObj" },
units = false,
}
function Holder:Done()
self:KickUnitsFromHolder()
end
function Holder:KickUnitsFromHolder()
local units = self.units
self.units = nil
if units then
local cur_thread = CurrentThread()
for i = 1, #units do
local unit = units[i]
assert(IsValid(unit), "(Shielded) Something went wrong. Units should not be invalid")
assert(unit.command_thread ~= cur_thread, "Probable destructor interuption")
if IsValid(unit) then
unit:KickFromBuilding(self)
end
end
end
end
function Holder:OnEnterHolder(unit)
local units = self.units
if units then
units[#units + 1] = unit
else
self.units = { unit }
end
end
function Holder:OnExitHolder(unit)
table.remove_entry(self.units, unit)
if unit == CameraFollowObjWaiting then
Camera3pFollow(unit)
end
end
|
module 'mock'
--------------------------------------------------------------------
CLASS: SceneLocationManager ()
:MODEL{}
function SceneLocationManager:__init()
self.locationRegistry = {}
end
function SceneLocationManager:getLocations()
end
--------------------------------------------------------------------
CLASS: SceneLocation ()
:MODEL{}
function SceneLocation:onAttach()
end
function SceneLocation:onDetach()
end
|
---------------------------
-- SmartFS: Smart Formspecs
-- License: CC0 or WTFPL
-- by Rubenwardy
---------------------------
local smartfs = {
_fdef = {},
_edef = {},
_ldef = {},
opened = {},
inv = {}
}
local function boolToStr(v)
return v and "true" or "false"
end
-- the smartfs() function
function smartfs.__call(self, name)
return smartfs.get(name)
end
function smartfs.get(name)
return smartfs._fdef[name]
end
------------------------------------------------------
-- Smartfs Interface - Creates a new form and adds elements to it by running the function. Use before Minetest loads. (like minetest.register_node)
------------------------------------------------------
-- Register forms and elements
function smartfs.create(name, onload)
assert(not smartfs._fdef[name],
"SmartFS - (Error) Form "..name.." already exists!")
assert(not smartfs.loaded or smartfs._loaded_override,
"SmartFS - (Error) Forms should be declared while the game loads.")
smartfs._fdef[name] = {
form_setup_callback = onload,
name = name,
show = smartfs._show_,
attach_to_node = smartfs._attach_to_node_
}
return smartfs._fdef[name]
end
------------------------------------------------------
-- Smartfs Interface - Creates a new element type
------------------------------------------------------
function smartfs.element(name, data)
assert(not smartfs._edef[name],
"SmartFS - (Error) Element type "..name.." already exists!")
assert(data.onCreate, "element requires onCreate method")
smartfs._edef[name] = data
return smartfs._edef[name]
end
------------------------------------------------------
-- Smartfs Interface - Creates a dynamic form. Returns state
------------------------------------------------------
function smartfs.dynamic(name,player)
if not smartfs._dynamic_warned then
smartfs._dynamic_warned = true
minetest.log("warning", "SmartFS - (Warning) On the fly forms are being used. May cause bad things to happen")
end
local statelocation = smartfs._ldef.player._make_state_location_(player)
local state = smartfs._makeState_({name=name}, nil, statelocation, player)
smartfs.opened[player] = state
return state
end
------------------------------------------------------
-- Smartfs Interface - Returns the name of an installed and supported inventory mod that will be used above, or nil
------------------------------------------------------
function smartfs.inventory_mod()
if minetest.global_exists("unified_inventory") then
return "unified_inventory"
elseif minetest.global_exists("inventory_plus") then
return "inventory_plus"
else
return nil
end
end
------------------------------------------------------
-- Smartfs Interface - Adds a form to an installed advanced inventory. Returns true on success.
------------------------------------------------------
function smartfs.add_to_inventory(form, icon, title)
local ldef
local invmod = smartfs.inventory_mod()
if invmod then
ldef = smartfs._ldef[invmod]
else
return false
end
return ldef.add_to_inventory(form, icon, title)
end
------------------------------------------------------
-- Smartfs Interface - Set the form as players inventory
------------------------------------------------------
function smartfs.set_player_inventory(form)
smartfs._ldef.inventory.set_inventory(form)
end
------------------------------------------------------
-- Smartfs Interface - Allows you to use smartfs.create after the game loads. Not recommended!
------------------------------------------------------
function smartfs.override_load_checks()
smartfs._loaded_override = true
end
------------------------------------------------------
-- Smartfs formspec locations
------------------------------------------------------
-- Unified inventory plugin
smartfs._ldef.unified_inventory = {
add_to_inventory = function(form, icon, title)
unified_inventory.register_button(form.name, {
type = "image",
image = icon,
})
unified_inventory.register_page(form.name, {
get_formspec = function(player, formspec)
local name = player:get_player_name()
local statelocation = smartfs._ldef.unified_inventory._make_state_location_(name)
local state = smartfs._makeState_(form, nil, statelocation, name)
if form.form_setup_callback(state) ~= false then
smartfs.inv[name] = state
return {formspec = state:_buildFormspec_(false)}
else
return nil
end
end
})
end,
_make_state_location_ = function(player)
return {
type = "inventory",
player = player,
_show_ = function(state)
unified_inventory.set_inventory_formspec(minetest.get_player_by_name(state.location.player), state.def.name)
end
}
end
}
-- Inventory plus plugin
smartfs._ldef.inventory_plus = {
add_to_inventory = function(form, icon, title)
minetest.register_on_joinplayer(function(player)
inventory_plus.register_button(player, form.name, title)
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "" and fields[form.name] then
local name = player:get_player_name()
local statelocation = smartfs._ldef.inventory_plus._make_state_location_(name)
local state = smartfs._makeState_(form, nil, statelocation, name)
if form.form_setup_callback(state) ~= false then
smartfs.inv[name] = state
state:show()
end
end
end)
end,
_make_state_location_ = function(player)
return {
type = "inventory",
player = player,
_show_ = function(state)
inventory_plus.set_inventory_formspec(minetest.get_player_by_name(state.location.player), state:_buildFormspec_(true))
end
}
end
}
-- Show to player
smartfs._ldef.player = {
_make_state_location_ = function(player)
return {
type = "player",
player = player,
_show_ = function(state)
if not state._show_queued then
state._show_queued = true
minetest.after(0, function(state)
if state then
state._show_queued = nil
if (not state.closed) and (not state.obsolete) then
minetest.show_formspec(state.location.player, state.def.name, state:_buildFormspec_(true))
end
end
end, state) -- state given as reference. Maybe additional updates are done in the meantime or the form is obsolete
end
end
}
end
}
-- Standalone inventory
smartfs._ldef.inventory = {
set_inventory = function(form)
if sfinv and sfinv.enabled then
sfinv.enabled = nil
end
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
local statelocation = smartfs._ldef.inventory._make_state_location_(name)
local state = smartfs._makeState_(form, nil, statelocation, name)
if form.form_setup_callback(state) ~= false then
smartfs.inv[name] = state
state:show()
end
end)
minetest.register_on_leaveplayer(function(player)
local name = player:get_player_name()
smartfs.inv[name].obsolete = true
smartfs.inv[name] = nil
end)
end,
_make_state_location_ = function(name)
return {
type = "inventory",
player = name,
_show_ = function(state)
if not state._show_queued then
state._show_queued = true
minetest.after(0, function(state)
if state then
state._show_queued = nil
local player = minetest.get_player_by_name(state.location.player)
--print("smartfs formspec:", state:_buildFormspec_(true))
player:set_inventory_formspec(state:_buildFormspec_(true))
end
end, state)
end
end
}
end
}
-- Node metadata
smartfs._ldef.nodemeta = {
_make_state_location_ = function(nodepos)
return {
type = "nodemeta",
pos = nodepos,
_show_ = function(state)
if not state._show_queued then
state._show_queued = true
minetest.after(0, function(state)
if state then
state._show_queued = nil
local meta = minetest.get_meta(state.location.pos)
meta:set_string("formspec", state:_buildFormspec_(true))
meta:set_string("smartfs_name", state.def.name)
meta:mark_as_private("smartfs_name")
end
end, state)
end
end,
}
end
}
-- Sub-container (internally used)
smartfs._ldef.container = {
_make_state_location_ = function(element)
local self = {
type = "container",
containerElement = element,
parentState = element.root
}
if self.parentState.location.type == "container" then
self.rootState = self.parentState.location.rootState
else
self.rootState = self.parentState
end
return self
end
}
------------------------------------------------------
-- Minetest Interface - on_receive_fields callback can be used in minetest.register_node for nodemeta forms
------------------------------------------------------
function smartfs.nodemeta_on_receive_fields(nodepos, formname, fields, sender, params)
local meta = minetest.get_meta(nodepos)
local nodeform = meta:get_string("smartfs_name")
if not nodeform then
print("SmartFS - (Warning) smartfs.nodemeta_on_receive_fields for node without smarfs data")
return false
end
-- get the currentsmartfs state
local opened_id = minetest.pos_to_string(nodepos)
local state
local form = smartfs.get(nodeform)
if not smartfs.opened[opened_id] or -- If opened first time
smartfs.opened[opened_id].def.name ~= nodeform or -- Or form is changed
smartfs.opened[opened_id].obsolete then
local statelocation = smartfs._ldef.nodemeta._make_state_location_(nodepos)
state = smartfs._makeState_(form, params, statelocation)
if smartfs.opened[opened_id] then
smartfs.opened[opened_id].obsolete = true
end
smartfs.opened[opened_id] = state
form.form_setup_callback(state)
else
state = smartfs.opened[opened_id]
end
-- Set current sender check for multiple users on node
local name
if sender then
name = sender:get_player_name()
state.players:connect(name)
end
-- take the input
state:_sfs_on_receive_fields_(name, fields)
-- Reset form if all players disconnected
if sender and not state.players:get_first() and not state.obsolete then
local statelocation = smartfs._ldef.nodemeta._make_state_location_(nodepos)
local resetstate = smartfs._makeState_(form, params, statelocation)
if form.form_setup_callback(resetstate) ~= false then
resetstate:show()
end
smartfs.opened[opened_id] = nil
end
end
------------------------------------------------------
-- Minetest Interface - on_player_receive_fields callback in case of inventory or player
------------------------------------------------------
minetest.register_on_player_receive_fields(function(player, formname, fields)
local name = player:get_player_name()
if smartfs.opened[name] and smartfs.opened[name].location.type == "player" then
if smartfs.opened[name].def.name == formname then
local state = smartfs.opened[name]
state:_sfs_on_receive_fields_(name, fields)
-- disconnect player if form closed
if not state.players:get_first() then
smartfs.opened[name].obsolete = true
smartfs.opened[name] = nil
end
end
elseif smartfs.inv[name] and smartfs.inv[name].location.type == "inventory" then
local state = smartfs.inv[name]
state:_sfs_on_receive_fields_(name, fields)
end
return false
end)
------------------------------------------------------
-- Minetest Interface - Notify loading of smartfs is done
------------------------------------------------------
minetest.after(0, function()
smartfs.loaded = true
end)
------------------------------------------------------
-- Form Interface [linked to form:show()] - Shows the form to a player
------------------------------------------------------
function smartfs._show_(form, name, params)
assert(form)
assert(type(name) == "string", "smartfs: name needs to be a string")
assert(minetest.get_player_by_name(name), "player does not exist")
local statelocation = smartfs._ldef.player._make_state_location_(name)
local state = smartfs._makeState_(form, params, statelocation, name)
if form.form_setup_callback(state) ~= false then
if smartfs.opened[name] then -- set maybe previous form to obsolete
smartfs.opened[name].obsolete = true
end
smartfs.opened[name] = state
state:show()
end
return state
end
------------------------------------------------------
-- Form Interface [linked to form:attach_to_node()] - Attach a formspec to a node meta
------------------------------------------------------
function smartfs._attach_to_node_(form, nodepos, params)
assert(form)
assert(nodepos and nodepos.x)
local statelocation = smartfs._ldef.nodemeta._make_state_location_(nodepos)
local state = smartfs._makeState_(form, params, statelocation)
if form.form_setup_callback(state) ~= false then
local opened_id = minetest.pos_to_string(nodepos)
if smartfs.opened[opened_id] then -- set maybe previous form to obsolete
smartfs.opened[opened_id].obsolete = true
end
state:show()
end
return state
end
------------------------------------------------------
-- Smartfs Framework - create a form object (state)
------------------------------------------------------
function smartfs._makeState_(form, params, location, newplayer)
------------------------------------------------------
-- State - -- Object to manage players
------------------------------------------------------
local function _make_players_(newplayer)
local self = {
_list = {}
}
function self.connect(self, player)
self._list[player] = true
end
function self.disconnect(self, player)
self._list[player] = nil
end
function self.get_first(self)
return next(self._list)
end
if newplayer then
self:connect(newplayer)
end
return self
end
------------------------------------------------------
-- State - create returning state object
------------------------------------------------------
return {
_ele = {},
def = form,
players = _make_players_(newplayer),
location = location,
is_inv = (location.type == "inventory"), -- obsolete. Please use location.type="inventory" instead
player = newplayer, -- obsolete. Please use location.player
param = params or {},
get = function(self,name)
return self._ele[name]
end,
close = function(self)
self.closed = true
end,
getSize = function(self)
return self._size
end,
size = function(self,w,h)
self._size = {w=w,h=h}
end,
setSize = function(self,w,h)
self._size = {w=w,h=h}
end,
getNamespace = function(self)
local ref = self
local namespace = ""
while ref.location.type == "container" do
namespace = ref.location.containerElement.name.."#"..namespace
ref = ref.location.parentState -- step near to the root
end
return namespace
end,
_buildFormspec_ = function(self,size)
local res = ""
if self._size and size then
res = "size["..self._size.w..","..self._size.h.."]"
end
for key,val in pairs(self._ele) do
if val:getVisible() then
res = res .. val:getBackgroundString() .. val:build() .. val:getTooltipString()
end
end
return res
end,
show = location._show_,
_get_element_recursive_ = function(self, field)
local topfield
for z in field:gmatch("[^#]+") do
topfield = z
break
end
local element = self._ele[topfield]
if element and field == topfield then
return element
elseif element then
if element._getSubElement_ then
local rel_field = string.sub(field, string.len(topfield)+2)
return element:_getSubElement_(rel_field)
else
return element
end
else
return nil
end
end,
-- process onInput hook for the state
_sfs_process_oninput_ = function(self, fields, player)
if self._onInput then
self:_onInput(fields, player)
end
-- recursive all onInput hooks on visible containers
for elename, eledef in pairs(self._ele) do
if eledef.getContainerState and eledef:getVisible() then
eledef:getContainerState():_sfs_process_oninput_(fields, player)
end
end
end,
-- Receive fields and actions from formspec
_sfs_on_receive_fields_ = function(self, player, fields)
local fields_todo = {}
for field, value in pairs(fields) do
local element = self:_get_element_recursive_(field)
if element then
fields_todo[field] = { element = element, value = value }
end
end
for field, todo in pairs(fields_todo) do
todo.element:setValue(todo.value)
end
self:_sfs_process_oninput_(fields, player)
for field, todo in pairs(fields_todo) do
if todo.element.submit then
todo.element:submit(todo.value, player)
end
end
-- handle key_enter
if fields.key_enter and fields.key_enter_field then
local element = self:_get_element_recursive_(fields.key_enter_field)
if element and element.submit_key_enter then
element:submit_key_enter(fields[fields.key_enter_field], player)
end
end
if not fields.quit and not self.closed and not self.obsolete then
self:show()
else
self.players:disconnect(player)
if not fields.quit and self.closed and not self.obsolete then
--closed by application (without fields.quit). currently not supported, see: https://github.com/minetest/minetest/pull/4675
minetest.show_formspec(player,"","size[5,1]label[0,0;Formspec closing not yet created!]")
end
end
return true
end,
onInput = function(self, func)
self._onInput = func -- (fields, player)
end,
load = function(self,file)
local file = io.open(file, "r")
if file then
local table = minetest.deserialize(file:read("*all"))
if type(table) == "table" then
if table.size then
self._size = table.size
end
for key,val in pairs(table.ele) do
self:element(val.type,val)
end
return true
end
end
return false
end,
save = function(self,file)
local res = {ele={}}
if self._size then
res.size = self._size
end
for key,val in pairs(self._ele) do
res.ele[key] = val.data
end
local file = io.open(file, "w")
if file then
file:write(minetest.serialize(res))
file:close()
return true
end
return false
end,
setparam = function(self,key,value)
if not key then return end
self.param[key] = value
return true
end,
getparam = function(self,key,default)
if not key then return end
return self.param[key] or default
end,
element = function(self,typen,data)
local type = smartfs._edef[typen]
assert(type, "Element type "..typen.." does not exist!")
assert(not self._ele[data.name], "Element "..data.name.." already exists")
data.type = typen
local ele = {
name = data.name,
root = self,
data = data,
remove = function(self)
self.root._ele[self.name] = nil
end,
setPosition = function(self,x,y)
self.data.pos = {x=x,y=y}
end,
getPosition = function(self)
return self.data.pos
end,
setSize = function(self,w,h)
self.data.size = {w=w,h=h}
end,
getSize = function(self)
return self.data.size
end,
setVisible = function(self, visible)
if visible == nil then
self.data.visible = true
else
self.data.visible = visible
end
end,
getVisible = function(self)
return self.data.visible
end,
getAbsName = function(self)
return self.root:getNamespace()..self.name
end,
setBackground = function(self, image)
self.data.background = image
end,
getBackground = function(self)
return self.data.background
end,
getBackgroundString = function(self)
if self.data.background then
local size = self:getSize()
if size then
return "background["..
self.data.pos.x..","..self.data.pos.y..";"..
size.w..","..size.h..";"..
self.data.background.."]"
else
return ""
end
else
return ""
end
end,
setValue = function(self, value)
self.data.value = value
end,
setTooltip = function(self,text)
self.data.tooltip = minetest.formspec_escape(text)
end,
getTooltip = function(self)
return self.data.tooltip
end,
getTooltipString = function(self)
if self.data.tooltip then
return "tooltip["..self:getAbsName()..";"..self:getTooltip().."]"
else
return ""
end
end,
}
ele.data.visible = true --visible by default
for key, val in pairs(type) do
ele[key] = val
end
self._ele[data.name] = ele
type.onCreate(ele)
return self._ele[data.name]
end,
------------------------------------------------------
-- State - Element Constructors
------------------------------------------------------
button = function(self, x, y, w, h, name, text, exitf)
return self:element("button", {
pos = {x=x,y=y},
size = {w=w,h=h},
name = name,
value = text,
closes = exitf or false
})
end,
image_button = function(self, x, y, w, h, name, text, image, exitf)
return self:element("button", {
pos = {x=x,y=y},
size = {w=w,h=h},
name = name,
value = text,
image = image,
closes = exitf or false
})
end,
item_image_button = function(self, x, y, w, h, name, text, item, exitf)
return self:element("button", {
pos = {x=x,y=y},
size = {w=w,h=h},
name = name,
value = text,
item = item,
closes = exitf or false
})
end,
label = function(self, x, y, name, text)
return self:element("label", {
pos = {x=x,y=y},
name = name,
value = text,
vertical = false
})
end,
vertlabel = function(self, x, y, name, text)
return self:element("label", {
pos = {x=x,y=y},
name = name,
value = text,
vertical = true
})
end,
toggle = function(self, x, y, w, h, name, list)
return self:element("toggle", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
id = 1,
list = list
})
end,
field = function(self, x, y, w, h, name, label)
return self:element("field", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
value = "",
label = label
})
end,
pwdfield = function(self, x, y, w, h, name, label)
local res = self:element("field", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
value = "",
label = label
})
res:isPassword(true)
return res
end,
textarea = function(self, x, y, w, h, name, label)
local res = self:element("field", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
value = "",
label = label
})
res:isMultiline(true)
return res
end,
image = function(self, x, y, w, h, name, img)
return self:element("image", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
value = img,
imgtype = "image"
})
end,
background = function(self, x, y, w, h, name, img)
return self:element("image", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
background = img,
imgtype = "background"
})
end,
item_image = function(self, x, y, w, h, name, img)
return self:element("image", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
value = img,
imgtype = "item"
})
end,
checkbox = function(self, x, y, name, label, selected)
return self:element("checkbox", {
pos = {x=x, y=y},
name = name,
value = selected,
label = label
})
end,
listbox = function(self, x, y, w, h, name, selected, transparent)
return self:element("list", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
selected = selected,
transparent = transparent
})
end,
dropdown = function(self, x, y, w, h, name, selected)
return self:element("dropdown", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name,
selected = selected
})
end,
inventory = function(self, x, y, w, h, name)
return self:element("inventory", {
pos = {x=x, y=y},
size = {w=w, h=h},
name = name
})
end,
container = function(self, x, y, name, relative)
return self:element("container", {
pos = {x=x, y=y},
name = name,
relative = false
})
end,
view = function(self, x, y, name, relative)
return self:element("container", {
pos = {x=x, y=y},
name = name,
relative = true
})
end,
}
end
-----------------------------------------------------------------
------------------------- ELEMENTS ----------------------------
-----------------------------------------------------------------
smartfs.element("button", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "button needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "button needs valid size")
assert(self.name, "button needs name")
assert(self.data.value, "button needs label")
end,
build = function(self)
local specstring
if self.data.image then
if self.data.closes then
specstring = "image_button_exit["
else
specstring = "image_button["
end
elseif self.data.item then
if self.data.closes then
specstring = "item_image_button_exit["
else
specstring = "item_image_button["
end
else
if self.data.closes then
specstring = "button_exit["
else
specstring = "button["
end
end
specstring = specstring ..
self.data.pos.x..","..self.data.pos.y..";"..
self.data.size.w..","..self.data.size.h..";"
if self.data.image then
specstring = specstring..self.data.image..";"
elseif self.data.item then
specstring = specstring..self.data.item..";"
end
specstring = specstring..self:getAbsName()..";"..
minetest.formspec_escape(self.data.value).."]"
return specstring
end,
submit = function(self, field, player)
if self._click then
self:_click(self.root, player)
end
end,
onClick = function(self,func)
self._click = func
end,
click = function(self,func)
self._click = func
end,
setText = function(self,text)
self:setValue(text)
end,
getText = function(self)
return self.data.value
end,
setImage = function(self,image)
self.data.image = image
self.data.item = nil
end,
getImage = function(self)
return self.data.image
end,
setItem = function(self,item)
self.data.item = item
self.data.image = nil
end,
getItem = function(self)
return self.data.item
end,
setClose = function(self,bool)
self.data.closes = bool
end,
getClose = function(self)
return self.data.closes or false
end
})
smartfs.element("toggle", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "toggle needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "toggle needs valid size")
assert(self.name, "toggle needs name")
assert(self.data.list, "toggle needs data")
end,
build = function(self)
return "button["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
minetest.formspec_escape(self.data.list[self.data.id])..
"]"
end,
submit = function(self, field, player)
self.data.id = self.data.id + 1
if self.data.id > #self.data.list then
self.data.id = 1
end
if self._tog then
self:_tog(self.root, player)
end
end,
onToggle = function(self,func)
self._tog = func
end,
setId = function(self,id)
self.data.id = id
end,
getId = function(self)
return self.data.id
end,
getText = function(self)
return self.data.list[self.data.id]
end
})
smartfs.element("label", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "label needs valid pos")
assert(self.data.value, "label needs text")
end,
build = function(self)
local specstring
if self.data.vertical then
specstring = "vertlabel["
else
specstring = "label["
end
return specstring..
self.data.pos.x..","..self.data.pos.y..
";"..
minetest.formspec_escape(self.data.value)..
"]"
end,
setText = function(self,text)
self:setValue(text)
end,
getText = function(self)
return self.data.value
end
})
smartfs.element("field", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "field needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "field needs valid size")
assert(self.name, "field needs name")
self.data.value = self.data.value or ""
self.data.label = self.data.label or ""
end,
build = function(self)
if self.data.ml then
return "textarea["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
minetest.formspec_escape(self.data.label)..
";"..
minetest.formspec_escape(self.data.value)..
"]"
elseif self.data.pwd then
return "pwdfield["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
minetest.formspec_escape(self.data.label)..
"]"..
self:getCloseOnEnterString()
else
return "field["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
minetest.formspec_escape(self.data.label)..
";"..
minetest.formspec_escape(self.data.value)..
"]"..
self:getCloseOnEnterString()
end
end,
setLabel = function(self,text)
self.data.label = text
end,
getLabel = function(self)
return self.data.label
end,
setText = function(self,text)
self:setValue(text)
end,
getText = function(self)
return self.data.value
end,
isPassword = function(self,bool)
self.data.pwd = bool
end,
isMultiline = function(self,bool)
self.data.ml = bool
end,
getCloseOnEnterString = function(self)
if self.close_on_enter == nil then
return ""
else
return "field_close_on_enter["..self:getAbsName()..";"..tostring(self.close_on_enter).."]"
end
end,
setCloseOnEnter = function(self, value)
self.close_on_enter = value
end,
getCloseOnEnter = function(self)
return self.close_on_enter
end,
submit_key_enter = function(self, field, player)
if self._key_enter then
self:_key_enter(self.root, player)
end
end,
onKeyEnter = function(self,func)
self._key_enter = func
end,
})
smartfs.element("image", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "image needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "image needs valid size")
self.data.value = self.data.value or ""
end,
build = function(self)
if self.data.imgtype == "background" then
return "" -- handled in _buildFormspec_ trough getBackgroundString()
elseif self.data.imgtype == "item" then
return "item_image["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self.data.value..
"]"
else
return "image["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self.data.value..
"]"
end
end,
setImage = function(self,text)
if self.data.imgtype == "background" then
self.data.background = text
else
self:setValue(text)
end
end,
getImage = function(self)
if self.data.imgtype == "background" then
return self.data.background
else
return self.data.value
end
end
})
smartfs.element("checkbox", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "checkbox needs valid pos")
assert(self.name, "checkbox needs name")
self.data.value = minetest.is_yes(self.data.value)
self.data.label = self.data.label or ""
end,
build = function(self)
return "checkbox["..
self.data.pos.x..","..self.data.pos.y..
";"..
self:getAbsName()..
";"..
minetest.formspec_escape(self.data.label)..
";" .. boolToStr(self.data.value) .."]"
end,
submit = function(self, field, player)
-- call the toggle function if defined
if self._tog then
self:_tog(self.root, player)
end
end,
setValue = function(self, value)
self.data.value = minetest.is_yes(value)
end,
getValue = function(self)
return self.data.value
end,
onToggle = function(self,func)
self._tog = func
end,
})
smartfs.element("list", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "list needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "list needs valid size")
assert(self.name, "list needs name")
self.data.value = minetest.is_yes(self.data.value)
self.data.items = self.data.items or {}
end,
build = function(self)
if not self.data.items then
self.data.items = {}
end
local escaped = {}
for i, v in ipairs(self.data.items) do
escaped[i] = minetest.formspec_escape(v)
end
return "textlist["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
table.concat(escaped, ",")..
";"..
tostring(self.data.selected or "")..
";"..
tostring(self.data.transparent or "false").."]"
end,
submit = function(self, field, player)
local _type = string.sub(field,1,3)
local index = tonumber(string.sub(field,5))
self.data.selected = index
if _type == "CHG" and self._click then
self:_click(self.root, index, player)
elseif _type == "DCL" and self._doubleClick then
self:_doubleClick(self.root, index, player)
end
end,
onClick = function(self, func)
self._click = func
end,
click = function(self, func)
self._click = func
end,
onDoubleClick = function(self, func)
self._doubleClick = func
end,
doubleclick = function(self, func)
self._doubleClick = func
end,
addItem = function(self, item)
table.insert(self.data.items, item)
-- return the index of item. It is the last one
return #self.data.items
end,
removeItem = function(self,idx)
table.remove(self.data.items,idx)
end,
getItem = function(self, idx)
return self.data.items[idx]
end,
popItem = function(self)
local item = self.data.items[#self.data.items]
table.remove(self.data.items)
return item
end,
clearItems = function(self)
self.data.items = {}
end,
setSelected = function(self,idx)
self.data.selected = idx
end,
getSelected = function(self)
return self.data.selected
end,
getSelectedItem = function(self)
return self:getItem(self:getSelected())
end,
})
smartfs.element("dropdown", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "dropdown needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "dropdown needs valid size")
assert(self.name, "dropdown needs name")
self.data.items = self.data.items or {}
self.data.selected = self.data.selected or 1
self.data.value = ""
end,
build = function(self)
return "dropdown["..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
self:getAbsName()..
";"..
table.concat(self.data.items, ",")..
";"..
tostring(self:getSelected())..
"]"
end,
submit = function(self, field, player)
self:getSelected()
if self._select then
self:_select(self.root, field, player)
end
end,
onSelect = function(self, func)
self._select = func
end,
addItem = function(self, item)
table.insert(self.data.items, item)
if #self.data.items == self.data.selected then
self.data.value = item
end
-- return the index of item. It is the last one
return #self.data.items
end,
removeItem = function(self,idx)
table.remove(self.data.items,idx)
end,
getItem = function(self, idx)
return self.data.items[idx]
end,
popItem = function(self)
local item = self.data.items[#self.data.items]
table.remove(self.data.items)
return item
end,
clearItems = function(self)
self.data.items = {}
end,
setSelected = function(self,idx)
self.data.selected = idx
self.data.value = self:getItem(idx) or ""
end,
setSelectedItem = function(self,itm)
for idx, item in ipairs(self.data.items) do
if item == itm then
self.data.selected = idx
self.data.value = item
end
end
end,
getSelected = function(self)
self.data.selected = 1
if #self.data.items > 1 then
for i = 1, #self.data.items do
if self.data.items[i] == self.data.value then
self.data.selected = i
end
end
end
return self.data.selected
end,
getSelectedItem = function(self)
return self.data.value
end,
})
smartfs.element("inventory", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "list needs valid pos")
assert(self.data.size and self.data.size.w and self.data.size.h, "list needs valid size")
assert(self.name, "list needs name")
end,
build = function(self)
return "list["..
(self.data.invlocation or "current_player") ..
";"..
self.name.. --no namespacing
";"..
self.data.pos.x..","..self.data.pos.y..
";"..
self.data.size.w..","..self.data.size.h..
";"..
(self.data.index or "") ..
"]"
end,
-- available inventory locations
-- "current_player": Player to whom the menu is shown
-- "player:<name>": Any player
-- "nodemeta:<X>,<Y>,<Z>": Any node metadata
-- "detached:<name>": A detached inventory
-- "context" does not apply to smartfs, since there is no node-metadata as context available
setLocation = function(self,invlocation)
self.data.invlocation = invlocation
end,
getLocation = function(self)
return self.data.invlocation or "current_player"
end,
usePosition = function(self, pos)
self.data.invlocation = string.format("nodemeta:%d,%d,%d", pos.x, pos.y, pos.z)
end,
usePlayer = function(self, name)
self.data.invlocation = "player:" .. name
end,
useDetached = function(self, name)
self.data.invlocation = "detached:" .. name
end,
setIndex = function(self,index)
self.data.index = index
end,
getIndex = function(self)
return self.data.index
end
})
smartfs.element("code", {
onCreate = function(self)
self.data.code = self.data.code or ""
end,
build = function(self)
if self._build then
self:_build()
end
return self.data.code
end,
submit = function(self, field, player)
if self._sub then
self:_sub(self.root, field, player)
end
end,
onSubmit = function(self,func)
self._sub = func
end,
onBuild = function(self,func)
self._build = func
end,
setCode = function(self,code)
self.data.code = code
end,
getCode = function(self)
return self.data.code
end
})
smartfs.element("container", {
onCreate = function(self)
assert(self.data.pos and self.data.pos.x and self.data.pos.y, "container needs valid pos")
assert(self.name, "container needs name")
local statelocation = smartfs._ldef.container._make_state_location_(self)
self._state = smartfs._makeState_(nil, self.root.param, statelocation)
end,
-- redefinitions. The size is not handled by data.size but by container-state:size
setSize = function(self,w,h)
self:getContainerState():setSize(w,h)
end,
getSize = function(self)
return self:getContainerState():getSize()
end,
-- element interface methods
build = function(self)
if self.data.relative ~= true then
return "container["..self.data.pos.x..","..self.data.pos.y.."]"..
self:getContainerState():_buildFormspec_(false)..
"container_end[]"
else
return self:getContainerState():_buildFormspec_(false)
end
end,
getContainerState = function(self)
return self._state
end,
_getSubElement_ = function(self, field)
return self:getContainerState():_get_element_recursive_(field)
end,
})
return smartfs |
ITEM.name = "Шницель"
ITEM.desc = "Обжаренная телятина, с луком."
ITEM.category = "Еда"
ITEM.model = "models/aoc_outdoor/meat_03.mdl"
ITEM.hunger = 35
ITEM.thirst = 0
ITEM.drunk = -10
ITEM.price = 100
ITEM.quantity = 3
ITEM.permit = "food" |
local layer, parent = torch.class('nn.MakeBoxes', 'nn.Module')
--[[
Inputs:
- x0, y0: Numbers giving coordinates of receptive field center for upper left
corner of inputs.
- sx, sy: Numbers giving horizontal and vertical stride between receptive
field centers.
- anchors: Tensor of shape 2 x k giving width and height for each of k
anchor boxes.
--]]
function layer:__init(x0, y0, sx, sy, anchors)
parent.__init(self)
self.x0 = x0
self.y0 = y0
self.sx = sx
self.sy = sy
self.anchors = anchors:clone()
self.input_perm = torch.Tensor()
self.boxes = torch.Tensor()
self.raw_anchors = torch.Tensor()
self.wa_expand = nil
self.ha_expand = nil
self.dtx = torch.Tensor()
self.dty = torch.Tensor()
self.dtw = torch.Tensor()
self.dth = torch.Tensor()
end
--[[
input: Tensor of shape N x 4k x H x W
output: Tensor of shape N x (k*H*W) x 4
--]]
function layer:updateOutput(input)
local N, H, W = input:size(1), input:size(3), input:size(4)
local k = input:size(2) / 4
self.boxes:resize(N, k, H, W, 4)
-- Unpack x, y, w, h from boxes; these are the centers and sizes of
-- the generated boxes, each of shape N x H x W x k
local x = self.boxes[{{}, {}, {}, {}, 1}]
local y = self.boxes[{{}, {}, {}, {}, 2}]
local w = self.boxes[{{}, {}, {}, {}, 3}]
local h = self.boxes[{{}, {}, {}, {}, 4}]
-- Reshape input from N x 4k x H x W to N x k x 4 x H x W
local input_view = input:view(N, k, 4, H, W)
-- Unpack tx, ty, tw, th from input
-- Each of these is N x k x H x W
local tx = input_view[{{}, {}, 1}]
local ty = input_view[{{}, {}, 2}]
local tw = input_view[{{}, {}, 3}]
local th = input_view[{{}, {}, 4}]
-- Unpack wa, ha from anchors; each has shape k, so we need to expand
local wa, ha = self.anchors[1], self.anchors[2]
self.wa_expand = wa:view(1, k, 1, 1):expand(N, k, H, W)
self.ha_expand = ha:view(1, k, 1, 1):expand(N, k, H, W)
-- Compute xa and ya using x0, sx, y0, sy
-- We also need to expand them
local xa = torch.range(0, W - 1):typeAs(input):mul(self.sx):add(self.x0)
local ya = torch.range(0, H - 1):typeAs(input):mul(self.sy):add(self.y0)
local xa_expand = xa:view(1, 1, 1, W):expand(N, k, H, W)
local ya_expand = ya:view(1, 1, H, 1):expand(N, k, H, W)
-- N x k x H x W x 4
self.raw_anchors:resizeAs(self.boxes)
self.raw_anchors:select(5, 1):copy(xa_expand)
self.raw_anchors:select(5, 2):copy(ya_expand)
self.raw_anchors:select(5, 3):copy(self.wa_expand)
self.raw_anchors:select(5, 4):copy(self.ha_expand)
self.raw_anchors = self.raw_anchors:view(N, k * H * W, 4)
-- Compute x = wa * tx + xa, y = ha * tx + ya
x:cmul(self.wa_expand, tx):add(xa_expand)
y:cmul(self.ha_expand, ty):add(ya_expand)
-- Compute w = wa * exp(tw) and h = ha * exp(th)
-- (which comes from tw = log(w / wa), th = log(h / ha))
w:exp(tw):cmul(self.wa_expand)
h:exp(th):cmul(self.ha_expand)
self.output = self.boxes:view(N, k * H * W, 4)
return self.output
end
-- This will only work properly if forward was just called
function layer:updateGradInput(input, gradOutput)
local N, H, W = input:size(1), input:size(3), input:size(4)
local k = input:size(2) / 4
self.gradInput:resizeAs(input):zero()
local dboxes = gradOutput:view(N, k, H, W, 4)
local dx = dboxes[{{}, {}, {}, {}, 1}]
local dy = dboxes[{{}, {}, {}, {}, 2}]
local dw = dboxes[{{}, {}, {}, {}, 3}]
local dh = dboxes[{{}, {}, {}, {}, 4}]
self.dtx:cmul(self.wa_expand, dx)
self.dty:cmul(self.ha_expand, dy)
local w = self.boxes[{{}, {}, {}, {}, 3}]
local h = self.boxes[{{}, {}, {}, {}, 4}]
self.dtw:cmul(w, dw)
self.dth:cmul(h, dh)
local gradInput_view = self.gradInput:view(N, k, 4, H, W)
gradInput_view[{{}, {}, 1}] = self.dtx
gradInput_view[{{}, {}, 2}] = self.dty
gradInput_view[{{}, {}, 3}] = self.dtw
gradInput_view[{{}, {}, 4}] = self.dth
return self.gradInput
end
|
-- * Metronome IM *
--
-- This file is part of the Metronome XMPP server and is released under the
-- ISC License, please see the LICENSE file in this source package for more
-- information about copyright and licensing.
local base64 = require "util.encodings".base64;
local sha1 = require "util.hashes".sha1;
local st = require "util.stanza";
local storagemanager = require "core.storagemanager";
local uuid = require "util.uuid".generate;
local now, pairs = os.time, pairs;
local xhtml_xmlns = "http://www.w3.org/1999/xhtml";
local bob_xmlns = "urn:xmpp:bob";
local bob_cache = storagemanager.open(module.host, "bob_cache");
local index = bob_cache:get() or {};
local queried = {};
local default_expire = module:get_option_number("muc_bob_default_cache_expire", 86400);
local check_caches = module:get_option_number("muc_bob_check_for_expiration", 900);
module:add_timer(check_caches, function()
module:log("debug", "checking for BoB caches that need to be expired...");
for cid, data in pairs(index) do
if now() - data.time > data.max then
index[cid] = nil;
bob_cache:set(cid, nil);
end
end
return check_caches;
end);
local function get_bob(jid, room, cid)
local iq = st.iq({ type = "get", from = room, to = jid, id = uuid() })
:tag("data", { xmlns = "urn:xmpp:bob", cid = cid }):up();
module:log("debug", "Querying %s for BoB image found into XHTML-IM with cid %s", jid, cid);
module:send(iq);
queried[cid] = {};
end
local function cache_data(tag)
if tag.name ~= "data" or tag.attr.xmlns ~= bob_xmlns then
return tag;
end
local cid, mime, max = tag.attr.cid, tag.attr.type, tag.attr["max-age"];
local encoded_data = tag:get_text();
local decoded_data = base64.decode(encoded_data);
local hash = sha1(decoded_data, true);
local calculated = "sha1+"..hash.."@bob.xmpp.org"
if cid ~= calculated then
module:log("warn", "Invalid BoB, cid doesn't match data, got %s instead of %s", cid, calculated);
return;
end
index[cid] = { time = now(), max = max or default_expire };
bob_cache:set(cid, { mime = mime, data = encoded_data });
bob_cache:set(nil, index);
if queried[cid] then
local iq = st.iq({ type = "result" });
iq:add_child(tag);
for jid, query in pairs(queried[cid]) do
iq.attr.from, iq.attr.to, iq.attr.id = query.from, jid, query.id;
module:send(iq);
end
query[cid] = nil;
end
return nil;
end
local function traverse_xhtml(tag, from, room)
if tag.name == "img" and tag.attr.xmlns == xhtml_xmlns and tag.attr.src then
local cid = tag.attr.src:match("^cid:(%w+%+%w+@bob%.xmpp%.org)$");
if not cid then return; end
if bob_cache:get(cid) or queried[cid] then return; end
get_bob(from, room, cid);
end
for child in tag:childtags(nil, xhtml_xmlns) do traverse_xhtml(tag, from, room); end
end
local function message_handler(event)
local origin, stanza = event.origin, event.stanza;
local from, room = stanza.attr.from, stanza.attr.to;
stanza:maptags(cache_data);
local xhtml_im = stanza:get_child("html", xhtml_xmlns);
if not xhtml_im then return; end
for body in xhtml_im:childtags("body", xhtml_xmlns) do traverse_xhtml(body, from, room); end
end
local function iq_handler(event)
local origin, stanza = event.origin, event.stanza;
local tag = stanza.tags[1];
if not tag then return; end
local cid = tag.attr.cid;
if (tag.name ~= "data" and tag.attr.xmlns ~= bob_xmlns) or not cid then return; end
if stanza.attr.type == "result" then cache_data(tag); end
if stanza.attr.type == "get" then
local cached = bob_cache:get(cid);
if not cached then
if queried[cid] then
module:log("debug", "IQ for requesting BoB for %s already sent, waiting for replies", cid);
queried[cid][stanza.attr.from] = { from = stanza.attr.to, id = stanza.attr.id };
return true;
else
module:log("debug", "Bit of Binary requested data is not present in cache (%s), ignoring", cid);
origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
return true;
end
end
local iq = st.reply(stanza);
iq:tag("data", { xmlns = bob_xmlns, cid = cid, type = cached.mime, ["max-age"] = index[cid].max })
:text(cached.data):up();
module:log("debug", "Delivering cached BoB data (%s) on behalf of %s", cid, stanza.attr.to);
module:send(iq);
return true;
end
end
module:hook("muc-disco-info-features", function(room, reply)
reply:tag("feature", { var = bob_xmlns }):up()
end, -98);
module:hook("message/bare", message_handler, 51);
module:hook("iq/full", iq_handler, 51);
module:hook("iq/bare", iq_handler, 51);
|
package.cpath = "../luaclib/?.so"
package.path = "../skynet/lualib/?.lua;../lualib/?.lua;../examples/?.lua"
if _VERSION ~= "Lua 5.3" then
error "Use lua 5.3"
end
local M = {}
local socket = require "clientwebsocket"
local json = require "cjson"
local tool = require "tool"
local fd = nil
local cb = nil
local cbt = nil
M.stop = false
function M.connect(ip, port, recvcb, timercb)
cb = recvcb
cbt = timercb
fd = assert(socket.connect(ip or "127.0.0.1", port or 11798))
end
function M.sleep(t)
socket.usleep(t)
end
local function request(name, args)
local t = {
_cmd = name,
_check = 0,
}
if type(args) == "table" then
for k, v in pairs(args) do
t[k] = v
end
end
local str = json.encode(t)
print("request:" .. str)
return str
end
local function send_package(fd, pack)
socket.send(fd, pack)
end
local function recv_package()
local r , istimeout= socket.recv(fd, 100)
if not r then
return nil
end
if r == "" and istimeout == 0 then
error "Server closed"
end
return r
end
local session = 0
function M.send(name, args)
session = session + 1
local str = request(name, args)
send_package(fd, str)
print("Request:", session)
end
local function dispatch_package()
while true do
local v
v = recv_package()
if not v or v == "" then
break
end
print("recv: " .. tool.dump(v))
if cb then
local t = json.decode(v)
cb(t)
else
print("cb == nil")
end
end
end
function M.start()
while true do
if M.stop then
break
end
dispatch_package()
if cbt then
cbt()
end
socket.usleep(50)
end
end
function CallBack(msg)
print("error:"..msg.error)
end
function M.init(ip,port,hander)
M.connect(ip,port,hander.CallBack,hander.CallBackTimer)
end
function M.login(account,password)
M.send("login.login", {account = account, password = password})
end
function M.create_room(game_name)
M.send("create_room", {game = game_name})
end
function M.enter_room(game,room_id)
M.send("enter_room", {id=room_id,game=game})
end
function M.leave_room()
M.send("leave_room",{})
end
return M
|
-- Stolen from Foreman
data.raw["gui-style"].default["blueprint_button_style"] =
{
type = "button_style",
parent = "button_style",
top_padding = 1,
right_padding = 5,
bottom_padding = 1,
left_padding = 5,
left_click_sound =
{
{
filename = "__core__/sound/gui-click.ogg",
volume = 1
}
}
} |
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
--[[
This module is for various classes and utilities that don't need their own
module.
]]
local core = {}
--[[
Returns whether obj is instance of class or not.
local object = Object:new()
local emitter = Emitter:new()
assert(instanceof(object, Object))
assert(not instanceof(object, Emitter))
assert(instanceof(emitter, Object))
assert(instanceof(emitter, Emitter))
assert(not instanceof(2, Object))
assert(not instanceof('a', Object))
assert(not instanceof({}, Object))
assert(not instanceof(function() end, Object))
Caveats: This function returns true for classes.
assert(instanceof(Object, Object))
assert(instanceof(Emitter, Object))
]]
function core.instanceof(obj, class)
if type(obj) ~= 'table' or obj.meta == nil or not class then
return false
end
if obj.meta.__index == class then
return true
end
local meta = obj.meta
while meta do
if meta.super == class then
return true
elseif meta.super == nil then
return false
end
meta = meta.super.meta
end
return false
end
--------------------------------------------------------------------------------
--[[
This is the most basic object in Luvit. It provides simple prototypal
inheritance and inheritable constructors. All other objects inherit from this.
]]
local Object = {}
core.Object = Object
Object.meta = {__index = Object}
-- Create a new instance of this object
function Object:create()
local meta = rawget(self, "meta")
if not meta then error("Cannot inherit from instance object") end
return setmetatable({}, meta)
end
--[[
Creates a new instance and calls `obj:initialize(...)` if it exists.
local Rectangle = Object:extend()
function Rectangle:initialize(w, h)
self.w = w
self.h = h
end
function Rectangle:getArea()
return self.w * self.h
end
local rect = Rectangle:new(3, 4)
p(rect:getArea())
]]
function Object:new(...)
local obj = self:create()
if type(obj.initialize) == "function" then
obj:initialize(...)
end
return obj
end
--[[
Creates a new sub-class.
local Square = Rectangle:extend()
function Square:initialize(w)
self.w = w
self.h = h
end
]]
function Object:extend()
local obj = self:create()
local meta = {}
-- move the meta methods defined in our ancestors meta into our own
--to preserve expected behavior in children (like __tostring, __add, etc)
for k, v in pairs(self.meta) do
meta[k] = v
end
meta.__index = obj
meta.super=self
obj.meta = meta
return obj
end
--------------------------------------------------------------------------------
--[[
This class can be used directly whenever an event emitter is needed.
local emitter = Emitter:new()
emitter:on('foo', p)
emitter:emit('foo', 1, 2, 3)
Also it can easily be sub-classed.
local Custom = Emitter:extend()
local c = Custom:new()
c:on('bar', onBar)
Unlike EventEmitter in node.js, Emitter class doesn't auto binds `self`
reference. This means, if a callback handler is expecting a `self` reference,
utils.bind() should be used, and the callback handler should have a `self` at
the beginning its parameter list.
function some_func(self, a, b, c)
end
emitter:on('end', utils.bind(some_func, emitter))
emitter:emit('end', 'a', 'b', 'c')
]]
local Emitter = Object:extend()
core.Emitter = Emitter
local function handlerRemoved()
end
-- By default, and error events that are not listened for should throw errors
function Emitter:missingHandlerType(name, ...)
if name == "error" then
local args = {...}
--error(tostring(args[1]))
-- we define catchall error handler
if self ~= process then
-- if process has an error handler
local handlers = rawget(process, "handlers")
if handlers and handlers["error"] then
-- delegate to process error handler
process:emit("error", ..., self)
else
debug("UNHANDLED ERROR", ...)
error("UNHANDLED ERROR. Define process:on('error', handler) to catch such errors")
end
else
debug("UNHANDLED ERROR", ...)
error("UNHANDLED ERROR. Define process:on('error', handler) to catch such errors")
end
end
end
-- Same as `Emitter:on` except it de-registers itself after the first event.
function Emitter:once(name, callback)
local emitter = self
local function wrapped(...)
emitter:removeListener(name, wrapped)
callback(...)
end
self:on(name, wrapped)
return self
end
-- Adds an event listener (`callback`) for the named event `name`.
function Emitter:on(name, callback)
local handlers = rawget(self, "handlers")
if not handlers then
handlers = {}
rawset(self, "handlers", handlers)
end
local handlers_for_type = rawget(handlers, name)
if not handlers_for_type then
if self.addHandlerType then
self:addHandlerType(name)
end
handlers_for_type = {}
rawset(handlers, name, handlers_for_type)
end
table.insert(handlers_for_type, callback)
return self
end
function Emitter:listenerCount(name)
local handlers = rawget(self, "handlers")
if not handlers then
return 0
end
local handlers_for_type = rawget(handlers, name)
if not handlers_for_type then
return 0
else
local count = 0
for _,handler in ipairs(handlers_for_type) do
if handler ~= handlerRemoved then
count = count + 1
end
end
return count
end
end
-- Emit a named event to all listeners with optional data argument(s).
function Emitter:emit(name, ...)
local handlers = rawget(self, "handlers")
if not handlers then
self:missingHandlerType(name, ...)
return
end
local handlers_for_type = rawget(handlers, name)
if not handlers_for_type then
self:missingHandlerType(name, ...)
return
end
local called = false
for i, callback in ipairs(handlers_for_type) do
if callback ~= handlerRemoved then
callback(...)
called = true
end
end
for i = #handlers_for_type, 1, -1 do
if handlers_for_type[i] == handlerRemoved then
table.remove(handlers_for_type, i)
end
end
if not called then
self:missingHandlerType(name, ...)
return
end
return self
end
-- Remove a listener so that it no longer catches events.
function Emitter:removeListener(name, callback)
local handlers = rawget(self, "handlers")
if not handlers then return end
local handlers_for_type = rawget(handlers, name)
if not handlers_for_type then return end
for i = #handlers_for_type, 1, -1 do
if callback == nil or handlers_for_type[i] == callback then
handlers_for_type[i] = handlerRemoved
end
end
end
-- Remove all listeners
-- @param {String?} name optional event name
function Emitter:removeAllListeners(name)
local handlers = rawget(self, "handlers")
if not handlers then return end
local handlers_for_type = rawget(handlers, name)
if handlers_for_type then
for i = #handlers_for_type, 1, -1 do
handlers_for_type[i] = nil
end
else
rawset(self, "handlers", {})
end
end
-- Get listeners
-- @param {String} name event name
function Emitter:listeners(name)
local handlers = rawget(self, "handlers")
if not handlers then
return 0
end
local handlers_for_type = rawget(handlers, name)
if not handlers_for_type then
return {}
else
for i = #handlers_for_type, 1, -1 do
if handlers_for_type[i] == handlerRemoved then
table.remove(handlers_for_type, i)
end
end
return handlers_for_type
end
end
--[[
Utility that binds the named method `self[name]` for use as a callback. The
first argument (`err`) is re-routed to the "error" event instead.
local Joystick = Emitter:extend()
function Joystick:initialize(device)
self:wrap("onOpen")
FS.open(device, self.onOpen)
end
function Joystick:onOpen(fd)
-- and so forth
end
]]
function Emitter:wrap(name)
local fn = self[name]
self[name] = function (err, ...)
if (err) then return self:emit("error", err) end
return fn(self, ...)
end
end
--------------------------------------------------------------------------------
--[[
This is an abstract interface that works like `uv.Stream` but doesn't actually
contain a uv struct (it's pure lua)
]]
local iStream = Emitter:extend()
core.iStream = iStream
function iStream:pipe(target)
self:on('data', function (chunk)
if target:write(chunk) == false and self.pause then
self:pause()
end
end)
target:on('drain', function()
if self.resume then
self:resume()
end
end)
local didOnEnd = false
local function onend()
if (didOnEnd) then
return
end
didOnEnd = true
if target._closeStream then
target:_closeStream()
end
if target.done then
target:done()
end
end
local function onclose()
if (didOnEnd) then
return
end
didOnEnd = true
if target.destroy then
target:destroy()
end
end
self:on('close', onclose)
self:on('end', onend)
end
--------------------------------------------------------------------------------
-- This is for code that wants structured error messages.
local Error = Object:extend()
core.Error = Error
-- Make errors tostringable
function Error.meta.__tostring(table)
return table.message
end
function Error:initialize(message)
self.message = message
end
--------------------------------------------------------------------------------
return core
|
local node_mod = require("luasnip.nodes.node")
local iNode = require("luasnip.nodes.insertNode")
local tNode = require("luasnip.nodes.textNode")
local util = require("luasnip.util.util")
local node_util = require("luasnip.nodes.util")
local types = require("luasnip.util.types")
local events = require("luasnip.util.events")
local mark = require("luasnip.util.mark").mark
local Environ = require("luasnip.util.environ")
local conf = require("luasnip.config")
local session = require("luasnip.session")
local pattern_tokenizer = require("luasnip.util.pattern_tokenizer")
local dict = require("luasnip.util.dict")
local true_func = function()
return true
end
local callbacks_mt = {
__index = function(table, key)
rawset(table, key, {})
return {}
end,
}
-- declare SN here, is needed in metatable.
local SN
local stored_mt = {
__index = function(table, key)
-- default-node is just empty text.
local val = SN(nil, { iNode.I(1) })
val.is_default = true
rawset(table, key, val)
return val
end,
}
local Snippet = node_mod.Node:new()
local Parent_indexer = {}
function Parent_indexer:new(o)
setmetatable(o, self)
self.__index = self
return o
end
-- Returns referred node from parent (or parents' parent).
function Parent_indexer:resolve(snippet)
-- recurse if index is a parent_indexer
if getmetatable(self.indx) == Parent_indexer then
return self.indx:resolve(snippet.parent)
else
return snippet.parent.insert_nodes[self.indx]
end
end
local function P(indx)
return Parent_indexer:new({ indx = indx })
end
function Snippet:init_nodes()
local insert_nodes = {}
for i, node in ipairs(self.nodes) do
node.parent = self
node.indx = i
if
node.type == types.insertNode
or node.type == types.exitNode
or node.type == types.snippetNode
or node.type == types.choiceNode
or node.type == types.dynamicNode
or node.type == types.restoreNode
then
if node.pos then
insert_nodes[node.pos] = node
end
end
node.update_dependents = function(node)
node:_update_dependents()
node.parent:update_dependents()
end
end
if insert_nodes[1] then
insert_nodes[1].prev = self
for i = 2, #insert_nodes do
insert_nodes[i].prev = insert_nodes[i - 1]
insert_nodes[i - 1].next = insert_nodes[i]
end
insert_nodes[#insert_nodes].next = self
self.inner_first = insert_nodes[1]
self.inner_last = insert_nodes[#insert_nodes]
else
self.inner_first = self
self.inner_last = self
end
self.insert_nodes = insert_nodes
end
local function wrap_nodes_in_snippetNode(nodes)
if getmetatable(nodes) then
-- is a node, not a table.
if nodes.type ~= types.snippetNode then
-- is not a snippetNode.
-- pos might have been nil, just set it correctly here.
nodes.pos = 1
return SN(nil, { nodes })
else
-- is a snippetNode, wrapping it twice is unnecessary.
return nodes
end
else
-- is a table of nodes.
return SN(nil, nodes)
end
end
local function init_opts(opts)
opts = opts or {}
opts.callbacks = opts.callbacks or {}
-- return empty table for non-specified callbacks.
setmetatable(opts.callbacks, callbacks_mt)
opts.condition = opts.condition or true_func
opts.show_condition = opts.show_condition or true_func
-- return sn(t("")) for so-far-undefined keys.
opts.stored = setmetatable(opts.stored or {}, stored_mt)
-- wrap non-snippetNode in snippetNode.
for key, nodes in pairs(opts.stored) do
opts.stored[key] = wrap_nodes_in_snippetNode(nodes)
end
return opts
end
local function S(context, nodes, opts)
if type(context) == "string" then
context = { trig = context }
end
-- context.dscr could be nil, string or table.
context.dscr = util.wrap_value(context.dscr or context.trig)
local dscr = util.to_line_table(context.dscr)
if context.docstring then
context.docstring = util.to_line_table(context.docstring)
end
-- default: true.
if context.wordTrig == nil then
context.wordTrig = true
end
opts = init_opts(opts)
nodes = util.wrap_nodes(nodes)
local snip = Snippet:new({
trigger = context.trig,
dscr = dscr,
name = context.name or context.trig,
wordTrig = context.wordTrig,
regTrig = context.regTrig,
docstring = context.docstring,
docTrig = context.docTrig,
nodes = nodes,
insert_nodes = {},
current_insert = 0,
condition = opts.condition,
show_condition = opts.show_condition,
callbacks = opts.callbacks,
mark = nil,
dependents = {},
active = false,
type = types.snippet,
hidden = context.hidden,
stored = opts.stored,
dependents_dict = dict.new(),
})
-- is propagated to all subsnippets, used to quickly find the outer snippet
snip.snippet = snip
-- the snippet may not have dependents.
snip._update_dependents = function() end
snip.update_dependents = snip._update_dependents
snip:init_nodes()
if not snip.insert_nodes[0] then
-- Generate implied i(0)
local i0 = iNode.I(0)
local i0_indx = #nodes + 1
i0.parent = snip
i0.indx = i0_indx
snip.insert_nodes[0] = i0
snip.nodes[i0_indx] = i0
end
return snip
end
function SN(pos, nodes, opts)
opts = init_opts(opts)
local snip = Snippet:new({
pos = pos,
nodes = util.wrap_nodes(nodes),
insert_nodes = {},
current_insert = 0,
callbacks = opts.callbacks,
mark = nil,
dependents = {},
active = false,
type = types.snippetNode,
})
snip:init_nodes()
return snip
end
local function ISN(pos, nodes, indent_text, opts)
local snip = SN(pos, nodes, opts)
function snip:indent(parent_indent)
Snippet.indent(self, indent_text:gsub("$PARENT_INDENT", parent_indent))
end
return snip
end
function Snippet:remove_from_jumplist()
-- prev is i(-1)(startNode), prev of that is the outer/previous snippet.
local pre = self.prev.prev
-- similar for next, self.next is the i(0).
local nxt = self.next.next
self:exit()
-- basically four possibilities: only snippet, between two snippets,
-- inside an insertNode (start), inside an insertNode (end).
if pre then
-- Snippet is linearly behind previous snip, the appropriate value
-- for nxt.prev is set later.
if pre.pos == 0 then
pre.next = nxt
else
if nxt ~= pre then
-- if not the only snippet inside the insertNode:
pre.inner_first = nxt
nxt.prev = pre
return
else
pre.inner_first = nil
pre.inner_last = nil
pre.inner_active = false
return
end
end
end
if nxt then
if nxt.pos == -1 then
nxt.prev = pre
else
-- only possible if this is the last inside an insertNode, only
-- snippet in insertNode is handled above
nxt.inner_last = pre
pre.next = nxt
end
end
end
local function insert_into_jumplist(snippet, start_node, current_node)
if current_node then
-- currently at the endpoint (i(0)) of another snippet, this snippet
-- is inserted _behind_ that snippet.
if current_node.pos == 0 then
if current_node.next then
if current_node.next.pos == -1 then
-- next is beginning of another snippet, this snippet is
-- inserted before that one.
current_node.next.prev = snippet.insert_nodes[0]
else
-- next is outer insertNode.
current_node.next.inner_last = snippet.insert_nodes[0]
end
end
snippet.insert_nodes[0].next = current_node.next
current_node.next = start_node
start_node.prev = current_node
elseif current_node.pos == -1 then
if current_node.prev then
if current_node.prev.pos == 0 then
current_node.prev.next = start_node
else
current_node.prev.inner_first = snippet
end
end
snippet.insert_nodes[0].next = current_node
start_node.prev = current_node.prev
current_node.prev = snippet.insert_nodes[0]
else
snippet.insert_nodes[0].next = current_node
-- jump into snippet directly.
current_node.inner_first = snippet
current_node.inner_last = snippet.insert_nodes[0]
start_node.prev = current_node
end
end
-- snippet is between i(-1)(startNode) and i(0).
snippet.next = snippet.insert_nodes[0]
snippet.prev = start_node
snippet.insert_nodes[0].prev = snippet
start_node.next = snippet
end
function Snippet:trigger_expand(current_node, pos)
-- expand tabs before indenting to keep indentstring unmodified
if vim.bo.expandtab then
self:expand_tabs(util.tab_width())
end
self:indent(util.line_chars_before(pos):match("^%s*"))
-- keep (possibly) user-set opts.
if not self.ext_opts then
-- if expanded outside another snippet use configs' ext_opts, if inside,
-- use those of that snippet and increase priority.
-- for now do a check for .indx, TODO: maybe only expand in insertNodes.
if current_node and (current_node.indx and current_node.indx > 1) then
self.ext_opts = util.increase_ext_prio(
vim.deepcopy(current_node.parent.ext_opts),
conf.config.ext_prio_increase
)
else
self.ext_opts = vim.deepcopy(conf.config.ext_opts)
end
end
self.env = Environ:new(pos)
self:subsnip_init()
self:init_positions({})
self:init_insert_positions({})
self:make_args_absolute()
self:set_dependents()
self:set_argnodes(self.dependents_dict)
-- at this point `stored` contains the snippetNodes that will actually
-- be used, indent them once here.
for _, node in pairs(self.stored) do
node:indent(self.indentstr)
end
local start_node = iNode.I(0)
local old_pos = vim.deepcopy(pos)
self:put_initial(pos)
-- update() may insert text, set marks appropriately.
local mark_opts = vim.tbl_extend("keep", {
right_gravity = false,
end_right_gravity = true,
}, self.ext_opts[types.snippet].passive)
self.mark = mark(old_pos, pos, mark_opts)
self:update()
self:update_all_dependents()
-- Marks should stay at the beginning of the snippet, only the first mark is needed.
start_node.mark = self.nodes[1].mark
start_node.pos = -1
start_node.parent = self
insert_into_jumplist(self, start_node, current_node)
end
-- returns copy of snip if it matches, nil if not.
function Snippet:matches(line_to_cursor)
local from
local match
local captures = {}
if self.regTrig then
-- capture entire trigger, must be put into match.
local find_res = { string.find(line_to_cursor, self.trigger .. "$") }
if #find_res > 0 then
from = find_res[1]
match = line_to_cursor:sub(from, #line_to_cursor)
for i = 3, #find_res do
captures[i - 2] = find_res[i]
end
end
else
if
line_to_cursor:sub(
#line_to_cursor - #self.trigger + 1,
#line_to_cursor
) == self.trigger
then
from = #line_to_cursor - #self.trigger + 1
match = self.trigger
end
end
-- Trigger or regex didn't match.
if not match then
return nil
end
if not self.condition(line_to_cursor, match, captures) then
return nil
end
-- if wordTrig is set, the char before the trigger can't be \w or the
-- word has to start at the beginning of the line.
if
self.wordTrig
and not (
from == 1
or string.match(
string.sub(line_to_cursor, from - 1, from - 1),
"[%w_]"
)
== nil
)
then
return nil
end
return { trigger = match, captures = captures }
end
function Snippet:enter_node(node_id)
if self.parent then
self.parent:enter_node(self.indx)
end
for i = 1, node_id - 1 do
self.nodes[i]:set_mark_rgrav(false, false)
end
local node = self.nodes[node_id]
node:set_mark_rgrav(
node.ext_gravities_active[1],
node.ext_gravities_active[2]
)
local _, node_to = node.mark:pos_begin_end_raw()
local i = node_id + 1
while i <= #self.nodes do
local other = self.nodes[i]
local other_from, other_to = other.mark:pos_begin_end_raw()
local end_equal = util.pos_equal(other_to, node_to)
other:set_mark_rgrav(util.pos_equal(other_from, node_to), end_equal)
i = i + 1
-- As soon as one end-mark wasn't equal, we no longer have to check as the
-- marks don't overlap.
if not end_equal then
break
end
end
while i <= #self.nodes do
self.nodes[i]:set_mark_rgrav(false, false)
i = i + 1
end
end
-- https://gist.github.com/tylerneylon/81333721109155b2d244
local function copy3(obj, seen)
-- Handle non-tables and previously-seen tables.
if type(obj) ~= "table" then
return obj
end
if seen and seen[obj] then
return seen[obj]
end
-- New table; mark it as seen an copy recursively.
local s = seen or {}
local res = {}
s[obj] = res
for k, v in next, obj do
res[copy3(k, s)] = copy3(v, s)
end
return setmetatable(res, getmetatable(obj))
end
function Snippet:copy()
return copy3(self)
end
function Snippet:set_text(node, text)
local node_from, node_to = node.mark:pos_begin_end_raw()
self:enter_node(node.indx)
local ok = pcall(
vim.api.nvim_buf_set_text,
0,
node_from[1],
node_from[2],
node_to[1],
node_to[2],
text
)
-- we can assume that (part of) the snippet was deleted; remove it from
-- the jumplist.
if not ok then
error("[LuaSnip Failed]: " .. vim.inspect(text))
end
end
function Snippet:del_marks()
for _, node in ipairs(self.nodes) do
vim.api.nvim_buf_del_extmark(0, session.ns_id, node.mark.id)
end
end
function Snippet:is_interactive()
for _, node in ipairs(self.nodes) do
-- return true if any node depends on another node or is an insertNode.
if
node.type == types.insertNode
or ((node.type == types.functionNode or node.type == types.dynamicNode) and #node.args ~= 0)
or node.type == types.choiceNode
then
return true
-- node is snippet, recurse.
elseif node.type == types.snippetNode then
return node:is_interactive()
end
end
return false
end
function Snippet:dump()
for i, node in ipairs(self.nodes) do
print(i)
print(node.mark.opts.right_gravity, node.mark.opts.end_right_gravity)
local from, to = node.mark:pos_begin_end()
print(from[1], from[2])
print(to[1], to[2])
end
end
function Snippet:put_initial(pos)
for _, node in ipairs(self.nodes) do
-- save pos to compare to later.
local old_pos = vim.deepcopy(pos)
node:put_initial(pos)
-- correctly set extmark for node.
-- does not modify ext_opts[node.type].
local mark_opts = vim.tbl_extend("keep", {
right_gravity = false,
end_right_gravity = false,
}, self.ext_opts[node.type].passive)
node.mark = mark(old_pos, pos, mark_opts)
end
self.visible = true
end
-- populate env,inden,captures,trigger(regex),... but don't put any text.
-- the env may be passed in opts via opts.env, if none is passed a new one is
-- generated.
function Snippet:fake_expand(opts)
if not opts then
opts = {}
end
-- set eg. env.TM_SELECTED_TEXT to $TM_SELECTED_TEXT
if opts.env then
self.env = opts.env
else
self.env = {}
setmetatable(self.env, {
__index = function(_, key)
return Environ.is_table(key) and { "$" .. key } or "$" .. key
end,
})
end
self.captures = {}
setmetatable(self.captures, {
__index = function(_, key)
return "$CAPTURE" .. tostring(key)
end,
})
if self.docTrig then
-- This fills captures[1] with docTrig if no capture groups are defined
-- and therefore slightly differs from normal expansion where it won't
-- be filled, but that's alright.
self.captures = { self.docTrig:match(self.trigger) }
self.trigger = self.docTrig
else
self.trigger = "$TRIGGER"
end
self.ext_opts = vim.deepcopy(conf.config.ext_opts)
self:indent("")
self:subsnip_init()
self:init_positions({})
self:init_insert_positions({})
self:make_args_absolute()
self:set_dependents()
self:set_argnodes(self.dependents_dict)
self:static_init()
-- no need for update_dependents_static, update_static alone will cause updates for all child-nodes.
self:update_static()
end
-- to work correctly, this may require that the snippets' env,indent,captures? are
-- set.
function Snippet:get_static_text()
if self.static_text then
return self.static_text
-- copy+fake_expand the snippet here instead of in whatever code needs to know the docstring.
elseif not self.ext_opts then
-- not a snippetNode and not yet initialized
local snipcop = self:copy()
-- sets env, captures, etc.
snipcop:fake_expand()
local static_text = snipcop:get_static_text()
self.static_text = static_text
return static_text
end
if not self.static_visible then
return nil
end
local text = { "" }
for _, node in ipairs(self.nodes) do
local node_text = node:get_static_text()
-- append first line to last line of text so far.
text[#text] = text[#text] .. node_text[1]
for i = 2, #node_text do
text[#text + 1] = node_text[i]
end
end
-- cache computed text, may be called multiple times for
-- function/dynamicNodes.
self.static_text = text
return text
end
function Snippet:get_docstring()
if self.docstring then
return self.docstring
-- copy+fake_expand the snippet here instead of in whatever code needs to know the docstring.
elseif not self.ext_opts then
-- not a snippetNode and not yet initialized
local snipcop = self:copy()
-- sets env, captures, etc.
snipcop:fake_expand()
local docstring = snipcop:get_docstring()
self.docstring = docstring
return docstring
end
local docstring = { "" }
for _, node in ipairs(self.nodes) do
local node_text = node:get_docstring()
-- append first line to last line of text so far.
docstring[#docstring] = docstring[#docstring] .. node_text[1]
for i = 2, #node_text do
docstring[#docstring + 1] = node_text[i]
end
end
-- cache computed text, may be called multiple times for
-- function/dynamicNodes.
-- if not outer snippet, wrap it in ${}.
self.docstring = self.type == types.snippet and docstring
or util.string_wrap(docstring, rawget(self, "pos"))
return self.docstring
end
function Snippet:update()
for _, node in ipairs(self.nodes) do
node:update()
end
end
function Snippet:update_static()
for _, node in ipairs(self.nodes) do
node:update_static()
end
end
function Snippet:update_restore()
for _, node in ipairs(self.nodes) do
node:update_restore()
end
end
function Snippet:store()
for _, node in ipairs(self.nodes) do
node:store()
end
end
function Snippet:indent(prefix)
self.indentstr = prefix
for _, node in ipairs(self.nodes) do
node:indent(prefix)
end
end
function Snippet:expand_tabs(tabwidth)
for _, node in ipairs(self.nodes) do
node:expand_tabs(tabwidth)
end
end
function Snippet:subsnip_init()
node_util.subsnip_init_children(self, self.nodes)
end
Snippet.init_positions = node_util.init_child_positions_func(
"absolute_position",
"nodes",
"init_positions"
)
Snippet.init_insert_positions = node_util.init_child_positions_func(
"absolute_insert_position",
"insert_nodes",
"init_insert_positions"
)
function Snippet:make_args_absolute()
for _, node in ipairs(self.nodes) do
node:make_args_absolute(self.absolute_insert_position)
end
end
function Snippet:input_enter()
self.active = true
if self.type == types.snippet then
self:set_ext_opts("passive")
end
self.mark:update_opts(self.ext_opts[self.type].active)
self:event(events.enter)
end
function Snippet:input_leave()
self:event(events.leave)
self:update_dependents()
self.mark:update_opts(self.ext_opts[self.type].passive)
if self.type == types.snippet then
self:set_ext_opts("snippet_passive")
end
self.active = false
end
function Snippet:set_ext_opts(opt_name)
for _, node in ipairs(self.nodes) do
node:set_ext_opts(opt_name)
end
end
function Snippet:jump_into(dir, no_move)
if self.active then
self:input_leave()
if dir == 1 then
return self.next:jump_into(dir, no_move)
else
return self.prev:jump_into(dir, no_move)
end
else
self:input_enter()
if dir == 1 then
return self.inner_first:jump_into(dir, no_move)
else
return self.inner_last:jump_into(dir, no_move)
end
end
end
-- Snippets inherit Node:jump_from, it shouldn't occur normally, but may be
-- used in LSP-Placeholders.
function Snippet:exit()
self.visible = false
for _, node in ipairs(self.nodes) do
node:exit()
end
self.mark:clear()
self.active = false
end
function Snippet:set_mark_rgrav(val_begin, val_end)
-- set own markers.
node_mod.Node.set_mark_rgrav(self, val_begin, val_end)
local snip_pos_begin, snip_pos_end = self.mark:pos_begin_end_raw()
if
snip_pos_begin[1] == snip_pos_end[1]
and snip_pos_begin[2] == snip_pos_end[2]
then
for _, node in ipairs(self.nodes) do
node:set_mark_rgrav(val_begin, val_end)
end
return
end
local node_indx = 1
-- the first node starts at begin-mark.
local node_on_begin_mark = true
-- only change gravities on nodes that absolutely have to.
while node_on_begin_mark do
-- will be set later if the next node has to be updated as well.
node_on_begin_mark = false
local node = self.nodes[node_indx]
if not node then
break
end
local node_pos_begin, node_pos_end = node.mark:pos_begin_end_raw()
-- use false, false as default, this is what most nodes will be set to.
local new_rgrav_begin, new_rgrav_end =
node.mark.opts.right_gravity, node.mark.opts.end_right_gravity
if
node_pos_begin[1] == snip_pos_begin[1]
and node_pos_begin[2] == snip_pos_begin[2]
then
new_rgrav_begin = val_begin
if
node_pos_end[1] == snip_pos_begin[1]
and node_pos_end[2] == snip_pos_begin[2]
then
new_rgrav_end = val_begin
-- both marks of this node were on the beginning of the snippet
-- so this has to be checked again for the next node.
node_on_begin_mark = true
node_indx = node_indx + 1
end
end
node:set_mark_rgrav(new_rgrav_begin, new_rgrav_end)
end
-- the first node starts at begin-mark.
local node_on_end_mark = true
node_indx = #self.nodes
while node_on_end_mark do
local node = self.nodes[node_indx]
if not node then
break
end
local node_pos_begin, node_pos_end = node.mark:pos_begin_end_raw()
-- will be set later if the next node has to be updated as well.
node_on_end_mark = false
-- use false, false as default, this is what most nodes will be set to.
local new_rgrav_begin, new_rgrav_end =
node.mark.opts.right_gravity, node.mark.opts.end_right_gravity
if
node_pos_end[1] == snip_pos_end[1]
and node_pos_end[2] == snip_pos_end[2]
then
new_rgrav_end = val_end
if
node_pos_begin[1] == snip_pos_end[1]
and node_pos_begin[2] == snip_pos_end[2]
then
new_rgrav_begin = val_end
-- both marks of this node were on the end-mark of the snippet
-- so this has to be checked again for the next node.
node_on_end_mark = true
node_indx = node_indx - 1
end
end
node:set_mark_rgrav(new_rgrav_begin, new_rgrav_end)
end
end
function Snippet:text_only()
for _, node in ipairs(self.nodes) do
if node.type ~= types.textNode then
return false
end
end
return true
end
function Snippet:event(event)
local callback = self.callbacks[-1][event]
if callback then
callback(self)
end
if self.type == types.snippetNode and self.pos then
-- if snippetNode, also do callback for position in parent.
callback = self.parent.callbacks[self.pos][event]
if callback then
callback(self)
end
end
session.event_node = self
vim.cmd("doautocmd User Luasnip" .. events.to_string(self.type, event))
end
local function nodes_from_pattern(pattern)
local nodes = {}
local text_active = true
local iNode_indx = 1
local tokens = pattern_tokenizer.tokenize(pattern)
for _, text in ipairs(tokens) do
if text_active then
nodes[#nodes + 1] = tNode.T(text)
else
nodes[#nodes + 1] = iNode.I(iNode_indx, text)
iNode_indx = iNode_indx + 1
end
text_active = not text_active
end
-- This is done so the user ends up at the end of the snippet either way
-- and may use their regular expand-key to expand the snippet.
-- Autoexpanding doesn't quite work, if the snippet ends with an
-- interactive part and the user overrides whatever is put in there, the
-- jump to the i(0) may trigger an expansion, and the helper-snippet could
-- not easily be removed, as the snippet the user wants to actually use is
-- inside of it.
-- Because of that it is easier to let the user do the actual expanding,
-- but help them on the way to it (by providing an easy way to override the
-- "interactive" parts of the pattern-trigger).
--
-- if even number of nodes, the last is an insertNode (nodes begins with
-- textNode and alternates between the two).
if #nodes % 2 == 0 then
nodes[#nodes] = iNode.I(0, tokens[#tokens])
else
nodes[#nodes + 1] = iNode.I(0)
end
return nodes
end
-- only call on actual snippets, snippetNodes don't have trigger.
function Snippet:get_pattern_expand_helper()
if not self.expand_helper_snippet then
local nodes = nodes_from_pattern(self.trigger)
self.expand_helper_snippet = S(self.trigger, nodes, {
callbacks = {
[0] = {
[events.enter] = function(_)
vim.schedule(function()
-- Remove this helper snippet as soon as the i(0)
-- is reached.
require("luasnip").unlink_current()
end)
end,
},
},
})
end
-- will be copied in actual expand.
return self.expand_helper_snippet
end
function Snippet:find_node(predicate)
for _, node in ipairs(self.nodes) do
if predicate(node) then
return node
else
local node_in_child = node:find_node(predicate)
if node_in_child then
return node_in_child
end
end
end
return nil
end
function Snippet:insert_to_node_absolute(position)
if #position == 0 then
return self.absolute_position
end
local insert_indx = util.pop_front(position)
return self.insert_nodes[insert_indx]:insert_to_node_absolute(position)
end
function Snippet:set_dependents()
for _, node in ipairs(self.nodes) do
node:set_dependents()
end
end
function Snippet:set_argnodes(dict)
node_mod.Node.set_argnodes(self, dict)
for _, node in ipairs(self.nodes) do
node:set_argnodes(dict)
end
end
function Snippet:update_all_dependents()
-- call the version that only updates this node.
self:_update_dependents()
-- only for insertnodes, others will not have dependents.
for _, node in ipairs(self.insert_nodes) do
node:update_all_dependents()
end
end
function Snippet:update_all_dependents_static()
-- call the version that only updates this node.
self:_update_dependents_static()
-- only for insertnodes, others will not have dependents.
for _, node in ipairs(self.insert_nodes) do
node:update_all_dependents_static()
end
end
function Snippet:resolve_position(position)
return self.nodes[position]
end
function Snippet:static_init()
node_mod.Node.static_init(self)
for _, node in ipairs(self.nodes) do
node:static_init()
end
end
return {
Snippet = Snippet,
S = S,
SN = SN,
P = P,
ISN = ISN,
wrap_nodes_in_snippetNode = wrap_nodes_in_snippetNode,
}
|
--First get the transaction number that is currently being processed and save to the tn variable
local tn = GetFieldValue("Transaction", "TransactionNumber");
--Execute the AddNote command.
ExecuteCommand("AddNote", {tn, "Sample Note"});
|
local lunit = require "luaunit"
local physfs = require "physfs"
local eq = lunit.assert_equals
local match = lunit.assert_str_matches
local fail = lunit.assert_error_msg_matches
print("version: ", physfs.version())
print("types: " .. #assert(physfs.supportedArchiveTypes()))
print("cdRom: " .. #assert(physfs.cdRomDirs()))
print("files: " .. #assert(physfs.files "/"))
function _G.testBaseInfo()
print("baseDir: " .. assert(physfs.baseDir))
assert(physfs.mount ".")
eq(physfs.mountPoint ".", "/")
eq(#physfs.searchPath(), 1)
assert(physfs.unmount ".")
eq(physfs.mountPoint ".", nil)
eq(#physfs.searchPath(), 0)
assert(physfs.mount ".")
local dir = assert(physfs.prefDir("github", "starwing"))
match(dir, ".-starwing.*")
assert(physfs.saneConfig("github", "starwing"))
match(physfs.writeDir(), ".-starwing.*")
assert(physfs.unmount(dir))
local useSymlink = physfs.useSymlink()
physfs.useSymlink(true)
physfs.useSymlink(useSymlink)
physfs.lastError "OUT_OF_MEMORY"
eq(physfs.lastError(), "OUT_OF_MEMORY")
physfs.lastError "OK"
assert(physfs.writeDir ".")
match(physfs.writeDir(), "%.")
end
function _G.testFile()
local fh = assert(physfs.openWrite "_test_file")
assert(#fh == 0)
eq(fh:eof(), false) -- only openRead could return true
fail("read: file open for writing", assert, fh:read())
assert(fh:write())
assert(fh:write("foobar"))
fail("bad argument #2 to.-%(invalid empty format.*", fh.writeInt, fh, "")
fail(".-invalid format char 'z'.*", fh.writeInt, fh, "z<z4ziz")
fail(".-invalid format char 'z'.*", fh.writeInt, fh, "<z4ziz")
fail(".-invalid format char 'z'.*", fh.writeInt, fh, "<4ziz")
fail(".-invalid format char 'z'.*", fh.writeInt, fh, "<4iz")
local fmts = {}
local piece = {
l0 = "", l1 = "<", l2 = ">",
w0 = "", w1 = "1", w2 = "2", w3 = "4", w4 = "8",
s1 = "i", s2 = "u"
}
for little = 0, 2 do
for wide = 0, 4 do
for sig = 1, 2 do
fmts[#fmts+1] = piece["l"..little]..piece["w"..wide]..piece["s"..sig]
end
end
end
for _, fmt in ipairs(fmts) do
assert(fh:writeInt(fmt, 1,2,3,4))
end
assert(fh:flush())
eq(fh.__tostring(1), nil)
match(tostring(fh), "physfs.File: 0x%x+")
assert(fh:close())
match(tostring(fh), "physfs.File: %(null%)")
local stat = assert(physfs.stat "_test_file")
eq(stat.size, 462)
eq(stat.type, "file")
eq(stat.readonly, false)
fh = assert(physfs.openRead "_test_file")
assert(fh:buffSize(1024))
assert(#fh == 462)
assert(fh:length() == 462)
eq(fh:eof(), false)
eq(fh:tell(), 0)
eq(#assert(fh:read()), 462)
eq(fh:eof(), true)
eq(fh:tell(), 462)
assert(fh:seek(0))
eq(fh:tell(), 0)
assert(fh:write())
fail(".-file open for reading", assert, fh:write "")
eq(assert(fh:read(6)), "foobar")
assert(fh:seek(0))
eq(assert(fh:read(6)), "foobar")
assert(fh:tell(), 6)
for _, fmt in ipairs(fmts) do
local a, b, c, d, e = fh:read(fmt, fmt, fmt, fmt)
eq(a, 1); eq(b, 2); eq(c, 3); eq(d, 4); eq(e, nil)
end
assert(fh:close())
assert(physfs.exists "_test_file")
eq(physfs.realDir "_test_file", ".")
assert(physfs.delete "_test_file")
assert(not physfs.exists "_test_file")
end
function _G.testDir()
assert(physfs.mkdir "_test_dir")
eq(physfs.stat "_test_dir".type, "dir")
assert(physfs.mkdir "_test_dir/a")
assert(physfs.mkdir "_test_dir/b")
assert(physfs.mkdir "_test_dir/c")
assert(physfs.delete "_test_dir/c")
assert(physfs.delete "_test_dir/b")
assert(physfs.delete "_test_dir/a")
assert(physfs.delete "_test_dir")
end
function _G.testConv()
eq(physfs.convInt("<1i", 4), 4)
eq(physfs.convInt("<2i", 4), 4)
eq(physfs.convInt("<4i", 4), 4)
eq(physfs.convInt("<8i", 4), 4)
eq(physfs.convInt(">1i", 4), 4)
eq(physfs.convInt(">2i", 4), 0x0400)
eq(physfs.convInt(">4i", 4), 0x04000000)
eq(physfs.convInt(">8i", 4), 0x0400000000000000)
eq(physfs.convInt("<1u", 4), 4)
eq(physfs.convInt("<2u", 4), 4)
eq(physfs.convInt("<4u", 4), 4)
eq(physfs.convInt("<8u", 4), 4)
eq(physfs.convInt(">1u", 4), 4)
eq(physfs.convInt(">2u", 4), 0x0400)
eq(physfs.convInt(">4u", 4), 0x04000000)
eq(physfs.convInt(">8u", 4), 0x0400000000000000)
end
function _G.testLoader()
fail(".-physfs search path.*", require, "foobar")
local function test_mod(m)
eq(m.info(), "this is a test module from physfs")
eq(m.add(1,2), 3)
end
assert(physfs.mount "test_mod.zip")
test_mod(require "test_mod")
local fh = assert(physfs.openRead "test_mod.zip")
match(tostring(fh), "physfs.File: 0x%x+")
local fh2 = assert(physfs.mountFile(fh, nil, "test2"))
eq(fh, fh2)
match(tostring(fh), "physfs.File: %(null%)")
-- NOTICE there is a bug, if not given name to mount(File|Memory),
-- physfs libary has several bugs about exists and searchPath.
-- eq(physfs.exists("test2/test_mod.lua"), true) -- fail
test_mod(require "test2.test_mod")
fh = assert(physfs.openRead "test_mod.zip")
local content = assert(fh:read())
eq(#content, #fh)
assert(fh:close())
assert(physfs.mountMemory(content, nil, "test3"))
test_mod(require "test3.test_mod")
end
os.exit(lunit.LuaUnit.run(), true)
|
-- Inofficial Stripe Extension (www.stripe.com) for MoneyMoney
-- Fetches balances from Stripe API and returns them as transactions
--
-- Password: Stripe Secret API Key
--
-- Copyright (c) 2018 Nico Lindemann
--
-- 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.
WebBanking{version = 1.1,
url = "https://api.stripe.com/",
services = {"Stripe Account"},
description = "Fetches balances from Stripe API and returns them as transactions"}
local apiSecret
local account
local apiUrlVersion = "v1"
function SupportsBank (protocol, bankCode)
return protocol == ProtocolWebBanking and bankCode == "Stripe Account"
end
function InitializeSession (protocol, bankCode, username, username2, password, username3)
account = username
apiSecret = password
end
function ListAccounts (knownAccounts)
local account = {
name = "Stripe Account",
accountNumber = account,
type = AccountTypeGiro
}
return {account}
end
function RefreshAccount (account, since)
return {balances=GetBalances(), transactions=GetTransactions(since)}
end
function StripeRequest (endPoint)
local headers = {}
headers["Authorization"] = "Bearer " .. apiSecret
headers["Accept"] = "application/json"
connection = Connection()
content = connection:request("GET", url .. apiUrlVersion .. "/" .. endPoint, nil, nil, headers)
json = JSON(content)
return json
end
function GetBalances ()
local balances = {}
stripeBalances = StripeRequest("balance"):dictionary()["available"]
for key, value in pairs(stripeBalances) do
local balance = {}
balance[1] = (value["amount"] / 100)
balance[2] = string.upper(value["currency"])
balances[#balances+1] = balance
end
return balances
end
function GetTransactions (since)
local transactions = {}
local lastTransaction = nil
local moreItemsAvailable
local requestString
repeat
if lastTransaction == nil then
requestString = "balance_transactions?limit=100&created[gt]=" .. since
else
requestString = "balance_transactions?limit=100&created[gt]=" .. since .. "&starting_after=" .. lastTransaction
end
stripeObject = StripeRequest(requestString):dictionary()
moreItemsAvailable = stripeObject["has_more"]
for key, value in pairs(stripeObject["data"]) do
lastTransaction = value["id"]
purpose = value["type"]
if value["description"] then
purpose = purpose .. "\n" .. value["description"]
end
if value["fee"] == 0 then
transactions[#transactions+1] = {
bookingDate = value["created"],
valueDate = value["available_on"],
purpose = purpose,
endToEndReference = value["source"],
amount = (value["amount"] / 100),
currency = string.upper(value["currency"])
}
else
for feeKey, feeValue in pairs(value["fee_details"]) do
transactions[#transactions+1] = {
bookingDate = value["created"],
valueDate = value["available_on"],
purpose = feeValue["type"] .. "\n" .. feeValue["description"],
amount = (feeValue["amount"] / 100) * -1,
currency = string.upper(feeValue["currency"])
}
end
transactions[#transactions+1] = {
bookingDate = value["created"],
valueDate = value["available_on"],
purpose = purpose,
endToEndReference = value["source"],
amount = (value["amount"] / 100),
currency = string.upper(value["currency"])
}
end
end
until(not moreItemsAvailable)
return transactions
end
function EndSession ()
-- Logout.
end
|
--- === cp.rx.Subject ===
---
--- `Subjects` function both as an [Observer](cp.rs.Observer.md) and as an [Observable](cp.rx.Observable.md). Subjects inherit all
--- `Observable` functions, including [subscribe](#subscribe). Values can also be pushed to the `Subject`, which will
--- be broadcasted to any subscribed [Observers](cp.rx.Observers.md).
local require = require
local insert = table.insert
local remove = table.remove
local Observable = require "cp.rx.Observable"
local Observer = require "cp.rx.Observer"
local Reference = require "cp.rx.Reference"
local util = require "cp.rx.util"
local Subject = setmetatable({}, Observable)
Subject.__index = Subject
Subject.__tostring = util.constant('Subject')
--- cp.rx.Subject.create() -> cp.rx.Subject
--- Constructor
--- Creates a new Subject.
--- Returns:
--- * The `Subject`.
function Subject.create()
local self = {
observers = {},
stopped = false
}
return setmetatable(self, Subject)
end
--- cp.rx.Subject:subscribe(onNext[, onError[, onCompleted]]) -> cp.rx.Reference
--- Method
--- Creates a new [Observer](cp.rx.Observer.md) and attaches it to the Subject.
---
--- Parameters:
--- * observer | onNext - Either an [Observer](cp.rx.Observer.md), or a `function` called
--- when the `Subject` produces a value.
--- * onError - A `function` called when the `Subject` terminates due to an error.
--- * onCompleted - A `function` called when the `Subject` completes normally.
---
--- Returns:
--- * The [Reference](cp.rx.Reference.md)
function Subject:subscribe(onNext, onError, onCompleted)
local observer
if util.isa(onNext, Observer) then
observer = onNext
else
observer = Observer.create(onNext, onError, onCompleted)
end
if self.stopped then
observer:onError("Subject has already stopped.")
return Reference.create(util.noop)
end
insert(self.observers, observer)
return Reference.create(function()
if not self.stopping then
for i = 1, #self.observers do
if self.observers[i] == observer then
remove(self.observers, i)
return
end
end
end
end)
end
-- cp.rx.Subject:_stop() -> nil
-- Method
-- Stops future signals from being sent, and unsubscribes any observers.
function Subject:_stop()
self.stopped = true
self.observers = {}
end
--- cp.rx.Subject:onNext(...) -> nil
--- Method
--- Pushes zero or more values to the `Subject`. They will be broadcasted to all [Observers](cp.rx.Observer.md).
---
--- Parameters:
--- * ... - The values to send.
function Subject:onNext(...)
if not self.stopped then
local observer
for i = 1, #self.observers do
observer = self.observers[i]
if observer then observer:onNext(...) end
end
end
end
--- cp.rx.Subject:onError(message) -> nil
--- Method
--- Signal to all `Observers` that an error has occurred.
---
--- Parameters:
--- * message - A string describing what went wrong.
function Subject:onError(message)
if not self.stopped then
self.stopping = true
local observer
for i = 1, #self.observers do
observer = self.observers[i]
if observer then observer:onError(message) end
end
self.stopping = true
self:_stop()
end
end
--- cp.rx.Subject:onCompleted() -> nil
--- Method
--- Signal to all [Observers](cp.rx.Observer.md) that the `Subject` will not produce any more values.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function Subject:onCompleted()
if not self.stopped then
self.stopping = true
local observer
for i = 1, #self.observers do
observer = self.observers[i]
if observer then observer:onCompleted() end
end
self.stopping = true
self:_stop()
end
end
Subject.__call = Subject.onNext
return Subject |
-- -*- lua -*-
whatis("Name: FOAM-extend Metamodule")
whatis("Version: 4.0")
whatis("Description: Metamodule for FOAM-extend 4.0 (Optimized)")
if (mode() == "load") then
load("gcc/6.3.0", "openmpi/2.1.0", "FOAM-extend/4.0")
else
load("FOAM-extend/4.0", "openmpi/2.1.0", "gcc/6.3.0")
end
|
--Created by Alex Crowley
--On August 21, 2016
--Copyright (c) 2016, TBD
--Licensed under the MIT license
--See LICENSE file for terms
function quicktype(types)
local type = types[#types].val types[#types] = nil
local t = {type = "quicktypes"}
for _,v in ipairs(types) do
v.type = type
table.insert(t, {name = v.val, ctype = type})
end
return t
end
function functionparams(params)
params = params or {}
local t = {}
for _, v in ipairs(params) do
if v.type == "quicktypes" then
appendTable(t, v)
else
table.insert(t, v)
end
end
return t
end
function noreturnhandle(name, params, returns, body)
if body == nil then
body = returns
returns = {}
end
return {type = "function", name = name.val, params = params, returns = returns, body = body} end
function node(p)
return p / function(left, op, right)
return { type = "operation", operator = op, left = left, right = right }
end
end |
------------------------------------------------------------------------------------------
-- SNS-HDR Lightroom Plugin
-- http://github.com/michaelkoetter/snshdr_lightroom
--
-- Copyright (c) 2012 Michael Kötter
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. The name of the author may not be used to endorse or promote products
-- derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-- OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-- IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
-- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-- NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------------------
local LrDialogs = import 'LrDialogs'
local LrFileUtils = import 'LrFileUtils'
local LrPathUtils = import 'LrPathUtils'
local LrTasks = import 'LrTasks'
local LrFunctionContext = import 'LrFunctionContext'
local LrProgressScope = import 'LrProgressScope'
local LrExportSettings = import 'LrExportSettings'
local SNSHDRProcess = {}
function SNSHDRProcess.createPostProcessCommand( renditionDir )
local postProcessCommand = LrPathUtils.child( renditionDir, "snshdr_callback.bat" )
local callbackFile = LrPathUtils.child( renditionDir, ".snshdr_callback" )
local f = assert(io.open( postProcessCommand, "w" ))
f:write("ECHO %1 > " .. callbackFile)
f:close()
return postProcessCommand, callbackFile
end
function SNSHDRProcess.getProcessedImage( functionContext, callbackFile )
local progress = LrProgressScope({
title = LOC "$$$/SNSHDR/Export/WaitingForProcessedImage=Waiting for HDR image...",
functionContext = functionContext
})
-- wait for the callback file to appear
repeat
LrTasks.sleep( 1 )
if progress:isCanceled() then
break
end
until LrFileUtils.exists( callbackFile )
if LrFileUtils.exists( callbackFile ) then
-- read filename from callback file
local f = assert(io.open( callbackFile, "r" ))
local processedImage = f:read("*line")
-- file name is enclosed in parentheses & contains line break
return string.sub(processedImage, 2, -3)
end
end
function SNSHDRProcess.getOutputFile( renditionFile, numRenditions, format )
local prefix = LrPathUtils.removeExtension( renditionFile )
local extension
if format == 'jpeg' then
extension = LrExportSettings.extensionForFormat( 'JPEG' )
else
extension = LrExportSettings.extensionForFormat( 'TIFF' )
end
return prefix .. '_SNSHDR_' .. numRenditions .. '.' .. extension
end
function SNSHDRProcess.processExport( exportContext )
local exportSession = exportContext.exportSession
local exportSettings = assert( exportContext.propertyTable )
local nPhotos = exportSession:countRenditions()
local progress = exportContext:configureProgress({
title = LOC("$$$/SNSHDR/Export/Progress=Exporting ^1 photos", nPhotos)
})
local callbackFile
local postProcessCommand
-- collect rendered files...
local renditionDir
local renditionFile
local sourceDir
local files = ""
for i, rendition in exportContext:renditions() do
renditionDir = LrPathUtils.parent( rendition.destinationPath )
renditionFile = rendition.destinationPath
sourceDir = LrPathUtils.parent( rendition.photo:getRawMetadata('path') )
if not rendition.wasSkipped then
files = files .. ' "' .. rendition.destinationPath .. '"'
rendition:waitForRender()
else
-- use source (original) images if rendition was skipped
files = files .. ' "' .. rendition.photo:getRawMetadata( 'path' ) .. '"'
end
end
if progress:isCanceled() then
return
end
-- Build the commandline ...
local cmd = '"' .. exportSettings.application .. '"'
if WIN_ENV == true then
-- open the command in a visible window
cmd = 'START "SNS-HDR" ' .. cmd
end
-- currently, only the "Lite" version accepts these commandline options
if exportSettings.enable_lite_options then
if not exportSettings.alignment then
cmd = cmd .. ' -da'
end
if not exportSettings.deghosting then
cmd = cmd .. ' -dd'
end
if exportSettings.panorama_mode then
cmd = cmd .. ' -pm'
end
cmd = cmd .. ' -' .. exportSettings.size
cmd = cmd .. ' -' .. exportSettings.preset
end
-- all version support the following options
if exportSettings.srgb then
cmd = cmd .. ' -srgb'
end
cmd = cmd .. ' -' .. exportSettings.output_format
-- specify output file
cmd = cmd .. ' -o "' .. SNSHDRProcess.getOutputFile( renditionFile, nPhotos, exportSettings.output_format ) .. '"'
-- create & append callback script
postProcessCommand, callbackFile = SNSHDRProcess.createPostProcessCommand( renditionDir );
cmd = cmd .. ' -ee "' .. postProcessCommand .. '"'
-- append rendered files
cmd = cmd .. files
-- LrDialogs.message( "Command", cmd )
-- execute the actual command
if LrTasks.execute( cmd ) ~= 0 then
LrDialogs.message( LOC "$$$/SNSHDR/Error=Error",
LOC "$$$/SNSHDR/Export/ErrorExecutingCommand=Error executing SNS-HDR command!" )
end
progress:done()
if callbackFile ~= nil then
-- wait for the callback file / processed image to appear
local processedImage = LrFunctionContext.callWithContext(
"getProcessedImage",
SNSHDRProcess.getProcessedImage,
callbackFile )
if processedImage ~= nil then
-- move the processed image to the source image directory
local destination = LrPathUtils.child( sourceDir, LrPathUtils.leafName( processedImage ) )
destination = LrFileUtils.chooseUniqueFileName( destination )
LrFileUtils.move( processedImage, destination )
-- import it?
if exportSettings.reimport then
exportSession.catalog:withWriteAccessDo( LOC "$$$/SNSHDR/Export/Import=Import tonemapped file",
function()
exportSession.catalog:addPhoto( destination )
end )
end
end
end
end
return SNSHDRProcess |
-----------------------------------------
-- ID: 5487
-- Ranger Die
-- Teaches the job ability Hunter's Roll
-----------------------------------------
function onItemCheck(target)
return target:canLearnAbility(92)
end
function onItemUse(target)
target:addLearnedAbility(92)
end
|
require("gitsigns").setup {
signs = {
add = { hl = "GitSignsAdd", text = "▍", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn" },
change = {
hl = "GitSignsChange",
text = "▍",
numhl = "GitSignsChangeNr",
linehl = "GitSignsChangeLn",
},
delete = {
hl = "GitSignsDelete",
text = "▸",
numhl = "GitSignsDeleteNr",
linehl = "GitSignsDeleteLn",
},
topdelete = {
hl = "GitSignsDelete",
text = "▾",
numhl = "GitSignsDeleteNr",
linehl = "GitSignsDeleteLn",
},
changedelete = {
hl = "GitSignsChange",
text = "▍",
numhl = "GitSignsChangeNr",
linehl = "GitSignsChangeLn",
},
},
keymaps = {
-- Default keymap options
noremap = true,
buffer = true,
["n ]c"] = { expr = true, "&diff ? ']c' : '<cmd>lua require\"gitsigns\".next_hunk()<CR>'" },
["n [c"] = { expr = true, "&diff ? '[c' : '<cmd>lua require\"gitsigns\".prev_hunk()<CR>'" },
-- Text objects
["o ih"] = ':<C-U>lua require"gitsigns".select_hunk()<CR>',
["x ih"] = ':<C-U>lua require"gitsigns".select_hunk()<CR>',
},
}
|
local json = require('json')
local timer = require('timer')
local http = require('coro-http')
local package = require('../../package.lua')
local Mutex = require('utils/Mutex')
local endpoints = require('endpoints')
local request = http.request
local f, gsub, byte = string.format, string.gsub, string.byte
local max, random = math.max, math.random
local encode, decode, null = json.encode, json.decode, json.null
local insert, concat = table.insert, table.concat
local sleep = timer.sleep
local running = coroutine.running
local BASE_URL = "https://discordapp.com/api/v7"
local JSON = 'application/json'
local PRECISION = 'millisecond'
local MULTIPART = 'multipart/form-data;boundary='
local USER_AGENT = f('DiscordBot (%s, %s)', package.homepage, package.version)
local majorRoutes = {guilds = true, channels = true, webhooks = true}
local payloadRequired = {PUT = true, PATCH = true, POST = true}
local function parseErrors(ret, errors, key)
for k, v in pairs(errors) do
if k == '_errors' then
for _, err in ipairs(v) do
insert(ret, f('%s in %s : %s', err.code, key or 'payload', err.message))
end
else
if key then
parseErrors(ret, v, f(k:find("^[%a_][%a%d_]*$") and '%s.%s' or tonumber(k) and '%s[%d]' or '%s[%q]', key, k))
else
parseErrors(ret, v, k)
end
end
end
return concat(ret, '\n\t')
end
local function sub(path)
return not majorRoutes[path] and path .. '/:id'
end
local function route(method, endpoint)
-- special case for reactions
if endpoint:find('reactions') then
endpoint = endpoint:match('.*/reactions')
end
-- remove the ID from minor routes
endpoint = endpoint:gsub('(%a+)/%d+', sub)
-- special case for message deletions
if method == 'DELETE' then
local i, j = endpoint:find('/channels/%d+/messages')
if i == 1 and j == #endpoint then
endpoint = method .. endpoint
end
end
return endpoint
end
local function generateBoundary(files, boundary)
boundary = boundary or tostring(random(0, 9))
for _, v in ipairs(files) do
if v[2]:find(boundary, 1, true) then
return generateBoundary(files, boundary .. random(0, 9))
end
end
return boundary
end
local function attachFiles(payload, files)
local boundary = generateBoundary(files)
local ret = {
'--' .. boundary,
'Content-Disposition:form-data;name="payload_json"',
'Content-Type:application/json\r\n',
payload,
}
for i, v in ipairs(files) do
insert(ret, '--' .. boundary)
insert(ret, f('Content-Disposition:form-data;name="file%i";filename=%q', i, v[1]))
insert(ret, 'Content-Type:application/octet-stream\r\n')
insert(ret, v[2])
end
insert(ret, '--' .. boundary .. '--')
return concat(ret, '\r\n'), boundary
end
local mutexMeta = {
__mode = 'v',
__index = function(self, k)
self[k] = Mutex()
return self[k]
end
}
local function tohex(char)
return f('%%%02X', byte(char))
end
local function urlencode(obj)
return (gsub(tostring(obj), '%W', tohex))
end
local API = require('class')('API')
function API:__init(client)
self._client = client
self._mutexes = setmetatable({}, mutexMeta)
end
function API:authenticate(token)
self._token = token
return self:getCurrentUser()
end
function API:request(method, endpoint, payload, query, files)
local _, main = running()
if main then
return error('Cannot make HTTP request outside of a coroutine', 2)
end
local url = BASE_URL .. endpoint
if query and next(query) then
url = {url}
for k, v in pairs(query) do
insert(url, #url == 1 and '?' or '&')
insert(url, urlencode(k))
insert(url, '=')
insert(url, urlencode(v))
end
url = concat(url)
end
local req = {
{'User-Agent', USER_AGENT},
{'X-RateLimit-Precision', PRECISION},
{'Authorization', self._token},
}
if payloadRequired[method] then
payload = payload and encode(payload) or '{}'
if files and next(files) then
local boundary
payload, boundary = attachFiles(payload, files)
insert(req, {'Content-Type', MULTIPART .. boundary})
else
insert(req, {'Content-Type', JSON})
end
insert(req, {'Content-Length', #payload})
end
local mutex = self._mutexes[route(method, endpoint)]
mutex:lock()
local data, err, delay = self:commit(method, url, req, payload, 0)
mutex:unlockAfter(delay)
if data then
return data
else
return nil, err
end
end
function API:commit(method, url, req, payload, retries)
local client = self._client
local options = client._options
local delay = options.routeDelay
local success, res, msg = pcall(request, method, url, req, payload)
if not success then
return nil, res, delay
end
for i, v in ipairs(res) do
res[v[1]] = v[2]
res[i] = nil
end
if res['X-RateLimit-Remaining'] == '0' then
delay = max(1000 * res['X-RateLimit-Reset-After'], delay)
end
local data = res['Content-Type'] == JSON and decode(msg, 1, null) or msg
if res.code < 300 then
client:debug('%i - %s : %s %s', res.code, res.reason, method, url)
return data, nil, delay
else
if type(data) == 'table' then
local retry
if res.code == 429 then -- TODO: global ratelimiting
delay = data.retry_after
retry = retries < options.maxRetries
elseif res.code == 502 then
delay = delay + random(2000)
retry = retries < options.maxRetries
end
if retry then
client:warning('%i - %s : retrying after %i ms : %s %s', res.code, res.reason, delay, method, url)
sleep(delay)
return self:commit(method, url, req, payload, retries + 1)
end
if data.code and data.message then
msg = f('HTTP Error %i : %s', data.code, data.message)
else
msg = 'HTTP Error'
end
if data.errors then
msg = parseErrors({msg}, data.errors)
end
end
if payload then
payloadjson = json.encode(payload)
local err = "Unknown"
if payload.content and #payload.content > 2000 then
err = "Content in message is over 2000!\n"
elseif payloadjson == '"[]"' or payloadjson == '"[]"'then
err = "Payload is empty!"
end
else
err = "Payload is empty!"
end
client:error('%i - %s : %s, %s %s Payload: %s', res.code, res.reason,err , method, url,payloadjson)
return nil, msg, delay
end
end
-- start of auto-generated methods --
function API:getGuildAuditLog(guild_id, query)
local endpoint = f(endpoints.GUILD_AUDIT_LOGS, guild_id)
return self:request("GET", endpoint, nil, query)
end
function API:getChannel(channel_id) -- not exposed, use cache
local endpoint = f(endpoints.CHANNEL, channel_id)
return self:request("GET", endpoint)
end
function API:modifyChannel(channel_id, payload) -- Channel:_modify
local endpoint = f(endpoints.CHANNEL, channel_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteChannel(channel_id) -- Channel:delete
local endpoint = f(endpoints.CHANNEL, channel_id)
return self:request("DELETE", endpoint)
end
function API:getChannelMessages(channel_id, query) -- TextChannel:get[First|Last]Message, TextChannel:getMessages
local endpoint = f(endpoints.CHANNEL_MESSAGES, channel_id)
return self:request("GET", endpoint, nil, query)
end
function API:getChannelMessage(channel_id, message_id) -- TextChannel:getMessage fallback
local endpoint = f(endpoints.CHANNEL_MESSAGE, channel_id, message_id)
return self:request("GET", endpoint)
end
function API:createMessage(channel_id, payload, files) -- TextChannel:send
local endpoint = f(endpoints.CHANNEL_MESSAGES, channel_id)
return self:request("POST", endpoint, payload, nil, files)
end
function API:createReaction(channel_id, message_id, emoji, payload) -- Message:addReaction
local endpoint = f(endpoints.CHANNEL_MESSAGE_REACTION_ME, channel_id, message_id, urlencode(emoji))
return self:request("PUT", endpoint, payload)
end
function API:deleteOwnReaction(channel_id, message_id, emoji) -- Message:removeReaction
local endpoint = f(endpoints.CHANNEL_MESSAGE_REACTION_ME, channel_id, message_id, urlencode(emoji))
return self:request("DELETE", endpoint)
end
function API:deleteUserReaction(channel_id, message_id, emoji, user_id) -- Message:removeReaction
local endpoint = f(endpoints.CHANNEL_MESSAGE_REACTION_USER, channel_id, message_id, urlencode(emoji), user_id)
return self:request("DELETE", endpoint)
end
function API:getReactions(channel_id, message_id, emoji, query) -- Reaction:getUsers
local endpoint = f(endpoints.CHANNEL_MESSAGE_REACTION, channel_id, message_id, urlencode(emoji))
return self:request("GET", endpoint, nil, query)
end
function API:deleteAllReactions(channel_id, message_id) -- Message:clearReactions
local endpoint = f(endpoints.CHANNEL_MESSAGE_REACTIONS, channel_id, message_id)
return self:request("DELETE", endpoint)
end
function API:editMessage(channel_id, message_id, payload) -- Message:_modify
local endpoint = f(endpoints.CHANNEL_MESSAGE, channel_id, message_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteMessage(channel_id, message_id) -- Message:delete
local endpoint = f(endpoints.CHANNEL_MESSAGE, channel_id, message_id)
return self:request("DELETE", endpoint)
end
function API:bulkDeleteMessages(channel_id, payload) -- GuildTextChannel:bulkDelete
local endpoint = f(endpoints.CHANNEL_MESSAGES_BULK_DELETE, channel_id)
return self:request("POST", endpoint, payload)
end
function API:editChannelPermissions(channel_id, overwrite_id, payload) -- various PermissionOverwrite methods
local endpoint = f(endpoints.CHANNEL_PERMISSION, channel_id, overwrite_id)
return self:request("PUT", endpoint, payload)
end
function API:getChannelInvites(channel_id) -- GuildChannel:getInvites
local endpoint = f(endpoints.CHANNEL_INVITES, channel_id)
return self:request("GET", endpoint)
end
function API:createChannelInvite(channel_id, payload) -- GuildChannel:createInvite
local endpoint = f(endpoints.CHANNEL_INVITES, channel_id)
return self:request("POST", endpoint, payload)
end
function API:deleteChannelPermission(channel_id, overwrite_id) -- PermissionOverwrite:delete
local endpoint = f(endpoints.CHANNEL_PERMISSION, channel_id, overwrite_id)
return self:request("DELETE", endpoint)
end
function API:triggerTypingIndicator(channel_id, payload) -- TextChannel:broadcastTyping
local endpoint = f(endpoints.CHANNEL_TYPING, channel_id)
return self:request("POST", endpoint, payload)
end
function API:getPinnedMessages(channel_id) -- TextChannel:getPinnedMessages
local endpoint = f(endpoints.CHANNEL_PINS, channel_id)
return self:request("GET", endpoint)
end
function API:addPinnedChannelMessage(channel_id, message_id, payload) -- Message:pin
local endpoint = f(endpoints.CHANNEL_PIN, channel_id, message_id)
return self:request("PUT", endpoint, payload)
end
function API:deletePinnedChannelMessage(channel_id, message_id) -- Message:unpin
local endpoint = f(endpoints.CHANNEL_PIN, channel_id, message_id)
return self:request("DELETE", endpoint)
end
function API:groupDMAddRecipient(channel_id, user_id, payload) -- GroupChannel:addRecipient
local endpoint = f(endpoints.CHANNEL_RECIPIENT, channel_id, user_id)
return self:request("PUT", endpoint, payload)
end
function API:groupDMRemoveRecipient(channel_id, user_id) -- GroupChannel:removeRecipient
local endpoint = f(endpoints.CHANNEL_RECIPIENT, channel_id, user_id)
return self:request("DELETE", endpoint)
end
function API:listGuildEmojis(guild_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD_EMOJIS, guild_id)
return self:request("GET", endpoint)
end
function API:getGuildEmoji(guild_id, emoji_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD_EMOJI, guild_id, emoji_id)
return self:request("GET", endpoint)
end
function API:createGuildEmoji(guild_id, payload) -- Guild:createEmoji
local endpoint = f(endpoints.GUILD_EMOJIS, guild_id)
return self:request("POST", endpoint, payload)
end
function API:modifyGuildEmoji(guild_id, emoji_id, payload) -- Emoji:_modify
local endpoint = f(endpoints.GUILD_EMOJI, guild_id, emoji_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteGuildEmoji(guild_id, emoji_id) -- Emoji:delete
local endpoint = f(endpoints.GUILD_EMOJI, guild_id, emoji_id)
return self:request("DELETE", endpoint)
end
function API:createGuild(payload) -- Client:createGuild
local endpoint = endpoints.GUILDS
return self:request("POST", endpoint, payload)
end
function API:getGuild(guild_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD, guild_id)
return self:request("GET", endpoint)
end
function API:modifyGuild(guild_id, payload) -- Guild:_modify
local endpoint = f(endpoints.GUILD, guild_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteGuild(guild_id) -- Guild:delete
local endpoint = f(endpoints.GUILD, guild_id)
return self:request("DELETE", endpoint)
end
function API:getGuildChannels(guild_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD_CHANNELS, guild_id)
return self:request("GET", endpoint)
end
function API:createGuildChannel(guild_id, payload) -- Guild:create[Text|Voice]Channel
local endpoint = f(endpoints.GUILD_CHANNELS, guild_id)
return self:request("POST", endpoint, payload)
end
function API:modifyGuildChannelPositions(guild_id, payload) -- GuildChannel:move[Up|Down]
local endpoint = f(endpoints.GUILD_CHANNELS, guild_id)
return self:request("PATCH", endpoint, payload)
end
function API:getGuildMember(guild_id, user_id) -- Guild:getMember fallback
local endpoint = f(endpoints.GUILD_MEMBER, guild_id, user_id)
return self:request("GET", endpoint)
end
function API:listGuildMembers(guild_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD_MEMBERS, guild_id)
return self:request("GET", endpoint)
end
function API:addGuildMember(guild_id, user_id, payload) -- not exposed, limited use
local endpoint = f(endpoints.GUILD_MEMBER, guild_id, user_id)
return self:request("PUT", endpoint, payload)
end
function API:modifyGuildMember(guild_id, user_id, payload) -- various Member methods
local endpoint = f(endpoints.GUILD_MEMBER, guild_id, user_id)
return self:request("PATCH", endpoint, payload)
end
function API:modifyCurrentUsersNick(guild_id, payload) -- Member:setNickname
local endpoint = f(endpoints.GUILD_MEMBER_ME_NICK, guild_id)
return self:request("PATCH", endpoint, payload)
end
function API:addGuildMemberRole(guild_id, user_id, role_id, payload) -- Member:addrole
local endpoint = f(endpoints.GUILD_MEMBER_ROLE, guild_id, user_id, role_id)
return self:request("PUT", endpoint, payload)
end
function API:removeGuildMemberRole(guild_id, user_id, role_id) -- Member:removeRole
local endpoint = f(endpoints.GUILD_MEMBER_ROLE, guild_id, user_id, role_id)
return self:request("DELETE", endpoint)
end
function API:removeGuildMember(guild_id, user_id, query) -- Guild:kickUser
local endpoint = f(endpoints.GUILD_MEMBER, guild_id, user_id)
return self:request("DELETE", endpoint, nil, query)
end
function API:getGuildBans(guild_id) -- Guild:getBans
local endpoint = f(endpoints.GUILD_BANS, guild_id)
return self:request("GET", endpoint)
end
function API:getGuildBan(guild_id, user_id) -- Guild:getBan
local endpoint = f(endpoints.GUILD_BAN, guild_id, user_id)
return self:request("GET", endpoint)
end
function API:createGuildBan(guild_id, user_id, query) -- Guild:banUser
local endpoint = f(endpoints.GUILD_BAN, guild_id, user_id)
return self:request("PUT", endpoint, nil, query)
end
function API:removeGuildBan(guild_id, user_id, query) -- Guild:unbanUser / Ban:delete
local endpoint = f(endpoints.GUILD_BAN, guild_id, user_id)
return self:request("DELETE", endpoint, nil, query)
end
function API:getGuildRoles(guild_id) -- not exposed, use cache
local endpoint = f(endpoints.GUILD_ROLES, guild_id)
return self:request("GET", endpoint)
end
function API:createGuildRole(guild_id, payload) -- Guild:createRole
local endpoint = f(endpoints.GUILD_ROLES, guild_id)
return self:request("POST", endpoint, payload)
end
function API:modifyGuildRolePositions(guild_id, payload) -- Role:move[Up|Down]
local endpoint = f(endpoints.GUILD_ROLES, guild_id)
return self:request("PATCH", endpoint, payload)
end
function API:modifyGuildRole(guild_id, role_id, payload) -- Role:_modify
local endpoint = f(endpoints.GUILD_ROLE, guild_id, role_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteGuildRole(guild_id, role_id) -- Role:delete
local endpoint = f(endpoints.GUILD_ROLE, guild_id, role_id)
return self:request("DELETE", endpoint)
end
function API:getGuildPruneCount(guild_id, query) -- Guild:getPruneCount
local endpoint = f(endpoints.GUILD_PRUNE, guild_id)
return self:request("GET", endpoint, nil, query)
end
function API:beginGuildPrune(guild_id, payload, query) -- Guild:pruneMembers
local endpoint = f(endpoints.GUILD_PRUNE, guild_id)
return self:request("POST", endpoint, payload, query)
end
function API:getGuildVoiceRegions(guild_id) -- Guild:listVoiceRegions
local endpoint = f(endpoints.GUILD_REGIONS, guild_id)
return self:request("GET", endpoint)
end
function API:getGuildInvites(guild_id) -- Guild:getInvites
local endpoint = f(endpoints.GUILD_INVITES, guild_id)
return self:request("GET", endpoint)
end
function API:getGuildIntegrations(guild_id) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_INTEGRATIONS, guild_id)
return self:request("GET", endpoint)
end
function API:createGuildIntegration(guild_id, payload) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_INTEGRATIONS, guild_id)
return self:request("POST", endpoint, payload)
end
function API:modifyGuildIntegration(guild_id, integration_id, payload) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_INTEGRATION, guild_id, integration_id)
return self:request("PATCH", endpoint, payload)
end
function API:deleteGuildIntegration(guild_id, integration_id) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_INTEGRATION, guild_id, integration_id)
return self:request("DELETE", endpoint)
end
function API:syncGuildIntegration(guild_id, integration_id, payload) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_INTEGRATION_SYNC, guild_id, integration_id)
return self:request("POST", endpoint, payload)
end
function API:getGuildEmbed(guild_id) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_EMBED, guild_id)
return self:request("GET", endpoint)
end
function API:modifyGuildEmbed(guild_id, payload) -- not exposed, maybe in the future
local endpoint = f(endpoints.GUILD_EMBED, guild_id)
return self:request("PATCH", endpoint, payload)
end
function API:getInvite(invite_code, query) -- Client:getInvite
local endpoint = f(endpoints.INVITE, invite_code)
return self:request("GET", endpoint, nil, query)
end
function API:deleteInvite(invite_code) -- Invite:delete
local endpoint = f(endpoints.INVITE, invite_code)
return self:request("DELETE", endpoint)
end
function API:acceptInvite(invite_code, payload) -- not exposed, invalidates tokens
local endpoint = f(endpoints.INVITE, invite_code)
return self:request("POST", endpoint, payload)
end
function API:getCurrentUser() -- API:authenticate
local endpoint = endpoints.USER_ME
return self:request("GET", endpoint)
end
function API:getUser(user_id) -- Client:getUser
local endpoint = f(endpoints.USER, user_id)
return self:request("GET", endpoint)
end
function API:modifyCurrentUser(payload) -- Client:_modify
local endpoint = endpoints.USER_ME
return self:request("PATCH", endpoint, payload)
end
function API:getCurrentUserGuilds() -- not exposed, use cache
local endpoint = endpoints.USER_ME_GUILDS
return self:request("GET", endpoint)
end
function API:leaveGuild(guild_id) -- Guild:leave
local endpoint = f(endpoints.USER_ME_GUILD, guild_id)
return self:request("DELETE", endpoint)
end
function API:getUserDMs() -- not exposed, use cache
local endpoint = endpoints.USER_ME_CHANNELS
return self:request("GET", endpoint)
end
function API:createDM(payload) -- User:getPrivateChannel fallback
local endpoint = endpoints.USER_ME_CHANNELS
return self:request("POST", endpoint, payload)
end
function API:createGroupDM(payload) -- Client:createGroupChannel
local endpoint = endpoints.USER_ME_CHANNELS
return self:request("POST", endpoint, payload)
end
function API:getUsersConnections() -- Client:getConnections
local endpoint = endpoints.USER_ME_CONNECTIONS
return self:request("GET", endpoint)
end
function API:listVoiceRegions() -- Client:listVoiceRegions
local endpoint = endpoints.VOICE_REGIONS
return self:request("GET", endpoint)
end
function API:createWebhook(channel_id, payload) -- GuildTextChannel:createWebhook
local endpoint = f(endpoints.CHANNEL_WEBHOOKS, channel_id)
return self:request("POST", endpoint, payload)
end
function API:getChannelWebhooks(channel_id) -- GuildTextChannel:getWebhooks
local endpoint = f(endpoints.CHANNEL_WEBHOOKS, channel_id)
return self:request("GET", endpoint)
end
function API:getGuildWebhooks(guild_id) -- Guild:getWebhooks
local endpoint = f(endpoints.GUILD_WEBHOOKS, guild_id)
return self:request("GET", endpoint)
end
function API:getWebhook(webhook_id) -- Client:getWebhook
local endpoint = f(endpoints.WEBHOOK, webhook_id)
return self:request("GET", endpoint)
end
function API:getWebhookWithToken(webhook_id, webhook_token) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN, webhook_id, webhook_token)
return self:request("GET", endpoint)
end
function API:modifyWebhook(webhook_id, payload) -- Webhook:_modify
local endpoint = f(endpoints.WEBHOOK, webhook_id)
return self:request("PATCH", endpoint, payload)
end
function API:modifyWebhookWithToken(webhook_id, webhook_token, payload) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN, webhook_id, webhook_token)
return self:request("PATCH", endpoint, payload)
end
function API:deleteWebhook(webhook_id) -- Webhook:delete
local endpoint = f(endpoints.WEBHOOK, webhook_id)
return self:request("DELETE", endpoint)
end
function API:deleteWebhookWithToken(webhook_id, webhook_token) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN, webhook_id, webhook_token)
return self:request("DELETE", endpoint)
end
function API:executeWebhook(webhook_id, webhook_token, payload) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN, webhook_id, webhook_token)
return self:request("POST", endpoint, payload)
end
function API:executeSlackCompatibleWebhook(webhook_id, webhook_token, payload) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN_SLACK, webhook_id, webhook_token)
return self:request("POST", endpoint, payload)
end
function API:executeGitHubCompatibleWebhook(webhook_id, webhook_token, payload) -- not exposed, needs webhook client
local endpoint = f(endpoints.WEBHOOK_TOKEN_GITHUB, webhook_id, webhook_token)
return self:request("POST", endpoint, payload)
end
function API:getGateway() -- Client:run
local endpoint = endpoints.GATEWAY
return self:request("GET", endpoint)
end
function API:getGatewayBot() -- Client:run
local endpoint = endpoints.GATEWAY_BOT
return self:request("GET", endpoint)
end
function API:getCurrentApplicationInformation() -- Client:run
local endpoint = endpoints.OAUTH2_APPLICATION_ME
return self:request("GET", endpoint)
end
-- end of auto-generated methods --
return API
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- [INI file] [PolicyTableUpdate] PTS snapshot storage on a file system
--
-- Check creation of PT snapshot
-- 1. Used preconditions:
-- Do not start default SDL
-- 2. Performed steps:
-- Set correct PathToSnapshot path in INI file
-- Start SDL
-- Initiate PT snapshot creation
--
-- Expected result:
-- SDL must store the PT snapshot as a JSON file which filename and filepath are defined in "PathToSnapshot" parameter of smartDeviceLink.ini file.
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
Test = require('connecttest')
local config = require('config')
require('user_modules/AppTypes')
config.defaultProtocolVersion = 2
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
require('cardinalities')
local mobile_session = require('mobile_session')
--[[ Local Variables ]]
local POLICY_SNAPSHOT_FILE_NAME = "sdl_mega_snapshot.json"
local SYSTEM_FILES_PATH = "/tmp" -- /tmp/fs/mp/images/ivsu_cache
local oldPathToPtSnapshot
local oldNameOfPtSnapshot
local TestData = {
path = config.pathToSDL .. "TestData",
isExist = false,
init = function(self)
if not self.isExist then
os.execute("mkdir ".. self.path)
os.execute("echo 'List test data files files:' > " .. self.path .. "/index.txt")
self.isExist = true
end
end,
store = function(self, message, pathToFile, fileName)
if self.isExist then
local dataToWrite = message
if pathToFile and fileName then
os.execute(table.concat({"cp ", pathToFile, " ", self.path, "/", fileName}))
dataToWrite = table.concat({dataToWrite, " File: ", fileName})
end
dataToWrite = dataToWrite .. "\n"
local file = io.open(self.path .. "/index.txt", "a+")
file:write(dataToWrite)
file:close()
end
end,
delete = function(self)
if self.isExist then
os.execute("rm -r -f " .. self.path)
self.isExist = false
end
end,
info = function(self)
if self.isExist then
commonFunctions:userPrint(35, "All test data generated by this test were stored to folder: " .. self.path)
else
commonFunctions:userPrint(35, "No test data were stored" )
end
end
}
--[[ Local Functions ]]
local function setValueInSdlIni(parameterName, parameterValue)
local sdlIniFileName = config.pathToSDL .. "smartDeviceLink.ini"
local oldParameterValue
local file = assert(io.open(sdlIniFileName, "r"))
if file then
local fileContent = file:read("*a")
file:close()
oldParameterValue = string.match(fileContent, parameterName .. "%s*=%s*(%S+)")
if oldParameterValue then
fileContent = string.gsub(fileContent, parameterName .. "%s*=%s*%S+", parameterName .. " = " .. parameterValue)
else
local lastCharOfFile = string.sub(fileContent, string.len(fileContent))
if lastCharOfFile == "\n" then
lastCharOfFile = ""
else
lastCharOfFile = "\n"
end
fileContent = table.concat({fileContent, lastCharOfFile, parameterName, " = ", parameterValue, "\n"})
oldParameterValue = nil
end
file = assert(io.open(sdlIniFileName, "w"))
if file then
file:write(fileContent)
file:close()
return true, oldParameterValue
else
return false
end
else
return false
end
end
function Test.changePtsPathInSdlIni(newPath, parameterName)
local result, oldPath = setValueInSdlIni(parameterName, newPath)
if not result then
commonFunctions:userPrint(31, "Test can't change SDL .ini file")
end
return oldPath
end
local function getAbsolutePath(path)
if path:match("^%./") then
return config.pathToSDL .. path:match("^%./(.+)")
end
if path:match("^/") then
return path
end
return config.pathToSDL .. path
end
function Test.checkPtsFile()
local file = io.open(getAbsolutePath(SYSTEM_FILES_PATH .. "/" .. POLICY_SNAPSHOT_FILE_NAME), "r")
if file then
file:close()
return true
else
return false
end
end
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:StopSDL_precondition()
TestData:init()
StopSDL(self)
end
function Test:Precondition_StartSDL()
TestData:store("Store original INI ", config.pathToSDL .. "smartDeviceLink.ini", "original_smartDeviceLink.ini")
oldNameOfPtSnapshot = self.changePtsPathInSdlIni(POLICY_SNAPSHOT_FILE_NAME, "PathToSnapshot")
oldPathToPtSnapshot = self.changePtsPathInSdlIni(SYSTEM_FILES_PATH, "SystemFilesPath")
TestData:store("Store INI before start SDL", config.pathToSDL .. "smartDeviceLink.ini", "new_smartDeviceLink.ini")
StartSDL(config.pathToSDL, true)
end
function Test:Precondition_InitHMIandMobileApp()
self:initHMI()
self:initHMI_onReady()
self:connectMobile()
self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession:StartService(7)
end
function Test:Precondition_ActivateApp()
local CorIdRAI = self.mobileSession:SendRPC("RegisterAppInterface",
{
syncMsgVersion =
{
majorVersion = 3,
minorVersion = 0
},
appName = "SPT",
isMediaApplication = true,
languageDesired = "EN-US",
hmiDisplayLanguageDesired = "EN-US",
appID = "1234567",
deviceInfo =
{
os = "Android",
carrier = "Megafon",
firmwareRev = "Name: Linux, Version: 3.4.0-perf",
osVersion = "4.4.2",
maxNumberRFCOMMPorts = 1
}
})
EXPECT_RESPONSE(CorIdRAI, { success = true, resultCode = "SUCCESS"})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered",
{
application =
{
appName = "SPT",
policyAppID = "1234567",
isMediaApplication = true,
hmiDisplayLanguageDesired = "EN-US",
deviceInfo =
{
name = "127.0.0.1",
id = config.deviceMAC,
transportType = "WIFI",
isSDLAllowed = false
}
}
})
:Do(function(_,data)
self.applications["SPT"] = data.params.application.appID
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["SPT"]})
EXPECT_HMIRESPONSE(RequestId, { result = {
code = 0,
isSDLAllowed = false},
method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestId2,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
end)
end)
end)
end
function Test.Precondition_WaitForSnapshot()
os.execute("sleep 3")
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:Test()
if not self:checkPtsFile() then
self:FailTestCase("PT snapshot wasn't created")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test:Postcondition()
commonSteps:DeletePolicyTable(self)
self.changePtsPathInSdlIni(oldNameOfPtSnapshot, "PathToSnapshot")
self.changePtsPathInSdlIni(oldPathToPtSnapshot, "SystemFilesPath")
TestData:store("Store INI at the end of test", config.pathToSDL .. "smartDeviceLink.ini", "restored_smartDeviceLink.ini")
TestData:info()
end
function Test.Postcondition_StopSDL()
StopSDL()
end
return Test
|
--[[
#3DreamEngine - 3D library by Luke100000
#Copyright 2020 Luke100000
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 lib = { }
if love.filesystem.read("debugEnabled") == "true" then
_DEBUGMODE = true
end
--load libraries
_G.mat2 = require((...) .. "/libs/luaMatrices/mat2")
_G.mat3 = require((...) .. "/libs/luaMatrices/mat3")
_G.mat4 = require((...) .. "/libs/luaMatrices/mat4")
_G.vec2 = require((...) .. "/libs/luaVectors/vec2")
_G.vec3 = require((...) .. "/libs/luaVectors/vec3")
_G.vec4 = require((...) .. "/libs/luaVectors/vec4")
_G.quat = require((...) .. "/libs/quat")
_G.cimg = require((...) .. "/libs/cimg")
_G.utils = require((...) .. "/libs/utils")
_G.packTable = require((...) .. "/libs/packTable")
lib.ffi = require("ffi")
--load sub modules
_3DreamEngine = lib
lib.root = (...)
require((...) .. "/functions")
require((...) .. "/settings")
require((...) .. "/classes")
require((...) .. "/shader")
require((...) .. "/loader")
require((...) .. "/materials")
require((...) .. "/resources")
require((...) .. "/render")
require((...) .. "/renderLight")
require((...) .. "/renderSky")
require((...) .. "/jobs")
require((...) .. "/particlesystem")
require((...) .. "/particles")
require((...) .. "/3doExport")
require((...) .. "/animations")
--loader
lib.loader = { }
for d,s in pairs(love.filesystem.getDirectoryItems((...) .. "/loader")) do
lib.loader[s:sub(1, #s-4)] = require((...) .. "/loader/" .. s:sub(1, #s-4))
end
--get color of sun based on sunrise sky texture
lib.sunlight = require(lib.root .. "/res/sunlight")
lib.skylight = require(lib.root .. "/res/skylight")
--supported canvas formats
lib.canvasFormats = love.graphics and love.graphics.getCanvasFormats() or { }
--default material library
lib.materialLibrary = { }
lib.objectLibrary = { }
lib.collisionLibrary = { }
--default settings
lib:setAO(32, 0.75, false)
lib:setBloom(-1)
lib:setFog()
lib:setFogHeight()
lib:setDaytime(0.3)
lib:setGamma(false)
lib:setExposure(1.0)
lib:setMaxLights(16)
lib:setNameDecoder("^(.+)_([^_]+)$")
lib:setFrustumCheck("fast")
lib:setLODDistance(100)
lib:setDither(false)
--shadows
lib:setShadowResolution(1024, 512)
lib:setShadowSmoothing(false)
lib:setShadowCascade(8, 4)
--loader settings
lib:setResourceLoader(true, true)
lib:setSmoothLoading(1 / 1000)
lib:setSmoothLoadingBufferSize(128)
lib:setMipmaps(true)
--sun
lib:setSunOffset(0.0, 0,0)
lib:setSunShadow(true)
--weather
lib:setWeather(0.5)
lib:setRainbow(0.0)
lib:setRainbowDir(vec3(1.0, -0.25, 1.0))
--sky
lib:setReflection(true)
lib:setSky(true)
lib:setSkyReflectionFormat(512, "rgba16f", 4)
--clouds
lib:setClouds(true)
lib:setWind(0.005, 0.0)
lib:setCloudsStretch(0, 20, 0)
lib:setCloudsAnim(0.01, 0.25)
lib:setUpperClouds(true)
--auto exposure
lib:setAutoExposure(false)
--canvas set settings
lib.renderSet = lib:newSetSettings()
lib.renderSet:setPostEffects(true)
lib.renderSet:setRefractions(true)
lib.renderSet:setAverageAlpha(false)
lib.renderSet:setMode("normal")
lib.reflectionsSet = lib:newSetSettings()
lib.reflectionsSet:setMode("direct")
lib.mirrorSet = lib:newSetSettings()
lib.mirrorSet:setMode("lite")
lib.shadowSet = lib:newSetSettings()
--default camera
lib.cam = lib:newCam()
--default scene
lib.scene = lib:newScene()
--hardcoded mipmap count, do not change
lib.reflections_levels = 5
--delton, disabled when not in debug mode
lib.delton = require((...) .. "/libs/delton"):new(512)
if not _DEBUGMODE then
lib.delton.start = function() end
lib.delton.stop = lib.delton.start
lib.delton.step = lib.delton.start
end
--default objects
lib.object_sky = lib:loadObject(lib.root .. "/objects/sky", "Phong", {splitMaterials = false})
lib.object_cube = lib:loadObject(lib.root .. "/objects/cube", "simple", {splitMaterials = false})
lib.object_plane = lib:loadObject(lib.root .. "/objects/plane", "Phong", {splitMaterials = false})
--default textures
local pix = love.image.newImageData(2, 2)
lib.textures = {
default = love.graphics.newImage(lib.root .. "/res/default.png"),
default_normal = love.graphics.newImage(lib.root .. "/res/default_normal.png"),
sky_fallback = love.graphics.newCubeImage({pix, pix, pix, pix, pix, pix}),
}
--load textures once actually needed
lib.initTextures = { }
function lib.initTextures:PBR()
if not self.PBR_done then
self.PBR_done = true
lib.textures.brdfLUT = love.graphics.newImage(lib.root .. "/res/brdfLut.png")
end
end
function lib.initTextures:sky()
if not self.sky_done then
self.sky_done = true
lib.textures.sky = love.graphics.newImage(lib.root .. "/res/sky.png")
lib.textures.moon = love.graphics.newImage(lib.root .. "/res/moon.png")
lib.textures.moon_normal = love.graphics.newImage(lib.root .. "/res/moon_normal.png")
lib.textures.sun = love.graphics.newImage(lib.root .. "/res/sun.png")
lib.textures.rainbow = love.graphics.newImage(lib.root .. "/res/rainbow.png")
lib.textures.clouds = lib.textures.clouds or love.graphics.newImage(lib.root .. "/res/clouds.png")
lib.textures.clouds_base = love.graphics.newImage(lib.root .. "/res/clouds_base.png")
lib.textures.clouds_base:setWrap("repeat")
lib.textures.clouds_top = love.graphics.newCubeImage("3DreamEngine/res/clouds_top.png")
lib.textures.stars = love.graphics.newCubeImage("3DreamEngine/res/stars.png")
lib.textures.clouds:setFilter("nearest")
end
end
--a canvas set is used to render a scene to
function lib.newCanvasSet(self, settings, w, h)
local set = { }
w = w or settings.resolution
h = h or settings.resolution
--settings
set.width = w
set.height = h
set.msaa = settings.msaa
set.mode = settings.mode
set.postEffects = settings.postEffects and settings.mode == "normal"
set.refractions = settings.alphaPass and settings.refractions and settings.mode == "normal"
set.averageAlpha = settings.alphaPass and settings.averageAlpha and settings.mode == "normal"
set.format = settings.format
set.alphaPass = settings.alphaPass
if settings.mode ~= "direct" then
--depth
set.depth_buffer = love.graphics.newCanvas(w, h, {format = self.canvasFormats["depth32f"] and "depth32f" or self.canvasFormats["depth24"] and "depth24" or "depth16", readable = false, msaa = set.msaa})
--temporary HDR color
set.color = love.graphics.newCanvas(w, h, {format = settings.format, readable = true, msaa = set.msaa})
--additional color if using refractions or averageAlpha
if set.averageAlpha or set.refractions then
set.colorAlpha = love.graphics.newCanvas(w, h, {format = "rgba16f", readable = true, msaa = set.msaa})
if set.averageAlpha then
set.dataAlpha = love.graphics.newCanvas(w, h, {format = "rgba16f", readable = true, msaa = set.msaa})
end
end
--depth
set.depth = love.graphics.newCanvas(w, h, {format = "r16f", readable = true, msaa = set.msaa})
end
--screen space ambient occlusion blurring canvases
if self.AO_enabled and settings.mode ~= "direct" then
set.AO_1 = love.graphics.newCanvas(w*self.AO_resolution, h*self.AO_resolution, {format = "r8", readable = true, msaa = 0})
if self.AO_blur then
set.AO_2 = love.graphics.newCanvas(w*self.AO_resolution, h*self.AO_resolution, {format = "r8", readable = true, msaa = 0})
end
end
--post effects
if set.postEffects then
--bloom blurring canvases
if self.bloom_enabled then
set.bloom_1 = love.graphics.newCanvas(w*self.bloom_resolution, h*self.bloom_resolution, {format = settings.format, readable = true, msaa = 0})
set.bloom_2 = love.graphics.newCanvas(w*self.bloom_resolution, h*self.bloom_resolution, {format = settings.format, readable = true, msaa = 0})
end
end
return set
end
--release set and free memory
function lib:unloadCanvasSet(set)
if set then
for d,s in pairs(set) do
if type(set) == "userdata" and set.release then
set:release()
end
end
end
end
--load canvases
function lib.resize(self, w, h)
--fully unload previous sets
self:unloadCanvasSet(self.canvases)
self:unloadCanvasSet(self.canvases_reflections)
--canvases sets
self.canvases = self:newCanvasSet(self.renderSet, w, h)
self.canvases_reflections = self:newCanvasSet(self.reflectionsSet)
self.canvases_mirror = self:newCanvasSet(self.mirrorSet, w, h)
--sky box
if self.sky_reflection == true then
self.sky_reflectionCanvas = love.graphics.newCanvas(self.sky_resolution, self.sky_resolution, {format = self.sky_format, readable = true, msaa = 0, type = "cube", mipmaps = "manual"})
else
self.sky_reflectionCanvas = false
end
self:loadShader()
self:initJobs()
end
--applies settings and load canvases
function lib.init(self, w, h)
if self.renderSet.mode == "direct" then
local width, height, flags = love.window.getMode()
if flags.depth == 0 then
print("Direct render is enabled, but there is no depth buffer! Using 16-bit depth from now on.")
love.window.updateMode(width, height, {depth = 16})
end
end
if self.autoExposure_enabled and self.renderSet.mode == "direct" then
print("Autoexposure does not work with direct render! Autoexposure has been disabled.")
self:setAutoExposure(false)
end
self:resize(w or love.graphics.getWidth(), h or love.graphics.getHeight())
--reset shader
self:loadShader()
--reset lighting
self.lighting = { }
--reset cache
self.cache = { }
--create sun shadow if requested
--TODO sun strength should receive setting
self.sunObject = lib:newLight("sun", 1, 1, 1, 1, 1, 1, 5)
if self.sun_shadow then
self.sunObject.shadow = lib:newShadow("sun")
else
self.sunObject.shadow = nil
end
end
--clears the current scene
function lib:prepare()
self.scenes = { }
lib:drawScene(self.scene)
self.scene:clear()
self.particleBatches = { }
self.particleBatchesActive = { }
self.particles = { }
self.particlesEmissive = { }
--keep track of reflections
self.reflections_last = self.reflections or { }
self.reflections = { }
--shader modules referenced this frame
self.allActiveShaderModules = { }
--reset stats
self.stats.shadersInUse = 0
self.stats.lightSetups = 0
self.stats.materialDraws = 0
self.stats.draws = 0
end
--add an object to the default scene
function lib:draw(obj, x, y, z, sx, sy, sz)
self.delton:start("draw")
--prepare transform matrix
local transform
if x then
--simple transform with arguments, ignores object transformation matrix
transform = mat4(
sx or 1, 0, 0, x,
0, sy or sx or 1, 0, y,
0, 0, sz or sx or 1, z,
0, 0, 0, 1
)
--also applies objects own transformation if present
if obj.transform then
transform = transform * obj.transform
end
else
--pre defined transform
transform = obj.transform
end
--fetch current color
local col = vec4(love.graphics.getColor())
--add to scene
self.delton:start("add")
self.scene:add(obj, transform, col)
self.delton:stop()
self.delton:stop()
end
--will render this scene
function lib:drawScene(scene)
self.scenes[scene] = true
end
--will render this batch
function lib:drawParticleBatch(batch)
self.particleBatchesActive[batch.emissionTexture and true or false] = true
self.particleBatches[batch] = true
end
--set vertical level of next particles
local vertical = 0.0
function lib:setParticleVertical(v)
assert(type(v) == "number", "number expected, got " .. type(v))
vertical = v
end
function lib:getParticleVertical()
return vertical
end
--set emission multiplier of next particles
local emission = false
function lib:setParticleEmission(e)
emission = e or false
end
function lib:getParticleEmission()
return emission
end
--draw a particle
function lib:drawParticle(drawable, quad, x, y, z, ...)
local r, g, b, a = love.graphics.getColor()
if type(quad) == "userdata" and quad:typeOf("Quad") then
self.particles[#self.particles+1] = {drawable, quad, {x, y, z}, {r, g, b, a}, vertical, emission or 0.0, {...}}
else
self.particles[#self.particles+1] = {drawable, {quad, x, y}, {r, g, b, a}, vertical, emission or 0.0, {z, ...}}
end
end
--draw a particle with emission texture
function lib:drawEmissionParticle(drawable, emissionDrawable, quad, x, y, z, ...)
local r, g, b, a = love.graphics.getColor()
if type(quad) == "userdata" and quad:typeOf("Quad") then
self.particlesEmissive[#self.particlesEmissive+1] = {drawable, emissionDrawable, quad, {x, y, z}, {r, g, b, a}, vertical, emission or 1.0, {...}}
else
self.particlesEmissive[#self.particlesEmissive+1] = {drawable, emissionDrawable, {quad, x, y}, {r, g, b, a}, vertical, emission or 1.0, {z, ...}}
end
end
return lib |
local config = {
maxLevel = getConfigInfo('maximumDoorLevel')
}
local increasingItems = {[416] = 417, [426] = 425, [446] = 447, [3216] = 3217, [3202] = 3215, [11062] = 11063}
local decreasingItems = {[417] = 416, [425] = 426, [447] = 446, [3217] = 3216, [3215] = 3202, [11063] = 11062}
local depots = {2589, 2590, 2591, 2592}
local checkCreature = {isPlayer, isMonster, isNpc}
local function pushBack(cid, position, fromPosition, displayMessage)
doTeleportThing(cid, fromPosition, false)
doSendMagicEffect(position, CONST_ME_MAGIC_BLUE)
if(displayMessage) then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "The tile seems to be protected against unwanted intruders.")
end
end
function onStepIn(cid, item, position, fromPosition)
if(not increasingItems[item.itemid]) then
return false
end
if(not isPlayerGhost(cid)) then
doTransformItem(item.uid, increasingItems[item.itemid])
end
if(item.actionid >= 194 and item.actionid <= 196) then
local f = checkCreature[item.actionid - 193]
if(f(cid)) then
pushBack(cid, position, fromPosition, false)
end
return true
end
if(item.actionid >= 191 and item.actionid <= 193) then
local f = checkCreature[item.actionid - 190]
if(not f(cid)) then
pushBack(cid, position, fromPosition, false)
end
return true
end
if(not isPlayer(cid)) then
return true
end
if(item.actionid == 189 and not isPremium(cid)) then
pushBack(cid, position, fromPosition, true)
return true
end
local gender = item.actionid - 186
if(isInArray({PLAYERSEX_FEMALE, PLAYERSEX_MALE, PLAYERSEX_GAMEMASTER}, gender)) then
if(gender ~= getPlayerSex(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local skull = item.actionid - 180
if(skull >= SKULL_NONE and skull <= SKULL_BLACK) then
if(skull ~= getCreatureSkullType(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local group = item.actionid - 150
if(group >= 0 and group < 30) then
if(group > getPlayerGroupId(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local vocation = item.actionid - 100
if(vocation >= 0 and vocation < 50) then
local playerVocationInfo = getVocationInfo(getPlayerVocation(cid))
if(playerVocationInfo.id ~= vocation and playerVocationInfo.fromVocation ~= vocation) then
pushBack(cid, position, fromPosition, true)
end
return true
end
if(item.actionid >= 1000 and item.actionid <= config.maxLevel) then
if(getPlayerLevel(cid) < item.actionid - 1000) then
pushBack(cid, position, fromPosition, true)
end
return true
end
if(item.actionid ~= 0 and getPlayerStorageValue(cid, item.actionid) <= 0) then
pushBack(cid, position, fromPosition, true)
return true
end
if(getTileInfo(position).protection) then
local depotPos, depot = getCreatureLookPosition(cid), {}
depotPos.stackpos = STACKPOS_GROUND
while(true) do
if(not getTileInfo(depotPos).depot) then
break
end
depotPos.stackpos = depotPos.stackpos + 1
depot = getThingFromPos(depotPos)
if(depot.uid == 0) then
break
end
if(isInArray(depots, depot.itemid)) then
local depotItems = getPlayerDepotItems(cid, getDepotId(depot.uid))
doPlayerSendTextMessage(cid, MESSAGE_STATUS_DEFAULT, "Your depot contains " .. depotItems .. " item" .. (depotItems > 1 and "s" or "") .. ".")
break
end
end
return true
end
return false
end
function onStepOut(cid, item, position, fromPosition)
if(not decreasingItems[item.itemid]) then
return false
end
if(not isPlayerGhost(cid)) then
doTransformItem(item.uid, decreasingItems[item.itemid])
return true
end
return false
end |
local helper = require "kong.plugins.gluu-oauth2-rs.helper"
--- Check uma_server_host is must https and not empty
-- @param given_value: Value of uma_server_host
-- @param given_config: whole config values including uma_server_host
local function uma_server_host_validator(given_value, given_config)
ngx.log(ngx.DEBUG, "uma_server_host_validator: given_value:" .. given_value)
if helper.is_empty(given_value) then
ngx.log(ngx.ERR, "Invalid uma_server_host. It is blank.")
return false
end
if helper.is_empty(given_value) then
ngx.log(ngx.ERR, "Invalid uma_server_host. It is blank.")
return false
end
if not (string.sub(given_value, 0, 8) == "https://") then
ngx.log(ngx.ERR, "Invalid uma_server_host. It does not start from 'https://', value: " .. given_value)
return false
end
return true
end
return {
no_consumer = true,
fields = {
oxd_host = { required = true, type = "string" },
uma_server_host = { required = true, type = "string", func = uma_server_host_validator },
protection_document = { type = "string" },
oauth_scope_expression = { type = "string" },
client_id = { type = "string" },
client_secret = { type = "string" },
oxd_id = { type = "string" },
client_id_of_oxd_id = { type = "string" },
setup_client_oxd_id = { type = "string" }
},
self_check = function(schema, plugin_t, dao, is_updating)
ngx.log(ngx.DEBUG, "is updating" .. tostring(is_updating))
if not helper.is_empty(plugin_t.oxd_id) and not is_updating then
return true
end
if helper.is_empty(plugin_t.protection_document) then
return true
end
if is_updating then
return helper.update_uma_rs(plugin_t), "Failed to update UMA RS on oxd server (make sure oxd server is running on oxd_host specified in configuration)"
else
return helper.register(plugin_t), "Failed to register API on oxd server (make sure oxd server is running on oxd_host specified in configuration)"
end
end
} |
function SmokeOut(keys)
local caster = keys.caster
local ability = keys.ability
local point = keys.target_points[1]
ProjectileManager:ProjectileDodge(caster)
ParticleManager:CreateParticle("particles/items_fx/blink_dagger_start.vpcf", PATTACH_ABSORIGIN, caster)
ability:ApplyDataDrivenThinker(caster, caster:GetAbsOrigin(), "modifier_mirratie_smoke_out", nil)
ability:CreateVisibilityNode(caster:GetAbsOrigin(), 10, ability:GetAbilitySpecial("duration"))
FindClearSpaceForUnit(caster, point, true)
ParticleManager:CreateParticle("particles/items_fx/blink_dagger_end.vpcf", PATTACH_ABSORIGIN, caster)
end |
-- copytable.lua
--[[
Table copying functions.
See: http://www.gammon.com.au/forum/?id=8042
Ideas by Shaun Biggs, David Haley, Nick Gammon
Date: 21st July 2007
This is intended to copy tables (make a real copy, rather than just the table
reference).
You can do a deep or shallow copy.
Shallow: Simply copies the keys and values.
If a value is a table, you will get the same table as in the original.
Deep: Copies keys and values recursively.
If a value is a table, makes a copy of that table, and so on.
Deep copy based on: http://lua-users.org/wiki/CopyTable
Restrictions: Items must be "safe" to copy (eg. not file IO userdata).
The deep copied tables share the same metatable as the original ones.
To change this, change the line:
return setmetatable(new_table, getmetatable(object))
to:
return setmetatable(new_table, _copy (getmetatable(object))
Example:
t1 = {
m = { a = 1, b = 2 },
n = { c = 3, d = 4 },
}
require "copytable" -- load this file
t2 = copytable.shallow (t1) -- shallow copy
t3 = copytable.deep (t1) -- copies sub tables as well
--]]
module (..., package.seeall)
function deep (object)
local lookup_table = {}
local function _copy (object)
if type (object) ~= "table" then
return object
elseif lookup_table [object] then
return lookup_table [object]
end -- if
local new_table = {}
lookup_table [object] = new_table
for index, value in pairs (object) do
new_table [_copy (index)] = _copy (value)
end -- for
return setmetatable (new_table, getmetatable (object))
end -- function _copy
return _copy (object)
end -- function deepcopy
function shallow (t)
assert (type (t) == "table", "You must specify a table to copy")
local result = {}
for k, v in pairs (t) do
result [k] = v
end -- for each table element
-- copy the metatable
return setmetatable (result, getmetatable (t))
end -- function shallow
|
function $funcname(key,data)
-- local obj = model_capnp_$name.$Name.parse(data) --deserialze capnp
-- local name = obj["name"]
-- res0 = model_$name_get(name)
-- if res0 == nil then
-- res = box.space.$name:auto_increment({obj['name'],data}) -- indexes the name
-- id = res[1]
-- else
-- id = res0[1]
-- end
-- if key==0 then
-- res = box.space.$name:auto_increment({data})
-- key = res[1]
-- end
-- obj["id"] = key
-- data = model_capnp_$name.$Name.serialize(obj) --reserialze with id inside
box.space.$name:put{key, data}
return key
end
box.schema.func.create('set', {if_not_exists = true})
box.schema.user.grant('$login', 'execute', 'function','set',{ if_not_exists= true})
|
-- This is a dummy file, for APGs home page! (As the home page is built like a module.) |
LoadLibrary('Asset')
Asset.Run('Dependencies.lua')
Asset.Run('HigherOrder.lua')
Asset.Run('ParseCore.lua')
Asset.Run('PlayController.lua')
gRenderer = Renderer.Create()
gFont = BitmapText:Create(DefaultFontDef)
gPath = "example_1.txt"
gIndicator = Sprite:Create()
gIndicator:SetTexture(Texture.Find("indicator.png"))
gGhostTrack = Sprite:Create()
gGhostTrack:SetTexture(Texture.Find("track.png"))
gPalette =
{
green = RGB(202, 224, 172),
orange = RGB(255, 180, 90),
red = RGB(225, 109, 95),
pale = RGB(236, 219, 203),
blue = RGB(121, 160, 204)
}
gTrackBar = TrackBar:Create
{
x = 0,
y = -100,
width = 512,
height = 8,
color = Vector.Create(0.5, 0.5, 0.5, 1),
texture = Texture.Find("groove.png"),
thumbTexture = Texture.Find("track.png")
}
local trackTime = 5
local trackingTween = Tween:Create(0, 1, trackTime)
local screenW = System.ScreenWidth()*-0.5
local screenH = System.ScreenHeight()*0.5
local tracklabelY = gTrackBar:Bottom() - 4
local stopButton
local playButton
local gPlayController
-- Play buttons
playButton = ModalButton:Create
{
texture = "play.png",
textureOn = "play_on.png",
OnGainFocus = function(self)
self.mBaseSprite:SetColor(Vector.Create(1, 1, 0, 1))
end,
OnLoseFocus = function(self)
self.mBaseSprite:SetColor(Vector.Create(1, 1, 1, 1))
end,
OnClick = function(self)
if not gConversation then return end
print(gPlayController.mState)
if gPlayController:IsPlaying() then
gPlayController:DoPause()
else
gPlayController:DoPlay()
end
end
}
stopButton = ModalButton:Create
{
texture = "stop.png",
textureOn = "stop_on.png",
OnGainFocus = function(self)
self.mBaseSprite:SetColor(Vector.Create(1, 1, 0, 1))
end,
OnLoseFocus = function(self)
self.mBaseSprite:SetColor(Vector.Create(1, 1, 1, 1))
end,
OnClick = function(self)
if not gConversation then return end
gPlayController:DoAtStart()
end
}
stopButton:TurnOn()
local buttonPad = 4
playButton:SetPosition(0 - buttonPad, gTrackBar:Bottom() - 24)
stopButton:SetPosition(0 + 16 + buttonPad, gTrackBar:Bottom() - 24)
gIndicator:SetColor(Vector.Create(0.5,0.5,0.5,1))
FixedSequence = {}
FixedSequence.__index = FixedSequence
function FixedSequence:Create()
local this =
{
mTimeline = {},
mClipIndex = 1,
mRuntime = 0, -- tracks how long the sequence has run for
mEventManager = DiscourseEventManager:Create(),
mPrevValue01 = 0
}
-- Testing
this.mEventManager:AddEvent(0.5)
this.mEventManager:AddEvent(0.75)
this.mEventManager:AddEvent(0.2)
setmetatable(this, self)
return this
end
function FixedSequence:GenerateBoxedTime()
local box = {}
for k, v in ipairs(self.mTimeline) do
table.insert(box, v:GenerateBoxedTime())
end
return box
end
function FixedSequence:JumpTo01(value)
-- printf("FixedSequence Jump01: %.2f -> %.2f %.3f", self.mPrevValue01, value, GetDeltaTime())
-- Need to find the clip, then how much we're into the clip
-- and tell it to jump to that point
self.mRuntime = self:CalcDuration() * value
self.mClipIndex = self:RuntimeToClipIndex()
local time = 0
local findActiveClip = true
for k, v in ipairs(self.mTimeline) do
local prevTime = time
time = time + v:Duration()
if time > self.mRuntime then
if findActiveClip then
-- We're in this clip
local currentClip01 = Lerp(self.mRuntime, prevTime, time, 0, 1)
v:JumpTo01(currentClip01)
findActiveClip = false
else
v:JumpTo01(0)
end
else
v:JumpTo01(1)
end
end
self.mEventManager:Jump01(self.mPrevValue01, value)
self.mPrevValue01 = value
end
function FixedSequence:Duration()
-- There's not reason this can't be cached
return self:CalcDuration()
end
function FixedSequence:CalcDuration()
local duration = 0
for k, v in ipairs(self.mTimeline) do
duration = duration + v:Duration()
end
return duration
end
--
-- Each clip needs:
-- Update
-- Render
-- Jump01
-- Duration
--
function FixedSequence:AddClip(clip)
table.insert(self.mTimeline, clip)
end
function FixedSequence:Update(dt, value01)
local dt = dt or GetDeltaTime()
self.mRuntime = self.mRuntime + dt
local prevIndex = self.mClipIndex
self.mClipIndex = self:RuntimeToClipIndex()
local clip = self.mTimeline[self.mClipIndex]
-- if prevIndex ~= self.mClipIndex then
-- print("Moved to next dialog box")
-- local newlyCreatedTypedText = clip.mTextbox.mTypedText
-- print("Typedtext ", tostring(newlyCreatedTypedText:SeenAllPages()))
-- end
clip:Update(dt)
self.mEventManager:Jump01(self.mPrevValue01, value01)
self.mPrevValue01 = value01
end
function FixedSequence:RuntimeToClipIndex()
-- Takes a time in seconds and transforms it into a clip index
local time = 0
for k, v in ipairs(self.mTimeline) do
time = time + v:Duration()
if time > self.mRuntime then
return k
end
end
-- We're overtime which is fine, we just need to return the last clip
return #self.mTimeline
-- Better way would be to get the current clip index, get it's start
-- time and subtract that
end
function FixedSequence:Render(renderer, trackbar)
local clip = self.mTimeline[self.mClipIndex]
clip:Render(renderer)
self.mEventManager:Render(gRenderer, trackbar)
end
function RawTagsToLookUp(tags)
-- Raw tags look like this
-- {
-- { line = 1, offset = 20, id = "pause", op = "open" },
-- { line = 3, offset = 9, id = "red", open = "open"}
-- ...
-- }
-- We're going to convert them to
--
-- table[line][offset] = { list of tags }
local function CreateTagInstance(id, tagDef)
local tagType = TagDB[id]
if tagType == null then
printf("Error: Failed to find tag type [%s]", tagType)
return
end
return tagType(tagDef) -- creates an instance
end
local lookup = {}
for k, v in ipairs(tags) do
local line = v.line
if v.op == "open" then
print("CREATING INSTANCE", v.id)
v.instance = CreateTagInstance(v.id, v)
end
lookup[line] = lookup[line] or {}
local offset = v.offset
lookup[line][offset] = lookup[line][offset] or {}
table.insert(lookup[line][offset], v)
end
return lookup
end
function TransformScriptTags(script)
for k, v in ipairs(script) do
v.tags = RawTagsToLookUp(v.tags)
end
end
function CreateConversationSequence(script)
local sequence = FixedSequence:Create()
print("Sequence start")
for k, v in ipairs(script) do
-- 1. Create a textbox
local h = 96
local w = math.floor(h * 2.414213)
local textbox = TextboxClip.CreateFixed(gRenderer,
0, 0, w, h,
{
font = gFont,
text = v.text,
tags = v.tags
})
sequence:AddClip(textbox)
end
return sequence
end
gConversation = nil
function LoadConversationScript(script)
-- Tags are per speech unit, so one down from the conversation level.
-- CreateConversationSequence maybe a good place to start?
local speakerMap = {}
for k, v in ipairs(script) do
speakerMap[v.speaker] = true
end
local speakerList = Keys(speakerMap)
local sequence = CreateConversationSequence(script)
local time = sequence:Duration()
local boxedTime = sequence:GenerateBoxedTime()
gConversation =
{
sequence = sequence,
time = time,
boxedTime = boxedTime
}
-- PrintTable(script)
PrintTable(boxedTime)
print(FormatTimeMS(time))
end
function RenderConversation()
local v = trackingTween:Value()
-- go from 1 to 0
v = 1 - v
local remaningTime = gConversation.time
remaningTime = remaningTime * v
local timeStr = FormatTimeMSD(remaningTime)
gFont:AlignText("center", "bottom")
gFont:DrawText2d(gRenderer, 0,-160, timeStr)
local y = gTrackBar:Y() + 16
local x = gTrackBar:LeftTrimmed()
--
-- Working out for boxes as a 0..1 of the full sequence
--
local totalTime = 0
local boxDurationList = {}
for k, box in ipairs(gConversation.boxedTime) do
boxDurationList[k] = 0
for _, entry in ipairs(box) do
totalTime = totalTime + entry.time
boxDurationList[k] = boxDurationList[k] + entry.time
end
end
for k, v in ipairs(gConversation.boxedTime) do
local boxDuration01 = boxDurationList[k] / totalTime
local w = gTrackBar:WidthTrimmed() * boxDuration01
DrawEntry(x, y, w, v, gPalette.red)
x = x + w
end
gConversation.sequence:Render(gRenderer, gTrackBar)
end
function DrawEntry(x, y, w, entry, c)
local subX = x
for k, v in ipairs(entry) do
local subW = w * v.time01
local subC = Vector.Create(c)
if v.id == "outro" or v.id == "intro" then
subC = gPalette.blue
end
if v.id == "pause" then
subC = subC * 0.80
end
-- Leave a 1 pixel gap at the
-- start of each entry
DrawBoxSprite(subX + 1, y, subW - 1, subC)
subX = subX + subW
end
end
function DrawBoxSprite(x, y, w, c)
local c = c or gPalette.blue
local timeBox = Texture.Find("time_box.png")
local textureWidth = timeBox:GetWidth()
local s = Sprite.Create()
local pixelWidth = w/textureWidth
s:SetScale(pixelWidth, 1)
-- Align from left
local alignedX = x + (w*0.5)
s:SetPosition(alignedX, y)
s:SetTexture(timeBox)
s:SetColor(c)
gRenderer:DrawSprite(s)
end
function SetupTrackbar()
-- It would be good to get a tracktime here in 0 to 1 then reapply after
trackTime = gConversation.time
trackingTween = Tween:Create(0, 1, trackTime)
end
function JumpTrackBar(v)
trackingTween:SetValue01(v)
end
function JumpTo01(value)
if gConversation then
playButton:TurnOff()
stopButton:TurnOn()
gConversation.sequence:JumpTo01(value)
JumpTrackBar(value)
gTrackBar:SetValue01(value)
end
end
-- Move all control here
gPlayController = PlayController:Create
{
OnPlay = function()
playButton:TurnOn()
stopButton:TurnOff()
end,
OnPause = function()
playButton:TurnOff()
end,
OnAtStart = function()
playButton:TurnOff()
stopButton:TurnOn()
trackingTween = Tween:Create(0, 1, trackTime)
gTrackBar:SetValue01(0)
if gConversation then
gConversation.sequence:JumpTo01(0)
end
end,
OnAtEnd = function()
playButton:TurnOff()
stopButton:TurnOn()
trackingTween = Tween:Create(1, 1, trackTime)
gTrackBar:SetValue01(1)
if gConversation then
gConversation.sequence:JumpTo01(1)
end
end
}
function handleInput()
if Keyboard.JustPressed(KEY_L) then
local path = string.format("code/project_how_to_rpg/projects/dialog_scripts/%s", gPath)
local f = io.open(path, "rb")
local content = f:read("*all")
f:close()
local script, result = DoParse(content, TagDB:TagsForParser())
if not result.isError then
gIndicator:SetColor(Vector.Create(0.05,0.95,0.05,1))
TransformScriptTags(script)
PrintTable(script)
errorLines = nil
errorLastLine = -1
LoadConversationScript(script)
SetupTrackbar()
else
gIndicator:SetColor(Vector.Create(0.95,0.05,0.05,1))
errorLines = result.errorLines or "unknown error"
errorLastLine = result.lastLine
-- PrintTable(result)
end
end
if Keyboard.JustPressed(KEY_SPACE) and gConversation then
if gPlayController:IsPlaying() then
gPlayController:DoPause()
else
gPlayController:DoPlay()
end
end
if Keyboard.JustPressed(KEY_1) then JumpTo01(0.05) end
if Keyboard.JustPressed(KEY_2) then JumpTo01(0.25) end
if Keyboard.JustPressed(KEY_3) then JumpTo01(0.333) end
if Keyboard.JustPressed(KEY_4) then JumpTo01(0.45) end
end
function MouseInTracker()
local pos = Mouse.Position()
-- Create a rect from the tracker?
local wPad = 20
local hPad = 20
local r = Rect.CreateFromLimits(gTrackBar:Left() - wPad,
gTrackBar:Bottom() - hPad,
gTrackBar:Right() + wPad,
gTrackBar:Top() + hPad)
-- clamp mouse pos to limited rect
return r:IsInside(pos:X(), pos:Y())
end
function ClampMouseToTracker()
local pos = Mouse.Position()
local r = Rect.CreateFromLimits(gTrackBar:LeftTrimmed(),
gTrackBar:Bottom(),
gTrackBar:RightTrimmed(),
gTrackBar:Top())
return r:Clamp(pos)
end
local errorLines = nil
local errorLastLine = -1
function update()
if playButton:IsOn() then
trackingTween:Update()
gTrackBar:SetValue01(trackingTween:Value())
gConversation.sequence:Update(GetDeltaTime(), trackingTween:Value())
if trackingTween:IsFinished() then
gPlayController:DoAtEnd()
end
end
if gConversation then
RenderConversation(gRenderer, gConversation)
end
gTrackBar:Render(gRenderer)
gFont:AlignText("left", "top")
gFont:DrawText2d(gRenderer, screenW + 5, screenH - 5, "Conversation Runner:")
gFont:AlignText("center", "top")
gFont:DrawText2d(gRenderer, gTrackBar:LeftTrimmed(), tracklabelY, "0")
gFont:DrawText2d(gRenderer, gTrackBar:RightTrimmed(), tracklabelY, "1")
stopButton:HandleUpdate()
playButton:HandleUpdate()
stopButton:Render(gRenderer)
playButton:Render(gRenderer)
handleInput()
if errorLastLine > -1 then
local x = -256
-- Print Errors
gFont:DrawText2d(gRenderer, x,0,"Error maybe line " .. tostring(errorLastLine))
for k, v in ipairs(errorLines) do
gFont:DrawText2d(gRenderer, x,k*-16, v)
end
end
gRenderer:DrawSprite(gIndicator)
local loadX = screenW + 32
local loadY = 156
gIndicator:SetPosition(loadX - 10, loadY - 5)
gFont:AlignText("left", "top")
gFont:DrawText2d(gRenderer, loadX, loadY, "PATH:\n " .. gPath)
if MouseInTracker() then
local cPos = ClampMouseToTracker()
gGhostTrack:SetColor(Vector.Create(1,1,0,1))
gGhostTrack:SetPosition(cPos:X(), gTrackBar:Y())
gRenderer:DrawSprite(gGhostTrack)
if Mouse.Held(MOUSE_BUTTON_LEFT) or Mouse.JustReleased(MOUSE_BUTTON_LEFT) then
local v = Lerp(cPos:X(), gTrackBar:LeftTrimmed(), gTrackBar:RightTrimmed(), 0, 1)
JumpTo01(v)
end
end
end
|
{data={name="Teleport Station", author="Magnus siiftun1857 Frankline"}, blocks={
{0x12e3f0, {-23.09, 0}, command={faction=1238}},
{0x12e406, {-21.647, -7.5}, 1.047},
{0x12e406, {-21.647, 7.5}, -1.047},
{0x12e41c, {-51.958, 0}, bindingId=1},
{0x12e41e, {-25.977, 45}},
{0x12e41d, {25.984, 45}},
{0x12e41a, {-25.977, -45}},
{0x12e41f, {25.984, -45}},
{0x12e402, {-92.939, 0}},
{0x12e402, {-122.939, 0}},
{0x12e419, {51.965, 0}},
{0x12e403, {23.098, 10}, -1.047},
{0x12e403, {23.098, -10}, 3.142},
{0x12e402, {-152.939, 0}},
{0x12e402, {-182.939, 0}},
{0x12e402, {-46.467, -80.49}, 1.047},
{0x12e402, {-61.467, -106.471}, 1.047},
{0x12e402, {-76.467, -132.452}, 1.047},
{0x12e402, {-91.467, -158.432}, 1.047},
{0x12e402, {46.475, -80.49}, 2.094},
{0x12e402, {61.475, -106.471}, 2.094},
{0x12e402, {76.475, -132.452}, 2.094},
{0x12e402, {91.475, -158.432}, 2.094},
{0x12e402, {92.946, 0}, 3.142},
{0x12e402, {122.946, 0}, -3.142},
{0x12e402, {152.946, 0}, -3.142},
{0x12e402, {182.946, 0}, -3.142},
{0x12e402, {46.475, 80.491}, -2.094},
{0x12e402, {61.475, 106.471}, -2.094},
{0x12e402, {76.475, 132.452}, -2.094},
{0x12e402, {91.475, 158.433}, -2.094},
{0x12e402, {-46.467, 80.491}, -1.047},
{0x12e402, {-61.467, 106.471}, -1.047},
{0x12e402, {-76.467, 132.452}, -1.047},
{0x12e402, {-91.467, 158.433}, -1.047},
{0x12e40b, {-223.919, 0}},
{0x12e40b, {-249.9, 45}},
{0x12e402, {-229.41, 80.491}, 1.047},
{0x12e402, {-214.41, 106.471}, 1.047},
{0x12e402, {-199.41, 132.452}, 1.047},
{0x12e402, {-184.41, 158.433}, 1.047},
{0x12e40b, {-163.919, 193.923}},
{0x12e40b, {-111.958, 193.923}},
{0x12e40b, {-85.977, 238.923}, -1.047},
{0x12e402, {-44.996, 238.923}},
{0x12e402, {-14.996, 238.923}},
{0x12e402, {15.004, 238.923}},
{0x12e402, {45.004, 238.923}},
{0x12e40b, {85.984, 238.923}, -1.047},
{0x12e40b, {111.965, 193.923}, -1.047},
{0x12e40b, {163.927, 193.923}, -2.094},
{0x12e402, {184.417, 158.433}, -1.047},
{0x12e402, {199.417, 132.452}, -1.047},
{0x12e402, {214.417, 106.471}, -1.047},
{0x12e402, {229.417, 80.491}, -1.047},
{0x12e40b, {249.908, 45}, -2.094},
{0x12e40b, {223.927, 0}, -2.094},
{0x12e40b, {249.908, -45}, -3.142},
{0x12e402, {229.417, -80.49}, -2.094},
{0x12e402, {214.417, -106.471}, -2.094},
{0x12e402, {199.417, -132.452}, -2.094},
{0x12e402, {184.417, -158.432}, -2.094},
{0x12e40b, {163.927, -193.923}, -3.142},
{0x12e40b, {111.965, -193.923}, -3.142},
{0x12e40b, {85.984, -238.923}, 2.094},
{0x12e402, {45.004, -238.923}, -3.142},
{0x12e402, {15.004, -238.923}, -3.142},
{0x12e402, {-14.996, -238.923}, -3.142},
{0x12e402, {-44.996, -238.923}, -3.142},
{0x12e40b, {-85.977, -238.923}, 2.094},
{0x12e40b, {-111.958, -193.923}, 2.094},
{0x12e40b, {-249.9, -45}, 1.047},
{0x12e402, {-229.41, -80.49}, 2.094},
{0x12e402, {-214.41, -106.471}, 2.094},
{0x12e402, {-199.41, -132.452}, 2.094},
{0x12e402, {-184.41, -158.432}, 2.094},
{0x12e40b, {-163.919, -193.923}, 1.047},
{0x12e3fc, {-301.862, 45}},
{0x12e3fc, {-301.862, -45}},
{0x12e3fc, {-327.843, 0}},
{0x12e3f9, {-137.947, -163.928}, -3.142},
{0x12e400, {-162.089, -157.093}, 2.094},
{0x12e400, {55.004, 188.922}},
{0x12e400, {-208.421, -56.825}, 2.094},
{0x12e3f9, {-210.92, -37.495}, 1.047},
{0x12e3f7, {-193.609, -22.499}, -1.047},
{0x12e3f7, {-184.948, -27.499}, -1.047},
{0x12e40c, {-178.118, -34.329}, -1.309},
{0x12e400, {-170.618, -38.659}, 1.571},
{0x12e3f7, {-173.118, -29.329}, -0.524},
{0x12e3f4, {-165.618, -27.886}, -1.571},
{0x12e3fd, {-163.118, -34.329}, 1.309},
{0x12e3fe, {-179.278, -19.999}, -0.262},
{0x12e3fe, {-159.278, -19.999}, -0.262},
{0x12e3fe, {-139.28, -19.996}, -0.262},
{0x12e3fe, {-119.279, -19.997}, -0.262},
{0x12e3fe, {-99.279, -19.998}, -0.262},
{0x12e3fe, {-79.279, -19.999}, -0.262},
{0x12e400, {-182.448, -41.829}, 2.094},
{0x12e3f5, {-192.165, -34.999}},
{0x12e400, {-191.108, -46.829}, 2.094},
{0x12e400, {55.004, 198.924}},
{0x12e400, {-136.126, -142.103}, 2.094},
{0x12e400, {-127.448, -137.103}, 2.094},
{0x12e40c, {-118.787, -137.092}, -0.785},
{0x12e3f7, {-111.957, -135.262}, 1.571},
{0x12e400, {-118.787, -128.432}, 2.618},
{0x12e3fd, {-111.287, -124.102}, 2.88},
{0x12e3f4, {-106.957, -129.489}, 0.524},
{0x12e3fe, {-106.957, -145.262}, 1.309},
{0x12e3fe, {-96.957, -127.942}, 1.309},
{0x12e3fe, {-86.957, -110.621}, 1.309},
{0x12e3fe, {-76.957, -93.301}, 1.309},
{0x12e3fe, {-66.957, -75.98}, 1.309},
{0x12e3fe, {-56.957, -58.66}, 1.309},
{0x12e3f7, {-116.288, -156.423}, -1.047},
{0x12e3f5, {-126.392, -148.933}, -3.142},
{0x12e3f7, {-116.287, -146.423}, -1.047},
{0x12e400, {-144.786, -147.103}, 2.094},
{0x12e400, {-153.438, -152.098}, 2.094},
{0x12e400, {-199.769, -51.83}, 2.094},
{0x12e400, {-217.072, -61.82}, 2.094},
{0x12e3fc, {-189.9, 238.923}, -1.047},
{0x12e3fc, {-163.919, 283.923}, -1.047},
{0x12e3fc, {-111.958, 283.923}, -1.047},
{0x12e3fc, {111.965, 283.923}, -2.094},
{0x12e3fc, {163.927, 283.923}, -2.094},
{0x12e3fc, {189.908, 238.923}, -2.094},
{0x12e3fc, {301.869, 45}, -3.142},
{0x12e3fc, {327.85, 0}, -3.142},
{0x12e3fc, {301.869, -45}, -3.142},
{0x12e3fc, {189.908, -238.923}, 2.094},
{0x12e3fc, {163.927, -283.923}, 2.094},
{0x12e3fc, {111.965, -283.923}, 2.094},
{0x12e3fc, {-111.958, -283.923}, 1.047},
{0x12e3fc, {-163.919, -283.923}, 1.047},
{0x12e3fc, {-189.9, -238.923}, 1.047},
{0x12e400, {-162.072, 157.083}, 1.047},
{0x12e400, {-144.769, 147.093}, 1.047},
{0x12e400, {-208.438, 56.836}, 1.047},
{0x12e400, {-199.786, 51.841}, 1.047},
{0x12e3f5, {-192.174, 34.995}, 2.094},
{0x12e3fe, {72.324, -165.262}, 2.356},
{0x12e3f7, {61.164, -164.592}, 2.618},
{0x12e400, {51.834, -167.092}, -2.618},
{0x12e3fd, {51.834, -158.431}, -2.356},
{0x12e3f4, {58.664, -157.375}, 1.571},
{0x12e40c, {59.334, -171.422}, 0.262},
{0x12e3f7, {68.664, -173.922}},
{0x12e3f7, {77.324, -178.923}},
{0x12e3f9, {72.994, -201.433}, -2.094},
{0x12e400, {55.004, -218.923}, 3.142},
{0x12e3f9, {72.994, 201.414}, -1.047},
{0x12e400, {-54.996, -208.913}, 3.142},
{0x12e3f9, {-72.987, -201.413}, 2.094},
{0x12e3f7, {-77.317, -178.923}},
{0x12e3f7, {-68.657, -173.922}},
{0x12e40c, {-59.327, -171.422}, -0.262},
{0x12e400, {-51.827, -167.092}, 2.618},
{0x12e3f7, {-61.157, -164.592}, 0.524},
{0x12e3f4, {-58.657, -157.375}, -0.524},
{0x12e3fd, {-51.827, -158.432}, 2.356},
{0x12e3fe, {-72.317, -165.262}, 0.785},
{0x12e3fe, {-62.317, -147.942}, 0.785},
{0x12e3fe, {-52.321, -130.621}, 0.785},
{0x12e3fe, {-42.319, -113.301}, 0.785},
{0x12e3fe, {-32.318, -95.98}, 0.785},
{0x12e3fe, {-22.317, -78.66}, 0.785},
{0x12e400, {-54.997, -178.922}, 3.142},
{0x12e3f5, {-65.77, -183.922}, 1.047},
{0x12e400, {-54.996, -188.922}, -3.142},
{0x12e3f7, {68.664, 173.923}, -3.142},
{0x12e400, {55.004, -188.943}, -3.142},
{0x12e400, {55.012, -178.928}, -3.142},
{0x12e3f5, {65.786, -183.928}, -2.094},
{0x12e400, {55.004, -198.943}, 3.142},
{0x12e400, {55.004, -208.933}, 3.142},
{0x12e400, {-54.996, -198.923}, 3.142},
{0x12e400, {-54.996, -218.903}, 3.142},
{0x12e3fe, {62.324, -147.942}, 2.356},
{0x12e3fe, {52.324, -130.621}, 2.356},
{0x12e3fe, {42.324, -113.3}, 2.356},
{0x12e3fe, {32.324, -95.98}, 2.356},
{0x12e3fe, {22.325, -78.66}, 2.356},
{0x12e400, {-182.457, 41.826}, 1.047},
{0x12e400, {-191.126, 46.841}, 1.047},
{0x12e3f7, {77.325, 178.923}, -3.142},
{0x12e400, {-136.108, 142.093}, 1.047},
{0x12e3f5, {-126.391, 148.923}, -1.047},
{0x12e400, {-127.447, 137.094}, 1.047},
{0x12e3fe, {-56.957, 58.661}, -1.309},
{0x12e3fe, {-66.957, 75.982}, -1.309},
{0x12e3fe, {-76.956, 93.304}, -1.309},
{0x12e3fe, {-86.955, 110.625}, -1.309},
{0x12e3fe, {-96.957, 127.942}, -1.309},
{0x12e3fe, {-106.958, 145.263}, -1.309},
{0x12e3fd, {-111.287, 124.103}, 0.262},
{0x12e3f4, {-106.957, 129.489}, -2.618},
{0x12e3f7, {-111.957, 135.263}, -1.571},
{0x12e400, {-118.787, 128.433}, 0.524},
{0x12e40c, {-118.787, 137.093}, -2.356},
{0x12e3f7, {-116.287, 146.424}, -2.094},
{0x12e3f7, {-116.288, 156.424}, -2.094},
{0x12e3f9, {-137.93, 163.918}},
{0x12e3fe, {159.285, -19.999}, -2.88},
{0x12e3fe, {139.285, -19.999}, -2.88},
{0x12e3fe, {119.285, -19.999}, -2.88},
{0x12e3fe, {99.285, -19.999}, -2.88},
{0x12e3fe, {79.286, -19.999}, -2.88},
{0x12e3fe, {179.285, -19.999}, -2.88},
{0x12e3f7, {173.125, -29.329}, -2.618},
{0x12e400, {170.625, -38.659}, -1.571},
{0x12e3fd, {163.125, -34.329}, -1.309},
{0x12e3f4, {165.625, -27.886}, 2.618},
{0x12e40c, {178.125, -34.329}, 1.309},
{0x12e3f7, {184.955, -27.499}, 1.047},
{0x12e3f7, {193.616, -22.499}, 1.047},
{0x12e3f9, {210.945, -37.505}, -1.047},
{0x12e400, {217.097, -61.83}, -2.094},
{0x12e3f5, {65.777, 183.923}, -2.094},
{0x12e400, {153.428, -152.088}, -2.094},
{0x12e3f9, {137.938, -163.918}, 3.142},
{0x12e3f7, {116.295, -156.423}, 1.047},
{0x12e3f7, {116.295, -146.423}, 1.047},
{0x12e40c, {118.795, -137.093}, 0.785},
{0x12e400, {118.795, -128.433}, -2.618},
{0x12e3f7, {111.965, -135.263}, 1.571},
{0x12e3f4, {106.964, -129.489}, 0.524},
{0x12e3fd, {111.294, -124.102}, -2.88},
{0x12e3fe, {106.965, -145.263}, 1.833},
{0x12e3fe, {96.965, -127.942}, 1.833},
{0x12e3fe, {86.963, -110.624}, 1.833},
{0x12e3fe, {76.964, -93.303}, 1.833},
{0x12e3fe, {66.964, -75.982}, 1.833},
{0x12e3fe, {56.965, -58.66}, 1.833},
{0x12e400, {127.455, -137.093}, -2.094},
{0x12e3f5, {126.399, -148.923}, 2.094},
{0x12e400, {136.115, -142.092}, -2.094},
{0x12e400, {55.005, 178.923}},
{0x12e400, {191.133, -46.84}, -2.094},
{0x12e400, {182.464, -41.825}, -2.094},
{0x12e3f5, {192.181, -34.995}, -1.047},
{0x12e400, {199.794, -51.84}, -2.094},
{0x12e400, {208.445, -56.835}, -2.094},
{0x12e400, {144.776, -147.093}, -2.094},
{0x12e400, {162.08, -157.083}, -2.094},
{0x12e400, {-153.421, 152.088}, 1.047},
{0x12e40c, {59.334, 171.423}, 2.88},
{0x12e400, {-217.089, 61.831}, 1.047},
{0x12e3f9, {-210.938, 37.505}, 2.094},
{0x12e3f7, {-193.608, 22.5}, -2.094},
{0x12e3f7, {-184.948, 27.5}, -2.094},
{0x12e40c, {-178.117, 34.33}, -1.833},
{0x12e3f4, {-165.617, 27.886}, -0.524},
{0x12e3fd, {-163.117, 34.33}, 1.833},
{0x12e400, {-170.618, 38.66}, 1.571},
{0x12e3f7, {-173.117, 29.33}, 0.524},
{0x12e3fe, {-179.278, 20}, 0.262},
{0x12e3fe, {-159.278, 20}, 0.262},
{0x12e3fe, {-139.278, 20}, 0.262},
{0x12e3fe, {-119.278, 20}, 0.262},
{0x12e3fe, {-79.278, 20}, 0.262},
{0x12e3fe, {-99.278, 20}, 0.262},
{0x12e3f7, {-68.657, 173.922}, 3.142},
{0x12e3f5, {-65.778, 183.928}, 1.047},
{0x12e400, {-54.996, 198.943}},
{0x12e3fe, {86.963, 110.625}, -1.833},
{0x12e3fe, {76.964, 93.303}, -1.833},
{0x12e3fe, {66.964, 75.982}, -1.833},
{0x12e3fe, {56.965, 58.661}, -1.833},
{0x12e3fe, {96.965, 127.942}, -1.833},
{0x12e3fe, {106.965, 145.263}, -1.833},
{0x12e3f7, {111.964, 135.263}, -1.571},
{0x12e400, {118.794, 128.433}, -0.524},
{0x12e3fd, {111.294, 124.102}, -0.262},
{0x12e3f4, {106.964, 129.489}, -2.618},
{0x12e40c, {118.794, 137.093}, 2.356},
{0x12e3f7, {116.295, 146.423}, 2.094},
{0x12e3f7, {116.295, 156.423}, 2.094},
{0x12e3f9, {137.955, 163.928}},
{0x12e400, {162.097, 157.093}, -1.047},
{0x12e3f7, {61.165, 164.593}, -2.618},
{0x12e400, {208.428, 56.826}, -1.047},
{0x12e3f9, {210.928, 37.495}, -2.094},
{0x12e3f7, {193.616, 22.5}, 2.094},
{0x12e3f7, {184.956, 27.5}, 2.094},
{0x12e40c, {178.125, 34.33}, 1.833},
{0x12e400, {170.626, 38.66}, -1.571},
{0x12e3f7, {173.125, 29.33}, 2.618},
{0x12e3f4, {165.625, 27.886}, 1.571},
{0x12e3fd, {163.125, 34.33}, -1.833},
{0x12e3fe, {179.286, 20}, 2.88},
{0x12e3fe, {159.285, 20}, 2.88},
{0x12e3fe, {139.286, 20}, 2.88},
{0x12e3fe, {119.286, 20}, 2.88},
{0x12e3fe, {99.285, 20}, 2.88},
{0x12e3fe, {79.286, 20}, 2.88},
{0x12e400, {182.456, 41.829}, -1.047},
{0x12e3f5, {192.172, 35}, -3.142},
{0x12e400, {191.115, 46.83}, -1.047},
{0x12e400, {51.835, 167.093}, -0.524},
{0x12e400, {136.133, 142.103}, -1.047},
{0x12e400, {127.456, 137.103}, -1.047},
{0x12e3f5, {126.399, 148.933}},
{0x12e400, {144.794, 147.103}, -1.047},
{0x12e400, {153.445, 152.098}, -1.047},
{0x12e400, {199.776, 51.831}, -1.047},
{0x12e400, {217.08, 61.821}, -1.047},
{0x12e400, {-54.996, 208.934}},
{0x12e400, {55.004, 218.904}},
{0x12e400, {55.004, 208.914}},
{0x12e3fd, {51.834, 158.432}, -0.785},
{0x12e400, {-54.996, 218.924}},
{0x12e3f9, {-72.987, 201.433}, 1.047},
{0x12e3f7, {-77.317, 178.923}, 3.142},
{0x12e3fe, {-22.317, 78.66}, -0.785},
{0x12e3fe, {-32.317, 95.981}, -0.785},
{0x12e3fe, {-42.317, 113.301}, -0.785},
{0x12e3fe, {-52.317, 130.621}, -0.785},
{0x12e3fe, {-62.317, 147.942}, -0.785},
{0x12e3fe, {-72.317, 165.262}, -0.785},
{0x12e3f4, {-58.657, 157.375}, -1.571},
{0x12e3fd, {-51.827, 158.432}, 0.785},
{0x12e400, {-51.827, 167.092}, 0.524},
{0x12e3f7, {-61.157, 164.592}, -0.524},
{0x12e40c, {-59.327, 171.422}, -2.88},
{0x12e400, {-55.005, 178.928}},
{0x12e400, {-54.996, 188.943}},
{0x12e3fe, {32.326, 95.981}, -2.356},
{0x12e3fe, {22.325, 78.66}, -2.356},
{0x12e3fe, {42.327, 113.301}, -2.356},
{0x12e3fe, {52.328, 130.621}, -2.356},
{0x12e3fe, {62.324, 147.942}, -2.356},
{0x12e3fe, {72.325, 165.263}, -2.356},
{0x12e3f4, {58.664, 157.376}, 2.618},
{0x12e42a, {185.275, -106.966}, -0.524, bindingId=1},
{0x12e42a, {167.963, -96.971}, -0.524, bindingId=1},
{0x12e42a, {0.004, -193.943}, -1.571, bindingId=1},
{0x12e42a, {0.004, -213.933}, -1.571, bindingId=1},
{0x12e42a, {-167.956, -96.971}, -2.618, bindingId=1},
{0x12e42a, {-185.251, -106.957}, -2.618, bindingId=1},
{0x12e42a, {-167.956, 96.972}, 2.618, bindingId=1},
{0x12e42a, {-185.251, 106.957}, 2.618, bindingId=1},
{0x12e42a, {0.004, 213.934}, 1.571, bindingId=1},
{0x12e42a, {0.003, 193.92}, 1.571, bindingId=1},
{0x12e42a, {185.275, 106.967}, 0.524, bindingId=1},
{0x12e42a, {167.964, 96.972}, 0.524, bindingId=1},
{0x12e410, {21.654, 0}, 3.142, bindingId=2}}} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.