content
stringlengths 5
1.05M
|
|---|
--
-- tests/actions/vstudio/cs2005/test_build_events.lua
-- Check generation of pre- and post-build commands for C# projects.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local suite = test.declare("vstudio_cs2005_build_events")
local cs2005 = premake.vstudio.cs2005
--
-- Setup
--
local sln, prj, cfg
function suite.setup()
io.esc = premake.vstudio.vs2005.esc
sln = test.createsolution()
end
local function prepare(platform)
prj = premake.solution.getproject(sln, 1)
cs2005.buildEvents(prj)
end
--
-- If no build steps are specified, nothing should be written.
--
function suite.noOutput_onNoEvents()
prepare()
test.isemptycapture()
end
--
-- If one command set is used and not the other, only the one should be written.
--
function suite.onlyOne_onPreBuildOnly()
prebuildcommands { "command1" }
prepare()
test.capture [[
<PropertyGroup>
<PreBuildEvent>command1</PreBuildEvent>
</PropertyGroup>
]]
end
function suite.onlyOne_onPostBuildOnly()
postbuildcommands { "command1" }
prepare()
test.capture [[
<PropertyGroup>
<PostBuildEvent>command1</PostBuildEvent>
</PropertyGroup>
]]
end
function suite.both_onBoth()
prebuildcommands { "command1" }
postbuildcommands { "command2" }
prepare()
test.capture [[
<PropertyGroup>
<PreBuildEvent>command1</PreBuildEvent>
<PostBuildEvent>command2</PostBuildEvent>
</PropertyGroup>
]]
end
--
-- Multiple commands are separated with escaped EOL characters.
--
function suite.splits_onMultipleCommands()
postbuildcommands { "command1", "command2" }
prepare()
test.capture [[
<PropertyGroup>
<PostBuildEvent>command1
command2</PostBuildEvent>
</PropertyGroup>
]]
end
|
local null_uuid_per_db_type = {
cassandra = "00000000-0000-0000-0000-000000000000",
postgres = nil
}
local function get_null_uuid(db_type)
return null_uuid_per_db_type[db_type]
end
return get_null_uuid
|
local function filter(t, f)
local nt = {}
for _,v in pairs(t) do
if f(v) then table.insert(nt, v) end
end
return nt
end
local function prune(bins, pos, tb)
local count = 0
local ch = ''
for _,n in ipairs(bins) do
if n:sub(pos, pos) == '1' then
count = count + 1
else
count = count - 1
end
end
if tb == 1 then
if count >= 0 then
ch = '1'
else
ch = '0'
end
else
if count >= 0 then
ch = '0'
else
ch = '1'
end
end
local filtered = filter(bins, function (n)
return n:sub(pos, pos) == ch
end)
if #filtered == 1 then
return filtered[1]
else
return prune(filtered, pos + 1, tb)
end
end
local binaries = {}
for line in io.lines() do
table.insert(binaries, line)
end
local oxygen = prune(binaries, 1, 1)
local co2 = prune(binaries, 1, 0)
print(oxygen, tonumber(oxygen, 2))
print(co2, tonumber(co2, 2))
print(tonumber(oxygen, 2) * tonumber(co2, 2))
|
function start(song) -- do nothing
end
function update(elapsed) -- do nothing
end
function beatHit(beat) -- do nothing
end
function stepHit(step)
if step == 412 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 414 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 620 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 622 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 795 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 798 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 956 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 958 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 1212 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 1214 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 1564 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
if step == 1566 then
playActorAnimation("dad","hehe",false,false)
print ("heh")
end
end
|
-- How to define game objects in the scene file
-- Step1: HowManyGameObjects must contain one more number than the last go_X that was declared because these start at 0
-- If you want to add a go add one to this variable
-- Step2: Structure
-- go_Number = {} -> where "Number" is the next to the last go declared
-- go_Number[0] = { Name = "", HowManyCmps = X} -> Name is the name of the GameObject. HowManyCmps is the number of components of the go
-- go_Number[1] = { Component = " ", General Data} -> Component is the ENUM used to identify the COMPONENT (getComponentType method from LuaParser).
-- General Data is the component data
-- You must bear in mind that in the definition of go, the first position of the array will always be the data that it needs to know its name
-- and how many components it has. The following positions in the array will be used to define the components
-- You can find component definition examples at the end of this document
HowManyGameObjects = 134
-- Player
go_0 = {}
go_0[0] = { Name = "Player", HowManyCmps = 13, Persist = false}
go_0[1] = { Component = "Transform", Coord = {X = 0, Y = 1.75, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=1, Y = 2, Z = 1}}
go_0[2] = { Component = "Camera", Plane = {Near = 0.1, Far = 100}, Compositors = {"JugadorVisionWeak", false, "JugadorVisionStrong", false, "JugadorVisionInjured", false}, SlaveRotation=false}
go_0[3] = { Component = "Listener", ListenerNumber = 0, Velocity = {X = 0, Y = 0, Z = 0} }
go_0[4] = { Component = "PlayerInteractiveComponent" }
go_0[5] = { Component = "PlayerKeysComponent"}
go_0[6] = { Component = "HealthComponent", HP=2 }
go_0[7] = { Component = "PlayerVisibilityComponent" }
go_0[8] = { Component = "RigidBody", Type="Box", Mass=10, Width=0.25,Height=1,Depth=0.25, Kinematic = false, ConstrainAngle = true, IsTrigger=false}
go_0[9] = { Component = "PlayerMovementComponent", SpeedForward = 320, SpeedSideWays = 260, SpeedBackwards = 260, CameraSpeed = 15, SlowCrouching = 0.5}
go_0[10] = { Component = "PlayerLookEnemyGlitchComponent"}
go_0[11] = { Component = "UIManagerComponent"}
go_0[12] = { Component = "AudioSource", Route = {"Assets/Audio/FootStep2.wav", "Assets/Audio/Footsteps1.ogg"}}
go_0[13] = { Component = "LightComponent", LightType= "POINT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 1, Blue = 1},
Specular = {Red = 1, Green= 1, Blue = 1},
LightDirection = {X = 0, Y = 0, Z = 0},
Intensity=5}
-- Suelo
go_1 = {}
go_1[0] = { Name = "Suelo", HowManyCmps = 3, Persist = false}
go_1[1] = { Component = "Transform", Coord = {X = 0, Y = -0.5, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 200, Y = 1, Z = 150}}
go_1[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_1[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- FirstAidKit
go_2 = {}
go_2[0] = { Name = "FirstAidKit", HowManyCmps = 5, Persist = false}
go_2[1] = { Component = "Transform", Coord = {X = -23.25, Y = 1.75, Z = 8.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .8, Y = 1, Z = .8}}
go_2[2] = { Component = "RenderObject", MeshName="firstAid.mesh", Material="botiquin", Visible=true, Shadows=false, RenderingDistance = 50}
go_2[3] = { Component = "BoxCollider", Type="Box",Width=1,Height=10,Depth=1,IsTrigger=true}
go_2[4] = { Component = "FirstAidKitComponent", HealthAmount = 1 }
go_2[5] = { Component = "AudioSource", Route = {"Assets/Audio/Bandage.wav" }, StopOnDestroy = false}
go_3 = {}
go_3[0] = { Name = "Key", HowManyCmps = 5, Persist = false}
go_3[1] = { Component = "Transform", Coord = {X = 30, Y = 0.4, Z = 8.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 0.8, Y = 0.8, Z = 0.8}}
go_3[2] = { Component = "RenderObject", MeshName="key.mesh", Material="key", Visible=true, Shadows=false, RenderingDistance = 50}
go_3[3] = { Component = "SphereCollider",Radius=1,IsTrigger=true}
go_3[4] = { Component = "KeyComponent" }
go_3[5] = { Component = "AudioSource", Route = {"Assets/Audio/KeyPickUp.wav" }, StopOnDestroy = false}
go_4 = {}
go_4[0] = { Name = "Puerta", HowManyCmps = 6, Persist = false}
go_4[1] = { Component = "Transform", Coord = {X = -35.5, Y = 2, Z = 17.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 13, Y = 4, Z = 1}}
go_4[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Orange", Visible=true, Shadows=false, RenderingDistance = 50}
go_4[3] = { Component = "SphereCollider",Radius=10,IsTrigger=true}
go_4[4] = { Component = "BoxCollider", Type="Box", Width=1, Height=1, Depth=1, IsTrigger=false}
go_4[5] = { Component = "AudioSource", Route = {"Assets/Audio/Lock.wav" }, StopOnDestroy = false}
go_4[6] = { Component = "DoorComponent" }
-- UI Manager
go_5 = {}
go_5[0] = { Name = "UIManager", HowManyCmps = 2, Persist = false}
go_5[1] = { Component = "Transform"}
go_5[2] = { Component = "OverlayComponent", Name = "GameUI", Hide = false}
-- Bush parte 1
go_6 = {}
go_6[0] = { Name = "Bush1", HowManyCmps = 4, Persist = false}
go_6[1] = { Component = "Transform", Coord = {X = -29.1, Y = 1, Z = -6.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.75, Y = 2, Z = 1.5}}
go_6[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Bush", Visible=true, Shadows=false, RenderingDistance = 50}
go_6[3] = { Component = "SphereCollider", Radius=1,IsTrigger=true}
go_6[4] = { Component = "HideoutComponent" }
-- Trampa
go_7 = {}
go_7[0] = { Name = "Trampa1", HowManyCmps = 5, Persist = false}
go_7[1] = { Component = "Transform", Coord = {X = -16.8, Y = 0.1, Z = -11.7}, Rotation = {X = -90, Y = 0, Z = 0}, Scale = {X = 1.6, Y = 1.8, Z = 3.6}}
go_7[2] = { Component = "RenderObject", MeshName="spikes.mesh", Material="pincho", Visible=true, Shadows=true, RenderingDistance = 50}
go_7[3] = { Component = "BoxCollider", Type="Box",Width=1,Height=1,Depth=50,IsTrigger=true}
go_7[4] = { Component = "TrapComponent",EnabledMaterial="Practica1/Red"}
go_7[5] = { Component = "AudioSource", Route = {"Assets/Audio/MetalHit.wav" }, StopOnDestroy = false}
-- Desactivador
go_8 = {}
go_8[0] = { Name = "Desactivador1", HowManyCmps = 5, Persist = false}
go_8[1] = { Component = "Transform", Coord = {X = -16.8, Y = 0.2, Z = -12.2}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .3, Y = .4, Z = .3}}
go_8[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Metal", Visible=true, Shadows=true, RenderingDistance = 50}
go_8[3] = { Component = "SphereCollider",Radius=2,IsTrigger=true}
go_8[4] = { Component = "ObjectDeactivatorComponent",ObjName="Trampa1"}
go_8[5] = { Component = "AudioSource", Route = {"Assets/Audio/SwitchSound.mp3" }, StopOnDestroy = false}
-- Paredes
-- SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN SPAWN
go_9 = {}
go_9[0] = { Name = "ParedS1", HowManyCmps = 3, Persist = false}
go_9[1] = { Component = "Transform", Coord = {X = -5, Y = 2, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=5, Y = 4, Z = 5}}
go_9[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_9[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_10 = {}
go_10[0] = { Name = "ParedS2", HowManyCmps = 3, Persist = false}
go_10[1] = { Component = "Transform", Coord = {X = 5.75, Y = 2, Z = 0.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 7.5, Y = 4, Z = 6}}
go_10[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_10[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_11 = {}
go_11[0] = { Name = "ParedS3", HowManyCmps = 3, Persist = false}
go_11[1] = { Component = "Transform", Coord = {X = 0, Y = 2, Z = 4.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 10, Y = 4, Z = 4}}
go_11[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_11[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_12 = {}
go_12[0] = { Name = "ParedS4", HowManyCmps = 3, Persist = false}
go_12[1] = { Component = "Transform", Coord = {X = -5, Y = 2, Z = 3.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_12[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_12[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A ZONA A
go_13 = {}
go_13[0] = { Name = "ParedA1", HowManyCmps = 3, Persist = false}
go_13[1] = { Component = "Transform", Coord = {X = -1.5, Y = 2, Z = -5.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=9, Y = 4, Z = 1}}
go_13[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_13[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_14 = {}
go_14[0] = { Name = "ParedA2", HowManyCmps = 3, Persist = false}
go_14[1] = { Component = "Transform", Coord = {X = 6.25, Y = 2, Z = -6.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=3, Y = 4, Z = 3}}
go_14[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_14[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_15 = {}
go_15[0] = { Name = "ParedA3", HowManyCmps = 3, Persist = false}
go_15[1] = { Component = "Transform", Coord = {X = 1, Y = 2, Z = -7.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=4, Y = 4, Z = 0.75}}
go_15[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_15[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_16 = {}
go_16[0] = { Name = "ParedA4", HowManyCmps = 3, Persist = false}
go_16[1] = { Component = "Transform", Coord = {X = -4.25, Y = 2, Z = -7}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=3.5, Y = 4, Z = 2}}
go_16[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_16[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_17 = {}
go_17[0] = { Name = "ParedA5", HowManyCmps = 3, Persist = false}
go_17[1] = { Component = "Transform", Coord = {X = -4.25, Y = 2, Z = -10.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=3.5, Y = 4, Z = 2}}
go_17[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_17[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_18 = {}
go_18[0] = { Name = "ParedA6", HowManyCmps = 3, Persist = false}
go_18[1] = { Component = "Transform", Coord = {X = -0.5, Y = 2, Z = -11.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=11, Y = 4, Z = 1}}
go_18[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_18[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_19 = {}
go_19[0] = { Name = "ParedA7", HowManyCmps = 3, Persist = false}
go_19[1] = { Component = "Transform", Coord = {X = 0.5, Y = 2, Z = -8.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=3, Y = 4, Z = 2}}
go_19[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_19[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_20 = {}
go_20[0] = { Name = "ParedA8", HowManyCmps = 3, Persist = false}
go_20[1] = { Component = "Transform", Coord = {X = 4.5, Y = 2, Z = -10.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=6, Y = 4, Z = 2}}
go_20[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_20[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
--- ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B ZONA B
go_21 = {}
go_21[0] = { Name = "ParedB1", HowManyCmps = 3, Persist = false}
go_21[1] = { Component = "Transform", Coord = {X = 11.75, Y = 2, Z = -10.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=4.5, Y = 4, Z = 3}}
go_21[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_21[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_22 = {}
go_22[0] = { Name = "ParedB2", HowManyCmps = 3, Persist = false}
go_22[1] = { Component = "Transform", Coord = {X = 18.625, Y = 2, Z = -10.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=5.75, Y = 4, Z = 3}}
go_22[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_22[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_23 = {}
go_23[0] = { Name = "ParedB3", HowManyCmps = 3, Persist = false}
go_23[1] = { Component = "Transform", Coord = {X = 12.75, Y = 2, Z = -6.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=6.5, Y = 4, Z = 2.8}}
go_23[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_23[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_24 = {}
go_24[0] = { Name = "ParedB4", HowManyCmps = 3, Persist = false}
go_24[1] = { Component = "Transform", Coord = {X = 19.5, Y = 2, Z = -7.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=4, Y = 4, Z = 4.5}}
go_24[2] = {Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo",Visible=true, Shadows=true, RenderingDistance = 1000}
go_24[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C ZONA C
go_25 = {}
go_25[0] = { Name = "ParedC1", HowManyCmps = 3, Persist = false}
go_25[1] = { Component = "Transform", Coord = {X = 12.5, Y = 2, Z = 0.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 6}}
go_25[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_25[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_26 = {}
go_26[0] = { Name = "ParedC2", HowManyCmps = 3, Persist = false}
go_26[1] = { Component = "Transform", Coord = {X = 10.5, Y = 2, Z = 6.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 6, Y = 4, Z = 3}}
go_26[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_26[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_27 = {}
go_27[0] = { Name = "ParedC3", HowManyCmps = 3, Persist = false}
go_27[1] = { Component = "Transform", Coord = {X = 17.5, Y = 2, Z = -0.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 4}}
go_27[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_27[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_28 = {}
go_28[0] = { Name = "ParedC4", HowManyCmps = 3, Persist = false}
go_28[1] = { Component = "Transform", Coord = {X = 17.5, Y = 2, Z = 7.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 4}}
go_28[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_28[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_29 = {}
go_29[0] = { Name = "ParedC5", HowManyCmps = 3, Persist = false}
go_29[1] = { Component = "Transform", Coord = {X = 19, Y = 2, Z = 3.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 4}}
go_29[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_29[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_30 = {}
go_30[0] = { Name = "ParedC6", HowManyCmps = 3, Persist = false}
go_30[1] = { Component = "Transform", Coord = {X = 15.5, Y = 2, Z = 2}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 4, Z = 1}}
go_30[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_30[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_31 = {}
go_31[0] = { Name = "ParedC7", HowManyCmps = 3, Persist = false}
go_31[1] = { Component = "Transform", Coord = {X = 15.5, Y = 2, Z = 5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 4, Z = 1}}
go_31[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_31[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D ZONA D
go_32 = {}
go_32[0] = { Name = "ParedD1", HowManyCmps = 3, Persist = false}
go_32[1] = { Component = "Transform", Coord = {X = 24.5, Y = 2, Z = -1.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=6, Y = 4, Z = 2}}
go_32[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_32[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_33 = {}
go_33[0] = { Name = "ParedD2", HowManyCmps = 3, Persist = false}
go_33[1] = { Component = "Transform", Coord = {X = 25.5, Y = 2, Z = -3.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=4, Y = 4, Z = 2.5}}
go_33[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_33[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_34 = {}
go_34[0] = { Name = "ParedD3", HowManyCmps = 3, Persist = false}
go_34[1] = { Component = "Transform", Coord = {X = 23.25, Y = 2, Z = 6.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=3, Y = 4, Z = 6}}
go_34[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_34[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_35 = {}
go_35[0] = { Name = "ParedD4", HowManyCmps = 3, Persist = false}
go_35[1] = { Component = "Transform", Coord = {X = 24.75, Y = 2, Z = 2.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=6, Y = 4, Z = 2}}
go_35[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_35[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E ZONA E
go_36 = {}
go_36[0] = { Name = "ParedE1", HowManyCmps = 3, Persist = false}
go_36[1] = { Component = "Transform", Coord = {X = -14.5, Y = 2, Z = -1.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2.5}}
go_36[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_36[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_37 = {}
go_37[0] = { Name = "ParedE2", HowManyCmps = 3, Persist = false}
go_37[1] = { Component = "Transform", Coord = {X = -12.5, Y = 2, Z = -3}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 1.5}}
go_37[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_37[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_38 = {}
go_38[0] = { Name = "ParedE3", HowManyCmps = 3, Persist = false}
go_38[1] = { Component = "Transform", Coord = {X = -18, Y = 2, Z = -8}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 10, Y = 4, Z = 5.5}}
go_38[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_38[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_39 = {}
go_39[0] = { Name = "ParedE4", HowManyCmps = 3, Persist = false}
go_39[1] = { Component = "Transform", Coord = {X = -11.75, Y = 2, Z = -7}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 3.5, Y = 4, Z = 7.5}}
go_39[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_39[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_40 = {}
go_40[0] = { Name = "ParedE5", HowManyCmps = 3, Persist = false}
go_40[1] = { Component = "Transform", Coord = {X = -20.5, Y = 2, Z = -4}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 3}}
go_40[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_40[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_41 = {}
go_41[0] = { Name = "ParedE6", HowManyCmps = 3, Persist = false}
go_41[1] = { Component = "Transform", Coord = {X = -18.75, Y = 2, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.5, Y = 4, Z = 5}}
go_41[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_41[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_42 = {}
go_42[0] = { Name = "ParedE7", HowManyCmps = 3, Persist = false}
go_42[1] = { Component = "Transform", Coord = {X = -17.55, Y = 2, Z = 3.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 3.75, Y = 4, Z = 2}}
go_42[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_42[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_43 = {}
go_43[0] = { Name = "ParedE8", HowManyCmps = 3, Persist = false}
go_43[1] = { Component = "Transform", Coord = {X = -26, Y = 2, Z = 2.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 13, Y = 4, Z = 4.5}}
go_43[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_43[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F ZONA F
go_44 = {}
go_44[0] = { Name = "ParedF1", HowManyCmps = 3, Persist = false}
go_44[1] = { Component = "Transform", Coord = {X = -12, Y = 2, Z = 4}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 3, Y = 4, Z = 3.5}}
go_44[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_44[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_45 = {}
go_45[0] = { Name = "ParedF2", HowManyCmps = 3, Persist = false}
go_45[1] = { Component = "Transform", Coord = {X = -9.75, Y = 2, Z = 3}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.5, Y = 4, Z = 5.5}}
go_45[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_45[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_46 = {}
go_46[0] = { Name = "ParedF3", HowManyCmps = 3, Persist = false}
go_46[1] = { Component = "Transform", Coord = {X = -8.5, Y = 2, Z = 5.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 4, Z = 1}}
go_46[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_46[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G ZONA G
go_47 = {}
go_47[0] = { Name = "ParedG1", HowManyCmps = 3, Persist = false}
go_47[1] = { Component = "Transform", Coord = {X = -11, Y = 2, Z = 9}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 7, Y = 4, Z = 2}}
go_47[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_47[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_48 = {}
go_48[0] = { Name = "ParedG2", HowManyCmps = 3, Persist = false}
go_48[1] = { Component = "Transform", Coord = {X = -13.5, Y = 2, Z = 14.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 10}}
go_48[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_48[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_49 = {}
go_49[0] = { Name = "ParedG3", HowManyCmps = 3, Persist = false}
go_49[1] = { Component = "Transform", Coord = {X = -10, Y = 2, Z = 19.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 6, Y = 4, Z = 4}}
go_49[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_49[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_50 = {}
go_50[0] = { Name = "ParedG4", HowManyCmps = 3, Persist = false}
go_50[1] = { Component = "Transform", Coord = {X = -11.5, Y = 2, Z = 16.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_50[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_50[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_51 = {}
go_51[0] = { Name = "ParedG5", HowManyCmps = 3, Persist = false}
go_51[1] = { Component = "Transform", Coord = {X = -8, Y = 2, Z = 16.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_51[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_51[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_52 = {}
go_52[0] = { Name = "ParedG6", HowManyCmps = 3, Persist = false}
go_52[1] = { Component = "Transform", Coord = {X = -7.5, Y = 2, Z = 10}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.5, Y = 4, Z = 4}}
go_52[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_52[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_53 = {}
go_53[0] = { Name = "ParedG7", HowManyCmps = 3, Persist = false}
go_53[1] = { Component = "Transform", Coord = {X = -9, Y = 2, Z = 12.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4.5, Y = 4, Z = 2}}
go_53[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_53[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1 LIMITES PARTE 1
go_54 = {}
go_54[0] = { Name = "ParedLimite1", HowManyCmps = 3, Persist = false}
go_54[1] = { Component = "Transform", Coord = {X = 10.5, Y = 2, Z = -19}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 34, Y = 4, Z = 10}}
go_54[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_54[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_55 = {}
go_55[0] = { Name = "ParedLimite2", HowManyCmps = 3, Persist = false}
go_55[1] = { Component = "Transform", Coord = {X = 28.5, Y = 2, Z = -10.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 10, Y = 4, Z = 7}}
go_55[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_55[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_56 = {}
go_56[0] = { Name = "ParedLimite3", HowManyCmps = 3, Persist = false}
go_56[1] = { Component = "Transform", Coord = {X = 31.5, Y = 2, Z = -2}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 11}}
go_56[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_56[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_57 = {}
go_57[0] = { Name = "ParedLimite4", HowManyCmps = 3, Persist = false}
go_57[1] = { Component = "Transform", Coord = {X = 33, Y = 2, Z = 7.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 8}}
go_57[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_57[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_58 = {}
go_58[0] = { Name = "ParedLimite5", HowManyCmps = 3, Persist = false}
go_58[1] = { Component = "Transform", Coord = {X = -7.5, Y = 2, Z = -20}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_58[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_58[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_59 = {}
go_59[0] = { Name = "ParedLimite6", HowManyCmps = 3, Persist = false}
go_59[1] = { Component = "Transform", Coord = {X = -16.75, Y = 2, Z = -17.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 16.5, Y = 4, Z = 10}}
go_59[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_59[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_60 = {}
go_60[0] = { Name = "ParedLimite7", HowManyCmps = 3, Persist = false}
go_60[1] = { Component = "Transform", Coord = {X = -27.5, Y = 2, Z = -10.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 5.5}}
go_60[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_60[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_61 = {}
go_61[0] = { Name = "ParedLimite8", HowManyCmps = 3, Persist = false}
go_61[1] = { Component = "Transform", Coord = {X = -35, Y = 2, Z = -5.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 10, Y = 4, Z = 6}}
go_61[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_61[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_62 = {}
go_62[0] = { Name = "ParedLimite9", HowManyCmps = 3, Persist = false}
go_62[1] = { Component = "Transform", Coord = {X = -39, Y = 2, Z = -1.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_62[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_62[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_63 = {}
go_63[0] = { Name = "ParedLimite10", HowManyCmps = 3, Persist = false}
go_63[1] = { Component = "Transform", Coord = {X = -37, Y = 2, Z = 2.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 6.5}}
go_63[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_63[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_64 = {}
go_64[0] = { Name = "ParedLimite11", HowManyCmps = 3, Persist = false}
go_64[1] = { Component = "Transform", Coord = {X = -31, Y = 2, Z = 7.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 7, Y = 4, Z = 4}}
go_64[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_64[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA DERECHA G ZONA DERECHA G ZONA DERECHA G ZONA DERECHA GZONA DERECHA G ZONA DERECHA G ZONA DERECHA G ZONA DERECHA G ZONA DERECHA G ZONA DERECHA G
go_65 = {}
go_65[0] = { Name = "ParedDERECHAG1", HowManyCmps = 3, Persist = false}
go_65[1] = { Component = "Transform", Coord = {X = -2.5, Y = 2, Z = 10.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 5}}
go_65[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_65[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_66 = {}
go_66[0] = { Name = "ParedDERECHAG2", HowManyCmps = 3, Persist = false}
go_66[1] = { Component = "Transform", Coord = {X = -4.5, Y = 2, Z = 18.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.5, Y = 4, Z = 6}}
go_66[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_66[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_67 = {}
go_67[0] = { Name = "ParedDERECHAG3", HowManyCmps = 3, Persist = false}
go_67[1] = { Component = "Transform", Coord = {X = -1, Y = 2, Z = 19}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2.5, Y = 4, Z = 5}}
go_67[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_67[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_68 = {}
go_68[0] = { Name = "ParedDERECHAG4", HowManyCmps = 3, Persist = false}
go_68[1] = { Component = "Transform", Coord = {X = -3, Y = 2, Z = 21}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 1}}
go_68[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_68[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_69 = {}
go_69[0] = { Name = "ParedDERECHAG5", HowManyCmps = 3, Persist = false}
go_69[1] = { Component = "Transform", Coord = {X = -1.25, Y = 2, Z = 13.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2.5, Y = 4, Z = 2}}
go_69[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_69[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J ZONA J
go_70 = {}
go_70[0] = { Name = "ParedJ1", HowManyCmps = 3, Persist = false}
go_70[1] = { Component = "Transform", Coord = {X = 3.25, Y = 2, Z = 19}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2.5, Y = 4, Z = 5}}
go_70[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_70[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_71 = {}
go_71[0] = { Name = "ParedJ2", HowManyCmps = 3, Persist = false}
go_71[1] = { Component = "Transform", Coord = {X = 5, Y = 2, Z = 20}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4, Y = 4, Z = 3}}
go_71[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_71[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_72 = {}
go_72[0] = { Name = "ParedJ3", HowManyCmps = 3, Persist = false}
go_72[1] = { Component = "Transform", Coord = {X = 3, Y = 2, Z = 11}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 6}}
go_72[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_72[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_73 = {}
go_73[0] = { Name = "ParedJ4", HowManyCmps = 3, Persist = false}
go_73[1] = { Component = "Transform", Coord = {X = 6.5, Y = 2, Z = 12.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 7, Y = 4, Z = 2.5}}
go_73[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_73[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_74 = {}
go_74[0] = { Name = "ParedJ5", HowManyCmps = 3, Persist = false}
go_74[1] = { Component = "Transform", Coord = {X = 8, Y = 2, Z = 15}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4, Y = 4, Z = 2}}
go_74[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_74[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_75 = {}
go_75[0] = { Name = "ParedJ6", HowManyCmps = 3, Persist = false}
go_75[1] = { Component = "Transform", Coord = {X = 11, Y = 2, Z = 12}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 1}}
go_75[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_75[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_76 = {}
go_76[0] = { Name = "ParedJ7", HowManyCmps = 3, Persist = false}
go_76[1] = { Component = "Transform", Coord = {X = 18, Y = 2, Z = 12.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 13, Y = 4, Z = 2}}
go_76[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_76[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_77 = {}
go_77[0] = { Name = "ParedJ8", HowManyCmps = 3, Persist = false}
go_77[1] = { Component = "Transform", Coord = {X = 23.75, Y = 2, Z = 15}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5, Y = 4, Z = 4}}
go_77[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_77[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_78 = {}
go_78[0] = { Name = "ParedJ9", HowManyCmps = 3, Persist = false}
go_78[1] = { Component = "Transform", Coord = {X = 19.75, Y = 2, Z = 16}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 3, Y = 4, Z = 2}}
go_78[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_78[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_79 = {}
go_79[0] = { Name = "ParedJ10", HowManyCmps = 3, Persist = false}
go_79[1] = { Component = "Transform", Coord = {X = 19, Y = 2, Z = 20.625}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4.5, Y = 4, Z = 3}}
go_79[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_79[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_80 = {}
go_80[0] = { Name = "ParedJ11", HowManyCmps = 3, Persist = false}
go_80[1] = { Component = "Transform", Coord = {X = 14.25, Y = 2, Z = 18.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 5.5, Y = 4, Z = 7}}
go_80[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_80[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_81 = {}
go_81[0] = { Name = "ParedJ12", HowManyCmps = 3, Persist = false}
go_81[1] = { Component = "Transform", Coord = {X = 10, Y = 2, Z = 19.875}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 3, Y = 4, Z = 4}}
go_81[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_81[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H ZONA H
go_82 = {}
go_82[0] = { Name = "ParedH1", HowManyCmps = 3, Persist = false}
go_82[1] = { Component = "Transform", Coord = {X = -20, Y = 2, Z = 7.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 8, Y = 4, Z = 1}}
go_82[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_82[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_83 = {}
go_83[0] = { Name = "ParedH2", HowManyCmps = 3, Persist = false}
go_83[1] = { Component = "Transform", Coord = {X = -19.25, Y = 2, Z = 8.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 6.5, Y = 4, Z = 1.5}}
go_83[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_83[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_84 = {}
go_84[0] = { Name = "ParedH3", HowManyCmps = 3, Persist = false}
go_84[1] = { Component = "Transform", Coord = {X = -17.15, Y = 2, Z = 10.65}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =2.25, Y = 4, Z = 2.25}}
go_84[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_84[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_85 = {}
go_85[0] = { Name = "ParedH4", HowManyCmps = 3, Persist = false}
go_85[1] = { Component = "Transform", Coord = {X = -16.55, Y = 2, Z = 13.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =1, Y = 4, Z = 4}}
go_85[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_85[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_86 = {}
go_86[0] = { Name = "ParedH5", HowManyCmps = 3, Persist = false}
go_86[1] = { Component = "Transform", Coord = {X = -21.5, Y = 2, Z = 15.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =9, Y = 4, Z = 1}}
go_86[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_86[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_87 = {}
go_87[0] = { Name = "ParedH6", HowManyCmps = 3, Persist = false}
go_87[1] = { Component = "Transform", Coord = {X = -22.25, Y = 2, Z = 13.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =7.5, Y = 4, Z = 1.25}}
go_87[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_87[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_88 = {}
go_88[0] = { Name = "ParedH7", HowManyCmps = 3, Persist = false}
go_88[1] = { Component = "Transform", Coord = {X = -25, Y = 2, Z = 9}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 4}}
go_88[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_88[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_89 = {}
go_89[0] = { Name = "ParedH8", HowManyCmps = 3, Persist = false}
go_89[1] = { Component = "Transform", Coord = {X = -23.75, Y = 2, Z = 11.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4.5, Y = 4, Z = .5}}
go_89[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_89[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_90 = {}
go_90[0] = { Name = "ParedH9", HowManyCmps = 3, Persist = false}
go_90[1] = { Component = "Transform", Coord = {X = -21.75, Y = 2, Z = 10.85}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.5, Y = 4, Z = 1.25}}
go_90[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_90[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- HUECOS PARA ZONA I HUECOS PARA ZONA I HUECOS PARA ZONA I HUECOS PARA ZONA I HUECOS PARA ZONA I HUECOS PARA ZONA I HUECOS PARA ZONA I
go_91 = {}
go_91[0] = { Name = "ParedI1", HowManyCmps = 3, Persist = false}
go_91[1] = { Component = "Transform", Coord = {X = -19.5, Y = 2, Z = 18.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =5, Y = 4, Z = 2}}
go_91[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_91[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_92 = {}
go_92[0] = { Name = "ParedI2", HowManyCmps = 3, Persist = false}
go_92[1] = { Component = "Transform", Coord = {X = -16.55, Y = 2, Z = 19.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =1, Y = 4, Z = 4}}
go_92[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_92[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_93 = {}
go_93[0] = { Name = "ParedI3", HowManyCmps = 3, Persist = false}
go_93[1] = { Component = "Transform", Coord = {X = -19.5, Y = 2, Z = 21.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =7, Y = 4, Z = 1}}
go_93[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_93[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_94 = {}
go_94[0] = { Name = "ParedI4", HowManyCmps = 3, Persist = false}
go_94[1] = { Component = "Transform", Coord = {X = -26.5, Y = 2, Z = 19.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X =7, Y = 4, Z = 5}}
go_94[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_94[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
-- LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2 LIMITES PARTE 2
go_95 = {}
go_95[0] = { Name = "ParedLimite12", HowManyCmps = 3, Persist = false}
go_95[1] = { Component = "Transform", Coord = {X = 32.5, Y = 2, Z = 15.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 8, Y = 4, Z = 8}}
go_95[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_95[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_96 = {}
go_96[0] = { Name = "ParedLimite13", HowManyCmps = 3, Persist = false}
go_96[1] = { Component = "Transform", Coord = {X = 25.5, Y = 2, Z = 23}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 6, Y = 4, Z = 8}}
go_96[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_96[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_97 = {}
go_97[0] = { Name = "ParedLimite14", HowManyCmps = 3, Persist = false}
go_97[1] = { Component = "Transform", Coord = {X = 21.5, Y = 2, Z = 27}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_97[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_97[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_98 = {}
go_98[0] = { Name = "ParedLimite15", HowManyCmps = 3, Persist = false}
go_98[1] = { Component = "Transform", Coord = {X = 19.5, Y = 2, Z = 26}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 4, Z = 2}}
go_98[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_98[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_99 = {}
go_99[0] = { Name = "ParedLimite16", HowManyCmps = 3, Persist = false}
go_99[1] = { Component = "Transform", Coord = {X = 17.75, Y = 2, Z = 24.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 7, Y = 4, Z = 1}}
go_99[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_99[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_100 = {}
go_100[0] = { Name = "ParedLimite17", HowManyCmps = 3, Persist = false}
go_100[1] = { Component = "Transform", Coord = {X = 9, Y = 2, Z = 26.675}, Rotation = {X = 0, Y = 2, Z = 0}, Scale = {X = 11, Y = 4, Z = 5}}
go_100[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_100[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_101 = {}
go_101[0] = { Name = "ParedLimite18", HowManyCmps = 3, Persist = false}
go_101[1] = { Component = "Transform", Coord = {X = -19, Y = 2, Z = 29.35}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 45, Y = 4, Z = 10}}
go_101[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_101[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_102 = {}
go_102[0] = { Name = "ParedLimite19", HowManyCmps = 3, Persist = false}
go_102[1] = { Component = "Transform", Coord = {X = -43.5, Y = 2, Z = 19.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 4, Y = 4, Z = 10}}
go_102[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_102[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_103 = {}
go_103[0] = { Name = "ParedLimite20", HowManyCmps = 3, Persist = false}
go_103[1] = { Component = "Transform", Coord = {X = -35.5, Y = 2, Z = 13.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 13, Y = 4, Z = 1.5}}
go_103[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_103[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_104 = {}
go_104[0] = { Name = "ParedLimite21", HowManyCmps = 3, Persist = false}
go_104[1] = { Component = "Transform", Coord = {X = -29.5, Y = 2, Z = 15.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 4, Z = 3}}
go_104[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_104[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
go_105 = {}
go_105[0] = { Name = "ParedLimite22", HowManyCmps = 3, Persist = false}
go_105[1] = { Component = "Transform", Coord = {X = -31, Y = 2, Z = 11.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 4, Z = 3.5}}
go_105[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 250}
go_105[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
--FirstAidKit part 2
go_106 = {}
go_106[0] = { Name = "FirstAidKit2", HowManyCmps = 5, Persist = false}
go_106[1] = { Component = "Transform", Coord = {X = -8.75, Y = 1, Z = 10.75}, Rotation = {X = 0, Y = -90, Z = 0}, Scale = {X = .8, Y = 1, Z = .8}}
go_106[2] = { Component = "RenderObject", MeshName="firstAid.mesh", Material="botiquin", Visible=true, Shadows=false, RenderingDistance = 50}
go_106[3] = { Component = "BoxCollider", Type="Box",Width=1,Height=10,Depth=1,IsTrigger=true}
go_106[4] = { Component = "FirstAidKitComponent", HealthAmount = 1 }
go_106[5] = { Component = "AudioSource", Route = {"Assets/Audio/Bandage.wav" }, StopOnDestroy = false}
--Enemigos
go_107 = {}
go_107[0] = { Name = "InvisibleEnemy", HowManyCmps = 3, Persist = false}
go_107[1] = { Component = "Transform", Coord = {X =-25, Y = 1, Z = 20}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_107[2] = { Component = "AudioSource", Route = {"Assets/Audio/MonsterNear.wav", "Assets/Audio/MonsterProwling.wav"}, Stereo = true,
MinMaxDistance = {Min = 1, Max = 2}, Volume = 0.1, Loops = {-1, 0}, Plays = {true, false}, StopOnDestroy = true}
go_107[3] = { Component = "InvisibleEnemyAIComponent", Speed = 1.25, HearingDistance = 35, MaxRadiusFindPlayer=10, SightingDistance = 34, }
go_108 = {}
go_108[0] = { Name = "Kamikaze1", HowManyCmps = 5, Persist = false}
go_108[1] = { Component = "Transform", Coord = {X = -7.5, Y = 1.5, Z = -16}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_108[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_108[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_108[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_108[5] = { Component = "KamikazeEnemyComponent" }
go_109 = {}
go_109[0] = { Name = "Kamikaze2", HowManyCmps = 5, Persist = false}
go_109[1] = { Component = "Transform", Coord = {X = -36, Y = 1.5, Z = -1.5}, Rotation = {X = 0, Y = 90, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_109[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_109[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_109[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_109[5] = { Component = "KamikazeEnemyComponent" }
go_110 = {}
go_110[0] = { Name = "Kamikaze3", HowManyCmps = 5, Persist = false}
go_110[1] = { Component = "Transform", Coord = {X = 10.5, Y = 1.5, Z = 0.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_110[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_110[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_110[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_110[5] = { Component = "KamikazeEnemyComponent" }
go_111 = {}
go_111[0] = { Name = "Kamikaze4", HowManyCmps = 5, Persist = false}
go_111[1] = { Component = "Transform", Coord = {X = 26, Y = 1.5, Z = 4}, Rotation = {X = 0, Y = 90, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_111[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_111[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_111[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_111[5] = { Component = "KamikazeEnemyComponent" }
go_112 = {}
go_112[0] = { Name = "Kamikaze5", HowManyCmps = 5, Persist = false}
go_112[1] = { Component = "Transform", Coord = {X = 5, Y = 1.5, Z = 19}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_112[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_112[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_112[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_112[5] = { Component = "KamikazeEnemyComponent" }
go_113 = {}
go_113[0] = { Name = "Kamikaze6", HowManyCmps = 5, Persist = false}
go_113[1] = { Component = "Transform", Coord = {X = -13, Y = 1.5, Z = 20.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2, Y = 2, Z = 2}}
go_113[2] = { Component = "RenderObject", MeshName="kamikaze.mesh", Material="Kamikaze", Visible=true, Shadows=true, RenderingDistance = 50}
go_113[3] = { Component = "RigidBody", Type="Sphere", Mass=9, kinematic = false,
ConstrainAngle = true, IsTrigger=false, StaticFriction = 0, DynamicFriction = 0, Bounciness = 1}
go_113[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.wav"}, Stereo = true,
MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false, StopOnDestroy = false}
go_113[5] = { Component = "KamikazeEnemyComponent" }
go_114 = {}
go_114[0] = { Name = "Screamer1", HowManyCmps = 5, Persist = false}
go_114[1] = { Component = "Transform", Coord ={X = -14.5, Y = 1, Z = -3.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.6, Y =2.4, Z = 1.6}}
go_114[2] = { Component = "RenderObject", MeshName="screamer.mesh", Material="mujer", Visible=true, Shadows=false, RenderingDistance = 50}
go_114[3] = { Component = "RigidBody", Type="Box", Mass=9, Kinematic = false, ConstrainAngle = true, IsTrigger= false}
go_114[4] = { Component = "AudioSource", Route = {"Assets/Audio/girl_sobbing.mp3" ,"Assets/Audio/screaming_girl.mp3"},
Stereo = true, MinMaxDistance = {Min = 2, Max = 6}, Volume= 1, Play = false}
go_114[5] = { Component = "ScreamerAIEnemyComponent", ShoutIntensityAttack = 1, ShoutIntensityIdle = 0.1,
IdleSoundRange = 10, DetectionRange = 7, FollowTime = 4, DyingTime = 3.5, MoveSpeed = 1}
go_115 = {}
go_115[0] = { Name = "Screamer2", HowManyCmps = 5, Persist = false}
go_115[1] = { Component = "Transform", Coord ={X = 23, Y = 1, Z = -13.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale ={X = 1.6, Y =2.4, Z = 1.6}}
go_115[2] = { Component = "RenderObject", MeshName="screamer.mesh", Material="mujer", Visible=true, Shadows=false, RenderingDistance = 50}
go_115[3] = { Component = "RigidBody", Type="Box", Mass=9, Kinematic = false, ConstrainAngle = true, IsTrigger= false}
go_115[4] = { Component = "AudioSource", Route = {"Assets/Audio/girl_sobbing.mp3" ,"Assets/Audio/screaming_girl.mp3"},
Stereo = true, MinMaxDistance = {Min = 2, Max = 6}, Volume= 1, Play = false}
go_115[5] = { Component = "ScreamerAIEnemyComponent", ShoutIntensityAttack = 1, ShoutIntensityIdle = 0.1,
IdleSoundRange = 10, DetectionRange = 7, FollowTime = 4, DyingTime = 3.5, MoveSpeed = 1}
go_116 = {}
go_116[0] = { Name = "Screamer3", HowManyCmps = 5, Persist = false}
go_116[1] = { Component = "Transform", Coord ={X = 22, Y = 1, Z = 24.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.6, Y =2.4, Z = 1.6}}
go_116[2] = { Component = "RenderObject", MeshName="screamer.mesh", Material="mujer", Visible=true, Shadows=false, RenderingDistance = 50}
go_116[3] = { Component = "RigidBody", Type="Box", Mass=9, Kinematic = false, ConstrainAngle = true, IsTrigger= false}
go_116[4] = { Component = "AudioSource", Route = {"Assets/Audio/girl_sobbing.mp3" ,"Assets/Audio/screaming_girl.mp3"},
Stereo = true, MinMaxDistance = {Min = 2, Max = 6}, Volume= 1, Play = false}
go_116[5] = { Component = "ScreamerAIEnemyComponent", ShoutIntensityAttack = 1, ShoutIntensityIdle = 0.1,
IdleSoundRange = 10, DetectionRange = 7, FollowTime = 4, DyingTime = 3.5, MoveSpeed = 1}
--Trampas part 2
go_117 = {}
go_117[0] = { Name = "Trampa2", HowManyCmps = 5, Persist = false}
go_117[1] = { Component = "Transform", Coord = {X = 10, Y = 0.07, Z = 9.6}, Rotation = {X = -90, Y = 0, Z = 0}, Scale = {X = 3, Y = 3.1, Z = 6}}
go_117[2] = { Component = "RenderObject", MeshName="spikes.mesh", Material="pincho", Visible=true, Shadows=true, RenderingDistance = 50}
go_117[3] = { Component = "BoxCollider", Type="Box",Width=2,Height=1,Depth=50,IsTrigger=true}
go_117[4] = { Component = "TrapComponent",EnabledMaterial="Practica1/Red"}
go_117[5] = { Component = "AudioSource", Route = {"Assets/Audio/MetalHit.wav" }, StopOnDestroy = false}
go_118 = {}
go_118[0] = { Name = "Desactivador2", HowManyCmps = 5, Persist = false}
go_118[1] = { Component = "Transform", Coord = {X = 10, Y = 0.2, Z = 9.75 + 1.875 - 0.3}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .3, Y = .4, Z = .3}}
go_118[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Metal", Visible=true, Shadows=true, RenderingDistance = 50}
go_118[3] = { Component = "SphereCollider",Radius=2,IsTrigger=true}
go_118[4] = { Component = "ObjectDeactivatorComponent",ObjName="Trampa2"}
go_118[5] = { Component = "AudioSource", Route = {"Assets/Audio/SwitchSound.mp3" }, StopOnDestroy = false}
-- Last First Aid
go_119 = {}
go_119[0] = { Name = "FirstAidKit3", HowManyCmps = 5, Persist = false}
go_119[1] = { Component = "Transform", Coord = {X = 10.75, Y = 1, Z = 13}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .8, Y = 1, Z = .8}}
go_119[2] = { Component = "RenderObject", MeshName="firstAid.mesh", Material="botiquin", Visible=true, Shadows=false, RenderingDistance = 50}
go_119[3] = { Component = "BoxCollider", Type="Box",Width=1,Height=10,Depth=1,IsTrigger=true}
go_119[4] = { Component = "FirstAidKitComponent", HealthAmount = 1 }
go_119[5] = { Component = "AudioSource", Route = {"Assets/Audio/Bandage.wav" }, StopOnDestroy = false}
--Bush part 2
go_120 = {}
go_120[0] = { Name = "Bush2", HowManyCmps = 4, Persist = false}
go_120[1] = { Component = "Transform", Coord = {X = -29.65, Y = 1, Z = 11.25}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.75, Y = 2, Z = 3.45}}
go_120[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Bush", Visible=true, Shadows=false, RenderingDistance = 50}
go_120[3] = { Component = "SphereCollider", Radius=1,IsTrigger=true}
go_120[4] = { Component = "HideoutComponent" }
go_121 = {}
go_121[0] = { Name = "Bush3", HowManyCmps = 4, Persist = false}
go_121[1] = { Component = "Transform", Coord = {X = 6.35, Y = 1, Z = -11.85}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X=2.5, Y = 2, Z = 1}}
go_121[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Bush", Visible=true, Shadows=false, RenderingDistance = 50}
go_121[3] = { Component = "SphereCollider", Radius=1,IsTrigger=true}
go_121[4] = { Component = "HideoutComponent" }
go_122 = {}
go_122[0] = { Name = "Bush4", HowManyCmps = 4, Persist = false}
go_122[1] = { Component = "Transform", Coord = {X = 5.35, Y = 1, Z = 11.1}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 2.5, Y = 2, Z = 1}}
go_122[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Bush", Visible=true, Shadows=false, RenderingDistance = 50}
go_122[3] = { Component = "SphereCollider", Radius=1,IsTrigger=true}
go_122[4] = { Component = "HideoutComponent" }
go_123 = {}
go_123[0] = { Name = "Bush5", HowManyCmps = 4, Persist = false}
go_123[1] = { Component = "Transform", Coord = {X = 21.5, Y = 1, Z = 25.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1.98, Y = 2, Z = 0.98}}
go_123[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Bush", Visible=true, Shadows=false, RenderingDistance = 50}
go_123[3] = { Component = "SphereCollider", Radius=1,IsTrigger=true}
go_123[4] = { Component = "HideoutComponent" }
go_124 = {}
go_124[0] = { Name = "Techo", HowManyCmps = 3, Persist = false}
go_124[1] = { Component = "Transform", Coord = {X = 0, Y = 4.5, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 200, Y = 1, Z = 150}}
go_124[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Suelo", Visible=true, Shadows=true, RenderingDistance = 1000}
go_124[3] = { Component = "RigidBody", Type="Box", Static=true, IsTrigger=false}
----------------------------------------------------------------------- LUCES ----------------------------------------------------------------------------------------
go_125 = {}
go_125[0] = { Name = "Luz1", HowManyCmps = 2, Persist = false}
go_125[1] = { Component = "Transform", Coord = {X = 22.5, Y = 3.5, Z = -13}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_125[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 0.2, Blue = 0.2},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=5}
go_126 = {}
go_126[0] = { Name = "Luz2", HowManyCmps = 2, Persist = false}
go_126[1] = { Component = "Transform", Coord = {X = 30, Y = 3.5, Z = 8.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_126[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 0.5, Blue = 0.2},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=5}
go_127 = {}
go_127[0] = { Name = "Luz3", HowManyCmps = 2, Persist = false}
go_127[1] = { Component = "Transform", Coord = {X = 4, Y = 3.5, Z = 23.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_127[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 0.2, Blue = 0.1},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=5}
go_128 = {}
go_128[0] = { Name = "Luz4", HowManyCmps = 2, Persist = false}
go_128[1] = { Component = "Transform", Coord = {X = -35.5, Y = 4, Z = 20.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_128[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 0.5, Green = 1, Blue = 0.5},
SpotLightRange = {InnerAngle = 5, OuterAngle = 80, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=5}
go_129 = {}
go_129[0] = { Name = "Luz5", HowManyCmps = 2, Persist = false}
go_129[1] = { Component = "Transform", Coord = {X=-20.5, Y = 3.5, Z = -1.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_129[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 0.6, Green= 0.6, Blue = 0.6},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=5}
--Luz e interruptor zona izquierda del mapa
go_130 = {}
go_130[0] = { Name = "LuzDesactivable1", HowManyCmps = 2, Persist = false}
go_130[1] = { Component = "Transform", Coord = {X = -35, Y = 4, Z = -1.75}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_130[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 0.2, Blue = 0.2},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=30}
go_131 = {}
go_131[0] = { Name = "DesactivadorLuz1", HowManyCmps = 5, Persist = false}
go_131[1] = { Component = "Transform", Coord = {X = -19.5, Y = 2, Z = -1}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .3, Y = .4, Z = .3}}
go_131[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Metal", Visible=true, Shadows=true, RenderingDistance = 50}
go_131[3] = { Component = "SphereCollider",Radius=1,IsTrigger=true}
go_131[4] = { Component = "SwitcherComponent",ObjName="LuzDesactivable1"}
go_131[5] = { Component = "AudioSource", Route = {"Assets/Audio/SwitchSound.mp3" }, StopOnDestroy = false}
--Luz e interruptor zona inferior del mapa
go_132 = {}
go_132[0] = { Name = "LuzDesactivable2", HowManyCmps = 2, Persist = false}
go_132[1] = { Component = "Transform", Coord ={X = 21, Y = 3, Z = 24.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 1, Y = 1, Z = 1}}
go_132[2] = { Component = "LightComponent", LightType= "SPOTLIGHT", Visible = true,
Attenuation = {Range = 200, Constant = 1.0, Linear = 0.30, Quadratic=2},
Diffuse = {Red = 1, Green= 0.2, Blue = 0.2},
SpotLightRange = {InnerAngle = 5, OuterAngle = 60, FallOf = 1},
LightDirection = {X = 0, Y = 1, Z = 0},
Intensity=30}
go_133 = {}
go_133[0] = { Name = "DesactivadorLuz2", HowManyCmps = 5, Persist = false}
go_133[1] = { Component = "Transform", Coord = {X = 8.5, Y = 2, Z = 21.5}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = .3, Y = .4, Z = .3}}
go_133[2] = { Component = "RenderObject", MeshName="cube.mesh", Material="Practica1/Metal", Visible=true, Shadows=true, RenderingDistance = 50}
go_133[3] = { Component = "SphereCollider",Radius=1,IsTrigger=true}
go_133[4] = { Component = "SwitcherComponent",ObjName="LuzDesactivable2"}
go_133[5] = { Component = "AudioSource", Route = {"Assets/Audio/SwitchSound.mp3" }, StopOnDestroy = false}
--Luces
--go_2 = {}
--go_2[0] = { Name = "Screamer", HowManyCmps = 5, Persist = false}
--go_2[1] = { Component = "Transform", Coord = {X = 0, Y = 5, Z = -30}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 0.1, Y = 0.1, Z = 0.1}}
--go_2[2] = { Component = "RenderObject", MeshName="ogrehead.mesh", Material="Practica1/Red",
-- RotateAngle = 0, Rotate={X=0, Y=0, Z=0}, Scale = {X=1, Y=1, Z=1}, LookAt ={X=0, Y=0, Z=0},
-- Visible=true, Shadows=false, RenderingDistance = 1000}
--go_2[3] = { Component = "RigidBody", Type="Box", Mass=9, Width=10, Depth=10, Height=10, Kinematic = false,
-- ConstrainAngle = true, IsTrigger= false}
--go_2[4] = { Component = "AudioSource", Route = {"Assets/Audio/woman_cry.mp3" ,"Assets/Audio/baby_crying.mp3"},
-- Stereo = true, MinMaxDistance = {Min = 2, Max = 6}, Volume= 1, Play = false}
--go_2[5] = { Component = "ParticleSystem", Path="Assets/ParticleSystems/Practica2.particle"}
--go_2[5] = { Component = "ScreamerAIEnemyComponent", ShoutIntensityAttack = 1, ShoutIntensityIdle = 0.1,
-- DetectionRange = 30, FollowTime = 5, DyingTime = 4, MoveSpeed = 3}
--go_3 = {}
--go_3[0] = { Name = "InvisibleEnemy", HowManyCmps = 4, Persist = false}
--go_3[1] = { Component = "Transform", Coord = {X = -15, Y = 5, Z = -30}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 0.1, Y = 0.1, Z = 0.1}}
--go_3[2] = { Component = "RenderObject", MeshName="ogrehead.mesh", Material="Practica1/Red",
-- RotateAngle = 0, Rotate={X=0, Y=0, Z=0}, Scale = {X=1, Y=1, Z=1}, LookAt ={X=0, Y=0, Z=0},
-- Visible=true, Shadows=false, RenderingDistance = 1000}
--go_3[3] = { Component = "AudioSource", Route = {"Assets/Audio/ProtoDarkMaze_Menu.mp3", "Assets/Audio/goat_cry.mp3"}, Stereo = true,
-- MinMaxDistance = {Min = 2, Max = 6}, Volume= 10, Play = false}
--go_3[4] = { Component = "InvisibleEnemyAIComponent"}
--go_4 = {}
--go_4[0] = { Name = "Kamikaze", HowManyCmps = 5, Persist = false}
--go_4[1] = { Component = "Transform", Coord = {X = 25, Y = 5, Z = -40}, Rotation = {X = 0, Y = 0, Z = 0}, Scale = {X = 0.1, Y = 0.1, Z = 0.1}}
--go_4[2] = { Component = "RenderObject", MeshName="ogrehead.mesh", Material="Practica1/Red",
-- RotateAngle = 0, Rotate={X=0, Y=0, Z=0}, Scale = {X=1, Y=1, Z=1}, LookAt ={X=0, Y=0, Z=0},
-- Visible=true, Shadows=false, RenderingDistance = 1000}
--go_4[3] = { Component = "RigidBody", Type="Box", Mass=9, Width=10, Depth=10, Height=10, kinematic = true,
-- ConstrainAngle = true, IsTrigger=false}
---go_4[4] = { Component = "AudioSource", Route = {"Assets/Audio/kamikaze_scream.wav" ,"Assets/Audio/kamikaze_explosion.mp3"}, Stereo = true,
-- MinMaxDistance = {Min = 2, Max = 6}, Volume= 15, Play = false}
--go_4[5] = { Component = "KamikazeEnemyComponent" }
--Luz direccional
-- go_2 = {}
-- go_2[0] = { Name = "LuzDireccional", HowManyCmps = 2, Persist = false}
-- go_2[1] = { Component = "Transform", Coord = {X = 0, Y = 500, Z = 0}, Rotation = {X = 0, Y = 0, Z = 0}}
-- go_2[2] = { Component = "LightComponent", LightType= "DIRECTIONAL", Visible = true,
-- Diffuse = {Red = 0.7, Green= 0.5, Blue = 0.5},
-- Specular = {Red = 1, Green= 1, Blue = 1},
-- LightDirection = {X = -1.3, Y = -1,Z = 0}}
|
local ffi = require("ffi")
do
ffi.errno(42)
local x = 0
for i=1,100 do x = x + ffi.errno() end
assert(x == 4200)
ffi.errno(0)
end
do
local a = ffi.new("uint8_t[?]", 101)
for i=0,99 do a[i] = i end
local s
for i=1,90 do s = ffi.string(a+i, 10) end
assert(s == "Z[\\]^_`abc")
for i=1,90 do s = ffi.string(a+i) end
assert(s == "Z[\\]^_`abc")
end
do
local a = ffi.new("uint8_t[?]", 100)
local x = 0
for i=0,90 do x = x + a[i]; ffi.fill(a+i, 10, i); x = x + a[i] end
assert(x == 8100)
for i=1,100 do ffi.fill(a, 15, 0x1234) end
assert(a[0] == 0x34 and a[14] == 0x34 and a[15] == 15)
local b = ffi.new("uint32_t[?]", 104)
for i=0,100 do ffi.fill(b+i, 15, 0x1234) end
assert(b[0] == 0x34343434)
assert(b[103] == (ffi.abi("le") and 0x343434 or 0x34343400))
end
do
local a = ffi.new("uint8_t[?]", 100)
local b = ffi.new("uint8_t[?]", 100)
for i=0,99 do b[i] = i end
local x = 0
for i=0,90 do x = x + a[i]; ffi.copy(a+i, b+i, 1); x = x + a[i] end
assert(x == 4095)
local x = 0
for i=0,90 do ffi.copy(b+i, a+90-i, 10); x = x + b[i] end
assert(x == 4095)
end
do
local a = ffi.new("uint8_t[?]", 100, 42)
for i=0,90 do ffi.copy(a+i, "abc") end
local x = 0
for i=0,99 do x = x + a[i] end
assert(x == 9276)
end
do
local tp = ffi.typeof("struct { int x, y; }")
local a = tp(1, 2)
local b = tp(3, 4)
local x = 0
for i=1,100 do a.y = i; ffi.copy(b, a, 8); x = x + b.y end
assert(x == 5050)
local x = 0
for i=1,100 do a.y = i; local t = tp(a); x = x + t.y end
assert(x == 5050)
end
do
local tp = ffi.typeof("struct { complex x, y; }")
local cx = ffi.typeof("complex")
local a = tp(cx(1, 2), cx(3, 4))
local x = 0
for i=1,100 do a.y = i; local t = tp(a); x = x + t.y.re end
assert(x == 5050)
end
do
local tp = ffi.typeof("int[10]")
local a = tp(42)
local b = ffi.new(ffi.typeof("struct { $ x; }", tp))
for i=1,100 do b.x = a end
assert(b.x[0] == 42 and b.x[9] == 42)
end
do
local tp = ffi.typeof("double[5]")
local a = tp(42)
local b = ffi.new(ffi.typeof("struct { $ x; }", tp))
for i=1,100 do b.x = a end
assert(b.x[0] == 42 and b.x[4] == 42)
b.x[0] = 0
for i=1,100 do ffi.copy(b.x, a, ffi.sizeof(a)) end
assert(b.x[0] == 42 and b.x[4] == 42)
end
do
local x, y
for i=1,100 do x = ffi.abi("32bit"); y = ffi.abi("64bit") end
assert(x == ffi.abi("32bit"))
assert(y == ffi.abi("64bit"))
for _,s in ipairs{"64bit", "32bit", "fpu", "softfp", "hardfp", "eabi", "win", "le", "be"} do
for i=1,100 do x = ffi.abi(s) end
assert(x == ffi.abi(s))
end
end
do
local ct = ffi.typeof("struct { int x; }")
local cd = ct()
for i=1,100 do assert(ffi.typeof(cd) == ct) end
end
|
function nonlocal()
local x = 0
for i = 1, 100 do
x = x + math.sin(i)
end
return x
end
local sin = math.sin
function localized()
local x = 0
for i = 1, 100 do
x = x + sin(i)
end
return x
end
return {
name = "function-localize",
desc = "calling local/global functions",
cases = {
{ name = "Non-local", entry = nonlocal },
{ name = "Localized", entry = localized },
},
}
|
if not _G.FreeInstanceSharer then return end
local F, L, P, G = unpack(_G.FreeInstanceSharer)
local fixer = {
"魔兽小知识:“瑞文戴尔的死亡战马”5人本【斯坦索姆】亡灵区首领【奥里尔斯.瑞文戴尔领主】小几率掉落-掉率0.7%。",
"魔兽小知识:“蓝色其拉作战坦克”60级团本【安其拉】小怪低几率掉落,掉率10-15%。",
"魔兽小知识:“绿色其拉作战坦克”60级团本【安其拉】小怪低几率掉落,掉率10-15%。",
"魔兽小知识:“黄色其拉作战坦克”60级团本【安其拉】小怪低几率掉落,掉率10-15%。",
"魔兽小知识:“红色其拉作战坦克”60级团本【安其拉】小怪低几率掉落,掉率10-15%。",
"魔兽小知识:“乌鸦之神”5人本【赛泰克大厅】英雄难度首领【安苏】小几率掉落,掉率1.6%。",
"魔兽小知识:“迅捷白色陆行鸟”5人本【导魔师平台】英雄难度首领【凯尔萨斯.逐日者】小几率掉落,掉率4%。",
"魔兽小知识:“炽热战马”70级团本【卡拉赞】首领【猎人阿图曼】小几率掉落,掉率0.9%。",
"魔兽小知识:“奥的灰烬”70级团本【风暴要塞】首领【凯尔萨斯.逐日者】小几率掉落,掉率2%。",
"魔兽小知识:“迷时始祖幼龙”诺森德风暴峭壁的超级稀有【迷时始祖幼龙】必掉落,个人拾取。",
"魔兽小知识:“青铜幼龙”5人本【净化斯坦索姆】英雄难度额外首领【永恒腐蚀者】必掉。",
"魔兽小知识:“蓝色始祖幼龙”5人本【乌特加德之巅】英雄难度首领【残忍的斯卡迪】小几率掉落,掉率1.5%。",
"魔兽小知识:“黑色幼龙”80级团本【黑曜石圣殿】首领【萨塔里奥】10人三龙模式必掉。",
"魔兽小知识:“暮光幼龙”80级团本【黑曜石圣殿】首领【萨塔里奥】25人三龙模式必掉。",
"魔兽小知识:“蓝色幼龙”80级团本【永恒之眼】首领【玛里苟斯】10/25人小几率掉落,掉率4/6%。",
"魔兽小知识:“碧蓝幼龙”80级团本【永恒之眼】首领【玛里苟斯】10/25人小几率掉落,掉率3%。",
"魔兽小知识:“重型黑色猛犸战象”80级团本【阿尔卡冯的宝库】10/25人所有首领小几率掉落,掉率1%。",
"魔兽小知识:“米米尔隆的头部”80级团本【奥杜尔】首领【尤格萨隆】25人0灯模式小几率掉落,掉率1.7%。",
"魔兽小知识:“奥妮克希亚座龙”80级团本【奥妮克希亚的巢穴】首领【奥妮克希亚】10/25人小几率掉落,掉率1.3%。",
"魔兽小知识:“无敌”80级团本【冰冠堡垒】首领【巫妖王】25人英雄难度小几率掉落,掉率1%。",
"魔兽小知识:“磷光石幼龙”深岩之洲的超级稀有【奥依纳克斯】必掉,个人拾取。",
"魔兽小知识:“灰色骑骑乘骆驼”奥丹姆超级稀有物体【神秘的骆驼雕像】进镜像击杀稀有可取得,可购买。",
"魔兽小知识:“驯服的海马”瓦斯琪尔的稀有【波塞冬斯】必掉,个人拾取。",
"魔兽小知识:“琉璃石幼龙”5人本【巨石之核】首领【岩革】小几率掉落,掉率0.8%。",
"魔兽小知识:“北风幼龙”5人本【旋云之巅】首领【艾塔伊洛斯】小几率掉落,掉率0.8%。",
"魔兽小知识:“阿曼尼战熊”5人本【祖阿曼】限时击杀四个动物首领获得。",
"魔兽小知识:“装甲拉扎什迅猛龙”5人本【祖尔格拉布】首领【血领主曼多基尔】小几率掉落,掉率1%。",
"魔兽小知识:“迅捷祖利安黑豹”5人本【祖尔格拉布】首领【高阶祭司基尔娜拉】小几率掉落,掉率1%。",
"魔兽小知识:“南风幼龙”85级团本【风神王座】首领【奥拉基尔】小几率掉落,掉率1%。",
"魔兽小知识:“奥利色拉佐尔的烈焰之爪”85级团本【火焰之地】首领【奥利色拉佐尔】小几率掉落,掉率2%。",
"魔兽小知识:“纯血火鹰”85级团本【火焰之地】首领【拉格纳罗斯】小几率掉落,掉率1%。",
"魔兽小知识:“实验体12-B”85级团本【巨龙之魂】首领【奥卓克希昂】小几率掉落,掉率1.2%。",
"魔兽小知识:“炽炎幼龙”85级团本【巨龙之魂】首领【疯狂的死亡之翼】小几率掉落,掉率4%。",
"魔兽小知识:“生命缚誓者仆从”85级团本【巨龙之魂】首领【疯狂的死亡之翼】小几率掉落,掉率1%。",
"魔兽小知识:“雷霆红玉云端翔龙”潘达利亚锦绣谷收集10个【天空碎片】后击杀【阿拉尼】必掉。",
"魔兽小知识:“岩灰原始恐角龙”潘达利亚稀有【赞达拉战争使者】较低几率掉落,掉率4%。",
"魔兽小知识:“珀光原始恐角龙”潘达利亚稀有【赞达拉战争使者】较低几率掉落,掉率4%。",
"魔兽小知识:“翡翠原始恐角龙”潘达利亚稀有【赞达拉战争使者】较低几率掉落,掉率4%。",
"魔兽小知识:“黑色原始迅猛龙”潘达利亚巨兽岛的恐龙掉落【原始恐龙蛋】3天后孵化必出一只。",
"魔兽小知识:“绿色原始迅猛龙”潘达利亚巨兽岛的恐龙掉落【原始恐龙蛋】3天后孵化必出一只。",
"魔兽小知识:“红色原始迅猛龙”潘达利亚巨兽岛的恐龙掉落【原始恐龙蛋】3天后孵化必出一只。",
"魔兽小知识:“雷霆玛瑙云端翔龙”潘达利亚锦稀有【惑龙】小几率掉落,掉率1%。",
"魔兽小知识:“神圣玛瑙云端翔龙”潘达利亚锦稀有【怒之煞龙】超低几率掉落,掉率0.03%。",
"魔兽小知识:“炮舰之子”潘达利亚锦稀有【炮舰】超低几率掉落,掉率0.02%。",
"魔兽小知识:“雷霆蓝晶云端翔龙”潘达利亚雷神岛稀有【风暴领主纳拉克】超低几率掉落,掉率0.03%。",
"魔兽小知识:“冰蓝原始恐角龙”潘达利亚稀有【乌达斯塔】超低几率掉落,掉率0.02%。",
"魔兽小知识:“星光云端翔龙”90级团本【魔古山宝库】首领【伊拉贡】小几率掉落,掉率1.3%。",
"魔兽小知识:“赫利东的子嗣”90级团本【雷电王座】首领【郝立东】小几率掉落,掉率3%。",
"魔兽小知识:“季鹍之嗣”90级团本【雷电王座】首领【季鹍】小几率掉落,掉率3%。",
"魔兽小知识:“库卡隆战蝎”90级团本【决战奥格瑞玛】史诗难度首领【加尔鲁什.地狱咆哮】小几率掉落,掉率1%。",
"魔兽小知识:“迅捷风蹄塔布羊”德拉诺影月谷稀有【觅径者】必掉。",
"魔兽小知识:“巨型灰牙野猪”德拉诺霜火岭稀有【戈罗克】必掉。",
"魔兽小知识:“天蓝淡水兽”德拉塔拉多岭稀有【泥皮】必掉。",
"魔兽小知识:“血蹄公牛”德拉纳格兰稀有【雷霆纳克】必掉。",
"魔兽小知识:“斑点草地践踏者”德拉诺纳格兰稀有【鲁克胡克】必掉。",
"魔兽小知识:“日隐小戈隆”德拉诺霜火岭稀有【重拳】必掉。",
"魔兽小知识:“夜嚎铁颚狼”德拉诺霜火岭稀有【诺卡罗什】必掉。",
"魔兽小知识:“装甲刀脊野猪”德拉诺塔纳安丛林四个军团勇士稀有掉落笼子,小几率开出,掉率11%。",
"魔兽小知识:“苔原冰蹄牛”德拉诺塔纳安丛林四个军团勇士稀有掉落笼子,小几率开出,掉率11%。",
"魔兽小知识:“战歌恐牙狼”德拉诺塔纳安丛林四个军团勇士稀有掉落笼子,小几率开出,掉率11%。",
"魔兽小知识:“黑暗之星的灵爪飞鹰”德拉诺塔各地区超级稀有【现世边界】传送门入内拾取,必掉。",
"魔兽小知识:“日光峰林飞鹰”德拉诺阿兰卡峰林稀有【鲁克玛】超小几率掉落,掉率0.03%。",
"魔兽小知识:“铁蹄毁灭者”100级团本【黑石铸造厂】史诗难度首领【黑手】小几率掉落,掉率1%。",
"魔兽小知识:“魔钢歼灭者”100级团本【地狱火堡垒】史诗难度首领【阿克蒙德】小几率掉落,掉率1%。",
"魔兽小知识:“永恒时空撕裂者”任何时光漫游5人本首领超小几率掉落,掉率0.1%。",
"魔兽小知识:“失落的角鹰兽”破碎群岛阿苏纳刷新瞬灭水晶后先找齐5个获得。",
"魔兽小知识:“燃烬巨龙”5人本【从返卡拉赞】史诗模式限时召唤出【夜之魇】必掉。",
"魔兽小知识:“午夜”5人本【从返卡拉赞】史诗模式首领【猎人阿图曼】小几率掉落,掉率1%。",
"魔兽小知识:“炎狱地狱火”110级团本【暗夜要塞】史诗模式首领【古尔丹】小几率掉落,掉率1%。",
"魔兽小知识:“邪焰地狱火”110级团本【暗夜要塞】史诗模式首领【古尔丹】小几率掉落,掉率1%。",
"魔兽小知识:“深渊蠕虫”110级团本【萨格拉斯之墓】首领【主母萨丝琳】小几率掉落,掉率1%。",
"魔兽小知识:“安托兰灼焦恶犬”110级团本【安托鲁斯.燃烧王座】首领【沙图格】小几率掉落,掉率1%。",
"魔兽小知识:“戴镣铐的乌祖尔”110级团本【安托鲁斯.燃烧王座】史诗模式首领【寂灭者阿古斯】小几率掉落,掉率1%。",
"魔兽小知识:“疯狂的混沌奔行者”破碎群岛阿古斯马凯雷的稀有【牧羊人卡沃斯】较低几率掉落,掉率3%。",
"魔兽小知识:“酸液喷射者”破碎群岛阿古斯马凯雷的稀有【吞噬者斯克里格】较低几率掉落,掉率3%。",
"魔兽小知识:“柔光法力鳐”破碎群岛阿古斯马凯雷的稀有【毒尾天鳍鳐】较低几率掉落,掉率3%。",
"魔兽小知识:“邪犬”破碎群岛阿古斯安托兰废墟的稀有【训犬大师克拉克兹】较低几率掉落,掉率3%。",
"魔兽小知识:“赤红涎喉者”破碎群岛阿古斯安托兰废墟的稀有【疱吼】较低几率掉落,掉率3%。",
"魔兽小知识:“毒牙撕咬者”破碎群岛阿古斯安托兰废墟的稀有【普西拉】和【弗拉克苏尔】较低几率掉落,掉率2%。",
"魔兽小知识:“暗孢法力鳐”破碎群岛多个稀有掉落【邪斑鱼卵】孵出。",
"魔兽小知识:“邪光法力鳐”破碎群岛多个稀有掉落【邪斑鱼卵】孵出。",
"魔兽小知识:“荧光法力鳐”破碎群岛多个稀有掉落【邪斑鱼卵】孵出。",
"魔兽小知识:“活跃法力鳐”破碎群岛多个稀有掉落【邪斑鱼卵】孵出。",
"魔兽小知识:“迅捷白化迅猛龙”120级版本阿拉希高地的稀有【驭兽者卡玛】有几率掉落。",
"魔兽小知识:“啮颅者”120级版本阿拉希高地的稀有【啮颅者】有几率掉落。",
"魔兽小知识:“高地野马”120级版本阿拉希高地的稀有【末日骑士赫尔格里姆】有几率掉落。",
"魔兽小知识:“失意高地野马”120级版本阿拉希高地的稀有【骑士队长阿尔德林】有几率掉落。",
"魔兽小知识:“小毛驴”120级版本阿拉希高地的稀有【监工克里克斯】有几率掉落。",
"魔兽小知识:“枯木恐翼蝠”120级版本阿拉希高地的稀有【屠戮者尼玛尔】有几率掉落。",
"魔兽小知识:“沙丘食腐狼”120级沃顿的【无信者蛇人】极低几率掉落,掉率0.01%。",
"魔兽小知识:“跃泽吮血蛛”120级纳兹米尔的【鲜血巨魔】极低几率掉落,掉率0.01%。",
"魔兽小知识:“金鬃”120级斯托送谷地的【人行怪物】极低几率掉落,掉率0.01%。",
"魔兽小知识:“惊怖驮骡”120级德鲁斯瓦的【女巫会成员】极低几率掉落,掉率0.01%。",
"魔兽小知识:“纳沙塔尔鲜血巨蛇”120级收集20个【深渊碎片】后召唤【深渊信徒】取得。",
"魔兽小知识:“墓穴猎手”5人本【诸王之眠】史诗难度首领【达萨大王】小几率掉落。",
"魔兽小知识:“鲨鱼饵”5人本【自由镇】史诗难度首领【哈兰.斯威提】小几率掉落。",
"魔兽小知识:“孢林抱齿兽”5人本【地渊孢林】史诗难度首领【不羁畸变怪】小几率掉落。",
"魔兽小知识:“黑掌”120级版本黑海岸的稀有【阿加丝.苦艾】/【黑掌】有几率掉落。",
"魔兽小知识:“灰谷奇美拉”120级版本黑海岸的稀有【阿拉什阿尼尔】有几率掉落。",
"魔兽小知识:“惊恐的科多兽”120级版本黑海岸的特殊稀有【惊恐的科多兽】必掉。",
"魔兽小知识:“珀色夜刃豹”120级版本黑海岸的稀有【斩颅者莫克索】/【阿希尔.露火】有几率掉落。",
"魔兽小知识:“卡多雷夜刃豹”120级版本黑海岸的稀有【克罗兹.血怒】/【影爪】有几率掉落。",
"魔兽小知识:“加氏灭世机甲”120级团本【达萨罗之战】首领【大工匠梅卡托克】小几率掉落。",
"魔兽小知识:“冰川狂潮”120级团本【达萨罗之战】史诗难度首领【吉安娜】小几率掉落,掉率1%。",
"魔兽小知识:“锈废飘移者”麦卡贡稀有【锈羽】几率掉落,掉率0.5%。",
"魔兽小知识:“生锈的机械爬蛛”麦卡贡稀有【蜘蛛收割者】几率掉落,掉率0.3%。",
"魔兽小知识:“麦卡贡维和者”5人本【麦卡贡行动】史诗难度首领【HK-8型空中压制单位】小几率掉落。",
"魔兽小知识:“R-21/X型空中单位”5人本【麦卡贡行动】史诗困难模式(点灯)最后首领【麦卡贡国王】必掉。",
"魔兽小知识:“喑声翔渊者”120级版本纳萨塔尔的稀有【无声者】小几率掉落,掉率0.5%。",
"魔兽小知识:“法比乌斯”120级版本纳萨塔尔与【法比乌斯】同框自拍获取。",
"魔兽小知识:“四风幼龙”120级版本奥丹姆稀有【四风之龙艾夏克】小几率掉落。",
"魔兽小知识:“馨劳”120级版本锦绣谷稀有【丹心魁麟昂德】小几率掉落。",
"魔兽小知识:“茉莉”120级版本沃顿稀有【食沙者克劳洛克】小几率掉落。",
"魔兽小知识:“恶毒工蜂”120级版本锦绣谷稀有【亥离】小几率掉落。",
"魔兽小知识:“亥离之嗣”120级版本奥丹姆稀有【食尸者】小几率掉落。",
"魔兽小知识:“尼奥罗萨全视者”120级团本【尼奥罗萨】史诗难度首领【腐蚀者恩佐斯】小几率掉落,掉率1%。",
"魔兽小知识:“皎白云端翔龙”120级版本锦绣谷稀有【皎白云端翔龙】小几率掉落。",
"魔兽小知识:“废土劫掠者”120级版本奥丹姆稀有【腐肉9999】小几率掉落。",
"魔兽小知识:“轻盈的迅蹄驼”120级版本沃顿喂食【海滩叶蔬沙拉】必掉。",
"魔兽小知识:“任衙的忠犬”120级版本锦绣谷魔古入侵时稀有【犬师任衙】小几率掉落。",
"魔兽小知识:“邮件吞噬者”120级版本惊魂幻象【开启邮箱】刷新出稀有【邮件吞噬者】必掉。",
}
local currentIndex = 1
local originSendMessage = F.SendMessage
F.SendMessage = function(self, text, chatType, ...)
if not F.db.SmartReply.OnlyWhisper or chatType == 'WHISPER' then
if text and text ~= '' then
local fixerText = ''
if F.db.SmartReply.ContentMode == 2 then
fixerText = fixer[currentIndex]
currentIndex = currentIndex + 1
if currentIndex > #fixer then
currentIndex = 1
end
else
fixerText = fixer[random(#fixer)]
end
local prefix = random(2)
if prefix == 1 then
text = fixerText .. F.db.SmartReply.Delimiter .. text
else
text = text .. F.db.SmartReply.Delimiter .. fixerText
end
end
end
return originSendMessage(self, text, chatType, ...)
end
P["SmartReply"] = {
["OnlyWhisper"] = true,
["Delimiter"] = '-',
["ContentMode"] = 1,
}
F.Options.args.Plugins.args.SmartReply = {
name = "自动前后缀",
type = 'group',
get = function(info) return F.db.SmartReply[info[#info]] end,
set = function(info, value) F.db.SmartReply[info[#info]] = value end,
args = {
OnlyWhisper = {
order = 1,
name = "仅在密语添加",
type = 'toggle',
},
Delimiter = {
order = 2,
name = "分隔符",
type = 'input',
},
ContentMode = {
order = 3,
name = "内容选择模式",
type = 'select',
style = 'radio',
values = {
[1] = "随机",
[2] = "顺序",
},
},
},
}
|
<% if reply.ups and #reply.ups >= topic.reply_up_threshold then %>
<div class='cell reply_area reply_item reply_highlight' reply_id="<%- reply.id %>" reply_to_id="<%- reply.reply_id or '' %>" id="<%- reply.id %>">
<% else %>
<div class='cell reply_area reply_item' reply_id="<%- reply.id %>" reply_to_id="<%- reply.reply_id or '' %>" id="<%- reply.id %>">
<% end %>
<% local author = reply.author %>
<div class='author_content'>
<a href="/user/<%- author.loginname %>" class="user_avatar">
<img src="<%- avatar(author.avatar_url) %>" title="<%- author.loginname %>"/></a>
<div class='user_info'>
<a class='dark reply_author' href="/user/<%- author.loginname %>"><%- author.loginname %></a>
<a class="reply_time" href="#<%- reply.id %>"><strong><%- indexInCollection %>楼</strong></a>
<%- showDate(reply.create_at) %>
<% if author.loginname == topic.author.loginname then %>
<span class="reply_by_author">楼主</span>
<% end %>
</div>
<div class='user_action'>
<span>
<i class="fa up_btn <%- (current_user and is_uped(current_user, reply)) and 'fa-thumbs-up uped' or 'fa-thumbs-o-up' %> <%- (not reply.ups or #reply.ups == 0) and ' invisible' or '' %>" title="喜欢"></i>
<span class="up-count"><%- (reply.ups and #reply.ups>0) and #reply.ups or '' %></span>
</span>
<% if (current_user and current_user.is_admin) or (current_user and current_user.id == reply.author.id) then %>
<a href='/reply/<%- reply.id %>/edit' class='edit_reply_btn'><i class="fa fa-pencil-square-o" title='编辑'></i></a>
<a href='javascript:void(0);' class='delete_reply_btn'><i class="fa fa-trash" title='删除'></i></a>
<% end %>
<span>
<% if current_user then %>
<i class="fa fa-reply reply2_btn" title="回复"></i>
<% end %>
</span>
</div>
</div>
<div class='reply_content from-<%- author.loginname %>'>
<%- markdown(reply.linkedContent or reply.content) %>
</div>
<div class='clearfix'>
<div class='reply2_area'>
<% if current_user then %>
<form class='reply2_form' action='/<%- topic.id %>/reply?_csrf=<%- csrf %>' method='post'>
<input type='hidden' name='_csrf' value='<%- csrf %>'/>
<input type='hidden' name='reply_id' value='<%- reply.id %>'/>
<div class='markdown_editor in_editor'>
<div class='markdown_in_editor'>
<textarea class='span8 editor reply_editor' id="reply2_editor_<%- reply.id %>" name='r_content' rows='4'></textarea>
<div class='editor_buttons'>
<% if topic.lock == 1 then %>
<input class='span-primary reply2_submit_btn submit_btn' type="submit" data-id='<%- reply.id %>' data-loading-text="回复中.." value="回复(此主题已锁定)" disabled="disabled"/>
<% else %>
<input class='span-primary reply2_submit_btn submit_btn' type="submit" data-id='<%- reply.id %>' data-loading-text="回复中.." value="回复" />
<% end %>
</div>
</div>
</div>
</form>
<% end %>
</div>
</div>
</div>
|
#!/usr/bin/env lua
local Spore = require 'Spore'
require 'Test.Assertion'
plan(13)
local client = Spore.new_from_spec './test/api.json'
equals( #client.middlewares, 0 )
error_matches( function () client:enable_if(true) end,
"bad argument #2 to enable_if %(function expected, got boolean%)" )
error_matches( function () client:enable_if(function () return true end, true) end,
"bad argument #3 to enable_if %(string expected, got boolean%)" )
error_matches( function () client:enable_if(function () return true end, 'MyMiddleware', true) end,
"bad argument #4 to enable_if %(table expected, got boolean%)" )
error_matches( function () client:enable(true) end,
"bad argument #2 to enable %(string expected, got boolean%)" )
error_matches( function () client:enable('MyMiddleware', true) end,
"bad argument #3 to enable %(table expected, got boolean%)" )
error_matches( function () client:enable 'Spore.Middleware.Unknown' end,
"module 'Spore%.Middleware%.Unknown' not found" )
error_matches( function () client:enable 'Unknown' end,
"module 'Spore%.Middleware%.Unknown' not found" )
package.loaded['Spore.Middleware.Dummy'] = { call = true }
error_matches( function () client:enable 'Dummy' end,
"Spore%.Middleware%.Dummy without a function call" )
package.loaded['Spore.Middleware.Dummy'] = { call = function () end }
client:enable 'Dummy'
equals( #client.middlewares, 1 )
is_table( client.middlewares[1] )
client:enable_if(function (req) return true end, 'Dummy')
equals( #client.middlewares, 2 )
client:reset_middlewares()
equals( #client.middlewares, 0 )
|
Config = {}
Config.DrawDistance = 100.0
--language currently available EN and SV
Config.Locale = 'es'
Config.Zones = {
PoliceDutyRow = {
Pos = { x = 441.0, y = -975.7, z = 29.70 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
PoliceDutyVesp = {
Pos = { x = 441.0, y = -975.7, z = 29.70 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
PoliceDutySandy = {
Pos = { x = 1851.44, y = 3690.87, z = 33.27 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
AmbulanceDuty = {
Pos = { x = 306.83, y = -597.78, z = 42.29 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
MechanicDuty = {
Pos = { x = -346.51, y = -127.14, z = 38.02 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
TaxiLS = {
Pos = { x = 895.26, y = -176.38, z = 73.69 },
Size = { x = 1.5, y = 1.5, z = 1.5 },
Color = { r = 0, g = 255, b = 0 },
Type = 27,
},
}
|
local util = require('colorscheme-tweaks.util')
local M = {}
-- Taken from: https://www.tutorialspoint.com/how-to-split-a-string-in-lua-programming
local function stringSplit(inputStr, seperator)
if(seperator == nil) then
seperator = '%s'
end
local t={}
for str in string.gmatch(inputStr, "([^"..seperator.."]+)") do
table.insert(t, str)
end
return t
end
-- Parse the output of :highlight to get all of the individual line items from a colorscheme
local function getHighlightGroups()
local highlightOutput = vim.api.nvim_exec([[highlight]], true)
local highlights = stringSplit(highlightOutput, '\n')
local commands = {}
for _,row in pairs(highlights) do
-- Sample Input: "SignColumn xxx ctermfg=14 ctermbg=242 guifg=#292E44 guibg=#12131B"
local currKey = nil
local inputs = stringSplit(row)
for idx, entry in ipairs(inputs) do
if idx == 1 then
currKey = entry
elseif idx >= 3 and string.find(entry, 'gui') then
local kvs = stringSplit(entry, '=') --guifg=#ffffff
if string.find(kvs[2], '#') and string.lower(kvs[2]) ~= '#none' then
local highInput = {}
highInput[kvs[1]] = kvs[2]
local input = {}
input[currKey] = highInput
table.insert(commands, input)
end
end
end
end
return commands
end
M.increaseContrastBy = function(increaseFactor)
local colors = getHighlightGroups()
-- Loops to increase contrast of existing color schemes
for _, val in pairs(colors) do
if type(val) == 'table' then
for key, nval in pairs(val) do
for ctype, cval in pairs(nval) do
if(increaseFactor == 0) then
elseif(increaseFactor > 0) then
local newValue = util.increaseContrast(cval, increaseFactor)
local command = 'highlight '..key..' '..ctype..'='..newValue
-- print(command)
vim.cmd(command)
end
end
end
end
end
end
M.decreaseContrastBy = function(decreaseFactor)
local colors = getHighlightGroups()
-- Loops to increase contrast of existing color schemes
for _, val in pairs(colors) do
if type(val) == 'table' then
for key, nval in pairs(val) do
for ctype, cval in pairs(nval) do
if(decreaseFactor > 0) then
local newValue = util.decreaseContrast(cval, decreaseFactor)
local command = 'highlight '..key..' '..ctype..'='..newValue
-- print(command)
vim.cmd(command)
end
end
end
end
end
end
return M
|
local lfs = require('lfs')
local helpers = require('test.functional.helpers')(after_each)
local clear, eq, matches = helpers.clear, helpers.eq, helpers.matches
local eval, command, call = helpers.eval, helpers.command, helpers.call
local exec_capture = helpers.exec_capture
describe('autochdir behavior', function()
local dir = 'Xtest_functional_legacy_autochdir'
before_each(function()
lfs.mkdir(dir)
clear()
end)
after_each(function()
helpers.rmdir(dir)
end)
-- Tests vim/vim/777 without test_autochdir().
it('sets filename', function()
command('set acd')
command('new')
command('w '..dir..'/Xtest')
eq('Xtest', eval("expand('%')"))
eq(dir, eval([[substitute(getcwd(), '.*[/\\]\(\k*\)', '\1', '')]]))
end)
it(':verbose pwd shows whether autochdir is used', function()
local subdir = 'Xautodir'
command('cd '..dir)
local cwd = eval('getcwd()')
command('edit global.txt')
matches('%[global%].*'..dir, exec_capture('verbose pwd'))
call('mkdir', subdir)
command('split '..subdir..'/local.txt')
command('lcd '..subdir)
matches('%[window%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
command('set autochdir')
command('wincmd w')
matches('%[autochdir%].*'..dir, exec_capture('verbose pwd'))
command('lcd '..cwd)
matches('%[window%].*'..dir, exec_capture('verbose pwd'))
command('tcd '..cwd)
matches('%[tabpage%].*'..dir, exec_capture('verbose pwd'))
command('cd '..cwd)
matches('%[global%].*'..dir, exec_capture('verbose pwd'))
command('edit')
matches('%[autochdir%].*'..dir, exec_capture('verbose pwd'))
command('wincmd w')
matches('%[autochdir%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
command('set noautochdir')
matches('%[autochdir%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
command('wincmd w')
matches('%[global%].*'..dir, exec_capture('verbose pwd'))
command('wincmd w')
matches('%[window%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
end)
end)
|
-- 0 is supposed to be the default (ie. don't close tree when opening a file),
-- but it closes anyway; see: https://github.com/kyazdani42/nvim-tree.lua/issues/502
vim.g.nvim_tree_quit_on_open = 0
vim.g.nvim_tree_disable_window_picker = 1
vim.g.nvim_tree_indent_markers = 1
vim.g.nvim_tree_show_icons = {
git = 0,
folders = 0,
files = 0,
folder_arrows = 0,
}
-- Normally README.md gets highlighted by default, which is a bit distracting.
vim.g.nvim_tree_special_files = {}
|
local function qqmusic(message)
local key = message:gsub("点歌 *","")
if key == "" then return "请正确输入关键词" end
local songID = tonumber(key)
if not songID and key then
local html = asyncHttpGet("https://c.y.qq.com/soso/fcgi-bin/client_search_cp", "?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song&searchid=&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w="..key:urlEncode())
local str = html:match("callback%((.+)%)")
local j,r,e = jsonDecode(str)
if r and j.data and j.data.song and j.data.song.list and j.data.song.list[1] then
songID = j.data.song.list[1].id
elseif e then
return "机器人爆炸了,原因:"..e
end
end
if songID then
return "[CQ:music,type=qq,id="..tostring(songID).."]"
else
return "机器人爆炸了,原因:根本没这首歌"
end
end
return {--点歌
check = function (data)
return data.msg:find("点歌") == 1
end,
run = function (data,sendMessage)
if not checkCoolDownTime(data,"qqmusic",sendMessage) then
return true
end
sys.taskInit(function()
local r = qqmusic(data.msg)
sendMessage(r)
if not r:find("爆炸") and r ~= "请正确输入关键词" then
setCoolDownTime(data,"qqmusic",5*60)
end
end)
return true
end,
explain = function ()
return "[CQ:emoji,id=127932]点歌 加 qq音乐id或歌名"
end
}
|
sniper_extra = class({})
LinkLuaModifier("modifier_sniper_extra_displacement", "abilities/heroes/sniper/sniper_extra/modifier_sniper_extra_displacement", LUA_MODIFIER_MOTION_BOTH)
LinkLuaModifier("modifier_sniper_extra_displacement_enemy", "abilities/heroes/sniper/sniper_extra/modifier_sniper_extra_displacement_enemy", LUA_MODIFIER_MOTION_BOTH)
function sniper_extra:OnAbilityPhaseStart()
EmitSoundOn("Ability.AssassinateLoad", self:GetCaster())
return true
end
function sniper_extra:GetCastAnimationCustom() return ACT_DOTA_ATTACK end
function sniper_extra:GetPlaybackRateOverride() return 0.4 end
function sniper_extra:GetCastPointSpeed() return 0 end
function sniper_extra:OnSpellStart()
local caster = self:GetCaster()
local origin = caster:GetAbsOrigin()
local point = CustomAbilitiesLegacy:GetCursorPosition(self)
local knockback_distance = self:GetSpecialValueFor("knockback_distance")
local damage = self:GetSpecialValueFor("damage_per_bullet")
local projectile_speed = self:GetSpecialValueFor("projectile_speed")
local projectile_distance = self:GetCastRange(Vector(0,0,0), nil)
local straight_direction = Direction2D(origin, point)
local directions = {}
table.insert(directions, straight_direction)
table.insert(directions, RotatePoint(Vector(0,0,0), Vector(0,0,0) + straight_direction, -30):Normalized())
table.insert(directions, RotatePoint(Vector(0,0,0), Vector(0,0,0) + straight_direction, 30):Normalized())
for _,direction in ipairs(directions) do
CustomEntitiesLegacy:ProjectileAttack(caster, {
tProjectile = {
EffectName = "particles/sniper/sniper_extra.vpcf",
vSpawnOrigin = caster:GetAbsOrigin() + Vector(0,0,60),
fDistance = projectile_distance,
fStartRadius = self:GetSpecialValueFor("hitbox"),
Source = caster,
vVelocity = direction * projectile_speed,
UnitBehavior = PROJECTILES_DESTROY,
TreeBehavior = PROJECTILES_NOTHING,
WallBehavior = PROJECTILES_DESTROY,
GroundBehavior = PROJECTILES_NOTHING,
fGroundOffset = 0,
UnitTest = function(_self, unit) return unit:GetUnitName() ~= "npc_dummy_unit" and not CustomEntitiesLegacy:Allies(_self.Source, unit) end,
OnUnitHit = function(_self, unit)
local x = unit:GetOrigin().x - origin.x
local y = unit:GetOrigin().y - origin.y
local distance = knockback_distance - (unit:GetOrigin() - origin):Length2D()
unit:AddNewModifier(
_self.Source, -- player source
self, -- ability source
"modifier_sniper_extra_displacement_enemy", -- modifier name
{
x = x,
y = y,
r = distance,
speed = (distance/0.35),
peak = 32,
}
)
local damage_table = {
victim = unit,
attacker = _self.Source,
damage = damage,
damage_type = DAMAGE_TYPE_MAGICAL,
}
ApplyDamage(damage_table)
end,
OnFinish = function(_self, pos)
self:PlayEffectsOnFinish(pos)
end,
}
})
end
local knockback_direction = -(point - origin):Normalized()
caster:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_sniper_mobility_displacement", -- modifier name
{
x = knockback_direction.x,
y = knockback_direction.y,
r = knockback_distance,
speed = (knockback_distance/0.35),
peak = 64,
}
)
self:PlayEffectsOnCast()
end
function sniper_extra:PlayEffectsOnCast()
EmitSoundOn("Hero_Techies.LandMine.Detonate", self:GetCaster())
end
function sniper_extra:PlayEffectsOnFinish(pos)
local caster = self:GetCaster()
EmitSoundOnLocationWithCaster(pos, "Hero_Sniper.ProjectileImpact", caster)
local particle_cast = "particles/units/heroes/hero_techies/techies_base_attack_explosion.vpcf"
local effect_cast = ParticleManager:CreateParticle(particle_cast, PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(effect_cast, 0, pos)
ParticleManager:SetParticleControl(effect_cast, 3, pos)
ParticleManager:ReleaseParticleIndex(effect_cast)
end
if IsClient() then require("wrappers/abilities") end
Abilities.Castpoint(sniper_extra)
|
local spot_index = 0
local function run(wsbuf, p, spots_count)
if not (type(spots_count) == "number" and spots_count > 0) then
spots_count = 1
end
local spots_distance = wsbuf:size()/spots_count
spot_index = (spot_index + 1) % spots_distance
wsbuf:fade(2,ws2812.FADE_OUT)
local pos = 0
for nspot = 0, spots_count -1 do
pos = spot_index+1+nspot*spots_distance
wsbuf:set(pos, 255 ,255, 255)
if pos < wsbuf:size() then wsbuf:set(pos+1, 64 ,64, 64) end
end
return 20 + ((200 * (255 - p.speed)) / 255)
end
return run
|
-- Import SM for statusbar-textures, font-styles and border-types
local SharedMedia = LibStub("LibSharedMedia-3.0");
-- Import translation
local L = WeakAuras.L;
-- Create region options table
local function createOptions(id, data)
local options = {
model_path = {
type = "input",
width = "double",
name = L["Model"],
order = 0
},
space1 = {
type = "execute",
name = "",
order = 2,
image = function() return "", 0, 0 end,
},
space2 = {
type = "execute",
name = "",
width = "half",
order = 5,
image = function() return "", 0, 0 end,
},
chooseModel = {
type = "execute",
name = L["Choose"],
width = "half",
order = 7,
func = function()
WeakAuras.OpenModelPick(data, "model_path");
end
},
model_z = {
type = "range",
name = L["Z Offset"],
softMin = -2,
softMax = 2,
step = .001,
bigStep = 0.05,
order = 20,
},
model_x = {
type = "range",
name = L["X Offset"],
softMin = -2,
softMax = 2,
step = .001,
bigStep = 0.05,
order = 30,
},
model_y = {
type = "range",
name = L["Y Offset"],
softMin = -2,
softMax = 2,
step = .001,
bigStep = 0.05,
order = 40,
},
advance = {
type = "toggle",
name = L["Animate"],
order = 25,
},
sequence = {
type = "range",
name = L["Animation Sequence"],
min = 0,
max = 150,
step = 1,
bigStep = 1,
order = 35,
disabled = function() return not data.advance end
},
rotation = {
type = "range",
name = L["Rotation"],
min = 0,
max = 360,
step = 1,
bigStep = 3,
order = 45
},
border_header = {
type = "header",
name = L["Border Settings"],
order = 46
},
spacer = {
type = "header",
name = "",
order = 50
}
};
--
options = WeakAuras.AddPositionOptions(options, id, data);
--
options = WeakAuras.AddBorderOptions(options, id, data);
--
return options;
end
local function createThumbnail(parent, fullCreate)
local borderframe = CreateFrame("FRAME", nil, parent);
borderframe:SetWidth(32);
borderframe:SetHeight(32);
local border = borderframe:CreateTexture(nil, "Overlay");
border:SetAllPoints(borderframe);
border:SetTexture("Interface\\BUTTONS\\UI-Quickslot2.blp");
border:SetTexCoord(0.2, 0.8, 0.2, 0.8);
local model = CreateFrame("PlayerModel", nil, WeakAuras.OptionsFrame() or UIParent);
borderframe.model = model;
model:SetFrameStrata("FULLSCREEN");
return borderframe;
end
local function modifyThumbnail(parent, region, data, fullModify, size)
local model = region.model
if(region:GetFrameStrata() == "TOOLTIP") then
model:SetParent(region);
model:SetAllPoints(region);
model:SetFrameStrata(region:GetParent():GetFrameStrata());
else
model:SetParent(WeakAuras.OptionsFrame() or UIParent);
model:ClearAllPoints();
region:SetScript("OnUpdate", function()
local x, y = region:GetCenter();
local optionsFrame = WeakAuras.OptionsFrame();
if(optionsFrame) then
model:ClearAllPoints();
model:SetPoint("center", UIParent, "bottomleft", x, y);
local scrollBottom = optionsFrame.buttonsContainer.frame:GetBottom();
local scrollTop = optionsFrame.buttonsContainer.frame:GetTop() and (optionsFrame.buttonsContainer.frame:GetTop() - 16);
if(
optionsFrame.buttonsContainer:IsVisible()
and region:GetTop() and scrollTop
and region:GetTop() < scrollTop
and region:GetBottom() and scrollBottom
and region:GetBottom() > scrollBottom
) then
model:Show();
else
model:Hide();
end
else
model:Hide();
end
end);
region:SetScript("OnShow", function() model:Show() end);
region:SetScript("OnHide", function() model:Hide() end);
end
model:SetWidth(region:GetWidth() - 2);
model:SetHeight(region:GetHeight() - 2);
model:SetPoint("center", region, "center");
if tonumber(data.model_path) then
model:SetDisplayInfo(tonumber(data.model_path))
else
model:SetModel(data.model_path);
end
model:SetScript("OnShow", function()
if tonumber(data.model_path) then
model:SetDisplayInfo(tonumber(data.model_path))
else
model:SetModel(data.model_path);
end
end);
model:SetPosition(data.model_z, data.model_x, data.model_y);
model:SetFacing(rad(data.rotation));
end
local function createIcon()
local data = {
model_path = "Creature/Arthaslichking/arthaslichking.m2",
model_x = 0,
model_y = 0,
model_z = 0.35,
sequence = 1,
advance = false,
rotation = 0,
scale = 1,
height = 40,
width = 40
};
local thumbnail = createThumbnail(UIParent);
modifyThumbnail(UIParent, thumbnail, data, nil, 50);
return thumbnail;
end
WeakAuras.RegisterRegionOptions("model", createOptions, createIcon, L["Model"], createThumbnail, modifyThumbnail, L["Shows a 3D model from the game files"]);
|
--[[
Easy run stats library.
Prints FPS and delta-time.
Methods:
void Update(DeltaTime) Send an update. Should be called every love.update()
void Display(x, y) Display pre-formatted text at (x, y) via love.graphics.print
void DisplayCustom(format_text, x, y) Display custom-formatted text at (x, y)
Formatting is the same as lua's system.
The default for this function:
FPS: %d | dt: %d ms
--]]
local RunStats = {}
local DELTA = 0
local TICKS = 0
local AVG_FPS = 0
local TIMER = 0
function RunStats:Update(Delta)
DELTA = Delta
AVG_FPS = AVG_FPS + (1/DELTA)
TICKS = TICKS + 1
TIMER = TIMER + Delta
if TIMER >= 1 then
TIMER = TIMER - 1
AVG_FPS = 0
TICKS = 0
end
end
function RunStats:DisplayCustom(Text, x, y)
local Text = Text or "FPS: %d | dt: %dms"
local x = x or 0
local y = y or 0
love.graphics.print(string.format(Text, math.floor(AVG_FPS / TICKS), math.floor(DELTA * 1000)), x, y)
end
function RunStats:Display(x, y)
RunStats:DisplayCustom(nil, x, y)
end
return RunStats
|
---------------------------------------------------------------------------------------------------
-- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0041-appicon-resumption.md
-- User story:TBD
-- Use case:TBD
--
-- Requirement summary:
-- TBD
--
-- Description:
-- In case:
-- 1) SDL, HMI are started.
-- 2) Mobile application is registered and sets custom icon via sending PutFile and valid SetAppIcon request.
-- 3) Mobile application is unregistered.
-- 4) Remove Icon for mobile app from the file system
-- 5) Mobile app is re-registered, mobile app is registered.
-- SDL does:
-- 1) SDL respond with result code "SUCCESS" and "iconResumed" = false for RAI request.
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/API/SetAppIcon/commonIconResumed')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local iconValue = "icon.png"
local allParams = {
requestParams = {
syncFileName = iconValue
},
requestUiParams = {
syncFileName = {
imageType = "DYNAMIC",
value = common.getPathToFileInStorage(iconValue)
}
}
}
local function removeIcon(pAppId)
os.remove(common.getIconValueForResumption(pAppId))
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Title("Test")
runner.Step("App registration with iconResumed = false", common.registerAppWOPTU, { 1, false })
runner.Step("Upload icon file", common.putFile)
runner.Step("SetAppIcon", common.setAppIcon, { allParams } )
runner.Step("App unregistration", common.unregisterAppInterface, { 1 })
runner.Step("Remove Icon for mobile app from the file system", removeIcon, { 1 })
runner.Step("App registration with iconResumed = false", common.registerAppWOPTU, { 1, false, true })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local base = require( "acid.paxos.base" )
local paxos = require( "acid.paxos" )
local round = require( "acid.paxos.round" )
local tableutil = require( "acid.tableutil" )
local logging = require( "acid.logging" )
local errors = base.errors
local prop_sto = {
committed= {
ver=1,
val = {
view={
{ a=1, b=1, c=1 },
{ c=1, d=1, e=1 },
},
},
},
}
local mes_receiver = {}
local prop_args = {
cluster_id = 'cluster_a',
ident='1',
}
local prop_impl = {
load= function( self, pp )
return tableutil.dup(prop_sto, true)
end,
time= function( self ) return os.time() end,
send_req= function( self, pp, id, mes )
mes_receiver[ id ] = mes
return 'resp'
end,
}
function test_new(t)
t:err( function() paxos.proposer.new( nil ) end, 'nil' )
t:err( function() paxos.proposer.new( {} ) end, 'empty table' )
local x, err = paxos.proposer.new( prop_args, prop_impl )
t:contain( prop_args, x )
t:eq( prop_impl, x.impl )
t:eqdict( prop_sto.committed.val.view, x.view, 'load view' )
t:eqdict( { a=true, b=true, c=true, d=true, e=true }, x.acceptors, 'acceptors' )
t:eqlist( { 0, prop_args.ident }, x.rnd, 'initial rnd' )
end
function test_new_with_ver(t)
local args = tableutil.dup( prop_args )
args.ver = 1
local x, err = paxos.proposer.new( args, prop_impl )
t:eq( nil, err )
t:eq( args.ver, x.ver )
args.ver = 2
local x, err = paxos.proposer.new( args, prop_impl )
t:eq( errors.VerNotExist, err )
end
function test_new_with_roundmaker(t)
local impl = tableutil.dup( prop_impl )
impl.new_rnd = function (self) return 123 end
local prop, err = paxos.proposer.new( { cluster_id="1", ident="2" }, impl )
t:eq( nil, err )
t:eq( 0, round.cmp( prop.rnd, { 123, "2" } ) )
end
function test_new_no_view(t)
local sto = {}
local args = {
ident='a',
}
local impl = {
load=function( key ) return sto end,
time= function( self ) return os.time() end,
}
local cases = {
{ committed=nil, rst=nil, err=errors.NoView },
{ committed={ ver=1, val=nil }, rst=nil, err=errors.NoView },
{ committed={ ver=1, val={view={}} }, rst=nil, err=errors.NoView },
{ committed={ ver=1, val={view={{}}} }, rst={}, err=nil },
}
for i, case in ipairs( cases ) do
sto.committed = case.committed
local x, err = paxos.proposer.new( args, impl )
if case.rst then
t:neq( nil, x, i..' committed: ' .. tableutil.repr( case.committed ) )
else
t:eq( nil, x, i..' committed: ' .. tableutil.repr( case.committed ) )
end
t:eq( case.err, err )
end
sto.committed = { ver=1, val={ view={ { a=1 } } } }
local x, err = paxos.proposer.new( args, impl )
t:neq( nil, x )
t:eq( nil, err )
t:neq( 0, tableutil.nkeys( x.acceptors ) )
end
function test_sendmes(t)
local prop = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
local resp = prop.impl:send_req( prop, 'theid', 1 )
t:eq( 1, mes_receiver.theid, 'receive mes' )
t:eq( 'resp', resp, 'got resp from send_req' )
end
function test_send_mes_all(t)
local x = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
local rs = x:send_mes_all(2)
t:eqdict( { a=2, b=2, c=2, d=2, e=2 }, mes_receiver, 'all got message' )
t:eqdict( {
a='resp',
b='resp',
c='resp',
d='resp',
e='resp',
}, rs )
end
function test_phase1(t)
local x = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
local rs = x:phase1()
t:eqdict( {
a='resp',
b='resp',
c='resp',
d='resp',
e='resp',
}, rs )
t:eqdict( { a=2, b=2, c=2, d=2, e=2 },
tableutil.intersection( { mes_receiver }, 2 ), 'got 5 mes' )
for k, v in pairs(mes_receiver) do
t:eq( 'phase1', v.cmd )
t:eq( prop_args.cluster_id, v.cluster_id )
t:eqlist( { 0, x.ident }, v.rnd )
end
end
function test_phase2(t)
local x = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
local rs = x:phase2('val')
t:eqdict( {
a='resp',
b='resp',
c='resp',
d='resp',
e='resp',
}, rs )
t:eqdict( { a=2, b=2, c=2, d=2, e=2 },
tableutil.intersection( { mes_receiver }, 2 ), 'got 5 mes' )
for k, v in pairs(mes_receiver) do
t:eq( 'phase2', v.cmd )
t:eq( prop_args.cluster_id, v.cluster_id )
t:eqlist( { 0, x.ident }, v.rnd )
t:eq( 'val', v.val )
end
end
function test_phase3(t)
local x = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
-- TODO test run decide twice
local rs, err = x:commit()
t:eq( nil, rs )
t:eq( errors.InvalidPhase, err, 'no accepted_val cause err' )
x.stat = {}
x.stat.accepted_val = 'accepted_val'
x.ver = 100
local c, err = x:commit()
t:eq( nil, err )
-- t:eqdict( {
-- a='resp',
-- b='resp',
-- c='resp',
-- d='resp',
-- e='resp',
-- }, rs )
t:eqdict( { a=2, b=2, c=2, d=2, e=2 },
tableutil.intersection( { mes_receiver }, 2 ), 'got 5 mes' )
for k, v in pairs(mes_receiver) do
t:eq( 'phase3', v.cmd )
t:eq( prop_args.cluster_id, v.cluster_id )
t:eq( 100+1, v.ver )
t:eq( 'accepted_val', v.val )
end
end
function test_decide_twice(t)
local x = paxos.proposer.new( prop_args, prop_impl )
mes_receiver = {}
local _, err = x:decide(0)
local _, err = x:decide(2)
t:eq( errors.InvalidPhase, err )
end
function test_choose_p1(t)
local x = paxos.proposer.new( prop_args, prop_impl )
local accepted, v, stat = x:choose_p1( {}, 1 )
t:eqdict( {}, accepted )
t:eqdict( x.rnd, stat.latest_rnd )
t:eq( 1, v )
-- val exists
local resps = {
a={ rnd=round.new({ 5, 'x' }), val='a', vrnd=round.new({ 2, 'c' }) },
b={ rnd=x.rnd },
c={ rnd=x.rnd, val='c', vrnd=round.new({ 1, 'a' }) },
}
local accepted, v, stat = x:choose_p1( resps, 10 )
t:eqdict( {b=2, c=2}, tableutil.union({accepted}, 2) )
t:eqdict( {5, 'x'}, stat.latest_rnd )
t:eq( 'a', v )
-- choose my val
local resps = {
a={ rnd=round.new({ 5, 'x' }) },
b={ rnd=x.rnd },
c={ rnd=x.rnd },
}
local accepted, v, stat = x:choose_p1( resps, 10 )
t:eqdict( {b=2, c=2}, tableutil.union({accepted}, 2) )
t:eqdict( {5, 'x'}, stat.latest_rnd )
t:eq( 10, v )
-- committed
local resps = {
a={ rnd=round.new({ 5, 'x' }) },
b={ err={ Code=errors.AlreadyCommitted, Message={ ver=3, val='committed-3' } } },
c={ err={ Code=errors.AlreadyCommitted, Message={ ver=2, val='committed-2' } } },
}
local accepted, v, stat = x:choose_p1( resps, 10 )
t:eqdict( {}, tableutil.union({accepted}, true) )
t:eqdict( { 5, 'x' }, stat.latest_rnd )
t:eq( 10, v )
t:eqdict( {ver=3, val='committed-3'}, stat.latest_committed )
-- stale_vers
local resps = {
a={ rnd=round.new({ 5, 'x' }) },
b={ err={ Code=errors.VerNotExist, Message=1 } },
c={ err={ Code=errors.VerNotExist, Message=0 } },
}
x.ver = 2
local accepted, v, stat = x:choose_p1( resps, 10 )
t:eqdict( {}, tableutil.union({accepted}, true) )
t:eqdict( {c=0, b=1}, stat.stale_vers )
end
function test_choose_p2(t)
local x = paxos.proposer.new( prop_args, prop_impl )
local accepted = x:choose_p2( {} )
t:eqdict( {}, accepted )
local resps = {
a={err={}},
b={},
c={},
}
local accepted = x:choose_p2( resps )
t:eqdict( {b=2, c=2}, tableutil.union({accepted}, 2) )
end
function test_is_quorum(t)
local x = paxos.proposer.new( prop_args, prop_impl )
x.view = {
{ a=1, b=1, c=1 },
}
t:eq( false, x:is_quorum( {} ) )
t:eq( false, x:is_quorum( {a=1} ) )
t:eq( false, x:is_quorum( {c=1} ) )
t:eq( true, x:is_quorum( {a=1, b=1} ) )
t:eq( true, x:is_quorum( {a=1, b=1, c=1} ) )
t:eq( false, x:is_quorum( {a=1, x=1, y=1} ) )
-- dual group
x.view = {
{ a=1, b=1, c=1 },
{ c=1, d=1, e=1 },
}
t:eq( true, x:is_quorum( { a=nil, b=1, c=1, d=1 } ) )
t:eq( true, x:is_quorum( { a=1, b=1, c=1, d=1 } ) )
t:eq( true, x:is_quorum( { a=1, b=1, c=nil, d=1, e=1 } ) )
t:eq( false, x:is_quorum( { a=1, b=nil, c=nil, d=1, e=1 } ) )
t:eq( false, x:is_quorum( { a=nil, b=nil, c=1, d=1, e=1 } ) )
end
function test_decide(t)
local resps
local args
local impl
local myval = 10
local none = {}
function handler( self, p, id, mes )
local r = resps[ id ] or {}
if mes.cmd == 'phase1' then
r = r.p1 or { rnd=mes.rnd }
if r == none then
return nil
end
elseif mes.cmd == 'phase2' then
r = r.p2 or {}
if r == none then
return nil
end
else
error( "invalid cmd " .. tableutil.repr( mes ) )
end
return r
end
args = {
ident='a',
}
impl = {
send_req=handler,
load=function( key )
return { committed={
ver=1,
val={ view={ { a=1, b=1, c=1 } } }
}}
end,
time= function( self ) return os.time() end,
}
cases = {
{
mes = 'all accept',
statchange = {
accepted_val = 10,
},
rst = { ok=true, val=myval, err=nil },
resps = {
a={ p1={ rnd={ 1, 'a' }, vrnd=nil, val=nil }, p2={}, },
b={ p1={ rnd={ 1, 'a' }, vrnd=nil, val=nil }, p2={}, },
c={ p1={ rnd={ 1, 'a' }, vrnd=nil, val=nil }, p2={}, },
},
},
{
mes = 'old round',
rst = { ok=false, val=nil, err=errors.OldRound },
resps = {
a={ p1={ rnd={ 1, 'a' } } },
b={ p1={ rnd={ 2, 'b' } } },
},
},
{
mes = 'only 1 on phase 1',
rst = { ok=false, val=nil, err=errors.QuorumFailure },
resps = {
a={ p1=nil },
b={ p1=none },
c={ p1=none },
},
},
{
mes = 'quorum failure',
rst = { ok=true, val=myval, err=nil },
resps = {
a={ p1=nil },
b={ p1=nil },
c={ p1=none, p2=none },
},
},
{
mes = 'quorum failure on phase 2',
rst = { ok=false, val=nil, err=errors.QuorumFailure },
resps = {
a={ p1=nil, p2=none },
b={ p1=nil },
c={ p1=none, p2=none },
},
},
{
mes = 'failure on phase 2',
rst = { ok=false, val=nil, err=errors.QuorumFailure },
resps = {
a={ p1=nil, p2={ err={Code="xx"} } },
b={ p1=nil },
c={ p1=none, p2=none },
},
},
{
mes = 'existent seen',
rst = { ok=false, val=2, err=nil },
resps = {
b={ p1={ rnd={ 0, 'b' }, vrnd={ 0, 'b' }, val=2 }, p2={}, },
},
},
{
mes = 'existent seen, newest one',
rst = { ok=false, val=2, err=nil },
resps = {
a={ p1={ rnd={ 1, 'a' }, vrnd={ 0, 'a' }, val=1 }, p2={}, },
b={ p1={ rnd={ 0, 'b' }, vrnd={ 0, 'b' }, val=2 }, p2={}, },
},
},
{
mes = 'committed',
statchange = {
latest_committed = { ver=4, val="committed-4" },
},
rst = { ok=true, val=10, err=nil },
resps = {
c={
p1={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
p2={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
},
},
},
{
mes = 'stale_vers, latest_rnd, latest_committed',
statchange = {
latest_committed = { ver=4, val="committed-4" },
stale_vers = { b=0 },
latest_rnd = { 100, 'x' },
},
rst = { ok=false, val=nil, err=errors.OldRound },
resps = {
a={
p1={
rnd = { 100, 'x' },
},
},
b={
p1={
err={
Code=errors.VerNotExist,
Message=0,
},
},
},
c={
p1={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
p2={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
},
},
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local x, err = paxos.proposer.new( args, impl )
t:eq( nil, err, mes )
local val, err = x:decide( myval )
local rst = case.rst
t:eq( rst.val, val, mes )
t:eq( rst.err, err, mes )
if case.statchange then
for k, v in pairs(case.statchange) do
t:eqdict( v, x.stat[ k ], mes )
end
end
end
end
function test_write(t)
local resps
local args
local impl
local myval = 10
local none = {}
function handler( self, p, id, mes )
local r = resps[ id ] or {}
if mes.cmd == 'phase1' then
r = r.p1 or { rnd=mes.rnd }
if r == none then
return nil
end
elseif mes.cmd == 'phase2' then
r = r.p2 or {}
if r == none then
return nil
end
elseif mes.cmd == 'phase3' then
r = r.p3 or {}
if r == none then
return nil
end
else
error( "invalid cmd" .. tableutil.repr( mes ) )
end
return r
end
args = {
ident='a',
}
impl = {
send_req=handler,
load=function( key )
return { committed={
ver=1,
val={ view={ { a=1, b=1, c=1 } } }
}}
end,
time= function( self ) return os.time() end,
}
cases = {
{
mes = 'all accept',
statchange = {
accepted_val = 10,
},
rst = { err=nil },
resps = {
a={ p1=nil, p2={}, p3=nil},
b={ p1=nil, p2={}, p3=nil},
c={ p1=nil, p2={}, p3=nil},
},
},
{
mes = 'old round',
rst = { err=errors.OldRound },
resps = {
a={ p1={ rnd={ 1, 'a' } } },
b={ p1={ rnd={ 2, 'b' } } },
},
},
{
mes = 'quorum failure on phase 1',
rst = { err=errors.QuorumFailure },
resps = {
a={ p1=nil },
b={ p1=none },
c={ p1=none },
},
},
{
mes = 'quorum failure on phase 2',
rst = { err=errors.QuorumFailure },
resps = {
a={ p1=none, p2=nil },
b={ p1=nil, p2=none },
c={ p1=nil, p2=none },
},
},
{
mes = 'quorum failure on phase 3',
rst = { err=errors.QuorumFailure },
resps = {
a={ p1=none, p2=nil, p3=none },
b={ p1=nil, p2=nil, p3=nil },
c={ p1=nil, p2=none, p3=none },
},
},
{
mes = 'failure on phase 2',
rst = { err=errors.QuorumFailure },
resps = {
a={ p1=nil, p2={ err={Code="xx"} } },
b={ p1=nil },
c={ p1=none, p2=none },
},
},
{
mes = 'existent seen',
rst = { val=2, err=errors.VerNotExist },
resps = {
b={ p1={ rnd={ 0, 'b' }, vrnd={ 0, 'b' }, val=2 }, },
},
},
{
mes = 'existent seen, newest one',
rst = { val=2, err=errors.VerNotExist },
resps = {
a={ p1={ rnd={ 1, 'a' }, vrnd={ 0, 'a' }, val=1 }, },
b={ p1={ rnd={ 0, 'b' }, vrnd={ 0, 'b' }, val=2 }, },
},
},
{
mes = 'committed',
statchange = {
latest_committed = { ver=4, val="committed-4" },
},
rst = { val=10, err=nil },
resps = {
c={
p1={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
p2={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
},
},
},
{
mes = 'stale_vers, latest_rnd, latest_committed',
statchange = {
latest_committed = { ver=4, val="committed-4" },
stale_vers = { b=0 },
latest_rnd = { 100, 'x' },
},
rst = { val=nil, err=errors.OldRound },
resps = {
a={
p1={
rnd = { 100, 'x' },
},
},
b={
p1={
err={
Code=errors.VerNotExist,
Message=0,
},
},
},
c={
p1={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
p2={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
},
},
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local x, err = paxos.proposer.new( args, impl )
t:eq( nil, err, mes )
local c, err = x:write( myval )
local rst = case.rst
t:eq( rst.err, err, mes )
if err == nil then
if rst.val ~= nil then
t:eq( rst.val, c.val, mes )
end
end
if case.statchange then
for k, v in pairs(case.statchange) do
t:eqdict( v, x.stat[ k ], mes )
end
end
end
end
function test_remote_read(t)
local resps
local args
local impl
local myval = 10
local none = {}
function _sendmes( self, p, id, mes )
local r = resps[ id ] or {}
if mes.cmd == 'phase3' then
r = r.p3 or {}
if r == none then
return nil
end
else
error( "invalid cmd" .. tableutil.repr( mes ) )
end
return r
end
args = {
ident='a',
}
impl = {
send_req=_sendmes,
load=function( key )
return { committed={
ver=1,
val={ view={ { a=1, b=1, c=1 } } }
}}
end,
time= function( self ) return os.time() end,
}
cases = {
{
mes = 'nothing responded',
rst = nil,
err = errors.VerNotExist,
resps = {
a={ p3=none},
b={ p3=none},
c={ p3=none},
},
},
{
mes = 'other error',
rst = nil,
err = errors.VerNotExist,
resps = {
a={ p3=none},
b={ p3=none},
c={ p3={err={ Code=errors.StorageError }}},
},
},
{
mes = 'one seen',
rst = { ver=1, val=2 },
resps = {
a={ p3=none},
b={ p3=none},
c={ p3={err={ Code=errors.AlreadyCommitted, Message={ ver=1, val=2 } }}},
},
},
{
mes = 'one seen, need quorum',
need_quorum = true,
rst = nil,
err = errors.QuorumFailure,
resps = {
a={ p3=none},
b={ p3=none},
c={ p3={err={ Code=errors.AlreadyCommitted, Message={ ver=1, val=2 } }}},
},
},
{
mes = 'two seen, need quorum',
need_quorum = true,
rst = { ver=3, val=4 },
err = nil,
resps = {
a={ p3=none},
b={ p3={err={ Code=errors.AlreadyCommitted, Message={ ver=3, val=4 } }}},
c={ p3={err={ Code=errors.AlreadyCommitted, Message={ ver=1, val=2 } }}},
},
},
{
mes = 'one seen with other error',
rst = { ver=1, val=2 },
resps = {
a={ p3=none},
b={ p3={err={ Code=errors.StorageError }}},
c={ p3={err={ Code=errors.AlreadyCommitted, Message={ ver=1, val=2 } }}},
},
},
{
mes = 'committed',
rst = { ver=5, val="committed-5" },
resps = {
a={ p3=none },
b={
p3={
err={
Code=errors.AlreadyCommitted,
Message={ ver=5, val="committed-5" },
},
},
},
c={
p3={
err={
Code=errors.AlreadyCommitted,
Message={ ver=4, val="committed-4" },
},
},
},
},
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local x, err = paxos.proposer.new( args, impl )
t:eq( nil, err, mes )
local c, err
if case.need_quorum then
c, err = x:quorum_read()
else
c, err = x:remote_read()
end
if case.err then
t:eq( nil, c, mes )
t:eqdict( case.err, err, mes )
else
t:eqdict( case.rst, c, mes )
t:eq( nil, err, mes )
end
end
end
local acc_view = { ver=1, val={ { a=1 } } }
local acc_store = {
kempty = {},
kp1 = {
committed = {
ver=2,
val= {
view={ {a=1} },
}
},
paxos_round = { rnd={ 2, 'b' }, vrnd=round.zero() },
},
kp2 = {
committed = {
ver=2,
val= {
view={ {a=1} },
}
},
paxos_round = { rnd={ 2, 'b' }, vrnd={ 2, 'b' }, val='val-b' },
},
kcmt = {
committed = {
ver=2,
val= {
view={ {a=1} },
val = 'val-3'
}
},
},
kcmtp1 = {
committed = {
ver=2,
val= {
view={ {a=1} },
val = 'val-c'
}
},
paxos_round={ rnd={ 3, 'c' }, vrnd=round.zero() }
},
}
local acc_reflect = {r=nil}
local function default_acc(t, sto)
local acc_args = {
cluster_id='cl',
ident='a',
}
local lock_ph = {}
local acc_impl = {
store=function( self, p )
t:eq( acc_args.cluster_id, p.cluster_id )
t:eq( acc_args.ident, p.ident )
acc_reflect.r = p.record
end,
load=function( self, p )
t:eq( acc_args.cluster_id, p.cluster_id )
t:eq( acc_args.ident, p.ident )
return tableutil.dup( sto or {}, true )
end,
time= function( self ) return os.time() end,
lock=function(self, p)
t:eq( acc_args.cluster_id, p.cluster_id )
t:eq( acc_args.ident, p.ident )
return lock_ph
end,
unlock=function(self, l)
t:eq( lock_ph, l, "lock object is sent back to unlock" )
end,
}
local acc, err = paxos.acceptor.new( acc_args, acc_impl )
t:eq( nil, err )
return acc
end
function test_new_acc(t)
local view = { { a=1, b=1 }, { b=1, c=1 } }
local args = {
cluster_id = 'cl',
ident = 'a',
}
local impl = {
store=function( self, pp ) end,
load=function( self, pp )
return {
committed={ ver=1, val={
foo={ __expire=os.time()-1 },
view=tableutil.dup(view, true)
} }
}
end,
time= function( self ) return os.time() end,
lock=function(self, key) return nil end,
unlock=function(self, key) end,
}
t:err( function() paxos.acceptor.new( nil ) end, 'nil' )
local x, err = paxos.acceptor.new( args, impl )
t:eq( nil, err )
t:contain( args, x )
x:load_rec()
t:eq( -1, x.record.committed.val.foo.__lease )
end
function test_new_acc_with_ver(t)
local view = { { a=1, b=1 }, { b=1, c=1 }, foo={ __expire=os.time()-1 } }
local args = {
cluster_id = 'cl',
ident = 'a',
ver = 2,
}
local impl = {
store=function( self, pp ) end,
load=function( self, pp )
return {
committed={ ver=1, val={view=tableutil.dup(view, true)} }
}
end,
time= function( self ) return os.time() end,
lock=function(self, key) return nil end,
unlock=function(self, key) end,
}
local x, err = paxos.acceptor.new( args, impl )
t:eq( nil, err )
t:eq( args.ver, x.ver )
local _, err, errmes = x:load_rec()
t:eq(nil, err)
local _, err, errmes = x:init_view()
t:eq( errors.VerNotExist, err )
end
function test_new_acc_args(t)
local view = { { a=1, b=1 }, { b=1, c=1 } }
local args = {
cluster_id = 'cl',
ident = 'a',
}
local impl = {
store=nil,
load=function( key )
return {
committed={ ver=1, val=view, }
}
end,
time= function( self ) return os.time() end,
lock=function(self, key) return nil end,
unlock=function(self, key) end,
}
for _, key in ipairs({ 'cluster_id', 'ident', 'load', 'lock', 'store' }) do
local a = tableutil.dup( args )
local e = tableutil.dup( impl )
a[ key ] = nil
e[ key ] = nil
local x, err = paxos.acceptor.new( a, e )
t:eq( nil, x, 'without ' .. key )
t:neq( nil, err, 'without ' .. key )
t:eq( errors.InvalidArgument, err, 'without ' .. key )
end
end
function test_acc_view_err(t)
local sto = {}
local args = {
cluster_id='cl',
ident='a',
}
local impl = {
store=function( key ) end,
load=function( key ) return sto end,
time= function( self ) return os.time() end,
lock=function(self, key) return nil end,
unlock=function(self, key) end,
}
local cases = {
{ committed=nil, err=errors.NoView },
{ committed={ ver=2, val=nil }, err=errors.NoView },
{ committed={ ver=2, val={} }, err=errors.NoView },
{ committed={ ver=2, val={view={{}}} }, err=errors.AlreadyCommitted },
}
for i, case in ipairs( cases ) do
sto.committed = case.committed
local x, err = paxos.acceptor.new( args, impl )
for _, cmd in ipairs({ 'phase1', 'phase2' }) do
local req = {
cmd = cmd,
cluster_id = "cl",
ver = 2,
}
local r, err, errmes = x:process( req )
local mes = i .. ': req=' .. tableutil.repr( req ) .. '\n resp=' .. tableutil.repr( r )
t:eq( case.err, err, mes )
end
end
end
function test_acc_process(t)
local x = default_acc(t)
local r, err, errmes = x:process( nil )
t:eq( errors.InvalidMessage, err )
r, err, errmes = x:process( {} )
t:eq( errors.InvalidMessage, err )
r, err, errmes = x:process( {cluster_id=1, ident=1, cmd=1} )
t:eq( errors.InvalidCommand, err )
end
function test_acc_not_my_mes(t)
local x = default_acc(t)
local mes = {
rnd={ 1, 'a' },
cluster_id = 'cl',
}
local cases = {
{ rst={ nil, errors.InvalidCluster, 'cl' }, mes={cluster_id='x'}, },
}
for i, case in ipairs(cases) do
local mes = tableutil.dup( mes )
tableutil.merge( mes, case.mes )
for _, phase in ipairs({ 'phase1', 'phase2', 'phase3' }) do
mes.cmd = phase
local r, err, errmes = x:process( mes )
local m = i .. ' req=' .. tableutil.repr( mes ) .. ' resp=' .. tableutil.repr( {r, err, errmes} )
t:eqdict( case.rst, {r, err, errmes}, m )
end
end
end
function test_acc_lock(t)
local acc_args = {
cluster_id='cl',
ident='a',
}
local impl = {
store=function( self )
acc_reflect.r = self.record
end,
load=function( self )
return tableutil.dup( sto or {}, true )
end,
time= function( self ) return os.time() end,
lock=function(self, key) return nil, "lockerr" end,
unlock=function(self, key) end,
logerr=function() end,
}
local reqbase = {
cmd = 'phase1',
cluster_id = 'cl',
ver = 1,
}
local acc, err = paxos.acceptor.new( acc_args, impl )
t:eq( nil, err )
local req = { rnd={0, 'x'}, ver=0 }
tableutil.merge( req, reqbase )
acc_reflect = {}
local r, err, errmes = acc:process(req)
t:eq(nil, r)
t:eqdict(errors.LockTimeout, err)
end
function test_acc_phase1(t)
local committed = { val=nil, ver=0 }
local req = {
cmd = 'phase1',
cluster_id = 'cl',
ver = 1,
}
local cases = {
{
sto = acc_store.kempty,
req = { rnd={ 0, 'x' }, ver=0, },
rst = { nil, errors.NoView },
stored = nil
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=0, },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=1, },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=2, },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=3, },
rst = { {rnd={ 2, 'b' }}, },
stored = nil,
},
{
sto = acc_store.kp1,
req = { rnd={ 3, 'x' }, ver=3 },
rst = { {rnd={ 3, 'x' }} },
stored = {
committed = acc_store.kp1.committed,
paxos_round = { rnd={ 3, 'x' }, vrnd=round.zero() },
},
},
{
sto = acc_store.kp2,
req = { rnd={ 1, 'a' }, ver=3 },
rst = { {rnd={ 2, 'b' }, vrnd={ 2, 'b' }, val='val-b'} },
stored = nil,
},
{
sto = acc_store.kp2,
req = { rnd={ 3, 'a' }, ver=3 },
rst = { {rnd={ 3, 'a' }, vrnd={ 2, 'b' }, val='val-b'} },
stored = {
committed = acc_store.kp2.committed,
paxos_round = { rnd={ 3, 'a' }, vrnd={ 2, 'b' }, val='val-b' },
},
},
{
sto = acc_store.kcmt,
req = { rnd={ 1, 'a' }, ver=1 },
rst = { nil, errors.AlreadyCommitted, acc_store.kcmt.committed },
stored = nil,
},
{
sto = acc_store.kcmt,
req = { rnd={ 1, 'a' }, ver=2, },
rst = { nil, errors.AlreadyCommitted, acc_store.kcmt.committed },
stored = nil,
},
{
sto = acc_store.kcmt,
req = { rnd={ 1, 'a' }, ver=3, },
rst = { {rnd={ 1, 'a' }} },
stored = {
committed = acc_store.kcmt.committed,
paxos_round = { rnd={ 1, 'a' }, vrnd=round.zero() },
},
},
}
for i, case in ipairs(cases) do
local x = default_acc( t, case.sto )
local req = tableutil.dup( req )
tableutil.merge( req, case.req )
acc_reflect = {}
local r, err, errmes = x:process( req )
local mes = i..": " .. tableutil.repr( { rnd=req.rnd, resp=r, stored=acc_reflect.r } )
t:eqdict( case.rst, {r, err, errmes}, mes )
t:eqdict( case.stored, acc_reflect.r, mes )
end
end
function test_acc_phase2(t)
local req = {
cmd = 'phase2',
cluster_id = 'cl',
ver = 1,
val = 'myval',
}
local committed = { val=nil, ver=0 }
local pr = {
rnd = round.zero(),
val = nil,
vrnd = round.zero(),
}
local cases = {
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=0 },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil,
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=1 },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil,
},
{
sto = acc_store.kp1,
req = { rnd={ 0, 'x' }, ver=2 },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil,
},
{
sto = acc_store.kp1,
req = { rnd={ 1, 'a' }, ver=3 },
rst = { nil, errors.OldRound },
stored = nil,
},
{
sto = acc_store.kp1,
req = { rnd={ 2, 'b' }, ver=3, },
rst = {nil, nil, nil},
stored = {
committed = acc_store.kp1.committed,
paxos_round = {
rnd = { 2, 'b' },
vrnd = { 2, 'b' },
val = 'myval',
}
}
},
{
mes = "__lease not affected in phase2",
sto = acc_store.kp1,
req = { rnd={ 2, 'b' }, ver=3, val={ foo={ __lease=10, } } },
rst = {nil, nil, nil},
stored = {
committed = acc_store.kp1.committed,
paxos_round = {
rnd = { 2, 'b' },
vrnd = { 2, 'b' },
val = { foo={ __lease=10 } },
}
}
},
{
sto = acc_store.kcmt,
req = { rnd={ 1, 'a' }, ver=2, },
rst = { nil, errors.AlreadyCommitted, acc_store.kcmt.committed },
stored = nil,
},
{
sto = acc_store.kcmt,
req = { rnd={ 1, 'a' }, ver=3, },
rst = { nil, errors.OldRound },
stored = nil,
},
}
for i, case in ipairs(cases) do
local x = default_acc( t, case.sto )
local req = tableutil.dup( req )
tableutil.merge( req, case.req )
acc_reflect = {}
local r, err, errmes = x:process( req )
local mes = i..": " .. tableutil.repr( { rnd=req.rnd, resp=r, stored=acc_reflect.r } )
t:eqdict( case.rst, {r, err, errmes}, mes )
t:eqdict( case.stored, acc_reflect.r, mes )
end
end
function test_acc_phase3(t)
local req = {
cmd = 'phase3',
cluster_id = 'cl',
ver = 1,
val = 'myval',
}
local committed = { val=nil, ver=0 }
local empty_pr = {
rnd = round.zero(),
val = nil,
vrnd = round.zero(),
}
local cases = {
{
mes = "ver=0 is not allowed to commit",
sto = acc_store.kempty,
req = { ver=0, },
rst = { nil, errors.AlreadyCommitted, { ver=0 } },
stored = nil,
},
{
mes = "empty storage is allowed to commit",
sto = acc_store.kempty,
req = { ver=1, },
rst = {},
stored = {
committed = { ver=1, val='myval' },
paxos_round = empty_pr,
}
},
{
mes = "empty storage is allowed to commit ver=2",
sto = acc_store.kempty,
req = { ver=2, },
rst = {},
stored = {
committed = { ver=2, val='myval' },
paxos_round = empty_pr,
}
},
{
mes = 'commmit ver=0 to existent ver=2',
sto = acc_store.kp1,
req = { ver=0, },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil,
},
{
mes = 'commmit ver=1 to existent ver=2',
sto = acc_store.kp1,
req = { ver=1, },
rst = { nil, errors.AlreadyCommitted, acc_store.kp1.committed },
stored = nil,
},
{
mes = 'commmit ver=2 to existent ver=2, paxos_round will not be clear',
sto = acc_store.kp1,
req = { ver=2, },
rst = {},
stored = {
committed = { ver=2, val='myval' },
paxos_round = { rnd={ 2, 'b' }, vrnd=round.zero() },
}
},
{
mes = 'commmit ver=3 to existent ver=2, paxos_round will be cleared',
sto = acc_store.kp1,
req = { ver=3, },
rst = {},
stored = {
committed = { ver=3, val='myval' },
paxos_round = empty_pr,
}
},
{
mes = '__lease should be converted to __expire',
sto = acc_store.kp1,
req = { ver=3, val={ foo={ __lease=10 } } },
rst = {},
stored = {
committed = { ver=3, val={ foo={ __expire=os.time()+10 } } },
paxos_round = empty_pr,
}
},
{
mes = 'commmit ver=100 to existent ver=2, paxos_round will be cleared',
sto = acc_store.kp1,
req = { ver=100, },
rst = {},
stored = {
committed = { ver=100, val='myval' },
paxos_round = empty_pr,
}
},
{
mes = 'commmit ver=2 to existent ver=2, with accepted val',
sto = acc_store.kp2,
req = { ver=2, },
rst = {},
stored = {
committed = { ver=2, val='myval' },
paxos_round = acc_store.kp2.paxos_round,
}
},
}
for i, case in ipairs(cases) do
local x = default_acc( t, case.sto )
local req = tableutil.dup( req )
tableutil.merge( req, case.req )
acc_reflect = {}
local r, err, errmes = x:process( req )
local mes = i..': '..(case.mes or '') .. ' req=' .. tableutil.repr( req ) .. ' resp='..tableutil.repr( r )
t:eqdict( case.rst, {r, err, errmes}, mes )
t:eqdict( case.stored, acc_reflect.r, mes )
end
end
|
data:extend(
{
{
type = "recipe-category",
name = "droids"
},
{
type = "item-group",
name = "droids",
order = "dr",
inventory_order = "dr",
icon_size = 32,
icon = "__base__/graphics/item-group/military.png"
},
{
type = "item",
name = "droid-smg",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_smg_undep.png",
flags = {},
order = "z[droid]",
subgroup = "capsule",
place_result = "droid-smg",
stack_size = 25
},
{
type = "item",
name = "droid-smg-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_smg.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "droid-flame",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_flame_undep.png",
flags = {},
order = "z[droid]",
subgroup = "capsule",
place_result = "droid-flame",
stack_size = 25
},
{
type = "item",
name = "droid-flame-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_flame.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "droid-rifle",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_rifle_undep.png",
flags = {},
order = "z[droid]",
subgroup = "capsule",
place_result = "droid-rifle",
stack_size = 25
},
{
type = "item",
name = "droid-rifle-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_rifle.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "droid-rocket",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_rocket_undep.png",
flags = {},
order = "z[droid]",
subgroup = "capsule",
place_result = "droid-rocket",
stack_size = 25
},
{
type = "item",
name = "droid-rocket-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid_rocket.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "terminator",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/terminator_undep.png",
flags = {},
order = "z[droid]",
subgroup = "capsule",
place_result = "terminator",
stack_size = 25
},
{
type = "item",
name = "terminator-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/terminator.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "defender-unit",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/defender_unit_undep.png",
flags = {},
order = "x[combatrobot]",
subgroup = "capsule",
place_result = "defender-unit",
stack_size = 25
},
{
type = "item",
name = "defender-unit-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/defender.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "distractor-unit",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/distractor_unit_undep.png",
flags = {},
order = "y[combatrobot]",
subgroup = "capsule",
place_result = "distractor-unit",
stack_size = 25
},
{
type = "item",
name = "distractor-unit-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/distractor.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "destroyer-unit",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/destroyer_unit_undep.png",
flags = {},
order = "z[combatrobot]",
subgroup = "capsule",
place_result = "destroyer-unit",
stack_size = 25
},
{
type = "item",
name = "destroyer-unit-dummy",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/destroyer.png",
flags = {"hidden"},
order = "z-z",
subgroup = "capsule",
place_result = "",
stack_size = 1
},
{
type = "item",
name = "droid-assembling-machine",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid-assembling-machine.png",
flags = {},
subgroup = "production-machine",
order = "b[droid-assembling-machine]",
place_result = "droid-assembling-machine",
stack_size = 50
},
{
type = "item",
name = "droid-guard-station",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid-guard-station.png",
flags = {},
subgroup = "production-machine",
order = "b[droid-guard-station]",
place_result = "droid-guard-station",
stack_size = 50
},
{
type = "item",
name = "droid-counter",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid-counter.png",
flags = {},
subgroup = "circuit-network",
place_result="droid-counter",
order = "b[combinators]-e[droid-counter]",
stack_size = 50,
},
{
type = "item",
name = "droid-settings",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/droid-settings.png",
flags = {},
subgroup = "circuit-network",
place_result="droid-settings",
order = "b[combinators]-e[droid-settings]",
stack_size = 50,
},
{
type = "item",
name = "loot-chest",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/loot-chest.png",
flags = {},
subgroup = "storage",
place_result="loot-chest",
order = "a[items]-c[loot-chest]",
stack_size = 50,
},
{
type = "item",
name = "patrol-pole",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/patrol-pole.png",
flags = {},
subgroup = "capsule",
place_result="patrol-pole",
order = "a[items]-d[patrol-pole]",
stack_size = 50,
},
{
-- This allows loading the selection-tool type item when mods are removed
type = "selection-tool",
name = "droid-selection-tool",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/selection_tool.png",
flags = {},
subgroup = "tool",
order = "d[droid-control]-s[selection]",
stack_size = 1,
stackable = false,
selection_color = { r = 0, g = 1, b = 0 },
alt_selection_color = { r = 0, g = 1, b = 0 },
selection_mode = {"same-force"},
alt_selection_mode = {"same-force"},
selection_cursor_box_type = "not-allowed",
alt_selection_cursor_box_type = "not-allowed"
},
{
-- This allows loading the selection-tool type item when mods are removed
type = "selection-tool",
name = "droid-pickup-tool",
icon_size = 32,
icon = "__robotarmy__/graphics/icons/pickup_tool.png",
flags = {},
subgroup = "tool",
order = "d[droid-control]-p[pickup]",
stack_size = 1,
stackable = false,
selection_color = { r = 1, g = 0, b = 0 },
alt_selection_color = { r = 1, g = 0, b = 0 },
selection_mode = {"blueprint"},
alt_selection_mode = {"blueprint"},
selection_cursor_box_type = "not-allowed",
alt_selection_cursor_box_type = "not-allowed"
},
})
|
love.filesystem.load("core.lua")()
love.filesystem.load("escena.lua")()
io.stdout:setvbuf("no")
local major, minor, revision, codename = love.getVersion( )
local LEFT_M_BUTTON = 'l'
if major >= 0 then
if minor > 9 then
LEFT_M_BUTTON = 1
end
end
SIZE_WIN_W = 512*2
SIZE_WIN_H = 384*2
function love.resize(w, h)
print(("Window resized to width: %d and height: %d."):format(w, h))
SIZE_WIN_H = h
SIZE_WIN_W = w
end
love.window.setTitle("John Huesos")
love.window.setMode(512*2,384*2,{resizable=true})
love.graphics.setDefaultFilter( 'nearest', 'nearest', 1 )
support = love.graphics.getSupported()
print(support.glsl3)
GAME_OVER_SONG = nil
LEVEL_COMPLETE_SONG = nil
LEVEL_BG_SONG = nil
LEVEL_BOSS_SONG = nil
TEXT_SOUND = nil
FONT_BOLD = nil
FONT = nil
FONT_SMALL = nil
INITIAL_SCORE = 0
SCORE = 0
LANG = 'EN'
USE_SHADERS = true
FULL_SCREEN = false
FPS = 60
EXIST_USER_SETTINGS = false
MIN_DT = 1/FPS
NEXT_TIME = 0
function writeUserSettings()
local dir = love.filesystem.getSaveDirectory( )
local data = '\r\n'
data = data..'LANG = "'..tostring(LANG)..'"\r\n'
data = data..'USE_SHADERS = '..tostring(USE_SHADERS)..'\r\n'
data = data..'FULL_SCREEN = '..tostring(FULL_SCREEN)..'\r\n'
success, message = love.filesystem.write("user_settings.lua",data, size )
end
CANVAS = nil
SHADER = nil
ESCENA_MANAGER = EscenaManager()
DRAW_TIMER = nil
--local init_scene = love.filesystem.load("Overworld.lua")()
--local init_scene = love.filesystem.load("cortinilla.lua")()
--ESCENA_MANAGER.push(init_scene)
function LevelData(map_file_name,backgrond_ima,normal_music,boss_music)
local self = {}
self.map_file_name =map_file_name
self.background_file_ima = backgrond_ima
self.normal_music = normal_music
self.boss_music = boss_music
return self
end
--LEVEL_1_DATA = LevelData()
CURRENT_LEVEL = 1
LEVEL_LIST = {
{'rsc/maps/level1.spk',
levelname = {
ES = '-Invasión de Calacatecuaro-',
EN = '-Invasion of Calacatecuaro-',
},
bossname = {
ES = 'U N I P O D E\nLos trípodes salian muy caros',
EN = 'U N I P O D\nThe tripods were very expensive',
},
},
{'rsc/maps/level2.spk',
levelname = {
ES = '-Luces sobre el cerro pelado-',
EN = '-Lights over the bald hill-',
},
bossname = {
ES = 'L. O. V. N. I.\nLetal Objeto Volador No Identificado',
EN = 'D. U. F. O.\nDeathly Unidentified Flying Object',
},
},
{'rsc/maps/level3.spk',
levelname = {
ES = '-Batalla al filo del amanecer-',
EN = '-Battle on the edge of the sunrise-',
},
bossname = {
ES = 'F E M U R T\nLider en jefe de la invasión',
EN = 'F E M U R T\nLeader in chief of the invasion',
},
},
}
function love.load()
TEXT_SOUND = love.audio.newSource("rsc/sounds/text.wav", "static")
FONT_BOLD = love.graphics.newFont('rsc/fonts/Fredoka_One/FredokaOne-Regular.ttf',35)
FONT = love.graphics.newFont('rsc/fonts/Lato/Lato-Bold.ttf',32)
FONT_SMALL = love.graphics.newFont('rsc/fonts/Lato/Lato-Bold.ttf',22)
DRAW_TIMER = Cronometro()
DRAW_TIMER.iniciar()
GAME_OVER_SONG = love.audio.newSource("rsc/music/Slaughter Vals.mp3",'stream')
LEVEL_COMPLETE_SONG = love.audio.newSource("rsc/music/2sp00ky4me.mp3",'stream')
LEVEL_BG_SONG = love.audio.newSource("rsc/music/glist_by_neurosys.xm",'stream')
LEVEL_BOSS_SONG = love.audio.newSource("rsc/music/Chicharron Zombie! - Crab sound.mp3",'stream')
local dir = love.filesystem.getSaveDirectory( ).."/"
local info = love.filesystem.getInfo("user_settings.lua")
EXIST_USER_SETTINGS = true
if not info then
EXIST_USER_SETTINGS = false
else
-- prints 'result: 2'
love.filesystem.load('user_settings.lua')()
--love.window.setFullscreen( FULL_SCREEN )
end
-- [[DEFAULT
local init_scene = love.filesystem.load("cortinilla.lua")()
ESCENA_MANAGER.push(init_scene)
--]]
--[[
local init_scene = love.filesystem.load("creditos.lua")()
ESCENA_MANAGER.push(init_scene)
--]]
--[[
local init_scene = love.filesystem.load("level.lua")()
ESCENA_MANAGER.push(init_scene,
{'rsc/maps/test.spk',
levelname = {
ES = '-El mapa de testeo-',
EN = '-The testing map-',
},
bossname = {
ES = 'Quien sabe\nestamos en pruebas',
EN = 'Who cares\nwe are on tests',
},
use_collision_layer = false
}
)
--]]
SHADER = love.graphics.newShader[[
extern vec2 distortionFactor;
extern vec2 scaleFactor;
extern number feather;
extern number time;
vec4 effect(vec4 color, Image tex, vec2 uv, vec2 px) {
// to barrel coordinates
uv = uv * 2.0 - vec2(1.0);
// distort
uv *= scaleFactor;
uv += (uv.yx*uv.yx) * uv * (distortionFactor - 1.0);
number mask = (1.0 - smoothstep(1.0-feather,1.0,abs(uv.x)))
* (1.0 - smoothstep(1.0-feather,1.0,abs(uv.y)));
// to cartesian coordinates
uv = (uv + vec2(1.0)) / 2.0;
// per row offset
float f = sin( uv.y * 320.f * 3.14f );
// scale to per pixel
float o = f * (0.35f / 320.f);
// scale for subtle effect
float s = f * .03f + 0.97f;
// scan line fading
float l = sin( time * 32.f )*.03f + 0.97f;
// sample in 3 colour offset
float r = Texel( tex, vec2( uv.x+o, uv.y+o ) ).x;
float g = Texel( tex, vec2( uv.x-o, uv.y+o ) ).y;
float b = Texel( tex, vec2( uv.x , uv.y-o ) ).z;
// combine as
return vec4( r*0.9f, g*0.9f, b*0.9f, l ) * s * mask;
}
]]
CANVAS = love.graphics.newCanvas(512*2,384*2)
NEXT_TIME = love.timer.getTime()
end
function love.keyreleased( key, scancode )
ESCENA_MANAGER.keyreleased(key,scancode)
end
function love.keypressed(key,scancode)
if key == "escape" then
love.event.quit()
end
ESCENA_MANAGER.keypressed(key,scancode)
end
function love.mousemoved(x, y, dx, dy, istouch)
ESCENA_MANAGER.mousemoved(x, y)
end
function love.update(dt)
--evitar que las cosas se caigan si se mueve la pantalla
dt = math.min(dt,1/30)
local accum = dt
while accum > 0 do -- accumulator for physics! no more penetration!
local dt = math.min( 1/200, accum ) -- use whatever max dt value works best for you
accum = accum - dt
ESCENA_MANAGER.update(dt)
-- now, do whatever it is you need to do with dt
end
--controlar los fps
--mando a recoger la basura manualmente...
collectgarbage()
SHADER:send("time",dt)
--if love.timer then love.timer.sleep(1.0/30.0) end
end
function love.draw()
if DRAW_TIMER.hanPasado(1/60) then
love.graphics.setCanvas(CANVAS)
ESCENA_MANAGER.draw()
love.graphics.setCanvas()
end
love.graphics.setBackgroundColor(0,0,0)
if USE_SHADERS then
local distortionFactor = {1.06, 1.065}
local feather = 0.02
local scaleFactor = {1,1}
-- [[
SHADER:send("distortionFactor",distortionFactor)
SHADER:send("feather",feather)
SHADER:send("scaleFactor",scaleFactor)
love.graphics.setBackgroundColor(0.46,0.24,0.10)
if ESCENA_MANAGER.getUseShaders() then
love.graphics.setShader(SHADER)
end
end
love.graphics.setColor(1,1,1)
local factor = SIZE_WIN_H/(384*2)
local x = (SIZE_WIN_W/2)-(512*factor)
local y = (SIZE_WIN_H/2) -(384*factor)
love.graphics.draw(CANVAS,x,y,0,factor,factor)
love.graphics.setShader()
--love.graphics.print(tostring(factor),0,0)
end
|
minetest.register_chatcommand("bx_save", {
params = "<name>",
description = "Uploads the selected region to the blockexchange server",
func = blockexchange.api_check_wrapper(function(name, schemaname)
local has_protected_upload_priv = minetest.check_player_privs(name, { blockexchange_protected_upload = true })
local has_blockexchange_priv = minetest.check_player_privs(name, { blockexchange = true })
local has_protection_bypass_priv = minetest.check_player_privs(name, { protection_bypass = true })
if not has_blockexchange_priv and not has_protected_upload_priv then
return true, "Required privs: 'blockexchange' or 'blockexchange_protected_upload'"
end
if not schemaname then
return true, "Usage: /bx_save <schemaname>"
end
local token = blockexchange.get_token(name)
if not token then
-- TODO check validity
return true, "Please login first to upload a schematic"
end
local pos1 = blockexchange.get_pos(1, name)
local pos2 = blockexchange.get_pos(2, name)
if not pos1 or not pos2 then
return true, "you need to set /bx_pos1 and /bx_pos2 first!"
end
if not has_blockexchange_priv and has_protected_upload_priv and not has_protection_bypass_priv then
-- kick off protection-check worker and add deferred upload context
blockexchange.protectioncheck(name, pos1, pos2, schemaname)
else
-- kick off upload without protect check
blockexchange.save(name, pos1, pos2, schemaname)
end
return true
end)
})
|
--[[---------------------------------------------------------
PlayerColor Material Proxy
Sets the clothing colour of custom made models to
ent.GetPlayerColor, a normalized vector colour.
-----------------------------------------------------------]]
local clrFallback = Vector( 62 / 255, 88 / 255, 106 / 255 )
matproxy.Add( {
name = "PlayerColor",
init = function( self, mat, values )
-- Store the name of the variable we want to set
self.ResultTo = values.resultvar
end,
bind = function( self, mat, ent )
if ( !IsValid( ent ) ) then return end
-- If entity is a ragdoll try to convert it into the player
-- ( this applies to their corpses )
if ( ent:IsRagdoll() ) then
local owner = ent:GetRagdollOwner()
if ( IsValid( owner ) ) then ent = owner end
end
-- If the target ent has a function called GetPlayerColor then use that
-- The function SHOULD return a Vector with the chosen player's colour.
if ( ent.GetPlayerColor ) then
local col = ent:GetPlayerColor()
if ( isvector( col ) ) then
mat:SetVector( self.ResultTo, col )
end
else
mat:SetVector( self.ResultTo, clrFallback )
end
end
} )
|
local offset = math.random()*math.pi
local startpos = script.parent.parent:GetPosition()
function Tick(deltaTime)
script.parent.parent:SetPosition(startpos + Vector3.New(0,20*math.sin(2+offset+4*time()),0))
script.parent:SetRotation(Rotation.New(0,0,-11+20*math.sin(offset+4*time())))
end
|
local tedaviyeri = createColSphere ( 1590.9909667969, 1796.5489501953, 2083.376953125, 3)
setElementInterior(tedaviyeri, 10)
setElementDimension(tedaviyeri, 180)
local pickup = createPickup(1590.9909667969, 1796.5489501953, 2083.376953125, 3, 1239)
setElementData(pickup, "informationicon:information", "#CC3333/tedaviol\n#CC3333/doktorcagir#ffffff\nMedical Department")
setElementInterior(pickup, 10)
setElementDimension(pickup, 180)
function tedavi(thePlayer, cmd)
local viprank2 = getElementData(thePlayer, "vip")==2
local viprank3 = getElementData(thePlayer, "vip")==3
if not exports.mrp_global:takeMoney(thePlayer, 200) and not (viprank2) and not (viprank3) then
outputChatBox("Sunucu: #ffffffTedavi olmak için ₺200 ödemeniz gerekli.", thePlayer, 255,0,0,true)
return
end
if not isElementWithinColShape(thePlayer, tedaviyeri) then
return
end
local health = 100
setElementHealth(thePlayer , tonumber(health))
outputChatBox("Sunucu: #ffffff₺200 karşılığında tedavi oldunuz.", thePlayer, 255,0,0,true)
end
addCommandHandler("tedaviol", tedavi)
local destekalani = createColSphere ( 1590.9909667969, 1796.5489501953, 2083.376953125, 3, 1779)
setElementDimension(destekalani , 180 )
setElementInterior(destekalani , 10 )
local oyuncu = {}
function poliscagir(thePlayer, commandName, ...)
local serial = getPlayerSerial(thePlayer)
if oyuncu[serial] and oyuncu[serial] + 60*60*1000 > getTickCount() then
outputChatBox("[!]#fdfdfd Bir daha doktor çağırabilmek için "..(math.ceil(2 - (getTickCount() - oyuncu[serial])/(60*1000))).." dakika beklemelisiniz.", thePlayer, 194, 0, 0, true)
return
end
if (isElementWithinColShape(thePlayer, destekalani)) then
local logged = getElementData(thePlayer, "loggedin")
outputChatBox("[!]#fdfdfd Doktor çağırma talebiniz departmana iletilmiştir, lütfen beklemede kalın.",thePlayer, 12, 243, 0, true)
for k, v in ipairs(getPlayersInTeam(getTeamFromName ("İstanbul Devlet Hastanesi"))) do
outputChatBox("[LSMD]#ffffff Bir vatandaş sizi departman'da bekliyor.", v, 50, 125, 200, true)
oyuncu[serial] = getTickCount()
end
end
end
addCommandHandler("doktorcagir", poliscagir, false, false)
|
Automation = {
required = {},
states = {},
}
function Automation:AddState(key, className, data)
-- Dynamic module Load
if Automation.required[className] == nil then
Automation.required[className] = true
require(className)
end
Automation.states[key] = _G[className]
Automation.states[key]:Init(data)
end
function Automation:AddNode(key, params)
Automation.states[key]:AddNode(params)
end
function Automation:Log()
for _, state in pairs(Automation.states) do state:Log() end
end
function Automation:Update(params)
for _, state in pairs(Automation.states) do state:Update(params) end
end
-- Test Module
Automation:AddState("test", "RepeatedStates")
Automation:Log()
function TestCallback(id) print("HERE - " .. id) end
Automation:AddNode("test", { condition = "a + 5 > 10", callback = TestCallback, id = 58})
for i = 1, 10 do Automation:Update({ a = i }) end
Automation:Log()
|
local _G = require "_G"
local assert = _G.assert
local error = _G.error
local getmetatable = _G.getmetatable
local ipairs = _G.ipairs
local pcall = _G.pcall
local select = _G.select
local tonumber = _G.tonumber
local tostring = _G.tostring
local type = _G.type
local coroutine = require "coroutine"
local newcoro = coroutine.create
local resume = coroutine.resume
local running = coroutine.running
local status = coroutine.status
local yield = coroutine.yield
local math = require "math"
local max = math.max
local min = math.min
local string = require "string"
local strfind = string.find
local strmatch = string.match
local strsub = string.sub
local debug = require "debug"
local setmetatable = debug.setmetatable
local memory = require "memory"
local memalloc = memory.create
local memfill = memory.fill
local memfind = memory.find
local memget = memory.get
local memrealloc = memory.resize
local mem2str = memory.tostring
local system = require "coutil.system"
local now = system.time
local sleep = system.suspend
local newaddr = system.address
local newsocket = system.socket
local nameaddr = system.nameaddr
local resolveaddr = system.findaddr
local procinfo = system.procinfo
local defaultsize = 8192
local function checkclass(self, expected)
if self.class ~= expected then
local actual = self.class or type(self)
error("bad argument #1 ("..expected.." expected, but got "..actual..")")
end
end
local addrset = getmetatable(newaddr("ipv4")).__newindex
local function toaddr(addr, host, port)
if not pcall(addrset, addr, "literal", host) then
local found<close>, errmsg = resolveaddr(host, port, "4")
if not found then return nil, errmsg end
found:getaddress(addr)
else
addr.port = port
end
return addr
end
local function wrapsock(class, metatable, domain, result, errmsg)
if not result then return nil, errmsg end
return setmetatable({
socket = result,
address = newaddr(domain),
buffer = memalloc(defaultsize),
readtimer = {},
writetimer = {},
class = class,
}, metatable)
end
local function timerbody(self)
while true do
while self.thread do
if sleep(self.timeout) then
assert(resume(self.thread, nil, timerbody))
end
end
self = yield()
end
end
local function starttimer(self, options)
local activemode = self.active
if not activemode then
activemode = options.mode or "none"
if activemode ~= "none" then
self.thread = running()
if status(self.timer) == "suspended" then
assert(resume(self.timer, self))
end
end
self.active = activemode
elseif activemode == "block" then
assert(resume(self.timer, false, "reset"))
end
end
local function canceltimer(self, ...)
local activemode = self.active or "none"
self.active = false
if activemode ~= "none" then
self.thread = false
local result, errmsg = ...
if not result and errmsg == timerbody then
return nil, "timeout"
end
assert(resume(self.timer, false, "cancel"))
end
return ...
end
local function connectsock(self, host, port, class)
local socket = self.socket
if not socket then return nil, "closed" end
local addr, errmsg = toaddr(self.address, host, port)
if not addr then return nil, errmsg end
local timer = self.writetimer
if timer.active then return nil, "in use" end
starttimer(timer, self)
local ok, errmsg = canceltimer(timer, socket:connect(addr))
if not ok then return nil, errmsg end
self.class = class
return true
end
local tcp = {
class = "tcp{master}",
first = 1,
last = 0,
}
tcp.__index = tcp
do
local modes = {
b = "block",
t = "total",
r = "total",
}
local timers = { "readtimer", "writetimer" }
function tcp:settimeout(value, mode)
if value then
assert(type(value) == "number", "number expected")
if value < 0 then value = false end
end
if value then
self.mode = assert(modes[strsub(mode or "b", 1, 1)], "invalid mode")
for _, field in ipairs(timers) do
local optimer = self[field]
optimer.timeout = value
if not optimer.timer then
optimer.timer = newcoro(timerbody)
end
end
else
self.mode = false
end
end
end
do
local function rawtostring(value)
local mt = getmetatable(value)
local tostr = mt.__tostring
if tostr ~= nil then
mt.__tostring = nil
end
local str = tostring(value)
if tostr ~= nil then
mt.__tostring = tostr
end
return strmatch(str, "%w+: (0x%x+)$")
end
function tcp:__tostring()
return self.class..": "..rawtostring(self)
end
end
function tcp:accept()
checkclass(self, "tcp{server}")
local socket = self.socket
if not socket then return nil, "closed" end
local timer = self.readtimer
if timer.active then return nil, "in use" end
starttimer(timer, self)
return wrapsock("tcp{client}", tcp, self.address.type,
canceltimer(timer, socket:accept()))
end
function tcp:bind(host, port)
local res, errmsg = self.socket:bind(toaddr(self.address, host, port))
if not res then return nil, errmsg end
-- force actual binding
res, errmsg = self.socket:getaddress("self", self.address)
if not res then return nil, errmsg end
return 1
end
function tcp:close()
local socket = self.socket
if not socket then return nil, "closed" end
self.timeout = false
self.timer = false
self.socket = false
return socket:close()
end
function tcp:connect(host, port)
checkclass(self, "tcp{master}")
return connectsock(self, host, port, "tcp{client}")
end
function tcp:dirty()
return self.first <= self.last
end
function tcp:getfd()
local socket = self.socket
if not socket then return -1 end
return math.huge
end
do
local function getaddr(self, side)
local addr = self.address
local res, errmsg = self.socket:getaddress(side, addr)
if not res then return nil, errmsg end
return addr.literal, addr.port
end
function tcp:getpeername()
return getaddr(self, "peer")
end
function tcp:getsockname()
return getaddr(self, "self")
end
end
function tcp:getstats()
checkclass(self, "tcp{client}")
error("not supported")
end
do
local lstmt do
local lstsck = assert(newsocket("passive", "ipv4"))
lstmt = getmetatable(lstsck)
lstsck:close()
end
function tcp:listen(backlog)
checkclass(self, "tcp{master}")
local socket = self.socket
if not socket then return nil, "closed" end
local oldmt = getmetatable(socket)
setmetatable(socket, lstmt)
local result, errmsg = socket:listen(backlog or 32)
if not result then
setmetatable(socket, oldmt)
return nil, errmsg
end
self.class = "tcp{server}"
return true
end
end
do
local pat2term = { ["*l"] = "\n" }
local function initbuf(self, prefix, required)
local buffer = self.buffer
local first = self.first
local last = self.last
local datasz = 1+last-first
local pfxsz = #prefix
local pfxidx = first-pfxsz
local bufsz = #buffer
local newbuf
local reqsz = required and max(0, required-datasz) or 1
if pfxsz+datasz+reqsz <= bufsz then
newbuf = buffer
end
if newbuf == buffer and pfxidx > 0 and first+datasz+reqsz-1 <= bufsz then
if pfxsz > 0 then memfill(buffer, prefix, pfxidx, first-1) end
else
local dataidx = first
pfxidx, first, last = 1, pfxsz+1, pfxsz+datasz
if not newbuf then
bufsz = last+max(reqsz, bufsz)
newbuf = memalloc()
memrealloc(newbuf, bufsz)
end
if datasz > 0 then memfill(newbuf, buffer, first, last, dataidx) end
if pfxsz > 0 then memfill(newbuf, prefix, 1, pfxsz) end
end
return newbuf, pfxidx, first, last
end
local function incbuf(self, buffer)
local defbuf = self.buffer
local bufsz = #buffer
local newsz = bufsz+#defbuf
if buffer == defbuf then
buffer = memalloc()
memrealloc(buffer, newsz)
memfill(buffer, defbuf, 1, bufsz)
else
memrealloc(buffer, newsz)
end
return buffer
end
function tcp:receive(pattern, prefix)
checkclass(self, "tcp{client}")
local socket = self.socket
if not socket then return nil, "closed" end
local timer = self.readtimer
if timer.active then return nil, "in use" end
if not pattern then pattern = "*l" end
if not prefix then prefix = "" end
local result, errmsg, partial = 0 -- to signal success
local pattype = type(pattern)
local required = (pattype == "number") and pattern or false
local buffer, pfxidx, first, last = initbuf(self, prefix, required)
local reqidx
if pattype == "number" then
reqidx = pfxidx+pattern-1
while reqidx > last do
starttimer(timer, self)
result, errmsg = socket:receive(buffer, last+1, reqidx)
if not result then
reqidx = last
break
end
last = last+result
end
partial = mem2str(buffer, pfxidx, reqidx)
else
local term = pat2term[pattern]
assert(term or pattern == "*a", "invalid pattern")
while true do
reqidx = term and memfind(buffer, term, first, last)
if reqidx then
break
else
first = last+1
if first > #buffer then buffer = incbuf(self, buffer) end
starttimer(timer, self)
result, errmsg = socket:receive(buffer, first)
if not result then
reqidx = last
break
end
last = last+result
end
end
local endidx = reqidx
if result then
if term == "\n" and memget(buffer, reqidx-1) == 13 then
endidx = reqidx-2
elseif term then
endidx = reqidx-#term
end
end
partial = mem2str(buffer, pfxidx, endidx)
if pattern == "*a" and errmsg == "end of file" and #partial > 0 then
result = 0 -- to signal success
end
end
first = reqidx+1
result, errmsg = canceltimer(timer, result, errmsg)
if first > last then
self.first, self.last = nil, nil
elseif buffer == self.buffer then
self.first, self.last = first, last
else
local datasz = 1+last-first
memfill(self.buffer, buffer, 1, datasz, first)
self.first, self.last = 1, datasz
end
if not result then
if errmsg == "end of file" then
errmsg = "closed"
end
return nil, errmsg, partial
end
return partial
end
end
function tcp:send(data, first, last)
checkclass(self, "tcp{client}")
local socket = self.socket
if not socket then return nil, "closed" end
local timer = self.writetimer
if timer.active then return nil, "in use" end
if not first then first = 1 end
if not last then last = #data end
if first > last then
return 0, nil, nil
end
starttimer(timer, self)
local result, errmsg = canceltimer(timer, socket:send(data, first, last))
if not result then
if errmsg == "broken pipe" then errmsg = "closed" end
return nil, errmsg, 1+last-first
end
return result, nil, nil
end
function tcp:setfd(fd)
error("not supported")
end
do
local name2opt = {
keepalive = "keepalive",
["tcp-nodelay"] = "nodelay",
reuseaddr = true,
}
function tcp:setoption(name, value)
local option = name2opt[name]
assert(option, "unsupported option")
if option == true then return 1 end
return self.socket:setoption(option, value)
end
end
tcp.setpeername = tcp.connect
tcp.setsockname = tcp.bind
function tcp:setstats()
checkclass(self, "tcp{client}")
error("not supported")
end
function tcp:shutdown(mode)
checkclass(self, "tcp{client}")
return self.socket:shutdown(mode)
end
local udp = {
class = "udp{unconnected}",
last = 0,
close = tcp.close,
getfd = tcp.getfd,
getpeername = tcp.getpeername,
getsockname = tcp.getsockname,
setfd = tcp.setfd,
setoption = tcp.setoption,
setsockname = tcp.bind,
settimeout = tcp.settimeout,
}
udp.__index = udp
function udp:dirty()
return self.last > 0
end
do
local function recvdgram(self, size, ...)
local socket = self.socket
if not socket then return nil, "closed" end
local timer = self.readtimer
if timer.active then return nil, "in use" end
local result, errmsg = self.last
if result == 0 then
local buffer = self.buffer
repeat
starttimer(timer, self)
result, errmsg = socket:receive(buffer, 1, size, ...)
if not result then break end
until result == size or result > 0
result, errmsg = canceltimer(timer, result, errmsg)
if not result then return nil, errmsg end
else
self.last = 0
end
return mem2str(buffer, 1, result)
end
function udp:receive(size)
checkclass(self, "udp{connected}")
return recvdgram(self, size)
end
function udp:receivefrom(size)
checkclass(self, "udp{unconnected}")
local addr = self.address
local result, errmsg = recvdgram(self, size, nil, addr)
if not result then return nil, errmsg end
return result, addr.literal, addr.port
end
end
function udp:send(data)
checkclass(self, "udp{connected}")
return self.socket:send(data)
end
function udp:sendto(data, host, port)
checkclass(self, "udp{unconnected}")
return self.socket:send(data, 1, -1, toaddr(self.address, host, port))
end
function udp:setpeername(host, port)
return connectsock(self, host, port, host == "*" and "udp{unconnected}"
or "udp{connected}")
end
local dns = {} do
local function resolve(address)
local addr = newaddr("ipv4")
local result<const>, errmsg = {
name = nil,
alias = {},
ip = {},
}
-- pick a name
if pcall(addrset, addr, "literal", address) then
table.insert(result.ip, address)
address, errmsg = nameaddr(addr)
if not address then return nil, errmsg end
else
result.name = address
end
-- get canonical name
result.name, errmsg = nameaddr(address)
if not result.name then return nil, errmsg end
if result.name ~= address then
table.insert(result.alias, address)
end
-- get IP addresses
local found<close>, errmsg = resolveaddr(result.name, 0, "4")
if not found then return nil, errmsg end
repeat
table.insert(result.ip, found:getaddress(addr).literal)
until not found:next()
return result
end
function dns.toip(...)
local result, errmsg = resolve(...)
if not result then return nil, errmsg end
return result.ip[1], result
end
function dns.tohostname(...)
local result, errmsg = resolve(...)
if not result then return nil, errmsg end
return result.name, result
end
function dns.gethostname()
return procinfo("n")
end
end
local socket = {
_VERSION = "LuaSocket 2.0.2",
dns = dns,
sleep = sleep,
skip = select,
}
function socket.gettime()
return now("epoch")
end
function socket.newtry(func)
return function (ok, ...)
if not ok then
pcall(func)
error{(...)}
end
return ...
end
end
do
local function cont(ok, ...)
if not ok then
local err = ...
if type(err) == "table" then
return nil, err[1]
end
error(err)
end
return ...
end
function socket.protect(func)
return function (...)
return cont(pcall(func, ...))
end
end
end
do
function socket.tcp()
return wrapsock(nil, tcp, "ipv4", newsocket("stream", "ipv4"))
end
function socket.udp()
return wrapsock(nil, udp, "ipv4", newsocket("datagram", "ipv4"))
end
local sockcls = { [tcp]=true, [udp]=true }
local function addresult(list, sock)
list[#list+1] = sock
list[sock] = true
end
local function collectpending(pending, list, result, event)
if list then
for _, value in ipairs(list) do
if sockcls[getmetatable(value)] and value.socket then
local sock = value.socket
if event == "w" or sock:dirty() then
addresult(result, value)
else
pending[value] = true
end
end
end
end
return next(pending) ~= nil
end
local function wait2read(self, thread)
self.last = self.socket:receive(self.buffer)
if self.last then
resume(thread, wait2read, self)
end
end
local function suspend(timeout)
if not timeout or timeout < 0 then
return yield()
end
return sleep(timeout)
end
function socket.select(recvt, sendt, timeout)
local recvok, sendok, result, errmsg = {}, {}
local pending = {}
if collectpending(pending, recvt, recvok, "r") or
collectpending(pending, sendt, sendok, "w") then
local thread = running()
for socket in pairs(pending) do
local waiter = newcoro(wait2read)
resume(waiter, socket, thread)
pending[socket] = waiter
end
result, errmsg = suspend(timeout)
if result == wait2read then
local ready = errmsg
pending[ready] = nil
addresult(recvok, ready)
elseif result then
errmsg = "timeout"
else
errmsg = "coroutine resumed"
end
for socket, waiter in pairs(pending) do
resume(waiter, nil, "cancel")
end
else
result, errmsg = suspend(timeout)
if result then
errmsg = "timeout"
else
errmsg = "coroutine resumed"
end
end
return recvok, sendok, errmsg
end
end
if LUASOCKET_DEBUG then
local function wrap(func)
return function (...)
local start = now()
local result, errmsg, partial = func(...)
return result, errmsg, partial, now() - start
end
end
tcp.receive = wrap(tcp.receive)
tcp.send = wrap(tcp.send)
socket._DEBUG = true
end
return socket
|
-- Copyright (c) 2019 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local Component = require "moonpie.ui.components.component"
local cache
local delay = 1
local last = 0
local function GetLatest()
if cache == nil or love.timer.getTime() - last > delay then
last = love.timer.getTime()
local mem = collectgarbage("count")
cache = Component.text({ text = "Memory: {{kbusage}} kb", kbusage = string.format("%.2f", mem) })
end
return cache
end
Component("memory_stats", function()
return GetLatest()
end)
|
local M = {}
local Path = require 'plenary.path'
local Job = require 'plenary.job'
local nerveux_config = require "nerveux.config"
local report_error = vim.fn['health#report_error']
local report_ok = vim.fn['health#report_ok']
local function is_neuron_cmd_ok()
vim.fn['health#report_info']('Checking neuron binary...')
local is_executable = vim.fn.executable(nerveux_config.neuron_cmd) == 1
local path_exists = Path:new(nerveux_config.neuron_cmd):exists()
return is_executable or path_exists
end
local function is_correct_neuron_version()
local version_string = Job:new({
command = nerveux_config.neuron_cmd,
args = {'--version'}
}):sync()
local major, minor = unpack(vim.split(version_string[1], '.', true))
return {tonumber(major) == 1 and tonumber(minor) >= 9, version_string[1]}
end
local function is_valid_zettelkasten_dir()
return Path:new(string.format([[%s/neuron.dhall]], nerveux_config.neuron_dir))
:exists()
end
M.checks = function()
vim.fn['health#report_start']('sanity checks')
if not is_neuron_cmd_ok() then
report_error(string.format([[ `%s` does not exist or is not executable ]],
nerveux_config.neuron_cmd),
"Make sure `neuron_cmd` is correct")
return
else
report_ok 'neuron executable exists'
end
local version_is_correct, error_detail = unpack(is_correct_neuron_version())
if not version_is_correct then
report_error(
string.format([[ Version `%s` is not supported ]], error_detail),
"Update neuron to version 1.9.x at least")
return
else
report_ok 'neuron version is >= 1.9.0 (neuron v2)'
end
if not is_valid_zettelkasten_dir() then
report_error(
string.format([[%s/neuron.dhall]], nerveux_config.neuron_dir) ..
" is not a valid directory",
"Set the proper directory via `neuron_dir` or change the current working directory")
else
report_ok '`neuron_dir` is a valid neuron directory'
end
end
return M
|
return {
Vehicles = {
"Vehicle.v_sport2_porsche_911turbo_player", -- 911 II (930) TURBO
"Vehicle.v_sport1_rayfield_aerondight_player", -- AERONDIGHT "GUINEVERE"
"Vehicle.v_sport2_villefort_alvarado_valentinos_player", -- ALVARADO "VATO"
"Vehicle.v_sport2_villefort_alvarado_player", -- ALVARADO V4F 570 DELEGATE
"Vehicle.v_sportbike3_brennan_apollo_nomad_player", -- APOLLO "SCORPION"
"Vehicle.v_sportbike3_brennan_apollo_player", -- APOLLO
"Vehicle.v_sportbike2_arch_player", -- ARCH NAZARÉ
"Vehicle.v_sport1_rayfield_caliburn_02_player", -- CALIBURN (BLACK)
"Vehicle.v_sport1_rayfield_caliburn_player", -- CALIBURN (WHITE)
"Vehicle.v_standard25_thorton_colby_nomad_player", -- COLBY "LITTLE MULE"
"Vehicle.v_standard2_thorton_colby_player", -- COLBY C125
"Vehicle.v_standard25_thorton_colby_pickup_player", -- COLBY CX410 BUTTE (GREEN)
"Vehicle.v_standard25_thorton_colby_pickup_02_player", -- COLBY CX410 BUTTE (RED)
"Vehicle.v_standard25_villefort_columbus_player", -- COLUMBUS V340-F FREIGHT
"Vehicle.v_standard2_villefort_cortes_player", -- CORTES V5000 VALOR
"Vehicle.v_standard2_villefort_cortes_delamain_player", -- DELAMAIN NO.21
"Vehicle.v_standard3_chevalier_emperor_player", -- EMPEROR 620 RAGNAR
"Vehicle.v_standard2_thorton_galena_nomad_player", -- GALENA "GECKO"
"Vehicle.v_standard2_thorton_galena_bobas_player", -- GALENA "RATTLER"
"Vehicle.v_standard2_thorton_galena_player", -- GALENA G240
"Vehicle.v_standard2_archer_hella_player", -- HELLA EC-D I360
"Vehicle.v_sportbike2_arch_jackie_player", -- JACKIE'S ARCH
"Vehicle.v_sportbike2_arch_jackie_tuned_player", -- JACKIE'S TUNED ARCH
"Vehicle.v_sportbike1_yaiba_kusanagi_tyger_player", -- KUSANAGI "MIZUCHI"
"Vehicle.v_sportbike1_yaiba_kusanagi_player", -- KUSANAGI CT-3X
"Vehicle.v_standard3_thorton_mackinaw_ncu_player", -- MACKINAW "BEAST"
"Vehicle.v_standard3_thorton_mackinaw_player", -- MACKINAW MTL1
"Vehicle.v_standard2_makigai_maimai_player", -- MAIMAI P126
"Vehicle.v_sportbike2_arch_tyger_player", -- NAZARÉ "ITSUMADE"
"Vehicle.v_sport1_herrera_outlaw_player", -- OUTLAW GTS
"Vehicle.v_standard2_archer_bandit_player", -- QUARTZ "BANDIT"
"Vehicle.v_standard2_archer_quartz_player", -- QUARTZ EC-T2 R660
"Vehicle.v_sport2_mizutani_shion_nomad_02_player", -- SHION "COYOTE" (RED)
"Vehicle.v_sport2_mizutani_shion_nomad_player", -- SHION "COYOTE"
"Vehicle.v_sport2_mizutani_shion_player", -- SHION MZ2
"Vehicle.v_standard25_mahir_supron_player", -- SUPRON FS3
"Vehicle.v_standard2_chevalier_thrax_player", -- THRAX 388 JEFFERSON
"Vehicle.v_sport1_quadra_turbo_player", -- TURBO-R 740
"Vehicle.v_sport1_quadra_turbo_r_player", -- TURBO-R V-TECH
"Vehicle.v_sport2_quadra_type66_nomad_ncu_player", -- TYPE-66 "CTHULHU"
"Vehicle.v_sport2_quadra_type66_nomad_player", -- TYPE-66 "JAVELINA"
"Vehicle.v_sport2_quadra_type66_player", -- TYPE-66 "JEN ROWLEY"
"Vehicle.v_sport2_quadra_type66_avenger_player", -- TYPE-66 AVENGER
},
}
|
return [[
{
"Lang": "nl",
"Name": "Nederlands",
"Spawner.Title": "Trein spawner",
"Spawner.Trains1": "Trein",
"Spawner.Trains2": "Maximum voor jou",
"Spawner.WagNum": "Aantal wagons",
"Spawner.AutoCouple": "Koppel wagons automatisch",
"Entities.gmod_subway_81-717_mvm.Spawner.Texture.Name": "Kleurstelling",
"Entities.gmod_subway_81-717_mvm.Spawner.PassTexture.Name": "Interieur",
"Entities.gmod_subway_81-717_mvm.Spawner.CabTexture.Name": "Cabine interieur",
"Entities.gmod_subway_81-717_mvm.Spawner.Announcer.Name": "Omroeper",
"Entities.gmod_subway_81-717_mvm.Spawner.Lighter.Name": "Aansteker",
"Entities.gmod_subway_81-717_mvm.Spawner.ARSType.Name": "Model ARS",
"Entities.gmod_subway_81-717_mvm.Spawner.ARSType.1": "Standaard(vierkante lampen)",
"Entities.gmod_subway_81-717_mvm.Spawner.ARSType.2": "Standard(ronde lampen)",
"Entities.gmod_subway_81-717_mvm.Spawner.ARSType.3": "Kiev/SPB",
"Entities.gmod_subway_81-717_mvm.Spawner.ARSType.4": "Oude ARS",
"Entities.gmod_subway_81-717_mvm.Spawner.Cran.Name": "Remhendel type",
"Entities.gmod_subway_81-717_mvm.Spawner.Cran.1": "334",
"Entities.gmod_subway_81-717_mvm.Spawner.Cran.2": "013",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.Name": "Voorkant",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.1": "2-2",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.2": "2-2-2",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.3": "1-4-1 bumper 1",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.4": "1-4-1 bumper 2",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.5": "1-1",
"Entities.gmod_subway_81-717_mvm.Spawner.MaskType.6": "Retro",
"Entities.gmod_subway_81-717_mvm.Spawner.LED.Name": "LED",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.Name": "BPSN type",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.1": "Oud hoge toon",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.2": "Oud medium toon",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.3": "Standaard(SPB)",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.4": "Standaard(TKL)",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.5": "Standaard",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.6": "Kiev",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.7": "Oud",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.8": "Standaard 2",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.9": "Standaard 3",
"Entities.gmod_subway_81-717_mvm.Spawner.BPSNType.10": "Geen geluid(BPN-115)",
"Entities.gmod_subway_81-717_mvm.Spawner.KVSnd.Name": "Controller geluid",
"Entities.gmod_subway_81-717_mvm.Spawner.KVSnd.1": "Type 1",
"Entities.gmod_subway_81-717_mvm.Spawner.KVSnd.2": "Type 2",
"Entities.gmod_subway_81-717_mvm.Spawner.KVSnd.3": "Type 3",
"Entities.gmod_subway_81-717_mvm.Spawner.NewKV.Name": "Nieuw controller model",
"Entities.gmod_subway_81-717_mvm.Spawner.HornType.Name": "SPB toeter",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.Name": "Bel geluid",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.1": "Oud",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.2": "Standaard met lage toon",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.3": "Standaard met hoge toon",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.4": "Standaard onderbroken met lage toon",
"Entities.gmod_subway_81-717_mvm.Spawner.RingType.5": "Standaard onderbroken met hoge toon",
"Entities.gmod_subway_81-717_mvm.Spawner.NM.Name": "Treinleiding",
"Entities.gmod_subway_81-717_mvm.Spawner.Battery.Name": "Batterij",
"Entities.gmod_subway_81-717_mvm.Spawner.Switches.Name": "Stoppen ingeschakeld",
"Entities.gmod_subway_81-717_mvm.Spawner.SwitchesR.Name": "Willekeurige stoppen",
"Entities.gmod_subway_81-717_mvm.Spawner.DoorsL.Name": "Open deuren linkerkant",
"Entities.gmod_subway_81-717_mvm.Spawner.DoorsR.Name": "Open deuren rechterkant",
"Entities.gmod_subway_81-717_mvm.Spawner.GV.Name": "Hoog-voltage schakelaar",
"Entities.gmod_subway_81-717_mvm.Spawner.PB.Name": "Parkeerrem",
"Entities.gmod_subway_81-717_mvm.Spawner.BortLampType.Name": "Type signaallampen",
"Entities.gmod_subway_81-717_mvm.Spawner.BortLampType.1": "Horizontaal",
"Entities.gmod_subway_81-717_mvm.Spawner.BortLampType.2": "Verticaal",
"Entities.gmod_subway_81-717_mvm.Spawner.MVM.Name": "MVM teken",
"Entities.gmod_subway_81-717_mvm.Spawner.HandRail.Name": "Handvaten model",
"Entities.gmod_subway_81-717_mvm.Spawner.HandRail.1": "Oud",
"Entities.gmod_subway_81-717_mvm.Spawner.HandRail.2": "Nieuw",
"Entities.gmod_subway_81-717_mvm.Spawner.SeatType.Name": "Stoel model",
"Entities.gmod_subway_81-717_mvm.Spawner.SeatType.1": "Oud",
"Entities.gmod_subway_81-717_mvm.Spawner.SeatType.2": "Nieuw",
"Entities.gmod_subway_81-717_mvm.Spawner.LampType.Name": "Verlichting type",
"Entities.gmod_subway_81-717_mvm.Spawner.LampType.1": "Type 1",
"Entities.gmod_subway_81-717_mvm.Spawner.LampType.2": "Type 2",
"Entities.gmod_subway_81-717_mvm.Spawner.LampType.3": "Type 3",
"Entities.gmod_subway_81-717_mvm.Spawner.Breakers.Name": "Stoppen rechterkant",
"Entities.gmod_subway_81-717_mvm.Spawner.Adverts.Name": "Advertenties type",
"Entities.gmod_subway_81-717_mvm.Spawner.Adverts.1": "Type 1",
"Entities.gmod_subway_81-717_mvm.Spawner.Adverts.2": "Type 2",
"Entities.gmod_subway_81-717_mvm.Spawner.Adverts.3": "Type 3",
"Entities.gmod_subway_81-717_mvm.Spawner.Adverts.4": "Geen advertenties",
"Entities.gmod_subway_81-720.Spawner.Texture.Name": "Kleurstelling",
"Entities.gmod_subway_81-720.Spawner.PassTexture.Name": "Interieur",
"Entities.gmod_subway_81-720.Spawner.CabTexture.Name": "Cabine interieur",
"Entities.gmod_subway_81-720.Spawner.Announcer.Name": "Omroeper",
"Entities.gmod_subway_81-720.Spawner.Scheme.Name": "Dienstregeling",
"Entities.gmod_subway_81-720.Spawner.PassSchemesInvert.Name": "Keer dienstregeling om",
"Entities.gmod_subway_81-720.Spawner.NM.Name": "Treinleiding",
"Entities.gmod_subway_81-720.Spawner.Battery.Name": "Batterij",
"Entities.gmod_subway_81-720.Spawner.BRU.Name": "Hoog-voltage schakelaar",
"Entities.gmod_subway_81-720.Spawner.PVZR.Name": "Willekeurige stoppen (trein)",
"Entities.gmod_subway_81-720.Spawner.PPZ.Name": "Activeer alle stoppen",
"Entities.gmod_subway_81-720.Spawner.PPZDepot.Name": "Deactiveer stoppen als in depot",
"Entities.gmod_subway_81-720.Spawner.PPZR.Name": "Willekeurige stoppen (wagon)",
"Entities.gmod_subway_81-720.Spawner.DoorsL.Name": "Open deuren linkerkant",
"Entities.gmod_subway_81-720.Spawner.DoorsR.Name": "Open deuren rechterkant",
"Entities.gmod_subway_81-722.Spawner.Texture.Name": "Kleurstelling",
"Entities.gmod_subway_81-722.Spawner.PassTexture.Name": "Interieur",
"Entities.gmod_subway_81-722.Spawner.CabTexture.Name": "Cabin interieur",
"Entities.gmod_subway_81-722.Spawner.Announcer.Name": "Omroeper",
"Entities.gmod_subway_81-722.Spawner.Scheme.Name": "Dienstregeling",
"Entities.gmod_subway_81-722.Spawner.SarmatInvert.Name": "Keer dienstregeling om",
"Entities.gmod_subway_81-722.Spawner.NM.Name": "Treinleiding",
"Entities.gmod_subway_81-722.Spawner.Battery.Name": "Batterij",
"Entities.gmod_subway_81-722.Spawner.Switches.Name": "Activeer alle stoppen",
"Entities.gmod_subway_81-722.Spawner.SwitchesR.Name": "Willekeurige stoppen",
"Entities.gmod_subway_81-722.Spawner.DoorsL.Name": "Open deuren linkerkant",
"Entities.gmod_subway_81-722.Spawner.DoorsR.Name": "Open deuren rechterkant",
"Spawner.Close": "Sluiten",
"Spawner.Spawn": "Klaar"
}
]]
|
-----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Luck Rune
-- Involved in Quest: Mhaura Fortune
-- !pos 70.736 -37.778 149.624 111
-----------------------------------
local ID = require("scripts/zones/Beaucedine_Glacier/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
class("PrepModelCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot0.facade:registerProxy(ContextProxy.New({}))
slot0.facade:registerProxy(ServerProxy.New({}))
slot0.facade:registerProxy(UserProxy.New())
slot0.facade:registerProxy(GatewayNoticeProxy.New())
slot0.facade:registerProxy(SettingsProxy.New())
end
return class("PrepModelCommand", pm.SimpleCommand)
|
-- file created: 2008-12-18
local dialog = require "far2.dialog"
local M = require "lf4ed_message"
local ExGuid = win.Uuid("e534a678-47e7-4a1b-8b6d-c34a10b75992")
local function ExecuteDialog (aData)
local D = dialog.NewDialog()
D._ = {"DI_DOUBLEBOX",3, 1,42, 8, 0, 0, 0, 0, M.MPluginSettings}
D.ReloadDefaultScript = {"DI_CHECKBOX", 6, 2,0, 0, 0, 0, 0, 0, M.MReloadDefaultScript}
D.RequireWithReload = {"DI_CHECKBOX", 6, 3,0, 0, 0, 0, 0, 0, M.MRequireWithReload}
D.UseStrict = {"DI_CHECKBOX", 6, 4,0, 0, 0, 0, 0, 0, M.MUseStrict}
D.ReturnToMainMenu = {"DI_CHECKBOX", 6, 5,0, 0, 0, 0, 0, 0, M.MReturnToMainMenu}
D.sep = {"DI_TEXT", 0, 6, 0, 0, 0, 0, 0, {DIF_BOXCOLOR=1,DIF_SEPARATOR=1}, ""}
D.btnOk = {"DI_BUTTON", 0, 7, 0, 0, 0, 0, 0, {DIF_CENTERGROUP=1, DIF_DEFAULTBUTTON=1}, M.MOk}
D.btnCancel = {"DI_BUTTON", 0, 7, 0, 0, 0, 0, 0, "DIF_CENTERGROUP", M.MCancel}
------------------------------------------------------------------------------
dialog.LoadData(D, aData)
local ret = far.Dialog (ExGuid,-1,-1,46,10,"PluginConfig",D)
if ret == D.btnOk.id then
dialog.SaveData(D, aData)
return true
end
end
local Cfg = (...)[1]
return ExecuteDialog(Cfg)
|
local pos = {x=5,y=5,w=20,h=6}
local state = 0
local dragPos = 0
local gpu = require("component").gpu
local event = require("event")
local w,h = gpu.getResolution()
local function redraw()
gpu.setForeground(15,true)
gpu.setBackground(15,true)
gpu.fill(1,1,w,h," ")
gpu.setBackground(3,true)
gpu.set(pos.x,pos.y,string.rep(" ",pos.w-1))
gpu.set(pos.x,pos.y,"Hello")
gpu.setBackground(14,true)
gpu.setForeground(0,true)
gpu.set(pos.x+pos.w-1,pos.y,"X")
gpu.setBackground(0,true)
gpu.fill(pos.x,pos.y+1,pos.w,pos.h," ")
gpu.setForeground(15,true)
gpu.set(pos.x,pos.y+1,"Hello world!")
gpu.set(pos.x,pos.y+2,"This is a test")
gpu.set(pos.x,pos.y+3,"Press X to exit")
gpu.setBackground(15,true)
gpu.setForeground(0,true)
end
redraw()
while true do
local e,_,a,b = event.pull()
if e == "touch" and a >= pos.x and a < pos.x+pos.w-1 and b == pos.y then
state = 1
dragPos = a - pos.x
end
if e == "touch" and a == pos.x + pos.w - 1 and b == pos.y then
gpu.fill(0,0,w,h," ")
break
end
if e == "drag" and state == 1 then
pos.x = a - dragPos
pos.y = b
redraw()
end
if e == "drop" then
state = 0
end
end
|
vim.opt_local.tabstop = 2
vim.opt_local.softtabstop = 2
vim.opt_local.shiftwidth = 2
vim.opt_local.expandtab = true
vim.opt_local.autoindent = true
vim.opt_local.fileformat = "unix"
|
if ACF.Version then --fallback to old acf, its not set in acf3
function ACF_DefineEngineold(id,data)
ACF_DefineEngine(id,data)
end
else
local class = "zACFE R"
local typeoverwrite = nil
-- Flat 2 engines
ACF.RegisterEngineClass(class, {
Name = "ACFE Radial Engines",
})
do
function ACF_DefineEngineold(id,data)
local Fueltype = {}
if data.fuel == "Petrol" then Fueltype = { Petrol = true } end
if data.fuel == "Diesel" then Fueltype = { Diesel = true } end
if data.fuel == "Multifuel" then Fueltype = { Petrol = true, Diesel = true } end
if data.fuel == "Electric" then Fueltype = { Electric = true } end
ACF.RegisterEngine(id, class, {
Name = data.name,
Description = data.desc,
Model = data.model,
Sound = data.sound,
Fuel = Fueltype,
Type = typeoverwrite or data.enginetype,
Mass = data.weight,
Torque = data.torque,
FlywheelMass = data.flywheelmass,
RPM = {
Idle = data.idlerpm,
PeakMin = data.peakminrpm,
PeakMax = data.peakmaxrpm,
Limit = data.limitrpm,
},
})
end
end
end
-- Radial engines
ACF_DefineEngineold( "R9-4.1", {
name = "R9 4.1L Petrol",
desc = "[ACFE] A tiny, old worn-out radial.",
model = "models/engines/radial9s.mdl",
sound = "acf_engines/r9b.wav",
category = "Radial",
fuel = "Petrol",
enginetype = "Radial",
weight = 150,
torque = 450,
flywheelmass = 0.15,
idlerpm = 700,
peakminrpm = 2700,
peakmaxrpm = 4400,
limitrpm = 4800
} )
ACF_DefineEngineold( "R9-18.5", {
name = "R9 18.5 Petrol",
desc = "[ACFE] Mid range radial, thirsty and smooth",
model = "models/engines/radial9m.mdl",
sound = "acf_engines/r9m.wav",
category = "Radial",
fuel = "Petrol",
enginetype = "Radial",
weight = 560,
torque = 1500,
flywheelmass = 0.45,
idlerpm = 700,
peakminrpm = 1500,
peakmaxrpm = 2150,
limitrpm = 2200
} )
ACF_DefineEngineold( "R9-36.5", {
name = "R9 36.5L Petrol",
desc = "[ACFE] Massive American radial monster, destined for fighter aircraft and heavy tanks.",
model = "models/engines/radial9b.mdl",
sound = "acf_engines/r9s.wav",
category = "Radial",
fuel = "Petrol",
enginetype = "Radial",
weight = 1200,
torque = 3205,
flywheelmass = 1,
idlerpm = 730,
peakminrpm = 500,
peakmaxrpm = 2200,
limitrpm = 2300
} )
|
local
function print_view(view)
str = "["
for i = 1, #view do
local elem = tostring(view[i])
str = str..elem
if i < #view then
str = str..", "
if elem:match("\n") then
str = str.."\n "
end
end
end
str = str.."]"
print(str)
end
print("view ops")
do
print_view(mathv.array("float", {1, 2, 3, 4}) + 1)
print_view(2 + mathv.array("float", {1, 2, 3, 4}))
print_view(mathv.array("vec2", {vec2(1, 2), vec2(3, 4)}) + vec2(5, 6))
print_view(vec2(5, 6) - mathv.array("vec2", {vec2(1, 2), vec2(3, 4)}))
print_view(vec2(1, 2) * mathv.array("vec2", {vec2(2, 2), vec2(3, 3)}))
print_view(vec2(2, 4) / mathv.array("vec2", {vec2(2, 4), vec2(1, 0.5)}))
print_view(vec3(1, 2, 3) * mathv.array("vec3", {vec3(2, 2, 2), vec3(3, 3, 3)}))
print_view(mathv.array("float", {10, 100, 1000}) * vec2(1, 2))
print_view(vec3(1, 2, 3) * mathv.array("float", {10, 100, 1000}))
print_view(mathv.array("vec3", {vec3(1, 2, 3), vec3(4, 5, 6), vec3(7, 8, 9)}) + mathv.array("vec3", {1, 0, 0, 0, 1, 0, 0, 0, 1}))
print_view(mathv.dot(mathv.array("vec2", {vec2(1, 1), vec2(2, 2)}), mathv.array("vec2", {vec2(3, 3), vec2(4, 4)})))
print_view(mathv.sign(mathv.array("float", {2, 0, -2})))
print_view(-mathv.array("float", {1, 2}))
end
print("view generators")
do
print_view(mathv.range("float", 11, -100, 100))
print_view(mathv.range("double", 3, 10, 0))
print_view(mathv.range("byte", 11, 100, -100))
print_view(mathv.range("ubyte", 5, 0, 40))
print_view(mathv.range("short", 7, -3000, 3000))
print_view(mathv.range("ushort", 6, 60000, 10000))
print_view(mathv.range("int", 2, -1000000, 1000000))
print_view(mathv.range("uint", 9, 10000000, 90000000))
-- these work, but we get slight differences on different platforms, possibly due to float formatting differences
-- print_view(mathv.random("float", 10))
-- print_view(mathv.random("double", 10, -10, 10))
-- print_view(mathv.random(am.rand(500), "float", 5, 0, 3))
-- print_view(mathv.random(am.rand(500), "float", 5, 0, 3))
print("view shape changers")
print_view(mathv.cart(mathv.array("ubyte", {1, 10, 100}), mathv.array("ubyte2", {2, 20, 200, 220})))
print_view(mathv.cart(mathv.array("short", {1, 10, 100}), mathv.array("short", {2, 20, 200})))
print_view(mathv.cart(mathv.array("float", {1, 10, 100}), mathv.array("float", {2, 20, 200})))
print_view(mathv.cart(mathv.array("vec2", {1, 2, 10, 20, 100, 200}), mathv.array("float", {3, 30, 300})))
print_view(mathv.cart(mathv.array("double", {3, 30, 300}), mathv.array("dvec2", {1, 2, 10, 20, 100, 200})))
print_view(mathv.vec2(mathv.array("float", {1, 2}), 3))
print_view(mathv.vec4(mathv.array("float", {1, 2}), 3, mathv.array("vec2", {vec2(4, 5), vec2(6, 7)})))
end
print("test matrix views")
do
local range = mathv.range("float", 3, 1, 3)
local mview1 = mathv.mat3(range * vec3(1, 0, 0), vec3(0, 1, 0) * range, vec3(0, 0, 1) * range)
print_view(mview1)
print_view(mview1 * vec3(1, 2, 3))
print_view(vec3(1, 2, 3) * mview1)
print_view(mathv.array("vec4", {1, 2, 3, 4, 5, 6, 7, 8}) * mat4(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2))
print_view(mat4(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2) * mathv.array("vec4", {1, 2, 3, 4, 5, 6, 7, 8}))
print_view(mathv.vec4(mathv.array("vec3", {1, 2, 3, 4, 5, 6}), 1) * mat4(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2))
end
print("view swizzle fields")
do
local view1 = mathv.array("vec2", {vec2(1, 2), vec2(3, 4), vec2(5, 6)})
print_view(view1.x)
print_view(view1.y)
print_view(view1.xy)
local view2 = mathv.array("vec3", {vec3(1, 2, 3), vec3(4, 5, 6), vec3(7, 8, 9)})
print_view(view2.xy)
print_view(view2.z)
local view3 = mathv.array("vec4", {vec4(1, 2, 3, 4), vec4(5, 6, 7, 8)})
print_view(view3.xy)
print_view(view3.yzw)
print_view(view3.zw)
print_view(view3.rgba)
print_view(view3.s)
print_view(view3.y)
print_view(view3.z)
print_view(view3.w)
view3.x = -1
print_view(view3)
view3.yz = mathv.array("vec2", {vec2(10, 20), vec2(30, 40)})
print_view(view3)
view3.yzw = {100, 200, 300, 400, 500, 600}
print_view(view3)
view3.xy = view3.zw
print_view(view3)
view3.xyzw = view3
print_view(view3)
end
print("view methods")
do
local view1 = mathv.vec2(mathv.range("float", 4, 1, 4), mathv.range("float", 4, 10, 40))
view1:add(view1, vec2(1, 2))
print_view(view1)
view1:vec2(mathv.range("float", 3, -1, -3), mathv.range("float", 3, 1, 3))
print_view(view1)
end
print("casting")
do
local src = mathv.array("dvec3", {1, 2, 3, 4, 5, 6})
local dst = mathv.array("vec3", 2)
dst.xyz = src
print_view(dst)
src = mathv.array("vec3", {1, 2, 3, 4, 5, 6})
dst = mathv.array("dvec3", 2)
dst.xyz = src
print_view(dst)
src = mathv.array("vec2", {1, 2, 3, 4})
dst = mathv.array("byte2", 2)
dst.xy = src
print_view(dst)
src = mathv.array("vec2", {1, 2, 3, 4})
dst = mathv.array("ushort2", 2)
dst.xy = src
print_view(dst)
src = mathv.array("double", {1, 2, 3})
dst = mathv.array("int", 3)
dst.x = src
print_view(dst)
print_view(mathv.cast("ubyte2", mathv.array("vec2", {vec2(2, 1), vec2(1, 3)})))
end
print("filter")
do
local view = mathv.array("float", {9, 3, 7, 1, 6, 10, 2})
print_view(mathv.filter(view, mathv.lt(5, view)))
print_view(mathv.filter(view, mathv.lte(view, 6)))
print_view(mathv.filter(view, mathv.and_(mathv.gt(view, 1), mathv.lte(view, 7))))
local view2 = mathv.array("float", {9, 2, 8, 1, 7, 11, 2})
print_view(mathv.filter(view, mathv.eq(view, view2)))
print_view(mathv.filter(view, mathv.eq(view, 1)))
print_view(mathv.filter(view, mathv.eq(1, view, 1.1)))
local iview = mathv.array("int", {9, 2, 8, 1, 7, 12, 4})
print_view(mathv.filter(iview, mathv.eq(iview % 2, 0)))
local n = iview:filter(mathv.eq(iview % 2, 1))
print_view(iview:slice(1, n))
end
print("aggregates")
do
print(mathv.sum(mathv.array("float", {1, 2, 3})))
print(mathv.sum(mathv.array("dvec2", {vec2(1, 2), vec2(3, 4)})))
print(mathv.sum(mathv.array("ushort3", {vec3(1, 2, 3), vec3(4, 5, 6)})))
print(mathv.sum(mathv.lt(mathv.array("float", {1, 5, 2}), mathv.array("float", {3, 2, 5}))))
print(mathv.greatest(mathv.array("float", {5})))
print(mathv.greatest(mathv.array("float", {5, 1, -1, 16, 8})))
print(mathv.greatest(mathv.array("ubyte4", {vec4(1, 2, 3, 4), vec4(4, 3, 2, 1)})))
print(mathv.least(mathv.array("short", {5})))
print(mathv.least(mathv.array("double", {5, 1, -1, 16, 8})))
print(mathv.least(mathv.array("vec3", {vec3(1, 2, 3), vec3(3, 2, 1)})))
end
print("array of structs")
do
local arr = mathv.array_of_structs(3, {
"pos", "vec2",
"color", "ubyte_norm4",
})
arr.pos = {0, 1, 2, 3, 4, 5}
arr.color = {vec4(0, 1, 0, 1), vec4(1, 0, 1, 1), vec4(1, 1, 0, 1)}
local slice = arr:slice(2, 1)
slice.pos = vec2(8, 9)
print_view(arr.pos)
slice = arr:slice(1, 2, 2)
slice.color = {vec4(1, 1, 1, 0), vec4(0, 0, 0, 1)}
print_view(arr.color)
local n = arr:filter(mathv.gt(arr.pos.x, 5))
print_view(arr.pos:slice(1, n))
print_view(arr.color:slice(1, n))
end
print("struct of arrays")
do
local arr = mathv.struct_of_arrays(3, {
"pos", "vec2",
"color", "ubyte_norm4",
})
arr.pos = {0, 1, 2, 3, 4, 5}
arr.color = {vec4(0, 1, 0, 1), vec4(1, 0, 1, 1), vec4(1, 1, 0, 1)}
local slice = arr:slice(2, 1)
slice.pos = vec2(8, 9)
print_view(arr.pos)
slice = arr:slice(1, 2, 2)
slice.color = {vec4(1, 1, 1, 0), vec4(0, 0, 0, 1)}
print_view(arr.color)
local n = arr:filter(mathv.gt(arr.pos.x, 5))
print_view(arr.pos:slice(1, n))
print_view(arr.color:slice(1, n))
end
print("empty arrays")
do
local arr = mathv.array("float", {})
local res = arr + arr
res = arr * 2
print_view(arr)
arr = mathv.array("vec3", 0)
res = vec3(1) + arr
res:filter(mathv.gt(mathv.array("float", 0), 1))
print_view(arr)
res = mathv.cart(mathv.array("vec2", {}), mathv.array("float", {1, 2, 3}))
print_view(res)
res = mathv.cart(mathv.array("float", {1, 2, 3}), mathv.array("vec2", {}))
print_view(res)
print(mathv.sum(mathv.array("float", 0, 1)))
print(mathv.greatest(mathv.array("float", 0)))
print(mathv.least(mathv.array("float", 0)))
end
|
require "block"
local gravity = require "blocks.templates.gravity"
gravel = create_block_behaviour(gravity)
|
local ffi = require('ffi')
local C = ffi.C
local levee = require("levee")
local _ = levee._
local d = levee.d
local p = levee.p
local CHARS64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
return {
core = {
test_close_writer = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local err, n = w:write("foo")
assert(not err)
assert.equal(n, 3)
local buf = levee.d.Buffer(4096)
local err, n = r:read(buf:tail())
assert(not err)
assert.equal(n, 3)
buf:bump(n)
assert.equal(buf:take(), "foo")
w:close()
local err = r:read(buf:tail())
assert.equal(err, levee.errors.CLOSED)
assert(not h:in_use())
end,
test_close_reader = function()
local h = levee.Hub()
local r, w = h.io:pipe()
r:close()
-- continue is required to flush the close
h:continue()
local err, n = w:write("foo")
assert(err)
end,
test_eagain = function()
local h = levee.Hub()
local r, w = h.io:pipe()
-- read eagain
local buf = levee.d.Buffer(100000)
h:spawn(function() err, n = r:read(buf:tail()); buf:bump(n) end)
local err, n = w:write("foo")
assert(not err)
assert.equal(n, 3)
assert.equal(buf:take(3), "foo")
-- write eagain
local want = ("."):rep(100000)
local check
h:spawn(function() check = {w:write(want)} end)
while #buf < 100000 do
local err, n = r:read(buf:tail())
assert(not err)
buf:bump(n)
end
assert.same(check, {nil, 100000})
assert.equal(buf:take(), want)
end,
test_timeout = function()
local h = levee.Hub()
local r, w = h.io:pipe(20)
local buf = levee.d.Buffer(4096)
local got = r:read(buf:tail())
assert.equal(got, levee.errors.TIMEOUT)
end,
test_last_read = function()
local h = levee.Hub()
local r, w = h.io:pipe()
w:write("foo")
w:close()
local buf = levee.d.Buffer(4096)
local err, n = r:read(buf:tail())
assert(not err)
assert.equal(n, 3)
buf:bump(n)
assert.equal(buf:take(), "foo")
local err, n = r:read(buf:tail())
assert(err)
assert(not h:in_use())
end,
test_readn = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local buf = levee.d.Buffer(4096)
-- nil len
local check
h:spawn(function()
local err, n = r:readn(buf:tail(), 6)
assert(not err)
buf:bump(n)
check = buf:take()
end)
assert(not check)
w:write("foo")
assert(not check)
w:write("bar123")
assert.equal(check, "foobar")
assert.equal(r:reads(), "123")
-- non nil len
local check
h:spawn(function()
local err, n = r:readn(buf:tail(), 6, 8)
assert(not err)
buf:bump(n)
check = buf:take()
end)
assert(not check)
w:write("foo")
assert(not check)
w:write("bar123")
assert.equal(check, "foobar12")
assert.equal(r:reads(), "3")
end,
test_readinto = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local buf = levee.d.Buffer(4096)
-- nil n
w:write("foo")
local err = r:readinto(buf)
assert(not err)
assert.equal(buf:take(), "foo")
-- non nil n
w:write("foo")
h:spawn(function() r:readinto(buf, 6) end)
assert.equal(#buf, 0)
w:write("bar123")
assert.equal(#buf, 9)
w:close()
local err = r:readinto(buf)
assert.equal(err, levee.errors.CLOSED)
assert(not h:in_use())
end,
test_reads = function()
local h = levee.Hub()
local r, w = h.io:pipe()
w:write("foo")
assert.equal(r:reads(), "foo")
w:close()
assert.equal(r:reads(), nil)
assert(not h:in_use())
end,
test_write_string = function()
local h = levee.Hub()
local r, w = h.io:pipe()
h:spawn(function()
local err = w:write(("X"):rep(128*1024))
assert.equal(err, nil)
w:close()
end)
local buf = d.Buffer()
while true do
buf:ensure(4096)
local err, n = r:read(buf:tail())
if err then break end
buf:bump(n)
end
assert.equal(buf:take(), ("X"):rep(128*1024))
end,
test_writev = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local iov = h.io.iovec(32)
-- to prevent gc
local keep = {}
local want = {}
for i = 1, 12 do
local s = tostring(i):rep(10000+i)
iov:write(s)
table.insert(keep, s)
table.insert(want, s)
end
want = table.concat(want)
local err, total
h:spawn(function()
err, total = w:writev(iov.iov, iov.n)
w:close()
end)
local got = {}
while true do
local s = r:reads(64*1024)
if not s then break end
table.insert(got, s)
end
got = table.concat(got)
assert.equal(#want, #got)
assert.equal(want, got)
assert.equal(total, #got)
assert(not err)
end,
test_iov = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local err, iov = w:iov()
local want = {}
h:spawn(function()
for i = 1, 1000 do
local s = tostring(i):rep(i)
table.insert(want, s)
iov:send(s)
end
-- test if items are added to the queue while we are mid-write
local s = ("."):rep(791532)
table.insert(want, s)
iov:send(s)
h:continue()
table.insert(want, "...")
iov:send(".")
iov:send(".")
iov:send(".")
iov.empty:recv()
w:close()
want = table.concat(want)
end)
local buf = levee.d.Buffer(4096)
while true do
local err = r:readinto(buf)
if err then break end
end
assert.equal(#want, #buf)
assert.equal(want, buf:take())
end,
test_sendfile = function()
local h = levee.Hub()
local tmp = _.path.Path:tmpdir()
defer(function() tmp:remove(true) end)
local path = tostring(tmp("foo"))
tmp("foo"):write(("x"):rep(8192*1024))
local err, serve = h.stream:listen()
local err, addr = serve:addr()
local err, c = h.stream:dial(addr:port())
local err, s = serve:recv()
local err, r1 = h.io:open(path)
local err, st = r1:stat()
local buf = d.Buffer()
h:spawn(function() s:readinto(buf, st.st_size) end)
local err, n = r1:sendfile(c, st.st_size)
assert(not err)
assert.equal(n, st.st_size)
h:sleep(10)
assert.equal(buf:take(), ("x"):rep(8192*1024))
end,
test_send = function()
local h = levee.Hub()
local r, w = h.io:pipe()
w:send("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")
assert.equal(r:reads(10), "1234567890")
r:close()
w:send("1")
h:continue()
local err = w:send("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")
assert(err)
end,
test_open = function()
local h = levee.Hub()
local tmp = os.tmpname()
local err, w = h.io:open(tmp, C.O_WRONLY)
w:write('{"foo":"bar"}')
w:close()
local err, r = h.io:open(tmp, C.O_RDONLY)
local s = r:stream()
local err, value = s:json()
assert.same(value, {foo = "bar"})
r:close()
os.remove(tmp)
assert(not h:in_use())
end,
},
stream = {
test_core = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
w:write("foo")
s:readin()
assert.equal(#s.buf, 3)
w:write("foo")
s:readin()
assert.equal(#s.buf, 6)
h:spawn(function() s:readin(9) end)
w:write("fo")
assert.equal(#s.buf, 6)
w:write("o")
assert.equal(#s.buf, 9)
w:write("o")
assert.equal(#s.buf, 9)
assert.equal(s:trim(), 9)
w:close()
s:readin(1)
assert.equal(s:take(1), 'o')
assert.same({s:readin(1)}, {levee.errors.CLOSED})
assert.equal(s:take(1), nil)
end,
test_read = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
local buf = levee.d.Buffer(4096)
-- read buffered
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(5))
assert.same({s:read(buf:tail(), 20)}, {nil, 10})
buf:bump(10)
assert.equal(buf:take(), ("."):rep(10))
-- read more than available
assert.same({s:read(buf:tail(), 5)}, {nil, 5})
buf:bump(5)
assert.equal(buf:take(), ("."):rep(5))
-- read less than available
w:write(("."):rep(20))
assert.same({s:read(buf:tail(), 10)}, {nil, 10})
buf:bump(10)
assert.equal(buf:take(), ("."):rep(10))
-- check remainder is still available
s:readin()
assert.equal(s:take(), ("."):rep(10))
end,
test_readn = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
local buf = levee.d.Buffer(4096)
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(5))
local check
h:spawn(function() check = {s:readn(buf:tail(), 20, 20)} end)
assert.equal(check, nil)
w:write(("."):rep(10))
assert.same(check, {nil, 20})
buf:bump(20)
assert.equal(buf:take(), ("."):rep(20))
s:readin()
assert.equal(s:take(), ("."):rep(5))
end,
test_readinto = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
local buf = levee.d.Buffer(4096)
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(20))
s:readinto(buf, 20)
assert.equal(buf:take(), ("."):rep(20))
s:readin()
assert.equal(s:take(), ("."):rep(10))
end,
test_json = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
w:write([[{"foo": "bar"}]])
local err, data = s:json()
assert.same(data, {foo = "bar"})
w:write([[{"foo": "bar"}]])
local err, data = s:json()
assert.same(data, {foo = "bar"})
end,
test_msgpack = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
w:send_msgpack({foo = "bar"})
local err, data = s:msgpack()
assert.same(data, {foo = "bar"})
w:send_msgpack({foo = "bar"})
local err, data = s:msgpack()
assert.same(data, {foo = "bar"})
end,
},
chunk = {
test_core = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
local c = s:chunk(10)
assert.equal(#c, 10)
h:spawn(function() w:write(("."):rep(15)) end)
assert.equal(c:tostring(), "..........")
assert.equal(c.done:recv(), levee.errors.CLOSED)
local c = s:chunk(10)
w:close()
assert.equal(c:tostring(), nil)
end,
test_tobuffer = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(20))
local c = s:chunk(20)
local err, buf = c:tobuffer()
assert.equal(buf:take(), ("."):rep(20))
c.done:recv()
s:readin(1)
assert.equal(s:take(), ("."):rep(10))
end,
test_discard = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local s = r:stream()
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(20))
local c = s:chunk(20)
assert.same({c:discard()}, {nil, 20})
c.done:recv()
assert.equal(s:take(), ("."):rep(10))
end,
test_json = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local json = '{"foo": "bar"}'
w:write(json)
local s = r:stream()
local c = s:chunk(#json)
local err, value = c:json()
assert.same(value, {foo = "bar"})
c.done:recv()
end,
},
splice = {
test_small = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local r2, w2 = h.io:pipe()
local s = r:stream()
w:write(("."):rep(10))
s:readin()
w:write(("."):rep(20))
local c = s:chunk(20)
assert.same({c:splice(w2)}, {nil, 20})
c.done:recv()
assert.equal(r2:reads(), ("."):rep(20))
assert.equal(s:take(), ("."):rep(10))
end,
test_big = function()
local pre = ("."):rep(10)
local val = CHARS64:rep(512)
local crc = C.sp_crc32c(0ULL, pre, #pre)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val - 10)
local N = 64 * 512 * 4
local h = levee.Hub()
local p1 = {}
p1.r, p1.w = h.io:pipe()
p1.s = p1.r:stream()
local p2 = {}
p2.r, p2.w = h.io:pipe()
p2.s = p2.r:stream()
-- setup thread to drain p2
local drained = (function()
local sender, recver = h:pipe()
h:spawn(function()
h:sleep(100) -- add a pause so the splice's write side fills up
p2.s:readin(N)
sender:close()
end)
return recver
end)()
-- buffer a few bytes ahead of splice
p1.w:write(pre)
p1.s:readin()
-- write main payload
h:spawn(function()
p1.w:write(val)
p1.w:write(val)
p1.w:write(val)
p1.w:write(val)
end)
p1.c = p1.s:chunk(N)
assert.same({p1.c:splice(p2.w)}, {nil, N})
p1.c.done:recv()
drained:recv()
assert.equal(#p2.s.buf, N)
assert.equal(C.sp_crc32c(0ULL, p2.s:value()), crc)
assert.equal(p1.s:take(10), "23456789+/")
p1.r:close()
p1.w:close()
p2.r:close()
p2.w:close()
assert(not h:in_use())
end,
test_error_on_read = function()
local val = CHARS64:rep(4096)
local crc = C.sp_crc32c(0ULL, val, #val)
local N = 64 * 4096
local h = levee.Hub()
local p1 = {}
p1.r, p1.w = h.io:pipe()
p1.s = p1.r:stream()
local p2 = {}
p2.r, p2.w = h.io:pipe()
p2.s = p2.r:stream()
h:spawn(function() assert.equal(p2.s:readin(N), levee.errors.CLOSED) end)
-- drop write half way through
h:spawn(function() p1.w:write(val, N/2) ; p1.w:close() end)
p1.c = p1.s:chunk(N)
assert.equal(p1.c:splice(p2.w), levee.errors.CLOSED)
p2.r:close()
p2.w:close()
h:continue()
assert(not h:in_use())
end,
test_error_on_write = function()
local val = CHARS64:rep(4096)
local crc = C.sp_crc32c(0ULL, val, #val)
local N = 64 * 4096
local h = levee.Hub()
local p1 = {}
p1.r, p1.w = h.io:pipe()
p1.s = p1.r:stream()
local p2 = {}
p2.r, p2.w = h.io:pipe()
p2.s = p2.r:stream()
-- drop read half way through
h:spawn(function() p2.s:readin(N/4); p2.r:close() end)
h:spawn(function()
local err = p1.w:write(val, N)
assert(not err)
p1.w:close()
end)
p1.c = p1.s:chunk(N)
local err = p1.c:splice(p2.w)
assert(err)
p2.w:close()
h:continue()
local want = #p1.c
local __, len = p1.c:value()
assert.equal(len, 0)
p1.c:readin(want)
local __, len = p1.c:value()
assert.equal(len, want)
assert.equal(p1.s:readin(), levee.errors.CLOSED)
assert(not h:in_use())
end,
test_tcp = function()
local h = levee.Hub()
local data = ("."):rep(200000)
local err, serve = h.tcp:listen()
local err, addr = serve:addr()
local port = addr:port()
local err, c1 = h.tcp:connect(port)
local err, s1 = serve:recv()
local err, c2 = h.tcp:connect(port)
local err, s2 = serve:recv()
local stream = s2:stream()
h:spawn(function()
while true do
local err = c1:write(("."):rep(10000))
if err then break end
h:sleep(2)
end
end)
s1:stream():chunk(#data):splice(c2)
assert.equal(stream:take(#data), data)
s1:stream():chunk(#data):splice(c2)
assert.equal(stream:take(#data), data)
s1:stream():chunk(#data):splice(c2)
assert.equal(stream:take(#data), data)
s1:close()
c2:close()
s2:close()
serve:close()
h:sleep(10)
assert(not h:in_use())
end,
},
tee = {
test_small_spawned = function()
local h = levee.Hub()
local source = {}
source.r, source.w = h.io:pipe()
source.s = source.r:stream()
local t1 = {}
t1.r, t1.w = h.io:pipe()
local t2 = {}
t2.r, t2.w = h.io:pipe()
-- buffer some bytes
source.w:write(("."):rep(10))
source.s:readin()
source.w:write(("."):rep(20))
source.c = source.s:chunk(20)
local check = ""
assert.same(
{source.c:tee(t1.w, t2.w, function(chunks)
for chunk in chunks do
check = check .. chunk:tostring()
end
end)},
{nil, 20})
assert.same(t1.r:reads(), ("."):rep(20))
assert.same(t2.r:reads(), ("."):rep(20))
assert.same(check, ("."):rep(20))
assert.equal(source.s:take(), ("."):rep(10))
source.r:close()
source.w:close()
t1.r:close()
t1.w:close()
t2.r:close()
t2.w:close()
assert(not h:in_use())
end,
test_small_spliced = function()
local h = levee.Hub()
local source = {}
source.r, source.w = h.io:pipe()
source.s = source.r:stream()
local t1 = {}
t1.r, t1.w = h.io:pipe()
local t2 = {}
t2.r, t2.w = h.io:pipe()
local t3 = {}
t3.r, t3.w = h.io:pipe()
-- buffer some bytes
source.w:write(("."):rep(10))
source.s:readin()
source.w:write(("."):rep(20))
source.c = source.s:chunk(20)
assert.same({source.c:tee(t1.w, t2.w, t3.w)}, {nil, 20})
assert.same(t1.r:reads(), ("."):rep(20))
assert.same(t2.r:reads(), ("."):rep(20))
assert.same(t3.r:reads(), ("."):rep(20))
assert.equal(source.s:take(), ("."):rep(10))
source.r:close()
source.w:close()
t1.r:close()
t1.w:close()
t2.r:close()
t2.w:close()
t3.r:close()
t3.w:close()
assert(not h:in_use())
end,
test_big_spawned = function()
local pre = ("."):rep(10)
local val = CHARS64:rep(512)
local crc = C.sp_crc32c(0ULL, pre, #pre)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val - 10)
local N = 64 * 512 * 4
local h = levee.Hub()
local source = {}
source.r, source.w = h.io:pipe()
source.s = source.r:stream()
local function teer()
local t = {}
t.r, t.w = h.io:pipe()
t.s = t.r:stream()
h:spawn(function()
while true do
if t.s:readin() then break end
end
end)
return t
end
local t1 = teer()
local t2 = teer()
-- buffer some bytes
source.w:write(("."):rep(10))
source.s:readin()
-- main writer
h:spawn(function()
source.w:write(val)
source.w:write(val)
source.w:write(val)
source.w:write(val)
end)
source.c = source.s:chunk(N)
local check
assert.same(
{source.c:tee(t1.w, t2.w, function(chunks)
local err
for chunk in chunks do
err, check = chunk:tobuffer(check)
end
end)},
{nil, N})
assert.equal(C.sp_crc32c(0ULL, t1.s:value()), crc)
assert.equal(C.sp_crc32c(0ULL, t2.s:value()), crc)
assert.equal(C.sp_crc32c(0ULL, check:value()), crc)
assert.equal(source.s:take(10), "23456789+/")
source.r:close()
source.w:close()
t1.r:close()
t1.w:close()
t2.r:close()
t2.w:close()
assert(not h:in_use())
end,
test_big_splice = function()
local pre = ("."):rep(10)
local val = CHARS64:rep(512)
local crc = C.sp_crc32c(0ULL, pre, #pre)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val)
crc = C.sp_crc32c(crc, val, #val - 10)
local N = 64 * 512 * 4
local h = levee.Hub()
local source = {}
source.r, source.w = h.io:pipe()
source.s = source.r:stream()
local function teer()
local t = {}
t.r, t.w = h.io:pipe()
t.s = t.r:stream()
h:spawn(function()
while true do
if t.s:readin() then break end
end
end)
return t
end
local t1 = teer()
local t2 = teer()
local t3 = teer()
-- buffer some bytes
source.w:write(("."):rep(10))
source.s:readin()
-- main writer
h:spawn(function()
source.w:write(val)
source.w:write(val)
source.w:write(val)
source.w:write(val)
end)
source.c = source.s:chunk(N)
assert.same({source.c:tee(t1.w, t2.w, t3.w)}, {nil, N})
h:continue()
assert.equal(C.sp_crc32c(0ULL, t1.s:value()), crc)
assert.equal(C.sp_crc32c(0ULL, t2.s:value()), crc)
assert.equal(C.sp_crc32c(0ULL, t3.s:value()), crc)
assert.equal(source.s:take(10), "23456789+/")
source.r:close()
source.w:close()
t1.r:close()
t1.w:close()
t2.r:close()
t2.w:close()
t3.r:close()
t3.w:close()
assert(not h:in_use())
end,
},
p = {
test_core = function()
local h = levee.Hub()
local r, w = h.io:pipe()
assert(r.p.rbuf)
assert(w.p.wbuf)
assert(not r.p.wbuf)
assert(not w.p.rbuf)
end,
chunk = {
test_tostring = function()
local h = levee.Hub()
local r, w = h.io:pipe()
w:write("foobar123")
local chunk = r.p:chunk(6)
assert.same({chunk:tostring()}, {nil, "foobar"})
assert.same({chunk:tostring()}, {nil, ""})
assert.equal(ffi.string(r.p:value()), "123")
end,
test_splice = function()
local h = levee.Hub()
local s1 = {}
s1.r, s1.w = h.io:pipe()
local s2 = {}
s2.r, s2.w = h.io:pipe()
s1.w:write("foobar123")
local chunk = s1.r.p:chunk(6)
chunk:splice(s2.w)
s2.w:close()
assert.same({s2.r.p:tostring()}, {nil, "foobar"})
assert.same({s2.r.p:tostring()}, {nil, ""})
assert.equal(ffi.string(s1.r.p:value()), "123")
end,
test_json = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local want = {foo="bar"}
w.p.json:write(want)
w:write("foobar123")
local chunk = r.p:chunk(14)
assert.same(want, chunk:json())
local err, got = chunk.json:read()
assert.equal(err, levee.errors.CLOSED)
assert.equal(ffi.string(r.p:value()), "foobar123")
end,
},
test_splice = function()
local h = levee.Hub()
local s1 = {}
s1.r, s1.w = h.io:pipe()
local s2 = {}
s2.r, s2.w = h.io:pipe()
h:spawn(function()
local err, n = s1.w:write(("X"):rep(128*1024))
assert.equal(n, 128*1024)
s1.w:close()
end)
s1.r.p:readin(1)
local err, n = s1.r.p:splice(s2.w, 32*1024-10)
assert.equal(n, 32*1024-10)
s2.r.p:readin(32*1024-10)
assert.equal(ffi.string(s2.r.p:value()), ("X"):rep(32*1024-10))
s2.r.p:trim()
h:spawn(function()
local err, n = s1.r.p:splice(s2.w)
assert.equal(n, 96*1024+10)
s2.w:close()
end)
local err, s = s2.r.p:tostring()
assert.equal(s, ("X"):rep(96*1024+10))
end,
test_msgpack = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local err = w.p.msgpack:write({foo="bar"})
assert(not err)
local err, data = r.p.msgpack:read()
assert.same(data, {foo="bar"})
end,
test_json = function()
local h = levee.Hub()
local r, w = h.io:pipe()
local err = w.p.json:write({foo="bar"})
assert(not err)
local err, data = r.p.json:read()
assert.same(data, {foo="bar"})
end,
},
}
|
local hmac = require "resty.hmac"
local hmacs = {}
local version = "v0"
local err
local _M = {
_VERSION = '0.01',
}
function _M.isAuthentic(request, signingsecret)
if hmacs[signingsecret] == nil then
hmacs[signingsecret] = hmac:new(signingsecret, hmac.ALGOS.SHA256)
end
local hmac_sha256 = hmacs[signingsecret]
local timestamp = request.get_headers()["X-Slack-Request-Timestamp"]
local signature = request.get_headers()["X-Slack-Signature"]
local body = request.get_body_data()
if body == nil or timestamp == nil or signature == nil then
return false
end
local basestring = version .. ":" .. timestamp .. ":" .. body
local mac = version .. "=" .. hmac_sha256:final(basestring, true)
hmac_sha256:reset()
return mac == signature
end
return _M
|
local test = require 'regress'
local ipc = require 'libipc'
test {
testSimple = function()
local fn = os.tmpname()
local flock = ipc.flock(fn)
assert(ipc.flock(fn, true) == nil)
flock:write("test")
flock:close()
flock = nil
collectgarbage()
local flock = ipc.flock(fn)
assert(flock:read() == "test")
end,
testDeadProcess = function()
local fn = os.tmpname()
os.remove(fn)
local pid = ipc.fork()
if pid == 0 then
local flock = ipc.flock(fn)
sys.sleep(0.1)
flock:close()
os.exit(0)
else
local i = 0
while ipc.flock(fn, true) == nil do
i = i + 1
if pid then
ipc.waitpid(pid)
pid = nil
end
end
assert(i > 0)
end
end,
}
|
----------------------------------------------------------------
-- File : Assets\BIZ_Scr\Login\lua_require.lua
-- Author : www.loywong.com
-- COPYRIGHT : (C)
-- Date : 2019/07/29
-- Description : desc
-- Version : 1.0
-- Maintain : [date] desc
----------------------------------------------------------------
require("Login/logincontroller")
require("Login/VI/M_Login_View")
require("Login/VI/UI_Login_View")
require("Login/VI/UI_LoginReg_View")
|
local config = require('orgmode.config')
local colors = require('orgmode.colors')
local M = {}
function M.define_agenda_colors()
local hl_map = M.get_agenda_hl_map()
local keyword_colors = colors.get_todo_keywords_colors()
local todo_keywords = config:get_todo_keywords()
for type, hlname in pairs(hl_map) do
local bold = ''
if vim.tbl_contains(todo_keywords.ALL, type) then
bold = ' gui=bold'
end
vim.cmd(string.format('hi %s guifg=%s ctermfg=%s%s', hlname, keyword_colors[type].gui, keyword_colors[type].cterm, bold))
end
end
function M.define_org_todo_keyword_colors()
local keyword_colors = colors.get_todo_keywords_colors()
local todo_keywords = config:get_todo_keywords()
vim.cmd(string.format([[syn match OrgTODO "\<\(%s\)\>" contained]], table.concat(todo_keywords.TODO, [[\|]])))
vim.cmd(string.format([[syn match OrgDONE "\<\(%s\)\>" contained]], table.concat(todo_keywords.DONE, [[\|]])))
vim.cmd(string.format('hi OrgTODO guifg=%s ctermfg=%s', keyword_colors.TODO.gui, keyword_colors.TODO.cterm))
vim.cmd(string.format('hi OrgDONE guifg=%s ctermfg=%s', keyword_colors.DONE.gui, keyword_colors.DONE.cterm))
end
function M.define_org_headline_colors()
local headline_colors = {'Title', 'Constant', 'Identifier', 'Statement', 'PreProc', 'Type', 'Special', 'String'}
local todo_keywords = config:get_todo_keywords()
local all_keywords = table.concat(todo_keywords.ALL, [[\|]])
for i, color in ipairs(headline_colors) do
local j = i
while j < 40 do
vim.cmd(string.format([[syn match OrgHeadlineLevel%d "^\*\{%d}\s\+\(\<\(%s\)\>\)\?.*$" contains=OrgTODO,OrgDONE]], j, j, all_keywords))
vim.cmd(string.format('hi default link OrgHeadlineLevel%d %s', j, color))
j = j + 8
end
end
end
---@return table<string, string>
function M.get_agenda_hl_map()
return {
TODO = 'OrgTODO',
DONE = 'OrgDONE',
deadline = 'OrgAgendaDeadline',
ok = 'OrgAgendaScheduled',
warning = 'OrgAgendaScheduledPast'
}
end
return M
|
#!/usr/bin/env lua
rules = {}
own = {}
others = {}
parsedRules = false
parsedOwn = false
for line in io.lines() do
line = string.gsub(line, "^%s*(.-)%s*$", "%1")
if line ~= nil and line ~= "" then
if not parsedRules then
if line == "your ticket:" then
parsedRules = true
else
local name, min1, max1, min2, max2 = string.match(line, "(.+):%s*(%d+)-(%d+)%s*or%s*(%d+)-(%d+)")
rules[name] = {
min1 = tonumber(min1),
max1 = tonumber(max1),
min2 = tonumber(min2),
max2 = tonumber(max2)
}
end
elseif not parsedOwn then
if line == "nearby tickets:" then
parsedOwn = true
else
own = {}
for n in string.gmatch(line, "[^,]+") do
table.insert(own, tonumber(n))
end
end
else
local ticket = {}
for n in string.gmatch(line, "[^,]+") do
table.insert(ticket, tonumber(n))
end
table.insert(others, ticket);
end
end
end
function rule_valid(value, rule)
return (value >= rule.min1 and value <= rule.max1) or (value >= rule.min2 and value <= rule.max2)
end
function any_valid(value, rules)
for _, rule in pairs(rules) do
if rule_valid(value, rule) then
return true
end
end
return false
end
function check_index(matched, tickets, rule)
local idx = nil
for check, _ in ipairs(own) do
local is_possibly_valid = true
for _, taken in pairs(matched) do
if check == taken then
is_possibly_valid = false
end
end
if is_possibly_valid then
for _, ticket in ipairs(tickets) do
if not rule_valid(ticket[check], rule) then
is_possibly_valid = false
break
end
end
end
if is_possibly_valid then
if idx ~= nil then
return nil
else
idx = check
end
end
end
return idx
end
valids = {}
for _, ticket in ipairs(others) do
local valid = true
for _, value in ipairs(ticket) do
if not any_valid(value, rules) then
valid = false
end
end
if valid then
table.insert(valids, ticket)
end
end
matched = {}
while true do
local any_left = false
for name, rule in pairs(rules) do
if rule ~= nil then
any_left = true
local idx = check_index(matched, valids, rule)
if idx ~= nil then
matched[name] = idx
rules[name] = nil
end
end
end
if not any_left then
break
end
end
departure_product = 1
for name, idx in pairs(matched) do
if string.sub(name, 1, #"departure") == "departure" then
departure_product = departure_product * own[idx]
end
end
print(departure_product)
|
local core = require "core"
local common = require "core.common"
local command = require "core.command"
local config = require "core.config"
local keymap = require "core.keymap"
local style = require "core.style"
local RootView = require "core.rootview"
config.scale_mode = "code"
config.scale_use_mousewheel = true
local font_cache = setmetatable({}, { __mode = "k" })
-- the following should be kept in sync with core.style's default font settings
font_cache[style.font] = { EXEDIR .. "/data/fonts/font.ttf", 14 * SCALE }
font_cache[style.big_font] = { EXEDIR .. "/data/fonts/font.ttf", 34 * SCALE }
font_cache[style.icon_font] = { EXEDIR .. "/data/fonts/icons.ttf", 14 * SCALE }
font_cache[style.code_font] = { EXEDIR .. "/data/fonts/monospace.ttf", 13.5 * SCALE }
local load_font = renderer.font.load
function renderer.font.load(...)
local res = load_font(...)
font_cache[res] = { ... }
return res
end
local function scale_font(font, s)
local fc = font_cache[font]
return renderer.font.load(fc[1], fc[2] * s)
end
local current_scale = SCALE
local default = current_scale
local function get_scale() return current_scale end
local function set_scale(scale)
scale = common.clamp(scale, 0.2, 6)
-- save scroll positions
local scrolls = {}
for _, view in ipairs(core.root_view.root_node:get_children()) do
local n = view:get_scrollable_size()
if n ~= math.huge then
scrolls[view] = view.scroll.y / (n - view.size.y)
end
end
local s = scale / current_scale
current_scale = scale
if config.scale_mode == "ui" then
SCALE = current_scale
style.padding.x = style.padding.x * s
style.padding.y = style.padding.y * s
style.divider_size = style.divider_size * s
style.scrollbar_size = style.scrollbar_size * s
style.caret_width = style.caret_width * s
style.tab_width = style.tab_width * s
style.big_font = scale_font(style.big_font, s)
style.icon_font = scale_font(style.icon_font, s)
style.font = scale_font(style.font, s)
end
style.code_font = scale_font(style.code_font, s)
-- restore scroll positions
for view, n in pairs(scrolls) do
view.scroll.y = n * (view:get_scrollable_size() - view.size.y)
view.scroll.to.y = view.scroll.y
end
core.redraw = true
end
local on_mouse_wheel = RootView.on_mouse_wheel
function RootView:on_mouse_wheel(d, ...)
if keymap.modkeys["ctrl"] and config.scale_use_mousewheel then
if d < 0 then command.perform "scale:decrease" end
if d > 0 then command.perform "scale:increase" end
else
return on_mouse_wheel(self, d, ...)
end
end
command.add(nil, {
["scale:reset" ] = function() set_scale(default) end,
["scale:decrease"] = function() set_scale(current_scale * 0.9) end,
["scale:increase"] = function() set_scale(current_scale * 1.1) end,
})
keymap.add {
["ctrl+0"] = "scale:reset",
["ctrl+-"] = "scale:decrease",
["ctrl+="] = "scale:increase",
}
return { get_scale = get_scale, set_scale = set_scale }
|
-------------- include libs ---------------
require ("mod-gui")
require ("cores.lib.class")
require ("cores.models.player")
--- Create the instance container
SE = {
-- Map<ItemName :: string -> MaxStackSize :: int>
StackSizeCache = {}
}
function SE.CachePrototypes()
-- Get item stack sizes
for name, proto in pairs(game.item_prototypes) do
SE.StackSizeCache[name] = proto.stack_size
end
end
-- Create the logger
SE.Logger = (require "cores.lib.logger")()
-- Log trace messages
SE.Logger.EnableTrace = false
SE.Logger.EnableLogging = true
--- Create constants
SE.Constants = (require 'cores.constants.constants')()
--- Get settings
SE.Settings = (require "cores.se-settings")()
--- Create the data store
SE.DataStore = (require "cores.se-data-store")()
--- Create the storage networks manager
SE.NetworksManager = (require "cores.handlers.networks-manager")()
--- Create the storage network handler
SE.NetworkHandler = (require "cores.handlers.network-handler")()
--- Create node handlers
SE.NodeHandlersRegistry = (require "cores.handlers.handlers-registry")()
local BaseHandler = (require "cores.handlers.nodes.base-node-handler")()
SE.NodeHandlersRegistry.AddHandler(BaseHandler)
SE.NodeHandlersRegistry.AddHandler((require "cores.handlers.nodes.controller-node-handler")(BaseHandler))
SE.NodeHandlersRegistry.AddHandler((require "cores.handlers.nodes.energy-acceptor-node-handler")(BaseHandler))
SE.NodeHandlersRegistry.AddHandler((require "cores.handlers.nodes.storage-node-handler")(BaseHandler))
SE.NodeHandlersRegistry.AddHandler((require "cores.handlers.nodes.interface-node-handler")(BaseHandler))
--- Link node handlers with entities
local protoNames = SE.Constants.Names.Proto
local handlerNames = SE.Constants.Names.NodeHandlers
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.Controller.Entity, handlerNames.Controller)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.EnergyAcceptor.Entity, handlerNames.EnergyAcceptor)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.StorageChestMk1.Entity, handlerNames.Storage)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.StorageChestMk2.Entity, handlerNames.Storage)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.RequesterChest.Entity, handlerNames.Storage)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.InterfaceChest.Entity, handlerNames.Interface)
SE.NodeHandlersRegistry.AddEntityHandler(protoNames.ProviderChest.Entity, handlerNames.Interface)
--- Create the Gui manager
SE.GuiManager = (require "cores.guis.gui-manager")()
--- Create the game event manager
SE.GameEventManager = (require "cores.game-events.game-events-manager")()
require "cores.guis.guis"
--- Register for events
SE.GameEventManager.RegisterHandlers()
|
--
-- https://technet.microsoft.com/en-us/library/dd734783(v=ws.10).aspx
-- protocol = { any | Integer | icmpv4 | icmpv6 | icmpv4:type,code | icmpv6:type,code | tcp | udp }
-- Windows 7 does not support multiple protocol
--
-- port = { any | Integer | rpc | rpc-epmap | teredo | [ ,... ] }
--
-- You have to set `protocol` if you whant ban specific port.
--
-- Example ban ports 5060 and 5080 for tcp and udp
-- action = {
-- {"advfirewall", {port = "5060,5080"; protocol = "udp"}};
-- {"advfirewall", {port = "5060,5080"; protocol = "tcp"}};
-- }
--
local unban = 'netsh advfirewall firewall delete rule name="SpyLog <BAN_UUID>"'
local ban = 'netsh advfirewall firewall add rule dir=in interface=any action=block ' ..
'name="SpyLog <UUID>" description="<DATE> <FILTER> <JAIL> <BANTIME>" ' ..
'remoteip="<HOST>/<NET>" localport="<PORT>" protocol="<PROTOCOL>" ';
local param = {
net = '32';
port = 'any';
protocol = 'any';
service = 'any';
}
ACTION{"advfirewall",
ban = ban;
unban = unban;
parameters = param;
options = { timeout = 10000 };
}
-- `program` parameter has no default value and can not be empty
ACTION{"advfirewall-program",
ban = ban .. ' program="<PROGRAM>"';
unban = unban;
parameters = param;
options = { timeout = 10000 };
}
-- `service=any` means that rule will be apply only to services but not to regular application
ACTION{"advfirewall-service",
ban = ban .. ' service="<SERVICE>"';
unban = unban;
parameters = param;
options = { timeout = 10000 };
}
ACTION{"advfirewall-program-service",
ban = ban .. ' program="<PROGRAM>" service="<SERVICE>"';
unban = unban;
parameters = param;
options = { timeout = 10000 };
}
|
-- by Qige from 6Harmonics
-- @ 2017.03.07
mqtt = {}
mqtt.conf = {}
mqtt.conf.broker = 'OttawaOffice.azure-devices.com'
mqtt.conf.broker_port = 1883
mqtt.conf.subscription_id = 'c53151fc-c4e2-4b51-919a-0f1533e04077'
mqtt.conf.iothub_name = 'OttawaOffice'
mqtt.conf.sap_id = 'iothubowner'
local MSAzure = nil
function callback(
topic, -- string
message) -- string
print("Topic: " .. topic .. ", message: '" .. message .. "'")
MSAzure:publish(args.topic_p, message)
end
function mqtt.Test()
local host = mqtt.conf.broker
local port = mqtt.conf.broker_port
local id = mqtt.conf.sap_id
local MQTT = require 'az/mqtt/mqtt_library'
MSAzure = MQTT.client.create(host, port)
MSAzure:connect(id)
io.write("dbg> connected.\n")
MSAzure:subscribe({ 'noise' })
local error_msg = nil
while(error_msg == nil) do
error_msg = MSAzure:handler()
scoket.sleep(1.0)
end
if (error_msg == nil) then
MSAzure:unsubscribe({ 'noise' })
MSAzure:destroy()
else
print(error_msg)
end
end
return mqtt
|
includeFile("custom_content/tangible/wearables/cybernetic/s05/cybernetic_s05_arm_l.lua")
includeFile("custom_content/tangible/wearables/cybernetic/s05/cybernetic_s05_arm_r.lua")
includeFile("custom_content/tangible/wearables/cybernetic/s05/cybernetic_s05_legs.lua")
includeFile("custom_content/tangible/wearables/cybernetic/s05/cybernetic_s05_torso.lua")
|
-- SPDX-License-Identifier: BSD-2-Clause
--
-- Copyright (c) 2019, David Karell
-- 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.
--
-- 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 HOLDER 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.
local core = require "core"
local menu = require "menu"
local config = require "config"
local welcome_entries = menu.welcome.all_entries
welcome_entries[#welcome_entries + 1] = {
entry_type = core.MENU_CAROUSEL_ENTRY,
carousel_id = "rescue_mode_menu_entry",
items = {"NO", "YES"},
name = function(_, choice, _)
return "Rescue mode: " .. tostring(choice)
end,
func = function(_, choice, _)
if choice == "YES" then
local rescue_name = "/boot/loader.conf.rescue"
config.processFile(rescue_name)
elseif choice == "NO" then
config.reload()
end
end,
}
|
local Player = game.Players.LocalPlayer
local PlayerModule = require(game.Players.LocalPlayer.PlayerScripts:WaitForChild("PlayerModule"))
local CustomCharacter = game.ReplicatedStorage:WaitForChild("CustomCharacter")
local CapsuleUtil = require(CustomCharacter:WaitForChild("CapsuleUtil"))
local Movement = require(game.ReplicatedStorage.CustomCharacter.Movement)
local BinaryUtil = require(game.ReplicatedStorage.CustomCharacter.BinaryUtil)
local Plugin = require(script.Plugin)
local ControlModule = PlayerModule:GetControls()
local Character = nil
local Capsule = nil
local Collider = nil
local Humanoid = nil
local CapsuleParts = nil
local HumanoidRootPart = nil
local FootPosition = Vector3.new()
local MovementVector = Vector3.new()
local LastValidFloorPosition = Vector3.new()
local CanUpdateNetwork = false
local LastVelocity = Vector3.new()
local GoodPositionCheck1 = nil
local GoodPositionCheck2 = nil
local GoodPositionCheck2Velocity = nil
local TimeAlive = 0
local Paused = true
local Sitting = false
local RunDecay = 1
local WalkSpeedMultiplier = 1
local JumpFatigue = 1
local TouchingParts = {}
local SLOPE_ANGLE = 0.7
local CurrentLadder = nil
local LadderPart = nil
local FloorObject = nil
local CONST_EPSILON = 0.001
local StartTime = workspace.DistributedGameTime
local BadBoy = false
local BadBoyTicks = 0
function newCharacter(NewChar)
if ( not NewChar ) then
return
end
TimeAlive = 0
Paused = true
Character = NewChar
HumanoidRootPart = Character:WaitForChild("HumanoidRootPart", 60)
Humanoid = Character:WaitForChild("Humanoid")
TouchingParts = {}
CapsuleParts = CapsuleUtil:CreateCharacterCollider(getRadius(), getHeight())
Capsule = CapsuleParts[1]
Collider = CapsuleParts[2]
LadderPart = Instance.new("Part")
LadderPart.Transparency = 1.0
LadderPart.Size = Vector3.new(2, 1, 2)
LadderPart.Name = "LadderPart"
LadderPart.Anchored = true
local DesiredPosition = HumanoidRootPart.CFrame
if ( LastValidFloorPosition ) then
DesiredPosition = CFrame.new(LastValidFloorPosition)
end
local Transformation = DesiredPosition + Vector3.new(0, getHeight(), 0)
Teleport(Transformation)
Capsule.Parent = workspace.CurrentCamera
Paused = false
pcall(function()
game:GetService('PhysicsService'):SetPartCollisionGroup(Capsule, "PlayerGroup")
game:GetService('PhysicsService'):SetPartCollisionGroup(Collider, "PlayerGroup")
end)
Humanoid.Changed:Connect(function(event)
if ( event == "Jump" or event == "JumpReplicate" ) then
if ( Humanoid.Jump ) then
requestJump()
game:GetService("RunService").Heartbeat:Wait()
Humanoid.Jump = false
end
end
end)
Humanoid.HealthChanged:Connect(function(Health)
if ( Health <= 0 ) then
reset()
end
end)
Humanoid:GetPropertyChangedSignal("SeatPart"):Connect(function()
if ( Humanoid.SeatPart ) then
Sitting = true
end
end)
end
function reset()
Capsule = nil
Collider = nil
if ( CapsuleParts ) then
for i = 1, #CapsuleParts do
CapsuleParts[i]:Destroy()
end
end
setLadder(nil)
LastValidFloorPosition = nil
FootPosition = nil
CapsuleParts = nil
TouchingParts = {}
if ( LadderPart ) then
LadderPart:Destroy()
LadderPart = nil
end
end
Player.CharacterRemoving:Connect(function()
Capsule = nil
CapsuleParts = nil
HumanoidRootPart = nil
Character = nil
Humanoid = nil
updateCharData("IsSliding", false)
updateCharData("OnGround", false)
updateCharData("FloorMaterial", Enum.Material.Air.Name)
FloorObject = nil
MovementVector = Vector3.new()
end)
function requestJump()
if ( getCharData("IsSliding") ) then
return
end
if ( not getCharData("OnGround") ) then
return
end
if ( not Capsule ) then
return
end
Capsule.Velocity = Capsule.Velocity + Vector3.new(0, getCharacterConfig():GetAttribute("JumpPower")*JumpFatigue, 0)
updateCharData("OnGround", false)
setLadder(nil)
end
function getRadius()
return getCharacterConfig():GetAttribute("Radius")
end
function getHeight()
return getCharacterConfig():GetAttribute("Height")
end
function getVelocity()
if ( not Capsule ) then
return Vector3.new()
end
return Capsule.Velocity
end
function getFlatVelocity()
local Velocity = getVelocity()
return Velocity * Vector3.new(1, 0, 1)
end
function isOnGround()
return getCharData("OnGround")
end
function getCharacterConfig()
return CustomCharacter.Config[getGroundState()][getPlayerState()]
end
function _G.GetCustomCharacterConfig(Player)
local CharData = Player:FindFirstChild("CharData")
if ( not CharData ) then
return nil
end
local GroundRef = game.ReplicatedStorage.CustomCharacter.Config:FindFirstChild(CharData.GroundState.Value)
if ( not GroundRef ) then
return nil
end
local PlayerState = GroundRef:FindFirstChild(CharData.PlayerState.Value)
if ( not PlayerState ) then
return nil
end
return PlayerState
end
function cpairs(t)
return next, t, nil
end
local NetworkToUpdate = {}
function updateCharData(KeyName, Value)
local Ref = Player.CharData:FindFirstChild(KeyName)
if ( not Ref ) then
return
end
local OldValue = Ref.Value
if ( Value == OldValue ) then
return
end
Ref.Value = Value
if ( CanUpdateNetwork ) then
NetworkToUpdate[KeyName] = Value
end
end
function getCharData(KeyName)
return Player.CharData[KeyName].Value
end
function getGroundState()
return Player.CharData.GroundState.Value
end
function setGroundState(Value)
updateCharData("GroundState", Value)
end
function getPlayerState()
return Player.CharData.PlayerState.Value
end
function setPlayerState(Value)
updateCharData("PlayerState", Value)
end
Plugin['_InternalSetPlayerStateEvent']:Connect(function(Value)
setPlayerState(Value)
end)
Plugin['_InternalSetSetRunStateEvent']:Connect(function(Value)
updateCharData("RunState", Value == true)
end)
Plugin['_InternalSetRunDecayEvent']:Connect(function(Value)
RunDecay = math.min(1, math.max(0, Value))
end)
Plugin['_InternalSetSetSitStateEvent']:Connect(function(Value)
Sitting = Value ~= nil and Value ~= false
end)
Plugin['_InternalSetJumpFatigueEvent']:Connect(function(Value)
JumpFatigue = math.min(1, math.max(0, Value))
end)
Plugin['_InternalSetLadderEvent']:Connect(function(Value)
setLadder(Value)
end)
Plugin['IsClimbing']:SetOnInvoke(function()
return isClimbing()
end)
Plugin['GetTouchingParts']:SetOnInvoke(function()
return TouchingParts
end)
function isClimbing()
return CurrentLadder and true or false
end
function setLadder(LadderObject)
if ( not LadderObject or typeof(LadderObject) ~= "Instance" ) then
CurrentLadder = nil
updateCharData("Ladder", nil)
return
end
local Top = LadderObject:FindFirstChild("Top")
if ( not Top or not Top:IsA("Attachment") ) then
return
end
local Bottom = LadderObject:FindFirstChild("Bottom")
if ( not Bottom or not Bottom:IsA("Attachment") ) then
return
end
CurrentLadder = LadderObject
updateCharData("Ladder", LadderObject)
local ClosestPoint = getNearestPointToLadder()
local FootPosition = getFootPosition(Capsule.Position)
local PushVector = (FootPosition - ClosestPoint).Unit * 0.1
Capsule.Velocity = Vector3.new(0,0,0)
Capsule.CFrame = CFrame.new(Capsule.Position + PushVector)
--Teleport(CFrame.new(FootPosition + PushVector))
end
function getNearestPointToLadder()
if (not isClimbing()) then
return nil
end
local FootPosition = getFootPosition(Capsule.Position)
return getClosestPointOnLine(FootPosition, CurrentLadder.Top.WorldPosition, CurrentLadder.Bottom.WorldPosition)
end
function getLadderVector()
if ( not isClimbing() ) then
return Vector3.new()
end
return (CurrentLadder.Top.WorldPosition - CurrentLadder.Bottom.WorldPosition).Unit
end
function getClosestPointOnLine(v, a, b)
local ba = b-a
local length = ba.Magnitude
local unitba = ba.Unit
local va = v-a
local vadotba = a:Dot(unitba)
return a + (unitba*vadotba)
end
function GetTouchingParts()
local TouchingParts = Collider:GetTouchingParts()
local Parts = {}
for i = 1, #TouchingParts do
local v = TouchingParts[i]
if ( not v:IsDescendantOf(Character) and not v:IsDescendantOf(workspace.CurrentCamera) ) then
Parts[#Parts+1] = v
end
end
return Parts
end
function collisionTest(Transform)
local OldTransform = Capsule.CFrame
Capsule.CFrame = Transform
local Parts = GetTouchingParts()
Capsule.CFrame = OldTransform
return (#Parts>0),Parts
end
function Teleport(Transformation)
warn("Request to teleport", Transformation)
LastValidFloorPosition = Transformation.Position
FootPosition = getFootPosition(Transformation.Position)
GoodPositionCheck1 = FootPosition
GoodPositionCheck2 = FootPosition
if ( HumanoidRootPart ) then HumanoidRootPart.CFrame = Transformation end
if ( Capsule ) then Capsule.CFrame = Transformation end
if ( Collider ) then Collider.CFrame = Transformation end
pcall(function()
HumanoidRootPart.BodyPosition.Position = Transformation.Position
end)
end
local LastTeleportTransform = nil
local Teleporting = false
game.ReplicatedStorage.TeleportPlayer.OnClientEvent:Connect(function(Transformation)
BadBoy = false
BadBoyTicks = 0
Teleporting = true
LastTeleportTransform = Transformation
Teleport(Transformation)
game:GetService("RunService").Heartbeat:Wait()
if ( LastTeleportTransform ~= Transformation ) then
Teleporting = false
return
end
Teleport(Transformation)
Teleporting = false
BadBoy = false
BadBoyTicks = 0
end)
-- Update
game.ReplicatedStorage['ServerUpdateEvent'].OnClientEvent:Connect(function(ConfigPacket)
local Config = {}
local len = BinaryUtil:ReadInt(ConfigPacket)
for i=1,len do
Config[BinaryUtil:ReadString(ConfigPacket)] = BinaryUtil:ReadString(ConfigPacket)
end
WalkSpeedMultiplier = tonumber(Config['WalkSpeedMultiplier']) or WalkSpeedMultiplier
SLOPE_ANGLE = tonumber(Config['SlopeAngle']) or SLOPE_ANGLE
end)
function getFootPosition(CenterPosition)
return CenterPosition - Vector3.new(0, getHeight()/2, 0)
end
local AirVelocity = Vector3.new()
function findGround(Delta, OptionalRepositionCharacter)
if ( OptionalRepositionCharacter == nil ) then
OptionalRepositionCharacter = true
end
local StepHeight = getCharacterConfig():GetAttribute("StepHeight")
local HeightOffset = getHeight()/2
local PotentialAirVelocity = getVelocity()
local ClosestResult = nil
local IsOnSlope = false
local Results = {}
if ( getVelocity().Y <= 0 or isOnGround() ) then
local yD = getVelocity().Y*Delta
local NextFrameOffset = getFlatVelocity()*Delta
local RayCenter = LastValidFloorPosition + NextFrameOffset + Vector3.new(0, StepHeight, 0)
local RayDirection = Vector3.new(0, -(0.1 + NextFrameOffset.Magnitude + StepHeight) + yD, 0)
local RayDirectionUp = Vector3.new(0, Capsule.Position.Y + HeightOffset - RayCenter.Y, 0)
-- Ray stuff
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.CollisionGroup = "PlayerGroup"
raycastParams.FilterDescendantsInstances = {Character, workspace.CurrentCamera}
raycastParams.IgnoreWater = true
local function cast(Origin, Direction)
return workspace:Raycast(Origin, Direction, raycastParams)
end
-- Cast all the rays around the player
Results[#Results+1] = cast(RayCenter, RayDirection)
local Rays = 7
local Rings = 3
for j=1,Rings do
for i=1,(Rays-(j-1)) do
local direction = ((i-1)/Rays * math.pi * 2)+j
local dist = (j/Rings)*getRadius()
local offset = RayCenter + Vector3.new(math.cos(direction)*dist, 0, math.sin(direction)*dist)
local Oof = cast(offset, RayDirectionUp)
if ( Oof ) then
Results[#Results+1] = nil
else
Results[#Results+1] = cast(offset, RayDirection)
end
end
end
-- Find which ray is the closest
local ClosestDist = math.huge
for i = 1, #Results do
local RayResult = Results[i]
if ( RayResult and RayResult.Normal.Y >= 0.025 ) then
local Dist = FootPosition.Y - RayResult.Position.Y + (1.0-RayResult.Normal.Y)
if ( Dist < ClosestDist * 0.95 ) then
ClosestDist = Dist
ClosestResult = RayResult
end
end
end
end
-- Snap player to ray position
local OnGround = false
local IsSliding = false
local FloorMaterial = Enum.Material.Air
local NewCapsuleCFrame = Capsule.CFrame
if ( ClosestResult ) then
local HitPosition = ClosestResult.Position
local NewFloorPosition = Vector3.new(Capsule.Position.X, HitPosition.Y, Capsule.Position.Z)
NewCapsuleCFrame = CFrame.new(NewFloorPosition+Vector3.new(0, HeightOffset, 0))
if ( OptionalRepositionCharacter ) then
local WillBeOnGround,WillBeSliding,_,_,NewTransform = findGround(Delta, false)
local IsSteppingUp = (NewCapsuleCFrame.Position.Y-Capsule.Position.Y) > StepHeight * 0.1
local HasCollisionAtNewLocation = collisionTest(NewCapsuleCFrame)
local WillCollideStep = HasCollisionAtNewLocation and IsSteppingUp
-- If ((we're not on the ground) OR (we are on the ground but will not BE sliding)) AND (we are not colliding with a step)
if ( (not isOnGround() or (isOnGround() and not WillBeSliding)) and not WillCollideStep ) then
Capsule.CFrame = NewCapsuleCFrame+Vector3.new(0, CONST_EPSILON, 0)
LastValidFloorPosition = NewFloorPosition
else -- In this case we cannot step up
--local LastValidPosition = Capsule.Position - Vector3.new(0, Capsule.Position.Y - (LastValidFloorPosition.Y + HeightOffset), 0)
--local LastValidPosition = LastValidFloorPosition + Vector3.new(0, HeightOffset, 0) + getVelocity()*Delta
--Capsule.CFrame = CFrame.new(LastValidPosition)
LastValidFloorPosition = Vector3.new(Capsule.Position.X, LastValidFloorPosition.Y, Capsule.Position.Z)
end
--LastValidFloorPosition = NewFloorPosition
end
-- Kind of bad sliding
local SurfaceNormal = ClosestResult.Normal
if ( SurfaceNormal.Y < SLOPE_ANGLE - (getVelocity().Y/64) ) then
if ( OptionalRepositionCharacter ) then
local SlopeVector = SurfaceNormal * getVelocity():Dot(SurfaceNormal) * -1
Capsule.Velocity = Capsule.Velocity + SlopeVector
end
IsSliding = true
else
Capsule.Velocity = getFlatVelocity()
end
LastVelocity = Capsule.Velocity
OnGround = true
FloorObject = ClosestResult.Instance
FloorMaterial = ClosestResult.Material
if ( FloorObject ) then
-- CHECK FOR TERRAIN
local gridSize = 1.5;
local GridVec = Vector3.new( gridSize, gridSize, gridSize )
local region = Region3.new( NewFloorPosition - GridVec, NewFloorPosition + GridVec ):ExpandToGrid(gridSize);
local materials, occupancy = game.Workspace.Terrain:ReadVoxels( region, 4 );
for x = 1, materials.Size.X do
for y = 1, materials.Size.Y do
for z = 1, materials.Size.Z do
local material = materials[x][y][z];
if ( material == Enum.Material.Water ) then
FloorMaterial = material;
end
end
end
end
-- Force sounds
if ( FloorObject.Name == "METAL" ) then
FloorMaterial = Enum.Material.Metal;
end
if ( FloorObject.Name == "WOOD" ) then
FloorMaterial = Enum.Material.Wood;
end
if ( FloorObject.Name == "WATER" ) then
FloorMaterial = Enum.Material.Water;
end
if ( FloorObject.Name == "DIRT" ) then
FloorMaterial = Enum.Material.Mud;
end
if ( FloorObject.Name == "SNOW" ) then
FloorMaterial = Enum.Material.Snow;
end
end
else
FloorObject = nil
if ( OptionalRepositionCharacter ) then
LastValidFloorPosition = Capsule.Position-Vector3.new(0, HeightOffset, 0)
end
end
if ( not OnGround or IsSliding ) then
AirVelocity = PotentialAirVelocity
end
return OnGround, IsSliding, FloorMaterial, FloorObject, NewCapsuleCFrame
end
function getForwardVector()
local _,Yaw,_ = game.Workspace.CurrentCamera.CFrame:ToOrientation()
return (CFrame.fromEulerAnglesXYZ(0, Yaw, 0)*CFrame.new(0, 0, -1)).Position
end
function movement(Delta)
if ( not Humanoid ) then
return
end
if ( not Capsule ) then
return
end
if ( Sitting ) then
return
end
checkSitting()
-- Find movement vector
MovementVector = Humanoid.MoveDirection*ControlModule:GetMoveVector().Magnitude
if ( MovementVector.Magnitude > 1 ) then
MovementVector = MovementVector.Unit
end
-- Cant move if legacy parts are anchored :(
if ( Humanoid.WalkSpeed == 0 and Humanoid.RootPart.Anchored ) then
MovementVector = Vector3.new()
end
-- Cant do normal movement if on ladder
if ( isClimbing() ) then
local LadderVec = getLadderVector()
local ForwardVec = getForwardVector()
local LookVec = game.Workspace.CurrentCamera.CFrame.LookVector
local ClimbMultiplier = ForwardVec:Dot(MovementVector)
local ClimbAmount = LookVec:Dot(LadderVec) * 4
local ClimbSpeed = getCharacterConfig():GetAttribute("ClimbSpeed") or 3.0
local LadderDelta = LadderVec * ClimbAmount * ClimbMultiplier * Delta * ClimbSpeed
LadderPart.CFrame = CFrame.new(LadderPart.Position + LadderDelta)
Capsule.CFrame = CFrame.new(Capsule.Position + LadderDelta)
if ( getFootPosition(Capsule.Position).Y > CurrentLadder.Top.WorldPosition.Y ) then
setLadder(nil)
elseif ( getFootPosition(Capsule.Position).Y + (getHeight() * 0.9) < CurrentLadder.Bottom.WorldPosition.Y ) then
setLadder(nil)
else
MovementVector = Vector3.new()
end
end
-- Acceleration
game.Players.LocalPlayer:Move(MovementVector)
local FinalFlatVelocity = Movement:Move(Player, MovementVector, getFlatVelocity(), Delta, getCharacterConfig(), RunDecay*WalkSpeedMultiplier)
Capsule.Velocity = FinalFlatVelocity + Vector3.new(0, getVelocity().Y, 0)
LastVelocity = Capsule.Velocity
-- Compute Speed
local Speed = FinalFlatVelocity.Magnitude
Plugin.Running:Fire(game.Players.LocalPlayer, Speed)
updateCharData("Speed", FinalFlatVelocity.Magnitude)
local CurrentFootPosition = getFootPosition(Capsule.Position)
local BadDist = GoodPositionCheck1 and (CurrentFootPosition-GoodPositionCheck1).Magnitude or 0
local TimeSinceStart = workspace.DistributedGameTime - StartTime
if ( BadDist > 1 and not Teleporting and TimeSinceStart > 5 ) then
BadBoyTicks = BadBoyTicks + 1
end
if ( _G.Speed or _G.settings ) then
BadBoy = true
end
GoodPositionCheck2 = CurrentFootPosition
GoodPositionCheck2Velocity = LastVelocity
end
function update()
if ( Humanoid ) then
--print(Sitting, Humanoid:GetState())
--if ( Sitting and Humanoid:GetState() ~= Enum.HumanoidStateType.Seated ) then
-- Sitting = false
--end
if ( Sitting ) then
Humanoid:SetStateEnabled(Enum.HumanoidStateType.Seated, true)
Humanoid:ChangeState(Enum.HumanoidStateType.Seated)
elseif ( isOnGround() ) then
Humanoid:SetStateEnabled(Enum.HumanoidStateType.Freefall, false)
Humanoid:ChangeState(Enum.HumanoidStateType.RunningNoPhysics)
elseif ( getCharData("IsSliding") ) then
Humanoid:SetStateEnabled(Enum.HumanoidStateType.Freefall, true)
Humanoid:ChangeState(Enum.HumanoidStateType.Freefall)
else
Humanoid:SetStateEnabled(Enum.HumanoidStateType.Freefall, true)
Humanoid:ChangeState(Enum.HumanoidStateType.Freefall)
end
end
--print("A", Humanoid:GetState())
end
function platformMove(Delta)
if ( not Capsule ) then
return
end
if ( Sitting ) then
return
end
-- Move with platform
if ( FloorObject ) then
Capsule.CFrame = Capsule.CFrame + (FloorObject.Velocity*Delta)
local OriginVectorWorld = Capsule.CFrame.Position-FloorObject.Position
local OriginVectorLocal = FloorObject.CFrame:toObjectSpace(Capsule.CFrame).Position
local FlootObjectRotation = FloorObject.CFrame - FloorObject.Position
local RotationMatrix = CFrame.fromEulerAnglesXYZ(FloorObject.RotVelocity.X*Delta, FloorObject.RotVelocity.Y*Delta, FloorObject.RotVelocity.Z*Delta)
local RotatedOffset = RotationMatrix*OriginVectorWorld
Capsule.CFrame = Capsule.CFrame + (RotatedOffset-OriginVectorWorld)
end
end
function onStep(Delta)
if ( not Capsule ) then
return
end
if ( not HumanoidRootPart ) then
return
end
checkSitting()
-- Update size
local StepHeight = getCharacterConfig():GetAttribute("StepHeight")
CapsuleUtil:SetSize(CapsuleParts, getRadius(), getHeight(), StepHeight)
-- Reset physics
Capsule.CFrame = CFrame.new(Capsule.CFrame.Position)
Capsule.RotVelocity = Vector3.new(0, 0, 0)
-- Find touching parts
TouchingParts = GetTouchingParts()
for i = 1, #TouchingParts do
Plugin['OnTouch']:Fire(TouchingParts[i])
end
-- Check for ground
if ( not Sitting ) then
local OnGround, Sliding, FloorMaterial, FloorObject = findGround(Delta)
setGroundState((OnGround and not Sliding) and "Ground" or "Air")
updateCharData("OnGround", OnGround)
updateCharData("IsSliding", Sliding)
updateCharData("FloorMaterial", FloorMaterial.Name)
updateCharData("FloorObject", FloorObject)
updateCharData("Velocity", LastVelocity)
end
update()
end
function checkSitting()
if ( Humanoid and not Humanoid.Sit and Sitting ) then
Sitting = false
end
if ( Humanoid and Humanoid.SeatPart ) then
Sitting = true
end
--[[for _,v in pairs(HumanoidRootPart:GetJoints()) do
if ( v:IsA("Seat") or v:IsA("VehicleSeat") ) then
Sitting = true
end
end]]
end
local MovementYaw = 0
function onRender(Delta)
if ( not Capsule ) then
return
end
if ( not HumanoidRootPart ) then
return
end
if ( Sitting ) then
FootPosition = HumanoidRootPart.Position
return
end
checkSitting()
if ( MovementVector and MovementVector.Magnitude > 0 ) then
_,MovementYaw,_ = CFrame.new(Vector3.new(), MovementVector):ToOrientation()
end
Capsule.Anchored = HumanoidRootPart.Anchored
Collider.Anchored = HumanoidRootPart.Anchored
if ( Paused or Sitting ) then
Capsule.Position = HumanoidRootPart.Position + Vector3.new(0, getHeight()/2, 0)
end
FootPosition = getFootPosition(Capsule.Position)
-- Update humanoid root part
if ( not Sitting and Humanoid.Health > 0 ) then
-- Orientation
if ( Player:FindFirstChild("CameraYaw") ) then
local BodyGyro = HumanoidRootPart:FindFirstChildOfClass("BodyGyro")
if ( BodyGyro ) then
BodyGyro.CFrame = CFrame.fromEulerAnglesXYZ(0, Player.CameraYaw.Value, 0)
end
end
-- Position Player
local BodyPosition = HumanoidRootPart:FindFirstChildOfClass("BodyPosition")
if ( FootPosition and FootPosition == FootPosition and BodyPosition and FootPosition.Magnitude > 0.1 ) then
BodyPosition.Position = FootPosition
end
local FootCFrame = CFrame.new(FootPosition) * (HumanoidRootPart.CFrame-HumanoidRootPart.Position)
HumanoidRootPart.CFrame = FootCFrame
HumanoidRootPart.Velocity = LastVelocity
HumanoidRootPart.AssemblyAngularVelocity = Vector3.new(0, 0, 0)
end
update()
end
function prestep(_, Delta)
if ( Collider ) then
Collider.CanCollide = not Sitting
end
-- Force ladder part under feet
if ( LadderPart ) then
if ( CurrentLadder ) then
LadderPart.Material = CurrentLadder.Material
end
LadderPart.CFrame = CFrame.new(FootPosition - Vector3.new(0, LadderPart.Size.Y/2, 0))
LadderPart.Parent = isClimbing() and workspace or nil
end
movement(Delta)
end
local function heartbeat(Delta)
Delta = math.min(1, Delta)
TimeAlive = TimeAlive + Delta
-- Check for bad boy
if ( GoodPositionCheck2 and GoodPositionCheck2Velocity and Capsule and not Sitting and not Teleporting ) then
local NextBestPosition = GoodPositionCheck2 + GoodPositionCheck2Velocity*Delta
local NextActualPosition = getFootPosition(Capsule.Position)
local Origin = GoodPositionCheck2
local v1 = (NextBestPosition-Origin).Unit
local v2 = (NextActualPosition-Origin).Unit
local d1 = (NextBestPosition-Origin).Magnitude
local d2 = (NextActualPosition-Origin).Magnitude
local dp = (d1+d2 > 0.1) and v1:Dot(v2) or 1
local DidABadBoy = false
if ( (d2 * 1.0)>(d1 * 1.1 + 0.5) and TimeAlive > 1) then
--BadBoyTicks = BadBoyTicks + 1
DidABadBoy = true
end
if ( (dp == dp) and dp < 0 and TimeAlive > 1 ) then
--BadBoyTicks = BadBoyTicks - (dp * 0.5)
DidABadBoy = true
end
if ( not DidABadBoy ) then
BadBoyTicks = math.max(BadBoyTicks-1, 0)
end
if ( BadBoyTicks > 24 ) then
BadBoy = true
end
end
CanUpdateNetwork = true
platformMove(Delta)
onStep(Delta)
--CanUpdateNetwork = false
onRender(Delta)
onEnd(Delta)
end
local LastSend = tick() + 1
function sendConfigChanges()
if ( tick() - LastSend < 1/10 ) then
return
end
LastSend = tick()
-- Send changes
for k,v in cpairs(NetworkToUpdate) do
print("SENDING", k, v)
game.ReplicatedStorage.CustomCharacter.Remote.Update:FireServer(k, v)
end
NetworkToUpdate = {}
end
function sendCapsulePacket()
-- Send capsule packet
local Packet = {}
BinaryUtil:WriteVector3(Packet, FootPosition or Vector3.new())
local x = 32000
local BadBoyVal = math.random(1,x) + (BadBoy and x or 0)
local SittingVal = math.random(1,x) + (Sitting and x or 0)
BinaryUtil:WriteShort(Packet, BadBoyVal)
BinaryUtil:WriteShort(Packet, SittingVal)
game.ReplicatedStorage.CustomCharacter.Remote.UpdateCollider:FireServer(Packet)
end
function onEnd(Delta)
sendConfigChanges()
sendCapsulePacket()
if ( Capsule ) then
GoodPositionCheck1 = getFootPosition(Capsule.Position)
end
end
game:GetService("RunService").Stepped:Connect(prestep)
game:GetService("RunService").Heartbeat:Connect(heartbeat)
game:GetService("RunService"):BindToRenderStep("RenderCharacter", Enum.RenderPriority.Camera.Value-1024, onRender)
-- Start
Player.CharacterAdded:Connect(newCharacter)
newCharacter(Player.Character)
|
--
-- ,gggg,
-- d8" "8I ,dPYb,
-- 88 ,dP IP'`Yb
-- 8888888P" I8 8I
-- 88 I8 8'
-- 88 gg gg ,g, I8 dPgg,
-- ,aa,_88 I8 8I ,8'8, I8dP" "8I
-- dP" "88P I8, ,8I ,8' Yb I8P I8
-- Yb,_,d88b,,_ ,d8b, ,d8b,,8'_ 8) ,d8 I8,
-- "Y8P" "Y888888P'"Y88P"`Y8P' "YY8P8P88P `Y8
--
-- This is the lush quickstart tutorial, it provides a basic overview
-- of the lush experience and API.
--
-- First, enable lush.ify on this file, run:
--
-- `:Lushify`
--
-- or
--
-- `:lua require('lush').ify()`
--
-- (try putting your cursor inside the ` and typing yi`:@"<CR>)
--
-- Calls to hsl()/hsluv() are now highlighted with the correct background colour
-- Highlight names groups will have the highlight style applied to them.
local lush = require('lush')
local hsl = lush.hsl
-- You may also use the HSLuv colorspace, see http://www.hsluv.org/ and h: lush-hsluv-colors.
-- Replace calls to hsl() with hsluv()
-- local hsluv = lush.hsluv
-- HSL stands for Hue (0 - 360)
-- Saturation (0 - 100)
-- Lightness (0 - 100)
--
-- By working with HSL, it's easy to define relationships between colours.
local sea_foam = hsl(208, 80, 80) -- Vim has a mapping, <n>C-a and <n>C-x to
local sea_crest = hsl(208, 90, 30) -- increment or decrement integers, or
local sea_deep = hsl(208, 90, 10) -- you can just type them normally.
local sea_gull = hsl("#c6c6c6") -- Or use hex form, preceeded with a #.
-- Note: Some CursorLine highlighting will obscure any other highlighing on the
-- current line until you move your cursor.
--
-- You can disable the cursor line temporarily with:
--
-- `setlocal nocursorline`
-- Lush.hsl provides a number of conveniece functions for:
--
-- Relative adjustment: rotate(), saturate(), desaturate(), lighten(), darken()
-- aliased to ro(), sa() de(), li(), da(), mix(), readable()
-- Overide: hue(), saturation(), lightness()
-- Access: .h, .s, .l
-- Coercion: tostring(), "Concatenation: " .. color
-- To define our colour scheme, we will write what is called a lush-spec.
-- We will use lush.hsl as an aid.
-- A lush-spec function which returns a table, which defines our
-- highlight groups. It's usage is much simpler than it reads.
-- We'll define our lush-spec below.
-- Call lush with our lush-spec.
local theme = lush(function()
return {
-- It's recommended to disable wrapping with `setlocal nowrap`. You may
-- also receive (mostly ignorable) linter/lsp warnings, because our lua is
-- a bit more dynamic than they expect. You may also wish to disable those
-- while editing your theme if they produce a lot of visual noise.
-- lush-spec statements are in the form:
--
-- <HighlightGroupName> { bg = <hsl>, fg = <hsl>, sp = <hsl>, gui = <string>},
--
-- Any vim highlight group name is valid, and any unrecognized key is
-- omitted.
--
-- Lets define our "Normal" highlight group, using our sea colours.
-- Set a highlight group from the hsl variables we defined at the start
-- Uncomment "Normal"
-- Normal { bg = sea_deep, fg = sea_foam }, -- normal text
-- You should be on the water now, Lush.ify has automatically recognized
-- our Highlight definition and applied it in real time.
-- Lush is most useful when you use previously defined groups aid in
-- picking colours for future groups.
--
-- For example, lets set our cursorline (if disabled: `setlocal cursorline`)
-- to be slightly lighter than our normal background.
-- Set a highlight group from another highlight group
-- CursorLine { bg = Normal.bg.lighten(5) }, -- Screen-line at the cursor, when 'cursorline' is set. Low-priority if foreground (ctermfg OR guifg) is not set.
-- Or maybe lets style our visual selection to match Cusorlines background,
-- and render text in Normal's foreground complement.
-- Visual { bg = CursorLine.bg, fg = Normal.fg.rotate(180) },
-- We can also link a group to another group. These will inherit all of the
-- linked group options (See h: hi-link). (`setlocal cursorcolumn`)
-- CursorColumn { CursorLine },
-- We can make white space characters slighly visible
-- Whitespace { fg = Normal.bg.desaturate(25).lighten(25) },
-- We can inherit properties if we want to tweak a group slightly
-- Note: This looks similar to a link, but the defined group will have its
-- own properties, cloned from the parent.
-- Lets make Comments look like Whitespace, but with italics
-- Comment { Whitespace, gui="italic" },
-- Here's how we might set our line numbers to be relational to Normal,
-- note that we're also using some function aliases, see the readme for more
-- information.
-- (`setlocal number`)
-- LineNr { bg = Normal.bg.da(10), fg = Normal.bg.li(5) }, -- Line number for ":number" and ":#" commands, and when 'number' or 'relativenumber' option is set.
-- CursorLineNr { bg = CursorLine.bg, fg = Normal.fg.ro(180) }, -- Like LineNr when 'cursorline' or 'relativenumber' is set for the cursor line.
-- You can also use highlight groups to define "base" colors, if you dont
-- want to use regular Lua variables. They will behave in the same way.
-- Note that these groups *will* be defined as a vim-highlight-group, so
-- try not to pick names that might end up being used by something else.
--
-- CamelCase is by tradition but you don't have to use it.
-- search_base { bg = hsl(52, 52, 52), fg = hsl(52, 10, 10) },
-- Search { search_base },
-- IncSearch { bg = search_base.bg.ro(-20), fg = search_base.fg.da(90) },
-- We can also mix colours together
-- Type { fg = Normal.fg.mix(LineNr.fg, 30) }
-- And that's the basics of using Lush!
--
-- For more information, see the README and :h lush or run :LushRunTutorial
}
end)
-- return our parsed theme for extension or use else where.
return theme
-- vi:nowrap:number
|
import "aergo-contract-ex/typecheck"
import "./token.lua"
state.var {
_meta = state.map(), -- string -> (string or number)
}
Detailed = Object(Token, {
init = typecheck('string', 'string', 'number')(function (name, symbol, decimals)
_meta['name'] = name
_meta['symbol'] = symbol
_meta['decimals'] = decimals
end),
name = typecheck('->', 'string')(function ()
return _meta['name']
end),
symbol = typecheck('->', 'string')(function ()
return _meta['symbol']
end),
decimals = typecheck('->', 'number')(function ()
return _meta['decimals']
end),
})
|
a = "hello" .. "world"
--t.n = t.n + 1
print(a)
print("========分割线==========")
x = 1
a, b = 10, 2 * x
print(a)
print(b)
print("========分割线==========")
--x, y = y, x -- swap 'x' for 'y'
--a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[i]'
print("========分割线==========")
a, b, c = 0, 1
print(a,b,c) --> 0 1 nil
a, b = a + 1, b + 1, b + 2 -- value of b+2 is ignored
print(a,b) --> 1 2
a, b, c = 0
print(a,b,c) --> 0 nil nil
a, b, c = 0, 0, 0
print(a,b,c)
--a, b = f()
x = 10
local i = 1 -- local to the chunk
while i <= x do
local x = i * 2
print(x)
i = i + 1
end
if i > 20 then
local x = 20 -- local to the "then" body
print(x + 2)
else
print(x) --> 10 (the gloval one)
end
print(x) --> 10 (the global one)
do
local a2 = 2 * a
local d = sqrt(b^2 - 4 * a * c)
x1 = (-b + d) / a2
x2 = (-b - d) / a2
end
print(x1,x2)
for i = 10,1,-1 do
print(i)
end
for i = 1,10 do
print(i)
end
max = i
local found = nil
for i = 1,a,n do
if a[i] == value then
found = i --save value of 'i'
break
end
end
print(found)
local i = 1
while a[i] do
if a[i] == v then
break
end
i = i + 1
end
|
--[[
Copyright 2019 Tyler Richard Hoyer
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 GF8x2 = {
[0]=0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e,0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e,
0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e,0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e,
0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e,0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e,
0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e,0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e,
0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e,0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e,
0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae,0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe,
0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce,0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde,
0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee,0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe,
0x1b,0x19,0x1f,0x1d,0x13,0x11,0x17,0x15,0x0b,0x09,0x0f,0x0d,0x03,0x01,0x07,0x05,
0x3b,0x39,0x3f,0x3d,0x33,0x31,0x37,0x35,0x2b,0x29,0x2f,0x2d,0x23,0x21,0x27,0x25,
0x5b,0x59,0x5f,0x5d,0x53,0x51,0x57,0x55,0x4b,0x49,0x4f,0x4d,0x43,0x41,0x47,0x45,
0x7b,0x79,0x7f,0x7d,0x73,0x71,0x77,0x75,0x6b,0x69,0x6f,0x6d,0x63,0x61,0x67,0x65,
0x9b,0x99,0x9f,0x9d,0x93,0x91,0x97,0x95,0x8b,0x89,0x8f,0x8d,0x83,0x81,0x87,0x85,
0xbb,0xb9,0xbf,0xbd,0xb3,0xb1,0xb7,0xb5,0xab,0xa9,0xaf,0xad,0xa3,0xa1,0xa7,0xa5,
0xdb,0xd9,0xdf,0xdd,0xd3,0xd1,0xd7,0xd5,0xcb,0xc9,0xcf,0xcd,0xc3,0xc1,0xc7,0xc5,
0xfb,0xf9,0xff,0xfd,0xf3,0xf1,0xf7,0xf5,0xeb,0xe9,0xef,0xed,0xe3,0xe1,0xe7,0xe5
}
local GF8x3 = {
[0]=0x00,0x03,0x06,0x05,0x0c,0x0f,0x0a,0x09,0x18,0x1b,0x1e,0x1d,0x14,0x17,0x12,0x11,
0x30,0x33,0x36,0x35,0x3c,0x3f,0x3a,0x39,0x28,0x2b,0x2e,0x2d,0x24,0x27,0x22,0x21,
0x60,0x63,0x66,0x65,0x6c,0x6f,0x6a,0x69,0x78,0x7b,0x7e,0x7d,0x74,0x77,0x72,0x71,
0x50,0x53,0x56,0x55,0x5c,0x5f,0x5a,0x59,0x48,0x4b,0x4e,0x4d,0x44,0x47,0x42,0x41,
0xc0,0xc3,0xc6,0xc5,0xcc,0xcf,0xca,0xc9,0xd8,0xdb,0xde,0xdd,0xd4,0xd7,0xd2,0xd1,
0xf0,0xf3,0xf6,0xf5,0xfc,0xff,0xfa,0xf9,0xe8,0xeb,0xee,0xed,0xe4,0xe7,0xe2,0xe1,
0xa0,0xa3,0xa6,0xa5,0xac,0xaf,0xaa,0xa9,0xb8,0xbb,0xbe,0xbd,0xb4,0xb7,0xb2,0xb1,
0x90,0x93,0x96,0x95,0x9c,0x9f,0x9a,0x99,0x88,0x8b,0x8e,0x8d,0x84,0x87,0x82,0x81,
0x9b,0x98,0x9d,0x9e,0x97,0x94,0x91,0x92,0x83,0x80,0x85,0x86,0x8f,0x8c,0x89,0x8a,
0xab,0xa8,0xad,0xae,0xa7,0xa4,0xa1,0xa2,0xb3,0xb0,0xb5,0xb6,0xbf,0xbc,0xb9,0xba,
0xfb,0xf8,0xfd,0xfe,0xf7,0xf4,0xf1,0xf2,0xe3,0xe0,0xe5,0xe6,0xef,0xec,0xe9,0xea,
0xcb,0xc8,0xcd,0xce,0xc7,0xc4,0xc1,0xc2,0xd3,0xd0,0xd5,0xd6,0xdf,0xdc,0xd9,0xda,
0x5b,0x58,0x5d,0x5e,0x57,0x54,0x51,0x52,0x43,0x40,0x45,0x46,0x4f,0x4c,0x49,0x4a,
0x6b,0x68,0x6d,0x6e,0x67,0x64,0x61,0x62,0x73,0x70,0x75,0x76,0x7f,0x7c,0x79,0x7a,
0x3b,0x38,0x3d,0x3e,0x37,0x34,0x31,0x32,0x23,0x20,0x25,0x26,0x2f,0x2c,0x29,0x2a,
0x0b,0x08,0x0d,0x0e,0x07,0x04,0x01,0x02,0x13,0x10,0x15,0x16,0x1f,0x1c,0x19,0x1a
}
local GF8x9 = {
[0]=0x00,0x09,0x12,0x1b,0x24,0x2d,0x36,0x3f,0x48,0x41,0x5a,0x53,0x6c,0x65,0x7e,0x77,
0x90,0x99,0x82,0x8b,0xb4,0xbd,0xa6,0xaf,0xd8,0xd1,0xca,0xc3,0xfc,0xf5,0xee,0xe7,
0x3b,0x32,0x29,0x20,0x1f,0x16,0x0d,0x04,0x73,0x7a,0x61,0x68,0x57,0x5e,0x45,0x4c,
0xab,0xa2,0xb9,0xb0,0x8f,0x86,0x9d,0x94,0xe3,0xea,0xf1,0xf8,0xc7,0xce,0xd5,0xdc,
0x76,0x7f,0x64,0x6d,0x52,0x5b,0x40,0x49,0x3e,0x37,0x2c,0x25,0x1a,0x13,0x08,0x01,
0xe6,0xef,0xf4,0xfd,0xc2,0xcb,0xd0,0xd9,0xae,0xa7,0xbc,0xb5,0x8a,0x83,0x98,0x91,
0x4d,0x44,0x5f,0x56,0x69,0x60,0x7b,0x72,0x05,0x0c,0x17,0x1e,0x21,0x28,0x33,0x3a,
0xdd,0xd4,0xcf,0xc6,0xf9,0xf0,0xeb,0xe2,0x95,0x9c,0x87,0x8e,0xb1,0xb8,0xa3,0xaa,
0xec,0xe5,0xfe,0xf7,0xc8,0xc1,0xda,0xd3,0xa4,0xad,0xb6,0xbf,0x80,0x89,0x92,0x9b,
0x7c,0x75,0x6e,0x67,0x58,0x51,0x4a,0x43,0x34,0x3d,0x26,0x2f,0x10,0x19,0x02,0x0b,
0xd7,0xde,0xc5,0xcc,0xf3,0xfa,0xe1,0xe8,0x9f,0x96,0x8d,0x84,0xbb,0xb2,0xa9,0xa0,
0x47,0x4e,0x55,0x5c,0x63,0x6a,0x71,0x78,0x0f,0x06,0x1d,0x14,0x2b,0x22,0x39,0x30,
0x9a,0x93,0x88,0x81,0xbe,0xb7,0xac,0xa5,0xd2,0xdb,0xc0,0xc9,0xf6,0xff,0xe4,0xed,
0x0a,0x03,0x18,0x11,0x2e,0x27,0x3c,0x35,0x42,0x4b,0x50,0x59,0x66,0x6f,0x74,0x7d,
0xa1,0xa8,0xb3,0xba,0x85,0x8c,0x97,0x9e,0xe9,0xe0,0xfb,0xf2,0xcd,0xc4,0xdf,0xd6,
0x31,0x38,0x23,0x2a,0x15,0x1c,0x07,0x0e,0x79,0x70,0x6b,0x62,0x5d,0x54,0x4f,0x46
}
local GF8x11 = {
[0]=0x00,0x0b,0x16,0x1d,0x2c,0x27,0x3a,0x31,0x58,0x53,0x4e,0x45,0x74,0x7f,0x62,0x69,
0xb0,0xbb,0xa6,0xad,0x9c,0x97,0x8a,0x81,0xe8,0xe3,0xfe,0xf5,0xc4,0xcf,0xd2,0xd9,
0x7b,0x70,0x6d,0x66,0x57,0x5c,0x41,0x4a,0x23,0x28,0x35,0x3e,0x0f,0x04,0x19,0x12,
0xcb,0xc0,0xdd,0xd6,0xe7,0xec,0xf1,0xfa,0x93,0x98,0x85,0x8e,0xbf,0xb4,0xa9,0xa2,
0xf6,0xfd,0xe0,0xeb,0xda,0xd1,0xcc,0xc7,0xae,0xa5,0xb8,0xb3,0x82,0x89,0x94,0x9f,
0x46,0x4d,0x50,0x5b,0x6a,0x61,0x7c,0x77,0x1e,0x15,0x08,0x03,0x32,0x39,0x24,0x2f,
0x8d,0x86,0x9b,0x90,0xa1,0xaa,0xb7,0xbc,0xd5,0xde,0xc3,0xc8,0xf9,0xf2,0xef,0xe4,
0x3d,0x36,0x2b,0x20,0x11,0x1a,0x07,0x0c,0x65,0x6e,0x73,0x78,0x49,0x42,0x5f,0x54,
0xf7,0xfc,0xe1,0xea,0xdb,0xd0,0xcd,0xc6,0xaf,0xa4,0xb9,0xb2,0x83,0x88,0x95,0x9e,
0x47,0x4c,0x51,0x5a,0x6b,0x60,0x7d,0x76,0x1f,0x14,0x09,0x02,0x33,0x38,0x25,0x2e,
0x8c,0x87,0x9a,0x91,0xa0,0xab,0xb6,0xbd,0xd4,0xdf,0xc2,0xc9,0xf8,0xf3,0xee,0xe5,
0x3c,0x37,0x2a,0x21,0x10,0x1b,0x06,0x0d,0x64,0x6f,0x72,0x79,0x48,0x43,0x5e,0x55,
0x01,0x0a,0x17,0x1c,0x2d,0x26,0x3b,0x30,0x59,0x52,0x4f,0x44,0x75,0x7e,0x63,0x68,
0xb1,0xba,0xa7,0xac,0x9d,0x96,0x8b,0x80,0xe9,0xe2,0xff,0xf4,0xc5,0xce,0xd3,0xd8,
0x7a,0x71,0x6c,0x67,0x56,0x5d,0x40,0x4b,0x22,0x29,0x34,0x3f,0x0e,0x05,0x18,0x13,
0xca,0xc1,0xdc,0xd7,0xe6,0xed,0xf0,0xfb,0x92,0x99,0x84,0x8f,0xbe,0xb5,0xa8,0xa3
}
local GF8x13 = {
[0]=0x00,0x0d,0x1a,0x17,0x34,0x39,0x2e,0x23,0x68,0x65,0x72,0x7f,0x5c,0x51,0x46,0x4b,
0xd0,0xdd,0xca,0xc7,0xe4,0xe9,0xfe,0xf3,0xb8,0xb5,0xa2,0xaf,0x8c,0x81,0x96,0x9b,
0xbb,0xb6,0xa1,0xac,0x8f,0x82,0x95,0x98,0xd3,0xde,0xc9,0xc4,0xe7,0xea,0xfd,0xf0,
0x6b,0x66,0x71,0x7c,0x5f,0x52,0x45,0x48,0x03,0x0e,0x19,0x14,0x37,0x3a,0x2d,0x20,
0x6d,0x60,0x77,0x7a,0x59,0x54,0x43,0x4e,0x05,0x08,0x1f,0x12,0x31,0x3c,0x2b,0x26,
0xbd,0xb0,0xa7,0xaa,0x89,0x84,0x93,0x9e,0xd5,0xd8,0xcf,0xc2,0xe1,0xec,0xfb,0xf6,
0xd6,0xdb,0xcc,0xc1,0xe2,0xef,0xf8,0xf5,0xbe,0xb3,0xa4,0xa9,0x8a,0x87,0x90,0x9d,
0x06,0x0b,0x1c,0x11,0x32,0x3f,0x28,0x25,0x6e,0x63,0x74,0x79,0x5a,0x57,0x40,0x4d,
0xda,0xd7,0xc0,0xcd,0xee,0xe3,0xf4,0xf9,0xb2,0xbf,0xa8,0xa5,0x86,0x8b,0x9c,0x91,
0x0a,0x07,0x10,0x1d,0x3e,0x33,0x24,0x29,0x62,0x6f,0x78,0x75,0x56,0x5b,0x4c,0x41,
0x61,0x6c,0x7b,0x76,0x55,0x58,0x4f,0x42,0x09,0x04,0x13,0x1e,0x3d,0x30,0x27,0x2a,
0xb1,0xbc,0xab,0xa6,0x85,0x88,0x9f,0x92,0xd9,0xd4,0xc3,0xce,0xed,0xe0,0xf7,0xfa,
0xb7,0xba,0xad,0xa0,0x83,0x8e,0x99,0x94,0xdf,0xd2,0xc5,0xc8,0xeb,0xe6,0xf1,0xfc,
0x67,0x6a,0x7d,0x70,0x53,0x5e,0x49,0x44,0x0f,0x02,0x15,0x18,0x3b,0x36,0x21,0x2c,
0x0c,0x01,0x16,0x1b,0x38,0x35,0x22,0x2f,0x64,0x69,0x7e,0x73,0x50,0x5d,0x4a,0x47,
0xdc,0xd1,0xc6,0xcb,0xe8,0xe5,0xf2,0xff,0xb4,0xb9,0xae,0xa3,0x80,0x8d,0x9a,0x97
}
local GF8x14 = {
[0]=0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a,0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a,
0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca,0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba,
0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1,0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81,
0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11,0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61,
0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87,0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7,
0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67,0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17,
0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c,0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c,
0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc,0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc,
0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b,0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b,
0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b,0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb,
0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0,0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0,
0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50,0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20,
0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6,0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6,
0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26,0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56,
0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d,0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d,
0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd,0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d
}
local s = {
[0]=0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16
}
local si = {
[0]=0x52,0x09,0x6A,0xD5,0x30,0x36,0xA5,0x38,0xBF,0x40,0xA3,0x9E,0x81,0xF3,0xD7,0xFB,
0x7C,0xE3,0x39,0x82,0x9B,0x2F,0xFF,0x87,0x34,0x8E,0x43,0x44,0xC4,0xDE,0xE9,0xCB,
0x54,0x7B,0x94,0x32,0xA6,0xC2,0x23,0x3D,0xEE,0x4C,0x95,0x0B,0x42,0xFA,0xC3,0x4E,
0x08,0x2E,0xA1,0x66,0x28,0xD9,0x24,0xB2,0x76,0x5B,0xA2,0x49,0x6D,0x8B,0xD1,0x25,
0x72,0xF8,0xF6,0x64,0x86,0x68,0x98,0x16,0xD4,0xA4,0x5C,0xCC,0x5D,0x65,0xB6,0x92,
0x6C,0x70,0x48,0x50,0xFD,0xED,0xB9,0xDA,0x5E,0x15,0x46,0x57,0xA7,0x8D,0x9D,0x84,
0x90,0xD8,0xAB,0x00,0x8C,0xBC,0xD3,0x0A,0xF7,0xE4,0x58,0x05,0xB8,0xB3,0x45,0x06,
0xD0,0x2C,0x1E,0x8F,0xCA,0x3F,0x0F,0x02,0xC1,0xAF,0xBD,0x03,0x01,0x13,0x8A,0x6B,
0x3A,0x91,0x11,0x41,0x4F,0x67,0xDC,0xEA,0x97,0xF2,0xCF,0xCE,0xF0,0xB4,0xE6,0x73,
0x96,0xAC,0x74,0x22,0xE7,0xAD,0x35,0x85,0xE2,0xF9,0x37,0xE8,0x1C,0x75,0xDF,0x6E,
0x47,0xF1,0x1A,0x71,0x1D,0x29,0xC5,0x89,0x6F,0xB7,0x62,0x0E,0xAA,0x18,0xBE,0x1B,
0xFC,0x56,0x3E,0x4B,0xC6,0xD2,0x79,0x20,0x9A,0xDB,0xC0,0xFE,0x78,0xCD,0x5A,0xF4,
0x1F,0xDD,0xA8,0x33,0x88,0x07,0xC7,0x31,0xB1,0x12,0x10,0x59,0x27,0x80,0xEC,0x5F,
0x60,0x51,0x7F,0xA9,0x19,0xB5,0x4A,0x0D,0x2D,0xE5,0x7A,0x9F,0x93,0xC9,0x9C,0xEF,
0xA0,0xE0,0x3B,0x4D,0xAE,0x2A,0xF5,0xB0,0xC8,0xEB,0xBB,0x3C,0x83,0x53,0x99,0x61,
0x17,0x2B,0x04,0x7E,0xBA,0x77,0xD6,0x26,0xE1,0x69,0x14,0x63,0x55,0x21,0x0C,0x7D
}
local rcon = {
0x8d,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,
0x2f,0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc5,0x91,0x39,
0x72,0xe4,0xd3,0xbd,0x61,0xc2,0x9f,0x25,0x4a,0x94,0x33,0x66,0xcc,0x83,0x1d,0x3a,
0x74,0xe8,0xcb,0x8d,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,
0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,
0xc5,0x91,0x39,0x72,0xe4,0xd3,0xbd,0x61,0xc2,0x9f,0x25,0x4a,0x94,0x33,0x66,0xcc,
0x83,0x1d,0x3a,0x74,0xe8,0xcb,0x8d,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,
0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4,0xb3,
0x7d,0xfa,0xef,0xc5,0x91,0x39,0x72,0xe4,0xd3,0xbd,0x61,0xc2,0x9f,0x25,0x4a,0x94,
0x33,0x66,0xcc,0x83,0x1d,0x3a,0x74,0xe8,0xcb,0x8d,0x01,0x02,0x04,0x08,0x10,0x20,
0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,0xc6,0x97,0x35,
0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc5,0x91,0x39,0x72,0xe4,0xd3,0xbd,0x61,0xc2,0x9f,
0x25,0x4a,0x94,0x33,0x66,0xcc,0x83,0x1d,0x3a,0x74,0xe8,0xcb,0x8d,0x01,0x02,0x04,
0x08,0x10,0x20,0x40,0x80,0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f,0x5e,0xbc,0x63,
0xc6,0x97,0x35,0x6a,0xd4,0xb3,0x7d,0xfa,0xef,0xc5,0x91,0x39,0x72,0xe4,0xd3,0xbd,
0x61,0xc2,0x9f,0x25,0x4a,0x94,0x33,0x66,0xcc,0x83,0x1d,0x3a,0x74,0xe8,0xcb,0x8d
}
local xor4 = {
[0]=0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,0,3,2,5,4,7,6,9,8,11,10,13,12,15,14,
2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13,
3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12,
4,5,6,7,0,1,2,3,12,13,14,15,8,9,10,11,
5,4,7,6,1,0,3,2,13,12,15,14,9,8,11,10,
6,7,4,5,2,3,0,1,14,15,12,13,10,11,8,9,
7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8,
8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,
9,8,11,10,13,12,15,14,1,0,3,2,5,4,7,6,
10,11,8,9,14,15,12,13,2,3,0,1,6,7,4,5,
11,10,9,8,15,14,13,12,3,2,1,0,7,6,5,4,
12,13,14,15,8,9,10,11,4,5,6,7,0,1,2,3,
13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2,
14,15,12,13,10,11,8,9,6,7,4,5,2,3,0,1,
15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,
}
local function xor8(a, b)
local al = a % 16
local bl = b % 16
return 16 * xor4[a - al + (b - bl) / 16] + xor4[16 * al + bl]
end
local function addRoundKey(state, key)
for i, byte in next, state do
state[i] = xor8(byte, key[i])
end
end
local function subBytes(state, s_box)
for i, byte in next, state do
state[i] = s_box[byte]
end
end
local function shiftRows(state)
state[5], state[6], state[7], state[8] =
state[6], state[7], state[8], state[5]
state[9], state[10], state[11], state[12] =
state[11], state[12], state[9], state[10]
state[13], state[14], state[15], state[16] =
state[16], state[13], state[14], state[15]
end
local function inv_shiftRows(state)
state[6], state[7], state[8], state[5] =
state[5], state[6], state[7], state[8]
state[11], state[12], state[9], state[10] =
state[9], state[10], state[11], state[12]
state[16], state[13], state[14], state[15] =
state[13], state[14], state[15], state[16]
end
local function mixColumns(state)
for cur = 1, 4 do
local a, b, c, d = state[cur], state[cur + 4], state[cur + 8], state[cur + 12]
state[cur + 0] = xor8(xor8(xor8(GF8x2[a], GF8x3[b]), c), d)
state[cur + 4] = xor8(xor8(xor8(a, GF8x2[b]), GF8x3[c]), d)
state[cur + 8] = xor8(xor8(xor8(a, b), GF8x2[c]), GF8x3[d])
state[cur + 12] = xor8(xor8(xor8(GF8x3[a], b), c), GF8x2[d])
end
end
local function inv_mixColumns(state)
for cur = 1, 4 do
local a, b, c, d = state[cur], state[cur + 4], state[cur + 8], state[cur + 12]
state[cur + 0] = xor8(xor8(xor8(GF8x14[a], GF8x11[b]), GF8x13[c]), GF8x9[d])
state[cur + 4] = xor8(xor8(xor8(GF8x9[a], GF8x14[b]), GF8x11[c]), GF8x13[d])
state[cur + 8] = xor8(xor8(xor8(GF8x13[a], GF8x9[b]), GF8x14[c]), GF8x11[d])
state[cur + 12] = xor8(xor8(xor8(GF8x11[a], GF8x13[b]), GF8x9[c]), GF8x14[d])
end
end
-- 256-bit key constants
local n = 32 -- number of bytes in the 256-bit encryption key
local b = 240 -- number of bytes in 15 128-bit round keys
local function schedule256(key)
local expanded = {}
for c = 0, n do
local byte = key % 256
expanded[c] = byte
key = (key - byte) / 256
end
local i = 1
local c = n
local t1 = expanded[1]
local t2 = expanded[2]
local t3 = expanded[3]
local t4 = expanded[4]
while c < b do
t1, t2, t3, t4 = xor8(rcon[i], s[t2]), s[t3], s[t4], s[t1]
i = i + 1
for _ = 1, 4 do
c = c + 1
t1 = xor8(t1, expanded[c - n])
expanded[c] = t1
c = c + 1
t2 = xor8(t2, expanded[c - n])
expanded[c] = t2
c = c + 1
t3 = xor8(t3, expanded[c - n])
expanded[c] = t3
c = c + 1
t4 = xor8(t4, expanded[c - n])
expanded[c] = t4
end
t1 = s[t1]
t2 = s[t2]
t3 = s[t3]
t4 = s[t4]
for _ = 1, 4 do
c = c + 1
t1 = xor8(t1, expanded[c - n])
expanded[c] = t1
c = c + 1
t2 = xor8(t2, expanded[c - n])
expanded[c] = t2
c = c + 1
t3 = xor8(t3, expanded[c - n])
expanded[c] = t3
c = c + 1
t4 = xor8(t4, expanded[c - n])
expanded[c] = t4
end
end
local roundKeys = {}
for round = 0, 14 do
local roundKey = {}
for byte = 1, 16 do
roundKey[byte] = expanded[round * 16 + byte]
end
roundKeys[round] = roundKey
end
return roundKeys
end
local function chunks(text, i)
local first = i * 16 + 1
if first > #text then
return
end
i = i + 1
local chunk = {text:byte(first, first + 15)}
for j = #chunk + 1, 16 do
chunk[j] = 0
end
return i, chunk
end
local function encrypt(state, roundKeys)
addRoundKey(state, roundKeys[0])
for round = 1, 13 do
subBytes(state, s)
shiftRows(state)
mixColumns(state)
addRoundKey(state, roundKeys[round])
end
subBytes(state, s)
shiftRows(state)
addRoundKey(state, roundKeys[14])
end
local function decrypt(state, roundKeys)
addRoundKey(state, roundKeys[14])
inv_shiftRows(state)
subBytes(state, si)
for round = 13, 1, -1 do
addRoundKey(state, roundKeys[round])
inv_mixColumns(state)
inv_shiftRows(state)
subBytes(state, si)
end
addRoundKey(state, roundKeys[0])
end
local function ECB_256(method, key, originaltext)
local text = {}
local roundKeys = schedule256(key)
for chunk, state in chunks, originaltext, 0 do
method(state, roundKeys)
text[chunk] = string.char(unpack(state))
end
return table.concat(text)
end
return {
encrypt = encrypt;
decrypt = decrypt;
ECB_256 = ECB_256;
}
|
-----------------------------------------------------------------------
-- --
-- Copyright (C) 2003-2015, Intelibo Ltd --
-- --
-- Project: LOS --
-- Filename: autotools.lua --
-- Description: build implementation with autotools --
-- --
-----------------------------------------------------------------------
-- autotool api imported and working in los module environment
local autotools = {}
function autotools.builddir()
local dir = path.src.dir
if autotools.opts.build_outside then
dir = api.makepath(lfs.dirname(conf["dir.src"]), "build", lfs.basename(path.src.dir))
end
return dir
end
function autotools.make(...)
local args = {...}
local env
if type(args[1]) == "table" then
env = api.mkenv(args[1])
table.remove(args, 1)
end
return api.executein(autotools.builddir(), conf["build.make"], env, unpack(args))
end
function autotools.configure(...)
if conf["build.stage"] == 0 then
--[[ ensure root permissions and install target
lfs.execout("id -u", function (uid)
assert(uid == "0", "Root permissions required during stage 0")
end)
]]
-- link install dir to location which will be available after chrooting in stage 1
if not lfs.isdir(path.install.dir) then
local installdir = path.install.dir
if string.sub(installdir, 1, 1) == "/" then
installdir = string.sub(installdir, 2)
end
local localinstalldir = api.makepath(conf["dir.sysroot"], installdir)
log.i("mkdir "..localinstalldir)
lfs.mkdir(localinstalldir)
log.i("link "..localinstalldir.." -> "..path.install.dir)
lfs.link(localinstalldir, path.install.dir)
end
end
local args = {...}
local opts =
{
ASFLAGS = conf["gcc.asflags"],
CFLAGS = "-I"..path.install.inc.." "..conf["gcc.cflags"],
CXXFLAGS = "-I"..path.install.inc.." "..conf["gcc.ccflags"],
LDFLAGS = "-L"..path.install.lib.." "..conf["gcc.ldflags"]
}
local extra = args[1]
local configurename = autotools.opts.configure or "configure"
if type(extra) == "table" then
-- process name=value args options
for i, v in pairs(extra) do
if type(i) == "string" then
if opts[i] then
opts[i] = opts[i].." "..v
else
opts[i] = v
end
else
assert(type(i) == "number")
table.insert(args, v)
end
end
table.remove(args, 1)
elseif not extra then
table.remove(args, 1)
else
assert(type(extra) == "string")
end
if not autotools.opts.noprefix then
opts["--prefix"] = opts["--prefix"] or path.install.dir
end
for i, v in pairs(opts) do
table.insert(args, i.."="..v)
end
local env = api.mkenv{
PKG_CONFIG_PATH = api.makepath(path.install.lib, "pkgconfig")..":"..api.makepath(path.install.dir, "share/pkgconfig")
}
if type(args[1]) == "table" then
table.fastcopy(args[1], env)
table.remove(args, 1)
elseif not args[1] then
table.remove(args, 1)
else
assert(type(args[1]) == "string")
end
local srcdir = path.src.dir
local blddir = autotools.builddir()
assert(string.sub(srcdir, 1, 1) == string.sub(blddir, 1, 1), "Build directory at "..blddir.." must be at the same drive as source directory at "..srcdir)
if autotools.opts.build_outside then
lfs.delete(blddir)
end
assert(lfs.mkdir(blddir))
-- finds relative path from build dir to source
local relpath = {}
while srcdir ~= blddir do
srcdir = lfs.dirname(srcdir)
blddir = lfs.dirname(blddir)
table.insert(relpath, "..")
end
local configurepath = api.makepath(table.concat(relpath, "/"), string.sub(path.src.dir, 1 + string.len(srcdir)))
assert(not env.PATH, "PATH can't be defined in autotools")
return api.executein(autotools.builddir(), "sh", env, api.makepath(configurepath, configurename), unpack(args))
end
local installdirs = {"bin", "lib", "include", "man", "man/man1"}
local function createinstalldirs()
for _, dir in ipairs(installdirs) do
local directory = lfs.concatfilenames(path.install.dir, dir)
log.d("mkdir", directory)
local ok, err = lfs.mkdir(directory)
if not ok then
return nil, err
end
end
return true
end
function autotools.install(...)
local args = {...}
table.insert(args, "install")
assert(autotools.make(unpack(args)))
end
return autotools
|
local parser = require "parser"
local error = error
local ipairs = ipairs
local setmetatable = setmetatable
local concat = table.concat
local rep = string.rep
local format = string.format
local function append(list, elm)
list[#list + 1] = elm
end
local T = {}
local mt = { __index = T }
function T.new(env)
return setmetatable({ buf = {} }, mt)
end
function T:_expr(node)
local tag = node[1]
if tag == "number" then
return node[2]
elseif tag == "string" then
return format('"%s"', node[2])
end
if tag == "ref" then
return node[2]
end
if tag == "call" then
return self:_call(node)
end
local op = tag
local lhs, rhs = self:_expr(node[2]), self:_expr(node[3])
if op == "+" then
return format("(%s + %s)", lhs, rhs)
elseif op == "-" then
return format("(%s - %s)", lhs, rhs)
elseif op == "%" then
return format("(%s % %s)", lhs, rhs)
elseif op == "*" then
return format("(%s * %s)", lhs, rhs)
elseif op == "/" then
return format("(%s / %s)", lhs, rhs)
elseif op == ">" then
return format("(%s > %s)", lhs, rhs)
elseif op == ">=" then
return format("(%s >= %s)", lhs, rhs)
elseif op == "<" then
return format("(%s < %s)", lhs, rhs)
elseif op == "<=" then
return format("(%s <= %s)", lhs, rhs)
elseif op == "==" then
return format("(%s == %s)", lhs, rhs)
elseif op == "!=" then
return format("(%s ~= %s)", lhs, rhs)
end
error(format("unexpected tag '%s'", tag))
end
function T:_if(node)
local cond = self:_expr(node[2])
local if_body = self:translate(node[3], {})
local else_node = node[4]
if else_node then
local else_body = self:translate(else_node[2], {})
return format("if %s then\n%s\nelse\n%s\nend", cond, if_body, else_body)
end
return format("if %s then\n%s\nend", cond, if_body)
end
function T:_while(node)
local cond = self:_expr(node[2])
local body = self:translate(node[3], {})
return format("while %s do\n%s\nend", cond, body)
end
function T:_def(node)
local id = node[2]
local pars = concat(node[3], ", ")
local body = self:translate(node[4], {})
return format("local function %s(%s)\n%s\nend", id, pars, body)
end
function T:_call(node)
local id = node[2]
local args = {}
for i, expr in ipairs(node[3]) do
args[i] = self:_expr(expr)
end
return format("%s(%s)", id, concat(args, ", "))
end
function T:_return(node)
local ret = node[2] and self:_expr(node[2])
if ret then
return format("return %s", ret)
else
return "return"
end
end
function T:_assign(node)
local id = node[2]
local expr = node[3]
return format("%s = %s", id, self:_expr(expr))
end
function T:_local(node)
local id = node[2]
local expr = node[3]
return format("local %s = %s", id, self:_expr(expr))
end
function T:visit(node)
local tag = node[1]
local visit = self["_" .. tag] or self._expr
return visit(self, node)
end
function T:translate(ast, buf)
if not buf then
buf = {}
end
for _, node in ipairs(ast) do
append(buf, self:visit(node))
end
return concat(buf, "\n")
end
return T
|
remote = require('net.box')
env = require('test_run')
test_run = env.new()
--
-- gh-4672: Due to an error in the serializer, -2^63 was
-- serialized as double, although in accordance with the rules of
-- serialization it should be serialized as an integer.
--
format={{name='u', type='unsigned'}, {name='i', type='integer'}}
s = box.schema.space.create('serializer_test_space', {format=format})
_ = s:create_index('ii')
s:insert({1, -2^63})
s:insert({2, -9223372036854775808LL})
s:insert({3, 0})
s:update(3, {{'=', 2, -2^63}})
s:insert({4, 0})
s:update(4, {{'=', 2, -9223372036854775808LL}})
box.schema.user.grant('guest', 'read, write', 'space', 'serializer_test_space')
cn = remote.connect(box.cfg.listen)
s = cn.space.serializer_test_space
s:insert({11, -2^63})
s:insert({12, -9223372036854775808LL})
s:insert({13, 0})
s:update(13, {{'=', 2, -2^63}})
s:insert({14, 0})
s:update(14, {{'=', 2, -9223372036854775808LL}})
cn:close()
box.schema.user.revoke('guest', 'read, write', 'space', 'serializer_test_space')
box.space.serializer_test_space:drop()
|
local function amnesic(time, t1, t2, c, m)
local U
if time < t1 then
U = 0
elseif time >= t1 and time < t2 then
U = c * (time - t1) / (t2 - t1)
else
U = c + (time - t2) / m
end
local w1 = (time - 1 - U) / time
local w2 = (1 + U) / time
return w1, w2
end
return amnesic
|
---------------------------------------- pure LUA AES Lib for HC3 QuickApps -----------------------------------------
aeslib = {
_VERSION = "0.2",
_DESCRIPTION = "pura LUA AES LIB",
_URL = "http://quickapps.info",
_LICENSE = [[
(c) tinman/Intuitech
]]
}
--------------------------------------------------------------------------------
-- USAGE:
-- call aeslib.decryptString or aeslib.encryptString
-- there is additional padding and aestil lib inside, check QA example
--------------------------------------------------------------------------------
-- Decrypt strings
-- key - byte array with key
-- string - string to decrypt
-- modefunction - ciphermode.decryptECB,ciphermode.decryptCBC,ciphermode.decryptOFB,ciphermode.decryptCFB,ciphermode.decryptCTR
-- iv - optional iv for modefunction
function aeslib.decryptString(key, data, modeFunction, iv)
return ciphermode.decryptString(key, data, modeFunction, iv)
end
-- Encrypt strings
-- key - byte array with key
-- string - string to encrypt
-- modefunction - ciphermode.encryptECB,ciphermode.encryptCBC,ciphermode.encryptOFB,ciphermode.encryptCFB,ciphermode.encryptCTR)
-- iv - optional iv for modefunction
function aeslib.encryptString(key, data, modeFunction, iv)
return ciphermode.encryptString(key, data, modeFunction, iv)
end
--------------------------------------------------------------------------------
-- small extra -> padding lib : PKCS#7, ANSI X9.23, ISO7816-4, ZERO and SPACE
--------------------------------------------------------------------------------
padding = {
_VERSION = "lua-resty-nettle.padding.lua v1.5 - 2020-04-01",
_LICENSE = [[
Copyright (c) 2014 - 2020, Aapo Talvensaari
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.
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 HOLDER 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.
]]
}
function padding.padPKCS7(data, blocksize, optional)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local ps = blocksize - #data % blocksize
if optional and ps == blocksize then return data end
return data .. string.rep(string.char(ps), ps)
end
function padding.unpadPKCS7(data, blocksize)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local len = #data
if len % blocksize ~= 0 then
return nil, "data length is not a multiple of the block size"
end
local chr = string.sub(data, -1)
local rem = string.byte(chr)
if rem > 0 and rem <= blocksize then
local chk = string.sub(data, -rem)
if chk == string.rep(chr, rem) then
return string.sub(data, 1, len - rem)
end
end
return data
end
function padding.padANSIX923(data, blocksize, optional)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local ps = blocksize - #data % blocksize
if optional and ps == blocksize then return data end
return data .. string.rep("\0", ps - 1) .. string.char(ps)
end
function padding.unpadANSIX923(data, blocksize)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local len = #data
if len % blocksize ~= 0 then
return nil, "data length is not a multiple of the block size"
end
local chr = string.sub(data, -1)
local rem = string.byte(chr)
if rem > 0 and rem <= blocksize then
local chk = string.sub(data, -rem)
if chk == string.rep("\0", rem - 1) .. chr then
return string.sub(data, 1, len - rem)
end
end
return data
end
function padding.padZERO(data, blocksize, optional)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local ps = blocksize - #data % blocksize
if optional and ps == blocksize then return data end
return data .. string.rep("\0", ps)
end
function padding.unpadZERO(data, blocksize)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local len = #data
if len % blocksize ~= 0 then
return nil, "data length is not a multiple of the block size"
end
data = string.gsub(data, "%z+$", "")
local rem = len - #data
if rem < 0 or rem > blocksize then
return nil, "data has invalid padding"
end
return data
end
function padding.padISO7816_4(data, blocksize, optional)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local ps = blocksize - #data % blocksize
if optional and ps == blocksize then return data end
return data .. "\x80" .. string.rep("\0", ps - 1)
end
function padding.unpadISO7816_4(data, blocksize)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local len = #data
if len % blocksize ~= 0 then
return nil, "data length is not a multiple of the block size"
end
local d = string.gsub(data, "%z+$", "")
if string.sub(d, -1) == "\x80" then
return string.sub(d, 1, #d - 1)
end
return data
end
function padding.padSPACE(data, blocksize, optional)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local ps = blocksize - #data % blocksize
if optional and ps == blocksize then return data end
return data .. string.rep(" ", ps)
end
function padding.unpadSPACE(data, blocksize)
blocksize = blocksize or 16
if type(blocksize) ~= "number" then
return nil, "invalid block size data type"
end
if blocksize < 1 or blocksize > 256 then
return nil, "invalid block size"
end
local len = #data
if len % blocksize ~= 0 then
return nil, "data length is not a multiple of the block size"
end
data = string.gsub(data, " +$", "")
local rem = len - #data
if rem < 0 or rem > blocksize then
return nil, "data has invalid padding"
end
return data
end
function padding.toHex(data)
local inputHexTab = {}
for c in data:gmatch(".") do
table.insert(inputHexTab, string.format("%02x", c:byte()))
end
return table.concat(inputHexTab, "")
end
function padding.fromHex(data)
return data:gsub(
"%x%x",
function(c)
return c.char(tonumber(c, 16))
end
)
end
--------------------------------------------------------------------------------
-- aes part of aeslib
--------------------------------------------------------------------------------
aesutil = {
_VERSION = "util.lua 0.2",
_LICENSE = [[
aeslua: Lua AES implementation
Copyright (c) 2006,2007 Matthias Hilbig
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser Public License for more details.
A copy of the terms and conditions of the license can be found in
License.txt or online at
http://www.gnu.org/copyleft/lesser.html
To obtain a copy, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Author
Matthias Hilbig
http://homepages.upb.de/hilbig/aeslua/
hilbig@upb.de
]]
}
--
-- calculate the parity of one byte
--
function aesutil.byteParity(byte)
byte = bit32.bxor(byte, bit32.rshift(byte, 4));
byte = bit32.bxor(byte, bit32.rshift(byte, 2));
byte = bit32.bxor(byte, bit32.rshift(byte, 1));
return bit32.band(byte, 1);
end
--
-- get byte at position index
--
function aesutil.getByte(number, index)
if (index == 0) then
return bit32.band(number,0xff);
else
return bit32.band(bit32.rshift(number, index*8),0xff);
end
end
--
-- put number into int at position index
--
function aesutil.putByte(number, index)
if (index == 0) then
return bit32.band(number,0xff);
else
return bit32.lshift(bit32.band(number,0xff),index*8);
end
end
--
-- convert byte array to int array
--
function aesutil.bytesToInts(bytes, start, n)
local ints = {};
for i = 0, n - 1 do
ints[i] = aesutil.putByte(bytes[start + (i*4) ], 3)
+ aesutil.putByte(bytes[start + (i*4) + 1], 2)
+ aesutil.putByte(bytes[start + (i*4) + 2], 1)
+ aesutil.putByte(bytes[start + (i*4) + 3], 0);
end
return ints;
end
--
-- convert int array to byte array
--
function aesutil.intsToBytes(ints, output, outputOffset, n)
n = n or #ints;
for i = 0, n do
for j = 0,3 do
output[outputOffset + i*4 + (3 - j)] = aesutil.getByte(ints[i], j);
end
end
return output;
end
--
-- convert bytes to hexString
--
function aesutil.bytesToHex(bytes)
local hexBytes = "";
for i,byte in ipairs(bytes) do
hexBytes = hexBytes .. string.format("%02x ", byte);
end
return hexBytes;
end
--
-- convert data to hex string
--
function aesutil.toHexString(data)
local type = type(data);
if (type == "number") then
return string.format("%08x",data);
elseif (type == "table") then
return aesutil.bytesToHex(data);
elseif (type == "string") then
local bytes = {string.byte(data, 1, #data)};
return aesutil.bytesToHex(bytes);
else
return data;
end
end
function aesutil.xorIV(data, iv)
for i = 1,16 do
data[i] = bit32.bxor(data[i], iv[i]);
end
end
function aesutil.increment(data)
local i = 16
while true do
local value = data[i] + 1
if value >= 256 then
data[i] = value - 256
i = (i - 2) % 16 + 1
else
data[i] = value
break
end
end
end
--------------------------------------------------------------------------------
aeslibgf = {
_VERSION = "gf.lua 0.2",
_LICENSE = [[
aeslua: Lua AES implementation
Copyright (c) 2006,2007 Matthias Hilbig
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser Public License for more details.
A copy of the terms and conditions of the license can be found in
License.txt or online at
http://www.gnu.org/copyleft/lesser.html
To obtain a copy, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Author
Matthias Hilbig
http://homepages.upb.de/hilbig/aeslua/
hilbig@upb.de
]]
}
-- gf data of gf
aeslibgf.n = 0x100;
aeslibgf.ord = 0xff;
aeslibgf.irrPolynom = 0x11b;
aeslibgf.exp = {};
aeslibgf.log = {};
--
-- add two polynoms (its simply xor)
--
function aeslibgf.add(operand1, operand2)
return bit32.bxor(operand1,operand2);
end
--
-- subtract two polynoms (same as addition)
--
function aeslibgf.sub(operand1, operand2)
return bit32.bxor(operand1,operand2);
end
--
-- inverts element a^(-1) = g^(order - log(a))
--
function aeslibgf.invert(operand)
-- special case for 1
if (operand == 1) then
return 1;
end;
-- normal invert
local exponent = aeslibgf.ord - aeslibgf.log[operand];
return aeslibgf.exp[exponent];
end
--
-- multiply two elements using a logarithm table
-- a*b = g^(log(a)+log(b))
--
function aeslibgf.mul(operand1, operand2)
if (operand1 == 0 or operand2 == 0) then
return 0;
end
local exponent = aeslibgf.log[operand1] + aeslibgf.log[operand2];
if (exponent >= aeslibgf.ord) then
exponent = exponent - aeslibgf.ord;
end
return aeslibgf.exp[exponent];
end
--
-- divide two elements
-- a/b = g^(log(a)-log(b))
--
function aeslibgf.div(operand1, operand2)
if (operand1 == 0) then
return 0;
end
-- TODO: exception if operand2 == 0
local exponent = aeslibgf.log[operand1] - aeslibgf.log[operand2];
if (exponent < 0) then
exponent = exponent + aeslibgf.ord;
end
return aeslibgf.exp[exponent];
end
--
-- print logarithmic table
--
function aeslibgf.printLog()
for i = 1, aeslibgf.n do
print("log(", i-1, ")=", aeslibgf.log[i-1]);
end
end
--
-- print exponentiation table
--
function aeslibgf.printExp()
for i = 1, aeslibgf.n do
print("exp(", i-1, ")=", aeslibgf.exp[i-1]);
end
end
--
-- calculate logarithmic and exponentiation table
--
function aeslibgf.initMulTable()
local a = 1;
for i = 0,aeslibgf.ord-1 do
aeslibgf.exp[i] = a;
aeslibgf.log[a] = i;
-- multiply with generator x+1 -> left shift + 1
a = bit32.bxor(bit32.lshift(a, 1), a);
-- if a gets larger than order, reduce modulo irreducible polynom
if a > aeslibgf.ord then
a = aeslibgf.sub(a, aeslibgf.irrPolynom);
end
end
end
aeslibgf.initMulTable();
--------------------------------------------------------------------------------
aeslibbuffer = {
_VERSION = "buffer.lua 0.2",
_LICENSE = [[
aeslua: Lua AES implementation
Copyright (c) 2006,2007 Matthias Hilbig
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser Public License for more details.
A copy of the terms and conditions of the license can be found in
License.txt or online at
http://www.gnu.org/copyleft/lesser.html
To obtain a copy, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Author
Matthias Hilbig
http://homepages.upb.de/hilbig/aeslua/
hilbig@upb.de
]]
}
function aeslibbuffer.new()
return {};
end
function aeslibbuffer.addString(stack, s)
table.insert(stack, s)
for i = #stack - 1, 1, -1 do
if #stack[i] > #stack[i+1] then
break;
end
stack[i] = stack[i] .. table.remove(stack);
end
end
function aeslibbuffer.toString(stack)
for i = #stack - 1, 1, -1 do
stack[i] = stack[i] .. table.remove(stack);
end
return stack[1];
end
--------------------------------------------------------------------------------
aes = {
_VERSION = "aes.lua 0.2",
_LICENSE = [[
aeslua: Lua AES implementation
Copyright (c) 2006,2007 Matthias Hilbig
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser Public License for more details.
A copy of the terms and conditions of the license can be found in
License.txt or online at
http://www.gnu.org/copyleft/lesser.html
To obtain a copy, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Author
Matthias Hilbig
http://homepages.upb.de/hilbig/aeslua/
hilbig@upb.de
]]
}
-- some constants
aes.ROUNDS = "rounds";
aes.KEY_TYPE = "type";
aes.ENCRYPTION_KEY=1;
aes.DECRYPTION_KEY=2;
-- aes SBOX
aes.SBox = {};
aes.iSBox = {};
-- aes tables
aes.table0 = {};
aes.table1 = {};
aes.table2 = {};
aes.table3 = {};
aes.tableInv0 = {};
aes.tableInv1 = {};
aes.tableInv2 = {};
aes.tableInv3 = {};
-- round constants
aes.rCon = {0x01000000,
0x02000000,
0x04000000,
0x08000000,
0x10000000,
0x20000000,
0x40000000,
0x80000000,
0x1b000000,
0x36000000,
0x6c000000,
0xd8000000,
0xab000000,
0x4d000000,
0x9a000000,
0x2f000000};
--
-- affine transformation for calculating the S-Box of AES
--
function aes.affinMap(byte)
mask = 0xf8;
result = 0;
for i = 1,8 do
result = bit32.lshift(result,1);
parity = aesutil.byteParity(bit32.band(byte,mask));
result = result + parity
-- simulate roll
lastbit = bit32.band(mask, 1);
mask = bit32.band(bit32.rshift(mask, 1),0xff);
if (lastbit ~= 0) then
mask = bit32.bor(mask, 0x80);
else
mask = bit32.band(mask, 0x7f);
end
end
return bit32.bxor(result, 0x63);
end
--
-- calculate S-Box and inverse S-Box of AES
-- apply affine transformation to inverse in finite field 2^8
--
function aes.calcSBox()
for i = 0, 255 do
if (i ~= 0) then
inverse = aeslibgf.invert(i);
else
inverse = i;
end
mapped = aes.affinMap(inverse);
aes.SBox[i] = mapped;
aes.iSBox[mapped] = i;
end
end
--
-- Calculate round tables
-- round tables are used to calculate shiftRow, MixColumn and SubBytes
-- with 4 table lookups and 4 xor operations.
--
function aes.calcRoundTables()
for x = 0,255 do
byte = aes.SBox[x];
aes.table0[x] = aesutil.putByte(aeslibgf.mul(0x03, byte), 0)
+ aesutil.putByte( byte , 1)
+ aesutil.putByte( byte , 2)
+ aesutil.putByte(aeslibgf.mul(0x02, byte), 3);
aes.table1[x] = aesutil.putByte( byte , 0)
+ aesutil.putByte( byte , 1)
+ aesutil.putByte(aeslibgf.mul(0x02, byte), 2)
+ aesutil.putByte(aeslibgf.mul(0x03, byte), 3);
aes.table2[x] = aesutil.putByte( byte , 0)
+ aesutil.putByte(aeslibgf.mul(0x02, byte), 1)
+ aesutil.putByte(aeslibgf.mul(0x03, byte), 2)
+ aesutil.putByte( byte , 3);
aes.table3[x] = aesutil.putByte(aeslibgf.mul(0x02, byte), 0)
+ aesutil.putByte(aeslibgf.mul(0x03, byte), 1)
+ aesutil.putByte( byte , 2)
+ aesutil.putByte( byte , 3);
end
end
--
-- Calculate inverse round tables
-- does the inverse of the normal roundtables for the equivalent
-- decryption algorithm.
--
function aes.calcInvRoundTables()
for x = 0,255 do
byte = aes.iSBox[x];
aes.tableInv0[x] = aesutil.putByte(aeslibgf.mul(0x0b, byte), 0)
+ aesutil.putByte(aeslibgf.mul(0x0d, byte), 1)
+ aesutil.putByte(aeslibgf.mul(0x09, byte), 2)
+ aesutil.putByte(aeslibgf.mul(0x0e, byte), 3);
aes.tableInv1[x] = aesutil.putByte(aeslibgf.mul(0x0d, byte), 0)
+ aesutil.putByte(aeslibgf.mul(0x09, byte), 1)
+ aesutil.putByte(aeslibgf.mul(0x0e, byte), 2)
+ aesutil.putByte(aeslibgf.mul(0x0b, byte), 3);
aes.tableInv2[x] = aesutil.putByte(aeslibgf.mul(0x09, byte), 0)
+ aesutil.putByte(aeslibgf.mul(0x0e, byte), 1)
+ aesutil.putByte(aeslibgf.mul(0x0b, byte), 2)
+ aesutil.putByte(aeslibgf.mul(0x0d, byte), 3);
aes.tableInv3[x] = aesutil.putByte(aeslibgf.mul(0x0e, byte), 0)
+ aesutil.putByte(aeslibgf.mul(0x0b, byte), 1)
+ aesutil.putByte(aeslibgf.mul(0x0d, byte), 2)
+ aesutil.putByte(aeslibgf.mul(0x09, byte), 3);
end
end
--
-- rotate word: 0xaabbccdd gets 0xbbccddaa
-- used for key schedule
--
function aes.rotWord(word)
local tmp = bit32.band(word,0xff000000);
return (bit32.lshift(word,8) + bit32.rshift(tmp,24)) ;
end
--
-- replace all bytes in a word with the SBox.
-- used for key schedule
--
function aes.subWord(word)
return aesutil.putByte(aes.SBox[aesutil.getByte(word,0)],0)
+ aesutil.putByte(aes.SBox[aesutil.getByte(word,1)],1)
+ aesutil.putByte(aes.SBox[aesutil.getByte(word,2)],2)
+ aesutil.putByte(aes.SBox[aesutil.getByte(word,3)],3);
end
--
-- generate key schedule for aes encryption
--
-- returns table with all round keys and
-- the necessary number of rounds saved in [aes.ROUNDS]
--
function aes.expandEncryptionKey(key)
local keySchedule = {};
local keyWords = math.floor(#key / 4);
if ((keyWords ~= 4 and keyWords ~= 6 and keyWords ~= 8) or (keyWords * 4 ~= #key)) then
print("Invalid key size: ", keyWords);
return nil;
end
keySchedule[aes.ROUNDS] = keyWords + 6;
keySchedule[aes.KEY_TYPE] = aes.ENCRYPTION_KEY;
for i = 0,keyWords - 1 do
keySchedule[i] = aesutil.putByte(key[i*4+1], 3)
+ aesutil.putByte(key[i*4+2], 2)
+ aesutil.putByte(key[i*4+3], 1)
+ aesutil.putByte(key[i*4+4], 0);
end
for i = keyWords, (keySchedule[aes.ROUNDS] + 1)*4 - 1 do
local tmp = keySchedule[i-1];
if ( i % keyWords == 0) then
tmp = aes.rotWord(tmp);
tmp = aes.subWord(tmp);
local index = math.floor(i/keyWords);
tmp = bit32.bxor(tmp,aes.rCon[index]);
elseif (keyWords > 6 and i % keyWords == 4) then
tmp = aes.subWord(tmp);
end
keySchedule[i] = bit32.bxor(keySchedule[(i-keyWords)],tmp);
end
return keySchedule;
end
--
-- Inverse mix column
-- used for key schedule of decryption key
--
function aes.invMixColumnOld(word)
local b0 = aesutil.getByte(word,3);
local b1 = aesutil.getByte(word,2);
local b2 = aesutil.getByte(word,1);
local b3 = aesutil.getByte(word,0);
return aesutil.putByte(aeslibgf.add(aeslibgf.add(aeslibgf.add(aeslibgf.mul(0x0b, b1),
aeslibgf.mul(0x0d, b2)),
aeslibgf.mul(0x09, b3)),
aeslibgf.mul(0x0e, b0)),3)
+ aesutil.putByte(aeslibgf.add(aeslibgf.add(aeslibgf.add(aeslibgf.mul(0x0b, b2),
aeslibgf.mul(0x0d, b3)),
aeslibgf.mul(0x09, b0)),
aeslibgf.mul(0x0e, b1)),2)
+ aesutil.putByte(aeslibgf.add(aeslibgf.add(aeslibgf.add(aeslibgf.mul(0x0b, b3),
aeslibgf.mul(0x0d, b0)),
aeslibgf.mul(0x09, b1)),
aeslibgf.mul(0x0e, b2)),1)
+ aesutil.putByte(aeslibgf.add(aeslibgf.add(aeslibgf.add(aeslibgf.mul(0x0b, b0),
aeslibgf.mul(0x0d, b1)),
aeslibgf.mul(0x09, b2)),
aeslibgf.mul(0x0e, b3)),0);
end
--
-- Optimized inverse mix column
-- look at http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
-- TODO: make it work
--
function aes.invMixColumn(word)
local b0 = aesutil.getByte(word,3);
local b1 = aesutil.getByte(word,2);
local b2 = aesutil.getByte(word,1);
local b3 = aesutil.getByte(word,0);
local t = bit32.bxor(b3,b2);
local u = bit32.bxor(b1,b0);
local v = bit32.bxor(t,u);
v = bit32.bxor(v,aeslibgf.mul(0x08,v));
w = bit32.bxor(v,aeslibgf.mul(0x04, bit32.bxor(b2,b0)));
v = bit32.bxor(v,aeslibgf.mul(0x04, bit32.bxor(b3,b1)));
return aesutil.putByte( bit32.bxor(bit32.bxor(b3,v), aeslibgf.mul(0x02, bit32.bxor(b0,b3))), 0)
+ aesutil.putByte( bit32.bxor(bit32.bxor(b2,w), aeslibgf.mul(0x02, t )), 1)
+ aesutil.putByte( bit32.bxor(bit32.bxor(b1,v), aeslibgf.mul(0x02, bit32.bxor(b0,b3))), 2)
+ aesutil.putByte( bit32.bxor(bit32.bxor(b0,w), aeslibgf.mul(0x02, u )), 3);
end
--
-- generate key schedule for aes decryption
--
-- uses key schedule for aes encryption and transforms each
-- key by inverse mix column.
--
function aes.expandDecryptionKey(key)
local keySchedule = aes.expandEncryptionKey(key);
if (keySchedule == nil) then
return nil;
end
keySchedule[aes.KEY_TYPE] = aes.DECRYPTION_KEY;
for i = 4, (keySchedule[aes.ROUNDS] + 1)*4 - 5 do
keySchedule[i] = aes.invMixColumnOld(keySchedule[i]);
end
return keySchedule;
end
--
-- xor round key to state
--
function aes.addRoundKey(state, key, round)
for i = 0, 3 do
state[i] = bit32.bxor(state[i], key[round*4+i]);
end
end
--
-- do encryption round (ShiftRow, SubBytes, MixColumn together)
--
function aes.doRound(origState, dstState)
dstState[0] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.table0[aesutil.getByte(origState[0],3)],
aes.table1[aesutil.getByte(origState[1],2)]),
aes.table2[aesutil.getByte(origState[2],1)]),
aes.table3[aesutil.getByte(origState[3],0)]);
dstState[1] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.table0[aesutil.getByte(origState[1],3)],
aes.table1[aesutil.getByte(origState[2],2)]),
aes.table2[aesutil.getByte(origState[3],1)]),
aes.table3[aesutil.getByte(origState[0],0)]);
dstState[2] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.table0[aesutil.getByte(origState[2],3)],
aes.table1[aesutil.getByte(origState[3],2)]),
aes.table2[aesutil.getByte(origState[0],1)]),
aes.table3[aesutil.getByte(origState[1],0)]);
dstState[3] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.table0[aesutil.getByte(origState[3],3)],
aes.table1[aesutil.getByte(origState[0],2)]),
aes.table2[aesutil.getByte(origState[1],1)]),
aes.table3[aesutil.getByte(origState[2],0)]);
end
--
-- do last encryption round (ShiftRow and SubBytes)
--
function aes.doLastRound(origState, dstState)
dstState[0] = aesutil.putByte(aes.SBox[aesutil.getByte(origState[0],3)], 3)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[1],2)], 2)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[2],1)], 1)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[3],0)], 0);
dstState[1] = aesutil.putByte(aes.SBox[aesutil.getByte(origState[1],3)], 3)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[2],2)], 2)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[3],1)], 1)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[0],0)], 0);
dstState[2] = aesutil.putByte(aes.SBox[aesutil.getByte(origState[2],3)], 3)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[3],2)], 2)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[0],1)], 1)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[1],0)], 0);
dstState[3] = aesutil.putByte(aes.SBox[aesutil.getByte(origState[3],3)], 3)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[0],2)], 2)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[1],1)], 1)
+ aesutil.putByte(aes.SBox[aesutil.getByte(origState[2],0)], 0);
end
--
-- do decryption round
--
function aes.doInvRound(origState, dstState)
dstState[0] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.tableInv0[aesutil.getByte(origState[0],3)],
aes.tableInv1[aesutil.getByte(origState[3],2)]),
aes.tableInv2[aesutil.getByte(origState[2],1)]),
aes.tableInv3[aesutil.getByte(origState[1],0)]);
dstState[1] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.tableInv0[aesutil.getByte(origState[1],3)],
aes.tableInv1[aesutil.getByte(origState[0],2)]),
aes.tableInv2[aesutil.getByte(origState[3],1)]),
aes.tableInv3[aesutil.getByte(origState[2],0)]);
dstState[2] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.tableInv0[aesutil.getByte(origState[2],3)],
aes.tableInv1[aesutil.getByte(origState[1],2)]),
aes.tableInv2[aesutil.getByte(origState[0],1)]),
aes.tableInv3[aesutil.getByte(origState[3],0)]);
dstState[3] = bit32.bxor(bit32.bxor(bit32.bxor(
aes.tableInv0[aesutil.getByte(origState[3],3)],
aes.tableInv1[aesutil.getByte(origState[2],2)]),
aes.tableInv2[aesutil.getByte(origState[1],1)]),
aes.tableInv3[aesutil.getByte(origState[0],0)]);
end
--
-- do last decryption round
--
function aes.doInvLastRound(origState, dstState)
dstState[0] = aesutil.putByte(aes.iSBox[aesutil.getByte(origState[0],3)], 3)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[3],2)], 2)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[2],1)], 1)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[1],0)], 0);
dstState[1] = aesutil.putByte(aes.iSBox[aesutil.getByte(origState[1],3)], 3)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[0],2)], 2)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[3],1)], 1)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[2],0)], 0);
dstState[2] = aesutil.putByte(aes.iSBox[aesutil.getByte(origState[2],3)], 3)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[1],2)], 2)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[0],1)], 1)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[3],0)], 0);
dstState[3] = aesutil.putByte(aes.iSBox[aesutil.getByte(origState[3],3)], 3)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[2],2)], 2)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[1],1)], 1)
+ aesutil.putByte(aes.iSBox[aesutil.getByte(origState[0],0)], 0);
end
--
-- encrypts 16 Bytes
-- key encryption key schedule
-- input array with input data
-- inputOffset start index for input
-- output array for encrypted data
-- outputOffset start index for output
--
function aes.encrypt(key, input, inputOffset, output, outputOffset)
--default parameters
inputOffset = inputOffset or 1;
output = output or {};
outputOffset = outputOffset or 1;
local state = {};
local tmpState = {};
if (key[aes.KEY_TYPE] ~= aes.ENCRYPTION_KEY) then
print("No encryption key: ", key[aes.KEY_TYPE]);
return;
end
state = aesutil.bytesToInts(input, inputOffset, 4);
aes.addRoundKey(state, key, 0);
local round = 1;
while (round < key[aes.ROUNDS] - 1) do
-- do a double round to save temporary assignments
aes.doRound(state, tmpState);
aes.addRoundKey(tmpState, key, round);
round = round + 1;
aes.doRound(tmpState, state);
aes.addRoundKey(state, key, round);
round = round + 1;
end
aes.doRound(state, tmpState);
aes.addRoundKey(tmpState, key, round);
round = round +1;
aes.doLastRound(tmpState, state);
aes.addRoundKey(state, key, round);
return aesutil.intsToBytes(state, output, outputOffset);
end
--
-- decrypt 16 bytes
-- key decryption key schedule
-- input array with input data
-- inputOffset start index for input
-- output array for decrypted data
-- outputOffset start index for output
---
function aes.decrypt(key, input, inputOffset, output, outputOffset)
-- default arguments
inputOffset = inputOffset or 1;
output = output or {};
outputOffset = outputOffset or 1;
local state = {};
local tmpState = {};
if (key[aes.KEY_TYPE] ~= aes.DECRYPTION_KEY) then
print("No decryption key: ", key[aes.KEY_TYPE]);
return;
end
state = aesutil.bytesToInts(input, inputOffset, 4);
aes.addRoundKey(state, key, key[aes.ROUNDS]);
local round = key[aes.ROUNDS] - 1;
while (round > 2) do
-- do a double round to save temporary assignments
aes.doInvRound(state, tmpState);
aes.addRoundKey(tmpState, key, round);
round = round - 1;
aes.doInvRound(tmpState, state);
aes.addRoundKey(state, key, round);
round = round - 1;
end
aes.doInvRound(state, tmpState);
aes.addRoundKey(tmpState, key, round);
round = round - 1;
aes.doInvLastRound(tmpState, state);
aes.addRoundKey(state, key, round);
return aesutil.intsToBytes(state, output, outputOffset);
end
-- calculate all tables when loading this file
aes.calcSBox();
aes.calcRoundTables();
aes.calcInvRoundTables();
--------------------------------------------------------------------------------
ciphermode = {
_VERSION = "ciphermode.lua 0.2",
_LICENSE = [[
aeslua: Lua AES implementation
Copyright (c) 2006,2007 Matthias Hilbig
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser Public License for more details.
A copy of the terms and conditions of the license can be found in
License.txt or online at
http://www.gnu.org/copyleft/lesser.html
To obtain a copy, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Author
Matthias Hilbig
http://homepages.upb.de/hilbig/aeslua/
hilbig@upb.de
]]
}
--
-- Encrypt strings
-- key - byte array with key
-- string - string to encrypt
-- modefunction - function for cipher mode to use
-- iv - optional iv for modefunction
--
function ciphermode.encryptString(key, data, modeFunction, iv)
if iv then
local ivCopy = {}
for i = 1, 16 do ivCopy[i] = iv[i] end
iv = ivCopy
else
iv = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
end
local keySched = aes.expandEncryptionKey(key)
local encryptedData = aeslibbuffer.new()
for i = 1, #data/16 do
local offset = (i-1)*16 + 1
local byteData = {string.byte(data,offset,offset +15)}
iv = modeFunction(keySched, byteData, iv)
aeslibbuffer.addString(encryptedData, string.char(unpack(byteData)))
end
return aeslibbuffer.toString(encryptedData)
end
--
-- the following 4 functions can be used as
-- modefunction for encryptString
--
function ciphermode.encryptECB(keySched, byteData, iv)
aes.encrypt(keySched, byteData, 1, byteData, 1)
end
-- Cipher block chaining mode encrypt function
function ciphermode.encryptCBC(keySched, byteData, iv)
aesutil.xorIV(byteData, iv)
aes.encrypt(keySched, byteData, 1, byteData, 1)
return byteData
end
-- Output feedback mode encrypt function
function ciphermode.encryptOFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
aesutil.xorIV(byteData, iv)
return iv
end
-- Cipher feedback mode encrypt function
function ciphermode.encryptCFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
aesutil.xorIV(byteData, iv)
return byteData
end
function ciphermode.encryptCTR(keySched, byteData, iv)
local nextIV = {}
for j = 1, 16 do nextIV[j] = iv[j] end
aes.encrypt(keySched, iv, 1, iv, 1)
aesutil.xorIV(byteData, iv)
aesutil.increment(nextIV)
return nextIV
end
--
-- Decrypt strings
-- key - byte array with key
-- string - string to decrypt
-- modefunction - function for cipher mode to use
-- iv - optional iv for modefunction
--
function ciphermode.decryptString(key, data, modeFunction, iv)
if iv then
local ivCopy = {}
for i = 1, 16 do ivCopy[i] = iv[i] end
iv = ivCopy
else
iv = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
end
local keySched
if (modeFunction == ciphermode.decryptOFB or modeFunction == ciphermode.decryptCFB or modeFunction == ciphermode.decryptCTR) then
keySched = aes.expandEncryptionKey(key)
else
keySched = aes.expandDecryptionKey(key)
end
local decryptedData = aeslibbuffer.new()
for i = 1, #data/16 do
local offset = (i-1)*16 + 1
local byteData = {string.byte(data,offset,offset +15)}
iv = modeFunction(keySched, byteData, iv)
aeslibbuffer.addString(decryptedData, string.char(unpack(byteData)))
end
return aeslibbuffer.toString(decryptedData)
end
--
-- the following 4 functions can be used as
-- modefunction for decryptString
--
function ciphermode.decryptECB(keySched, byteData, iv)
aes.decrypt(keySched, byteData, 1, byteData, 1)
return iv
end
-- Cipher block chaining mode decrypt function
function ciphermode.decryptCBC(keySched, byteData, iv)
local nextIV = {}
for j = 1, 16 do nextIV[j] = byteData[j] end
aes.decrypt(keySched, byteData, 1, byteData, 1)
aesutil.xorIV(byteData, iv)
return nextIV
end
-- Output feedback mode decrypt function
function ciphermode.decryptOFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
aesutil.xorIV(byteData, iv)
return iv
end
-- Cipher feedback mode decrypt function
function ciphermode.decryptCFB(keySched, byteData, iv)
local nextIV = {}
for j = 1, 16 do nextIV[j] = byteData[j] end
aes.encrypt(keySched, iv, 1, iv, 1)
aesutil.xorIV(byteData, iv)
return nextIV
end
ciphermode.decryptCTR = ciphermode.encryptCTR
--------------------------------------------- end of lib ---------------------------------------------
|
object_tangible_loot_creature_loot_collections_statuette_piece_001 = object_tangible_loot_creature_loot_collections_shared_statuette_piece_001:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_statuette_piece_001, "object/tangible/loot/creature/loot/collections/statuette_piece_001.iff")
|
function ExtendAll(getTarget)
return function (arg)
local arr = {}
for _, v in pairs(arg) do
table.insert(arr, getTarget(v))
end
data:extend(arr)
end
end
return {
ExtendAll = ExtendAll
}
|
-- This file is huge and Noita doesn't have real requires, so
-- manually guard against multiple dofiles
if JSON then return end
-- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2017 Jeffrey Friedl
-- http://regex.info/blog/
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as:
-- 1) the copyright notice above is maintained
-- 2) the web-page links above are maintained
-- 3) the 'AUTHOR_NOTE' string below is maintained
--
local VERSION = '20170927.26' -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20170927.26 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- JSON definition: http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING DURING DECODE
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location (and, an 'etc' argument had been
-- provided to decode(), its value is tacked onto the message as well),
-- and then calls JSON.assert(), which itself defaults to Lua's built-in
-- assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the 'etc' argument allows stronger coordination between
-- decoding and error reporting, especially when you provide your own
-- error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
-- If the JSON text passed to decode() has trailing garbage (e.g. as with the JSON "[123]xyzzy"),
-- the method
--
-- JSON:onTrailingGarbage(json_text, location, parsed_value, etc)
--
-- is invoked, where:
--
-- 'json_text' is the original JSON text being parsed,
-- 'location' is the count of bytes into 'json_text' where the garbage starts (6 in the example),
-- 'parsed_value' is the Lua result of what was successfully parsed ({123} in the example),
-- 'etc' is as above.
--
-- If JSON:onTrailingGarbage() does not abort, it should return the value decode() should return,
-- or nil + an error message.
--
-- local new_value, error_message = JSON:onTrailingGarbage()
--
-- The default JSON:onTrailingGarbage() simply invokes JSON:onDecodeError("trailing garbage"...),
-- but you can have this package ignore trailing garbage via
--
-- function JSON:onTrailingGarbage(json_text, location, parsed_value, etc)
-- return parsed_value
-- end
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object. Also see "HANDLING UNSUPPORTED VALUE TYPES" below.
--
-- The 'etc' in the error call is the second argument to encode() and encode_pretty(), or nil if it wasn't provided.
--
--
--
--
-- ENCODING OPTIONS
--
-- An optional third argument, a table of options, can be provided to encode().
--
-- encode_options = {
-- -- options for making "pretty" human-readable JSON (see "PRETTY-PRINTING" below)
-- pretty = true, -- turn pretty formatting on
-- indent = " ", -- use this indent for each level of an array/object
-- align_keys = false, -- if true, align the keys in a way that sounds like it should be nice, but is actually ugly
-- array_newline = false, -- if true, array elements become one to a line rather than inline
--
-- -- other output-related options
-- null = "\0", -- see "ENCODING JSON NULL VALUES" below
-- stringsAreUtf8 = false, -- see "HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA" below
-- }
--
-- json_string = JSON:encode(mytable, etc, encode_options)
--
--
--
-- For reference, the defaults are:
--
-- pretty = false
-- null = nil,
-- stringsAreUtf8 = false,
--
--
--
-- PRETTY-PRINTING
--
-- Enabling the 'pretty' encode option helps generate human-readable JSON.
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true,
-- indent = " ",
-- align_keys = false,
-- })
--
-- encode_pretty() is also provided: it's identical to encode() except
-- that encode_pretty() provides a default options table if none given in the call:
--
-- { pretty = true, indent = " ", align_keys = false, array_newline = false }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following lines all return identical strings:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = false, array_newline = false})
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " " })
-- JSON:encode (data, nil, { pretty = true, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA
--
-- If the 'stringsAreUtf8' encode option is set to true, consider Lua strings not as a sequence of bytes,
-- but as a sequence of UTF-8 characters.
--
-- Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
-- separators, if found in a string, are encoded with a JSON escape instead of being dumped as is.
-- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
-- to also be valid Java.
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- ENCODING JSON NULL VALUES
--
-- Lua tables completely omit keys whose value is nil, so without special handling there's
-- no way to represent JSON object's null value in a Lua table. For example
-- JSON:encode({ username = "admin", password = nil })
--
-- produces:
--
-- {"username":"admin"}
--
-- In order to actually produce
--
-- {"username":"admin", "password":null}
--
-- one can include a string value for a "null" field in the options table passed to encode()....
-- any Lua table entry with that value becomes null in the JSON output:
--
-- JSON:encode({ username = "admin", password = "xyzzy" }, -- First arg is the Lua table to encode as JSON.
-- nil, -- Second arg is the 'etc' value, ignored here
-- { null = "xyzzy" }) -- Third arg is th options table
--
-- produces:
--
-- {"username":"admin", "password":null}
--
-- Just be sure to use a string that is otherwise unlikely to appear in your data.
-- The string "\0" (a string with one null byte) may well be appropriate for many applications.
--
-- The "null" options also applies to Lua tables that become JSON arrays.
-- JSON:encode({ "one", "two", nil, nil })
--
-- produces
--
-- ["one","two"]
--
-- while
--
-- NullPlaceholder = "\0"
-- encode_options = { null = NullPlaceholder }
-- JSON:encode({ "one", "two", NullPlaceholder, NullPlaceholder}, nil, encode_options)
-- produces
--
-- ["one","two",null,null]
--
--
--
-- HANDLING LARGE AND/OR PRECISE NUMBERS
--
--
-- Without special handling, numbers in JSON can lose precision in Lua.
-- For example:
--
-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
--
-- print("small: ", type(T.small), T.small)
-- print("big: ", type(T.big), T.big)
-- print("precise: ", type(T.precise), T.precise)
--
-- produces
--
-- small: number 12345
-- big: number 1.2345678901235e+28
-- precise: number 9876.6789012346
--
-- Precision is lost with both 'big' and 'precise'.
--
-- This package offers ways to try to handle this better (for some definitions of "better")...
--
-- The most precise method is by setting the global:
--
-- JSON.decodeNumbersAsObjects = true
--
-- When this is set, numeric JSON data is encoded into Lua in a form that preserves the exact
-- JSON numeric presentation when re-encoded back out to JSON, or accessed in Lua as a string.
--
-- This is done by encoding the numeric data with a Lua table/metatable that returns
-- the possibly-imprecise numeric form when accessed numerically, but the original precise
-- representation when accessed as a string.
--
-- Consider the example above, with this option turned on:
--
-- JSON.decodeNumbersAsObjects = true
--
-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
--
-- print("small: ", type(T.small), T.small)
-- print("big: ", type(T.big), T.big)
-- print("precise: ", type(T.precise), T.precise)
--
-- This now produces:
--
-- small: table 12345
-- big: table 12345678901234567890123456789
-- precise: table 9876.67890123456789012345
--
-- However, within Lua you can still use the values (e.g. T.precise in the example above) in numeric
-- contexts. In such cases you'll get the possibly-imprecise numeric version, but in string contexts
-- and when the data finds its way to this package's encode() function, the original full-precision
-- representation is used.
--
-- You can force access to the string or numeric version via
-- JSON:forceString()
-- JSON:forceNumber()
-- For example,
-- local probably_okay = JSON:forceNumber(T.small) -- 'probably_okay' is a number
--
-- Code the inspects the JSON-turned-Lua data using type() can run into troubles because what used to
-- be a number can now be a table (e.g. as the small/big/precise example above shows). Update these
-- situations to use JSON:isNumber(item), which returns nil if the item is neither a number nor one
-- of these number objects. If it is either, it returns the number itself. For completeness there's
-- also JSON:isString(item).
--
-- If you want to try to avoid the hassles of this "number as an object" kludge for all but really
-- big numbers, you can set JSON.decodeNumbersAsObjects and then also set one or both of
-- JSON:decodeIntegerObjectificationLength
-- JSON:decodeDecimalObjectificationLength
-- They refer to the length of the part of the number before and after a decimal point. If they are
-- set and their part is at least that number of digits, objectification occurs. If both are set,
-- objectification occurs when either length is met.
--
-- -----------------------
--
-- Even without using the JSON.decodeNumbersAsObjects option, you can encode numbers in your Lua
-- table that retain high precision upon encoding to JSON, by using the JSON:asNumber() function:
--
-- T = {
-- imprecise = 123456789123456789.123456789123456789,
-- precise = JSON:asNumber("123456789123456789.123456789123456789")
-- }
--
-- print(JSON:encode_pretty(T))
--
-- This produces:
--
-- {
-- "precise": 123456789123456789.123456789123456789,
-- "imprecise": 1.2345678912346e+17
-- }
--
--
-- -----------------------
--
-- A different way to handle big/precise JSON numbers is to have decode() merely return the exact
-- string representation of the number instead of the number itself. This approach might be useful
-- when the numbers are merely some kind of opaque object identifier and you want to work with them
-- in Lua as strings anyway.
--
-- This approach is enabled by setting
--
-- JSON.decodeIntegerStringificationLength = 10
--
-- The value is the number of digits (of the integer part of the number) at which to stringify numbers.
-- NOTE: this setting is ignored if JSON.decodeNumbersAsObjects is true, as that takes precedence.
--
-- Consider our previous example with this option set to 10:
--
-- JSON.decodeIntegerStringificationLength = 10
--
-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
--
-- print("small: ", type(T.small), T.small)
-- print("big: ", type(T.big), T.big)
-- print("precise: ", type(T.precise), T.precise)
--
-- This produces:
--
-- small: number 12345
-- big: string 12345678901234567890123456789
-- precise: number 9876.6789012346
--
-- The long integer of the 'big' field is at least JSON.decodeIntegerStringificationLength digits
-- in length, so it's converted not to a Lua integer but to a Lua string. Using a value of 0 or 1 ensures
-- that all JSON numeric data becomes strings in Lua.
--
-- Note that unlike
-- JSON.decodeNumbersAsObjects = true
-- this stringification is simple and unintelligent: the JSON number simply becomes a Lua string, and that's the end of it.
-- If the string is then converted back to JSON, it's still a string. After running the code above, adding
-- print(JSON:encode(T))
-- produces
-- {"big":"12345678901234567890123456789","precise":9876.6789012346,"small":12345}
-- which is unlikely to be desired.
--
-- There's a comparable option for the length of the decimal part of a number:
--
-- JSON.decodeDecimalStringificationLength
--
-- This can be used alone or in conjunction with
--
-- JSON.decodeIntegerStringificationLength
--
-- to trip stringification on precise numbers with at least JSON.decodeIntegerStringificationLength digits after
-- the decimal point. (Both are ignored if JSON.decodeNumbersAsObjects is true.)
--
-- This example:
--
-- JSON.decodeIntegerStringificationLength = 10
-- JSON.decodeDecimalStringificationLength = 5
--
-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
--
-- print("small: ", type(T.small), T.small)
-- print("big: ", type(T.big), T.big)
-- print("precise: ", type(T.precise), T.precise)
--
-- produces:
--
-- small: number 12345
-- big: string 12345678901234567890123456789
-- precise: string 9876.67890123456789012345
--
--
-- HANDLING UNSUPPORTED VALUE TYPES
--
-- Among the encoding errors that might be raised is an attempt to convert a table value that has a type
-- that this package hasn't accounted for: a function, userdata, or a thread. You can handle these types as table
-- values (but not as table keys) if you supply a JSON:unsupportedTypeEncoder() method along the lines of the
-- following example:
--
-- function JSON:unsupportedTypeEncoder(value_of_unsupported_type)
-- if type(value_of_unsupported_type) == 'function' then
-- return "a function value"
-- else
-- return nil
-- end
-- end
--
-- Your unsupportedTypeEncoder() method is actually called with a bunch of arguments:
--
-- self:unsupportedTypeEncoder(value, parents, etc, options, indent, for_key)
--
-- The 'value' is the function, thread, or userdata to be converted to JSON.
--
-- The 'etc' and 'options' arguments are those passed to the original encode(). The other arguments are
-- probably of little interest; see the source code. (Note that 'for_key' is never true, as this function
-- is invoked only on table values; table keys of these types still trigger the onEncodeError method.)
--
-- If your unsupportedTypeEncoder() method returns a string, it's inserted into the JSON as is.
-- If it returns nil plus an error message, that error message is passed through to an onEncodeError invocation.
-- If it returns only nil, processing falls through to a default onEncodeError invocation.
--
-- If you want to handle everything in a simple way:
--
-- function JSON:unsupportedTypeEncoder(value)
-- return tostring(value)
-- end
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onTrailingGarbage
-- onEncodeError
-- unsupportedTypeEncoder
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, indent = default_pretty_indent, align_keys = false, array_newline = false }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function getnum(op)
return type(op) == 'number' and op or op.N
end
local isNumber = {
__tostring = function(T) return T.S end,
__unm = function(op) return getnum(op) end,
__concat = function(op1, op2) return tostring(op1) .. tostring(op2) end,
__add = function(op1, op2) return getnum(op1) + getnum(op2) end,
__sub = function(op1, op2) return getnum(op1) - getnum(op2) end,
__mul = function(op1, op2) return getnum(op1) * getnum(op2) end,
__div = function(op1, op2) return getnum(op1) / getnum(op2) end,
__mod = function(op1, op2) return getnum(op1) % getnum(op2) end,
__pow = function(op1, op2) return getnum(op1) ^ getnum(op2) end,
__lt = function(op1, op2) return getnum(op1) < getnum(op2) end,
__eq = function(op1, op2) return getnum(op1) == getnum(op2) end,
__le = function(op1, op2) return getnum(op1) <= getnum(op2) end,
}
isNumber.__index = isNumber
function OBJDEF:asNumber(item)
if getmetatable(item) == isNumber then
-- it's already a JSON number object.
return item
elseif type(item) == 'table' and type(item.S) == 'string' and type(item.N) == 'number' then
-- it's a number-object table that lost its metatable, so give it one
return setmetatable(item, isNumber)
else
-- the normal situation... given a number or a string representation of a number....
local holder = {
S = tostring(item), -- S is the representation of the number as a string, which remains precise
N = tonumber(item), -- N is the number as a Lua number.
}
return setmetatable(holder, isNumber)
end
end
--
-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
-- return the string version. This shouldn't be needed often because the 'isNumber' object should autoconvert
-- to a string in most cases, but it's here to allow it to be forced when needed.
--
function OBJDEF:forceString(item)
if type(item) == 'table' and type(item.S) == 'string' then
return item.S
else
return tostring(item)
end
end
--
-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
-- return the numeric version.
--
function OBJDEF:forceNumber(item)
if type(item) == 'table' and type(item.N) == 'number' then
return item.N
else
return tonumber(item)
end
end
--
-- If the given item is a number, return it. Otherwise, return nil.
-- This, this can be used both in a conditional and to access the number when you're not sure its form.
--
function OBJDEF:isNumber(item)
if type(item) == 'number' then
return item
elseif type(item) == 'table' and type(item.N) == 'number' then
return item.N
else
return nil
end
end
function OBJDEF:isString(item)
if type(item) == 'string' then
return item
elseif type(item) == 'table' and type(item.S) == 'string' then
return item.S
else
return nil
end
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at byte %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
function OBJDEF:onTrailingGarbage(json_text, location, parsed_value, etc)
return self:onDecodeError("trailing garbage", json_text, location, etc)
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, options)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
if options.decodeNumbersAsObjects then
local objectify = false
if not options.decodeIntegerObjectificationLength and not options.decodeDecimalObjectificationLength then
-- no options, so objectify
objectify = true
elseif (options.decodeIntegerObjectificationLength
and
(integer_part:len() >= options.decodeIntegerObjectificationLength or exponent_part:len() > 0))
or
(options.decodeDecimalObjectificationLength
and
(decimal_part:len() >= options.decodeDecimalObjectificationLength or exponent_part:len() > 0))
then
-- have options and they are triggered, so objectify
objectify = true
end
if objectify then
return OBJDEF:asNumber(full_number_text), i
end
-- else, fall through to try to return as a straight-up number
else
-- Not always decoding numbers as objects, so perhaps encode as strings?
--
-- If we're told to stringify only under certain conditions, so do.
-- We punt a bit when there's an exponent by just stringifying no matter what.
-- I suppose we should really look to see whether the exponent is actually big enough one
-- way or the other to trip stringification, but I'll be lazy about it until someone asks.
--
if (options.decodeIntegerStringificationLength
and
(integer_part:len() >= options.decodeIntegerStringificationLength or exponent_part:len() > 0))
or
(options.decodeDecimalStringificationLength
and
(decimal_part:len() >= options.decodeDecimalStringificationLength or exponent_part:len() > 0))
then
return full_number_text, i -- this returns the exact string representation seen in the original JSON
end
end
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
return as_number, i
end
local function grok_string(self, text, start, options)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, options)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, options)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, options.etc)
return nil, i -- in case the error method doesn't abort, return something sensible
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i, options)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, options.etc)
return nil, i -- in case the error method doesn't abort, return something sensible
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local function grok_array(self, text, start, options)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i, options)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or ']'", text, i, options.etc)
return nil, i -- in case the error method doesn't abort, return something sensible
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, options.etc)
return nil, i -- in case the error method doesn't abort, return something sensible
end
grok_one = function(self, text, start, options)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, options.etc)
return nil, start -- in case the error method doesn't abort, return something sensible
end
if text:find('^"', start) then
return grok_string(self, text, start, options.etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, options)
elseif text:find('^%{', start) then
return grok_object(self, text, start, options)
elseif text:find('^%[', start) then
return grok_array(self, text, start, options)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return options.null, start + 4
else
self:onDecodeError("can't parse JSON", text, start, options.etc)
return nil, 1 -- in case the error method doesn't abort, return something sensible
end
end
function OBJDEF:decode(text, etc, options)
--
-- If the user didn't pass in a table of decode options, make an empty one.
--
if type(options) ~= 'table' then
options = {}
end
--
-- If they passed in an 'etc' argument, stuff it into the options.
-- (If not, any 'etc' field in the options they passed in remains to be used)
--
if etc ~= nil then
options.etc = etc
end
if type(self) ~= 'table' or self.__index ~= OBJDEF then
local error_message = "JSON:decode must be called in method format"
OBJDEF:onDecodeError(error_message, nil, nil, options.etc)
return nil, error_message -- in case the error method doesn't abort, return something sensible
end
if text == nil then
local error_message = "nil passed to JSON:decode()"
self:onDecodeOfNilError(error_message, nil, nil, options.etc)
return nil, error_message -- in case the error method doesn't abort, return something sensible
elseif type(text) ~= 'string' then
local error_message = "expected string argument to JSON:decode()"
self:onDecodeError(string.format("%s, got %s", error_message, type(text)), nil, nil, options.etc)
return nil, error_message -- in case the error method doesn't abort, return something sensible
end
if text:match('^%s*$') then
-- an empty string is nothing, but not an error
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
local error_message = "HTML passed to JSON:decode()"
self:onDecodeOfHTMLError(error_message, text, nil, options.etc)
return nil, error_message -- in case the error method doesn't abort, return something sensible
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
local error_message = "JSON package groks only UTF-8, sorry"
self:onDecodeError(error_message, text, nil, options.etc)
return nil, error_message -- in case the error method doesn't abort, return something sensible
end
--
-- apply global options
--
if options.decodeNumbersAsObjects == nil then
options.decodeNumbersAsObjects = self.decodeNumbersAsObjects
end
if options.decodeIntegerObjectificationLength == nil then
options.decodeIntegerObjectificationLength = self.decodeIntegerObjectificationLength
end
if options.decodeDecimalObjectificationLength == nil then
options.decodeDecimalObjectificationLength = self.decodeDecimalObjectificationLength
end
if options.decodeIntegerStringificationLength == nil then
options.decodeIntegerStringificationLength = self.decodeIntegerStringificationLength
end
if options.decodeDecimalStringificationLength == nil then
options.decodeDecimalStringificationLength = self.decodeDecimalStringificationLength
end
--
-- Finally, go parse it
--
local success, value, next_i = pcall(grok_one, self, text, 1, options)
if success then
local error_message = nil
if next_i ~= #text + 1 then
-- something's left over after we parsed the first thing.... whitespace is allowed.
next_i = skip_whitespace(text, next_i)
-- if we have something left over now, it's trailing garbage
if next_i ~= #text + 1 then
value, error_message = self:onTrailingGarbage(text, next_i, value, options.etc)
end
end
return value, error_message
else
-- If JSON:onDecodeError() didn't abort out of the pcall, we'll have received
-- the error message here as "value", so pass it along as an assert.
local error_message = value
if self.assert then
self.assert(false, error_message)
else
assert(false, error_message)
end
-- ...and if we're still here (because the assert didn't throw an error),
-- return a nil and throw the error message on as a second arg
return nil, error_message
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local LINE_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2028)
local PARAGRAPH_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2029)
local function json_string_literal(value, options)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
if options.stringsAreUtf8 then
--
-- This feels really ugly to just look into a string for the sequence of bytes that we know to be a particular utf8 character,
-- but utf8 was designed purposefully to make this kind of thing possible. Still, feels dirty.
-- I'd rather decode the byte stream into a character stream, but it's not technically needed so
-- not technically worth it.
--
newval = newval:gsub(LINE_SEPARATOR_as_utf8, '\\u2028'):gsub(PARAGRAPH_SEPARATOR_as_utf8,'\\u2029')
end
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
elseif type(key) == 'boolean' then
table.insert(string_keys, tostring(key))
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
--
-- pretty -- If true, return a pretty-printed version.
--
-- indent -- A string (usually of spaces) used to indent each nested level.
--
-- align_keys -- If true, align all the keys when formatting a table. The result is uglier than one might at first imagine.
-- Results are undefined if 'align_keys' is true but 'pretty' is not.
--
-- array_newline -- If true, array elements are formatted each to their own line. The default is to all fall inline.
-- Results are undefined if 'array_newline' is true but 'pretty' is not.
--
-- null -- If this exists with a string value, table elements with this value are output as JSON null.
--
-- stringsAreUtf8 -- If true, consider Lua strings not as a sequence of bytes, but as a sequence of UTF-8 characters.
-- (Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
-- separators, if found in a string, are encoded with a JSON escape instead of as raw UTF-8.
-- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
-- to also be valid Java.)
--
--
local function encode_value(self, value, parents, etc, options, indent, for_key)
--
-- keys in a JSON object can never be null, so we don't even consider options.null when converting a key value
--
if value == nil or (not for_key and options and options.null and value == options.null) then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value, options)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
if self.unsupportedTypeEncoder then
local user_value, user_error = self:unsupportedTypeEncoder(value, parents, etc, options, indent, for_key)
-- If the user's handler returns a string, use that. If it returns nil plus an error message, bail with that.
-- If only nil returned, fall through to the default error handler.
if type(user_value) == 'string' then
return user_value
elseif user_value ~= nil then
self:onEncodeError("unsupportedTypeEncoder method returned a " .. type(user_value), etc)
elseif user_error then
self:onEncodeError(tostring(user_error), etc)
end
end
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
elseif getmetatable(value) == isNumber then
return tostring(value)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local key_indent
if options.array_newline then
key_indent = indent .. tostring(options.indent or "")
else
key_indent = indent
end
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, key_indent))
end
if options.array_newline then
result_value = "[\n" .. key_indent .. table.concat(ITEMS, ",\n" .. key_indent) .. "\n" .. indent .. "]"
elseif options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent, true)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent, true)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
local function top_level_encode(self, value, etc, options)
local val = encode_value(self, value, {}, etc, options)
if val == nil then
--PRIVATE("may need to revert to the previous public verison if I can't figure out what the guy wanted")
return val
else
return val
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
--
-- If the user didn't pass in a table of decode options, make an empty one.
--
if type(options) ~= 'table' then
options = {}
end
return top_level_encode(self, value, etc, options)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
--
-- If the user didn't pass in a table of decode options, use the default pretty ones
--
if type(options) ~= 'table' then
options = default_pretty_options
end
return top_level_encode(self, value, etc, options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
JSON = OBJDEF:new() -- Noita expects to just dofile everything :(
--return OBJDEF:new()
--
-- Version history:
--
-- 20170927.26 Use option.null in decoding as well. Thanks to Max Sindwani for the bump, and sorry to Oliver Hitz
-- whose first mention of it four years ago was completely missed by me.
--
-- 20170823.25 Added support for JSON:unsupportedTypeEncoder().
-- Thanks to Chronos Phaenon Eosphoros (https://github.com/cpeosphoros) for the idea.
--
-- 20170819.24 Added support for boolean keys in tables.
--
-- 20170416.23 Added the "array_newline" formatting option suggested by yurenchen (http://www.yurenchen.com/)
--
-- 20161128.22 Added:
-- JSON:isString()
-- JSON:isNumber()
-- JSON:decodeIntegerObjectificationLength
-- JSON:decodeDecimalObjectificationLength
--
-- 20161109.21 Oops, had a small boo-boo in the previous update.
--
-- 20161103.20 Used to silently ignore trailing garbage when decoding. Now fails via JSON:onTrailingGarbage()
-- http://seriot.ch/parsing_json.php
--
-- Built-in error message about "expected comma or ']'" had mistakenly referred to '['
--
-- Updated the built-in error reporting to refer to bytes rather than characters.
--
-- The decode() method no longer assumes that error handlers abort.
--
-- Made the VERSION string a string instead of a number
--
-- 20160916.19 Fixed the isNumber.__index assignment (thanks to Jack Taylor)
--
-- 20160730.18 Added JSON:forceString() and JSON:forceNumber()
--
-- 20160728.17 Added concatenation to the metatable for JSON:asNumber()
--
-- 20160709.16 Could crash if not passed an options table (thanks jarno heikkinen <jarnoh@capturemonkey.com>).
--
-- Made JSON:asNumber() a bit more resilient to being passed the results of itself.
--
-- 20160526.15 Added the ability to easily encode null values in JSON, via the new "null" encoding option.
-- (Thanks to Adam B for bringing up the issue.)
--
-- Added some support for very large numbers and precise floats via
-- JSON.decodeNumbersAsObjects
-- JSON.decodeIntegerStringificationLength
-- JSON.decodeDecimalStringificationLength
--
-- Added the "stringsAreUtf8" encoding option. (Hat tip to http://lua-users.org/wiki/JsonModules )
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
|
PLUGIN.name = "Prop Descriptions"
PLUGIN.author = "Blazing & Angelsaur"
PLUGIN.desc = "Set descriptions for props."
nut.command.add("propdesc", {
syntax = "<string description>",
adminOnly = true,
onRun = function(client, arguments)
local objdesc = arguments[1];
local ent = client:GetEyeTrace().Entity
if (!arguments[1]) then
ent:setNetVar("exDesc", "")
end
if (IsValid(ent)) then
ent:setNetVar("exDesc", objdesc)
end
end
})
function PLUGIN:ShouldDrawEntityInfo(entity)
if (IsValid(entity) and (entity:GetClass("prop_*")) and entity:getNetVar("exDesc", exdesc)) then
return true
end
end
local drawText = nut.util.drawText
local descInfo = {}
function PLUGIN:DrawEntityInfo(entity, alpha)
local exdesc = entity:getNetVar("exDesc")
local stringFind = string.find
descInfo = {}
if stringFind(entity:GetClass(), "prop_") then
if (IsValid(entity) and exdesc ) then
if (exdesc != entity.nutDescCache) then
entity.nutDescCache = exdesc
entity.nutDescLines = nut.util.wrapText(exdesc, ScrW() * 0.7, "nutMediumFont")
end
for i = 1, #entity.nutDescLines do
descInfo[#descInfo + 1] = {entity.nutDescLines[i]}
end
local position = entity:LocalToWorld(entity:OBBCenter()):ToScreen()
local ty = 0
local x, y = position.x, position.y
-- hook.Run("DrawDescInfo", descInfo)
for i = 1, #descInfo do
local info = descInfo[i]
_, ty = drawText(info[1], x, y, color_white, 1, 1, "nutMediumFont")
y = y + ty
end
end
end
end
local entityMeta = FindMetaTable("Entity")
function entityMeta:getExDesc()
return self:getNetVar("exDesc")
end
|
require "struct.class"
base_type = class() -- 定义一个基类 base_type
function base_type:ctor(x) -- 定义 base_type 的构造函数
print("base_type ctor")
self.x=x
end
function base_type:print_x() -- 定义一个成员函数 base_type:print_x
print(self.x)
end
function base_type:hello() -- 定义另一个成员函数 base_type:hello
print("hello base_type")
end
return base_type
|
-- =============================================================
-- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved)
-- =============================================================
_G.ssk = _G.ssk or {}
local points = {}
_G.ssk.points = points
-- ==
-- ssk.points:new( ... ) - Create a new points instance.
-- ==
function points.new( ... )
local pointsInstance = {}
-- ==
-- pointsInstance:add( x1,y1,... ) - Appends any number of point x,y pairs to the points list.
-- ==
function pointsInstance:add(...)
if(#arg % 2 == 1) then return end
local i = 1
while(i < #arg) do
pointsInstance[#pointsInstance+1] = {x=arg[i],y=arg[i+1]}
i = i + 2
end
end
-- ==
-- pointsInstance:insert( index, x1,y1,... )
-- ==
function pointsInstance:insert(index, ...)
local index = index or 1
if(#arg % 2 == 1) then return end
local i = 1
while(i < #arg) do
table.insert( self, index, {x=arg[i],y=arg[i+1]} )
i = i + 2
index = index + 1
end
end
-- ==
-- pointsInstance:get( index ) - Gets a single point out of the points list.
-- ==
function pointsInstance:get(index)
local index = index or 1
return pointsInstance[index]
end
-- ==
-- pointsInstance:remove( index ) - Removes a single point from the points list
-- ==
function pointsInstance:remove(index)
local index = index or 1
local element = table.remove( self, index )
return element
end
-- ==
-- pointsInstance:push( x1,y1,... ) - Treats points list like a stack/FILO and pushes one or more point sets onto the points list top (end).
-- ==
function pointsInstance:push(...)
if(#arg % 2 == 1) then return end
local i = 1
while(i < #arg) do
pointsInstance[#pointsInstance+1] = {x=arg[i],y=arg[i+1]}
i = i + 2
end
end
-- ==
-- pointsInstance:peek( ) - Treats points list like a stack/FILO and retrieves the point at the top (end) of the points list.
-- ==
function pointsInstance:peek()
return self[#self]
end
-- ==
-- pointsInstance:pop( ) - Treats points list like a stack/FILO and pops the point at the top (end) off the points list.
-- ==
function pointsInstance:pop()
if( not #self ) then return nil end
local element = self[#self]
self[#self] = nil
return element
end
-- ==
-- pointsInstance:push_head( x1,y1,... ) - Treats points list like a queue/FIFO and pushes one or more point sets (in reverse order) onto the points list front. Like calling insert(1, x1,y1), insert(1, x2,y2), ..., insert(1, xN,yN),
-- ==
function pointsInstance:push_head(...)
if(#arg % 2 == 1) then return end
local i = 1
while(i < #arg) do
table.insert( self, 1, {x=arg[i],y=arg[i+1]} )
i = i + 2
end
end
-- ==
-- pointsInstance:peek_head( ) - Treats points list like a queue/FIFO and retrieves the point at the front of the points list. Like a get at 1.
-- ==
function pointsInstance:peek_head()
return self[1]
end
-- ==
-- pointsInstance:pop_head( ) - Treats points list like a queue/FIFO and pops the point at the front off the points list. Like a remove at 1.
-- ==
function pointsInstance:pop_head(x,y)
local element = table.remove( self, 1 )
return element
end
-- If any points were passed, add them now
pointsInstance:add( unpack( arg ) )
return pointsInstance
end
return points
|
local BotsInit = require( "game/botsinit" );
local MyModule = BotsInit.CreateGeneric();
local Data = require(GetScriptDirectory() .. "/ability_item_data")
local mutil = require(GetScriptDirectory() .. "/MyUtility")
local bot = GetBot();
function AbilityLevelUpThink ()
end
function CourierUsageThink ()
end
function BuybackUsageThink ()
end
if bot:GetUnitName() == 'npc_dota_hero_monkey_king' then
local trueMK = nil;
for i, id in pairs(GetTeamPlayers(GetTeam())) do
if IsPlayerBot(id) and GetSelectedHeroName(id) == 'npc_dota_hero_monkey_king' then
local member = GetTeamMember(i);
if member ~= nil then
trueMK = member;
end
end
end
if trueMK ~= nil and bot ~= trueMK then
print("AbilityItemUsage "..tostring(bot).." isn't true MK")
return;
elseif trueMK == nil or bot == trueMK then
print("AbilityItemUsage "..tostring(bot).." is true MK")
end
end
if bot:IsInvulnerable() or bot:IsHero() == false or bot:IsIllusion()
then
return;
end
function GetNumEnemyNearby(building)
local nearbynum = 0;
for i,id in pairs(GetTeamPlayers(GetOpposingTeam())) do
if IsHeroAlive(id) then
local info = GetHeroLastSeenInfo(id);
if info ~= nil then
local dInfo = info[1];
if dInfo ~= nil and GetUnitToLocationDistance(building, dInfo.location) <= 2750 and dInfo.time_since_seen < 1.0 then
nearbynum = nearbynum + 1;
end
end
end
end
return nearbynum;
end
function GetNumOfAliveHeroes(team)
local nearbynum = 0;
for i,id in pairs(GetTeamPlayers(team)) do
if IsHeroAlive(id) then
nearbynum = nearbynum + 1;
end
end
return nearbynum;
end
function GetRemainingRespawnTime()
if TimeDeath == nil then
return 0;
else
return bot:GetRespawnTime() - ( DotaTime() - TimeDeath );
end
end
function IsMeepoClone()
if bot:GetUnitName() == "npc_dota_hero_meepo" and bot:GetLevel() > 1
then
for i=0, 5 do
local item = bot:GetItemInSlot(i);
if item ~= nil and not ( string.find(item:GetName(),"boots") or string.find(item:GetName(),"treads") )
then
return false;
end
end
return true;
end
return false;
end
function ItemUsageThink()
--print(bot:GetUnitName().."item usage")
if GetGameState() ~= GAME_STATE_PRE_GAME and GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS then
return;
end
UnImplementedItemUsage()
--UseShrine()
end
function AbilityUsageThink()
if GetGameState() ~= GAME_STATE_PRE_GAME and GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS then
return;
end
local bot = GetBot()
local enemies = bot:GetNearbyHeroes(1600, true, BOT_MODE_NONE )
local enemy = bot:GetTarget()
if not enemy or not enemy:IsAlive() then
enemy = enemies[1]
end
if mutil.CanNotUseAbility(bot) and enemy then
bot:Action_ClearActions(false)
bot:Action_AttackMove(enemy:GetAbsOrigin())
return
end
if bot:IsChanneling() or bot:IsUsingAbility() or bot:IsInvisible() or bot:IsMuted( ) or bot:HasModifier("modifier_doom_bringer_doom") then
return;
end
mutil.IsGoingOnSomeone(bot) -- setup targets if needed
local name = bot:GetUnitName()
local shortName = name:sub(15, -1)
if shortName == "sand_king" then
shortName = "sandking"
end
local allies = bot:GetNearbyHeroes(1600, false, BOT_MODE_NONE )
local didAct = false
local couldAct = false
if #enemies == 0 then
return
end
for abilityIndex = 0, 8 do
local ability = bot:GetAbilityInSlot(abilityIndex)
local target = enemy
if bit.band(ability:GetTargetTeam(), 3) == 1 then
target = allies[RandomInt(1, #allies)]
end
if not didAct and ability and ability:GetName():sub(-4) ~= "aura" then
local abilityName = ability:GetName()
if not ability:IsHidden() and not ability:IsPassive() and not ability:IsTalent() and ability:IsFullyCastable() and ability:GetName():sub(0, #shortName) == shortName then
local modifier = Data[abilityName]
local behave = ability:GetBehavior()
local targetFlags = ability:GetTargetType()
if modifier ~= false then
modifier = modifier or "none"
if not bot:HasModifier(modifier) and bit.band(behave, 4) == 4 then
local shouldCast, isAOE = ConsiderAOERadiusAbility(bot, ability)
if shouldCast > 0 then
print('Casting AOE ability ' .. ability:GetName() .. ' / ' .. tostring(ability:GetToggleState()))
didAct, couldAct = CheckAndUseAbility(ability, modifier, nil, true)
elseif not isAOE then
didAct, couldAct = CheckAndUseAbility(ability, modifier, nil, true)
end
elseif bit.band(targetFlags, 64) == 64 then
-- this ability targets trees
local trees = bot:GetNearbyTrees(600)
if #trees > 0 then
didAct = true
bot:Action_UseAbilityOnTree(ability, trees[1])
end
elseif target then
didAct, couldAct = CheckAndUseAbility(ability, modifier, target, true)
end
end
end
end
end
if enemy and not didAct and not bot:IsChanneling() and not bot:IsUsingAbility() then
bot:Action_ClearActions(false)
bot:Action_AttackMove(enemy:GetAbsOrigin())
end
if couldAct or not enemy then
-- last, change targets
local targets = bot:GetNearbyHeroes(1200, true, BOT_MODE_NONE)
if #targets < 1 then
return didAct, couldAct
end
local newTarget = targets[RandomInt(1, #targets)]
bot:SetTarget(newTarget)
end
return didAct, couldAct
end
function PrintCourierState(state)
if state == 0 then
print("COURIER_STATE_IDLE ");
elseif state == 1 then
print("COURIER_STATE_AT_BASE");
elseif state == 2 then
print("COURIER_STATE_MOVING");
elseif state == 3 then
print("COURIER_STATE_DELIVERING_ITEMS");
elseif state == 4 then
print("COURIER_STATE_RETURNING_TO_BASE");
elseif state == 5 then
print("COURIER_STATE_DEAD");
else
print("UNKNOWN");
end
end
local courierTime = -90;
local cState = -1;
bot.SShopUser = false;
local returnTime = -90;
local apiAvailable = false;
function IsHumanHaveItemInCourier()
local numPlayer = GetTeamPlayers(GetTeam());
for i = 1, #numPlayer
do
if not IsPlayerBot(numPlayer[i]) then
local member = GetTeamMember(i);
if member ~= nil and member:IsAlive() and member:GetCourierValue( ) > 0
then
return true;
end
end
end
return false;
end
function GetCourierEmptySlot(courier)
local amount = 0;
for i=0, 8 do
if courier:GetItemInSlot(i) == nil then
amount = amount + 1;
end
end
return amount;
end
function GetNumStashItem(unit)
local amount = 0;
for i=9, 14 do
if unit:GetItemInSlot(i) ~= nil then
amount = amount + 1;
end
end
return amount;
end
function UpdateSShopUserStatus(bot)
local numPlayer = GetTeamPlayers(GetTeam());
for i = 1, #numPlayer
do
local member = GetTeamMember(i);
if member ~= nil and IsPlayerBot(numPlayer[i]) and member:GetUnitName() ~= bot:GetUnitName()
then
member.SShopUser = false;
end
end
end
function IsTargetedByUnit(courier)
for i = 0, 10 do
local tower = GetTower(GetOpposingTeam(), i)
if tower ~= nil and tower:GetAttackTarget() == courier then
return true;
end
end
for i,id in pairs(GetTeamPlayers(GetOpposingTeam())) do
if IsHeroAlive(id) then
local info = GetHeroLastSeenInfo(id);
if info ~= nil then
local dInfo = info[1];
if dInfo ~= nil and GetUnitToLocationDistance(courier, dInfo.location) <= 700 and dInfo.time_since_seen < 0.5 then
return true;
end
end
end
end
return false;
end
function IsInvFull(npcHero)
for i=0, 8 do
if(npcHero:GetItemInSlot(i) == nil) then
return false;
end
end
return true;
end
function CanCastOnTarget( npcTarget )
return npcTarget:CanBeSeen() and not npcTarget:IsMagicImmune() and not npcTarget:IsInvulnerable();
end
function CanCastOnMagicImmuneTarget( npcTarget )
return npcTarget:CanBeSeen() and not npcTarget:IsInvulnerable();
end
function IsDisabled(npcTarget)
if npcTarget:IsRooted( ) or npcTarget:IsStunned( ) or npcTarget:IsHexed( ) or npcTarget:IsSilenced() or npcTarget:IsNightmared() then
return true;
end
return false;
end
function UseConsumables()
end
function GiveToMidLaner()
local teamPlayers = GetTeamPlayers(GetTeam())
local target = nil;
for k,v in pairs(teamPlayers)
do
local member = GetTeamMember(k);
if member ~= nil and not member:IsIllusion() and member:IsAlive() then
local num_stg = GetItemCount(member, "item_tango_single");
local num_ff = GetItemCount(member, "item_faerie_fire");
if num_ff > 0 and num_stg < 1 then
return member;
end
end
end
return nil;
end
function GetItemCount(unit, item_name)
local count = 0;
for i = 0, 8
do
local item = unit:GetItemInSlot(i)
if item ~= nil and item:GetName() == item_name then
count = count + 1;
end
end
return count;
end
function CanSwitchPTStat(pt)
if bot:GetPrimaryAttribute() == ATTRIBUTE_STRENGTH and pt:GetPowerTreadsStat() ~= ATTRIBUTE_STRENGTH then
return true;
elseif bot:GetPrimaryAttribute() == ATTRIBUTE_AGILITY and pt:GetPowerTreadsStat() ~= ATTRIBUTE_INTELLECT then
return true;
elseif bot:GetPrimaryAttribute() == ATTRIBUTE_INTELLECT and pt:GetPowerTreadsStat() ~= ATTRIBUTE_AGILITY then
return true;
end
return false;
end
local giveTime = -90;
function UnImplementedItemUsage()
if bot:IsChanneling() or bot:IsUsingAbility() or bot:IsInvisible() or bot:IsMuted( ) or bot:HasModifier("modifier_doom_bringer_doom") then
return;
end
local tableNearbyEnemyHeroes = bot:GetNearbyHeroes( 800, true, BOT_MODE_NONE );
local npcTarget = bot:GetTarget();
local mode = BOT_MODE_ATTACK
local pt = IsItemAvailable("item_power_treads");
if pt~=nil and pt:IsFullyCastable() then
if mode == BOT_MODE_RETREAT and pt:GetPowerTreadsStat() ~= ATTRIBUTE_STRENGTH and bot:WasRecentlyDamagedByAnyHero(5.0) then
bot:Action_UseAbility(pt);
return
elseif mode == BOT_MODE_ATTACK and CanSwitchPTStat(pt) then
bot:Action_UseAbility(pt);
return
else
local enemies = bot:GetNearbyHeroes( 1300, true, BOT_MODE_NONE );
if #enemies == 0 and mode ~= BOT_MODE_RETREAT and CanSwitchPTStat(pt) then
bot:Action_UseAbility(pt);
return
end
end
end
local bas = IsItemAvailable("item_ring_of_basilius");
if bas~=nil and bas:IsFullyCastable() then
if mode == BOT_MODE_LANING and not bas:GetToggleState() then
bot:Action_UseAbility(bas);
return
elseif mode ~= BOT_MODE_LANING and bas:GetToggleState() then
bot:Action_UseAbility(bas);
return
end
end
local aq = IsItemAvailable("item_ring_of_aquila");
if aq~=nil and aq:IsFullyCastable() then
if mode == BOT_MODE_LANING and not aq:GetToggleState() then
bot:Action_UseAbility(aq);
return
elseif mode ~= BOT_MODE_LANING and aq:GetToggleState() then
bot:Action_UseAbility(aq);
return
end
end
local itg=IsItemAvailable("item_tango");
if itg~=nil and itg:IsFullyCastable() then
local tCharge = itg:GetCurrentCharges()
if DotaTime() > -80 and DotaTime() < 0 and bot:DistanceFromFountain() == 0 and role.CanBeSupport(bot:GetUnitName())
and bot:GetAssignedLane() ~= LANE_MID and tCharge > 2 and DotaTime() > giveTime + 2.0 then
local target = GiveToMidLaner()
if target ~= nil then
bot:ActionImmediate_Chat(string.gsub(bot:GetUnitName(),"npc_dota_hero_","")..
" giving tango to "..
string.gsub(target:GetUnitName(),"npc_dota_hero_","")
, false);
bot:Action_UseAbilityOnEntity(itg, target);
giveTime = DotaTime();
return;
end
elseif bot:GetActiveMode() == BOT_MODE_LANING and role.CanBeSupport(bot:GetUnitName()) and tCharge > 1 and DotaTime() > giveTime + 2.0 then
local allies = bot:GetNearbyHeroes(1200, false, BOT_MODE_NONE)
for _,ally in pairs(allies)
do
local tangoSlot = ally:FindItemSlot('item_tango');
if ally:GetUnitName() ~= bot:GetUnitName() and not ally:IsIllusion()
and tangoSlot == -1 and GetItemCount(ally, "item_tango_single") == 0
then
bot:Action_UseAbilityOnEntity(itg, ally);
giveTime = DotaTime();
return
end
end
end
end
local bdg=IsItemAvailable("item_blink");
if bdg~=nil and bdg:IsFullyCastable() then
if mutil.IsStuck(bot)
then
bot:ActionImmediate_Chat("I'm using blink while stuck.", true);
bot:Action_UseAbilityOnLocation(bdg, bot:GetXUnitsTowardsLocation( GetAncient(GetTeam()):GetLocation(), 1100 ));
return;
end
end
local fst=IsItemAvailable("item_force_staff");
if fst~=nil and fst:IsFullyCastable() then
if mutil.IsStuck(bot)
then
bot:ActionImmediate_Chat("I'm using force staff while stuck.", true);
bot:Action_UseAbilityOnEntity(fst, bot);
return;
end
end
local tpt=IsItemAvailable("item_tpscroll");
if tpt~=nil and tpt:IsFullyCastable() then
if mutil.IsStuck(bot)
then
bot:ActionImmediate_Chat("I'm using tp while stuck.", true);
bot:Action_UseAbilityOnLocation(tpt, GetAncient(GetTeam()):GetLocation());
return;
end
end
local its=IsItemAvailable("item_tango_single");
if its~=nil and its:IsFullyCastable() and bot:DistanceFromFountain() > 1000 then
if DotaTime() > 10*60
then
local tableNearbyEnemyHeroes = bot:GetNearbyHeroes( 1600, true, BOT_MODE_NONE );
local trees = bot:GetNearbyTrees(1000);
if trees[1] ~= nil and ( IsLocationVisible(GetTreeLocation(trees[1])) or IsLocationPassable(GetTreeLocation(trees[1])) )
and #tableNearbyEnemyHeroes == 0
then
bot:Action_UseAbilityOnTree(its, trees[1]);
return;
end
end
end
local irt=IsItemAvailable("item_iron_talon");
if irt~=nil and irt:IsFullyCastable() then
if bot:GetActiveMode() == BOT_MODE_FARM
then
local neutrals = bot:GetNearbyNeutralCreeps(500);
local maxHP = 0;
local target = nil;
for _,c in pairs(neutrals) do
local cHP = c:GetHealth();
if cHP > maxHP and not c:IsAncientCreep() then
maxHP = cHP;
target = c;
end
end
if target ~= nil then
bot:Action_UseAbilityOnEntity(irt, target);
return;
end
end
end
local msh=IsItemAvailable("item_moon_shard");
if msh~=nil and msh:IsFullyCastable() then
if not bot:HasModifier("modifier_item_moon_shard_consumed")
then
bot:Action_UseAbilityOnEntity(msh, bot);
return;
end
end
local mg=IsItemAvailable("item_enchanted_mango");
if mg~=nil and mg:IsFullyCastable() then
if bot:GetMana()/bot:GetMaxMana() < 0.10 and mode == BOT_MODE_ATTACK then
bot:Action_UseAbility(mg);
return;
end
end
local tok=IsItemAvailable("item_tome_of_knowledge");
if tok~=nil and tok:IsFullyCastable() then
bot:Action_UseAbility(tok);
return;
end
local ff=IsItemAvailable("item_faerie_fire");
if ff~=nil and ff:IsFullyCastable() then
if ( mode == BOT_MODE_RETREAT and
bot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH and
bot:DistanceFromFountain() > 0 and
( bot:GetHealth() / bot:GetMaxHealth() ) < 0.15 ) or DotaTime() > 10*60
then
bot:Action_UseAbility(ff);
return;
end
end
local bst=IsItemAvailable("item_bloodstone");
if bst ~= nil and bst:IsFullyCastable() then
if mode == BOT_MODE_RETREAT and
bot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH and
( bot:GetHealth() / bot:GetMaxHealth() ) < 0.30 - ( bot:GetLevel() / 500 )
then
bot:Action_UseAbilityOnLocation(bst, bot:GetLocation());
return;
end
end
local pb=IsItemAvailable("item_phase_boots");
if pb~=nil and pb:IsFullyCastable()
then
if ( mode == BOT_MODE_ATTACK or
mode == BOT_MODE_RETREAT or
mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK or
mode == BOT_MODE_DEFEND_ALLY )
then
bot:Action_UseAbility(pb);
return;
end
end
local eb=IsItemAvailable("item_ethereal_blade");
if eb~=nil and eb:IsFullyCastable() and bot:GetUnitName() ~= "npc_dota_hero_morphling"
then
if ( mode == BOT_MODE_ATTACK or
mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK or
mode == BOT_MODE_DEFEND_ALLY )
then
local npcTarget = bot:GetTarget();
if ( npcTarget ~= nil and npcTarget:IsHero() and CanCastOnTarget(npcTarget) and GetUnitToUnitDistance(npcTarget, bot) < 1000 )
then
bot:Action_UseAbilityOnEntity(eb,npcTarget);
return
end
end
end
local rs=IsItemAvailable("item_refresher_shard");
if rs~=nil and rs:IsFullyCastable()
then
if ( mode == BOT_MODE_ATTACK or
mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK or
mode == BOT_MODE_DEFEND_ALLY ) and mutil.CanUseRefresherShard(bot)
then
bot:Action_UseAbility(rs);
return
end
end
local ro=IsItemAvailable("item_refresher");
if ro~=nil and ro:IsFullyCastable()
then
if ( mode == BOT_MODE_ATTACK or
mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK or
mode == BOT_MODE_DEFEND_ALLY ) and mutil.CanUseRefresherOrb(bot)
then
bot:Action_UseAbility(ro);
return
end
end
local sc=IsItemAvailable("item_solar_crest");
if sc~=nil and sc:IsFullyCastable()
then
if ( mode == BOT_MODE_ATTACK or
mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK or
mode == BOT_MODE_DEFEND_ALLY )
then
if ( npcTarget ~= nil and npcTarget:IsHero()
and not npcTarget:HasModifier('modifier_item_solar_crest_armor_reduction')
and not npcTarget:IsMagicImmune()
and GetUnitToUnitDistance(npcTarget, bot) < 900 )
then
bot:Action_UseAbilityOnEntity(sc, npcTarget);
return
end
end
end
if sc~=nil and sc:IsFullyCastable() then
local Allies=bot:GetNearbyHeroes(1000,false,BOT_MODE_NONE);
for _,Ally in pairs(Allies) do
if Ally:GetUnitName() ~= bot:GetUnitName() and not Ally:HasModifier('modifier_item_solar_crest_armor_reduction') and
( ( Ally:GetHealth()/Ally:GetMaxHealth() < 0.35 and tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 and CanCastOnTarget(Ally) ) or
( IsDisabled(Ally) and CanCastOnTarget(Ally) ) )
then
bot:Action_UseAbilityOnEntity(sc,Ally);
return;
end
end
end
local se=IsItemAvailable("item_silver_edge");
if se ~= nil and se:IsFullyCastable() then
if mode == BOT_MODE_RETREAT and bot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH and
tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0
then
bot:Action_UseAbility(se);
return;
end
if ( mode == BOT_MODE_ROAM or
mode == BOT_MODE_TEAM_ROAM or
mode == BOT_MODE_GANK )
then
if ( npcTarget ~= nil and npcTarget:IsHero() and GetUnitToUnitDistance(npcTarget, bot) > 1000 and GetUnitToUnitDistance(npcTarget, bot) < 2500 )
then
bot:Action_UseAbility(se);
return;
end
end
end
local hood=IsItemAvailable("item_pipe") or IsItemAvailable("item_hood_of_defiance");
if hood~=nil and hood:IsFullyCastable() and bot:GetHealth()/bot:GetMaxHealth()<0.8 and not bot:HasModifier('modifier_item_pipe_barrier')
then
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 then
bot:Action_UseAbility(hood);
return;
end
end
local cguard=IsItemAvailable("item_crimson_guard")
if cguard~=nil and cguard:IsFullyCastable() and not bot:HasModifier('modifier_item_crimson_guard_nostack')
then
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 then
bot:Action_UseAbility(cguard);
return;
end
end
local cguard=IsItemAvailable("item_ancient_janggo")
if cguard~=nil and cguard:IsFullyCastable() and not bot:HasModifier('modifier_item_ancient_janggo_active')
then
if tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 then
bot:Action_UseAbility(cguard);
return;
end
end
local lotus=IsItemAvailable("item_lotus_orb");
if lotus~=nil and lotus:IsFullyCastable()
then
if not bot:HasModifier('modifier_item_lotus_orb_active')
and not bot:IsMagicImmune()
and (
bot:IsSilenced()
or ( tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 and bot:GetHealth()/bot:GetMaxHealth() < 0.35 + (0.05*#tableNearbyEnemyHeroes) )
or HasLotusableProjectile(bot)
)
then
bot:Action_UseAbilityOnEntity(lotus,bot);
return;
end
end
if lotus~=nil and lotus:IsFullyCastable()
then
local Allies=bot:GetNearbyHeroes(1000,false,BOT_MODE_NONE);
for _,Ally in pairs(Allies) do
if not Ally:HasModifier('modifier_item_lotus_orb_active')
and not Ally:IsMagicImmune()
and (
Ally:IsSilenced()
or HasLotusableProjectile(Ally)
)
then
bot:Action_UseAbilityOnEntity(lotus,Ally);
return;
end
end
end
local hurricanpike = IsItemAvailable("item_hurricane_pike");
if hurricanpike~=nil and hurricanpike:IsFullyCastable()
then
if ( mode == BOT_MODE_RETREAT and bot:GetActiveModeDesire() >= BOT_MODE_DESIRE_HIGH )
then
for _,npcEnemy in pairs( tableNearbyEnemyHeroes )
do
if ( GetUnitToUnitDistance( npcEnemy, bot ) < 400 and CanCastOnTarget(npcEnemy) )
then
bot:Action_UseAbilityOnEntity(hurricanpike,npcEnemy);
return
end
end
if bot:IsFacingLocation(GetAncient(GetTeam()):GetLocation(),10) and bot:DistanceFromFountain() > 0
then
bot:Action_UseAbilityOnEntity(hurricanpike,bot);
return;
end
end
end
local glimer=IsItemAvailable("item_glimmer_cape");
if glimer~=nil and glimer:IsFullyCastable() then
if not bot:HasModifier('modifier_item_glimmer_cape')
and not bot:IsMagicImmune()
and ( bot:IsSilenced() or ( tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 and bot:GetHealth()/bot:GetMaxHealth() < 0.35 + (0.05*#tableNearbyEnemyHeroes) ) )
then
bot:Action_UseAbilityOnEntity(glimer,bot);
return;
end
end
if glimer~=nil and glimer:IsFullyCastable() then
local Allies=bot:GetNearbyHeroes(1000,false,BOT_MODE_NONE);
for _,Ally in pairs(Allies) do
if not Ally:HasModifier('modifier_item_glimmer_cape')
and not Ally:IsMagicImmune()
and Ally:WasRecentlyDamagedByAnyHero(2.0)
and (( Ally:GetHealth()/Ally:GetMaxHealth() < 0.35 and tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes > 0 ) or IsDisabled(Ally) or Ally:IsChanneling())
then
bot:Action_UseAbilityOnEntity(glimer,Ally);
return;
end
end
end
local hom=IsItemAvailable("item_hand_of_midas");
if hom~=nil and hom:IsFullyCastable() then
local range = bot:GetAttackRange() + 200;
local tableNearbyCreeps = bot:GetNearbyCreeps( range, true );
if #tableNearbyCreeps > 0
and tableNearbyCreeps[1] ~= nil
and tableNearbyCreeps[1]:IsMagicImmune() == false
and tableNearbyCreeps[1]:IsAncientCreep() == false
then
bot:Action_UseAbilityOnEntity(hom, tableNearbyCreeps[1]);
return;
end
end
local guardian=IsItemAvailable("item_guardian_greaves");
if guardian~=nil and guardian:IsFullyCastable() then
local Allies=bot:GetNearbyHeroes(1000,false,BOT_MODE_NONE);
for _,Ally in pairs(Allies) do
if Ally:GetHealth()/Ally:GetMaxHealth() < 0.35 and tableNearbyEnemyHeroes~=nil and #tableNearbyEnemyHeroes > 0
then
bot:Action_UseAbility(guardian);
return;
end
end
end
local satanic=IsItemAvailable("item_satanic");
if satanic~=nil and satanic:IsFullyCastable() then
if bot:GetHealth()/bot:GetMaxHealth() < 0.50 and
tableNearbyEnemyHeroes~=nil and #tableNearbyEnemyHeroes > 0 and
bot:GetActiveMode() == BOT_MODE_ATTACK
then
bot:Action_UseAbility(satanic);
return;
end
end
local cyclone=IsItemAvailable("item_cyclone");
if cyclone~=nil and cyclone:IsFullyCastable() then
if npcTarget ~= nil and ( npcTarget:HasModifier('modifier_teleporting') or npcTarget:HasModifier('modifier_abaddon_borrowed_time') )
and CanCastOnTarget(npcTarget) and GetUnitToUnitDistance(bot, npcTarget) < 775
then
bot:Action_UseAbilityOnEntity(cyclone, npcTarget);
return;
end
end
local metham=IsItemAvailable("item_meteor_hammer");
if metham~=nil and metham:IsFullyCastable() then
if mutil.IsPushing(bot) then
local towers = bot:GetNearbyTowers(800, true);
if #towers > 0 and towers[1] ~= nil and towers[1]:IsInvulnerable() == false then
bot:Action_UseAbilityOnLocation(metham, towers[1]:GetLocation());
return;
end
elseif mutil.IsInTeamFight(bot, 1200) then
local locationAoE = bot:FindAoELocation( true, true, bot:GetLocation(), 600, 300, 0, 0 );
if ( locationAoE.count >= 2 )
then
bot:Action_UseAbilityOnLocation(metham, locationAoE.targetloc);
return;
end
elseif mutil.IsGoingOnSomeone(bot) then
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, bot, 800)
and mutil.IsDisabled(true, npcTarget) == true
then
bot:Action_UseAbilityOnLocation(metham, npcTarget:GetLocation());
return;
end
end
end
local sv=IsItemAvailable("item_spirit_vessel");
if sv~=nil and sv:IsFullyCastable() and sv:GetCurrentCharges() > 0
then
if mutil.IsGoingOnSomeone(bot)
then
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, bot, 900)
and npcTarget:HasModifier("modifier_item_spirit_vessel_damage") == false and npcTarget:GetHealth()/npcTarget:GetMaxHealth() < 0.65
then
bot:Action_UseAbilityOnEntity(sv, npcTarget);
return;
end
else
local Allies=bot:GetNearbyHeroes(1150,false,BOT_MODE_NONE);
for _,Ally in pairs(Allies) do
if Ally:HasModifier('modifier_item_spirit_vessel_heal') == false and mutil.CanCastOnNonMagicImmune(Ally) and
Ally:GetHealth()/Ally:GetMaxHealth() < 0.35 and #tableNearbyEnemyHeroes == 0 and Ally:WasRecentlyDamagedByAnyHero(2.5) == false
then
bot:Action_UseAbilityOnEntity(sv,Ally);
return;
end
end
end
end
local hod=IsItemAvailable("item_helm_of_the_dominator");
if hod and hod:IsFullyCastable() and ThinkAboutMindControl(hod, "none") then
return
end
local armlet = IsItemAvailable("item_armlet");
if armlet then
local shouldArmlet = npcTarget and npcTarget:IsAlive() and mutil.IsInRange(npcTarget, bot, bot:GetAttackRange() + 200)
shouldArmlet = not (not shouldArmlet)
local isArmlet = bot:HasModifier('modifier_item_armlet_unholy_strength')
-- print('armlet? ' .. tostring(shouldArmlet) .. ', ' .. tostring(isArmlet))
if isArmlet ~= shouldArmlet then
if armlet:IsFullyCastable() then
CastAbility(armlet, nil)
print('Toggled armlet')
return
end
end
end
local bkb = IsItemAvailable("item_black_king_bar");
if bkb then
if bot:IsSilenced()
or (npcTarget and npcTarget:IsAlive() and mutil.IsInRange(npcTarget, bot, bot:GetAttackRange() + 200))
then
if not bot:IsMagicImmune() and bkb:IsFullyCastable() then
CastAbility(bkb, nil)
end
end
end
local itemTable = {
item_heavens_halberd = "modifier_heavens_halberd_debuff",
item_nullifier = "modifier_item_nullifier_mute",
item_sheepstick = "modifier_sheepstick_debuff",
item_bloodthorn = "modifier_bloodthorn_debuff",
item_medallion_of_courage = "modifier_item_medallion_of_courage_armor_reduction",
item_solar_crest = "modifier_item_solar_crest_armor_reduction",
item_rod_of_atos = "modifier_rod_of_atos_debuff",
}
local didAct = false
local couldAct = false
if npcTarget then
for itemName, modifier in pairs(itemTable) do
local tempCouldAct
didAct, tempCouldAct = CheckAndUseItem(itemName, modifier, npcTarget, false)
if didAct then
return
end
if tempCouldAct then
couldAct = true
end
end
end
if couldAct then
-- last, change targets
local targets = bot:GetNearbyHeroes(1200, true, BOT_MODE_NONE)
local newTarget = targets[RandomInt(1, #targets)]
bot:SetTarget(newTarget)
end
end
function HasLotusableProjectile (bot)
local incProj = bot:GetIncomingTrackingProjectiles()
for _,proj in ipairs(incProj) do
if not proj.is_attack then
if GetUnitToLocationDistance(bot, proj.location) < 200 then
return true
end
end
end
return false
end
function CastAbility (ability, npcTarget)
local behave = ability:GetBehavior()
if bit.band(behave, 8) == 8 and npcTarget ~= nil then
print('Casting ' .. ability:GetName() .. ' directly')
bot:Action_UseAbilityOnEntity(ability, npcTarget);
return
end
if bit.band(behave, 16) == 16 and npcTarget ~= nil then
print('Casting ' .. ability:GetName() .. ' by location ' .. tostring(npcTarget:GetLocation()))
bot:Action_UseAbilityOnLocation(ability, npcTarget:GetLocation());
return
end
print('Casting ' .. ability:GetName())
bot:Action_UseAbility(ability);
end
function CheckAndUseSpell (spellName, modifier, npcTarget, castThroughStuns)
local ability = bot:GetAbilityByName(spellName)
return CheckAndUseAbility(ability, modifier, npcTarget, castThroughStuns)
end
function CheckAndUseAbility (ability, modifier, npcTarget, castThroughStuns)
if ability~=nil and ability:IsFullyCastable()
then
if mutil.IsGoingOnSomeone(bot)
then
if npcTarget == nil then
CastAbility(ability, nil)
return true, false;
end
local castRange = ability:GetCastRange()
local abilityName = ability:GetName()
if castRange < 1 then
local shortName = abilityName:sub(abilityName:find('_') + 1, -1)
castRange = ability:GetSpecialValueInt( shortName .. "_range" )
end
if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, bot, castRange)
and not npcTarget:HasModifier(modifier)
then
if not castThroughStuns and IsDisabled(npcTarget) then
return false, true
end
print('Casting stuff on this badguy! ' .. ability:GetName())
CastAbility(ability, npcTarget)
return true, false;
end
end
return false, true
end
return false, false
end
function CheckAndUseItem (itemName, modifier, npcTarget, castThroughStuns)
local item = IsItemAvailable(itemName);
return CheckAndUseAbility(item, modifier, npcTarget, castThroughStuns)
end
function IsItemAvailable(item_name)
--[[for i = 0, 5 do
local item = bot:GetItemInSlot(i);
if item~=nil and item:GetName() == item_name then
return item;
end
end]]--
local slot = bot:FindItemSlot(item_name);
if bot:GetItemSlotType(slot) == ITEM_SLOT_TYPE_MAIN then
return bot:GetItemInSlot(slot);
end
return nil;
end
function ThinkAboutMindControl (ability, modifier)
if ability == nil or not ability:IsFullyCastable() then
return false
end
local maxHP = 0;
local NCreep = nil;
local canTargetAncients = bit.band(ability:GetTargetFlags(), 512) == 0
local tableNearbyNeutrals = bot:GetNearbyNeutralCreeps( 1600 );
if tableNearbyNeutrals ~= nil and #tableNearbyNeutrals >= 1 then
for _,neutral in pairs(tableNearbyNeutrals)
do
local NeutralHP = neutral:GetHealth();
if NeutralHP > maxHP and neutral:GetTeam() ~= bot:GetTeam() and (canTargetAncients or not neutral:IsAncientCreep())
then
NCreep = neutral;
maxHP = NeutralHP;
end
end
end
tableNearbyNeutrals = bot:GetNearbyCreeps( 1600, true );
if tableNearbyNeutrals ~= nil and #tableNearbyNeutrals >= 1 then
for _,neutral in pairs(tableNearbyNeutrals)
do
local NeutralHP = neutral:GetHealth();
if NeutralHP > maxHP and neutral:GetTeam() ~= bot:GetTeam() and (canTargetAncients or not neutral:IsAncientCreep())
then
NCreep = neutral;
maxHP = NeutralHP;
end
end
end
local tableNearbyAllies = nil
local distances = {}
local myDistance = 0
local alliedNeutralCount = 0
if NCreep then
myDistance = GetUnitToUnitDistance(bot, NCreep)
tableNearbyAllies = bot:GetNearbyHeroes(1600, false, BOT_MODE_NONE)
alliedNeutralCount = #(bot:GetNearbyCreeps( 1600, false ));
end
if NCreep and tableNearbyAllies ~= nil and #tableNearbyAllies >= 1 then
for _,hero in pairs(tableNearbyAllies) do
if NCreep and GetUnitToUnitDistance(hero, NCreep) < myDistance then
if alliedNeutralCount > 0 then
alliedNeutralCount = alliedNeutralCount - 1
else
NCreep = nil
end
end
end
end
if NCreep == nil then
return false
end
bot:Action_UseAbilityOnEntity(ability, NCreep);
return true
end
function ConsiderAOERadiusAbility(unit, ability, nRadius)
local isToggle = bit.band(ability:GetBehavior(), 512) == 512
local desireNone = BOT_ACTION_DESIRE_NONE
local desireHigh = BOT_ACTION_DESIRE_HIGH
local abilityName = ability:GetName()
-- print(ability:GetName() .. ' . ' .. tostring(isToggle) .. ' / ' .. tostring(ability:GetToggleState()))
if not nRadius then
nRadius = math.max(ability:GetCastRange(), ability:GetSpecialValueInt( "radius" ))
end
if unit:HasScepter() then
local scepterRadius = ability:GetSpecialValueInt( "radius_scepter" )
nRadius = math.max(scepterRadius, nRadius)
end
if nRadius < 1 then
local shortName = abilityName:sub(abilityName:find('_') + 1, -1)
nRadius = ability:GetSpecialValueInt( shortName .. "_radius" )
end
local isAOE = nRadius > 0
if isToggle and ability:GetToggleState() then
nRadius = nRadius + 100
desireHigh = BOT_ACTION_DESIRE_NONE
desireNone = BOT_ACTION_DESIRE_HIGH
end
-- Make sure it's castable
if (not ability or not ability:IsFullyCastable() or ability:IsHidden()) then
return BOT_ACTION_DESIRE_NONE, isAOE;
end
local tableAllNearbyEnemyHeroes = unit:GetNearbyHeroes( nRadius, true, BOT_MODE_NONE );
local tableNearbyEnemyHeroes = {}
if Data[ability:GetName()] then
local modifier = Data[ability:GetName()]
for _,unit in ipairs(tableAllNearbyEnemyHeroes) do
if not unit:HasModifier(modifier) then
table.insert(tableNearbyEnemyHeroes, unit)
end
end
else
tableNearbyEnemyHeroes = tableAllNearbyEnemyHeroes
end
if ( tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes >= 1 ) then
return desireHigh, isAOE;
end
return desireNone, isAOE;
end
return MyModule;
|
AddCSLuaFile()
ENT.RenderGroup = RENDERGROUP_OPAQUE
ENT.Base = "base_anim"
ENT.Type = "anim"
ENT.Author = "TankNut"
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.SuitData = {}
function ENT:SpawnFunction(ply, tr, class)
local ang = Angle(0, ply:EyeAngles().y + 90, 0)
local ent = ents.Create(class)
ent:SetCreator(ply)
ent:SetPos(tr.HitPos)
ent:SetAngles(ang)
ent:Spawn()
ent:Activate()
-- Duplicate of the prop alignment code from the spawnmenu
local pos = tr.HitPos - (tr.HitNormal * 512)
pos = ent:NearestPoint(pos)
pos = ent:GetPos() - pos
pos = tr.HitPos + pos
ent:SetPos(pos + Vector(0, 0, 1))
ent:GetPhysicsObject():Wake()
undo.Create(class)
undo.AddEntity(ent)
undo.SetPlayer(ply)
undo.SetCustomUndoText("Undone " .. ent.PrintName)
undo.Finish()
return ent
end
function ENT:Initialize()
self:SetModel("models/props_c17/SuitCase001a.mdl")
if SERVER then
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WEAPON)
self:SetUseType(SIMPLE_USE)
end
end
function ENT:Footstep(ply, foot, volume)
local data = self.SuitData
if isbool(data.Footsteps) then
return true
end
local snd = data.Footsteps[foot + 1] -- 1 for left, 2 for right
if istable(snd) then
snd = table.Random(snd)
end
if snd then
local pitch = istable(data.FootstepPitch) and math.Rand(unpack(data.FootstepPitch)) or 100
local vol = data.FootstepVolume * volume
ply:EmitSound(snd, 75, pitch, vol, CHAN_BODY)
return true
end
end
function ENT:ScaleDamage(ply, dmg)
end
if CLIENT then
function ENT:RenderScreenspaceEffects()
end
end
if SERVER then
function ENT:Use(ply)
if not IsValid(ply) or not ply:IsPlayer() then
return
end
if not self:CanWear(ply) then
return
end
local worn = suit.GetWorn(ply)
if IsValid(worn) then
if worn:GetClass() == self:GetClass() then
return
end
if not worn:CanUnwear(ply) then
return
end
suit.Unwear(worn)
worn:SetPos(self:GetPos() + Vector(0, 0, 1))
worn:SetAngles(self:GetAngles())
worn:GetPhysicsObject():Wake()
end
suit.Wear(ply, self)
ply:EmitSound("items/ammopickup.wav")
end
function ENT:CanWear(ply)
local res = hook.Run("CanWearSuit", ply)
if res then
return res
end
return true
end
function ENT:CanUnwear(ply)
local res = hook.Run("CanUnwearSuit", ply)
if res then
return res
end
return true
end
function ENT:OnRemove()
suit.Unwear(self)
end
function ENT:GetSpeedMod(ply)
return 1
end
function ENT:SetupNPCRelationship(ply, npc)
if not IsValid(npc) or not npc:IsNPC() then
return
end
local classify = npc:Classify()
local relationship = self.SuitData.NPCRelationships[classify]
if relationship then
self.StoreData.NPCRelationships[npc] = npc:Disposition(ply)
npc:AddEntityRelationship(ply, relationship, 99)
end
end
function ENT:SetupNPCRelationships(ply)
self.StoreData.NPCRelationships = {}
for _, v in pairs(ents.GetAll()) do
self:SetupNPCRelationship(ply, v)
end
end
function ENT:RestoreNPCRelationships(ply)
if not self.StoreData.NPCRelationships then
return
end
for npc, relationship in pairs(self.StoreData.NPCRelationships) do
if not IsValid(npc) then
continue
end
npc:AddEntityRelationship(ply, relationship, 99)
end
end
function ENT:SetupModel(ply)
local data = self.SuitData
if data.Model then
ply:SetModel(data.Model)
ply:SetSubMaterial()
ply:SetMaterial("")
end
if data.Material then
ply:SetMaterial(data.Material)
end
end
function ENT:OnWear(ply)
self.StoreData = {}
self:SetupModel(ply)
ply:SetupHands()
local speed = self:GetSpeedMod(ply)
if speed != 1 then
self.StoreData.WalkSpeed = ply:GetWalkSpeed()
self.StoreData.RunSpeed = ply:GetRunSpeed()
ply:SetWalkSpeed(self.StoreData.WalkSpeed * speed)
ply:SetRunSpeed(self.StoreData.RunSpeed * speed)
end
if self.SuitData.Weapons then
self.StoreData.Weapons = {}
for _, v in pairs(self.SuitData.Weapons) do
table.insert(self.StoreData.Weapons, ply:Give(v))
end
end
if self.SuitData.NPCRelationships then
self:SetupNPCRelationships(ply)
end
end
function ENT:OnUnwear(ply)
local data = self.StoreData
ply:SetMaterial("")
hook.Run("PlayerSetModel", ply)
ply:SetupHands()
if data.WalkSpeed then
ply:SetWalkSpeed(data.WalkSpeed)
ply:SetRunSpeed(data.RunSpeed)
end
if data.Weapons then
for _, v in pairs(data.Weapons) do
if IsValid(v) then
ply:StripWeapon(v:GetClass())
end
end
end
if data.NPCRelationships then
self:RestoreNPCRelationships(ply)
end
end
end
|
--[[
ReturnTable.lua
Copyright (c) 2019 Toshiba Memory Corporation.
All sample code on this page is licensed under BSD 2-Clause License
https://github.com/FlashAirDevelopers/LuaTutorial/blob/master/LICENSE
]]
local function _foo()
print("Hello World!")
end
return {
foo=_foo
}
|
local PROGRESS_BAR = script:GetCustomProperty("ProgressBar"):WaitForObject()
local TEXT_BOX = script:GetCustomProperty("TextBox"):WaitForObject()
local LOCAL_PLAYER = Game.GetLocalPlayer()
function OnResourceChanged(player, resource, value)
if resource =="actionMax" then
PROGRESS_BAR.progress= (value-LOCAL_PLAYER.clientUserData.turnNumberAction)/LOCAL_PLAYER:GetResource("actionMax")
TEXT_BOX.text = (value-LOCAL_PLAYER.clientUserData.turnNumberAction).."/"..value.." action(s) per turn"
end
end
function Tick()
value=LOCAL_PLAYER:GetResource("actionMax")
if LOCAL_PLAYER.clientUserData.turnNumberAction==nil then LOCAL_PLAYER.clientUserData.turnNumberAction=0 end
PROGRESS_BAR.progress= (value-LOCAL_PLAYER.clientUserData.turnNumberAction)/value
TEXT_BOX.text = (value-LOCAL_PLAYER.clientUserData.turnNumberAction).."/"..value.." action(s) per turn"
Task.Wait(1)
end
LOCAL_PLAYER.resourceChangedEvent:Connect(OnResourceChanged)
|
--[[
******************************************************************
* _____ ___ _ *
* ( _ ) ( _`\ _ ( )_ *
* | (_) | _ __ ___ | (_(_) ___ _ __ (_) _ _ | ,_) *
* | _ |( '__)/'___)`\__ \ /'___)( '__)| |( '_`\ | | *
* | | | || | ( (___ ( )_) |( (___ | | | || (_) )| |_ *
* (_) (_)(_) `\____)`\____)`\____)(_) (_)| ,__/'`\__) *
* | | *
* (_) *
* *
* OpenSource Scripting Team *
* <http://www.arcemu.org> *
* *
******************************************************************
This software is provided as free and open source by the
staff of The ArcScript Project, in accordance with
the GPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
Staff of ArcScript Project, Feb 2008
~~End of License Agreement
#############################################################
-- ]]
--HORDE
--Undercity
function TaxiUC_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 68, 60000)
end
function TaxiUC_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiUC_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(4551, 1, "TaxiUC_Combat")
RegisterUnitEvent(4551, 2, "TaxiUC_LeaveCombat")
RegisterUnitEvent(4551, 4, "TaxiUC_Died")
--Thunderbluff
function TaxiTB_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
end
function TaxiTB_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiTB_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2995, 1, "TaxiTB_Combat")
RegisterUnitEvent(2995, 2, "TaxiTB_LeaveCombat")
RegisterUnitEvent(2995, 4, "TaxiTB_Died")
--Silvermoon
function TaxiSM_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
Unit:SpawnCreature(9521, x, y, z, o, 1602, 60000)
end
function TaxiSM_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiSM_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(16192, 1, "TaxiSM_Combat")
RegisterUnitEvent(16192, 2, "TaxiSM_LeaveCombat")
RegisterUnitEvent(16192, 4, "TaxiSM_Died")
--Orgimmar
function TaxiOG_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
Unit:SpawnCreature(9297, x, y, z, o, 83, 60000)
end
function TaxiOG_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiOG_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(3310, 1, "TaxiOG_Combat")
RegisterUnitEvent(3310, 2, "TaxiOG_LeaveCombat")
RegisterUnitEvent(3310, 4, "TaxiOG_Died")
--Alliance
--Stormwind
function TaxiSW_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 12, 60000)
end
function TaxiSW_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiSW_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(352, 1, "TaxiSW_Combat")
RegisterUnitEvent(352, 2, "TaxiSW_LeaveCombat")
RegisterUnitEvent(352, 4, "TaxiSW_Died")
--Darnassus
function TaxiRT_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 80, 60000)
end
function TaxiRT_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiRT_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(3838, 1, "TaxiRT_Combat")
RegisterUnitEvent(3838, 2, "TaxiRT_LeaveCombat")
RegisterUnitEvent(3838, 4, "TaxiRT_Died")
--Ironforge
function TaxiIF_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
Unit:SpawnCreature(9526, x, y, z, o, 55, 60000)
end
function TaxiIF_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiIF_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(1573, 1, "TaxiIF_Combat")
RegisterUnitEvent(1573, 2, "TaxiIF_LeaveCombat")
RegisterUnitEvent(1573, 4, "TaxiIF_Died")
--Exodar
function TaxiEX_Combat(Unit, Event)
local x = Unit:GetX()
local y = Unit:GetY()
local z = Unit:GetZ()
local o = Unit:GetO()
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
Unit:SpawnCreature(9527, x, y, z, o, 1638, 60000)
end
function TaxiEX_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
function TaxiEX_Died(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(17555, 1, "TaxiEX_Combat")
RegisterUnitEvent(17555, 2, "TaxiEX_LeaveCombat")
RegisterUnitEvent(17555, 4, "TaxiEX_Died")
|
local function search(k, plist)
for i = 1, #plist do
local v = plist[i][k]
if v then
return v
end
end
end
function createClass(...)
local c = {}
local parents = {...}
setmetatable(c, {__index = function(t, k)
return search(k, parents)
end})
c.__index = c
function c:new(o)
o = o or {}
setmetatable(o, c)
return o
end
return c
end
|
SKILL.name = "Mortal Strike"
SKILL.LevelReq = 5
SKILL.SkillPointCost = 1
SKILL.Incompatible = {
}
SKILL.RequiredSkills = {
}
SKILL.icon = "vgui/skills/Ability_warrior_savageblow.png"
SKILL.category = "Warriors Path"
SKILL.slot = "MELEE" -- ULT, RANGED, MELEE, AOE, PASSIVE
SKILL.class = {
"statestroop",
"reaver"
}
SKILL.desc = [[
Empowers your next attack dealing high damage.
If used on a player it removes their natural health regen
for 10 seconds.
Level Requirement: ]] .. SKILL.LevelReq .. [[
Skill Point Cost:]] .. SKILL.SkillPointCost .. [[
Class Restriction: Statestroop, Reaver
]]
SKILL.coolDown = 20
local function ability( SKILL, ply )
local nospam = ply:GetNWBool( "nospamMelee" ) // nospamRanged, nospamUlt, nospamAOE, nospamMelee
if (nospam) then
if timer.Exists(ply:SteamID().."nospamMelee") then return end
timer.Create(ply:SteamID().."nospamMelee", SKILL.coolDown, 1, function()
ply:SetNWBool( "nospamMelee", false )
end)
return
end
local mana = ply:getLocalVar("mana", 0)
if mana < 20 then
return
end
ply:setLocalVar("mana", mana - 20)
if !(ply:GetNWBool("MortalStrike" )) then
local char = ply:getChar()
local naturalDamage = char:getData("naturalDamage",0)
local str = char:getAttrib("str")
local damage = naturalDamage + (str * 5) + 100 + ((25 * (char:getLevel()*char:getLevel()) / (char:getLevel()+char:getLevel())))
char:setData("tempDamage", damage)
timer.Simple(0, function()
ParticleEffectAttach("fantasy_warrior_mortal_strike", PATTACH_POINT_FOLLOW, ply, 5)
end)
timer.Simple(10, function()
if ( ply:GetNWBool("MortalStrike") ) then
if SERVER then
char:setData("tempDamage", math.max(0,naturalDamage))
ply:SetNWBool("MortalStrike", false)
end
end
end)
end
ply:SetNWBool("MortalStrike", true )
if (SERVER) then
ply:SetNWBool( "nospamMelee", true )
net.Start( "MeleeActivated" ) // RangedActivated, UltActivated, AOEActivated, MeleeActivated
net.Send( ply )
if timer.Exists(ply:SteamID().."nospamMelee") then return end
timer.Create(ply:SteamID().."nospamMelee", SKILL.coolDown, 1, function()
ply:SetNWBool( "nospamMelee", false )
end)
end
end
SKILL.ability = ability
|
local class = require "class"
local queue = class:create("queue")
function queue:new(...)
self.s = select("#", ...)
for _, v in pairs{...} do
self:push(v)
end
return self
end
function queue:front()
if self.s > 0 then
return self[1]
end
return -1
end
function queue:back()
if self.s > 0 then
return self[#self]
end
return -1
end
function queue:empty()
return (self.s <= 0)
end
function queue:size()
return self.s
end
function queue:push(val)
if val and (self.s >= 0) then
self.s = self.s + 1
self[self.s] = val
end
end
function queue:pop()
if self.s > 0 then
table.remove(self, 1)
self.s = self.s - 1
end
end
-- used in dequeue
-- function queue:erase(val)
-- if self.s > 0 then
-- for k, _ in pairs(self) do
-- if self[k] == val then
-- self[k] = nil
-- end
-- end
-- end
-- end
-- used in dequeue
-- function queue:clear()
-- if self.s > 0 then
-- for _, v in pairs(self) do
-- self:erase(v)
-- end
-- end
-- end
-- used in dequeue
-- function queue:at(idx)
-- if self.s > 0 and idx > 0 then
-- return self[idx]
-- end
-- return -1
-- end
return queue
|
local skynet = require "skynet";
skynet.start(function()
print("==========Service1 Start=========")
end)
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local tables = require "moonpie.tables"
local EquipSlots = require "game.rules.inventory.equip_slots"
local selectors = {}
function selectors.getEquippedItem(state, entity, slot)
local inventory = selectors.getInventory(state, entity)
if inventory then
return inventory.equipped[slot]
end
end
function selectors.getInventory(state, entity)
return state.inventory[entity]
end
function selectors.getRangedWeapon(state, entity)
return selectors.getEquippedItem(state, entity, EquipSlots.ranged)
end
function selectors.isCarryingItem(state, entity, item)
local inv = selectors.getInventory(state, entity)
return tables.findFirst(inv.carried, function(slot) return slot.item == item end) ~= nil
end
return selectors
|
--[[
イベントの登録
]]
|
--
-- c_water.lua
--
myWaterShader = nil
local isSunEnabled = true
function startWaterShine()
if wsEffectEnabled then return end
-- Create shader
myWaterShader, tec = dxCreateShader ( "fx/water.fx",0,0,false )
if not myWaterShader then
outputChatBox( "Could not create shader. Please use debugscript 3" )
else
outputConsole( "Shader Water2: using technique " .. tec )
if isSunEnabled then enableSunLight() end
-- Set textures
textureVol = dxCreateTexture ( "images/wavemap.png" );
textureCube = dxCreateTexture ( "images/cube_env256.dds" );
dxSetShaderValue ( myWaterShader, "sRandomTexture", textureVol );
dxSetShaderValue ( myWaterShader, "sReflectionTexture", textureCube );
-- Apply to global txd 13
engineApplyShaderToWorldTexture ( myWaterShader, "waterclear256" )
-- Update water color incase it gets changed by persons unknown
watTimer = setTimer( function()
if myWaterShader then
local r,g,b,a = getWaterColor()
dxSetShaderValue ( myWaterShader, "sWaterColor", r/255, g/255, b/255, a/255 );
local rSkyTop,gSkyTop,bSkyTop,rSkyBott,gSkyBott,bSkyBott = getSkyGradient ()
dxSetShaderValue ( myWaterShader, "sSkyColorTop", rSkyTop/255, gSkyTop/255, bSkyTop/255)
dxSetShaderValue ( myWaterShader, "sSkyColorBott", rSkyBott/255, gSkyBott/255, bSkyBott/255)
end
end
,100,0 )
end
wsEffectEnabled = true
end
function stopWaterShine()
if not wsEffectEnabled then return end
if myWaterShader then
killTimer(watTimer)
engineRemoveShaderFromWorldTexture ( myWaterShader, "waterclear256" )
destroyElement(myWaterShader)
myWaterShader = nil
destroyElement(textureVol)
textureVol = nil
destroyElement(textureCube)
textureCube = nil
wsEffectEnabled = false
end
end
|
version = '0.6.0.4'
versionString = [[Changelog:
Removed royal jelly from neutral list.
]]
|
return require'packer'.startup(function()
use 'wbthomason/packer.nvim'
use 'akinsho/nvim-toggleterm.lua'
use 'bfredl/nvim-miniyank'
use 'editorconfig/editorconfig-vim'
use {
'folke/zen-mode.nvim',
config = function()
require('zen-mode').setup {
window = {
backdrop = 1,
width = 100,
options = {
signcolumn = 'no',
number = false,
relativenumber = false,
list = false,
},
},
}
end
}
use 'glepnir/dashboard-nvim'
use {'glepnir/galaxyline.nvim', branch = 'main', requires = {'kyazdani42/nvim-web-devicons', opt = true}}
use 'glepnir/lspsaga.nvim'
use 'hrsh7th/nvim-compe'
use {'junegunn/fzf', dir = '~/.fzf', run = './install --all'}
use 'junegunn/fzf.vim'
use 'kyazdani42/nvim-tree.lua'
use 'kyazdani42/nvim-web-devicons'
use 'lbrayner/vim-rzip'
use 'leafOfTree/vim-vue-plugin'
use 'lewis6991/gitsigns.nvim'
-- use 'ludovicchabant/vim-gutentags'
use 'mattn/emmet-vim'
use 'mfussenegger/nvim-dap'
use 'neovim/nvim-lspconfig'
use 'neovimhaskell/haskell-vim'
use 'norcalli/nvim-colorizer.lua'
use 'nvim-lua/popup.nvim'
use 'nvim-lua/plenary.nvim'
use {'nvim-telescope/telescope.nvim', requires = {'nvim-lua/popup.nvim', 'nvim-lua/plenary.nvim'}}
use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make'}
use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'}
use {'nvim-treesitter/playground', requires = 'nvim-treesitter/nvim-treesitter'}
use 'pacokwon/plink.nvim'
use 'peitalin/vim-jsx-typescript'
use 'ray-x/lsp_signature.nvim'
use 'rust-lang/rust.vim'
use 'scalameta/nvim-metals'
use 'steelsojka/pears.nvim'
use {'styled-components/vim-styled-components', branch = 'develop'}
use 'tommcdo/vim-exchange'
use 'tpope/vim-commentary'
use {'tpope/vim-dispatch', opt = true, cmd = {'Dispatch', 'Make', 'Focus', 'Start'}}
use 'tpope/vim-fugitive'
use 'tpope/vim-repeat'
use 'tpope/vim-surround'
use 'vifm/vifm.vim'
use 'vimwiki/vimwiki'
-- colors
use 'Shatur95/neovim-ayu'
use 'arzg/vim-colors-xcode'
use 'folke/tokyonight.nvim'
use 'haishanh/night-owl.vim'
use 'ishan9299/modus-theme-vim'
use 'mhartington/oceanic-next'
use 'morhetz/gruvbox'
use 'navarasu/onedark.nvim'
use 'pacokwon/onedarkhc.vim'
use 'pacokwon/panic.vim'
use 'projekt0n/github-nvim-theme'
use 'savq/melange'
use 'srcery-colors/srcery-vim'
end)
|
local platform = require 'bee.platform'
local files = require 'files'
local furi = require 'file-uri'
local workspace = require "workspace"
local config = require 'config'
local m = {}
m.cache = {}
--- `aaa/bbb/ccc.lua` 与 `?.lua` 将返回 `aaa.bbb.cccc`
local function getOnePath(uri, path, searcher)
local separator = config.get(uri, 'Lua.completion.requireSeparator')
local stemPath = path
: gsub('%.[^%.]+$', '')
: gsub('[/\\%.]+', separator)
local stemSearcher = searcher
: gsub('%.[^%.]+$', '')
: gsub('[/\\%.]+', separator)
local start = stemSearcher:match '()%?' or 1
for pos = start, #stemPath do
local word = stemPath:sub(start, pos)
local newSearcher = stemSearcher:gsub('%?', (word:gsub('%%', '%%%%')))
if newSearcher == stemPath then
return word
end
end
return nil
end
function m.getVisiblePath(suri, path)
local searchers = config.get(suri, 'Lua.runtime.path')
local strict = config.get(suri, 'Lua.runtime.pathStrict')
path = workspace.normalize(path)
local uri = furi.encode(path)
local libraryPath = files.getLibraryPath(uri)
if not m.cache[path] then
local result = {}
m.cache[path] = result
if libraryPath then
libraryPath = libraryPath:gsub('^[/\\]+', '')
end
for _, searcher in ipairs(searchers) do
local isAbsolute = searcher:match '^[/\\]'
or searcher:match '^%a+%:'
searcher = workspace.normalize(searcher)
local cutedPath = path
local currentPath = path
local head
local pos = 1
if not isAbsolute then
if libraryPath then
pos = #libraryPath + 2
else
currentPath = workspace.getRelativePath(uri)
end
end
repeat
cutedPath = currentPath:sub(pos)
head = currentPath:sub(1, pos - 1)
pos = currentPath:match('[/\\]+()', pos)
if platform.OS == 'Windows' then
searcher = searcher :gsub('[/\\]+', '\\')
else
searcher = searcher :gsub('[/\\]+', '/')
end
local expect = getOnePath(suri, cutedPath, searcher)
if expect then
local mySearcher = searcher
if head then
mySearcher = head .. searcher
end
result[#result+1] = {
searcher = mySearcher,
expect = expect,
}
end
until not pos or strict
end
end
return m.cache[path]
end
--- 查找符合指定require path的所有uri
---@param path string
function m.findUrisByRequirePath(suri, path)
if type(path) ~= 'string' then
return {}
end
local separator = config.get(suri, 'Lua.completion.requireSeparator')
local fspath = path:gsub('%' .. separator, '/')
local vm = require 'vm'
local cache = vm.getCache 'findUrisByRequirePath'
if cache[path] then
return cache[path].results, cache[path].searchers
end
tracy.ZoneBeginN('findUrisByRequirePath')
local results = {}
local searchers = {}
for uri in files.eachDll() do
local opens = files.getDllOpens(uri) or {}
for _, open in ipairs(opens) do
if open == fspath then
results[#results+1] = uri
end
end
end
for uri in files.eachFile() do
local infos = m.getVisiblePath(suri, furi.decode(uri))
for _, info in ipairs(infos) do
local fsexpect = info.expect:gsub('%' .. separator, '/')
if fsexpect == fspath then
results[#results+1] = uri
searchers[uri] = info.searcher
end
end
end
tracy.ZoneEnd()
cache[path] = {
results = results,
searchers = searchers,
}
return results, searchers
end
function m.flush()
m.cache = {}
end
files.watch(function (ev)
if ev == 'create'
or ev == 'remove' then
m.flush()
end
end)
config.watch(function (uri, key, value, oldValue)
if key == 'Lua.completion.requireSeparator'
or key == 'Lua.runtime.path'
or key == 'Lua.runtime.pathStrict' then
m.flush()
end
end)
return m
|
#!/usr/local/bin/luvit
--- Terraria chat bridge to/from discord by Rami Sabbagh (RamiLego4Game)
-- A discord bot written in Lua to bridge chat between a Terraria server and a discord channel.
print("--------------------------------------------------------")
print("Terraria-Discord-Bridge by Rami Sabbagh (@ramilego4game)")
print("Version - 1.3.1")
print("--------------------------------------------------------")
print("")
local json = require("json")
--Load the configuration
local config
do
local file = assert(io.open("configuration.json"))
local data = assert(file:read("*a"))
file:close()
config = json.decode(data)
end
--Clear the output file
do
local file = assert(io.open(config.serverOutput, "w"))
file:close()
end
--Prepare the server startup command
local serverCommand = string.format("%s -config %s > %s",
config.serverExecutable, config.serverConfig, config.serverOutput
)
local input = assert(io.popen(serverCommand, "w")) --Writing to this file is like sending input to the server.
local output = assert(io.open(config.serverOutput, "r")) --Reading from this file is reading the output of the server.
local timer = require("timer")
local http = require("coro-http")
local discordia = require('discordia')
local client = discordia.Client()
local serverReady = false
local playersCount = 0
--Update the bot's status with the players count
local function updateStatus()
client:setGame({
name = string.format("%d players online", playersCount),
type = 3,
})
end
--Send a message using the configured webhook
local function sendMessage(content, name)
local avatarURL = nil
if config.players[name] then --The players snowflakes are converted to user objects in the ready event
avatarURL = config.players[name]:getAvatarURL()
name = config.players[name].name
end
local payload = {
content = content,
username = name,
avatar_url = avatarURL
}
payload = json.encode(payload)
http.request("POST", config.bridgeWebhook, {
{"content-type", "application/json"},
{"content-length", #payload}
}, payload)
end
--Check the server log for any new players messages (including join and leave messages).
local function checkServerLog()
if serverReady then
for line in output:lines() do
line = line:gsub("[\r\n]",""):gsub("^ :", "")
if line:match("^<.->") then
local sender = line:match("^<.->"):sub(2,-2)
local content = line:gsub("^<.->%s+", "")
if #sender > 0 and #content > 0 and sender ~= "Server" then
print("Terraria -> Discord", sender, ":", content)
sendMessage(content, sender)
end
elseif line:match("has joined.$") then
playersCount = playersCount + 1
updateStatus()
pcall(sendMessage, "_joined the game._", line:sub(1,-13))
elseif line:match("has left.$") then
playersCount = playersCount - 1
updateStatus()
pcall(sendMessage, "_left the game._", line:sub(1,-11))
end
end
end
end
--Set the server log monitor every 1 second
timer.setInterval(1, function() coroutine.wrap(checkServerLog)() end)
client:on('ready', function()
for gameName, user in pairs(config.players) do
print("Requesting "..gameName.."'s user...")
config.players[gameName] = client:getUser(user)
end
print("Waiting for the server to be ready...")
client:setGame("loading world...")
while output:read("*l") ~= ": " do end
updateStatus()
print("Terraria's bridge ready!")
serverReady = true
pcall(sendMessage, "_The server is now online._", "Server")
end)
client:on('messageCreate', function(message)
if message.channel.id == config.bridgeChannel then
if serverReady and #message.content > 0 and not message.author.bot then
print("Discord -> Terraria", message.author.name, ":", message.content)
local content = message.content:gsub("\r","").."\n"
for line in content:gmatch(".-\n") do
input:write("say [")
input:write(message.author.name)
input:write("]: ")
input:write(line)
end
input:flush()
end
elseif message.channel.type == 1 then --Direct (private) messages
--Check if the messages are from the a server owner.
local owner = false
for _, id in pairs(config.owners) do
if id == message.author.id then owner = true break end
end
--If not from an owner, ignore them.
if not owner then return end
--If the server is not in a ready state, refuse to execute the commands.
if not serverReady then
message.channel:send("The server is not ready ⚠")
return
end
if message.content == "exit" then --Exit the server properly
serverReady = false
client:setGame("exitting...")
input:write("exit\n")
input:flush()
input:close()
output:close()
message.channel:send("Exited server successfully ✅")
pcall(sendMessage("_The server has shutdown_", "Server"))
client:setGame("goodbye")
client:stop()
os.exit(0)
elseif message.content == "save" then --Save the world
serverReady = false
client:setGame("saving world...")
pcall(sendMessage, "_Saving the world..._", "Server")
input:write("say Saving world...\n")
input:flush()
input:write("save\n")
input:flush()
while output:read("*l") ~= ": " do end
input:write("say Saved successfully.\n")
input:flush()
serverReady = true
updateStatus()
message.channel:send("Saved successfully ✅")
pcall(sendMessage, "_Saved successfully._", "Server")
elseif message.content:sub(1,4) == "kick" then --Kick a player
input:write(message.content)
input:write("\n")
input:flush()
message.channel:send("Kicked successfully ✅")
input:write(message.content:sub(6,-1).." has been kicked.")
input:flush()
pcall(sendMessage, "_"..message.content:sub(6,-1).." has been kicked._", "Server")
elseif message.content:sub(1,3) == "ban" then --Ban a player
input:write(message.content)
input:write("\n")
input:flush()
message.channel:send("Banned successfully ✅")
input:write(message.content:sub(5,-1).." has been banned.")
input:flush()
pcall(sendMessage, "_"..message.content:sub(5,-1).." has been banned._", "Server")
elseif message.content:sub(1,3) == "say" then --Say a message as the server
input:write(message.content)
input:write("\n")
input:flush()
message.channel:send("Sent successfully ✅")
pcall(sendMessage, message.content:sub(5,-1), "Server")
end
end
end)
client:run("Bot "..config.token)
|
--[[ Copyright (C) 2018 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local maze_generation = require 'dmlab.system.maze_generation'
local PositionTrigger = {}
local PositionTriggerMT = {__index = PositionTrigger}
--[[ Create a position trigger class that starts at currentTime, if specified.
You must call `update(currentPosition)` whenever the `currentPosition` changes.
This call will make any callbacks on any triggers that have fired with the new
position.
--]]
function PositionTrigger.new()
return setmetatable({_triggers = {}}, PositionTriggerMT)
end
--[[ Start trigger `kwargs.name` that will fire when currentPosition overlaps
a square in `kwargs.maze` that matches `kwargs.triggerWhenEnter` or
`kwargs.triggerWhenExit`.
Once the trigger fires, `kwargs.callback` will be called and the trigger will be
removed unless `true` is returned.
Keyword arguments:
* `name` (string) The name of the trigger.
* `maze` (string) A text layout of the maze.
* `triggerWhenEnter` (character) The character in `maze` that sets off the
trigger, the first time the position is on that character in `maze`.
* `triggerWhenExit` (character) The character in `maze` that sets off the
trigger, when position stops being that character in `maze`.
* `callback` (function) Callback that's called when the trigger goes off.
If the callback returns `true` then the trigger is re-engaged to go off
under the same enter/exit conditions. By default, however, the trigger is
removed.
Example: Print a happy message in 2 seconds.
```Lua
local PositionTrigger = require 'common.position_trigger'
local HAPPINESS_LAYER = [ [
..LL.LL..
.L..L..L.
..L...L..
...L.L...
....L....
] ]
myTriggers = PositionTrigger.new()
myTriggers:start{
name = 'my happiness trigger',
maze = HAPPINESS_LAYER,
triggerWhenEnter = 'L',
callback = function() print('HAPPINESS!') io.flush() end,
}
function api:myFunctionCalledEveryFrame(currentPosition)
myPositionTrigger:update(currentPosition)
end
```
--]]
function PositionTrigger:start(kwargs)
assert(kwargs.name)
assert(kwargs.maze)
assert(kwargs.triggerWhenExit or kwargs.triggerWhenEnter)
assert(kwargs.callback)
local sizeI, sizeJ = self:mazeSize()
self._triggers[kwargs.name] = {
maze = maze_generation:mazeGeneration{entity = kwargs.maze},
triggerWhenExit = kwargs.triggerWhenExit,
triggerWhenEnter = kwargs.triggerWhenEnter,
callback = kwargs.callback,
}
-- All mazes must have the same size, since `update(currentPosition)` assumes
-- the same maze for all position triggers.
assert(sizeI == nil or
self._triggers[kwargs.name].maze:size() == sizeI, sizeJ)
end
-- Remove `name` from the active triggers.
function PositionTrigger:remove(name)
self._triggers[name] = nil
end
-- Remove all triggers, but maintain the current position.
function PositionTrigger:removeAll()
self._triggers = {}
end
-- Returns true if there exists an active trigger called `name`.
function PositionTrigger:exists(name)
return self._triggers[name] ~= nil
end
-- All mazes must have the same size. Return the size of the first trigger's
-- maze, or nil if no triggers exist.
function PositionTrigger:mazeSize()
for _, v in pairs(self._triggers) do
return v.maze:size()
end
return nil, nil
end
-- Return the size of the first text maze, which has to be consistent for all
-- triggers.
function PositionTrigger:mazeCoordinatesFromWorldPosition(worldPosition)
for _, v in pairs(self._triggers) do
return v.maze:fromWorldPos(worldPosition[1], worldPosition[2])
end
return nil, nil
end
--[[ Provide the new current position in world space.
Check if any triggers have fired.
For triggers that have fired, call their callbacks and remove them unless
the callback returns `true`. Must be called manually by the owner of this class.
--]]
function PositionTrigger:update(currentPosition)
-- If we have no triggers, or if the maze coordinates haven't changed, then
-- there is nothing to do.
local nextI, nextJ = self:mazeCoordinatesFromWorldPosition(currentPosition)
if nextI == nil then return end
if self._currentI == nextI and self._currentJ == nextJ then return end
-- Check if we've transitioned cell types. If so, see if we've triggered
-- the enter or exit criteria. If so, make callback.
local triggersToRemove = {}
for name, v in pairs(self._triggers) do
local currentCell = self._currentI and
v.maze:getEntityCell(self._currentI, self._currentJ)
local nextCell = v.maze:getEntityCell(nextI, nextJ)
if currentCell ~= nextCell then
if (v.triggerWhenExit and v.triggerWhenExit == currentCell) or
(v.triggerWhenEnter and v.triggerWhenEnter == nextCell) then
local persist = v.callback()
if not persist then
triggersToRemove[#triggersToRemove + 1] = name
end
end
end
end
-- Remove any triggers that have fired.
for _, name in pairs(triggersToRemove) do
self:remove(name)
end
-- Update our current maze coordinates.
self._currentI = nextI
self._currentJ = nextJ
end
return PositionTrigger
|
-- exploring interaction with editor functionality
editor=import.EditorLogic.fetch
pl=import.PartLoader.Instance
sc=import.ShipConstruction
ship=editor.ship
parts=ship.parts
part=parts[0]
apart=pl.getPartInfoByName(part.name)
newpart=apart.partPrefab
function each(lst,action)
for i=0,lst.count-1 do
action(lst[i])
end
end
for part in parts do
each(part.Modules,function(m)
print(m)
end)
end
|
-- the draw handler contains all camera handling
-- and draw related code
local scale = 1.0 -- the current scaling
local tileWidth = 32 -- default texture width
local tileHeight = 32 -- default texture height
local xtrans = 0 -- default camera x-transposition
local ytrans = 0 -- default camera y-transposition
local scales = {0.5, 1, 2} -- all possible scale levels
local timer = 0 -- time the game is running. can be used for all sorts of calculations
local function applyFloorTransformations()
love.graphics.origin()
love.graphics.translate(love.graphics:getWidth() / 2, love.graphics:getHeight() / 2)
love.graphics.scale(scale * 2, scale)
love.graphics.rotate(-math.pi / 4)
love.graphics.translate(-love.graphics:getWidth() / 2, -love.graphics:getHeight() / 2)
love.graphics.translate(-xtrans, -ytrans)
end
local function applyObjectTransformations()
love.graphics.origin()
love.graphics.translate(love.graphics:getWidth() / 2, love.graphics:getHeight() / 2)
love.graphics.scale(scale, scale)
love.graphics.rotate(-math.pi / 4)
love.graphics.translate(-love.graphics:getWidth() / 2, -love.graphics:getHeight() / 2)
love.graphics.translate(-xtrans * 2, -ytrans)
end
-- converts the given screen coordinates to world coordinates
function drawHandler_screenToTiles(x, y)
local xs = love.graphics:getWidth() / 2
local ys = love.graphics:getHeight() / 2
-- screen center to origin and scale
local xt = (x - xs) / (2 * scale)
local yt = (y - ys) / scale
-- rotate
local xn = xt * math.cos(math.pi / 4) - yt * math.sin(math.pi / 4)
local yn = xt * math.sin(math.pi / 4) + yt * math.cos(math.pi / 4)
-- origin to screen center and shift
xn = xn + xs + xtrans
yn = yn + ytrans + ys
return math.floor(xn / tileWidth) + 1, math.floor(yn / tileWidth) + 1
end
-- converts the given world coordinates to screen coordinates
function drawHandler_tilesToScreen(x, y)
local xs = love.graphics:getWidth() / 2
local ys = love.graphics:getHeight() / 2
local xt = (x - 1) * tileWidth - xtrans - xs
local yt = (y - 1) * tileHeight - ytrans - ys
local xn = xt * math.cos(-math.pi / 4) - yt * math.sin(-math.pi / 4)
local yn = xt * math.sin(-math.pi / 4) + yt * math.cos(-math.pi / 4)
xn = xn * 2 * scale
yn = yn * scale
return xn + xs, yn + ys
end
-- load all textures
-- TODO: overwrite default values by reading from file
function drawHandler_init()
local tiles = love.image.newImageData( "res/tileset.png" )
tileset = {}
local tempData = love.image.newImageData(tileWidth, tileHeight)
tempData:paste(tiles, 0, 0, tileWidth, 0, tileWidth, tileHeight)
tileset["floor"] = love.graphics.newImage( tempData )
tempData:paste(tiles, 0, 0, tileWidth * 2, 0, tileWidth, tileHeight)
tileset["wall"] = love.graphics.newImage( tempData )
tempData:paste(tiles, 0, 0, tileWidth * 3, 0, tileWidth, tileHeight)
tileset["barrel"] = love.graphics.newImage( tempData )
local tiles = love.image.newImageData( "res/charset.png" )
charset = {}
tempData = love.image.newImageData(64, 64)
tempData:paste(tiles, 0, 0, 0, 0, 64, 64)
charset["standing"] = love.graphics.newImage( tempData )
end
function drawHandler_zoomIn()
if scale == scales[2] then
scale = scales[3]
end
if scale == scales[1] then
scale = scales[2]
end
end
function drawHandler_update(dt)
timer = timer + dt
end
function drawHandler_zoomOut()
if scale == scales[2] then
scale = scales[1]
end
if scale == scales[3] then
scale = scales[2]
end
end
-- move the camera into the Direction specified
function drawHandler_shift(dir)
if dir == "up" then
ytrans = ytrans - 50
xtrans = xtrans + 50
end
if dir == "left" then
ytrans = ytrans - 50
xtrans = xtrans - 50
end
if dir == "down" then
ytrans = ytrans + 50
xtrans = xtrans - 50
end
if dir == "right" then
ytrans = ytrans + 50
xtrans = xtrans + 50
end
end
-- main draw function
function drawHandler_draw()
-- setup colors
love.graphics.setBackgroundColor(10, 50, 130, 255) -- * (math.sin(timer / 5) + 1), 30 * (math.cos(timer / 4) + 1), 10 + 30 * (math.sin( timer / 3) + 1), 255)
love.graphics.setColor(255, 255, 255, 255)
-- draw sea
local tiles = core_getSea()
local objects = core_getObjects()
local x0 = drawHandler_screenToTiles(0, love.graphics:getHeight())
local xt = drawHandler_screenToTiles(love.graphics:getWidth(), 0)
local xtrash, y0 = drawHandler_screenToTiles(0, 0)
local xtrash2, yt = drawHandler_screenToTiles(love.graphics:getWidth(), love.graphics:getHeight())
yt = yt + 2
x0 = x0 - 1
for i = xt,x0,-1 do
for j = y0,yt do
if tiles[i] ~= nil and tiles[i][j] ~= nil then
applyFloorTransformations()
local level = tiles[i][j].level
if tiles[i][j].__name == nil then
love.graphics.rectangle('line', (i - 1) * tileWidth, (j - 1) * tileHeight, tileWidth, tileHeight)
elseif tiles[i][j].__name == 'Tile'then
love.graphics.draw(tileset["floor"], (i - 1) * tileWidth, (j - 1) * tileHeight)
elseif tiles[i][j].__name == 'Box' then
if tiles[i - 1] == nil or tiles[i - 1][j].level < level then
love.graphics.draw(tileset["wall"], (i - 2.5 + level) * tileWidth, (j + 0.5 - level) * tileHeight, 0, 1.5, 1, 0, 0, 0, -1.5)
end
if tiles[i][j + 1] == nil or tiles[i][j + 1].level < level then
love.graphics.draw(tileset["wall"], (i - 1 + level) * tileWidth, (j - 0 - level) * tileHeight, 0, 1, 1.5, 0, 0, -1.5, 0)
end
love.graphics.draw(tileset["wall"], (i - 1 + level) * tileWidth, (j - 1 - level) * tileHeight)
end
-- if objects are located at tile daw them as well
love.graphics.origin()
for k,thing in pairs(objects[i][j]) do
local x, y = drawHandler_tilesToScreen(thing.x + thing.level, thing.y - thing.level)
if thing.__name == 'Spaceman' then
love.graphics.draw(charset["standing"], x, y, 0, scale, scale, 64 / 2, 64 * 0.9)
end
end
end
end
end
-- reset coordinate grid
love.graphics.origin()
-- draw debug info box
if DEBUG then
love.graphics.setColor(10, 50, 130, 255)
love.graphics.rectangle('fill', 0, 0, 120, 30)
love.graphics.setColor(230, 230, 230, 220)
love.graphics.rectangle('line', 0, 0, 120, 30)
local delta = love.timer.getAverageDelta()
love.graphics.print(string.format("Avg f/s: %.2f ms", 1000 / (1000 * delta)), 10, 10)
end
end
|
local playsession = {
{"rocifier", {105489}},
{"BravePotato", {1008}},
{"Antonitto", {102}}
}
return playsession
|
local BasePlugin = require "kong.plugins.base_plugin"
local UpstreamHeaderApiHandler = BasePlugin:extend()
function UpstreamHeaderApiHandler:new()
UpstreamHeaderApiHandler.super.new(self, "upstream-header-api")
end
function UpstreamHeaderApiHandler:access(conf)
UpstreamHeaderApiHandler.super.access(self)
local upstream_uri = ngx.var.upstream_uri
local path = conf.path
local header_key = conf.header_key
local stable_version = conf.stable_version
local api_version = nil
local api_path = string.format('%s/%s/', path, stable_version)
local find_str = string.format('%s/', path)
api_version = ngx.req.get_headers()[header_key]
if string.match(path, '/$') then
find_str = path
end
if api_version then
api_path = string.format('%s/%s/', path, api_version)
end
upstream_uri = string.gsub(upstream_uri, find_str, api_path)
ngx.var.upstream_uri = upstream_uri
end
UpstreamHeaderApiHandler.PRIORITY = 100
return UpstreamHeaderApiHandler
|
game:DefineFastFlag("UseNewLeaveGamePrompt", false)
return function()
return game:GetFastFlag("UseNewLeaveGamePrompt")
end
|
function collides(a, b)
-- based on https://sheepolution.com/learn/book/13 , thanks!
local a_left = a.x - (a.width/2)
local a_right = a.x + (a.width/2)
local a_top = a.y - (a.height/2)
local a_bottom = a.y + (a.height/2)
local b_left = b.x - (b.width/2)
local b_right = b.x + (b.width/2)
local b_top = b.y - (b.height/2)
local b_bottom = b.y + (b.height/2)
if a_right > b_left and
a_left < b_right and
a_bottom > b_top and
a_top < b_bottom then
return true
end
return false
end
|
add_rules("mode.debug", "mode.release")
target("foo")
add_rules("mdk.static")
add_files("src/foo/*.c")
target("hello")
add_deps("foo")
add_rules("mdk.console")
add_files("src/*.c", "src/*.s")
add_defines("__EVAL", "__MICROLIB")
add_includedirs("src/lib/cmsis")
|
--[[
1. key - 令牌桶的 key
2. intervalPerTokens - 生成令牌的间隔(ms)
3. curTime - 当前时间
4. initTokens - 令牌桶初始化的令牌数
5. bucketMaxTokens - 令牌桶的上限
6. resetBucketInterval - 重置桶内令牌的时间间隔
7. currentTokens - 当前桶内令牌数
8. bucket - 当前 key 的令牌桶对象
]] --
local key = KEYS[1]
local intervalPerTokens = tonumber(ARGV[1])
local curTime = tonumber(ARGV[2])
local initTokens = tonumber(ARGV[3])
local bucketMaxTokens = tonumber(ARGV[4])
local resetBucketInterval = tonumber(ARGV[5])
local bucket = redis.call('hgetall', key)
local currentTokens
-- 若当前桶未初始化,先初始化令牌桶
if table.maxn(bucket) == 0 then
-- 初始桶内令牌
currentTokens = initTokens
-- 设置桶最近的填充时间是当前
redis.call('hset', key, 'lastRefillTime', curTime)
-- 初始化令牌桶的过期时间, 设置为间隔的 1.5 倍
redis.call('pexpire', key, resetBucketInterval * 1.5)
-- 若桶已初始化,开始计算桶内令牌
-- 为什么等于 4 ? 因为有两对 field, 加起来长度是 4
-- { "lastRefillTime(上一次更新时间)","curTime(更新时间值)","tokensRemaining(当前保留的令牌)","令牌数" }
elseif table.maxn(bucket) == 4 then
-- 上次填充时间
local lastRefillTime = tonumber(bucket[2])
-- 剩余的令牌数
local tokensRemaining = tonumber(bucket[4])
-- 当前时间大于上次填充时间
if curTime > lastRefillTime then
-- 拿到当前时间与上次填充时间的时间间隔
-- 举例理解: curTime = 2620 , lastRefillTime = 2000, intervalSinceLast = 620
local intervalSinceLast = curTime - lastRefillTime
-- 如果当前时间间隔 大于 令牌的生成间隔
-- 举例理解: intervalSinceLast = 620, resetBucketInterval = 1000
if intervalSinceLast > resetBucketInterval then
-- 将当前令牌填充满
currentTokens = initTokens
-- 更新重新填充时间
redis.call('hset', key, 'lastRefillTime', curTime)
-- 如果当前时间间隔 小于 令牌的生成间隔
else
-- 可授予的令牌 = 向下取整数( 上次填充时间与当前时间的时间间隔 / 两个令牌许可之间的时间间隔 )
-- 举例理解 : intervalPerTokens = 200 ms , 令牌间隔时间为 200ms
-- intervalSinceLast = 620 ms , 当前距离上一个填充时间差为 620ms
-- grantedTokens = 620/200 = 3.1 = 3
local grantedTokens = math.floor(intervalSinceLast / intervalPerTokens)
-- 可授予的令牌 > 0 时
-- 举例理解 : grantedTokens = 620/200 = 3.1 = 3
if grantedTokens > 0 then
-- 生成的令牌 = 上次填充时间与当前时间的时间间隔 % 两个令牌许可之间的时间间隔
-- 举例理解 : padMillis = 620%200 = 20
-- curTime = 2620
-- curTime - padMillis = 2600
local padMillis = math.fmod(intervalSinceLast, intervalPerTokens)
-- 将当前令牌桶更新到上一次生成时间
redis.call('hset', key, 'lastRefillTime', curTime - padMillis)
end
-- 更新当前令牌桶中的令牌数
-- Math.min(根据时间生成的令牌数 + 剩下的令牌数, 桶的限制) => 超出桶最大令牌的就丢弃
currentTokens = math.min(grantedTokens + tokensRemaining, bucketMaxTokens)
end
else
-- 如果当前时间小于或等于上次更新的时间, 说明刚刚初始化, 当前令牌数量等于桶内令牌数
-- 不需要重新填充
currentTokens = tokensRemaining
end
end
-- 如果当前桶内令牌小于 0,抛出异常
assert(currentTokens >= 0)
-- 如果当前令牌 == 0 ,更新桶内令牌, 返回 0
if currentTokens == 0 then
redis.call('hset', key, 'tokensRemaining', currentTokens)
return 0
else
-- 如果当前令牌 大于 0, 更新当前桶内的令牌 -1 , 再返回当前桶内令牌数
redis.call('hset', key, 'tokensRemaining', currentTokens - 1)
return currentTokens
end
|
-- Train an auto-encoder using config.json.
require('torch')
require('nn')
require('nnx')
require('optim')
require('hdf5')
require('cunn')
require('cunnx')
require('lfs')
package.path = package.path .. ";" .. lfs.currentdir() .. '/?/th/init.lua'
lib = require('lib')
--- Append the tensor tensor to the tensor acc which may initially be nil.
local function appendTensor(acc, tensor, dim)
local dim = dim or 1
if acc == nil then
acc = tensor:float()
else
acc = torch.cat(acc, tensor:float(), dim)
end
return acc
end
inputFile = '/BS/dstutz/work/data/3d/training_prior_points_10000_5000_32x32x32_easy.h5'
valInputFile = '/BS/dstutz/work/data/3d/validation_points_1000_5000_32x32x32_easy.h5'
inputs = lib.utils.readHDF5(inputFile)
print('[Training] read ' .. inputFile)
valInputs = lib.utils.readHDF5(valInputFile)
print('[Training] read ' .. valInputFile)
--inputs = inputs + 0.5
--valInputs = valInputs + 0.5
shuffle = torch.randperm(inputs:size(2))
shuffle = shuffle:narrow(1, 1, 1000)
shuffle = shuffle:long()
inputs = inputs:index(2, shuffle)
valInputs = valInputs:index(2, shuffle)
-- Check dimensions.
N = inputs:size(1)
nPoints = inputs:size(2)
print('[Training] using ' .. nPoints .. ' points')
inputs = nn.utils.addSingletonDimension(inputs, 2)
valInputs = nn.utils.addSingletonDimension(valInputs, 2)
outputs = inputs:clone()
valOutputs = valInputs:clone()
--- This is a model for testing which allows the network, at least in theory, to learn
-- the identity mapping without any bottleneck
-- @return model
local function model1()
local model = nn.Sequential()
model:add(nn.Identity())
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.SpatialConvolution(1, 128, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialConvolution(128, 128, 3, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialConvolution(128, 256, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(256))
model:add(nn.SpatialConvolution(256, 4, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.SpatialConvolution(4, 256, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(256))
model:add(nn.SpatialConvolution(256, 128, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialFullConvolution(128, 128, 3, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialConvolution(128, 1, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
return model
end
--- This is a bottleneck model where average pooling is used to compute a 256-dimensional bottleneck.
-- @return model
local function model2()
local model = nn.Sequential()
model:add(nn.Identity())
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.SpatialConvolution(1, 128, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialConvolution(128, 256, 3, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(256))
model:add(nn.SpatialConvolution(256, 256, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(256))
model:add(nn.SpatialAveragePooling(1, 1000, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
--model:add(nn.SpatialConvolution(256, 256, 1, 1, 1, 1, 0, 0))
--if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.SpatialFullConvolution(256, 256, 1, 1000, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(256))
model:add(nn.SpatialConvolution(256, 128, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialFullConvolution(128, 128, 3, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
model:add(nn.ReLU(true))
model:add(nn.SpatialBatchNormalization(128))
model:add(nn.SpatialConvolution(128, 1, 1, 1, 1, 1, 0, 0))
if printDimensions then model:add(nn.PrintDimensions()) end
return model
end
--- This is the general model where encoder and decoder can be adapted and the
-- bottleneck is computed using a linear layer.
-- @return model
local function model3()
local model = nn.Sequential()
local autoEncoderConfig = lib.pointAutoEncoder.config
autoEncoderConfig.encoder.features = {64, 128, 256, 512}
autoEncoderConfig.encoder.transfers = {true, true, true, true}
autoEncoderConfig.encoder.normalizations = {true, true, true, true}
autoEncoderConfig.encoder.transfer = nn.ReLU
autoEncoderConfig.decoder.features = {512, 256, 128, 64}
autoEncoderConfig.decoder.transfers = {true, true, true, true}
autoEncoderConfig.decoder.normalizations = {true, true, true, true}
autoEncoderConfig.decoder.transfer = nn.ReLU
autoEncoderConfig.inputNumber = nPoints
autoEncoderConfig.outputNumber = nPoints
autoEncoderConfig.code = 10
local model, context = lib.pointAutoEncoder.autoEncoder(model, autoEncoderConfig)
return model
end
model = model2()
model = model:cuda()
print(model)
-- Criterion.
criterion = nn.SmoothL1ChamferDistanceCriterion()
criterion.sizeAverage = false
criterion = criterion:cuda()
errCriterion = nn.MaxDistanceCriterion()
errCriterion = errCriterion:cuda()
-- Learning hyperparameters.
batchSize = 32
learningRate = 0.05
momentum = 0.5
weightDecay = 0.0001
lossIterations = 10
testIterations = 500
decayIterations = 100
minimumLearningRate = 0.000000001
decayLearningRate = 0.75
decayMomentum = 1.05
maximumMomentum = 0.95
parameters, gradParameters = model:getParameters()
parameters = parameters:cuda()
gradParameters = gradParameters:cuda()
-- Smoothed statistics.
epochs = 20
iterations = epochs*math.floor(N/batchSize)
protocol = torch.Tensor(iterations, 2)
for t = 1, iterations do
-- Sample a random batch from the dataset.
local shuffle = torch.randperm(N)
shuffle = shuffle:narrow(1, 1, batchSize)
shuffle = shuffle:long()
local input = inputs:index(1, shuffle)
local output = outputs:index(1, shuffle)
-- Appyl a random permutation on inputs and outputs
-- to enforce invariance to the order of points in input and output.
for b = 1, input:size(1) do
local shuffle = torch.randperm(input:size(3)):long()
input[b] = input[b]:index(2, shuffle)
--shuffle = torch.randperm(input:size(3)):long()
output[b] = output[b]:index(2, shuffle)
end
input = input:cuda()
output = output:cuda()
--- Definition of the objective on the current mini-batch.
-- This will be the objective fed to the optimization algorithm.
-- @param x input parameters
-- @return object value, gradients
local feval = function(x)
-- Get new parameters.
if x ~= parameters then
parameters:copy(x)
end
-- Reset gradients
gradParameters:zero()
-- Evaluate function on mini-batch.
local pred = model:forward(input)
local f = criterion:forward(pred, output)
local d = errCriterion:forward(pred, output)
protocol[t][1] = f
protocol[t][2] = d
-- Estimate df/dW.
local df_do = criterion:backward(pred, input)
model:backward(input, df_do)
-- Weight decay:
if weightDecay > 0 then
f = f + weightDecay * torch.norm(parameters,2)^2/2
gradParameters:add(parameters:clone():mul(weightDecay))
end
-- return f and df/dX
return f, gradParameters
end
adamState = adamState or {
learningRate = learningRate,
momentum = momentum,
learningRateDecay = 0 -- will be done manually below
}
-- Returns the new parameters and the objective evaluated
-- before the update.
--p, f = optim.adam(feval, parameters, adamState)
p, f = optim.adam(feval, parameters, adamState)
-- Report a smoothed loss instead of batch loss.
if t%lossIterations == 0 then
local smoothedLoss = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 1, 1))
local smoothedDistance = torch.mean(protocol:narrow(1, t - lossIterations + 1, lossIterations):narrow(2, 2, 1))
print('[Training] ' .. t .. ': ' .. smoothedLoss .. ' | ' .. smoothedDistance)
end
-- Validate on validation set.
if t%testIterations == 0 then
local valBatchSize = batchSize
local valNumBatches = math.floor(valInputs:size(1)/valBatchSize)
local valLoss = 0
local valErr = 0
local accValPreds = nil
for b = 0, valNumBatches - 1 do
local input = valInputs:narrow(1, b*valBatchSize + 1, math.min((b + 1)*valBatchSize - b*valBatchSize, valInputs:size(1) - b*valBatchSize))
input = input:cuda()
local output = valOutputs:narrow(1, b*valBatchSize + 1, math.min((b + 1)*valBatchSize - b*valBatchSize, valOutputs:size(1) - b*valBatchSize))
output = output:cuda()
local valPreds = model:forward(input)
accValPreds = appendTensor(accValPreds, valPreds)
valLoss = valLoss + criterion:forward(valPreds, output)
valErr = valErr + errCriterion:forward(valPreds, output)
end
print('[Training] ' .. t .. ': validation loss ' .. valLoss/valNumBatches)
print('[Training] ' .. t .. ': max error ' .. valErr/valNumBatches)
predFile = t .. '.h5'
lib.utils.writeHDF5(predFile, accValPreds)
print('[Training] wrote ' .. predFile)
end
-- Decay learning rate.
if t%decayIterations == 0 then
learningRate = math.max(minimumLearningRate, learningRate*decayLearningRate)
momentum = math.min(maximumMomentum, momentum*decayMomentum)
print('[Training] ' .. t .. ': learning rate ' .. learningRate)
print('[Training] ' .. t .. ': momentum ' .. momentum)
end
end
torch.save('model.dat', model)
print('[Training] snapshot model.dat')
|
--Minetest
--Copyright (C) 2014 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------------
local function get_formspec(tabview, name, tabdata)
if modmgr.global_mods == nil then
modmgr.refresh_globals()
end
if tabdata.selected_mod == nil then
tabdata.selected_mod = 1
end
local retval =
"label[0.05,-0.25;".. fgettext("Installed Mods:") .. "]" ..
"textlist[0,0.25;5.1,4.35;modlist;" ..
modmgr.render_modlist(modmgr.global_mods) ..
";" .. tabdata.selected_mod .. "]"
retval = retval ..
-- "label[0.8,4.2;" .. fgettext("Add mod:") .. "]" ..
-- TODO Disabled due to upcoming release 0.4.8 and irrlicht messing up localization
-- "button[0.75,4.85;1.8,0.5;btn_mod_mgr_install_local;".. fgettext("Local install") .. "]" ..
-- TODO Disabled due to service being offline, and not likely to come online again, in this form
-- "button[0,4.85;5.25,0.5;btn_modstore;".. fgettext("Online mod repository") .. "]"
""
local selected_mod = nil
if filterlist.size(modmgr.global_mods) >= tabdata.selected_mod then
selected_mod = modmgr.global_mods:get_list()[tabdata.selected_mod]
end
if selected_mod ~= nil then
local modscreenshot = nil
--check for screenshot beeing available
local screenshotfilename = selected_mod.path .. DIR_DELIM .. "screenshot.png"
local error = nil
local screenshotfile,error = io.open(screenshotfilename,"r")
if error == nil then
screenshotfile:close()
modscreenshot = screenshotfilename
end
if modscreenshot == nil then
modscreenshot = defaulttexturedir .. "no_screenshot.png"
end
retval = retval
.. "image[5.5,0;3,2;" .. core.formspec_escape(modscreenshot) .. "]"
.. "label[8.25,0.6;" .. selected_mod.name .. "]"
local descriptionlines = nil
error = nil
local descriptionfilename = selected_mod.path .. "description.txt"
local descriptionfile,error = io.open(descriptionfilename,"r")
if error == nil then
local descriptiontext = descriptionfile:read("*all")
descriptionlines = core.splittext(descriptiontext,42)
descriptionfile:close()
else
descriptionlines = {}
table.insert(descriptionlines,fgettext("No mod description available"))
end
retval = retval ..
"label[5.5,1.7;".. fgettext("Mod information:") .. "]" ..
"textlist[5.5,2.2;6.2,2.4;description;"
for i=1,#descriptionlines,1 do
retval = retval .. core.formspec_escape(descriptionlines[i]) .. ","
end
if selected_mod.is_modpack then
retval = retval .. ";0]" ..
"button[10,4.85;2,0.5;btn_mod_mgr_rename_modpack;" ..
fgettext("Rename") .. "]"
retval = retval .. "button[5.5,4.85;4.5,0.5;btn_mod_mgr_delete_mod;"
.. fgettext("Uninstall selected modpack") .. "]"
else
--show dependencies
retval = retval .. "," .. fgettext("Depends:") .. ","
local toadd = modmgr.get_dependencies(selected_mod.path)
retval = retval .. toadd .. ";0]"
retval = retval .. "button[5.5,4.85;4.5,0.5;btn_mod_mgr_delete_mod;"
.. fgettext("Uninstall selected mod") .. "]"
end
end
return retval
end
--------------------------------------------------------------------------------
local function handle_buttons(tabview, fields, tabname, tabdata)
if fields["modlist"] ~= nil then
local event = core.explode_textlist_event(fields["modlist"])
tabdata.selected_mod = event.index
return true
end
if fields["btn_mod_mgr_install_local"] ~= nil then
core.show_file_open_dialog("mod_mgt_open_dlg",fgettext("Select Mod File:"))
return true
end
if fields["btn_modstore"] ~= nil then
local modstore_ui = ui.find_by_name("modstore")
if modstore_ui ~= nil then
tabview:hide()
modstore.update_modlist()
modstore_ui:show()
else
print("modstore ui element not found")
end
return true
end
if fields["btn_mod_mgr_rename_modpack"] ~= nil then
local dlg_renamemp = create_rename_modpack_dlg(tabdata.selected_mod)
dlg_renamemp:set_parent(tabview)
tabview:hide()
dlg_renamemp:show()
return true
end
if fields["btn_mod_mgr_delete_mod"] ~= nil then
local dlg_delmod = create_delete_mod_dlg(tabdata.selected_mod)
dlg_delmod:set_parent(tabview)
tabview:hide()
dlg_delmod:show()
return true
end
if fields["mod_mgt_open_dlg_accepted"] ~= nil and
fields["mod_mgt_open_dlg_accepted"] ~= "" then
modmgr.installmod(fields["mod_mgt_open_dlg_accepted"],nil)
return true
end
return false
end
--------------------------------------------------------------------------------
tab_mods = {
name = "mods",
caption = fgettext("Mods"),
cbf_formspec = get_formspec,
cbf_button_handler = handle_buttons,
on_change = gamemgr.update_gamelist
}
|
local missions = {
[[
mission
{
victory_type vco_type_mp_versus;
key wh_main_mp_versus_victory;
issuer CLAN_ELDERS;
primary_objectives_and_payload
{
objective
{
type RAZE_OR_OWN_X_SETTLEMENTS;
total 999;
}
payload
{
game_victory;
}
}
}
]],
[[
mission
{
victory_type vco_type_mp_coop;
key wh_main_mp_coop_victory;
issuer CLAN_ELDERS;
primary_objectives_and_payload
{
objective
{
type ALL_PLAYERS_RAZE_OR_OWN_X_SETTLEMENTS;
total 999;
}
payload
{
game_victory;
}
}
}
]]
};
return missions;
|
local drunk = Condition(CONDITION_DRUNK)
drunk:setParameter(CONDITION_PARAM_TICKS, 60000)
local poison = Condition(CONDITION_POISON)
poison:setParameter(CONDITION_PARAM_DELAYED, true)
poison:setParameter(CONDITION_PARAM_MINVALUE, -50)
poison:setParameter(CONDITION_PARAM_MAXVALUE, -120)
poison:setParameter(CONDITION_PARAM_STARTVALUE, -5)
poison:setParameter(CONDITION_PARAM_TICKINTERVAL, 4000)
poison:setParameter(CONDITION_PARAM_FORCEUPDATE, true)
local fluidMessage = {
[3] = "Aah...",
[4] = "Urgh!",
[5] = "Mmmh.",
[7] = "Aaaah...",
[10] = "Aaaah...",
[11] = "Urgh!",
[13] = "Urgh!",
[15] = "Aah...",
[19] = "Urgh!",
[43] = "Aaaah..."
}
local fluid = Action()
function fluid.onUse(player, item, fromPosition, target, toPosition, isHotkey)
local targetItemType = ItemType(target.itemid)
if targetItemType and targetItemType:isFluidContainer() then
if target.type == 0 and item.type ~= 0 then
target:transform(target:getId(), item.type)
item:transform(item:getId(), 0)
return true
elseif target.type ~= 0 and item.type == 0 then
target:transform(target:getId(), 0)
item:transform(item:getId(), target.type)
return true
end
end
if target.itemid == 1 then
if item.type == 0 then
player:sendTextMessage(MESSAGE_FAILURE, "It is empty.")
elseif target.uid == player.uid then
if table.contains({3, 15, 43}, item.type) then
player:addCondition(drunk)
elseif item.type == 4 then
player:addCondition(poison)
elseif item.type == 7 then
player:addMana(math.random(50, 150))
fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif item.type == 10 then
player:addHealth(60)
fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE)
end
player:say(fluidMessage[item.type] or "Gulp.", TALKTYPE_MONSTER_SAY)
item:transform(item:getId(), 0)
else
Game.createItem(2886, item.type, toPosition):decay()
item:transform(item:getId(), 0)
end
else
local fluidSource = targetItemType and targetItemType:getFluidSource() or 0
if fluidSource ~= 0 then
item:transform(item:getId(), fluidSource)
elseif item.type == 0 then
player:sendTextMessage(MESSAGE_FAILURE, "It is empty.")
else
if toPosition.x == CONTAINER_POSITION then
toPosition = player:getPosition()
end
Game.createItem(2886, item.type, toPosition):decay()
item:transform(item:getId(), 0)
end
end
return true
end
fluid:id(2524, 2873, 2874, 2875, 2876, 2877, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2893, 2901, 2902, 2903, 2904, 3477, 3478, 3479, 3480)
fluid:register()
|
local M = {}
-- system dependent path separator from plenary.nvim
M.path = {}
M.path.sep = (function()
if jit then
local os = string.lower(jit.os)
if os == "linux" or os == "osx" or os == "bsd" then
return "/"
else
return "\\"
end
else
return package.config:sub(1, 1)
end
end)()
M.path.split = function(path)
local parts = vim.split(path, M.path.sep)
-- only a name given
if #parts == 1 then
return nil, parts[1]
end
-- else return dir and basename
local dir = vim.fn.join(M.slice(parts, 1, #parts - 1), M.path.sep)
local name = parts[#parts]
return dir, name
end
M.slice = function(tbl, s, e)
return { unpack(tbl, s, e) }
end
---@param default table
---@param override table
---@return table
---merges override into default, overriding anything in default
M.merge = function(default, override)
override = override or {}
return vim.tbl_deep_extend("force", {}, default, override)
end
return M
|
if AkDebugLoad then print("Loading ak.train.RollingStockModel ...") end
---@class RollingStockModel
local RollingStockModel = {}
function RollingStockModel:new(o)
o = o or {}
self.__index = self
setmetatable(o, self)
return o
end
function RollingStockModel:setLine(rollingStockName, line)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
assert(type(line) == "string", "Need 'line' as string")
-- Overwrite me
end
function RollingStockModel:setDestination(rollingStockName, destination)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
assert(type(destination) == "string", "Need 'destination' as string")
-- Overwrite me
end
function RollingStockModel:setStations(rollingStockName, stations)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
assert(type(stations) == "string", "Need 'stations' as string")
-- Overwrite me
end
function RollingStockModel:setWagonNr(rollingStockName, wagonNumber)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
assert(type(wagonNumber) == "string", "Need 'wagonNumber' as string")
-- Overwrite me
end
function RollingStockModel:openDoors(rollingStockName)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
-- Overwrite me
end
function RollingStockModel:closeDoors(rollingStockName)
assert(type(self) == "table", "Call this method with ':'")
assert(type(rollingStockName) == "string", "Need 'rollingStockName' as string")
-- Overwrite me
end
return RollingStockModel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.