content
stringlengths 5
1.05M
|
|---|
local input = require "input"
local morse = require "morse"
local class = require "libs.middleclass"
local dahThreshold = 0.3
local letterThreshold = 0.6
local multiThreshold = 0.7
local MorseReader = class("MorseReader")
function MorseReader:initialize()
self:reset()
end
function MorseReader:reset()
self.value = 0
self.duration = 0
self.code = ""
self.buffer = ""
end
function MorseReader:update(dt)
self.duration = self.duration + dt
if input.beep:pressed() then
self.duration = 0
elseif input.beep:released() then
self.code = self.code .. (self.duration > dahThreshold and "-" or ".")
self.duration = 0
end
local letter
if not input.beep:isDown() and self.code ~= "" and self.duration > letterThreshold then
letter = morse[self.code] or ""
self.buffer = self.buffer .. letter
self.code = ""
end
self.value = input.beep:isDown() and self.duration / dahThreshold or 0
return letter, self.buffer
end
local MultiReader = class("MultiReader")
function MultiReader:initialize()
self:reset()
end
function MultiReader:reset()
self.duration = 0
self.beeps = 0
end
function MultiReader:update(dt)
self.duration = self.duration + dt
if input.beep:pressed() then
self.beeps = self.beeps + 1
self.duration = 0
elseif input.beep:released() then
self.duration = 0
end
if self.duration > multiThreshold and self.beeps > 0 then
local beeps = self.beeps
self.beeps = 0
if not input.beep:isDown() then
return true, beeps
end
end
return false, self.beeps
end
return {
MorseReader = MorseReader,
MultiReader = MultiReader
}
|
workspace "Razor"
architecture "x64"
startproject "Sandbox"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "Razor/vendor/GLFW/include"
IncludeDir["Glad"] = "Razor/vendor/Glad/include"
IncludeDir["ImGui"] = "Razor/vendor/imgui"
IncludeDir["glm"] = "Razor/vendor/glm"
IncludeDir["stb"] = "Razor/vendor/stb"
IncludeDir["assimp"] = "Razor/vendor/assimp/include"
IncludeDir["lua"] = "Razor/vendor/lua/include"
IncludeDir["bullet"] = "Razor/vendor/bullet/include"
IncludeDir["openal"] = "Razor/vendor/openal/include"
IncludeDir["opencv"] = "Razor/vendor/opencv/include"
include "Razor/vendor/GLFW"
include "Razor/vendor/Glad"
include "Razor/vendor/ImGui"
project "Razor"
location "Razor"
kind "StaticLib"
staticruntime "on"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "rzpch.h"
pchsource "Razor/src/rzpch.cpp"
linkoptions { "-IGNORE:4221", "-IGNORE:4006" }
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cc",
"%{prj.name}/src/**.cpp",
"%{prj.name}/vendor/glm/glm/**.hpp",
"%{prj.name}/vendor/glm/glm/**.inl",
"%{prj.name}/vendor/assimp/include/**",
}
includedirs
{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.glm}",
"%{IncludeDir.stb}",
"%{IncludeDir.lua}",
"%{IncludeDir.bullet}",
"%{IncludeDir.openal}",
"%{IncludeDir.opencv}",
"%{prj.name}/vendor/assimp/include",
"%{prj.name}/vendor/assimp/build/include"
}
libdirs {
"%{prj.name}/vendor/assimp/build/code/Release",
"%{prj.name}/vendor/lua",
"%{prj.name}/vendor/bullet/lib",
"%{prj.name}/vendor/openal",
"%{prj.name}/vendor/opencv",
}
links
{
"GLFW",
"Glad",
"ImGui",
"opengl32.lib",
"assimp",
"lua53.lib",
"OpenAL32.lib",
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"IMGUI_API=__declspec(dllexport)",
"RZ_PLATFORM_WINDOWS",
"GLFW_INCLUDE_NONE",
"_CRT_SECURE_NO_WARNINGS"
}
postbuildcommands
{
--"{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Sandbox",
--"{COPY} %{cfg.buildtarget.relpath} ../bin/" .. outputdir .. "/Server",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Release-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Debug-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Release-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Debug-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Release-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Debug-windows-x86_64/Sandbox",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Release-windows-x86_64/Server",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Debug-windows-x86_64/Server",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Release-windows-x86_64/Server",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Debug-windows-x86_64/Server",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Release-windows-x86_64/Server",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Debug-windows-x86_64/Server",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Release-windows-x86_64/Client",
"{COPY} ../Razor/vendor/assimp/build/code/Release/assimp.dll ../bin/Debug-windows-x86_64/Client",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Release-windows-x86_64/Client",
"{COPY} ../Razor/vendor/lua/lua53.dll ../bin/Debug-windows-x86_64/Client",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Release-windows-x86_64/Client",
"{COPY} ../Razor/vendor/openal/OpenAL32.dll ../bin/Debug-windows-x86_64/Client"
}
filter "configurations:Debug"
defines "RZ_DEBUG"
buildoptions {"/MTd"}
symbols "On"
links {
"BulletCollision_Debug.lib",
"BulletDynamics_Debug.lib",
"BulletSoftBody_Debug.lib",
"LinearMath_Debug.lib",
"opencv_core411d.lib",
"opencv_imgcodecs411d.lib",
"opencv_highgui411d.lib",
"opencv_imgproc411d.lib",
"opencv_videoio411d.lib"
}
filter "configurations:Release"
defines "RZ_RELEASE"
runtime "Release"
optimize "On"
links {
"BulletCollision.lib",
"BulletDynamics.lib",
"BulletSoftBody.lib",
"LinearMath.lib",
"opencv_core411.lib",
"opencv_imgcodecs411.lib",
"opencv_highgui411.lib",
"opencv_imgproc411.lib",
"opencv_videoio411.lib"
}
filter "configurations:Dist"
defines "RZ_DIST"
runtime "Release"
optimize "On"
links {
"BulletCollision.lib",
"BulletDynamics.lib",
"BulletSoftBody.lib",
"LinearMath.lib",
"opencv_core411.lib",
"opencv_imgcodecs411.lib",
"opencv_highgui411.lib",
"opencv_imgproc411.lib",
"opencv_videoio411.lib"
}
project "Sandbox"
location "Sandbox"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Razor/vendor/spdlog/include",
"Razor/src",
"Razor/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.bullet}"
}
links
{
"Razor"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"RZ_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "RZ_DEBUG"
kind "ConsoleApp"
symbols "On"
filter "configurations:Release"
defines "RZ_RELEASE"
optimize "On"
kind "WindowedApp"
entrypoint "mainCRTStartup"
filter "configurations:Dist"
defines "RZ_DIST"
optimize "On"
kind "WindowedApp"
entrypoint "mainCRTStartup"
project "Server"
location "Server"
kind "ConsoleApp"
language "C++"
linkoptions {
"-IGNORE:4099"
}
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Razor/vendor/spdlog/include",
"Razor/src",
"Razor/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.bullet}"
}
links
{
"Razor"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"_CRT_SECURE_NO_WARNINGS",
"RZ_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "RZ_DEBUG"
symbols "On"
buildoptions {"/MTd"}
filter "configurations:Release"
defines "RZ_RELEASE"
optimize "On"
filter "configurations:Dist"
defines "RZ_DIST"
optimize "On"
project "Client"
location "Client"
language "C++"
kind "WindowedApp"
linkoptions {
"-IGNORE:4099"
}
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"%{IncludeDir.GLFW}",
"Razor/vendor/spdlog/include",
"Razor/src",
"Razor/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.bullet}"
}
links
{
"Razor"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines
{
"_CRT_SECURE_NO_WARNINGS",
"RZ_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "RZ_DEBUG"
symbols "On"
kind "ConsoleApp"
buildoptions {"/MTd"}
filter "configurations:Release"
defines "RZ_RELEASE"
optimize "On"
entrypoint "mainCRTStartup"
filter "configurations:Dist"
defines "RZ_DIST"
optimize "On"
entrypoint "mainCRTStartup"
|
--@name Setpos methods
--@author Neatro
--@server
if not hasPermission( "entities.setPos", owner() ) then
throw( "You need Entities permission to see this example code! Enable permission entities.setpos" )
end
--[[
This example code shows how smooth Setpos is achieved.
You may have tried to directly setPos() an entity and saw how the movement was very choppy.
This is because this method doesn't have any interpolation.
It can be good for other uses unless you want smooth motion with setPos().
To do this, you need to setPos() the physicsObject of an entity.
This retains the interpolation and makes motion looks smooth.
As an example, The red box has setPos on itself.
The greenbox has setPos on the physicsObject.
]]--
--ignore this bit, it's for creating the prop
function create( c )
p = prop.create( Vector( 0), Angle( 0 ), "models/props_junk/wood_crate001a.mdl", 1 )
p:setColor( c )
return p
end
--hook
hook.add( "tick", "runtime", function()
--movement code
Motion = chip():getPos() + Vector( math.sin( timer.systime() * 4 ) * 64, 0, 48 )
--spawns prop when it doesn't exist
normal = ( ( not normal or not normal:isValid() ) and prop.canSpawn() ) and create( Color( 255, 0, 0, 255 ) ) or normal
--check
if normal and normal:isValid() and normal:isValidPhys() then
--This is setpos WITHOUT getting the entities getPhysicsObject()
--There is NO interpolation!
normal:setPos( Motion )
end
--movement code
Motion = Motion + Vector( 0, 0, 48 )
--spawns prop when it doesn't exist
normalandphys = ( ( not normalandphys or not normalandphys:isValid() ) and prop.canSpawn() ) and create( Color( 0, 255, 0, 255 ) ) or normalandphys
--check
if normalandphys and normalandphys:isValid() and normalandphys:isValidPhys() then
--This is setpos With getting the entities getPhysicsObject()
--Interpolation will work!
normalandphys:getPhysicsObject():setPos( Motion )
-- __________________
end
end )
|
--[[
Copyright 2018 H8UL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
data:extend{
{
type = "string-setting",
name = "research-causes-evolution-weighting",
setting_type = "startup",
default_value = "early",
allowed_values = {"early", "equal", "late"}
},
{
type = "bool-setting",
name = "research-causes-evolution-include-upgrades",
setting_type = "startup",
default_value = "true"
}
}
|
---- importing ----
if string.sub(_VERSION,1,7)=='Lua 5.0' then
-- lua5.0 doesnt have a nice way to do this
lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
assert(lib)()
else
-- lua 5.1 does
require('example')
end
-- Call our gcd() function
x = 42
y = 105
g = example.gcd(x,y)
print("The gcd of",x,"and",y,"is",g)
-- Manipulate the Foo global variable
-- Output its current value
print("Foo = ", example.Foo)
-- Change its value
example.Foo = 3.1415926
-- See if the change took effect
print("Foo = ", example.Foo)
|
--------------------------------------------------------------------------------
-- 0130-priority_queue.lua: tests for priority queue
-- This file is a part of lua-nucleo library
-- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local make_suite = assert(loadfile('test/test-lib/init/strict.lua'))(...)
local is_table
= import 'lua-nucleo/type.lua'
{
'is_table'
}
local assert_is_table,
assert_is_number
= import 'lua-nucleo/typeassert.lua'
{
'assert_is_table',
'assert_is_number'
}
local arguments
= import 'lua-nucleo/args.lua'
{
'arguments'
}
local ensure,
ensure_equals,
ensure_tequals,
ensure_fails_with_substring
= import 'lua-nucleo/ensure.lua'
{
'ensure',
'ensure_equals',
'ensure_tequals',
'ensure_fails_with_substring'
}
local tstr,
tclone,
tgenerate_n,
tequals,
tset
= import 'lua-nucleo/table.lua'
{
'tstr',
'tclone',
'tgenerate_n',
'tequals',
'tset'
}
local invariant,
make_generator_mt
= import 'lua-nucleo/functional.lua'
{
'invariant',
'make_generator_mt'
}
local make_priority_queue,
priority_queue_exports
= import 'lua-nucleo/priority_queue.lua'
{
'make_priority_queue'
}
local make_value_generators
= import 'test/test-lib/value_generators.lua'
{
'make_value_generators'
}
--------------------------------------------------------------------------------
local test = make_suite("priority_queue", priority_queue_exports)
local check_insert_pop_elements = function(elements)
arguments(
"table", elements
)
elements = tclone(elements)
local priority_queue = ensure("created priority queue", make_priority_queue())
-- Separate queue to ensure front does not affect pop.
local priority_queue_2 = ensure("created priority queue 2", make_priority_queue())
ensure_equals("no first before element", priority_queue:front(), nil)
print("Building queues")
for i = 1, #elements do
if i % 1000 == 0 then
print(i, "of", #elements)
end
local v = elements[i]
priority_queue:insert(v.p, v.v)
priority_queue_2:insert(v.p, v.v)
end
print("Sorting elements")
table.sort(elements, function(lhs, rhs) return lhs.p < rhs.p end)
print("Detecting duplicates")
local element_counts = setmetatable(
{ },
make_generator_mt(function()
return setmetatable(
{ },
make_generator_mt(invariant(0))
)
end)
)
for i = 1, #elements do
if i % 1000 == 0 then
print(i, "of", #elements)
end
local priority_element_counts = element_counts[elements[i].p]
priority_element_counts[elements[i].v] = priority_element_counts[elements[i].v] + 1
end
print("Popping")
for i = 1, #elements do
if i % 1000 == 0 then
print(i, "of", #elements)
end
local front = { priority_queue_2:front() }
local popped = { priority_queue:pop() }
ensure_tequals("pop2 " .. i, { priority_queue_2:pop() }, front)
ensure_tequals("front matches popped " .. i, front, popped)
local expected = { elements[i].p, elements[i].v }
local popped_p, popped_v = unpack(popped)
local expected_p = unpack(expected)
local handled_duplicate = false
if popped_p == expected_p then
local priority_element_counts = element_counts[popped_p]
if priority_element_counts[popped_v] > 0 then
priority_element_counts[popped_v] = priority_element_counts[popped_v] - 1
handled_duplicate = true
else
-- Would be handled in the check below
print("unexpected element", popped_v, "for priority", popped_p)
end
end
if not handled_duplicate then
ensure_tequals( -- Would fail. It is here for consistent error message.
"popped priority " .. i,
popped,
expected
)
end
end
ensure_equals("no first after element", priority_queue:front(), nil)
for p, priority_element_counts in pairs(element_counts) do
for v, count in pairs(priority_element_counts) do
if count ~= 0 then
error(
"detected unhandled elements"
.. " p: " .. tostring(p)
.. " v: " .. tostring(v)
.. " count: " .. tostring(count)
)
end
end
end
print("Done")
end
--------------------------------------------------------------------------------
test:factory "make_priority_queue" (make_priority_queue)
test:methods "insert"
"pop"
"front"
--------------------------------------------------------------------------------
test "empty" (function()
local priority_queue = make_priority_queue()
ensure("created priority queue", priority_queue)
ensure_equals("no first element", priority_queue:front(), nil)
end)
--------------------------------------------------------------------------------
test "empty-pop" (function()
local priority_queue = make_priority_queue()
ensure("created priority queue", priority_queue)
ensure_equals("no first element", priority_queue:front(), nil)
ensure_equals("pop on empty queue", priority_queue:pop(), nil)
priority_queue:insert(1, "1")
ensure_tequals(
"pop on non-empty queue",
{ priority_queue:pop() },
{ 1, "1" }
)
ensure_equals("pop on empty queue again", priority_queue:pop(), nil)
end)
--------------------------------------------------------------------------------
test "insert-pop-insert" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
ensure_equals("no first element", priority_queue:front(), nil)
priority_queue:insert(2, "2")
priority_queue:insert(1, "1")
priority_queue:insert(priority_queue:pop())
print(tstr(priority_queue.queue_))
ensure_tequals("pop 2", { priority_queue:pop() }, { 1, "1" })
ensure_tequals("pop 1", { priority_queue:pop() }, { 2, "2" })
ensure_tequals("empty", { priority_queue:pop() }, { nil })
end)
--------------------------------------------------------------------------------
test "single-element" (function()
check_insert_pop_elements({{p = 42, v = function() end}})
end)
--------------------------------------------------------------------------------
test "single-invalid-priority-type" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
local value = 42
ensure_fails_with_substring(
"priority cannot be of 'nil' type",
function() priority_queue:insert(nil, value) end,
"expected `number', got `nil'"
)
ensure_fails_with_substring(
"priority cannot be of 'string' type",
function() priority_queue:insert("the string", value) end,
"expected `number', got `string'"
)
ensure_fails_with_substring(
"priority cannot be of 'table' type",
function() priority_queue:insert({}, value) end,
"expected `number', got `table'"
)
ensure_fails_with_substring(
"priority cannot be of 'function' type",
function() priority_queue:insert(function() end, value) end,
"expected `number', got `function'"
)
ensure_fails_with_substring(
"priority cannot be of 'coroutine' type",
function() priority_queue:insert(coroutine.create(function() end), value) end,
"expected `number', got `thread'"
)
ensure_fails_with_substring(
"priority cannot be of 'userdata' type",
function() priority_queue:insert(newproxy(), value) end,
"expected `number', got `userdata'"
)
end)
--------------------------------------------------------------------------------
test "insert_nil_fails" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
ensure_fails_with_substring(
"can't insert nil",
function() priority_queue:insert(1, nil) end,
"value can't be nil"
)
end)
test "many-elements-direct" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
local elements =
{
{ p = 1, v = 322 };
{ p = 2, v = "v" };
{ p = 3, v = function() end };
{ p = 4, v = {} };
}
check_insert_pop_elements(elements)
end)
test "many-elements-reversed" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
local elements =
{
{ p = 4, v = {} };
{ p = 3, v = function() end };
{ p = 2, v = "v" };
{ p = 1, v = 322 };
}
check_insert_pop_elements(elements)
end)
test "many-elements-random-hardcoded" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
local elements =
{
{ p = 2, v = "v" };
{ p = 3, v = function() end };
{ p = 1, v = 322 };
{ p = 4, v = {} };
}
check_insert_pop_elements(elements)
end)
test "many-elements-random-generated" (function()
local priority_queue = ensure("created priority queue", make_priority_queue())
local value_generators = make_value_generators(tset({ "userdata" }))
local MIN_ELEMENTS = 0
local MAX_ELEMENTS = 1e4
local MIN_PRIORITY = 0
local MAX_PRIORITY = 1e3
local elements = tgenerate_n(
math.random(MIN_ELEMENTS, MAX_ELEMENTS),
function()
return
{
p = math.random(MIN_PRIORITY, MAX_PRIORITY);
v = value_generators[math.random(#value_generators)]();
}
end
)
check_insert_pop_elements(elements)
end)
|
--- Created By : TheOfficialSouthern
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if IsPedInAnyVehicle(GetPlayerPed(-1), false)
then if GetPedInVehicleSeat(GetVehiclePedIsIn(GetPlayerPed(-1), false), 0) == GetPlayerPed(-1)
then if GetIsTaskActive(GetPlayerPed(-1), 165)
then SetPedIntoVehicle(GetPlayerPed(-1), GetVehiclePedIsIn(GetPlayerPed(-1), false), 0) SetPedConfigFlag(lPed, 32, true)
end
end
end
end
end)
|
local crt = ...
return {
include = function()
includedirs "../vendor/breakpad/src/"
configuration "linux"
includedirs { "vendor/breakpad/src/" }
configuration {}
end,
run = function()
language "C++"
kind "StaticLib"
if _OPTIONS['game'] ~= 'server' and crt then
staticruntime 'On'
end
configuration "linux"
includedirs { "vendor/breakpad/src/" }
files_project "../vendor/breakpad/src/" {
"client/linux/handler/exception_handler.cc",
"client/linux/handler/minidump_descriptor.cc",
"client/linux/dump_writer_common/thread_info.cc",
"client/linux/dump_writer_common/ucontext_reader.cc",
"client/linux/crash_generation/crash_generation_client.cc",
"client/linux/crash_generation/crash_generation_server.cc",
"client/linux/microdump_writer/microdump_writer.cc",
"client/linux/minidump_writer/linux_core_dumper.cc",
"client/linux/minidump_writer/linux_dumper.cc",
"client/linux/minidump_writer/linux_ptrace_dumper.cc",
"client/linux/minidump_writer/minidump_writer.cc",
"client/minidump_file_writer.cc",
"client/linux/log/log.cc",
"common/md5.cc",
"common/string_conversion.cc",
"common/linux/elf_core_dump.cc",
"common/linux/elfutils.cc",
"common/linux/file_id.cc",
"common/linux/guid_creator.cc",
"common/linux/linux_libc_support.cc",
"common/linux/memory_mapped_file.cc",
"common/linux/safe_readlink.cc",
"common/linux/http_upload.cc",
"common/convert_UTF.cc",
"common/linux/breakpad_getcontext.S",
}
configuration "windows"
files_project "../vendor/breakpad/src/" {
"client/windows/handler/exception_handler.cc",
"client/windows/crash_generation/client_info.cc",
"client/windows/crash_generation/crash_generation_client.cc",
"client/windows/crash_generation/crash_generation_server.cc",
"client/windows/crash_generation/minidump_generator.cc",
"common/windows/guid_string.cc",
"common/windows/http_upload.cc",
"common/windows/string_utils.cc",
}
end
}
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
-----------------
-- Guild Ranks --
-----------------
ZO_GUILD_RANK_PERMISSON_HEADER_TEMPLATE_GAMEPAD_HEIGHT = 43
local GUILD_RENAME_RANK_GAMEPAD_DIALOG = "GAMEPAD_RENAME_RANK_DIALOG"
local GUILD_DELETE_RANK_GAMEPAD_DIALOG = "GAMEPAD_DELETE_RANK_DIALOG"
local GUILD_DELETE_RANK_GAMEPAD_WARNING_DIALOG = "GUILD_REMOVE_RANK_WARNING"
local GUILDMASTER_INDEX = 1
local REFRESH_SCREEN = true
local DONT_REFRESH_SCREEN = false
local ADD_RANK_DIALOG_NAME = "GUILD_ADD_RANK_GAMEPAD"
local GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE = "ZO_GamepadMenuEntryTemplate"
local LIST_DISPLAY_MODES =
{
RANKS = 1,
OPTIONS = 2,
SELECT_ICON = 3,
CHANGE_PERMISSIONS = 4,
}
local function SetupRequestEntry(control, data, selected, reselectingDuringRebuild, enabled, active)
local isValid = enabled
if data.validInput then
isValid = data.validInput()
data.disabled = not isValid
data:SetEnabled(isValid)
end
ZO_SharedGamepadEntry_OnSetup(control, data, selected, reselectingDuringRebuild, isValid, active)
end
local ZO_GuildRanks_Gamepad = ZO_GuildRanks_Shared:Subclass()
function ZO_GuildRanks_Gamepad:New(...)
local guildRanks = ZO_GuildRanks_Shared.New(self, ...)
guildRanks:Initialize(...)
return guildRanks
end
function ZO_GuildRanks_Gamepad:SetMainList(list)
self.rankList = list
end
function ZO_GuildRanks_Gamepad:SetOptionsList(optionsList)
self.optionsList = optionsList
end
function ZO_GuildRanks_Gamepad:SetOwningScreen(owningScreen)
self.owningScreen = owningScreen
end
function ZO_GuildRanks_Gamepad:Initialize(control)
local templateData =
{
gridListClass = ZO_GridScrollList_Gamepad,
entryTemplate = "ZO_CheckboxTile_Gamepad_Control",
entryWidth = ZO_CHECKBOX_TILE_GAMEPAD_WIDTH,
entryHeight = ZO_CHECKBOX_TILE_GAMEPAD_HEIGHT,
headerTemplate = "ZO_GuildRanks_Permission_Gamepad_Header_Template",
headerHeight = ZO_GUILD_RANK_PERMISSON_HEADER_TEMPLATE_GAMEPAD_HEIGHT,
highlightTemplate = "ZO_GuildRanks_Permission_Gamepad_Highlight_Template",
}
ZO_GuildRanks_Shared.Initialize(self, control, templateData)
-- Initialize grid list object
local ALWAYS_ANIMATE = true
GUILD_RANKS_PERMISSION_PANEL_FRAGMENT = ZO_FadeSceneFragment:New(self.permissionsGridListControl, ALWAYS_ANIMATE)
self.rankIconPickerGridListControl = self.control:GetNamedChild("RankIconPicker")
GUILD_RANK_ICON_PICKER_FRAGMENT = ZO_FadeSceneFragment:New(self.rankIconPickerGridListControl, ALWAYS_ANIMATE)
self:InitializePermissionsGridList()
self.rankIconPicker = ZO_GuildRankIconPicker_Gamepad:New(self.rankIconPickerGridListControl)
self.rankIconPicker:SetGetSelectedRankFunction(function(...) return self:GetSelectedRank() end)
self.rankIconPicker:SetRankIconPickedCallback(function(...) self.selectedRank:SetIconIndex(...) end)
GUILD_RANKS_GAMEPAD_FRAGMENT = ZO_FadeSceneFragment:New(self.control, ALWAYS_ANIMATE)
GUILD_RANKS_GAMEPAD_FRAGMENT:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_SHOWING then
self:ResetRankSelection()
self:PerformDeferredInitialization()
self:ReloadAndRefreshScreen()
self:OnTargetChanged(self.rankList, self.rankList:GetTargetData())
self.owningScreen:SetListsUseTriggerKeybinds(true)
KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor)
local OnRefresh = function()
self:ReloadAndRefreshScreen()
end
local OnRefreshMatchGuildId = function(_, guildId)
if self:MatchesGuild(guildId) then
self:RefreshScreen()
end
end
self.control:RegisterForEvent(EVENT_GUILD_DATA_LOADED, OnRefresh)
self.control:RegisterForEvent(EVENT_GUILD_RANKS_CHANGED, OnRefreshMatchGuildId)
self.control:RegisterForEvent(EVENT_GUILD_RANK_CHANGED, OnRefreshMatchGuildId)
self.control:RegisterForEvent(EVENT_SAVE_GUILD_RANKS_RESPONSE, OnRefreshMatchGuildId)
elseif newState == SCENE_HIDING then
self:RemoveUnusedFragments()
self:SetChangePermissionsEnabled(false)
self.rankIconPicker:Deactivate()
GAMEPAD_NAV_QUADRANT_1_BACKGROUND_FRAGMENT:TakeFocus()
if self.currentDropdown then
self.currentDropdown:Deactivate(true)
end
self.owningScreen:SetListsUseTriggerKeybinds(false)
KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor)
self.control:UnregisterForEvent(EVENT_GUILD_DATA_LOADED)
self.control:UnregisterForEvent(EVENT_GUILD_RANKS_CHANGED)
self.control:UnregisterForEvent(EVENT_GUILD_RANK_CHANGED)
self.control:UnregisterForEvent(EVENT_SAVE_GUILD_RANKS_RESPONSE)
if self:NeedsSave() then
PlaySound(SOUNDS.GUILD_RANK_SAVED)
self:Save()
end
end
end)
end
function ZO_GuildRanks_Gamepad:InitializePermissionsGridListControl()
self.permissionsGridListControl = self.control:GetNamedChild("PermissionsPanel")
end
function ZO_GuildRanks_Gamepad:InitializePermissionsGridList()
ZO_GuildRanks_Shared.InitializePermissionsGridList(self)
self.permissionsGridList:SetOnSelectedDataChangedCallback(function(...) self:OnPermissionsGridSelectionChanged(...) end)
end
function ZO_GuildRanks_Gamepad:OnPermissionsGridSelectionChanged(oldSelectedData, selectedData)
-- Deselect previous tile
if oldSelectedData and oldSelectedData.dataEntry then
oldSelectedData.isSelected = false
end
-- Select newly selected tile.
if selectedData and selectedData.dataEntry then
selectedData.isSelected = true
end
self.permissionsGridList:RefreshGridList()
local currentSelectedData = self.permissionsGridList:GetSelectedData()
if currentSelectedData then
local permission = currentSelectedData.value
local permissionInfo = ZO_GuildRanks_Shared.GetToolTipInfoForPermission(permission)
GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP)
if permissionInfo then
GAMEPAD_TOOLTIPS:LayoutTextBlockTooltip(GAMEPAD_RIGHT_TOOLTIP, permissionInfo)
end
end
end
function ZO_GuildRanks_Gamepad:OnPermissionGridListEntryToggle(...)
self.selectedRank:SetPermission(...)
self.permissionsGridList:RefreshGridList()
end
function ZO_GuildRanks_Gamepad:GetSelectedRank()
return self.selectedRank
end
function ZO_GuildRanks_Gamepad:ResetRankSelection()
self.selectedRank = nil
self:ActivateRankList(DONT_REFRESH_SCREEN)
end
function ZO_GuildRanks_Gamepad:ActivateRankList(refreshScreen)
self.listDisplayMode = LIST_DISPLAY_MODES.RANKS
if refreshScreen then
self:RefreshScreen()
end
self.owningScreen:SetCurrentList(self.rankList)
end
function ZO_GuildRanks_Gamepad:ActivateOptionsList(refreshScreen)
if self.selectedRank == nil then
return
end
self.listDisplayMode = LIST_DISPLAY_MODES.OPTIONS
if refreshScreen then
self:RefreshScreen()
end
GAMEPAD_NAV_QUADRANT_1_BACKGROUND_FRAGMENT:TakeFocus()
self.owningScreen:SetCurrentList(self.optionsList)
end
function ZO_GuildRanks_Gamepad:DeactivateOptionsList()
self.optionsList:Deactivate()
GAMEPAD_NAV_QUADRANT_1_BACKGROUND_FRAGMENT:ClearFocus()
end
function ZO_GuildRanks_Gamepad:PerformDeferredInitialization()
if self.deferredInitialized then
return
end
self.deferredInitialized = true
self:InitializeKeybindStrip()
self:InitializeDeleteRankDialog()
self:InitializeRenameRankDialog()
self:InitializeAddRankDialog()
end
function ZO_GuildRanks_Gamepad:ReloadAndRefreshScreen()
self:PopulateRanks()
self:RefreshScreen()
end
function ZO_GuildRanks_Gamepad:RefreshScreen()
self:RefreshLists()
self:RefreshContent()
self.owningScreen:RefreshHeader()
end
function ZO_GuildRanks_Gamepad:RefreshLists()
if self:IsDisplayingRankList() then
self:RefreshRankList()
elseif self:IsDisplayingOptionsList() then
self:RefreshOptionsList()
end
end
function ZO_GuildRanks_Gamepad:RefreshContent()
if self:IsDisplayingRankList() then
self:ActivateFragment(GUILD_RANKS_PERMISSION_PANEL_FRAGMENT)
self.permissionsGridList:RefreshGridList()
elseif self:IsDisplayingOptionsList() then
self:ActivateFragment(GUILD_RANKS_PERMISSION_PANEL_FRAGMENT)
self.permissionsGridList:RefreshGridList()
elseif self:IsDisplayingRankIconPicker() then
self:ActivateFragment(GUILD_RANK_ICON_PICKER_FRAGMENT)
self.rankIconPicker:RefreshGridList()
self.owningScreen:SetListsUseTriggerKeybinds(false)
elseif self:IsDisplayingChangePermissions() then
self:ActivateFragment(GUILD_RANKS_PERMISSION_PANEL_FRAGMENT)
self.owningScreen:SetListsUseTriggerKeybinds(false)
end
self:SetChangePermissionsEnabled(self:IsDisplayingChangePermissions())
self:SetChangeRankIconPickerEnabled(self:IsDisplayingRankIconPicker())
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
-----------------
-- Dropdowns --
-----------------
function ZO_GuildRanks_Gamepad:SetCurrentDropdown(dropdown)
self.currentDropdown = dropdown
end
------------------
-- Rank Dialogs --
------------------
function ZO_GuildRanks_Gamepad:InitializeAddRankDialog()
local dialogName = ADD_RANK_DIALOG_NAME
local parametricDialog = ZO_GenericGamepadDialog_GetControl(GAMEPAD_DIALOGS.PARAMETRIC)
local function UpdateSelectedName(name)
if self.selectedName ~= name then
self.selectedName = name
self.noViolations = self.selectedName ~= "" and self.selectedName ~= nil
end
end
local function UpdateSelectedRankIndex(rank)
if self.selectedRankIndex ~= rank then
self.selectedRankIndex = rank
end
end
local function ReleaseDialog()
ZO_Dialogs_ReleaseDialogOnButtonPress(dialogName)
end
ZO_Dialogs_RegisterCustomDialog(dialogName,
{
gamepadInfo = {
dialogType = GAMEPAD_DIALOGS.PARAMETRIC,
},
setup = function(dialog)
self.noViolations = nil
self.selectedRankIndex = nil
self.selectedName = nil
UpdateSelectedName("")
dialog:setupFunc()
end,
blockDialogReleaseOnPress = true, -- We'll handle Dialog Releases ourselves since we don't want DIALOG_PRIMARY to release the dialog on press.
title =
{
text = SI_GUILD_RANKS_ADD_RANK,
},
parametricList =
{
-- guild name edit box
{
template = "ZO_Gamepad_GenericDialog_Parametric_TextFieldItem",
templateData = {
nameField = true,
textChangedCallback = function(control)
local newName = control:GetText()
if self.selectedName ~= newName then
UpdateSelectedName(newName)
ZO_GenericParametricListGamepadDialogTemplate_RefreshVisibleEntries(parametricDialog)
end
end,
setup = function(control, data, selected, reselectingDuringRebuild, enabled, active)
control.highlight:SetHidden(not selected)
control.editBoxControl.textChangedCallback = data.textChangedCallback
if self.selectedName == "" then
ZO_EditDefaultText_Initialize(control.editBoxControl, GetString(SI_GAMEPAD_GUILD_RANK_DIALOG_DEFAULT_TEXT))
end
control.editBoxControl:SetMaxInputChars(MAX_GUILD_RANK_NAME_LENGTH)
control.editBoxControl:SetText(self.selectedName)
KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups()
end,
},
},
-- rank to copy entry
{
header = GetString(SI_GUILD_RANKS_COPY_HEADER),
template = "ZO_GamepadDropdownItem",
templateData = {
rankSelector = true,
setup = function(control, data, selected, reselectingDuringRebuild, enabled, active)
control.dropdown:SetSortsItems(false)
self:SetCurrentDropdown(control.dropdown)
control.dropdown:ClearItems()
local function UpdateDropdownSelection()
if(self.selectedRankIndex) then
control.dropdown:SetSelectedItemText(self.ranks[self.selectedRankIndex].name)
else
control.dropdown:SetSelectedItemText(GetString(SI_GUILD_RANKS_COPY_NONE))
end
end
local function OnRankSelected(comboBox, entryText, entry)
UpdateSelectedRankIndex(entry.rankIndex)
end
local noneEntry = control.dropdown:CreateItemEntry(GetString(SI_GUILD_RANKS_COPY_NONE), OnRankSelected)
control.dropdown:AddItem(noneEntry)
--Skip Guild Master
for i = 2, #self.ranks do
local entry = control.dropdown:CreateItemEntry(self.ranks[i].name, OnRankSelected)
entry.rankIndex = i
control.dropdown:AddItem(entry)
end
control.dropdown:UpdateItems()
UpdateDropdownSelection()
end,
},
},
-- create
{
template = "ZO_GamepadTextFieldSubmitItem",
templateData = {
finishedSelector = true,
text = GetString(SI_DIALOG_ACCEPT),
setup = SetupRequestEntry,
validInput = function()
return self.noViolations
end,
},
icon = ZO_GAMEPAD_SUBMIT_ENTRY_ICON,
},
},
buttons =
{
-- Cancel Button
{
keybind = "DIALOG_NEGATIVE",
text = GetString(SI_DIALOG_CANCEL),
callback = function()
ReleaseDialog()
end,
},
-- Select Button (used for entering name)
{
keybind = "DIALOG_PRIMARY",
text = GetString(SI_GAMEPAD_SELECT_OPTION),
callback = function(dialog)
local targetData = dialog.entryList:GetTargetData()
local targetControl = dialog.entryList:GetTargetControl()
if targetData.nameField and targetControl then
targetControl.editBoxControl:TakeFocus()
elseif targetData.rankSelector then
self.currentDropdown:Activate()
local highlightIndex = 1
if self.selectedRankIndex ~= nil then
highlightIndex = self.selectedRankIndex
end
self.currentDropdown:SetHighlightedItem(highlightIndex)
elseif targetData.finishedSelector then
if self.noViolations then
self:AddRank(self.selectedName, self.selectedRankIndex)
self:RefreshScreen()
end
ReleaseDialog()
end
end,
enabled = function()
local targetData = parametricDialog.entryList:GetTargetData()
local enabled = true
if targetData.finishedSelector then
enabled = self.noViolations
end
return enabled
end,
},
},
noChoiceCallback = function(dialog)
ReleaseDialog()
end,
})
end
function ZO_GuildRanks_Gamepad:InitializeRenameRankDialog()
local dialogName = GUILD_RENAME_RANK_GAMEPAD_DIALOG
local parametricDialog = ZO_GenericGamepadDialog_GetControl(GAMEPAD_DIALOGS.PARAMETRIC)
local function UpdateSelectedName(name)
if self.selectedName ~= name then
self.selectedName = name
self.noViolations = self.selectedName ~= "" and self.selectedName ~= nil
end
end
local function ReleaseDialog()
ZO_Dialogs_ReleaseDialogOnButtonPress(dialogName)
end
ZO_Dialogs_RegisterCustomDialog(dialogName,
{
gamepadInfo = {
dialogType = GAMEPAD_DIALOGS.PARAMETRIC,
},
setup = function(dialog)
self.noViolations = nil
self.selectedName = nil
UpdateSelectedName(self.selectedRank:GetName())
dialog:setupFunc()
end,
blockDialogReleaseOnPress = true, -- We'll handle Dialog Releases ourselves since we don't want DIALOG_PRIMARY to release the dialog on press.
title =
{
text = SI_GAMEPAD_GUILD_RANK_RENAME,
},
parametricList =
{
-- guild name edit box
{
template = "ZO_Gamepad_GenericDialog_Parametric_TextFieldItem",
templateData = {
nameField = true,
textChangedCallback = function(control)
local newName = control:GetText()
if self.selectedName ~= newName then
UpdateSelectedName(newName)
ZO_GenericParametricListGamepadDialogTemplate_RefreshVisibleEntries(parametricDialog)
end
end,
setup = function(control, data, selected, reselectingDuringRebuild, enabled, active)
control.highlight:SetHidden(not selected)
control.editBoxControl.textChangedCallback = data.textChangedCallback
if self.selectedName == "" then
ZO_EditDefaultText_Initialize(control.editBoxControl, GetString(SI_GAMEPAD_GUILD_RANK_DIALOG_DEFAULT_TEXT))
end
control.editBoxControl:SetMaxInputChars(MAX_GUILD_RANK_NAME_LENGTH)
control.editBoxControl:SetText(self.selectedName)
KEYBIND_STRIP:UpdateCurrentKeybindButtonGroups()
end,
},
},
-- confirm rename
{
template = "ZO_GamepadTextFieldSubmitItem",
templateData = {
finishedSelector = true,
text = GetString(SI_DIALOG_ACCEPT),
setup = SetupRequestEntry,
validInput = function()
return self.noViolations
end,
},
icon = ZO_GAMEPAD_SUBMIT_ENTRY_ICON,
},
},
buttons =
{
-- Cancel Button
{
keybind = "DIALOG_NEGATIVE",
text = GetString(SI_DIALOG_CANCEL),
callback = function()
ReleaseDialog()
end,
},
-- Select Button (used for entering name)
{
keybind = "DIALOG_PRIMARY",
text = GetString(SI_GAMEPAD_SELECT_OPTION),
callback = function(dialog)
local targetData = dialog.entryList:GetTargetData()
local targetControl = dialog.entryList:GetTargetControl()
if targetData.nameField and targetControl then
targetControl.editBoxControl:TakeFocus()
elseif targetData.finishedSelector then
if self.noViolations then
self.selectedRank:SetName(self.selectedName)
self:RefreshScreen()
end
ReleaseDialog()
end
end,
enabled = function()
local targetData = parametricDialog.entryList:GetTargetData()
local enabled = true
if targetData.finishedSelector then
enabled = self.noViolations
end
return enabled
end,
},
},
noChoiceCallback = function(dialog)
ReleaseDialog()
end,
})
end
local g_deleteRankOnFinished = false
function ZO_GuildRanks_Gamepad:InitializeDeleteRankDialog()
ZO_Dialogs_RegisterCustomDialog(GUILD_DELETE_RANK_GAMEPAD_DIALOG,
{
gamepadInfo = {
dialogType = GAMEPAD_DIALOGS.BASIC,
},
title =
{
text = function()
return zo_strformat(SI_GAMEPAD_GUILD_RANK_DELETE_TITLE, self.selectedRank:GetName())
end,
},
mainText =
{
text = function()
return zo_strformat(SI_GUILD_RANK_DELETE_WARNING, self.selectedRank:GetName())
end,
},
setup = function()
g_deleteRankOnFinished = false
end,
finishedCallback = function(dialog)
if g_deleteRankOnFinished then
self:DeleteSelectedRank()
end
end,
buttons =
{
{
keybind = "DIALOG_PRIMARY",
text = SI_GAMEPAD_DIALOG_YES_BUTTON,
callback = function()
g_deleteRankOnFinished = true
end,
},
{
keybind = "DIALOG_NEGATIVE",
text = SI_GAMEPAD_DIALOG_NO_BUTTON,
callback = function()
self:RefreshScreen()
end,
},
}
})
end
------------------
-- Screen Stats --
------------------
function ZO_GuildRanks_Gamepad:IsDisplayingRankList()
return self.listDisplayMode == LIST_DISPLAY_MODES.RANKS
end
function ZO_GuildRanks_Gamepad:IsDisplayingOptionsList()
return self.listDisplayMode == LIST_DISPLAY_MODES.OPTIONS
end
function ZO_GuildRanks_Gamepad:IsDisplayingRankIconPicker()
return self.listDisplayMode == LIST_DISPLAY_MODES.SELECT_ICON
end
function ZO_GuildRanks_Gamepad:IsDisplayingChangePermissions()
return self.listDisplayMode == LIST_DISPLAY_MODES.CHANGE_PERMISSIONS
end
-------------------------
-- Fragment Management --
-------------------------
function ZO_GuildRanks_Gamepad:RemoveUnusedFragments(fragmentBeingAdded)
local fragments =
{
GUILD_RANKS_PERMISSION_PANEL_FRAGMENT,
GUILD_RANK_ICON_PICKER_FRAGMENT,
}
for i, fragment in ipairs(fragments) do
if fragmentBeingAdded ~= fragment then
GAMEPAD_GUILD_HOME_SCENE:RemoveFragment(fragment)
end
end
end
function ZO_GuildRanks_Gamepad:ActivateFragment(fragment)
self:RemoveUnusedFragments(fragment)
GAMEPAD_GUILD_HOME_SCENE:AddFragment(fragment)
end
function ZO_GuildRanks_Gamepad:GetMessageText()
if self:IsEditingRank() then
return self.selectedRank:GetName()
end
return nil
end
function ZO_GuildRanks_Gamepad:IsEditingRank()
return not self:IsDisplayingRankList() and self.selectedRank ~= nil
end
------------------------
-- Change Permissions --
------------------------
function ZO_GuildRanks_Gamepad:SetChangePermissionsEnabled(state)
if self.changePermissionsEnabled ~= state then
if state then
self:DeactivateOptionsList()
self.permissionsGridList:Activate()
elseif self.changePermissionsEnabled then
self.permissionsGridList:Deactivate()
self:ActivateOptionsList()
end
self.changePermissionsEnabled = state
end
end
function ZO_GuildRanks_Gamepad:SetChangeRankIconPickerEnabled(state)
if self.changeRankIconPickerEnabled ~= state then
if state then
self:DeactivateOptionsList()
self.rankIconPicker:Activate()
elseif self.changeRankIconPickerEnabled then
self.rankIconPicker:Deactivate()
self:ActivateOptionsList()
end
self.changeRankIconPickerEnabled = state
end
end
------------------
-- Reorder Rank --
------------------
function ZO_GuildRanks_Gamepad:GetSelectedRankIndex()
return self:GetRankIndexById(self.selectedRank:GetRankId())
end
function ZO_GuildRanks_Gamepad:IsGuildMasterSelected()
if self.selectedRank ~= nil and self.selectedRank.index ~= nil then
return IsGuildRankGuildMaster(self.guildId, self.selectedRank.index)
end
return false
end
function ZO_GuildRanks_Gamepad:IsLastRankSelected()
return self:GetSelectedRankIndex() >= #self.ranks
end
function ZO_GuildRanks_Gamepad:InSecondRankSelected()
return self:GetSelectedRankIndex() <= GUILDMASTER_INDEX + 1
end
function ZO_GuildRanks_Gamepad:ReorderSelectedRank(up)
if self.selectedRank ~= nil then
local oldIndex = self:GetSelectedRankIndex()
local newIndex = oldIndex
if up then
newIndex = newIndex - 1
else
newIndex = newIndex + 1
end
newIndex = zo_clamp(newIndex, GUILDMASTER_INDEX + 1, #self.ranks)
if newIndex ~= oldIndex then
local tmp = self.ranks[oldIndex]
self.ranks[oldIndex] = self.ranks[newIndex]
self.ranks[newIndex] = tmp
PlaySound(SOUNDS.GUILD_RANK_REORDERED)
self:ActivateRankList(REFRESH_SCREEN)
self.rankList:SetSelectedIndexWithoutAnimation(newIndex)
end
end
end
------------------------
-- Delete Rank Dialog --
------------------------
function ZO_GuildRanks_Gamepad:DeleteSelectedRank()
local index = self:GetSelectedRankIndex()
table.remove(self.ranks, index)
self:ResetRankSelection()
PlaySound(SOUNDS.GUILD_RANK_DELETED)
self:ActivateRankList(REFRESH_SCREEN)
self.rankList:SetSelectedIndexWithoutAnimation(1)
end
--------------------
-- Key Bind Strip --
--------------------
function ZO_GuildRanks_Gamepad:InitializeKeybindStrip()
self.keybindStripDescriptor = {
alignment = KEYBIND_STRIP_ALIGN_LEFT,
-- select
{
name = function()
return GetString(SI_GAMEPAD_SELECT_OPTION)
end,
keybind = "UI_SHORTCUT_PRIMARY",
callback = function()
if self:IsDisplayingOptionsList() then
local selectedOptionsData = self.optionsList:GetTargetData()
if selectedOptionsData ~= nil and selectedOptionsData.callback ~= nil then
selectedOptionsData.callback()
end
elseif self:IsDisplayingRankList() then
local selectedRankData = self.rankList:GetTargetData()
if selectedRankData.addRank then
selectedRankData.callback()
else
PlaySound(SOUNDS.GAMEPAD_MENU_FORWARD)
self:ActivateOptionsList(REFRESH_SCREEN)
end
elseif self:IsDisplayingRankIconPicker() then
self.rankIconPicker:OnRankIconPickerSelectedGridListEntryClicked()
self:ActivateOptionsList(REFRESH_SCREEN)
elseif self:IsDisplayingChangePermissions() then
local selectedData = self.permissionsGridList:GetSelectedData()
if selectedData then
selectedData.dataEntry.control.object:OnCheckboxToggle()
end
end
end,
visible = function()
return DoesPlayerHaveGuildPermission(self.guildId, GUILD_PERMISSION_PERMISSION_EDIT) and #self.ranks > 0
end,
},
-- back
{
name = GetString(SI_GAMEPAD_BACK_OPTION),
keybind = "UI_SHORTCUT_NEGATIVE",
callback = function()
if self:IsDisplayingRankList() then
GAMEPAD_GUILD_HUB:SetEnterInSingleGuildList(true)
SCENE_MANAGER:Hide(GAMEPAD_GUILD_HOME_SCENE_NAME)
elseif self:IsDisplayingRankIconPicker() or self:IsDisplayingChangePermissions() then
if self:NeedsSave() then
PlaySound(SOUNDS.GUILD_RANK_SAVED)
self:Save()
end
self.permissionsGridList:Deactivate()
self.owningScreen:SetListsUseTriggerKeybinds(true)
self:ActivateOptionsList(REFRESH_SCREEN)
GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP)
PlaySound(SOUNDS.GAMEPAD_MENU_BACK)
else
PlaySound(SOUNDS.GAMEPAD_MENU_BACK)
self:ActivateRankList(REFRESH_SCREEN)
end
end,
},
}
end
-------------
-- Options --
-------------
do
local ICON_PERMISSIONS = "EsoUI/Art/Guild/Gamepad/gp_guild_options_permissions.dds"
local ICON_RENAME = "EsoUI/Art/Guild/Gamepad/gp_guild_options_rename.dds"
local ICON_DELETE = "EsoUI/Art/Guild/Gamepad/gp_guild_options_delete.dds"
local ICON_CHANGE_ICON = "EsoUI/Art/Guild/Gamepad/gp_guild_options_changeIcon.dds"
local ICON_REORDER_UP = "EsoUI/Art/Guild/Gamepad/gp_guild_options_reorder_up.dds"
local ICON_REORDER_DOWN = "EsoUI/Art/Guild/Gamepad/gp_guild_options_reorder_down.dds"
function ZO_GuildRanks_Gamepad:RefreshOptionsList()
if self.selectedRank ~= nil then
local isGuildmasterRankSelected = self:IsGuildMasterSelected()
self.optionsList:Clear()
local data = nil
local firstEntry = true
local function AddEntry(data)
data:SetIconTintOnSelection(true)
if firstEntry then
data:SetHeader(GetString(SI_GAMEPAD_GUILD_RANK_OPTIONS))
self.optionsList:AddEntryWithHeader(GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE, data)
firstEntry = false
else
self.optionsList:AddEntry(GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE, data)
end
end
local canChangePermissions = DoesPlayerHaveGuildPermission(self.guildId, GUILD_PERMISSION_PERMISSION_EDIT) and #self.ranks > 0 and (not self:IsGuildMasterSelected())
if canChangePermissions then
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_CHANGE_PERMISSIONS), ICON_PERMISSIONS)
data.callback = function()
PlaySound(SOUNDS.GAMEPAD_MENU_FORWARD)
self.listDisplayMode = LIST_DISPLAY_MODES.CHANGE_PERMISSIONS
self:RefreshScreen()
end
AddEntry(data)
end
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_RENAME_ENTRY), ICON_RENAME)
data.callback = function()
ZO_Dialogs_ShowGamepadDialog(GUILD_RENAME_RANK_GAMEPAD_DIALOG)
end
AddEntry(data)
if not isGuildmasterRankSelected then
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_DELETE_ENTRY), ICON_DELETE)
data.callback = function()
if self:IsRankOccupied(self.selectedRank) then
ZO_Dialogs_ShowGamepadDialog(GUILD_DELETE_RANK_GAMEPAD_WARNING_DIALOG, nil, { buttonKeybindOverrides = { "DIALOG_PRIMARY" }})
else
ZO_Dialogs_ShowGamepadDialog(GUILD_DELETE_RANK_GAMEPAD_DIALOG)
end
end
AddEntry(data)
end
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_CHANGE_ICON), ICON_CHANGE_ICON)
data.callback = function()
PlaySound(SOUNDS.GAMEPAD_MENU_FORWARD)
self.listDisplayMode = LIST_DISPLAY_MODES.SELECT_ICON
self:RefreshScreen()
end
AddEntry(data)
if not isGuildmasterRankSelected then
if not self:InSecondRankSelected() then
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_REORDER_UP), ICON_REORDER_UP)
data.unfadeRankList = true
data.callback = function()
self:ReorderSelectedRank(true)
end
AddEntry(data)
end
if not self:IsLastRankSelected() then
data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_REORDER_DOWN), ICON_REORDER_DOWN)
data.unfadeRankList= true
data.callback = function()
self:ReorderSelectedRank(false)
end
AddEntry(data)
end
end
self.optionsList:Commit()
end
end
end
---------------
-- Add Rank --
---------------
function ZO_GuildRanks_Gamepad:AddRank(rankName, copyPermissionsFromRankIndex)
local rank = ZO_GuildRank_Shared:New(GUILD_RANKS_GAMEPAD, self.guildId, nil, rankName)
local newRankIndex = self:InsertRank(rank, copyPermissionsFromRankIndex)
self:RefreshScreen()
self.rankList:SetSelectedIndexWithoutAnimation(newRankIndex)
end
---------------
-- Rank List --
---------------
function ZO_GuildRanks_Gamepad:OnTargetChanged(list, selectedData, oldSelectedData)
if selectedData ~= nil then
if selectedData.addRank then
self:RemoveUnusedFragments()
self.selectedRank = nil
elseif selectedData.rankObject ~= nil and self.selectedRank ~= selectedData.rankObject then
self.selectedRank = selectedData.rankObject
self:RefreshContent()
end
end
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
function ZO_GuildRanks_Gamepad:CancelDialog()
self:RefreshScreen()
end
function ZO_GuildRanks_Gamepad:PopulateRanks()
self:ResetRankSelection(false)
self.ranks = {}
if self.guildId then
for i = 1, GetNumGuildRanks(self.guildId) do
local rankObject = ZO_GuildRank_Shared:New(GUILD_RANKS_GAMEPAD, self.guildId, i)
self.ranks[i] = rankObject
end
end
end
function ZO_GuildRanks_Gamepad:RefreshRankList()
self.rankList:Clear()
local rankPermission = DoesPlayerHaveGuildPermission(self.guildId, GUILD_PERMISSION_PERMISSION_EDIT)
for i = 1, #self.ranks do
local rankObject = self.ranks[i]
local data = ZO_GamepadEntryData:New(rankObject:GetName(), rankObject:GetLargeIcon())
data:SetIconTintOnSelection(true)
data.rankObject = rankObject
if i == 1 then
local headerText = GetString(SI_WINDOW_TITLE_GUILD_RANKS)
if rankPermission then
headerText = GetString(SI_GAMEPAD_GUILD_RANK_EDIT)
end
data:SetHeader(headerText)
self.rankList:AddEntryWithHeader(GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE, data)
else
self.rankList:AddEntry(GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE, data)
end
end
local addRankEnabled = #self.ranks < MAX_GUILD_RANKS and rankPermission
if addRankEnabled then
local data = ZO_GamepadEntryData:New(GetString(SI_GAMEPAD_GUILD_RANK_ADD), "EsoUI/Art/Buttons/Gamepad/gp_plus_large.dds")
data:SetIconTintOnSelection(true)
data.addRank = true
data.callback = function()
ZO_Dialogs_ShowGamepadDialog(ADD_RANK_DIALOG_NAME)
end
data:SetHeader(GetString(SI_GAMEPAD_GUILD_RANK_NEW_HEADER))
self.rankList:AddEntryWithHeader(GAMEPAD_GUILD_RANKS_MENU_ENTRY_TEMPLATE, data)
end
self.rankList:Commit()
end
-- XML functions
----------------
function ZO_GuildRanks_Gamepad_Initialize(control)
GUILD_RANKS_GAMEPAD = ZO_GuildRanks_Gamepad:New(control)
end
|
MINIGAME.Time = 60
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Initialize()
self.players = {}
self.spawnPoints = {}
local spawnPoints = ents.FindByClass("info_player_spawn")
for k, entity in pairs(spawnPoints) do
if (entity.minigames) then
if (entity.team) then
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
self.spawnPoints.team = self.spawnPoints.team or {}
local teamID
if (entity.team == "blue") then
teamID = TEAM_BLUE
elseif (entity.team == "red") then
teamID = TEAM_RED
elseif (entity.team == "green") then
teamID = TEAM_GREEN
elseif (entity.team == "orange") then
teamID = TEAM_ORANGE
end
self.spawnPoints.team[teamID] = self.spawnPoints.team[teamID] or {}
table.insert(self.spawnPoints.team[teamID], entity)
end
end
else
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
table.insert(self.spawnPoints, entity)
end
end
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Start()
local String = self.Name.." - "..self.Description
for k, player in pairs(self.players) do
player:ChatPrint(String)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Finish(timeLimit)
local players = self:GetPlayers()
self.players = {}
for k, player in pairs(player.GetAll()) do
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
end
for k, player in pairs(players) do
self:RespawnPlayer(player)
end
if (!timeLimit) then
SS.Lobby.Minigame:FinishGame()
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RemovePlayer(player, noRespawn)
for k, v in pairs(self.players) do
if (v == player) then
self.players[k] = nil
v:SetNetworkedBool("ss.playingminigame", false)
v.minigame = nil
if (!noRespawn) then
self:RespawnPlayer(player)
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RespawnPlayer(player)
player.leavingMinigame = true
local spawnPoint = hook.Run("PlayerSelectSpawn", player)
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
player:Spawn()
player:SetPos(spawnPoint:GetPos())
player:SetEyeAngles(spawnPoint:GetAngles())
if (player:IsBot()) then
player:Freeze(true)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Think()
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:KeyPress(player, key)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:DoPlayerDeath(victim, inflictor, dmginfo)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSlap(player, target, nextSlap)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerSlap(player, target, nextSlap)
return nextSlap
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSuicide(player)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerLoadout(player)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerShouldTakeDamage(player, attacker)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasRequirements(players, teams)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetPlayers()
return self.players
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasPlayer(player)
local players = self:GetPlayers()
for k, v in pairs(players) do
if (v == player) then
return true
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetSpawnPoints(player)
if (self.spawnPoints.team) then
local teamID = player:Team()
return self.spawnPoints.team[teamID]
else
return self.spawnPoints
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:AnnounceWin(player)
if (IsValid(player)) then
local teamID = player:Team()
if (teamID > TEAM_READY) then
local nick = player:Nick()
local teamName = team.GetName(teamID)
SS.Lobby.Minigame:AddScore(teamID, 1)
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
else
local teams = {}
for k, player in pairs(self.players) do
if (IsValid(player)) then
local id = player:Team()
local exists = false
for i = 1, #teams do
if (teams[i].id == id) then
exists = true
break
end
end
if (!exists) then
table.insert(teams, {id = id, players = {}})
end
for i = 1, #teams do
if (teams[i].id == id) then
table.insert(teams[i].players, player)
end
end
end
end
if (#teams == 1) then
local players = teams[1].players
local teamName = team.GetName(teams[1].id)
if (#players > 1) then
util.PrintAll("[MINIGAME] The " .. teamName .. " team has won the game!")
else
local nick = players[1]:Nick()
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
SS.Lobby.Minigame:AddScore(teams[1].id, 1)
return true
end
return false
end
end
|
--[[---------------------------------------------------------
Name: Variables
-----------------------------------------------------------]]
local PANEL = {}
--[[---------------------------------------------------------
Name: Init
-----------------------------------------------------------]]
function PANEL:Init()
--> Variables
local GroupModerator = { "superadmin", "admin", "moderator" }
--> Menu - Size
local MenuWidth = ScrW() - 200
local MenuHeight = ScrH() - 200
if MenuWidth > 950 then MenuWidth = 950 end
--> Menu - Create
self:SetSize( MenuWidth, MenuHeight )
self:SetPos( ScrW()/2 - self:GetWide()/2, ScrH() )
self:MoveTo( ScrW()/2 - self:GetWide()/2, ScrH()/2 - self:GetTall()/2, 0.2, 0 )
--> Inside Box
self.InsideBox = vgui.Create( "DPanel", self )
self.InsideBox.Paint = function( pnl, w, h )
--> Background
draw.RoundedBox( 0, 0, 0, w, h, Color( 240, 240, 240, 255 ) )
end
--> Players Box
self.Players = vgui.Create( "FG-DScrollPanel", self.InsideBox )
self.Players:Dock( FILL )
--> Admin Box
self.Admins = vgui.Create( "DPanel", self.InsideBox )
self.Admins:Dock( BOTTOM )
self.Admins:SetHeight( 30 )
self.Admins:DockPadding( 4, 4, 4, 4 )
self.Admins.Paint = function( pnl, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 230, 230, 230, 255 ) )
draw.RoundedBox( 0, 0, 0, w, 1, Color( 215, 215, 215, 255 ) )
draw.DrawText( "Players: " .. #player.GetAll() .. "/" .. game.MaxPlayers() .. ". Map: " .. game.GetMap(), "FG_JaapokkiRegular_22", 6, 7, Color( 100, 100, 100, 255 ), 0, 1 )
end
self.AdminP = vgui.Create( "FG-DButton", self.Admins )
self.AdminP:Dock( RIGHT )
self.AdminP:SetWidth( 120 )
self.AdminP:SetText( "Admin Actions" )
self.AdminP.Toffset = 2
if table.HasValue( GroupModerator, LocalPlayer():GetNWString( "usergroup" ) ) then
self.AdminP.ButtonColor = Color( 52, 152, 219, 255 )
else
self.AdminP.ButtonColor = Color( 150, 150, 150, 255 )
end
self.AdminP.DoClick = function()
if table.HasValue( GroupModerator, LocalPlayer():GetNWString( "usergroup" ) ) then
AdminMenu = DermaMenu( self.AdminP )
AdminMenu.Think = function()
if not AdminMenu:GetParent():IsVisible() then
AdminMenu:Remove()
end
end
AdminMenu:AddOption( "Clear Decals", function() RunConsoleCommand( "_FAdmin", "ClearDecals" ) end ):SetIcon( "icon16/picture_delete.png" )
AdminMenu:AddOption( "Stop Sounds", function() RunConsoleCommand( "_FAdmin", "StopSounds" ) end ):SetIcon( "icon16/sound_delete.png" )
AdminMenu:AddSpacer()
AdminMenu:AddOption( "Disconnected Props", function() RunConsoleCommand( "FPP_Cleanup", "disconnected" ) end ):SetIcon( "icon16/box.png" )
AdminMenu:Open()
end
end
--> Header
self.Header = vgui.Create( "Panel", self )
self.Header:Dock( TOP )
self.Header:SetHeight( 40 )
--> Server Name
self.Name = self.Header:Add( "DLabel" )
self.Name:SetFont( "FG_JaapokkiRegular_32" )
self.Name:SetTextColor( Color( 255, 255, 255, 255 ) )
self.Name:Dock( TOP )
self.Name:SetHeight( 46 )
self.Name:SetContentAlignment( 5 )
self.Name:SetExpensiveShadow( 2, Color( 0, 0, 0, 200 ) )
end
--[[---------------------------------------------------------
Name: Paint
-----------------------------------------------------------]]
function PANEL:Paint( w, h )
--> Background
draw.RoundedBox( 0, 0, 0, w, h, Color( 240, 240, 240, 255 ) )
--> Title
draw.RoundedBox( 0, 0, 0, w, 40, Color( 40, 40, 50, 255 ) )
--> Inside Border
draw.RoundedBox( 0, 19, 40 + 19, w - 19 * 2, h - 40 - 19 * 2, Color( 215, 215, 215, 255 ) )
--> Inside Box
self.InsideBox:SetSize( w - 20 * 2, h - 40 - 20 * 2 )
self.InsideBox:SetPos( 20, 40 + 20 )
end
--[[---------------------------------------------------------
Name: Think
-----------------------------------------------------------]]
function PANEL:Think()
--> Variables
self.PlayerList = {}
--> Server Name
self.Name:SetText( GetHostName() )
--> Team Info
if !ValidPanel( self.TeamInfo ) then
--> Team Info
self.TeamInfo = self.Players:Add( "DPanel" )
self.TeamInfo:Dock( TOP )
self.TeamInfo:SetHeight( 30 )
self.TeamInfo:SetContentAlignment( 5 )
self.TeamInfo.Paint = function( pnl, w, h )
draw.RoundedBox( 0, 0, 0, w, h, Color( 240, 240, 240, 255 ) )
draw.RoundedBox( 0, 0, h-1, w, 1, Color( 200, 200, 200, 255 ) )
end
--> Information
local TeamAvatar = self.TeamInfo:Add( "DLabel" )
TeamAvatar:Dock( LEFT )
TeamAvatar:SetWidth( 42 )
TeamAvatar:SetFont( "FG_JaapokkiRegular_20" )
TeamAvatar:SetTextColor( Color( 100, 100, 100, 255 ) )
TeamAvatar:SetText( "-" )
TeamAvatar:SetContentAlignment( 5 )
local TeamName = self.TeamInfo:Add( "DLabel" )
TeamName:Dock( LEFT )
TeamName:SetFont( "FG_JaapokkiRegular_20" )
TeamName:SetTextColor( Color( 100, 100, 100, 255 ) )
TeamName:SetText( "Name" )
TeamName:SetContentAlignment( 5 )
local TeamPing = self.TeamInfo:Add( "DLabel" )
TeamPing:Dock( RIGHT )
TeamPing:SetWidth( 60 )
TeamPing:SetFont( "FG_JaapokkiRegular_20" )
TeamPing:SetTextColor( Color( 100, 100, 100, 255 ) )
TeamPing:SetText( "Ping" )
TeamPing:SetContentAlignment( 5 )
local TeamDeaths = self.TeamInfo:Add( "DLabel" )
TeamDeaths:Dock( RIGHT )
TeamDeaths:SetWidth( 60 )
TeamDeaths:SetFont( "FG_JaapokkiRegular_20" )
TeamDeaths:SetTextColor( Color( 100, 100, 100, 255 ) )
TeamDeaths:SetText( "Deaths" )
TeamDeaths:SetContentAlignment( 5 )
local TeamKills = self.TeamInfo:Add( "DLabel" )
TeamKills:Dock( RIGHT )
TeamKills:SetWidth( 60 )
TeamKills:SetFont( "FG_JaapokkiRegular_20" )
TeamKills:SetTextColor( Color( 100, 100, 100, 255 ) )
TeamKills:SetText( "Kills" )
TeamKills:SetContentAlignment( 5 )
end
--> Loop Players
for id, ply in pairs( player.GetAll() ) do
--> Check Player
if not IsValid( ply ) or not ply:IsPlayer() then return end
--> Check Entry
if IsValid( ply.ScoreEntry ) and ply.ScoreEntry.Team == ply:Team() then continue end
--> Team
if not self.PlayerList[ ply:Team() ] then
self.PlayerList[ ply:Team() ] = {}
end
--> Insert
table.insert( self.PlayerList[ ply:Team() ], ply )
end
--> Loop Teams
for id, job in pairs( self.PlayerList ) do
--> Team Display
local TeamPanel = self.Players:Add( "DPanel" )
TeamPanel:Dock( TOP )
TeamPanel:SetHeight( 30 )
TeamPanel.Think = function()
if team.GetPlayers( id ) == 0 then
TeamPanel:Remove()
end
end
TeamPanel.Paint = function( pnl, w, h )
draw.RoundedBox( 0, 0, 0, w, h, team.GetColor( id ) )
draw.DrawText( team.GetName( id ), "FG_JaapokkiRegular_22", 10, 6, Color( 255, 255, 255, 255 ) )
end
--> Players
for k,v in pairs( job ) do
--> Create
v.ScoreEntry = vgui.Create( "FG-Scoreboard-Player" )
v.ScoreEntry:Setup( v )
--> Add
self.Players:AddItem( v.ScoreEntry )
end
end
end
--[[---------------------------------------------------------
Name: DefineControl
-----------------------------------------------------------]]
derma.DefineControl( "FG-Scoreboard", "FG-Scoreboard", PANEL, "EditablePanel" )
|
local lang = {
common = {
welcome = "Bienvenue. Utilise les touches du téléphone pour les menus.~n~dernière connexion: {1}",
no_player_near = "~r~Pas de joueur à proximité.",
invalid_value = "~r~Valeur incorrecte.",
invalid_name = "~r~Nom incorrect.",
not_found = "~r~Non trouvé.",
request_refused = "~r~Requête refusée.",
wearing_uniform = "~r~Attention, vous portez un uniforme.",
not_allowed = "~r~Non autorisé."
},
weapon = {
pistol = "Pistolet"
},
survival = {
starving = "Affamé",
thirsty = "Assoiffé"
},
money = {
display = "{1} <span class=\"symbol\">$</span>",
given = "Vous avez donné ~r~{1}$.",
received = "Vous avez reçu ~g~{1}$.",
not_enough = "~r~Pas assez d'argent.",
paid = "Payé ~r~{1}$.",
give = {
title = "Donner de l'argent",
description = "Donner de l'argent au joueur le plus proche.",
prompt = "Montant à donner:"
}
},
inventory = {
title = "Inventaire",
description = "Ouvrir l'inventaire.",
iteminfo = "({1})<br /><br />{2}<br /><em>{3} kg</em>",
info_weight = "poids {1}/{2} kg",
give = {
title = "Donner",
description = "Donner un objet au joueur le plus proche.",
prompt = "Quantité à donner (max {1}):",
given = "Vous avez donné ~r~{1} ~s~{2}.",
received = "Vous avez reçu ~g~{1} ~s~{2}.",
},
trash = {
title = "Jeter",
description = "Jeter un objet.",
prompt = "Quantité à jeter (max {1}):",
done = "Jeté ~r~{1} ~s~{2}."
},
missing = "~r~Manque {2} {1}.",
full = "~r~Inventaire plein.",
chest = {
title = "Coffre",
already_opened = "~r~Ce coffre est déjà ouvert par quelqu'un d'autre.",
full = "~r~Coffre plein.",
take = {
title = "Prendre",
prompt = "Quantité à prendre (max {1}):"
},
put = {
title = "Mettre",
prompt = "Quantité à mettre (max {1}):"
}
}
},
atm = {
title = "Distributeur de billets",
info = {
title = "Info",
bank = "Banque: {1} $"
},
deposit = {
title = "Dépot",
description = "Déposez de l'argent sur votre compte",
prompt = "Entrez le montant à déposer:",
deposited = "Vous avez déposé ~r~{1}$~s~."
},
withdraw = {
title = "Retirer",
description = "Retirez de l'argent de votre compte",
prompt = "Entrez le montant à retirer:",
withdrawn = "Vous avez retiré ~g~{1}$ ~s~.",
not_enough = "~r~Vous n'avez pas assez d'argent sur votre compte."
}
},
business = {
title = "Chambre de commerce",
directory = {
title = "Annuaire",
description = "Annuaire des entreprises",
dprev = "> Précédent",
dnext = "> Suivant",
info = "<em>Capital: </em>{1} $<br /><em>Propriétaire: </em>{2} {3}<br /><em>Immatriculation: </em>{4}<br /><em>Téléphone: </em>{5}"
},
info = {
title = "Information sur l'entreprise",
info = "<em>Nom: </em>{1}<br /><em>Capital: </em>{2} $<br /><em>Capital de transfert: </em>{3} $<br /><br/>Le capital de transfert représente la quantité d'argent transférée pour une période. Le maximum ne peut pas dépasser le capital de l'entreprise."
},
addcapital = {
title = "Ajout de capital",
description = "Augmentez le capital de votre entreprise.",
prompt = "Montant à ajouter à votre capital:",
added = "~r~{1}$ ~s~ ajoutés au capital de votre entreprise."
},
launder = {
title = "Blanchiment d'argent",
description = "Utilisez votre entreprise pour blanchir de l'argent.",
prompt = "Montant d'argent sale à blanchir (max {1} $): ",
laundered = "~g~{1}$ ~s~ blanchis.",
not_enough = "~r~Pas assez d'argent sale."
},
open = {
title = "Ouvrir une entreprise",
description = "Ouvrez votre entreprise, le capital minimum est de {1} $.",
prompt_name = "Nom de l'entreprise (ne peut pas être modifié ultérieurement, maximum {1} chars):",
prompt_capital = "Capital initial (min {1})",
created = "~g~Entreprise créée."
}
},
cityhall = {
title = "Hôtel de ville",
identity = {
title = "Nouvelle identité",
description = "Creez une nouvelle identité, frais de création = {1} $.",
prompt_firstname = "Entrez votre prénom:",
prompt_name = "Entrez votre nom de famille:",
prompt_age = "Entrez votre âge:"
},
menu = {
title = "Identité",
info = "<em>Nom: </em>{1}<br /><em>Prénom: </em>{2}<br /><em>Age: </em>{3}<br /><em>N° d'immatriculation: </em>{4}<br /><em>Téléphone: </em>{5}<br /><em>Adresse: </em>{7}, {6}"
}
},
police = {
title = "Police",
wanted = "Recherché rang {1}",
not_handcuffed = "~r~Pas menotté.",
cloakroom = {
title = "Vestiaire",
uniform = {
title = "Uniforme",
description = "Mettre l'uniforme."
}
},
pc = {
title = "PC",
searchreg = {
title = "Recherche immatriculation",
description = "Recherche d'identité par immatriculation.",
prompt = "Entrez l'immatriculation:"
},
closebusiness = {
title = "Fermer l'entreprise",
description = "Fermer l'entreprise du joueur le plus proche",
request = "Êtes vous sûr de vouloir fermer l'entreprise {3} gérée par {1} {2} ?",
closed = "~g~Entreprise fermée."
},
trackveh = {
title = "Localisation de véhicule",
description = "Localisation de véhicule par immatriculation.",
prompt_reg = "Entrez l'immatriculation:",
prompt_note = "Entrez une note ou une raison:",
tracking = "~b~Localisation commencée.",
track_failed = "~b~Recherche de {1}~s~ ({2}) ~n~~r~Echouée.",
tracked = "{1} ({2}) localisé."
},
records = {
show = {
title = "Afficher casier",
description = "Afficher casier judiciaire par immatriculation."
},
delete = {
title = "Effacer casier",
description = "Effacer casier judiciaire par immatriculation",
deleted = "~b~Casier judiciaire effacé."
}
}
},
menu = {
handcuff = {
title = "Menotter",
description = "Menotter/démenotter le joueur le plus proche."
},
putinveh = {
title = "Mettre dans le véhicule",
description = "Mettre le joueur menotté le plus proche dans le véhicule le plus proche vous appartenant."
},
getoutveh = {
title = "Sortir du véhicule",
description = "Sortir du véhicule le joueur menotté le plus proche."
},
askid = {
title = "Demander les papiers",
description = "Demander les papiers d'identité du joueur le plus proche.",
request = "Voulez vous montrer vos papiers d'identité ?",
request_hide = "Fermer les informations d'identité.",
asked = "Demande des papiers..."
},
check = {
title = "Fouiller le joueur",
description = "Fouiller l'argent, les objets et les armes du joueur le plus proche.",
request_hide = "Fermer le rapport de fouille.",
info = "<em>Argent: </em>{1} $<br /><br /><em>Inventaire: </em>{2}<br /><br /><em>Armes: </em>{3}",
checked = "Vous avez été fouillé."
},
seize = {
seized = "Saisis {2} ~r~{1}",
weapons = {
title = "Saisir armes",
description = "Saisir les armes du joueur à proximité.",
seized = "~b~Vos armes ont été saisies."
},
items = {
title = "Saisir illégaux",
description = "Saisir les objets illégaux.",
seized = "~b~Vos objets illégaux ont été saisis."
}
},
jail = {
title = "Prison",
description = "Mettre en prison/libérer le joueur le plus proche dans la prison la plus proche.",
not_found = "~r~Pas de prison trouvée.",
jailed = "~b~Emprisonné.",
unjailed = "~b~Libéré.",
notify_jailed = "~b~Vous avez été emprisonné.",
notify_unjailed = "~b~Vous avez été libéré."
},
fine = {
title = "Amende",
description = "Mettre une amende au joueur le plus proche.",
fined = "~b~Vous avez mis une amende de ~s~{2} $ pour ~b~{1}.",
notify_fined = "~b~Vous avez été condamné à une amende de~s~ {2} $ pour~b~ {1}.",
record = "[Amende] {2} $ pour {1}"
},
store_weapons = {
title = "Ranger ses armes",
description = "Ranger ses armes dans son inventaire."
}
},
identity = {
info = "<em>Nom: </em>{1}<br /><em>Prénom: </em>{2}<br /><em>Age: </em>{3}<br /><em>N° d'immatriculation: </em>{4}<br /><em>Téléphone: </em>{5}<br /><em>Entreprise: </em>{6}<br /><em>Capital de l'entreprise: </em>{7} $<br /><em>Adresse: </em>{9}, {8}"
}
},
emergency = {
menu = {
revive = {
title = "Réanimer",
description = "Réanimer le joueur le plus proche.",
not_in_coma = "~r~Le joueur n'est pas dans le coma."
}
}
},
phone = {
title = "Téléphone",
directory = {
title = "Répertoire",
description = "Ouvrir le Répertoire.",
add = {
title = "> Ajouter",
prompt_number = " Entrez le n° de téléphone à ajouter:",
prompt_name = "Entrez un nom associé au n° de téléphone:",
added = "~g~N° de téléphone ajouté."
},
sendsms = {
title = "Envoyer un SMS",
prompt = " Entrez le message à envoyer (max {1} chars):",
sent = "~g~ Envoyé au n°{1}.",
not_sent = "~r~ n°{1} non disponible."
},
sendpos = {
title = "Envoi de la position",
},
remove = {
title = "Supprimer"
}
},
sms = {
title = "Historique des SMS",
description = "Historique des SMS reçus.",
info = "<em>{1}</em><br /><br />{2}",
notify = "SMS~b~ {1}:~s~ ~n~{2}"
},
smspos = {
notify = "SMS-Position ~b~ {1}"
},
service = {
title = "Service",
description = "Appelez un service ou un n° d'urgence.",
prompt = "Si besoin, entrez un message pour le service:",
ask_call = "Reception d'un appel ({1}), voulez vous le prendre ? <em>{2}</em>",
taken = "~r~Cet appel est déjà pris."
},
announce = {
title = "Annonce",
description = "Envoyer une annonce visible à tous pendant quelques secondes.",
item_desc = "{1} $<br /><br/>{2}",
prompt = "Contenu de l'annonce (10-1000 caractères): "
}
},
emotes = {
title = "Emotes",
clear = {
title = "> Arrêter",
description = "Arrête toutes les emotes en cours."
}
},
home = {
buy = {
title = "Acheter",
description = "Acheter un logement ici, le prix est {1} $.",
bought = "~g~Acheté.",
full = "~r~Plus de place.",
have_home = "~r~Vous avez déjà un logement."
},
sell = {
title = "Vendre",
description = "Vendre son logement pour {1} $",
sold = "~g~vendu.",
no_home = "~r~Vous n'avez pas de logement ici."
},
intercom = {
title = "Interphone",
description = "Utiliser l'interphone pour entrer dans un logement.",
prompt = "Numéro:",
not_available = "~r~Indisponible.",
refused = "~r~Entrée refusée.",
prompt_who = "Dites qui vous êtes:",
asked = "Demande...",
request = "Quelqu'un veut rentrer dans votre logement: <em>{1}</em>"
},
slot = {
leave = {
title = "Sortir"
},
ejectall = {
title = "Expulser",
description = "Expulse tous les visiteurs, même vous, et ferme le logement."
}
},
wardrobe = {
title = "Garde-robe",
save = {
title = "> Sauvegarder",
prompt = "Nom de la sauvegarde:"
}
},
gametable = {
title = "Table de jeux",
bet = {
title = "Commencer un pari",
description = "Commencer un pari avec les joueurs à proximité, le gagnant sera choisis aléatoirement.",
prompt = "Mise du pari:",
request = "[PARI] Voulez vous parier {1} $ ?",
started = "~g~Pari commencé."
}
}
},
garage = {
title = "Garage ({1})",
owned = {
title = "Mes véhicules",
description = "Véhicules m'appartenant"
},
buy = {
title = "Acheter",
description = "Acheter des véhicules.",
info = "{1} $<br /><br />{2}"
},
sell = {
title = "Vendre",
description = "Vendre des véhicules."
},
rent = {
title = "Location",
description = "Louer un véhicule pour la session (jusqu'à déconnexion)."
},
store = {
title = "Rentrer au garage",
description = "Rentrez votre véhicule au garage."
}
},
vehicle = {
title = "Véhicule",
no_owned_near = "~r~Pas de véhicule vous appartenant à proximité.",
trunk = {
title = "Coffre",
description = "Ouvrir le coffre du véhicule."
},
detach_trailer = {
title = "Détacher remorque",
description = "Détacher la remorque."
},
detach_towtruck = {
title = "Détacher dépanneuse",
description = "Détacher le lien de la dépanneuse."
},
detach_cargobob = {
title = "Détacher cargobob",
description = "Détacher le lien de l'hélico de transport."
},
lock = {
title = "Fermer/ouvrir",
description = "Fermer ou ouvrir le véhicule."
},
engine = {
title = "Moteur on/off",
description = "Démarrer ou arrêter le moteur."
},
asktrunk = {
title = "Demander ouvrir coffre",
asked = "~g~Demande...",
request = "Voulez vous ouvrir le coffre ?"
},
replace = {
title = "Replacer véhicule",
description = "Replacer sur le sol le véhicule le plus proche."
},
repair = {
title = "Réparer véhicule",
description = "Réparer le véhicule le plus proche."
}
},
gunshop = {
title = "Magasin d'armes ({1})",
prompt_ammo = "Quantité de munition à acheter pour {1}:",
info = "<em>Arme: </em> {1} $<br /><em>Munition: </em> {2} $/u<br /><br />{3}"
},
market = {
title = "Supérette ({1})",
prompt = "Quantité de {1} à acheter:",
info = "{1} $<br /><br />{2}"
},
skinshop = {
title = "Magasin de vêtements"
},
cloakroom = {
title = "Vestiaire ({1})",
undress = {
title = "> Enlever"
}
},
itemtr = {
informer = {
title = "Informateur illégal",
description = "{1} $",
bought = "~g~Position envoyée au GPS."
}
},
mission = {
blip = "Mission ({1}) {2}/{3}",
display = "<span class=\"name\">{1}</span> <span class=\"step\">{2}/{3}</span><br /><br />{4}",
cancel = {
title = "Abandonner la mission"
}
},
aptitude = {
title = "Compétences",
description = "Afficher les compétences.",
lose_exp = "Compétence ~b~{1}/{2} ~r~-{3} ~s~exp.",
earn_exp = "Compétence ~b~{1}/{2} ~g~+{3} ~s~exp.",
level_down = "Compétence ~b~{1}/{2} ~r~descend en niveau ({3}).",
level_up = "Compétence ~b~{1}/{2} ~g~monte en niveau ({3}).",
display = {
group = "{1}: ",
aptitude = "--- {1} | exp {2} | niv. {3} | progression {4}%"
}
}
}
return lang
|
-- alnbox, alignment viewer based on the curses library
-- Copyright (C) 2015 Boris Nagaev
-- See the LICENSE file for terms of use
return function(foreground, background)
return background * 8 + 7 - foreground
end
|
local Player = Rect:extend()
local function setPointsOnGround(self, shapeList)
for i = 1, #self.points do
self.points[i].isOnGround = self:isPointOnGroundWithShapeList(i, shapeList)
end
end
local function setSfx(self)
for i = 1, #self.points do
if self:isPointOnGround(i) then
if not self.points[i].isSfxPlayed then
love.audio.play(SFX_TOUCH_GOUND)
self.points[i].isSfxPlayed = true
end
else
self.points[i].isSfxPlayed = false
end
end
end
function Player:new(position)
local len = Base.player.len
local colorFill = Base.cloneTable(Base.color.gray)
colorFill[4] = 0.5
local colorMesh = {0, 0, 0, 0}
Player.super.new(self, position, len, len, 0, colorFill, Base.color.line, colorMesh)
self.stuck = false
self.spdX = 0
self.spdY = 0
self.points = {
{isOnGround = false, isSfxPlayed = true},
{isOnGround = false, isSfxPlayed = true}
}
end
function Player:update(dt, mode, shapeList)
if mode == 0 then
-- move
self:moveXY()
self:setCollisionXY(dt, shapeList)
-- update position
self.position.x = self.position.x + self.spdX * dt
self.position.y = self.position.y + self.spdY * dt
elseif mode == 1 then
setPointsOnGround(self, shapeList)
self:collisionXZ(dt)-- move
setSfx(self)
end
end
function Player:draw(mode)
Player.super.draw(self, mode)
-- draw points
if mode == 1 then
for i = 1, #self.points do
local radius = 3
local cPoint = Base.ternary(self:isPointOnGround(i), Base.color.white, Base.color.darkGray)
love.graphics.setColor(cPoint)
love.graphics.circle('fill', self:getPointX(i), self:getPointZ(i), radius)
end
end
end
--- why name so long: lua don't have overloaded
---@param index number
---@param shapeList table
---@return boolean
function Player:isPointOnGroundWithShapeList(index, shapeList)
local flag = false
local x = self:getPointX(index)
local z = self:getPointZ(index)
for key, shape in pairs(shapeList) do
if shape:is(Rect) or shape:is(Cuboid) or shape:is(Ball) then
flag = shape:isCollisionPointInXZ(x, z)
if flag then
break
end
end
end
return flag
end
---@param index number
---@return boolean
function Player:isPointOnGround(index)
return self.points[index].isOnGround
end
---@return boolean
function Player:isOnGround()
return self:isPointOnGround(1) and self:isPointOnGround(2)
end
function Player:moveXY()
if Base.isDown(Base.keys.left) then
self.spdX = -Base.player.spdXY
elseif Base.isDown(Base.keys.right) then
self.spdX = Base.player.spdXY
else
self.spdX = 0
end
if Base.isDown(Base.keys.up) then
self.spdY = -Base.player.spdXY
elseif Base.isDown(Base.keys.down) then
self.spdY = Base.player.spdXY
else
self.spdY = 0
end
-- 45 degree
if self.spdX ~= 0 and self.spdY ~= 0 then
local spd45 = Base.player.spdXY / math.sqrt(2)
self.spdX = spd45 * Base.sign(self.spdX)
self.spdY = spd45 * Base.sign(self.spdY)
end
end
function Player:moveXZ(dt)
local spdXZ
if Base.isDown(Base.keys.left) then
spdXZ = -Base.player.spdXZ
elseif Base.isDown(Base.keys.right) then
spdXZ = Base.player.spdXZ
else
spdXZ = 0
end
self.radian = self.radian + spdXZ * dt
end
---@param dt number
---@param shapeList table
function Player:setCollisionXY(dt, shapeList)
self.stuck = false
local left = self:getPointX(self:getPointIndex('left'))
local right = self:getPointX(self:getPointIndex('right'))
local top = self.position.y
local bottom = self.position.y + self.lenY
local centerX = (left + right) / 2
local centerY = (top + bottom) / 2
for key, obj in pairs(shapeList) do
if not (obj:is(Rect) or obj:is(Cuboid)) then
goto continue
end
local oLeft, oRight
if obj:is(Rect) then
oLeft = obj:getPointX(obj:getPointIndex('left'))
oRight = obj:getPointX(obj:getPointIndex('right'))
else
oLeft = obj.position.x
oRight = obj.position.x + obj.lenX
end
local oTop = obj.position.y
local oBottom = obj.position.y + obj.lenY
if bottom > oTop and top < oBottom then
-- check how far between x and the line
for key2, xValue in pairs({oLeft, oRight}) do
local disX = math.abs(centerX - xValue)
local signX = Base.sign(centerX - xValue)
local disMin = math.abs(self:getVectorX() / 2)
-- stuck
if disMin - disX > 1 then
self.stuck = true
self.spdY = 0
self.spdX = 0
-- push
elseif math.abs(disX * signX + self.spdX * dt) < disMin then
self.position.x = xValue + disMin * signX - self:getVectorX() / 2
self.spdX = 0
break
end
end
end
-- y
if right > oLeft and left < oRight then
-- check how far between y and the line
for key2, yValue in pairs({oTop, oBottom}) do
local disY = math.abs(centerY - yValue)
local signY = Base.sign(centerY - yValue)
local disMin = self.lenY / 2
-- stuck
if disMin - disY > 1 then
self.stuck = true
self.spdY = 0
self.spdX = 0
-- push
elseif math.abs(disY * signY + self.spdY * dt) < disMin then
self.position.y = yValue + disMin * signY - disMin
self.spdY = 0
break
end
end
end
::continue::
end
end
---@param obj Shape
---@return boolean
function Player:isCollisionObjInXY(obj)
local flag = false
if not (obj:is(Rect) or obj:is(Cuboid)) then
return flag
end
local left = self:getPointX(self:getPointIndex('left'))
local right = self:getPointX(self:getPointIndex('right'))
local top = self.position.y
local bottom = self.position.y + self.lenY
local oLeft, oRight
if obj:is(Rect) then
oLeft = obj:getPointX(obj:getPointIndex('left'))
oRight = obj:getPointX(obj:getPointIndex('right'))
else
oLeft = obj.position.x
oRight = obj.position.x + obj.lenX
end
local oTop = obj.position.y
local oBottom = obj.position.y + obj.lenY
if left <= oRight and right >= oLeft and
top <= oBottom and bottom >= oTop then
flag = true
end
return flag
end
---@param obj Shape
---@param mode number
---@return boolean
function Player:isTouch(obj, mode)
local flag = false
if mode == 0 then
if self:isCollisionObjInXY(obj) then
flag = true
end
elseif mode == 1 then
for i = 1, #self.points do
if self:isPointOnGroundWithShapeList(i, {obj}) then
flag = true
break
end
end
end
return flag
end
local function swapPoints(self)
self.position.x = self:getPointX(2)
self.position.z = self:getPointZ(2)
self.radian = self.radian - math.pi
end
---@param dt number
function Player:collisionXZ(dt)
-- both not on ground
if not (self:isPointOnGround(1) or self:isPointOnGround(2)) then
-- garvity
self.position.z = self.position.z + Base.garvity * dt
else
-- make sure point1 is the main point
-- both side on ground
if self:isPointOnGround(1) and self:isPointOnGround(2) then
if (Base.isDown(Base.keys.left) and self.position.x ~= self:getPointX(self:getPointIndex('left')))
or (Base.isDown(Base.keys.right) and self.position.x ~= self:getPointX(self:getPointIndex('right'))) then
swapPoints(self)
end
-- one side on ground
else
if not self:isPointOnGround(1) then
swapPoints(self)
end
-- garvity
if not ( Base.isDown(Base.keys.left) or Base.isDown(Base.keys.right) ) then
local spdG
if self:getPointIndex('left') == 1 then
spdG = Base.player.spdXZ
else
spdG = -Base.player.spdXZ
end
-- fix shaking when radian = pi/2 or -3/2*pi (point down)
local positiveRadian = self.radian
if positiveRadian < 0 then
positiveRadian = positiveRadian + math.pi * 2
end
if positiveRadian ~= math.pi/2 then
local addRadtian = spdG * dt
local absRadtianBetween = math.abs(math.pi/2 - positiveRadian)
if absRadtianBetween < math.abs(spdG * dt) then
addRadtian = absRadtianBetween * Base.sign(spdG)
end
self.radian = self.radian + addRadtian
end
end
end
-- control radian
self:moveXZ(dt)
-- limit radian
if self.radian <= -math.pi * 2 then
self.radian = self.radian + math.pi * 2
elseif self.radian >= math.pi * 2 then
self.radian = self.radian - math.pi * 2
end
end
end
return Player
|
-- erhalte die letzte Summe
local sum = Command:getData()
-- Wenn bisher keine daten gesetzt sind, setze sie auf 0
if not tonumber(sum) then
sum = 0
end
-- Erhöhe die Summe im 1
sum = sum + 1
-- speichere Summe
Command:setData(sum)
-- Gebe die Summe aus
Chat:output("Der Befehl wurde " .. sum .. " mal ausgeführt")
|
---
-- @classmod StatsStorage
local middleclass = require("middleclass")
local flatdb = require("flatdb")
local types = require("luaplot.types")
local Stats = require("models.stats")
local StatsStorage = middleclass("StatsStorage")
---
-- @table instance
-- @tfield FlatDB _db
---
-- @function new
-- @tparam string path
-- @treturn StatsStorage
function StatsStorage:initialize(path)
assert(type(path) == "string")
self._db = flatdb(path)
if not self._db.stats then
self._db.stats = {
normal_time = 0,
soft_limit_time = 0,
hard_limit_time = 0,
}
end
end
---
-- @treturn Stats
function StatsStorage:get_stats()
return Stats:new(
self._db.stats.normal_time,
self._db.stats.soft_limit_time,
self._db.stats.hard_limit_time
)
end
---
-- @tparam Stats stats
function StatsStorage:store_stats(stats)
assert(types.is_instance(stats, Stats))
self._db.stats = {
normal_time = stats.normal_time,
soft_limit_time = stats.soft_limit_time,
hard_limit_time = stats.hard_limit_time,
}
self._db:save()
end
return StatsStorage
|
-- A few constants
OSROOT = "/PaulCC"
-- Let's wrap the APIs needed
-- (Note: certain APIs need to remain alive)
-- I cannot disable coroutines, as they are heavily used. Maybe disable the commands except yield in the user processes?
-- os.pullEventRaw is required to be wrapped; maybe os.pullEvent too.
-- We should handle disks too; mounting disks would be nice after all, but this means peripherals have to be wrapped too
-- Raw disk access is alright; we just need to wrap the file system
-- disk.isPresent is safe
-- disk.hasData is safe
rawdisk_getmountpath = disk.getMountPath
function disk_getMountPathReal(side)
return disk.isPresent(side) and "mnt/" .. rawdisk_getmountpath(side) or nil
end
-- disk.setLabel is safe
-- disk.getID is safe
-- disk.hasAudio is safe
-- disk.getAudioTitle is safe
-- disk.playAudio is safe
-- disk.stopAudio is safe
-- disk.eject is safe
-- Wrapping the FS (note: absolute paths!)
mtabl = {}
rawfs_getdrive = fs.getDrive
rawfs_exists = fs.exists
rawfs_isdir = fs.isDir
rawfs_isreadonly = fs.isReadOnly
rawfs_list = fs.list
rawfs_getsize = fs.getSize
rawfs_getfreespace = fs.getFreeSpace
rawfs_makedir = fs.makeDir
rawfs_mode = fs.move
rawfs_copy = fs.copy
rawfs_delete = fs.delete
rawfs_open = fs.open
rawfs_find = fs.find -- for some reason it works separately
-- Find all mounted disks
for n, item in pairs(fs.list("")) do
if (rawfs_getdrive(item) ~= "hdd") and (rawfs_getdrive(item) ~= "rom") then
mtabl[rawfs_getdrive(item)] = item
end
end
function resolve_path(
function isdisk(path)
local realpath = path
if string.sub(path, 1, 1) == "/" then realpath = string.sub(path, 2) end
realpath = string.sub(realpath, 1, string.find(realpath, "/"))
return realpath == "mnt"
end
rawfs_list = fs.list
function disklist(path)
local realpath = path
if string.sub(path, 1, 1) == "/" then realpath = string.sub(path, 2) end
if realpath == "mnt" then
local result = {}
for index, _ in pairs(mtabl) do
result[#result+1] = index
end
return result
end
if not isdisk(path) return nil
realpath = string.sub(realpath, 5)
disk = string.sub(realpath, 1, string.find(realpath, "/")-1) or disk
if mtabl[disk] == nil then return nil end
end
function fs_listReal(path)
return disklist(path) or rawfs_list(fs.combine(OSROOT, path))
end
rawfs_exists = fs.exists
function diskexists(path)
if not isdisk(path) then return false end
if string.sub(path, 1, 1) == "/" then path = string.sub(path, 2) end
if path == "mnt" then return true end
path = string.sub(path, 5)
disk = string.sub(path, 1, string.find(path, "/")-1)
if mtabl[disk] == nil then return false end
return rawfs_exists(fs.combine(mtabl[disk], path))
end
function fs_existsReal(path)
if isdisk(path) then return diskexists(path) else
return rawfs_exists(fs.combine(OSROOT, path)) end
end
function fs_getDriveReal(path)
local realpath = path
if string.sub(path, 1, 1) == "/" then realpath = string.sub(path, 2) end
if string.sub(realpath, 1, string.find(realpath, "/")-1) == "rom" then return "rom" end
if string.sub(realpath, 1, string.find(realpath, "/")-1) ~= "mnt" then return "hdd" end
local disk = string.sub(realpath, 1, string.find(realpath, "/")-1)
return mtabl[disk] ~= nil and disk or nil
end
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "vaults_beta",
primary_key = { "id" },
cache_key = { "prefix" },
endpoint_key = "prefix",
workspaceable = true,
subschema_key = "name",
subschema_error = "vault '%s' is not installed",
admin_api_name = "vaults-beta",
dao = "kong.db.dao.vaults",
fields = {
{ id = typedefs.uuid },
-- note: prefix must be valid in a host part of vault reference uri:
-- {vault://<vault-prefix>/<secret-id>[/<secret-key]}
{ prefix = { type = "string", required = true, unique = true, unique_across_ws = true,
match = [[^[a-z][a-z%d-]-[a-z%d]+$]] }},
{ name = { type = "string", required = true }},
{ description = { type = "string" }},
{ config = { type = "record", abstract = true }},
{ created_at = typedefs.auto_timestamp_s },
{ updated_at = typedefs.auto_timestamp_s },
{ tags = typedefs.tags },
},
}
|
-- protocol naming
p4_lr_msg_type = Proto('p4_lr_msg_type','P4_LR_MSG_TYPEProtocol')
-- protocol fields
local p4_lr_msg_type_msg_type = ProtoField.string('p4_lr_msg_type.msg_type','msg_type')
p4_lr_msg_type.fields = {p4_lr_msg_type_msg_type}
-- protocol dissector function
function p4_lr_msg_type.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = 'P4_LR_MSG_TYPE'
local subtree = tree:add(p4_lr_msg_type,buffer(),'P4_LR_MSG_TYPE Protocol Data')
subtree:add(p4_lr_msg_type_msg_type,tostring(buffer(0,1):bitfield(0,8)))
local mydissectortable = DissectorTable.get('p4_lr_msg_type.msg_type')
mydissectortable:try(buffer(0,1):bitfield(0,8), buffer:range(1):tvb(),pinfo,tree)
end
print( (require 'debug').getinfo(1).source )
-- creation of table for next layer(if required)
local newdissectortable = DissectorTable.new('p4_lr_msg_type.msg_type','P4_LR_MSG_TYPE.MSG_TYPE',ftypes.STRING)
-- protocol registration
my_table = DissectorTable.get('p4_udp.dstPort')
my_table:add(0x04d2,p4_lr_msg_type)
|
-- Copyright (C) Miracle
-- Copyright (C) OpenWAF
local _M = {
_VERSION = "1.0.0"
}
local twaf_func = require "lib.twaf.inc.twaf_func"
local arr_index = "arr_tonumber"
_M.api = {}
_M.help = {}
_M.api.config = {}
-- get config, e.g: GET /api/config/{policy}/{module}/{key}
_M.api.config.get = function(_twaf, log, u)
local i = 2
local v = _twaf.config
repeat
local str = u[i]
if not str then
break
end
if type(v) ~= "table" then
log.success = 0
log.reason = "the value of "..u[i-1].." is not a table"
return
end
local from, to, err = str:find(arr_index)
if from and to then
local t = next(v)
if t and t~= 1 then
log.success = 0
log.reason = "the value of "..u[i-1].."is not a array"
return
end
local max_len = #v -- post + 1
str = tonumber(str:sub(to+1))
if type(str) ~= "number" then
log.success = 0
log.reason = "the value of "..arr_index.." must be a number"
return
end
if str == 0 then
log.success = 0
log.reason = "the value of "..arr_index.." can't be '0'"
return
end
if str > max_len then
log.success = 0
log.reason = "the value of "..arr_index.." can't be greater than "..max_len
return
end
end
v = v[str]
if v == nil then v = "nil" end
i = i + 1
until false
log.result = v
end
-- post config, e.g: POST /api/config/{policy}/{module}/{key}
_M.api.config.post = function(_twaf, log, u)
local i = 2
local v = _twaf.config
local data = twaf_func.api_check_json_body(log)
if not data then
return
end
repeat
local str1 = u[i]
local str2 = u[i+1]
if not str1 then
break
end
if type(v) ~= "table" then
log.success = 0
log.reason = "the value of "..u[i-1].." is not a table"
return
end
local from, to, err = str1:find(arr_index)
if from and to then
local t = next(v)
if t and t~= 1 then
log.success = 0
log.reason = "the value of "..u[i-1].."is not a array"
return
end
local max_len = #v + 1
if to == #str1 then
str1 = max_len
else
str1 = tonumber(str1:sub(to+1))
end
if type(str1) ~= "number" then
log.success = 0
log.reason = "the value of "..arr_index.." must be a number"
return
end
if str1 == 0 then
log.success = 0
log.reason = "the value of "..arr_index.." can't be '0'"
return
end
if str1 > max_len then
log.success = 0
log.reason = "the value of "..arr_index.." can't be greater than "..max_len
return
end
if not str2 then
log.result = data.config
table.insert(v, str1, data.config)
break
end
end
if not str2 then
log.result = data.config
v[str1] = data.config
break
end
v = v[str1]
i = i + 1
until false
end
-- update config, e.g: PUT /api/config/{policy}/{module}/{key}
_M.api.config.put = function(_twaf, log, u)
local i = 2
local v = _twaf.config
local data = twaf_func.api_check_json_body(log)
if not data then
return
end
repeat
local str1 = u[i]
local str2 = u[i+1]
if not str1 then
break
end
if type(v) ~= "table" then
log.success = 0
log.reason = "the value of "..u[i-1].." is not a table"
return
end
local from, to, err = str1:find(arr_index)
if from and to then
local t = next(v)
if t and t~= 1 then
log.success = 0
log.reason = "the value of "..u[i-1].."is not a array"
return
end
local max_len = #v + 1
if to == #str1 then
str1 = max_len
else
str1 = tonumber(str1:sub(to+1))
end
if type(str1) ~= "number" then
log.success = 0
log.reason = "the value of "..arr_index.." must be a number"
return
end
if str1 == 0 then
log.success = 0
log.reason = "the value of "..arr_index.." can't be '0'"
return
end
if str1 > max_len then
log.success = 0
log.reason = "the value of "..arr_index.." can't be greater than "..max_len
return
end
end
if not str2 then
log.result = data.config
v[str1] = data.config
break
end
v = v[str1]
i = i + 1
until false
end
-- delete config, e.g: DELETE /api/config/{policy}/{module}/{key}
_M.api.config.delete = function(_twaf, log, u)
local i = 2
local v = _twaf.config
repeat
local str1 = u[i]
local str2 = u[i+1]
if not str1 then
ngx.log(ngx.ERR, "break: ", i)
break
end
if type(v) ~= "table" then
log.success = 0
log.reason = "the value of "..u[i-1].." is not a table"
return
end
local from, to, err = str1:find(arr_index)
if from and to then
local t = next(v)
if t and t~= 1 then
log.success = 0
log.reason = "the value of "..u[i-1].."is not a array"
return
end
local max_len = #v
str1 = tonumber(str1:sub(to+1))
if type(str1) ~= "number" then
log.success = 0
log.reason = "the value of "..arr_index.." must be a number"
return
end
if str1 == 0 then
log.success = 0
log.reason = "the value of "..arr_index.." can't be '0'"
return
end
if str1 > max_len then
log.success = 0
log.reason = "the value of "..arr_index.." can't be greater than "..max_len
return
end
if not str2 then
log.result = v[str1]
table.remove(v, str1)
break
end
end
if not str2 then
if v[str1] == nil then
log.success = 0
log.reason = "Can't find '"..str1.."'"
return
end
log.result = v[str1]
v[str1] = nil
break
end
v = v[str1]
i = i + 1
until false
end
_M.help.config = {
"GET /api/config/{policy}/{module}/{key}",
"POST /api/config/{policy}/{module}/{key}",
"PUT /api/config/{policy}/{module}/{key}",
"DELETE /api/config/{policy}/{module}/{key}"
}
return _M
|
deathspeaker_xunra_rune_of_roots_penalty_modifier = class({})
function deathspeaker_xunra_rune_of_roots_penalty_modifier:OnCreated( kv )
self.roots_move_speed_percentage = self:GetAbility():GetSpecialValueFor("roots_move_speed_percentage")
self.roots_damage = self:GetAbility():GetSpecialValueFor("roots_damage")
self.roots_duration = self:GetAbility():GetSpecialValueFor("roots_duration")
if not IsServer() then return end
local victim = self:GetParent()
self.oldPos = victim:GetAbsOrigin()
self.interval = 0.5
self:StartIntervalThink( self.interval )
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_TOOLTIP,
}
return funcs
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:OnIntervalThink()
if not IsServer() then return end
local caster = self:GetCaster()
local victim = self:GetParent()
local damage = ( self.roots_damage / self.roots_duration ) * self.interval
-- Apply Damage --
EncounterApplyDamage(victim, caster, self:GetAbility(), damage, DAMAGE_TYPE_MAGICAL, DOTA_DAMAGE_FLAG_NONE)
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:GetModifierMoveSpeedBonus_Percentage( params )
return self.roots_move_speed_percentage
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:OnTooltip( params )
return self.roots_duration
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:GetAttributes()
return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:IsHidden()
return false
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:IsPurgable()
return false
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:IsPurgeException()
return false
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:IsStunDebuff()
return false
end
function deathspeaker_xunra_rune_of_roots_penalty_modifier:IsDebuff()
return true
end
|
--------------------------------
-- @module DisplayManager
-- @extend Ref
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#DisplayManager] getDisplayRenderNode
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#DisplayManager] getAnchorPointInPoints
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getDisplayRenderNodeType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#DisplayManager] removeDisplay
-- @param self
-- @param #int index
--------------------------------
--
-- @function [parent=#DisplayManager] setForceChangeDisplay
-- @param self
-- @param #bool force
--------------------------------
--
-- @function [parent=#DisplayManager] init
-- @param self
-- @param #ccs.Bone bone
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#DisplayManager] getContentSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getBoundingBox
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- @overload self, cc.Node, int
-- @overload self, ccs.DisplayData, int
-- @function [parent=#DisplayManager] addDisplay
-- @param self
-- @param #ccs.DisplayData displayData
-- @param #int index
--------------------------------
-- @overload self, float, float
-- @overload self, vec2_table
-- @function [parent=#DisplayManager] containPoint
-- @param self
-- @param #float x
-- @param #float y
-- @return bool#bool ret (retunr value: bool)
--------------------------------
-- Change display by index. You can just use this method to change display in the display list.<br>
-- The display list is just used for this bone, and it is the displays you may use in every frame.<br>
-- Note : if index is the same with prev index, the method will not effect<br>
-- param index The index of the display you want to change<br>
-- param force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame.
-- @function [parent=#DisplayManager] changeDisplayWithIndex
-- @param self
-- @param #int index
-- @param #bool force
--------------------------------
--
-- @function [parent=#DisplayManager] changeDisplayWithName
-- @param self
-- @param #string name
-- @param #bool force
--------------------------------
--
-- @function [parent=#DisplayManager] isForceChangeDisplay
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#DisplayManager] getCurrentDisplayIndex
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#DisplayManager] getAnchorPoint
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getDecorativeDisplayList
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- Determines if the display is visible<br>
-- see setVisible(bool)<br>
-- return true if the node is visible, false if the node is hidden.
-- @function [parent=#DisplayManager] isVisible
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets whether the display is visible<br>
-- The default value is true, a node is default to visible<br>
-- param visible true if the node is visible, false if the node is hidden.
-- @function [parent=#DisplayManager] setVisible
-- @param self
-- @param #bool visible
--------------------------------
--
-- @function [parent=#DisplayManager] create
-- @param self
-- @param #ccs.Bone bone
-- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] DisplayManager
-- @param self
return nil
|
local get_input = require("refactoring.get_input")
local M = {}
function M.from_input(refactor)
local file_name = get_input("106: File Name > ", vim.fn.expand("%:h"))
-- OPTIONS? We should probably configure this
-- extract on second method added
vim.cmd(":vnew")
vim.cmd(string.format(":set filetype=%s", refactor.filetype))
vim.cmd(string.format(":w! %s", file_name))
table.insert(refactor.buffers, vim.fn.bufnr())
return true, refactor
end
return M
|
--lns/tags/Inq.lns
local _moduleObj = {}
local __mod__ = '@lns.@tags.@Inq'
local _lune = {}
if _lune6 then
_lune = _lune6
end
function _lune.loadModule( mod )
if __luneScript then
return __luneScript:loadModule( mod )
end
return require( mod )
end
function _lune.__isInstanceOf( obj, class )
while obj do
local meta = getmetatable( obj )
if not meta then
return false
end
local indexTbl = meta.__index
if indexTbl == class then
return true
end
if meta.ifList then
for index, ifType in ipairs( meta.ifList ) do
if ifType == class then
return true
end
if _lune.__isInstanceOf( ifType, class ) then
return true
end
end
end
obj = indexTbl
end
return false
end
function _lune.__Cast( obj, kind, class )
if kind == 0 then -- int
if type( obj ) ~= "number" then
return nil
end
if math.floor( obj ) ~= obj then
return nil
end
return obj
elseif kind == 1 then -- real
if type( obj ) ~= "number" then
return nil
end
return obj
elseif kind == 2 then -- str
if type( obj ) ~= "string" then
return nil
end
return obj
elseif kind == 3 then -- class
return _lune.__isInstanceOf( obj, class ) and obj or nil
end
return nil
end
if not _lune6 then
_lune6 = _lune
end
local DBCtrl = _lune.loadModule( 'lns.tags.DBCtrl' )
local Util = _lune.loadModule( 'lns.tags.Util' )
local LuneAst = _lune.loadModule( 'go/github:com.ifritJP.LuneScript.src.lune.base.Ast' )
local function InqDef( db, pattern )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapSymbolDecl( pattern, function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, pattern, path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqDef = InqDef
local function InqRef( db, pattern, onlySet )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapSymbolRef( pattern, onlySet, function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, pattern, path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqRef = InqRef
local function InqAllmut( db )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapAllmutDecl( function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, "allmut", path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqAllmut = InqAllmut
local function InqAsync( db, asyncMode )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapAsyncMode( asyncMode, function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, string.format( "%d", asyncMode), path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqAsync = InqAsync
local function InqLuaval( db )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapLuavalRef( function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, "luaval", path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqLuaval = InqLuaval
local function InqAsyncLock( db )
local factory = Util.SourceCodeLineAccessorFactory.new()
db:mapAsyncLock( function ( item )
local path = db:getFilePath( item:get_fileId() )
if nil == path then
local _path = path
error( string.format( "file id is illegal -- %d", item:get_fileId()) )
end
Util.outputLocate( io.stdout, "luaval", path, factory:create( path ), item:get_line() )
return true
end )
end
_moduleObj.InqAsyncLock = InqAsyncLock
return _moduleObj
|
nut.dialogue = nut.dialogue or {}
nut.dialogue.list = nut.dialogue.list or {}
function nut.dialogue.loadFromDir(directory)
for k, v in ipairs(file.Find(directory.."/*.lua", "LUA")) do
local niceName = v:sub(4, -5)
DIALOGUE = nut.dialogue.list[niceName] or {}
if (PLUGIN) then
DIALOGUE.plugin = PLUGIN.uniqueID
end
DIALOGUE.tree = {}
DIALOGUE.addTopic = function(topicID, data)
local topicData = {
statement = data.statement or "",
response = data.response or "",
preCallback = data.preCallback,
postCallback = data.postCallback,
options = data.options or {}
}
DIALOGUE.tree[topicID] = topicData
end
nut.util.include(directory.."/"..v)
DIALOGUE.name = DIALOGUE.name or "Unknown"
nut.dialogue.list[niceName] = DIALOGUE
DIALOGUE = nil
end
end
function nut.dialogue.addTopic(id, topicID, statement, response, preCallback, postCallback, options)
local dialogue = nut.dialogue.list[id]
if not dialogue then return end
local topic = {}
topic.statement = statement or ""
topic.response = response or ""
topic.preCallback = preCallback
topic.postCallback = postCallback
topic.options = options or {}
dialogue.tree[topicID] = topic
end
function nut.dialogue.getTopic(id, topicID)
local dialogue = nut.dialogue.list[id]
if not dialogue then return end
return dialogue.tree[topicID]
end
hook.Add("DoPluginIncludes", "nutDialogueLib", function(path)
nut.dialogue.loadFromDir(path.."/dialogue")
end)
|
-- Third Party Libs
local stringy = require "stringy"
local multipart = require "multipart"
local cjson = require "cjson"
-- Openresty Based Libs
local string_find = string.find
local string_len = string.len
local table_maxn = table.maxn
local req_clear_header = ngx.req.clear_header
local req_set_header = ngx.req.set_header
local req_get_headers = ngx.req.get_headers
local req_set_uri_args = ngx.req.set_uri_args
local req_get_uri_args = ngx.req.get_uri_args
local req_get_body_data = ngx.req.get_body_data
local req_set_body_data = ngx.req.set_body_data
local req_read_body = ngx.req.read_body
local encode_args = ngx.encode_args
local ngx_decode_args = ngx.decode_args
-- Lua Based Libs
local unpack = unpack
local pcall = pcall
local _M = {}
local CONTENT_LENGTH = "content-length"
local CONTENT_TYPE = "content-type"
-- Different HTTP POST TYPE
local JSON, MULTI, ENCODED = "json", "multi_part", "form_encoded"
local HTTP_METHOD = {
POST = "POST",
GET = "GET"
}
local function parse_json(body)
if body then
local status, res = pcall(cjson.decode, body)
if status then
return res
end
end
end
local function decode_args(body)
if body then
return ngx_decode_args(body)
end
return {}
end
local function get_content_type(content_type)
if content_type == nil then
return
end
if string_find(content_type:lower(), "application/json", nil, true) then
return JSON
elseif string_find(content_type:lower(), "multipart/form-data", nil, true) then
return MULTI
elseif string_find(content_type:lower(), "application/x-www-form-urlencoded", nil, true) then
return ENCODED
end
end
local function transform_json_to_form(body, content_length)
local content_length = (body and string_len(body)) or 0
local parameters = parse_json(body)
if parameters == nil and content_length > 0 then return false, nil end -- Couldn't modify body
req_set_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
return true, encode_args(parameters)
end
local function transform_form_to_json(body, content_length)
local content_length = (body and string_len(body)) or 0
local parameters = decode_args(body)
if parameters == nil and content_length > 0 then return false, nil end -- Couldn't modify body
req_set_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
return true, cjson.encode(parameters)
end
local function req_transform(conf)
local content_type_value = req_get_headers(0)[CONTENT_TYPE]
local content_type = get_content_type(content_type_value)
if content_type == nil or conf.transformer == nil then
return -- POST body only supports three basic types.
end
req_read_body()
local body = req_get_body_data()
local is_body_transformed = false
local content_length = (body and string_len(body)) or 0
-- Call req_read_body to read the request body first
if "JSON_TO_FORM" == conf.transformer and content_type == JSON then
is_body_transformed, body = transform_json_to_form(body, content_length)
end
if "FORM_TO_JSON" == conf.transformer and content_type == FORM then
is_body_transformed, body = transform_form_to_json(body, content_length)
end
if is_body_transformed then
req_set_body_data(body)
req_set_header(CONTENT_LENGTH, string_len(body))
end
end
-- This method would transfer head attribute to body or querystring based on request type
-- Only supports POST & GET method
function _M.execute(conf)
local request_method = ngx.req.get_method()
if HTTP_METHOD.POST == request_method then
req_transform(conf)
end
end
return _M
|
--[[------------------------------------------------------------------------------------------------
| EDIT CODE BELOW AT YOUR OWN RISK |
------------------------------------
]]--
--[[
CONSTANTS
]]--
DISCORD = DISCORD or {}
DISCORD.State = DISCORD.State or "Default"
local CLIENT_ID = DISCORD.Client_ID
local net = net
local hook = hook
local http = http
local timer = timer
local string = string
local tostring = tostring
local istable = istable
local SysTime = SysTime
local MIN_PORT = 6463
local MAX_PORT = 6473
local PORT_COUNT = MAX_PORT - MIN_PORT
local CONNECTION_ADDRESS = "http://127.0.0.1:%s"
local DISCORD_ASSETS_ADDRESS = string.format( "https://discordapp.com/api/v6/oauth2/applications/%s/assets", CLIENT_ID )
local RPC_ADDRESS = "http://127.0.0.1:%s/rpc?v=1&client_id=%s"
local ACTIVITY_SYNC_COOLDOWN = 15
local FALLBACK_ACTIVITY = {
details = "N/A",
state = "Doing nothing"
}
--[[
PRINT FUNCTIONS
]]
local printDebug = DISCORD.printDebug
local printSuccess = DISCORD.printSuccess
local printWarn = DISCORD.printWarn
--[[
DISCORD HTTP LOADED CHECK
Wait until http loaded, so we can
initialize discord
]]--
if not DISCORD.HTTPLoaded then
printDebug( "Waiting for HTTP to load" )
timer.Create( "Discord.HTTPLoadedCheck", 3, 0, function()
http.Fetch( "http://www.google.com/", function()
DISCORD.HTTPLoaded = true
printSuccess( "HTTP loaded" )
hook.Run( "Discord.OnHTTPLoaded" )
timer.Remove( "Discord.HTTPLoadedCheck" )
end, function() end )
end )
end
--[[
DISCORD ON HTTP LOADED HOOK
This hook will be called when http was
successfully loaded, and initializes
discord
]]--
hook.Add( "Discord.OnHTTPLoaded", "Discord.OnHTTPLoaded", function()
printDebug( "Starting to initialize" )
DISCORD:Init()
end )
--[[
DISCORD INIT
With this function we will initialize
our discord rpc, we need to find a
valid port
]]--
function DISCORD:Init()
self:CheckPort( MIN_PORT, function()
RPC_ADDRESS = string.format( RPC_ADDRESS, self.Port, CLIENT_ID )
self:PostInit()
self:SetActivity( { state = "Initializing" } )
end )
end
--[[
DISCORD CHECK PORT
With this function we will check if the
given port is valid for our api calls
]]--
function DISCORD:CheckPort( iPort, fCallback, iTryedPorts )
iTryedPorts = ( iTryedPorts or 0 ) + 1
if iTryedPorts == PORT_COUNT then
printWarn( "Connection failed, unable to find port between: " .. MIN_PORT .. ", " .. MAX_PORT )
return
end
http.Fetch( string.format( CONNECTION_ADDRESS, iPort ),
function( sBody )
if not string.match( sBody, "Authorization Required" ) then
self:CheckPort( iPort + 1, fCallback, iTryedPorts )
return
end
printSuccess( "Connected successfully on port " .. iPort )
self.Port = iPort
if fCallback then fCallback() end
end, function()
self:CheckPort( iPort + 1, fCallback, iTryedPorts )
end )
end
--[[
DISCORD POST INIT
This function will be callled after our
rpc client has ben initialized
]]--
function DISCORD:PostInit()
http.Fetch( DISCORD_ASSETS_ADDRESS, function( sBody )
printSuccess( "Successfully ran post init" )
timer.Create( "Discord.GetActitivity", ACTIVITY_SYNC_COOLDOWN, 0, function()
self:GetActivity()
end )
end, function( sError )
printWarn( "Failed to run post init, trying again in 3 seconds" )
timer.Simple( 3, self.PostInit )
end )
end
--[[
DISCORD SET ACTIVITY
With this function you will be able to
the discord acitvity
]]--
function DISCORD:SetActivity( tActivity, fCallback )
self:SendHTTP( {
cmd = "SET_ACTIVITY",
args = {
pid = 0,
activity = tActivity
},
nonce = tostring( SysTime() )
}, fCallback, RPC_ADDRESS )
end
--[[
DISCORD GET ACTIVITY
With this function you will be able to
the discord acitvity
]]--
function DISCORD:GetActivity()
local tActivity = hook.Run( "Discord.GetActivity", self:GetState() )
if not istable( tActivity ) then
tActivity = FALLBACK_ACTIVITY
end
self:SetActivity( tActivity )
end
--[[
DISCORD SET STATE
With this function you will set the
discord state that will be send with
each hook
]]--
function DISCORD:SetState( sState )
self.State = sState
end
--[[
DISCORD GET STATE
With this function you can get the current
discord state
]]--
function DISCORD:GetState()
return self.State
end
--[[
DISCORD AUTHORIZE
With this function you can authorize the
current localplayer
]]--
function DISCORD:Authorize()
self:SendHTTP( {
cmd = "AUTHORIZE",
args = {
client_id = CLIENT_ID,
scopes = { "identify", "guilds.join" }
},
nonce = tostring( SysTime() )
}, function( tBody, sError )
if not tBody then
printWarn( "Failed to authorize, error : " .. sError )
return
end
local tData = tBody.data
if not tData then
printWarn( "Failed to authorize, error : Invalid data" )
return
end
local sCode = tData.code
if not sCode then
printWarn( "Failed to authorize, error : Invalid code" )
return
end
net.Start( "Discord.SendAuthCode" )
net.WriteString( sCode )
net.SendToServer()
end, RPC_ADDRESS )
end
--[[
DISCORD AUTHORIZE HOOK
If this hook is called it will start the
client authorize process
]]--
hook.Add( "Discord.Authorize", "Discord.Authorize", function()
DISCORD:Authorize()
end )
--[[
DISCORD CHANGE STATE HOOK
If this hook is called with a string state
it will set the discord state to the given
state
]]--
hook.Add( "Discord.ChangeState", "Discord.ChangeState", function( sState )
if not sState or #sState <= 0 then return end
DISCORD:SetState( sState )
end )
hook.Add( "ShutDown", "Discord.ShutDown", function()
DISCORD:SetActivity( nil )
end )
|
function opponentNoteHit()
triggerEvent('Screen Shake', '0.1, 0.01', '0.1, 0.01');
health = getProperty('health')
setProperty('health', health- 0.005);
end
function onUpdate(elapsed)
if bfName == 'bf' or 'bf-3d' or 'bf-winner' or 'tunnel-bf' or 'bandu night' then --replace the name for your character name
for i=0,4,1 do
setPropertyFromGroup('opponentStrums', i, 'texture', 'NOTE_assets_3D')
end
for i = 0, getProperty('unspawnNotes.length')-1 do
if not getPropertyFromGroup('unspawnNotes', i, 'mustPress') then
setPropertyFromGroup('unspawnNotes', i, 'texture', 'NOTE_assets_3D'); --Change texture
end
end
end
if curStep == 20 then
started = true
end
songPos = getSongPosition()
local currentBeat = (songPos/5000)*(curBpm/60)
doTweenY('opponentmove', 'dad', 100 - 400*math.sin((currentBeat+12*12)*math.pi), 2)
doTweenX('disruptor2', 'disruptor2.scale', 0 - 50*math.sin((currentBeat+1*0.1)*math.pi), 6)
doTweenY('disruptor2', 'disruptor2.scale', 0 - 31*math.sin((currentBeat+1*1)*math.pi), 6)
if started == true then
noteTweenY('player1', 4, defaultPlayerStrumY3 - 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('player2', 5, defaultPlayerStrumY1 + 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('player3', 6, defaultPlayerStrumY0 - 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('player4', 7, defaultPlayerStrumY2 + 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('opponent1', 0, defaultOpponentStrumY3 + 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('opponent2', 1, defaultOpponentStrumY1 - 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('opponent3', 2, defaultOpponentStrumY0 + 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenY('opponent4', 3, defaultOpponentStrumY2 - 300*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('playerx1', 4, defaultPlayerStrumX0 + 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('playerx2', 5, defaultPlayerStrumX1 - 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('playerx3', 6, defaultPlayerStrumX2 + 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('playerx4', 7, defaultPlayerStrumX3 - 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('opponentx1', 0, defaultOpponentStrumX0 - 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('opponentx2', 1, defaultOpponentStrumX1 + 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('opponentx3', 2, defaultOpponentStrumX2 - 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
noteTweenX('opponentx4', 3, defaultOpponentStrumX3 + 600*math.sin((currentBeat+8*0.1)*math.pi), 3)
end
end
function onCreatePost()
if not lowQuality then
makeLuaSprite('disruption', 'disruption',-400, -200)
addLuaSprite('disruption')
addGlitchEffect('disruption',2,2)
end end
|
-- https://github.com/denoland/deno
local root_pattern = require("lspconfig/util").root_pattern
return {
-- cmd = { "deno", "lsp" },
filetypes = {
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
},
init_options = { enable = true, lint = true, unstable = true },
root_dir = root_pattern("mod.ts", "import_map.json"),
}
|
-- Adapted from https://github.com/malkia/ufo/blob/master/ffi/OpenCL.lua
local ffi = require( "ffi" )
local name, path = "af", os.getenv("AF_PATH") .. "/"
local is_32_bit = ffi.abi("32bit") -- used to typedef dim_t
if ArrayFireMode == "cl" or ArrayFireMode == "cuda" or ArrayFireMode == "cpu" then
name = name .. ArrayFireMode
end
local libs = ffi_ArrayFireLibs or {
-- OSX = { x86 = path .. name, x64 = path .. name },
Windows = { x86 = path .. name, x64 = path .. name },
-- Linux = { x86 = path .. "lib" .. name, x64 = path .. "lib" .. name, arm = "bin/Linux/arm/lib" .. name }
}
local lib = ffi_ArrayFire_lib or libs[ ffi.os ][ ffi.arch ]
local af = ffi.load( lib )
ffi.cdef[[ af_err af_get_version (int *, int *, int *); ]]
local major, minor, patch = ffi.new("int[1]"), ffi.new("int[1]"), ffi.new("int[1]")
af.af_get_version(major, minor, patch)
local Version, Patch = major[0] * 10 + minor[0], patch[0]
local UsesCUDA = name == "af" or name == "afcuda"
local UsesOpenCL = name == "af" or name == "afcl"
local def = ([[
typedef enum {
///
/// The function returned successfully
///
AF_SUCCESS = 0,
// 100-199 Errors in environment
///
/// The system or device ran out of memory
///
AF_ERR_NO_MEM = 101,
///
/// There was an error in the device driver
///
AF_ERR_DRIVER = 102,
///
/// There was an error with the runtime environment
///
AF_ERR_RUNTIME = 103,
// 200-299 Errors in input parameters
///
/// The input array is not a valid af_array object
///
AF_ERR_INVALID_ARRAY = 201,
///
/// One of the function arguments is incorrect
///
AF_ERR_ARG = 202,
///
/// The size is incorrect
///
AF_ERR_SIZE = 203,
///
/// The type is not suppported by this function
///
AF_ERR_TYPE = 204,
///
/// The type of the input arrays are not compatible
///
AF_ERR_DIFF_TYPE = 205,
///
/// Function does not support GFOR / batch mode
///
AF_ERR_BATCH = 207,
// 300-399 Errors for missing software features
///
/// The option is not supported
///
AF_ERR_NOT_SUPPORTED = 301,
///
/// This build of ArrayFire does not support this feature
///
AF_ERR_NOT_CONFIGURED = 302,
$MIN_VERSION(32)$
///
/// This build of ArrayFire is not compiled with "nonfree" algorithms
///
AF_ERR_NONFREE = 303,
$END_MIN$
// 400-499 Errors for missing hardware features
///
/// This device does not support double
///
AF_ERR_NO_DBL = 401,
///
/// This build of ArrayFire was not built with graphics or this device does
/// not support graphics
///
AF_ERR_NO_GFX = 402,
// 500-599 Errors specific to heterogenous API
$MIN_VERSION(32)$
///
/// There was an error when loading the libraries
///
AF_ERR_LOAD_LIB = 501,
///
/// There was an error when loading the symbols
///
AF_ERR_LOAD_SYM = 502,
///
/// There was a mismatch between the input array and the active backend
///
AF_ERR_ARR_BKND_MISMATCH = 503,
$END_MIN$
// 900-999 Errors from upstream libraries and runtimes
///
/// There was an internal error either in ArrayFire or in a project
/// upstream
///
AF_ERR_INTERNAL = 998,
///
/// Unknown Error
///
AF_ERR_UNKNOWN = 999
} af_err;
typedef enum {
f32, ///< 32-bit floating point values
c32, ///< 32-bit complex floating point values
f64, ///< 64-bit complex floating point values
c64, ///< 64-bit complex floating point values
b8, ///< 8-bit boolean values
s32, ///< 32-bit signed integral values
u32, ///< 32-bit unsigned integral values
u8, ///< 8-bit unsigned integral values
s64, ///< 64-bit signed integral values
u64, ///< 64-bit unsigned integral values
$MIN_VERSION(32)$
s16, ///< 16-bit signed integral values
u16, ///< 16-bit unsigned integral values
$END_MIN$
} af_dtype;
typedef enum {
afDevice, ///< Device pointer
afHost, ///< Host pointer
} af_source;
// A handle for an internal array object
typedef void * af_array;
typedef enum {
AF_INTERP_NEAREST, ///< Nearest Interpolation
AF_INTERP_LINEAR, ///< Linear Interpolation
AF_INTERP_BILINEAR, ///< Bilinear Interpolation
AF_INTERP_CUBIC, ///< Cubic Interpolation
AF_INTERP_LOWER ///< Floor Indexed
} af_interp_type;
typedef enum {
///
/// Out of bound values are 0
///
AF_PAD_ZERO = 0,
///
/// Out of bound values are symmetric over the edge
///
AF_PAD_SYM
} af_border_type;
typedef enum {
///
/// Connectivity includes neighbors, North, East, South and West of current pixel
///
AF_CONNECTIVITY_4 = 4,
///
/// Connectivity includes 4-connectivity neigbors and also those on Northeast, Northwest, Southeast and Southwest
///
AF_CONNECTIVITY_8 = 8
} af_connectivity;
typedef enum {
///
/// Output of the convolution is the same size as input
///
AF_CONV_DEFAULT,
///
/// Output of the convolution is signal_len + filter_len - 1
///
AF_CONV_EXPAND,
} af_conv_mode;
typedef enum {
AF_CONV_AUTO, ///< ArrayFire automatically picks the right convolution algorithm
AF_CONV_SPATIAL, ///< Perform convolution in spatial domain
AF_CONV_FREQ, ///< Perform convolution in frequency domain
} af_conv_domain;
typedef enum {
AF_SAD = 0, ///< Match based on Sum of Absolute Differences (SAD)
AF_ZSAD, ///< Match based on Zero mean SAD
AF_LSAD, ///< Match based on Locally scaled SAD
AF_SSD, ///< Match based on Sum of Squared Differences (SSD)
AF_ZSSD, ///< Match based on Zero mean SSD
AF_LSSD, ///< Match based on Locally scaled SSD
AF_NCC, ///< Match based on Normalized Cross Correlation (NCC)
AF_ZNCC, ///< Match based on Zero mean NCC
AF_SHD ///< Match based on Sum of Hamming Distances (SHD)
} af_match_type;
$MIN_VERSION(31)$
typedef enum {
AF_YCC_601 = 601, ///< ITU-R BT.601 (formerly CCIR 601) standard
AF_YCC_709 = 709, ///< ITU-R BT.709 standard
AF_YCC_2020 = 2020 ///< ITU-R BT.2020 standard
} af_ycc_std;
$END_MIN$
typedef enum {
AF_GRAY = 0, ///< Grayscale
AF_RGB, ///< 3-channel RGB
AF_HSV, ///< 3-channel HSV
$MIN_VERSION(31)$
AF_YCbCr ///< 3-channel YCbCr
$END_MIN$
} af_cspace_t;
typedef enum {
AF_MAT_NONE = 0, ///< Default
AF_MAT_TRANS = 1, ///< Data needs to be transposed
AF_MAT_CTRANS = 2, ///< Data needs to be conjugate tansposed
AF_MAT_CONJ = 4, ///< Data needs to be conjugate
AF_MAT_UPPER = 32, ///< Matrix is upper triangular
AF_MAT_LOWER = 64, ///< Matrix is lower triangular
AF_MAT_DIAG_UNIT = 128, ///< Matrix diagonal contains unitary values
AF_MAT_SYM = 512, ///< Matrix is symmetric
AF_MAT_POSDEF = 1024, ///< Matrix is positive definite
AF_MAT_ORTHOG = 2048, ///< Matrix is orthogonal
AF_MAT_TRI_DIAG = 4096, ///< Matrix is tri diagonal
AF_MAT_BLOCK_DIAG = 8192 ///< Matrix is block diagonal
} af_mat_prop;
typedef enum {
AF_NORM_VECTOR_1, ///< treats the input as a vector and returns the sum of absolute values
AF_NORM_VECTOR_INF, ///< treats the input as a vector and returns the max of absolute values
AF_NORM_VECTOR_2, ///< treats the input as a vector and returns euclidean norm
AF_NORM_VECTOR_P, ///< treats the input as a vector and returns the p-norm
AF_NORM_MATRIX_1, ///< return the max of column sums
AF_NORM_MATRIX_INF, ///< return the max of row sums
AF_NORM_MATRIX_2, ///< returns the max singular value). Currently NOT SUPPORTED
AF_NORM_MATRIX_L_PQ, ///< returns Lpq-norm
AF_NORM_EUCLID = AF_NORM_VECTOR_2, ///< The default. Same as AF_NORM_VECTOR_2
} af_norm_type;
typedef enum {
AF_COLORMAP_DEFAULT = 0, ///< Default grayscale map
AF_COLORMAP_SPECTRUM= 1, ///< Spectrum map
AF_COLORMAP_COLORS = 2, ///< Colors
AF_COLORMAP_RED = 3, ///< Red hue map
AF_COLORMAP_MOOD = 4, ///< Mood map
AF_COLORMAP_HEAT = 5, ///< Heat map
AF_COLORMAP_BLUE = 6 ///< Blue hue map
} af_colormap;
$MIN_VERSION(31)$
typedef enum {
AF_FIF_BMP = 0, ///< FreeImage Enum for Bitmap File
AF_FIF_ICO = 1, ///< FreeImage Enum for Windows Icon File
AF_FIF_JPEG = 2, ///< FreeImage Enum for JPEG File
AF_FIF_JNG = 3, ///< FreeImage Enum for JPEG Network Graphics File
AF_FIF_PNG = 13, ///< FreeImage Enum for Portable Network Graphics File
AF_FIF_PPM = 14, ///< FreeImage Enum for Portable Pixelmap (ASCII) File
AF_FIF_PPMRAW = 15, ///< FreeImage Enum for Portable Pixelmap (Binary) File
AF_FIF_TIFF = 18, ///< FreeImage Enum for Tagged Image File Format File
AF_FIF_PSD = 20, ///< FreeImage Enum for Adobe Photoshop File
AF_FIF_HDR = 26, ///< FreeImage Enum for High Dynamic Range File
AF_FIF_EXR = 29, ///< FreeImage Enum for ILM OpenEXR File
AF_FIF_JP2 = 31, ///< FreeImage Enum for JPEG-2000 File
AF_FIF_RAW = 34 ///< FreeImage Enum for RAW Camera Image File
} af_image_format;
$END_MIN$
$MIN_VERSION(32)$
typedef enum {
AF_HOMOGRAPHY_RANSAC = 0, ///< Computes homography using RANSAC
AF_HOMOGRAPHY_LMEDS = 1 ///< Computes homography using Least Median of Squares
} af_homography_type;
// These enums should be 2^x
typedef enum {
AF_BACKEND_DEFAULT = 0, ///< Default backend order: OpenCL -> CUDA -> CPU
AF_BACKEND_CPU = 1, ///< CPU a.k.a sequential algorithms
AF_BACKEND_CUDA = 2, ///< CUDA Compute Backend
AF_BACKEND_OPENCL = 4, ///< OpenCL Compute Backend
} af_backend;
$END_MIN$
// Below enum is purely added for example purposes
// it doesn't and shoudn't be used anywhere in the
// code. No Guarantee's provided if it is used.
typedef enum {
AF_ID = 0
} af_someenum_t;
typedef ]] .. (is_32_bit and "int" or "long long") .. [[ dim_t;
typedef long long intl;
typedef unsigned long long uintl;
typedef void * af_features;
typedef struct af_cfloat {
float real;
float imag;
} af_cfloat;
typedef struct af_cdouble {
double real;
double imag;
} af_cdouble;
typedef struct af_seq {
double begin, end;
double step;
} af_seq;
typedef struct af_index_t{
union {
af_array arr; ///< The af_array used for indexing
af_seq seq; ///< The af_seq used for indexing
} idx;
bool isSeq; ///< If true the idx value represents a seq
bool isBatch; ///< If true the seq object is a batch parameter
} af_index_t;
typedef struct {
int row;
int col;
const char* title;
af_colormap cmap;
} af_cell;
typedef unsigned long long af_window;
$USES_CUDA$
typedef struct CUstream_st* cudaStream_t;
$END_USES_CUDA$
$USES_OPENCL$
typedef struct _cl_device_id * cl_device_id;
typedef struct _cl_context * cl_context;
typedef struct _cl_command_queue * cl_command_queue;
$END_USES_OPENCL$
/* Constructors */
af_err af_create_array (af_array *, const void * const, const unsigned, const dim_t * const, const af_dtype);
af_err af_create_handle (af_array *, const unsigned, const dim_t * const, const af_dtype);
af_err af_device_array (af_array *, const void *, const unsigned, const dim_t * const, const af_dtype)
/* Create Array */
af_err af_constant (af_array *, const double val, const unsigned, const dim_t * const, const af_dtype);
af_err af_constant_complex (af_array *, const double, const double, const unsigned, const dim_t * const, const af_dtype);
af_err af_constant_long (af_array *, const intl, const unsigned, const dim_t * const);
af_err af_constant_ulong (af_array *, const uintl, const unsigned, const dim_t * const);
af_err af_diag_create (af_array *, const af_array, const int);
af_err af_diag_extract (af_array *, const af_array, const int);
af_err af_get_seed (uintl *);
af_err af_identity (af_array *, const unsigned, const dim_t * const, const af_dtype);
af_err af_iota (af_array *, const unsigned, const dim_t * const, const unsigned, const dim_t * const, const af_dtype);
af_err af_lower (af_array *, const af_array, bool);
af_err af_randn (af_array *, const unsigned, const dim_t * const, const af_dtype);
af_err af_randu (af_array *, const unsigned, const dim_t * const, const af_dtype);
af_err af_range (af_array *, const unsigned, const dim_t * const, const int, const af_dtype);
af_err af_set_seed (const uintl);
af_err af_upper (af_array *, const af_array, bool);
/* Backends */
$MIN_VERSION(32)$
af_err af_get_available_backends (int *);
af_err af_get_backend_count (unsigned *);
af_err af_get_backend_id (af_backend *, const af_array);
af_err af_set_backend (const af_backend);
$END_MIN$
/* Computer Vision */
$MIN_VERSION(31)$
af_err af_dog (af_array *, const af_array, const int, const int);
$END_MIN$
af_err af_fast (af_features *, const af_array, const float, const unsigned, const bool, const float, const unsigned);
$MIN_VERSION(32)$
af_err af_gloh (af_features *, af_array *, const af_array, const unsigned, const float, const float, const float, const bool, const float, const float);
$END_MIN$
af_err af_hamming_matcher (af_array *, af_array *, const af_array, const af_array, const dim_t, const unsigned);
$MIN_VERSION(31)$
af_err af_harris (af_features *, const af_array, const unsigned, const float, const float, const unsigned, const float);
$END_MIN$
$MIN_VERSION(32)$
af_err af_homography (af_array *, int *, const af_array, const af_array, const af_array, const af_array, const af_homography_type, const float, const unsigned, const af_dtype);
$END_MIN$
af_err af_match_template (af_array *, const af_array, const af_array, const af_match_type);
af_err af_orb (af_features *, af_array *, const af_array, const float, const unsigned, const float, const unsigned, const bool);
$MIN_VERSION(31)$
af_err af_nearest_neighbour (af_array *, af_array *, const af_array, const af_array, const dim_t, const unsigned, const af_match_type);
af_err af_sift (af_features *, af_array *, const af_array, const unsigned, const float, const float, const float, const bool, const float, const float);
af_err af_susan (af_features *, const af_array, const unsigned, const float, const float, const float, const unsigned);
$END_MIN$
/* Features */
af_err af_create_features (af_features *, dim_t);
af_err af_get_features_num (dim_t *, const af_features);
af_err af_get_features_orientation (af_array *, const af_features);
af_err af_get_features_score (af_array *, const af_features);
af_err af_get_features_size (af_array *, const af_features);
af_err af_get_features_xpos (af_array *, const af_features);
af_err af_get_features_ypos (af_array *, const af_features);
af_err af_release_features (af_features);
af_err af_retain_features (af_features *, const af_features);
/* Image Processing */
af_err af_bilateral (af_array *, const af_array, const float, const float, const bool);
af_err af_color_space (af_array *, const af_array, const af_cspace_t, const af_cspace_t);
af_err af_dilate (af_array *, const af_array, const af_array);
af_err af_dilate3 (af_array *, const af_array, const af_array);
af_err af_erode (af_array *, const af_array, const af_array);
af_err af_erode3 (af_array *, const af_array, const af_array);
af_err af_gaussian_kernel (af_array *, const int, const int, const double, const double);
af_err af_gray2rgb (af_array *, const af_array, const float, const float, const float);
af_err af_hist_equal (af_array *, const af_array, const af_array);
af_err af_histogram (af_array *, const af_array, const unsigned, const double, const double);
af_err af_hsv2rgb (af_array *, const af_array);
af_err af_maxfilt (af_array *, const af_array, const dim_t, const dim_t, const af_border_type);
af_err af_mean_shift (af_array *, const af_array, const float, const float, const unsigned, const bool);
af_err af_medfilt (af_array *, const af_array, const dim_t, const dim_t, const af_border_type);
af_err af_minfilt (af_array *, const af_array, const dim_t, const dim_t, const af_border_type);
af_err af_regions (af_array *, const af_array, const af_connectivity, const af_dtype);
af_err af_resize (af_array *, const af_array, const dim_t, const dim_t, const af_interp_type);
af_err af_rgb2gray (af_array *, const af_array, const float, const float, const float);
af_err af_rgb2hsv (af_array *, const af_array);
$MIN_VERSION(31)$
af_err af_rgb2ycbcr (af_array *, const af_array, const af_ycc_std);
$END_MIN$
af_err af_rotate (af_array *, const af_array, const float, const bool, const af_interp_type);
$MIN_VERSION(31)$
af_err af_sat (af_array *, const af_array);
$END_MIN$
af_err af_scale (af_array *, const af_array, const float, const float, const dim_t, const dim_t, const af_interp_type);
af_err af_skew (af_array *, const af_array, const float, const float, const dim_t, const dim_t, const af_interp_type, const bool);
af_err af_sobel_operator (af_array *, af_array *, const af_array, const unsigned);
af_err af_transform (af_array *, const af_array, const af_array, const dim_t, const dim_t, const af_interp_type, const bool);
af_err af_translate (af_array *, const af_array, const float, const float, const dim_t, const dim_t, const af_interp_type);
$MIN_VERSION(31)$
af_err af_unwrap (af_array *, const af_array, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const bool);
af_err af_wrap (af_array *, const af_array, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const dim_t, const bool);
af_err af_ycbcr2rgb (af_array *, const af_array, const af_ycc_std);
$END_MIN$
/* Interface */
$MIN_VERSION(32)$
$USES_OPENCL$
af_err afcl_get_context (cl_context *, const bool);
af_err afcl_get_device_id (cl_device_id *);
af_err afcl_get_queue (cl_command_queue *, const bool);
$END_USES_OPENCL$
$USES_CUDA$
af_err afcu_get_native_id (int *, int);
af_err afcu_get_stream (cudaStream_t *, int);
$END_USES_CUDA$
$END_MIN$
/* IO */
$MIN_VERSION(31)$
af_err af_delete_image_memory (void *);
$END_MIN$
af_err af_load_image (af_array *, const char *, const bool);
$MIN_VERSION(31)$
af_err af_load_image_memory (af_array *, const void *);
$END_MIN$
$MIN_VERSION(32)$
af_err af_load_image_native (af_array *, const char *);
$END_MIN$
af_err af_read_array_index (af_array *, const char *, const unsigned);
af_err af_read_array_key (af_array *, const char *, const char *);
af_err af_read_array_key_check (int *, const char *, const char *);
af_err af_save_array (int *, const char *, const af_array, const char *, const bool);
af_err af_save_image (const char *, const af_array);
$MIN_VERSION(31)$
af_err af_save_image_memory (void **, const af_array, const af_image_format);
$END_MIN$
$MIN_VERSION(32)$
af_err af_save_image_native (const char *, const af_array);
$END_MIN$
/* Linear Algebra */
af_err af_cholesky (af_array *, int *, const af_array, const bool);
af_err af_cholesky_inplace (int *, const af_array, const bool);
af_err af_det (double *, double *, const af_array);
af_err af_dot (af_array *, const af_array, const af_array, const af_mat_prop, const af_mat_prop);
af_err af_inverse (af_array *, const af_array, const af_mat_prop);
af_err af_lu (af_array *, af_array *, af_array *, const af_array);
af_err af_lu_inplace (af_array *, af_array, const bool);
af_err af_matmul (af_array *, const af_array, const af_array, const af_mat_prop, const af_mat_prop);
af_err af_norm (double *, const af_array, const af_norm_type, const double, const double);
af_err af_qr (af_array *, af_array *, af_array *, const af_array);
af_err af_qr_inplace (af_array *, af_array);
af_err af_rank (unsigned *, const af_array, const double);
af_err af_solve (af_array *, const af_array, const af_array, const af_mat_prop);
af_err af_solve_lu (af_array *, const af_array, const af_array, const af_array, const af_mat_prop);
$MIN_VERSION(31)$
af_err af_svd (af_array *, af_array *, af_array *, const af_array);
af_err af_svd_inplace (af_array *, af_array *, af_array *, const af_array);
$END_MIN$
af_err af_transpose (af_array *, af_array, const bool);
af_err af_transpose_inplace (af_array, const bool);
/* Mathematics */
af_err af_abs (af_array *, const af_array);
af_err af_acos (af_array *, const af_array);
af_err af_acosh (af_array *, const af_array);
af_err af_add (af_array *, const af_array, const af_array, const bool);
af_err af_and (af_array *, const af_array, const af_array, const bool);
af_err af_arg (af_array *, const af_array);
af_err af_asin (af_array *, const af_array);
af_err af_asinh (af_array *, const af_array);
af_err af_atan (af_array *, const af_array);
af_err af_atanh (af_array *, const af_array);
af_err af_atan2 (af_array *, const af_array, const af_array, const bool);
af_err af_bitand (af_array *, const af_array, const af_array, const bool);
af_err af_bitor (af_array *, const af_array, const af_array, const bool);
af_err af_bitshiftl (af_array *, const af_array, const af_array, const bool);
af_err af_bitshiftr (af_array *, const af_array, const af_array, const bool);
af_err af_bitxor (af_array *, const af_array, const af_array, const bool);
af_err af_cbrt (af_array *, const af_array);
af_err af_ceil (af_array *, const af_array);
af_err af_conjg (af_array *, const af_array);
af_err af_cos (af_array *, const af_array);
af_err af_cosh (af_array *, const af_array);
af_err af_cplx (af_array *, const af_array);
af_err af_cplx2 (af_array *, const af_array, const af_array, const bool);
af_err af_div (af_array *, const af_array, const af_array, const bool);
af_err af_eq (af_array *, const af_array, const af_array, const bool);
af_err af_erf (af_array *, const af_array);
af_err af_erfc (af_array *, const af_array);
af_err af_exp (af_array *, const af_array);
af_err af_expm1 (af_array *, const af_array);
af_err af_factorial (af_array *, const af_array);
af_err af_floor (af_array *, const af_array);
af_err af_ge (af_array *, const af_array, const af_array, const bool);
af_err af_gt (af_array *, const af_array, const af_array, const bool);
af_err af_hypot (af_array *, const af_array, const af_array, const bool);
af_err af_imag (af_array *, const af_array);
af_err af_le (af_array *, const af_array, const af_array, const bool);
af_err af_lgamma (af_array *, const af_array);
af_err af_lt (af_array *, const af_array, const af_array, const bool);
af_err af_log (af_array *, const af_array);
af_err af_log10 (af_array *, const af_array);
af_err af_log1p (af_array *, const af_array);
af_err af_maxof (af_array *, const af_array, const af_array, const bool);
af_err af_minof (af_array *, const af_array, const af_array, const bool);
af_err af_mod (af_array *, const af_array, const af_array, const bool);
af_err af_mul (af_array *, const af_array, const af_array, const bool);
af_err af_neq (af_array *, const af_array, const af_array, const bool);
af_err af_not (af_array *, const af_array);
af_err af_or (af_array *, const af_array, const af_array, const bool);
af_err af_pow (af_array *, const af_array, const af_array, const bool);
af_err af_real (af_array *, const af_array);
af_err af_rem (af_array *, const af_array, const af_array, const bool);
af_err af_root (af_array *, const af_array, const af_array, const bool);
af_err af_round (af_array *, const af_array);
$MIN_VERSION(31)$
AFAPI af_err af_sigmoid (af_array *, const af_array);
$END_MIN$
af_err af_sign (af_array *, const af_array);
af_err af_sin (af_array *, const af_array);
af_err af_sinh (af_array *, const af_array);
af_err af_sub (af_array *, const af_array, const af_array, const bool);
af_err af_sqrt (af_array *, const af_array);
af_err af_tan (af_array *, const af_array);
af_err af_tanh (af_array *, const af_array);
af_err af_trunc (af_array *, const af_array);
af_err af_tgamma (af_array *, const af_array);
/* Signal Processing */
af_err af_approx1 (af_array *, const af_array, const af_array, const af_interp_type, const float);
af_err af_approx2 (af_array *, const af_array, const af_array, const af_array, const af_interp_type, const float);
af_err af_convolve1 (af_array *, const af_array, const af_array, const af_conv_mode, af_conv_domain);
af_err af_convolve2 (af_array *, const af_array, const af_array, const af_conv_mode, af_conv_domain);
af_err af_convolve2_sep (af_array *, const af_array, const af_array, const af_array, const af_conv_mode);
af_err af_convolve3 (af_array *, const af_array, const af_array, const af_conv_mode, af_conv_domain);
af_err af_fft (af_array *, const af_array, const double, const dim_t);
af_err af_fft_convolve2 (af_array *, const af_array, const af_array, const af_conv_mode);
af_err af_fft_convolve3 (af_array *, const af_array, const af_array, const af_conv_mode);
$MIN_VERSION(31)$
af_err af_fft_c2r (af_array *, const af_array, const double, const bool);
af_err af_fft_inplace (af_array, const double);
af_err af_fft_r2c (af_array *, const af_array, const double, const dim_t);
$END_MIN$
af_err af_fft2 (af_array *, const af_array, const double, const dim_t, const dim_t);
$MINVER(31)$
af_err af_fft2_c2r (af_array *, const af_array, const double, const bool);
af_err af_fft2_inplace (af_array, const double);
af_err af_fft2_r2c (af_array *, const af_array, const double, const dim_t, const dim_t);
$/MINVER$
af_err af_fft3 (af_array *, const af_array, const double, const dim_t, const dim_t, const dim_t);
$MIN_VERSION(31)$
af_err af_fft3_c2r (af_array *, const af_array, const double, const bool);
af_err af_fft3_inplace (af_array, const double);
af_err af_fft3_r2c (af_array *, const af_array, const double, const dim_t, const dim_t, const dim_t);
$END_MIN$
af_err af_fir (af_array *, const af_array, const af_array);
af_err af_ifft (af_array *, const af_array, const double, const dim_t);
$MIN_VERSION(31)$
af_err af_ifft_inplace (af_array, const double);
$END_MIN
af_err af_ifft2 (af_array *, const af_array, const double, const dim_t, const dim_t);
$MIN_VERSION(31)$
af_err af_ifft2_inplace (af_array, const double);
$END_MIN$
af_err af_ifft3 (af_array *, const af_array, const double, const dim_t, const dim_t, const dim_t);
$MIN_VERSION(31)$
af_err af_ifft3_inplace (af_array, const double);
$END_MIN$
af_err af_iir (af_array *, const af_array, const af_array, const af_array);
/* Statistics */
af_err af_corrcoef (double *, double *, const af_array, const af_array);
af_err af_cov ( af_array *, const af_array, const af_array, const bool);
af_err af_mean (af_array *, const af_array, const dim_t);
af_err af_mean_all (double *, double *, const af_array);
af_err af_mean_all_weighted (double *, double *, const af_array, const af_array);
af_err af_mean_weighted (af_array *, const af_array, const af_array, const dim_t);
af_err af_median (af_array *, const af_array, const dim_t);
af_err af_median_all (double *, double *, const af_array);
af_err af_stdev (af_array *, const af_array, const dim_t);
af_err af_stdev_all (double *, double *, const af_array);
af_err af_var (af_array *, const af_array, const bool, const dim_t);
af_err af_var_all (double *, double *, const af_array, const bool);
af_err af_var_all_weighted (double *, double *, const af_array, const af_array);
af_err af_var_weighted (af_array *, const af_array, const af_array, const dim_t);
/* Util */
af_err af_print_array (af_array arr);
$MIN_VERSION(31)$
af_err af_print_array_gen (const char *, const af_array, const int);
af_err af_array_to_string (char **, const char *, const af_array, const int, const bool);
$END_MIN$
/* Vector */
af_err af_accum (af_array *, const af_array, const int);
af_err af_all_true (af_array *, const af_array, const int);
af_err af_all_true_all (double *, double *, const af_array);
af_err af_any_true (af_array *, const af_array, const int);
af_err af_any_true_all (double *, double *, const af_array);
af_err af_count (af_array *, const af_array, const int);
af_err af_count_all (double *, double *, const af_array);
af_err af_diff1 (af_array *, const af_array, const int);
af_err af_diff2 (af_array *, const af_array, const int);
af_err af_gradient (af_array *, af_array *, const af_array);
af_err af_imax (af_array *, af_array *, const af_array, const int);
af_err af_imax_all (double *, double *, unsigned *, const af_array);
af_err af_imin (af_array *, af_array *, const af_array, const int);
af_err af_imin_all (double *, double *, unsigned *, const af_array);
af_err af_max (af_array *, const af_array, const int);
af_err af_max_all (double *, double *, const af_array);
af_err af_min (af_array *, const af_array, const int);
af_err af_min_all (double *, double *, const af_array);
af_err af_product (af_array *, const af_array, const int);
af_err af_product_all (double *, double *, const af_array);
$MIN_VERSION(31)$
af_err af_product_nan (af_array *, const af_array, const int, const double);
af_err af_product_nan_all (double *, double *, const af_array, const double);
$END_MIN$
af_err af_set_intersect (af_array *, const af_array, const af_array, const bool);
af_err af_set_union (af_array *, const af_array, const af_array, const bool);
af_err af_set_unique (af_array *, const af_array, const bool);
af_err af_sort (af_array *, const af_array, const unsigned, const bool);
af_err af_sort_by_key (af_array *, af_array *, const af_array, const af_array, const unsigned, const bool);
af_err af_sort_index (af_array *, af_array *, const af_array, const unsigned, const bool);
af_err af_sum (af_array *, const af_array, const int);
af_err af_sum_all (double *, double *, const af_array);
$MIN_VERSION(31)$
af_err af_sum_nan (af_array *, const af_array, const int, const double);
af_err af_sum_nan_all (double *, double *, const af_array, const double);
$END_MIN$
af_err af_where (af_array *, const af_array);
/* Array Methods */
af_err af_copy_array (af_array *, const af_array);
af_err af_eval (af_array);
$MIN_VERSION(31)$
af_err af_get_data_ref_count (int *, const af_array);
$END_MIN$
af_err af_get_dims (dim_t *, dim_t *, dim_t *, dim_t *, const af_array);
af_err af_get_elements (dim_t *, const af_array);
af_err af_get_data_ptr (void *, const af_array);
af_err af_get_numdims (unsigned *, const af_array);
af_err af_get_type (af_dtype *, const af_array);
af_err af_is_bool (bool *, const af_array);
af_err af_is_column (bool *, const af_array);
af_err af_is_complex (bool *, const af_array);
af_err af_is_double (bool *, const af_array);
af_err af_is_empty (bool *, const af_array);
af_err af_is_floating (bool *, const af_array);
af_err af_is_integer (bool *, const af_array);
af_err af_is_real (bool *, const af_array);
af_err af_is_realfloating (bool *, const af_array);
af_err af_is_row (bool *, const af_array);
af_err af_is_scalar (bool *, const af_array);
af_err af_is_single (bool *, const af_array);
af_err af_is_vector (bool *, const af_array);
af_err af_release_array (af_array);
af_err af_retain_array (af_array *, const af_array);
af_err af_write_array (af_array, const void *, const size_t, af_source);
/* Assign / Index */
af_err af_assign_gen (af_array *, const af_array, const dim_t, const af_index_t *, const af_array);
af_err af_assign_seq (af_array *, const af_array, const unsigned, const af_seq * const, const af_array);
$MIN_VERSION(32)$
af_err af_create_indexers (af_index_t **);
$END_MIN$
af_err af_index (af_array *, const af_array, const unsigned, const af_seq * const);
af_err af_index_gen (af_array *, const af_array, const dim_t, const af_index_t *);
af_err af_lookup (af_array *, const af_array, const af_array, const unsigned);
$MIN_VERSION(32)$
af_err af_release_indexers (af_index_t *);
af_err af_set_array_indexer (af_index_t *, const af_array, const dim_t);
af_err af_set_seq_indexer (af_index_t *, const af_seq *, const dim_t, const bool);
af_err af_set_seq_param_indexer (af_index_t *, const double, const double, const double, const dim_t, const bool);
$END_MIN$
af_seq af_make_seq (double, double, double);
static const af_seq af_span = {1, 1, 0};
/* Device */
af_err af_alloc_device (void **, const dim_t);
af_err af_alloc_pinned (void **, const dim_t);
af_err af_device_gc ();
af_err af_device_info (char *, char *, char *, char *);
af_err af_device_mem_info (size_t *, size_t *, size_t *, size_t *);
af_err af_free_device (void *);
af_err af_free_pinned (void *);
af_err af_get_device (int *);
af_err af_get_device_count (int *);
af_err af_get_device_ptr (void **, const af_array);
af_err af_get_dbl_support (bool *, const int);
af_err af_get_mem_step_size (size_t *);
af_err af_info ();
$MIN_VERSION(31)$
af_err af_lock_device_ptr (const af_array);
$END_MIN$
af_err af_set_device (const int);
af_err af_set_mem_step_size (const size_t);
af_err af_sync (const int);
$MIN_VERSION(31)$
af_err af_unlock_device_ptr (const af_array);
$END_MIN$
/* Helper */
af_err af_cast (af_array *, const af_array, const af_dtype);
af_err af_isinf (af_array *, const af_array);
af_err af_iszero (af_array *, const af_array);
/* Move / Reorder */
af_err af_flat (af_array *, const af_array);
af_err af_flip (af_array *, const af_array, const unsigned);
af_err af_join (af_array *, const int, const af_array, const af_array);
af_err af_join_many (af_array *, const int, const unsigned, const af_array *);
af_err af_moddims (af_array *, const af_array, const unsigned, const dim_t *);
af_err af_reorder (af_array *, const af_array, const unsigned, const unsigned, const unsigned, const unsigned);
$MIN_VERSION(31)$
af_err af_replace (af_array, const af_array, const af_array);
af_err af_replace_scalar (af_array, const af_array, const double);
af_err af_select (af_array *, const af_array, const af_array, const af_array);
af_err af_select_scalar_r (af_array *, const af_array, const af_array, const double);
af_err af_select_scalar_l (af_array *, const af_array, const double, const af_array);
$END_MIN$
af_err af_shift (af_array *, const af_array, const int, const int, const int, const int);
af_err af_tile (af_array *, const af_array, const unsigned, const unsigned, const unsigned, const unsigned);
/* Draw */
af_err af_draw_hist (const af_window, const af_array, const double, const double, const af_cell *);
af_err af_draw_image (const af_window, const af_array, const af_cell *);
af_err af_draw_plot (const af_window, const af_array, const af_array, const af_cell *);
$MIN_VERSION(32)$
af_err af_draw_plot3 (const af_window, const af_array, const af_cell *);
$END_MIN$
$MIN_VERSION(32.1)$
af_err af_draw_surface (const af_window, const af_array, const af_array, const af_array, const af_cell *);
$END_MIN$
/* Window */
af_err af_create_window (af_window *, const int, const int, const char * const);
af_err af_destroy_window (const af_window);
af_err af_grid (const af_window, const int, const int);
af_err af_is_window_closed (bool *, const af_window);
af_err af_set_position (const af_window, const unsigned, const unsigned);
$MIN_VERSION(31)$
af_err af_set_size (const af_window, const unsigned, const unsigned);
$END_MIN$
af_err af_set_title (const af_window, const char * const);
af_err af_show (const af_window);
]]):gsub("%$MIN_VERSION%((%d+)%.?(%d*)%)%$(.-)%$END_MIN%$", function (version, patch_id, code)
version, patch_id = tonumber(version), tonumber(patch_id) or -1
if Version >= version and (Version > version or Patch >= patch_id) then
return code
else
return ""
end
end):gsub("%$USES_CUDA%$(.-)%END_USES_CUDA%$", function (code) -- strip CUDA if not supported
return UsesCUDA and code or ""
end):gsub("%$USES_OPENCL%$(.-)%$END_USES_OPENCL%$", function (code) -- strip OpenCL if not supported
return UsesOpenCL and code or ""
end)
ffi.cdef(def)
return af
|
require "ircmess"
for i=1, 50000 do
s = ircmess.parse(":cyka.yolo-swag.com 001 Xena :Welcome to IRC!\r\n")
assert(s.verb == "001")
assert(s.source == "cyka.yolo-swag.com")
assert(#s.argv == 2)
assert(s.argv[1] == "Xena")
s = ircmess.parse("PING :cyka.yolo-swag.com")
assert(s.source == "")
assert(s.verb == "PING")
assert(#s.argv == 1)
assert(s.argv[1] == "cyka.yolo-swag.com")
s = ircmess.parse(":cyka.yolo-swag.com 003 Swaglogbot :This server was created Mon Apr 7 2014 at 2:06:11 EDT")
assert(s.source == "cyka.yolo-swag.com")
assert(s.verb == "003")
assert(#s.argv == 2)
assert(s.argv[1] == "Swaglogbot")
end
print("All tests passed!")
|
Spectator = {
}
function Spectator:OnInit()
System.Log("spectator init");
end
function Spectator:OnShutDown()
end
function Spectator:OnUpdate( DeltaTime )
end
function Spectator:OnContact( Entity )
end
function Spectator:OnEvent( EventId, Params )
end
function Spectator:OnSave( props )
end
function Spectator:OnLoad( props )
end
|
--[[
Reportamus.lua
--]]
local Reportamus, dbg, dbgf = Object:newClass{ className = "Reportamus", register = true }
--- Constructor for extending class.
--
function Reportamus:newClass( t )
return Object.newClass( self, t )
end
--- Constructor for new instance.
--
function Reportamus:new( t )
local o = Object.new( self, t )
return o
end
function Reportamus:one()
app:show( self:toString() .. " one" )
end
function Reportamus:_getKeywordPath( keyword )
if self.lookup[keyword] then return self.lookup[keyword] end
local comp = { keyword:getName() }
local parent = keyword:getParent()
while parent do
comp[#comp + 1] = parent:getName()
parent = parent:getParent()
end
tab:reverseInPlace( comp )
local kwPath = "/" .. table.concat( comp, "/" )
self.lookup[keyword] = kwPath
return kwPath
end
local _asdf
function Reportamus:keywordReport( title )
app:call( Service:new{ name=title, async=true, progress=true, guard=App.guardVocal, main=function( call )
call:initStats{ 'nil', '0', '1', '2', '3', '4', '5', 'bad' }
self.lookup = {}
call:setCaption( "Dialog box needs your attention..." )
local targetPhotos = catalog:getMultipleSelectedOrAllPhotos()
if #targetPhotos == 0 then
app:show{ warning="No photos." }
call:cancel()
return
end
local allPhotos = catalog:getAllPhotos()
local button = app:show{ confirm="Create Keyword Report? (report will be available for copy to clipboard via dialog box).",
buttons = { dia:btn( str:fmtx( "Within Filmstrip (^1)", str:nItems( #targetPhotos, "photos" ) ), 'ok' ), dia:btn( str:fmtx( "Whole Catalog (^1)", str:nItems( #allPhotos, "photos" ) ), 'other' ) },
actionPrefKey = "Create keyword report",
}
if button == 'cancel' then
call:cancel()
return
end
local limited
if button == 'ok' then
-- target-photos already set.
limited = tab:createSet( targetPhotos )
elseif button == 'other' then
targetPhotos = allPhotos
-- not limited.
else
error( "bad button" )
end
local inclPhotos = app:getPref( 'includePhotos' )
local inclEmpties = not limited and app:getPref( 'includeEmptyKeywords' )
local cachePhotos
if not limited or inclEmpties then
cachePhotos = allPhotos
else -- limited and not including empties.
cachePhotos = targetPhotos
end
call:setCaption( "Acquiring a batch of keyword metadata..." )
local cache = lrMeta:createCache{ photos=cachePhotos, rawIds={ 'path', 'keywords', 'rating', 'isVirtualCopy' }, fmtIds={ 'copyName' } }
call:setCaption( "Creating report..." )
local keywordTable = {}
-- note: incl-photos is not considered until 2nd phase.
--[[ obs: save for a while...
if limited and not inclEmpties then -- performance boost in case only considering photo keywords.
for i, photo in ipairs( targetPhotos ) do
local keywords = cache:getRawMetadata( photo, 'keywords' )
for j, keyword in ipairs( keywords ) do
local keywordPath = self:_getKeywordPath( keyword )
local photos = keywordTable[keywordPath]
if photos == nil then
keywordTable[keywordPath] = {}
photos = keywordTable[keywordPath]
end
photos[#photos + 1] = photo
end
end
else -- gotta go through all of 'em.
--]]
local addKids -- forward reference
local function addKid( parentPath, kid )
local photos = kid:getPhotos()
local keywordPath = parentPath.."/"..kid:getName() -- self:_getKeywordPath( kid )
if #photos > 0 or inclEmpties then
if limited then
local include = {}
for i, photo in ipairs( photos ) do
if limited[photo] then
include[#include + 1] = photo
end
end
if #include > 0 or inclEmpties then
keywordTable[keywordPath] = include
else
app:logv( "Keyword has no photos in the target set - ignoring '^1'", keywordPath )
end
else
keywordTable[keywordPath] = photos
end
else
app:logv( "Keyword has no photos - ignoring '^1'", keywordPath )
end
addKids( parentPath.."/"..kid:getName(), kid:getChildren() )
end
function addKids( parentPath, kids ) -- local
for i, kid in ipairs( kids ) do
addKid( parentPath, kid )
end
end
addKids( "", catalog:getKeywords() )
--end
-- 2nd phase:
local b = {} -- line buffer.
local sortFunc
local sort
local function customSort( one, two )
--Debug.logn( LrPathUtils.leafName( one ), LrPathUtils.leafName( two ) )
return sortFunc {
keywordTable = keywordTable,
keywordPathOne = one,
keywordPathTwo = two
}
end
sortFunc = app:getPref{ name='sortFunc', expectedType='function', default=nil }
if not sortFunc then
app:log( "Using default keyword sort order." )
sort = function( one, two )
if LrPathUtils.leafName( two ) > LrPathUtils.leafName( one ) then return true end
end
else
app:log( "Using custom keyword sort order." )
sort = customSort
end
local inclBlanks = app:getPref( 'includeBlankLines' )
local kwCount = tab:countItems( keywordTable )
local index = 0
local photoSeen = {}
local sep = app:getPref( 'separator' )
for keywordPath, photos in tab:sortedPairs( keywordTable, sort ) do
call:setPortionComplete( index, kwCount )
index = index + 1
repeat
assert( #photos > 0 or inclEmpties, "?" )
local stats = Call:newStats{ 'nil', '0', '1', '2', '3', '4', '5', 'bad' } -- per-keyword stats.
local maxRating = 0
b[#b + 1] = "" -- reserve slot for hdr.
local hdrIndex = #b
for i, photo in ipairs( photos ) do
if inclPhotos then
b[#b + 1] = cat:getPhotoNameDisp( photo, true, cache )
end
local rating = cache:getRawMetadata( photo, 'rating' )
if rating ~= nil then
local sRating = str:to( rating )
if rating ~= 0 then
if rating <= 5 then
local stars = string.rep( '*', rating )
stats:incrStat( sRating )
call:incrStat( sRating )
b[#b] = b[#b].." "..stars
if rating > maxRating then
maxRating = rating
end
else
stats:incrStat( 'bad' )
if not photoSeen[photo] then
call:incrStat( 'bad' )
end
end
else
stats:incrStat( '0' )
if not photoSeen[photo] then
call:incrStat( '0' )
end
end
else
stats:incrStat( 'nil' )
if not photoSeen[photo] then
call:incrStat( 'nil' )
end
end
photoSeen[photo] = true
end
local rb = {}
if stats:getStat( 'nil' ) > 0 then
rb[#rb + 1] = str:fmtx( "unrated: ^1", stats:getStat( 'nil' ) )
end
if stats:getStat( '0' ) > 0 then
rb[#rb + 1] = str:fmtx( "0: ^1", stats:getStat( '0' ) )
end
if stats:getStat( '1' ) > 0 then
rb[#rb + 1] = str:fmtx( "* ^1", stats:getStat( '1' ) )
end
if stats:getStat( '2' ) > 0 then
rb[#rb + 1] = str:fmtx( "** ^1", stats:getStat( '2' ) )
end
if stats:getStat( '3' ) > 0 then
rb[#rb + 1] = str:fmtx( "*** ^1", stats:getStat( '3' ) )
end
if stats:getStat( '4' ) > 0 then
rb[#rb + 1] = str:fmtx( "**** ^1", stats:getStat( '4' ) )
end
if stats:getStat( '5' ) > 0 then
rb[#rb + 1] = str:fmtx( "***** ^1", stats:getStat( '5' ) )
end
if stats:getStat( 'bad' ) > 0 then
rb[#rb + 1] = str:fmtx( "bad rating: ^1", stats:getStat( 'bad' ) )
end
local ratings = table.concat( rb, " | " )
b[hdrIndex] = str:fmtx( "^1 - ^2, max rating: ^3 (^4)", keywordPath, str:nItems( #photos, "photos" ), maxRating, ratings )
if inclPhotos and inclBlanks then
b[#b + 1] = sep
end
until true
if call:isQuit() then
return
end
end
call:setPortionComplete( 1 )
local contents = table.concat( b, sep )
call:setCaption( "Large reports take time to settle into dialog box..." )
local ok = dialog:putTextOnClipboard{ title="Copy Keyword Report To Clipboard", contents=contents, dataName = "Report Info" }
if ok then
app:logv( "You promised text was copied to clipboard." )
else
app:logv( "You may have copied text to clipboard, but wouldn't swear to it." )
end
end, finale=function( call )
if call.status and not call:isCanceled() then
app:log()
app:log( "Totals:" )
app:logStat( "^1 unrated", call:getStat( 'nil' ), "photos" )
for i = 0, 5 do
if call:getStat( str:to( i ) ) > 0 then
app:log( "Rating ^1: ^2", i, str:nItems( call:getStat( str:to( i ) ), "photos" ) )
end
end
app:logStat( "^1 with bad rating value.", call:getStat( 'bad' ), "photos" )
--app:log()
end
--Debug.showLogFile()
end } )
end
return Reportamus
|
-- Copyright (C) 2019 Igara Studio S.A.
--
-- This file is released under the terms of the MIT license.
-- Read LICENSE.txt for more information.
local fs = app.fs
local sep = fs.pathSeparator
assert('' == fs.filePath('first.png'))
assert('path' == fs.filePath('path/second.png'))
assert('C:\\path' == fs.filePath('C:\\path\\third.png'))
assert('first.png' == fs.fileName('first.png'))
assert('second.png' == fs.fileName('path/second.png'))
assert('third.png' == fs.fileName('C:\\path\\third.png'))
assert('png' == fs.fileExtension('path/file.png'))
assert('first' == fs.fileTitle('first.png'))
assert('second' == fs.fileTitle('path/second.png'))
assert('third' == fs.fileTitle('C:\\path\\third.png'))
assert('first' == fs.filePathAndTitle('first.png'))
assert('path/second' == fs.filePathAndTitle('path/second.png'))
assert('C:\\path\\third' == fs.filePathAndTitle('C:\\path\\third.png'))
assert('hi/bye' == fs.joinPath('hi/', 'bye'))
assert('hi/bye' .. sep .. 'smth.png' == fs.joinPath('hi/', 'bye', 'smth.png'))
local pwd = fs.currentPath
assert(pwd ~= nil)
assert(fs.isDirectory(pwd))
assert(not fs.isFile(pwd))
assert(fs.isFile(fs.joinPath(pwd, 'run-tests.sh')))
do
local runTestsFound = false
local readmeFound = false
local files = fs.listFiles(pwd)
for i in pairs(files) do
if files[i] == 'run-tests.sh' then
runTestsFound = true
elseif files[i] == 'README.md' then
readmeFound = true
end
local fullFs = fs.joinPath(pwd, files[i])
if fs.isFile(fullFs) then
assert(fs.fileSize(fullFs) > 0)
end
end
assert(runTestsFound)
assert(readmeFound)
end
-- Create directories
do
assert(fs.makeDirectory("_tmp"))
assert(fs.isDirectory("_tmp"))
assert(fs.makeAllDirectories("_tmp/a/b"))
assert(fs.isDirectory("_tmp/a"))
assert(fs.isDirectory("_tmp/a/b"))
assert(fs.removeDirectory("_tmp/a/b"))
assert(not fs.isDirectory("_tmp/a/b"))
assert(fs.isDirectory("_tmp/a"))
assert(not fs.removeDirectory("_tmp")) -- Should fail
assert(fs.isDirectory("_tmp/a"))
assert(fs.isDirectory("_tmp"))
assert(fs.removeDirectory("_tmp/a"))
assert(fs.removeDirectory("_tmp"))
assert(not fs.isDirectory("_tmp/a"))
assert(not fs.isDirectory("_tmp"))
end
|
return {
["quiet"] = true,
["compress"] = "bz2"
}
|
local cfg = {}
-- define market types like garages and weapons
-- _config: blipid, blipcolor, permissions (optional, only users with the permission will have access to the market)
cfg.market_types = {
["Mercado"] = {
_config = {blipid=52, blipcolor=2},
-- list itemid => price
-- Drinks
["milk"] = 2,
["water"] = 2,
["coffee"] = 4,
["tea"] = 4,
["icetea"] = 8,
["orangejuice"] = 8,
["gocagola"] = 12,
["redgull"] = 12,
["lemonlimonad"] = 14,
["vodka"] = 30,
--Food
["bread"] = 2,
["donut"] = 2,
["tacos"] = 8,
["sandwich"] = 14,
["kebab"] = 20,
["pdonut"] = 65,
},
["Samu"] = {
_config = {blipid=403, blipcolor=49, permissions={"emergency.market"}},
["medkit"] = 0,
["dipiroca"] = 0,
["nocucedin"] = 0,
["paracetanal"] = 0,
["decupramim"] = 0,
["buscopau"] = 0,
["navagina"] = 0,
["analdor"] = 0,
["sefodex"] = 0,
["phodac"] = 0,
["danec"] = 0,
["cotovelol"]= 0,
["nokusin"] = 0,
["viagral"] = 0,
["glicoanal"] = 0,
["quigosado"] = 0
},
["Ferramentas"] = {
_config = {blipid=255, blipcolor=5},
["scubagear"] = 5000,
["algemas"] = 500,
["vendaolhos"] = 200,
},
["Mecanico"] = {
_config = {blipid=402, blipcolor=47, permissions={"repair.market"}},
["repairkit"] = 50
}
}
-- list of markets {type,x,y,z}
cfg.markets = {
{"Mercado",128.1410369873, -1286.1120605469, 29.281036376953},
{"Mercado",-47.522762298584,-1756.85717773438,29.4210109710693},
{"Mercado",25.7454013824463,-1345.26232910156,29.4970207214355},
{"Mercado",1135.57678222656,-981.78125,46.4157981872559},
{"Mercado",1163.53820800781,-323.541320800781,69.2050552368164},
{"Mercado",374.190032958984,327.506713867188,103.566368103027},
{"Mercado",2555.35766601563,382.16845703125,108.622947692871},
{"Mercado",2676.76733398438,3281.57788085938,55.2411231994629},
{"Mercado",1960.50793457031,3741.84008789063,32.3437385559082},
{"Mercado",1393.23828125,3605.171875,34.9809303283691},
{"Mercado",1166.18151855469,2709.35327148438,38.15771484375},
{"Mercado",547.987609863281,2669.7568359375,42.1565132141113},
{"Mercado",1698.30737304688,4924.37939453125,42.0636749267578},
{"Mercado",1729.54443359375,6415.76513671875,35.0372200012207},
{"Mercado",-3243.9013671875,1001.40405273438,12.8307056427002},
{"Mercado",-2967.8818359375,390.78662109375,15.0433149337769},
{"Mercado",-3041.17456054688,585.166198730469,7.90893363952637},
{"Mercado",-1820.55725097656,792.770568847656,138.113250732422},
{"Mercado",-1486.76574707031,-379.553985595703,40.163387298584},
{"Mercado",-1223.18127441406,-907.385681152344,12.3263463973999},
{"Mercado",-707.408996582031,-913.681701660156,19.2155857086182},
{"Samu", 310.36694335938,-598.89642333984,43.291820526123},
{"Mecanico",-231.54925537109,-1378.5734863281,31.258247375488},
{"Ferramentas",22.58203125,-1109.8516845703,29.793336868286}
}
return cfg
|
function on_activate(parent, ability)
local targets = parent:targets():hostile():visible()
local targeter = parent:create_targeter(ability)
targeter:set_selection_visible()
targeter:add_all_selectable(targets)
targeter:add_all_effectable(targets)
targeter:activate()
end
function on_target_select(parent, ability, targets)
local target = targets:first()
ability:activate(parent)
game:play_sfx("sfx/disenchant")
local stats = parent:stats()
local amount = 10 + stats.caster_level / 2 + stats.intellect_bonus / 4
local effect = target:create_effect(ability:name(), ability:duration())
effect:set_tag("assay")
effect:add_num_bonus("defense", -amount)
effect:add_num_bonus("fortitude", -amount)
effect:add_num_bonus("reflex", -amount)
effect:add_num_bonus("will", -amount)
if parent:ability_level(ability) > 1 then
effect:add_num_bonus("armor", -5 - stats.caster_level - stats.intellect_bonus / 3)
end
local gen = target:create_particle_generator("arrow_down")
gen:set_moves_with_parent()
gen:set_position(gen:param(0.0), gen:param(-1.5))
gen:set_particle_size_dist(gen:fixed_dist(0.5), gen:fixed_dist(0.5))
gen:set_gen_rate(gen:param(6.0))
gen:set_particle_position_dist(gen:dist_param(gen:uniform_dist(-0.7, 0.7), gen:uniform_dist(-0.1, 0.1)),
gen:dist_param(gen:fixed_dist(0.0), gen:uniform_dist(1.0, 1.5)))
gen:set_particle_duration_dist(gen:fixed_dist(0.75))
gen:set_color(gen:param(1.0), gen:param(0.2), gen:param(0.1))
effect:add_anim(gen)
effect:apply()
end
|
object_tangible_meatlump_event_meatlump_weapon_palette_01_03 = object_tangible_meatlump_event_shared_meatlump_weapon_palette_01_03:new {
}
ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_weapon_palette_01_03, "object/tangible/meatlump/event/meatlump_weapon_palette_01_03.iff")
|
-- fixparse.lua
--
-- Uses BitMaul to handle FIX ASCII
--
local FixFields = require'fixtypes'
-- The dissector ; tells PDURecord about message boundaries.
--
local FixDissector = {
-- how to get the next record
-- 1st we get message length 9=??
-- 2nd we determine PDU ends at message_length from above
--
what_next = function( tbl, pdur, swbuf)
if tbl.state=='init' then
pdur:want_to_pattern("9=%d+\1")
elseif tbl.state=='get_full_record' then
pdur:want_next(tbl.moredata)
end
end,
-- handle a reassembled record
-- we just print the fields here
on_record = function( tbl, pdur, strbuf)
if tbl.state=='init' then
tbl.state='get_full_record'
tbl.header = strbuf
-- msg size 9=88
local f,l,bytes = strbuf:find("9=(%d+)\1")
tbl.moredata = tonumber(bytes) + 7
elseif tbl.state=='get_full_record' then
tbl.state='init'
local resource={}
for k,v in strbuf:gmatch("(%w+)=([^\1]+)\1") do
resource[#resource+1] = (FixFields[k].."="..v)
end
-- generate a Resource - in Trisul a LOG entry is a RESOURCE
--
if pdur.engine then
pdur.engine:add_resource("{7D1B9296-BF19-403C-0497-E002FEBB385B}",pdur.flowkey:id(),
"FIX log", table.concat(resource,","))
else
print("-------------------------")
print(table.concat(resource,"\n"))
end
end
end ,
}
-- so return a new dissector
--
return {
new= function(key)
local p = setmetatable( {state="init", moredata=0}, { __index = FixDissector})
return p
end
}
|
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
-- INSTALL: CINEMA
-- weapon_vape_american.lua
-- Defines a vape which emits red, white, and blue clouds and plays Donald Trump sounds
-- Vape SWEP by Swamp Onions - http://steamcommunity.com/id/swamponions/
if CLIENT then
include('weapon_vape/cl_init.lua')
else
include('weapon_vape/shared.lua')
end
SWEP.PrintName = "American Vape"
SWEP.Instructions = "LMB: Rip Fat Clouds\n (Hold and release)\nRMB: Bing Bong\nReload: MAGA\n\nA patriotic vape made in honor of President Trump."
SWEP.VapeID = 7
SWEP.VapeAccentColor = Vector(0.5, 0.5, 0.5)
--tells the matproxy to substitute red/white/blue fader (todo: change how this works)
SWEP.VapeTankColor = Vector(-2, -2, -2)
function SWEP:SecondaryAttack()
--this makes it so the "bing bong" sounds the same to everyone instead of the owner hearing a different noise due to randomness
if CLIENT then
return
else
SuppressHostEvents(NULL)
end
if GetConVar("vape_block_sounds"):GetBool() then return end
local pitch = 100 + (self.SoundPitchMod or 0) + (self.Owner:Crouching() and 40 or 0) + math.Rand(-25, 25)
self:ExtEmitSound("vapebing" .. tostring(math.random(1, 2)) .. ".wav", {
pitch = pitch,
speech = -1
})
end
function SWEP:Reload()
if GetConVar("vape_block_sounds"):GetBool() then return end
if self.reloading then return end
self.reloading = true
timer.Simple(0.5, function()
self.reloading = false
end)
local pitch = 100 + (self.SoundPitchMod or 0) + (self.Owner:Crouching() and 40 or 0)
self:ExtEmitSound("vapemaga.wav", {
pitch = pitch,
speech = -1
})
end
|
return function()
local CoreGui = game:GetService("CoreGui")
local CorePackages = game:GetService("CorePackages")
local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies)
local Roact = InGameMenuDependencies.Roact
local Rodux = InGameMenuDependencies.Rodux
local RoactRodux = InGameMenuDependencies.RoactRodux
local UIBlox = InGameMenuDependencies.UIBlox
local InGameMenu = script.Parent.Parent.Parent
local Localization = require(InGameMenu.Localization.Localization)
local LocalizationProvider = require(InGameMenu.Localization.LocalizationProvider)
local reducer = require(InGameMenu.reducer)
local AppDarkTheme = require(CorePackages.AppTempCommon.LuaApp.Style.Themes.DarkTheme)
local AppFont = require(CorePackages.AppTempCommon.LuaApp.Style.Fonts.Gotham)
local appStyle = {
Theme = AppDarkTheme,
Font = AppFont,
}
local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local GetFixGraphicsQuality = require(RobloxGui.Modules.Flags.GetFixGraphicsQuality)
local SendNotificationInfo = Instance.new("BindableEvent")
SendNotificationInfo.Name = "SendNotificationInfo"
SendNotificationInfo.Parent = RobloxGui
local GraphicsQualityEntry = require(script.Parent.GraphicsQualityEntry)
local UserGameSettings = UserSettings():GetService("UserGameSettings")
local RenderSettings = settings().Rendering
it("should create and destroy without errors", function()
local element = Roact.createElement(RoactRodux.StoreProvider, {
store = Rodux.Store.new(reducer)
}, {
ThemeProvider = Roact.createElement(UIBlox.Core.Style.Provider, {
style = appStyle,
}, {
LocalizationProvider = Roact.createElement(LocalizationProvider, {
localization = Localization.new("en-us"),
}, {
GraphicsQualityEntry = Roact.createElement(GraphicsQualityEntry, {
LayoutOrder = 2,
}),
}),
}),
})
local instance = Roact.mount(element)
UserGameSettings.SavedQualityLevel = 10
RenderSettings.QualityLevel = 5
Roact.unmount(instance)
end)
it("should set the rendering setting to the saved quality level when initalized", function()
local element = Roact.createElement(RoactRodux.StoreProvider, {
store = Rodux.Store.new(reducer)
}, {
ThemeProvider = Roact.createElement(UIBlox.Core.Style.Provider, {
style = appStyle,
}, {
LocalizationProvider = Roact.createElement(LocalizationProvider, {
localization = Localization.new("en-us"),
}, {
GraphicsQualityEntry = Roact.createElement(GraphicsQualityEntry, {
LayoutOrder = 2,
}),
}),
}),
})
if GetFixGraphicsQuality() then
UserGameSettings.GraphicsQualityLevel = 11
local instance = Roact.mount(element)
expect(RenderSettings.QualityLevel).to.equal(Enum.QualityLevel.Level11)
Roact.unmount(instance)
UserGameSettings.GraphicsQualityLevel = 21
instance = Roact.mount(element)
expect(RenderSettings.QualityLevel).to.equal(Enum.QualityLevel.Level21)
Roact.unmount(instance)
else
UserGameSettings.SavedQualityLevel = Enum.SavedQualitySetting.QualityLevel2
local instance = Roact.mount(element)
expect(RenderSettings.QualityLevel).to.equal(Enum.QualityLevel.Level03)
Roact.unmount(instance)
UserGameSettings.SavedQualityLevel = Enum.SavedQualitySetting.QualityLevel10
instance = Roact.mount(element)
expect(RenderSettings.QualityLevel).to.equal(Enum.QualityLevel.Level21)
Roact.unmount(instance)
end
end)
end
|
-- craft ui
-- global CraftList
local entity_name=Pow.currentFile()
local _=BaseEntity.new(entity_name,true)
local _craftables=nil
--_.drawUnscaledUi=function()
-- love.graphics.print(entity_name.."unscaled")
--end
_.draw_ui=function()
-- overlay
love.graphics.setColor(0, 0.2, 0.2, 0.8)
local width, height = love.window.getMode( )
love.graphics.rectangle("fill",0,0,width,height)
love.graphics.setColor( 1, 1, 1, 1)
-- items
local x=16
local y=16
for k,craftable in pairs(_craftables) do
local craftable_name=craftable.name
local icon=Img.get(craftable_name)
love.graphics.draw(icon,x,y)
-- todo: not calc this at draw
craftable.x=x
craftable.y=y
craftable.w=icon:getWidth()
craftable.h=icon:getHeight()
love.graphics.rectangle("line", x, y,craftable.w, craftable.h)
y=y+24
end
-- love.graphics.print("wasted",94,116)
end
_.set=function(craftables)
_craftables=craftables
end
_.mouse_pressed_exclusive=true
local _is_open=false
_.open=function()
if _is_open then return end
Entity.add(CraftList)
_is_open=true
end
_.close=function()
if not _is_open then return end
Entity.remove(CraftList)
_is_open=false
end
_.mousePressed=function(gameX,gameY,button,istouch)
if button~=1 then
_.close()
end
local ui_x,ui_y=Pow.get_ui_coords(gameX,gameY)
-- todo: generic bbox hit
for k,craftable in pairs(_craftables) do
local x1=craftable.x
local x2=x1+craftable.w
if ui_x>x1 and ui_x<x2 then
local y1=craftable.y
local y2=y1+craftable.h
if ui_y>y1 and ui_y<y2 then
log("clicked:"..craftable.name)
-- todo: lock until server response
local event=Event.new("craft_request")
event.target="server"
event.craftable=craftable
Event.process(event)
end
end
end
end
return _
|
require "helper"
function AmielF2()
activateWin(AmielWin)
delay(100)
pressFx(AmielWin,2)
-- if getWindowCount()>2 then
-- activateWin(AmielWin)
-- delay(100)
-- pressFx(AmielWin,2)
--end
activateWin(MainWin)
end;
function AmielMana()
activateWin(AmielWin)
delay(100)
pressFx(AmielWin,1)
-- if getWindowCount()>2 then
-- activateWin(AmielWin)
-- delay(100)
-- pressFx(AmielWin,2)
--end
activateWin(MainWin)
end
registerHotKey("ctrl+q","AmielF2");
registerHotKey("ctrl+e","AmielMana");
|
test_run = require('test_run').new()
engine = test_run:get_cfg('engine')
_ = box.space._session_settings:update('sql_default_engine', {{'=', 2, engine}})
-- Forbid multistatement queries.
box.execute('select 1;')
box.execute('select 1; select 2;')
box.execute('create table t1 (id INT primary key); select 100;')
box.space.t1 == nil
box.execute(';')
box.execute('')
box.execute(' ;')
box.execute('\n\n\n\t\t\t ')
-- gh-3820: only table constraints can have a name.
--
box.execute('CREATE TABLE test (id INTEGER PRIMARY KEY, b INTEGER CONSTRAINT c1 NULL)')
box.execute('CREATE TABLE test (id INTEGER PRIMARY KEY, b INTEGER CONSTRAINT c1 DEFAULT 300)')
box.execute('CREATE TABLE test (id INTEGER PRIMARY KEY, b TEXT CONSTRAINT c1 COLLATE "binary")')
-- Make sure that type of literals in meta complies with its real
-- type. For instance, typeof(0.5) is number, not integer.
--
box.execute('SELECT 1;')
box.execute('SELECT 1.5;')
box.execute('SELECT 1.0;')
box.execute('SELECT 1.5e0;')
box.execute('SELECT 1e0;')
box.execute('SELECT \'abc\';')
box.execute('SELECT X\'4D6564766564\'')
--
-- gh-4139: assertion when reading a temporary space.
--
format = {{name = 'id', type = 'integer'}}
s = box.schema.space.create('s',{format=format, temporary=true})
i = s:create_index('i')
box.execute('select * from "s"')
s:drop()
--
-- gh-4267: Full power of vdbe_field_ref
-- Tarantool's SQL internally stores data offset for all acceded
-- fields. It also keeps a bitmask of size 64 with all initialized
-- slots in actual state to find the nearest left field really
-- fast and parse tuple from that position. For fieldno >= 64
-- bitmask is not applicable, so it scans data offsets area in
-- a cycle.
--
-- The test below covers a case when this optimisation doesn't
-- work and the second lookup require parsing tuple from
-- beginning.
---
format = {}
t = {}
for i = 1, 70 do \
format[i] = {name = 'FIELD'..i, type = 'unsigned'} \
t[i] = i \
end
s = box.schema.create_space('TEST', {format = format})
pk = s:create_index('pk', {parts = {70}})
s:insert(t)
box.execute('SELECT field70, field64 FROM test')
-- In the case below described optimization works fine.
pk:alter({parts = {66}})
box.execute('SELECT field66, field68, field70 FROM test')
box.space.TEST:drop()
-- gh-4933: Make sure that autoindex optimization is used.
box.execute('CREATE TABLE t1(i INT PRIMARY KEY, a INT);')
box.execute('CREATE TABLE t2(i INT PRIMARY KEY, b INT);')
for i = 1, 10240 do\
box.execute('INSERT INTO t1 VALUES ($1, $1);', {i})\
box.execute('INSERT INTO t2 VALUES ($1, $1);', {i})\
end
box.execute('EXPLAIN QUERY PLAN SELECT a, b FROM t1, t2 WHERE a = b;')
-- gh-5592: Make sure that diag is not changed with the correct query.
box.execute('SELECT a;')
diag = box.error.last()
box.execute('SELECT * FROM (VALUES(true));')
diag == box.error.last()
-- exclude_null + SQL correctness
box.execute([[CREATE TABLE j (s1 INT PRIMARY KEY, s2 STRING, s3 VARBINARY)]])
s = box.space.J
i = box.space.J:create_index('I3',{parts={2,'string', exclude_null=true}})
box.execute([[INSERT INTO j VALUES (1,NULL,NULL), (2,'',X'00');]])
box.execute([[SELECT * FROM j;]])
box.execute([[SELECT * FROM j INDEXED BY I3;]])
box.execute([[SELECT COUNT(*) FROM j GROUP BY s2;]])
box.execute([[SELECT COUNT(*) FROM j INDEXED BY I3;]])
box.execute([[UPDATE j INDEXED BY i3 SET s2 = NULL;]])
box.execute([[INSERT INTO j VALUES (3, 'a', X'33');]])
box.execute([[SELECT * FROM j;]])
box.execute([[SELECT * FROM j INDEXED BY I3;]])
box.execute([[UPDATE j INDEXED BY i3 SET s3 = NULL;]])
s:select{}
s:drop()
|
-- Script Description
fx_version 'cerulean'
games { 'gta5' }
author 'lowheartrate & Slyforn'
description 'Street Label by lowheartrate'
version '1.1.0'
-- Client Scripts
client_scripts {
'configuration.lua',
'client.lua'
}
ui_page('html/index.html')
files({
'html/index.html',
'html/listener.js',
'html/styles.css',
'html/font-face.css',
'html/dynamic.css'
})
|
local image = require 'image'
local path = require 'path'
local function newwriter()
return {
bytes = {},
write8 = function( self, x )
self.bytes[ #self.bytes + 1 ] = string.char( x & 255 )
end,
write16 = function( self, x )
self.bytes[ #self.bytes + 1 ] = string.char( ( x >> 8 ) & 255, x & 255 )
end,
write32 = function( self, x )
self.bytes[ #self.bytes + 1 ] = string.char( ( x >> 24 ) & 255, ( x >> 16 ) & 255, ( x >> 8 ) & 255, x & 255 )
end,
append = function( self, rle )
self.bytes[ #self.bytes + 1 ] = table.concat( rle.bytes )
end,
get = function( self )
self.bytes = { table.concat( self.bytes ) }
return self.bytes[ 1 ]
end,
size = function( self )
self.bytes = { table.concat( self.bytes ) }
return #self.bytes[ 1 ]
end,
save = function( self, name )
local file, err = io.open( name, 'wb' )
if not file then error( err ) end
self.bytes = { table.concat( self.bytes ) }
file:write( self.bytes[ 1 ] )
file:close()
end
}
end
local function rgbto16( r, g, b )
r = r * 31 // 255
g = g * 63 // 255
b = b * 31 // 255
return ( r << 11 ) | ( g << 5 ) | b
end
local function getpixel( png, x, y, transp )
local r, g, b, a = image.split( png:getPixel( x, y ) )
local c = rgbto16( r, g, b )
if c == transp then
r, g, b, a = 0, 0, 0, 0
end
if a >= 0 and a <= 31 then
a = 0 -- transparent
elseif a >= 32 and a <= 95 then
a = 1 -- 25%
elseif a >= 96 and a <= 159 then
a = 2 -- 50%
elseif a >= 160 and a <= 223 then
a = 3 -- 75%
else
a = 4 -- opaque
end
return rgbto16( r, g, b ), a
end
local function rlerow( png, y, limit, transp )
local rle = {}
local width = png:getWidth()
local used = 0
local numcols = ( width + ( limit - 1 ) ) // limit
for i = 1, numcols do
rle[ #rle + 1 ] = 0
end
for xx = 0, width - 1, limit do
rle[ xx // limit + 1 ] = #rle
local x = xx
rle[ #rle + 1 ] = 0
local runs = #rle
while x < ( xx + limit ) and x < width do
local _, a = getpixel( png, x, y, transp )
local count = 0
local xsave = x
while x < ( xx + limit ) and x < width do
local c, aa = getpixel( png, x, y, transp )
if aa ~= a then
break
end
count = count + 1
x = x + 1
end
rle[ #rle + 1 ] = ( a << 13 | count )
rle[ runs ] = rle[ runs ] + 1
if a ~= 0 then
for i = 0, count - 1 do
local c = getpixel( png, xsave + i, y, transp )
rle[ #rle + 1 ] = c
used = used + 1
end
end
end
end
local final = newwriter()
for i = 1, #rle do
final:write16( rle[ i ] )
end
return final, used
end
local function rleimage( png, limit, transp )
local width, height = png:getSize()
local rows = {}
local used = 0
limit = limit or 1e10
for y = 0, height - 1 do
local row, u = rlerow( png, y, limit, transp )
rows[ y ] = row
used = used + u
end
local rle = newwriter()
rle:write16( width )
rle:write16( height )
rle:write32( used )
local count = 0
for y = 0, height - 1 do
rle:write32( count )
count = count + rows[ y ]:size()
end
for y = 0, height - 1 do
rle:append( rows[ y ] )
end
return rle
end
local function main( args )
if #args == 0 then
io.write[[
RLE-encodes an image to a format ready to be used with rl_image_create. The
--margin argument should be given, and must be the same as the value of the
RL_BACKGRND_MARGIN when retroluxury was compiled. If it's not given, the image
is still valid, but it must be entirely contained within the background
boundaries when blit.
Usage: luai rlrle.lua [ options ] <image>
--transp r g b makes the given color transparent
--tl makes the color at (0,0) transparent
--bl makes the color at (0,height-1) transparent
--tr makes the color at (width-1,0) transparent
--br makes the color at (width-1,height-1) transparent
--margin x sets the pixel limit on RLE runs on a row
(must be equal to RL_BACKGRND_MARGIN)
]]
return 0
end
local name, limit, transp
for i = 1, #args do
if args[ i ] == '--transp' then
transp = rgbto16( tonumber( args[ i + 1 ] ), tonumber( args[ i + 2 ] ), tonumber( args[ i + 3 ] ) )
i = i + 3
elseif args[ i ] == '--tl' or args[ i ] == '--bl' or args[ i ] == '--tr' or args[ i ] == '--br' then
transp = args[ i ]
elseif args[ i ] == '--margin' then
limit = tonumber( args[ i + 1 ] )
i = i + 1
else
name = args[ i ]
end
end
name = path.realpath( name )
local png = image.load( name )
if transp == '--tl' then
transp = rgbto16( image.split( png:getPixel( 0, 0 ) ) )
elseif transp == '--bl' then
transp = rgbto16( image.split( png:getPixel( 0, png:getHeight() - 1 ) ) )
elseif transp == '--tr' then
transp = rgbto16( image.split( png:getPixel( png:getWidth() - 1, 0 ) ) )
elseif transp == '--br' then
transp = rgbto16( image.split( png:getPixel( png:getWidth() - 1, png:getHeight() - 1 ) ) )
end
local rle = rleimage( png, limit, transp )
local dir, name, ext = path.split( name )
rle:save( dir .. path.separator .. name .. '.rle' )
return 0
end
return main, rleimage
|
return {
fadeOut = 1.5,
mode = 2,
id = "HUAPOHAIKONGZHIYI1",
once = true,
fadeType = 2,
fadein = 1.5,
scripts = {
{
say = "塞潘岛西侧海域 午后",
side = 2,
bgName = "bg_map_maliyana",
dir = 1,
bgmDelay = 1,
bgm = "level",
flashin = {
delay = 0.5,
dur = 0.5,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107230,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 102090,
dir = 1,
nameColor = "#a9f548",
say = "怎么了,普林斯顿,你看起来不是很高兴啊。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 2,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
nameColor = "#a9f548",
say = "克利夫兰,我们现在的策略…是不是有些太保守了?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107230,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "明明已经占领了塞潘岛,却只是在周围摆好架势等待重樱的进攻...",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
nameColor = "#a9f548",
say = "以我们现在的实力,完全可以主动出击。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102140,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "嗯,大姐头,我也觉得现在正应该是进攻的时候!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
},
action = {
{
type = "shake",
y = 45,
delay = 0,
dur = 0.15,
x = 0,
number = 2
}
}
},
{
actor = 102090,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "轻敌可是大忌哦?普林斯顿,蒙彼利埃。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 102090,
dir = 1,
nameColor = "#a9f548",
say = "三天前我们接到了潜艇部队传来的目击报告,现在重樱的舰队肯定已经抵达周边海域了。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102090,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "虽然我也觉得主动出击不坏,不过,既然司令部已经选择了更加稳妥的策略,我们就安心防守吧~",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 102230,
dir = 1,
nameColor = "#a9f548",
say = "在无法掌握具体位置的情况下,我也觉得采取防守的策略更为稳妥。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102230,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "在这片大海上,从来不缺乏以少胜多的战役……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102140,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "我明白了,大姐头...",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107230,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "嗯…如果萨拉托加前辈在这里,她会怎么选择呢......",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "看来大家对司令部采取防守态势的布局有些想法啊。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
nameColor = "#a9f548",
say = "企业,你听到了啊......",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 2,
side = 2,
bgName = "bg_map_maliyana",
actor = 107060,
dir = 1,
nameColor = "#a9f548",
say = "我也不是不能理解大家的想法。AF战役之后,我们一路顺利反攻到这里,如今所有人都充满了燃烧的战意和必胜的信心,我也不例外。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "但是,正因如此,我们才更加不能松懈。越是接近胜利之时,越是要绷紧神经,绝对不能因轻敌而给敌人可乘之机。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 3,
side = 2,
bgName = "bg_map_maliyana",
actor = 107060,
dir = 1,
nameColor = "#a9f548",
say = "不然,我们之前的一切努力将因不慎而付诸东流。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107230,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "你说的没错。抱歉,是我有些心急了...",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "呵呵,我还没说完呢。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 3,
side = 2,
bgName = "bg_map_maliyana",
actor = 107060,
dir = 1,
nameColor = "#a9f548",
say = "虽然司令部的策略是稳健防守,但一味固守也不是白鹰的风格。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "我身为第三支队的旗舰,在接到总攻的命令之前必须驻守此处。不过我和其他支队的队长商量后,决定分派一些舰队先行清理周边岛屿上的机场,为总攻清扫障碍。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "普林斯顿,这个任务交给你可以么?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 2,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
nameColor = "#a9f548",
say = "哎?!没问题,请放心交给我吧!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "很好。然后是护卫舰...克利夫兰,我想让你们姐妹中的一艘加上里诺共同作为普利斯顿的护卫,你有什么想法吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102140,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "大姐头,我可以去么?!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
},
action = {
{
type = "shake",
y = 45,
delay = 0,
dur = 0.15,
x = 0,
number = 2
}
}
},
{
expression = 4,
side = 2,
bgName = "bg_map_maliyana",
actor = 102090,
dir = 1,
nameColor = "#a9f548",
say = "唔…我想…还是让伯明翰去。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
hideOther = true,
nameColor = "#a9f548",
bgName = "bg_map_maliyana",
side = 0,
dir = 1,
actor = 102230,
actorName = "伯明翰&蒙彼利埃",
say = "欸?!",
dialogShake = {
speed = 0.09,
x = 10,
number = 2
},
subActors = {
{
actor = 102140,
pos = {
x = 1185
}
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 102090,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "蒙彼利埃,你的急性子要好好治一治才行,这次就留在我身边吧!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 102090,
dir = 1,
nameColor = "#a9f548",
say = "而伯明翰呢,你平时太谨慎了,偶尔也要主动一点才行啊。没问题吧?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 1,
side = 2,
bgName = "bg_map_maliyana",
actor = 102230,
dir = 1,
nameColor = "#a9f548",
say = "既然大姐头这么说的话……我没问题。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "那好,就这么决定了。普林斯顿,里诺,伯明翰,你们的任务是清理周边岛屿上的重樱机场。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 107060,
side = 2,
bgName = "bg_map_maliyana",
nameColor = "#a9f548",
dir = 1,
say = "如果遭遇敌方主力舰队的话,也不用勉强。向司令部发消息,我们随后就到。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 2,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
nameColor = "#a9f548",
say = "是!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
expression = 3,
side = 2,
bgName = "bg_map_maliyana",
actor = 107230,
dir = 1,
blackBg = true,
nameColor = "#a9f548",
say = "(虽然只是清理岛屿机场这样的小目标......不过终于可以主动出击了!)",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
}
}
}
|
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author.
--]]
local PANEL = {}
local PLUGIN = PLUGIN
function PANEL:Init()
local parent = self
self.updateButton = self:Add("ixNewButton")
self.updateButton:Dock(BOTTOM)
self.updateButton:SetTall(64)
self.updateButton:DockMargin(2,2,2,2)
self.updateButton:SetText("Update Model")
self.character = LocalPlayer():GetCharacter()
self:Dock(FILL)
self.modelDock = self:Add("DPanel")
self.modelDock:Dock(FILL)
self.modelDock:DockMargin(2,2,2,2)
function self.modelDock:Paint()
surface.SetDrawColor(30, 30, 30, 150)
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
surface.SetDrawColor(Color(100, 170, 220, 80))
surface.DrawOutlinedRect(0, 0, self:GetWide(), self:GetTall())
end
self.model = self.modelDock:Add("ixModelPanel")
self.model:Dock(FILL)
self.model:SetFOV(55)
self.buttonDock = self:Add("DScrollPanel")
self.buttonDock:Dock(LEFT)
self.buttonDock:SetWide(512)
self.buttonDock:DockMargin(2,2,2,2)
local buttons = {}
for k, v in ipairs(PLUGIN.config.otaTypes) do
local button = self.buttonDock:Add("ixNewButton")
button.model = v.model
button.arrayIndex = k
button:Dock(TOP)
button:SetHeight(64)
button:DockMargin(2,2,2,2)
button.selected = false
button:SetText(v.name)
button:SetHelixTooltip(function(tooltip)
local name = tooltip:AddRow("description")
name:SetText(v.name)
name:SetImportant()
name:SetFont("ixMediumFont")
name:SizeToContents()
local description = tooltip:AddRow("description")
description:SetText(v.description)
description:SetFont("ixPluginTooltipDescFont")
description:SizeToContents()
if(v.voiceType) then
local division = tooltip:AddRow("description")
division:SetText(string.format("\nThis will set your voice type to '%s'.", v.voiceType))
division:SetFont("ixPluginTooltipDescFont")
division:SizeToContents()
end
end)
function button:DoClick()
for k, v in pairs(buttons) do
v.selected = false
end
parent.arrayIndex = self.arrayIndex
parent.model:SetModel(self.model)
self.selected = true
end
function button:PaintOver()
if(self.selected) then
surface.SetDrawColor(255, 255, 255, 25)
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
end
end
table.insert(buttons, button)
end
function self.updateButton:DoClick()
if(parent.arrayIndex) then
net.Start("ixUpdateOverwatchModel")
net.WriteInt(parent.arrayIndex, 8)
net.SendToServer()
end
if(IsValid(ix.gui.menu)) then
ix.gui.menu:Remove()
end
end
end
function PANEL:Paint()
surface.SetDrawColor(30, 30, 30, 150)
surface.DrawRect(0, 0, self:GetWide(), self:GetTall())
surface.SetDrawColor(Color(100, 170, 220, 80))
surface.DrawOutlinedRect(0, 0, self:GetWide(), self:GetTall())
end
-- Basically a fix to remove the janky model staying on the screen when the menu is closing
function PANEL:Think()
if(ix.gui.menu and ix.gui.menu.bClosing) then
self.model:Remove()
end
end
vgui.Register("ixOutfitMenu", PANEL, "DPanel")
-- Called when all of the tabs are being created.
hook.Add("CreateMenuButtons", "ixOutfitMenu", function(tabs)
if(LocalPlayer():GetCharacter():GetFaction() == FACTION_OTA) then
tabs["outfit"] = {
Create = function(info, container)
ix.gui.outfitMenu = container:Add("ixOutfitMenu")
end,
}
end
end)
|
-- Casts given buff on target
function cast_buff(icon, spellName)
if GetSpellCooldownByName(spellName) ~= 0 then return end
if not is_in_buff_range() then return end
if UnitIsDead("target") then return end
if hasBuff("target", icon) then return end
CastSpellByName(spellName)
end
-- Casts given buff on player
function cast_buff_player(icon, spellName)
if GetSpellCooldownByName(spellName) ~= 0 then return end
if player_hasBuff(icon) then return end
CastSpellByName(spellName)
end
function player_hasBuff(icon)
return hasBuff("player", icon)
end
-- Return whether given target has the given buff
function hasBuff(target, icon)
return getIndexOfBuff(target, icon) ~= -1
end
-- Returns the index of given buff, if the target has it, otherwise -1
function getIndexOfBuff(target, icon)
local i=1
while UnitBuff(target,i) ~= nil do
if "Interface\\Icons\\" .. icon == UnitBuff(target,i) then
return i
end
i=i+1
end
return -1
end
-- Buffs azs.targetList with spell
function buffTargetList(icon, spellName, ltargetList)
ltargetList=ltargetList or azs.targetList.all
for target,info in pairs(ltargetList) do
castBuff(icon, spellName, target)
end
end
function castBuff(icon, spell, target)
if hasBuff(target, icon) then return end
ClearFriendlyTarget()
CastSpellByName(spell)
if IsValidSpellTarget(target) then
SpellTargetUnit(target)
return
end
SpellStopTargeting()
end
function removeBuff(icon)
index = getIndexOfBuff("player", icon)
if index ~= -1 then
CancelPlayerBuff(index)
end
end
|
att.PrintName = "H3 Styled Counter Colored"
att.Icon = Material("snowysnowtime/2k/ico/h3/smg_sil.png")
att.Description = "Halo 3 inspired ammunition counter. Colorable."
att.Desc_Pros = {
}
att.Desc_Cons = {
}
att.SortOrder = 995
att.Slot = "hivk_counter"
att.AttachSound = "attch/snow/halo/h3/x_button.wav"
att.DetachSound = "attch/snow/halo/h3/b_button.wav"
att.ActivateElements = {"h3_c"}
|
local Rand = require("api.Rand")
local Chara = require("api.Chara")
local Ui = require("api.Ui")
local I18N = require("api.I18N")
local Quest = require("mod.elona_sys.api.Quest")
local QuestMap = require("mod.elona.api.QuestMap")
local Map = require("api.Map")
local Calc = require("mod.elona.api.Calc")
local Enum = require("api.Enum")
local Gui = require("api.Gui")
local Input = require("api.Input")
local ElonaQuest = require("mod.elona.api.ElonaQuest")
local Event = require("api.Event")
local IOwned = require("api.IOwned")
local Item = require("api.Item")
local IItem = require("api.item.IItem")
local quest_harvest = {
_type = "base.map_archetype",
_id = "quest_harvest",
starting_pos = function(map, chara, prev)
-- >>>>>>>> shade2/map_rand.hsp:375 gLevelStartOn=mStartSpec ..
return {
x = Rand.rnd(map:width() / 3) + map:width() / 3,
y = Rand.rnd(map:height() / 3) + map:height() / 3
}
-- <<<<<<<< shade2/map_rand.hsp:377 map_placePlayer ..
end,
properties = {
types = { "quest" },
tileset = "elona.wilderness",
-- >>>>>>>> shade2/sound.hsp:413 if gQuest=qHarvest :music=mcVillage1 ...
music = "elona.village1",
-- <<<<<<<< shade2/sound.hsp:412 if gQuest=qHunt :music=mcBattle1 ..
level = 1,
is_indoor = false,
is_temporary = true,
max_crowd_density = 15,
default_ai_calm = "base.calm_null",
shows_floor_count_in_name = true,
prevents_building_shelter = true
}
}
function quest_harvest.on_map_entered(map)
if not Item.find("elona.masters_delivery_chest", "ground", map) then
local player = Chara.player()
local harvest_chest = Item.create("elona.masters_delivery_chest", player.x, player.y, {}, map)
harvest_chest.own_state = Enum.OwnState.NotOwned
end
end
function quest_harvest.chara_filter(map)
-- >>>>>>>> shade2/map.hsp:71 if gQuest>=qHeadRdQuest{ ..
local quest = Quest.get_immediate_quest()
local difficulty = 1
if quest then
difficulty = quest.difficulty
end
local level = Calc.calc_object_level(difficulty, map)
level = math.clamp(level / 4, 1, 8)
return {
level = level,
quality = Calc.calc_object_quality(Enum.Quality.Normal),
tag_filters = {"wild"}
}
-- <<<<<<<< shade2/map.hsp:75 return ..
end
data:add(quest_harvest)
local function is_harvest_great_success(quest)
return quest.params.required_weight * 125 / 100 < quest.params.current_weight
end
local harvest = {
_id = "harvest",
_type = "elona_sys.quest",
_ordering = 60000,
elona_id = 1006,
client_chara_type = 5,
reward = "elona.supply",
reward_fix = 60,
min_fame = 0,
chance = function(client, town)
if town.archetype_id == "elona.yowyn" then
return 2
end
return 30
end,
params = { required_weight = types.number, current_weight = types.number },
difficulty = function()
return math.clamp(Rand.rnd(Chara.player():calc("level") + 5) +
Rand.rnd(Chara.player():calc("fame") / 800 + 1) + 1,
1, 50)
end,
expiration_hours = function() return (Rand.rnd(6) + 2) * 24 end,
generate = function(self, client)
self.reward_fix = 60 + self.difficulty * 2
self.params = {
required_weight = 15000 + self.difficulty * 2500,
current_weight = 0
}
return true
end,
locale_data = function(self, is_active)
local required_weight = Ui.display_weight(self.params.required_weight)
local objective = I18N.get("quest.info.harvest.text", required_weight)
if is_active then
objective = objective .. I18N.get("quest.info.now", Ui.display_weight(self.params.current_weight))
end
return {
objective = objective,
required_weight = required_weight
}
end,
calc_reward_gold = function(self, gold)
-- >>>>>>>> shade2/quest.hsp:456 if qExist(rq)=qHarvest:if qParam1(rq)!0:if qParam ...
if is_harvest_great_success(self) then
gold = math.clamp(gold*self.params.current_weight/self.params.required_weight, gold, gold*3)
end
-- <<<<<<<< shade2/quest.hsp:456 if qExist(rq)=qHarvest:if qParam1(rq)!0:if qParam ..
return gold
end,
on_time_expired = function(self)
-- >>>>>>>> shade2/main.hsp:1625 if gQuest=qHarvest{ ...
if self.params.required_weight < self.params.current_weight then
self.state = "completed"
Gui.mes_c("quest.harvest.complete", "Green")
Input.query_more()
else
self.state = "failed"
Gui.mes_c("quest.harvest.fail", "Purple")
end
-- <<<<<<<< shade2/main.hsp:1635 if gQuest=qConquer{ ..
ElonaQuest.travel_to_previous_map()
end
}
function harvest.on_accept(self)
return true, "elona.quest_harvest:accept"
end
function harvest.on_complete()
return "elona.quest_harvest:complete"
end
data:add(harvest)
data:add {
_type = "elona_sys.dialog",
_id = "quest_harvest",
nodes = {
accept = {
text = "talk.npc.quest_giver.accept.harvest",
on_finish = function(t)
local quest = Quest.for_client(t.speaker)
assert(quest)
local harvest_map = QuestMap.generate_harvest(quest.difficulty)
local current_map = t.speaker:current_map()
local player = Chara.player()
harvest_map:set_previous_map_and_location(current_map, player.x, player.y)
Quest.set_immediate_quest(quest)
-- >>>>>>>> shade2/map_rand.hsp:335 gTimeLimit=120:gCountNotice=9999 ...
Quest.set_immediate_quest_time_limit(quest, 120)
-- <<<<<<<< shade2/map_rand.hsp:334 *map_createDungeonHarvest ..
Map.travel_to(harvest_map)
end
},
complete = {
on_start = function(t)
local quest = Quest.for_client(t.speaker)
assert(quest)
Quest.complete(quest, t.speaker)
end,
text = function(t)
local text = I18N.get("quest.giver.complete.done_well", t.speaker)
-- >>>>>>>> shade2/text.hsp:1252 if qExist(rq)=qHarvest:if qParam1(rq)*125/100<qP ..
local quest = Quest.for_client(t.speaker)
assert(quest)
if is_harvest_great_success(quest) then
text = text .. I18N.space() .. I18N.get("quest.giver.complete.extra_coins", t.speaker)
end
-- <<<<<<<< shade2/text.hsp:1252 if qExist(rq)=qHarvest:if qParam1(rq)*125/100<qP ..
return {text}
end,
jump_to = "elona.default:__start"
}
}
}
local function display_quest_message_harvest(map)
local quest = Quest.get_immediate_quest()
-- >>>>>>>> shade2/map.hsp:2161 if gQuest=qHarvest{ ...
if quest and quest._id == "elona.harvest" then
if quest.params.required_weight <= 0 then
quest.params.required_weight = 15000
quest.reward_gold = 400
end
Gui.mes_c("map.quest.on_enter.harvest", "SkyBlue", Ui.display_weight(quest.params.required_weight), save.elona_sys.quest_time_limit)
end
-- <<<<<<<< shade2/map.hsp:2164 } ..
end
Event.register("base.on_map_entered", "Display quest message (harvest)", display_quest_message_harvest)
local CAN_INCLUDE_QUEST_ITEMS = table.set {
"elona.inv_examine",
"elona.inv_drop",
"elona.inv_get",
"elona.inv_eat",
"elona.inv_harvest_delivery_chest",
}
local function filter_quest_items(_, params, result)
-- >>>>>>>> shade2/command.hsp:3423 if iProperty(cnt)=propQuest:if (invCtrl!1)&(invC ..
local context = params.context
local item = params.item
if item.own_state ~= Enum.OwnState.Quest then
return result
end
local can_include = CAN_INCLUDE_QUEST_ITEMS[context.proto._id]
if can_include == nil then
return false
end
return result
-- <<<<<<<< shade2/command.hsp:3423 if iProperty(cnt)=propQuest:if (invCtrl!1)&(invC ..
end
Event.register("base.on_inventory_context_filter", "Filter quest items in most inventory contexts", filter_quest_items)
local function remove_quest_items_on_leave(_, params, result)
-- >>>>>>>> shade2/quest.hsp:314 if gQuest=qHarvest{ ..
local quest = params.quest
if quest._id ~= "elona.harvest" then
return
end
local player = Chara.player()
local pred = function(i) return i.own_state == Enum.OwnState.Quest end
player:iter_items():filter(pred):each(IItem.remove_ownership)
player:refresh_weight()
-- <<<<<<<< shade2/quest.hsp:320 } ..
end
Event.register("elona_sys.on_quest_map_leave", "When exiting map, remove quest items", remove_quest_items_on_leave)
local function start_harvesting_action(item, params, result)
-- >>>>>>>> shade2/action.hsp:151 if iType(ci)=fltFood:if iProperty(ci)=propQuest: ...
local chara = params.chara
if item:has_category("elona.food")
and item.own_state == Enum.OwnState.Quest
-- We also call Action.get() from the activity, which triggers this event,
-- but during the activity's on_finish callback, so we can skip this logic
-- when the item is successfully harvested.
and not chara:has_activity()
then
-- HACK: Here we want to skip running the normal item getting logic and
-- instead run the harvest activity. There is currently nothing in the
-- events logic that allows for this in a general fashion, so instead we
-- send down a turn result. There is a hack in Action.get() to skip the
-- logic if it sees the current result is a string (meaning "turn
-- result"). Otherwise `result` will be a boolean or nil.
if chara:is_inventory_full() then
Gui.mes("ui.inv.common.inventory_is_full")
return "player_turn_query" -- TODO skip rest
end
chara:start_activity("elona.harvest", { item = item })
return "turn_end"
end
-- <<<<<<<< shade2/action.hsp:155 } ..
return result
end
Event.register("base.on_get_item", "Start harvesting action", start_harvesting_action, 50000)
|
-- Copyright 2020-2022 The Defold Foundation
-- Copyright 2014-2020 King
-- Copyright 2009-2014 Ragnar Svensson, Christian Murray
-- Licensed under the Defold License version 1.0 (the "License"); you may not use
-- this file except in compliance with the License.
--
-- You may obtain a copy of the License, together with FAQs at
-- https://www.defold.com/license
--
-- 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 M = {}
local level_width = 1180
local level_height = 620
local screen_width = 1280
local screen_height = 720
function M.get_aabb()
local padding_x = (screen_width - level_width) * 0.5
local padding_y = (screen_height - level_height) * 0.5
local level_min = vmath.vector3(padding_x, padding_y, 0)
local level_max = vmath.vector3(screen_width - padding_x, screen_height - padding_y, 0)
return level_min, level_max
end
function M.clamp(p)
local min, max = M.get_aabb()
if p.x < min.x then p.x = min.x end
if p.y < min.y then p.y = min.y end
if p.x > max.x then p.x = max.x end
if p.y > max.y then p.y = max.y end
return p
end
local function draw_box(min, max)
local c = vmath.vector4(1, 1, 1, 1)
msg.post("@render:", "draw_line", { start_point = vmath.vector3(min.x, min.y, 0), end_point = vmath.vector3(max.x, min.y, 0), color = c } )
msg.post("@render:", "draw_line", { start_point = vmath.vector3(min.x, max.y, 0), end_point = vmath.vector3(max.x, max.y, 0), color = c } )
msg.post("@render:", "draw_line", { start_point = vmath.vector3(min.x, min.y, 0), end_point = vmath.vector3(min.x, max.y, 0), color = c } )
msg.post("@render:", "draw_line", { start_point = vmath.vector3(max.x, min.y, 0), end_point = vmath.vector3(max.x, max.y, 0), color = c } )
end
function M.draw()
local min, max = M.get_aabb()
draw_box(min, max)
local margin = 5
min.x = min.x - margin
min.y = min.y - margin
max.x = max.x + margin
max.y = max.y + margin
draw_box(min, max)
end
return M
|
--[[
Copyright (c) 2016, Cristian Cardellino.
This work is licensed under the "New BSD License".
See LICENSE for more information.
]]--
local SparseDataset = torch.class('mltools.SparseDataset')
function SparseDataset:__init(fname_or_indices, zero_based_or_values, target, shape)
if type(fname_or_indices) == 'string' then
if zero_based_or_values == nil then zero_based_or_values = false end
if type(zero_based_or_values) ~= 'boolean' then error('Wrong second argument. Should be of type boolean.') end
-- If the indices starts with 0 or 1 (default)
self:readFromFile(fname_or_indices, zero_based_or_values)
elseif type(fname_or_indices) == 'table' then
if type(zero_based_or_values) ~= 'table' or not target or type(shape) ~= 'table' then
error('Wrong argument type')
end
self.indices = fname_or_indices -- Table of Tensors
self.values = zero_based_or_values -- Table of Tensors
self.target = target:type('torch.IntTensor') -- One dimensional Tensor
self.shape = shape -- Tuple with 2 values: rows and cols
end
end
function SparseDataset:getDenseDataset()
local dataset = torch.FloatTensor(self.shape.rows, self.shape.cols):zero()
for i = 1, #self.indices do
dataset[{i, {}}]:indexAdd(1,
self.indices[i]:type('torch.LongTensor'),
self.values[i]:type('torch.FloatTensor')
)
end
return dataset
end
function SparseDataset:readFromFile(fname, zero_based)
if zero_based == nil then zero_based = false end
print('Reading ' .. fname)
local function readline(line)
local label = tonumber(string.match(line, '^([%+%-]?%s?%d+)'))
if not label then
error('could not read label')
end
local vals = {}
local inds = {}
local indcntr = 0
for ind, val in string.gmatch(line, '(%d+):([%+%-]?%d?%.?%d+)') do
indcntr = indcntr + 1
ind = tonumber(ind)
val = tonumber(val)
if not ind or not val then
error('reading failed')
end
if zero_based then ind = ind + 1 end -- We transform the zero based in one-based
if ind < indcntr then
error('indices are not in increasing order')
end
inds[#inds+1] = ind
vals[#vals+1] = val
end
return torch.LongTensor(inds), torch.FloatTensor(vals), label
end
local indices = {}
local values = {}
local target = {}
local shape = {rows = 0, cols = 0}
local labels = {}
setmetatable(labels, { __index = function() return 0 end })
for line in io.lines(fname) do
local inds, vals, tgt = readline(line)
indices[#indices+1] = inds
values[#values+1] = vals
target[#target+1] = tgt
shape.rows = shape.rows + 1
shape.cols = math.max(shape.cols, inds[-1])
labels[tgt] = labels[tgt] + 1
end
for l, c in pairs(labels) do
io.write(string.format("# of samples of label %d = %d\n", l, c))
end
io.write(string.format("# of total samples = %d\n", shape.rows))
io.write(string.format("# of features = %d\n", shape.cols))
self.indices = indices
self.values = values
self.target = torch.IntTensor(target)
self.shape = shape
end
function SparseDataset:writeToFile(fname)
print('Writing ' .. fname)
local function vectostr(i, x)
local str = {}
local cntr = 1
x:apply(function(v)
table.insert(str, string.format('%d:%g', i[cntr], v))
cntr = cntr + 1
return v
end)
return table.concat(str, ' ')
end
local of = torch.DiskFile(fname, 'w')
for i = 1, #self.indices do
of:writeString(string.format('%g %s\n', self.target[i], vectostr(self.indices[i], self.values[i])))
end
of:close()
end
|
--[[
Copyright (c) 2013 Romain Meynet
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
--]]
local lg = love.graphics
local events = require 'events'
local Snake = require 'snake'
local Bonus = require 'bonus'
local Highscore = require 'highscore'
local rsc = require 'resources'
local score=require 'score'
local snake={}
local bmgr={}
local state=nil
local playstate={}
local gameoverstate={}
local pausestate={}
local hiscorestate={}
function love.load()
math.randomseed(os.time())
love.keyboard.setTextInput(false)
SW,SH = lg.getWidth(), lg.getHeight()
lg.setBackgroundColor({0,64,64})
rsc.load()
Highscore.init()
gameoverstate:init()
hiscorestate:init()
state=hiscorestate
state:enter()
end
function reset()
state=playstate
playstate.sleep=false
events.clean()
score.reset()
bmgr=Bonus(10)
snake=Snake(30, math.floor(SH/2),10)
snake.fcollision = function (x,y,r) return bmgr:genCollision(x,y,r) end
end
function intersect(hb1,hb2)
return not ((hb1[1]>hb2[3]) or (hb2[1]>hb1[3]) or (hb1[2]>hb2[4]) or (hb2[2]>hb1[4]))
end
function playstate:update(dt)
events.update(dt)
snake:update(dt)
bmgr:update(dt)
if not self.sleep and snake.waitcount < 0 then
self.sleep=true
--bmgr:sleep()
snake:sleep()
elseif self.sleep and snake.waitcount > 0 then
self.sleep=false
--bmgr:wakeup(evmgr)
snake:wakeup()
end
if not self.sleep then
local events = bmgr:genEvents(snake:getDisk(1))
for _,e in ipairs(events) do
if e[1] == "FRUIT" then
score.add(e[2])
snake:addRing()
score.grow(1)
end
end
end
if snake:selfhit() then
state=gameoverstate
state:enter()
end
end
function playstate:draw()
snake:draw()
bmgr:draw()
score.draw()
end
function playstate:keypressed(key)
if key == "p" then
state = pausestate
end
end
function hiscorestate:init()
local titreOffset = 20
self.titreBgColor = {0,0,196/255,.5}
self.titreFgColor= {1,1,1}
self.titre = "OPHIDIAN CRAWLER"
local titreHeight = math.floor(rsc.titleFont:getHeight()*1.5)
self.titreY = titreOffset + math.floor(rsc.titleFont:getHeight()*0.25)
self.titreRectangle = {0,titreOffset,SW,titreHeight}
self.message="PRESS ANY KEY TO PLAY"
self.messageY = SH - 1.5*rsc.font:getHeight()
self.demoSnakes={}
for i=1,5 do
self.demoSnakes[i]=Snake(30, math.random(1,SH),30)
end
self.selectSnake = Snake(30, math.floor(SH/2),10)
self.selectSnake.bodyColor={196/255,196/255,196/255}
self.selectSnake.headColor={196/255,20/255,20/255}
local ns = Highscore.getNbScores()
self.scoreY={}
local sh = (ns + 4)*1.2*rsc.menuFont:getHeight()
self.scoreTitreY = (SH - titreHeight - titreOffset - sh) / 2 + titreHeight + titreOffset
self.scoreY[1] = self.scoreTitreY + 2.4 * rsc.menuFont:getHeight()
for i= 2 , ns do
self.scoreY[i] = self.scoreY[i-1] + 1.2 * rsc.menuFont:getHeight()
end
self.scoreY[ns+1] = self.scoreY[ns] + 2.4 * rsc.menuFont:getHeight()
self.scoreW = rsc.menuFont:getWidth("99. MMMMMMMMMM 999999")
self.scoreX={}
self.scoreX[1] = (SW - self.scoreW)/2
self.scoreX[2] = self.scoreX[1] + rsc.menuFont:getWidth("99. ")
self.scoreX[3] = self.scoreX[1] + rsc.menuFont:getWidth("99. MMMMMMMMMM ")
self.scoreLastW = self.scoreX[1]+self.scoreW-self.scoreX[3]
self.scoreColor = {1,1,1}
self.scoreSelectColor = {1,1,0}
end
function hiscorestate:enter()
love.keyboard.setTextInput(false)
self.showMessage=true
events.clean()
events.addEvent(0.5,self,self.flipMessage)
for _,s in ipairs(self.demoSnakes) do
s:setAutoPilot()
s.speed = math.random(200,300)
end
self.listNames=Highscore.getListNames()
self.iListe=1
self.currentScores = Highscore.getHighScores(self.listNames[self.iListe])
self.currentXOff = 0
events.addEvent(5,self,self.nextHighscoreList)
end
function hiscorestate:nextHighscoreList()
self.iListe = self.iListe + 1
if self.iListe > #self.listNames then
self.iListe=1
end
self.oldScores = self.currentScores
self.currentScores = Highscore.getHighScores(self.listNames[self.iListe])
self.currentXOff=SW
events.addEvent(5,self,self.nextHighscoreList)
end
function hiscorestate:flipMessage()
self.showMessage = not self.showMessage
events.addEvent(0.5,self,self.flipMessage)
end
function hiscorestate:update(dt)
if self.currentXOff > 0 then
self.currentXOff= self.currentXOff - SW/2*dt
else
self.currentXOff=0
end
events.update(dt)
for _,s in ipairs(self.demoSnakes) do
s:update(dt)
end
--self.selectSnake:update(dt)
end
function hiscorestate:drawScores(xoff,scores)
-- display high scores
local s = scores
lg.setFont(rsc.menuFont)
lg.setColor(self.scoreColor)
lg.printf(s.title,xoff,self.scoreTitreY,SW,"center")
for i,sc in ipairs(s) do
if sc.last then
lg.setColor(self.scoreSelectColor)
else
lg.setColor(self.scoreColor)
end
lg.print(i,self.scoreX[1]+xoff,self.scoreY[i])
lg.print(sc.name,self.scoreX[2]+xoff,self.scoreY[i])
lg.printf(s.fmt(sc.score),self.scoreX[3]+xoff,self.scoreY[i],self.scoreLastW,"right")
end
lg.setColor(self.scoreSelectColor)
lg.print("LAST SCORE",self.scoreX[1]+xoff,self.scoreY[#s+1])
lg.printf(s.fmt(s.lastScore),self.scoreX[3]+xoff,self.scoreY[#s+1],self.scoreLastW,"right")
end
function hiscorestate:draw()
for _,s in ipairs(self.demoSnakes) do
s:draw()
end
--self.selectSnake:draw()
lg.setColor(self.titreBgColor)
lg.rectangle('fill',unpack(self.titreRectangle))
lg.setColor(self.titreFgColor)
lg.setFont(rsc.titleFont)
lg.printf(self.titre,0,self.titreY,SW,"center")
if self.showMessage then
lg.setColor({1,1,1})
lg.setFont(rsc.font)
lg.printf(self.message,0,self.messageY,SW,"center")
end
-- display high scores
self:drawScores(self.currentXOff,self.currentScores)
if self.currentXOff > 0 then
self:drawScores(self.currentXOff-SW,self.oldScores)
end
end
function hiscorestate:keypressed(key)
reset()
end
function gameoverstate:init()
self.message="PRESS ANY KEY TO PLAY"
self.messageY = SH - 1.5*rsc.font:getHeight()
self.y = (SH-rsc.font:getHeight())/2
end
function gameoverstate:enter()
events.clean()
self.showMessage=true
self.hscores={}
self.text="GAME OVER\nFINAL SCORE : "..score.value().."\n\n"
self.enterName=false
if score.setLastScore() then
love.keyboard.setTextInput(true)
self.text = self.text .. "HIGH SCORE - PLEASE ENTER NAME"
self.enterName=true
self.name = Highscore.getPlayerName()
else
events.addEvent(0.5,self,self.flipMessage)
events.addEvent(3,self,self.startDemo)
self.text = self.text .. "NO HIGH SCORE - TRY AGAIN"
end
end
function gameoverstate:startDemo()
state = hiscorestate
state:enter()
end
function gameoverstate:flipMessage()
self.showMessage = not self.showMessage
events.addEvent(0.5,self,self.flipMessage)
end
function gameoverstate:update(dt)
events.update(dt)
end
function gameoverstate:draw()
playstate:draw()
lg.setColor({1,1,1})
lg.setFont(rsc.titleFont)
lg.printf(self.text,0,100,SW,"center")
if self.enterName then
lg.setColor({0,0,196/255,0.5})
local fh = rsc.titleFont:getHeight()
local fw = rsc.titleFont:getWidth(self.name.."_")+30
lg.rectangle('fill',(SW-fw)/2,self.y-fh*0.25,fw,fh*1.5)
lg.setColor({1,0,0})
lg.printf(self.name.."_",0,self.y,SW,"center")
elseif self.showMessage then
lg.setFont(rsc.font)
lg.printf(self.message,0,self.messageY,SW,"center")
end
end
function gameoverstate:keypressed(key)
if self.enterName then
if key == "backspace" then
if #self.name > 0 then
self.name=string.sub(self.name,1,-2)
end
elseif key == "return" then
score.recordHighScore(self.name)
state=hiscorestate
state:enter()
end
else
reset()
end
end
function gameoverstate:textinput(unicode)
if self.enterName then
local ch = string.upper(unicode)
if (ch>="A" and ch<="Z" ) or (ch>="0" and ch <="9") then
if #self.name < 8 then
self.name = self.name .. ch
end
end
else
reset()
end
end
function pausestate:update(dt)
end
function pausestate:draw()
playstate:draw()
end
function pausestate:keypressed(key)
if key==" " or key =="return" then
state = playstate
end
end
function love.update(dt)
state:update(dt)
end
function love.draw()
lg.draw(rsc.bgCanvas,0,0)
state:draw(dt)
lg.setFont(rsc.menuFont)
lg.setColor({1,1,1})
lg.print(love.timer.getFPS( ),0,SH-20)
end
--
function love.keypressed(key)
state:keypressed(key)
end
--
function love.textinput(unicode)
if state.textinput then
state:textinput(unicode)
end
end
--]]
|
-- Logging utilities for command line output.
local Logger = {}
function Logger:Format(raw, simple)
local module = self.module
if simple then
module = "Bartmoss | " .. module
end
return self.template:format(module, tostring(raw))
end
function Logger:Info(raw)
if self.writer then
self.writer.info(self:Format(raw))
if not self.tee then
return
end
end
print(self:Format(raw, true))
end
function Logger:Debug(raw)
if self.writer then
self.writer.debug(self:Format(raw))
if not self.tee then
return
end
end
print(self:Format(raw, true))
end
function Logger:Warning(raw)
if self.writer then
self.writer.warning(self:Format(raw))
if not self.tee then
return
end
end
print(self:Format(raw, true))
end
function Logger:Error(raw)
if self.writer then
self.writer.error(self:Format(raw))
if not self.tee then
return
end
end
print(self:Format(raw, true))
end
function Logger:Critical(raw)
if self.writer then
self.writer.critical(self:Format(raw))
if not self.tee then
return
end
end
print(self:Format(raw, true))
end
function Logger:Tee(raw)
if self.writer then
self.writer.info(self:Format(raw))
end
print(self:Format(raw, true))
end
function Logger:New(module, writer, template, tee)
local I = {}
setmetatable(I, self)
self.__index = self
I.writer = writer or spdlog
I.module = module or "Bartmoss"
I.template = template or "[%s] %s"
I.tee = tee or false
return I
end
return Logger
|
local scheduler = {}
local sharedScheduler = CCDirector:sharedDirector():getScheduler()
function scheduler.scheduleUpdateGlobal(listener)
return sharedScheduler:scheduleScriptFunc(listener, 0, false)
end
function scheduler.scheduleGlobal(listener, interval)
return sharedScheduler:scheduleScriptFunc(listener, interval, false)
end
function scheduler.unscheduleGlobal(handle)
sharedScheduler:unscheduleScriptEntry(handle)
end
function scheduler.performWithDelayGlobal(listener, time)
local handle
handle = sharedScheduler:scheduleScriptFunc(function()
scheduler.unscheduleGlobal(handle)
listener()
end, time, false)
return handle
end
return scheduler
|
local dht_pin = 4
local bat_ratio = 10.37
local wifi_retries = 25
local mqtt_retries = 5
local push_retries = 10
adc.force_init_mode(adc.INIT_ADC)
local w = require('wifimodule')
local m = require('mqttmodule')
tmr.create():alarm(300, tmr.ALARM_AUTO, function(t)
if w.isConnected() then
tmr.unregister(t)
m.connect()
tmr.create():alarm(300, tmr.ALARM_AUTO, function(tw)
if m.connected then
tmr.unregister(tw)
battery()
dht22()
tmr.create():alarm(300, tmr.ALARM_AUTO, function(off)
if m.publish and m.publish_bat then
node.dsleep(5000000, 1)
end
push_retries = push_retries - 1
if push_retries == 0 then
node.dsleep(1000000, 1)
end
end)
else
m.connect()
mqtt_retries = mqtt_retries - 1
if mqtt_retries == 0 then
node.dsleep(1000000, 1)
end
end
end)
else
-- print('offline...\n')
wifi_retries = wifi_retries - 1
if wifi_retries == 0 then
node.dsleep(1000000, 1)
end
end
end)
function dht22()
status, temp, humi, temp_dec, humi_dec = dht.read(dht_pin)
if status == dht.OK then
-- tmr.unregister(td)
print( "t"..temp.."\n" )
print( "h"..humi.."\n" )
m.publish('{"tempValue":'..temp..',"humiValue":'..humi..'}')
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
end
function battery()
input = adc.read(0)
bat = (input * 3.04 / 1024) * bat_ratio
m.publishBattery('{"batValue":'..bat..'}')
end
|
RageUI.PanelColour = {
HairCut = {
{ 28, 31, 33 }, -- 0
{ 39, 42, 44 }, -- 1
{ 49, 46, 44 }, -- 2
{ 53, 38, 28 }, -- 3
{ 75, 50, 31 }, -- 4
{ 92, 59, 36 }, -- 5
{ 109, 76, 53 }, -- 6
{ 107, 80, 59 }, -- 7
{ 118, 92, 69 }, -- 8
{ 127, 104, 78 }, -- 9
{ 153, 129, 93 }, -- 10
{ 167, 147, 105 }, -- 11
{ 175, 156, 112 }, -- 12
{ 187, 160, 99 }, -- 13
{ 214, 185, 123 }, -- 14
{ 218, 195, 142 }, -- 15
{ 159, 127, 89 }, -- 16
{ 132, 80, 57 }, -- 17
{ 104, 43, 31 }, -- 18
{ 97, 18, 12 }, -- 19
{ 100, 15, 10 }, -- 20
{ 124, 20, 15 }, -- 21
{ 160, 46, 25 }, -- 22
{ 182, 75, 40 }, -- 23
{ 162, 80, 47 }, -- 24
{ 170, 78, 43 }, -- 25
{ 98, 98, 98 }, -- 26
{ 128, 128, 128}, -- 27
{ 170, 170, 170 }, -- 28
{ 197, 197, 197 }, -- 29
{ 70, 57, 85 }, -- 30
{ 90, 63, 107 }, -- 31
{ 118, 60, 118 }, -- 32
{ 237, 116, 227 }, -- 33
{ 235, 75, 147 }, -- 34
{ 242, 153, 188 }, -- 35
{ 4, 149, 158 }, -- 36
{ 2, 95, 134 }, -- 37
{ 2, 57, 116 }, -- 38
{ 63, 161, 106 }, -- 39
{ 33, 124, 97 }, -- 40
{ 24, 92, 85 }, -- 41
{ 182, 192, 52 }, -- 42
{ 112, 169, 11 }, -- 43
{ 67, 157, 19 }, -- 44
{ 220, 184, 87 }, -- 45
{ 229, 177, 3 }, -- 46
{ 230, 145, 2 }, -- 47
{ 242, 136, 49 }, -- 48
{ 251, 128, 87 }, -- 49
{ 226, 139, 88 }, -- 50
{ 209, 89, 60 }, -- 51
{ 206, 49, 32 }, -- 52
{ 173, 9, 3 }, -- 53
{ 136, 3, 2 }, -- 54
{ 31, 24, 20 }, -- 55
{ 41, 31, 25 }, -- 56
{ 46, 34, 27 }, -- 57
{ 55, 41, 30 }, -- 58
{ 46, 34, 24 }, -- 59
{ 35, 27, 21 }, -- 60
{ 2, 2, 2 }, -- 61
{ 112, 108, 102 }, -- 62
{ 157, 122, 80 } -- 63
},
MakeUp = {
{ 153, 37, 50 }, -- 0
{ 200, 57, 93 }, -- 1
{ 189, 81, 108 }, -- 2
{ 184, 99, 122 }, -- 3
{ 166, 82, 107 }, -- 4
{ 177, 67, 76 }, -- 5
{ 127, 49, 51 }, -- 6
{ 164, 100, 93 }, -- 7
{ 193, 135, 121 }, -- 8
{ 203, 160, 150 }, -- 9
{ 198, 145, 143 }, -- 10
{ 171, 111, 99}, -- 11
{ 176, 96, 80 }, -- 12
{ 168, 76, 51 }, -- 13
{ 180, 113, 120 }, -- 14
{ 202, 127, 146 }, -- 15
{ 237, 156, 190 }, -- 16
{ 231, 117, 164 }, -- 17
{ 222, 62, 129 }, -- 18
{ 179, 76, 110 }, -- 19
{ 113, 39, 57 }, -- 20
{ 79, 31, 42 }, -- 21
{ 170, 34, 47 }, -- 22
{ 222, 32, 52 }, -- 23
{ 207, 8, 19 }, -- 24
{ 229, 84, 112 }, -- 25
{ 220, 63, 181 }, -- 26
{ 192, 39, 178 }, -- 27
{ 160, 28, 169 }, -- 28
{ 110, 24, 117 }, -- 29
{ 115, 20, 101 }, -- 30
{ 86, 22, 92 }, -- 31
{ 109, 26, 157 }, -- 32
{ 27, 55, 113 }, -- 33
{ 29, 78, 167 }, -- 34
{ 30, 116, 187 }, -- 35
{ 33, 163, 206 }, -- 36
{ 37, 194, 210 }, -- 37
{ 35, 204, 165 }, -- 38
{ 39, 192, 125 }, -- 39
{ 27, 156, 50 }, -- 40
{ 20, 134, 4 }, -- 41
{ 112, 208, 65 }, -- 42
{ 197, 234, 52 }, -- 43
{ 225, 227, 47 }, -- 44
{ 255, 221, 38 }, -- 45
{ 250, 192, 38 }, -- 46
{ 247, 138, 39 }, -- 47
{ 254, 89, 16 }, -- 48
{ 190, 110, 25 }, -- 49
{ 247, 201, 127 }, -- 50
{ 251, 229, 192 }, -- 51
{ 245, 245, 245 }, -- 52
{ 179, 180, 179 }, -- 53
{ 145, 145, 145 }, -- 54
{ 86, 78, 78 }, -- 55
{ 24, 14, 14 }, -- 56
{ 88, 150, 158 }, -- 57
{ 77, 111, 140 }, -- 58
{ 26, 43, 85 }, -- 59
{ 160, 126, 107 }, -- 60
{ 130, 99, 85 }, -- 61
{ 109, 83, 70 }, -- 62
{ 62, 45, 39 } -- 63
}
}
|
--- `ds.Vector` class.
-- A factory class that generates specific vector object under user's request.
-- Currently, `ds.DoubleVector` and `ds.LuaVector` are implemented.
-- @classmod Vector
local DoubleVector = require "ds.DoubleVector"
local LuaVector = require "ds.LuaVector"
local Vector = {}
package.loaded['Vector'] = Vector
Vector.__index = Vector
local function _check_type(e)
assert(e == "native" or e == "number" or e == nil)
end
local function _get_type(options)
local _type = nil
if type(options) == "table" then
_type = options["type"]
end
_check_type(_type)
if _type == nil then
_type = "native"
end
return _type
end
local function _infer_type(t)
local n = #t
if n > 10 then
n = 10
end
local is_number = true
for i = 1, n do
if type(t[i]) ~= "number" then
is_number = false
break
end
end
local _type = nil
if is_number then
_type = "number"
else
_type = "native"
end
return _type
end
--- Create an empty vector.
-- @param size size
-- @param options Optional. A hash-style table presents options, including:
--
-- * type: native or number. Default to native, i.e. LuaVector.
--
-- @return A vector.
function Vector:new(size, options)
local _type = _get_type(options)
if _type == "number" then
return DoubleVector:new(size)
elseif _type == "native" then
return LuaVector:new(size)
else
return nil
end
end
--- Create an vector with the elements from an array-style table.
-- @param table an array-style table
-- @param options Optional. A hash-style table presents options, including:
--
-- * type: native or number. Default to native, i.e. LuaVector.
--
-- If no option supplied, the method will infer proper vector type by the
-- elements in the table.
-- @return A vector.
function Vector:from_table(table, options)
local _type = nil
if type(options) == "table" then
_type = _get_type(options)
else
_type = _infer_type(table)
end
if _type == "number" then
return DoubleVector:from_table(table)
elseif _type == "native" then
return LuaVector:from_table(table)
else
return nil
end
end
return Vector
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You 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 core = require("apisix.core")
local ngx_re = require("ngx.re")
local tab_concat = table.concat
local string = string
local io_open = io.open
local io_close = io.close
local ngx = ngx
local os = os
local ipairs = ipairs
local pairs = pairs
local tonumber = tonumber
local plugin_name = "proxy-cache"
local schema = {
type = "object",
properties = {
cache_zone = {
type = "string",
minLength = 1,
maxLength = 100,
default = "disk_cache_one",
},
cache_key = {
type = "array",
minItems = 1,
items = {
description = "a key for caching",
type = "string",
pattern = [[(^[^\$].+$|^\$[0-9a-zA-Z_]+$)]],
},
default = {"$host", "$request_uri"}
},
cache_http_status = {
type = "array",
minItems = 1,
items = {
description = "http response status",
type = "integer",
minimum = 200,
maximum = 599,
},
uniqueItems = true,
default = {200, 301, 404},
},
cache_method = {
type = "array",
minItems = 1,
items = {
description = "http method",
type = "string",
enum = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD",
"OPTIONS", "CONNECT", "TRACE"},
},
uniqueItems = true,
default = {"GET", "HEAD"},
},
hide_cache_headers = {
type = "boolean",
default = false,
},
cache_bypass = {
type = "array",
minItems = 1,
items = {
type = "string",
pattern = [[(^[^\$].+$|^\$[0-9a-zA-Z_]+$)]]
},
},
no_cache = {
type = "array",
minItems = 1,
items = {
type = "string",
pattern = [[(^[^\$].+$|^\$[0-9a-zA-Z_]+$)]]
},
},
},
}
local _M = {
version = 0.1,
priority = 1009,
name = plugin_name,
schema = schema,
}
function _M.check_schema(conf)
local ok, err = core.schema.check(schema, conf)
if not ok then
return false, err
end
for _, key in ipairs(conf.cache_key) do
if key == "$request_method" then
return false, "cache_key variable " .. key .. " unsupported"
end
end
local found = false
local local_conf = core.config.local_conf()
if local_conf.apisix.proxy_cache then
for _, cache in ipairs(local_conf.apisix.proxy_cache.zones) do
if cache.name == conf.cache_zone then
found = true
end
end
if found == false then
return false, "cache_zone " .. conf.cache_zone .. " not found"
end
end
return true
end
local tmp = {}
local function generate_complex_value(data, ctx)
core.table.clear(tmp)
core.log.info("proxy-cache complex value: ", core.json.delay_encode(data))
for i, value in ipairs(data) do
core.log.info("proxy-cache complex value index-", i, ": ", value)
if string.byte(value, 1, 1) == string.byte('$') then
tmp[i] = ctx.var[string.sub(value, 2)]
else
tmp[i] = value
end
end
return tab_concat(tmp, "")
end
-- check whether the request method and response status
-- match the user defined.
local function match_method_and_status(conf, ctx)
local match_method, match_status = false, false
-- Maybe there is no need for optimization here.
for _, method in ipairs(conf.cache_method) do
if method == ctx.var.request_method then
match_method = true
break
end
end
for _, status in ipairs(conf.cache_http_status) do
if status == ngx.status then
match_status = true
break
end
end
if match_method and match_status then
return true
end
return false
end
local function file_exists(name)
local f = io_open(name, "r")
if f ~= nil then
io_close(f)
return true
end
return false
end
local function generate_cache_filename(cache_path, cache_levels, cache_key)
local md5sum = ngx.md5(cache_key)
local levels = ngx_re.split(cache_levels, ":")
local filename = ""
local index = #md5sum
for k, v in pairs(levels) do
local length = tonumber(v)
index = index - length
filename = filename .. md5sum:sub(index+1, index+length) .. "/"
end
if cache_path:sub(-1) ~= "/" then
cache_path = cache_path .. "/"
end
filename = cache_path .. filename .. md5sum
return filename
end
local function cache_purge(conf, ctx)
local cache_zone_info = ngx_re.split(ctx.var.upstream_cache_zone_info, ",")
local filename = generate_cache_filename(cache_zone_info[1], cache_zone_info[2],
ctx.var.upstream_cache_key)
if file_exists(filename) then
os.remove(filename)
return nil
end
return "Not found"
end
function _M.rewrite(conf, ctx)
core.log.info("proxy-cache plugin rewrite phase, conf: ", core.json.delay_encode(conf))
ctx.var.upstream_cache_zone = conf.cache_zone
local value = generate_complex_value(conf.cache_key, ctx)
ctx.var.upstream_cache_key = value
core.log.info("proxy-cache cache key value:", value)
if ctx.var.request_method == "PURGE" then
local err = cache_purge(conf, ctx)
if err ~= nil then
return 404
end
return 200
end
if conf.cache_bypass ~= nil then
local value = generate_complex_value(conf.cache_bypass, ctx)
ctx.var.upstream_cache_bypass = value
core.log.info("proxy-cache cache bypass value:", value)
end
end
function _M.header_filter(conf, ctx)
core.log.info("proxy-cache plugin header filter phase, conf: ", core.json.delay_encode(conf))
local no_cache = "1"
if match_method_and_status(conf, ctx) then
no_cache = "0"
end
if conf.no_cache ~= nil then
local value = generate_complex_value(conf.no_cache, ctx)
core.log.info("proxy-cache no-cache value:", value)
if value ~= nil and value ~= "" and value ~= "0" then
no_cache = "1"
end
end
if conf.hide_cache_headers == true then
ctx.var.upstream_hdr_cache_control = ""
ctx.var.upstream_hdr_expires = ""
else
ctx.var.upstream_hdr_cache_control = ctx.var.upstream_http_cache_control
ctx.var.upstream_hdr_expires = ctx.var.upstream_http_expires
end
ctx.var.upstream_no_cache = no_cache
core.log.info("proxy-cache no cache:", no_cache)
end
return _M
|
local Bd_Log = require('lua.bdlib.BdLog')
local str_format = string.format
WRITE_LOG = Bd_Log.write_log
local ActionBase = {}
function ActionBase:init()
local logId, logId_r = nil, nil
if self.logId then logId = self.logId end
if self.logId_r then logId_r = self.logId_r end
ngx.log(ngx.DEBUG, str_format("logId [%s] logId_r [%s]", logId, logId_r))
Bd_Log.init_log(logId, logId_r)
end
return ActionBase
|
class 'RacingClient'
local debug = false
function RacingClient:__init()
print('Initializing client module')
self.lastCheckpoint = nil
self.nextCheckpoint = nil
self.track = nil
Events:Subscribe('Level:Loaded', self, self.OnLoad)
Events:Subscribe('Level:Destroy', self, self.OnDestroy)
Events:Subscribe('Extension:Loaded', function()
WebUI:Init()
WebUI:Hide()
end)
end
function RacingClient:OnLoad()
Events:Subscribe('Client:PostFrameUpdate', self, self.Update)
Events:Subscribe('Player:UpdateInput', self, self.UpdateInput)
NetEvents:Subscribe('Checkpoint:Reset', self, self.ResetCheckpoint)
NetEvents:Subscribe('Checkpoint:Change', self, self.CheckpointChanged)
NetEvents:Subscribe('Time', self, self.TimeChanged)
NetEvents:Subscribe('Position', self, self.PositionChanged)
NetEvents:Subscribe('Scoreboard', self, self.ScoreboardUpdated)
Hooks:Install('UI:PushScreen', 1, function(hook, screen, priority, parentGraph)
screen = UIScreenAsset(screen)
local scoreboardDir = 'UI/Flow/Screen/Scoreboards/'
if screen.name:sub(1, #scoreboardDir) == scoreboardDir and screen.name:find('HUD') then
hook:Return(nil)
end
end)
self.lastCheckpoint = nil
self.nextCheckpoint = nil
self.track = g_RacingShared.track
self:ResetCheckpoint()
WebUI:ExecuteJS('setScoreboardVisible(false)')
WebUI:ExecuteJS(string.format('trackChanged(%s)', json.encode({ name = self.track.name, checkpoints = #self.track.checkpoints })))
WebUI:Show()
NetEvents:SendLocal('Scoreboard')
if debug then
Events:Subscribe('UI:DrawHud', self, self.DrawTrack)
end
end
function RacingClient:OnDestroy()
Events:Unsubscribe('Client:PostFrameUpdate')
Events:Unsubscribe('Player:UpdateInput')
Events:Unsubscribe('UI:DrawHud')
NetEvents:Unsubscribe()
WebUI:Hide()
self.lastCheckpoint = nil
self.nextCheckpoint = nil
self.track = nil
end
function RacingClient:ResetCheckpoint()
self.lastCheckpoint = nil
if self.nextCheckpoint ~= nil then
self.nextCheckpoint:SetActive(false)
self.nextCheckpoint = nil
local data = {
number = 0,
position = Vec2(),
}
WebUI:ExecuteJS(string.format('updateWaypoint(%s)', json.encode(data)))
end
WebUI:ExecuteJS(string.format('updateCheckpoint(%s)', json.encode({ number = 0 })))
end
function RacingClient:CheckpointChanged(newNumber)
if self.nextCheckpoint ~= nil then
if self.nextCheckpoint.number == newNumber then
return
end
self.lastCheckpoint = self.nextCheckpoint
self.nextCheckpoint = nil
if newNumber >= 1 then
WebUI:ExecuteJS(string.format('checkpointReached(%s)', json.encode({ number = self.lastCheckpoint.number })))
end
self.lastCheckpoint:SetActive(false)
end
if newNumber <= 0 then
self.nextCheckpoint = nil
return
end
if #g_RacingShared.checkpoints > 0 then
self.nextCheckpoint = g_RacingShared.checkpoints[newNumber]
self.nextCheckpoint:SetActive(true)
end
if self.lastCheckpoint ~= nil then
WebUI:ExecuteJS(string.format('updateCheckpoint(%s)', json.encode({ number = self.lastCheckpoint.number })))
else
WebUI:ExecuteJS(string.format('updateCheckpoint(%s)', json.encode({ number = 0 })))
end
end
function RacingClient:TimeChanged(data)
WebUI:ExecuteJS(string.format('updateTime(%s)', json.encode(data)))
end
function RacingClient:PositionChanged(data)
WebUI:ExecuteJS(string.format('updatePosition(%s)', json.encode(data)))
end
function RacingClient:ScoreboardUpdated(data)
for _, entry in ipairs(data) do
local player = PlayerManager:GetPlayerById(entry.id)
if player ~= nil then
entry.name = player.name
else
entry.name = '???'
end
end
local jsonData, errorMessage = json.encode(data)
if jsonData == nil then
print(string.format('Received invalid scoreboard update (%s)', errorMessage))
print(data)
else
WebUI:ExecuteJS(string.format('updateScoreboard(%s)', jsonData))
end
end
function RacingClient:Update(_)
if self.nextCheckpoint ~= nil then
local data
local position = ClientUtils:WorldToScreen(self.nextCheckpoint.transform.trans)
if position == nil then
data = {
number = 0,
position = Vec2(),
finish = false,
}
else
data = {
number = self.nextCheckpoint.number,
position = position,
finish = self.nextCheckpoint.finish,
}
end
WebUI:ExecuteJS(string.format('updateWaypoint(%s)', json.encode(data)))
end
end
function RacingClient:UpdateInput()
if debug and InputManager:WentKeyDown(InputDeviceKeys.IDK_Q) then
local player = PlayerManager:GetLocalPlayer()
if player == nil or not player.alive or player.soldier == nil then
return
end
local transform = player.soldier.worldTransform
print(string.format('LinearTransform(Vec3%s, Vec3%s, Vec3%s, Vec3%s)', transform.left, transform.up, transform.forward, transform.trans))
end
if InputManager:WentDown(InputConceptIdentifiers.ConceptScoreboard) then
NetEvents:SendLocal('Scoreboard')
WebUI:ExecuteJS('setScoreboardVisible(true)')
elseif not InputManager:IsDown(InputConceptIdentifiers.ConceptScoreboard) then
WebUI:ExecuteJS('setScoreboardVisible(false)')
end
end
function RacingClient:DrawTrack()
if self.track == nil then
return
end
local startColor = Vec4(0, 1, 0, 1)
local endColor = Vec4(1, 0, 0, 1)
local previousCheckpoint
for i, checkpoint in ipairs(self.track.checkpoints) do
local progress = i / #self.track.checkpoints
local color = Vec4(
MathUtils:Lerp(startColor.x, endColor.x, progress),
MathUtils:Lerp(startColor.y, endColor.y, progress),
MathUtils:Lerp(startColor.z, endColor.z, progress),
MathUtils:Lerp(startColor.w, endColor.w, progress)
)
if previousCheckpoint ~= nil then
DebugRenderer:DrawLine(previousCheckpoint.trans, checkpoint.trans, color, color)
end
local position = ClientUtils:WorldToScreen(checkpoint.trans)
if position ~= nil then
DebugRenderer:DrawText2D(position.x, position.y, tostring(i), color, 1)
end
previousCheckpoint = checkpoint
end
end
g_RacingClient = RacingClient()
|
--[[------------------------------------------------------------------
TEXT
Map characters from a texture and render text
]]--------------------------------------------------------------------
if CLIENT then
local FILE_W, FILE_H = 256, 128;
local CHARACTERS = {
["!"] = {x = 7, y = 1, w = 6, h = 10},
["\""] = {x = 14, y = 1, w = 7, h = 10},
["#"] = {x = 22, y = 1, w = 9, h = 10},
["$"] = {x = 31, y = 1, w = 9, h = 10},
["%"] = {x = 41, y = 1, w = 8, h = 10},
["&"] = {x = 49, y = 1, w = 9, h = 10},
["`"] = {x = 59, y = 1, w = 8, h = 10},
["'"] = {x = 59, y = 1, w = 8, h = 10},
["("] = {x = 67, y = 1, w = 6, h = 10},
[")"] = {x = 75, y = 1, w = 6, h = 10},
["*"] = {x = 83, y = 1, w = 10, h = 10},
["+"] = {x = 93, y = 1, w = 8, h = 10},
[","] = {x = 101, y = 1, w = 7, h = 10},
["-"] = {x = 109, y = 1, w = 8, h = 10},
["."] = {x = 119, y = 1, w = 6, h = 10},
["/"] = {x = 127, y = 1, w = 9, h = 10},
["0"] = {x = 137, y = 1, w = 8, h = 10},
["1"] = {x = 146, y = 1, w = 5, h = 10},
["2"] = {x = 152, y = 1, w = 8, h = 10},
["3"] = {x = 161, y = 1, w = 8, h = 10},
["4"] = {x = 170, y = 1, w = 8, h = 10},
["5"] = {x = 179, y = 1, w = 8, h = 10},
["6"] = {x = 188, y = 1, w = 8, h = 10},
["7"] = {x = 197, y = 1, w = 8, h = 10},
["8"] = {x = 206, y = 1, w = 8, h = 10},
["9"] = {x = 215, y = 1, w = 8, h = 10},
[":"] = {x = 224, y = 1, w = 8, h = 10},
[";"] = {x = 234, y = 1, w = 8, h = 10},
["<"] = {x = 241, y = 1, w = 8, h = 10},
["="] = {x = 1, y = 11, w = 8, h = 10},
[">"] = {x = 11, y = 11, w = 7, h = 10},
["?"] = {x = 18, y = 11, w = 8, h = 10},
["@"] = {x = 27, y = 11, w = 9, h = 10},
["A"] = {x = 37, y = 11, w = 8, h = 10},
["B"] = {x = 46, y = 11, w = 8, h = 10},
["C"] = {x = 55, y = 11, w = 8, h = 10},
["D"] = {x = 64, y = 11, w = 8, h = 10},
["E"] = {x = 73, y = 11, w = 8, h = 10},
["F"] = {x = 82, y = 11, w = 8, h = 10},
["G"] = {x = 91, y = 11, w = 8, h = 10},
["H"] = {x = 100, y = 11, w = 8, h = 10},
["I"] = {x = 109, y = 11, w = 6, h = 10},
["J"] = {x = 116, y = 11, w = 8, h = 10},
["K"] = {x = 126, y = 11, w = 8, h = 10},
["L"] = {x = 133, y = 11, w = 8, h = 10},
["M"] = {x = 142, y = 11, w = 8, h = 10},
["N"] = {x = 151, y = 11, w = 8, h = 10},
["O"] = {x = 160, y = 11, w = 8, h = 10},
["P"] = {x = 169, y = 11, w = 8, h = 10},
["Q"] = {x = 178, y = 11, w = 8, h = 10},
["R"] = {x = 187, y = 11, w = 8, h = 10},
["S"] = {x = 196, y = 11, w = 8, h = 10},
["T"] = {x = 205, y = 11, w = 8, h = 10},
["U"] = {x = 214, y = 11, w = 8, h = 10},
["V"] = {x = 223, y = 11, w = 8, h = 10},
["W"] = {x = 232, y = 11, w = 8, h = 10},
["X"] = {x = 241, y = 11, w = 8, h = 10},
["Y"] = {x = 1, y = 21, w = 8, h = 10},
["Z"] = {x = 10, y = 21, w = 8, h = 10},
["["] = {x = 21, y = 21, w = 9, h = 10},
["\\"] = {x = 27, y = 21, w = 9, h = 10},
["]"] = {x = 37, y = 21, w = 5, h = 10},
["_"] = {x = 54, y = 21, w = 8, h = 10},
["a"] = {x = 71, y = 21, w = 8, h = 10},
["b"] = {x = 80, y = 21, w = 8, h = 10},
["c"] = {x = 89, y = 21, w = 8, h = 10},
["d"] = {x = 98, y = 21, w = 8, h = 10},
["e"] = {x = 107, y = 21, w = 8, h = 10},
["f"] = {x = 116, y = 21, w = 8, h = 9},
["g"] = {x = 125, y = 21, w = 8, h = 9},
["h"] = {x = 134, y = 21, w = 8, h = 10},
["i"] = {x = 143, y = 21, w = 5, h = 9},
["j"] = {x = 149, y = 21, w = 8, h = 10},
["k"] = {x = 158, y = 21, w = 7, h = 10},
["l"] = {x = 166, y = 21, w = 6, h = 10},
["m"] = {x = 173, y = 21, w = 9, h = 9},
["n"] = {x = 183, y = 21, w = 7, h = 10},
["o"] = {x = 191, y = 21, w = 8, h = 9},
["p"] = {x = 200, y = 21, w = 8, h = 9},
["q"] = {x = 209, y = 21, w = 8, h = 9},
["r"] = {x = 218, y = 21, w = 8, h = 10},
["s"] = {x = 227, y = 21, w = 8, h = 9},
["t"] = {x = 236, y = 21, w = 7, h = 9},
["u"] = {x = 0, y = 31, w = 8, h = 10},
["v"] = {x = 9, y = 31, w = 8, h = 10},
["w"] = {x = 19, y = 31, w = 8, h = 10},
["x"] = {x = 28, y = 31, w = 8, h = 10},
["y"] = {x = 36, y = 31, w = 9, h = 10},
["z"] = {x = 46, y = 31, w = 9, h = 10},
["("] = {x = 56, y = 31, w = 7, h = 10},
["|"] = {x = 65, y = 31, w = 7, h = 10},
[")"] = {x = 74, y = 31, w = 9, h = 10},
["{"] = {x = 56, y = 31, w = 7, h = 10},
["}"] = {x = 56, y = 31, w = 7, h = 10},
};
local FONT_TEXTURE = Material("unrealhud/font1.png", "noclamp");
local WHITE_TEXTURE = Material("unrealhud/font2.png", "noclamp");
local BLANK = 5;
--[[------------------------------------------------------------------
Draws a character
@param {number} x
@param {number} y
@param {string} character
@param {boolean|nil} should be tinted white
@param {number|nil} scale
@param {Color|nil} colour
]]--------------------------------------------------------------------
function U1HUD:DrawCharacter(x, y, char, tint, scale, colour)
if (not CHARACTERS[char]) then return end
scale = scale or 1;
colour = colour or U1HUD.WHITE;
if (tint) then
surface.SetMaterial(WHITE_TEXTURE);
else
surface.SetMaterial(FONT_TEXTURE);
end
surface.SetDrawColor(colour);
local data = CHARACTERS[char];
surface.DrawTexturedRectUV(x, y, math.Round(data.w * scale), math.Round(data.h * scale), data.x/FILE_W, data.y/FILE_H, (data.x + data.w)/FILE_W, (data.y + data.h)/FILE_H);
end
--[[------------------------------------------------------------------
Returns the text size
@param {string} text
@param {number} scale
@return {number} width
]]--------------------------------------------------------------------
function U1HUD:GetTextSize(text, scale)
if (type(text) == "string") then text = string.ToTable(text); end
local size = 0;
for i, char in pairs(text) do
if (CHARACTERS[char]) then
size = size + (CHARACTERS[char].w * scale);
else
size = size + (BLANK * scale);
end
end
return size;
end
--[[------------------------------------------------------------------
Draws a text
@param {number} x
@param {number} y
@param {string} text
@param {number|nil} alignment
@param {boolean|nil} should be tinted white
@param {number|nil} scale
@param {Color|nil} colour
]]--------------------------------------------------------------------
function U1HUD:DrawText(x, y, text, align, tint, scale, colour)
scale = scale or 1;
local chars = string.ToTable(text);
-- Apply offset
local offset = 0;
local size = 0;
if (align == TEXT_ALIGN_RIGHT) then
offset = -U1HUD:GetTextSize(text, scale);
elseif (align == TEXT_ALIGN_CENTER) then
offset = -U1HUD:GetTextSize(text, scale) * 0.5;
end
-- Draw
local pos = 0;
for i, char in pairs(chars) do
if (not CHARACTERS[char]) then pos = pos + (BLANK * scale); continue; end
U1HUD:DrawCharacter(x + offset + pos, y, char, tint, scale, colour);
pos = pos + (CHARACTERS[char].w * scale);
end
end
end
|
local client = require "resty.websocket.client"
local wb, err = client:new()
local uri = "ws://127.0.0.1:8000/l"
local ok, err = wb:connect(uri)
if not ok then
ngx.say("failed to connect: " .. err)
return
end
local data = "test ok!"
local bytes, err = wb:send_text("copy: " .. data)
if not bytes then
ngx.say("failed to send frame: ", err)
return
end
local data, typ, err = wb:recv_frame()
if not data then
ngx.say("failed to receive the frame: ", err)
return
end
ngx.say(string.format("received: [%s] typ(%s) err(%s)", data, typ, err))
local bytes, err = wb:send_close()
if not bytes then
ngx.say("failed to send frame: ", err)
return
end
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseBossTakeReward_pb', package.seeall)
local BSEBOSSTAKEREWARD = protobuf.Descriptor();
local BSEBOSSTAKEREWARD_SUCCESS_FIELD = protobuf.FieldDescriptor();
local BSEBOSSTAKEREWARD_DESC_FIELD = protobuf.FieldDescriptor();
BSEBOSSTAKEREWARD_SUCCESS_FIELD.name = "success"
BSEBOSSTAKEREWARD_SUCCESS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBossTakeReward.success"
BSEBOSSTAKEREWARD_SUCCESS_FIELD.number = 1
BSEBOSSTAKEREWARD_SUCCESS_FIELD.index = 0
BSEBOSSTAKEREWARD_SUCCESS_FIELD.label = 2
BSEBOSSTAKEREWARD_SUCCESS_FIELD.has_default_value = true
BSEBOSSTAKEREWARD_SUCCESS_FIELD.default_value = true
BSEBOSSTAKEREWARD_SUCCESS_FIELD.type = 8
BSEBOSSTAKEREWARD_SUCCESS_FIELD.cpp_type = 7
BSEBOSSTAKEREWARD_DESC_FIELD.name = "desc"
BSEBOSSTAKEREWARD_DESC_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBossTakeReward.desc"
BSEBOSSTAKEREWARD_DESC_FIELD.number = 2
BSEBOSSTAKEREWARD_DESC_FIELD.index = 1
BSEBOSSTAKEREWARD_DESC_FIELD.label = 1
BSEBOSSTAKEREWARD_DESC_FIELD.has_default_value = false
BSEBOSSTAKEREWARD_DESC_FIELD.default_value = ""
BSEBOSSTAKEREWARD_DESC_FIELD.type = 9
BSEBOSSTAKEREWARD_DESC_FIELD.cpp_type = 9
BSEBOSSTAKEREWARD.name = "BseBossTakeReward"
BSEBOSSTAKEREWARD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBossTakeReward"
BSEBOSSTAKEREWARD.nested_types = {}
BSEBOSSTAKEREWARD.enum_types = {}
BSEBOSSTAKEREWARD.fields = {BSEBOSSTAKEREWARD_SUCCESS_FIELD, BSEBOSSTAKEREWARD_DESC_FIELD}
BSEBOSSTAKEREWARD.is_extendable = false
BSEBOSSTAKEREWARD.extensions = {}
BseBossTakeReward = protobuf.Message(BSEBOSSTAKEREWARD)
_G.BSEBOSSTAKEREWARD_PB_BSEBOSSTAKEREWARD = BSEBOSSTAKEREWARD
|
local _ = require('bzst17')
|
--[[
Attach this script to an Actor to allow it to stretch and compress itself to
adapt to viewport size. Generally it should be used on panel backgrounds.
The script requires the Actor to have any combination of these properties:
* "Left" & "LeftEnd"
* "Right" & "RightEnd"
* "Up" & "UpEnd"
* "Down" & "DownEnd"
Each pair of property declares:
* A boolean ([true;false]), enabling/disabling the stretching direction.
* A number ([0;100]), indicating a percentage of the screen where the stretching should
end.
For example:
* "Right" checked and "RightEnd" set to "100" would mean that the given Actor should
stretch up to the width of the window.
* "Right" checked and "RightEnd" set to "50" would mean that the given Actor should
stretch up to half of the window width.
Property values should make sense, i.e. "LeftEnd" should never be greater than "RightEnd".
]]
local thisActor = ...
local size_changed = false
--- Actor Properties used to define stretching behavior:
local _right = scaleform.Actor.property(thisActor, "Right")
local _right_end = scaleform.Actor.property(thisActor, "RightEnd")
local _right_end_offset = scaleform.Actor.property(thisActor, "RightEndOffset")
local _left = scaleform.Actor.property(thisActor, "Left")
local _left_end = scaleform.Actor.property(thisActor, "LeftEnd")
local _left_end_offset = scaleform.Actor.property(thisActor, "LeftEndOffset")
local _up = scaleform.Actor.property(thisActor, "Up")
local _up_end = scaleform.Actor.property(thisActor, "UpEnd")
local _up_end_offset = scaleform.Actor.property(thisActor, "UpEndOffset")
local _down = scaleform.Actor.property(thisActor, "Down")
local _down_end = scaleform.Actor.property(thisActor, "DownEnd")
local _down_end_offset = scaleform.Actor.property(thisActor, "DownEndOffset")
--- Send a "StretchComplete" Event, to notify potential listeners that the stretching computation
--- was applied.
--
-- Some parts of the UI might require updates after applying a stretch (scroll panels for example).
-- Registering to the "scaleform.EventTypes.ViewportResize" Event could trigger callbacks before
-- the stretching is applied (since the computation itself happens when that very event is fired),
-- thus is custom notification is required.
local function _notify_stretch_complete()
local event = {
eventId = scaleform.EventTypes.Custom,
name = "GUI.Stretch.Complete",
data = {
target = scaleform.Actor.name(scaleform.Actor.scene(thisActor)),
sender = scaleform.Actor.name(thisActor)
}
}
scaleform.Stage.dispatch_event(event)
end
--- Stretch the Actor to the Right.
--
-- @param right_end Percentage of the right area to strech out to.
local function _stretch_right(right_end, end_offset)
local rect = scaleform.Actor.world_bounds(thisActor)
local scale = scaleform.Actor.local_scale(thisActor)
local current_width = rect.x2 - rect.x1
local start_point = rect.x1
local end_point = scaleform.Stage.dimensions().width * right_end / 100
local required_width = math.abs(end_point - start_point - end_offset)
--scale
local ratio = current_width / required_width
local difference = required_width - current_width
if (math.abs(difference) >= 1) then
scale.x = scale.x / ratio
scaleform.Actor.set_local_scale(thisActor, scale)
end
--The actor may be offset on account of pivot point. adapt position
local offset = scaleform.Actor.world_bounds(thisActor).x1 - start_point
if offset ~= 0 then
local pos = scaleform.Actor.local_position(thisActor)
pos.x = pos.x - offset
scaleform.Actor.set_local_position(thisActor, pos)
end
end
--- Stretch the Actor to the Left.
--
-- @param left_end Percentage of the left area to strech out to.
local function _stretch_left(left_end, end_offset)
local rect = scaleform.Actor.world_bounds(thisActor)
local scale = scaleform.Actor.local_scale(thisActor)
local current_width = rect.x2 - rect.x1
local start_point = rect.x2
local end_point = scaleform.Stage.dimensions().width * left_end / 100
local required_width = math.abs(end_point - start_point - end_offset)
--scale
local ratio = current_width / required_width
local difference = required_width - current_width
if (math.abs(difference) >= 1) then
scale.x = scale.x / ratio
scaleform.Actor.set_local_scale(thisActor, scale)
end
--The actor may be offset on account of pivot point. adapt position
local offset = scaleform.Actor.world_bounds(thisActor).x2 - start_point
if offset ~= 0 then
local pos = scaleform.Actor.local_position(thisActor)
pos.x = pos.x - offset
scaleform.Actor.set_local_position(thisActor, pos)
end
end
--- Stretch the Actor Up.
--
-- @param up_end Percentage of the up area to strech out to.
local function _stretch_up(up_end, end_offset)
local rect = scaleform.Actor.world_bounds(thisActor)
local scale = scaleform.Actor.local_scale(thisActor)
local current_height = rect.y1 - rect.y2
local start_point = rect.y2
local end_point = scaleform.Stage.dimensions().height * up_end / 100
local required_height = math.abs(end_point - start_point - end_offset)
-- Scale:
local ratio = current_height / required_height
local difference = required_height - current_height
if (math.abs(difference) >= 1) then
scale.y = scale.y / ratio
scaleform.Actor.set_local_scale(thisActor, scale)
end
-- The Actor may be offset on account of pivot point. Adapt position:
local offset = scaleform.Actor.world_bounds(thisActor).y2 - start_point
if offset ~= 0 then
local pos = scaleform.Actor.local_position(thisActor)
pos.y = pos.y - offset
scaleform.Actor.set_local_position(thisActor, pos)
end
end
--- Stretch the Actor Down.
--
-- @param down_end Percentage of the down area to strech out to.
local function _stretch_down(down_end, end_offset)
local rect = scaleform.Actor.world_bounds(thisActor)
local scale = scaleform.Actor.local_scale(thisActor)
local current_height = rect.y2 - rect.y1
local start_point = rect.y1
local end_point = scaleform.Stage.dimensions().height * down_end / 100
local required_height = math.abs(end_point - start_point - end_offset)
-- Scale:
local ratio = current_height / required_height
local difference = required_height - current_height
if (math.abs(difference) >= 1) then
scale.y = scale.y / ratio
scaleform.Actor.set_local_scale(thisActor, scale)
end
-- The Actor may be offset on account of pivot point. Adapt position:
local offset = scaleform.Actor.world_bounds(thisActor).y1 - start_point
if offset ~= 0 then
local pos = scaleform.Actor.local_position(thisActor)
pos.y = pos.y - offset
scaleform.Actor.set_local_position(thisActor, pos)
end
end
--- Handle the stretching of the Actor in any direction, according to its set Dynamic Properties.
local function _stretch()
-- Handle the stretching to the Right:
if (_right and _right ~= "Right" and _right_end and _right_end ~= "RightEnd") then
local end_offset = 0
if (_right_end_offset and _right_end_offset ~= "RightEndOffset") then
end_offset = _right_end_offset
end
_stretch_right(_right_end, end_offset)
end
-- Handle the stretching to the Left:
if (_left and _left ~= "Left" and _left_end and _left_end ~= "LeftEnd") then
local end_offset = 0
if (_left_end_offset and _left_end_offset ~= "LeftEndOffset") then
end_offset = _left_end_offset
end
_stretch_left(_left_end, end_offset)
end
-- Handle the stretching up:
if (_up and _up ~= "Up" and _up_end and _up_end ~= "UpEnd") then
local end_offset = 0
if (_up_end_offset and _up_end_offset ~= "UpEndOffset") then
end_offset = _up_end_offset
end
_stretch_up(_up_end, end_offset)
end
-- Handle the stretching down:
if (_down and _down ~= "Down" and _down_end and _down_end ~= "DownEnd") then
local end_offset = 0
if (_down_end_offset and _down_end_offset ~= "DownEndOffset") then
end_offset = _down_end_offset
end
_stretch_down(_down_end, end_offset)
end
-- Notify potential listeners that the stretching computation is over:
_notify_stretch_complete()
end
local added_listener = scaleform.EventListener.create(added_listener, function(e)
_stretch()
end);
local viewport_resize_listener = scaleform.EventListener.create(viewport_resize_listener, function (e)
size_changed = true
end);
local leave_frame_listener = scaleform.EventListener.create(leave_frame_listener, function (e)
if size_changed then
_stretch()
size_changed = false
end
end);
scaleform.EventListener.connect(added_listener, thisActor, scaleform.EventTypes.AddedToStage)
scaleform.EventListener.connect(viewport_resize_listener, thisActor, scaleform.EventTypes.ViewportResize)
scaleform.EventListener.connect(leave_frame_listener, thisActor, scaleform.EventTypes.LeaveFrame)
|
local function loadfilefrompath(cad)
-- TODO win32,linux,mac?
cad = string.gsub(cad, "%.",path_sep) --"/")
------------------------------------
local paths = stsplit(package.path,";")
for i, path in ipairs(paths) do
local file=string.gsub(path,"?",cad)
local exist = io.open(file)
if exist then
exist:close()
local chunk,errorst = loadfile(file)
print("loadfilefrompath",file,errorst)
if chunk then
return chunk
end
end
end
error("could not loadfilefrompath "..cad)
end
local function newrequire(cad)
local env = getfenv(2)
if package.loaded[cad] then return package.loaded[cad] end
local chunk = loadfilefrompath(cad)
setfenv(chunk, env)
package.loaded[cad] = chunk()
return package.loaded[cad]
end
local CachedFiles = {files = {}}
function CachedFiles:open(name)
if self.files[name] then return end
self.files[name] = {}
local file = io.open(name)
if not file then print("CachedFiles:Error opening "..tostring(name).."\n"); return end
for i=1,math.huge do
local str = file:read()
if not str then break end
self.files[name][i] = str
end
file:close()
end
function CachedFiles:read(name,line)
if not self.files[name] then self:open(name) end
return self.files[name][line]
end
function getSourceLine(source,line)
return CachedFiles:read(source,line)
end
function loadinEnv(file,env)
local function newindex(t,key,val)
--[[ the functions are done in other place
local info=debug.getinfo(2)
--print ("setting "..key.." from line "..info.currentline.." in file "..info.short_src)
local src
if type(val)=="function" then
src = getSourceLine(info.source:sub(2),info.currentline)
end
local args
if src then args = src:match(".-function.-(%(.+%))") end
sckeywordsSource[key] = {currentline = info.currentline,source = info.source,def=src,args=args}
--]]
if type(val) == "table" then
local info=debug.getinfo(2)
sckeywordsSource[key] = {currentline = info.currentline,source = info.source}
end
rawset(t,key,val)
end
if not env then
env = setmetatable({}, {__index = _G,__newindex = newindex})
env.require = newrequire
env.package = setmetatable({}, {__index = _G.package})
env.package.loaded = {}
end
local f = loadfilefrompath(file)
setfenv(f, env)
f()
return env
end
function GetSCKeyWords()
require"random" -- dont want to require dll in env TODO:solve it other way
socket = require"socket" -- dont want to require dll in env TODO:solve it other way
sckeywordsSource = {}
local env = loadinEnv"sc.callback_wrappers"
loadinEnv("sc.synthdefsc",env)
loadinEnv("sc.playerssc",env)
loadinEnv("sc.stream",env)
loadinEnv("sc.utils",env)
loadinEnv("sc.miditoosc",env)
loadinEnv("sc.scbuffer",env)
loadinEnv("sc.routines",env)
--loadinEnv("sc.ctrl_bus",env)
loadinEnv("sc.oscfunc",env)
local keyword_table = {}
for index, value in pairs(env) do
if type(value)=="function" then
table.insert(keyword_table, index.." ")
local info = debug.getinfo(value)
local src = getSourceLine(info.source:sub(2),info.linedefined)
local args
if src then args = src:match(".-function.-(%(.+%))") end
sckeywordsSource[index] = {currentline = info.linedefined,source = info.source,def=src,args=args}
elseif type(value)=="table" then
table.insert(keyword_table, index.." ")
for i2,v2 in pairs(value) do
if type(v2)=="function" then
table.insert(keyword_table, index.."."..i2.." ")
local info = debug.getinfo(v2)
local src = getSourceLine(info.source:sub(2),info.linedefined)
local args
if src then args = src:match(".-function.-(%(.+%))") end
sckeywordsSource[index.."."..i2] = {currentline = info.linedefined,source = info.source,def=src,args=args}
end
end
end
end
--LogFile(ToStr(sckeywordsSource))
table.sort(keyword_table)
return table.concat(keyword_table)
end
|
local Host = require 'autoswagger.host'
local API = require 'autoswagger.api'
describe('API', function()
local host
before_each(function()
host = Host:new('foo', nil, nil, nil, 'host_guid')
end)
it('can be created', function()
local api = API:new(host, '/foo/bar', 'api_guid')
assert.equal(api.host, host)
assert.equal(api.path, '/foo/bar')
end)
describe('add_operation_info', function()
it('adds parameter info to the api', function()
local a = API:new(host, '/api/accounts/*.xml', 'api_guid')
a:add_operation_info("PUT",
"/api/accounts/42",
"user_id=1&cat_id=4")
assert.truthy(a.operations.PUT)
assert.truthy(a.operations.PUT.parameters.account_id)
end)
end)
describe('get_swagger_path', function()
it('replaces wildcards with awesome names', function()
local a = API:new(host, '/apis/*/accounts/*.xml', 'api_guid')
assert.equal(a:get_swagger_path(), '/apis/{api_id}/accounts/{account_id}.xml')
end)
end)
describe('new_from_table', function()
it('creates a new api', function()
local tbl = {
path = "/foo/bar/*.xml",
operations = {
{ method = 'GET',
parameters = {
{ paramType = 'path',
name = 'app_id',
values = {'8', '9', '10'}
}
}
},
{ method = 'POST',
parameters = {
{ paramType = 'path',
name = 'app_id',
possible_values = {'8', '9', '10'}
}
}
}
}
}
local api = API:new_from_table(host, tbl)
assert.equal(api.path, '/foo/bar/*.xml')
assert.same(api:get_methods(), {'GET', 'POST'})
end)
end)
end)
|
hosted_init()
--if CONFIG.auto_resolution then
gl.setup(NATIVE_WIDTH, NATIVE_HEIGHT)
--else
--gl.setup(CONFIG.width, CONFIG.height)
--end
--util.no_globals()
local on = false
local font = resource.load_font "silkscreen.ttf"
util.data_mapper{
state = function(state)
on = state == '1'
end,
}
node.set_flag("slow_gc", false)
local iblib = require "iblib"
setmetatable(_G, {
__newindex = function(t, k, v)
error("cannot assign " .. k)
end
})
local title_start = 99999999
local idx = 0 -- offset before first item. will be incremented during first get_next_item
local playlist_source = function()
return CONFIG.playlist
end;
local playlist_source2 = function()
return CONFIG.playlist2
end;
local overlay = resource.create_colored_texture(0, 0, 0, 1)
local player = iblib.playlist{
get_next_item = function()
local playlist = playlist_source()
idx = idx + 1
if idx > #playlist then
idx = 1
end
local item = playlist[idx]
if not item then
return nil
else
return {
title = item.title;
duration = item.duration;
obj = item.file();
}
end
end;
get_switch_time = function()
return 0
end;
fade = function(...)
title_start = sys.now() + 1.0
return 0
end;
draw = util.draw_correct;
}
local player2 = iblib.playlist{
get_next_item = function()
local playlist = playlist_source2()
idx = idx + 1
if idx > #playlist then
idx = 1
end
local item = playlist[idx]
if not item then
return nil
else
return {
title = item.title;
duration = item.duration;
obj = item.file();
}
end
end;
get_switch_time = function()
return 0
end;
fade = function(...)
title_start = sys.now() + 1.0
return 0
end;
draw = util.draw_correct;
}
function node.render()
--CONFIG.background_color.clear()
if on then
player2.draw(0, 0, WIDTH, HEIGHT) --font:write(120, 320, "RED", 100, 1,1,1,1)
else
player.draw(0, 0, WIDTH, HEIGHT)
end
end
|
-----------------------------------------
-- ID: 5588
-- Item: serving_of_karni_yarik
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Agility 3
-- Vitality -1
-- Attack % 20 (cap 65)
-- Ranged Attack % 20 (cap 65)
-- Evasion +6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD, 0, 0, 1800, 5588)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.AGI, 3)
target:addMod(tpz.mod.VIT, -1)
target:addMod(tpz.mod.FOOD_ATTP, 20)
target:addMod(tpz.mod.FOOD_ATT_CAP, 65)
target:addMod(tpz.mod.FOOD_RATTP, 20)
target:addMod(tpz.mod.FOOD_RATT_CAP, 65)
target:addMod(tpz.mod.EVA, 6)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.AGI, 3)
target:delMod(tpz.mod.VIT, -1)
target:delMod(tpz.mod.FOOD_ATTP, 20)
target:delMod(tpz.mod.FOOD_ATT_CAP, 65)
target:delMod(tpz.mod.FOOD_RATTP, 20)
target:delMod(tpz.mod.FOOD_RATT_CAP, 65)
target:delMod(tpz.mod.EVA, 6)
end
|
AddCSLuaFile()
ENT.Type = "anim"
ENT.PrintName = "Garbage"
ENT.Author = "Black Tea"
ENT.Category = "NutScript - CityRP"
ENT.Spawnable = true
ENT.AdminOnly = false
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.modelTable = {
"models/props_junk/PopCan01a.mdl",
"models/props_junk/plasticbucket001a.mdl",
"models/props_junk/metal_paintcan001a.mdl",
"models/props_c17/lamp001a.mdl",
"models/props_c17/metalPot002a.mdl",
"models/props_junk/garbage_milkcarton002a.mdl",
"models/props_junk/garbage_milkcarton001a.mdl",
"models/props_junk/garbage_metalcan002a.mdl",
"models/props_junk/garbage_metalcan001a.mdl",
"models/props_junk/garbage_glassbottle003a.mdl",
"models/props_junk/garbage_glassbottle002a.mdl",
"models/props_junk/garbage_glassbottle001a.mdl",
"models/props_junk/garbage_coffeemug001a.mdl",
"models/props_junk/garbage_plasticbottle001a.mdl",
"models/props_junk/garbage_plasticbottle003a.mdl",
"models/props_junk/garbage_takeoutcarton001a.mdl",
"models/props_junk/GlassBottle01a.mdl",
}
if (SERVER) then
CITYRP_JUNKS = CITYRP_JUNKS or {}
function ENT:Initialize()
self:SetModel(table.Random(self.modelTable))
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
self:SetUseType(SIMPLE_USE)
self:DrawShadow(false)
self:PhysWake()
CITYRP_JUNKS[self:EntIndex()] = self
for k, v in ipairs(player.GetAll()) do
local char = v:getChar()
if (char) then
local class = char:getClass()
if (class != CLASS_HOBO) then
self:SetPreventTransmit(v, true)
end
end
end
timer.Simple(100, function()
if (self and self:IsValid()) then
self:Remove()
end
end)
end
function ENT:Use(client)
if (self:isVisible(client)) then
self:EmitSound("physics/cardboard/cardboard_box_break"..math.random(1, 3)..".wav")
client:setNetVar("garbage", client:getNetVar("garbage", 0) + math.random(10, 20))
self:Remove()
end
end
function ENT:OnTakeDamage(dmginfo)
end
function ENT:OnRemove()
CITYRP_JUNKS[self:EntIndex()] = nil
end
-- CityRP only hook
hook.Add("ResetVariables", "nutTransmitUpdate", function(client, signal)
local char = client:getChar()
if (char) then
local class = char:getClass()
if (class) then
if (class == CLASS_HOBO) then
for k, v in pairs(CITYRP_JUNKS) do
v:SetPreventTransmit(client, false)
end
else
for k, v in pairs(CITYRP_JUNKS) do
v:SetPreventTransmit(client, true)
end
end
end
end
end)
else
function ENT:Draw()
if (self:isVisible()) then
self:DrawModel()
end
end
function ENT:onShouldDrawEntityInfo()
return self:isVisible()
end
function ENT:onDrawEntityInfo(alpha)
local position = (self:LocalToWorld(self:OBBCenter()) + self:GetUp()*25):ToScreen()
local x, y = position.x, position.y
nut.util.drawText(L"garbage", x, y, ColorAlpha(nut.config.get("color"), alpha), 1, 1, nil, alpha * 0.65)
nut.util.drawText(L"garbaseDesc", x, y + 16, ColorAlpha(color_white, alpha), 1, 1, "nutSmallFont", alpha * 0.65)
end
end
function ENT:isVisible(client)
if (CLIENT) then
client = LocalPlayer()
end
local char = client:getChar()
if (char) then
local class = char:getClass()
return (class == CLASS_HOBO)
end
return
end
|
if path == nil then path = {} end
---[[
function path:find_path(unit, path_corners)
unit.next_corner_num = 1
Timers:CreateTimer(0.1, function()
local i = tonumber(unit.next_corner_num)
local path_corner = path_corners[i]
if path_corner then
local next_corner = Entities:FindByName(nil, path_corner)
if not GameRules:IsGamePaused() then
local next_corner_point = next_corner:GetOrigin()
local distance = path:distance_between_two_point(
unit:GetOrigin(), next_corner_point)
-- 到达目标点附近,指向下一个点,否则继续移动到目标点
if (distance <= 10.0 and distance >= 0) then
unit.next_corner_num = i + 1
else
unit:MoveToPositionAggressive(next_corner_point)
end
end
end
return 0.1
end)
return 0.1
end
-- ]]
-- 计算两点(三维向量)之间距离
function path:distance_between_two_point(point_1, point_2)
return ((point_1.x - point_2.x) ^ 2 + (point_1.y - point_2.y) ^ 2) ^ 0.5
end
|
--ELF·远古森林巨龙
function c1190103.initial_effect(c)
--
aux.AddSynchroProcedure(c,c1190103.syfilter1,c1190103.syfilter2,1)
c:EnableReviveLimit()
--
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,1190103)
e1:SetCost(c1190103.cost1)
e1:SetCondition(c1190103.con1)
e1:SetOperation(c1190103.op1)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCountLimit(1,1190153)
e2:SetCondition(c1190103.con2)
e2:SetTarget(c1190103.tg2)
e2:SetOperation(c1190103.op2)
c:RegisterEffect(e2)
local e5=e2:Clone()
e5:SetCode(EVENT_REMOVE)
c:RegisterEffect(e5)
local e6=e2:Clone()
e6:SetCode(EVENT_TO_DECK)
c:RegisterEffect(e6)
--
end
--
c1190103.named_with_ELF=1
function c1190103.IsELF(c)
local m=_G["c"..c:GetCode()]
return m and m.named_with_ELF
end
--
function c1190103.syfilter1(c)
return c1190002.IsELF(c) and c:IsType(TYPE_TUNER)
end
function c1190103.syfilter2(c)
return c1190002.IsELF(c) and c:IsType(TYPE_MONSTER)
end
--
function c1190103.con1(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO
end
function c1190103.cost1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,2000) end
Duel.PayLPCost(tp,2000)
end
function c1190103.op1(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetReset(RESET_PHASE+PHASE_END,2)
Duel.RegisterEffect(e1,tp)
end
--
function c1190103.con2(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and e:GetHandler():IsPreviousPosition(POS_FACEUP)
end
function c1190103.filter2(c,e,tp)
return c1190002.IsELF(c) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsLevelBelow(1) and c:IsType(TYPE_MONSTER)
end
function c1190103.tg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c1190103.filter2,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_DECK)
end
function c1190103.op2(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c1190103.filter2,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
|
function engineBreak()
local health = getElementHealth(source)
local driver = getVehicleController(source)
local vehID = getElementData(source, "dbid")
if (driver) then
if (health<=300) then
local rand = math.random(1, 2)
if (rand==1) then -- 50% chance
setVehicleEngineState(source, false)
exports.mrp_anticheat:changeProtectedElementDataEx(source, "engine", 0, false)
exports.mrp_global:sendLocalDoAction(driver, "Aracın motorunda çok hasar var.")
-- Take key / Give key to player when engine off by Anthony
if exports['mrp_global']:hasItem(source, 3, vehID) then
exports['mrp_global']:takeItem(source, 3, vehID)
exports['mrp_global']:giveItem(driver, 3, vehID)
else
end
end
elseif (health<=400) then
local rand = math.random(1, 5)
if (rand==1) then -- 20% chance
setVehicleEngineState(source, false)
exports.mrp_anticheat:changeProtectedElementDataEx(source, "engine", 0, false)
exports.mrp_global:sendLocalDoAction(driver, "Aracın motorunda çok hasar var.")
-- Take key / Give key to player when engine off by Anthony
if exports['mrp_global']:hasItem(source, 3, vehID) then
exports['mrp_global']:takeItem(source, 3, vehID)
exports['mrp_global']:giveItem(driver, 3, vehID)
else
end
end
end
end
end
addEventHandler("onVehicleDamage", getRootElement(), engineBreak)
|
function GM.PlayerBindPressPERP2 ( Player, Bind, Press )
if (string.find(string.lower(Bind), "voicerecord") && !Player:Alive()) then return true; end
if (string.find(string.lower(Bind), "zoom")) then return true; end
if (PERP_SpectatingEntity && Press) then
if (string.find(string.lower(Bind), "+jump")) then
PERP_SpectatingEntity = nil;
RunConsoleCommand("perp_a_ss");
return true;
elseif (string.find(string.lower(Bind), "+attack")) then
local ToDo
local GrabNext = false;
local First;
for k, v in pairs(player.GetAll()) do
if !First then
First = v;
end
if GrabNext then
ToDo = v;
break;
elseif v:UniqueID() == PERP_SpectatingEntity:UniqueID() then
GrabNext = true
end
end
if !ToDo then ToDo = First; end
PERP_SpectatingEntity = ToDo;
RunConsoleCommand('perp_a_s', ToDo:UniqueID())
return true;
elseif (string.find(string.lower(Bind), "+attack2")) then
local ToDo
local Last;
for k, v in pairs(player.GetAll()) do
if v:UniqueID() == PERP_SpectatingEntity:UniqueID() and Last then
ToDo = Last;
end
Last = v;
end
if !ToDo then ToDo = Last; end
PERP_SpectatingEntity = ToDo;
RunConsoleCommand('perp_a_s', ToDo:UniqueID())
return true;
end
return;
end
local vT;
if (LocalPlayer():InVehicle()) then vT = lookForVT(LocalPlayer():GetVehicle()); end
if (Press && string.find(string.lower(Bind), "impulse 100") && LocalPlayer():InVehicle()) then
RunConsoleCommand("perp_v_f");
elseif (Press && string.find(string.lower(Bind), "impulse 201") && LocalPlayer():InVehicle()) then
RunConsoleCommand("perp_v_ug");
elseif (Press && string.find(string.lower(Bind), "+reload") && LocalPlayer():InVehicle()) then
RunConsoleCommand("perp_v_su");
elseif (LocalPlayer():InVehicle() && (!vT || !vT.SirenNoise_Alt || !LocalPlayer():GetVehicle():GetNetworkedBool("siren", false)) && Press && string.find(string.lower(Bind), "+walk")) then
RunConsoleCommand("perp_v_h");
elseif (Press && string.find(string.lower(Bind), "+speed") && LocalPlayer():InVehicle()) then
RunConsoleCommand("perp_v_y");
elseif (Press && string.find(string.lower(Bind), "+menu")) then
RunConsoleCommand("perp_r_c");
elseif (string.find(string.lower(Bind), "+duck") && (Player:InVehicle() || PERP_SpectatingEntity) && Press) then
local iVal = GetConVar("gmod_vehicle_viewmode"):GetInt();
if ( iVal == 0 ) then iVal = 1 else iVal = 0 end
RunConsoleCommand("gmod_vehicle_viewmode", iVal)
return true;
end
end
hook.Add("PlayerBindPress", "PlayerBindPressPERP2", GM.PlayerBindPressPERP2)
CreateConVar("gmod_vehicle_viewmode",0)
|
local monitor = peripheral.wrap("top")
local terminal = term.redirect(monitor)
local door = true
local spawner = true
local file = "state.txt"
if fs.exists(file) then
local openFile = assert(fs.open(file, "r"))
if openFile.readLine() == "false" then
door = false
end
if openFile.readLine() == "false" then
spawner = false
end
openFile.close()
end
while true do
redstone.setOutput("left",door)
redstone.setOutput("back",spawner)
term.setBackgroundColor(colors.black)
term.clear()
if door then
paintutils.drawFilledBox(1,1,7,2,colors.green)
term.setBackgroundColor(colors.green)
term.setTextColor(colors.white)
term.setCursorPos(1,1)
term.write("Door")
term.setCursorPos(1,2)
term.write("Closed")
else
paintutils.drawFilledBox(1,1,7,2,colors.red)
term.setBackgroundColor(colors.red)
term.setTextColor(colors.white)
term.setCursorPos(1,1)
term.write("Door")
term.setCursorPos(1,2)
term.write("Opened")
end
if spawner then
paintutils.drawFilledBox(1,4,7,5,colors.red)
term.setBackgroundColor(colors.red)
term.setTextColor(colors.white)
term.setCursorPos(1,4)
term.write("Spawner")
term.setCursorPos(1,5)
term.write("Offline")
else
paintutils.drawFilledBox(1,4,7,5,colors.green)
term.setBackgroundColor(colors.green)
term.setTextColor(colors.white)
term.setCursorPos(1,4)
term.write("Spawner")
term.setCursorPos(1,5)
term.write("Online")
end
_,_,xPos,yPos = os.pullEvent("monitor_touch")
if yPos <= 2 then
door = not door
elseif yPos >= 4 then
spawner = not spawner
end
local fileHandle = fs.open(file,"w")
fileHandle.write(tostring(door).."\n")
fileHandle.write(tostring(spawner))
fileHandle.close()
end
|
local PLUGIN = PLUGIN
function PLUGIN:LoadData()
SH_SZ.SafeZones = self:GetData() or {}
for _, sz in pairs(SH_SZ.SafeZones) do
local shape = SH_SZ.ShapesIndex[sz.shape]
if (!shape) then
return end
SH_SZ:CreateSafeZone(sz, shape)
end
end
function PLUGIN:SaveData()
self:SetData(SH_SZ.SafeZones)
end
function PLUGIN:CanPlayerEnterSafeZone(entity, activator)
if (activator:GetPenaltyTime() > CurTime()) then
local dir = (entity:GetPos() - activator:GetPos()):GetNormalized()
activator:SetVelocity(dir * -100)
return false
end
end
function PLUGIN:PlayerExitSafeZone(client)
client.protection_time = CurTime() + 10
client:SetNoCollideWithTeammates(false)
client:SetAvoidPlayers(true)
-- client:SetCollisionGroup(COLLISION_GROUP_PLAYER)
end
function PLUGIN:PlayerEnterSafeZone(client)
-- client:SetCollisionGroup(COLLISION_GROUP_PASSABLE_DOOR)
client:SetNoCollideWithTeammates(true)
client:SetAvoidPlayers(false)
if (self.collides[client]) then
self.collides[client] = nil
end
end
function PLUGIN:PlayerSpawn(client)
client:SetNoCollideWithTeammates(false)
client:SetAvoidPlayers(true)
if (self.collides[client]) then
self.collides[client] = nil
end
end
-- идиотский ShouldCollide крашит физику, пришлось костыль сделать.
PLUGIN.collides = PLUGIN.collides or {}
timer.Create("StuckPlayers", 0.5, 0, function()
for _, v in ipairs(player.GetAll()) do
if (IsValid(v) and !PLUGIN.collides[v] and v:Alive() and v:GetMoveType() == MOVETYPE_WALK and v:GetLocalVar("SH_SZ.Safe", SH_SZ.OUTSIDE) == SH_SZ.OUTSIDE and v:IsStuck()) then
v:SetNoCollideWithTeammates(true)
v:SetAvoidPlayers(true)
PLUGIN.collides[v] = true
end
end
if (table.IsEmpty(PLUGIN.collides)) then return end
for k in pairs(PLUGIN.collides) do
if (IsValid(k) and k:Alive() and k:GetMoveType() == MOVETYPE_WALK and k:GetLocalVar("SH_SZ.Safe", SH_SZ.OUTSIDE) == SH_SZ.OUTSIDE) then
if (!k:IsStuck()) then
k:SetNoCollideWithTeammates(false)
PLUGIN.collides[k] = nil
end
else
PLUGIN.collides[k] = nil
end
end
end)
|
local path = "hall/num_gold_pin.png"
local num_gold_pin_map = {
["wan.png"] = {
file=path,
x=2,y=2,
width=42,height=41,
rotated=true
},
["yi.png"] = {
file=path,
x=46,y=2,
width=42,height=39,
rotated=true
},
["%.png"] = {
file=path,
x=90,y=2,
width=29,height=42,
rotated=false
},
["-.png"] = {
file=path,
x=46,y=43,
width=42,height=25,
rotated=true
},
["8.png"] = {
file=path,
x=2,y=45,
width=42,height=23,
rotated=true
},
["6.png"] = {
file=path,
x=90,y=46,
width=23,height=42,
rotated=false
},
["9.png"] = {
file=path,
x=2,y=70,
width=42,height=23,
rotated=true
},
["0.png"] = {
file=path,
x=46,y=70,
width=42,height=23,
rotated=true
},
["7.png"] = {
file=path,
x=2,y=95,
width=42,height=23,
rotated=true
},
["4.png"] = {
file=path,
x=46,y=95,
width=42,height=23,
rotated=true
},
["3.png"] = {
file=path,
x=121,y=2,
width=42,height=22,
rotated=true
},
["5.png"] = {
file=path,
x=165,y=2,
width=42,height=22,
rotated=true
},
["2.png"] = {
file=path,
x=209,y=2,
width=42,height=21,
rotated=true
},
["1.png"] = {
file=path,
x=209,y=25,
width=42,height=14,
rotated=true
},
["dou.png"] = {
file=path,
x=121,y=26,
width=42,height=11,
rotated=true
},
["dian.png"] = {
file=path,
x=165,y=26,
width=42,height=9,
rotated=true
},
}
return num_gold_pin_map
|
outbreak_prisoner = Creature:new {
customName = "Afflicted Prisoner",
--objectName = "",
--randomNameType = NAME_GENERIC_TAG,
socialGroup = "outbreak_townsperson",
faction = "",
level = 100,
chanceHit = 0.5,
damageMin = 200,
damageMax = 600,
baseXp = 1400,
baseHAM = 7000,
baseHAMmax = 8000,
armor = 0,
resists = {10,5,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
scale = 1.2,
templates = {"object/mobile/outbreak_prisoner_m_04.iff",
"object/mobile/outbreak_prisoner_m_bith_01.iff",
"object/mobile/outbreak_prisoner_m_bith_02.iff",
"object/mobile/outbreak_prisoner_m_hum_01.iff",
"object/mobile/outbreak_prisoner_m_hum_02.iff",
"object/mobile/outbreak_prisoner_m_hum_03.iff",
"object/mobile/outbreak_prisoner_m_hum_04.iff",
"object/mobile/outbreak_prisoner_m_hum_05.iff",
"object/mobile/outbreak_prisoner_m_ith_01.iff",
"object/mobile/outbreak_prisoner_m_ith_02.iff",
"object/mobile/outbreak_prisoner_m_wke_01.iff",
"object/mobile/outbreak_prisoner_m_wke_02.iff",
"object/mobile/outbreak_prisoner_m_monc_01.iff",
"object/mobile/outbreak_prisoner_m_monc_02.iff",
"object/mobile/outbreak_prisoner_m_twi_01.iff",
"object/mobile/outbreak_prisoner_m_twi_02.iff",
"object/mobile/outbreak_prisoner_m_zab_01.iff",
"object/mobile/outbreak_prisoner_m_zab_02.iff",},
lootGroups = {
{
groups = {
{group = "junk", chance = 10000000}
},
lootChance = 10000000
},
{
groups = {
{group = "artifact", chance = 10000000}
},
lootChance = 1000000
},
{
groups = {
{group = "tierone", chance = 10000000}
},
lootChance = 750000
},
{
groups = {
{group = "tiertwo", chance = 10000000}
},
lootChance = 100000
},
{
groups = {
{group = "tierthree", chance = 10000000}
},
lootChance = 50000
},
{
groups = {
{group = "outbreak", chance = 10000000}
},
lootChance = 500000
},
},
weapons = {},
conversationTemplate = "",
reactionStf = "",
attacks = {
{"stunattack",""},
},
}
CreatureTemplates:addCreatureTemplate(outbreak_prisoner, "outbreak_prisoner")
|
local ls = require("luasnip")
local s = ls.snippet
local sn = ls.snippet_node
local t = ls.text_node
local i = ls.insert_node
local f = ls.function_node
local c = ls.choice_node
local d = ls.dynamic_node
ls.config.set_config({
history = true,
updateevents = "TextChanged,TextChangedI",
})
require("luasnip/loaders/from_vscode").lazy_load()
|
local math_floor = math.floor
local string_find = string.find
local string_sub = string.sub
local string_gsub = string.gsub
local table_insert = table.insert
p = 'C:/jlabenski/development/wx/wx/wxWidgets/wxWidgets-trunk/docs/doxygen/out/xml/'
--p = "/home/jlabenski/wx/wx-svn/wx/wxWidgets/wxWidgets-trunk/docs/doxygen/out/xml/"
f_html = {
'index.xml',
'defs_8h.xml',
'brush_8h.xml',
'classwx_brush.xml',
'artprov_8h.xml',
'classwx_art_provider.xml',
'classwx_html_cell.xml',
'classwx_html_cell_event.xml',
'classwx_html_colour_cell.xml',
'classwx_html_container_cell.xml',
'classwx_html_d_c_renderer.xml',
'classwx_html_easy_printing.xml',
'classwx_html_filter.xml',
'classwx_html_help_controller.xml',
'classwx_html_help_data.xml',
'classwx_html_help_dialog.xml',
'classwx_html_help_frame.xml',
'classwx_html_help_window.xml',
'classwx_html_link_event.xml',
'classwx_html_link_info.xml',
'classwx_html_list_box.xml',
'classwx_html_modal_help.xml',
'classwx_html_parser.xml',
'classwx_html_printout.xml',
'classwx_html_rendering_info.xml',
'classwx_html_rendering_style.xml',
'classwx_html_tag.xml',
'classwx_html_tag_handler.xml',
'classwx_html_tags_module.xml',
'classwx_html_widget_cell.xml',
'classwx_html_win_parser.xml',
'classwx_html_win_tag_handler.xml',
'classwx_html_window.xml',
'classwx_date_time.xml',
'classwx_date_span.xml'
}
--f_html = {p.."compound.xsd"}
--for line in io.lines(p.."/0dir.txt") do
-- f_html[#f_html+1] = line
--end
function parse()
local t1 = os.time()
--for i = 2,5 do --#f_html do
for i = 2,#f_html do
print(i, f_html[i])
local filename = p..f_html[i]
local T_file, T_xml = ParseXMLFile(filename)
DoxyXMLTable[filename] = T_xml
ParseDoxyXMLTable(T_xml)
end
local t2 = os.time()
print("Completed in : "..t2-t1.." secs")
end
DoxyXMLTable =
{
-- ["filename.xml"] = ParseXmlFile("filename.xml")
}
DoxyClassTable =
{
-- ["wxDateTime"] = {
-- baseclassnames[1] = { name="BaseClassName", prot="public/protected/private", virt="virtual/non-virtual" }
-- classname = "wxDateTime"
-- includes[1] = { local="yes/no", name="wx/datetime.h" }
-- innerclass = { "wxDateTime::TimeZone", "wxDateTime::Tm" } // member classes, if any.
-- kind = "class"
-- memberdef_enums[1] = {
-- kind = "enum",
-- name = "TZ",
-- prot = "public",
-- static = "no",
-- { {name = "Local"} {name = "EEST", initializer = "GMT3"} }
-- }
-- memberdef_functions = {
-- "Add"[1] = { // an array since there may be overloads
-- argstring = "(const wxDateSpan& diff) const", // everything after the function name
-- const = "yes/no",
-- definition = "virtual wxDateTime wxDateTime::Add" // everything before the '('
-- explicit = "yes/no"
-- inline = "yes/no"
-- kind = "function"
-- name = "Add"
-- params[1] = { declname = "diff", kind = "param", type = "const wxDateSpan&", types = { "const", "wxDateSpan", "&" } }
-- prot = "public"
-- static = "yes/no"
-- type = "wxDateTime" // the return value
-- types = { "wxDateTime" } // the return value unrolled, like types in params above
-- virt = "virtual/non-virtual"
-- }
-- }
-- memberdef_typedefs = {
-- definition = "typedef unsigned short wxDateTime::wxDateTime_t"
-- kind = "typedef"
-- name = "wxDateTime_t"
-- prot = "public"
-- static = "no"
-- type = "unsigned short"
-- types = { "unsigned short" }
-- }
-- memberdef_variables = {}
-- prot = "public/protected/private"
-- xml_filename = "/path/to/filename.xml"
-- }
}
DoxyFileTable = {
-- classes = { "wxBrush", "wxBrushList" }
-- defines = {}
-- enums[1] = {
-- { initializer = "-1", name = "wxBRUSHSTYLE_INVALID" },
-- kind = "enum",
-- name = "wxBrushStyle",
-- prot = "public",
-- static = "no"
-- }
-- filename = "brush.h"
-- functions = {}
-- kind = "file"
-- typedefs = {}
-- variables = {
-- { definition = "wxBrush wxNullBrush", kind = "variable", mutable = "no",
-- name = "wxNullBrush", prot = "public", static = "no", type = "wxBrush" }
-- }
-- xml_filename = "file.xml"
}
DoxyIndexTable = {}
-- --------------------------------------------------------------------------
-- Parse the Lua table returned by ParseXMLString from a Doxygen XML file
-- --------------------------------------------------------------------------
function ParseDoxyXMLTable(T_xml)
for k, v in ipairs(T_xml) do
if type(v) == "table" then
if (v.label == "xsd:schema") and (v.xarg["xmlns:xsd"] ~= nil) then
-- compound.xsd : <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
local T = {}
local T_file = ParseDoxyXSD_schema(v, T, T)
AddToTable(T_file, "xml_filename", T_xml.xml_filename)
AddToTable(DoxyFileTable, T_file.filename, T_file, v)
elseif (v.label == "compounddef") and (v.xarg.kind == "file") then
-- brush_8h.xml : <compounddef id="brush_8h" kind="file">
local T_file = ParseDoxyXML_compounddef_file(v, {})
AddToTable(T_file, "xml_filename", T_xml.xml_filename)
AddToTable(DoxyFileTable, T_file.filename, T_file, v)
elseif (v.label == "compounddef") and (v.xarg.kind == "class") then
-- classwx_brush.xml : <compounddef id="classwx_brush" kind="class" prot="public">
local T_class = ParseDoxyXML_compounddef_class(v, {})
AddToTable(T_class, "xml_filename", T_xml.xml_filename)
AddToTable(DoxyClassTable, T_class.classname, T_class)
elseif (v.label == "doxygen") then
-- this tag encloses the XML data in most of the files
-- <doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.5.5">
AddToTable(v, "xml_filename", T_xml.xml_filename)
ParseDoxyXMLTable(v)
elseif (v.label == "doxygenindex") then
-- this tag encloses the XML data in the file index.xml
-- <doxygenindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="index.xsd" version="1.5.5">
T_index = ParseDoxyXML_doxygenindex(v, {})
AddToTable(T_index, "xml_filename", T_xml.xml_filename)
DoxyIndexTable[#DoxyIndexTable+1] = T_index
else
print("Unknown value in ParseDoxyXMLTable:", k, v, " on line ", v.line, "in file", T_xml.xml_filename)
end
elseif (type(v) == "string") and string.find(v, "<?xml version") then
-- ignore
else
printf("Unknown XML tag in ParseDoxyXMLTable '%s'='%s' on line %d in file '%s'.", tostring(k), tostring(v), v.line or 0, T_xml.xml_filename)
end
end
end
-- --------------------------------------------------------------------------
-- Parse Doxygen XML Lua table for label="xsd:schema"
-- --------------------------------------------------------------------------
function ParseDoxyXSD_schema(T_xml, T_doxidx, T_root)
local func_name = "ParseDoxyXSD_schema"
if not T_root.xsd_types then
T_root["xsd_types"] = {}
end
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "xsd:element") then
if not v.xarg.type then
T_doxidx[v.xarg.name] = 0
else
-- create linked tables to access them both ways
if T_root["xsd_types"][v.xarg.type] then
T_doxidx[v.xarg.name] = T_root["xsd_types"][v.xarg.type]
else
T_root["xsd_types"][v.xarg.type] = {}
end
AddToTable(T_doxidx, v.xarg.name, T_root["xsd_types"][v.xarg.type])
AddToTable(T_doxidx[v.xarg.name], "xsd_type", v.xarg.type)
end
local minOccurs = v.xarg.minOccurs or 1
local maxOccurs = v.xarg.maxOccurs or 1
CheckDoxyXML_nvalues(v, #v == 0, func_name)
CheckDoxyXML_xarg(v, {"name", "~type", "~minOccurs", "~maxOccurs"}, func_name)
elseif (v.label == "xsd:attribute") then
if not T_doxidx["attributes"] then
T_doxidx["attributes"] = {}
end
if not v.xarg.type then
T_doxidx["attributes"][v.xarg.name] = 0
else
-- create linked tables to access them both ways
if T_root["xsd_types"][v.xarg.type] then
T_doxidx["attributes"][v.xarg.name] = T_root["xsd_types"][v.xarg.type]
else
T_root["xsd_types"][v.xarg.type] = {}
end
AddToTable(T_doxidx["attributes"], v.xarg.name, T_root["xsd_types"][v.xarg.type])
AddToTable(T_doxidx["attributes"][v.xarg.name], "xsd_type", v.xarg.type)
end
CheckDoxyXML_nvalues(v, #v == 0, func_name)
CheckDoxyXML_xarg(v, {"name", "type", "~use"}, func_name)
elseif (v.label == "xsd:complexType") then
if not T_root["xsd_types"][v.xarg.name] then
T_root["xsd_types"][v.xarg.name] = {}
end
ParseDoxyXSD_schema(v, T_root["xsd_types"][v.xarg.name], T_root)
CheckDoxyXML_nvalues(v, #v >= 0, func_name) -- can be 0 for docEmptyType
CheckDoxyXML_xarg(v, {"name", "~mixed"}, func_name)
elseif (v.label == "xsd:simpleType") then
if not T_root["xsd_types"][v.xarg.name] then
T_root["xsd_types"][v.xarg.name] = {}
end
ParseDoxyXSD_schema(v, T_root["xsd_types"][v.xarg.name], T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"name"}, func_name)
elseif (v.label == "xsd:simpleContent") then
ParseDoxyXSD_schema(v, T_doxidx, T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "xsd:sequence") then
ParseDoxyXSD_schema(v, T_doxidx, T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"~minOccurs", "~maxOccurs"}, func_name)
elseif (v.label == "xsd:restriction") then
ParseDoxyXSD_schema(v, T_doxidx, T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"base"}, func_name)
elseif (v.label == "xsd:extension") and v.xarg and (v.xarg.base == "xsd:string") then
ParseDoxyXSD_schema(v, T_doxidx, T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"base"}, func_name)
elseif (v.label == "xsd:enumeration") then
AddToTable(T_doxidx, v.xarg.value, 1)
T_doxidx["xsd:enumeration"] = (T_doxidx["xsd:enumeration"] or "")..v.xarg.value..";"
CheckDoxyXML_nvalues(v, #v == 0, func_name)
CheckDoxyXML_xarg(v, {"value"}, func_name)
elseif (v.label == "xsd:choice") then
ParseDoxyXSD_schema(v, T_doxidx, T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"~minOccurs", "~maxOccurs"}, func_name)
elseif (v.label == "xsd:group") and v.xarg and (v.xarg.name) then
if not T_root["xsd_types"][v.xarg.name] then
T_root["xsd_types"][v.xarg.name] = {}
end
ParseDoxyXSD_schema(v, T_root["xsd_types"][v.xarg.name], T_root)
CheckDoxyXML_nvalues(v, #v > 0, func_name)
CheckDoxyXML_xarg(v, {"name"}, func_name)
elseif (v.label == "xsd:group") and v.xarg and (v.xarg.ref) then
-- create linked tables to access them both ways
if not T_root["xsd_types"][v.xarg.ref] then
T_root["xsd_types"][v.xarg.ref] = {}
end
AddToTable(T_doxidx, "xsd:ref", T_root["xsd_types"][v.xarg.ref])
T_doxidx["xsd:ref"]["xsd_type"] = v.xarg.ref
local minOccurs = v.xarg.minOccurs or 1
local maxOccurs = v.xarg.maxOccurs or 1
CheckDoxyXML_nvalues(v, #v >= 0, func_name)
CheckDoxyXML_xarg(v, {"ref", "~minOccurs", "~maxOccurs"}, func_name)
else
print("Unknown value in ParseDoxyXSD_schema:", k, v, " on line ", v.line)
end
end
return T_doxidx
end
-- --------------------------------------------------------------------------
-- Parse Doxygen XML Lua table for label="compounddef" xarg.kind="file"
-- --------------------------------------------------------------------------
function ParseDoxyXML_doxygenindex(T_xml, T_doxidx)
local func_name = "ParseDoxyXML_doxygenindex"
CheckDoxyXML_xarg(T_xml, {"kind"}, func_name)
-- parse "compound" XML tagged items and add them to the T_out table
local function ParseCompoundMember(v, T_out)
if (v.label == "name") then
T_out.name = v[1] -- should just be a single item
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "member") then
local name = v[1][1] -- should be a single "name" tag enclosed
if (v.xarg.kind == "function") then
if T_out.functions == nil then T_out.functions = {} end
T_out.functions[#T_out.functions+1] = name
elseif (v.xarg.kind == "variable") then
if T_out.variables == nil then T_out.variables = {} end
AddToTable(T_out.variables, name, name)
elseif (v.xarg.kind == "typedef") then
if T_out.typedefs == nil then T_out.typedefs = {} end
AddToTable(T_out.typedefs, name, name)
elseif (v.xarg.kind == "enum") then
if T_out.enums == nil then T_out.enums = {} end
AddToTable(T_out.enums, name, name)
elseif (v.xarg.kind == "enumvalue") then
if T_out.enumvalues == nil then T_out.enumvalues = {} end
AddToTable(T_out.enumvalues, name, name)
elseif (v.xarg.kind == "friend") then
if T_out.friends == nil then T_out.friends = {} end
AddToTable(T_out.friends, name, name)
elseif (v.xarg.kind == "define") then
if T_out.defines == nil then T_out.defines = {} end
AddToTable(T_out.defines, name, name)
else
print("Unknown value in ParseDoxyXML_doxygenindex for compound member:", k, v, " on line ", v.line)
end
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
if v[1].label ~= "name" then
printf("Unknown label in ParseDoxyXML_doxygenindex for compound member:", k, v, " on line ", v.line)
end
CheckDoxyXML_nvalues(v[1], #v[1] == 1, func_name)
CheckDoxyXML_xarg(v[1], {}, func_name)
else
print("Unknown value in ParseDoxyXML_doxygenindex for compound:", k, v, " on line ", v.line)
end
end
if not T_doxidx.kind then
T_doxidx.kind = "doxygenindex"
T_doxidx.classes = {}
T_doxidx.structs = {}
T_doxidx.enums = {}
T_doxidx.variables = {}
T_doxidx.unions = {}
T_doxidx.files = {}
T_doxidx.groups = {}
T_doxidx.pages = {}
T_doxidx.dirs = {}
end
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "compound") and (v.xarg.kind == "class") then
local T_class = {}
T_class.kind = v.xarg.kind
T_class.filename = v.xarg.refid
for k2, v2 in ipairs(v) do
ParseCompoundMember(v2, T_class)
end
AddToTable(T_doxidx.classes, T_class.name, T_class)
CheckDoxyXML_nvalues(v, #v >= 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "struct") then
local T_struct = {}
T_struct.kind = v.xarg.kind
T_struct.filename = v.xarg.refid
for k2, v2 in ipairs(v) do
ParseCompoundMember(v2, T_struct)
end
AddToTable(T_doxidx.structs, T_struct.name, T_struct)
CheckDoxyXML_nvalues(v, #v >= 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "union") then
local T_union = {}
T_union.kind = v.xarg.kind
T_union.filename = v.xarg.refid
for k2, v2 in ipairs(v) do
ParseCompoundMember(v2, T_union)
end
AddToTable(T_doxidx.unions, T_union.name, T_union)
CheckDoxyXML_nvalues(v, #v >= 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "file") then
local T_file = {}
T_file.kind = v.xarg.kind
T_file.filename = v.xarg.refid
for k2, v2 in ipairs(v) do
ParseCompoundMember(v2, T_file)
ParseCompoundMember(v2, T_doxidx) -- add to globals too
end
AddToTable(T_doxidx.files, T_file.filename, T_file)
CheckDoxyXML_nvalues(v, #v >= 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "group") then
local T_group = {}
T_group.kind = v.xarg.kind
T_group.filename = v.xarg.refid
for k2, v2 in ipairs(v) do
ParseCompoundMember(v2, T_group)
end
AddToTable(T_doxidx.groups, T_group.name, T_group)
CheckDoxyXML_nvalues(v, #v >= 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "page") then
AddToTable(T_doxidx.pages, v[1][1], v[1][1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
CheckDoxyXML_nvalues(v[1], #v[1] == 1, func_name)
CheckDoxyXML_xarg(v[1], {}, func_name)
elseif (v.label == "compound") and (v.xarg.kind == "dir") then
AddToTable(T_doxidx.dirs, v[1][1], v[1][1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "kind"}, func_name)
CheckDoxyXML_nvalues(v[1], #v[1] == 1, func_name)
CheckDoxyXML_xarg(v[1], {}, func_name)
else
print("Unknown value in ParseDoxyXML_doxygenindex:", k, v, " on line ", v.line)
end
end
return T_doxidx
end
-- --------------------------------------------------------------------------
-- Parse Doxygen XML Lua table for label="compounddef" xarg.kind="file"
-- --------------------------------------------------------------------------
function ParseDoxyXML_compounddef_file(T_xml, T_file)
local func_name = "ParseDoxyXML_compounddef_file"
CheckDoxyXML_xarg(T_xml, {"kind", "~id"}, func_name)
if not T_file.kind then
T_file.kind = "file"
T_file.classes = {}
T_file.enums = {}
T_file.variables = {}
T_file.defines = {}
T_file.typedefs = {}
T_file.functions = {}
end
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "compoundname") then
AddToTable(T_file, "filename", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "sectiondef") then
ParseDoxyXML_compounddef_file(v, T_file)
CheckDoxyXML_xarg(v, {"kind"}, func_name)
elseif (v.label == "innerclass") then
--if v.xarg.prot == "public" then
AddToTable(T_file.classes, #T_file.classes+1, v[1])
--end
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "prot"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "enum") then
local T_enum = ParseDoxyXML_compounddef_memberdef_enum(v)
T_file.enums[#T_file.enums+1] = T_enum
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "variable") then
local T_variable = ParseDoxyXML_compounddef_memberdef_variable(v)
T_file.variables[#T_file.variables+1] = T_variable
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static", "mutable"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "define") then
local T_define = ParseDoxyXML_compounddef_memberdef_define(v)
T_file.defines[#T_file.defines+1] = T_define
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "typedef") then
local T_typedef = ParseDoxyXML_compounddef_memberdef_typedef(v)
T_file.typedefs[#T_file.typedefs+1] = T_typedef
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "function") then
local T_function = ParseDoxyXML_compounddef_class_memberdef_function(v, nil)
if T_file.functions[T_function.name] == nil then
T_file.functions[T_function.name] = {}
end
T_file.functions[T_function.name][#T_file.functions[T_function.name]+1] = T_function
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static", "const", "explicit", "inline", "virt"}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "description") or
(v.label == "header") or
(v.label == "location") then
-- ignore
else
print("Unknown value in ParseDoxyXML_compounddef_file:", k, v.label, " on line ", v.line)
end
end
return T_file
end
-- --------------------------------------------------------------------------
-- Parse the children of <sectiondef kind="enum/"> or
-- classwx_brush.xml : <compounddef id="classwx_brush" kind="class" prot="public">
function ParseDoxyXML_compounddef_class(T_xml, T_class)
local func_name = "ParseDoxyXML_compounddef_class"
CheckDoxyXML_xarg(T_xml, {"kind", "~id", "~prot", "~abstract"}, func_name)
if not T_class.kind then
T_class.kind = "class"
T_class.memberdef_functions = {}
T_class.memberdef_enums = {}
T_class.memberdef_variables = {}
T_class.memberdef_typedefs = {}
T_class.innerclass = {}
end
if T_xml.xarg.prot then
AddToTable(T_class, "prot", T_xml.xarg.prot)
end
if T_xml.xarg.abstract then
AddToTable(T_class, "abstract", T_xml.xarg.abstract)
end
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "compoundname") then
AddToTable(T_class, "classname", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "basecompoundref") then
if not T_class["baseclassnames"] then T_class["baseclassnames"] = {} end
local T_baseclass = {}
T_baseclass.name = v[1]
T_baseclass.prot = v.xarg.prot
T_baseclass.virt = v.xarg.virt
T_class["baseclassnames"][#T_class["baseclassnames"]+1] = T_baseclass
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "prot", "virt"}, func_name)
elseif (v.label == "includes") then
if not T_class["includes"] then T_class["includes"] = {} end
local T_include = {}
T_include.name = v[1]
T_include["local"] = v.xarg["local"]
T_class["includes"][#T_class["includes"]+1] = T_include
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"local"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "function") then
local T_function = ParseDoxyXML_compounddef_class_memberdef_function(v, T_class.classname)
if T_class.memberdef_functions[T_function.name] == nil then
T_class.memberdef_functions[T_function.name] = {}
end
T_class.memberdef_functions[T_function.name][#T_class.memberdef_functions[T_function.name]+1] = T_function
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static", "const", "explicit", "inline", "virt"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "enum") then
local T_enum = ParseDoxyXML_compounddef_memberdef_enum(v)
T_class.memberdef_enums[#T_class.memberdef_enums+1] = T_enum
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "variable") then
local T_variable = ParseDoxyXML_compounddef_memberdef_variable(v)
AddToTable(T_class.memberdef_variables, T_variable.name, T_variable)
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static", "mutable"}, func_name)
elseif (v.label == "memberdef") and (v.xarg.kind == "typedef") then
local T_typedef = ParseDoxyXML_compounddef_memberdef_typedef(v)
T_class.memberdef_typedefs[#T_class.memberdef_typedefs+1] = T_typedef
CheckDoxyXML_xarg(v, {"kind", "id", "prot", "static"}, func_name)
elseif (v.label == "innerclass") then
AddToTable(T_class.innerclass, v[1], v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {"refid", "prot"}, func_name)
elseif (v.label == "sectiondef") then
ParseDoxyXML_compounddef_class(v, T_class)
CheckDoxyXML_xarg(v, {"kind"}, func_name)
elseif (v.label == "description") or
(v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "derivedcompoundref") or
(v.label == "inheritancegraph") or
(v.label == "collaborationgraph") or
(v.label == "location") or
(v.label == "listofallmembers") or
(v.label == "header") or -- desciption of section
(v.label == "memberdef" and (v.xarg.kind == "friend")) or
(v.label == "reimplementedby") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_class:", v.label, " on line ", v.line)
end
end
return T_class
end
-- --------------------------------------------------------------------------
--
-- <memberdef kind="function" id="group__group__funcmacro__log_1gaf57b7e28ab76bacf10b3be044e8bd634"
-- prot="public" static="no" const="no" explicit="no" inline="no" virt="non-virtual">
function ParseDoxyXML_compounddef_class_memberdef_function(T_xml, classname)
local func_name = "ParseDoxyXML_compounddef_class_memberdef_function"
CheckDoxyXML_xarg(T_xml, {"kind", "id", "prot", "static", "const", "explicit", "inline", "virt"}, func_name)
local T_function = {}
T_function.kind = "function"
T_function.prot = T_xml.xarg.prot
T_function.static = T_xml.xarg.static
T_function.const = T_xml.xarg.const
T_function.explicit = T_xml.xarg.explicit
T_function.inline = T_xml.xarg.inline
T_function.virt = T_xml.xarg.virt
--T_function.params = {} only created if used
--T_function.type = only created if used, types concatenated together
--T_function.types = {} only created if used
--T_function.constructor = nil
--T_function.operator = nil or "=="
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "type") then
local T_types = {}
for kt, vt in ipairs(v) do
vt = RemoveDoxyXML_ref(vt)
T_types[#T_types+1] = vt
end
if #T_types > 0 then
AddToTable(T_function, "types", T_types)
AddToTable(T_function, "type", table.concat(T_types, " "))
end
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "definition") then
AddToTable(T_function, "definition", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "argsstring") then
AddToTable(T_function, "argstring", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "name") then
local name = v[1]
AddToTable(T_function, "name", name)
if name == classname then
T_function.constructor = true
elseif string.find(name, "operator", 1, 1) == 1 then
T_function.operator = string.sub(name, 9)
end
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "param") then
local T_param = ParseDoxyXML_param(v, T_function)
if not T_function.params then T_function.params = {} end
T_function.params[#T_function.params+1] = T_param
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "templateparamlist") then
local T_param = ParseDoxyXML_param(v[1], T_function)
if not T_function.templateparamlist then T_function.templateparamlist = {} end
T_function.templateparamlist[#T_function.templateparamlist+1] = T_param
CheckDoxyXML_nvalues(v, v[1].label == "param", func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "inbodydescription") or
(v.label == "location") or
(v.label == "reimplementedby") or
(v.label == "reimplements") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_class_memberdef_function:", v.label, " on line ", v.line)
end
end
return T_function
end
-- --------------------------------------------------------------------------
-- Parse a <param> or <templateparamlist>
function ParseDoxyXML_param(T_xml, T_class)
local func_name = "ParseDoxyXML_param"
CheckDoxyXML_xarg(T_xml, {}, func_name)
local T_param = {}
T_param.kind = "param"
--T_param.types = {} only created if used
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "type") then
local T_types = {}
for kt, vt in ipairs(v) do
vt = RemoveDoxyXML_ref(vt)
T_types[#T_types+1] = vt
end
if #T_types > 0 then
T_param.types = T_types
AddToTable(T_param, "type", table.concat(T_types, " "))
end
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "declname") then
AddToTable(T_param, "declname", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "defname") then
AddToTable(T_param, "defname", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "array") then
AddToTable(T_param, "array", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "defval") then
local defval = ""
for i = 1,#v do
defval = defval..RemoveDoxyXML_ref(v[i])
end
AddToTable(T_param, "defval", defval)
CheckDoxyXML_xarg(v, {}, func_name)
else
print("Unknown label in ParseDoxyXML_param:", v.label)
end
end
return T_param
end
-- --------------------------------------------------------------------------
-- Parse a <compounddef> <memberdef kind="variable" ...>
-- <memberdef kind="enum" id="toplevel_8h_1adb49720dc49f7d4e4cf9adbf2948e409" prot="public" static="no">
function ParseDoxyXML_compounddef_memberdef_enum(T_xml)
local func_name = "ParseDoxyXML_compounddef_memberdef_enum"
CheckDoxyXML_xarg(T_xml, {"kind", "id", "prot", "static"}, func_name)
local T_enum = {};
T_enum.kind = "enum"
T_enum.prot = T_xml.xarg.prot
T_enum.static = T_xml.xarg.static
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "name") then
AddToTable(T_enum, "name", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "enumvalue") then
local T_enumvalue = {}
for ke, ve in ipairs(v) do
ve = RemoveDoxyXML_ref(ve)
if (ve.label == "name") then
T_enumvalue.name = ve[1]
CheckDoxyXML_nvalues(ve, #ve == 1, func_name)
CheckDoxyXML_xarg(ve, {}, func_name)
elseif (ve.label == "initializer") then
T_enumvalue.initializer = ve[1]
CheckDoxyXML_xarg(ve, {}, func_name)
elseif (ve.label == "briefdescription") or
(ve.label == "detaileddescription") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_memberdef_enum:", ve.label, " on line ", ve.line)
end
end
T_enum[#T_enum+1] = T_enumvalue
CheckDoxyXML_xarg(v, {"id", "prot"}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "inbodydescription") or
(v.label == "location") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_memberdef_enum:", v.label, " on line ", v.line)
end
end
return T_enum
end
-- --------------------------------------------------------------------------
-- Parse a <compounddef> <memberdef kind="variable" ...>
-- <memberdef kind="variable" id="pen_8h_1a4dbfd18a818b95630453f3d755a1c95d" prot="public" static="no" mutable="no">
function ParseDoxyXML_compounddef_memberdef_variable(T_xml)
local func_name = "ParseDoxyXML_compounddef_memberdef_variable"
CheckDoxyXML_xarg(T_xml, {"kind", "id", "prot", "static", "mutable"}, func_name)
local T_variable = {};
T_variable.kind = "variable"
T_variable.types = {}
T_variable.prot = T_xml.xarg.prot
T_variable.static = T_xml.xarg.static
T_variable.mutable = T_xml.xarg.mutable
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "type") then
for kt, vt in ipairs(v) do
vt = RemoveDoxyXML_ref(vt)
T_variable.types[#T_variable.types+1] = vt
end
AddToTable(T_variable, "type", table.concat(T_variable.types, " "))
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "definition") then
AddToTable(T_variable, "definition", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "argsstring") then
AddToTable(T_variable, "argsstring", v[1])
CheckDoxyXML_nvalues(v, #v < 2, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "name") then
AddToTable(T_variable, "name", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "initializer") then
AddToTable(T_variable, "initializer", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "inbodydescription") or
(v.label == "location") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_memberdef_variable:", v.label, " on line ", v.line)
end
end
return T_variable
end
-- --------------------------------------------------------------------------
-- Parse a <compounddef> <memberdef kind="define" ...>
-- <memberdef kind="define" id="defs_8h_1a5ca7bb9c778fe2d44b4a1af3ceed8355" prot="public" static="no">
function ParseDoxyXML_compounddef_memberdef_define(T_xml)
local func_name = "ParseDoxyXML_compounddef_memberdef_define"
CheckDoxyXML_xarg(T_xml, {"kind", "id", "prot", "static"}, func_name)
local T_define = {};
T_define.kind = "define"
T_define.prot = T_xml.xarg.prot
T_define.static = T_xml.xarg.static
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "initializer") then
s = ""
for i = 1,#v do
s = s..RemoveDoxyXML_ref(v[i])
end
AddToTable(T_define, "initializer", s)
--CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "param") then
-- Check if there is a table of params since it may be empty, e.g. DEFINE()
if v[1] then
if not T_define.param then T_define.param = {} end
T_define.param[#T_define.param+1] = v[1][1]
CheckDoxyXML_nvalues(v, v[1].label == "defname", func_name)
CheckDoxyXML_nvalues(v, #v[1] == 1, func_name)
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
end
elseif (v.label == "name") then
AddToTable(T_define, "name", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "inbodydescription") or
(v.label == "location") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_memberdef_define:", v.label, " on line ", v.line)
end
end
return T_define
end
-- --------------------------------------------------------------------------
-- Parse a <compounddef> <memberdef kind="typedef" ...>
-- <memberdef kind="typedef" id="artprov_8h_1ad9c24b799a686f312c2bb64f47b6ef95" prot="public" static="no">
function ParseDoxyXML_compounddef_memberdef_typedef(T_xml)
local func_name = "ParseDoxyXML_compounddef_memberdef_typedef"
CheckDoxyXML_xarg(T_xml, {"kind", "id", "prot", "static"}, func_name)
local T_typedef = {};
T_typedef.kind = "typedef"
T_typedef.types = {}
T_typedef.prot = T_xml.xarg.prot
T_typedef.static = T_xml.xarg.static
for k, v in ipairs(T_xml) do
v = RemoveDoxyXML_ref(v)
if (v.label == "type") then
for kt, vt in ipairs(v) do
vt = RemoveDoxyXML_ref(vt)
T_typedef.types[#T_typedef.types+1] = vt
end
AddToTable(T_typedef, "type", table.concat(T_typedef.types, " "))
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "definition") then
AddToTable(T_typedef, "definition", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "argsstring") then
AddToTable(T_typedef, "argsstring", v[1]) -- should be nil, but XML has these tags anyway
CheckDoxyXML_nvalues(v, #v == 0 or #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "name") then
AddToTable(T_typedef, "name", v[1])
CheckDoxyXML_nvalues(v, #v == 1, func_name)
CheckDoxyXML_xarg(v, {}, func_name)
elseif (v.label == "briefdescription") or
(v.label == "detaileddescription") or
(v.label == "inbodydescription") or
(v.label == "location") then
-- ignore
else
print("Unknown label in ParseDoxyXML_compounddef_memberdef_typedef:", v.label, " on line ", v.line)
end
end
return T_typedef
end
-- --------------------------------------------------------------------------
-- Remove the <ref refid="other_xml_file"...> </ref> tag returning the inner tags
-- Ex. aboutdlg_8h.xml: <type><ref refid="classwx_window" kindref="compound">wxWindow</ref> *</type>
-- returns this part <type>wxWindow *</type>
function RemoveDoxyXML_ref(v)
if (type(v) == "table") and (v.label == "ref") then
CheckDoxyXML_xarg(v, {"refid", "kindref"}, "RemoveDoxyXML_ref")
CheckDoxyXML_nvalues(v, #v == 1, "RemoveDoxyXML_ref")
v = v[1]
end
return v
end
-- --------------------------------------------------------------------------
-- Compares T.xarg with a table of expected xargs to warn of unexpected xargs
-- T_known_xarg = { 'required_arg1', '~optional_arg2', ...}
-- --------------------------------------------------------------------------
function CheckDoxyXML_xarg(T, T_known_xarg, func_name)
local T_xarg = T.xarg
if not T_xarg then T_xarg = {} end
if ((T_xarg == nil) or (CountTable(T_xarg or {}) == 0)) and
((T_known_xarg == nil) or (CountTable(T_known_xarg or {}) == 0))then
return
end
local n_T_xarg = CountTable(T_xarg)
local n_T_known_xarg = CountTable(T_known_xarg)
local T_known_xarg_v = {}
for k, v in ipairs(T_known_xarg) do
if (string.sub(v,1,1) == "~") then
T_known_xarg_v[string.sub(v,2)] = 1
else
T_known_xarg_v[v] = 1
if (T_xarg[v] == nil) then
local linenumber = debug.getinfo(2).currentline -- get source line #
printf("WARNING: Missing xarg '%s' on line %d in func '%s' line %d.", v, T.line, func_name, linenumber)
end
end
end
for k, v in pairs(T_xarg) do
if T_known_xarg_v[k] == nil then
local linenumber = debug.getinfo(2).currentline -- get source line #
printf("WARNING: Extra xarg '%s' on line %d in func '%s' line %d.", k, T.line, func_name, linenumber)
end
end
if n_T_xarg ~= n_T_known_xarg then
--local linenumber = debug.getinfo(2).currentline -- get source line #
--printf("WARNING: Different number of xargs on line %d in func '%s' line %d.", T.line, func_name, linenumber)
end
end
-- --------------------------------------------------------------------------
-- The table element from ParseXMLFile() has the proper number of expected values if 'ok' = true
function CheckDoxyXML_nvalues(T, ok, func_name)
if not ok then
local linenumber = debug.getinfo(2).currentline -- get source line #
printf("WARNING: '%s' has %d values on line %s in func '%s' on line %d.", T.label, #T, tostring(T.line), func_name, linenumber)
end
end
-- --------------------------------------------------------------------------
-- Generic helper functions not related to XML
-- --------------------------------------------------------------------------
-- --------------------------------------------------------------------------
-- Add to the table T[key] = value, prints a warning if the key already exits
function AddToTable(T, key, value, v)
if (T[key] ~= nil) and (T[key] ~= value) then
printf("WARNING: Replacing existing table key='%s' value='%s' with value='%s'.", tostring(key), tostring(T[key]), tostring(value))
if v then
printf(" in file %s on line %s\n", tostring(v.filename), tostring(v.line))
end
end
T[key] = value
end
-- --------------------------------------------------------------------------
-- Returns the number of elements in the table
function CountTable(T)
local n = 0
for k, v in pairs(T) do
n = n + 1
end
return n
end
-- --------------------------------------------------------------------------
-- Returns true if the table is empty, else false
function IsEmptyTable(T)
for k, v in pairs(T) do
return false
end
return true
end
-- ---------------------------------------------------------------------------
-- Replacement for pairs(table) that sorts them alphabetically, returns iterator
-- Code from "Programming in Lua" by Roberto Ierusalimschy
-- the input is a Lua table and optional comp function (see table.sort)
-- ---------------------------------------------------------------------------
function pairs_sort(atable, comp_func)
local a = {}
for n in pairs(atable) do table.insert(a, n) end
table.sort(a, table_sort_comp)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], atable[a[i]] end
end
return iter
end
function table_sort_comp(a, b)
local ta = type(a)
local tb = type(b)
if (ta ~= tb) then
return ta < tb
end
return a < b
end
-- --------------------------------------------------------------------------
-- http://www2.dcs.elf.stuba.sk/TeamProject/2003/team05/produkt/player/utils/serialize/serialize.lua
--! Serialization
--% Serializes a lua variable (good for table visualization)
--@ o (any) Variable to serialize
--@ d (number) INTERNAL (RECURSIVE FUNCTION)
function Serialize(o, d)
if not d then d = 0 end
local s = ""
if type(o) == "number" then
s = s..o
elseif type(o) == "string" then
s = s..string.format("%q", o)
elseif type(o) == "boolean" then
if(o) then s = s.."true" else s = s.."false" end
elseif type(o) == "table" then
s = s.."{\n"
for k,v in pairs_sort(o) do
for f = 1,d do
s = s.." "
end
if type(k) == "string" and not string.find(k, "[^%w_]") then
s = s.." "..k.." = "
else
s = s.." ["
s = s..Serialize(k)
s = s.."] = "
end
s = s..Serialize(v, d + 1)
if type(v) ~= "table" then s = s..",\n" end
end
for f = 1,d do
s = s.." "
end
s = s.."}"
if d ~= 0 then
s = s..","
end
s = s.."\n"
elseif type(o) == "function" then
s = s..tostring(o)
else
error("cannot serialize a "..type(o))
end
return s
end
-- --------------------------------------------------------------------------
function printf(fmt, ...)
print(string.format(fmt, ...))
end
-- --------------------------------------------------------------------------
-- --------------------------------------------------------------------------
-- --------------------------------------------------------------------------
-- Parse an XML file and return the lines of the file in a Lua table as well
-- as a parsed version of the XML from ParseXMLString().
-- --------------------------------------------------------------------------
function ParseXMLFile(filename)
local T_file = {}
local T_line_chars = {}
local last_line_char = 0
for line in io.lines(filename) do
T_file[#T_file+1] = line
last_line_char = last_line_char + #line
T_line_chars[#T_line_chars+1] = last_line_char
end
local s = table.concat(T_file)
local T_xml = ParseXMLString(s, T_line_chars)
T_xml.xml_filename = filename
return T_file, T_xml
end
-- --------------------------------------------------------------------------
-- Generic Lua XML parser. Original code written by Roberto Ierusalimschy.
-- License : MIT
-- http://lua-users.org/wiki/LuaXml
-- It has been modified to also save the line number, replace HTML chars, and
-- throw out comments.
--
-- The returned Lua table is numerically indexed for each <>...</> full item
-- with the keys of "label", "xarg", "empty", and "line"
-- e.g. <innerclass refid="classwx_brush" prot="public">wxBrush</innerclass>
-- T_xml.label="innerclass"; T_xml[1]="wxBrush"; T_xml.line=file line number
-- T_xml.xargs = {"refid"="classwx_brush", "prot"="public"}
-- note that T_xml[1] is a table if the item has children.
-- --------------------------------------------------------------------------
function ParseXMLString(s, T_line_chars)
local function UnHTMLString(s)
if string_find(s, "&", 1, 1) then
s = string_gsub(s, "&", "&")
s = string_gsub(s, """, "\"")
s = string_gsub(s, "'", "'")
s = string_gsub(s, ">", ">")
s = string_gsub(s, "<", "<")
end
return s
end
local function parseargs(s)
local arg = nil
string_gsub(s, "([%:%w]+)=([\"'])(.-)%2",
function (w, _, a) arg = arg or {}; arg[w] = a end)
return arg
end
local find_line = function (i) return nil end -- line table may not be provided
if T_line_chars then
local i_linetable = 1
find_line = function (i_char)
while (i_linetable < #T_line_chars) and (i_char > T_line_chars[i_linetable]) do
i_linetable = i_linetable + 1
end
return i_linetable
end
end
local stack = {}
local top = {}
stack[#stack+1] = top
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string_find(s, "<(%/?)([%w:]+)(.-)(%/?)>", i)
if not ni then break end
label = UnHTMLString(label)
xarg = UnHTMLString(xarg)
local text = string_sub(s, i, ni-1)
if not string_find(text, "^%s*$") then
if not string_find(text, "<!--") then
top[#top+1] = UnHTMLString(text)
end
end
if empty == "/" then -- empty element tag
top[#top+1] = {label=label, xarg=parseargs(xarg), empty=1, line=find_line(i)}
elseif c == "" then -- start tag
top = {label=label, xarg=parseargs(xarg), line=find_line(i)}
stack[#stack+1] = top -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("nothing to close with "..label)
end
if toclose.label ~= label then
error("trying to close "..toclose.label.." with "..label)
end
top[#top+1] = toclose
end
i = j+1
end
local text = string_sub(s, i)
if not string_find(text, "^%s*$") then
table_insert(stack[#stack], UnHTMLString(text))
end
if #stack > 1 then
error("unclosed "..stack[stack.n].label)
end
return stack[1]
end
|
--[[----------------------------------------------------------------------------
Interface for accessing the Common Objects in COntext (COCO) dataset.
For an overview of the API please see http://mscoco.org/dataset/#download.
CocoApi.lua (this file) is modeled after the Matlab CocoApi.m:
https://github.com/pdollar/coco/blob/master/MatlabAPI/CocoApi.m
The following API functions are defined in the Lua API:
CocoApi - Load COCO annotation file and prepare data structures.
getAnnIds - Get ann ids that satisfy given filter conditions.
getCatIds - Get cat ids that satisfy given filter conditions.
getImgIds - Get img ids that satisfy given filter conditions.
loadAnns - Load anns with the specified ids.
loadCats - Load cats with the specified ids.
loadImgs - Load imgs with the specified ids.
showAnns - Display the specified annotations.
Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
For detailed usage information please see cocoDemo.lua.
LIMITATIONS: the following API functions are NOT defined in the Lua API:
loadRes - Load algorithm results and create API for accessing them.
download - Download COCO images from mscoco.org server.
In addition, currently the getCatIds() and getImgIds() do not accept filters.
getAnnIds() can be called using getAnnIds({imgId=id}) and getAnnIds({catId=id}).
Note: loading COCO JSON annotations to Lua tables is quite slow. Hence, a call
to CocApi(annFile) converts the annotations to a custom 'flattened' format that
is more efficient. The first time a COCO JSON is loaded, the conversion is
invoked (this may take up to a minute). The converted data is then stored in a
t7 file (the code must have write permission to the dir of the JSON file).
Future calls of cocoApi=CocApi(annFile) take a fraction of a second. To view the
created data just inspect cocoApi.data of a created instance of the CocoApi.
Common Objects in COntext (COCO) Toolbox. version 3.0
Data, paper, and tutorials available at: http://mscoco.org/
Code written by Pedro O. Pinheiro and Piotr Dollar, 2016.
Licensed under the Simplified BSD License [see coco/license.txt]
------------------------------------------------------------------------------]]
local json = require 'cjson'
local coco = require 'coco.env'
local TensorTable = torch.class('TensorTable',coco)
local CocoSeg = torch.class('CocoSeg',coco)
local CocoApi = torch.class('CocoApi',coco)
--------------------------------------------------------------------------------
--[[ TensorTable is a lightweight data structure for storing variable size 1D
tensors. Tables of tensors are slow to save/load to disk. Instead, TensorTable
stores all the data in a single long tensor (along with indices into the tensor)
making serialization fast. A TensorTable may only contain 1D same-type torch
tensors or strings. It supports only creation from a table and indexing. ]]
function TensorTable:__init( T )
local n = #T; assert(n>0)
local isStr = torch.type(T[1])=='string'
assert(isStr or torch.isTensor(T[1]))
local c=function(s) return torch.CharTensor(torch.CharStorage():string(s)) end
if isStr then local S=T; T={}; for i=1,n do T[i]=c(S[i]) end end
local ms, idx = torch.LongTensor(n), torch.LongTensor(n+1)
for i=1,n do ms[i]=T[i]:numel() end
idx[1]=1; idx:narrow(1,2,n):copy(ms); idx=idx:cumsum()
local type = string.sub(torch.type(T[1]),7,-1)
local data = torch[type](idx[n+1]-1)
if isStr then type='string' end
for i=1,n do if ms[i]>0 then data:sub(idx[i],idx[i+1]-1):copy(T[i]) end end
if ms:eq(ms[1]):all() and ms[1]>0 then data=data:view(n,ms[1]); idx=nil end
self.data, self.idx, self.type = data, idx, type
end
function TensorTable:__index__( i )
if torch.type(i)~='number' then return false end
local d, idx, type = self.data, self.idx, self.type
if idx and idx[i]==idx[i+1] then
if type=='string' then d='' else d=torch[type]() end
else
if idx then d=d:sub(idx[i],idx[i+1]-1) else d=d[i] end
if type=='string' then d=d:clone():storage():string() end
end
return d, true
end
--------------------------------------------------------------------------------
--[[ CocoSeg is an efficient data structure for storing COCO segmentations. ]]
function CocoSeg:__init( segs )
local polys, pIdx, sizes, rles, p, isStr = {}, {}, {}, {}, 0, 0
for i,seg in pairs(segs) do if seg.size then isStr=seg.counts break end end
isStr = torch.type(isStr)=='string'
for i,seg in pairs(segs) do
pIdx[i], sizes[i] = {}, {}
if seg.size then
sizes[i],rles[i] = seg.size,seg.counts
else
if isStr then rles[i]='' else rles[i]={} end
for j=1,#seg do p=p+1; pIdx[i][j],polys[p] = p,seg[j] end
end
pIdx[i],sizes[i] = torch.LongTensor(pIdx[i]),torch.IntTensor(sizes[i])
if not isStr then rles[i]=torch.IntTensor(rles[i]) end
end
for i=1,p do polys[i]=torch.DoubleTensor(polys[i]) end
self.polys, self.pIdx = coco.TensorTable(polys), coco.TensorTable(pIdx)
self.sizes, self.rles = coco.TensorTable(sizes), coco.TensorTable(rles)
end
function CocoSeg:__index__( i )
if torch.type(i)~='number' then return false end
if self.sizes[i]:numel()>0 then
return {size=self.sizes[i],counts=self.rles[i]}, true
else
local ids, polys = self.pIdx[i], {}
for i=1,ids:numel() do polys[i]=self.polys[ids[i]] end
return polys, true
end
end
--------------------------------------------------------------------------------
--[[ CocoApi is the API to the COCO dataset, see main comment for details. ]]
function CocoApi:__init( annFile )
assert( string.sub(annFile,-4,-1)=='json' and paths.filep(annFile) )
local torchFile = string.sub(annFile,1,-6) .. '.t7'
if not paths.filep(torchFile) then self:__convert(annFile,torchFile) end
local data = torch.load(torchFile)
self.data, self.inds = data, {}
for k,v in pairs({images='img',categories='cat',annotations='ann'}) do
local M = {}; self.inds[v..'IdsMap']=M
if data[k] then for i=1,data[k].id:size(1) do M[data[k].id[i]]=i end end
end
end
function CocoApi:__convert( annFile, torchFile )
print('convert: '..annFile..' --> .t7 [please be patient]')
local tic = torch.tic()
-- load data and decode json
local data = torch.CharStorage(annFile):string()
data = json.decode(data); collectgarbage()
-- transpose and flatten each field in the coco data struct
local convert = {images=true, categories=true, annotations=true}
for field, d in pairs(data) do if convert[field] then
print('converting: '..field)
local n, out = #d, {}
if n==0 then d,n={d},1 end
for k,v in pairs(d[1]) do
local t, isReg = torch.type(v), true
for i=1,n do isReg=isReg and torch.type(d[i][k])==t end
if t=='number' and isReg then
out[k] = torch.DoubleTensor(n)
for i=1,n do out[k][i]=d[i][k] end
elseif t=='string' and isReg then
out[k]={}; for i=1,n do out[k][i]=d[i][k] end
out[k] = coco.TensorTable(out[k])
elseif t=='table' and isReg and torch.type(v[1])=='number' then
out[k]={}; for i=1,n do out[k][i]=torch.DoubleTensor(d[i][k]) end
out[k] = coco.TensorTable(out[k])
if not out[k].idx then out[k]=out[k].data end
else
out[k]={}; for i=1,n do out[k][i]=d[i][k] end
if k=='segmentation' then out[k] = coco.CocoSeg(out[k]) end
end
collectgarbage()
end
if out.id then out.idx=torch.range(1,out.id:size(1)) end
data[field] = out
collectgarbage()
end end
-- create mapping from cat/img index to anns indices for that cat/img
print('convert: building indices')
local makeMap = function( type, type_id )
if not data[type] or not data.annotations then return nil end
local invmap, n = {}, data[type].id:size(1)
for i=1,n do invmap[data[type].id[i]]=i end
local map = {}; for i=1,n do map[i]={} end
data.annotations[type_id..'x'] = data.annotations[type_id]:clone()
for i=1,data.annotations.id:size(1) do
local id = invmap[data.annotations[type_id][i]]
data.annotations[type_id..'x'][i] = id
table.insert(map[id],data.annotations.id[i])
end
for i=1,n do map[i]=torch.LongTensor(map[i]) end
return coco.TensorTable(map)
end
data.annIdsPerImg = makeMap('images','image_id')
data.annIdsPerCat = makeMap('categories','category_id')
-- save to disk
torch.save( torchFile, data )
print(('convert: complete [%.2f s]'):format(torch.toc(tic)))
end
function CocoApi:getAnnIds( filters )
if not filters then filters = {} end
if filters.imgId then
return self.data.annIdsPerImg[self.inds.imgIdsMap[filters.imgId]] or {}
elseif filters.catId then
return self.data.annIdsPerCat[self.inds.catIdsMap[filters.catId]] or {}
else
return self.data.annotations.id
end
end
function CocoApi:getCatIds()
return self.data.categories.id
end
function CocoApi:getImgIds()
return self.data.images.id
end
function CocoApi:loadAnns( ids )
return self:__load(self.data.annotations,self.inds.annIdsMap,ids)
end
function CocoApi:loadCats( ids )
return self:__load(self.data.categories,self.inds.catIdsMap,ids)
end
function CocoApi:loadImgs( ids )
return self:__load(self.data.images,self.inds.imgIdsMap,ids)
end
function CocoApi:showAnns( img, anns )
local n, h, w = #anns, img:size(2), img:size(3)
local MaskApi, clrs = coco.MaskApi, torch.rand(n,3)*.6+.4
local O = img:clone():contiguous():float()
if n==0 then anns,n={anns},1 end
if anns[1].keypoints then for i=1,n do if anns[i].iscrowd==0 then
local sk, kp, j, k = self:loadCats(anns[i].category_id)[1].skeleton
kp=anns[i].keypoints; k=kp:size(1); j=torch.range(1,k,3):long(); k=k/3;
local x,y,v = kp:index(1,j), kp:index(1,j+1), kp:index(1,j+2)
for _,s in pairs(sk) do if v[s[1]]>0 and v[s[2]]>0 then
MaskApi.drawLine(O,x[s[1]],y[s[1]],x[s[2]],y[s[2]],.75,clrs[i])
end end
for j=1,k do if v[j]==1 then MaskApi.drawCirc(O,x[j],y[j],4,{0,0,0}) end end
for j=1,k do if v[j]>0 then MaskApi.drawCirc(O,x[j],y[j],3,clrs[i]) end end
end end end
if anns[1].segmentation or anns[1].bbox then
local Rs, alpha = {}, anns[1].keypoints and .25 or .4
for i=1,n do
Rs[i]=anns[i].segmentation
if Rs[i] and #Rs[i]>0 then Rs[i]=MaskApi.frPoly(Rs[i],h,w) end
if not Rs[i] then Rs[i]=MaskApi.frBbox(anns[i].bbox,h,w)[1] end
end
MaskApi.drawMasks(O,MaskApi.decode(Rs),nil,alpha,clrs)
end
return O
end
function CocoApi:__load( data, map, ids )
if not torch.isTensor(ids) then ids=torch.LongTensor({ids}) end
local out, idx = {}, nil
for i=1,ids:numel() do
out[i], idx = {}, map[ids[i]]
for k,v in pairs(data) do out[i][k]=v[idx] end
end
return out
end
|
local L = BigWigs:NewBossLocale("Atal'Dazar Trash", "zhCN")
if not L then return end
if L then
L.skyscreamer = "飨宴的啸天龙"
L.tlonja = "特隆加"
L.shieldbearer = "祖尔的持盾卫士"
L.witchdoctor = "赞枢利巫医"
L.kisho = "恐龙首领吉什奥"
L.priestess = "鎏金女祭司"
L.stalker = "影刃追猎者"
L.confessor = "达萨莱神官"
L.augur = "达萨莱占卜师"
end
|
local mods = minetest.get_mod_storage()
local modname = minetest.get_current_modname()
mapgen.structures = minetest.deserialize(mods:get_string("structures") ~= "" or "{}") or {}
function mapgen.register_structure(name, def)
mapgen.structures[name] = {}
mapgen.registered_structures[name] = def
minetest.register_node(modname..":"..name, {
drawtype = "airlike",
walkable = false,
pointable = false,
buildable_to = true,
paramtype = "light",
sunlight_propagates = true,
groups = {structure_placeholder = 1},
})
minetest.register_decoration({
deco_type = "simple",
place_on = def.placeon or "vk_nodes:grass",
decoration = modname..":"..name,
fill_ratio = def.rarity,
biomes = {"green_biome"},
y_min = def.y_min or 8,
y_max = def.y_max or 8,
flags = "force_placement, all_floors",
})
end
minetest.register_lbm({
label = "Place structures",
name = modname..":place_structure",
nodenames = {"group:structure_placeholder"},
run_at_every_load = true,
action = function(pos, node)
local schemname = mapgen.get_schemname(node.name)
local result
local structure = mapgen.registered_structures[schemname]
minetest.remove_node(pos)
if mapgen.structure_is_nearby(pos, mapgen.registered_structures[schemname].bubble) == false then
vkore.scan_flood(pos, structure.radius, function(p, dist)
local nodename = minetest.get_node(p).name
if p.y < pos.y-1 or p.y > pos.y+1 then return false end -- Just scan a node off from y 8 (ground level)
if p.y <= 8 then
if nodename == "air" then
result = "Will jut over edge"
return true
end
else
if nodename == "vk_nodes:grass" then -- There is terrain in the way
result = "Will break terrain"
return true
end
end
end)
pos.y = pos.y - 1
if math.abs(pos.x) + structure.radius >= vkore.settings.world_size or
math.abs(pos.z) + structure.radius >= vkore.settings.world_size then
result = "Too close to map edge"
end
if not result then
result = minetest.place_schematic(
pos, -- pos to place schematic
minetest.get_modpath(modname) .. "/schems/structures/" .. schemname .. ".mts",
"random", -- rotation
nil, -- replacements
true, -- force_placement
"place_center_x, place_center_z" -- flags
)
end
else
result = "Pops a bubble"
end
if result == true then
mapgen.new_structure(schemname, pos)
minetest.log("action", "Spawned structure " .. schemname .. " at "..minetest.pos_to_string(pos))
elseif vkore.settings.game_mode == "dev" then
minetest.log("error",
"Failed to spawn structure " .. schemname .. " at " .. minetest.pos_to_string(pos) ..
". result = " .. dump(result)
)
end
end
})
function mapgen.get_schemname(name)
return name:sub(name:find(":")+1)
end
-- Check to see if a structure placed at pos will break another structure's 'bubble' with its own
function mapgen.structure_is_nearby(pos, bubble)
for structure, positions in pairs(mapgen.structures) do
local bubble2 = mapgen.registered_structures[structure].bubble
for _, structpos in ipairs(positions) do
if vector.distance(pos, structpos) <= bubble + bubble2 then
return true
end
end
end
return false
end
function mapgen.new_structure(schemname, pos)
table.insert(mapgen.structures[schemname], pos)
mods:set_string("structures", minetest.serialize(mapgen.structures))
end
mapgen.register_structure("town1", {
rarity = 0.00005,
radius = 40,
bubble = 100,
})
-- mapgen.register_structure("dungeon1", {
-- rarity = 0.00001,
-- radius = 7,
-- bubble = 25,
-- })
|
--[[
Construct the commands using the 'prepare', 'make' & 'post' branches of the recipe
Patch branch:
prepare:
patches:
# a) get patch from URL, check its integrity and save to the source cache:
- url : http://example.com/patch
sha256: hash
# b) use patch defined in the 'files' branch, don't need to check integrity
# because file is under your control:
- name: file.patch
# c) get patch from URL, check integrity and save to the source cache
# using the different name:
- url : http://example.com/patch
sha1: hash
name: match.patch
When you use local files for patch [b) case], and for any local files,
each used file should be defined inside 'files' branch either by 'content'
multiline field or by 'link' to real file.
files:
# a) insert plain text file (only UTF-8 encoded with Unix line endings) inside the recipe:
- name: foo
content: |
...
# b) insert binary file (or text file not matched the a) requirements) as base64 encoded:
- name: bar
type: base64
content: |
...
# c) provide relative path to the file (you may skip './' at the start):
- name: baz
link: relative-path-to-baz
--]]
local conf = dofile '/etc/bbq.conf' -- load BBQ configuration
local lib = require 'bbq.lib'
local die = lib.die
local function getPatchFromUrl (patch, dir)
local hand
if not patch.name then
patch.name = patch.url:gsub('.*/', '') -- basename
end
hand = io.open (conf.src..patch.name)
if not hand then
lib.exec ('wget -O "%s" "%s"', conf.src..patch.name, patch.url)
hand = io.open (conf.src..patch.name)
if not hand then
die ("\n%{red}ERROR: Can't get patch from \"%s\"", patch.url)
end
end
if hand then hand:close() end
lib.exec ('cp %s %s', conf.src..patch.name, dir)
-- check file integrity
patch.file = patch.name
if not lib.checkIntegrity (patch) then
die ("\n%{red}ERROR: Checksum doesn't match!")
end
end
local function getFileFromRecipe (recipe, filename, dir)
local index, file
if not recipe.files then
die ("\n%{red}ERROR: Can't get file \"%s\" from recipe (no files defined)", filename)
else
for i, j in ipairs (recipe.files) do
if j.name == filename then
index = i
end
end
if not index then
die ("\n%{red}ERROR: Can't get file \"%s\" from recipe (not defined)", filename)
end
end
if recipe.files[index].link then
lib.exec ('cd %s; cp %s %s',
conf.wok .. recipe.name,
'./' .. recipe.files[index].link, dir..filename)
elseif recipe.files[index].content then
file = io.open (dir..'temp', 'w')
file:write (recipe.files[index].content)
file:close () -- or file will be partially saved
if recipe.files[index].type then
if recipe.files[index].type == 'base64' then
lib.exec ('base64 -d %s > %s; rm %s', dir..'temp', dir..filename, dir..'temp')
else
die ('\n%{red}ERROR: Unknown type "%s" for file "%s"', recipe.files[index].type, recipe.files[index].name)
end
else
lib.exec ('mv %s %s', dir..'temp', dir..filename)
end
end
end
local function makePrepare (recipe, s)
local p = recipe.prepare
local patchdir
s:write ('\nprepare_rules() {\n')
if type (p) == 'string' then
s:write ('\n# rules:\n' .. p) -- short form of 'prepare.rules:' is just 'prepare:'
elseif type (p) == 'table' then
if p.patches then
patchdir = conf.wok .. recipe.name .. '/patches/'
lib.emptyDir (patchdir)
s:write ('\n# patches:\n')
for _, v in ipairs (p.patches) do
if v.url then
getPatchFromUrl (v, patchdir)
elseif v.name then
getFileFromRecipe (recipe, v.name, patchdir)
end
s:write (lib.printf('patch %s -i %s\n', (v.args or '-Np1'), patchdir..v.name))
end
end
if p.rules then
s:write ('\n# rules:\n' .. p.rules)
end
else
s:write (':\n') --define empty function
end
s:write ('}\n')
end
--[[
variants:
args: foo
args:
- foo
- bar
args:
- foo: bar
- baz: qux
args: # mixed:
- foo: bar # foo="bar"
- baz=qux # baz=qux
- rol: # rol=""
- ose # ose
--]]
local function Pairs (branch, template)
local out = ''
if type (branch) == 'string' then
out = out .. lib.printf (template, branch)
elseif type (branch) == 'table' then
for _, i in pairs (branch) do
if type (i) == 'string' then
out = out .. lib.printf (template, i)
elseif type (i) == 'table' then
for j,k in pairs (i) do
out = out .. lib.printf (template, j..'="'..k..'"')
end
end
end
end
return out
end
local function makeMake (recipe, s)
local m = recipe.make
if not m then
return -- no make rules
end
s:write ('\nmake_rules() {\n')
s:write (Pairs (m.env, 'export %s\n'))
-- use <defargs: ''> to DISABLE adding default $CONFIGURE_ARGS
if not m.defargs then
m.defargs = '$CONFIGURE_ARGS '
else
m.defargs = ''
end
if m.type == 'gnu' then
s:write (
Pairs (m.vars, '%s \\\n') ..
'./configure \\\n' ..
Pairs (m.args, '\t%s \\\n') ..
Pairs (m.defargs, '\t%s&&\n') ..
"if [ -e 'libtool' ]; then\n" ..
"\tsed -i 's| -shared | -Wl,-Os,--as-needed\\0|g' libtool\n" ..
"fi &&\n" ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') .. '&&\n' ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') ..
Pairs (m.destdir, 'DESTDIR=$install ') .. 'install || return 1\n'
)
elseif m.type == 'perl' then
s:write (
'PERL_MM_USE_DEFAULT=1 \\\n' .. Pairs (m.vars, '%s \\\n') ..
'perl Makefile.PL \\\n' ..
'\tINSTALLDIRS=vendor \\\n' .. Pairs (m.args, '\t%s \\\n') ..
'\t&&\n' ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') .. '&&\n' ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') ..
'PERL_MM_USE_DEFAULT=1 DESTDIR=$install install &&\n' ..
'chmod -R u+w $install\n'
)
elseif m.type == 'cmake' then
s:write (
Pairs ((m.build or 'build'), 'mkdir %s\n') ..
Pairs ((m.build or 'build'), 'cd %s\n') ..
Pairs (m.vars, '%s \\\n') ..
'cmake \\\n' ..
Pairs (m.args, '\t%s \\\n') ..
'\t.. &&\n' ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') .. '&&\n' ..
Pairs (m.makevars, '%s ') .. 'make ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.makeargs, '%s ') ..
Pairs (m.destdir, 'DESTDIR=$install ') .. 'install || return 1\n'
)
elseif m.type == 'meson' then
s:write (
Pairs ((m.build or 'build'), 'mkdir %s\n') ..
Pairs ((m.build or 'build'), 'cd %s\n') ..
Pairs (m.vars, '%s \\\n') ..
'meson-wrapper \\\n' ..
Pairs (m.args, '\t%s \\\n') ..
'\t&&\n' ..
Pairs (m.ninjavars, '%s ') .. 'ninja ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.ninjaargs, '%s ') .. '&&\n' ..
Pairs (m.ninjavars, '%s ') .. 'ninja ' .. Pairs (m.jobs, '-j%s ') .. Pairs (m.ninjaargs, '%s ') ..
Pairs (m.destdir, 'DESTDIR=$install ') .. 'install || return 1\n'
)
elseif m.type == 'python2' then
s:write (
'python2 -B setup.py install ' .. Pairs (m.args, '%s ') .. '--root=$install &&\n' ..
"find $install -type f -name '*.pyc' -delete\n"
)
elseif m.type == 'python3' then
s:write (
'python3 -B setup.py install ' .. Pairs (m.args, '%s ') .. '--root=$install &&\n' ..
"find $install -type f -name '*.pyc' -delete\n"
)
elseif m.type == 'python2+3' then
s:write (
-- use $install for python2
'python2 -B setup.py install ' .. Pairs (m.args, '%s ') .. '--root=$install &&\n' ..
"find $install -type f -name '*.pyc' -delete\n" ..
-- use $install-3 for python3
'python3 -B setup.py install ' .. Pairs (m.args, '%s ') .. '--root=$install-3 &&\n' ..
"find $install-3 -type f -name '*.pyc' -delete\n"
)
elseif m.type == 'ruby' then
s:write (
[[
gem install \
--no-document \
--ignore-dependencies \
--no-user-install \
--build-root $install \
$src/$TARBALL \
]] ..
Pairs (m.args, ' %s \\\n') ..
' || return 1\n'..
Pairs (m.insert, '%s') ..
[[
# some useful operations while Ruby gems cooking
_gems="$(ruby -e'puts Gem.default_dir')"
# remove unwanted empty folders
rmdir --ignore-fail-on-non-empty \
$install/$_gems/build_info/ \
$install/$_gems/cache/ \
$install/$_gems/doc/ \
$install/$_gems/extensions/
# move files to docdir
docdir=$install/usr/share/doc/$PACKAGE-$VERSION
for i in $(ls -ap $install/$_gems/gems/${PACKAGE#*-}-$VERSION/ | sed '
/\/$/d; /^\./d; /gemspec$/d; /Rakefile*/d; /Gemfile*/d; /Makefile/d;
/\.c$/d; /\.h$/d; /\.o$/d; /\.rb$/d; /\.so$/d; /\.yml$/d;
/Manifest/d; /\.inc$/d; /depend/d;
'); do
mkdir -p $docdir # docdir will not be created when nothing to move
mv $install/$_gems/gems/${PACKAGE#*-}-$VERSION/$i $docdir
done
if [ -d $install/$_gems/gems/${PACKAGE#*-}-$VERSION/doc/ ]; then
mkdir -p $docdir
mv $install/$_gems/gems/${PACKAGE#*-}-$VERSION/doc/ $docdir
fi
if [ -d $docdir ]; then
# move man pages
unset man_to_copy
for i in $(seq 1 8); do
for j in $(find $docdir -type f -name "*.$i" | sed '/LGPL-2\.1/d'); do
man_to_copy="$man_to_copy $j"
done
done
if [ -n "$man_to_copy" ]; then
cook_pick_manpages $man_to_copy
rm $man_to_copy
fi
# Install UTF-8 locale
tazpkg -gi --quiet --local --cookmode locale-en-base
mkdir -p /usr/lib/locale
localedef -i 'en_US' -c -f 'UTF-8' /usr/lib/locale/en_US.UTF-8
# convert rdoc to markdown (thanks https://gist.github.com/teeparham/8a99e308884e1c32735a)
for i in $(find $docdir -type f -name '*.rdoc'); do
LC_ALL=en_US.UTF-8 \
ruby -r rdoc -e 'puts RDoc::Markup::ToMarkdown.new.convert File.read(ARGV[0] || "'$i'")' \
>$i.md && rm $i || rm $i.md
done
fi
# move man pages (from the different place)
rubyman=$install/$_gems/gems/${PACKAGE#*-}-$VERSION/man
if [ -d $rubyman ]; then
unset man_to_copy
for i in $(seq 1 8); do
for j in $(find $rubyman -type f -name "*.$i" | sed '/LGPL-2\.1/d'); do
man_to_copy="$man_to_copy $j"
done
done
if [ -n "$man_to_copy" ]; then
cook_pick_manpages $man_to_copy
fi
rm -r $rubyman
fi
]])
end
s:write (Pairs (m.rules, '%s\n'))
s:write ('}\n')
end
-- if the file defined in 'files:' then install it from $files (it is already there),
-- otherwise install it from current path ($src)
local function installFile (recipe, name, to, mode)
local prefix = ''
if recipe.files then
for _,i in ipairs (recipe.files) do
if i.name == name then
prefix = '$files/'
end
end
end
return (lib.printf ('install -Dm%s %s %s\n', mode, prefix..name, to))
end
local function installBranch (recipe, branch, to, mode)
local ret = ''
if branch then
if type (branch) == 'string' then
ret = ret .. installFile (recipe, branch, to..branch, mode)
elseif type (branch) == 'table' then
for _,i in ipairs (branch) do
if type (i) == 'string' then
ret = ret .. installFile (recipe, i, to..i, mode)
elseif type (i) == 'table' then
if i.to:match ('/$') then
-- install to specified folder with the original name
ret = ret .. installFile (recipe, i.from, '$install'..i.to..i.from, (i.mode or '644'))
else
-- install to specified folder/name
ret = ret .. installFile (recipe, i.from, '$install'..i.to, (i.mode or '644'))
end
end
end
end
end
return ret
end
local function iconSize (fileName)
local file, w, h, tmp, svg, ew, eh, ev, v
-- four bytes - to size
local function qb2s (qb)
return (((qb:byte(1) * 256 + qb:byte(2)) * 256 + qb:byte(3)) * 256 + qb:byte(4))
end
file = io.open (fileName, 'rb')
if fileName:match ('%.png$') then
file:seek ('set', 16) -- skip 16 bytes
w = qb2s (file:read (4)) -- https://www.w3.org/TR/PNG/#11IHDR
h = qb2s (file:read (4))
file:close ()
elseif fileName:match ('%.svg$') then
-- yes, using regexps to parse an XML, but kitten will be alive :-)
tmp = file:read ('*a')
file:close ()
svg = tmp:gsub ('.*<svg([^>]*)>.*$' , '%1') :gsub ('[\a\r]', ' ')
w,ew = svg:gsub ('.*width="(%d+)p*x*".*$' , '%1')
h,eh = svg:gsub ('.*height="(%d+)p*x*".*$', '%1')
if ew == 0 or eh == 0 then
-- 'width="..."' and/or 'heigth="..."' missing, try to use 'viewBox="..."'
v,ev = svg:gsub ('.*viewBox="([^"]+)".*$', '%1')
if ev ~= 0 then
w,ew = v:gsub ('[%d%.]+[^%d%.]+[%d%.]+[^%d%.]+([%d%.]+)[^%d%.]+[%d%.]+', '%1')
h,eh = v:gsub ('[%d%.]+[^%d%.]+[%d%.]+[^%d%.]+[%d%.]+[^%d%.]+([%d%.]+)', '%1')
if ew == 0 or eh == 0 then w,h = 0, 0 end
else
return 0, 0 -- error
end
end
else
return 0, 0 -- error
end
return w, h
end
--[[
| cmd: foo | desktop: foo.desktop
|-----------------|-------------------------------------
| cmd: [foo, bar] | desktop: [foo.desktop, bar.desktop]
|-----------------|-------------------------------------
| cmd: | desktop:
| - foo | - foo.desktop
| - bar | - bar.desktop
---
|file:
|- from: foo
| to : /usr/share/bar/ # copy 'foo' to folder '/usr/share/bar/'
# default mode is 644
|- from: bar
| to : /usr/share/baz # copy 'bar' as file '/usr/share/baz'
| mode: 444
---
if nothing but 'rules:', short form allowed:
|post:
| rules: <rules>
|post: <rules>
---
icon:
- name: foo.png # file name from the 'files:' branch
to : bar.png # optional new file name (allow name without '.png' or '.svg')
cat : status # optional; default is 'apps'
size: 48 # optional; default is WxH read from file; also 'scalable' and 'symbolic' are supported
- from: icons/foo.svg # file name related to $src
to : home # optional new file name (allow name without '.png' or '.svg')
cat : places # optional; default is 'apps'
size: 16 # mandatory, because we can't guess the size at the rules creation time
--]]
local function makePost (recipe, s)
local p = recipe.post
local w,h, filesdir, dir, basename
-- shell functions to copy man pages and docs
s:write [[
scopy() {
if [ "$(stat -c %h -- "$1")" -eq 1 ]; then
cp -a "$1" "$2" # copy generic files
else
cp -al "$1" "$2" # copy hardlinks
fi
}
cook_pick_manpages() {
local name section
for i in $@; do
name=$(echo $i | sed 's|\.[gbx]z2*$||')
section=${name##*/}; section=${section##*.}
mkdir -p $install/usr/share/man/man$section
scopy $i $install/usr/share/man/man$section
done
}
cook_pick_docs() {
local docdir="$install/usr/share/doc/$PACKAGE-$VERSION"
mkdir -p $docdir
cp -r $@ $docdir
chmod -R a+r $docdir
}
]]
s:write ('\npost_rules() {\n')
if type (p) == 'string' then
s:write (Pairs (p, '%s\n')) -- short form, only rules
elseif type (p) == 'table' then
s:write (Pairs (p.rules, '%s\n'))
s:write (installBranch (recipe, p.cmd, '$install/usr/bin/', '755'))
s:write (installBranch (recipe, p.desktop, '$install/usr/share/desktop/', '644'))
s:write (installBranch (recipe, p.file))
if p.icon then
filesdir = conf.wok .. recipe.name .. '/files/'
lib.emptyDir (filesdir)
for _,j in ipairs (p.icon) do
if j.name then
getFileFromRecipe (recipe, j.name, filesdir)
if j.size then
if j.size == 'scalable' or j.size == 'symbolic' then
dir = j.size
else
dir = j.size .. 'x' .. j.size
end
else
w,h = iconSize (filesdir..j.name)
dir = w .. 'x' .. h
end
s:write (lib.printf ('install -Dm644 %s $install/usr/share/icons/hicolor/%s/%s/%s\n',
filesdir..j.name, dir, (j.cat or 'apps'), (j.to or j.name))
)
elseif j.from then
if j.size then
if j.size == 'scalable' or j.size == 'symbolic' then
dir = j.size
else
dir = j.size .. 'x' .. j.size
end
else
die ('Undefined size to copy icon')
end
basename = j.from:gsub ('^.*/', '')
s:write (lib.printf ('install -Dm644 $src/%s $install/usr/share/icons/hicolor/%s/%s/%s\n',
j.from, dir, (j.cat or 'apps'), (j.to or basename))
)
end
end
end
s:write (Pairs (p.doc, 'cook_pick_docs %s\n'))
s:write (Pairs (p.man, 'cook_pick_manpages %s\n'))
else
s:write ('\t:\n')
end
s:write ('}\n')
end
local function makeTest (recipe, s)
local t = recipe.test
s:write ('\ntest_rules() {\n')
if type (t) == 'string' then
s:write (t .. '\n') -- short form of 'test.rules:' is just 'test:'
elseif type (t) == 'table' then
if t.rules then
s:write (t.rules .. '\n')
else
s:write (':\n') --define empty function
end
else
s:write (':\n') --define empty function
end
s:write ('}\n')
end
local function make (recipe, script)
local s -- script handler
s = io.open (script, 'w')
local tarball
if recipe.src then tarball = recipe.src[1].file end
s:write (
'# global variables:\n' ..
Pairs (conf.flags[conf.arch], 'export %s\n') ..
'\n# package variables:\n' ..
Pairs (recipe.name, 'PACKAGE="%s"\n') ..
Pairs (recipe.version, 'VERSION="%s"\n') ..
Pairs (tarball, 'TARBALL="%s"\n') ..
'\n# useful variables:\n' ..
'src="' .. conf.wok .. recipe.name .. '/src/' .. recipe.name .. '-' .. recipe.version ..'"\n' ..
'install="' .. conf.wok .. recipe.name .. '/install"\n' ..
'files="' .. conf.wok .. recipe.name .. '/files"\n'
)
makePrepare (recipe, s)
makeMake (recipe, s)
makePost (recipe, s)
makeTest (recipe, s)
s:write [[
if [ -n "$continue" ]; then
prepare_rules || return 1
fi
make_rules &&
post_rules &&
test_rules
]]
s:close()
end
return {
make = make
}
|
local INJECTED_SCRIPTS = {}
function injectScript ( script )
if exports.global:isPlayerScripter( getLocalPlayer( ) ) and type(script) == "string" and #script > 0 then
script = script:lower()
if INJECTED_SCRIPTS[script] then
outputChatBox("Script '" .. script .. "' already loaded.", 255, 0, 0)
return false
else
local xmlFile = xmlLoadFile ( "scripts/" .. script .. ".lua" )
if not xmlFile then
outputChatBox ( "Error: Couldn't open scripts/" .. script .. ".lua", 255, 0, 0 )
return false
else
local code = xmlNodeGetValue ( xmlFile )
local chunk = loadstring(code)
if not chunk then
outputChatBox ( "Error: cannot compile scripts/" .. script .. ".lua", 255, 0, 0 )
return false
else
local newEnv = { globalVars = {}, wrappers = { commands = {}, events = {}, binds = {}, timers = {}, elements = {} } }
for k, v in pairs(_G) do
if k ~= "INJECTED_SCRIPTS" then
newEnv.globalVars[k] = v
end
end
chunk = setfenv ( chunk, newEnv.globalVars )
-- Export some MTA functions that require wrapping
newEnv.wrappers.table = table
newEnv.wrappers.ipairs = ipairs
newEnv.wrappers.pairs = pairs
newEnv.wrappers._addCommandHandler = addCommandHandler
newEnv.wrappers._removeCommandHandler = removeCommandHandler
newEnv.wrappers._addEventHandler = addEventHandler
newEnv.wrappers._removeEventHandler = removeEventHandler
newEnv.wrappers._bindKey = bindKey
newEnv.wrappers._unbindKey = unbindKey
newEnv.wrappers._setTimer = setTimer
newEnv.wrappers._killTimer = killTimer
newEnv.wrappers._destroyElement = destroyElement
newEnv.wrappers._playSound = playSound
newEnv.wrappers._playSound3D = playSound3D
newEnv.wrappers._createBlip = createBlip
newEnv.wrappers._createBlipAttachedTo = createBlipAttachedTo
newEnv.wrappers._createColCircle = createColCircle
newEnv.wrappers._createColCuboid = createColCuboid
newEnv.wrappers._createColRectangle = createColRectangle
newEnv.wrappers._createColSphere = createColSphere
newEnv.wrappers._createColTube = createColTube
newEnv.wrappers._createColPolygon = createColPolygon
newEnv.wrappers._createElement = createElement
newEnv.wrappers._engineImportCOL = engineImportCOL
newEnv.wrappers._engineImportTXD = engineImportTXD
newEnv.wrappers._engineLoadCOL = engineLoadCOL
newEnv.wrappers._engineLoadDFF = engineLoadDFF
newEnv.wrappers._engineLoadTXD = engineLoadTXD
newEnv.wrappers._guiCreateButton = guiCreateButton
newEnv.wrappers._guiCreateCheckBox = guiCreateCheckBox
newEnv.wrappers._guiCreateEdit = guiCreateEdit
newEnv.wrappers._guiCreateGridList = guiCreateGridList
newEnv.wrappers._guiCreateMemo = guiCreateMemo
newEnv.wrappers._guiCreateProgressBar = guiCreateProgressBar
newEnv.wrappers._guiCreateRadioButton = guiCreateRadioButton
newEnv.wrappers._guiCreateScrollBar = guiCreateScrollBar
newEnv.wrappers._guiCreateScrollPane = guiCreateScrollPane
newEnv.wrappers._guiCreateStaticImage = guiCreateStaticImage
newEnv.wrappers._guiCreateTabPanel = guiCreateTabPanel
newEnv.wrappers._guiCreateTab = guiCreateTab
newEnv.wrappers._guiCreateLabel = guiCreateLabel
newEnv.wrappers._guiCreateWindow = guiCreateWindow
newEnv.wrappers._createMarker = createMarker
newEnv.wrappers._createObject = createObject
newEnv.wrappers._createPed = createPed
newEnv.wrappers._createPickup = createPickup
newEnv.wrappers._createProjectile = createProjectile
newEnv.wrappers._createRadarArea = createRadarArea
newEnv.wrappers._createVehicle = createVehicle
newEnv.wrappers._createWater = createWater
newEnv.globalVars.addCommandHandler = setfenv ( function ( cmd, fn, ... )
-- Create a state
local state = { cmd, fn }
table.insert ( commands, state )
return _addCommandHandler ( cmd, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.removeCommandHandler = setfenv ( function ( cmd, fn, ... )
-- Find the states to remove
for k, state in ipairs ( commands ) do
if state[1] == cmd and ( fn == state[2] or not fn ) then
table.remove ( commands, k )
end
end
return _removeCommandHandler ( cmd, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.addEventHandler = setfenv ( function ( evt, entity, fn, ... )
-- Create a state
local state = { evt, entity, fn }
table.insert ( events, state )
return _addEventHandler ( evt, entity, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.removeEventHandler = setfenv ( function ( evt, entity, fn, ... )
-- Find the states to remove
for k, state in ipairs ( events ) do
if state[1] == evt and ( state[2] == entity or not entity ) and ( state[3] == fn or not fn ) then
table.remove ( events, k )
end
end
return _removeEventHandler ( evt, entity, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.bindKey = setfenv ( function ( key, keyState, fn, ... )
-- Create a state
local state = { key, keyState, fn }
table.insert ( binds, state )
return _bindKey ( key, keyState, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.unbindKey = setfenv ( function ( key, keyState, fn, ... )
-- Find the states to remove
for k, state in ipairs ( binds ) do
if state[1] == key and ( state[2] == keyState or not keyState ) and ( state[3] == fn or not fn ) then
table.remove ( binds, k )
end
end
return _unbindKey ( key, keyState, fn, ... )
end, newEnv.wrappers )
newEnv.globalVars.setTimer = setfenv ( function ( ... )
-- Get the timer element
local theTimer = _setTimer ( ... )
if theTimer then
timers[theTimer] = true
end
return theTimer
end, newEnv.wrappers )
newEnv.globalVars.killTimer = setfenv ( function ( theTimer )
if theTimer then timers[theTimer] = nil end
return _killTimer ( theTimer )
end, newEnv.wrappers )
newEnv.globalVars.playSound = setfenv ( function ( ... )
local element = _playSound ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.playSound3D = setfenv ( function ( ... )
local element = _playSound3D ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.destroyElement = setfenv ( function ( element )
if element then elements[ element ] = nil end
return _destroyElement ( element )
end, newEnv.wrappers )
newEnv.globalVars.createBlip = setfenv ( function ( ... )
local element = _createBlip ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createBlipAttachedTo = setfenv ( function ( ... )
local element = _createBlipAttachedTo ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColCircle = setfenv ( function ( ... )
local element = _createColCircle ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColCuboid = setfenv ( function ( ... )
local element = _createColCuboid ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColRectangle = setfenv ( function ( ... )
local element = _createColRectangle ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColSphere = setfenv ( function ( ... )
local element = _createColSphere ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColTube = setfenv ( function ( ... )
local element = _createColTube ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createColPolygon = setfenv ( function ( ... )
local element = _createColPolygon ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createElement = setfenv ( function ( ... )
local element = _createElement ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.engineImportCOL = setfenv ( function ( ... )
local element = _engineImportCOL ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.engineImportTXD = setfenv ( function ( ... )
local element = _engineImportTXD ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.engineLoadCOL = setfenv ( function ( ... )
local element = _engineLoadCOL ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.engineLoadDFF = setfenv ( function ( ... )
local element = _engineLoadDFF ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.engineLoadTXD = setfenv ( function ( ... )
local element = _engineLoadTXD ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateButton = setfenv ( function ( ... )
local element = _guiCreateButton ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateCheckBox = setfenv ( function ( ... )
local element = _guiCreateCheckBox ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateEdit = setfenv ( function ( ... )
local element = _guiCreateEdit ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateGridList = setfenv ( function ( ... )
local element = _guiCreateGridList ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateMemo = setfenv ( function ( ... )
local element = _guiCreateMemo ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateProgressBar = setfenv ( function ( ... )
local element = _guiCreateProgressBar ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateRadioButton = setfenv ( function ( ... )
local element = _guiCreateRadioButton ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateScrollBar = setfenv ( function ( ... )
local element = _guiCreateScrollBar ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateScrollPane = setfenv ( function ( ... )
local element = _guiCreateScrollPane ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateStaticImage = setfenv ( function ( ... )
local element = _guiCreateStaticImage ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateTabPanel = setfenv ( function ( ... )
local element = _guiCreateTabPanel ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateTab = setfenv ( function ( ... )
local element = _guiCreateTab ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateLabel = setfenv ( function ( ... )
local element = _guiCreateLabel ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.guiCreateWindow = setfenv ( function ( ... )
local element = _guiCreateWindow ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createMarker = setfenv ( function ( ... )
local element = _createMarker ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createObject = setfenv ( function ( ... )
local element = _createObject ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createPed = setfenv ( function ( ... )
local element = _createPed ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createPickup = setfenv ( function ( ... )
local element = _createPickup ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createProjectile = setfenv ( function ( ... )
local element = _createProjectile ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createRadarArea = setfenv ( function ( ... )
local element = _createRadarArea ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createVehicle = setfenv ( function ( ... )
local element = _createVehicle ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
newEnv.globalVars.createWater = setfenv ( function ( ... )
local element = _createWater ( ... )
if element then
elements[ element ] = true
end
return element
end, newEnv.wrappers )
INJECTED_SCRIPTS[script] = newEnv
chunk ()
outputChatBox ( "Script '" .. script .. ".lua' loaded", 0, 255, 0 )
return true
end
end
end
end
return false
end
local function uninjectScript ( script )
if exports.global:isPlayerScripter( getLocalPlayer( ) ) and type(script) == "string" and #script > 0 then
script = script:lower()
if not INJECTED_SCRIPTS[script] then
outputChatBox("Script '" .. script .. ".lua' not loaded.", 255, 0, 0)
return false
else
-- Unload all commands, events, keybinds and timers
local wrappers = INJECTED_SCRIPTS[script].wrappers
for k, v in ipairs ( wrappers.commands ) do
removeCommandHandler ( v[1], v[2] )
end
for k, v in ipairs ( wrappers.events ) do
removeEventHandler ( v[1], v[2], v[3] )
end
for k, v in ipairs ( wrappers.binds ) do
unbindKey ( v[1], v[2], v[3] )
end
for k, v in pairs ( wrappers.timers ) do
killTimer ( v )
end
for element in pairs ( wrappers.elements ) do
destroyElement ( element )
end
INJECTED_SCRIPTS[script] = nil
outputChatBox("Script '" .. script .. ".lua' unloaded.", 0, 255, 0)
return true
end
end
return false
end
addCommandHandler ( "inject", function ( c, ... ) injectScript ( table.concat( { ... }, " " ) ) end )
addCommandHandler ( "uninject", function ( c, ... ) uninjectScript ( table.concat( { ... }, " " ) ) end )
addCommandHandler ( "reinject", function ( c, ... ) if uninjectScript ( table.concat( { ... }, " " ) ) then injectScript ( table.concat( { ... }, " " ) ) end end )
|
local LIBFRAMEFADE_VERSION = 4;
if LibFrameFade and (LibFrameFade.VERSION or 0) >= LIBFRAMEFADE_VERSION then
return;
end
local function RehashTable(tbl)
local strkey = "LibFrameFade_RehashKey";
local numkey = 2^32;
tbl[strkey] = nil;
repeat
if tbl[numkey] == nil then
tbl[numkey] = nil;
end
numkey = numkey + 1;
until issecurevariable(tbl, strkey);
end
LibFrameFade = LibFrameFade or CreateFrame("Frame");
function LibFrameFade:OnLoad()
if not self.closures then
self.closures = {};
end
if not self.hooks then
self.hooks = {};
end
if not self.faderPool then
-- luacheck: no unused
local creationFunc = function(pool) return self:CreateFader(); end;
local resetterFunc = function(pool, fader) return self:ResetFader(fader); end;
self.faderPool = CreateObjectPool(creationFunc, resetterFunc);
self.faderPool:SetResetDisallowedIfNew(true);
end
if not self.frameFaders then
self.frameFaders = {};
end
-- For v4+ hooks can be disabled later if needed. Any earlier version
-- unfortunately can't have hooks removed - to accomodate, the booleans
-- for 'isUIFrameFadeHooked' and 'isUIFrameFadeRemoveFrameHooked' are
-- kept around on the library table if we need to detect this one day.
self:SecureHook("UIFrameFade", self:GetOrCreateMethodClosure("ProcessGlobalFadeFrames"));
self:SecureHook("UIFrameFadeRemoveFrame", self:GetOrCreateMethodClosure("StopFadingFrame"));
-- When upgrading or initially loading we should take ownership of any
-- active fades being handled by UIFrameFade.
self:ProcessGlobalFadeFrames();
end
function LibFrameFade:OnFaderFinished(fader)
local fadeInfo = self:GetFadeInfoForFader(fader);
self:ReleaseFader(fader);
-- Dispatching the on-finish function should be the last thing done as
-- we need to be in a state to allow new fades to be started on the frame
-- we just finished with.
if fadeInfo and fadeInfo.finishedFunc then
local arg1 = fadeInfo.finishedArg1;
local arg2 = fadeInfo.finishedArg2;
local arg3 = fadeInfo.finishedArg3;
local arg4 = fadeInfo.finishedArg4;
xpcall(fadeInfo.finishedFunc, CallErrorHandler, arg1, arg2, arg3, arg4);
end
end
function LibFrameFade:OnFaderStopped(fader, requested) -- luacheck: no unused (requested)
self:ReleaseFader(fader);
end
function LibFrameFade:OnFaderUpdate(fader, elapsed) -- luacheck: no unused (elapsed)
local frame = self:GetFrameForFader(fader);
if not frame then
return;
end
-- The smooth progress value reflects the current alpha progress of the
-- animation and isn't affected by any start or end delays.
local alpha = fader.Anim:GetSmoothProgress();
frame:SetAlpha(alpha);
end
function LibFrameFade:IsFadingFrame(frame)
return self.frameFaders[frame] ~= nil;
end
function LibFrameFade:StartFadingFrame(frame, fadeInfo)
-- Clean up any ongoing fade operations for this frame before continuing.
if self:IsFadingFrame(frame) then
self:StopFadingFrame(frame);
end
local fader = self.faderPool:Acquire();
-- The '.startAlpha' field on the 'fadeInfo' table is explicitly ignored
-- when configuring the from-alpha value for the animation in favor of
-- the current alpha value of the frame.
--
-- The reason is that we need to support the case where animations are
-- already in-progress via UIFrameFade. This may happen if we're loaded
-- late, or in an edge case where addons are possibly writing directly
-- to the FADEFRAMES global bypassing our hooks until something triggers
-- them later.
--
-- This works fine for both the above cases and the normal case where
-- we're called at the start of a fade request, since the UIFrameFade
-- function that we've hooked guarantees that the alpha of 'frame' will
-- be set to the '.startAlpha' value.
local fromAlpha = frame:GetAlpha();
local toAlpha = fadeInfo.endAlpha;
local duration = fadeInfo.timeToFade;
local elapsed = fadeInfo.fadeTimer or 0;
local endDelay = fadeInfo.fadeHoldTime or 0;
fader.Anim:SetTarget(frame);
fader.Anim:SetFromAlpha(fromAlpha);
fader.Anim:SetToAlpha(toAlpha);
fader.Anim:SetDuration(duration - elapsed);
fader.Anim:SetEndDelay(endDelay);
if self:ShouldFrameReceiveAlphaUpdates(frame) then
fader:SetScript("OnUpdate", self:GetOrCreateMethodClosure("OnFaderUpdate"));
end
fader:Play();
self.frameFaders[frame] = fader;
end
function LibFrameFade:StopFadingFrame(frame)
local fader = self:GetFaderForFrame(frame);
if not fader then
return;
end
-- Note that because SetToFinalAlpha is in effect here the final alpha
-- value on 'frame' after stopping the animation will be set according to
-- its progress, which aligns with the behavior of UIFrameFadeRemoveFrame.
fader:Stop();
end
function LibFrameFade:GetFaderForFrame(frame)
return self.frameFaders[frame];
end
function LibFrameFade:GetFadeInfoForFrame(frame)
return frame.fadeInfo;
end
function LibFrameFade:GetFadeInfoForFader(fader)
local frame = self:GetFrameForFader(fader);
local fadeInfo = frame and self:GetFadeInfoForFrame(frame) or nil;
return fadeInfo;
end
function LibFrameFade:GetFrameForFader(fader)
local frame = fader.Anim:GetTarget();
-- 'self' is used as a sentinel value for target to indicate that there
-- is no frame actively being faded by the fader. 'self' in particular
-- is used because it's the default target on construction of the
-- animation, and because we can't call 'Anim:SetTarget(nil)'.
--
-- As such if the target is 'self', redirect it to always be nil when
-- queried.
if frame == self then
frame = nil;
end
return frame;
end
function LibFrameFade:CreateFader()
local fader = self:CreateAnimationGroup();
fader:SetScript("OnFinished", self:GetOrCreateMethodClosure("OnFaderFinished"));
fader:SetScript("OnStop", self:GetOrCreateMethodClosure("OnFaderStopped"));
fader:SetToFinalAlpha(true);
fader.Anim = fader:CreateAnimation("Alpha");
fader.Anim:SetOrder(1);
return fader;
end
function LibFrameFade:ResetFader(fader)
fader.Anim:SetTarget(self); -- See GetFrameForFader for why we use 'self'.
fader:SetScript("OnUpdate", nil);
end
function LibFrameFade:ReleaseFader(fader)
local frame = self:GetFrameForFader(fader);
if frame then
self.frameFaders[frame] = nil;
end
if self.faderPool:IsActive(fader) then
self.faderPool:Release(fader);
end
end
function LibFrameFade:ProcessGlobalFadeFrames()
local frames = FADEFRAMES;
for index, frame in ipairs_reverse(frames) do
local fadeInfo = self:GetFadeInfoForFrame(frame);
self:StartFadingFrame(frame, fadeInfo);
table.remove(frames, index);
end
-- Rehash the table to prevent taint due to UIFrameFade accessing
-- keys directly as part of its loops.
RehashTable(frames);
end
function LibFrameFade:ShouldFrameReceiveAlphaUpdates(frame)
-- By rewriting the UIFrameFade system to be animation based, one defect
-- that occurs is that SetAlpha is no longer called on each frame, which
-- can interfere with other addons. One example is ElvUI's chat tabs
-- which rely on a hook to prevent the tabs from fading out.
--
-- To work around this, if a SetAlpha method is present on the frame
-- directly - instead of just being part of the metatable - we'll
-- trigger a SetAlpha call every frame while the frame is fading.
if rawget(frame, "SetAlpha") ~= nil then
return true;
else
return false;
end
end
function LibFrameFade:GetOrCreateMethodClosure(funcName, ...)
local func = self.closures[funcName];
if not func then
func = GenerateClosure(function(...) return self[funcName](self, ...); end, ...);
self.closures[funcName] = func;
end
return func;
end
function LibFrameFade:SecureHook(funcName, func)
local isHookInstalled = (self.hooks[funcName] ~= nil);
local isHookBeingRemoved = (func == nil);
if not isHookInstalled and isHookBeingRemoved then
return; -- No hook is installed, thus there's nothing to remove.
end
-- All secure hooks go through a layer of indirection via our 'hooks'
-- table to ensure that, if later required, we can disable them on
-- upgrades.
if isHookBeingRemoved then
self.hooks[funcName] = nop;
else
self.hooks[funcName] = func;
end
if not isHookInstalled then
hooksecurefunc(funcName, function(...) return self.hooks[funcName](...); end);
end
end
function LibFrameFade:SecureUnhook(funcName)
self:SecureHook(funcName, nil);
end
-- The UIFrameIsFading function is relied upon by a few addons and needs to
-- return correct results, which it won't due to our mucking around with
-- the FADEFRAMES table.
--
-- This function is unused by Blizzard in any live or test client for all
-- game flavors as of 9.1.0, 2.5.2, and 1.14.0 - as a result it should be
-- a safe replacement, despite tainting.
function UIFrameIsFading(frame)
return LibFrameFade:IsFadingFrame(frame);
end
LibFrameFade:OnLoad();
LibFrameFade.VERSION = LIBFRAMEFADE_VERSION;
|
require("gmake2")
local p = premake
local m = p.modules.gmake2
local cpp = m.cpp
if _ACTION == "gmake2" then
rule("asm")
fileExtension({ ".asm" })
buildoutputs({ "$(OBJDIR)/%{file.objname}.o" })
buildmessage("$(notdir $<)")
buildcommands({ "nasm %{premake.modules.gmake2.cpp.asmFileFlags(cfg, file)} -o \"$@\" \"$<\"" })
end
p.override(cpp, "createRuleTable", function(base, prj)
local rules = {}
local function addRule(extension, rule)
if type(extension) == 'table' then
for _, value in ipairs(extension) do
addRule(value, rule)
end
else
rules[extension] = rule
end
end
-- add all rules.
local usedRules = table.join({'asm', 'cpp', 'cc', 'resource'}, prj.rules)
for _, name in ipairs(usedRules) do
local rule = p.global.getRule(name)
addRule(rule.fileExtension, rule)
end
-- create fileset categories.
local filesets = {
['.o'] = 'OBJECTS',
['.obj'] = 'OBJECTS',
['.asm'] = 'SOURCES',
['.cc'] = 'SOURCES',
['.cpp'] = 'SOURCES',
['.cxx'] = 'SOURCES',
['.mm'] = 'SOURCES',
['.c'] = 'SOURCES',
['.s'] = 'SOURCES',
['.m'] = 'SOURCES',
['.rc'] = 'RESOURCES',
}
-- cache the result.
prj._gmake = prj._gmake or {}
prj._gmake.rules = rules
prj._gmake.filesets = filesets
end)
local function archToNASM(architecture)
if common.target == "windows" then
if architecture == "x86" then
return "win32"
else
return "win64"
end
elseif common.target == "macosx" then
if architecture == "x86" then
return "macho32"
else
return "macho64"
end
else
if architecture == "x86" then
return "elf32"
else
return "elf64"
end
end
end
function errorReport()
if common.target == "windows" then
return "vc"
else
return "gnu"
end
end
cpp.nasmOptimizeFlags = {
["Off"] = "-O0",
["On"] = "-O1",
["Debug"] = "-O1",
["Size"] = "-Ox",
["Speed"] = "-Ox",
["Full"] = "-Ox"
}
function cpp.asmFileFlags(cfg, file)
local fcfg = p.fileconfig.getconfig(file, cfg)
cfg = fcfg.config
local command = "-X" .. errorReport() .. " -f " .. archToNASM(cfg.architecture)
for _, inc in ipairs(cfg.includedirs) do
command = command .. " -i \"" .. inc .. "\""
end
for _, def in ipairs(cfg.defines) do
command = command .. " \"-d" .. def .. "\""
end
for _, udef in ipairs(cfg.undefines) do
command = command .. " \"-u" .. udef .. "\""
end
if cfg.symbols == "On" then
command = command .. " -g"
end
command = command .. " " .. cpp.nasmOptimizeFlags[cfg.optimize]
return command
end
|
solution "steamworks4j"
configurations { "release" }
platforms { "x64" }
buildoptions {
"-std=c++11",
"-Wall"
}
includedirs {
"../java-wrapper/src/main/native/include/jni",
"../java-wrapper/src/main/native/include/jni/linux",
"../sdk/public/steam"
}
defines {
"NDEBUG",
"LINUX"
}
flags {
"Optimize"
}
project "steamworks4j"
kind "SharedLib"
language "C++"
files {
"../java-wrapper/src/main/native/**.cpp"
}
includedirs {
"../java-wrapper/src/main/native",
}
libdirs {
"../sdk/redistributable_bin/linux64"
}
links {
"steam_api"
}
project "steamworks4j-server"
kind "SharedLib"
language "C++"
files {
"../server/src/main/native/**.cpp"
}
excludes {
"../server/src/main/native/**EncryptedAppTicket*.cpp"
}
includedirs {
"../server/src/main/native",
}
libdirs {
"../sdk/redistributable_bin/linux64"
}
links {
"steam_api"
}
project "steamworks4j-encryptedappticket"
kind "SharedLib"
language "C++"
files {
"../server/src/main/native/**EncryptedAppTicket*.cpp"
}
includedirs {
"../server/src/main/native",
}
libdirs {
"../sdk/public/steam/lib/linux64"
}
links {
"sdkencryptedappticket"
}
|
events.trigger{
collision = function(self, event)
local im = jvgslua.InputManager_getInstance()
im:sendQuitEvent()
end
}
|
--[[ DataElement.lua | Copyright Notice
INC Game Framework - OS Game Framework for Roblox
Copyright (C) 2022 Inctus (Haashim-Ali Hussain)
Full notice in IGF.lua ]]--
local DataElement = {}
export type DataElement = typeof(DataElement)
return DataElement
|
local modpath = minetest.get_modpath("murk")
minetest.register_abm({
nodenames = {"murk:dirt"},
neighbors = {"murk:dirt_with_grass"},
interval = 8,
chance = 40,
catch_up = false,
action = function(pos, node)
if (minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0) > 13 then
minetest.swap_node(pos, {name = "murk:dirt_with_grass"})
end
end
})
minetest.register_abm({
nodenames = {"murk:dirt"},
neighbors = {"murk:dirt_with_dry_grass"},
interval = 10,
chance = 40,
catch_up = false,
action = function(pos, node)
if (minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0) > 13 then
minetest.swap_node(pos, {name = "murk:dirt_with_dry_grass"})
end
end
})
minetest.register_abm({
nodenames = {"murk:dirt"},
neighbors = {"murk:dirt_with_leaf_grass"},
interval = 9,
chance = 40,
catch_up = false,
action = function(pos, node)
if (minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0) > 13 then
minetest.swap_node(pos, {name = "murk:dirt_with_leaf_grass"})
end
end
})
minetest.register_abm({
nodenames = {"murk:dirt"},
neighbors = {"murk:dirt_with_snow"},
interval = 40,
chance = 40,
catch_up = false,
action = function(pos, node)
if (minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0) > 13 then
minetest.swap_node(pos, {name = "murk:dirt_with_snow"})
end
end
})
minetest.register_abm({
nodenames = {"murk:dirt_with_grass", "murk:dirt_with_dry_grass", "murk:dirt_with_leaf_grass"},
interval = 6,
chance = 40,
catch_up = false,
action = function(pos, node)
local above = {x = pos.x, y = pos.y + 1, z = pos.z}
if (minetest.get_node_light(above, 0.5) or 0) < 10 and minetest.get_node_or_nil(above) then
if node.name == "murk:dirt_with_grass" then
minetest.swap_node(pos, {name = "murk:dirt_with_yellow_grass"})
else
minetest.swap_node(pos, {name = "murk:dirt"})
end
end
end
})
minetest.register_abm({
nodenames = {"murk:dirt_with_yellow_grass"},
interval = 6,
chance = 25,
catch_up = false,
action = function(pos, node)
local light = minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0
if light < 9 then
minetest.swap_node(pos, {name = "murk:dirt"})
elseif light > 13 then
minetest.swap_node(pos, {name = "murk:dirt_with_grass"})
end
end
})
minetest.register_abm({
nodenames = {"murk:cobble", "murk:cobble_wall", "murk:cobble_slab", "murk:cobble_stair", "murk:cobble_stair_outer", "murk:cobble_stair_inner"},
neighbors = {"murk:moss_cobble", "murk:moss_cobble_wall", "murk:moss_cobble_slab", "murk:moss_cobble_stair", "murk:moss_cobble_stair_outer", "murk:moss_cobble_stair_inner"},
interval = 8,
chance = 40,
catch_up = false,
action = function(pos, node)
local above = {x = pos.x, y = pos.y + 1, z = pos.z}
local water = minetest.find_node_near(pos, 1, "group:water")
local light = minetest.get_node_light(above) or 0
if light == 0 then
local pos = minetest.find_node_near(pos, 1, "air")
if pos then
light = minetest.get_node_light(pos) or 0
light = light - 1
end
end
if water and light < 13 and light > 5 then
local above = minetest.get_node(above)
if minetest.get_item_group(above.name, "water") == 0 then
minetest.swap_node(pos, {name = node.name:gsub(":", ":moss_"), param2 = node.param2})
end
end
end
})
minetest.register_abm({
nodenames = {"murk:moss_cobble", "murk:moss_cobble_wall", "murk:moss_cobble_slab", "murk:moss_cobble_stair", "murk:moss_cobble_stair_outer", "murk:moss_cobble_stair_inner"},
interval = 8,
chance = 40,
catch_up = false,
action = function(pos, node)
if (minetest.get_node_light({x = pos.x, y = pos.y + 1, z = pos.z}) or 0) > 13 then
minetest.swap_node(pos, {name = node.name:gsub(":moss_", ":"), param2 = node.param2})
end
end
})
--[[
minetest.register_node("murk:schematic_helper", {
description = "Used to help schematics set param1 and metadata",
tiles = {"unknown_node.png"},
groups = {not_in_creative_inventory = 1}
})
minetest.register_abm({
nodenames = {"murk:schematic_helper"},
interval = 1,
chance = 1,
action = function(pos, node)
if node.param2 == 0 then
minetest.swap_node(pos, {name = "murk:trunk_apple", param1 = 1})
else
minetest.remove_node(pos)
end
end
})
--]]
|
cc.FileUtils:getInstance():setPopupNotify(false)
cc.FileUtils:getInstance():addSearchPath("src/",true)
cc.FileUtils:getInstance():addSearchPath("res/",true)
print("main.lua load Billiards alone")
require("gameBilliards.app.utils.Tools")
require("gameBilliards.app.utils.Help")
g_myGameName = "gameBilliards"
local function main()
require("gameBilliards.app.GameApp"):create():run()
end
local status, msg = xpcall(main, __G__TRACKBACK__)
if not status then
print(msg)
end
|
PLUGIN.name = "Looting"
PLUGIN.author = "orc, thadah, hikka (fix), kek1ch"
PLUGIN.desc = "A plugin for dropping player inventory on death."
PLUGIN.ignored = PLUGIN.ignored or {}
PLUGIN.ignored = PLUGIN.equip or {}
nut.util.include("sh_ignored.lua")
nut.util.include("sv_plugin.lua")
nut.config.add("lootTime", 360, "Number of seconds before loot disappears.", nil, {
data = {min = 1, max = 86400},
category = "Looting"
})
if (CLIENT) then
netstream.Hook("lootOpen", function(entity, index)
local inventory = nut.item.inventories[index]
local ply = LocalPlayer()
local char = ply:getChar()
if (IsValid(nut.gui.inv1)) or (IsValid(invent_info_kek)) or (IsValid(equipment_panel)) or (IsValid(equipment)) then return false end
if (IsValid(entity) and inventory and inventory.slots) and (char) then
nut.gui.inv1 = vgui.Create("nutInventory")
nut.gui.inv1:ShowCloseButton(false)
local inventory2 = char:getInv()
if (inventory2) then nut.gui.inv1:setInventory(inventory2) end
nut.gui.inv1:SetSize(nut.gui.inv1:GetWide(), nut.gui.inv1:GetTall())
nut.gui.inv1:SetPos(ScrW()*0.6592, ScrH()*0.29)
invent_info_kek = vgui.Create("invent_info_kek")
invent_info_kek:SetPos(ScrW()*0.6592, ScrH()*0.067)
invent_info_kek:SetSize(invent_info_kek:GetSize())
case_info_kek = vgui.Create("safe_info_kek")
case_info_kek:SetPos(ScrW()*0.035, ScrH()*0.067)
case_info_kek:SetSize(case_info_kek:GetSize())
--case_info_kek:setup()
equipment_panel = vgui.Create("equipment_panel")
equipment_panel:SetPos(ScrW()*0.35, ScrH()*0.29)
equipment_panel:SetSize(equipment_panel:GetSize())
safebox_menuINV = vgui.Create("nutInventory")
safebox_menuINV:ShowCloseButton(false)
safebox_menuINV:SetTitle("")
safebox_menuINV:setInventory(inventory)
safebox_menuINV:SetPos(ScrW()*0.035, ScrH()*0.29)
safebox_menuINV.OnClose = function(this)
if (IsValid(nut.gui.inv1) and !IsValid(nut.gui.menu)) then
nut.gui.inv1:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
case_info_kek:Remove()
end
netstream.Start("lootExit", entity)
end
function safebox_menuINV:Paint(w, h)
nut.util.drawBlur(self, 10)
surface.SetDrawColor(Color( 20, 20, 20, 220))
surface.DrawRect( 0, 0, w, h )
surface.DrawOutlinedRect(0, 0, w, h)
surface.SetDrawColor(0, 0, 14, 150)
surface.DrawRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033)
surface.SetDrawColor(Color( 30, 30, 30, 90))
surface.DrawOutlinedRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033) --шапка
draw.DrawText("Инвентарь", "Roh20", ScrW() * 0.005, ScrH() * 0.003, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT )
surface.SetDrawColor(Color( 138, 149, 151, 60))
surface.DrawLine(ScrW() * 0.018, ScrH() * 0.0325, ScrW() * 0.29, ScrH() * 0.0325)
surface.SetDrawColor(Color( 0, 33, 55, 210))
surface.DrawRect(ScrW() * 0.017, ScrH() * 0.059, ScrW() * 0.2715, ScrH() * 0.027) --верхняя панель крафта
draw.DrawText("Рюкзак", "Roh20", ScrW() * 0.02, ScrH() * 0.06, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT )
surface.SetDrawColor(Color( 0, 0, 0, 255))
surface.DrawOutlinedRect(ScrW() * 0.0165, ScrH() * 0.059, ScrW() * 0.273, ScrH() * 0.53) --обводка модели игрока
surface.SetDrawColor( Color(125, 105, 0, 40) )
surface.SetMaterial( Material("lgh/circle_gradient.png") )
surface.DrawTexturedRectUV( -ScrW() * 0.01, ScrH() * 0.657, ScrW() * 0.35, ScrH() * 0.032, 1, 0.9, 0, 0.3 )
end
local oldClose = nut.gui.inv1.OnClose
nut.gui.inv1.OnClose = function()
if (IsValid(safebox_menuINV) and !IsValid(nut.gui.menu)) then
safebox_menuINV:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
case_info_kek:Remove()
end
netstream.Start("lootExit", entity)
nut.gui.inv1.OnClose = oldClose
end
nut.gui["inv"..index] = safebox_menuINV
end
end)
netstream.Hook("closeLootMenuSafe", function()
if (IsValid(nut.gui.inv1) and !IsValid(nut.gui.menu)) then
nut.gui.inv1:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
if IsValid(case_info_kek) then
case_info_kek:Remove()
end
end
if (IsValid(safebox_menuINV) and !IsValid(nut.gui.menu)) then
safebox_menuINV:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
case_info_kek:Remove()
end
end)
end
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
local CAMPTASKINFO_PB = require("CampTaskInfo_pb")
module('CampTaskInfo2DB_pb')
CAMPTASKINFO2DB = protobuf.Descriptor();
local CAMPTASKINFO2DB_RESETTIME_FIELD = protobuf.FieldDescriptor();
local CAMPTASKINFO2DB_INFOS_FIELD = protobuf.FieldDescriptor();
local CAMPTASKINFO2DB_REFRESHTIMES_FIELD = protobuf.FieldDescriptor();
local CAMPTASKINFO2DB_REWARDTIMES_FIELD = protobuf.FieldDescriptor();
local CAMPTASKINFO2DB_REWARDTIME_FIELD = protobuf.FieldDescriptor();
CAMPTASKINFO2DB_RESETTIME_FIELD.name = "resetTime"
CAMPTASKINFO2DB_RESETTIME_FIELD.full_name = ".KKSG.CampTaskInfo2DB.resetTime"
CAMPTASKINFO2DB_RESETTIME_FIELD.number = 1
CAMPTASKINFO2DB_RESETTIME_FIELD.index = 0
CAMPTASKINFO2DB_RESETTIME_FIELD.label = 1
CAMPTASKINFO2DB_RESETTIME_FIELD.has_default_value = false
CAMPTASKINFO2DB_RESETTIME_FIELD.default_value = 0
CAMPTASKINFO2DB_RESETTIME_FIELD.type = 5
CAMPTASKINFO2DB_RESETTIME_FIELD.cpp_type = 1
CAMPTASKINFO2DB_INFOS_FIELD.name = "infos"
CAMPTASKINFO2DB_INFOS_FIELD.full_name = ".KKSG.CampTaskInfo2DB.infos"
CAMPTASKINFO2DB_INFOS_FIELD.number = 2
CAMPTASKINFO2DB_INFOS_FIELD.index = 1
CAMPTASKINFO2DB_INFOS_FIELD.label = 3
CAMPTASKINFO2DB_INFOS_FIELD.has_default_value = false
CAMPTASKINFO2DB_INFOS_FIELD.default_value = {}
CAMPTASKINFO2DB_INFOS_FIELD.message_type = CAMPTASKINFO_PB.CAMPTASKINFO
CAMPTASKINFO2DB_INFOS_FIELD.type = 11
CAMPTASKINFO2DB_INFOS_FIELD.cpp_type = 10
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.name = "refreshTimes"
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.full_name = ".KKSG.CampTaskInfo2DB.refreshTimes"
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.number = 3
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.index = 2
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.label = 1
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.has_default_value = false
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.default_value = 0
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.type = 5
CAMPTASKINFO2DB_REFRESHTIMES_FIELD.cpp_type = 1
CAMPTASKINFO2DB_REWARDTIMES_FIELD.name = "rewardTimes"
CAMPTASKINFO2DB_REWARDTIMES_FIELD.full_name = ".KKSG.CampTaskInfo2DB.rewardTimes"
CAMPTASKINFO2DB_REWARDTIMES_FIELD.number = 4
CAMPTASKINFO2DB_REWARDTIMES_FIELD.index = 3
CAMPTASKINFO2DB_REWARDTIMES_FIELD.label = 1
CAMPTASKINFO2DB_REWARDTIMES_FIELD.has_default_value = false
CAMPTASKINFO2DB_REWARDTIMES_FIELD.default_value = 0
CAMPTASKINFO2DB_REWARDTIMES_FIELD.type = 5
CAMPTASKINFO2DB_REWARDTIMES_FIELD.cpp_type = 1
CAMPTASKINFO2DB_REWARDTIME_FIELD.name = "rewardTime"
CAMPTASKINFO2DB_REWARDTIME_FIELD.full_name = ".KKSG.CampTaskInfo2DB.rewardTime"
CAMPTASKINFO2DB_REWARDTIME_FIELD.number = 5
CAMPTASKINFO2DB_REWARDTIME_FIELD.index = 4
CAMPTASKINFO2DB_REWARDTIME_FIELD.label = 1
CAMPTASKINFO2DB_REWARDTIME_FIELD.has_default_value = false
CAMPTASKINFO2DB_REWARDTIME_FIELD.default_value = 0
CAMPTASKINFO2DB_REWARDTIME_FIELD.type = 5
CAMPTASKINFO2DB_REWARDTIME_FIELD.cpp_type = 1
CAMPTASKINFO2DB.name = "CampTaskInfo2DB"
CAMPTASKINFO2DB.full_name = ".KKSG.CampTaskInfo2DB"
CAMPTASKINFO2DB.nested_types = {}
CAMPTASKINFO2DB.enum_types = {}
CAMPTASKINFO2DB.fields = {CAMPTASKINFO2DB_RESETTIME_FIELD, CAMPTASKINFO2DB_INFOS_FIELD, CAMPTASKINFO2DB_REFRESHTIMES_FIELD, CAMPTASKINFO2DB_REWARDTIMES_FIELD, CAMPTASKINFO2DB_REWARDTIME_FIELD}
CAMPTASKINFO2DB.is_extendable = false
CAMPTASKINFO2DB.extensions = {}
CampTaskInfo2DB = protobuf.Message(CAMPTASKINFO2DB)
|
---@class CS.FairyGUI.UIObjectFactory
---@type CS.FairyGUI.UIObjectFactory
CS.FairyGUI.UIObjectFactory = { }
---@return CS.FairyGUI.UIObjectFactory
function CS.FairyGUI.UIObjectFactory.New() end
---@overload fun(url:string, t:string): void
---@param url string
---@param creator (fun():CS.FairyGUI.GComponent)
function CS.FairyGUI.UIObjectFactory.SetPackageItemExtension(url, creator) end
---@overload fun(t:string): void
---@param creator (fun():CS.FairyGUI.GLoader)
function CS.FairyGUI.UIObjectFactory.SetLoaderExtension(creator) end
function CS.FairyGUI.UIObjectFactory.Clear() end
---@overload fun(t:number): CS.FairyGUI.GObject
---@return CS.FairyGUI.GObject
---@param pi CS.FairyGUI.PackageItem
---@param optional userClass string
function CS.FairyGUI.UIObjectFactory.NewObject(pi, userClass) end
return CS.FairyGUI.UIObjectFactory
|
local json = require 'json'
local diagDefault = require 'constant.DiagnosticDefaultSeverity'
local VERSION = "0.14.2"
local package = {
name = "lua",
displayName = "Lua",
description = "Lua Language Server coded by Lua",
author = "sumneko",
icon = "images/logo.png",
license = "MIT",
repository = {
type = "git",
url = "https://github.com/sumneko/lua-language-server"
},
publisher = "sumneko",
categories = {
"Linters",
"Programming Languages",
"Snippets"
},
keywords = {
"Lua",
"LSP",
"GoTo Definition",
"IntelliSense"
},
engines = {
vscode = "^1.23.0"
},
activationEvents = {
"onLanguage:lua"
},
main = "./client/out/extension",
contributes = {
configuration = {
type = "object",
title = "Lua",
properties = {
["Lua.runtime.version"] = {
scope = "resource",
type = "string",
default = "Luau",
enum = {
"Luau",
"Lua 5.1",
"Lua 5.2",
"Lua 5.3",
"Lua 5.4",
"LuaJIT"
},
markdownDescription = "%config.runtime.version%"
},
["Lua.runtime.path"] = {
scope = "resource",
type = "array",
items = {
type = 'string',
},
markdownDescription = "%config.runtime.path%",
default = {
"?.lua",
"?/init.lua",
"?/?.lua"
}
},
["Lua.diagnostics.enable"] = {
scope = 'resource',
type = 'boolean',
default = true,
markdownDescription = "%config.diagnostics.enable%"
},
["Lua.diagnostics.disable"] = {
scope = "resource",
type = "array",
items = {
type = 'string',
},
markdownDescription = "%config.diagnostics.disable%"
},
["Lua.diagnostics.globals"] = {
scope = "resource",
type = "array",
items = {
type = 'string',
},
markdownDescription = "%config.diagnostics.globals%"
},
["Lua.diagnostics.syntax"] = {
scope = 'resource',
type = 'boolean',
default = true,
markdownDescription = "%config.diagnostics.syntax%"
},
["Lua.diagnostics.ignore"] = {
scope = "resource",
type = "array",
items = {
type = 'string',
},
markdownDescription = "%config.diagnostics.ignore%"
},
["Lua.diagnostics.datamodelAsIgnore"] = {
scope = 'resource',
type = 'boolean',
default = true,
markdownDescription = "%config.diagnostics.datamodelAsIgnore%"
},
["Lua.diagnostics.severity"] = {
scope = "resource",
type = 'object',
markdownDescription = "%config.diagnostics.severity%",
title = "severity",
properties = {}
},
["Lua.workspace.ignoreDir"] = {
scope = "resource",
type = "array",
items = {
type = 'string',
},
markdownDescription = "%config.workspace.ignoreDir%",
default = {
".vscode",
},
},
["Lua.workspace.ignoreSubmodules"] = {
scope = "resource",
type = "boolean",
default = true,
markdownDescription = "%config.workspace.ignoreSubmodules%"
},
["Lua.workspace.rojoProjectFile"] = {
scope = "resource",
type = "string",
default = "default",
markdownDescription = "%config.workspace.rojoProjectFile%"
},
["Lua.workspace.loadMode"] = {
scope = "resource",
type = "string",
default = "All Files",
enum = {
"All Files",
"Rojo Project"
},
markdownEnumDescriptions = {
"%config.workspace.loadMode.allFiles%",
"%config.workspace.loadMode.rojoProject%"
},
markdownDescription = "%config.workspace.loadMode%"
},
["Lua.workspace.useGitIgnore"] = {
scope = "resource",
type = "boolean",
default = true,
markdownDescription = "%config.workspace.useGitIgnore%"
},
["Lua.workspace.maxPreload"] = {
scope = "resource",
type = "integer",
default = 300,
markdownDescription = "%config.workspace.maxPreload%"
},
["Lua.workspace.preloadFileSize"] = {
scope = "resource",
type = "integer",
default = 100,
markdownDescription = "%config.workspace.preloadFileSize%"
},
["Lua.workspace.library"] = {
scope = 'resource',
type = 'object',
markdownDescription = "%config.workspace.library%"
},
["Lua.completion.enable"] = {
scope = "resource",
type = "boolean",
default = true,
markdownDescription = "%config.completion.enable%"
},
["Lua.completion.fastAutocompletion"] = {
scope = "resource",
type = "boolean",
default = false,
markdownDescription = "%config.completion.fastAutocompletion%"
},
["Lua.completion.callSnippet"] = {
scope = "resource",
type = "string",
default = "Disable",
enum = {
"Disable",
"Both",
"Replace",
},
markdownEnumDescriptions = {
"%config.completion.callSnippet.Disable%",
"%config.completion.callSnippet.Both%",
"%config.completion.callSnippet.Replace%",
},
markdownDescription = "%config.completion.callSnippet%"
},
["Lua.completion.keywordSnippet"] = {
scope = "resource",
type = "string",
default = "Replace",
enum = {
"Disable",
"Both",
"Replace",
},
markdownEnumDescriptions = {
"%config.completion.keywordSnippet.Disable%",
"%config.completion.keywordSnippet.Both%",
"%config.completion.keywordSnippet.Replace%",
},
markdownDescription = "%config.completion.keywordSnippet%"
},
--["Lua.plugin.enable"] = {
-- scope = "resource",
-- type = "boolean",
-- default = false,
-- markdownDescription = "%config.plugin.enable%"
--},
--["Lua.plugin.path"] = {
-- scope = "resource",
-- type = "string",
-- default = ".vscode/lua-plugin/*.lua",
-- markdownDescription = "%config.plugin.path%"
--},
["Lua.zzzzzz.cat"] = {
scope = "resource",
type = "boolean",
default = false,
markdownDescription = "%config.zzzzzz.cat%"
},
}
},
grammars = {
{
language = "lua",
scopeName = "source.lua",
path = "./syntaxes/lua.tmLanguage.json"
}
}
},
__metadata = {
id = "3a15b5a7-be12-47e3-8445-88ee3eabc8b2",
publisherDisplayName = "sumneko",
publisherId = "fb626675-24cf-4881-8c13-b465f29bec2f",
},
}
local DiagSeverity = package.contributes.configuration.properties["Lua.diagnostics.severity"].properties
for name, level in pairs(diagDefault) do
DiagSeverity[name] = {
scope = 'resource',
type = 'string',
default = level,
enum = {
'Error',
'Warning',
'Information',
'Hint',
}
}
end
package.version = VERSION
io.save(ROOT:parent_path() / 'package.json', json.encode(package))
local example = {
library = [[
```json
"Lua.workspace.library": {
"C:/lua": true,
"../lib": [
"temp/*"
]
}
```
]],
disable = [[
```json
"Lua.diagnostics.disable" : [
"unused-local",
"lowercase-global"
]
```
]],
globals = [[
```json
"Lua.diagnostics.globals" : [
"GLOBAL1",
"GLOBAL2"
]
```
]],
ignore = [[
```json
"Lua.diagnostics.ignore" : [
"NAME1",
"NAME2"
]
```
]],
severity = [[
```json
"Lua.diagnostics.severity" : {
"redefined-local" : "Warning",
"emmy-lua" : "Hint"
}
```
]],
ignoreDir = [[
```json
"Lua.workspace.ignoreDir" : [
"temp/*.*",
"!temp/*.lua"
]
```
]]
}
io.save(ROOT:parent_path() / 'package.nls.json', json.encode {
["config.runtime.version"] = "Lua runtime version.",
["config.runtime.path"] = "`package.path`",
["config.diagnostics.enable"] = "Enable diagnostics.",
["config.diagnostics.syntax"] = "Enable syntax errors.",
["config.diagnostics.datamodelAsIgnore"] = "Use datamodel.json as ignore list.",
["config.diagnostics.disable"] = "Disabled diagnostic (Use code in hover brackets).\n" .. example.disable,
["config.diagnostics.globals"] = "Defined global variables.\n" .. example.globals,
["config.diagnostics.ignore"] = "Ignored instance members.\n" .. example.ignore,
["config.diagnostics.severity"] = "Modified diagnostic severity.\n" .. example.severity,
["config.workspace.ignoreDir"] = "Ignored directories (Use `.gitignore` grammar).\n" .. example.ignoreDir,
["config.workspace.ignoreSubmodules"] = "Ignore submodules.",
["config.workspace.rojoProjectFile"] = "The name of the .project.json file without the extension.",
["config.workspace.loadMode"] = "What files should be preloaded.",
["config.workspace.loadMode.allFiles"] = "Load all files in workspace.",
["config.workspace.loadMode.rojoProject"] = "Load all files found in Rojo Project.",
["config.workspace.useGitIgnore"] = "Ignore files list in `.gitignore` .",
["config.workspace.maxPreload"] = "Max preloaded files.",
["config.workspace.preloadFileSize"] = "Skip files larger than this value (KB) when preloading.",
["config.workspace.library"] = [[
Load external library.
This feature can load external Lua files, which can be used for definition, automatic completion and other functions. Note that the language server does not monitor changes in external files and needs to restart if the external files are modified.
The following example shows loaded files in `C:/lua` and `../lib` ,exclude `../lib/temp`.
]] .. example.library,
['config.completion.enable'] = 'Enable completion.',
['config.completion.fastAutocompletion'] = 'EXPERIMENTAL. Enable it only if Auto-Completion is too slow.',
['config.completion.callSnippet'] = 'Shows function call snippets.',
['config.completion.callSnippet.Disable'] = "Only shows `function name`.",
['config.completion.callSnippet.Both'] = "Shows `function name` and `call snippet`.",
['config.completion.callSnippet.Replace'] = "Only shows `call snippet.`",
['config.completion.keywordSnippet'] = 'Shows keyword syntax snippets.',
['config.completion.keywordSnippet.Disable'] = "Only shows `keyword`.",
['config.completion.keywordSnippet.Both'] = "Shows `keyword` and `syntax snippet`.",
['config.completion.keywordSnippet.Replace'] = "Only shows `syntax snippet`.",
['config.zzzzzz.cat'] = 'DO NOT TOUCH ME, LET ME SLEEP >_<\n\n(This will enable beta version, which are still in the early stages of development, and all features will fail after enabling this setting.)',
})
io.save(ROOT:parent_path() / 'package.nls.zh-cn.json', json.encode {
["config.runtime.version"] = "Lua运行版本。",
["config.runtime.path"] = "`package.path`",
["config.diagnostics.enable"] = "启用诊断。",
["config.diagnostics.syntax"] = "Enable syntax errors.",
["config.diagnostics.datamodelAsIgnore"] = "Use datamodel.json as ignore list.",
["config.diagnostics.disable"] = "禁用的诊断(使用浮框括号内的代码)。\n" .. example.disable,
["config.diagnostics.globals"] = "已定义的全局变量。\n" .. example.globals,
["config.diagnostics.ignore"] = "Ignored instance members.\n" .. example.ignore,
["config.diagnostics.severity"] = "修改诊断等级。\n" .. example.severity,
["config.workspace.ignoreDir"] = "忽略的目录(使用 `.gitignore` 语法)。\n" .. example.ignoreDir,
["config.workspace.ignoreSubmodules"] = "忽略子模块。",
["config.workspace.rojoProjectFile"] = "The name of the .project.json file without the extension.",
["config.workspace.loadMode"] = "What files should be preloaded.",
["config.workspace.loadMode.allFiles"] = "Load all files in workspace.",
["config.workspace.loadMode.rojoProject"] = "Load all files found in Rojo Project.",
["config.workspace.useGitIgnore"] = "忽略 `.gitignore` 中列举的文件。",
["config.workspace.maxPreload"] = "最大预加载文件数。",
["config.workspace.preloadFileSize"] = "预加载时跳过大小大于该值(KB)的文件。",
["config.workspace.library"] = [[
加载外部函数库。
该功能可以加载外部的Lua文件,用于函数定义、自动完成等功能。注意,语言服务不会监视外部文件的变化,如果修改了外部文件需要重启。
下面这个例子表示加载`C:/lua`与`../lib`中的所有文件,但不加载`../lib/temp`中的文件。
]] .. example.library,
['config.completion.enable'] = '启用自动完成。',
['config.completion.fastAutocompletion'] = 'EXPERIMENTAL. Enable it only if Auto-Completion is too slow.',
['config.completion.callSnippet'] = '显示函数调用片段。',
['config.completion.callSnippet.Disable'] = "只显示 `函数名`。",
['config.completion.callSnippet.Both'] = "显示 `函数名` 与 `调用片段`。",
['config.completion.callSnippet.Replace'] = "只显示 `调用片段`。",
['config.completion.keywordSnippet'] = '显示关键字语法片段',
['config.completion.keywordSnippet.Disable'] = "只显示 `关键字`。",
['config.completion.keywordSnippet.Both'] = "显示 `关键字` 与 `语法片段`。",
['config.completion.keywordSnippet.Replace'] = "只显示 `语法片段`。",
['config.zzzzzz.cat'] = 'DO NOT TOUCH ME, LET ME SLEEP >_<\n\n(这会启用还处于早期开发阶段的beta版,开启后所有的功能都会失效)',
})
|
--
-- FUEL
--
crafting.register("fuel", {
input = {
["crystal:red"] = 1,
},
output = {
["crystal:empty"] = 1,
},
burntime = 50.0,
})
crafting.register("fuel", {
input = {
["crystal:blue"] = 1,
},
output = {
["crystal:empty"] = 1,
},
burntime = 35.0,
})
crafting.register("fuel", {
input = {
["crystal:green"] = 1,
},
output = {
["crystal:empty"] = 1,
},
burntime = 20.0,
})
|
local M = {}
local function hex (hex)
local redColor,greenColor,blueColor=hex:match('(..)(..)(..)')
redColor, greenColor, blueColor = tonumber(redColor, 16)/255, tonumber(greenColor, 16)/255, tonumber(blueColor, 16)/255
redColor, greenColor, blueColor = math.floor(redColor*100)/100, math.floor(greenColor*100)/100, math.floor(blueColor*100)/100
return redColor, greenColor, blueColor
end
local function rgb (r, g, b)
local redColor,greenColor,blueColor=r/255, g/255, b/255
redColor, greenColor, blueColor = math.floor(redColor*100)/100, math.floor(greenColor*100)/100, math.floor(blueColor*100)/100
return redColor, greenColor, blueColor
end
M.hex = hex
M.rgb = rgb
return M
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.