content
stringlengths 5
1.05M
|
---|
require("hall/password/type/passwordTypeObject");
require("hall/gameData/txtMgr");
require("hall/userInfo/data/userInfoData");
require("hall/community/data/communityDataInterface");
require("hall/password/jump/jumpInterfaceMatchHall");
local PasswordTypeObjectAddFriends = class(PasswordTypeObject);
------------------------口令数据------------------------------
-- virtual
PasswordTypeObjectAddFriends.generateData = function(self)
local data = {
nick = kUserInfoData:getNickname(),
mid = kUserInfoData:getUserId(),
cid = kUserInfoData:getUserCid(),
};
return data;
end
-- virtual
PasswordTypeObjectAddFriends.analyseData = function(self, data)
data.mid = tonumber(data.mid) or 0;
data.nick = tostring(data.nick or "") or "";
data.cid = tonumber(data.cid) or 0;
return data;
end
------------------------口令弹框------------------------------
-- virtual
PasswordTypeObject.getTitle = function(self)
return "好友口令";
end
-- virtual
PasswordTypeObjectAddFriends.getBtnText = function(self)
return "立即参加比赛";
end
-- virtual
PasswordTypeObjectAddFriends.getMessage = function(self)
local str = string.format("你接受了玩家%s(id:%s)的邀请加入游戏。玩牌也能赢大奖,快去看看吧~", self.m_data.nick, self.m_data.cid);
return str;
end
-- virtual
PasswordTypeObjectAddFriends.getTips = function(self)
return "TA已经在你的好友列表中,常联系啊~";
end
-- virtual
PasswordTypeObjectAddFriends.executeOnShow = function(self, obj, func, sourceType)
JumpInterfaceMatchHall.getInstance();
-- 自动加好友
local msg = json.encode({add_friend_type = ImSdkConstants.eAddFriendType.AUTO});
CommunityDataInterface.getInstance():requestAddFriend(self.m_data.cid, msg);
end
-- virtual
PasswordTypeObjectAddFriends.executeOnConfirm = function(self, obj, func, sourceType)
-- enter match hall
JumpInterfaceMatchHall.getInstance():enterMacthHallScene();
-- callback
if obj and func then
func(obj);
end
end
-- virtual
PasswordTypeObjectAddFriends.executeOnClose = function(self)
JumpInterfaceMatchHall.releaseInstance();
end
------------------------邀请弹框------------------------------
-- virtual
PasswordTypeObjectAddFriends.shareByWechat = function(self, password, isShareSwitchOpen)
local text = self:_getShareContent(password);
if not string.isEmpty(text) then
PasswordDataInterface.getInstance():setTextToClipboard(text);
WeixinShareUtil.getInstance():openWeiXin();
end
end
-- virtual
PasswordTypeObjectAddFriends.shareByMessage = function(self, password, hasContact)
local text = self:_getShareContent(password);
return text;
end
------------------------------------private-----------------------------------------
PasswordTypeObjectAddFriends._getShareContent = function(self, password)
local content = table.verify(TxtMgr.getInstance():getDescByKey("token_content_format"));
local urlMap = table.verify(content.url);
local region = kClientInfo:getRegionId();
local url = urlMap[tostring(region) or ""] or "";
local appName = RegionConfigDataInterface.getInstance():getRegionProductName();
local addFriend = content.add_friends or "";
local addFriendStr = string.gsub(addFriend, "{app}", appName);
addFriendStr = string.gsub(addFriendStr, "{token}", string.format("约会口令%s", password or ""));
addFriendStr = string.gsub(addFriendStr, "{url}", url);
return addFriendStr;
end
PasswordTypeObjectAddFriends._getShowContent = function(self, password)
local content = table.verify(TxtMgr.getInstance():getDescByKey("token_content_format"));
local appName = RegionConfigDataInterface.getInstance():getRegionProductName();
local gamePrefix = content.game_prefix or "";
local gameSuffix = content.game_suffix or "";
local gamePrefixStr = string.gsub(gamePrefix, "{app}", appName);
local gameSuffixStr = string.gsub(gameSuffix, "{token}", password or "");
return gamePrefixStr, gameSuffixStr;
end
return PasswordTypeObjectAddFriends;
|
--
-- network.lua
-- network status notification
--
local naughty = require("naughty")
local beautiful = require("beautiful")
-- ========================================
-- Config
-- ========================================
local icons_path = beautiful.icons_path .. "network/"
-- ========================================
-- Logic
-- ========================================
-- Notify wireless connected notification
local notify_connected_wireless = function(essid)
naughty.notify {
icon = icons_path .. "connected_notification.svg",
title = "Connection Established",
text = string.format("You are now connected to <b>%s</b>", essid),
}
end
-- Notify wired connected notification
local notify_connected_wired = function(interface)
naughty.notify {
icon = icons_path .. "wired.svg",
title = "Connection Established",
text = string.format("Connected to internet with <b>%s</b>", interface),
}
end
-- Notify wireless disconnected notification
local notify_disconnected_wireless = function()
naughty.notify {
icon = icons_path .. "wifi-strength-off.svg",
title = "Disconnected",
text = "Wi-Fi network has been disconnected",
}
end
-- Notify wired disconnected notification
local notify_disconnected_wired = function()
naughty.notify {
icon = icons_path .. "wired-off.svg",
title = "Disconnected",
text = "Ethernet network has been disconnected",
}
end
-- ========================================
-- Initialization
-- ========================================
awesome.connect_signal("daemon::network::connected::wireless", function (_, essid)
notify_connected_wireless(essid)
end)
awesome.connect_signal("daemon::network::connected::wired", function (interface)
notify_connected_wired(interface)
end)
awesome.connect_signal("daemon::network::disconnected::wireless", function ()
notify_disconnected_wireless()
end)
awesome.connect_signal("daemon::network::disconnected::wired", function ()
notify_disconnected_wired()
end)
|
-----------------------------------------------------------------------------------------------------------------------------------------
-- INICIAR TREM
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
SwitchTrainTrack(0,true)
SwitchTrainTrack(3,true)
N_0x21973bbf8d17edfa(0,120000)
SetRandomTrains(true)
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DENSITY NPCS 2
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
SetPedDensityMultiplierThisFrame(1.0)
SetVehicleDensityMultiplierThisFrame(0.05)
SetSomeVehicleDensityMultiplierThisFrame(1.0)
SetRandomVehicleDensityMultiplierThisFrame(1.0)
SetParkedVehicleDensityMultiplierThisFrame(0.35)
SetScenarioPedDensityMultiplierThisFrame(1.0,1.0)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- LIGHTS
-----------------------------------------------------------------------------------------------------------------------------------------
local lights = {
--ROXOS
{ 103.01,-1938.72,30.80,76,6,79,50.0,1.0 },
--AMARELOS
{ 336.98,-2042.08,31.30,245,242,5,50.0,1.0 },
--VERMELHOS
{ -183.46,-1615.13,33.76,155,0,0,100.0,1.0 },
--MARABUNTAS
--{ 1226.33,-1626.2,49.81,0,0,255,100.0,1.0 },
--CAMPINHO
{ 771.18,-233.62,66.12,255,255,255,50.0,1.0 },
}
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
for k,v in ipairs(lights) do
local x,y,z,r,g,b,range,intensity = table.unpack(v)
if GetClockHours() > 20 or GetClockHours() < 6 then
DrawLightWithRangeAndShadow(x,y,z,r,g,b,range,intensity,0.1)
end
end
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DISPATCH
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
for i = 1,120 do
EnableDispatchService(i,false)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DIMINUIR DANO X NA MOTO
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
local idle = 500
local ped = PlayerPedId()
if IsPedInAnyVehicle(ped) then
SetPedConfigFlag(PlayerPedId(),35,false)
idle = 1
local vehicle = GetVehiclePedIsIn(ped)
if (GetPedInVehicleSeat(vehicle,-1) == ped or GetPedInVehicleSeat(vehicle,0) == ped) and GetVehicleClass(vehicle) == 8 then
N_0x4757f00bc6323cfe(GetHashKey("WEAPON_UNARMED"),0.02)
end
else
N_0x4757f00bc6323cfe(GetHashKey("WEAPON_UNARMED"),0.8)
end
Citizen.Wait(idle)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DESABILITAR A CORONHADA
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
local idle = 500
local ped = PlayerPedId()
if IsPedArmed(ped,6) then
idle = 1
DisableControlAction(0,140,true)
DisableControlAction(0,141,true)
DisableControlAction(0,142,true)
else
DisableControlAction(0,140,true)
end
Citizen.Wait(idle)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- REMOVER ARMA ABAIXO DE 40MPH DENTRO DO CARRO
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
local ped = PlayerPedId()
if IsPedInAnyVehicle(ped) then
local vehicle = GetVehiclePedIsIn(PlayerPedId())
if GetPedInVehicleSeat(vehicle,-1) == ped then
local speed = GetEntitySpeed(vehicle)*2.236936
if speed >= 40 then
SetPlayerCanDoDriveBy(PlayerId(),false)
else
SetPlayerCanDoDriveBy(PlayerId(),true)
end
end
end
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- ESTOURAR OS PNEUS SE O CARRO CAPOTAR
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
local veh = GetVehiclePedIsUsing(PlayerPedId())
local roll = GetEntityRoll(veh)
if roll > 75.0 or roll < -75.0 then
if GetVehicleClass(veh) ~= 8 and GetVehicleClass(veh) ~= 13 then
local tyre = math.random(4)
if math.random(100) <= 90 then
if tyre == 1 then
if not IsVehicleTyreBurst(veh,0,false) then
SetVehicleTyreBurst(veh,0,true,1000.0)
end
elseif tyre == 2 then
if not IsVehicleTyreBurst(veh,1,false) then
SetVehicleTyreBurst(veh,1,true,1000.0)
end
elseif tyre == 3 then
if not IsVehicleTyreBurst(veh,4,false) then
SetVehicleTyreBurst(veh,4,true,1000.0)
end
elseif tyre == 4 then
if not IsVehicleTyreBurst(veh,5,false) then
SetVehicleTyreBurst(veh,5,true,1000.0)
end
end
end
end
end
Citizen.Wait(1000)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DRIFT
-----------------------------------------------------------------------------------------------------------------------------------------
local activated = false
Citizen.CreateThread( function()
while true do
Citizen.Wait(1)
local ped = PlayerPedId()
veh = GetVehiclePedIsIn(ped,false)
if IsControlJustPressed(0,21) and IsPedInAnyVehicle(ped,false) and not activated and IsInputDisabled(0) then
if GetPedInVehicleSeat(veh,-1) == ped and IsVehicleOnAllWheels(veh) then
if (GetVehicleClass(veh) >= 0 and GetVehicleClass(veh) <= 7) or GetVehicleClass(veh) == 9 then
if GetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff") < 50.0 then
activated = true
DriftEnable()
end
end
end
end
if IsControlJustReleased(0,21) and IsPedInAnyVehicle(ped,false) and activated and IsInputDisabled(0) then
if GetPedInVehicleSeat(veh,-1) == ped and IsVehicleOnAllWheels(veh) then
if (GetVehicleClass(veh) >= 0 and GetVehicleClass(veh) <= 7) or GetVehicleClass(veh) == 9 then
if GetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff") >= 50.0 then
activated = false
DriftDisable()
end
end
end
end
if veh ~= GetVehiclePedIsIn(ped,true) and activated then
activated = false
veh = GetVehiclePedIsIn(ped,true)
DriftDisable()
end
end
end)
function DriftEnable()
SetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff",GetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff")+90.22)
if GetVehicleHandlingFloat(veh,"CHandlingData","fDriveBiasFront") == 0.0 then
SetVehicleEnginePowerMultiplier(veh,190.0)
else
SetVehicleEnginePowerMultiplier(veh,100.0)
end
SetVehicleHandlingFloat(veh,"CHandlingData","fDriveInertia",GetVehicleHandlingFloat(veh,"CHandlingData","fDriveInertia")+0.31)
SetVehicleHandlingFloat(veh,"CHandlingData","fSteeringLock",GetVehicleHandlingFloat(veh,"CHandlingData","fSteeringLock")+25.0)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMax",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMax")-1.1)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMin",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMin")-0.4)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveLateral",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveLateral")+2.5)
SetVehicleHandlingFloat(veh,"CHandlingData","fLowSpeedTractionLossMult",GetVehicleHandlingFloat(veh,"CHandlingData","fLowSpeedTractionLossMult")-0.57)
end
function DriftDisable()
SetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff",GetVehicleHandlingFloat(veh,"CHandlingData","fInitialDragCoeff")-90.22)
SetVehicleHandlingFloat(veh,"CHandlingData","fDriveInertia",GetVehicleHandlingFloat(veh,"CHandlingData","fDriveInertia")-0.31)
SetVehicleHandlingFloat(veh,"CHandlingData","fSteeringLock",GetVehicleHandlingFloat(veh,"CHandlingData","fSteeringLock")-25.0)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMax",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMax")+1.1)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMin",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveMin")+0.4)
SetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveLateral",GetVehicleHandlingFloat(veh,"CHandlingData","fTractionCurveLateral")-2.5)
SetVehicleHandlingFloat(veh,"CHandlingData","fLowSpeedTractionLossMult",GetVehicleHandlingFloat(veh,"CHandlingData","fLowSpeedTractionLossMult")+0.57)
SetVehicleEnginePowerMultiplier(veh,0.0)
SetVehicleModKit(veh,0)
SetVehicleMod(veh,11,GetVehicleMod(veh,11),true)
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- BLIPS
-----------------------------------------------------------------------------------------------------------------------------------------
local blips = {
{ 265.64,-1261.30,29.29,361,41,"Posto de Gasolina",0.4 },
{ 819.65,-1028.84,26.40,361,41,"Posto de Gasolina",0.4 },
{ 1208.95,-1402.56,35.22,361,41,"Posto de Gasolina",0.4 },
{ 1181.38,-330.84,69.31,361,41,"Posto de Gasolina",0.4 },
{ 620.84,269.10,103.08,361,41,"Posto de Gasolina",0.4 },
{ 2581.32,362.03,108.46,361,41,"Posto de Gasolina",0.4 },
{ 176.63,-1562.02,29.26,361,41,"Posto de Gasolina",0.4 },
{ 176.63,-1562.02,29.26,361,41,"Posto de Gasolina",0.4 },
{ -319.29,-1471.71,30.54,361,41,"Posto de Gasolina",0.4 },
{ 1784.32,3330.55,41.25,361,41,"Posto de Gasolina",0.4 },
{ 49.418,2778.79,58.04,361,41,"Posto de Gasolina",0.4 },
{ 263.89,2606.46,44.98,361,41,"Posto de Gasolina",0.4 },
{ 1039.95,2671.13,39.55,361,41,"Posto de Gasolina",0.4 },
{ 1207.26,2660.17,37.89,361,41,"Posto de Gasolina",0.4 },
{ 2539.68,2594.19,37.94,361,41,"Posto de Gasolina",0.4 },
{ 2679.85,3263.94,55.24,361,41,"Posto de Gasolina",0.4 },
{ 2005.05,3773.88,32.40,361,41,"Posto de Gasolina",0.4 },
{ 1687.15,4929.39,42.07,361,41,"Posto de Gasolina",0.4 },
{ 1701.31,6416.02,32.76,361,41,"Posto de Gasolina",0.4 },
{ 179.85,6602.83,31.86,361,41,"Posto de Gasolina",0.4 },
{ -94.46,6419.59,31.48,361,41,"Posto de Gasolina",0.4 },
{ -2554.99,2334.40,33.07,361,41,"Posto de Gasolina",0.4 },
{ -1800.37,803.66,138.65,361,41,"Posto de Gasolina",0.4 },
{ -1437.62,-276.74,46.20,361,41,"Posto de Gasolina",0.4 },
{ -2096.24,-320.28,13.16,361,41,"Posto de Gasolina",0.4 },
{ -724.61,-935.16,19.21,361,41,"Posto de Gasolina",0.4 },
{ -526.01,-1211.00,18.18,361,41,"Posto de Gasolina",0.4 },
{ -70.21,-1761.79,29.53,361,41,"Posto de Gasolina",0.4 },
{ 55.43,-876.19,30.66,357,0,"Garagem",0.4 },
{ 317.25,2623.14,44.46,357,0,"Garagem",0.4 },
{ -773.34,5598.15,33.60,357,0,"Garagem",0.4 },
{ 596.40,90.65,93.12,357,0,"Garagem",0.4 },
{ -340.76,265.97,85.67,357,0,"Garagem",0.4 },
{ -2030.01,-465.97,11.60,357,0,"Garagem",0.4 },
{ -1184.92,-1510.00,4.64,357,0,"Garagem",0.4 },
{ -73.44,-2004.99,18.27,357,0,"Garagem",0.4 },
{ 214.02,-808.44,31.01,357,0,"Garagem",0.4 },
{ -348.88,-874.02,31.31,357,0,"Garagem",0.4 },
{ 67.74,12.27,69.21,357,0,"Garagem",0.4 },
{ 361.90,297.81,103.88,357,0,"Garagem",0.4 },
{ 1156.90,-453.73,66.98,357,0,"Garagem",0.4 },
{ 275.17,-345.5,45.18,357,0,"Garagem",0.4 },
{ -102.21,6345.18,31.57,357,0,"Garagem",0.4 },
{ -1065.23,-850.06,5.05,60,0,"Departamento Policial",0.5 },
{ 1851.45,3686.71,34.26,60,0,"Departamento Policial",0.5 },
{ -448.18,6011.68,31.71,60,0,"Departamento Policial",0.5 },
{ -1034.68,-855.1,5.06,60,29,"Pátio da Policia",0.5 },
{ 25.65,-1346.58,29.49,52,4,"Loja de Departamentos",0.5 },
{ 2556.75,382.01,108.62,52,4,"Loja de Departamentos",0.5 },
{ 1163.54,-323.04,69.20,52,4,"Loja de Departamentos",0.5 },
{ -707.37,-913.68,19.21,52,4,"Loja de Departamentos",0.5 },
{ -47.73,-1757.25,29.42,52,4,"Loja de Departamentos",0.5 },
{ 373.90,326.91,103.56,52,4,"Loja de Departamentos",0.5 },
{ -3243.10,1001.23,12.83,52,4,"Loja de Departamentos",0.5 },
{ 1729.38,6415.54,35.03,52,4,"Loja de Departamentos",0.5 },
{ 547.90,2670.36,42.15,52,4,"Loja de Departamentos",0.5 },
{ 1960.75,3741.33,32.34,52,4,"Loja de Departamentos",0.5 },
{ 2677.90,3280.88,55.24,52,4,"Loja de Departamentos",0.5 },
{ 1698.45,4924.15,42.06,52,4,"Loja de Departamentos",0.5 },
{ -1820.93,793.18,138.11,52,4,"Loja de Departamentos",0.5 },
{ 1392.46,3604.95,34.98,52,4,"Loja de Departamentos",0.5 },
{ -2967.82,390.93,15.04,52,4,"Loja de Departamentos",0.5 },
{ -3040.10,585.44,7.90,52,4,"Loja de Departamentos",0.5 },
{ 1135.56,-982.20,46.41,52,4,"Loja de Departamentos",0.5 },
{ 1165.91,2709.41,38.15,52,4,"Loja de Departamentos",0.5 },
{ -1487.18,-379.02,40.16,52,4,"Loja de Departamentos",0.5 },
{ -1222.78,-907.22,12.32,52,4,"Loja de Departamentos",0.5 },
{ -560.17,286.79,82.17,93,4,"Bar",0.5 },
{ 128.11,-1284.99,29.27,93,4,"Bar",0.5 },
{ 1985.80,3053.68,47.21,93,4,"Bar",0.5 },
{ -430.04,261.80,83.00,93,4,"Bar",0.5 },
{ -80.89,214.78,96.55,93,4,"Bar",0.5 },
{ 224.60,-1511.02,29.29,93,4,"Bar",0.5 },
{ -1387.82,-587.80,30.31,93,4,"Bar",0.5 },
{ 285.37,-587.86,43.37,80,49,"Hospital",0.5 },
{ -248.14,6332.97,32.42,80,49,"Hospital",0.5 },
{ 75.40,-1392.92,29.37,73,4,"Loja de Roupas",0.5 },
{ -709.40,-153.66,37.41,73,4,"Loja de Roupas",0.5 },
{ -163.20,-302.03,39.73,73,4,"Loja de Roupas",0.5 },
{ 425.58,-806.23,29.49,73,4,"Loja de Roupas",0.5 },
{ -822.34,-1073.49,11.32,73,4,"Loja de Roupas",0.5 },
{ -1193.81,-768.49,17.31,73,4,"Loja de Roupas",0.5 },
{ -1450.85,-238.15,49.81,73,4,"Loja de Roupas",0.5 },
{ 4.90,6512.47,31.87,73,4,"Loja de Roupas",0.5 },
{ 1693.95,4822.67,42.06,73,4,"Loja de Roupas",0.5 },
{ 126.05,-223.10,54.55,73,4,"Loja de Roupas",0.5 },
{ 614.26,2761.91,42.08,73,4,"Loja de Roupas",0.5 },
{ 1196.74,2710.21,38.22,73,4,"Loja de Roupas",0.5 },
{ -3170.18,1044.54,20.86,73,4,"Loja de Roupas",0.5 },
{ -1101.46,2710.57,19.10,73,4,"Loja de Roupas",0.5 },
{ 1692.62,3759.50,34.70,76,4,"Loja de Armamentos",0.4 },
{ 252.89,-49.25,69.94,76,4,"Loja de Armamentos",0.4 },
{ 843.28,-1034.02,28.19,76,4,"Loja de Armamentos",0.4 },
{ -331.35,6083.45,31.45,76,4,"Loja de Armamentos",0.4 },
{ -663.15,-934.92,21.82,76,4,"Loja de Armamentos",0.4 },
{ -1305.18,-393.48,36.69,76,4,"Loja de Armamentos",0.4 },
{ -1118.80,2698.22,18.55,76,4,"Loja de Armamentos",0.4 },
{ 2568.83,293.89,108.73,76,4,"Loja de Armamentos",0.4 },
{ -3172.68,1087.10,20.83,76,4,"Loja de Armamentos",0.4 },
{ 21.32,-1106.44,29.79,76,4,"Loja de Armamentos",0.4 },
{ 811.19,-2157.67,29.61,76,4,"Loja de Armamentos",0.4 },
{ -815.59,-182.16,37.56,71,4,"Salão de Beleza",0.5 },
{ 139.21,-1708.96,29.30,71,4,"Salão de Beleza",0.5 },
{ -1282.00,-1118.86,7.00,71,4,"Salão de Beleza",0.5 },
{ 1934.11,3730.73,32.85,71,4,"Salão de Beleza",0.5 },
{ 1211.07,-475.00,66.21,71,4,"Salão de Beleza",0.5 },
{ -34.97,-150.90,57.08,71,4,"Salão de Beleza",0.5 },
{ -280.37,6227.01,31.70,71,4,"Salão de Beleza",0.5 },
{ -1213.44,-331.02,37.78,207,0,"Banco",0.5 },
{ -351.59,-49.68,49.04,207,0,"Banco",0.5 },
{ 235.12,216.84,106.28,207,0,"Banco",0.5 },
{ 313.47,-278.81,54.17,207,0,"Banco",0.5 },
{ 149.35,-1040.53,29.37,207,0,"Banco",0.5 },
{ -2962.60,482.17,15.70,207,0,"Banco",0.5 },
{ -112.81,6469.91,31.62,207,0,"Banco",0.5 },
{ 1175.74,2706.80,38.09,207,0,"Banco",0.5 },
{ 1322.64,-1651.97,52.27,75,4,"Tatuagens",0.4 },
{ -1153.67,-1425.68,4.95,75,4,"Tatuagens",0.4 },
{ 322.13,180.46,103.58,75,4,"Tatuagens",0.4 },
{ -3170.07,1075.05,20.82,75,4,"Tatuagens",0.4 },
{ 1864.63,3747.73,33.03,75,4,"Tatuagens",0.4 },
{ -293.71,6200.04,31.48,75,4,"Tatuagens",0.4 },
{ 336.96,176.14,103.16,135,4,"Cinema",0.4 },
{ -1612.35,-1180.02,0.31,266,4,"Embarcações",0.5 },
{ -1522.91,1501.84,110.65,266,4,"Embarcações",0.5 },
{ 1336.21,4278.94,31.05,266,4,"Embarcações",0.5 },
{ -183.69,795.89,197.35,266,4,"Embarcações",0.5 },
{ -803.62,-224.19,37.23,225,4,"Concessionária",0.4 },
{ -305.31,6118.07,31.5,225,4,"Concessionária",0.4 },
{ -69.41,62.85,71.9,225,3,"Concessionária VIP",0.4 },
{ 938.35,-969.75,39.8,402,17,"Mecânica",0.7 },
{ 110.6,6625.94,31.79,402,17,"Mecânica",0.7 },
{ 1769.07,3330.31,41.44,402,17,"Mecânica",0.7 },
{ -70.93,-801.04,44.22,408,4,"Imobiliária",0.5 },
{ -1194.45,-1189.33,7.69,408,4,"Escritório",0.5 },
{ -1007.12,-486.67,39.97,408,4,"Escritório",0.5 },
{ -1913.48,-574.11,11.43,408,4,"Escritório",0.5 },
{ 242.99,-392.82,46.31,79,0,"Tribunal",0.4 },
{ 1054.88,-501.88,62.96,120,0,"Bairro Lucas Samir",0.5 },
-- { 1874.57,276.49,165.53,84,59,"Vermelhos",0.5 },
-- { 1475.85,-112.63,142.86,84,46,"Amarelos",0.5 },
-- { 2070.16,-4.74,213.07,84,27,"Roxos",0.5 },
{ -1816.72,-1193.83,14.30,68,13,"Central | Pescadores",0.5 },
{ -1097.51,-2506.22,15.46,67,13,"Central | Carteiros",0.5 },
{ -421.66,6137.39,31.88,67,13,"Central | Carteiros",0.5 },
{ -349.84,-1569.79,25.22,318,13,"Central | Lixeiros",0.5 },
{ 909.34,-177.30,74.21,198,13,"Central | Taxistas",0.5 },
{ -33.23,6455.41,31.48,198,13,"Central | Taxistas",0.5 },
{ 455.15,-601.45,28.53,513,13,"Central | Motoristas",0.5 },
{ -199.97,6234.33,31.51,513,13,"Central | Motoristas",0.5 },
{ 1218.74,-1266.87,36.42,285,13,"Central | Lenhadores",0.5 },
{ 173.10,-26.04,68.34,499,13,"Central | Leiteiros",0.5 },
{ -421.75,-2171.22,11.33,310,13,"Central | Contrabandistas",0.5 },
-- { -287.81,-1062.71,27.20,458,13,"Central | Assassinos",0.5 },
{ -399.25,4711.35,264.88,442,13,"Central | Caçadores",0.5 },
{ 1054.13,-1952.76,32.09,477,13,"Central | Mineradores",0.5 },
{ 1240.15,-3173.54,7.10,477,13,"Central | Caminhoneiro",0.5 },
{ 751.89,6458.85,31.53,479,13,"Central | Fazendeiros",0.5 },
{ -741.05,5593.12,41.65,36,4,"Teleférico",0.5 },
{ 562.38,2741.57,42.87,273,4,"PetShop",0.4 },
{ -5853.25,1151.59,7.61,197,48,"Ilha dos Solteiros",0.5 },
{ -658.1,-857.51,24.5,459,4,"Eletrônicos",0.6 },
{ 93.28,-230.01,54.67,403,4,"Farmácia",0.6 },
}
Citizen.CreateThread(function()
for _,v in pairs(blips) do
local blip = AddBlipForCoord(v[1],v[2],v[3])
SetBlipSprite(blip,v[4])
SetBlipAsShortRange(blip,true)
SetBlipColour(blip,v[5])
SetBlipScale(blip,v[7])
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(v[6])
EndTextCommandSetBlipName(blip)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- TASERTIME
-----------------------------------------------------------------------------------------------------------------------------------------
local tasertime = false
Citizen.CreateThread(function()
while true do
Citizen.Wait(100)
local ped = PlayerPedId()
if IsPedBeingStunned(ped) then
SetPedToRagdoll(ped,10000,10000,0,0,0,0)
end
if IsPedBeingStunned(ped) and not tasertime then
tasertime = true
SetTimecycleModifier("REDMIST_blend")
ShakeGameplayCam("FAMILY5_DRUG_TRIP_SHAKE",1.0)
elseif not IsPedBeingStunned(ped) and tasertime then
tasertime = false
SetTimeout(5000,function()
SetTimecycleModifier("hud_def_desat_Trevor")
SetTimeout(10000,function()
SetTimecycleModifier("")
SetTransitionTimecycleModifier("")
StopGameplayCamShaking()
end)
end)
end
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- BLACKLIST WEAPONS
-----------------------------------------------------------------------------------------------------------------------------------------
blackWeapons = {
"WEAPON_PISTOL50",
"WEAPON_SNSPISTOL_MK2",
"WEAPON_HEAVYPISTOL",
"WEAPON_FLAREGUN",
"WEAPON_MARKSMANPISTOL",
--"WEAPON_REVOLVER_MK2",
"WEAPON_DOUBLEACTION",
--"WEAPON_RAYPISTOL",
"WEAPON_SMG_MK2",
--"WEAPON_MACHINEPISTOL",
"WEAPON_MINISMG",
"WEAPON_RAYCARBINE",
"WEAPON_PUMPSHOTGUN",
"WEAPON_SAWNOFFSHOTGUN",
"WEAPON_ASSAULTSHOTGUN",
"WEAPON_BULLPUPSHOTGUN",
"WEAPON_HEAVYSHOTGUN",
"WEAPON_DBSHOTGUN",
"WEAPON_AUTOSHOTGUN",
"WEAPON_ASSAULTRIFLE_MK2",
--"WEAPON_CARBINERIFLE_MK2",
"WEAPON_ADVANCEDRIFLE",
"WEAPON_SPECIALCARBINE",
"WEAPON_SPECIALCARBINE_MK2",
"WEAPON_BULLPUPRIFLE",
"WEAPON_BULLPUPRIFLE_MK2",
--"WEAPON_COMPACTRIFLE",
"WEAPON_MG",
"WEAPON_COMBATMG",
"WEAPON_COMBATMG_MK2",
"WEAPON_SNIPERRIFLE",
"WEAPON_HEAVYSNIPER",
--"WEAPON_HEAVYSNIPER_MK2",
"WEAPON_MARKSMANRIFLE",
"WEAPON_MARKSMANRIFLE_MK2",
--"WEAPON_RPG",
"WEAPON_GRENADELAUNCHER",
"WEAPON_GRENADELAUNCHER_SMOKE",
"WEAPON_MINIGUN",
--"WEAPON_FIREWORK",
"WEAPON_RAILGUN",
"WEAPON_HOMINGLAUNCHER",
"WEAPON_COMPACTLAUNCHER",
"WEAPON_RAYMINIGUN",
"WEAPON_GRENADE",
--"WEAPON_BZGAS",
"WEAPON_MOLOTOV",
--"WEAPON_STICKYBOMB",
"WEAPON_PROXMINE",
"WEAPON_PIPEBOMB",
--"WEAPON_BALL",
--"WEAPON_SNOWBALL",
"WEAPON_SMOKEGRENADE"
}
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
for k,v in ipairs(blackWeapons) do
if GetSelectedPedWeapon(PlayerPedId()) == GetHashKey(v) then
RemoveWeaponFromPed(PlayerPedId(),GetHashKey(v))
end
end
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- DAMAGE WALK MODE
-----------------------------------------------------------------------------------------------------------------------------------------
local hurt = false
Citizen.CreateThread(function()
while true do
Citizen.Wait(500)
local ped = PlayerPedId()
if not IsEntityInWater(ped) then
if GetEntityHealth(ped) <= 149 then
setHurt()
elseif hurt and GetEntityHealth(ped) >= 150 then
setNotHurt()
end
end
end
end)
function setHurt()
hurt = true
RequestAnimSet("move_m@injured")
SetPedMovementClipset(PlayerPedId(),"move_m@injured",true)
SetTimecycleModifier("damage")
SetPlayerHealthRechargeMultiplier(PlayerId(),0.0)
DisableControlAction(0,21)
DisableControlAction(0,22)
end
function setNotHurt()
hurt = false
SetTimecycleModifier("")
SetPlayerHealthRechargeMultiplier(PlayerId(),0.0)
ResetPedMovementClipset(PlayerPedId(),0.0)
ResetPedWeaponMovementClipset(PlayerPedId())
ResetPedStrafeClipset(PlayerPedId())
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- COOLDOWN BUNNYHOP
-----------------------------------------------------------------------------------------------------------------------------------------
local bunnyhop = 0
Citizen.CreateThread(function()
while true do
Citizen.Wait(5000)
if bunnyhop > 0 then
bunnyhop = bunnyhop - 5
end
end
end)
Citizen.CreateThread(function()
while true do
local ped = PlayerPedId()
if IsPedJumping(ped) and bunnyhop <= 0 then
bunnyhop = 5
end
if bunnyhop > 0 then
DisableControlAction(0,22,true)
end
Citizen.Wait(5)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- COOLDOWN MELEE COMBAT
-----------------------------------------------------------------------------------------------------------------------------------------
local melee = 0
Citizen.CreateThread(function()
while true do
Citizen.Wait(3000)
if melee > 0 then
melee = melee - 3
end
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
local ped = PlayerPedId()
local x,y,z = table.unpack(GetEntityCoords(ped))
if GetSelectedPedWeapon(ped) == GetHashKey("WEAPON_UNARMED") then
if IsShockingEventInSphere(112,x,y,z,1.0) then
melee = 3
if melee > 0 then
DisableControlAction(0,24,true)
end
end
end
end
end) |
object_tangible_item_beast_converted_gubbur_decoration = object_tangible_item_beast_shared_converted_gubbur_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_gubbur_decoration, "object/tangible/item/beast/converted_gubbur_decoration.iff")
|
local knife = game.Players:GetChildren()
local people = game.Players:GetChildren()
for i,v in pairs(knife) do
if v.Backpack:FindFirstChild("Knife") then
v.Backpack.Knife:Clone().Parent = game.Players.LocalPlayer.Backpack
v.Backpack.Knife:Clone().Parent = game.Players.LocalPlayer.StarterGear
end
end
local gun = game.Players:GetChildren()
for i,v in pairs(gun) do
if v.Backpack:FindFirstChild("Gun") then
v.Backpack.Gun:Clone().Parent = game.Players.LocalPlayer.Backpack
v.Backpack.Gun:Clone().Parent = game.Players.LocalPlayer.StarterGear
end
end
for i,v in pairs(people) do
if game.Players.LocalPlayer.StarterGear:FindFirstChild("Knife") then
game.Players.LocalPlayer.StarterGear.Knife:Clone().Parent = v.Backpack
end
end |
--[[CRQ: APPLINK-28163: [GENIVI] SDL must retrieve the value of 'menuIcon' and 'menuTitle' parameters from .ini file]]
--[[Clarifications
-- APPLINK-29383: Should SDL consider parameters menuIcon/MenuTitle as empty if they are missing in INI file
-- APPLINK-29383 => APPLINK-13145
]]
--[[General Precondition: Update sdl_preloaded_pt.json to allow: SetGlobalProperties and ResetGlobalProperties]]
--[[Testing coverage]]
--APPLINK-20657: [ResetGlobalProperties] "MENUICON" reset
--APPLINK-22707: [INI file] [ApplicationManager] MenuIcon
--[[Tests:
001_ATF_P_menuIcon_absolute_path_INI
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = absolute path
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
002_ATF_P_menuIcon_relative_path_INI
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = relative path
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
003_ATF_P_menuIcon_absolute_path_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = absolute path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
004_ATF_P_menuIcon_relative_path_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = relative path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
005_ATF_P_menuIcon_relative_path_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = relative path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
006_ATF_P_menuIcon_absolute_path_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = absolute path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
007_ATF_P_menuIcon_relative_path_INI_PrecSGP_Resumption_MobileDisconnect
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = relative path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of mobile disconnect -> connect. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
008_ATF_P_menuIcon_absolute_path_INI_PrecSGP_Resumption_MobileDisconnect
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon = absolute path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of mobile disconnect -> connect. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path})
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
019_ATF_P_menuIcon_empty_path_INI
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon =
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties() is received without parameter menuIcon
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
020_ATF_P_menuIcon_empty_path_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties() is received without parameter menuIcon
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
021_ATF_P_menuIcon_empty_path_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties() is received without parameter menuIcon
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
022_ATF_P_menuIcon_empty_path_INI_PrecSGP_Resumption_MobileDisconnect
-- Precondition
1. Check that menuIcon exists in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }) and check
3.1 UI.SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of mobile disconnect -> connect. => menuIcon is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON") and check:
1.1 UI.SetGlobalProperties() is received without parameter menuIcon
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
]]
--APPLINK-20656: [ResetGlobalProperties] "MENUNAME" reset
--APPLINK-22706: [INI file] [ApplicationManager] MenuTitle
--[[Tests:
009_ATF_P_menuTitle_INI
-- Precondition
1. Check in INI file menuTitle = "MENU"
-- Test
1. Send ResetGlobalProperties(properties = "MENUNAME") and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
010_ATF_P_menuTitle_INI_PrecSGP
-- Precondition
1. Check in INI file menuTitle = "MENU"
2. Send SetGlobalProperties(menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title")
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUNAME") and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
011_ATF_P_menuTitle_INI_PrecSGP_Resumption
-- Precondition
1. Check in INI file menuTitle = "MENU"
2. Send SetGlobalProperties(menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title")
3.2 TTS.SetGlobalProperties is not sent.
3. Perform resumption because of IGN_OFF -> IGN_ON. => menuTitle is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUNAME") and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
012_ATF_P_menuTitle_INI_PrecSGP_Resumption_MobileDisconnect
-- Precondition
1. Check in INI file menuTitle = "MENU"
2. Send SetGlobalProperties(menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title")
3.2 TTS.SetGlobalProperties is not sent.
3. Perform resumption because of mobile disconnect->connect. => menuTitle is resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUNAME") and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
]]
--APPLINK-20657: [ResetGlobalProperties] "MENUICON" reset
--APPLINK-22707: [INI file] [ApplicationManager] MenuIcon
--APPLINK-20656: [ResetGlobalProperties] "MENUNAME" reset
--APPLINK-22706: [INI file] [ApplicationManager] MenuTitle
--[[Tests:
013_ATF_P_menuIcon_absolute_path_menuTitle_INI
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = absolute path
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
014_ATF_P_menuIcon_relative_path_menuTitle_INI
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = relative path
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
015_ATF_P_menuIcon_absolute_path_menuTitle_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = absolute path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
016_ATF_P_menuIcon_relative_path_menuTitle_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = relative path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
017_ATF_P_menuIcon_relative_path_menuTitle_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = relative path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuTitle and menuIcon are resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = relative path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
018_ATF_P_menuIcon_absolute_path_menuTitle_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon = absolute path
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuTitle and menuIcon are resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuIcon = {imageType = "DYNAMIC", value = absolute path}, menuTitle = "MENU")
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
023_ATF_P_menuIcon_empty_path_menuTitle_INI
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon =
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU"), menuIcon is not sent.
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
024_ATF_P_menuIcon_empty_path_menuTitle_INI_PrecSGP
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU"), menuIcon is not sent.
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
025_ATF_P_menuIcon_empty_path_menuTitle_INI_PrecSGP_Resumption
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Perform resumption because of IGN_OFF -> IGN_ON. => menuTitle and menuIcon are resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU"), menuIcon is not sent.
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
026_ATF_P_menuIcon_empty_path_menuTitle_INI_PrecSGP_Resumption_MobileDisconnect
-- Precondition
1. Check that menuIcon exists and menuTitle = "MENU" in INI file.
2. Update menuIcon =
3. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
3.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
3.2 TTS.SetGlobalProperties is not sent.
4. Disconnect mobile. Connect mobile => menuTitle and menuIcon are resumed
-- Test
1. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
1.1 UI.SetGlobalProperties(menuTitle = "MENU"), menuIcon is not sent.
1.2 TTS.SetGlobalProperties is not sent.
1.3 OnHashChange is received.
]]
--[[MANUAL test: [01][HP][MAN]_TC_MenuIcon_INI_file_Empty
1. Check that menuIcon exists and menuTitle = "MENU" in INI file. By default in INI file menuIcon = relative path; param_menuIcon = menuIcon
2. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
2.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
2.2 TTS.SetGlobalProperties is not sent.
3. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
3.1 UI.SetGlobalProperties ( menuTitle = "MENU", menuIcon = { imageType = "DYNAMIC", value = param_menuIcon})
3.2 TTS.SetGlobalProperties is not sent.
3.3 MENU button is displayed with icon defined in param_menuIcon
4. IGN_OFF and update param_menuIcon = menuIcon = relative path. IGN_ON
5. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
5.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
5.2 TTS.SetGlobalProperties is not sent.
6. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
6.1 UI.SetGlobalProperties ( menuTitle = "MENU", menuIcon = { imageType = "DYNAMIC", value = param_menuIcon})
6.2 TTS.SetGlobalProperties is not sent.
6.3 MENU button is displayed with icon defined in param_menuIcon
7. IGN_OFF and update menuIcon = empty. IGN_ON
8. Send SetGlobalProperties(menuIcon = { value = "action.png", imageType = "DYNAMIC" }, menuTitle = "Menu Title") and check
8.1 UI.SetGlobalProperties(menuTitle = "Menu Title", menuIcon = { value = "action.png", imageType = "DYNAMIC" })
8.2 TTS.SetGlobalProperties is not sent.
9. Send ResetGlobalProperties(properties = "MENUICON", "MENUNAME" ) and check:
9.1 UI.SetGlobalProperties ( menuTitle = "MENU"), menuIcon is not sent.
9.2 TTS.SetGlobalProperties is not sent.
9.3 MENU button is displayed without any icon.
]]
|
local _, nCore = ...
-- Forked from rVignette by zork - 2014
function nCore:VignetteAlert()
local addon = CreateFrame("Frame")
local function OnEvent(self, event, id)
if not nCoreDB.VignetteAlert then return end
if event == "VIGNETTE_MINIMAP_UPDATED" then
if not id then return end
self.vignettes = self.vignettes or {}
if self.vignettes[id] then return end
local vignetteInfo = C_VignetteInfo.GetVignetteInfo(id)
if not vignetteInfo then return end
local atlasInfo = C_Texture.GetAtlasInfo(vignetteInfo.atlasName)
local left = atlasInfo.leftTexCoord * 256
local right = atlasInfo.rightTexCoord * 256
local top = atlasInfo.topTexCoord * 256
local bottom = atlasInfo.bottomTexCoord * 256
local str = "|TInterface\\MINIMAP\\ObjectIconsAtlas:0:0:0:0:256:256:"..(left)..":"..(right)..":"..(top)..":"..(bottom).."|t"
if vignetteInfo.name ~= "Garrison Cache" and vignetteInfo.name ~= "Full Garrison Cache" and vignetteInfo.name ~= nil then
RaidNotice_AddMessage(RaidWarningFrame, str.." "..vignetteInfo.name.." spotted!", ChatTypeInfo["RAID_WARNING"])
print(str.." "..vignetteInfo.name,"spotted!")
self.vignettes[id] = true
end
end
end
-- Listen for vignette event.
addon:RegisterEvent("VIGNETTE_MINIMAP_UPDATED")
addon:SetScript("OnEvent", OnEvent)
end
|
-- Copyright (C) 2018 jerrykuku <[email protected]>
-- Licensed to the public under the GNU General Public License v3.
module("luci.controller.vssr", package.seeall)
function index()
if not nixio.fs.access("/etc/config/vssr") then
return
end
if nixio.fs.access("/usr/bin/ssr-redir") then
entry({"admin", "vpn"}, firstchild(), "VPN", 45).dependent = false
entry({"admin", "vpn", "vssr"},
alias("admin", "vpn", "vssr", "client"), _("Hello World"), 10).dependent =
true -- 首页
entry({"admin", "vpn", "vssr", "client"}, cbi("vssr/client"),
_("SSR Client"), 10).leaf = true -- 基本设置
entry({"admin", "vpn", "vssr", "servers"}, cbi("vssr/servers"),
_("Node List"), 11).leaf = true -- 服务器节点
entry({"admin", "vpn", "vssr", "servers"},
arcombine(cbi("vssr/servers"), cbi("vssr/client-config")),
_("Node List"), 11).leaf = true -- 编辑节点
entry({"admin", "vpn", "vssr", "subscription"},cbi("vssr/subscription"),
_("Subscription"),12).leaf = true
entry({"admin", "vpn", "vssr", "control"}, cbi("vssr/control"),
_("Access Control"), 13).leaf = true -- 访问控制
entry({"admin", "vpn", "vssr", "servers-list"}, cbi("vssr/servers-list"),
_("Severs Nodes"), 14).leaf = true
entry({"admin", "vpn", "vssr", "appointlist"},form("vssr/appointlist"),
_("Appointlist List"), 15).leaf = true
entry({"admin", "vpn", "vssr", "udp2raw"},cbi("vssr/udp2raw"),
_("udp2raw tunnel"),16).leaf = true
entry({"admin", "vpn", "vssr", "advanced"}, cbi("vssr/advanced"),
_("Advanced Settings"), 17).leaf = true -- 高级设置
elseif nixio.fs.access("/usr/bin/ssr-server") then
entry({"admin", "vpn", "vssr"},
alias("admin", "vpn", "vssr", "server"), _("vssr"), 10).dependent =
true
else
return
end
if nixio.fs.access("/usr/bin/ssr-server") then
entry({"admin", "vpn", "vssr", "server"},
arcombine(cbi("vssr/server"), cbi("vssr/server-config")),
_("SSR Server"), 20).leaf = true
end
entry({"admin", "vpn", "vssr", "status"},form("vssr/status"),_("Status"), 23).leaf = true
entry({"admin", "vpn", "vssr", "log"}, cbi("vssr/log"), _("Log"), 30).leaf =
true
entry({"admin", "vpn", "vssr", "refresh"}, call("refresh_data")) -- 更新白名单和GFWLIST
entry({"admin", "vpn", "vssr", "checkport"}, call("check_port")) -- 检测单个端口并返回Ping
entry({"admin", "vpn", "vssr", "checkports"}, call("check_ports"))
entry({"admin", "vpn", "vssr", "ping"}, call("act_ping")).leaf=true
entry({"admin", "vpn", "vssr", "run"}, call("act_status")) -- 检测全局服务器状态
entry({"admin", "vpn", "vssr", "change"}, call("change_node")) -- 切换节点
entry({"admin", "vpn", "vssr", "allserver"}, call("get_servers")) -- 获取所有节点Json
entry({"admin", "vpn", "vssr", "subscribe"}, call("get_subscribe")) -- 执行订阅
entry({"admin", "vpn", "vssr", "flag"}, call("get_flag")) -- 获取节点国旗 iso code
entry({"admin", "vpn", "vssr", "ip"}, call("check_ip")) -- 获取ip情况
end
-- 执行订阅
function get_subscribe()
local cjson = require "cjson"
local e = {}
local uci = luci.model.uci.cursor()
local auto_update = luci.http.formvalue("auto_update")
local auto_update_time = luci.http.formvalue("auto_update_time")
local proxy = luci.http.formvalue("proxy")
local subscribe_url = luci.http.formvalue("subscribe_url")
if subscribe_url ~= "[]" then
local cmd1 = 'uci set vssr.@server_subscribe[0].auto_update="' ..
auto_update .. '"'
local cmd2 = 'uci set vssr.@server_subscribe[0].auto_update_time="' ..
auto_update_time .. '"'
local cmd3 = 'uci set vssr.@server_subscribe[0].proxy="' .. proxy .. '"'
luci.sys.call('uci delete vssr.@server_subscribe[0].subscribe_url ')
luci.sys.call(cmd1)
luci.sys.call(cmd2)
luci.sys.call(cmd3)
for k, v in ipairs(cjson.decode(subscribe_url)) do
luci.sys.call(
'uci add_list vssr.@server_subscribe[0].subscribe_url="' .. v ..
'"')
end
luci.sys.call('uci commit vssr')
luci.sys.call(
"nohup /usr/bin/lua /usr/share/vssr/subscribe.lua >/www/check_update.htm 2>/dev/null &")
e.error = 0
else
e.error = 1
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
-- 获取所有节点
function get_servers()
local uci = luci.model.uci.cursor()
local server_table = {}
uci:foreach("vssr", "servers", function(s)
local e = {}
e["name"] = s[".name"]
local t1 = luci.sys.exec(
"ping -c 1 -W 1 %q 2>&1 | grep -o 'time=[0-9]*.[0-9]' | awk -F '=' '{print$2}'" %
s["server"])
e["t1"] = t1
table.insert(server_table, e)
end)
luci.http.prepare_content("application/json")
luci.http.write_json(server_table)
end
-- 切换节点
function change_node()
local e = {}
local uci = luci.model.uci.cursor()
local sid = luci.http.formvalue("set")
local name = ""
uci:foreach("vssr", "global", function(s) name = s[".name"] end)
e.status = false
e.sid = sid
if sid ~= "" then
uci:set("vssr", name, "global_server", sid)
uci:commit("vssr")
luci.sys.call("/etc/init.d/vssr restart")
e.status = true
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
-- 检测全局服务器状态
function act_status()
math.randomseed(os.time())
local e = {}
-- 全局服务器
e.global=luci.sys.call("ps -w | grep ssr-retcp | grep -v grep >/dev/null") == 0
--检测负载均衡状态
if tonumber(luci.sys.exec("ps -w | grep haproxy |grep -v grep| wc -l"))>0 then
e.haproxy= true
end
--检测kcptun状态
if tonumber(luci.sys.exec("ps -w | grep kcptun-client |grep -v grep| wc -l"))>0 then
e.kcptun= true
end
--检测HTTP代理状态
if luci.sys.call("pidof privoxy >/dev/null") == 0 then
e.privoxy= true
end
--检测chinadns状态
if tonumber(luci.sys.exec("ps -w | grep chinadns |grep -v grep| wc -l"))>0 then
e.chinadns= true
elseif tonumber(luci.sys.exec("ps -w | grep dnsparsing |grep -v grep| wc -l"))>0 then
e.chinadns= true
elseif tonumber(luci.sys.exec("ps -w | grep dnscrypt-proxy |grep -v grep| wc -l"))>0 then
e.chinadns= true
elseif tonumber(luci.sys.exec("ps -w | grep pdnsd |grep -v grep| wc -l"))>0 then
e.chinadns= true
elseif tonumber(luci.sys.exec("ps -w | grep dnsforwarder |grep -v grep| wc -l"))>0 then
e.chinadns= true
end
--检测SOCKS5状态
if tonumber(luci.sys.exec("ps -w | grep ssr-local |grep -v grep| wc -l"))>0 then
e.SOCKS5= true
elseif tonumber(luci.sys.exec("ps -w | grep ss-local |grep -v grep| wc -l"))>0 then
e.SOCKS5= true
elseif tonumber(luci.sys.exec("ps -w | grep v2-ssr-local |grep -v grep| wc -l"))>0 then
e.SOCKS5= true
elseif tonumber(luci.sys.exec("ps -w | grep trojan-ssr-local |grep -v grep| wc -l"))>0 then
e.SOCKS5= true
end
--检测UDP2RAW状态
if tonumber(luci.sys.exec("ps -w | grep udp2raw |grep -v grep| wc -l"))>0 then
e.udp2raw= true
end
--检测UDPspeeder状态
if tonumber(luci.sys.exec("ps -w | grep udpspeeder |grep -v grep| wc -l"))>0 then
e.udpspeeder= true
end
--检测服务端状态
if tonumber(luci.sys.exec("ps -w | grep ssr-server |grep -v grep| wc -l"))>0 then
e.server= true
end
if luci.sys.call("pidof ssr-server >/dev/null") == 0 then
e.ssr_server= true
end
if luci.sys.call("pidof ss-server >/dev/null") == 0 then
e.ss_server= true
end
if luci.sys.call("ps -w | grep trojan-server | grep -v grep >/dev/null") == 0 then
e.trojan_server= true
end
if luci.sys.call("ps -w | grep v2ray-server | grep -v grep >/dev/null") == 0 then
e.v2_server= true
end
-- 检测游戏模式状态
e.game = false
if tonumber(luci.sys.exec("ps -w | grep ssr-reudp |grep -v grep| wc -l"))>0 then
e.game= true
else
if tonumber(luci.sys.exec("ps -w | grep ssr-retcp |grep \"\\-u\"|grep -v grep| wc -l"))>0 then
e.game= true
end
end
-- 检测国外通道
--[[ http=require("socket.http")
http.TIMEOUT = 1
result=http.request("http://ip111cn.appspot.com/?z="..math.random(1,100000))
if result then
e.google = result
else
e.google = false
end
result1=http.request("http://45.32.164.128/ip.php?z="..math.random(1,100000))
if result1 then
e.outboard = result1
else
e.outboard = false
end
--]]
-- 检测国内通道
e.baidu = false
sret = luci.sys.call("/usr/bin/ssr-check www.baidu.com 80 3 1")
if sret == 0 then
e.baidu = true
end
-- 检测国外通道
e.google = false
sret = luci.sys.call("/usr/bin/ssr-check www.google.com 80 3 1")
if sret == 0 then
e.google = true
end
-- 检测Socks5
if tonumber(luci.sys.exec("ps -w | grep ssr-local |grep -v grep| wc -l"))>0 then
e.socks5 = true
elseif tonumber(luci.sys.exec("ps -w | grep ss-local |grep -v grep| wc -l"))>0 then
e.socks5 = true
elseif tonumber(luci.sys.exec("ps -w | grep v2-ssr-local |grep -v grep| wc -l"))>0 then
e.socks5 = true
elseif tonumber(luci.sys.exec("ps -w | grep trojan-ssr-local |grep -v grep| wc -l"))>0 then
e.socks5 = true
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function act_ping()
local e = {}
local domain = luci.http.formvalue("domain")
local port = luci.http.formvalue("port")
e.index = luci.http.formvalue("index")
local iret = luci.sys.call(" ipset add ss_spec_wan_ac " .. domain .. " 2>/dev/null")
local socket = nixio.socket("inet", "stream")
socket:setopt("socket", "rcvtimeo", 3)
socket:setopt("socket", "sndtimeo", 3)
e.socket = socket:connect(domain, port)
socket:close()
e.ping = luci.sys.exec("ping -c 1 -W 1 %q 2>&1 | grep -o 'time=[0-9]*.[0-9]' | awk -F '=' '{print$2}'" % domain)
if (iret == 0) then
luci.sys.call(" ipset del ss_spec_wan_ac " .. domain)
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function check_status()
local set ="/usr/bin/ssr-check www." .. luci.http.formvalue("set") .. ".com 80 3 1"
sret=luci.sys.call(set)
if sret== 0 then
retstring ="0"
else
retstring ="1"
end
luci.http.prepare_content("application/json")
luci.http.write_json({ ret=retstring })
end
-- 刷新检测文件
function refresh_data()
local set =luci.http.formvalue("set")
local icount =0
if set == "gfw_data" then
if nixio.fs.access("/usr/bin/wget-ssl") then
refresh_cmd="wget-ssl --no-check-certificate https://cdn.jsdelivr.net/gh/gfwlist/gfwlist/gfwlist.txt -O /tmp/gfw.b64"
else
refresh_cmd="wget -O /tmp/gfw.b64 http://iytc.net/tools/list.b64"
end
sret=luci.sys.call(refresh_cmd .. " 2>/dev/null")
if sret== 0 then
luci.sys.call("/usr/bin/vssr-gfw")
icount = luci.sys.exec("cat /tmp/gfwnew.txt | wc -l")
if tonumber(icount)>1000 then
oldcount=luci.sys.exec("cat /etc/dnsmasq.ssr/gfw_list.conf | wc -l")
if tonumber(icount) ~= tonumber(oldcount) then
luci.sys.exec("cp -f /tmp/gfwnew.txt /etc/dnsmasq.ssr/gfw_list.conf")
retstring=tostring(math.ceil(tonumber(icount)/2))
else
retstring ="0"
end
else
retstring ="-1"
end
luci.sys.exec("rm -f /tmp/gfwnew.txt ")
else
retstring ="-1"
end
elseif set == "ip_data" then
if (luci.model.uci.cursor():get_first('vssr', 'global', 'chnroute', '0') == '1') then
refresh_cmd="wget-ssl --no-check-certificate -O - " .. luci.model.uci.cursor():get_first('vssr', 'global', 'chnroute_url', 'https://pexcn.me/daily/chnroute/chnroute.txt') .. ' > /tmp/china_ssr.txt 2>/dev/null'
else
refresh_cmd="wget -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' 2>/dev/null| awk -F\\| '/CN\\|ipv4/ { printf(\"%s/%d\\n\", $4, 32-log($5)/log(2)) }' > /tmp/china_ssr.txt"
end
sret=luci.sys.call(refresh_cmd)
icount = luci.sys.exec("cat /tmp/china_ssr.txt | wc -l")
if sret== 0 and tonumber(icount)>1000 then
oldcount=luci.sys.exec("cat /etc/china_ssr.txt | wc -l")
if tonumber(icount) ~= tonumber(oldcount) then
luci.sys.exec("cp -f /tmp/china_ssr.txt /etc/china_ssr.txt")
retstring=tostring(tonumber(icount))
else
retstring ="0"
end
else
retstring ="-1"
end
luci.sys.exec("rm -f /tmp/china_ssr.txt ")
else
if nixio.fs.access("/usr/bin/wget-ssl") then
refresh_cmd="wget-ssl --no-check-certificate -O - ".. luci.model.uci.cursor():get_first('vssr', 'global', 'adblock_url','https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt') .." > /tmp/adnew.conf"
end
sret=luci.sys.call(refresh_cmd .. " 2>/dev/null")
if sret== 0 then
luci.sys.call("/usr/bin/vssr-ad")
icount = luci.sys.exec("cat /tmp/ad.conf | wc -l")
if tonumber(icount)>1000 then
if nixio.fs.access("/etc/dnsmasq.ssr/ad.conf") then
oldcount=luci.sys.exec("cat /etc/dnsmasq.ssr/ad.conf | wc -l")
else
oldcount=0
end
if tonumber(icount) ~= tonumber(oldcount) then
luci.sys.exec("cp -f /tmp/ad.conf /etc/dnsmasq.ssr/ad.conf")
retstring=tostring(math.ceil(tonumber(icount)))
if oldcount==0 then
luci.sys.call("/etc/init.d/dnsmasq restart")
end
else
retstring ="0"
end
else
retstring ="-1"
end
luci.sys.exec("rm -f /tmp/ad.conf")
else
retstring ="-1"
end
end
luci.http.prepare_content("application/json")
luci.http.write_json({ ret=retstring ,retcount=icount})
end
-- 检测所有服务器
function check_ports()
local set = ""
local retstring = "<br /><br />"
local s
local server_name = ""
local vssr = "vssr"
local uci = luci.model.uci.cursor()
local iret = 1
uci:foreach(
vssr,
"servers",
function(s)
if s.alias then
server_name = s.alias
elseif s.server and s.server_port then
server_name = "%s:%s" % {s.server, s.server_port}
end
iret = luci.sys.call(" ipset add ss_spec_wan_ac " .. s.server .. " 2>/dev/null")
socket = nixio.socket("inet", "stream")
socket:setopt("socket", "rcvtimeo", 3)
socket:setopt("socket", "sndtimeo", 3)
ret = socket:connect(s.server, s.server_port)
if tostring(ret) == "true" then
socket:close()
retstring = retstring .. "<font color='green'>[" .. server_name .. "] OK.</font><br />"
else
retstring = retstring .. "<font color='red'>[" .. server_name .. "] Error.</font><br />"
end
if iret == 0 then
luci.sys.call(" ipset del ss_spec_wan_ac " .. s.server)
end
end
)
luci.http.prepare_content("application/json")
luci.http.write_json({ret = retstring})
end
-- 检测单个节点状态并返回连接速度
function check_port()
local e = {}
-- e.index=luci.http.formvalue("host")
local t1 = luci.sys.exec(
"ping -c 1 -W 1 %q 2>&1 | grep -o 'time=[0-9]*.[0-9]' | awk -F '=' '{print$2}'" %
luci.http.formvalue("host"))
luci.http.prepare_content("application/json")
luci.http.write_json({ret = 1, used = t1})
end
function JudgeIPString(ipStr)
if type(ipStr) ~= "string" then return false end
-- 判断长度
local len = string.len(ipStr)
if len < 7 or len > 15 then -- 长度不对
return false
end
-- 判断出现的非数字字符
local point = string.find(ipStr, "%p", 1) -- 字符"."出现的位置
local pointNum = 0 -- 字符"."出现的次数 正常ip有3个"."
while point ~= nil do
if string.sub(ipStr, point, point) ~= "." then -- 得到非数字符号不是字符"."
return false
end
pointNum = pointNum + 1
point = string.find(ipStr, "%p", point + 1)
if pointNum > 3 then return false end
end
if pointNum ~= 3 then -- 不是正确的ip格式
return false
end
-- 判断数字对不对
local num = {}
for w in string.gmatch(ipStr, "%d+") do
num[#num + 1] = w
local kk = tonumber(w)
if kk == nil or kk > 255 then -- 不是数字或超过ip正常取值范围了
return false
end
end
if #num ~= 4 then -- 不是4段数字
return false
end
return ipStr
end
-- 检测 当前节点ip 和 网站访问情况
function check_ip()
local e = {}
http = require("socket.http")
http.TIMEOUT = 1
result = luci.sys.exec("curl -s https://api.ip.sb/ip")
if JudgeIPString(result) then
local cmd = '/usr/share/vssr/getip.sh '..result
e.outboard = result
e.outboardip = luci.sys.exec(cmd)
else
e.outboard = false
end
-- 检测国内通道
e.baidu = false
sret1 = luci.sys.call("/usr/bin/ssr-check www.baidu.com 80 3 1")
if sret1 == 0 then e.baidu = true end
e.taobao = false
sret2 = luci.sys.call("/usr/bin/ssr-check www.taobao.com 80 3 1")
if sret2 == 0 then e.taobao = true end
-- 检测国外通道
e.google = false
sret3 = luci.sys.call("/usr/bin/ssr-check www.google.com 80 3 1")
if sret3 == 0 then e.google = true end
e.youtube = false
sret4 = luci.sys.call("/usr/bin/ssr-check www.youtube.com 80 3 1")
if sret4 == 0 then e.youtube = true end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
-- 获取节点国旗 iso code
function get_flag()
local e = {}
local host = luci.http.formvalue("host")
local remark = luci.http.formvalue("remark")
local cmd1 = '/usr/share/vssr/getflag.sh "' .. remark .. '" ' .. host
e.host = host
e.flag = luci.sys.exec(cmd1)
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
|
local i;
local rtWidth;
local rtHeight;
-- Positive
FileWriteLineFast("test/output.txt", "Positive test", FM_WRITE);
ScreenInit(640, 480, false, "Font test");
TextureInit(IKDM_SMALL, 32);
TtfInit(IKDM_SMALL, 32);
PrimitiveInit();
TimerInit();
SpriteInit(IKDM_SMALL, 32);
FontInit(IKDM_SMALL, 32);
local ttf = TtfLoad("test/media/Vera.ttf");
TtfSetSizes(ttf, 24, 24);
local font = FontCacheTtf("Font", ttf, 1);
rtWidth = FontGetStringWidth(font, "Hello World");
rtHeight = FontGetHeight(font);
FileWriteLineFast("test/output.txt", "rtWidth: " .. rtWidth, FM_APPEND);
FileWriteLineFast("test/output.txt", "rtHeight: " .. rtHeight, FM_APPEND);
for i = 0, 60, 1 do
TimerStart();
PrimitiveFill_c(0x000000);
FontDrawString_f(font, 32, 32, "Hello World");
ScreenFlip();
TimerDelayForFPS(30);
end;
for i = 0, FontGetAtlasesCount(font) - 1, 1 do
local sprite = FontGetAtlasSprite(font, i);
if sprite ~= 0 then
local texture = SpriteGetTexture(sprite);
TextureSave(texture, "test/output_" .. i .. ".png");
end;
end;
TtfFree(ttf);
FontFree(font);
local sprMbf_00 = SpriteLoad("test/media/mbf_big_00.png", 10, 12, 16,
16, 256, 0, 0);
local sprMbf_04 = SpriteLoad("test/media/mbf_big_04.png", 10, 12, 16,
16, 256, 0, 0);
local fontMbf = FontCreate("MBF", 5);
FontAddAtlas(fontMbf, sprMbf_00, 0);
FontAddAtlas(fontMbf, sprMbf_00, 4);
rtWidth = FontGetStringWidth(font, "Hello World");
rtHeight = FontGetHeight(font);
FileWriteLineFast("test/output.txt", "rtWidth: " .. rtWidth, FM_APPEND);
FileWriteLineFast("test/output.txt", "rtHeight: " .. rtHeight, FM_APPEND);
for i = 0, 60, 1 do
TimerStart();
PrimitiveFill_c(0x000000);
FontDrawString_f(fontMbf, 32, 32, "Hello World");
ScreenFlip();
TimerDelayForFPS(30);
end;
FontFree(fontMbf);
--TextureFree(renderedText);
--FontSetTtfOutline(ttf, 4);
--rtWidth = FontGetStringWidth(ttf, "Hello World");
--rtHeight = FontGetHeight(ttf);
--renderedText = TextureCreate("rendered text texture", rtWidth, rtHeight);
--FontRenderTtfString(ttf, renderedText, 0xFF, 0x00, 0x00, "Hello World");
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- TextureBlit_f(renderedText, 32, 32);
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
--TextureFree(renderedText);
--FontSetTtfOutline(ttf, 0);
--FontSetTtfStyle(ttf, FS_BOLD);
--rtWidth = FontGetStringWidth(ttf, "Hello World");
--rtHeight = FontGetHeight(ttf);
--renderedText = TextureCreate("rendered text texture", rtWidth, rtHeight);
--FontRenderTtfString(ttf, renderedText, 0xFF, 0x00, 0x00, "Hello World");
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- TextureBlit_f(renderedText, 32, 32);
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
--TextureFree(renderedText);
--FontSetTtfStyle(ttf, FS_ITALIC);
--rtWidth = FontGetStringWidth(ttf, "Hello World");
--rtHeight = FontGetHeight(ttf);
--renderedText = TextureCreate("rendered text texture", rtWidth, rtHeight);
--FontRenderTtfString(ttf, renderedText, 0xFF, 0x00, 0x00, "Hello World");
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- TextureBlit_f(renderedText, 32, 32);
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
--TextureFree(renderedText);
--FontSetTtfStyle(ttf, FS_UNDERLINE);
--rtWidth = FontGetStringWidth(ttf, "Hello World");
--rtHeight = FontGetHeight(ttf);
--renderedText = TextureCreate("rendered text texture", rtWidth, rtHeight);
--FontRenderTtfString(ttf, renderedText, 0xFF, 0x00, 0x00, "Hello World");
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- TextureBlit_f(renderedText, 32, 32);
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
--TextureFree(renderedText);
--FontSetTtfStyle(ttf, FS_STRIKETHROUGH);
--rtWidth = FontGetStringWidth(ttf, "Hello World");
--rtHeight = FontGetHeight(ttf);
--renderedText = TextureCreate("rendered text texture", rtWidth, rtHeight);
--FontRenderTtfString(ttf, renderedText, 0xFF, 0x00, 0x00, "Hello World");
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- TextureBlit_f(renderedText, 32, 32);
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
FontFree(ttf);
--local mbf_big_00 = TextureLoad("test/media/mbf_big_00.png");
--local mbf_big_04 = TextureLoad("test/media/mbf_big_04.png");
--local mbf = FontCreateMbf("MBF font", 5, 10, 12);
--FontAddMbfTextureTable(mbf, mbf_big_00, 0);
--FontAddMbfTextureTable(mbf, mbf_big_04, 4);
--for i = 0, 60, 1 do
-- TimerStart();
-- PrimitiveFill_c(0x000000);
-- FontDrawMbfString_f(mbf, 32, 32, "Hello World");
-- FontDrawMbfString_f(mbf, 32, 64, "Привет мир");
-- ScreenFlip();
-- TimerDelayForFPS(30);
--end;
--FontFree(mbf);
--TextureFree(mbf_big_00);
--TextureFree(mbf_big_04);
|
return {
Janitor = {
URL = "https://raw.githubusercontent.com/RoStrap/Events/master/Janitor.lua";
Documentation = "https://rostrap.github.io/Libraries/Events/Janitor/";
ParentFolderPath = "Events";
};
Signal = {
URL = "https://raw.githubusercontent.com/RoStrap/Events/master/Signal.lua";
Documentation = "https://rostrap.github.io/Libraries/Events/Signal/";
ParentFolderPath = "Events";
};
ReplicatedValue = {
URL = "https://raw.githubusercontent.com/RoStrap/Events/master/ReplicatedValue.lua";
Documentation = "https://rostrap.github.io/Libraries/Events/ReplicatedValue/";
ParentFolderPath = "Events";
};
Keys = {
URL = "https://raw.githubusercontent.com/RoStrap/Input/master/Keys.lua";
Documentation = "https://rostrap.github.io/Libraries/Input/Keys/";
ParentFolderPath = "Input";
};
Enumeration = {
URL = "https://raw.githubusercontent.com/RoStrap/Classes/master/Enumeration.lua";
Documentation = "https://rostrap.github.io/Libraries/Classes/Enumeration";
ParentFolderPath = "Classes";
};
PseudoInstance = {
URL = "https://raw.githubusercontent.com/RoStrap/Classes/master/PseudoInstance.lua";
Documentation = "https://rostrap.github.io/Libraries/Classes/PseudoInstance/";
ParentFolderPath = "Classes";
};
ReplicatedPseudoInstance = {
URL = "https://raw.githubusercontent.com/RoStrap/Classes/master/ReplicatedPseudoInstance.lua";
Documentation = "https://rostrap.github.io/Libraries/Classes/ReplicatedPseudoInstance/";
ParentFolderPath = "Classes";
};
Sentry = {
URL = "https://github.com/RoStrap/Sentry";
Documentation = "https://rostrap.github.io/Libraries/Sentry/";
};
Bezier = {
URL = "https://raw.githubusercontent.com/RoStrap/Interpolation/master/Bezier.lua";
Documentation = "https://rostrap.github.io/Libraries/Interpolation/Bezier/";
ParentFolderPath = "Interpolation";
};
EasingFunctions = {
URL = "https://raw.githubusercontent.com/RoStrap/Interpolation/master/EasingFunctions.lua";
Documentation = "https://rostrap.github.io/Libraries/Interpolation/EasingFunctions/";
ParentFolderPath = "Interpolation";
};
Lerps = {
URL = "https://raw.githubusercontent.com/RoStrap/Interpolation/master/Lerps.lua";
Documentation = "https://rostrap.github.io/Libraries/Interpolation/Lerps/";
ParentFolderPath = "Interpolation";
};
Tween = {
URL = "https://raw.githubusercontent.com/RoStrap/Interpolation/master/Tween.lua";
Documentation = "https://rostrap.github.io/Libraries/Interpolation/Tween/";
ParentFolderPath = "Interpolation";
};
Array = {
URL = "https://raw.githubusercontent.com/RoStrap/DataTypes/master/Array.lua";
Documentation = "https://rostrap.github.io/Libraries/DataTypes/Array/";
ParentFolderPath = "DataTypes";
};
--[[
HTMLParser = {
URL = "https://raw.githubusercontent.com/RoStrap/DataTypes/master/HTMLParser.lua";
Documentation = "https://rostrap.github.io/Libraries/DataTypes/HTMLParser/";
ParentFolderPath = "DataTypes";
};
--]]
SortedArray = {
URL = "https://raw.githubusercontent.com/RoStrap/DataTypes/master/SortedArray.lua";
Documentation = "https://rostrap.github.io/Libraries/DataTypes/SortedArray/";
ParentFolderPath = "DataTypes";
};
Table = {
URL = "https://raw.githubusercontent.com/RoStrap/DataTypes/master/Table.lua";
Documentation = "https://rostrap.github.io/Libraries/DataTypes/Table/";
ParentFolderPath = "DataTypes";
};
BigNum = {
URL = "https://raw.githubusercontent.com/RoStrap/Math/master/BigNum.lua";
Documentation = "https://rostrap.github.io/Libraries/Math/BigNum/";
ParentFolderPath = "Math";
};
Leveler = {
URL = "https://raw.githubusercontent.com/RoStrap/Math/master/Leveler.lua";
Documentation = "https://rostrap.github.io/Libraries/Math/Leveler/";
ParentFolderPath = "Math";
};
Normal = {
URL = "https://raw.githubusercontent.com/RoStrap/Math/master/Normal.lua";
Documentation = "https://rostrap.github.io/Libraries/Math/Normal/";
ParentFolderPath = "Math";
};
Spring = {
URL = "https://raw.githubusercontent.com/RoStrap/Math/master/Spring.lua";
Documentation = "https://rostrap.github.io/Libraries/Math/Spring/";
ParentFolderPath = "Math";
};
WeightedProbabilityFunction = {
URL = "https://raw.githubusercontent.com/RoStrap/Math/master/WeightedProbabilityFunction.lua";
Documentation = "https://rostrap.github.io/Libraries/Math/WeightedProbabilityFunction/";
ParentFolderPath = "Math";
};
FastSpawn = {
URL = "https://raw.githubusercontent.com/RoStrap/Helper/master/FastSpawn.lua";
Documentation = "https://rostrap.github.io/Libraries/Helper/FastSpawn/";
ParentFolderPath = "Helper";
};
Make = {
URL = "https://raw.githubusercontent.com/RoStrap/Helper/master/Make.lua";
Documentation = "https://rostrap.github.io/Libraries/Helper/Make/";
ParentFolderPath = "Helper";
};
Date = {
URL = "https://raw.githubusercontent.com/RoStrap/Time/master/Date.lua";
Documentation = "https://rostrap.github.io/Libraries/Time/Date/";
ParentFolderPath = "Time";
};
SyncedPoller = {
URL = "https://raw.githubusercontent.com/RoStrap/Time/master/SyncedPoller.lua";
Documentation = "https://rostrap.github.io/Libraries/Time/SyncedPoller/";
ParentFolderPath = "Time";
};
ConditionalPoller = {
URL = "https://raw.githubusercontent.com/RoStrap/Time/master/ConditionalPoller.lua";
Documentation = "https://rostrap.github.io/Libraries/Time/ConditionalPoller/";
ParentFolderPath = "Time";
};
Debug = {
URL = "https://raw.githubusercontent.com/RoStrap/Debugging/master/Debug.lua";
Documentation = "https://rostrap.github.io/Libraries/Debugging/Debug/";
ParentFolderPath = "Debugging";
};
Typer = {
URL = "https://raw.githubusercontent.com/RoStrap/Debugging/master/Typer.lua";
Documentation = "https://rostrap.github.io/Libraries/Debugging/Typer/";
ParentFolderPath = "Debugging";
};
AsymmetricTransformation = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/AsymmetricTransformation.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/AsymmetricTransformation/";
ParentFolderPath = "RoStrapUI";
};
Checkbox = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Checkbox.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Checkbox/";
ParentFolderPath = "RoStrapUI";
};
ChoiceDialog = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/ChoiceDialog.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/ChoiceDialog/";
ParentFolderPath = "RoStrapUI";
};
ConfirmationDialog = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/ConfirmationDialog.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/ConfirmationDialog/";
ParentFolderPath = "RoStrapUI";
};
Color = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Color.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Color/";
ParentFolderPath = "RoStrapUI";
};
Radio = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Radio.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Radio/";
ParentFolderPath = "RoStrapUI";
};
RadioGroup = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/RadioGroup.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/RadioGroup/";
ParentFolderPath = "RoStrapUI";
};
RippleButton = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/RippleButton.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/RippleButton/";
ParentFolderPath = "RoStrapUI";
};
Rippler = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Rippler.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Rippler/";
ParentFolderPath = "RoStrapUI";
};
RoStrapPriorityUI = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/RoStrapPriorityUI.lua";
Documentation = "WIP";
ParentFolderPath = "RoStrapUI";
};
SelectionController = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/SelectionController.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/SelectionController/";
ParentFolderPath = "RoStrapUI";
};
Shadow = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Shadow.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Shadow/";
ParentFolderPath = "RoStrapUI";
};
Snackbar = {
URL = "https://raw.githubusercontent.com/RoStrap/RoStrapUI/master/Snackbar.lua";
Documentation = "https://rostrap.github.io/Libraries/RoStrapUI/Snackbar/";
ParentFolderPath = "RoStrapUI";
};
Try = {
URL = "Validark/RBX-Try-Library/tree/patch-4";
Description = "An asynchronous pcall-wrapper for interdependent error-prone functions";
};
EvLightning = {
URL = "evaera/EvLightning";
Description = "Realistic-looking lightning bolt generator";
Documentation = "https://github.com/evaera/EvLightning/blob/master/README.md";
};
RadialImage = {
URL = "evaera/RadialSpriteSheetGenerator/blob/master/roblox/RadialImage.lua";
Description = "A library which displays radial progress indicators using a sprite sheet generated by a nifty tool";
Documentation = "https://github.com/evaera/RadialSpriteSheetGenerator/blob/master/README.md";
};
DataStoreService = {
URL = "buildthomas/MockDataStoreService/tree/master/lib";
Description = "An implementation of DataStoreService in Lua for use in Studio";
Documentation = "https://github.com/buildthomas/MockDataStoreService/blob/master/README.md";
};
Promise = {
URL = "evaera/roblox-lua-promise/tree/master/lib";
Description = "An implementation of Promise similar to Promise/A+";
Documentation = "https://eryn.io/roblox-lua-promise/";
};
Cmdr = {
URL = "evaera/Cmdr";
Description = "A fully extensible and type-safe admin-commands console";
Documentation = "https://github.com/evaera/Cmdr/blob/master/README.md";
ParentFolderPath = "Cmdr.Server"; -- Dot separated directory within Repository.Packages into which Cmdr will be installed
};
-- Succeeded by Rocs.
--[[
Aurora = {
URL = "evaera/Aurora/tree/master/lib";
Description = "A library that can manage status effects (known as \"Auras\") in your Roblox game";
Documentation = "https://github.com/evaera/Aurora/blob/master/README.md";
};
]]
Roact = {
URL = "Roblox/roact/tree/master/src";
Description = "A declarative UI library similar to Facebook's React";
Documentation = "https://roblox.github.io/roact/";
};
Rodux = {
URL = "Roblox/rodux/tree/master/src";
Description = "A state management library inspired by Redux";
Documentation = "https://roblox.github.io/rodux/";
};
["Roact-Rodux"] = {
URL = "Roblox/roact-rodux/tree/master/src";
Description = "An ergonomic binding between Roact and Rodux";
Documentation = "https://roblox.github.io/roact-rodux/";
};
Replica = {
URL = "headjoe3/Replica/tree/master/Replica";
Description = "An easily controllable Server/Client data replication library";
Documentation = "https://github.com/headjoe3/Replica/blob/master/README.md";
};
Rocrastinate = {
URL = "headjoe3/Rocrastinate/tree/master/Rocrastinate";
Description = "A React/Redux-like state management and view library optimized for Roblox";
Documentation = "https://github.com/headjoe3/Rocrastinate/blob/master/docs/1-1-introduction.md";
};
DataStore2 = {
URL = "Kampfkarren/Roblox/tree/master/DataStore2";
Description = "DataStore2 is a simple to use data store system that caches, leading to significantly faster performance over traditional data stores";
Documentation = "https://kampfkarren.github.io/Roblox/";
};
/*
ContextControls = {
URL = "vocksel/ContextControls/tree/master/lib";
Description = "Wrapper for ContextActionService with easy mobile button support";
Documentation = "https://github.com/vocksel/ContextControls/blob/master/README.md";
};
*/
t = {
URL = "osyrisrblx/t/tree/master/lib";
Description = "A module which allows you to create type definitions to check values against";
Documentation = "https://github.com/osyrisrblx/t/blob/master/README.md";
};
Tag = {
URL = "vocksel/Tag/tree/master/lib";
Description = "Class to make tagging instances easy and typesafe";
Documentation = "https://github.com/vocksel/Tag/blob/master/README.md";
};
TestEZ = {
URL = "Roblox/testez/tree/master/src";
Description = "BDD-style test and assertion library for Roblox Lua";
Documentation = "https://roblox.github.io/testez/";
};
CameraShaker = {
URL = "Sleitnick/RbxCameraShaker/tree/master/src/CameraShaker";
Description = "Camera shake effects for Roblox games";
Documentation = "https://github.com/Sleitnick/RbxCameraShaker/blob/master/README.md";
};
Rocs = {
URL = "rocs-rbx/Rocs/tree/master/lib";
Description = "Roblox Component System";
Documentation = "https://rocs-rbx.github.io/Rocs/#rocs";
};
Scheduler = {
URL = "howmanysmall/Scheduler/tree/master/src";
Description = "A RunService.Heartbeat alternative to Roblox functions that use the legacy scheduler";
Documentation = "https://github.com/howmanysmall/Scheduler/blob/master/README.md";
};
}
|
--[[
JpegTran.lua
Represents jpegtran command-line utility.
--]]
local JpegTran, dbg, dbgf = ExternalApp:newClass{ className = 'JpegTran', register = true }
--- Constructor for extending class.
--
function JpegTran:newClass( t )
return ExternalApp.newClass( self, t )
end
--- Constructor for new instance.
--
-- @usage pass pref-name, win-exe-name, or mac-pathed-name, if desired, else rely on defaults (but know what they are - see code).
--
function JpegTran:new( t )
t = t or {}
t.name = t.name or "JpegTran"
t.prefName = t.prefName or 'jpegTranApp' -- same pref-name for win & mac.
t.winExeName = t.winExeName or "jpegtran.exe" -- if included with plugin - may not be.
t.macAppName = t.macAppName or "jpegtran" -- ###1 if included with plugin, also: pre-requisite condition for mac-default-app-path to be used instead of mac-pathed-name, if present on system.
t.winDefaultExePath = nil -- is there a default path? (doesn't matter - it's always built in).
t.macDefaultAppPath = "/usr/local/bin/jpegtran"
t.winPathedName = nil -- pathed access to converter not supported on Windows.
t.macPathedName = nil -- ditto
local o = ExternalApp.new( self, t )
return o
end
return JpegTran
|
function fibonacci_search(arr, x, n)
local fib2 = 0
local fib1 = 1
local fibM = fib2 + fib1
while fibM < n do
fib2 = fib1
fib1 = fibM
fibM = fib2 + fib1
end
local offset = -1
while fibM > 1 do
local i = math.min(offset + fib2, n - 1)
if arr[i] < x then
fibM = fib1
fib1 = fib2
fib2 = fibM - fib1
offset = i
elseif (arr[i] > x) then
fibM = fib2
fib1 = fib1 - fib2
fib2 = fibM - fib1
else
return i
end
end
if fib1 == 1 and arr[offset + 1] == x then
return offset + 1
end
return - 1
end
--test
arr = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}
x = 85
n = 11 --array lenght
print("values: 10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100")
print("wanted value: " .. x )
print("value found at index: " .. fibonacci_search(arr, x, n))
|
local mod = DBM:NewMod(1783, "DBM-BrokenIsles", nil, 822)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17077 $"):sub(12, -3))
mod:SetCreatureID(110321)
mod:SetEncounterID(1950)
mod:SetReCombatTime(20)
mod:SetZone()
--mod:SetMinSyncRevision(11969)
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 219349",
"SPELL_CAST_SUCCESS 219861",
"SPELL_AURA_APPLIED 219591 219865"
)
local warnCorrodingSpray = mod:NewCastAnnounce(219349, 2, nil, nil, "Tank")
local warnWebWrap = mod:NewTargetAnnounce(219865, 2)
local specWarnFoundation = mod:NewSpecialWarningSpell(219591)
local specWarnWebWrap = mod:NewSpecialWarningSwitch(219865, "Dps")--Overkill? maybe just melee or just ranged or off by default
local timerCorrodingSprayCD = mod:NewCDTimer(23.2, 219349, nil, nil, nil, 5, nil, DBM_CORE_TANK_ICON)
local timerFoundatoinCD = mod:NewAITimer(90, 219591, nil, nil, nil, 6)
local timerWebWrapCD = mod:NewCDTimer(36.9, 219865, nil, nil, nil, 3)
--mod:AddReadyCheckOption(37460, false)
function mod:OnCombatStart(delay, yellTriggered)
if yellTriggered then
end
end
function mod:OnCombatEnd()
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 219349 then
warnCorrodingSpray:Show()
timerCorrodingSprayCD:Start()
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 219861 then
specWarnWebWrap:Show()
timerWebWrapCD:Start()
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 219591 then
specWarnFoundation:Show()
-- specWarnFoundation:Play("")
timerFoundatoinCD:start()
elseif spellId == 219865 then
warnWebWrap:CombinedShow(0.3, args.destName)
end
end
|
local allowCountdown = false
function onStartCountdown()
if not allowCountdown and isStoryMode and not seenCutscene then --Block the first countdown
allowCountdown = true;
return Function_Stop;
end
return Function_Continue;
end
function onCreate()
setPropertyFromClass('GameOverSubstate', 'characterName', 'Majinbf'); --Character json file for the death animation
setPropertyFromClass('GameOverSubstate', 'deathSoundName', 'fnf_loss_sfx'); --put in mods/sounds/
setPropertyFromClass('GameOverSubstate', 'loopSoundName', ''); --put in mods/music/
setPropertyFromClass('GameOverSubstate', 'endSoundName', 'gameOverEnd'); --put in mods/music/
end |
remote = require 'net.box'
fiber = require 'fiber'
test_run = require('test_run').new()
LISTEN = require('uri').parse(box.cfg.listen)
space = box.schema.space.create('net_box_test_space')
index = space:create_index('primary', { type = 'tree' })
box.schema.user.grant('guest', 'read,write', 'space', 'net_box_test_space')
box.schema.user.grant('guest', 'execute', 'universe')
cn = remote.connect(box.cfg.listen)
cn.space[space.id] ~= nil
cn.space.net_box_test_space ~= nil
cn.space.net_box_test_space ~= nil
cn.space.net_box_test_space.index ~= nil
cn.space.net_box_test_space.index.primary ~= nil
cn.space.net_box_test_space.index[space.index.primary.id] ~= nil
cn.space.net_box_test_space:insert{234, 1,2,3}
cn.space.net_box_test_space:replace{354, 1,2,4}
cn.space.net_box_test_space.index.primary:min(354)
cn.space.net_box_test_space.index.primary:max(234)
cn.space.net_box_test_space.index.primary:count(354)
box.schema.user.create('netbox', { password = 'test' })
box.schema.user.grant('netbox', 'read,write', 'space', 'net_box_test_space')
box.schema.user.grant('netbox', 'execute', 'universe')
cn = remote.connect(LISTEN.host, LISTEN.service, { user = 'netbox', password = 'test' })
cn.state
cn.error
cn:ping()
function ret_after(to) fiber.sleep(to) return {{to}} end
cn:ping({timeout = 1.00})
cn:ping({timeout = 1e-9})
cn:ping()
remote_space = cn.space.net_box_test_space
remote_pk = remote_space.index.primary
remote_space:insert({0}, { timeout = 1.00 })
remote_space:insert({1}, { timeout = 1e-9 })
remote_space:insert({2})
remote_space:replace({0}, { timeout = 1e-9 })
remote_space:replace({1})
remote_space:replace({2}, { timeout = 1.00 })
remote_space:upsert({3}, {}, { timeout = 1e-9 })
remote_space:upsert({4}, {})
remote_space:upsert({5}, {}, { timeout = 1.00 })
remote_space:upsert({3}, {})
remote_space:update({3}, {}, { timeout = 1e-9 })
remote_space:update({4}, {})
remote_space:update({5}, {}, { timeout = 1.00 })
remote_space:update({3}, {})
remote_pk:update({5}, {}, { timeout = 1e-9 })
remote_pk:update({4}, {})
remote_pk:update({3}, {}, { timeout = 1.00 })
remote_pk:update({5}, {})
remote_space:get({0})
remote_space:get({1}, { timeout = 1.00 })
remote_space:get({2}, { timeout = 1e-9 })
remote_pk:get({3}, { timeout = 1e-9 })
remote_pk:get({4})
remote_pk:get({5}, { timeout = 1.00 })
remote_space:select({2}, { timeout = 1e-9 })
remote_space:select({2}, { timeout = 1.00 })
remote_space:select({2})
remote_pk:select({2}, { timeout = 1.00 })
remote_pk:select({2}, { timeout = 1e-9 })
remote_pk:select({2})
remote_space:select({5}, { timeout = 1.00, iterator = 'LE', limit = 5 })
remote_space:select({5}, { iterator = 'LE', limit = 5})
remote_space:select({5}, { timeout = 1e-9, iterator = 'LE', limit = 5 })
remote_pk:select({2}, { timeout = 1.00, iterator = 'LE', limit = 5 })
remote_pk:select({2}, { iterator = 'LE', limit = 5})
remote_pk:select({2}, { timeout = 1e-9, iterator = 'LE', limit = 5 })
remote_pk:count({2}, { timeout = 1.00})
remote_pk:count({2}, { timeout = 1e-9})
remote_pk:count({2})
remote_pk:count({2}, { timeout = 1.00, iterator = 'LE' })
remote_pk:count({2}, { iterator = 'LE'})
remote_pk:count({2}, { timeout = 1e-9, iterator = 'LE' })
remote_pk:min(nil, { timeout = 1.00 })
remote_pk:min(nil, { timeout = 1e-9 })
remote_pk:min(nil)
remote_pk:min({0}, { timeout = 1e-9 })
remote_pk:min({1})
remote_pk:min({2}, { timeout = 1.00 })
remote_pk:max(nil)
remote_pk:max(nil, { timeout = 1e-9 })
remote_pk:max(nil, { timeout = 1.00 })
remote_pk:max({0}, { timeout = 1.00 })
remote_pk:max({1}, { timeout = 1e-9 })
remote_pk:max({2})
--
-- gh-3262: index:count() inconsistent results
--
test_run:cmd("setopt delimiter ';'")
function do_count_test(min, it)
local r1 = remote_pk:count(min, {iterator = it} )
local r2 = box.space.net_box_test_space.index.primary:count(min, {iterator = it} )
local r3 = remote.self.space.net_box_test_space.index.primary:count(min, {iterator = it} )
return r1 == r2 and r2 == r3
end;
data = remote_pk:select();
for _, v in pairs(data) do
local itrs = {'GE', 'GT', 'LE', 'LT' }
for _, it in pairs(itrs) do
assert(do_count_test(v[0], it) == true)
end
end;
test_run:cmd("setopt delimiter ''");
_ = remote_space:delete({0}, { timeout = 1e-9 })
_ = remote_pk:delete({0}, { timeout = 1.00 })
_ = remote_space:delete({1}, { timeout = 1.00 })
_ = remote_pk:delete({1}, { timeout = 1e-9 })
_ = remote_space:delete({2}, { timeout = 1e-9 })
_ = remote_pk:delete({2})
_ = remote_pk:delete({3})
_ = remote_pk:delete({4})
_ = remote_pk:delete({5})
remote_space:get(0)
remote_space:get(1)
remote_space:get(2)
remote_space = nil
cn:call('ret_after', {0.01}, { timeout = 1.00 })
cn:call('ret_after', {1.00}, { timeout = 1e-9 })
cn:eval('return ret_after(...)', {0.01}, { timeout = 1.00 })
cn:eval('return ret_after(...)', {1.00}, { timeout = 1e-9 })
--
-- :timeout()
-- @deprecated since 1.7.4
--
cn:timeout(1).space.net_box_test_space.index.primary:select{234}
cn:call('ret_after', {.01})
cn:timeout(1):call('ret_after', {.01})
cn:timeout(.01):call('ret_after', {1})
cn = remote:timeout(0.0000000001):connect(LISTEN.host, LISTEN.service, { user = 'netbox', password = '123' })
cn:close()
cn = remote:timeout(1):connect(LISTEN.host, LISTEN.service, { user = 'netbox', password = '123' })
remote.self:ping()
remote.self.space.net_box_test_space:select{234}
remote.self:timeout(123).space.net_box_test_space:select{234}
remote.self:is_connected()
remote.self:wait_connected()
cn:close()
-- cleanup database after tests
space:drop()
box.schema.user.revoke('guest', 'execute', 'universe')
|
-- Completion for snippets.
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
-- LSP Lua (build from source without telemetry (use grep to find config)
-- https://github.com/sumneko/lua-language-server
-- cd lua-language-server
-- Then change the path to your 'lua-language-server' build
require('lsp.lua-ls')
-- Parse English.
--require('lint-nv')
-- C++ and C Language Server
require('lsp.ccls')
-- Bash Language Server
require('lspconfig').bashls.setup{}
-- Typescript + Javascript Language Server
require('lspconfig').tsserver.setup{}
-- SASS Language Server
require('lspconfig').tailwindcss.setup{}
-- HTML Language Server
require('lspconfig').html.setup {
-- Enable (broadcasting) snippet capability for completion
capabilities = capabilities,
}
-- CSS + Less + SASS Language Server
require('lsp.cssls')
|
--
-- IMPORTANT: This script resource may be attached to all Button widgets created by the Widget Creator panel.
-- If modifications are required, then first copy this file to a unique path and fix all necessary
-- script components' resource paths.
--
local thisActor = ...;
scaleform.Actor.set_mouse_enabled_for_children(thisActor, false);
scaleform.Actor.set_visible(thisActor,false)
-- Helper function to set the label text of the button.
-- setLabelText("new button label");
local setLabelText = function(labelText)
local container = scaleform.Actor.container(thisActor);
local labelActor = scaleform.ContainerComponent.actor_by_name(container, "label");
if labelActor ~= nil then
scaleform.TextComponent.set_text(scaleform.Actor.component_by_index(labelActor, 1) , labelText);
end
end
-- Helper function to get the label text of the button.
-- local btnLabel = getLabelText();
local getLabelText = function()
local container = scaleform.Actor.container(thisActor);
local labelActor = scaleform.ContainerComponent.actor_by_name(container, "label");
if labelActor ~= nil then
return scaleform.TextComponent.text(scaleform.Actor.component_by_index(labelActor, 1));
end
end
local emitEvent = function(func, param)
local comp = scaleform.Actor.component_by_name(thisActor, "WidgetHandler");
if comp ~= nil then
local handlerObject = scaleform.ScriptComponent.script_results(comp);
if handlerObject ~= nil then
if handlerObject[func] ~= nil then
if (param) then
handlerObject[func](param);
else
handlerObject[func]();
end
end
end
end
end
mouseDownEventListener = scaleform.EventListener.create(mouseDownEventListener, function(e)
local container = scaleform.Actor.container(thisActor);
scaleform.AnimationComponent.play_label(container, "press");
emitEvent("pressed");
emitEvent("stateChanged", "press");
end )
mouseUpEventListener = scaleform.EventListener.create(mouseUpEventListener, function(e)
local container = scaleform.Actor.container(thisActor);
scaleform.AnimationComponent.play_label(container, "over");
emitEvent("clicked");
emitEvent("stateChanged", "over");
end )
mouseOverEventListener = scaleform.EventListener.create(mouseOverEventListener, function(e)
local container = scaleform.Actor.container(thisActor);
scaleform.AnimationComponent.play_label(container, "over");
emitEvent("stateChanged", "over");
end )
mouseOutEventListener = scaleform.EventListener.create(mouseOutEventListener, function(e)
local container = scaleform.Actor.container(thisActor);
scaleform.AnimationComponent.play_label(container, "normal");
emitEvent("stateChanged", "normal");
end )
mouseReleaseOutsideEventListener = scaleform.EventListener.create(mouseReleaseOutsideEventListener, function(e)
local container = scaleform.Actor.container(thisActor);
scaleform.AnimationComponent.play_label(container, "normal");
emitEvent("releasedOutside");
emitEvent("stateChanged", "normal");
end )
customEventListener = scaleform.EventListener.create(customEventListener, function(e)
if e.name == "CallToAction" then
scaleform.Actor.set_visible(thisActor,true)
end
end )
scaleform.EventListener.connect(mouseDownEventListener, thisActor, scaleform.EventTypes.MouseDown)
scaleform.EventListener.connect(mouseUpEventListener, thisActor, scaleform.EventTypes.MouseUp)
scaleform.EventListener.connect(mouseOverEventListener, thisActor, scaleform.EventTypes.MouseOver)
scaleform.EventListener.connect(mouseOutEventListener, thisActor, scaleform.EventTypes.MouseOut)
scaleform.EventListener.connect(mouseReleaseOutsideEventListener, thisActor, scaleform.EventTypes.MouseUpOutside)
scaleform.EventListener.connect(customEventListener, thisActor, scaleform.EventTypes.Custom)
-- Save the methods below in this script component to use them from elsewhere
local exports = {
setLabelText = setLabelText;
getLabelText = getLabelText;
}
return exports;
|
require "lunit"
module(..., lunit.testcase, package.seeall)
common = dofile("common.lua")
--assert = common.assert
local EventEmitter = require "luanode.event_emitter"
function test()
local callbacks_called = {}
local e = EventEmitter()
function callback1()
table.insert(callbacks_called, "callback1")
e:addListener("foo", callback2)
e:addListener("foo", callback3)
e:removeListener("foo", callback1)
end
function callback2()
table.insert(callbacks_called, "callback2")
e:removeListener("foo", callback2)
end
function callback3()
table.insert(callbacks_called, "callback3")
e:removeListener("foo", callback3)
end
e:addListener("foo", callback1)
assert_equal(1, #e:listeners("foo"))
e:emit("foo")
assert_equal(2, #e:listeners("foo"))
assert_equal("callback1", callbacks_called[1])
e:emit("foo")
assert_equal(0, #e:listeners("foo"))
assert_equal("callback1", callbacks_called[1])
assert_equal("callback2", callbacks_called[2])
assert_equal("callback3", callbacks_called[3])
e:emit("foo")
assert_equal(0, #e:listeners("foo"))
assert_equal("callback1", callbacks_called[1])
assert_equal("callback2", callbacks_called[2])
assert_equal("callback3", callbacks_called[3])
e:addListener("foo", callback1)
e:addListener("foo", callback2)
assert_equal(2, #e:listeners("foo"))
e:removeAllListeners("foo")
assert_equal(0, #e:listeners("foo"))
-- Verify that removing callbacks while in emit allows emits to propagate to
-- all listeners
callbacks_called = {}
e:addListener("foo", callback2)
e:addListener("foo", callback3)
assert_equal(2, #e:listeners("foo"))
e:emit("foo")
assert_equal("callback2", callbacks_called[1])
assert_equal("callback3", callbacks_called[2])
assert_equal(0, #e:listeners("foo"))
process:loop()
end |
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: gui_ReclaimInfo.lua
-- brief: Shows the amount of metal/energy when using area reclaim.
-- original author: Janis Lukss
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "ReclaimInfo",
desc = "Shows the amount of metal/energy when using area reclaim.",
author = "Pendrokar",
date = "Nov 17, 2007",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local start = false --reclaim area cylinder drawing has been started
local metal = 0 --metal count from features in cylinder
local energy = 0 --energy count from features in cylinder
local nonground = "" --if reclaim order done with right click on a feature or unit
local rangestart = {} --counting start center
local rangestartinminimap = false --both start and end need to be equaly checked
local rangeend = {} --counting radius end point
local b1was = false -- cursor was outside the map?
local vsx, vsy = widgetHandler:GetViewSizes()
local form = 12 --text format depends on screen size
local xstart,ystart = 0
local cmd,xend,yend,x,y,b1,b2
local inMinimap = false --mouse cursor in minimap
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
form = math.floor(vsx/87)
end
local function InMinimap(x,y)
local posx,posy,sizex,sizey,minimized,maximized = Spring.GetMiniMapGeometry()
rx,ry = (x-posx)/sizex,(y-posy)/sizey
return (not (minimized or maximized)) and
(rx>=0)and(rx<=1)and
(ry>=0)and(ry<=1),rx,ry
end
local function MinimapToWorld(rx,ry)
if (rx>=0)and(rx<=1)and
(ry>=0)and(ry<=1)
then
local mapx,mapz = Game.mapSizeX*rx,Game.mapSizeZ-Game.mapSizeZ*ry
local mapy = Spring.GetGroundHeight(mapx,mapz)
return {mapx,mapy,mapz}
else
return {-1,-1,-1}
end
end
function widget:Initialize()
end
function widget:DrawScreen()
_,cmd,_ = Spring.GetActiveCommand()
x, y, b1,_,b2 = Spring.GetMouseState() --b1 = left button pressed?
nonground,_ = Spring.GetMouseCursor()
x, y = math.floor(x), math.floor(y) --TraceScreenRay needs this
if ((cmd==CMD.RECLAIM) and (rangestart ~= nil) and (b1) and (b1was == false)) or ((nonground == "Reclaim") and (b1was == false) and (b2) and (rangestart ~= nil)) then
if(rangestart[1] == 0) and (rangestart[3] == 0) then
local rx,ry
inMinimap,rx,ry = InMinimap(x,y)
if inMinimap then
rangestart = MinimapToWorld(rx,ry)
xstart,ystart = x,y
start = false
rangestartinminimap = true
else
xstart,ystart = x,y
start = false
rangestartinminimap = false
_, rangestart = Spring.TraceScreenRay(x, y, true) --cursor on world pos
end
end
elseif (rangestart == nil) and (b1) then
b1was = true
else
b1was = false
rangestart = {0, _,0}
end
--bit more precise showing when mouse is moved by 4 pixels (start)
if (b1 and (rangestart ~= nil) and (cmd==CMD.RECLAIM) and (start==false)) or ((nonground == "Reclaim") and (rangestart ~= nil) and (start==false) and (b2)) then
xend, yend = x,y
if (((xend>xstart+4)or(xend<xstart-4))or((yend>ystart+4)or(yend<ystart-4))) then
start=true
end
end
--
if (b1 and (rangestart ~= nil) and (cmd==CMD.RECLAIM) and start) or ((nonground == "Reclaim") and start and b2 and (rangestart ~= nil)) then
local rx,ry
inMinimap,rx,ry = InMinimap(x,y)
if inMinimap and rangestartinminimap then
rangeend = MinimapToWorld(rx,ry)
else
_, rangeend = Spring.TraceScreenRay(x,y,true)
end
if(rangeend == nil) then
return
end
metal=0
energy=0
local rdx, rdy = (rangestart[1] - rangeend[1]), (rangestart[3]- rangeend[3])
local dist = math.sqrt((rdx * rdx) + (rdy * rdy))
--because there is only GetFeaturesInRectangle. Features outside of the circle are needed to be ignored
local units = Spring.GetFeaturesInRectangle(rangestart[1]-dist,rangestart[3]-dist,rangestart[1]+dist,rangestart[3]+dist)
for _,unit in ipairs(units) do
local ux, _, uy = Spring.GetFeaturePosition(unit)
local udx, udy = (ux - rangestart[1]), (uy - rangestart[3])
udist = math.sqrt((udx * udx) + (udy * udy))
if(udist < dist) then
local fm,_,fe = Spring.GetFeatureResources(unit)
metal = metal + fm
energy = energy + fe
end
end
metal=math.floor(metal)
energy=math.floor(energy)
local textwidth = 12*gl.GetTextWidth(" M:"..metal.."\255\255\255\128".." E:"..energy)
if(textwidth+x>vsx) then
x = x - textwidth - 10
end
if(12+y>vsy) then
y = y - form
end
gl.Text(" M:"..metal.."\255\255\255\128".." E:"..energy,x,y,form)
end
--Unit resource info when mouse on one
if (nonground=="Reclaim") and (rangestart ~= nil) and ((energy==0) or (metal==0)) and (b1==false) then
local isunit, unitID = Spring.TraceScreenRay(x, y) --if on unit pos!
if (isunit == "unit") and (Spring.GetUnitHealth(unitID)) then --Getunithealth just to make sure that it is in los
local unitDefID = Spring.GetUnitDefID(unitID)
local _,_,_,_,buildprogress = Spring.GetUnitHealth(unitID)
metal=math.floor(UnitDefs[unitDefID].metalCost*buildprogress)
local textwidth = 12*gl.GetTextWidth(" M:"..metal.."\255\255\255\128")
if(textwidth+x>vsx) then
x = x - textwidth - 10
end
if(12+y>vsy) then
y = y - form
end
local color = "\255\255\255\255"
if not UnitDefs[Spring.GetUnitDefID(unitID)].reclaimable then
color = "\255\220\10\10"
end
gl.Text(color.." M:"..metal,x,y,form)
end
end
--
metal = 0
energy = 0
end
|
--------------------------------
-- @module OrbitCamera
-- @extend ActionCamera
-- @parent_module cc
--------------------------------
-- @function [parent=#OrbitCamera] create
-- @param self
-- @param #float float
-- @param #float float
-- @param #float float
-- @param #float float
-- @param #float float
-- @param #float float
-- @param #float float
-- @return OrbitCamera#OrbitCamera ret (return value: cc.OrbitCamera)
--------------------------------
-- @function [parent=#OrbitCamera] startWithTarget
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#OrbitCamera] clone
-- @param self
-- @return OrbitCamera#OrbitCamera ret (return value: cc.OrbitCamera)
--------------------------------
-- @function [parent=#OrbitCamera] update
-- @param self
-- @param #float float
return nil
|
function love.load()
love.window.setMode(1000, 768)
anim8 = require 'libraries/anim8/anim8'
sti = require 'libraries/Simple-Tiled-Implementation/sti'
sprites = {}
sprites.playerSheet = love.graphics.newImage('sprites/playerSheet.png')
local grid = anim8.newGrid(614, 564, sprites.playerSheet:getWidth(), sprites.playerSheet:getHeight())
animations = {}
animations.idle = anim8.newAnimation(grid('1-15',1), 0.05)
animations.jump = anim8.newAnimation(grid('1-7',2), 0.05)
animations.run = anim8.newAnimation(grid('1-15',3), 0.05)
wf = require 'libraries/windfield/windfield'
world = wf.newWorld(0, 800, false)
world:setQueryDebugDrawing(true)
world:addCollisionClass('Platform')
world:addCollisionClass('Player'--[[, {ignores = {'Platform'}}]])
world:addCollisionClass('Danger')
require('player')
--dangerZone = world:newRectangleCollider(0, 550, 800, 50, {collision_class = "Danger"})
--dangerZone:setType('static')
platforms = {}
loadMap()
end
function love.update(dt)
world:update(dt)
gameMap:update(dt)
playerUpdate(dt)
end
function love.draw()
gameMap:drawLayer(gameMap.layers["Tile Layer 1"])
world:draw()
drawPlayer()
end
function love.keypressed(key)
if key == 'up' then
if player.grounded then
player:applyLinearImpulse(0, -4000)
end
end
end
function love.mousepressed(x, y, button)
if button == 1 then
local colliders = world:queryCircleArea(x, y, 200, {'Platform', 'Danger'})
for i,c in ipairs(colliders) do
c:destroy()
end
end
end
function spawnPlatform(x, y, width, height)
local platform = world:newRectangleCollider(x, y, width, height, {collision_class = "Platform"})
platform:setType('static')
table.insert(platforms, platform)
end
function loadMap()
gameMap = sti("maps/level1.lua")
for i, obj in pairs(gameMap.layers["Platforms"].objects) do
spawnPlatform(obj.x, obj.y, obj.width, obj.height)
end
end |
---------------------------------------------------------------------------------------------------
--
--filename: game.entities.data.SkillData
--date:2019/10/11 14:24:48
--author:heguang
--desc:装备的技能
--
---------------------------------------------------------------------------------------------------
local strClassName = 'game.entities.data.SkillData'
local SkillData = lua_declare(strClassName, lua_class(strClassName))
function SkillData:ctor(skillID, entityData)
self.skill_id = skillID
self.entityData = entityData
self.skill_data = cfg_skill[skillID]
self.attr2Data = {}
end
function SkillData:dtor()
end
function SkillData:Install()
if self.skill_data ~= nil then
if self.skill_data.attributes ~= nil then
local att = self.skill_data.attributes
if type(att[1]) == "table" then
for _,v in ipairs(att) do
self:HandlePlusAttribute(v)
end
else
self:HandlePlusAttribute(att)
end
end
if self.skill_data.buffs ~= nil then
local buffs = self.skill_data.buffs
if type(buffs) == "table" then
for _,v in ipairs(buffs) do
self:HandleAddBuff(v)
end
else
self:HandleAddBuff(buffs)
end
end
end
end
function SkillData:Uninstall()
if self.skill_data ~= nil then
if self.skill_data.attributes ~= nil then
local att = self.skill_data.attributes
if type(att[1]) == "table" then
for _,v in ipairs(att) do
self:HandleMinusAttribute(v)
end
else
self:HandleMinusAttribute(att)
end
end
if self.skill_data.buffs ~= nil then
local buffs = self.skill_data.buffs
if type(buffs) == "table" then
for _,v in ipairs(buffs) do
self:HandleRemoveBuff(v)
end
else
self:HandleRemoveBuff(buffs)
end
end
end
self.attr2Data = {}
end
function SkillData:HandlePlusAttribute(v)
local attrName = v[1]
if self.entityData[attrName] == nil then
return
end
local attrValue = 0
if #v == 3 and v[3] then
--按百分比计算
attrValue = self.entityData[attrName] * v[2]
else
--按固定数值计算
attrValue = v[2]
end
self.attr2Data[v] = attrValue
self.entityData[attrName] = self.entityData[attrName] + attrValue
end
function SkillData:HandleMinusAttribute(v)
local attrName = v[1]
if self.entityData[attrName] == nil then
return
end
local attrValue = self.attr2Data[v]
if attrValue == nil then
return
end
self.entityData[attrName] = self.entityData[attrName] - attrValue
end
function SkillData:HandleAddBuff(buffID)
self.entityData.owner:AddBuff(buffID)
end
function SkillData:HandleRemoveBuff(buffID)
self.entityData.owner:RemoveBuff(buffID)
end
return SkillData
|
local function GraphDisplay( pn )
local t = Def.ActorFrame {
Def.GraphDisplay {
InitCommand=cmd(Load,"GraphDisplay";);
OnCommand=cmd(x,-7.5;y,-25;zoomx,1.55);
BeginCommand=function(self)
local ss = SCREENMAN:GetTopScreen():GetStageStats();
self:Set( ss, ss:GetPlayerStageStats(pn) );
self:player( pn );
end
};
};
return t;
end
local function PercentScore( pn )
local t = LoadFont("Common normal")..{
InitCommand=cmd(zoom,0.625;shadowlength,1;player,pn);
BeginCommand=cmd(playcommand,"Set");
SetCommand=function(self)
-- todo: color by difficulty
local SongOrCourse, StepsOrTrail;
if GAMESTATE:IsCourseMode() then
SongOrCourse = GAMESTATE:GetCurrentCourse()
StepsOrTrail = GAMESTATE:GetCurrentTrail(pn)
else
SongOrCourse = GAMESTATE:GetCurrentSong()
StepsOrTrail = GAMESTATE:GetCurrentSteps(pn)
end;
if SongOrCourse and StepsOrTrail then
local st = StepsOrTrail:GetStepsType();
local diff = StepsOrTrail:GetDifficulty();
local courseType = GAMESTATE:IsCourseMode() and SongOrCourse:GetCourseType() or nil;
local cd = GetCustomDifficulty(st, diff, courseType);
self:diffuse(CustomDifficultyToColor(cd));
self:shadowcolor(CustomDifficultyToDarkColor(cd));
end
local pss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(pn);
if pss then
local pct = pss:GetPercentDancePoints();
if pct == 1 then
self:settext("100%");
else
self:settext(FormatPercentScore(pct));
end;
end;
end;
};
return t;
end
----{W1,W2,W3,W4,W5,miss,W1+W2+W3+W4+W5,held,mine,maxcombo,letgo}
local P1Stat = {0,0,0,0,0,0,0,0,0,0,0}
local animetedP1 = {0,0,0,0,0,0,0,0,0,0,0}
if GAMESTATE:IsPlayerEnabled(PLAYER_1) then
local Stat1=STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
P1Stat = {Stat1:GetTapNoteScores('TapNoteScore_W1'),Stat1:GetTapNoteScores('TapNoteScore_W2'),Stat1:GetTapNoteScores('TapNoteScore_W3'),Stat1:GetTapNoteScores('TapNoteScore_W4'),Stat1:GetTapNoteScores('TapNoteScore_W5'),Stat1:GetTapNoteScores('TapNoteScore_Miss'),Stat1:GetTapNoteScores('TapNoteScore_W5')+Stat1:GetTapNoteScores('TapNoteScore_W4')+Stat1:GetTapNoteScores('TapNoteScore_W3')+Stat1:GetTapNoteScores('TapNoteScore_W2')+Stat1:GetTapNoteScores('TapNoteScore_W1'),Stat1:GetHoldNoteScores('HoldNoteScore_Held'),Stat1:GetTapNoteScores('TapNoteScore_HitMine'),Stat1:MaxCombo(),Stat1:GetHoldNoteScores('HoldNoteScore_LetGo')}
animetedP1 = P1Stat
end
local P2Stat = {0,0,0,0,0,0,0,0,0,0,0}
local animetedP2 = {0,0,0,0,0,0,0,0,0,0,0}
if GAMESTATE:IsPlayerEnabled(PLAYER_2) then
local Stat2=STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
P2Stat = {Stat2:GetTapNoteScores('TapNoteScore_W1'),Stat2:GetTapNoteScores('TapNoteScore_W2'),Stat2:GetTapNoteScores('TapNoteScore_W3'),Stat2:GetTapNoteScores('TapNoteScore_W4'),Stat2:GetTapNoteScores('TapNoteScore_W5'),Stat2:GetTapNoteScores('TapNoteScore_Miss'),Stat2:GetTapNoteScores('TapNoteScore_W5')+Stat2:GetTapNoteScores('TapNoteScore_W4')+Stat2:GetTapNoteScores('TapNoteScore_W3')+Stat2:GetTapNoteScores('TapNoteScore_W2')+Stat2:GetTapNoteScores('TapNoteScore_W1'),Stat2:GetHoldNoteScores('HoldNoteScore_Held'),Stat2:GetTapNoteScores('TapNoteScore_HitMine'),Stat2:MaxCombo(),Stat2:GetHoldNoteScores('HoldNoteScore_LetGo')}
animetedP2 = P2Stat
end
local jud1 = TP[ToEnumShortString(PLAYER_1)].ActiveModifiers.JudgmentGraphic or "tor12315za";
local jud2 = TP[ToEnumShortString(PLAYER_2)].ActiveModifiers.JudgmentGraphic or "tor12315za";
local frame1;
local percent = 0;
local vib = 20;
local nep = 0;
local whatx = 0;
local whaty = 0;
local GradeforP1 = "Normal 4x2.png"--in 589
local profileP1 = PROFILEMAN:GetProfile(PLAYER_1);
local nameP1 = profileP1:GetDisplayName();
local LVP1 = TP[ToEnumShortString(PLAYER_1)].Level.Level or 1
if nameP1 == "tor12315za" or nameP1 == "Neptune" or (MonthOfYear() == 10-1 and DayOfMonth() == 8) then
GradeforP1 = "Tor 4x2.png"
elseif MonthOfYear() == 10-1 and DayOfMonth() == 31 then
GradeforP1 = "Horror 4x2.png"
end
TP[ToEnumShortString(PLAYER_1)].Level.Level = LVP1 + 5
local GradeforP2 = "Normal 4x2.png"--in 589
local profileP2 = PROFILEMAN:GetProfile(PLAYER_2);
local nameP2 = profileP2:GetDisplayName();
if nameP2 == "tor12315za" or nameP2 == "Neptune" or (MonthOfYear() == 10-1 and DayOfMonth() == 8) then
GradeforP2 = "Tor 4x2.png"
elseif MonthOfYear() == 10-1 and DayOfMonth() == 31 then
GradeforP2 = "Horror 4x2.png"
end
local percentP1;
local percentP2;
percentP1 = STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_1):GetPercentDancePoints()
percentP2 = STATSMAN:GetCurStageStats():GetPlayerStageStats(PLAYER_2):GetPercentDancePoints()
LoadActor("../_save/Battle.lua")
local t = LoadFallbackB();
--t[#t+1] = StandardDecorationFromFileOptional("StageDisplay","StageDisplay");
t[#t+1] = Def.ActorFrame{
OnCommand=cmd(playcommand,'loop');
loopCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
if psssss:FullCombo() then
nep = nep + 0.02
whatx = math.random(-vib,vib)
whaty = math.random(-vib,vib)
self:x(whatx)
self:y(whaty)
if nep >= 16.188 then
vib = vib - 1;
end
end
elseif GAMESTATE:IsWinner(PLAYER_2) then
nep = nep + 0.02
if nep >= 2.249 then
vib = vib - 1;
whatx = math.random(-vib,vib)
whaty = math.random(-vib,vib)
self:x(whatx)
self:y(whaty)
end
end
self:sleep(0.02)
self:queuecommand('loop')
end;
LoadActor("hrror.png") .. {
InitCommand=cmd(Center;zoom,0.5;cropright,0.5);
OnCommand=function(self)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
self:player(0)
end
self:diffusetopedge(PlayerColor(PLAYER_1))
local steps = GAMESTATE:GetCurrentSteps(PLAYER_1)
local meter = steps:GetDifficulty()
if meter then
if meter == "Difficulty_Beginner" then
self:diffusebottomedge(color("#FFAAAA"))
elseif meter == "Difficulty_Easy" then
self:diffusebottomedge(color("#55ff55"))
elseif meter == "Difficulty_Medium" then
self:diffusebottomedge(color("#fFff22"))
elseif meter == "Difficulty_Hard" then
self:diffusebottomedge(color("#ff4444"))
elseif meter == "Difficulty_Challenge" then
self:diffusebottomedge(color("#CCCCff"))
elseif meter == "Difficulty_Edit" then
self:diffusebottomedge(color("#AAAAAA"))
end
end
end;
};
LoadFont("_determination mono 24px") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-105;y,SCREEN_CENTER_Y+152;zoom,0.4);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
profile = PROFILEMAN:GetProfile(PLAYER_1);
name = profile:GetTotalDancePoints();
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
flowey = psssss:GetScore()
frisk = FormatPercentScore(psssss:GetPercentDancePoints())
self:settext(flowey.."\n"..frisk)
end;
};
LoadFont("_8-bit madness 72px")..{
InitCommand=cmd(x,SCREEN_CENTER_X-169;y,SCREEN_CENTER_Y+150;zoom,0.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(PLAYER_1)
local meter = steps:GetMeter()
if meter then
if meter == 1943951546 then
self:settext("??")
self:zoom(0.4)
elseif meter >= 10 then
self:zoom(0.4)
self:settext(meter)
elseif meter >= 100 then
self:zoom(0.25)
self:settext(meter)
elseif meter >= 1000 then
self:zoom(0.15)
self:settext(meter)
else
self:settext(meter)
self:zoom(0.5)
end
end
end;
};
LoadFont("_determination mono 24px") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-230;y,SCREEN_CENTER_Y+153;zoom,0.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(PLAYER_1)
local meter = steps:GetDifficulty()
if meter then
if meter == "Difficulty_Beginner" then
self:settext("Beginer");
self:zoom(0.8);
elseif meter == "Difficulty_Easy" then
self:settext("Easy");
self:zoom(0.8);
elseif meter == "Difficulty_Medium" then
self:settext("Normal");
self:zoom(0.8);
elseif meter == "Difficulty_Hard" then
self:settext("Hard");
self:zoom(0.8);
elseif meter == "Difficulty_Challenge" then
self:settext("Expert");
self:zoom(0.7);
elseif meter == "Difficulty_Edit" then
if steps:GetDescription() then
self:settext(steps:GetDescription());
else
self:settext("edit");
end
self:zoom(0.5);
end
end
end;
};
LoadFont("_determination mono 24px") .. {
InitCommand=cmd(Center;zoom,2;settext,"Hello");
};
LoadFont("common normal") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y+102;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
awesome = psssss:GetPeakComboAward()
self:settext(awesome)
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y-52;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
awesome = psssss:GetStageAward()
if awesome then
self:rainbow()
else
self:stopeffect()
end
self:settext(THEME:GetString( "StageAward", ToEnumShortString( awesome ) ))
end;
};
LoadFont("common edit") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y-66;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
awesome = psssss:GetStageAward()
if awesome then
self:y(SCREEN_CENTER_Y-66)
self:rainbow()
else
self:stopeffect()
self:y(SCREEN_CENTER_Y-59)
end
local profile = PROFILEMAN:GetProfile(PLAYER_1);
local name = profile:GetDisplayName();
if GAMESTATE:IsHumanPlayer(PLAYER_1) then
if name then
self:settext(name)
elseif GAMESTATE:IsHumanPlayer(PLAYER_1) then
self:settext("P1 guy")
end
else
self:settext("Bad guy")
end
end;
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25);
BeginCommand=function(self)
self:visible(GAMESTATE:ShowW1())
end;
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if frame1 then
self:setstate(0*1)
else
self:setstate(0)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W1"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[1]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
----{W1,W2,W3,W4,W5,miss,W1+W2+W3+W4+W5,held,mine,maxcombo,letgo}
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*1);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(2*1)
else
self:setstate(1)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W2"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
if percent < 100 then
percent = percent + 1
animetedP1 = {P1Stat[1]*percent/100,P1Stat[2]*percent/100,P1Stat[3]*percent/100,P1Stat[4]*percent/100,P1Stat[5]*percent/100,P1Stat[6]*percent/100,P1Stat[7]*percent/100,P1Stat[8]*percent/100,P1Stat[9]*percent/100,P1Stat[10]*percent/100,P1Stat[11]*percent/100}
animetedP2 = {P2Stat[1]*percent/100,P2Stat[2]*percent/100,P2Stat[3]*percent/100,P2Stat[4]*percent/100,P2Stat[5]*percent/100,P2Stat[6]*percent/100,P2Stat[7]*percent/100,P2Stat[8]*percent/100,P2Stat[9]*percent/100,P2Stat[10]*percent/100,P2Stat[11]*percent/100}
else
animetedP2 = P2Stat
animetedP1 = P1Stat
end
numberr = animetedP1[2]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*2);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(2*2)
else
self:setstate(2)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W3"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[3]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*3);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(3*2)
else
self:setstate(3)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W4"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[4]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*2);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(2*2)
else
self:setstate(2)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W3"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[3]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*4);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(4*2)
else
self:setstate(4)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W5"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[5]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*2);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(2*2)
else
self:setstate(2)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W3"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[3]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*5);
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud1) );
if self:GetNumStates() == 12 then
frame1 = true
else
frame1 = false
end
if frame1 then
self:setstate(5*2)
else
self:setstate(5)
end
end;
};
};
Def.ActorFrame{
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_Miss"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[6]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:settext("Tap")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[7]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*1);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:settext("Held")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[8]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*2);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:settext("Mine")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[9]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*3);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:settext("MaxCombo")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[10]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*4);
BeginCommand=function(self)
self:diffuse(color("#ff5555"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
self:settext("LetitGO")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP1[11]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-220;wag;effectmagnitude,0,-45,0;effectperiod,math.random(15,25);effectoffset,math.random(0,5));
OnCommand=function(self)
if Isbattle then
self:sleep(3)
self:decelerate(1)
self:x(SCREEN_CENTER_X-25)
self:zoom(0.35)
self:y(150)
end
end;
LoadActor(GradeforP1)..{
InitCommand=cmd(y,SCREEN_CENTER_Y-150;diffusealpha,0.45;zoom,1.25*1.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
if GradeforP1 == "Tor 4x2.png" then
self:zoom(0.5*1.5)
end
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
Gade = psssss:GetGrade()
self:pause();
----------------------Fantastic
if Gade == "Grade_Tier01" then
self:setstate(0)
elseif Gade == "Grade_Tier02" then
self:setstate(1)
elseif Gade == "Grade_Tier03" then
self:setstate(2)
elseif Gade == "Grade_Tier04" then
self:setstate(3)
elseif Gade == "Grade_Tier05" then
self:setstate(4)
elseif Gade == "Grade_Tier06" then
self:setstate(5)
elseif Gade == "Grade_Tier07" then
self:setstate(6)
else
self:setstate(7)
end
end;
};
LoadActor(GradeforP1)..{
InitCommand=cmd(y,SCREEN_CENTER_Y-150;z,20;zoom,1.25);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
if GradeforP1 == "Tor 4x2.png" then
self:zoom(0.5)
end
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_1)
Gade = psssss:GetGrade()
self:pause();
----------------------Fantastic
if Gade == "Grade_Tier01" then
self:setstate(0)
elseif Gade == "Grade_Tier02" then
self:setstate(1)
elseif Gade == "Grade_Tier03" then
self:setstate(2)
elseif Gade == "Grade_Tier04" then
self:setstate(3)
elseif Gade == "Grade_Tier05" then
self:setstate(4)
elseif Gade == "Grade_Tier06" then
self:setstate(5)
elseif Gade == "Grade_Tier07" then
self:setstate(6)
else
self:setstate(7)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-220;wag;effectmagnitude,0,-45,0;effectperiod,math.random(15,25);effectoffset,math.random(0,5));
OnCommand=function(self)
self:visible(Isbattle)
if Isbattle then
self:zoom(0)
self:sleep(3)
self:decelerate(1)
self:zoom(1)
end
end;
Def.ActorFrame{
OnCommand=cmd(diffuse,color("#FFFFFF68"));
LoadFont("_special elite 108px") .. {
InitCommand=cmd(y,SCREEN_CENTER_Y-150;diffusealpha,0.45;zoom,1*1.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
if percentP1 > percentP2 then
self:settext(P1Sc+1)
self:diffuse(color("#FFFFFF68"))
self:rainbowscroll(true)
else
self:settext(P1Sc)
self:diffuse(color("#FF8800"))
self:rainbowscroll(false)
end
end;
};
};
LoadFont("_special elite 108px") .. {
InitCommand=cmd(y,SCREEN_CENTER_Y-150;z,20;zoom,1);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_1))
end;
BeginCommand=function(self)
if percentP1 > percentP2 then
self:settext(P1Sc+1)
self:diffuse(color("#FFFFFF"))
self:rainbowscroll(true)
else
self:settext(P1Sc)
self:diffuse(color("#FF8800"))
self:rainbowscroll(false)
end
end;
};
};
};
----------------------------------------------
-------------P2-------------------------------
----------------------------------------------
t[#t+1] = Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-100);
OnCommand=cmd(playcommand,'loop');
loopCommand=function(self)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
psssss2 = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
if psssss2:FullCombo() then
nep = nep + 0.02
whatx2 = math.random(-vib,vib)
whaty2 = math.random(-vib,vib)
self:x(SCREEN_CENTER_X-100+whatx2)
self:y(whaty2)
if nep >= 16.188 then
vib = vib - 1;
end
end
elseif GAMESTATE:IsWinner(PLAYER_1) then
nep = nep + 0.02
if nep >= 2.249 then
vib = vib - 1;
whatx2 = math.random(-vib,vib)
whaty2 = math.random(-vib,vib)
self:x(SCREEN_CENTER_X-100+whatx2)
self:y(whaty2)
end
self:sleep(0.02)
self:queuecommand('loop')
end
end;
LoadActor("hrror.png") .. {
InitCommand=cmd(Center;zoom,0.5;cropright,0.5);
OnCommand=function(self)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
self:player(1)
end
self:diffusetopedge(PlayerColor(PLAYER_2))
local steps = GAMESTATE:GetCurrentSteps(PLAYER_2)
local meter = steps:GetDifficulty()
if meter then
if meter == "Difficulty_Beginner" then
self:diffusebottomedge(color("#FFAAAA"))
elseif meter == "Difficulty_Easy" then
self:diffusebottomedge(color("#55ff55"))
elseif meter == "Difficulty_Medium" then
self:diffusebottomedge(color("#fFff22"))
elseif meter == "Difficulty_Hard" then
self:diffusebottomedge(color("#ff4444"))
elseif meter == "Difficulty_Challenge" then
self:diffusebottomedge(color("#CCCCff"))
elseif meter == "Difficulty_Edit" then
self:diffusebottomedge(color("#AAAAAA"))
end
end
end;
};
LoadFont("_8-bit madness 72px")..{
InitCommand=cmd(x,SCREEN_CENTER_X-169;y,SCREEN_CENTER_Y+150;zoom,0.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(PLAYER_2)
local meter = steps:GetMeter()
if meter then
if meter == 1943951546 then
self:settext("??")
self:zoom(0.4)
elseif meter >= 10 then
self:zoom(0.4)
self:settext(meter)
elseif meter >= 100 then
self:zoom(0.25)
self:settext(meter)
elseif meter >= 1000 then
self:zoom(0.15)
self:settext(meter)
else
self:settext(meter)
self:zoom(0.5)
end
end
end;
};
LoadFont("_determination mono 24px") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-230;y,SCREEN_CENTER_Y+153;zoom,0.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(PLAYER_2)
local meter = steps:GetDifficulty()
if meter then
if meter == "Difficulty_Beginner" then
self:settext("Beginer");
self:zoom(0.8);
elseif meter == "Difficulty_Easy" then
self:settext("Easy");
self:zoom(0.8);
elseif meter == "Difficulty_Medium" then
self:settext("Normal");
self:zoom(0.8);
elseif meter == "Difficulty_Hard" then
self:settext("Hard");
self:zoom(0.8);
elseif meter == "Difficulty_Challenge" then
self:settext("Expert");
self:zoom(0.7);
elseif meter == "Difficulty_Edit" then
if steps:GetDescription() then
self:settext(steps:GetDescription());
else
self:settext("edit");
end
self:zoom(0.5);
end
end
end;
};
LoadFont("_determination mono 24px") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-105;y,SCREEN_CENTER_Y+152;zoom,0.4);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
flowey = psssss:GetScore()
frisk = FormatPercentScore(psssss:GetPercentDancePoints())
self:settext(flowey.."\n"..frisk)
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y+102;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
awesome = psssss:GetPeakComboAward()
self:settext(awesome)
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y-52;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
awesome = psssss:GetStageAward()
if awesome then
self:rainbow()
else
self:stopeffect()
end
self:settext(THEME:GetString( "StageAward", ToEnumShortString( awesome ) ))
end;
};
LoadFont("common edit") .. {
InitCommand=cmd(x,SCREEN_CENTER_X-167;y,SCREEN_CENTER_Y-66;zoom,0.75);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
awesome = psssss:GetStageAward()
if awesome then
self:y(SCREEN_CENTER_Y-66)
self:rainbow()
else
self:stopeffect()
self:y(SCREEN_CENTER_Y-59)
end
local profile = PROFILEMAN:GetProfile(PLAYER_2);
local name = profile:GetDisplayName();
if GAMESTATE:IsHumanPlayer(PLAYER_2) then
if name then
self:settext(name)
elseif GAMESTATE:IsHumanPlayer(PLAYER_2) then
self:settext("P2 guy")
end
else
self:settext("Bad guy")
end
end;
};
Def.ActorFrame{
OnCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25;horizalign,right);
BeginCommand=function(self)
self:visible(GAMESTATE:ShowW1())
end;
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if frame2 then
self:setstate(0*2)
else
self:setstate(0)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W1"])
self:visible(GAMESTATE:ShowW1())
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[1]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*1);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W2"])
end;
Def.ActorFrame{
OnCommand=cmd(horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if self:GetNumStates() == 12 then
frame2 = true
else
frame2 = false
end
if frame2 then
self:setstate(1*2)
else
self:setstate(1)
end
end;
};
};
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[2]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
OnCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*2;horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if frame2 then
self:setstate(2*2)
else
self:setstate(2)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*2);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W3"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[3]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
OnCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*3;horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if frame2 then
self:setstate(3*2)
else
self:setstate(3)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*3);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W4"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[4]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
OnCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*4;horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if frame2 then
self:setstate(4*2)
else
self:setstate(4)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*4);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_W5"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[5]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
OnCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*5;horizalign,right);
Def.Sprite{
InitCommand=cmd(zoom,0.30);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:pause();
self:Load( THEME:GetPathG("", "_judgmentsSomechai/" .. jud2) );
if frame2 then
self:setstate(5*2)
else
self:setstate(5)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-190;y,SCREEN_CENTER_Y-25+20*5);
BeginCommand=function(self)
self:diffuse(GameColor.Judgment["JudgmentLine_Miss"])
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[6]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:settext("Tap")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[7]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*1);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:settext("Held")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[8]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*2);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:settext("Mine")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[9]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*3);
BeginCommand=function(self)
self:diffuse(color("#cccccc"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:settext("MaxCombo")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[10]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-95;y,SCREEN_CENTER_Y-25+20*4);
BeginCommand=function(self)
self:diffuse(color("#ff5555"))
end;
LoadFont("common normal") .. {
InitCommand=cmd(x,-55;zoom,0.65;horizalign,left);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
self:settext("LetitGO")
end;
};
LoadFont("common normal") .. {
InitCommand=cmd(x,20;zoom,0.65);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
self:playcommand("neptune");
end;
neptuneCommand=function(self)
numberr = animetedP2[11]
realnumis = string.format("%.0f",numberr)
if numberr == 0 then helo = "000"; elseif numberr < 10 then helo = "000"; elseif numberr < 100 then helo = "00"; elseif numberr < 1000 then helo = "0"; else helo = ""; end
self:settext(helo..realnumis)
if numberr == 0 then self:AddAttribute(0, {Length=4, Diffuse=color("#777777")}); elseif numberr < 10 then self:AddAttribute(0, {Length=3, Diffuse=color("#777777")}); elseif numberr < 100 then self:AddAttribute(0, {Length=2, Diffuse=color("#777777")}); elseif numberr < 1000 then self:AddAttribute(0, {Length=1, Diffuse=color("#777777")}); else self:AddAttribute(0, {Length=0, Diffuse=color("#777777")}); end
--You mad bro
self:sleep(0.02)
self:queuecommand('neptune')
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-220+110;wag;effectmagnitude,0,45,0;effectperiod,math.random(15,25);effectoffset,math.random(0,5));
OnCommand=function(self)
if Isbattle then
self:sleep(3)
self:decelerate(1)
self:x(125)
self:zoom(0.35)
self:y(150)
end
end;
LoadActor(GradeforP2)..{
InitCommand=cmd(y,SCREEN_CENTER_Y-150;diffusealpha,0.45;zoom,1.25*1.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
if GradeforP2 == "Tor 4x2.png" then
self:zoom(0.5*1.5)
end
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
Gade = psssss:GetGrade()
self:pause();
----------------------Fantastic
if Gade == "Grade_Tier01" then
self:setstate(0)
elseif Gade == "Grade_Tier02" then
self:setstate(1)
elseif Gade == "Grade_Tier03" then
self:setstate(2)
elseif Gade == "Grade_Tier04" then
self:setstate(3)
elseif Gade == "Grade_Tier05" then
self:setstate(4)
elseif Gade == "Grade_Tier06" then
self:setstate(5)
elseif Gade == "Grade_Tier07" then
self:setstate(6)
else
self:setstate(7)
end
end;
};
LoadActor(GradeforP2)..{
InitCommand=cmd(y,SCREEN_CENTER_Y-150;z,20;zoom,1.25);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
if GradeforP2 == "Tor 4x2.png" then
self:zoom(0.5)
end
psssss = STATSMAN:GetPlayedStageStats(1):GetPlayerStageStats(PLAYER_2)
Gade = psssss:GetGrade()
self:pause();
----------------------Fantastic
if Gade == "Grade_Tier01" then
self:setstate(0)
elseif Gade == "Grade_Tier02" then
self:setstate(1)
elseif Gade == "Grade_Tier03" then
self:setstate(2)
elseif Gade == "Grade_Tier04" then
self:setstate(3)
elseif Gade == "Grade_Tier05" then
self:setstate(4)
elseif Gade == "Grade_Tier06" then
self:setstate(5)
elseif Gade == "Grade_Tier07" then
self:setstate(6)
else
self:setstate(7)
end
end;
};
};
Def.ActorFrame{
InitCommand=cmd(x,SCREEN_CENTER_X-220+110;wag;effectmagnitude,0,-45,0;effectperiod,math.random(15,25);effectoffset,math.random(0,5));
OnCommand=function(self)
self:visible(Isbattle)
if Isbattle then
self:zoom(0)
self:sleep(3)
self:decelerate(1)
self:zoom(1)
end
end;
Def.ActorFrame{
OnCommand=cmd(diffuse,color("#FFFFFF68"));
LoadFont("_special elite 108px") .. {
InitCommand=cmd(y,SCREEN_CENTER_Y-150;diffusealpha,0.45;zoom,1*1.5);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
if percentP1 < percentP2 then
self:settext(P2Sc+1)
self:diffuse(color("#FFFFFF68"))
self:rainbowscroll(true)
else
self:settext(P2Sc)
self:diffuse(color("#FF880068"))
end
end;
};
};
LoadFont("_special elite 108px") .. {
InitCommand=cmd(y,SCREEN_CENTER_Y-150;z,20;zoom,1);
OnCommand=function(self)
self:visible(GAMESTATE:IsPlayerEnabled(PLAYER_2))
end;
BeginCommand=function(self)
if percentP1 < percentP2 then
self:settext(P2Sc+1)
self:diffuse(color("#FFFFFF"))
self:rainbowscroll(true)
else
self:settext(P2Sc)
self:diffuse(color("#FF8800"))
end
end;
};
};
};
--Alll rave STUFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF--
t[#t+1] = Def.ActorFrame{
InitCommand=cmd();
OnCommand=cmd(playcommand,'loop');
loopCommand=function(self)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
else
if nep >= 2.249 then
self:x(whatx)
self:y(whaty)
end
self:sleep(0.02)
self:queuecommand('loop')
end
end;
LoadActor("Lose")..{
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y+50;zoom,2);
OnCommand=function(self)
if GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
self:diffusealpha(0)
else
self:diffusealpha(0)
self:zoom(5)
self:sleep(2.249-0.25)
self:linear(0.25)
self:zoom(2)
if GAMESTATE:IsWinner(PLAYER_1) then
self:diffuse(PlayerColor(PLAYER_2))
self:addx(162.5555)
elseif GAMESTATE:IsWinner(PLAYER_2) then
self:diffuse(PlayerColor(PLAYER_1))
self:addx(-162.5555)
else
self:diffusealpha(0)
end
end
--+162.5555
end;
};
};
if ShowStandardDecoration("GraphDisplay") and GAMESTATE:GetPlayMode() ~= "PlayMode_Rave" then
for pn in ivalues(GAMESTATE:GetHumanPlayers()) do
t[#t+1] = StandardDecorationFromTable( "GraphDisplay" .. ToEnumShortString(pn), GraphDisplay(pn) );
end
end
t[#t+1] = StandardDecorationFromFileOptional("SongInformation","SongInformation") .. {
BeginCommand=function(self)
local SongOrCourse;
if GAMESTATE:GetCurrentSong() then
SongOrCourse = GAMESTATE:GetCurrentSong();
elseif GAMESTATE:GetCurrentCourse() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
else
return
end
if SongOrCourse:HasBanner() then
self:visible(false);
else
self:visible(true);
end
end;
SetCommand=function(self)
local c = self:GetChildren();
local SongOrCourse;
if GAMESTATE:GetCurrentSong() then
SongOrCourse = GAMESTATE:GetCurrentSong();
c.TextTitle:settext( SongOrCourse:GetDisplayMainTitle() or nil );
c.TextSubtitle:settext( SongOrCourse:GetDisplaySubTitle() or nil );
c.TextArtist:settext( SongOrCourse:GetDisplayArtist() or nil );
if SongOrCourse:GetDisplaySubTitle() == "" then
c.TextTitle:visible(true);
c.TextTitle:y(-16.5/2);
c.TextSubtitle:visible(false);
c.TextSubtitle:y(0);
c.TextArtist:visible(true);
c.TextArtist:y(18/2);
else
c.TextTitle:visible(true);
c.TextTitle:y(-16.5);
c.TextSubtitle:visible(true);
c.TextSubtitle:y(0);
c.TextArtist:visible(true);
c.TextArtist:y(18);
end
-- self:playcommand("Tick");
elseif GAMESTATE:GetCurrentCourse() then
SongOrCourse = GAMESTATE:GetCurrentCourse();
c.TextTitle:settext( SongOrCourse:GetDisplayMainTitle() or nil );
c.TextSubtitle:settext( SongOrCourse:GetDisplaySubTitle() or nil );
c.TextArtist:settext( SongOrCourse:GetDisplayArtist() or nil );
-- self:playcommand("Tick");
else
SongOrCourse = nil;
c.TextTitle:settext("");
c.TextSubtitle:settext("");
c.TextArtist:settext("");
self:playcommand("Hide")
end
end;
-- OnCommand=cmd(playcommand,"Set");
CurrentSongChangedMessageCommand=cmd(playcommand,"Set");
CurrentCourseChangedMessageCommand=cmd(playcommand,"Set");
DisplayLanguageChangedMessageCommand=cmd(playcommand,"Set");
};
--t[#t+1] = StandardDecorationFromFileOptional("LifeDifficulty","LifeDifficulty");
--t[#t+1] = StandardDecorationFromFileOptional("TimingDifficulty","TimingDifficulty");
t[#t+1] = StandardDecorationFromFileOptional("GameType","GameType");
t[#t+1] = Def.ActorFrame {
Condition=GAMESTATE:HasEarnedExtraStage() and GAMESTATE:IsExtraStage() and not GAMESTATE:IsExtraStage2();
InitCommand=cmd(draworder,105);
LoadActor( THEME:GetPathS("ScreenEvaluation","try Extra1" ) ) .. {
Condition=THEME:GetMetric( Var "LoadingScreen","Summary" ) == false;
OnCommand=cmd(play);
};
LoadActor( THEME:GetPathG("ScreenStageInformation","Stage extra1" ) ) .. {
Condition=THEME:GetMetric( Var "LoadingScreen","Summary" ) == false;
InitCommand=cmd(Center);
OnCommand=cmd(diffusealpha,0;zoom,0.85;bounceend,1;zoom,1;diffusealpha,1;sleep,0;glow,Color("White");decelerate,1;glow,Color("Invisible");smooth,0.35;zoom,0.25;y,SCREEN_BOTTOM-72);
};
};
t[#t+1] = Def.ActorFrame {
Condition=GAMESTATE:HasEarnedExtraStage() and not GAMESTATE:IsExtraStage() and GAMESTATE:IsExtraStage2();
InitCommand=cmd(draworder,105);
LoadActor( THEME:GetPathS("ScreenEvaluation","try Extra2" ) ) .. {
Condition=THEME:GetMetric( Var "LoadingScreen","Summary" ) == false;
OnCommand=cmd(play);
};
LoadActor( THEME:GetPathG("ScreenStageInformation","Stage extra2" ) ) .. {
Condition=THEME:GetMetric( Var "LoadingScreen","Summary" ) == false;
InitCommand=cmd(Center);
OnCommand=cmd(diffusealpha,0;zoom,0.85;bounceend,1;zoom,1;diffusealpha,1;sleep,0;glow,Color("White");decelerate,1;glow,Color("Invisible");smooth,0.35;zoom,0.25;y,SCREEN_BOTTOM-72);
};
};
return t
|
GateActions("Highspeed")
GateActions["highspeed_write"] = {
name = "Highspeed Write",
inputs = { "Clk", "Memory", "Address", "Data" },
inputtypes = { "NORMAL", "WIRELINK", "NORMAL", "NORMAL" },
output = function(gate, Clk, Memory, Address, Data)
if not Memory then return 0 end
if not Memory.WriteCell then return 0 end
if Clk <= 0 then return 0 end
Address = math.floor(Address)
if Address < 0 then return 0 end
return Memory:WriteCell(Address, Data) and 1 or 0
end,
label = function(Out, Clk, Memory, Address, Data)
return string.format("Clock:%s Memory:%s Address:%s Data:%s = %s", Clk, Memory, Address, Data, Out)
end
}
GateActions["highspeed_read"] = {
name = "Highspeed Read",
inputs = { "Clk", "Memory", "Address" },
inputtypes = { "NORMAL", "WIRELINK", "NORMAL" },
output = function(gate, Clk, Memory, Address)
if not Memory then return 0 end
if not Memory.ReadCell then return 0 end
if Clk <= 0 then return 0 end
Address = math.floor(Address)
if Address < 0 then return 0 end
return Memory:ReadCell(Address) or 0
end,
label = function(Out, Clk, Memory, Address)
return string.format("Clock:%s Memory:%s Address:%s = %s", Clk, Memory, Address, Out)
end
}
GateActions()
|
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local DT = E:GetModule('DataTexts')
--Lua functions
local join = string.join
--WoW API / Variables
local BASE_MOVEMENT_SPEED = BASE_MOVEMENT_SPEED
local GetUnitSpeed = GetUnitSpeed
local IsFalling = IsFalling
local IsFlying = IsFlying
local IsSwimming = IsSwimming
local displayNumberString = ''
local movementSpeedText = L["Mov. Speed:"]
local beforeFalling
local lastPanel
local function OnEvent(self)
local _, runSpeed, flightSpeed, swimSpeed = GetUnitSpeed("player")
local speed = runSpeed
if (IsSwimming("player")) then
speed = swimSpeed
elseif (IsFlying("player")) then
speed = flightSpeed
end
if (IsFalling("player")) then
speed = beforeFalling or speed
else
beforeFalling = speed
end
self.text:SetFormattedText(displayNumberString, movementSpeedText, speed/BASE_MOVEMENT_SPEED*100)
lastPanel = self
end
local function ValueColorUpdate(hex)
displayNumberString = join("", "%s ", hex, "%.0f%%|r")
if lastPanel ~= nil then
OnEvent(lastPanel)
end
end
E.valueColorUpdateFuncs[ValueColorUpdate] = true
DT:RegisterDatatext('MovementSpeed', {"UNIT_STATS", "UNIT_AURA", "ACTIVE_TALENT_GROUP_CHANGED", "PLAYER_TALENT_UPDATE", "UNIT_SPELL_HASTE"}, OnEvent, nil, nil, nil, nil, STAT_MOVEMENT_SPEED)
|
local rpc = {}
local list = {
ID_CLIENT_JOIN = 1,
ID_UPDATE_DATA = 2,
ID_SERVER_JOIN = 3,
ID_SERVER_QUIT = 4,
ID_STREAMED_OUT = 5,
ID_CLIENT_MESSAGE = 6,
ID_CLIENT_COMMAND = 7,
ID_UPDATE_TIME = 8,
ID_UPDAET_WEATHER = 9,
ID_UPDATE_POSITION = 10,
ID_UPDATE_INTERIOR = 11,
ID_UPDATE_SKIN = 12,
ID_STREAMED_IN = 13,
ID_TOGGLE_SPECTATE = 14,
ID_SPECTATE_PLAYER = 15,
ID_UPDATE_CAMERA_POS = 16,
ID_UPDATE_CAMERA_ROT = 17,
ID_UPDATE_SPAWN = 18,
ID_SHOW_DIALOG = 19,
ID_DIALOG_RESPONSE = 20,
ID_RESTORE_CAMERA = 21,
ID_UPDATE_CONTROL = 22,
ID_UPDATE_ROTATION = 23,
ID_OBJECT_CREATE = 24,
ID_OBJECT_DELETE = 25,
}
rpc.list = list
local function call_client_join(bs, address, port)
local nickname = bs:read(BS_STRING, bs:read(BS_UINT8))
local authkey = bs:read(BS_STRING, bs:read(BS_UINT8))
local clientver = bs:read(BS_STRING, bs:read(BS_UINT8))
local free = clients.find_free()
if free == 0 then
packets.send(packets["list"]["ID_NO_FREE_INCOMING_CONNECTIONS"], nil, address, port)
return -- all slots are in use and no free slots are available
end
local client = clients.by_address(address, port)
if client ~= 0 then return end -- already connected (/==/)
if clientver ~= "1.0.0" then
local data = bstream.new(); data:write(BS_UINT8, 1)
packets.send(packets["list"]["ID_CONNECTION_ATTEMPT_FAILED"], data, address, port)
return -- client version is incorrect
end
local client = clients.by_nickname(nickname)
if client ~= 0 or not nickname:match('^[A-Za-z0-9_%-%.]+$') or #nickname < 3 or #nickname > 25 then
local data = bstream.new(); data:write(BS_UINT8, 2)
packets.send(packets["list"]["ID_CONNECTION_ATTEMPT_FAILED"], data, address, port)
return -- nickname with this nickname is already connected or nickname is bad
end
local data = bstream.new()
data:write(BS_UINT8, #config.hostname)
data:write(BS_STRING, config.hostname)
packets.send(packets["list"]["ID_CONNECTION_REQUEST_ACCEPTED"], data, address, port, SNET_SYSTEM_PRIORITY)
clients.list[free] = { -- add new client to clients list and send response to client
nickname = nickname,
ping = 0, score = 0,
address = address,
port = port, skin = 0,
gamestate = 1, -- onfoot
stream = {
players = {},
objects = {},
},
pos = {0, 0, 0},
quat = {0, 0, 0, 0},
vec = {0, 0, 0}, rot = 0,
world = 0, interior = 0,
last_ping = 0, last_sync = 0,
health = 100, armour = 0,
last_dialog = 0, keys = 0,
vars = {},
}
local udata = bstream.new()
udata:write(BS_UINT16, free)
udata:write(BS_UINT8, #nickname)
udata:write(BS_STRING, nickname)
functions.getPlayerPointer(free):setTime(config.time)
functions.getPlayerPointer(free):setWeather(config.weather)
clients.foreach(function(index, value)
local data = bstream.new()
data:write(BS_UINT16, index)
data:write(BS_UINT8, #value.nickname)
data:write(BS_STRING, value.nickname)
rpc.send(list["ID_SERVER_JOIN"], data, address, port)
if index ~= free then
rpc.send(list["ID_SERVER_JOIN"], udata, value.address, value.port)
end
end)
console_log("[SERVER] New client connected: "..nickname.." [" .. free .. "] ("..address..":"..port..")")
inner_function("onPlayerConnect", true, true, free) -- callback onPlayerConnect [PlayerID]
end
function rpc.process(id, bs, address, port)
if id == list["ID_CLIENT_JOIN"] then
call_client_join(bs, address, port)
elseif id == list["ID_CLIENT_MESSAGE"] then
local client = clients.by_address(address, port)
if client ~= 0 then
local text = bs:read(BS_STRING, bs:read(BS_UINT8))
local result = inner_function("onPlayerText", true, true, client, text) -- callback onPlayerText [PlayerID] [Text]
if not result then functions.sendMessage(0xFFFFFFFF, string.format("* %s[%s]: {F5F5F5}%s", functions.getPlayerPointer(client):getNickname(), client, text)) end
end
elseif id == list["ID_CLIENT_COMMAND"] then
local client = clients.by_address(address, port)
if client ~= 0 then
local text = bs:read(BS_STRING, bs:read(BS_UINT8))
local result = inner_function("onPlayerCommand", true, true, client, text) -- callback onPlayerCommand [PlayerID] [Text]
if not result then functions.getPlayerPointer(client):sendMessage(0xC9C9C9FF, "* Unknown command, type /help to show commands list.") end
end
elseif id == list["ID_DIALOG_RESPONSE"] then
local client = clients.by_address(address, port)
if client == 0 then return end
local id = bs:read(BS_UINT16)
if clients.list[client].last_dialog ~= id then return end
local btn = bs:read(BS_UINT8)
local selected = bs:read(BS_UINT8)
local inputtext = bs:read(BS_STRING, bs:read(BS_UINT8))
inner_function("onDialogResponse", true, true, client, id, btn, selected, inputtext)
-- callback onDialogRespose [PlayerID] [DialogID] [Button] [Selected] [Input]
end
end
function rpc.send(id, bs, address, port)
if not bs then bs = bstream.new() end
bs = bstream.new(bs.bytes) -- clone bstream
bs.write_ptr = 1; bs:write(BS_BOOLEAN, true)
server:send(id, bs, SNET_SYSTEM_PRIORITY, address, port)
end
return rpc |
--journalmod.lua
local loaded = false
function JOURNALMOD_ON_INIT(addon, frame)
if not loaded then
loaded = true
local function setupHook(newFunction, hookedFunctionStr)
local storeOldFunc = hookedFunctionStr .. "_OLD"
if _G[storeOldFunc] == nil then
_G[storeOldFunc] = _G[hookedFunctionStr]
end
_G[hookedFunctionStr] = newFunction
end
setupHook(ADVENTURE_BOOK_CHECK_STATE_FILTER_HOOKED, "ADVENTURE_BOOK_CHECK_STATE_FILTER")
setupHook(SCR_QUEST_SHOW_ZONE_LIST_HOOKED, "SCR_QUEST_SHOW_ZONE_LIST")
setupHook(ADVENTURE_BOOK_QUEST_CREATE_MAP_QUEST_TREE_HOOKED, "ADVENTURE_BOOK_QUEST_CREATE_MAP_QUEST_TREE")
setupHook(IS_QUEST_NEED_TO_SHOW_HOOKED, "IS_QUEST_NEED_TO_SHOW")
setupHook(ADVENTURE_BOOK_QUEST_DROPLIST_INIT_HOOKED, "ADVENTURE_BOOK_QUEST_DROPLIST_INIT")
if ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE_OLD == nil then
ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE_OLD = ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE
end
ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE = ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE_HOOKED
end
end
function ADVENTURE_BOOK_CHECK_STATE_FILTER_HOOKED(frame, collectionInfo, searchText, collectionClass, collection)
local collectionStateDropList = GET_CHILD_RECURSIVELY(frame, 'collectionStateDropList');
local stateIndex = collectionStateDropList:GetSelItemIndex();
if stateIndex == 1 and collectionInfo.view ~= 2 then -- 완성
return false;
elseif stateIndex == 2 and collectionInfo.view ~= 0 then -- 미확인
return false;
elseif stateIndex == 3 and collectionInfo.view ~= 1 then -- 미완성
return false;
end
if searchText ~= nil and searchText ~= '' then
local collectionName = ADVENTURE_BOOK_COLLECTION_REPLACE_NAME(collectionInfo.name);
searchText = string.lower(searchText);
collectionName = dic.getTranslatedStr(collectionName)
collectionName = string.lower(collectionName);
local desc = GET_COLLECTION_MAGIC_DESC(collectionClass.ClassID)
desc = string.lower(dic.getTranslatedStr(desc))
if string.find(collectionName, searchText) == nil and string.find(desc, searchText) == nil then
local collectionList = session.GetMySession():GetCollection()
local curCount, maxCount = GET_COLLECTION_COUNT(collectionClass.ClassID, collectionList:Get(collectionClass.ClassID))
for num = 1, maxCount do
local itemName = TryGetProp(collectionClass, "ItemName_" .. num)
if itemName == nil or itemName == "None" then
return false
end
itemName = dic.getTranslatedStr(GetClass("Item", itemName).Name)
itemName = string.lower(itemName)
if string.find(itemName, searchText) ~= nil then
return true
end
end
return false;
end
end
return true;
end
function ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_COMPLETE_HOOKED(mapClsID)
local t = ADVENTURE_BOOK_MAP_CONTENT.IS_COMPLETE(mapClsID)
if t == true or t == 1 then
return false;
end
t = ADVENTURE_BOOK_MAP_CONTENT.IS_NOT_DETECTED(mapClsID)
if t == true or t == 1 then
return false;
else
return true;
end
end
function SCR_QUEST_SHOW_ZONE_LIST_HOOKED(nowframe)
local questList, cnt = GetClassList('QuestProgressCheck');
local topFrame = nowframe:GetTopParentFrame();
local questSearchEdit = GET_CHILD_RECURSIVELY(topFrame, 'questSearchEdit');
local searchText = questSearchEdit:GetText();
local zoneList = {}
searchText = string.lower(searchText)
local pc = GetMyPCObject()
local questCateDrop = GET_CHILD_RECURSIVELY(topFrame, 'questCateDrop')
local questLevelDrop = GET_CHILD_RECURSIVELY(topFrame, 'questLevelDrop')
local questStateDrop = GET_CHILD_RECURSIVELY(topFrame, 'questStateDrop')
local cateIndex = questCateDrop:GetSelItemIndex()
local lvIndex = questLevelDrop:GetSelItemIndex()
local stateIndex = (questStateDrop ~= nil) and questStateDrop:GetSelItemIndex() or 0
for index = 0, cnt - 1 do
local questCls = GetClassByIndexFromList(questList, index);
if table.find(zoneList, questCls.StartMap) == 0 then
if questCls.Level ~= 9999 then
if questCls.Lvup ~= -9999 then
if questCls.PeriodInitialization == 'None' then
local questMode = questCls.QuestMode;
if questMode ~= 'KEYITEM' and questMode ~= 'PARTY' then
--local questCateDrop = GET_CHILD_RECURSIVELY(topFrame, 'questCateDrop');
--local cateIndex = questCateDrop:GetSelItemIndex();
if cateIndex == 0 or (cateIndex == 1 and questCls.QuestMode == 'MAIN') or (cateIndex == 2 and questCls.QuestMode == 'SUB') or (cateIndex == 3 and questCls.QuestMode ~= 'MAIN' and questCls.QuestMode ~= 'SUB') then
--local questLevelDrop = GET_CHILD_RECURSIVELY(topFrame, 'questLevelDrop');
--local lvIndex = questLevelDrop:GetSelItemIndex();
if lvIndex == 0 or math.ceil(questCls.Level / 100) == lvIndex then
if searchText == '' or string.find(string.lower(dic.getTranslatedStr(questCls.Name)), searchText) ~= nil then
local result = SCR_QUEST_CHECK_C(pc, questCls.ClassName)
if stateIndex == 0 or (stateIndex == 1 and result == 'COMPLETE') or (stateIndex == 2 and result ~= 'COMPLETE') then
zoneList[#zoneList + 1] = questCls.StartMap
end
end
end
end
end
end
end
end
end
end
return zoneList
end
function ADVENTURE_BOOK_QUEST_CREATE_MAP_QUEST_TREE_HOOKED(questMapBox, mapCls, isSearchMode)
local quest_tree = questMapBox:CreateOrGetControlSet('quest_tree', 'QUEST_MAP_'..mapCls.ClassID, 0, 0);
local text = quest_tree:GetChild('text');
text:SetText(mapCls.Name);
if isSearchMode == true then
quest_tree = AUTO_CAST(quest_tree);
local EXPAND_ON_IMG = quest_tree:GetUserConfig('EXPAND_ON_IMG');
local expandBtn = GET_CHILD(quest_tree, 'expandBtn');
expandBtn:SetImage(EXPAND_ON_IMG);
quest_tree:SetUserValue('QUEST_MAP_CLASS_NAME', mapCls.ClassName)
quest_tree:SetUserValue('IS_EXPAND', 1)
else
quest_tree:SetUserValue('QUEST_MAP_CLASS_NAME', mapCls.ClassName);
end
return quest_tree;
end
function IS_QUEST_NEED_TO_SHOW_HOOKED(frame, questCls, mapName, searchText)
if mapName ~= nil and questCls.StartMap ~= mapName then
return false;
end
if questCls.Level == 9999 then
return false;
end
if questCls.Lvup == -9999 then
return false;
end
if questCls.PeriodInitialization ~= 'None' then
return false;
end
local questMode = questCls.QuestMode;
if questMode == 'KEYITEM' or questMode == 'PARTY' then
return false;
end
if IS_ADVENTURE_BOOK_EXCEPT_QUEST(questCls.ClassName) == 'YES' then
return false;
end
local questCateDrop = GET_CHILD_RECURSIVELY(frame, 'questCateDrop');
local cateIndex = questCateDrop:GetSelItemIndex();
if cateIndex == 1 and questCls.QuestMode ~= 'MAIN' then -- main
return false;
elseif cateIndex == 2 and questCls.QuestMode ~= 'SUB' then -- sub
return false;
elseif cateIndex == 3 and (questCls.QuestMode == 'MAIN' or questCls.QuestMode == 'SUB') then -- etc
return false;
end
local questLevelDrop = GET_CHILD_RECURSIVELY(frame, 'questLevelDrop');
local lvIndex = questLevelDrop:GetSelItemIndex();
if lvIndex ~= 0 and math.ceil(questCls.Level / 100) ~= lvIndex then
return false;
end
local questStateDrop = GET_CHILD_RECURSIVELY(frame, 'questStateDrop')
local stateIndex = questStateDrop:GetSelItemIndex()
local result = SCR_QUEST_CHECK_C(GetMyPCObject(), questCls.ClassName)
if stateIndex == 1 and result ~= 'COMPLETE' then
return false
elseif stateIndex == 2 and result == 'COMPLETE' then
return false
end
local questname = string.lower(dic.getTranslatedStr(questCls.Name))
searchText = string.lower(searchText)
if searchText == '' or string.find(questname, searchText) ~= nil then
return true
end
local mapname = questCls.StartMap
if mapname and mapname ~= "None" then
local mapnameText = GetClass("Map", mapname).Name
mapnameText = string.lower(dic.getTranslatedStr(mapnameText))
if string.find(mapnameText, searchText) ~= nil then
return true
end
end
return false
end
function ADVENTURE_BOOK_QUEST_DROPLIST_INIT_HOOKED(page_quest)
local questCateDrop = GET_CHILD_RECURSIVELY(page_quest, 'questCateDrop');
if questCateDrop:GetItemCount() > 6 then
return;
end
questCateDrop:ClearItems();
questCateDrop:AddItem(0, ClMsg('PartyShowAll'));
questCateDrop:AddItem(1, ClMsg('MAIN'));
questCateDrop:AddItem(2, ClMsg('SUB'));
questCateDrop:AddItem(3, ClMsg('WCL_Etc'));
local levelText = GET_CHILD_RECURSIVELY(page_quest, 'levelText');
levelText:SetMargin(194, 25, 20, 24);
local questLevelDrop = GET_CHILD_RECURSIVELY(page_quest, 'questLevelDrop');
questLevelDrop:ClearItems();
questLevelDrop:SetMargin(194, 48, 178, 20)
questLevelDrop:SetVisibleLine(7)
questLevelDrop:AddItem(0, ClMsg('Auto_MoDu_BoKi'))
questLevelDrop:AddItem(1, 'Lv.1 ~ Lv.100')
questLevelDrop:AddItem(2, 'Lv.101 ~ Lv.200')
questLevelDrop:AddItem(3, 'Lv.201 ~ Lv.300')
questLevelDrop:AddItem(4, 'Lv.301 ~ Lv.400')
questLevelDrop:AddItem(5, 'Lv.401 ~ Lv.500')
questLevelDrop:AddItem(6, 'Lv.501 ~ Lv.600')
local stateText = page_quest:CreateOrGetControl("richtext", "stateText", 378, 25, 20, 24)
stateText:SetText("@dicID_^*$UI_20170912_002757$*^")
stateText:SetFontName("black_16_b")
local questStateDrop = page_quest:CreateOrGetControl("droplist", "questStateDrop", 378, 48, 178, 20)
tolua.cast(questStateDrop, "ui::CDropList")
questStateDrop:SetSkinName("droplist_normal")
questStateDrop:SetSelectedScp("ADVENTURE_BOOK_QUEST_DROPLIST")
questStateDrop:SetTextAlign("left","center")
questStateDrop:ClearItems()
questStateDrop:SetVisibleLine(3)
questStateDrop:AddItem(0, ClMsg('Auto_MoDu_BoKi'), 0, 0, " ")
questStateDrop:AddItem(1, ClMsg('Complete'), 0, 0, " ")
questStateDrop:AddItem(2, ClMsg('NotComplete'), 0, 0, " ")
end |
assert.Equal(255, 0xff)
assert.Equal(-255, -0xff) |
local depth = {}
while true do
local n = io.read '*n'
if n == nil then
break
end
table.insert(depth, n)
end
local prev = 0
local count = -1 -- first one doesn't count
for _, d in ipairs(depth) do
if d - prev > 0 then
count = count + 1
end
prev = d
end
print(count)
|
-- ... init.lua
require("nvim-web-devicons").setup()
|
return {
name = 'truemedian/extensions',
version = '1.0.0',
description = 'A combination of extensions to the Lua standard libraries and other useful utilities for libraries I use.',
tags = {'lua', 'luvit', 'extension', 'stdlib'},
license = 'MIT',
author = {name = 'Nameless'},
homepage = 'https://github.com/truemedian/lua-extensions',
dependencies = {},
files = {'**.lua'},
}
|
-- Copyright © 2016 Silv3r <[email protected]>
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
name = "Leveling: Victory Road (near Indigo Plateau)"
author = "ananas"
description = [[hehe]]
function onStart()
setMount("Yellow Bicycle")
if getUsablePokemonCount() > 0 then
if getMapName() == "Indigo Plateau Center" then
moveToCell(10,28)
elseif getMapName() == "Indigo Plateau" then
moveToCell(21,31)
elseif getMapName() == "Victory Road Kanto 3F" then
moveToRectangle(46, 19, 47, 22)
end
else
if getMapName() == "Victory Road Kanto 3F" then
moveToCell(46,13)
elseif getMapName() == "Indigo Plateau" then
moveToCell(32,12)
elseif getMapName() == "Indigo Plateau Center" then
talkToNpcOnCell(4, 22)
end
end
end
function onPathAction()
if getUsablePokemonCount() > 0 then
if getMapName() == "Indigo Plateau Center" then
moveToCell(10,28)
elseif getMapName() == "Indigo Plateau" then
moveToCell(21,31)
elseif getMapName() == "Victory Road Kanto 3F" then
moveToRectangle(46, 19, 47, 22)
end
else
if getMapName() == "Victory Road Kanto 3F" then
moveToCell(46,13)
elseif getMapName() == "Indigo Plateau" then
moveToCell(32,12)
elseif getMapName() == "Indigo Plateau Center" then
talkToNpcOnCell(4, 22)
end
end
end
-- poliwrath is effective towards ground and rock.
function onBattleAction()
if isWildBattle() and isOpponentShiny() then
if useItem("Ultra Ball") or useItem("Great Ball") or useItem("Pokeball") then
return
end
end
if getUsablePokemonCount() > 0 then
return attack() or sendUsablePokemon() or run() or sendAnyPokemon()
else
return run() or attack() or sendUsablePokemon() or sendAnyPokemon()
end
end |
local MakePlayerCharacter = require "prefabs/player_common"
local assets = {
Asset( "ANIM", "anim/player_basic.zip" ),
Asset( "ANIM", "anim/player_idles_shiver.zip" ),
Asset( "ANIM", "anim/player_actions.zip" ),
Asset( "ANIM", "anim/player_actions_axe.zip" ),
Asset( "ANIM", "anim/player_actions_pickaxe.zip" ),
Asset( "ANIM", "anim/player_actions_shovel.zip" ),
Asset( "ANIM", "anim/player_actions_blowdart.zip" ),
Asset( "ANIM", "anim/player_actions_eat.zip" ),
Asset( "ANIM", "anim/player_actions_item.zip" ),
Asset( "ANIM", "anim/player_actions_uniqueitem.zip" ),
Asset( "ANIM", "anim/player_actions_bugnet.zip" ),
Asset( "ANIM", "anim/player_actions_fishing.zip" ),
Asset( "ANIM", "anim/player_actions_boomerang.zip" ),
Asset( "ANIM", "anim/player_bush_hat.zip" ),
Asset( "ANIM", "anim/player_attacks.zip" ),
Asset( "ANIM", "anim/player_idles.zip" ),
Asset( "ANIM", "anim/player_rebirth.zip" ),
Asset( "ANIM", "anim/player_jump.zip" ),
Asset( "ANIM", "anim/player_amulet_resurrect.zip" ),
Asset( "ANIM", "anim/player_teleport.zip" ),
Asset( "ANIM", "anim/wilson_fx.zip" ),
Asset( "ANIM", "anim/player_one_man_band.zip" ),
Asset( "ANIM", "anim/shadow_hands.zip" ),
Asset( "SOUND", "sound/sfx.fsb" ),
Asset( "SOUND", "sound/wilson.fsb" ),
Asset( "ANIM", "anim/beard.zip" ),
Asset( "ANIM", "anim/brook.zip" ),
Asset( "ANIM", "anim/ghost_brook_build.zip" ),
}
local prefabs = {
}
-- Custom starting items
local start_inv = {
"swordcane",
"violin",
}
-- When the character is revived from human
local function onbecamehuman(inst)
-- Set speed when loading or reviving from ghost (optional)
inst.components.locomotor.walkspeed = 4
inst.components.locomotor.runspeed = 6
end
-- When loading or spawning the character
local function onload(inst)
inst:ListenForEvent("ms_respawnedfromghost", onbecamehuman)
if not inst:HasTag("playerghost") then
onbecamehuman(inst)
end
end
local function sanityfn(inst)
local x, y, z = inst.Transform:GetWorldPosition()
local delta = 0
local max_rad = 10
local ents = TheSim:FindEntities(x, y, z, max_rad, { "player" }, { "playerghost", "deadbones" })
for i, v in ipairs(ents) do
delta = delta + TUNING.DAPPERNESS_SMALL
end
-- brook is alone
if (delta == 0) then
delta = delta - TUNING.DAPPERNESS_TINY
end
return delta
end
-- This initializes for both the server and client. Tags can be added here.
local common_postinit = function(inst)
-- Minimap icon
inst.MiniMapEntity:SetIcon( "brook.tex" )
-- character tags
inst:AddTag("deadbones")
end
-- This initializes for the server only. Components are added here.
local master_postinit = function(inst)
-- choose which sounds this character will play
inst.soundsname = "woodie"
-- Uncomment if "wathgrithr"(Wigfrid) or "webber" voice is used
--inst.talker_path_override = "dontstarve_DLC001/characters/"
inst.components.health:SetMaxHealth(TUNING.BROOK.health)
inst.components.hunger:SetMax(TUNING.BROOK.hunger)
inst.components.sanity:SetMax(TUNING.BROOK.sanity)
inst.components.combat.damagemultiplier = TUNING.BROOK.damage
inst.components.sanity.custom_rate_fn = sanityfn
-- Food heals halved
local _Eat = inst.components.eater.Eat
function inst.components.eater:Eat( food )
if food.components.edible.healthvalue > 2 then
food.components.edible.healthvalue = food.components.edible.healthvalue/2
end
return _Eat( self, food )
end
-- Insulated from temp changes
inst.components.temperature.inherentinsulation = TUNING.BROOK.coldresist
inst.components.temperature.inherentsummerinsulation = TUNING.BROOK.heatresist
-- Can play violin
inst:AddComponent("sanityaura")
inst.components.sanityaura.aura = 0
inst.OnLoad = onload
inst.OnNewSpawn = onload
end
return MakePlayerCharacter("brook", prefabs, assets, common_postinit, master_postinit, start_inv)
|
--[[============================================================
--=
--= Global Functions
--=
--=-------------------------------------------------------------
--=
--= MyHappyList - manage your AniDB MyList
--= - Written by Marcus 'ReFreezed' Thunström
--= - MIT License (See main.lua)
--=
--==============================================================
assertf, assertarg, check
clamp
cleanupPath
cmdAsync, cmdSync, cmdDetached, cmdCapture, scriptCaptureAsync, scriptRunDetached, isScriptRunning, cmdEscapeArgs, run
compareTables
copyTable
cwdPush, cwdPop
eatSpaces
encodeHtmlEntities
errorf, fileerror
F, formatBytes
findPreviousChar
getColumn
getKeys
getLineNumber
getStored, store, storeItem, getStorage
getStoredEventCallback, getStoredEventCallbackAll, storeEventCallbacks
getTime
getTimezone, getTimezoneOffsetString, getTimezoneOffset
gsub2
handleError, wrapCall
iff
indexOf, itemWith, itemWithAll, indexWith
insertMultiple, removeItem
ipairsr, iprev
isAny
isHost
isInt
isStringMatchingAnyPattern
iterate, arrayIterator
logStart, logEnd, logHeader, log, logprint, logprinterror, logprintOnce
makePrintable
matchLines
newSet
newStringBuilder
openFileExternally, openFileInNotepad, showFileInExplorer
pack
pairsSorted
print, printOnce, printf, printfOnce, printobj
quit, maybeQuit
range
round
serializeLua
setAndInsert, setAndInsertIfNew, unsetAndRemove
sort
sortNatural, compareNatural
splitString
T, getText, getTranslations
tablePathGet, tablePathSet
trim, trimNewlines
unzip
utf8IsValid
updater_getUnzipDir
updater_moveFilesAfterUnzipMain, updater_moveFilesAfterUnzipUpdater
--============================================================]]
require(... .."_filesystem")
require(... .."_wx")
function isStringMatchingAnyPattern(s, patterns)
for _, pat in ipairs(patterns) do
if s:find(pat) then return true end
end
return false
end
-- errorf( [ level=1, ] formatString, ...)
function errorf(level, s, ...)
if type(level) == "number" then
error(F(s, ...), level+1)
else
error(F(level, s, ...), 2)
end
end
-- fileerror( path, contents, position, formatString, ... )
-- fileerror( path, nil, lineNumber, formatString, ... )
function fileerror(path, contents, pos, s, ...)
local ln = contents and getLineNumber(contents, pos) or pos
if type(s) ~= "string" then
s = F("%s:%d: %s", path, ln, tostring(s))
else
s = F("%s:%d: "..s, path, ln, ...)
end
error(s, 2)
end
function handleError(err)
local errWithStack = debug.traceback(tostring(err), 2)
print(errWithStack)
logEnd()
if isApp and not DEBUG then
-- if isApp then -- DEBUG
local dialog = wxTextEntryDialog(
wxNULL,
F(
"%s\n%s\n\n%s: %s\n\n%s:",
T"error_appCrash1", T"error_appCrash2", T"label_logFile", logFilePath, T"label_message"
),
"Error",
errWithStack,
wxOK + wxCENTRE + wxTE_MULTILINE + wxTE_DONTWRAP
)
showModalAndDestroy(dialog)
end
os.exit(1)
end
function wrapCall(f)
return function(...)
local args = pack(...)
local returnValues = nil
xpcall(
function()
returnValues = pack(f(unpack(args, 1, args.n)))
end,
handleError
)
if returnValues then
return unpack(returnValues, 1, returnValues.n)
end
end
end
function getLineNumber(s, pos)
local lineCount = 1
for posCurrent in s:gmatch"()\n" do
if posCurrent < pos then
lineCount = lineCount+1
else
break
end
end
return lineCount
end
do
local values = {}
local oncePrints = {}
local function printArgsToString(...)
local argCount = select("#", ...)
for i = 1, argCount do
values[i] = tostring(select(i, ...))
end
return table.concat(values, "\t", 1, argCount)
end
local function safePrintUtf8(s)
local ok, errPos = utf8IsValid(s)
if not ok then
local errPositions = {}
repeat
errPositions[errPos] = true
ok, errPos = utf8IsValid(s, errPos+1)
until ok
s = s:gsub("()(.)", function(pos, c)
return errPositions[pos] and "?" or c
end)
end
_print(s)
end
function print(...)
local s = printArgsToString(...)
safePrintUtf8(s)
log(s)
end
function printOnce(...)
local s = printArgsToString(...)
if oncePrints[s] then return end
oncePrints[s] = true
safePrintUtf8(s)
log(s)
end
end
function printf(s, ...)
print(s:format(...))
end
function printfOnce(s, ...)
printOnce(s:format(...))
end
-- printobj( ... )
-- Note: Does not write to log.
do
local out = io.stdout
local _tostring = tostring
local function tostring(v)
return (_tostring(v):gsub('^table: ', ''))
end
local function compareKeys(a, b)
return compareNatural(tostring(a), tostring(b))
end
local function _printobj(v, tables)
local vType = type(v)
if vType == "table" then
if tables[v] then
out:write(tostring(v), " ")
return
end
out:write(tostring(v), "{ ")
tables[v] = true
local indices = {}
for i = 1, #v do indices[i] = true end
for _, k in ipairs(sort(getKeys(v), compareKeys)) do
if not indices[k] then
out:write(tostring(k), "=")
_printobj(v[k], tables)
end
end
for i = 1, #v do
out:write(i, "=")
_printobj(v[i], tables)
end
out:write("} ")
elseif vType == "number" then
out:write(F("%g ", v))
elseif vType == "string" then
out:write('"', v:gsub("%z", "\\0"):gsub("\n", "\\n"), '" ')
else
out:write(tostring(v), " ")
end
end
function printobj(...)
for i = 1, select("#", ...) do
if i > 1 then out:write("\t") end
_printobj(select(i, ...), {})
end
out:write("\n")
end
end
do
local logBuffer = {}
local function logEmptyBuffer()
for i, s in ipairs(logBuffer) do
writeLine(logFile, s)
logBuffer[i] = nil
end
end
function logStart(basename)
if logFile then
errorf(2, "Log file already started. (new: '%s', old: '%s')", basename, logFilePath)
end
logFilePath = F("%s/%s.log", DIR_LOGS, basename)
logFile = assert(openFile(logFilePath, "a"))
logEmptyBuffer()
end
function logEnd()
if not logFile then return end
logFile:close()
logFile = nil
end
function logHeader()
log("~~~ MyHappyList ~~~")
log(os.date"%Y-%m-%d %H:%M:%S")
if DEBUG_LOCAL then
print("!! DEBUG (local) !!")
elseif DEBUG then
print("!!!!!! DEBUG !!!!!!")
end
end
-- log( string )
-- log( formatString, ... )
function log(s, ...)
if select("#", ...) > 0 then s = s:format(...) end
if not logFile then
table.insert(logBuffer, s)
return
end
logEmptyBuffer()
writeLine(logFile, s)
end
-- logprint( agent, string )
-- logprint( agent, formatString, ... )
-- agent can be nil.
function logprint(agent, s, ...)
if select("#", ...) > 0 then s = s:format(...) end
local time = getTime()
if agent then
printf("%s.%03d|%s| %s", os.date("%H:%M:%S", time), 1000*(time%1), agent, s)
else
printf("%s.%03d| %s", os.date("%H:%M:%S", time), 1000*(time%1), s)
end
end
-- logprinterror( agent, string )
-- logprinterror( agent, formatString, ... )
-- agent can be nil.
function logprinterror(agent, s, ...)
if select("#", ...) > 0 then s = s:format(...) end
local time = getTime()
-- io.stdout:write("\27[91m") -- Bright red. (No support in Sublime. :/ )
if agent then
printf("%s.%03d|%s| Error: %s", os.date("%H:%M:%S", time), 1000*(time%1), agent, s)
else
printf("%s.%03d| Error: %s", os.date("%H:%M:%S", time), 1000*(time%1), s)
end
-- io.stdout:write("\27[0m") -- Clean.
end
-- logprintOnce( agent, string )
-- logprintOnce( agent, formatString, ... )
-- agent can be nil.
function logprintOnce(agent, s, ...)
if select("#", ...) > 0 then s = s:format(...) end
local time = getTime()
if agent then
printfOnce("%s.%03d|%s| %s", os.date("%H:%M:%S", time), 1000*(time%1), agent, s)
else
printfOnce("%s.%03d| %s", os.date("%H:%M:%S", time), 1000*(time%1), s)
end
end
end
F = string.format
function formatBytes(n)
if n >= 1024*1024*1024 then
return F("%.2f GB", n/(1024*1024*1024))
elseif n >= 1024*1024 then
return F("%.2f MB", n/(1024*1024))
elseif n >= 1024 then
return F("%.2f KB", n/(1024))
else
return T("label_numBytes", {n=n})
end
end
function trim(s)
s = s :gsub("^%s+", "") :gsub("%s+$", "")
return s
end
function trimNewlines(s)
s = s :gsub("^\n+", "") :gsub("\n+$", "")
return s
end
-- array = sortNatural( array [, attribute ] )
do
local function pad(numStr)
return F("%03d%s", #numStr, numStr)
end
function compareNatural(a, b)
return tostring(a):gsub("%d+", pad) < tostring(b):gsub("%d+", pad)
end
function sortNatural(t, k)
if k then
table.sort(t, function(a, b)
return compareNatural(a[k], b[k])
end)
else
table.sort(t, compareNatural)
end
return t
end
end
function assertf(v, err, ...)
if not v then
if select("#", ...) > 0 then err = err:format(...) end
assert(false, err)
end
return v
end
-- value = assertarg( [ functionName=auto, ] argumentNumber, value, expectedValueType... [, depth=2 ] )
do
local function _assertarg(fName, n, v, ...)
local vType = type(v)
local varargCount = select("#", ...)
local lastArg = select(varargCount, ...)
local hasDepthArg = (type(lastArg) == "number")
local typeCount = varargCount+(hasDepthArg and -1 or 0)
for i = 1, typeCount do
if vType == select(i, ...) then return v end
end
local depth = 2+(hasDepthArg and lastArg or 2)
if not fName then
fName = debug.traceback("", depth-1):match": in function '(.-)'" or "?"
end
local expects = table.concat({...}, " or ", 1, typeCount)
error(F("bad argument #%d to '%s' (%s expected, got %s)", n, fName, expects, vType), depth)
end
function assertarg(fNameOrArgNum, ...)
if type(fNameOrArgNum) == "string" then
return _assertarg(fNameOrArgNum, ...)
else
return _assertarg(nil, fNameOrArgNum, ...)
end
end
end
function check(v, ...)
if not v then
local err = "Error: "..tostring((...))
print(debug.traceback(err, 2))
end
return v, ...
end
function indexOf(t, v)
for i, item in ipairs(t) do
if item == v then return i end
end
return nil
end
-- item, index = itemWith( array, key1, value1, ...)
function itemWith(t, ...)
for i, item in ipairs(t) do
local isMatch = true
for argIndex = 1, select("#", ...), 2 do
local k, v = select(argIndex, ...)
if item[k] ~= v then
isMatch = false
break
end
end
if isMatch then
return item, i
end
end
return nil
end
-- items = itemWithAll( array, key1, value1, ...)
function itemWithAll(t, ...)
local items = {}
for i, item in ipairs(t) do
local isMatch = true
for argIndex = 1, select("#", ...), 2 do
local k, v = select(argIndex, ...)
if item[k] ~= v then
isMatch = false
break
end
end
if isMatch then
table.insert(items, item)
end
end
return items
end
-- index = indexWith( array, key1, value1, ...)
function indexWith(t, ...)
local _, i = itemWith(t, ...)
return i
end
-- html = encodeHtmlEntities( string [, excludeApostrophe=false ] )
do
local ENTITIES = {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
}
function encodeHtmlEntities(s, excludeApostrophe)
return (s:gsub((excludeApostrophe and "[&<>\"]" or "[&<>\"']"), ENTITIES))
end
end
function pack(...)
return {n=select("#", ...), ...}
end
-- parts = splitString( string, separatorPattern [, startIndex=1, plain=false ] )
function splitString(s, sep, i, plain)
i = i or 1
local parts = {}
while true do
local i1, i2 = s:find(sep, i, plain)
if not i1 then break end
table.insert(parts, s:sub(i, i1-1))
i = i2+1
end
table.insert(parts, s:sub(i))
return parts
end
function round(n)
return math.floor(n+0.5)
end
-- builder = newStringBuilder( )
do
local mt = {
__call = function(b, ...)
local len = select("#", ...)
if len == 0 then return table.concat(b) end
local s = len == 1 and tostring(...) or F(...)
table.insert(b, s)
end,
}
function newStringBuilder()
return setmetatable({}, mt)
end
end
function getKeys(t)
local keys = {}
for k in pairs(t) do table.insert(keys, k) end
return keys
end
-- bool = isAny( valueToCompare, value1, ... )
-- bool = isAny( valueToCompare, arrayOfValues )
function isAny(v, ...)
local len = select("#", ...)
if len == 1 and type(...) == "table" then
for _, item in ipairs(...) do
if v == item then return true end
end
else
for i = 1, len do
if v == select(i, ...) then return true end
end
end
return false
end
-- insertMultiple( array, value1, ...)
function insertMultiple(t, ...)
local insert = table.insert
local select = select
for i = 1, select("#", ...) do
insert(t, (select(i, ...)))
end
end
-- anyItemGotRemoved = removeItem( array, value1, ... )
function removeItem(t, ...)
local anyItemGotRemoved = false
for argIndex = 1, select("#", ...) do
local i = indexOf(t, select(argIndex, ...))
if i then
table.remove(t, i)
anyItemGotRemoved = true
end
end
return anyItemGotRemoved
end
-- Same as string.gsub(), but "%" has no meaning in the replacement.
function gsub2(s, pat, repl, ...)
return s:gsub(pat, repl:gsub("%%", "%%%%"), ...)
end
function getTime()
return socket and socket.gettime() or os.time()
end
-- Compute the difference in seconds between local time and UTC. (Normal time.)
-- http://lua-users.org/wiki/TimeZone
function getTimezone()
local now = os.time()
return os.difftime(now, os.time(os.date("!*t", now)))
end
-- Return a timezone string in ISO 8601:2000 standard form (+hhmm or -hhmm).
function getTimezoneOffsetString(tz)
local h, m = math.modf(tz/3600)
return F("%+.4d", 100*h+60*m)
end
-- Return the timezone offset in seconds, as it was on the given time. (DST obeyed.)
-- timezoneOffset = getTimezoneOffset( [ time=now ] )
function getTimezoneOffset(time)
time = time or os.time()
local dateUtc = os.date("!*t", time)
local dateLocal = os.date("*t", time)
dateLocal.isdst = false -- This is the trick.
return os.difftime(os.time(dateLocal), os.time(dateUtc))
end
function cleanupPath(someKindOfPath)
local path = toNormalPath(someKindOfPath)
local count
repeat
path, count = path:gsub("/[^/]+/%.%./", "/", 1) -- Not completely fool proof!
until count == 0
return path
end
function ipairsr(t)
return iprev, t, #t+1
end
function iprev(t, i)
i = i-1
local v = t[i]
if v ~= nil then return i, v end
end
-- for key, value, index in pairsSorted( table ) do
function pairsSorted(t)
local keys = sortNatural(getKeys(t))
local i = 0
return function()
i = i+1
local k = keys[i]
if k ~= nil then return k, t[k], i end
end
end
function sort(t, ...)
table.sort(t, ...)
return t
end
function isInt(v)
return
type(v) == "number"
and v == v -- Not NaN.
and v == math.floor(v)
and math.abs(v) ~= math.huge
end
function makePrintable(v)
return (tostring(v)
:gsub("\r", "\\r")
:gsub("\n", "\\n")
:gsub("\t", "\\t")
:gsub("[%z\1-\31]", function(c)
return "\\"..c:byte()
end)
:gsub("(pass=).-(&[^a])", "%1***%2") -- Simple password hiding. Note: "&" should be encoded as "&".
)
end
function iff(v, a, b)
if v then
return a
else
return b
end
end
function clamp(n, min, max)
return math.min(math.max(n, min), max)
end
-- Return any data as a Lua code string.
-- luaString = serializeLua( value )
do
local SIMPLE_TYPES = {["boolean"]=true,["nil"]=true,["number"]=true}
local KEYWORDS = {
["and"]=true,["break"]=true,["do"]=true,["else"]=true,["elseif"]=true,
["end"]=true,["false"]=true,["for"]=true,["function"]=true,["if"]=true,
["in"]=true,["local"]=true,["nil"]=true,["not"]=true,["or"]=true,["repeat"]=true,
["return"]=true,["then"]=true,["true"]=true,["until"]=true,["while"]=true,
}
local function _serializeLua(out, data)
local dataType = type(data)
if dataType == "table" then
local first = true
local i = 0
local indices = {}
local insert = table.insert
insert(out, "{")
while true do
i = i+1
if data[i] == nil then
i = i+1
if data[i] == nil then break end
if not first then insert(out, ",") end
insert(out, "nil")
first = false
end
if not first then insert(out, ",") end
first = false
_serializeLua(out, data[i])
indices[i] = true
end
for k, v in pairs(data) do
if not indices[k] then
if not first then insert(out, ",") end
first = false
if not KEYWORDS[k] and type(k) == "string" and k:find"^[a-zA-Z_][a-zA-Z0-9_]*$" then
insert(out, k)
else
insert(out, "[")
_serializeLua(out, k)
insert(out, "]")
end
insert(out, "=")
_serializeLua(out, v)
end
end
insert(out, "}")
elseif dataType == "string" then
table.insert(out, F("%q", data))
elseif SIMPLE_TYPES[dataType] then
table.insert(out, tostring(data))
else
errorf("Cannot serialize value type '%s'. (%s)", dataType, tostring(data))
end
return out
end
function serializeLua(data)
return (table.concat(_serializeLua({}, data)))
end
end
-- processStarted = cmdAsync( ... )
function cmdAsync(pathToApp, ...)
local cmd = cmdEscapeArgs(toWindowsPath(pathToApp), ...)
return processStart(cmd, PROCESS_METHOD_ASYNC)
end
-- success, exitCode = cmdSync( ... )
function cmdSync(pathToApp, ...)
local cmd = cmdEscapeArgs(toWindowsPath(pathToApp), ...)
local exitCode = -1
local ok = processStart(cmd, PROCESS_METHOD_SYNC, function(process, _exitCode)
exitCode = _exitCode
end)
return (ok and exitCode == 0), exitCode
end
-- processStarted = cmdDetached( ... )
function cmdDetached(pathToApp, ...)
local cmd = cmdEscapeArgs(toWindowsPath(pathToApp), ...)
return processStart(cmd, PROCESS_METHOD_DETACHED)
end
-- output, errorMessage = cmdCapture( ... )
-- Note: output may be the contents of stderr.
function cmdCapture(pathToApp, ...)
local cmd = cmdEscapeArgs(toWindowsPath(pathToApp), ...)
local output
local ok = processStart(cmd, PROCESS_METHOD_SYNC, function(process, exitCode)
output = processReadEnded(process, exitCode, true)
end)
if not ok then return nil, "Could not start process." end
return output
end
do
local scriptsRunning = {}
-- processStarted = scriptCaptureAsync( scriptName, callback, arg1, ... )
-- callback = function( output )
function scriptCaptureAsync(scriptName, cb, ...)
local cmd = cmdEscapeArgs("wlua5.1.exe", "src/script.lua", scriptName, ...)
local ok = processStart(cmd, PROCESS_METHOD_ASYNC, function(process, exitCode)
scriptsRunning[scriptName] = false
cb(processReadEnded(process, exitCode, true))
end)
if not ok then return false end
scriptsRunning[scriptName] = true
return true
end
-- processStarted = scriptRunDetached( scriptName, arg1, ... )
function scriptRunDetached(scriptName, ...)
return cmdDetached("wlua5.1.exe", "src/script.lua", scriptName, ...)
end
function isScriptRunning(scriptName)
return scriptsRunning[scriptName] or false
end
end
function cmdEscapeArgs(...)
local buffer = {}
for i = 1, select('#', ...) do
local arg = select(i, ...)
if type(arg) == "number" then
arg = tostring(arg)
elseif arg:find'[%z\n\r]' then
print("Arg "..i..": "..arg)
error("Argument contains invalid characters.")
end
if i > 1 then
table.insert(buffer, ' ')
end
if arg == '' then
table.insert(buffer, '""')
elseif not arg:find'[%s"]' then
table.insert(buffer, arg)
else
arg = arg
:gsub('(\\*)"', '%1%1\\"')
:gsub('(\\+)$', '%1%1')
table.insert(buffer, '"')
table.insert(buffer, arg)
table.insert(buffer, '"')
end
end
return table.concat(buffer)
end
function run(pathToApp, ...)
local ok, exitCode = cmdSync(pathToApp, ...)
if not ok then
local cmd = cmdEscapeArgs(toWindowsPath(pathToApp), ...)
errorf("Command returned %d: %s", exitCode, cmd)
end
end
-- for value... in iterate( callback, argument... ) do
-- 'value...' is whatever the callback yields.
do
local coroutine_create = coroutine.create
local coroutine_resume = coroutine.resume
local coroutine_wrap = coroutine.wrap
local coroutine_yield = coroutine.yield
local function initiator(cb, ...)
coroutine_yield()
return cb(...)
end
local function iterator(co)
return select(2, assert(coroutine_resume(co)))
end
function iterate(cb, ...)
if select('#', ...) <= 2 then
return coroutine_wrap(cb), ...
end
local co = coroutine_create(initiator)
assert(coroutine_resume(co, cb, ...))
return iterator, co
end
end
-- for item in arrayIterator( array ) do
function arrayIterator(t)
local i = 0
return function()
i = i+1
local v = t[i]
if v ~= nil then return v end
end
end
function newSet(t)
local set = {}
for _, v in ipairs(t) do set[v] = true end
return set
end
-- success = setAndInsert( table, key [, item=key ] )
function setAndInsert(t, k, item)
if isAny(type(k), "number","nil") then
errorf(2, "The key cannot be a number or nil. (Got %s)", type(k))
end
if t[k] then return false end
if item == nil then item = k end
t[k] = item
table.insert(t, item)
return true
end
-- resultingItemInTable = setAndInsertIfNew( table, key, item )
function setAndInsertIfNew(t, k, item)
setAndInsert(t, k, item)
return t[k]
end
-- success = unsetAndRemove( table, key )
function unsetAndRemove(t, k)
assert(type(k) ~= "number", "The key cannot be a number.")
local item = t[k]
if not item then return false end
t[k] = nil
removeItem(t, item)
return true
end
-- position = findPreviousChar( string, char, startPosition )
function findPreviousChar(s, c, i)
local byte = c:byte()
for ptr = i, 1, -1 do
if s:byte(ptr) == byte then return ptr end
end
return nil
end
-- success = openFileExternally( path )
function openFileExternally(path)
return cmdDetached("explorer", toShortPath(path, true))
end
-- success = openFileInNotepad( path )
function openFileInNotepad(path)
return cmdDetached("notepad", toShortPath(path, true))
end
-- success = showFileInExplorer( path )
function showFileInExplorer(path)
-- This *sometimes* seem to leave a lingering explorer process for some reason, even
-- after MyHappyList closes. Need confirmation on this. Most of the time the process
-- stops after some time though. The command looks something like this:
-- C:\Windows\explorer.exe /factory,{75(...)4b} -Embedding
return cmdDetached("explorer", "/select,"..toShortPath(path, true))
end
-- array = range( [ from=1, ] to )
function range(from, to)
if not to then
from, to = 1, from
end
local t = {}
local i = 0
for n = from, to do
i = i+1
t[i] = n
end
return t
end
-- values = getColumn( array, key )
function getColumn(t, k)
local values = {}
for i, item in ipairs(t) do
values[i] = item[k]
end
return values
end
do
local allStorage = setmetatable({}, {__mode="k"})
-- storage = getStorage( object [, doNotCreate=false ] )
function getStorage(obj, doNotCreate)
local storage = allStorage[obj]
if not (storage or doNotCreate) then
storage = {}
allStorage[obj] = storage
end
return storage
end
function getStored(obj, k)
local storage = allStorage[obj]
return storage and storage[k]
end
function store(obj, k, v)
getStorage(obj)[k] = v
end
-- storeItem( object, item ) -- Store directly in storage.
-- storeItem( object, key, item ) -- Store in an array field.
function storeItem(obj, kOrItem, item)
local storage = getStorage(obj)
if item ~= nil then
local k = kOrItem
local t = storage[k]
if not t then
storage[k] = {item}
else
table.insert(t, item)
end
else
item = kOrItem
assert(item ~= nil)
table.insert(storage, item)
end
end
end
function getStoredEventCallback(eHolder, eType, id)
local storage = getStorage(eHolder, true)
return storage and tablePathGet(storage, "events", eType, id)
end
-- callbacks = getStoredEventCallbackAll( eventHolder, eventType )
-- callbacks = { [id1]=callback1, ... }
function getStoredEventCallbackAll(eHolder, eType)
local storage = getStorage(eHolder, true)
return storage and tablePathGet(storage, "events", eType)
end
function storeEventCallbacks(eHolder, eType, id, cb)
tablePathSet(getStorage(eHolder), "events", eType, id, cb)
end
-- value = tablePathGet( table, key1, ... )
function tablePathGet(t, k, ...)
for i = 1, select("#", ...) do
if not t[k] then return nil end
t = t[k]
k = select(i, ...)
end
return t[k]
end
-- tablePathSet( table, key1, ..., value )
function tablePathSet(t, k, ...)
local argCount = select("#", ...)
for i = 1, argCount-1 do
if not t[k] then
t[k] = {}
end
t = t[k]
k = select(i, ...)
end
t[k] = select(argCount, ...)
end
function eatSpaces(s, ptr)
local _, to = s:find(" *", ptr)
return to+1
end
do
local cwds = {}
function cwdPush(path)
table.insert(cwds, wxGetCwd())
wxSetWorkingDirectory(path)
end
function cwdPop()
wxSetWorkingDirectory(table.remove(cwds))
end
end
-- line1, ... [, rest ] = matchLines( string, lineCount [, returnRest=false ] )
function matchLines(s, count, rest)
if count < 1 then
if rest then return s end
return
end
local pat = "^([^\n]+)" .. ("\n([^\n]+)"):rep(count-1)
if rest then
pat = pat.."\n?(.*)"
end
return s:match(pat)
end
function isHost(host, wantedHost)
return
host == wantedHost
or #host > #wantedHost and ("."..host):sub(#host+1-#wantedHost) == "."..wantedHost
end
function quit()
topFrame:Close(true)
wxGetApp():ExitMainLoop()
end
function maybeQuit()
if topFrame:Close() then
wxGetApp():ExitMainLoop()
end
end
-- success, errorMessage = unzip( zipFilePath, targetDirectory [, unwrapRootDirectoryInZipFile=false ] [, filter ] )
-- doUnzip = filter( relativePath )
-- Note: relativePath can be a directory or file.
function unzip(zipPath, targetDir, unwrapRoot, filter)
if type(unwrapRoot) == "function" then
unwrapRoot, filter = false, unwrapRoot
end
if not isDirectoryWritable(targetDir) then
return false, targetDir..": Directory is not writable."
end
local zip = assert(require"zip".open(zipPath))
assert(createDirectory(targetDir))
for archivedFile in zip:files() do
local pathRel = archivedFile.filename
if unwrapRoot and pathRel:find"^[^/]+/$" then
-- void
-- Directory.
elseif pathRel:find"/$" then
pathRel = pathRel:sub(1, #pathRel-1)
local pathRelFinal = unwrapRoot and pathRel:gsub("^[^/]+/", "") or pathRel
if not filter or filter(pathRelFinal) then
local path = targetDir.."/"..pathRelFinal
assert(createDirectory(path))
end
-- File.
else
local pathRelFinal = unwrapRoot and pathRel:gsub("^[^/]+/", "") or pathRel
if not filter or filter(pathRelFinal) then
local file = assert(zip:open(pathRel))
local contents = file:read"*a"
file:close()
local path = targetDir.."/"..pathRelFinal
assert(writeFile(path, contents))
end
end
end
zip:close()
return true
end
function updater_getUnzipDir()
return DIR_TEMP.."/LatestVersion"
end
do
local function moveFiles(isMain, dangerModeActive)
traverseDirectory(updater_getUnzipDir(), function(pathOld, pathRel, name, mode)
local pathNew = DIR_APP.."/"..pathRel
if (pathRel == "misc/Update" or pathRel:find"^misc/Update/" ~= nil) == isMain then
-- Skip for now.
elseif mode == "directory" then
if dangerModeActive then
logprint(nil, "Creating %s", pathNew)
assert(createDirectory(pathNew))
else
logprint("Sim", "Create directory: %s", pathNew)
end
else
if dangerModeActive then
logprint(nil, "Moving %s", pathNew)
assert(renameFile(pathOld, pathNew, true))
else
logprint("Sim", "Move file to: %s", pathNew)
end
end
end)
end
function updater_moveFilesAfterUnzipMain(dangerModeActive)
moveFiles(true, dangerModeActive)
end
function updater_moveFilesAfterUnzipUpdater(dangerModeActive)
moveFiles(false, dangerModeActive)
end
end
local DEFAULT_LANGUAGE = "en-US"
local textTables = nil
local function loadTexts()
textTables = {}
traverseFiles("languages", function(path, pathRel, filename, ext)
if ext ~= "txt" then return end
local file = assert(openFile(path, "r"))
local ln = 0
local langCode = filename:sub(1, -5) -- Remove ".txt"
assert(langCode ~= "")
local textTable = {language_code=langCode}
table.insert(textTables, textTable)
textTables[langCode] = textTable
for line in file:lines() do
ln = ln+1
line = trim(line)
if line == "" or line:find"^#" then
-- void
else
local textKey, text = line:match"^([%w_]+)%s*=%s*(.*)$"
if not textKey then
logprinterror("i18n", "%s:%d: Bad line format: %s", path, ln, line)
elseif text ~= "" then
textTable[textKey] = text
end
end
end
file:close()
textTable.language_title = textTable.language_title or langCode
end)
end
function T(textKey, values)
return getText(appSettings.language, textKey, values, DEFAULT_LANGUAGE)
end
-- text = getText( languageCode, textKey [, values, fallbackLanguageCode ] )
function getText(langCode, textKey, values, fallback)
if not textTables then
loadTexts()
end
local text
= textTables[langCode][textKey]
or fallback and textTables[fallback][textKey]
or F("<%s>", textKey)
if values then
text = text:gsub("{([%w_.]+)}", function(k)
return values[k] or "{UNKNOWN_VALUE}"
end)
end
return text
end
-- translations = getTranslations( )
-- translation = { code=languageCode, title=languageTitle }
function getTranslations()
if not textTables then
loadTexts()
end
local translations = {}
for _, textTable in ipairs(textTables) do
table.insert(translations, {code=textTable.language_code, title=textTable.language_title})
end
return translations
end
-- copy = copyTable( table [, deep=false ] )
do
local function deepCopy(t, copy, tableCopies)
for k, v in pairs(t) do
if type(v) == "table" then
local vCopy = tableCopies[v]
if vCopy then
copy[k] = vCopy
else
vCopy = {}
tableCopies[v] = vCopy
copy[k] = deepCopy(v, vCopy, tableCopies)
end
else
copy[k] = v
end
end
return copy
end
function copyTable(t, deep)
if deep then
return deepCopy(t, {}, {})
end
local copy = {}
for k, v in pairs(t) do copy[k] = v end
return copy
end
end
-- tablesAreEqual = compareTables( table1, table2 [, deep=false ] )
function compareTables(t1, t2, deep)
for k, v1 in pairs(t1) do
local v2 = t2[k]
if v1 ~= v2 and not (deep and type(v1) == "table" and type(v2) == "table" and compareTables(v1, v2, true)) then
return false
end
end
for k, v2 in pairs(t2) do
if t1[k] == nil then return false end
end
return true
end
-- isValid, errorPosition = utf8IsValid( string [, startBytePosition=1 ] )
-- https://github.com/kikito/utf8_validator.lua/blob/master/utf8_validator.lua
function utf8IsValid(s, ptr)
ptr = ptr or 1
local len = #s
local find = string.find
while ptr <= len do
if ptr == find(s, "[%z\1-\127]", ptr) then ptr = ptr + 1
elseif ptr == find(s, "[\194-\223][\128-\191]", ptr) then ptr = ptr + 2
elseif ptr == find(s, "\224[\160-\191][\128-\191]", ptr)
or ptr == find(s, "[\225-\236][\128-\191][\128-\191]", ptr)
or ptr == find(s, "\237[\128-\159][\128-\191]", ptr)
or ptr == find(s, "[\238-\239][\128-\191][\128-\191]", ptr) then ptr = ptr + 3
elseif ptr == find(s, "\240[\144-\191][\128-\191][\128-\191]", ptr)
or ptr == find(s, "[\241-\243][\128-\191][\128-\191][\128-\191]", ptr)
or ptr == find(s, "\244[\128-\143][\128-\191][\128-\191]", ptr) then ptr = ptr + 4
else
return false, ptr
end
end
return true
end
|
--[[
##########################################################
S V U I By: Failcoder
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local ipairs = _G.ipairs;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local assert = _G.assert;
local math = _G.math;
--[[ MATH METHODS ]]--
local random = math.random;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['InkedSV']
local L = SV.L;
local LSM = _G.LibStub("LibSharedMedia-3.0")
local MOD = SV.UnitFrames
if(not MOD) then return end
local oUF_InkedSV = MOD.oUF
assert(oUF_InkedSV, "InkedSV UnitFrames: unable to locate oUF.")
if(SV.class ~= "ROGUE") then return end
--[[
##########################################################
LOCALS
##########################################################
]]--
local TRACKER_FONT = [[Interface\AddOns\InkedSV\assets\fonts\Combo.ttf]];
local EMPTY_TEXTURE = [[Interface\AddOns\InkedSV\assets\textures\EMPTY]];
local BLOOD_TEXTURE = [[Interface\Addons\InkedSV_UnitFrames\assets\Class\COMBO-ANIMATION]];
local ICON_BG = [[Interface\Addons\InkedSV_UnitFrames\assets\Class\ROGUE-SMOKE]];
local ICON_ANTI = [[Interface\Addons\InkedSV_UnitFrames\assets\Class\ROGUE-ANTICIPATION]];
local ICON_FILE = [[Interface\Addons\InkedSV_UnitFrames\assets\Class\ROGUE]];
local ICON_COORDS = {
{0,0.5,0.5,1},
{0,0.5,0.5,1},
{0,0.5,0.5,1},
{0,0.5,0.5,1},
};
local cpointColor = {
{0.69,0.31,0.31},
{0.69,0.31,0.31},
{0.65,0.63,0.35},
{0.65,0.63,0.35},
{0.33,0.59,0.33}
};
--[[
##########################################################
POSITIONING
##########################################################
]]--
local OnMove = function()
SV.db.UnitFrames.player.classbar.detachFromFrame = true
end
local ShowPoint = function(self)
--self.FX:SetEffect("default")
end
local HidePoint = function(self)
local coords = ICON_COORDS[random(2,4)];
self.Icon:SetTexCoord(coords[1],coords[2],coords[3],coords[4])
self.Blood:SetTexture(BLOOD_TEXTURE)
end
local Reposition = function(self)
local db = SV.db.UnitFrames.player
local bar = self.HyperCombo;
if not db then return end
local height = db.classbar.height
local width = height * 3;
local textwidth = height * 1.25;
bar.Holder:SetSize(width, height)
if(not db.classbar.detachFromFrame) then
SV:ResetAnchors(L["Classbar"])
end
local holderUpdate = bar.Holder:GetScript('OnSizeChanged')
if holderUpdate then
holderUpdate(bar.Holder)
end
bar:ClearAllPoints()
bar:SetAllPoints(bar.Holder)
local points = bar.Combo;
local max = UnitPowerMax("player", Enum.PowerType.ComboPoints);
points:ClearAllPoints()
points:SetAllPoints(bar)
if(db.classbar.altComboPoints) then
for i = 1, max do
--points[i].FX:SetAlpha(0)
points[i]:ClearAllPoints()
points[i]:SetSize(height, height)
points[i].Icon:SetTexture(ICON_FILE)
if i==1 then
points[i]:SetPoint("LEFT", points)
else
points[i]:SetPoint("LEFT", points[i - 1], "RIGHT", -8, 0)
end
end
bar.PointShow = nil;
bar.PointHide = HidePoint;
else
for i = 1, max do
if points[i] then
--points[i].FX:SetAlpha(1)
points[i]:ClearAllPoints()
points[i]:SetSize(height, height)
points[i].Icon:SetTexture(EMPTY_TEXTURE)
if(points[i].Blood) then
points[i].Blood:SetTexture(EMPTY_TEXTURE)
end
if i==1 then
points[i]:SetPoint("LEFT", points)
else
points[i]:SetPoint("LEFT", points[i - 1], "RIGHT", -8, 0)
end
end
end
bar.PointShow = ShowPoint;
bar.PointHide = nil;
end
end
--[[
##########################################################
ROGUE COMBO TRACKER
##########################################################
]]--
function MOD:CreateClassBar(playerFrame)
local max = UnitPowerMax("player", Enum.PowerType.ComboPoints)
local size = 20
local coords
local bar = CreateFrame("Frame", nil, playerFrame)
bar:SetFrameLevel(playerFrame.TextGrip:GetFrameLevel() + 30)
bar.Combo = CreateFrame("Frame",nil,bar)
for i = 1, max do
local coords = ICON_COORDS[random(2,4)]
local cpoint = CreateFrame('Frame', nil, bar.Combo)
cpoint:SetSize(size,size)
SV.SpecialFX:SetFXFrame(cpoint, "default")
local icon = cpoint:CreateTexture(nil,"OVERLAY",nil,1)
icon:SetAllPoints(cpoint)
icon:SetTexture(ICON_FILE)
icon:SetBlendMode("BLEND")
icon:SetTexCoord(coords[1],coords[2],coords[3],coords[4])
cpoint.Icon = icon
local blood = cpoint:CreateTexture(nil,"OVERLAY",nil,2)
blood:SetAllPoints(cpoint)
blood:SetTexture(EMPTY_TEXTURE)
blood:SetBlendMode("ADD")
SV.Animate:Sprite4(blood,0.08,2,true)
cpoint.Blood = blood
bar.Combo[i] = cpoint
end
bar.PointShow = ShowPoint;
bar.PointHide = HidePoint;
local classBarHolder = CreateFrame("Frame", "Player_ClassBar", bar)
classBarHolder:SetPoint("TOPLEFT", playerFrame, "BOTTOMLEFT", 0, -2)
bar:SetPoint("TOPLEFT", classBarHolder, "TOPLEFT", 0, 0)
bar.Holder = classBarHolder
SV:NewAnchor(bar.Holder, L["Classbar"], OnMove)
playerFrame.MaxClassPower = max;
playerFrame.RefreshClassBar = Reposition;
playerFrame.HyperCombo = bar
return 'HyperCombo'
end
|
--Start of Global Scope---------------------------------------------------------
-- Serving an event which is used to trigger the ControlFlow. Must be served to the Engine CROWN.
-- Engine events are always global, no serve in App properties necessary
Script.serveEvent('Engine.OnMyEventIn', 'OnMyEventIn')
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
local function main()
-- Notify the event to trigger the ControlFlow directly after startup
Script.notifyEvent('OnMyEventIn')
end
--The following registration is part of the global scope which runs once after startup
--Registration of the 'main' function to the 'Engine.OnStarted' event
Script.register('Engine.OnStarted', main)
-- Function is registered to the event which is raised from the flow
local function callFromFlow()
print('ControlFlow says hello')
end
-- Registration to the 'Engine.OnMyEventOut' as specified in the ControlFlow
Script.register('Engine.OnMyEventOut', callFromFlow)
--End of Function and Event Scope-----------------------------------------------
|
local Server = {}
Server._doc = [[
Lowerlevel of game server, handles all things before game started.
And ServerGameModule handles others.]]
local FSM = require 'Utils.FSM'
setmetatable(Server, { __index = FSM })
local Config = require 'Config'
local _LogT, _LogD, _LogI, _LogW, _LogE = require('unity.Debug').GetLogFuncs('[SRV]')
local Utils = require 'Utils.Utils'
local Time = require 'Utils.Time'
local Unity = require 'unity.Unity'
local MsgPack = require 'Game.MsgPack'
local Chan = csharp.checked_import('networking.Chan')
local ChanBreakReason = Chan[{csharp.p_nested_type(), 'BreakReason'}]
local Reason_ChanModule = ChanBreakReason.ChanModule
local Delegate = require 'Utils.Delegate'
local _OnConnected
local _OnRecv
local _OnProxyConnected
local _OnProxyRecv
local _SendProxy
local _TickServer
local _LoginToProxy
local _StartGame
local _BroadcastPlayerReady
local _HandleProxyInstantMessage -- uses _HandleIncomingMessage and _HandleInstantMessage
local _HandleIncomingMessage -- uses HandleInstantMessage
local _HandleInstantMessage
local _Debug_OnServiceStarted
local _ChanFromSess
local _ChanFromPlayer
local _MakeSession
local _NextUniqueId
local _uniqueId = 101
local _InitDelegates = function(s)
s.delegates = {
onGameStarted = Delegate(),
onGameEnded = Delegate(),
loadPlayGround = Delegate(),
onMsgReceived = Delegate(),
onFrameUpdated = Delegate(),
onServerTick = Delegate(),
}
end
function Server:Awake()
FSM.Awake(self)
local Native = csharp.checked_import('Server')
self.native = assert(self:GetComponent(Native))
-- init
self.time = Time.New('server', 'fixed')
self.sessions = {}
self.proxy = {
addr = false,
chan = false,
chanEstablished = false,
chanEncryptedModule = false,
stackedPacks = {}
}
self.messages = {}
self.nextServerTickTime = 0
self.sessId2Player = {}
self.playerId2Sess = {}
self.players = {}
self.sessId2PlayerInst = {}
self.playerId2PlayerInst = {}
self.gameStarted = false
_InitDelegates(self)
end
function Server:Serve(port, proxy, serverId, config)
self.config = config or Config.testServerConfig
self.port = port
self.serverId = serverId
self.networkIdStart = Config.maxNetworkInstancePerClient
self.serverNetworkId = Config.serverNetworkIdStart
self.proxy.addr = proxy
if proxy.addr ~= 'none' and proxy.addr ~= 'localhost' then
self.hasProxy = true
local onProxyConnected = function(chan)
_OnProxyConnected(self, chan)
_LoginToProxy(self, tostring(serverId))
end
local onProxyRecv = function(data)
local ok, err = pcall(_OnProxyRecv, self, data)
if not ok then
_LogE('ERROR: ' .. err)
end
end
self.native:ConnectProxy(proxy.addr, proxy.port, onProxyConnected, onProxyRecv)
end
local onConnected = function(chan)
return _OnConnected(self, chan)
end
local onRecv = function(id, data)
local ok, err = pcall(_OnRecv, self, id, data)
if not ok then
_LogE('ERROR: ' .. err)
end
end
self.native:Serve(port, onConnected, onRecv)
self.delegates.loadPlayGround()
_Debug_OnServiceStarted(self)
end
function Server:SendGameMsgByPid(playerId, msg)
end
function Server:SendGameMsgBySid(sessId, msg)
end
function Server:BroadcastGameMsg(name, msg)
for _, player in ipairs(self.players) do
local bytes = MsgPack.Pack('game', name, msg, player.id, self.serverId)
_SendProxy(self, bytes, player.sessId)
end
end
function Server:GetPlayer(pid)
local idx = assert(self.playerId2PlayerInst[pid])
return assert(self.players[idx])
end
local _Broadcast = function(s, proto, name, msg)
for _, player in ipairs(s.players) do
local bytes = MsgPack.Pack(proto, name, msg, player.id, s.serverId)
_SendProxy(s, bytes, player.sessId)
end
end
_LoginToProxy = function(s, token)
_LogT('LoginToProxy ' .. token)
local bytes = MsgPack.Pack('relay', 'LoginRequest', {token = token})
_SendProxy(s, bytes)
end
_StartGame = function(s)
_LogD('StartGame')
s.gameStarted = true
_Broadcast(s, 'game', 'StartGame')
s.delegates.onGameStarted()
end
_EndGame = function(s)
_LogD('EndGame')
s.gameStarted = false
_Broadcast(s, 'game', 'EndGame')
s.delegates.onGameEnded()
end
_BroadcastPlayerReady = function(s)
_LogD('_BroadcastPlayerReady')
local msg = { playerIds = {} }
for _, p in ipairs(s.players) do
table.insert(msg.playerIds, p.id)
end
s:BroadcastGameMsg('PlayerReady', msg)
end
local Profiler = Unity.Profiling.Profiler
function Server:Update()
--Profiler.BeginSample('Server.Update')
if self.gameStarted then
self.delegates.onFrameUpdated()
local time = Time.RS()
if time > self.nextServerTickTime then
self.nextServerTickTime = time + Config.serverTickDur
_TickServer(self)
end
end
--Profiler.EndSample()
end
_TickServer = function(s)
--Profiler.BeginSample('_TickServer')
local msgs = s.messages
s.messages = {}
for _, bundle in ipairs(msgs) do
local gameOp, msg, from = unpack(bundle)
s.delegates.onMsgReceived(gameOp, msg, from)
end
s.delegates.onServerTick()
--Profiler.EndSample()
end
-- FSM
function Server:FSM_OnOnePlayerReadyToGo()
if #self.players == self.config.allowedPlayer then
_StartGame(self)
self:SendFsmEvent('CE_StartGame')
end
end
-- connect & recv
----------------------------
-- Proxy
local _FlushProxyStackedPacks = function(s)
if s.proxy.stackedPacks and #s.proxy.stackedPacks > 0 then
for _, b in ipairs(s.proxy.stackedPacks) do
s.proxy.chan:Send(b)
end
end
s.proxy.stackedPacks = false
end
_OnProxyConnected = function(s, chan)
_LogT('_OnProxyConnected')
chan.name = 'proxy'
if Config.useEncryptedChan then
_LogT('proxy client using encrypted chan')
local EncryptedChanModule = require 'Game.EncryptedChanModule'
local cm = EncryptedChanModule.New()
cm.onEstablished = function()
_LogT('encrypted chan established')
s.proxy.chanEstablished = true
_FlushProxyStackedPacks(s)
end
s.proxy.chanEncryptedModule = cm
chan:SetChanModule(cm.native)
else
s.proxy.chanEstablished = true
end
s.proxy.chan = chan
end
_OnProxyRecv = function(s, data)
--_LogT('_OnProxyRecv ' .. #data .. ' bytes:\n' .. csharp.hex_dump(data))
local op = MsgPack.Peek(data)
if op == 'PikeSeedRequest' then
if not s.proxy.chanEncryptedModule then
s.proxy.chan:Break(Reason_ChanModule)
return
end
s.proxy.chanEncryptedModule:CheckInitReply(data)
elseif op == 'SendRequest' then
-- redirect to server
local gameOp, msg, from, to = MsgPack.Unpack(data)
_LogD(tostring(from) .. ' -> ' .. gameOp .. ':' .. tostring(msg))
assert(to == s.serverId)
local bundle = {gameOp, msg, from, to}
_HandleProxyInstantMessage(s, bundle)
end
end
_SendProxy = function(s, bytes, sessId)
local chan
if not sessId then
chan = s.proxy.chan
else
chan = _ChanFromSess(s, sessId)
end
if chan == s.proxy.chan then
if s.proxy.chanEstablished then
_FlushProxyStackedPacks(s)
s.proxy.chan:Send(bytes)
else
table.insert(s.proxy.stackedPacks, bytes)
end
else
-- local client
s.sessions[sessId].chan:Send(bytes)
end
end
----------------------------
_NextUniqueId = function()
local id = _uniqueId
_uniqueId = _uniqueId + 1
return id
end
_OnConnected = function(s, chan)
_LogT('_OnConnected')
local chanEncryptedModule
local sessId = _NextUniqueId()
chan.name = 'serverplayer'..sessId
if Config.useEncryptedChan then
_LogI('using encrypted chan')
local EncryptedChanModule = require 'Game.EncryptedChanModule'
local cm = EncryptedChanModule.New('passive')
chanEncryptedModule = cm
chan:SetChanModule(cm.native)
end
local sess = {
id = sessId,
chan = chan,
chanEncryptedModule = chanEncryptedModule,
}
s.sessions[sessId] = sess
return sessId
end
_MakeSession = function(s, chan)
local sessId = _NextUniqueId()
local sess = {
id = sessId,
chan = chan,
chanEncryptedModule = false,
}
s.sessions[sessId] = sess
return sessId
end
_OnRecv = function(s, sessId, data)
--_LogT('_OnRecv from ' .. tostring(id) .. ' ' .. #data .. ' bytes:\n'..csharp.hex_dump(data))
local sess = s.sessions[sessId]
if not sess then
_LogE('session ' .. sessId .. ' not found, ignore packet')
return
end
local op = MsgPack.Peek(data)
if op == 'PikeSeedRequest' then
if not sess.chanEncryptedModule then
sess.chan:Break(Reason_ChanModule)
return
end
sess.chanEncryptedModule:CheckInitRequest(sess.chan, data)
elseif op == 'LoginRequest' then
-- must be local client connected
local _, msg = MsgPack.Unpack(data)
_LogD('LoginRequest' .. _ToString(msg))
-- simply discard
elseif op == 'SendRequest' then
local gameOp, msg, from, to = MsgPack.Unpack(data)
assert(gameOp) -- no proxy so there should be no SendReply
_LogD(tostring(from) .. ' -> ' .. gameOp .. ':' .. _ToString(msg))
assert(to == s.serverId)
local bundle = {gameOp, msg, from, to}
_HandleIncomingMessage(s, sessId, bundle)
end
end
_HandleProxyInstantMessage = function(s, bundle)
local gameOp, msg, from, to = unpack(bundle)
if gameOp == 'Ready' then
if not s.playerId2Sess[from] then
local sessId = _MakeSession(s, s.proxy.chan)
return _HandleInstantMessage(s, sessId, bundle)
else
_LogE('player ' .. from .. ' ready twice?')
-- ignore this message
return true
end
else
local sessId = assert(s.playerId2Sess[from], 'player ' .. from .. ' not ready?')
_HandleIncomingMessage(s, sessId, bundle)
end
end
local _GetPlayerTeam = function(s, pid)
for name, team in pairs(s.config.team) do
if Utils.Contains(team, pid) then
return name
end
end
end
_HandleInstantMessage = function(s, sessId, bundle)
local gameOp, msg, from, to = unpack(bundle)
if gameOp == 'SyncTime' then
local bytes = MsgPack.Pack('game', 'SyncTimeAck', {ts = msg.ts, srv_ts = s.time:TS()}, from, s.serverId)
_SendProxy(s, bytes, sessId)
return true
elseif gameOp == 'Ready' then
s.sessId2Player[sessId] = from
s.playerId2Sess[from] = sessId
local networkIdStart = s.networkIdStart + (#s.players + 1) * Config.maxNetworkInstancePerClient
local player = {
id = from,
sessId = sessId,
networkIdStart = networkIdStart,
team = assert(_GetPlayerTeam(s, from)), -- cached here
}
table.insert(s.players, player)
local index = #s.players
s.sessId2PlayerInst[sessId] = index
s.playerId2PlayerInst[from] = index
local bytes = MsgPack.Pack(
'game', 'ReadyAck',
{
scene = s.config.scene,
networkId = player.networkIdStart,
},
from, s.serverId)
_SendProxy(s, bytes, sessId)
_BroadcastPlayerReady(s)
return true
elseif gameOp == 'ReadyToGo' then
s:SendFsmEvent('CE_OnePlayerReadyToGo')
end
end
_HandleIncomingMessage = function(s, sessId, bundle)
local ate = _HandleInstantMessage(s, sessId, bundle)
if not ate then
if s.gameStarted then
table.insert(s.messages, bundle)
else
local gameOp = bundle[1]
_LogW('game not started, drop ' .. gameOp)
end
end
end
_ChanFromPlayer = function(s, playerId)
local sessId = assert(s.playerId2Sess[playerId])
return _ChanFromSess(s, sessId)
end
_ChanFromSess = function(s, sessId)
local sess = assert(s.sessions[sessId])
return sess.chan
end
------------------
local _ExecuteCommand = function(s, cmd)
_LogD('execute cmd: ' .. cmd)
local chunk, errmsg = load('return function(s)\n' .. cmd .. '\nend\n')
if not chunk then
return errmsg
end
local f = chunk()
local _, ret = pcall(f, s)
return ret
end
_Debug_OnServiceStarted = function(s)
if _UNITY['EDITOR'] then
FSDBG = csharp.checked_import('FullScreenDebugable')
FSDBG.instance:Editor_AddToolbarButton(
'server',
function()
s.native:Editor_ToggleGUI()
end
)
local title = ':'..s.port .. ' <-> '
if s.hasProxy then
title = title .. s.proxy.addr.addr .. ':' .. s.proxy.addr.port
else
title = title .. ' no proxy'
end
s.native:Editor_SetTitle(title)
local Screen = Unity.Screen
local x = Screen.width / 4
local y = Screen.height / 4
local width = Screen.width / 2
local height = Screen.height / 2
s.native:Editor_SetArea(x, y, width, height)
s.native:Editor_SetCmdHandler(
function(cmd)
local r = _ExecuteCommand(s, cmd)
FSDBG.instance:Editor_PopUp('server> '..tostring(r)..'\n')
end
)
end
end
return Server
|
function s030_baselab.main()
s030_baselab.PatrolRoutesGeneration()
s030_baselab.PatrolRoutesFinalNodesAssignation()
end
function s030_baselab.SetupDebugGameBlackboard()
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_CURRENT_SPECIAL_ENERGY", "f", 1000)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_MAX_SPECIAL_ENERGY", "f", 1000)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_SPECIAL_ENERGY", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_CURRENT_LIFE", "f", 299)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_MAX_LIFE", "f", 299)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_MISSILE_MAX", "f", 22)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_MISSILE_CURRENT", "f", 22)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_SUPER_MISSILE", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_ICE_MISSILE", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_POWER_BOMB", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_POWER_BOMB_MAX", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_POWER_BOMB_CURRENT", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_VARIA_SUIT", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_GRAVITY_SUIT", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_DOUBLE_JUMP", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_SPACE_JUMP", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_SCREW_ATTACK", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_FLOOR_SLIDE", "f", 1)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_MORPH_BALL", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_BOMB", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_LINE_BOMB", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_CHARGE_BEAM", "f", 1)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_WIDE_BEAM", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_DIFFUSION_BEAM", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_GRAPPLE_BEAM", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_PLASMA_BEAM", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_WEAPON_WAVE_BEAM", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_MAGNET_GLOVE", "f", 1)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_SPEED_BOOSTER", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_OPTIC_CAMOUFLAGE", "f", 1)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_GHOST_AURA", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_SONAR", "f", 0)
Blackboard.SetProp("PLAYER_INVENTORY", "ITEM_METROIDNIZATION", "f", 0)
end
local QUARENTINE_OPENED = Blackboard.GetProp("GAME_PROGRESS", "QUARENTINE_OPENED")
local LAB_EMMY_SPAWNED = false
local LAB_POSTXRELEASE_APPLIED = false
local L3_1 = false
function s030_baselab.InitFromBlackboard()
Game.ReinitPlayerFromBlackboard()
LAB_EMMY_SPAWNED = Scenario.ReadFromBlackboard(Scenario.LUAPropIDs.LAB_EMMY_SPAWNED, false)
LAB_POSTXRELEASE_APPLIED = Scenario.ReadFromBlackboard(Scenario.LUAPropIDs.LAB_POSTXRELEASE_APPLIED, false)
QUARENTINE_OPENED = Blackboard.GetProp("GAME_PROGRESS", "QUARENTINE_OPENED")
if QUARENTINE_OPENED == true then
s030_baselab.Activate_Setup_PostXRelease()
end
end
function s030_baselab.Activate_Setup_PostXRelease()
if LAB_POSTXRELEASE_APPLIED == false then
Game.PushSetup("PostXRelease", true, true)
Scenario.WriteToBlackboard(Scenario.LUAPropIDs.LAB_POSTXRELEASE_APPLIED, "b", true)
LAB_POSTXRELEASE_APPLIED = true
end
end
s030_baselab.tGetOnDeathOverrides = {ShowDeath = true, GoToMainMenu = false}
function s030_baselab.GetOnDeathOverrides()
return s030_baselab.tGetOnDeathOverrides
end
function s030_baselab.OnBeforeGenerate()
end
function s030_baselab.OnEmmyBaseLabGenerated(_ARG_0_, _ARG_1_)
CurrentScenario.oEmmyEntity = _ARG_1_
AI.SetWorldGraphToEmmy("LE_WorldGraph", _ARG_1_.sName)
s030_baselab.ChangePatrolEmmy("PATROLROUTE_01")
print("EMMY: Generation OK. Starting patrol: " .. _ARG_1_.AI.sCurrentPatrol)
end
function s030_baselab.OnEnter_EmmyLAB_Deactivation()
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) and CurrentScenario.oEmmyEntity ~= nil then
CurrentScenario.oEmmyEntity.bEnabled = false
print("EMMY DESACTIVADO")
end
end
function s030_baselab.OnEnter_EmmyLAB_Presentation()
print("ACTIVANDO EMMY")
GUI.AddEmmyMissionLogEntry("#MLOG_ENCOUNTER_EMMY_LAB")
local oActor = Game.GetActor("TG_EmmyLAB_Deactivation")
if oActor ~= nil then
oActor.bEnabled = false
end
Scenario.WriteToBlackboard(Scenario.LUAPropIDs.LAB_EMMY_SPAWNED, "b", true)
LAB_EMMY_SPAWNED = true
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) and CurrentScenario.oEmmyEntity ~= nil then
local oActor = Game.GetActor("LM_EmmyPresentation")
CurrentScenario.oEmmyEntity.bEnabled = false
CurrentScenario.oEmmyEntity.vPos = oActor.vPos
CurrentScenario.oEmmyEntity.vAng = oActor.vAng
CurrentScenario.oEmmyEntity.bEnabled = true
print("EMMY REACTIVADO")
end
local oShutter = Game.GetActor("doorshutter_001")
if oShutter ~= nil then
oShutter.ANIMATION:SetAction("opened", true)
end
end
function s030_baselab.EmmyLabSpawnSequenceEnd()
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) then
CurrentScenario.oEmmyEntity.AI:ForceStartChase()
end
end
function s030_baselab.DelayedEmmyLABSpawnSequence()
GUI.ShowMessage("#BASELAB_EMMY_PRESENTATION", true, "")
local oPlayer = Game.GetPlayer()
if oPlayer ~= nil then
oPlayer.INPUT:IgnoreInput(false, false, "OnEnter_EmmyLAB_Presentation")
end
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) and CurrentScenario.oEmmyEntity ~= nil then
local oActor = Game.GetActor("LM_EmmyPresentation")
CurrentScenario.oEmmyEntity.bEnabled = false
CurrentScenario.oEmmyEntity.vPos = oActor.vPos
CurrentScenario.oEmmyEntity.vAng = oActor.vAng
CurrentScenario.oEmmyEntity.bEnabled = true
print("EMMY REACTIVADO")
end
end
function s030_baselab.OnEmmyBaseLabDead()
Game.PushSetup("PostEmmy", true, true)
end
function s030_baselab.OnEmmyAbilityObtainedFadeOutCompleted()
Game.GetActor("TG_EnablePostEmmyEnemies").bEnabled = true
local oActor = Game.GetActor("centralunitmagmacontroller")
if oActor ~= nil then
oActor.CENTRALUNIT:OnEmmyAbilityObtainedFadeOutCompleted()
end
end
function s030_baselab.DelayedOnEmmyBaseLabDead()
GUI.ShowMessage("#PLACEHOLDER_EMMYBASELAB_KILLED", true, "")
local oPlayer = Game.GetPlayer()
if oPlayer ~= nil then
oPlayer.INPUT:IgnoreInput(false, false, "OnEmmyBaseLabDead")
end
end
function s030_baselab.OnEmmyDeathMessageSkipped()
end
function s030_baselab.OnUnlockEmmyDoors()
local oActor = Game.GetActor("centralunitmagmacontroller")
if oActor ~= nil then
oActor.CENTRALUNIT:UnlockDoors()
else
print("CENTRAL_UNIT: centralunitmagmacontroller not found")
end
end
function s030_baselab.OnUnlockEmmyDoors()
local oActor = Game.GetActor("centralunitmagmacontroller")
if oActor ~= nil then
oActor.CENTRALUNIT:UnlockDoors()
else
print("CENTRAL_UNIT: centralunitbaselabcontroller not found")
end
end
function s030_baselab.OnLockEmmyDoors()
local oActor = Game.GetActor("centralunitmagmacontroller")
if oActor ~= nil then
oActor.CENTRALUNIT:LockDoors()
else
print("CENTRAL_UNIT: centralunitbaselabcontroller not found")
end
end
function s030_baselab.OnCheckpoint_SpeedBooster()
s030_baselab.OnLockEmmyDoors()
end
function s030_baselab.PatrolRoutesGeneration()
local oActor = Game.GetActor("SP_Emmy")
if oActor ~= nil then
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_01")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_02")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_03")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_04")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_05")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_06")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_07")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_08")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_09")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_10")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_11")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_12")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_13")
oActor.SPAWNPOINT:AddPatrolShape("LS_PATROLEMMY_14")
end
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_01", "LS_PATROLEMMY_01")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_02", "LS_PATROLEMMY_02")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_03", "LS_PATROLEMMY_03")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_04", "LS_PATROLEMMY_04")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_05", "LS_PATROLEMMY_05")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_06", "LS_PATROLEMMY_06")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_07", "LS_PATROLEMMY_07")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_08", "LS_PATROLEMMY_08")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_09", "LS_PATROLEMMY_09")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_10", "LS_PATROLEMMY_10")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_11", "LS_PATROLEMMY_11")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_12", "LS_PATROLEMMY_12")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_13", "LS_PATROLEMMY_13")
AI.AddPatrol("LE_WorldGraph", "PATROLROUTE_14", "LS_PATROLEMMY_14")
print("s030_baselab.PatrolRoutesGeneration(): Patrol designation OK")
end
function s030_baselab.PatrolRoutesFinalNodesAssignation()
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_01", { "WorldGraph_21" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_01", { "WorldGraph_16", "WorldGraph_15" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_02", { "WorldGraph_5", "WorldGraph_11" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_02", { "WorldGraph_21" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_03", { "WorldGraph_22", "WorldGraph_24" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_03", { "WorldGraph_26" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_04", { "WorldGraph_57", "WorldGraph_56" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_04", { "WorldGraph_30", "WorldGraph_31" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_05", { "WorldGraph_56", "WorldGraph_38" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_05", { "WorldGraph_46" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_06", { "WorldGraph_46", "WorldGraph_47" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_06", { "WorldGraph_56" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_06", { "WorldGraph_31", "WorldGraph_35" }, 2)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_06", { "WorldGraph_55" }, 3)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_07", { "WorldGraph_65" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_07", { "WorldGraph_56" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_08", { "WorldGraph_60" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_08", { "WorldGraph_72" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_09", { "WorldGraph_60" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_09", { "WorldGraph_81" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_10", { "WorldGraph_75" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_10", { "WorldGraph_81" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_11", { "WorldGraph_1" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_11", { "WorldGraph_11" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_11", { "WorldGraph_17" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_12", { "WorldGraph_100", "WorldGraph_98" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_12", { "WorldGraph_94", "WorldGraph_93" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_12", { "WorldGraph_87", "WorldGraph_84" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_12", { "WorldGraph_85", "WorldGraph_86" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_13", { "WorldGraph_109" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_109" }, 0)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_117" }, 1)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_115" }, 2)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_111", "WorldGraph_112" }, 3)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_101" }, 4)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_107", "WorldGraph_105" }, 5)
AI.SetPatrolFinalNode("LE_WorldGraph", "PATROLROUTE_14", { "WorldGraph_104" }, 6)
print("s030_baselab.PatrolRoutesFinalNodesAssignation(): Final Nodes Assignation OK")
end
function s030_baselab.ChangePatrolEmmy(_ARG_0_)
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) then
CurrentScenario.oEmmyEntity.AI.sCurrentPatrol = _ARG_0_
print("EMMY: Assigned route " .. _ARG_0_)
else
print("EMMY: Not found, route " .. _ARG_0_ .. " not assigned")
end
end
function s030_baselab.OnEnter_PatrolEmmyActivator(_ARG_0_, _ARG_1_)
local sName = string.gsub(_ARG_0_.sName, "TG_PATROLEMMYACTIVATOR_", "PATROLROUTE_")
s030_baselab.ChangePatrolEmmy(sName)
end
function s030_baselab.OnExit_PatrolEmmyActivator(_ARG_0_, _ARG_1_)
end
function s030_baselab.OnEnter_EmmySpawnAfterAqua()
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) and CurrentScenario.oEmmyEntity ~= nil then
L3_1 = true
local oActor = Game.GetActor("LM_EmmySpawnAfterAqua")
CurrentScenario.oEmmyEntity.bEnabled = false
CurrentScenario.oEmmyEntity.vPos = oActor.vPos
CurrentScenario.oEmmyEntity.vAng = oActor.vAng
CurrentScenario.oEmmyEntity.bEnabled = true
s030_baselab.ChangePatrolEmmy("PATROLROUTE_13")
end
end
s030_baselab.tEmmyDoor = nil
function s030_baselab.OnWalkThroughEmmyDoor(_ARG_0_, _ARG_1_, _ARG_2_)
if Scenario.CheckEmmyAlive(CurrentScenario.oEmmyEntity) and LAB_EMMY_SPAWNED then
if _ARG_1_ then
if CurrentScenario.oEmmyEntity ~= nil then
local L3_2 = nil
if _ARG_2_ then
L3_2 = s030_baselab.HardEmmyRelocationDoor(_ARG_0_)
else
L3_2 = s030_baselab.EmmyRelocationDoor(_ARG_0_)
end
if L3_2 ~= nil then
local L4_2 = Game.GetActor(L3_2)
print(L4_2.sName)
CurrentScenario.oEmmyEntity.bEnabled = false
CurrentScenario.oEmmyEntity.vPos = L4_2.vPos
CurrentScenario.oEmmyEntity.vAng = L4_2.vAng
CurrentScenario.oEmmyEntity.bEnabled = true
end
end
else
CurrentScenario.oEmmyEntity.bEnabled = false
end
end
end
function s030_baselab.HardEmmyRelocationDoor(_ARG_0_)
print("Door: Hard " .. _ARG_0_.sName)
if _ARG_0_.sName == "dooremmy_000" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_000"
}
elseif _ARG_0_.sName == "dooremmy_001" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_004"
}
elseif _ARG_0_.sName == "dooremmy_003" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_010"
}
elseif _ARG_0_.sName == "dooremmy_004" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_010"
}
elseif _ARG_0_.sName == "dooremmy_005" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_015"
}
elseif _ARG_0_.sName == "dooremmy_006" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_016"
}
elseif _ARG_0_.sName == "dooremmy_008" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_022"
}
elseif _ARG_0_.sName == "dooremmy_009" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_021"
}
elseif _ARG_0_.sName == "dooremmy_010" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_026"
}
elseif _ARG_0_.sName == "dooremmy_012" then
if L3_1 then
L3_1 = false
return "nil"
else
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_027"
}
end
else
s030_baselab.tEmmyDoor = nil
end
if s030_baselab.tEmmyDoor ~= nil then
return s030_baselab.tEmmyDoor[math.random(table.maxn(s030_baselab.tEmmyDoor))]
else
return nil
end
end
function s030_baselab.EmmyRelocationDoor(_ARG_0_)
if _ARG_0_.sName == "dooremmy_000" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_000",
"LM_EmmyEntrancePoint_001",
"LM_EmmyEntrancePoint_002",
"LM_EmmyEntrancePoint_006"
}
elseif _ARG_0_.sName == "dooremmy_001" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_003",
"LM_EmmyEntrancePoint_005",
"LM_EmmyEntrancePoint_007"
}
elseif _ARG_0_.sName == "dooremmy_003" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_012",
"LM_EmmyEntrancePoint_010"
}
elseif _ARG_0_.sName == "dooremmy_004" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_010",
"LM_EmmyEntrancePoint_011",
"LM_EmmyEntrancePoint_013"
}
elseif _ARG_0_.sName == "dooremmy_005" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_023",
"LM_EmmyEntrancePoint_015",
"LM_EmmyEntrancePoint_017"
}
elseif _ARG_0_.sName == "dooremmy_006" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_015",
"LM_EmmyEntrancePoint_016",
"LM_EmmyEntrancePoint_020"
}
elseif _ARG_0_.sName == "dooremmy_008" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_022",
"LM_EmmyEntrancePoint_021",
"LM_EmmyEntrancePoint_024"
}
elseif _ARG_0_.sName == "dooremmy_009" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_021",
"LM_EmmyEntrancePoint_022"
}
elseif _ARG_0_.sName == "dooremmy_010" then
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_025",
"LM_EmmyEntrancePoint_026"
}
elseif _ARG_0_.sName == "dooremmy_012" then
if L3_1 then
L3_1 = false
return "nil"
else
s030_baselab.tEmmyDoor = {
"LM_EmmyEntrancePoint_027",
"LM_EmmyEntrancePoint_028",
"LM_EmmyEntrancePoint_029"
}
end
else
s030_baselab.tEmmyDoor = nil
end
if s030_baselab.tEmmyDoor ~= nil then
return s030_baselab.tEmmyDoor[math.random(table.maxn(s030_baselab.tEmmyDoor))]
else
return nil
end
end
function s030_baselab.OnTeleport_Checkpoint_CU()
Game.AddSF(1, "s030_baselab.Checkpoint_RelocatingEmmy_CU", "")
end
function s030_baselab.Checkpoint_RelocatingEmmy_CU()
if CurrentScenario.oEmmyEntity ~= nil then
local oActor = Game.GetActor("LM_EmmyEntrancePoint_027")
if oActor ~= nil then
CurrentScenario.oEmmyEntity.bEnabled = false
CurrentScenario.oEmmyEntity.vPos = oActor.vPos
CurrentScenario.oEmmyEntity.vAng = oActor.vAng
CurrentScenario.oEmmyEntity.bEnabled = true
s030_baselab.ChangePatrolEmmy("PATROLROUTE_12")
end
end
end
function s030_baselab.OnEnter_AP_04()
local L0_2 = Game.GetActor("accesspoint_000")
local L1_2 = Blackboard.GetProp("GAME_PROGRESS", "ADAMDIALOGUE")
if L0_2 ~= nil then
if L1_2 == "DIAG_ADAM_MAGMA_2" then
L0_2.USABLE:ActiveDialogue("DIAG_ADAM_LAB_1")
Blackboard.SetProp("GAME_PROGRESS", "ADAMDIALOGUE", "s", "DIAG_ADAM_LAB_1")
elseif L1_2 == "DIAG_ADAM_CAVE_4" then
local L2_2 = Blackboard.GetProp("PLAYER_INVENTORY", "ITEM_SCREW_ATTACK")
if L2_2 ~= nil and L2_2 > 0 then
L0_2.USABLE:ActiveDialogue("DIAG_ADAM_AQUA_3")
Blackboard.SetProp("GAME_PROGRESS", "ADAMDIALOGUE", "s", "DIAG_ADAM_AQUA_3")
end
end
end
end
function s030_baselab.OnEnter_AP_06()
local L0_2 = Game.GetActor("accesspoint_001")
local L1_2 = Blackboard.GetProp("GAME_PROGRESS", "ADAMDIALOGUE")
if L0_2 ~= nil then
if L1_2 == "DIAG_ADAM_AQUA_1" then
L0_2.USABLE:ActiveDialogue("DIAG_ADAM_LAB_2")
Blackboard.SetProp("GAME_PROGRESS", "ADAMDIALOGUE", "s", "DIAG_ADAM_LAB_2")
elseif L1_2 == "DIAG_ADAM_CAVE_4" then
local L2_2 = Blackboard.GetProp("PLAYER_INVENTORY", "ITEM_SCREW_ATTACK")
if L2_2 ~= nil and L2_2 > 0 then
L0_2.USABLE:ActiveDialogue("DIAG_ADAM_AQUA_3")
Blackboard.SetProp("GAME_PROGRESS", "ADAMDIALOGUE", "s", "DIAG_ADAM_AQUA_3")
end
end
end
end
function s030_baselab.SubAreaChangeRequest(_ARG_0_, _ARG_1_, _ARG_2_, _ARG_3_)
Scenario.SubAreaChangeRequest(_ARG_0_, _ARG_1_, _ARG_2_, _ARG_3_)
end
function s030_baselab.OnSubAreaChange(_ARG_0_, _ARG_1_, _ARG_2_, _ARG_3_, _ARG_4_)
end
function s030_baselab.OnEnter_ActivatePostBlackout()
Game.PushSetup("PostBlackout", true, true)
Game.StopMusic(true)
end
function s030_baselab.Event_ShakerNaut_Activation()
local oActor1 = Game.GetActor("SP_Shakernaut_001B_shakernaut")
if oActor1 ~= nil then
oActor1.ANIMATION:SetAction("spawn_baselab_part015_relaxtopath", true)
end
local oActor2 = Game.GetActor("SP_Shakernaut_001B")
if oActor2 ~= nil then
oActor2.SPAWNPOINT:Deactivate()
end
local oActor3 = Game.GetActor("SP_Shakernaut_001")
if oActor3 ~= nil then
oActor3.SPAWNPOINT:Activate()
end
end
function s030_baselab.DetectingDirection()
local L0_2 = Game.GetActor("SP_Shakernaut_001B_shakernaut")
if L0_2 ~= nil then
if L0_2.ANIMATION:IsPlayingAnim("spawn_baselab_part015_relaxtopath", false) then
Game.AddSF(0, "s030_baselab.DetectingDirection", "")
else
local L1_2 = Game.GetPlayer()
local L2_2 = V3D(-1, 0, 0)
if L1_2 ~= nil then
L2_2 = L1_2.vPos - L0_2.vPos
end
if L2_2.x > 0 then
L0_2.ANIMATION:SetAction("spawn_baselab_part015_turn_right", true)
L2_2 = V3D(1, 0, 0)
else
L0_2.ANIMATION:SetAction("spawn_baselab_part015_turn_left", true)
L2_2 = V3D(-1, 0, 0)
end
L0_2.AI:SetNavigationDir(L2_2)
end
end
end
function s030_baselab.OnEnter_ActivatePostBlackout2()
Game.PushSetup("PostBlackout2", true, true)
Game.StopMusic(true)
end
function s030_baselab.OnEnter_ActivatePostEmmyEnemies(_ARG_0_, _ARG_1_)
local oActor1 = Game.GetActor("SG_PostEmmy_000")
local oActor2 = Game.GetActor("SG_PostEmmy_001")
if oActor1 ~= nil then
oActor1.SPAWNGROUP:EnableSpawnGroup()
end
if oActor2 ~= nil then
oActor2.SPAWNGROUP:EnableSpawnGroup()
end
_ARG_0_.bEnabled = false
end
function s030_baselab.OnCutscene39End()
s030_baselab.EmmyLabSpawnSequenceEnd()
local oActor = Game.GetActor("emmyvalve_reg_gen_002")
if oActor ~= nil then
oActor.EMMYVALVE:CleanForceStateFlag()
end
end
|
local helper = require("piemenu.lib.testlib.helper")
describe("piemenu.lib.list", function()
before_each(helper.before_each)
after_each(helper.after_each)
for _, c in ipairs({
{ items = {}, expected = {} },
{ items = { 1 }, expected = { { 1, 1, 1 } } },
{ items = { 1, 2 }, expected = { { 2, 1, 2 }, { 1, 2, 1 } } },
{ items = { 1, 2, 3 }, expected = { { 3, 1, 2 }, { 1, 2, 3 }, { 2, 3, 1 } } },
}) do
it(("tri_circular(%s) == %s"):format(vim.inspect(c.items), vim.inspect(c.expected)), function()
local actual = require("piemenu.lib.list").tri_circular(c.items)
assert.is_same(c.expected, actual)
end)
end
for _, c in ipairs({
{ items = {}, expected = {} },
{ items = { 4 }, expected = { 4 } },
{ items = { 1, 2, 3, 4 }, expected = { 4, 1, 2, 3 } },
{ items = { 1, 2, 3 }, expected = { 1, 2, 3 } },
}) do
it(("circular_shift(%s, greater_than_3) == %s"):format(vim.inspect(c.items), vim.inspect(c.expected)), function()
local actual = require("piemenu.lib.list").circular_shift(c.items, function(item)
return item > 3
end)
assert.is_same(c.expected, actual)
end)
end
end)
|
require "CustomSharpeners"
print(nn.MulSoftMax)
gigi = nn.MulSoftMax()
print(gigi:forward(torch.Tensor{0.1, 0.3}))
|
require 'nn'
require 'nngraph'
require 'optim'
require 'cutorch'
require 'cunn'
require 'image'
require 'cudnn'
matio=require 'matio'
cmd = torch.CmdLine()
cmd:text()
cmd:text('Options:')
cmd:option('--modelPath','/home/jchen16/NEW/code/checkpoint/fungus_XX_20_seq_whole/unet_420000.000000.bin','path to the trained model')
cmd:option('--imageDir', '/home/jchen16/NEW/data/fungus/training_data', 'the directory to load')
cmd:option('--outputDir', '/home/jchen16/NEW/data/fungus/encoder', 'the directory to save the input for RNN')
cmd:option('--ext','.mat','only load a specific type of images')
cmd:option('--training',false,'training mode or not')
cmd:option('--RAM',false,'load to RAM or not')
cmd:option('--XX',20,'the key parameter to determine the size of image')
cmd:option('--rho',3,'the length of sequence in RNN')
cmd:option('--gpu',1,'the gpu to use')
cmd:option('--outputLayer',2,'1 means the last one, 2 means the second last one')
cmd:option('--imageType',1,'1: grayscale, 3: RGB')
cmd:text()
opt = cmd:parse(arg or {})
XX=opt.XX
cutorch.setDevice(opt.gpu)
-- 1. Get the list of files in the given directory
files = {}
for file in paths.files(opt.imageDir) do
if file:find(opt.ext .. '$') then
table.insert(files, paths.concat(opt.imageDir,file))
end
end
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. opt.ext)
end
table.sort(files, function (a,b) return a < b end)
if opt.RAM then
-- 2. Load all the files into RAM
data = {}
for i,file in ipairs(files) do
-- load each image
table.insert(data, matio.load(file))
end
end
-- 3. Load Model
unet=torch.load(opt.modelPath)
unet:evaluate()
-- 4. Process images one by one
for i=1, #files do
local image_seq, target_seq
if opt.RAM then
image_seq = data[i].image
if opt.training then
target_seq = data[i].target
end
else
local data = matio.load(files[i])
image_seq = data.image
if opt.training then
target_seq = data.target
end
end
local fm_seq={}
for j=1,#image_seq do
print('i='..i..', j='..j)
local input_image = torch.FloatTensor(1,opt.imageType,16*XX+92,16*XX+92)
input_image[1][1]=image_seq[j]
local b=unet:forward(input_image:cuda()):double()
local fm
if opt.outputLayer==1 then
fm = b[1]
elseif opt.outputLayer==2 then
fm=unet.modules[66].output[1]
end
table.insert(fm_seq, fm:float())
print(fm:size())
if i==1 and j<10 then
local softmax = nn.SoftMax()
out = softmax:forward(b[1])
local str0= string.format('test%d.png',j);
image.save(str0,out:select(1,4))
--[[
for kk=1,fm:size(1) do
local a=fm:select(1,kk)
print(a[1][100])
print(type(a))
local str1= string.format('test_fm_%d.png',kk);
image.save(str1,a:float())
end
--]]
end
end
if opt.training then
obj={input=fm_seq, target=target_seq}
else
obj={input=fm_seq}
end
local str= string.format('%s/train_%d.t7',opt.outputDir,i);
torch.save(str,obj)
collectgarbage()
-- write the segmentation result to file
--local filename=string.format('%s/prob_%d.png',opt.segDir,i);
--image.save(filename,output_image)
end
|
cooldown = 0
cooldownTimer = nil
localPlayer = getLocalPlayer()
function isLSPD()
return getTeamName(getPlayerTeam(getLocalPlayer())) == "Los Santos Police Department"
end
function switchMode()
if (getPedWeapon(localPlayer)==24) and (getPedTotalAmmo(localPlayer)>0) then -- has an un-empty deagle
local mode = getElementData(localPlayer, "deaglemode")
if mode == 0 then -- tazer mode
setElementData(localPlayer, "deaglemode", 1, true)
outputChatBox( "You switched your multipurpose handgun to Lethal Mode", 0, 255, 0 )
elseif mode == 1 and isLSPD() then -- lethal mode
outputChatBox( "You switched your multipurpose handgun to Radar Mode", 0, 255, 0 )
setElementData(localPlayer, "deaglemode", 2, true)
elseif mode == 2 or mode == 1 then -- radar gun mode
outputChatBox( "You switched your multipurpose handgun to Tazer Mode", 0, 255, 0 )
setElementData(localPlayer, "deaglemode", 0, true)
end
triggerServerEvent("sendLocalMeAction", localPlayer, localPlayer, "switched their multipurpose handgun mode.")
end
end
function bindKeys(res)
bindKey("n", "down", switchMode)
local mode = getElementData(localPlayer, "deaglemode")
if not (mode) then setElementData(localPlayer, "deaglemode", 0, true) end
end
addEventHandler("onClientResourceStart", getResourceRootElement(), bindKeys)
function enableCooldown()
cooldown = 1
cooldownTimer = setTimer(disableCooldown, 3000, 1)
toggleControl("fire", false)
setElementData(getLocalPlayer(), "deagle:reload", true)
end
function disableCooldown()
cooldown = 0
toggleControl("fire", true)
setElementData(getLocalPlayer(), "deagle:reload", false)
if (cooldownTimer~=nil) then
killTimer(cooldownTimer)
cooldownTimer = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), disableCooldown)
function weaponFire(weapon, ammo, ammoInClip, hitX, hitY, hitZ, hitElement)
if (weapon==24) then -- deagle
local mode = getElementData(localPlayer, "deaglemode")
if (mode==0) then -- tazer mode
enableCooldown()
local px, py, pz = getElementPosition(localPlayer)
local distance = getDistanceBetweenPoints3D(hitX, hitY, hitZ, px, py, pz)
if (distance<35) then
fxAddSparks(hitX, hitY, hitZ, 1, 1, 1, 1, 10, 0, 0, 0, true, 3, 1)
end
playSoundFrontEnd(38)
triggerServerEvent("tazerFired", localPlayer, hitX, hitY, hitZ, hitElement)
end
end
end
addEventHandler("onClientPlayerWeaponFire", localPlayer, weaponFire)
function weaponAim(target)
if (target) then
if (getElementType(target)=="vehicle") then
if (getPedWeapon(localPlayer)==24) then
local mode = getElementData(localPlayer, "deaglemode")
if (mode==2) then
local speedx, speedy, speedz = getElementVelocity(target)
actualspeed = math.ceil(((speedx^2 + speedy^2 + speedz^2)^(0.5)*100))
outputChatBox(getVehicleName(target) .. " clocked in at " .. actualspeed .. " km/h.", 255, 194, 14)
end
end
end
end
end
addEventHandler("onClientPlayerTarget", getRootElement(), weaponAim)
-- code for the target/tazed person
function cancelTazerDamage(attacker, weapon, bodypart, loss)
if (weapon==24) then -- deagle
local mode = getElementData(attacker, "deaglemode")
if (mode==0 or mode==2) then -- tazer mode / radar gun mode
cancelEvent()
end
end
end
addEventHandler("onClientPlayerDamage", localPlayer, cancelTazerDamage)
function showTazerEffect(x, y, z)
fxAddSparks(x, y, z, 1, 1, 1, 1, 100, 0, 0, 0, true, 3, 2)
playSoundFrontEnd(38)
end
addEvent("showTazerEffect", true )
addEventHandler("showTazerEffect", getRootElement(), showTazerEffect)
local underfire = false
local fireelement = nil
local localPlayer = getLocalPlayer()
local originalRot = 0
local shotsfired = 0
function onTargetPDPed(element)
if (isElement(element)) then
if (getElementType(element)=="ped") and (getElementModel(element)==282) and not (underfire) and (getControlState("aim_weapon")) then
underfire = true
fireelement = element
originalRot = getPedRotation(element)
addEventHandler("onClientRender", getRootElement(), makeCopFireOnPlayer)
addEventHandler("onClientPlayerWasted", getLocalPlayer(), onDeath)
end
end
end
addEventHandler("onClientPlayerTarget", getLocalPlayer(), onTargetPDPed)
function makeCopFireOnPlayer()
if (underfire) and (fireelement) then
local rot = getPedRotation(localPlayer)
local x, y, z = getPedBonePosition(localPlayer, 7)
setPedRotation(fireelement, rot - 180)
setPedControlState(fireelement, "aim_weapon", true)
setPedAimTarget(fireelement, x, y, z)
setPedControlState(fireelement, "fire", true)
shotsfired = shotsfired + 1
if (shotsfired>40) then
triggerServerEvent("killmebyped", getLocalPlayer(), fireelement)
end
end
end
function onDeath()
if (fireelement) and (underfire) then
setPedControlState(fireelement, "aim_weapon", false)
setPedControlState(fireelement, "fire", false)
setPedRotation(fireelement, originalRot)
fireelement = nil
underfire = false
removeEventHandler("onClientRender", getRootElement(), makeCopFireOnPlayer)
removeEventHandler("onClientPlayerWasted", getLocalPlayer(), onDeath)
end
end |
--[[
Scripted By: Xander1998 (X. Cross)
--]]
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
server_script "server.lua"
client_script "client.lua" |
--- Array class.
-- Useful array object specialized for numerical values, although most
-- operations work with arbitrary values as well. Functions taking functions
-- may accept _string lambdas_, which have either a placeholder '_' or two
-- placeholders '_1' or '_2'. As a special case, if the expression has no
-- identifier chars, it's assumed to be a binary operator. So '+' is equivalent
-- to '_1+_2'
-- The '+','-','*','/' operators are overloaded, so expressions like `2*x+1` or 'x+y'
-- work as expected. With two array arguments, '*' and '/' mean element-wise operations.
-- @module android.array
local array = {}
array.__index = array
local function _array (a)
return setmetatable(a,array)
end
--- array constructor.
-- Useful for generating a set of values between `x1` and `x2`.
-- @param x1 initial value in range, or a table of values. (If that table
-- is itself an `array` then this acts like a copy constructor)
-- @param x2 final value in range
-- @param dx interval.
-- @treturn array
function array.new (x1,x2,dx)
local xvalues = {}
if x1 ~= nil then
if type(x1) == 'table' then
if getmetatable(x1) == array then
return x1:sub()
else
return _array(x1)
end
end
local i = 1
for x = x1, x2 , dx do
xvalues[i] = x
i = i + 1
end
end
return _array(xvalues)
end
local _function_cache = {}
local function _function_arg (f)
if type(f) == 'string' then
if _function_cache[f] then return _function_cache[f] end
if not f:match '[_%a]' then f = '_1'..f..'_2' end
local args = f:match '_2' and '_1,_2' or '_'
local chunk,err = loadstring('return function('..args..') return '..f..' end',f)
if err then error("bad function argument "..err,3) end
local fn = chunk()
_function_cache[f] = fn
return fn
end
return f
end
local function _map (src,i1,i2,dest,j,f,...)
f = _function_arg(f)
for i = i1,i2 do
dest[j] = f(src[i],...)
j = j + 1
end
return dest
end
--- map a function over this array.
-- @param f a function, callable or 'string lambda'
-- @param ... any other arguments to the function
-- @treturn array
function array:map (f,...)
return _array(_map(self,1,#self,{},1,f,...))
end
--- apply the function to each element of this array.
-- @param f function as in `array.map`
function array:apply (f,...)
_map(self,1,#self,self,1,f,...)
end
--- map a function over two arrays.
-- @param f as with `array.may` but must have at least two arguments.
-- @tparam array other
-- @treturn array
function array:map2 (f,other)
if #self ~= #other then error("arrays not the same size",2) end
f = _function_arg(f)
local res = {}
for i = 1,#self do
res[i] = f(self[i],other[i])
end
return _array(res)
end
--- find the index corresponding to `value`.
-- If it isn't an exact match, will give an index with a
-- _fractional part_.
-- @param value
-- @treturn number
function array:find_linear (value)
for i = 1,#self do
local v = self[i]
if v >= value then
if v > value then
local x1,x2 = self[i-1],self[i]
return i-1 + (value-x1)/(x2-x1)
else
return i -- on the nose!
end
end
end
end
local floor = math.floor
local function fsplit (x)
local i = floor(x)
return i, x - i
end
--- get the numerical value at `idx`.
-- As with `array.find_linear` this index may have
-- a fractional part, allowing for linear interpolation.
-- @return number
function array:at (idx)
local i,delta = fsplit(idx)
local res = self[i]
if delta ~= 0 then
res = delta*(self[i+1]-self[i])
end
return res
end
array.append, array.remove = table.insert, table.remove
--- extend this array with values from `other`
-- @tparam array other
function array:extend (other)
_map(other,1,#other,self,#self+1,'_')
end
--- get a 'slice' of the array.
-- This works like `string.sub`; `i2` may be a negative integer.
-- Like with `array.at` the indices may have fractional parts.
function array:sub (i1,i2)
i1 = i1 or 1
i2 = i2 or -1
if i2 < 0 then i2 = #self + i2 + 1 end -- -1 is #self, and so forth
local res,j = {},1
local int1,int2 = floor(i1),floor(i2)
if i1 ~= int1 then
res[j] = self:at(i1)
j = j + 1
end
for i = int1,int2 do
res[j] = self[i]
j = j + 1
end
if i2 ~= int2 then
res[j] = self:at(i2)
end
return _array(res)
end
--- concatenation
-- @tparam list other
-- @treturn array
function array:__concat (other)
local res = self:sub(1)
res:extend(other)
return res
end
local function mapm(a1,op,a2)
local M = type(a2)=='table' and array.map2 or array.map
return M(a1,op,a2)
end
--- elementwise arithmetric operations
function array.__add(a1,a2) return mapm(a1,'_1 + _2',a2) end
function array.__sub(a1,a2) return mapm(a1,'_1 - _2',a2) end
function array.__div(a1,a2) return mapm(a1,'_1 / _2',a2) end
function array.__mul(a1,a2) return mapm(a2,'_1 * _2',a1) end
function array:__tostring ()
local n,cb = #self,']'
if n > 15 then
n = 15
cb = '...]'
end
local strs = _map(self,1,n,{},1,tostring)
return '['..table.concat(strs,',')..cb
end
--- adds a given method to this array for calling that method over all objects.
function array:forall_method (name)
self[name] = function (self,...)
for i = 1,#self do
local obj = self[i]
obj[name](obj,...)
end
end
end
--- create an iterator over this array's values.
-- @param f optional function for filtering the
-- iterator
-- @return an iterator
function array:iter (f)
local i = 0
if not f then
return function()
i = i + 1
return self[i]
end
else
f = _function_arg(f)
return function()
local val
repeat
i = i + 1
val = self[i]
until val == nil or f(val)
return val
end
end
end
--- get the minimum and maximum values of this array.
-- The values must be comparable!
-- @return minimum
-- @return maximum
function array:minmax ()
local min,max = math.huge,-math.huge
for i = 1,#self do
local val = self[i]
if val > max then max = val end
if val < min then min = val end
end
return min,max
end
--- 'reduce' an array using a function.
-- @param f a function
function array:reduce (f)
f = _function_arg(f)
local res = self[1]
for i = 2,#self do
res = f(self[i],res)
end
return res
end
--- sum all values in an array
function array:sum ()
return self:reduce '+'
end
--- scale an array so that the sum of its values is one.
-- @return this array
function array:normalize ()
self:apply('/',self:sum())
return self
end
--- create a function which scales values between two ranges.
-- @number xmin input min
-- @number xmax input max
-- @number min output min
-- @number max output max
-- @treturn func of one argument
function array.scaler (xmin,xmax,min,max)
local xd = xmax-xmin
local scl = (max-min)/xd
return function(x)
return scl*(x - xmin) + min
end
end
--- scale this array to the specified range
-- @number min output min
-- @number max output max
-- @return this array
function array:scale_to (min,max)
local xmin,xmax = self:minmax()
self:apply(array.scaler(xmin,xmax,min,max))
return self
end
setmetatable(array,{
__call = function(_,...) return array.new(...) end
})
return array
|
-- **color(s: str, arg1, arg2. ...):str**
local function color(s,...)
local all = {red=31, green=32, yellow=33, purple=34}
print('\27[1m\27['.. all[s] ..'m'..string.format(...)..'\27[0m') end
-- **sfmt(fmt :string, ?arg1 :any, ?arg2 :any, ...)**
-- format a string
local function sfmt(...) return string.format(...) end
-- **fmt(fmt :string, ?arg1 :any, ?arg2 :any, ...)**
-- format and print t a string.
local function fmt( ...) io.write(sfmt(...)) end
return {color=color, fmt=fm, sfmt=sfmt}
|
function Netharel_OnEnterCombat(Unit,Event)
Unit:RegisterEvent("Netharel_DebilitatingStrike", 15000, 0)
Unit:RegisterEvent("Netharel_Evasion", 30000, 0)
Unit:RegisterEvent("Netharel_ManaBurn", 7000, 0)
Unit:RegisterEvent("Netharel_Metamorphosis", 1000, 1)
end
function Netharel_DebilitatingStrike(Unit,Event)
Unit:FullCastSpellOnTarget(39135,Unit:GetClosestPlayer())
end
function Netharel_Evasion(Unit,Event)
Unit:FullCastSpellOnTarget(37683,Unit:GetClosestPlayer())
end
function Netharel_ManaBurn(Unit,Event)
Unit:FullCastSpellOnTarget(39262,Unit:GetClosestPlayer())
end
function Netharel_Metamorphosis(Unit,Event)
if Unit:GetHealthPct() == 10 then
Unit:CastSpell(36298)
end
end
function Netharel_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function Netharel_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(21164, 1, "Netharel_OnEnterCombat")
RegisterUnitEvent(21164, 2, "Netharel_OnLeaveCombat")
RegisterUnitEvent(21164, 4, "Netharel_OnDied") |
-- Junction size
-- Selection type, per player_data
-- TODO: possibly allow junction size as a setting even though it could potentially require recalculation of data if it exceeds previous maximum
-- TODO: locale for setting and shortcut
data:extend({
--[[{type = "int-setting",
name = "tte-max-junction-size",
setting_type = "runtime-per-user",
default_value = 128,
minimum_value =
},--]]
{
type = "string-setting",
name = "tte-selection-mode",
setting_type = "runtime-per-user",
default_value = "Entities",
allowed_values = {"Entities", "Trains"}
}
})
|
------------------------------------------------------------------------------------------------------------------------
-- Game Type Manager Server
-- Author Morticai (META) - (https://www.coregames.com/user/d1073dbcc404405cbef8ce728e53d380)
-- Date: 2021/3/4
-- Version 0.1.2
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- REQUIRES
------------------------------------------------------------------------------------------------------------------------
local ABGS = require(script:GetCustomProperty("APIBasicGameState"))
while not _G.META_GAME_MODES do
Task.Wait()
end
local GT_API = _G.META_GAME_MODES
------------------------------------------------------------------------------------------------------------------------
-- OBJECTS
------------------------------------------------------------------------------------------------------------------------
local ROOT = script:GetCustomProperty("ROOT"):WaitForObject()
local GAME_TYPE_LIST = script:GetCustomProperty("GameTypesData"):WaitForObject()
local NETWORKED = script:GetCustomProperty("GameTypeNetworked"):WaitForObject()
local DEFAULT_GAME_STATE = ROOT:GetCustomProperty("DEFAULT_GAME_ID")
------------------------------------------------------------------------------------------------------------------------
-- LOCAL VARIABLES
------------------------------------------------------------------------------------------------------------------------
local currentGameTypeId
local scoreLimit
local roundStartTime = nil
local listeners = {}
local joinedTimes = {}
------------------------------------------------------------------------------------------------------------------------
-- LOCAL FUNCTIONS
------------------------------------------------------------------------------------------------------------------------
local function SetRespawnFlag(player)
if currentGameTypeId and currentGameTypeId > 0 and GT_API.GetShouldRespawn(currentGameTypeId) then
player:SetResource("GM.RESPAWN_ENABLED", 1)
else
player:SetResource("GM.RESPAWN_ENABLED", 0)
end
end
local function SetPlayersRespawn()
for _, player in ipairs(Game.GetPlayers()) do
SetRespawnFlag(player)
end
end
local function SetCurrentGameId(gameTypeId)
NETWORKED:SetNetworkedCustomProperty("GAME_TYPE_ID", gameTypeId)
currentGameTypeId = gameTypeId
Task.Wait()
SetPlayersRespawn()
end
local function SetRoundDuration(duration)
NETWORKED:SetNetworkedCustomProperty("ROUND_DURATION", duration)
end
local function GetCurrentGameId()
currentGameTypeId = NETWORKED:GetCustomProperty("GAME_TYPE_ID")
return currentGameTypeId
end
local function OnGameTypeChanged(object, string)
if object == NETWORKED then
GetCurrentGameId()
end
end
local function CleanUp(player)
if not Object.IsValid(player) then
return
end
if not listeners[player.id] then
return
end
for _, listener in pairs(listeners[player.id]) do
if listener.isConnected then
listener:Disconnect()
end
end
listeners[player.id] = nil
end
local function MarkPlayersWhoPlayedMoreThanHalf()
local duration = time() - roundStartTime
local roundMidTime = roundStartTime + duration / 2
for _, player in ipairs(Game.GetPlayers()) do
if joinedTimes[player.id] <= roundMidTime then
player.serverUserData.playedHalfRound = true
end
end
end
------------------------------------------------------------------------------------------------------------------------
-- GLOBAL FUNCTIONS
------------------------------------------------------------------------------------------------------------------------
function Int()
GT_API.RegisterGameTypes(GAME_TYPE_LIST)
Task.Wait(1)
SetCurrentGameId(DEFAULT_GAME_STATE)
end
-- nil OnPlayerDied(Player, Damage)
function OnPlayerDied(player, damage)
GT_API.OnPlayerDied(player, damage, currentGameTypeId)
end
-- nil OnPlayerDied(Player, Damage)
function OnPlayerDamaged(player, damage)
GT_API.OnPlayerDamaged(player, damage, currentGameTypeId)
end
function OnPlayerLeft(player)
CleanUp(player)
Task.Wait() -- Wait one frame to make sure player that left is no longer in game
if ABGS.GetGameState() == ABGS.GAME_STATE_ROUND then
local players = Game.GetPlayers()
local shouldEnd = true
local lastTeam
for _, remainingPlayer in ipairs(players) do
lastTeam = lastTeam or remainingPlayer.team
if remainingPlayer.team ~= lastTeam then
shouldEnd = false
end
end
if lastTeam and #players <= 1 or lastTeam and shouldEnd then
_G["GameWinner"] = lastTeam
Game.SetTeamScore(lastTeam, 5)
Task.Wait()
Events.Broadcast("TeamVictory", lastTeam)
ABGS.SetGameState(ABGS.GAME_STATE_ROUND_END)
end
elseif ABGS.GetGameState() == ABGS.GAME_STATE_LOBBY then
local players = Game.GetPlayers()
if #players <= 1 then
ABGS.SetGameState(ABGS.GAME_STATE_LOBBY)
end
end
end
-- nil OnPlayerJoined(Player)
-- Register the diedEvent when a player joins
function OnPlayerJoined(player)
listeners[player.id] = {}
listeners[player.id]["diedEvent"] = player.diedEvent:Connect(OnPlayerDied)
listeners[player.id]["damagedEvent"] = player.damagedEvent:Connect(OnPlayerDamaged)
joinedTimes[player.id] = time()
SetRespawnFlag(player)
Task.Wait()
if ABGS.GetGameState() == ABGS.GAME_STATE_ROUND_END then
if not Object.IsValid(player) then
return
end
for _, equipment in pairs(player:GetEquipment()) do -- remove all equipment
if Object.IsValid(equipment) then
equipment:Destroy()
end
end
Events.Broadcast("EmptyBackpack", player)
player.movementControlMode = MovementControlMode.NONE
player.lookControlMode = LookControlMode.NONE
Task.Spawn(
function()
while ABGS.GetGameState() == ABGS.GAME_STATE_ROUND_END do
Task.Wait()
end
player.movementControlMode = MovementControlMode.LOOK_RELATIVE
player.lookControlMode = LookControlMode.RELATIVE
end
)
end
end
-- nil Tick(float)
-- Watches for a team hitting the maximum score and ends the round
function Tick(deltaTime)
if not ABGS.IsGameStateManagerRegistered() then
return
end
if ABGS.GetGameState() == ABGS.GAME_STATE_ROUND then
local winningTeam = nil
for i = 0, 4 do
if Game.GetTeamScore(i) >= GT_API.GetCurrentScoreLimit(currentGameTypeId) then
if winningTeam then
Events.Broadcast("TieVictory")
ABGS.SetGameState(ABGS.GAME_STATE_ROUND_END)
_G["GameWinner"] = i
return
else
winningTeam = i
end
end
end
if winningTeam then
_G["GameWinner"] = winningTeam
SetCurrentGameId(0) -- Used to reset Game Modes
Events.Broadcast("TeamVictory", winningTeam)
ABGS.SetGameState(ABGS.GAME_STATE_ROUND_END)
--NETWORKED:SetNetworkedCustomProperty("GAME_TYPE_ID", 1)
end
end
end
function OnGameStateChanged(oldState, newState, hasDuration, stateTime)
if newState == ABGS.GAME_STATE_ROUND_END and oldState ~= ABGS.GAME_STATE_ROUND_END then
SetCurrentGameId(0) -- Used to reset Game Modes
if not roundStartTime then
roundStartTime = 0
end
SetRoundDuration(time() - roundStartTime)
MarkPlayersWhoPlayedMoreThanHalf()
end
if newState == ABGS.GAME_STATE_ROUND and oldState ~= ABGS.GAME_STATE_ROUND then
local currentState = GetCurrentGameId()
roundStartTime = time()
if currentState > 0 then
Events.BroadcastToAllPlayers("BannerMessage", nil, 5, currentState)
Events.Broadcast("GM.START", currentState)
end
end
end
------------------------------------------------------------------------------------------------------------------------
-- INTALIZATION
------------------------------------------------------------------------------------------------------------------------
Game.playerJoinedEvent:Connect(OnPlayerJoined)
Game.playerLeftEvent:Connect(OnPlayerLeft)
NETWORKED.networkedPropertyChangedEvent:Connect(OnGameTypeChanged)
Events.Connect("GameStateChanged", OnGameStateChanged)
Int()
|
-- FIFO, we push element from left, pop from right,
-- new element is at left, old element is at right
-- because redis has no reversely retrieve method on list
module(..., package.seeall)
local List = require 'lglib.list'
local rdlist = require 'bamboo.db.redis.list'
local db = BAMBOO_DB
function save (key, tbl, length)
for i,v in ipairs(tbl) do
push(key,v,length);
end
end
function update (key, tbl, length)
for i,v in ipairs(tbl) do
push(key,v,length);
end
end
function push (key, val, length)
local len = db:llen(key)
if len < length then
db:lpush(key, val)
else
-- if FIFO is full, push this element from left, pop one old from right
db:rpop(key)
db:lpush(key, val)
end
end
function pop( key )
return rdlist.pop(key)
end
function remove( key, val )
return rdlist.remove(key, val)
end
function retrieve( key )
return rdlist.retrieve(key)
end
function len( key )
return rdlist.len(key)
end
function del( key )
return rdlist.del(key)
end
function fakedel(key)
return db:rename(key, 'DELETED:' + key)
end
function has(key, obj)
return rdlist.have(key, obj)
end
|
-- Various entities modelling the juju state and the model
require "scriptlets-driver.base"
Model = JujuEntity:new()
-- function Model.load_config
Config = JujuEntity:new()
Application = JujuEntity:new()
Unit = JujuEntity:new()
|
return {
-- Returns the monotonic time the system has been up, in secconds.
monotime = function()
return os.clock()
end,
-- Sleep for n seconds.
sleep = function(n)
os.sleep(n)
end,
-- Returns the current system time, 1970 (UTC), in secconds.
gettime = function()
return os.epoch('utc') / 1000
end,
}
|
--Made by Joseph Pace (Thorinori)
--Maybe not needed. Not needed especially until Windows support is the focus.
local sep = package.config:sub(1,1)
--package.cpath = package.cpath .. ";./Modules/lib/lua/5.3/?.so;"
--package.cpath = package.cpath .. ";.\\Modules\\lib\\lua\\5.3\\?.so;"
package.cpath = package.cpath .. ";./libs/UNIX/iup_installed/lib?53.so;"
package.cpath = package.cpath .. ";./libs/UNIX/iup_installed/lib?.so;" --UNIX Version of IUP
--package.cpath = package.cpath .. ";.\\libs\\Windows\\iup\\Lua53\\?53.dll;"
--package.cpath = package.cpath .. ";.\\libs\\Windows\\iup\\?53.dll;"
--package.cpath = package.cpath .. ";.\\libs\\Windows\\iup\\?.dll;"
--package.cpath = package.cpath .. ";.\\libs\\Windows\\iup\\?.lib;"
package.cpath = package.cpath .. ";.\\libs\\Windows\\iup\\Lua53\\?53.lib;"--Windows Version of IUP
require("iuplua")
--lfs = require("lfs")
require("Modules/FileIO")
require("Modules/TableFunctions")
require("Modules/DataLoader")
require("Modules/Util")
--Misc Functions
--Globals
debug_mode = true -- For debug print statements into the multitext console (Primary use of the console)
unpack = unpack or table.unpack
types_enum = {['Weapons and Shields'] = 3, ['Helmets'] = 2, ['Leg Armor'] = 2, ['Boots'] = 2,
['Gloves'] = 2, ['Shoulder Armor'] = 2, ['Body Armor'] = 2, ['Belts'] = 2, ['Rings'] = 2, ['Amulets'] = 2}
bodypart_to_string = {['Weapons and Shields'] = 'weapon_r', ['Helmets'] = 'helmet', ['Leg Armor'] = 'legs', ['Boots'] = 'feet',
['Gloves'] = 'arm', ['Shoulder Armor'] = 'Shoulder', ['Body Armor'] = 'chest_armor', ['Belts'] = 'belt', ['Rings'] = 'ring', ['Amulets'] = 'amulet'}
affixes = generate_affixes()
organized_affixes = organize_affixes(affixes)
implicits = generate_implicits()
items = generate_items()
organized_items = organize_items(items)
output_table = {["Quality"] = 5, ["Value"] = "1"}
--Instantiate seed
math.randomseed(os.time())
--[[Configs
config = iup.config{}
config.app_name = "Wolcen Item Generator"
config:Load()]]
--Primary Components
parameter_panel = iup.vbox{iup.label{title='Item Builder',alignment='ACENTER'},padding="10x5", alignment="ALEFT"}
--scroll = iup.scrollbox{parameter_panel}
--add_child(scroll,parameter_panel)
reset_all_button = iup.button{title = "Reset All", padding="10x10", margin="10x10"}
add_child(parameter_panel,iup.hbox{reset_all_button, alignment="ACENTER",padding="10x10",margin="10x10"})
item_ilvl_field = iup.text{visiblecolumns = '3'}
add_child(parameter_panel,iup.hbox{iup.label{title='Item Level: '},item_ilvl_field, alignment="ALEFT"})
inventory_x_field = iup.text{visiblecolumns = '3'}
add_child(parameter_panel,iup.hbox{iup.label{title='Inventory X Position: '},inventory_x_field, alignment="ALEFT"})
inventory_y_field = iup.text{visiblecolumns = '3'}
add_child(parameter_panel,iup.hbox{iup.label{title='Inventory Y Position: '},inventory_y_field, alignment="ALEFT"})
item_rarity_selector = iup.list{"Normal", "Magic", "Rare", "Legendary"
,dropdown="YES", padding="10x10", margin="10x10",visiblecolumns='20'}
add_child(parameter_panel,iup.hbox{iup.label{title='Item Rarity: '},item_rarity_selector, alignment="ARIGHT"})
item_type_selector = iup.list{"Weapons and Shields", "Helmets", "Shoulder Armor", "Gloves", "Boots", "Rings", "Belts", "Amulets", "Body Armor", "Leg Armor"
,dropdown="YES", padding="10x10", margin="10x10", sort="YES",visiblecolumns='20'}
add_child(parameter_panel,iup.hbox{iup.label{title='Item Type: '},item_type_selector, alignment="ARIGHT"})
item_base_selector = iup.list{dropdown="YES", padding="10x10", margin="10x10", sort="YES", autoredraw="YES", visiblecolumns='20'}
add_child(parameter_panel,iup.hbox{iup.label{title='Item Base: '},item_base_selector, alignment="ARIGHT"})
affix_panel = iup.vbox{}
add_child(parameter_panel,affix_panel)
json_text = iup.text{multiline = "YES", scrollbar = "YES", visiblecolumns = 30,alignment = "ALEFT", visible="YES", readonly = "YES", wordwrap="YES",expand = "VERTICAL"}
--modifier_text = iup.vbox{alignment = 'ALEFT', padding='10x5'}
display_panel = iup.vbox{iup.label{title='Item Preview',alignment='ACENTER'}, json_text, alignment='ALEFT',padding="10x5"}
editor_panel = iup.hbox{parameter_panel,iup.fill{},display_panel}
main_panel = iup.vbox{editor_panel}
--Setup multitext "console"
local visible = "NO"
local console = "NO"--config:GetVariable("MainWindow", "Console")
if console == "YES" then
visible = "YES"
end
multitext = iup.text{multiline = "YES", expand = "HORIZONTAL", scrollbar = "YES", visiblelines = 12, alignment = "ALEFT", visible=visible, readonly = "YES", wordwrap="YES"}
--Menu Seperator
local horiz_sep = iup.separator{}
--File Menu
local exit_button = iup.item{title = "Exit"}
--File Menu Button Functions
function exit_button:action()
return iup.CLOSE
end
local file_menu = iup.menu{horiz_sep,exit_button}
local file_submenu = iup.submenu{file_menu, title="File"}
--Help Menu
local about_button = iup.item{title="About"}
function about_button:action()
iup.Message("About", "Wolcen Item Generator\nAuthor: Joseph Pace (Thorinori)")
end
local help_menu = iup.menu{about_button}
local help_submenu = iup.submenu{help_menu, title="Help"}
--View Menu
local console_button = iup.item{title="Console"}
function console_button:action()
local curr = multitext.visible
if curr == "YES" then
multitext.visible = "NO"
iup.Unmap(multitext)
iup.Refresh(main_win)
--multitext:detach()
else
multitext.visible = "YES"
iup.Append(main_panel,multitext)
iup.Map(multitext)
iup.Refresh(main_win)
end
iup.Refresh(main_win)
iup.RefreshChildren(main_win)
end
local view_menu = iup.menu{console_button}
local view_submenu = iup.submenu{view_menu, title="View"}
--Main Menu
local menu = iup.menu{file_submenu,view_submenu,help_submenu}
main_win = iup.dialog{
menu=menu,
main_panel,
title = "Wolcen Item Generator",
size="HALFxFULL",
close_cb = exit_button.action
}
main_win:showxy(iup.CENTER,iup.CENTER)
function reset_all_button:action()
item_ilvl_field.value = ''
inventory_x_field.value = ''
inventory_y_field.value = ''
item_rarity_selector.value = 0
item_type_selector.value = 0
item_base_selector['1'] = nil
reset_children(affix_panel)
reset_output()
end
function item_ilvl_field:valuechanged_cb()
if(self.value ~= '') then
if(tonumber(self.value) or not self.value == '') then
reset_children(affix_panel)
if(tonumber(self.value) > 200) then
self.value = "200"
end
if(tonumber(self.value) < 1) then
self.value = "1"
end
output_table["Level"] = tonumber(self.value)
else
iup.Message("Invalid Input", "Item Level must be a number between 1 and 200")
end
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
else
reset_children(affix_panel)
self.value = "1"
output_table["Level"] = tonumber(self.value)
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
end
end
function inventory_x_field:valuechanged_cb()
if(self.value ~= '') then
if(tonumber(self.value) or not self.value == '') then
if(tonumber(self.value) > 9) then
self.value = "9"
end
if(tonumber(self.value) < 0) then
self.value = "0"
end
output_table["InventoryX"] = tonumber(self.value)
else
iup.Message("Invalid Input", "X Value must be between 0 and 9")
end
else
output_table["InventoryX"] = 0
self.value = '0'
end
end
function inventory_y_field:valuechanged_cb()
if(self.value ~= '') then
if(tonumber(self.value) or not self.value == '') then
if(tonumber(self.value) > 4) then
self.value = "4"
end
if(tonumber(self.value) < 0) then
self.value = "0"
end
output_table["InventoryY"] = tonumber(self.value)
else
iup.Message("Invalid Input", "Y Value must be between 0 and 4")
end
else
output_table["InventoryX"] = 0
self.value = '0'
end
end
local num_affixes = 0
function item_rarity_selector:action(str, index, state)
if(index == 1 and state == 1) then
num_affixes = 0
output_table["Rarity"] = index
reset_children(affix_panel)
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
elseif (index == 2 and state == 1) then
num_affixes = 2
output_table["Rarity"] = index
reset_children(affix_panel)
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
elseif (index == 3 and state == 1) then
num_affixes = 4
output_table["Rarity"] = index
reset_children(affix_panel)
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
elseif (index == 4 and state == 1) then
num_affixes = 6
output_table["Rarity"] = index
reset_children(affix_panel)
if(item_base_selector.value ~= '0') then
item_base_selector:action(nil, item_base_selector.value, 1)
end
end
end
local item_type = ''
function item_type_selector:action(str, index, state)
if(state == 1) then
item_type = item_type_selector[tostring(index)]
output_table["Type"] = types_enum[item_type]
reset_item_bases(item_type)
reset_children(affix_panel)
end
end
local item_base = ''
local prefixes = {}
local suffixes = {}
function item_base_selector:action(str, index, state)
if(state == 1) then
reset_children(affix_panel)
item_base = item_base_selector[tostring(index)]
output_table["ItemType"] = items[item_base]._attr.ItemType
if(items[item_base]._attr.BodyPart == 'weapon_r') then
output_table["Armor"] = nil
output_table["Weapon"] = {["Name"] = item_base, ["DamageMin"] = ((output_table["Quality"] * 10/100) + 1) * tonumber(items[item_base]._attr.LowDamage_Max)
,["DamageMax"] = ((output_table["Quality"] * 10/100) + 1) * tonumber(items[item_base]._attr.HighDamage_Max)
,["ResourceGeneration"] = tonumber(items[item_base]._attr.ResourceGain_Max)}
else
output_table["Weapon"] = nil
output_table["Armor"] = {["Name"] = item_base}
local item_class = items[item_base]._attr.ArmorType
if(item_class == "Mage") then
output_table["Armor"].Armor = tonumber(items[item_base]._attr.ForceShieldMax)
elseif(item_class == "Rogue") then
output_table["Armor"].Armor = tonumber(items[item_base]._attr.ForceShieldMax)
output_table["Armor"].Health = tonumber(items[item_base]._attr.HealthBonusMax)
elseif(item_class == "Heavy") then
output_table["Armor"].Resistance = tonumber(items[item_base]._attr.AllResistanceMax)
else
output_table["Armor"].Health = tonumber(items[item_base]._attr.HealthBonusMax)
output_table["Armor"].Resistance = tonumber(items[item_base]._attr.AllResistanceMax)
end
end
prefixes = generate_valid_affixes(items[item_base],tonumber(item_ilvl_field.value) or 1, 'prefix')
suffixes = generate_valid_affixes(items[item_base],tonumber(item_ilvl_field.value) or 1, 'suffix')
generate_implicit_affixes(items[item_base])
for i=1, (num_affixes/2) do
gen_affix_selector(prefixes,'Prefixes')
end
for i=1, (num_affixes/2) do
gen_affix_selector(suffixes,'Suffixes')
end
end
end
-- to be able to run this script inside another context (From IUP Documentation)
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
iup.Close()
end
|
local Snake = class("Snake", function() return cc.Layer:create() end)
local SnakeNode = require "SnakeNode"
require "math"
function Snake:ctor()
self._nodes = {}
end
function Snake:init(len, direction, x, y)
local len = len or 3
local direction = direction or "left"
local x = x or math.floor(G.maxX / 2)
local y = y or math.floor(G.maxY / 2)
print(x)
self.nextZ = self:zIndexGenerator()
local head = SnakeNode:new()
head:init("res/head.png", x, y, direction)
self._nodes[#self._nodes + 1] = head
function nextPosition()
if direction == 'left' then x = x + 1; return end
if direction == 'right' then x = x - 1; return end
if direction == 'up' then y = y - 1; return end
if direction == 'down' then y = y + 1; return end
end
for i = 1, len do
nextPosition()
local body = SnakeNode:new()
local res = i % 2 ~= 0 and "res/body0.png" or "res/body1.png"
body:init(res, x, y, direction)
self._nodes[#self._nodes + 1] = body
end
nextPosition()
local endNode = SnakeNode:new()
endNode:init("res/end.png", x, y, direction)
self._nodes[#self._nodes + 1] = endNode
for i = 1, #self._nodes do
self:addChild(self._nodes[i], self.nextZ())
end
end
function Snake:step(opt)
local opt = opt or {}
for i = 1, #self._nodes do
local node = self._nodes[i]
local x, y = node.x, node.y
if node.direction == 'left' then
x = (node.x - 1 + G.maxX) % G.maxX
end
if node.direction == 'right' then
x = (node.x + 1) % G.maxX
end
if node.direction == 'up' then
y = (node.y + 1) % G.maxY
end
if node.direction == 'down' then
y = (node.y - 1 + G.maxY) % G.maxY
end
-- 检测与障碍物碰撞
if opt.barriers ~= nil then
if self:isCollideWithBarriers(opt.barriers, x, y) then
if opt.onCollision then opt.onCollision() end
return
end
end
-- 当蛇到达边缘的时候,将node向外围再移动一格
if (node.x == 0 and x == G.maxX-1) or
(node.x == G.maxX-1 and x == 0) or
(node.y == 0 and y == G.maxY-1) or
(node.y == G.maxY-1 and y == 0) then
local newX, newY = x, y
if x == 0 then
newX = -1
end
if x == G.maxX-1 then
newX = G.maxX
end
if y == 0 then
newY = -1
end
if y == G.maxY-1 then
newY = G.maxY
end
G.setPosition(node, newX, newY)
end
--print(x, y)
node:moveTo(x, y)
if self._newNode ~= nil then
table.insert(self._nodes, 2, self._newNode)
break
end
end
if self._newNode == nil then
for i = #self._nodes, 2, -1 do
self._nodes[i].preDirection = self._nodes[i].direction
self._nodes[i].direction = self._nodes[i-1].direction
end
end
self._newNode = nil
-- 旋转
for i = 1, #self._nodes do
local node = self._nodes[i]
if node.preDirection ~= nil and node.preDirection ~= node.direction then
local angle = G.angleMap[node.preDirection][node.direction]
node:rotateTo(angle)
end
end
-- 头部的preDirection
if self._nodes[1] ~= nil then
self._nodes[1].preDirection = self._nodes[1].direction
end
-- 检测有没有吃到食物
if opt.foods ~= nil then
local ret, i = self:eatFood(opt.foods)
if ret then
if opt.onEatFood then opt.onEatFood(i) end
end
end
-- 检测有没有吃到自己
if self:isEatMyself() then
if opt.onEatItself then opt.onEatItself() end
end
end
function Snake:onTouch(location)
if #self._nodes == 0 then return end
if self._nodes[1]:getPositionX() <= G.winSize.width / 2 then
self:onTouchLeft(location)
else
self:onTouchRight(location)
end
if self._newNode ~= nil then
self._newNode.direction = self._nodes[1].direction
end
end
function Snake:onTouchLeft(location)
print("onTouchLeft")
local head = self._nodes[1]
head.preDirection = head.direction
if head.direction == 'left' or head.direction == 'right' then
if location.y > head:getPositionY() then
head.direction = 'up'
elseif location.y < head:getPositionY() then
head.direction = 'down'
end
elseif head.direction == 'up' or head.direction == 'down' then
if location.x > head:getPositionX() then
head.direction = 'right'
elseif location.x < head:getPositionX() then
head.direction = 'left'
end
end
end
function Snake:onTouchRight(location)
print("onTouchRight")
local head = self._nodes[1]
head.preDirection = head.direction
if head.direction == 'left' or head.direction == 'right' then
if location.y < head:getPositionY() then
head.direction = 'up'
elseif location.y > head:getPositionY() then
head.direction = 'down'
end
elseif head.direction == 'up' or head.direction == 'down' then
if location.x < head:getPositionX() then
head.direction = 'right'
elseif location.x > head:getPositionX() then
head.direction = 'left'
end
end
end
function Snake:eatFood(foods)
if #self._nodes == 0 then return end
for i = 1, #foods do
if foods[i].x == self._nodes[1].x and
foods[i].y == self._nodes[1].y then
-- 吃到食物,添加一节
self._newNode = SnakeNode:new()
local texture = #self._nodes % 2 ~= 0 and "res/body0.png" or "res/body1.png"
self._newNode:init(texture,foods[i].x, foods[i].y, self._nodes[i].direction)
self:addChild(self._newNode, self.nextZ())
return true, i
end
end
return false
end
function Snake:isCollideWithBarriers(barriers, x, y)
for i, barrier in ipairs(barriers) do
if barrier:containsXY(x, y) then
return true
end
end
return false
end
function Snake:isEatMyself()
local head = self._nodes[1]
for i = 2, #self._nodes do
local node = self._nodes[i]
if head.x == node.x and head.y == node.y then
-- 截断
local endnode = self._nodes[#self._nodes]
-- 复制前一节点所有属性到结尾节点
self._nodes[i-1]:cloneValue(endnode)
--endnode, self._nodes[i-1] = self._nodes[i-1], endnode
--self._nodes[i-1]:cloneValue(self._nodes[#self._nodes])
self._nodes[#self._nodes], self._nodes[i-1] = self._nodes[i-1], self._nodes[#self._nodes]
for k = #self._nodes, i, -1 do
self:removeChild(self._nodes[k],true)
table.remove(self._nodes,k)
end
endnode:rotateTo(G.initAngleMap[endnode.direction])
G.setPosition(endnode, endnode.x, endnode.y)
print(#self._nodes)
return true
end
end
return false
end
function Snake:containsXY(x, y)
for i = 1, #self._nodes do
if self._nodes[i].x == x and
self._nodes[i].y == y then
return true
end
end
return false
end
function Snake:zIndexGenerator()
local z = 1000
return function()
z = z - 1
return z + 1
end
end
function Snake:getSize()
return #self._nodes
end
return Snake
|
module('levels', package.seeall)
levels = {
}
currentLevel = nil
function pushEnemies( timer, enemies )
for _, enemy in ipairs(enemies) do
enemy:getWarning()
end
timer.running = false
end
function registerEnemies( timer, enemies)
for _, enemy in ipairs(enemies) do
enemy:register()
end
timer.running = false
end
local levelEnv = {}
local enemycreator, enemycreatorwarning = {}, {}
function levelEnv.enemy( name, n, format, ... )
name = name or 'simpleball'
n = n or 1
local initInfo = select('#', ...) > 0 and {...} or nil
local enemylist = {}
local cp
if format and format.applyOn then cp = format.copy or {}
else cp = format or {} end
cp.side = cp.side or format and format.side
cp.onInitInfo = initInfo
if type(name) == 'string' then
local enemy = enemies[name]
for i = 1, n do
enemylist[i] = enemy:new(clone(cp))
end
else
local k, s = 1, #name
for i = 1, n do
enemylist[i] = enemies[name[k]]:new(clone(cp))
k = k + 1
if k > s then k = 1 end
end
end
if format then
if format.applyOn then
format:applyOn(enemylist)
end
end
local extraelements = {enemylist}
if levelEnv.warnEnemies then
-- warns about the enemy
local warn = timer:new{timelimit = levelEnv.time - (levelEnv.warnEnemiesTime or 1), funcToCall = pushEnemies,
extraelements = extraelements, onceonly = true, registerSelf = false}
table.insert(currentLevel.timers_, warn)
if format and format.shootattarget then
-- follows the target with the warnings
table.insert(currentLevel.timers_, timer:new {
timelimit = levelEnv.time - (levelEnv.warnEnemiesTime or 1) + .01,
prevtarget = format.target:clone(),
registerSelf = false,
funcToCall = function(self)
self.timelimit = nil
if not enemylist[1].warning then self:remove() return end
if self.prevtarget == format.target then return end
local speed = format.speed or v
for i = 1, n do
enemylist[i].speed:set(format.target):sub(enemylist[i].position):normalize():mult(speed, speed)
enemylist[i].warning:recalc_angle()
end
self.prevtarget:set(target)
end
})
end
end
-- release the enemy onscreen
local t = timer:new{timelimit = levelEnv.time, funcToCall = registerEnemies,
extraelements = extraelements, onceonly = true, registerSelf = false}
table.insert(currentLevel.timers_, t)
end
function levelEnv.wait( s )
levelEnv.time = levelEnv.time + s
end
function levelEnv.formation( data )
local t = data.type or 'empty'
data.type = nil
return formations[t]:new(data)
end
function levelEnv.registerTimer( data )
data.time = -levelEnv.time
data.registerSelf = false
table.insert(currentLevel.timers_, timer:new(data))
end
function levelEnv.doNow( func )
levelEnv.registerTimer {
funcToCall = func,
timelimit = 0,
onceonly = true
}
end
setmetatable(levelEnv, {__index = _G})
function runLevel( name )
local prevtitle = currentLevel and currentLevel.title
closeLevel()
currentLevel = name and levels[name]
currentLevelname = name
currentLevel.reload()
local changetitle = currentLevel.title and currentLevel.title ~= "" and currentLevel.title ~= prevtitle
local delay = changetitle and -5 or 0
for _, t in ipairs(currentLevel.timers_) do
t:register()
t:start(t.time + delay)
end
if changetitle then
local t = text:new {
text = currentLevel.title,
alphafollows = vartimer:new{ var = 255 },
font = getCoolFont(100),
position = vector:new{50, 200},
limit = width - 100,
align = 'center',
printmethod = graphics.printf,
variance = 0
}
t:register()
timer:new{
timelimit = 3,
running = true,
funcToCall = function ( timer )
if timer.first then t.delete = true timer:remove() return end
timer.first = true
t.alphafollows:setAndGo(255, 0, 100)
end
}
end
end
function closeLevel()
if not currentLevel then return end
for _, t in ipairs(currentLevel.timers_) do
t:remove()
end
currentLevel.timers_ = nil
currentLevel = nil
end
function loadLevel( lev )
return function ()
currentLevel = { reload = currentLevel.reload }
setfenv(lev, currentLevel)
lev()
currentLevel.timers_ = {}
levelEnv.time = 0
setfenv(currentLevel.run, levelEnv)
currentLevel.run()
end
end
local loaded = false
function loadAll()
if loaded then return end
loaded = true
cleartable(levels)
local files = filesystem.getDirectoryItems('levels')
for _, file in ipairs(files) do
local lev = assert(filesystem.load('levels/' .. file))
currentLevel = {}
currentLevel.reload = loadLevel(lev)
levels[file:sub(0, file:len() - 4)] = currentLevel
currentLevel.run = nil
end
currentLevel = nil
end
function reloadPractice( )
local ls = {}
local levelselectalpha = vartimer:new{ speed = 300, pausable = false }
local translate = vartimer:new{ var = 0, speed = width*2, pausable = false }
local b = {}
b[1] = button:new {size = 100, position = vector:new{156, height/2 - 100}, fontsize = 20,
menu = levelselect, pressed = function(self)
self.alphafollows:setAndGo(255, 0)
self.visible = falsen
neweffects(self, 40)
reloadStory(self.levelname)
end,
draw = function(self)
if not self.visible or self.alphafollows.var == 0 then return end
graphics.translate(-translate.var, 0)
button.draw(self)
if self.hoverring and self.hoverring.size > 2 then circleEffect.draw(self.hoverring) end
graphics.translate(translate.var, 0)
end,
isClicked = function ( self, x, y )
return button.isClicked(self, x + translate.var, y )
end,
update = function(self, dt)
if self.hoverring.size > self.size then
self.hoverring.size = self.size
self.hoverring.sizeGrowth = 0
end
if self.menu ~= state then
if self.onHover then
self.onHover = false
self:hover(false)
end
return
end
if self.onHover ~= ((mouseX + translate.var - self.x)^2 + (mouseY - self.y)^2 < self.size^2) then
self.onHover = not self.onHover
self:hover(self.onHover)
end
end}
b[2] = b[1]:clone()
b[2].position:set(412, nil)
b[3] = b[1]:clone()
b[3].position:set(668, nil)
b[4] = b[1]:clone()
b[4].position:set(924, nil)
local back = button:new{
size = 50,
position = vector:new{width - 160, 580},
text = "back",
fontsize = 20,
menu = levelselect,
alphafollows = levelselectalpha,
draw = function(self)
button.draw(self)
graphics.setColor(color(colortimer.time + self.variance, self.alpha or self.alphafollows and self.alphafollows.var, self.coloreffect))
graphics.setFont(getCoolFont(70))
graphics.printf("Practice", 0, 30, width, 'center')
end,
pressed = function(self)
for _, but in pairs(UI.paintables.levelselect) do
but:close()
end
self.visible = false
neweffects(self, 26)
self.alphafollows:setAndGo(255, 0, 300)
UI.restartMenu()
end
}
table.insert(ls, back)
local nextB = button:new{
size = 50,
position = vector:new{width/2 + 100, 400},
text = ">",
fontsize = 55,
draw = b[1].draw,
isClicked = b[1].isClicked,
update = b[1].update,
menu = levelselect,
pressed = function(self)
translate:setAndGo(nil, translate.var + width)
end
}
local prevB = button:new{
size = 50,
position = vector:new{width/2 - 100, 400},
text = "<",
fontsize = 55,
draw = b[1].draw,
isClicked = b[1].isClicked,
update = b[1].update,
menu = levelselect,
pressed = function(self)
translate:setAndGo(nil, translate.var - width)
end
}
local fixeff = function(self)
self.effectsBurst.funcToCall = function()
self.x = self.x - translate.var
neweffects(self, 2)
self.x = self.x + translate.var
end
end
local transl = vector:new{0, 0}
local levelN = 5
for i = 1, levelN do
if 'Level ' .. i > lastLevel then break end
for j = 1, 4 do
if j ~= 4 or i ~= 1 then
local levelname = 'Level ' .. i .. '-' .. j
if lastLevel < levelname then break end
local but = b[j]:clone()
but.levelname = levelname
but.position:add(transl)
but:setText(but.levelname)
but.alphafollows = levelselectalpha
fixeff(but)
table.insert(ls, but)
end
end
if i > 1 then
but = prevB:clone()
but.position:add(transl)
but:setText()
but.alphafollows = levelselectalpha
fixeff(but)
table.insert(ls, but)
end
if i < levelN and 'Level ' .. (i+1) <= lastLevel then
but = nextB:clone()
but.position:add(transl)
but:setText()
but.alphafollows = levelselectalpha
fixeff(but)
table.insert(ls, but)
end
transl:add(width, 0)
end
UI.paintables.levelselect = ls
end |
local fs = require('be.fs')
local projects = {
all = { }
}
local function project (project_type, name_or_suffix)
local function parse (t)
if type(t) ~= 'table' then
fatal('Expected table!', nil, { t = be.util.sprint_r(t) })
end
return function (configured_group)
local name, suffix
if type(name_or_suffix) ~= 'string' then
name = configured_group.group.name
elseif name_or_suffix:sub(1, 1) == '-' then
name = configured_group.group.name .. name_or_suffix
suffix = name_or_suffix:sub(2)
else
name = name_or_suffix
end
local project = projects.all[name]
if not project then
project = {
name = name,
suffix = suffix,
type = project_type,
group = configured_group.group,
fns = { },
configurations = { }
}
projects.all[name] = project
projects[#projects + 1] = project
configured_group.group.projects[#configured_group.group.projects + 1] = project
for k, v in pairs(t) do
if type(k) == 'number' then
project.fns[#project.fns + 1] = v
elseif type(k) == 'string' and not protected_config_properties[k] then
project[k] = v
else
fatal('The ' .. k .. ' property cannot be set directly!', project)
end
end
end
if project.type ~= project_type then
fatal('"' .. name .. '" is a ' .. project.type .. ', not a ' .. project_type .. '!', project)
end
if project.group ~= configured_group.group then
fatal('A project named "' .. name .. '" already exists in the "' .. project.group.name .. '" ' .. project.group.type, project)
end
end
end
if type(name_or_suffix) == 'table' then
return parse(name_or_suffix)
else
return parse
end
end
function build_scripts.env.app (name_or_suffix)
return project('app', name_or_suffix)
end
function build_scripts.env.lib (name_or_suffix)
return project('lib', name_or_suffix)
end
function build_scripts.env.dyn_lib (name_or_suffix)
return project('dyn_lib', name_or_suffix)
end
function build_scripts.env.ext_lib (name_or_suffix)
return project('ext_lib', name_or_suffix)
end
function configure_project (project, toolchain, configuration, configured_group)
local configured = deep_copy(configured_group)
configured.projects = nil
deep_copy(project, configured)
project.configurations[configuration] = configured
configured.project = project
configured.toolchain = toolchain
configured.configuration = configuration
configured.configurations = project.configurations
configured.group = configured_group.group
configured.configured_group = configured_group
for f = 1, #project.fns do
project.fns[f](configured)
end
configured.path = fs.canonical(configured.path)
if not configured.output_base then
configured.output_base = configured.name .. configured.configuration_suffix
end
configured.is_lib = configured.type == 'lib'
configured.is_app = configured.type == 'app'
configured.is_dyn_lib = configured.type == 'dyn_lib'
configured.is_ext = configured.type == 'ext_lib'
configured.is_ext_lib = configured.type == 'ext_lib'
if configured.is_ext_lib then
configured.output_dir, configured.output_dir_abs = ext_lib_dir()
else
configured.output_dir, configured.output_dir_abs = out_dir()
end
if configured.is_lib or configured.is_dyn_lib then
configured_group.has_include_headers = true
end
if not configured.is_ext then
configured.define.BE_TARGET = configured.name
configured.define.BE_TARGET_BASE = configured_group.name
end
if configured.test_type == nil then
if configured.suffix == 'test' or configured.suffix == 'perf' then
configured.test_type = configured.suffix
end
end
if configured.console == nil and not configured.gui then
configured.console = true
end
local search_paths = { configured.path, root_dir }
configured.include = expand_pathspec(configured.include or default_include_paths(configured), search_paths, configured, 'd?')
be.log.verbose('Expanding src patterns for ' .. configured.output_base, { ['Search Paths'] = be.util.sprint_r(search_paths) })
if not configured.src then
local original = default_source_patterns(configured)
local expanded = expand_pathspec(original, search_paths, configured)
be.log.verbose('Expanded src pattern', { Pattern = be.util.sprint_r(original), Results = be.util.sprint_r(expanded) })
configured.src = { expanded }
else
for i = 1, #configured.src do
local original = configured.src[i]
local expanded = expand_pathspec(original, search_paths, configured)
be.log.verbose('Expanded src pattern', { Pattern = be.util.sprint_r(original), Results = be.util.sprint_r(expanded) })
if expanded.pch_src and not expanded.pch then
expanded.pch = 'pch.hpp'
end
configured.src[i] = expanded
end
end
if not configured.limp_src then
configured.limp_src = { }
else
for i = 1, #configured.limp_src do
local original = configured.limp_src[i]
local expanded = expand_pathspec(original, search_paths, configured)
be.log.verbose('Expanded limp_src pattern', { Pattern = be.util.sprint_r(original), Results = be.util.sprint_r(expanded) })
configured.limp_src[i] = expanded
end
end
configured.link = interpolate_sequence(configured.link or { }, configured)
configured.link_internal = interpolate_sequence(configured.link_internal or { }, configured)
configured.link_project = interpolate_sequence(configured.link_project or { }, configured)
configured.linked_configurations = { }
if configured.icon then
configured.icon = expand_path(configured.icon, search_paths)
if not configured.icon then
fatal('Could not locate icon for project "' .. configured.name .. '"', configured)
end
end
for k, v in pairs(configured) do
if not protected_config_properties[k] and type(v) == 'string' then
configured[k] = interpolate_string(v, configured)
end
end
return configured
end
local function link_project (configured_project, project_name_to_link)
local configured = configured_project
local project_to_link = projects.all[project_name_to_link]
if not project_to_link then
fatal(configured.name .. ' can\'t link to project "' .. project_name_to_link .. '"; project does not exist!', configured)
end
if project_to_link.is_app then
fatal(configured.name .. ' can\'t link to project "' .. project_name_to_link .. '"; project is not a library!', configured)
end
local config_to_link = project_to_link.configurations[configured.configuration]
local link_spec = fs.compose_path(config_to_link.output_dir, config_to_link.name .. config_to_link.configuration_suffix)
append_sequence({ config_to_link }, configured.linked_configurations, true)
append_sequence(config_to_link.link, configured.link, true)
append_sequence({ link_spec }, configured.link_internal, true)
for k, v in pairs(config_to_link.export_define) do
if configured.define[k] == nil then
configured.define[k] = v
end
end
for i = 1, #config_to_link.link_project do
local name = config_to_link.link_project[i]
link_project(configured_project, name)
end
end
function finalize_project_configuration (configured_project, groups)
local configured = configured_project
local direct_dependencies = append_sequence(configured.link_project)
for i = 1, #configured.link_project do
local name = configured.link_project[i]
link_project(configured_project, name)
end
local dependencies = { }
local defines = { }
for i = 1, #configured.link_internal do
local link_spec = configured.link_internal[i]
dependencies[#dependencies + 1] = fs.path_filename(link_spec)
end
for k, v in pairs(configured.define) do
if k ~= 'BE_TARGET' and k ~= 'BE_TARGET_BASE' then
if v then
defines[#defines + 1] = k .. '=' .. v
else
defines[#defines + 1] = k
end
end
end
if #dependencies > 0 then
dependencies = table.concat(dependencies, ' ')
else
dependencies = nil
end
if #direct_dependencies > 0 then
direct_dependencies = table.concat(direct_dependencies, ' ')
else
direct_dependencies = nil
end
if #defines > 0 then
defines = table.concat(defines, ' ')
else
defines = nil
end
if dependencies or defines then
be.log.verbose('Dependencies for ' .. configured.output_base, { Direct = direct_dependencies, All = dependencies, Defines = defines, })
end
end
return projects
|
object_ship_nova_orion_boss_ship_tier1 = object_ship_shared_nova_orion_boss_ship_tier1:new {
}
ObjectTemplates:addTemplate(object_ship_nova_orion_boss_ship_tier1, "object/ship/nova_orion_boss_ship_tier1.iff")
|
ITEM.name = "Cleaver"
ITEM.description = "An old, pre-war looking cleaver. "
ITEM.model = "models/weapons/tfa_nmrih/w_me_cleaver.mdl"
ITEM.class = "tfa_nmrih_cleaver"
ITEM.weaponCategory = "melee"
ITEM.flag = "v"
ITEM.width = 2
ITEM.height = 1
ITEM.bDropOnDeath = true
ITEM.iconCam = {
ang = Angle(-0.23955784738064, 270.44906616211, 0),
fov = 10.780103254469,
pos = Vector(0, 200, 0)
} |
-- 大室花子
-- ①:自分フィールド上に「大室櫻子」が表側表示で存在する場合、このカードは手札から特殊召喚することができる。
-- ②:このカードが召喚に成功した時、デッキから「古谷楓」を1枚手札に加えることができる。
-- ③:このカードが相手によって破壊され墓地へ送られた時、自分のデッキから「大室櫻子」を特殊召喚することができる。
function c1070.initial_effect(c)
-- special summon
local e1 = Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(1070, 0))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c1070.e1condition)
c:RegisterEffect(e1)
-- search
local e2 = Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(1070, 1))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetTarget(c1070.e2target)
e2:SetOperation(c1070.e2operation)
c:RegisterEffect(e2)
-- special summon when to grave
local e3 = Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(1070, 2))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCondition(c1070.e3condition)
e3:SetTarget(c1070.e3target)
e3:SetOperation(c1070.e3operation)
c:RegisterEffect(e3)
end
-- 櫻子フィルター
function c1070.e1spfilter(c)
-- 表側表示(=IsFaceup)かつ櫻子(=1050)か
return c:IsFaceup() and c:IsCode(1050)
end
function c1070.e1condition(e, c)
if c == nil then return true end
return Duel.GetLocationCount(c:GetControler(), LOCATION_MZONE) > 0 and
Duel.IsExistingMatchingCard(c1070.e1spfilter, c:GetControler(), LOCATION_ONFIELD, 0, 1, nil)
end
-- 楓フィルター
function c1070.e2filter(c)
return c:IsCode(1090) and c:IsAbleToHand()
end
function c1070.e2target(e, tp, eg, ep, ev, re, r, rp, chk)
if chk == 0 then return Duel.IsExistingMatchingCard(c1070.e2filter, tp, LOCATION_DECK, 0, 1, nil) end
Duel.SetOperationInfo(0, CATEGORY_TOHAND, nil, 1, tp, LOCATION_DECK)
end
function c1070.e2operation(e, tp, eg, ep, ev, re, r, rp)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_ATOHAND)
local g = Duel.SelectMatchingCard(tp, c1070.e2filter, tp, LOCATION_DECK, 0, 1, 1, nil)
if g:GetCount() > 0 then
Duel.SendtoHand(g, nil, REASON_EFFECT)
Duel.ConfirmCards(1 - tp, g)
end
end
function c1070.e3condition(e, tp, eg, ep, ev, re, r, rp)
return rp ~= tp and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and e:GetHandler():IsReason(REASON_DESTROY)
end
-- (特殊召喚する)櫻子フィルター
function c1070.e3filter(c, e, tp)
return c:IsCode(1050) and c:IsCanBeSpecialSummoned(e, 0, tp, false, false)
end
function c1070.e3target(e, tp, eg, ep, ev, re, r, rp, chk, chkc)
if chkc then return chkc:IsLocation(LOCATION_DECK) and chkc:IsControler(tp) and c1070.e3filter(chkc, e, tp) end
if chk == 0 then return Duel.IsExistingTarget(c1070.e3filter, tp, LOCATION_DECK, 0, 1, nil, e, tp) end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local g = Duel.SelectTarget(tp, c1070.e3filter, tp, LOCATION_DECK, 0, 1, 1, nil, e, tp)
Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, g, 1, 0, 0)
end
function c1070.e3operation(e, tp, eg, ep, ev, re, r, rp)
local tc = Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc, 0, tp, tp, false, false, POS_FACEUP)
end
end
|
local id = ID("remoteedit.openremotefile")
local lastfile = ""
local editors = {}
local function reportErr(err) return(err:gsub('.-:%d+:%s*','')) end
local mobdebug = require("mobdebug")
local copas = require("copas")
return {
name = "Remote edit",
description = "Allows to edit files remotely while debugging is in progress.",
author = "Paul Kulchenko",
version = 0.13,
dependencies = "1.40",
onRegister = function(self)
local menu = ide:GetMenuBar():GetMenu(ide:GetMenuBar():FindMenu(TR("&File")))
menu:Insert(2, id, "Open Remotely...")
ide:GetMainFrame():Connect(id, wx.wxEVT_COMMAND_MENU_SELECTED,
function()
local file = wx.wxGetTextFromUser("Enter name (with path) of the remote file",
"Open remote file", lastfile)
if file and #file > 0 then
self:loadFile(file)
lastfile = file
end
end)
ide:GetMainFrame():Connect(id, wx.wxEVT_UPDATE_UI,
function (event)
local debugger = ide:GetDebugger()
event:Enable(debugger:IsConnected() and not debugger:IsRunning())
end)
end,
onUnRegister = function(self)
ide:RemoveMenuItem(id)
end,
onEditorClose = function(self, editor)
editors[editor] = nil
end,
onEditorPreSave = function(self, editor)
local remote = editors[editor]
if remote and ide:GetDocument(editor):IsModified() then
self:saveFile(remote, editor)
return false
end
end,
loadFile = function(self, remote)
local debugger = ide:GetDebugger()
if not debugger:IsConnected() or debugger:IsRunning() then return end
local code = ([[(function() local f, err = io.open(%s); if not f then error(err) end; local c = f:read('*a'); f:close(); return c end)()]])
:format(mobdebug.line(remote))
copas.addthread(function()
local debugger = ide:GetDebugger()
local res, _, err = debugger:evaluate(code)
if err then
ide:Print(("Failed to load file '%s': %s."):format(remote, reportErr(err)))
return
end
local ok, content = LoadSafe("return "..res)
if ok then
ide:Print(("Loaded file '%s'."):format(remote))
self.onIdleOnce = function()
local editor = NewFile("remote: "..remote)
editor:SetText(content)
editor:SetSavePoint()
editors[editor] = remote
end
else
ide:Print(("Failed to load file '%s': %s."):format(remote, content))
end
end)
end,
saveFile = function(self, remote, editor)
local debugger = ide:GetDebugger()
if not debugger:IsConnected() or debugger:IsRunning() then return end
local content = editor:GetText()
local code = ([[local f, err = io.open(%s, 'w'); if not f then error(err) end; f:write(%s); f:close()]])
:format(mobdebug.line(remote), mobdebug.line(content))
copas.addthread(function()
local err = select(3, debugger:execute(code))
if not err then
editor:SetSavePoint()
ide:Print(("Saved file '%s'."):format(remote))
else
ide:Print(("Failed to save file '%s': %s."):format(remote, reportErr(err)))
end
end)
end,
}
|
return {
source = {
location = '[email protected]:bazurbat/ast-rootfs.git',
name = 'rootfs'
},
build = {
type = true,
dir = '$jagen_target_dir'
},
uses = 'hi-sdk'
}
|
-----------------------------------
-- Area: Southern San d'Oria
-- NPC: Atelloune
-- Starts and Finishes Quest: Atelloune's Lament
-- !pos 122 0 82 230
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
local ID = require("scripts/zones/Southern_San_dOria/IDs");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(ID.text.FLYER_REFUSED);
end
end
-----lady bug
if (player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.ATELLOUNE_S_LAMENT) == QUEST_ACCEPTED) then
if (trade:hasItemQty(2506,1) and trade:getItemCount() == 1) then
player:startEvent(891);
end
end
end;
function onTrigger(player,npc)
atellounesLament = player:getQuestStatus(SANDORIA,tpz.quest.id.sandoria.ATELLOUNE_S_LAMENT)
sanFame = player:getFameLevel(SANDORIA);
if (atellounesLament == QUEST_AVAILABLE and sanFame >= 2) then
player:startEvent(890);
elseif (atellounesLament == QUEST_ACCEPTED) then
player:startEvent(892);
elseif (atellounesLament == QUEST_COMPLETED) then
player:startEvent(884); -- im profesors research
elseif (sanFame < 2) then
player:startEvent(884);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 890) then
player:addQuest(SANDORIA,tpz.quest.id.sandoria.ATELLOUNE_S_LAMENT);
elseif (csid == 891) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,15008); -- Trainee Gloves
else
player:addItem(15008);
player:messageSpecial(ID.text.ITEM_OBTAINED,15008); -- Trainee Gloves
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,tpz.quest.id.sandoria.ATELLOUNE_S_LAMENT);
end
end
end;
|
-- exports a playlist manager "object"
-- handles:
-- iterating over the playlist of files
-- formatting either a regular list or circular buffer depending on how long
-- the list is
-- filtering the list by search
-- does not handle the OSD
local utils = require("mp.utils")
local settings = {
-- number of lines displayed
num_lines = 10,
-- display line prefixes
playing_str = "->",
cursor_str = ">"
}
-- this object is exported
local playlist = {
-- index in playlist of currently playing video
-- assume this is updated before display, including scrolling
pos = 0,
-- playlist length
len = 0,
-- cursor iterates through playlist - bidirectional
cursor = 0,
-- active manager - ie don't reset cursor
active = false,
-- the actual playlist
files = {}
}
function playlist:init()
self:update()
self.files = self:get_playlist()
end
-- sync member variables to the values of their mirrored properties
function playlist:update()
self.pos = mp.get_property_number('playlist-pos', 0)
self.len = mp.get_property_number('playlist-count', 0)
end
-- cursor movements
function playlist:increment()
self.cursor = (self.cursor + 1) % self.len
end
function playlist:decrement()
self.cursor = self.cursor - 1
if self.cursor == -1 then
self.cursor = self.len - 1
end
end
function playlist:print()
print(string.format("playlist: pos=%s, len=%s, cursor=%s",
self.pos, self.len, self.cursor))
end
-- get the actual playlist from mpv as an array - 0-based
function playlist:get_playlist()
local pl = {}
for i=0, self.len-1, 1
do
local l_path, l_file = utils.split_path(mp.get_property('playlist/'..i..'/filename'))
pl[i] = l_file
end
return pl
end
-- functions to prepare output
-- note - the playlist array is 0-based, but lua arrays are usually 1-based
-- so my display arrays are 1-based
-- returns array of strings
function playlist:short_list_display_lines(_playlist)
local display_files = {}
for i = 0, #_playlist do
display_files[i+1] = _playlist[i]
if i == self.pos then
display_files[i+1] = settings.playing_str..display_files[i+1]
end
if i == self.cursor then
display_files[i+1] = settings.cursor_str..display_files[i+1]
end
end
return display_files
end
-- handles circular buffer display
-- returns array of strings
function playlist:long_list_display_lines(_playlist)
local display_files = {}
local first = self.cursor - settings.num_lines / 2
if settings.num_lines % 2 == 0 then
first = first + 1
end
local index = 0
for i = first, first + settings.num_lines - 1 do
if i < 0 then
index = #_playlist + 1 + i
elseif i > #_playlist then
index = i - (#_playlist + 1)
else
index = i
end
display_files[#display_files+1] = _playlist[index]
if index == self.pos then
display_files[#display_files] = settings.playing_str..display_files[#display_files]
end
if index == self.cursor then
display_files[#display_files] = settings.cursor_str..display_files[#display_files]
end
end
return display_files
end
-- returns multiline string
function playlist:format_lines(_playlist)
local display_files = {}
if self.len <= settings.num_lines then
display_files = self:short_list_display_lines(_playlist)
else
display_files = self:long_list_display_lines(_playlist)
end
local output = display_files[1]
for i = 2, #display_files do
output = output.."\n"..display_files[i]
end
return output
end
-- Convert to case insensitive pattern for searching
-- "xyz = %d+ or %% end" --> "[xX][yY][zZ] = %d+ [oO][rR] %% [eE][nN][dD]"
-- not sure if it can handle all corner cases of patterns
-- https://stackoverflow.com/questions/11401890/case-insensitive-lua-pattern-matching
function case_insensitive_pattern(pattern)
-- find an optional '%' (group 1) followed by any character (group 2)
local p = pattern:gsub("(%%?)(.)", function(percent, letter)
if percent ~= "" or not letter:match("%a") then
-- if the '%' matched, or `letter` is not a letter, return "as is"
return percent .. letter
else
-- else, return a case-insensitive character class of the matched letter
return string.format("[%s%s]", letter:lower(), letter:upper())
end
end)
return p
end
-- returns 0-based array of {index, filepath} for each file in the playlist
-- where index is the index of the filepath in the playlist
-- search_term - a lua pattern - not quite regexp, but ., *, +, and ? work the same
-- escape with % rather than \
-- matches are case-insensitive
function playlist:filtered_playlist(search_term)
case_insensitive_term = case_insensitive_pattern(search_term)
filtered = {}
f_index = 0
for i=0, #self.files do
local filename = self.files[i]
m = string.match(filename, case_insensitive_term)
if m and #m > 0 then
local row = {i, filename}
filtered[f_index] = row
f_index = f_index + 1
end
end
return filtered
end
return playlist
|
include("Mastergear/MasterGearLua.lua")
target_maneuver_count = {
["light maneuver"] = 1,
["dark maneuver"] = 0,
["earth maneuver"] = 0,
["wind maneuver"] = 1,
["water maneuver"] = 0,
["ice maneuver"] = 0,
["fire maneuver"] = 1,
["thunder maneuver"] = 0,
}
maneuver_cast = {"light maneuver", "wind maneuver", "fire maneuver"}
maneuver_recast_ids = {
["light maneuver"] = 147,
["dark maneuver"] = 148,
["earth maneuver"] = 144,
["wind maneuver"] = 143,
["water maneuver"] = 146,
["ice maneuver"] = 142,
["fire maneuver"] = 141,
["thunder maneuver"] = 145,
}
maneuver_cast_index = 1
deploy_on_engage = false
auto_maneuvers = false
function custom_get_sets()
ws = {}
ws["Combo"] = { set = sets["Raging Fist"], tp_bonus = true }
ws["Shoulder Tackle"] = { set = sets["Dragon Kick"], tp_bonus = true }
ws["One Inch Punch"] = { set = sets["Dragon Kick"], tp_bonus = true }
ws["Backhand Blow"] = { set = sets["Dragon Kick"], tp_bonus = false }
ws["Raging Fist"] = { set = sets["Raging Fist"], tp_bonus = true }
ws["Spinning Attack"] = { set = sets["Dragon Kick"], tp_bonus = false }
ws["Howling Fist"] = { set = sets["Dragon Kick"], tp_bonus = true }
ws["Dragon Kick"] = { set = sets["Dragon Kick"], tp_bonus = true }
ws["Asuran Fist"] = { set = sets["Victory Smite"], tp_bonus = false }
ws["Tornado Kick"] = { set = sets["Victory Smite"], tp_bonus = true }
ws["Shijin Spiral"] = { set = sets["Raging Fist"], tp_bonus = false }
ws["Victory Smite"] = { set = sets["Victory Smite"], tp_bonus = false }
ws["Stringing Pummel"] = { set = sets["Victory Smite"], tp_bonus = false }
print_current_maneuvers()
send_command('@input /macro book 13;wait 1;input /macro set 1')
end
function custom_command(args)
if args[1] == "maneuver" then
if args[2] and args[3] and args[4] then
local ele1 = string.lower(args[2]) .. " maneuver"
local ele2 = string.lower(args[3]) .. " maneuver"
local ele3 = string.lower(args[4]) .. " maneuver"
if target_maneuver_count[ele1] and target_maneuver_count[ele2] and target_maneuver_count[ele3] then
target_maneuver_count["light maneuver"] = 0
target_maneuver_count["dark maneuver"] = 0
target_maneuver_count["earth maneuver"] = 0
target_maneuver_count["wind maneuver"] = 0
target_maneuver_count["water maneuver"] = 0
target_maneuver_count["ice maneuver"] = 0
target_maneuver_count["fire maneuver"] = 0
target_maneuver_count["thunder maneuver"] = 0
target_maneuver_count[ele1] = target_maneuver_count[ele1] + 1
target_maneuver_count[ele2] = target_maneuver_count[ele2] + 1
target_maneuver_count[ele3] = target_maneuver_count[ele3] + 1
maneuver_cast = {ele1, ele2, ele3}
maneuver_cast_index = 1
print_current_maneuvers()
end
else
do_maneuver()
end
elseif args[1] == "engagedeploy" then
if deploy_on_engage then deploy_on_engage = false
else deploy_on_engage = true end
windower.add_to_chat(122, "Deploy On Engage: " .. tostring(deploy_on_engage))
elseif args[1] == "automaneuver" then
if auto_maneuvers then auto_maneuvers = false
else auto_maneuvers = true end
windower.add_to_chat(122, "Auto Maneuvers: " .. tostring(auto_maneuvers))
end
end
function do_maneuver()
local recasts = windower.ffxi.get_ability_recasts()
for i = 1, 3 do
local temp_index = maneuver_cast_index + i - 1
if temp_index > 3 then temp_index = temp_index - 3 end
local maneuver = maneuver_cast[temp_index]
if buffactive[maneuver] == nil or buffactive[maneuver] < target_maneuver_count[maneuver] then
if not recasts[210] or recasts[210] == 0 then
send_command('input /ja "' .. maneuver .. '" <me>')
maneuver_cast_index = temp_index + 1
if maneuver_cast_index > 3 then maneuver_cast_index = 1 end
return
end
end
end
local maneuver = maneuver_cast[maneuver_cast_index]
if not recasts[210] or recasts[210] == 0 then
send_command('input /ja "' .. maneuver_cast[maneuver_cast_index] .. '" <me>')
maneuver_cast_index = maneuver_cast_index + 1
if maneuver_cast_index > 3 then maneuver_cast_index = 1 end
end
end
function custom_precast(spell)
if string.lower(spell.english):contains("maneuver") then
equip(sets["Maneuver"])
return true
end
end
function custom_status_change(new,old)
if new == 'Engaged' and deploy_on_engage and pet.isvalid then
send_command('wait 1;input /ja Deploy <t>')
end
end
function pet_change(pet,gain)
maneuver_cast_index = 1
end
function print_current_maneuvers()
local text = ""
for k,v in pairs(maneuver_cast) do
text = text .. v .. ", "
end
add_to_chat(122, "Current Maneuvers: " .. text)
end
function auto_maneuver(new, old)
if auto_maneuvers and player.in_combat then
local recasts = windower.ffxi.get_ability_recasts()
if pet.isvalid then
if pet.status ~= "Engaged" then
send_command('input /ja Deploy <t>')
elseif not recasts[210] or recasts[210] == 0 then
for i = 1, 3 do
local maneuver = maneuver_cast[i]
if buffactive[maneuver] == nil or buffactive[maneuver] < target_maneuver_count[maneuver] then
send_command('input /ja "' .. maneuver .. '" <me>')
return
end
end
end
else
if not recasts[205] or recasts[205] == 0 then
send_command('input /ja Activate <me>')
elseif not recasts[115] or recasts[115] == 0 then
send_command('input /ja "Deus Ex Automata" <me>')
end
end
end
end
windower.register_event('time change', auto_maneuver) |
local m,s,o
m=Map("overwall",translate("IP Access Control"))
s=m:section(TypedSection,"access_control")
s.anonymous=true
s:tab("wan_ac",translate("WAN IP AC"))
o=s:taboption("wan_ac",DynamicList,"wan_bp_ips",translate("WAN White List IP"))
o.datatype="ip4addr"
o=s:taboption("wan_ac",DynamicList,"wan_fw_ips",translate("Proxy IP by Main Server"))
o.datatype="ip4addr"
s:tab("lan_ac",translate("LAN IP AC"))
o=s:taboption("lan_ac",ListValue,"lan_ac_mode",translate("LAN Access Control"))
o:value("w",translate("Allow listed only"))
o:value("b",translate("Allow all except listed"))
o.rmempty=false
o=s:taboption("lan_ac",DynamicList,"lan_ac_ips",translate("LAN Host List"))
o.datatype="ipaddr"
luci.ip.neighbors({family=4},function(entry)
if entry.reachable then
o:value(entry.dest:string())
end
end)
o:depends("lan_ac_mode","w")
o:depends("lan_ac_mode","b")
o=s:taboption("lan_ac",DynamicList,"lan_fp_ips",translate("LAN Force Proxy Host List"))
o.datatype="ipaddr"
luci.ip.neighbors({family=4},function(entry)
if entry.reachable then
o:value(entry.dest:string())
end
end)
o=s:taboption("lan_ac",DynamicList,"lan_gm_ips",translate("Game Mode Host List"))
o.datatype="ipaddr"
luci.ip.neighbors({family=4},function(entry)
if entry.reachable then
o:value(entry.dest:string())
end
end)
s:tab("yb_ac",translate("Youtube IP AC"))
o=s:taboption("yb_ac",DynamicList,"yb_fw_ips",translate("Proxy IP by Youtube Server"))
o.datatype="ip4addr"
s:tab("nf_ac",translate("Netflix IP AC"))
o=s:taboption("nf_ac",DynamicList,"nf_fw_ips",translate("Proxy IP by Netflix Server"))
o.datatype="ip4addr"
s:tab("cu_ac",translate("Custom IP AC"))
o=s:taboption("cu_ac",DynamicList,"cu_fw_ips",translate("Proxy IP by Custom Server"))
o.datatype="ip4addr"
s:tab("tg_ac",translate("Telegram IP AC"))
o=s:taboption("tg_ac",DynamicList,"tg_fw_ips",translate("Proxy IP by Telegram Server")
,translate("Telegram IP ranges has been proxied by default,No need to add"))
o.datatype="ip4addr"
return m
|
module:depends("http");
module:depends("pubsub");
local streams = {};
local service = hosts[module.host].modules.pubsub.service;
function client_closed(response)
local node = response._eventsource_node;
module:log("debug", "Destroying client for %q", node);
streams[node][response] = nil;
if next(streams[node]) == nil then
streams[node] = nil;
end
end
function serve_stream(event, node)
module:log("debug", "Client subscribed to: %s", node);
local response = event.response;
response.on_destroy = client_closed;
response._eventsource_node = node;
response.conn:write(table.concat({
"HTTP/1.1 200 OK";
"Content-Type: text/event-stream";
"Access-Control-Allow-Origin: *";
"Access-Control-Allow-Methods: GET";
"Access-Control-Max-Age: 7200";
"";
"";
}, "\r\n"));
local clientlist = streams[node];
if not clientlist then
clientlist = {};
streams[node] = clientlist;
end
clientlist[response] = response.conn;
return true;
end
function handle_update(event)
module:log("debug", "Item published: %q", event.node);
local node = event.node;
local clientlist = streams[node];
local item = event.item;
if (item.name == "json" and item.attr.xmlns == "urn:xmpp:json:0") or (item.name == "data" and item.attr.xmlns == "https://prosody.im/protocol/data") then
item = item[1];
end
local data = "data: "..tostring(item):gsub("\n", "\ndata: \n").."\n\n";
if not clientlist then module:log("debug", "No clients for %q", node); return; end
for response, conn in pairs(clientlist) do
conn:write(data);
end
end
module:provides("http", {
name = "eventsource";
route = {
["GET /*"] = serve_stream;
};
});
module:hook_object_event(service.events, "item-published", handle_update);
|
-- Gemeinschaft 5 module: dialplan class
-- (c) AMOOMA GmbH 2012-2013
--
module(...,package.seeall)
Dialplan = {}
-- local constants
local DIAL_TIMEOUT = 120;
local MAX_LOOPS = 20;
local DIALPLAN_FUNCTION_PATTERN = '^f[_%-].*';
local CALL_FORWARDING_SERVICES = {
USER_BUSY = 'busy',
CALL_REJECTED = 'busy',
NO_ANSWER = 'noanswer',
USER_NOT_REGISTERED = 'offline',
HUNT_GROUP_EMPTY = 'offline',
ACD_NO_AGENTS = 'offline',
ACD_TIMEOUT = 'noanswer',
}
-- create dialplan object
function Dialplan.new(self, arg)
require 'common.str';
require 'common.array';
arg = arg or {}
object = arg.object or {}
setmetatable(object, self);
self.__index = self;
self.log = arg.log;
self.database = arg.database;
self.caller = arg.caller;
return object;
end
function Dialplan.domain_get(self, domain)
local global_domain = freeswitch.API():execute('global_getvar', 'domain');
if common.str.blank(global_domain) then
if common.str.blank(domain) then
require 'common.database'
local database = common.database.Database:new{ log = self.log }:connect();
if not database:connected() then
self.log:error('[', uuid,'] DIALPLAN_DOMAIN - cannot connect to Gemeinschaft database');
else
require 'configuration.sip'
local domains = configuration.sip.Sip:new{ log = self.log, database = database }:domains();
if domains[1] then
domain = domains[1]['host'];
end
end
end
if database then
database:release();
end
if not common.str.blank(domain) then
self.log:notice('DIALPLAN_DOMAIN - setting default domain: ', domain);
freeswitch.API():execute('global_setvar', 'domain=' .. tostring(domain));
end
else
domain = global_domain;
end
if common.str.blank(domain) then
self.log:error('DIALPLAN_DOMAIN - no domain found');
end
return domain;
end
function Dialplan.configuration_read(self)
require 'common.configuration_table';
-- dialplan configuration
self.config = common.configuration_table.get(self.database, 'dialplan');
self.node_id = common.str.to_i(self.config.parameters.node_id);
self.domain = self:domain_get(self.config.parameters.domain);
self.dial_timeout = tonumber(self.config.parameters.dial_timeout) or DIAL_TIMEOUT;
self.max_loops = tonumber(self.config.parameters.max_loops) or MAX_LOOPS;
self.user_image_url = common.str.to_s(self.config.parameters.user_image_url);
self.phone_book_entry_image_url = common.str.to_s(self.config.parameters.phone_book_entry_image_url);
self.phonebook_number_lookup = self.config.parameters.phonebook_number_lookup;
self.geo_number_lookup = self.config.parameters.geo_number_lookup;
self.default_language = self.config.parameters.default_language or 'en';
self.send_ringing_to_gateways = self.config.parameters.send_ringing_to_gateways;
if tonumber(self.config.parameters.default_ringtone) then
self.default_ringtone = 'http://amooma.de;info=Ringer' .. self.config.parameters.default_ringtone .. ';x-line-id=0';
else
self.default_ringtone = 'http://amooma.de;info=Ringer1;x-line-id=0';
end
return (self.config ~= nil);
end
function Dialplan.hangup(self, code, phrase, cause)
if self.caller:ready() then
if tonumber(code) then
self.caller:respond(code, phrase or 'Thank you for flying Gemeinschaft5');
end
self.caller:hangup(cause or 16);
else
self.log:info('HANGUP - caller sesson down - cause: ', self.caller.session:hangupCause());
end
end
function Dialplan.auth_node(self)
require 'common.node'
local node = common.node.Node:new{ log = self.log, database = self.database }:find_by_address(self.caller.sip_contact_host);
if node then
self.log:info('AUTH_NODE - node_id: ', self.caller.node_id, ', contact address:', self.caller.sip_contact_host);
return true;
end
end
function Dialplan.auth_account(self)
if not common.str.blank(self.caller.auth_account_type) then
self.log:info('AUTH auth_account - ', self.caller.auth_account_type, '=', self.caller.account_id, '/', self.caller.account_uuid);
return true;
elseif not common.str.blank(self.caller.previous_destination_type) and not common.str.blank(self.caller.previous_destination_uuid) then
self.log:info('AUTH previous_destination - ', self.caller.previous_destination_type, '=', self.caller.previous_destination_id, '/', self.caller.previous_destination_uuid);
return true;
end
end
function Dialplan.auth_gateway(self)
require 'common.gateway';
local gateway_class = common.gateway.Gateway:new{ log = self.log, database = self.database};
local gateway = false;
if self.caller:to_b('gs_from_gateway') then
gateway = {
name = self.caller:to_s('gs_gateway_name'),
id = self.caller:to_i('gs_gateway_id'),
}
log:info('AUTH gateway - authenticaded by password and username: ', self.caller:to_s('username'), ', gateway=', gateway.id, '|', gateway.name, ', ip: ', self.caller.sip_contact_host);
return gateway_class:find_by_id(gateway.id);
else
gateway = gateway_class:authenticate(self.caller);
end
if gateway then
log:info('AUTH gateway - ', gateway.auth_source, ' ~ ', gateway.auth_pattern, ', gateway=', gateway.id, '|', gateway.name, ', ip: ', self.caller.sip_contact_host);
return gateway_class:find_by_id(gateway.id);
end
end
function Dialplan.object_find(self, arguments)
require 'common.object';
return common.object.Object:new{ log = self.log, database = self.database}:find(arguments);
end
function Dialplan.retrieve_caller_data(self)
self.caller.caller_phone_numbers_hash = {};
if not common.str.blank(self.caller.previous_destination_type) and not common.str.blank(self.caller.previous_destination_uuid) then
self.log:debug('CALLER_DATA - authenticate by previous destination: ', self.caller.previous_destination_type, '=', self.caller.previous_destination_id, '/', self.caller.previous_destination_uuid);
self.caller.auth_account = self:object_find{class = self.caller.previous_destination_type, uuid = self.caller.previous_destination_uuid};
elseif not common.str.blank(self.caller.auth_account_type) and not common.str.blank(self.caller.auth_account_uuid) then
self.caller.auth_account = self:object_find{class = self.caller.auth_account_type, uuid = self.caller.auth_account_uuid};
elseif not common.str.blank(self.caller.dialed_sip_user) then
self.caller.auth_account = self:object_find{class = 'sipaccount', domain = self.caller.dialed_domain, auth_account = self.caller.dialed_sip_user};
end
if self.caller.auth_account then
self.log:info('CALLER_DATA - auth account: ', self.caller.auth_account.class, '=', self.caller.auth_account.id, '/', self.caller.auth_account.uuid, ', groups: ', table.concat(self.caller.auth_account.groups, ','));
if self.caller.auth_account.owner then
self.log:info('CALLER_DATA - auth owner: ', self.caller.auth_account.owner.class, '=', self.caller.auth_account.owner.id, '/', self.caller.auth_account.owner.uuid, ', groups: ', table.concat(self.caller.auth_account.owner.groups, ','));
else
self.log:error('CALLER_DATA - auth owner not found');
end
if self.caller.set_auth_account then
self.caller:set_auth_account(self.caller.auth_account);
end
else
self.log:info('CALLER_DATA - no data - unauthenticated call: ', self.caller.auth_account_type, '=', self.caller.auth_account_id, '/', self.caller.auth_account_uuid);
end
if not common.str.blank(self.caller.account_type) and not common.str.blank(self.caller.account_uuid) then
self.caller.account = self:object_find{class = self.caller.account_type, uuid = self.caller.account_uuid};
if self.caller.account then
self.caller.clir = common.str.to_b(common.array.try(self.caller, 'account.record.clir'));
self.caller.clip = common.str.to_b(common.array.try(self.caller, 'account.record.clip'));
require 'common.phone_number'
self.caller.caller_phone_numbers = common.phone_number.PhoneNumber:new{ log = self.log, database = self.database }:list_by_owner(self.caller.account.id, self.caller.account.class);
for index, caller_number in ipairs(self.caller.caller_phone_numbers) do
self.caller.caller_phone_numbers_hash[caller_number] = true;
end
if not common.str.blank(self.caller.account.record.language_code) then
self.caller.language = self.caller.account.record.language_code;
end
self.log:info('CALLER_DATA - caller account: ', self.caller.account.class, '=', self.caller.account.id, '/', self.caller.account.uuid, ', phone_numbers: ', #self.caller.caller_phone_numbers, ', language: ', self.caller.language, ', groups: ', table.concat(self.caller.account.groups, ','));
if self.caller.account.owner then
self.log:info('CALLER_DATA - caller owner: ', self.caller.account.owner.class, '=', self.caller.account.owner.id, '/', self.caller.account.owner.uuid, ', groups: ', table.concat(self.caller.account.owner.groups, ','));
else
self.log:error('CALLER_DATA - caller owner not found');
end
if not self.caller.clir and self.caller.set_caller_id then
self.caller:set_caller_id(self.caller.caller_phone_numbers[1], self.caller.account.record.caller_name or self.caller.account.record.name);
end
else
self.log:error('CALLER_DATA - caller account not found: ', self.caller.account_type, '/', self.caller.account_uuid);
end
end
end
function Dialplan.destination_new(self, arg)
local destination = {
number = arg.number or '',
type = arg.type or 'unknown',
id = common.str.to_i(arg.id),
uuid = arg.uuid or '',
phone_number = arg.phone_number,
node_id = common.str.to_i(arg.node_id),
call_forwarding = {},
data = arg.data,
}
destination.type = common.str.downcase(destination.type);
if not common.str.blank(destination.number) then
if destination.type == 'unknown' and destination.number:find(DIALPLAN_FUNCTION_PATTERN) then
destination.type = 'dialplanfunction';
elseif destination.type == 'phonenumber' or destination.type == 'unknown' then
require 'common.phone_number'
destination.phone_number = common.phone_number.PhoneNumber:new{ log = self.log, database = self.database }:find_by_number(destination.number);
if destination.phone_number then
destination.type = common.str.downcase(destination.phone_number.record.phone_numberable_type);
destination.id = common.str.to_i(destination.phone_number.record.phone_numberable_id);
destination.uuid = common.str.to_s(destination.phone_number.record.phone_numberable_uuid);
destination.node_id = common.str.to_i(destination.phone_number.record.gs_node_id);
destination.account = self:object_find{ class = destination.type, id = destination.id};
if self.caller then
require 'common.call_forwarding';
local call_forwarding_class = common.call_forwarding.CallForwarding:new{ log = self.log, database = self.database, caller = self.caller }
destination.call_forwarding = call_forwarding_class:list_by_owner(destination.id, destination.type, self.caller.caller_phone_numbers);
for service, call_forwarding_entry in pairs(call_forwarding_class:list_by_owner(destination.phone_number.id, destination.phone_number.class, self.caller.caller_phone_numbers)) do
destination.call_forwarding[service] = call_forwarding_entry;
end
-- destination.call_forwarding = destination.phone_number:call_forwarding(self.caller.caller_phone_numbers);
end
elseif destination.type == 'unknown' then
require 'common.sip_account'
destination.account = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_auth_name(destination.number);
if destination.account then
destination.type = 'sipaccount';
destination.id = common.str.to_i(destination.account.record.id);
destination.uuid = common.str.to_s(destination.account.record.uuid);
destination.node_id = common.str.to_i(destination.account.record.gs_node_id);
end
end
end
end
if destination.node_id == 0 then
destination.node_id = self.node_id;
destination.node_local = true;
else
destination.node_local = (destination.node_id == self.node_id);
end
self.log:info('DESTINATION_NEW - ', destination.type, '=', destination.id, '/', destination.uuid,'@', destination.node_id, ', number: ', destination.number);
return destination;
end
function Dialplan.set_caller_picture(self, entry_id, entry_type, image)
entry_type = entry_type:lower();
if entry_type == 'user' then
require 'dialplan.user'
local user = dialplan.user.User:new{ log = self.log, database = self.database }:find_by_id(entry_id);
if user then
self.caller:export_variable('sip_h_Call-Info', '<' .. self.user_image_url .. '/' .. tonumber(entry_id) .. '/snom_caller_picture_' .. tostring(user.record.image) .. '>;purpose=icon');
end
elseif entry_type == 'phonebookentry' and image then
self.caller:export_variable('sip_h_Call-Info', '<' .. self.phone_book_entry_image_url .. '/' .. tonumber(entry_id) .. '/snom_caller_picture_' .. tostring(image) .. '>;purpose=icon');
end
end
function Dialplan.dial(self, destination)
local user_id = nil;
local tenant_id = nil;
destination.caller_id_number = destination.caller_id_number or self.caller.caller_phone_numbers[1];
if destination.node_local and destination.type == 'sipaccount' then
destination.pickup_groups = {};
destination.account = self:object_find{class = destination.type, id = destination.id};
if destination.account then
destination.uuid = destination.account.uuid;
if destination.account.class == 'sipaccount' then
destination.callee_id_name = destination.account.record.caller_name;
self.caller:set_callee_id(destination.number, destination.account.record.caller_name);
table.insert(destination.pickup_groups, 's' .. destination.account.id );
end
require 'common.group';
local group_names, group_ids = common.group.Group:new{ log = self.log, database = self.database }:name_id_by_permission(destination.id, destination.type, 'pickup');
self.log:debug('DESTINATION_GROUPS - pickup_groups: ', table.concat(group_names, ','));
for index=1, #group_ids do
table.insert(destination.pickup_groups, 'g' .. group_ids[index]);
end
end
if destination.account and destination.account.owner then
if destination.account.owner.class == 'user' then
user_id = destination.account.owner.id;
tenant_id = tonumber(destination.account.owner.record.current_tenant_id);
local user = self:object_find{class = destination.account.owner.class, id = tonumber(user_id)};
elseif destination.account.owner.class == 'tenant' then
tenant_id = destination.account.owner.id;
end
self.caller:set_variable('gs_destination_owner_type', destination.account.owner.class);
self.caller:set_variable('gs_destination_owner_id', destination.account.owner.id);
self.caller:set_variable('gs_destination_owner_uuid', destination.account.owner.uuid);
end
end
if not self.caller.clir then
if user_id or tenant_id then
if self.phonebook_number_lookup then
require 'dialplan.phone_book'
self.caller.phone_book_entry = dialplan.phone_book.PhoneBook:new{ log = self.log, database = self.database }:find_entry_by_number_user_tenant(self.caller.caller_phone_numbers, user_id, tenant_id);
end
if self.caller.phone_book_entry then
self.log:info('PHONE_BOOK_ENTRY - phone_book=', self.caller.phone_book_entry.phone_book_id, ' (', self.caller.phone_book_entry.phone_book_name, '), caller_id_name: ', self.caller.phone_book_entry.caller_id_name, ', ringtone: ', self.caller.phone_book_entry.bellcore_id);
destination.caller_id_name = common.str.to_ascii(self.caller.phone_book_entry.caller_id_name);
if tonumber(self.caller.phone_book_entry.bellcore_id) then
self.log:debug('RINGTONE - phonebookentry=', self.caller.phone_book_entry.id, ', ringtone: ', self.caller.phone_book_entry.bellcore_id);
self.caller:export_variable('alert_info', 'http://amooma.de;info=Ringer' .. self.caller.phone_book_entry.bellcore_id .. ';x-line-id=0');
end
if not common.str.blank(self.caller.phone_book_entry.image) then
self:set_caller_picture(self.caller.phone_book_entry.id, 'phonebookentry', self.caller.phone_book_entry.image);
elseif self.caller.account and self.caller.account.owner then
self:set_caller_picture(self.caller.account.owner.id, self.caller.account.owner.class);
end
elseif self.caller.account and self.caller.account.owner then
self:set_caller_picture(self.caller.account.owner.id, self.caller.account.owner.class);
elseif self.geo_number_lookup then
require 'dialplan.geo_number'
local geo_number = dialplan.geo_number.GeoNumber:new{ log = self.log, database = self.database }:find(destination.caller_id_number);
if geo_number then
self.log:info('GEO_NUMBER - found: ', geo_number.name, ', ', geo_number.country);
if geo_number.name then
destination.caller_id_name = common.str.to_ascii(geo_number.name) .. ', ' .. common.str.to_ascii(geo_number.country);
else
destination.caller_id_name = common.str.to_ascii(geo_number.country);
end
end
end
end
self.caller:set_caller_id(destination.caller_id_number, destination.caller_id_name or self.caller.caller_id_name);
end
local destinations = { destination };
if self.caller.forwarding_service == 'assistant' and self.caller.auth_account and self.caller.auth_account.class == 'sipaccount' then
self.caller.auth_account.type = self.caller.auth_account.class;
local forwarding_destination = self:destination_new( self.caller.auth_account );
if forwarding_destination then
forwarding_destination.alert_info = 'http://amooma.com;info=Ringer0;x-line-id=0'
table.insert(destinations, forwarding_destination);
end
end
require 'dialplan.sip_call'
return dialplan.sip_call.SipCall:new{ log = self.log, database = self.database, caller = self.caller }:fork(
destinations,
{ timeout = self.dial_timeout_active,
send_ringing = ( self.send_ringing_to_gateways and self.caller.from_gateway ),
bypass_media_network = self.config.parameters.bypass_media_network,
update_callee_display = self.config.parameters.update_callee_display,
detect_dtmf_after_bridge_caller = self.detect_dtmf_after_bridge_caller,
detect_dtmf_after_bridge_callee = self.detect_dtmf_after_bridge_callee,
}
);
end
function Dialplan.huntgroup(self, destination)
local hunt_group = self:object_find{class = 'huntgroup', id = tonumber(destination.id)};
if not hunt_group then
self.log:error('DIALPLAN_HUNTGROUP - huntgroup not found');
return { continue = true, code = 404, phrase = 'Huntgroup not found' }
end
self.caller:set_callee_id(destination.number, hunt_group.record.name);
destination.caller_id_number = destination.caller_id_number or self.caller.caller_phone_numbers[1];
if not self.caller.clir then
self.caller:set_caller_id(destination.caller_id_number, tostring(hunt_group.record.name) .. ' '.. tostring(self.caller.caller_id_name));
if self.caller.account and self.caller.account.owner then
self:set_caller_picture(self.caller.account.owner.id, self.caller.account.owner.class);
end
else
self.caller.anonymous_name = tostring(hunt_group.record.name);
end
self.caller.auth_account = hunt_group;
self.caller:set_auth_account(self.caller.auth_account);
self.caller.forwarding_number = destination.number;
self.caller.forwarding_service = 'huntgroup';
self.caller:set_variable('gs_forwarding_service', self.caller.forwarding_service);
self.caller:set_variable('gs_forwarding_number', self.caller.forwarding_number);
return hunt_group:run(self, self.caller, destination);
end
function Dialplan.acd(self, destination)
local acd = self:object_find{class = 'automaticcalldistributor', id = tonumber(destination.id)};
if not acd then
self.log:error('DIALPLAN_ACD - acd not found');
return { continue = true, code = 404, phrase = 'ACD not found' }
end
self.caller:set_callee_id(destination.number, acd.record.name);
destination.caller_id_number = destination.caller_id_number or self.caller.caller_phone_numbers[1];
if not self.caller.clir then
self.caller:set_caller_id(destination.caller_id_number, tostring(acd.record.name) .. ' '.. tostring(self.caller.caller_id_name));
if self.caller.account and self.caller.account.owner then
self:set_caller_picture(self.caller.account.owner.id, self.caller.account.owner.class);
end
else
self.caller.anonymous_name = tostring(acd.record.name);
end
self.caller.auth_account = acd;
self.caller:set_auth_account(self.caller.auth_account);
self.caller.forwarding_number = destination.number;
self.caller.forwarding_service = 'automaticcalldistributor';
self.caller:set_variable('gs_forwarding_service', self.caller.forwarding_service);
self.caller:set_variable('gs_forwarding_number', self.caller.forwarding_number);
acd:caller_new(self.caller.uuid);
local result = acd:run(self, self.caller, destination);
acd:caller_delete();
return result;
end
function Dialplan.conference(self, destination)
require 'common.conference';
local conference = common.conference.Conference:new{ log = self.log, database = self.database }:find_by_id(destination.id);
if not conference then
return { continue = false, code = 404, phrase = 'Conference not found' }
end
return conference:enter(self.caller, self.domain);
end
function Dialplan.faxaccount(self, destination)
require 'dialplan.fax'
local fax_account = dialplan.fax.Fax:new{ log = self.log, database = self.database }:find_by_id(destination.id);
if not fax_account then
return { continue = false, code = 404, phrase = 'Fax not found' }
end
self.log:info('FAX_RECEIVE start - fax_account=', fax_account.id, '/', fax_account.uuid, ', name: ', fax_account.record.name, ', station_id: ', fax_account.record.station_id);
self.caller:set_caller_id(self.caller.caller_phone_number);
self.caller:set_callee_id(destination.number, fax_account.record.name);
local fax_document = fax_account:receive(self.caller);
if not fax_document then
self.log:error('FAX_RECEIVE - error receiving fax document - fax_account=', fax_account.id, '/', fax_account.uuid);
return { continue = false, code = 500, phrase = 'Error receiving fax' };
end
fax_document.caller_id_number = self.caller.caller_phone_number;
fax_document.caller_id_name = self.caller.caller_id_name;
fax_document.uuid = self.caller.uuid;
self.log:info('FAX_RECEIVE end - success: ', fax_document.success,
', remote: ', fax_document.remote_station_id,
', pages: ', fax_document.transferred_pages, '/', fax_document.total_pages,
', result: ', fax_document.result_code, ' ', fax_document.result_text);
if fax_document.success then
self.log:notice('FAX_RECEIVE - saving fax document: ', fax_document.filename );
if not fax_account:insert_document(fax_document) then
self.log:error('FAX_RECEIVE - error inserting fax document to database - fax_account=', fax_account.id, '/', fax_account.uuid, ', file: ', fax_document.filename);
end
fax_account:trigger_notification(fax_account.id, self.caller.uuid);
end
return { continue = false, code = 200, phrase = 'OK' }
end
function Dialplan.callthrough(self, destination)
-- Callthrough
require 'dialplan.callthrough'
callthrough = dialplan.callthrough.Callthrough:new{ log = self.log, database = self.database }:find_by_id(destination.id)
if not callthrough then
self.log:error('CALLTHROUGH - no callthrough for destination number: ', destination.number);
return { continue = false, code = 404, phrase = 'Fax not found' }
end
self.log:info('CALLTHROUGH - number: ' .. destination.number .. ', name: ' .. callthrough.record.name);
local authorization = callthrough:authenticate(self.caller);
if not authorization then
self.log:notice('CALLTHROUGH - authentication failed');
return { continue = false, code = 403, phrase = 'Authentication failed' }
end
if type(authorization) == 'table' and tonumber(authorization.sip_account_id) and tonumber(authorization.sip_account_id) > 0 then
local auth_account = self:object_find{class = 'sipaccount', id = tonumber(authorization.sip_account_id)};
self.caller.forwarding_number = destination.number;
self.caller.forwarding_service = 'callthrough';
self.caller:set_variable('gs_forwarding_service', self.caller.forwarding_service);
self.caller:set_variable('gs_forwarding_number', self.caller.forwarding_number);
if auth_account then
self.caller.auth_account = auth_account;
self.caller:set_auth_account(self.caller.auth_account);
self.log:info('AUTH_ACCOUNT_UPDATE - account: ', self.caller.auth_account.class, '=', self.caller.auth_account.id, '/', self.caller.auth_account.uuid);
if self.caller.auth_account.owner then
self.log:info('AUTH_ACCOUNT_UPDATE - auth owner: ', self.caller.auth_account.owner.class, '=', self.caller.auth_account.owner.id, '/', self.caller.auth_account.owner.uuid);
else
self.log:error('AUTH_ACCOUNT_UPDATE - auth owner not found');
end
self.log:info('CALLTHROUGH - use sip account: ', auth_account.id, ' (', auth_account.record.caller_name, ')');
end
else
self.log:info('CALLTHROUGH - no sip account');
end
local destination_number = '';
for i = 1, 3, 1 do
if destination_number ~= '' then
break;
end
destination_number = session:read(2, 16, "ivr/ivr-enter_destination_telephone_number.wav", 3000, "#");
end
if destination_number == '' then
self.log:debug("no callthrough destination - hangup call");
return { continue = false, code = 404, phrase = 'No destination' }
end
require 'dialplan.router'
local route = dialplan.router.Router:new{ log = self.log, database = self.database, caller = self.caller, variables = self.caller }:route_run('prerouting', true);
if route and route.destination_number then
destination_number = route.destination_number;
end
if not callthrough:whitelist(destination_number) then
self.log:debug('caller not authorized to call destination number: ' .. destination_number .. ' - hangup call');
return { continue = false, code = 403, phrase = 'Unauthorized' }
end
return { continue = true, code = 302, number = destination_number }
end
function Dialplan.voicemail(self, destination)
require 'dialplan.voicemail';
local voicemail_account = nil;
if common.str.to_i(destination.id) > 0 then
voicemail_account = dialplan.voicemail.Voicemail:new{ log = self.log, database = self.database, domain = self.domain }:find_by_id(destination.id);
elseif self.caller.auth_account and self.caller.auth_account.class == 'sipaccount' then
voicemail_account = dialplan.voicemail.Voicemail:new{ log = self.log, database = self.database, domain = self.domain }:find_by_sip_account_id(self.caller.auth_account.id);
elseif self.caller.forwarding_number then
voicemail_account = dialplan.voicemail.Voicemail:new{ log = self.log, database = self.database, domain = self.domain }:find_by_number(self.caller.forwarding_number);
end
if not voicemail_account then
self.log:error('VOICEMAIL - mailbox not found, ');
return { continue = false, code = 404, phrase = 'Mailbox not found' }
end
voicemail_account:leave(self.caller, destination.number, self.caller.forwarding_number);
if self.caller:to_s("voicemail_message_len") == '' then
self.log:info('VOICEMAIL - no message saved');
end
return { continue = false, code = 200 }
end
function Dialplan.dialplanfunction(self, destination)
require 'dialplan.functions'
return dialplan.functions.Functions:new{ log = self.log, database = self.database, domain = self.domain, parent = self }:dialplan_function(self.caller, destination.number);
end
function Dialplan.switch(self, destination)
local result = nil;
self.dial_timeout_active = self.dial_timeout;
if not destination.node_local then
return self:dial(destination);
end
for service, call_forwarding in pairs(destination.call_forwarding) do
if self.caller.caller_phone_numbers_hash[call_forwarding.number] then
self.log:info('CALL_FORWARDING - caller number equals destination: ', call_forwarding.number,' - ignore service: ', service);
destination.call_forwarding[service] = nil;
end
end
if destination.call_forwarding.noanswer then
self.dial_timeout_active = tonumber(destination.call_forwarding.noanswer.timeout) or self.dial_timeout;
end
if destination.call_forwarding.always then
return { continue = true, call_forwarding = destination.call_forwarding.always }
elseif destination.call_forwarding.assistant then
if common.str.downcase(destination.call_forwarding.assistant.type) == 'huntgroup' then
require 'dialplan.hunt_group'
local hunt_group = dialplan.hunt_group.HuntGroup:new{ log = self.log, database = self.database }:find_by_id(destination.call_forwarding.assistant.id);
self.log:info('CALL_FORWARDING - huntgroup - auth_account: ', self.caller.auth_account_type, '=', self.caller.auth_account_uuid);
if hunt_group and (hunt_group:is_member_by_numbers(self.caller.caller_phone_numbers)) then
self.log:info('CALL_FORWARDING - caller is huntgroup member - ignore service: ', destination.call_forwarding.assistant.service);
else
return { continue = true, call_forwarding = destination.call_forwarding.assistant }
end
else
return { continue = true, call_forwarding = destination.call_forwarding.assistant }
end
end
-- reset ringtone
self.caller:export_variable('alert_info', self.default_ringtone);
if destination.phone_number then
destination.ringtone = destination.phone_number:ringtone();
end
if not destination.ringtone and destination.account and destination.account.ringtone then
destination.ringtone = destination.account:ringtone();
end
if destination.ringtone then
if destination.ringtone.bellcore_id then
self.log:debug('DESTINATION_RINGTONE - ', destination.ringtone.ringtoneable_type .. '=', destination.ringtone.ringtoneable_id, ', ringtone: ' .. destination.ringtone.bellcore_id);
self.caller:export_variable('alert_info', 'http://amooma.de;info=Ringer' .. tonumber(destination.ringtone.bellcore_id) .. ';x-line-id=0');
end
end
if destination.type == 'sipaccount' then
result = self:dial(destination);
if CALL_FORWARDING_SERVICES[result.disposition] then
result.call_forwarding = destination.call_forwarding[CALL_FORWARDING_SERVICES[result.disposition]];
if result.call_forwarding then
result.continue = true;
end
end
return result;
elseif destination.type == 'conference' then
return self:conference(destination);
elseif destination.type == 'faxaccount' then
return self:faxaccount(destination);
elseif destination.type == 'callthrough' then
return self:callthrough(destination);
elseif destination.type == 'huntgroup' then
result = self:huntgroup(destination);
if CALL_FORWARDING_SERVICES[result.disposition] then
result.call_forwarding = destination.call_forwarding[CALL_FORWARDING_SERVICES[result.disposition]];
if result.call_forwarding then
result.continue = true;
end
end
return result;
elseif destination.type == 'automaticcalldistributor' then
result = self:acd(destination);
if CALL_FORWARDING_SERVICES[result.disposition] then
result.call_forwarding = destination.call_forwarding[CALL_FORWARDING_SERVICES[result.disposition]];
if result.call_forwarding then
result.continue = true;
end
end
return result;
elseif destination.type == 'voicemail' or destination.type == 'voicemailaccount' then
return self:voicemail(destination);
elseif destination.type == 'dialplanfunction' then
return self:dialplanfunction(destination);
elseif not common.str.blank(destination.number) then
local result = { continue = false, code = 404, phrase = 'No route' }
local clip_no_screening = common.array.try(self.caller, 'account.record.clip_no_screening');
self.caller.caller_id_numbers = {}
if not common.str.blank(clip_no_screening) then
for index, number in ipairs(common.str.strip_to_a(clip_no_screening, ',')) do
table.insert(self.caller.caller_id_numbers, number);
end
end
for index, number in ipairs(self.caller.caller_phone_numbers) do
table.insert(self.caller.caller_id_numbers, number);
end
self.log:info('SWITCH - clir: ', self.caller.clir, ', caller_id_numbers: ', table.concat(self.caller.caller_id_numbers, ','));
destination.callee_id_number = destination.number;
destination.callee_id_name = nil;
if self.phonebook_number_lookup then
local user_id = common.array.try(self.caller, 'account.owner.id');
local tenant_id = common.array.try(self.caller, 'account.owner.record.current_tenant_id');
if user_id or tenant_id then
require 'dialplan.phone_book'
self.caller.callee_phone_book_entry = dialplan.phone_book.PhoneBook:new{ log = self.log, database = self.database }:find_entry_by_number_user_tenant({ destination.number }, user_id, tenant_id);
if self.caller.callee_phone_book_entry then
self.log:info('PHONE_BOOK_ENTRY - phone_book=', self.caller.callee_phone_book_entry.phone_book_id, ' (', self.caller.callee_phone_book_entry.phone_book_name, '), callee_id_name: ', common.str.to_ascii(self.caller.callee_phone_book_entry.caller_id_name));
destination.callee_id_name = common.str.to_ascii(self.caller.callee_phone_book_entry.caller_id_name);
end
end
end
if self.geo_number_lookup and not destination.callee_id_name then
require 'dialplan.geo_number'
local geo_number = dialplan.geo_number.GeoNumber:new{ log = self.log, database = self.database }:find(destination.number);
if geo_number then
self.log:info('GEO_NUMBER - found: ', geo_number.name, ', ', geo_number.country);
if geo_number.name then
destination.callee_id_name = common.str.to_ascii(geo_number.name) .. ', ' .. common.str.to_ascii(geo_number.country);
else
destination.callee_id_name = common.str.to_ascii(geo_number.country);
end
end
end
self.caller:set_callee_id(destination.callee_id_number, destination.callee_id_name);
require 'dialplan.router'
local routes = dialplan.router.Router:new{ log = self.log, database = self.database, caller = self.caller, variables = self.caller }:route_run('outbound');
if not routes or #routes == 0 then
self.log:notice('SWITCH - no route - number: ', destination.number);
return { continue = false, code = 404, phrase = 'No route' }
end
for index, route in ipairs(routes) do
self.caller:set_callee_id(route.callee_id_number or destination.callee_id_number, route.callee_id_name or destination.callee_id_name);
if route.type == 'hangup' then
self.log:notice('SWITCH_HANGUP - code: ', route.code, ', phrase: ', route.phrase, ', cause: ', route.cause);
return { continue = false, code = route.code or '404', phrase = route.phrase, cause = route.cause }
end
if route.type == 'forward' then
self.log:notice('SWITCH_CALL_FORWARDING - number: ', route.number);
return { continue = true, call_forwarding = { number = route.number, service = 'route', type = 'phonenumber' }}
end
for key, value in pairs(route) do
destination[key] = value;
end
result = self:dial(destination);
if result.continue == false then
break;
end
if common.str.to_b(self.route_failover[tostring(result.code)]) == true then
self.log:info('SWITCH - failover - code: ', result.code);
elseif common.str.to_b(self.route_failover[tostring(result.cause)]) == true then
self.log:info('SWITCH - failover - cause: ', result.cause);
else
self.log:info('SWITCH - no failover - cause: ', result.cause, ', code: ', result.code);
break;
end
end
return result;
end
self.log:error('SWITCH - destination not found - type: ', destination.type);
return { continue = true, code = 404, phrase = destination.type .. ' not found' }
end
function Dialplan.run(self, destination)
require 'dialplan.router';
self.caller:set_variable('hangup_after_bridge', false);
self.caller:set_variable('bridge_early_media', 'true');
self.caller:set_variable('gs_save_cdr', true);
self.caller:set_variable('gs_call_service', 'dial');
self.caller.session:setAutoHangup(false);
self.caller.date = os.date('%y%m%d%w');
self.caller.time = os.date('%H%M%S');
if self.config then
self.caller:export_variable('sip_cid_type=' .. (self.config.sip_cid_type or 'none'));
end
if type(self.config.variables) == 'table' then
for key, value in pairs(self.config.variables) do
self.caller:set_variable(key, value);
end
end
self.caller.domain_local = self.domain;
self:retrieve_caller_data();
self.route_failover = common.configuration_table.get(self.database, 'call_route', 'failover');
self.caller.language = self.caller.language or self.default_language;
if not destination or destination.type == 'unknown' then
local route = nil;
if self.caller.gateway then
if not common.str.blank(self.caller.gateway.settings.number_source) then
self.log:debug('INBOUND_NUMBER: number_source: ', self.caller.gateway.settings.number_source, ', number: ', self.caller:to_s(self.caller.gateway.settings.number_source));
self.caller.destination_number = self.caller:to_s(self.caller.gateway.settings.number_source);
end
route = dialplan.router.Router:new{ log = self.log, database = self.database, caller = self.caller, variables = self.caller }:route_run('inbound', true);
if route then
local ignore_keys = {
id = true,
gateway = true,
['type'] = true,
channel_variables = true,
};
for key, value in pairs(route) do
if not ignore_keys[key] then
self.caller[key] = value;
end
end
self.caller.caller_phone_numbers[1] = self.caller.caller_id_number;
else
self.log:notice('INBOUND - no route');
end
else
route = dialplan.router.Router:new{ log = self.log, database = self.database, caller = self.caller, variables = self.caller }:route_run('prerouting', true);
if route then
local ignore_keys = {
id = true,
gateway = true,
['type'] = true,
channel_variables = true,
};
for key, value in pairs(route) do
if not ignore_keys[key] then
self.caller[key] = value;
end
end
end
end
if route then
if type(route.channel_variables) == 'table' then
for key, value in pairs(route.channel_variables) do
self.caller:set_variable(key, value);
end
end
destination = self:destination_new{ ['type'] = route.type, id = route.id, number = route.destination_number }
self.caller.destination_number = destination.number;
self.caller.destination = destination;
elseif not destination or destination.type == 'unknown' then
destination = self:destination_new{ number = self.caller.destination_number }
self.caller.destination = destination;
end
end
self.caller:set_variable('default_language', self.caller.language);
self.caller:set_variable('sound_prefix', common.array.try(self.config, 'sounds.' .. tostring(self.caller.language)));
self.log:info('DIALPLAN start - caller_id: ',self.caller.caller_id_number, ' "', self.caller.caller_id_name, '" , number: ', destination.number, ', language: ', self.caller.language);
self.caller.static_caller_id_number = self.caller.caller_id_number;
self.caller.static_caller_id_name = self.caller.caller_id_name;
self.caller:set_variable('gs_caller_id_number', self.caller.caller_id_number);
self.caller:set_variable('gs_caller_id_name', self.caller.caller_id_name);
local result = { continue = false };
local loop = self.caller.loop_count;
while self.caller:ready() and loop < self.max_loops do
loop = loop + 1;
self.caller.loop_count = loop;
self.caller.caller_id_number = self.caller.static_caller_id_number;
self.caller.caller_id_name = self.caller.static_caller_id_name;
self.log:info('LOOP ', loop,
' - destination: ', destination.type, '=', destination.id, '/', destination.uuid,'@', destination.node_id,
', number: ', destination.number);
self.caller:set_variable('gs_clir', self.caller.clir);
self.caller:set_variable('gs_destination_type', destination.type);
self.caller:set_variable('gs_destination_id', destination.id);
self.caller:set_variable('gs_destination_uuid', destination.uuid);
self.caller:set_variable('gs_destination_number', destination.number);
self.caller:set_variable('gs_destination_node_local', destination.node_local);
self.caller:set_variable('gs_destination_node_id, ', destination.node_id);
result = self:switch(destination);
result = result or { continue = false, code = 502, cause = 'DESTINATION_OUT_OF_ORDER', phrase = 'Destination out of order' }
if result.call_service then
self.caller:set_variable('gs_call_service', result.call_service);
end
if not result.continue then
break;
end
if result.call_forwarding then
self.log:info('LOOP ', loop, ' CALL_FORWARDING - service: ', result.call_forwarding.service,
', destination: ', result.call_forwarding.type, '=', result.call_forwarding.id,
', number: ', result.call_forwarding.number);
local auth_account = self:object_find{class = destination.type, id = destination.id};
self.caller.forwarding_number = destination.number;
self.caller.forwarding_service = result.call_forwarding.service;
self.caller:set_variable('gs_forwarding_service', self.caller.forwarding_service);
self.caller:set_variable('gs_forwarding_number', self.caller.forwarding_number);
if auth_account then
self.caller.auth_account = auth_account;
self.caller:set_auth_account(self.caller.auth_account);
self.log:info('AUTH_ACCOUNT_UPDATE - account: ', self.caller.auth_account.class, '=', self.caller.auth_account.id, '/', self.caller.auth_account.uuid);
if self.caller.auth_account.owner then
self.log:info('AUTH_ACCOUNT_UPDATE - auth owner: ', self.caller.auth_account.owner.class, '=', self.caller.auth_account.owner.id, '/', self.caller.auth_account.owner.uuid);
else
self.log:error('AUTH_ACCOUNT_UPDATE - auth owner not found');
end
end
destination = self:destination_new(result.call_forwarding);
self.caller.destination = destination;
self.caller.destination_number = destination.number;
if not result.no_cdr and auth_account then
require 'common.call_history'
common.call_history.CallHistory:new{ log = self.log, database = self.database }:insert_forwarded(
self.caller.uuid,
auth_account.class,
auth_account.id,
self.caller,
destination,
result
);
local forwarding_path = self.caller:to_s('gs_forwarding_path');
if forwarding_path ~= '' then
forwarding_path = forwarding_path .. ',';
end
forwarding_path = forwarding_path .. auth_account.class:sub(1,1) .. ':' .. auth_account.id;
self.caller:set_variable('gs_forwarding_path', forwarding_path);
self.log:debug('FORWARDING_PATH: ', forwarding_path);
end
end
if result.number then
self.log:info('LOOP ', loop, ' NEW_DESTINATION_NUMBER - number: ', result.number );
destination = self:destination_new{ number = result.number }
self.caller.destination = destination;
self.caller.destination_number = destination.number;
end
end
if loop >= self.max_loops then
result = { continue = false, code = 483, cause = 'EXCHANGE_ROUTING_ERROR', phrase = 'Too many hops' }
end
self.log:info('DIALPLAN end - caller_id: ',self.caller.caller_id_number, ' "', self.caller.caller_id_name,'"',
', destination: ', destination.type, '=', destination.id, '/', destination.uuid,'@', destination.node_id,
', number: ', destination.number, ', result: ', result.code, ' ', result.phrase);
if self.caller:ready() then
self:hangup(result.code, result.phrase, result.cause);
end
self.caller:set_variable('gs_save_cdr', not result.no_cdr);
end
|
data:extend{
{
type = 'item',
name = 'hand-crank',
icon = '__HandCrank__/graphics/icon/hand-crank.png',
icon_size = 64,
flags = {'goes-to-quickbar'},
subgroup = 'energy',
place_result='hand-crank',
order = 'b[energy]-d[hand-crank]',
stack_size = 10,
}
}
|
--
-- c_switch.lua
--
----------------------------------------------------------------
----------------------------------------------------------------
-- Effect switching on and off
--
-- To switch on:
-- triggerEvent( "switchBloom", root, true )
--
-- To switch off:
-- triggerEvent( "switchBloom", root, false )
--
----------------------------------------------------------------
----------------------------------------------------------------
--------------------------------
-- Switch effect on or off
--------------------------------
function switchBloom( blOn )
-- outputDebugString( "switchBloom: " .. tostring(blOn) )
if blOn then
enableBloom()
else
disableBloom()
end
end
addEvent( "switchBloom", true )
addEventHandler( "switchBloom", resourceRoot, switchBloom )
|
local Rollbar = require('love-rollbar')
local config = require('config')
function love.load()
--configure rollbar
Rollbar.access_token = config.rollbar_api_key
Rollbar.environment = 'development'
Rollbar.app_version = '0.0.0'
local foo = {}
x=foo.bar.baz
end
local old_error = love.errhand
function love.errhand(message)
Rollbar.error(message, {
level = "critical",
data = {
my_custom_data = 12345
}
})
old_error(message)
end
|
--Load configuration settings which affect the replications
local reps_multiplier = settings.startup['replresearch-item-multiplier'].value
local research_time = settings.startup['replresearch-item-time'].value
local repl_penalty = settings.startup['replication-penalty'].value
local fluid_quantity = settings.startup['replication-fluid-quantity'].value
--Go through every replication and make the technologies and recipes for them
for _, current_replication in pairs(repl_table) do
--Don't even spend time looking at replications from disabled recipes
if current_replication.category.enabled then
--Remove all items which do not exist
local item_table = current_replication.items
for currentItem = #item_table, 1, -1 do
if item_table[currentItem].pointer == nil then
log('The item "' .. item_table[currentItem].name .. '" was removed from the repltech "' .. current_replication.name .. '" because the item in question does not exist.')
table.remove(item_table, currentItem)
end
end
--only make the technology if at least one item will be created
if (#current_replication.items > 0) then
--If for whatever reason we have a bug with technology not unlocking whilst having every prerequisite tech unlocked, Look here. Activate line 192
--Set up temporary storage space for new data
local repl_data = {}
--Generate recipe data for each item
local effects = {}
for _, current_item in ipairs(current_replication.items) do
--Calculate the item's cost and round it to the nearest single decimal place (minimum 0.1)
local cost = current_item.cost
if type(cost) ~= 'number' then
if type(cost) == 'table' then
log('Something went really wrong when it comes to the replication of "' .. current_item.name .. "\". Somehow its cost table could not be processed into a number even though there are enough default cases that this should never be possible. Maybe a replication is there twice or something. Factorio is going to go and crash now. Here's what the table itself looked like after somehow slipping through cost calculations: " .. table.tostring(cost))
else
cost = tonumber(cost)
end
end
if current_item.fluid then
cost = cost * fluid_quantity
end
cost = math.floor((cost + repl_penalty) * 10 + 0.5) / 10
if cost <= 0 then
cost = 0.1
end
--Put whether the item is a fluid or not into string form
local type
local amount
if current_item.fluid then
type = 'fluid'
amount = fluid_quantity
else
type = 'item'
amount = 1
end
--Make the icon for the item
local icon
if current_item.pointer.icon then
--Create a layered icon consisting of the item's icon underneath the replication border for this replication's category
icon = {
{icon = current_item.pointer.icon, icon_size = current_item.pointer.icon_size},
{
icon = '__dark-tech__/graphics/icons/borders/repl-' .. current_replication.category.name .. '.png'
}
}
elseif current_item.pointer.icons then
--Create a copy of the item's already layered icon
icon = {}
for _, current_layer in ipairs(current_item.pointer.icons) do
local icon_size = current_layer.icon_size or current_item.pointer.icon_size
icon[#icon + 1] = {
icon = current_layer.icon,
icon_size = icon_size
}
end
--Add the replication border as an extra layer
icon[#icon + 1] = {
icon_size = 32,
icon = '__dark-tech__/graphics/icons/borders/repl-' .. current_replication.category.name .. '.png'
}
else
log('The item ' .. current_item.pointer.name .. ' does not have an icon. Factorio will now crash due to being unable to create a replication icon for it. That and because the item itself does not have an icon.')
end
--Generate the recipe itself WITH LIQUID MATTER
repl_data[#repl_data + 1] = {
type = 'recipe',
name = 'repl-' .. (current_item.internal_name_override or current_item.name),
category = 'replication-' .. current_replication.tier,
enabled = false,
energy_required = cost,
ingredients = {{type = 'fluid', name = 'eridium', amount = 1 + cost * 2}},
results = {
{
type = type,
name = current_item.name,
amount = amount
}
},
icons = icon,
icon_size = 32,
subgroup = 'replication-recipes-' .. current_replication.category.name
}
--Create an unlock effect for this recipe
effects[#effects + 1] = {type = 'unlock-recipe', recipe = 'repl-' .. current_item.name}
end
--Get the technology's icon
local tech_icon
local tech_icon_size
if current_replication.overrides.icon then
tech_icon = {
{icon = current_replication.overrides.icon},
{icon = '__dark-tech__/graphics/icons/borders/tech-' .. current_replication.category.name .. '.png'}
}
tech_icon_size = 128
else
if tonumber(repl_data[1].icons[1].icon_size) > 32 then
tech_icon = {
repl_data[1].icons[1],
{
icon = '__dark-tech__/graphics/icons/borders/tech-' .. current_replication.category.name .. '.png',
icon_size = 128,
scale = repl_data[1].icons[1].icon_size / 128
}
}
tech_icon_size = repl_data[1].icons[1].icon_size
else
tech_icon = repl_data[1].icons
tech_icon_size = repl_data[1].icons[1].icon_size
end
end
--log(serpent.block(tech_icon))
--Find and put together the pieces of the technology's display name
local display_name = {'repltype-tech.display', {'repltype-tech.' .. current_replication.category.name}}
local first_item = current_replication.items[1]
if current_replication.overrides.localized_name then
display_name[3] = current_replication.overrides.localized_name
elseif first_item.pointer.localised_name then
display_name[3] = first_item.pointer.localised_name
elseif first_item.pointer.place_result then
--If an item can be placed as an entity then its item display name defaults to that entity's display name during localization. Many placable items do not have actual names of their own and instead use the names of their placed forms.
display_name[3] = {'entity-name.' .. first_item.pointer.place_result}
elseif first_item.fluid then
display_name[3] = {'fluid-name.' .. first_item.pointer.name}
else
display_name[3] = {'item-name.' .. first_item.pointer.name}
end
--Generate technology data
local upgrade = current_replication.overrides.upgrade
if upgrade == nil then
upgrade = current_replication.category.upgrade
end
local research_multiplier = current_replication.overrides.research_multiplier or current_replication.category.research_multiplier or 1
repl_data[#repl_data + 1] = {
type = 'technology',
name = 'repl-' .. current_replication.name,
localised_name = display_name,
icons = tech_icon,
icon_size = tech_icon_size,
effects = effects,
prerequisites = current_replication.prerequisites,
unit = repl_research(current_replication.tier, reps_multiplier * research_multiplier, research_time),
upgrade = upgrade,
order = 'z-z-z'
--"z-"..current_replication.category.order
}
--Add the new data to Factorio's main data structure
data:extend(repl_data)
else
log('The repltech "' .. current_replication.name .. '" was not created as a technology because it does not contain any replicatable items.')
end
end
end
|
function GetPlayerLookPos(Player)
local World = Player:GetWorld()
local Start = Player:GetEyePosition()
local End = Start + Player:GetLookVector() * 150
local HitCoords = nil
local Callbacks =
{
OnNextBlock = function(BlockPos, BlockType)
if BlockType ~= E_BLOCK_AIR then
HitCoords = BlockPos
return true
end
end
}
cLineBlockTracer:Trace(World, Callbacks, Start, End)
return HitCoords
end
function IsEnchantable()
if HeldItemType >= 256 and HeldItemType <= 259 then
return true
elseif HeldItemType >= 267 and HeldItemType <= 279 then
return true
elseif HeldItemType >= 283 and HeldItemType <= 286 then
return true
elseif HeldItemType >= 290 and HeldItemType <= 294 then
return true
elseif HeldItemType >= 298 and HeldItemType <= 317 then
return true
elseif HeldItemType >= 290 and HeldItemType <= 294 then
return true
elseif HeldItemType == 346 or HeldItemType == 359 or HeldItemType == 261 then
return true
end
end
function GetAverageNum(Table)
local Sum = 0
for i,Num in ipairs(Table) do
Sum = Sum + Num
end
return (Sum / #Table)
end
function CheckPlayer(Player)
if UsersINI:GetValue(Player:GetUUID(), "Jailed") == "true" then
Jailed[Player:GetUUID()] = true
else
Jailed[Player:GetUUID()] = false
end
if UsersINI:GetValue(Player:GetUUID(), "Muted") == "true" then
Muted[Player:GetUUID()] = true
else
Muted[Player:GetUUID()] = false
end
end
|
--[[
Copyright (C) 2019 Onset Roleplay
Developers:
* Logic
Contributors:
* Blue Mountains GmbH
]]--
local colour = ImportPackage('colours')
AddCommand("refuel", function (playerid)
if GetPlayerState(playerid) ~= PS_DRIVER then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You must be in the driver seat.</>")
end
local vehicle = GetPlayerVehicle(playerid)
if GetVehicleEngineState(vehicle) ~= false then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You must turn the engine off first.</>")
end
local id = Pump_Nearest(playerid)
if id == 0 then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: You are not in range of any gas pump.</>")
end
if PumpData[id].is_occupied ~= 0 then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: This fuel pump is already occupied.")
end
if VehicleData[vehicle].fuel > 95 then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: This vehicle doesn't need any fuel.</>")
end
if PumpData[id].litres == 0 then
return AddPlayerChat(playerid, "<span color=\""..colour.COLOUR_LIGHTRED().."\">Error: This pump doesn't have enough fuel.")
end
local x, y, z = GetPlayerLocation(playerid)
AddPlayerChatRange(x, y, 800.0, "* "..GetPlayerName(playerid).." has started refilling their vehicle.")
PumpData[id].is_occupied = playerid
PumpData[id].timer = CreateTimer(OnPumpTick, 1000, id, vehicle)
end)
AddCommand("fill", function (playerid)
local vehicleid = GetNearestVehicle(playerid)
if (IsPlayerInVehicle(playerid) or vehicleid == 0) then
return AddPlayerChatError(playerid, "You are not standing near any vehicle.")
end
if (not Inventory_HasItem(playerid, INV_ITEM_FUELCAN)) then
return AddPlayerChatError(playerid, "You don't have any fuel cans on you.")
end
if (GetVehicleEngineState(vehicleid)) then
return AddPlayerChatError(playerid, "You must shut off the engine first.")
end
if (GetVehicleFuel(vehicleid) > 95) then
return AddPlayerChatError(playerid, "This vehicle doesn't need any fuel.")
end
if (PlayerData[playerid].fuel_can) then
return AddPlayerChatError(playerid, "You are already using a can of fuel.")
end
PlayerData[playerid].fuel_can = 1
Inventory_TakeItem(playerid, INV_ITEM_FUELCAN, 1)
local x, y, z = GetPlayerLocation(playerid)
AddPlayerChatRange(x, y, 800.0, "* " .. GetPlayerName(playerid) .. " opens a can of fuel and fills the vehicle.")
SetVehicleFuel(vehicleid, 100)
return
end)
AddCommand("gotopump", function (playerid, pumpid)
if (PlayerData[playerid].admin < 3) then
return AddPlayerChatError(playerid, "You don't have permission to use this command.")
end
if pumpid == nil then
return AddPlayerChatUsage(playerid, "/gotopump <pump>")
end
pumpid = tonumber(pumpid)
if PumpData[pumpid] == nil then
return AddPlayerChatError(playerid, "Pump " .. pumpid .. " doesn't exist.")
end
SetPlayerLocation(playerid, PumpData[pumpid].x, PumpData[pumpid].y, PumpData[pumpid].z)
AddPlayerChat(playerid, "You have been teleported to pump ID: " .. pumpid ..".")
end) |
return {'tuf','tuffen','tufkrijt','tufsteen','tuftuf','tuft','tufte','tuften','tuftufs'} |
local call_count
local normalizer = function(key)
call_count = call_count + 1
local num = tonumber(key)
return num, (not num) and "not a valid number"
end
-- create a simple cache, returns the cache, but also it's cache
-- table for test inspection
local function create_cache(weak)
local cache
local r = {
get = function(self, key)
return cache[key]
end,
set = function(self, key, value)
cache[key] = value
return true
end,
delete = function(self, key)
cache[key] = nil
return true
end,
flush_all = function(self)
cache = {}
-- self.cache = cache -- for debugging only
if weak then
setmetatable(cache, { __mode = "v" })
end
end
}
r:flush_all() -- initialize the internal cache
return r, cache
end
describe("ncache:", function()
local ncache, cache
before_each(function()
ncache = require("ncache")
cache = ncache.new(normalizer)
call_count = 0
end)
after_each(function()
cache = nil
end)
it("requires anormalizer function", function()
assert.has.error(function()
ncache.new(nil)
end)
end)
it("stores an entry", function()
cache:set(5, "value 5")
assert.equal(1, call_count) -- normalized once
assert.equal("value 5", cache:get(5))
assert.equal(1, call_count) -- don't normalize again
end)
it("getting a non existing key returns a 'key not found' error", function()
local value, err = cache:get(5)
assert.is_nil(value)
assert.equal(ncache.ERR_NOT_FOUND, err)
end)
it("setting a value to nil is supported", function()
cache:set(5, nil) -- set value to nil
assert.equal(1, call_count)
local value, err = cache:get(5)
assert.is_nil(value)
assert.is_nil(err) -- no error in this case
assert.equal(1, call_count)
end)
it("caches raw and normalized keys", function()
cache:set("5", "value 5")
assert.equal(1, call_count) -- normalized once
assert.equal("value 5", cache:get(5)) -- get using normalized key
assert.equal(1, call_count) -- don't normalize again
assert.equal("value 5", cache:get("5")) -- get using raw key
assert.equal(1, call_count) -- don't normalize again
end)
it("set updates all related entries", function()
local value = {} -- by reference value
cache:set(5, "value 5")
cache:get("5")
assert.equal(2, call_count) -- once for each key
cache:set("5", value)
assert.equal(2, call_count) -- no new ones
assert.equal(value, cache:get("5")) -- get using raw key
assert.equal(value, cache:get(5)) -- get using normalized key
assert.equal(2, call_count) -- still no new ones
end)
it("delete removes entry", function()
cache:set(5, "value 5")
assert.equal(1, call_count) -- normalized once
cache:delete(5)
cache:set(5, "value 5")
assert.equal(2, call_count) -- normalized again after deleting
end)
it("raw_set bypasses the normalizer", function()
cache:raw_set("5", "value 5")
cache:raw_set(5, "why 5?")
assert.equal(0, call_count) -- normalized never
assert.equal("value 5", cache:get("5"))
assert.equal("why 5?", cache:get(5))
assert.equal(0, call_count) -- normalized still never
end)
it("delete removes key-variants as well", function()
cache:set(5, "value 5")
cache:set("5", "value 5")
assert.equal(2, call_count) -- normalized both variants
cache:delete(5) -- delete by normalized-key -> orphane the raw one
collectgarbage()
collectgarbage() -- make sure to clean weak tables
cache:set(5, "value 5")
cache:set("5", "value 5")
assert.equal(4, call_count) -- normalized both variants again
end)
it("delete removes key-variants without GC", function()
finally(function()
collectgarbage("restart")
end)
cache:set(5, "value 5")
cache:set("5", "value 5")
assert.equal(2, call_count) -- normalized both variants
collectgarbage("stop")
cache:delete(5) -- delete by normalized-key -> orphane the raw one
cache:set(5, "value 5")
cache:set("5", "value 5")
assert.equal(4, call_count) -- normalized both variants again
end)
it("flush_all removes entries", function()
cache:set(5, "value 5")
cache:flush_all()
assert.is_nil(cache:get(5))
end)
it("flush_all removes key-variants as well", function()
cache:set(5, "value 5")
cache:set("5", "value 5")
assert.equal(2, call_count) -- normalized both variants
cache:flush_all()
assert.is_nil(cache:get(5))
assert.is_nil(cache:get("5"))
assert.equal(4, call_count) -- normalized both variants again
end)
it("set/get/delete return error on key-normalization failure", function()
local result, err = cache:set(nil,"some value")
assert.is_nil(result)
assert.matches(err, "failed to normalize key: not a valid number")
local result, err = cache:get(nil,"some value")
assert.is_nil(result)
assert.matches(err, "failed to normalize key: not a valid number")
local result, err = cache:delete(nil,"some value")
assert.is_nil(result)
assert.matches(err, "failed to normalize key: not a valid number")
end)
it("external eviction of cache-keys regenerates them", function()
local key_cache, inspect = create_cache()
local value_cache = create_cache()
local nc = ncache.new(normalizer, key_cache, value_cache)
nc:set(5, "value 5")
nc:get("5")
assert.equal(2, call_count) -- normalized both variants
assert(inspect["5"]) -- value should be there
inspect["5"] = nil -- remove it, emulate external eviction
assert.equal("value 5", nc:get("5")) -- retrieve proper value
assert.equal(3, call_count) -- one more normalization
end)
it("external eviction of cache-values also drops key-variants", function()
local key_cache = create_cache()
local value_cache, inspect = create_cache()
local nc = ncache.new(normalizer, key_cache, value_cache)
nc:set(5, "value 5")
nc:get("5")
assert(inspect[5]) -- value should be there
inspect[5] = nil -- remove it, emulate external eviction
local value, err = nc:get("5") -- retrieve proper value
assert.is_nil(value) -- should no longer be available
assert.equal(err, ncache.ERR_NOT_FOUND)
end)
end)
|
--Script Name : scriptTemplate
--Author : Jean Loup Pecquais
--Description : Simple template
--v1.0.0
local libPath = reaper.GetExtState("Reaper Evolution", "libPath")
if not libPath or libPath == "" then
reaper.MB("Reaper Evolution library is not found. Please refer to user guide", "Library not found", 0)
return
end
loadfile(libPath .. "reaVolutionLib.lua")()
-------------------------------------------------------------------------------------------------------------
function main()
reaper.BR_GetMouseCursorContext()
local track = reaper.BR_GetMouseCursorContext_Track()
local itemUnderMouse = reaper.BR_GetMouseCursorContext_Item()
local position = reaper.BR_PositionAtMouseCursor( false )
local itemStart = {}
local itemEnd = {}
local closestEdge1, closestEdge2
if reaper.CountTrackMediaItems(track) == 0 then return end
if itemUnderMouse == nil then
local j = 1
for i=1, reaper.CountMediaItems(0) do
local item = reaper.GetMediaItem( 0, i-1 )
local isHold = reaper.MediaItemDescendsFromTrack(item, track)
if isHold == 1 then
itemStart[j] = reaper.GetMediaItemInfo_Value(item, "D_POSITION")
itemEnd[j] = itemStart[j] + reaper.GetMediaItemInfo_Value(item, "D_LENGTH")
-- table.insert(itemStart, reaper.GetMediaItemInfo_Value(item, "D_POSITION"))
-- table.insert(itemEnd, itemStart[i] + reaper.GetMediaItemInfo_Value(item, "D_LENGTH"))
-- print(itemStart[i])
-- print(itemEnd[i])
local val = position - itemEnd[j]
if val < 0 then
closestEdge1 = itemEnd[j-1] or 0
closestEdge2 = itemStart[j]
if closestEdge2 ~= nil then reaper.GetSet_LoopTimeRange2(0, true, false, closestEdge1, closestEdge2, true) end
return
end
j = j+1
end
end
end
end
main() |
--GamePadMenu
DefineClass.GamepadIGMenu = {
__parents = {"ItemMenu"},
hide_single_category = true,
}
function IsHUDResupplyEnabled()
return (not g_Tutorial or g_Tutorial.EnableResupply) and g_Consts.SupplyMissionsEnabled == 1 and true or false
end
function IsHUDResearchEnabled()
return (not g_Tutorial or g_Tutorial.EnableResearch) and true or false
end
GamepadIGMenu_game_items = {
{ --build menu
name = "idBuild",
display_name = T(4237, "Build Menu"),
icon = "UI/Icons/console_build.tga",
action = function() HUD.idBuildOnPress() end,
description = "",
close_parent = false,
},
{ --overview
name = "idOverview",
display_name = T(3996, "Map Overview"),
icon = "UI/Icons/console_overview.tga",
action = function() HUD.idOverviewOnPress() end,
description = "",
close_parent = false,
},
{ --resupply
name = "idResupply",
display_name = T(3997, "Resupply"),
icon = "UI/Icons/console_resupply.tga",
enabled_fn = IsHUDResupplyEnabled,
action = function() HUD.idResupplyOnPress() end,
description = "",
},
{ --researh
name = "idResearch",
display_name = T(311, "Research"),
icon = "UI/Icons/console_research.tga",
enabled_fn = IsHUDResearchEnabled,
action = function() HUD.idResearchOnPress() end,
description = "",
},
{ --mars screen
name = "idMarsScreen",
display_name = T(11030, "Planetary View"),
icon = "UI/Icons/console_mars_screen.tga",
enabled_fn = function () return not g_Tutorial end,
action = function() HUD.idPlanetaryViewOnPress() end,
description = "",
},
{ --goals
name = "idGoals",
display_name = T(10092, "Mission Profile"),
icon = "UI/Icons/console_goals.tga",
enabled_fn = function () return not g_Tutorial end,
action = function() HUD.idGoalsOnPress() end,
description = "",
},
{ --command center
name = "idColonyControlCenter",
display_name = T(137542936955, "Command Center"),
icon = "UI/Icons/console_command_center.tga",
action = function() HUD.idColonyControlCenterOnPress() end,
description = "",
close_parent = false,
},
{ --markers
name = "idMilestones",
display_name = T(973748367669, "Milestones"),
icon = "UI/Icons/console_milestones.tga",
action = function() HUD.idMilestonesOnPress() end,
description = "",
},
{ --radio
name = "idRadio",
display_name = T(796804896133, "Radio"),
icon = "UI/Icons/console_radio.tga",
action = function() HUD.idRadioOnPress() end,
description = "",
},
{ --encyclopedia
name = "encyclopedia",
display_name = T(7384, "Encyclopedia"),
icon = "UI/Icons/console_encyclopedia.tga",
action = function(this)
PlayFX("EncyclopediaButtonClick", "start")
OpenEncyclopedia()
end,
description = "",
},
}
function GamepadIGMenu:Init()
SelectObj(false)
CloseInfopanelItems()
self.idContainer:SetScaleModifier(point(750,750))
end
function GamepadIGMenu:Open(...)
self:RecalculateMargins()
ItemMenu.Open(self, ...)
end
function GamepadIGMenu:GetCategories()
return empty_table
end
function GamepadIGMenu:GetItems(category_id)
local buttons = {}
for i=1, #GamepadIGMenu_game_items do
local item = GamepadIGMenu_game_items[i]
item.ButtonAlign = i%2==1 and "top" or "bottom"
local enabled_fn = rawget(item, "enabled_fn")
if enabled_fn then
item.enabled = enabled_fn()
end
local btn = HexButtonItem:new(item, self.idButtonsList)
if enabled_fn then
btn:SetEnabled(item.enabled)
end
buttons[#buttons + 1] = btn
end
return buttons
end
function GamepadIGMenu:OnXButtonUp(button, controller_id)
if button == "LeftTrigger" or button == "Start" then
CloseXGamepadMainMenu()
return "break"
end
return ItemMenu.OnXButtonUp(self, button, controller_id)
end
function GamepadIGMenu:RecalculateMargins()
local hud, hud_margins = GetHUD()
if hud then
local gamepad = GetUIStyleGamepad() and not UseHybridControls()
local ui_scale = GetUIScale()
local hud_height = Max(hud.idBottom.measure_height, hud.idBottom.MinHeight)
hud_height = MulDivRound(hud_height, 100, ui_scale)
local bottom_margin = gamepad and 0 or hud_height
hud_margins = box(0, 0, 0, bottom_margin)
end
self:SetMargins(GamepadIGMenu.Margins + hud_margins + GetSafeMargins())
end
function OnMsg.SafeAreaMarginsChanged()
local dlg = GetDialog("GamepadIGMenu")
if dlg then
dlg:RecalculateMargins()
end
end
function GamepadIGMenu:Close(...)
ItemMenu.Close(self,...)
end
function OpenXGamepadMainMenu()
--don't open this over the pregame menu
if not GameState.gameplay then return end
--Don't open this one while the build menu is opened
if GetDialog("XBuildMenu") then
return
end
--The hud needs to be visible
local hud = GetDialog("HUD")
if not hud or not hud:GetVisible() then
return
end
return GetDialog("GamepadIGMenu") or
OpenDialog("GamepadIGMenu", GetInGameInterface(), empty_table)
end
function CloseXGamepadMainMenu()
CloseDialog("GamepadIGMenu")
end
function OnMsg.SelectionChange()
if SelectedObj then
CloseXGamepadMainMenu()
end
end
|
-- https://github.com/moody/DethsDBLib
local _, Addon = ...
local metadata = {
name = "DethsDBLib",
version = "2.0.2",
description = "Addon library for managing Saved Variables.",
author = "Dethanyel"
}
local name = ("%s_%s"):format(metadata.name, metadata.version)
local lib = _G[name]
if lib then
lib.__loaded = true
else
lib = {
metadata = metadata,
consts = {},
mixins = {},
utils = {}
}
_G[name] = lib
end
Addon[metadata.name] = lib
|
Citizen.CreateThread(function()
while true do
SetDiscordAppId(628965646415298561)
SetDiscordRichPresenceAsset('redside')
--SetDiscordRichPresenceAssetText("")
SetDiscordRichPresenceAssetSmall('discord')
SetDiscordRichPresenceAssetSmallText('discord.gg/redside')
SetRichPresence(GetPlayerName(PlayerId()) .. " [" .. GetPlayerServerId(PlayerId()) .. "] - " .. #(GetActivePlayers()) .. "/128")
Citizen.Wait(60000)
end
end) |
function Auctionator.AH.Initialize()
if Auctionator.AH.Internals ~= nil then
return
end
Auctionator.AH.Internals = {}
Auctionator.AH.Internals.throttling = CreateFrame(
"FRAME",
"AuctionatorAHThrottlingFrame",
AuctionHouseFrame,
"AuctionatorAHThrottlingFrameTemplate"
)
Auctionator.AH.Internals.itemKeyLoader = CreateFrame(
"FRAME",
"AuctionatorAHItemKeyLoaderFrame",
AuctionHouseFrame,
"AuctionatorAHItemKeyLoaderFrameTemplate"
)
Auctionator.AH.Queue:Init()
end
|
local box = CompactUnitFrameProfilesGeneralOptionsFrameKeepGroupsTogether
local mode = CompactRaidFrameContainer_SetGroupMode
local function checkBox()
-- in separate party groups, doesn't allow raid frames to glom together or sort
box:SetChecked(true)
mode(CompactRaidFrameContainer, "discrete")
end
local function uncheckBox()
-- not in separate party groups, allows raid frames to glom together and sort
box:SetChecked(false)
mode(CompactRaidFrameContainer, "flush")
end
local function toggleBox()
-- same as clicking the checkbox in the foreground UI, toggles to opposing state
box:Click()
end
local function slashHandler(msg)
local cmd, opt = strsplit(" ", msg)
if cmd == "fix" then -- toggle twice to fix tainted raid frames
toggleBox()
toggleBox()
if opt == "verbose" then print("ftrf: toggled raid frames twice to fix tainted frames") end
elseif cmd == "toggle" then -- toggle once to opposing state of groupmode
toggleBox()
local checked = box:GetChecked()
if opt == "verbose" then
if checked then
print("ftrf: toggled, now showing party groups")
else
print("ftrf: toggled, now without party groups")
end
end
elseif cmd == "check" then -- force to checked state regardless of starting state
checkBox()
if opt == "verbose" then print("ftrf: showing raid frames in party groups") end
elseif cmd == "uncheck" then -- force to unchecked state regardless of starting state
uncheckBox()
if opt == "verbose" then print("ftrf: showing raid frames without party groups") end
else -- just show usage text
print("FixTaintedRaidFrames usage")
print("Works on Interface>Raid Profiles>Keep Groups Together")
print("------------------------------------------------------")
print("/ftrf fix - toggles K.G.T. twice to fix tainted frames")
print("/ftrf toggle - toggles K.G.T. once to opposing state")
print("/ftrf check - K.G.T. checked")
print("/ftrf uncheck - K.G.T. unchecked")
print("------------------------------------------------------")
print("Include second argument \"verbose\" to get confirmation")
print("/ftrf fix verbose - example with confirmation message")
end
end
SLASH_FTRF1 = "/FixTaintedRaidFrames"
SLASH_FTRF2 = "/ftrf"
SlashCmdList["FTRF"] = slashHandler
|
-- co
co = coroutine.create(function (a)
local r = coroutine.yield(a+1) -- yield()返回a+1给调用它的resume()函数,即2
print("r=" ..r) -- r的值是第2次resume()传进来的,100
end)
status, r = coroutine.resume(co, 1) -- resume()返回两个值,一个是自身的状态true,一个是yield的返回值2
print(status, r)
coroutine.resume(co, 100)
-- co2
co2 = coroutine.create(function (a, b)
local s = coroutine.yield(a+b)
print("now value = " .. s)
end)
status, r = coroutine.resume(co2, 3, 2)
print(status, r)
coroutine.resume(co2, 200)
-- co3
co3 = coroutine.create(function (a, b)
local s = coroutine.yield(a+b)
print("now value = " .. s)
end)
status, r = coroutine.resume(co3, 3, 2)
print(status, r)
coroutine.resume(co3, 500, 300)
|
-- The following code tests the mathematical metamethods that are supplied
-- in Lua.
header = 'Metamethods test: '
-- Test vector metamethods
v1 = math.v4(1.0, 1.0, 1.0, 1.0)
v2 = math.v4(0.0, 1.0, 2.0, 4.0)
a = 10
b = 100
print('Contents of v1.')
print('Using ipairs.')
for i,v in ipairs(v1) do print(i .. ': ' .. v) end
print('Using # length unary operator. Valid because we use integer indices.')
for i=1,#v1 do
print(i .. ': ' .. v1[i])
end
print('Pretty printed vector:')
helpStr(v1)
print('Metatable:')
for i,v in ipairs(getmetatable(v1)) do print(i .. ': ' .. v) end
print('Contents of v2: ' .. helpStr(v2))
-----------------------------------------
-- Test scalar * vector multiplication --
-----------------------------------------
v = a * v1
if v[1] ~= 10.0 or v[2] ~= 10.0 or v[3] ~= 10.0 or v[4] ~= 10.0 then
error(header .. 'Failed scalar/vector multiplication.')
end
print('Passed scalar multiplication: ' .. helpStr(v))
v = v1 * a
if v[1] ~= 10.0 or v[2] ~= 10.0 or v[3] ~= 10.0 or v[4] ~= 10.0 then
error(header .. 'Failed scalar/vector multiplication.')
end
print('Passed scalar multiplication: ' .. helpStr(v))
v = b * v2
if v[1] ~= 0.0 or v[2] ~= 100.0 or v[3] ~= 200.0 or v[4] ~= 400.0 then
error(header .. 'Failed scalar/vector multiplication.')
end
print('Passed scalar multiplication: ' .. helpStr(v))
v = v2 * b
if v[1] ~= 0.0 or v[2] ~= 100.0 or v[3] ~= 200.0 or v[4] ~= 400.0 then
error(header .. 'Failed scalar/vector multiplication.')
end
print('Passed scalar multiplication: ' .. helpStr(v))
-----------------------------
-- Test vector dot product --
-----------------------------
r = v1 * v2
if r < 6.999 or r > 7.001 then
error(header .. 'Failed vector dot product.')
end
print('Passed dot product: ' .. r)
r = v2 * v1
if r < 6.999 or r > 7.001 then
error(header .. 'Failed vector dot product.')
end
print('Passed dot product: ' .. r)
--------------------------
-- Test vector addition --
--------------------------
v = v1 + v2
if v[1] ~= 1.0 or v[2] ~= 2.0 or v[3] ~= 3.0 or v[4] ~= 5.0 then
error(header .. 'Failed vector addition.')
end
print('Passed vector addition: ' .. helpStr(v))
v = v2 + v1
if v[1] ~= 1.0 or v[2] ~= 2.0 or v[3] ~= 3.0 or v[4] ~= 5.0 then
error(header .. 'Failed vector addition.')
end
print('Passed vector addition: ' .. helpStr(v))
-----------------------------
-- Test vector subtraction --
-----------------------------
vr = v1 - v2
if vr[1] ~= 1.0 or vr[2] ~= 0.0 or vr[3] ~= -1.0 or vr[4] ~= -3.0 then
error(header .. 'Failed vector subtraction.')
end
print('Passed vector subtraction: ' .. helpStr(vr))
vr = v2 - v1
if vr[1] ~= -1.0 or vr[2] ~= 0.0 or vr[3] ~= 1.0 or vr[4] ~= 3.0 then
error(header .. 'Failed vector subtraction.')
end
print('Passed vector subtraction: ' .. helpStr(vr))
--v1 = math.v4(1.0, 1.0, 1.0, 1.0)
--v2 = math.v4(0.0, 1.0, 2.0, 4.0)
-------------------------
-- Test unary negation --
-------------------------
vr = -v1
if vr[1] ~= -1.0 or vr[2] ~= -1.0 or vr[3] ~= -1.0 or vr[4] ~= -1.0 then
error(header .. 'Failed unary negation.')
end
print('Passed unary negation: ' .. helpStr(vr))
vr = -v2
if vr[1] ~= 0.0 or vr[2] ~= -1.0 or vr[3] ~= -2.0 or vr[4] ~= -4.0 then
error(header .. 'Failed unary negation.')
end
print('Passed unary negation: ' .. helpStr(vr))
-- Test matrix metamethods
print ('Beginning matrix tests')
m1 = math.m4x4() -- Constructs an identity matrix by default.
vt = math.v4(1.0, 2.0, 3.0, 4.0)
print('Contents of m1: ' .. helpStr(m1))
-----------------------------------------
-- Test Matrix * scalar multiplication --
-----------------------------------------
r = m1 * a
if r[1][1] ~= 10.0 or r[2][2] ~= 10.0 or r[3][3] ~= 10.0 or r[4][4] ~= 10.0 then
error(header .. 'Failed matrix scalar multiplication.')
end
-- Perform dot products against rows to verify...
if r[1] * vt ~= 10.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 1.')
end
if r[2] * vt ~= 20.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 2.')
end
if r[3] * vt ~= 30.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 3.')
end
if r[4] * vt ~= 40.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 4.')
end
print('Passed scalar right multiplication')
print('Contents of r: ' .. helpStr(r))
r = a * m1
-- Perform dot products against rows to verify...
if r[1] * vt ~= 10.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 1.')
end
if r[2] * vt ~= 20.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 2.')
end
if r[3] * vt ~= 30.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 3.')
end
if r[4] * vt ~= 40.0 then
error(header .. 'Failed matrix scalar multiplication; dot product 4.')
end
print('Passed scalar left multiplication')
print('Contents of r: ' .. helpStr(r))
-----------------------------------------
-- Test Matrix * vector multiplication --
-----------------------------------------
r = 2 * m1
r = r * math.v4(1.0, 2.0, 3.0, 4.0)
if r[1] ~= 2.0 or r[2] ~= 4.0 or r[3] ~= 6.0 or r[4] ~= 8.0 then
error(header .. 'Failed matrix * vector multiplication')
end
print('Passed matrix * vector multiplication.')
-----------------------------------------
-- Test matrix * matrix multiplication --
-----------------------------------------
m1 = math.m4x4();
m1[1] = math.v4(1.0, 2.0, 3.0, 4.0)
m1[2] = math.v4(4.0, 3.0, 2.0, 1.0)
m1[3] = math.v4(0.0, 1.0, -1.0, 0.0)
m1[4] = math.v4(-20.0, 0.0, 3.0, 4.0)
print('m1: ' .. helpStr(m1))
m2 = math.m4x4();
m2[1] = math.v4(1.0, 1.0, 1.0, 1.0)
m2[2] = math.v4(-1.0, -1.0, 1.0, 1.0)
m2[3] = math.v4(1.0, -1.0, 1.0, -1.0)
m2[4] = math.v4(1.0, 1.0, -1.0, -1.0)
print('m2: ' .. helpStr(m2))
r = m1 * m2
if r[1][1] ~= m1[1][1]*m2[1][1]+m1[1][2]*m2[2][1]+m1[1][3]*m2[3][1]+m1[1][4]*m2[4][1] or
r[1][2] ~= m1[1][1]*m2[1][2]+m1[1][2]*m2[2][2]+m1[1][3]*m2[3][2]+m1[1][4]*m2[4][2] or
r[1][3] ~= m1[1][1]*m2[1][3]+m1[1][2]*m2[2][3]+m1[1][3]*m2[3][3]+m1[1][4]*m2[4][3] or
r[1][4] ~= m1[1][1]*m2[1][4]+m1[1][2]*m2[2][4]+m1[1][3]*m2[3][4]+m1[1][4]*m2[4][4] or
r[2][1] ~= m1[2][1]*m2[1][1]+m1[2][2]*m2[2][1]+m1[2][3]*m2[3][1]+m1[2][4]*m2[4][1] or
r[2][2] ~= m1[2][1]*m2[1][2]+m1[2][2]*m2[2][2]+m1[2][3]*m2[3][2]+m1[2][4]*m2[4][2] or
r[2][3] ~= m1[2][1]*m2[1][3]+m1[2][2]*m2[2][3]+m1[2][3]*m2[3][3]+m1[2][4]*m2[4][3] or
r[2][4] ~= m1[2][1]*m2[1][4]+m1[2][2]*m2[2][4]+m1[2][3]*m2[3][4]+m1[2][4]*m2[4][4] or
r[3][1] ~= m1[3][1]*m2[1][1]+m1[3][2]*m2[2][1]+m1[3][3]*m2[3][1]+m1[3][4]*m2[4][1] or
r[3][2] ~= m1[3][1]*m2[1][2]+m1[3][2]*m2[2][2]+m1[3][3]*m2[3][2]+m1[3][4]*m2[4][2] or
r[3][3] ~= m1[3][1]*m2[1][3]+m1[3][2]*m2[2][3]+m1[3][3]*m2[3][3]+m1[3][4]*m2[4][3] or
r[3][4] ~= m1[3][1]*m2[1][4]+m1[3][2]*m2[2][4]+m1[3][3]*m2[3][4]+m1[3][4]*m2[4][4] or
r[4][1] ~= m1[4][1]*m2[1][1]+m1[4][2]*m2[2][1]+m1[4][3]*m2[3][1]+m1[4][4]*m2[4][1] or
r[4][2] ~= m1[4][1]*m2[1][2]+m1[4][2]*m2[2][2]+m1[4][3]*m2[3][2]+m1[4][4]*m2[4][2] or
r[4][3] ~= m1[4][1]*m2[1][3]+m1[4][2]*m2[2][3]+m1[4][3]*m2[3][3]+m1[4][4]*m2[4][3] or
r[4][4] ~= m1[4][1]*m2[1][4]+m1[4][2]*m2[2][4]+m1[4][3]*m2[3][4]+m1[4][4]*m2[4][4] then
error(header .. 'Failed matrix * matrix multiplication')
end
print('Passed matrix * matrix multiplication.')
print('Result of multiplication: ' .. helpStr(r))
|
if not metrolib then metrolib = {} end
if not metrolib.constants then metrolib.constants = {} end
metrolib.constans.tick_time = 120
|
-- to work around slow init times due to packagesrv.com being down
premake.downloadModule = function()
return false
end
_G._ROOTPATH = path.getabsolute('.')
xpcall(function()
newoption {
trigger = "with-asan",
value = "libpath",
description = "Use asan for Windows."
}
newoption {
trigger = "builddir",
value = "path",
description = "Output directory for build/ files."
}
newoption {
trigger = "bindir",
value = "path",
description = "Root directory for bin/ files."
}
dofile('tools/build/init.lua')
-- perform component processing
if _OPTIONS['game'] == 'dummy' then
return
end
root_cwd = os.getcwd()
-- initialize components
dofile('components/config.lua')
load_privates('privates_config.lua')
dofile('vendor/config.lua')
component
{
name = 'platform:' .. os.target(),
rawName = os.target(),
vendor = { dummy = true }
}
workspace "CitizenMP"
configurations { "Debug", "Release" }
symbols "Full"
characterset "Unicode"
flags { "No64BitChecks" }
flags { "NoIncrementalLink", "NoMinimalRebuild" } -- this breaks our custom section ordering in citilaunch, and is kind of annoying otherwise
editandcontinue 'Off'
includedirs {
"shared/",
"client/shared/",
"../vendor/jitasm/",
"../vendor/rapidjson/include/",
"../vendor/fmtlib/include/",
"deplibs/include/",
os.getenv("BOOST_ROOT")
}
defines { "GTEST_HAS_PTHREAD=0", "BOOST_ALL_NO_LIB" }
defines { "_HAS_AUTO_PTR_ETC" } -- until boost gets fixed
libdirs { "deplibs/lib/" }
location ((_OPTIONS['builddir'] or "build/") .. _OPTIONS['game'])
cppdialect "C++17"
if os.istarget('windows') then
if _OPTIONS['game'] ~= 'server' then
buildoptions { '/await', '/d2FH4-' }
end
systemversion '10.0.18362.0'
else
vectorextensions 'SSSE3'
end
-- special build dirs for FXServer
if _OPTIONS['game'] == 'server' then
location ((_OPTIONS['builddir'] or "build/") .. "server/" .. os.target())
architecture 'x64'
defines 'IS_FXSERVER'
startproject 'DuplicityMain'
else
startproject 'CitiLaunch'
end
local binroot = ((_OPTIONS['bindir'] or "bin/") .. _OPTIONS['game']) .. '/'
if _OPTIONS['game'] == 'server' then
binroot = (_OPTIONS['bindir'] or "bin/") .. 'server/' .. os.target() .. '/'
end
if _OPTIONS['with-asan'] then
toolset 'msc-llvm'
libdirs { _OPTIONS['with-asan'] }
links { 'clang_rt.asan_dynamic-x86_64', 'clang_rt.asan_dynamic_runtime_thunk-x86_64' }
filter 'language:C or language:C++'
buildoptions '-mpclmul -maes -mssse3 -mavx2 -mrtm'
buildoptions '-fsanitize=address -fsanitize-recover=address'
end
filter { 'action:vs*' }
implibdir "$(IntDir)/lib/"
symbolspath "$(TargetDir)dbg/$(TargetName).pdb"
filter {}
-- debug output
configuration "Debug*"
targetdir (binroot .. "/debug")
defines "NDEBUG"
-- this slows down the application a lot
defines { '_ITERATOR_DEBUG_LEVEL=0' }
-- allow one level of inlining
if os.istarget('windows') then
buildoptions { '/Ob1', '/JMC-' }
end
-- release output
configuration "Release*"
targetdir (binroot .. "/release")
defines "NDEBUG"
optimize "Speed"
if _OPTIONS["game"] == "ny" then
filter { "configurations:Release*", "kind:SharedLib or kind:ConsoleApp or kind:WindowedApp" }
linkoptions "/SAFESEH:NO"
configuration "game=ny"
defines "GTA_NY"
architecture 'x86'
elseif _OPTIONS["game"] == "five" then
configuration "game=five"
defines "GTA_FIVE"
filter 'language:C or language:C++'
architecture 'x64'
elseif _OPTIONS["game"] == "rdr3" then
configuration "game=rdr3"
defines "IS_RDR3"
filter 'language:C or language:C++'
architecture 'x64'
elseif _OPTIONS["game"] == "launcher" then
configuration "game=launcher"
defines "IS_LAUNCHER"
filter 'language:C or language:C++'
architecture 'x64'
end
configuration "windows"
links { "winmm" }
filter { 'system:not windows', 'language:C or language:C++' }
architecture 'x64'
links { 'stdc++' }
buildoptions {
"-fPIC", -- required to link on AMD64
}
-- TARGET: launcher
if _OPTIONS['game'] ~= 'server' then
-- game launcher
include 'client/launcher'
include 'client/console'
include 'client/diag'
else
include 'server/launcher'
end
if os.istarget('windows') then
include 'premake5_layout.lua'
end
-- TARGET: corert
include 'client/citicore'
if _OPTIONS['game'] ~= 'server' then
include 'client/ipfsdl'
project "CitiGame"
targetname "CitizenGame"
language "C++"
kind "SharedLib"
includedirs { 'client/citicore/' }
files
{
"client/common/Error.cpp",
"client/citigame/Launcher.cpp",
"client/common/StdInc.cpp"
}
links { "Shared", "citicore" }
defines "COMPILING_GAME"
pchsource "client/common/StdInc.cpp"
pchheader "StdInc.h"
end
require 'vstudio'
premake.override(premake.vstudio.dotnetbase, 'debugProps', function(base, cfg)
if cfg.symbols == premake.ON then
_p(2,'<DebugSymbols>true</DebugSymbols>')
end
_p(2,'<DebugType>portable</DebugType>')
_p(2,'<Optimize>%s</Optimize>', iif(premake.config.isOptimizedBuild(cfg), "true", "false"))
end)
premake.override(premake.vstudio.vc2010, 'ignoreImportLibrary', function(base, cfg)
if cfg.flags.NoImportLib then
premake.vstudio.vc2010.element("IgnoreImportLibrary", nil, "true")
end
end)
premake.override(premake.vstudio.vc2010, 'buildCommands', function(base, cfg, cond)
base(cfg, cond)
premake.vstudio.vc2010.element("BuildInParallel", cond, "true")
end)
premake.override(premake.vstudio.vc2010, 'importLanguageTargets', function(base, prj)
base(prj)
local hasPostBuild = false
for cfg in premake.project.eachconfig(prj) do
if cfg.postbuildcommands and #cfg.postbuildcommands > 0 then
hasPostBuild = true
break
end
end
if hasPostBuild then
_p(1, '<Target Name="DisablePostBuildEvent" AfterTargets="Link" BeforeTargets="PostBuildEvent">')
_p(2, '<PropertyGroup>')
_p(3, '<PostBuildEventUseInBuild Condition="\'$(LinkSkippedExecution)\' == \'True\'">false</PostBuildEventUseInBuild>')
_p(2, '</PropertyGroup>')
_p(1, '</Target>')
end
local hasPreLink = false
for cfg in premake.project.eachconfig(prj) do
if cfg.prelinkcommands and #cfg.prelinkcommands > 0 then
hasPreLink = true
break
end
end
if hasPreLink then
_p(1, '<PropertyGroup>')
_p(2, '<PreLinkEventUseInBuild>false</PreLinkEventUseInBuild>')
_p(1, '</PropertyGroup>')
-- DoLinkOutputFilesMatch is right before PreLinkEvent; so it won't evaluate the condition yet
_p(1, '<Target Name="EnablePreLinkEvent" Inputs="@(Link)" Outputs="$(ProjectDir)/$(ProjectName).res" BeforeTargets="DoLinkOutputFilesMatch">')
-- use CreateProperty task to set property based on skipped state
_p(2, '<CreateProperty Value="true">')
_p(3, '<Output TaskParameter="ValueSetByTask" PropertyName="PreLinkEventUseInBuild" />')
_p(2, '</CreateProperty>')
_p(1, '</Target>')
end
end)
local function WriteDocumentationFileXml(_premake, _cfg)
if _cfg.project.name == 'CitiMonoSystemDrawingStub' then
_premake.w(('<AssemblyOriginatorKeyFile>%s</AssemblyOriginatorKeyFile>'):format(
path.getabsolute("client/clrref/msft.snk")
))
_premake.w('<SignAssembly>true</SignAssembly>')
_premake.w('<DelaySign>true</DelaySign>')
return
end
if _cfg.project.name ~= 'CitiMono' then
return
end
_premake.w('<DocumentationFile>' .. string.gsub(_cfg.buildtarget.relpath, ".dll", ".xml") .. '</DocumentationFile>')
end
premake.override(premake.vstudio.dotnetbase, "compilerProps", function(base, cfg)
base(cfg)
WriteDocumentationFileXml(premake, cfg)
premake.w('<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>')
end)
premake.override(premake.vstudio.cs2005, "targets", function(base, prj)
base(prj)
if prj.name == 'CitiMono' then
_p(1, '<PropertyGroup>')
_p(2, '<GenAPITargetDir>%s</GenAPITargetDir>', path.getabsolute("client/clrref/" .. _OPTIONS['game']))
_p(2, '<GenAPITargetPath>$(GenAPITargetDir)\\$(TargetName).cs</GenAPITargetPath>')
_p(2, '<GenAPIAdditionalParameters>%s</GenAPIAdditionalParameters>', ('--exclude-api-list "%s" --exclude-attributes-list "%s"'):format(
path.getabsolute("client/clrref/exclude_list.txt"),
path.getabsolute("client/clrref/exclude_attributes_list.txt")
))
_p(2, '<GenerateReferenceAssemblySource>true</GenerateReferenceAssemblySource>')
_p(1, '</PropertyGroup>')
_p(1, '<Import Project="$(ProjectDir)\\packages\\Microsoft.DotNet.GenAPI.6.0.0-beta.21063.5\\build\\Microsoft.DotNet.GenAPI.targets" />')
_p(1, '<Target Name="CreateReferenceAssemblyDirectory" BeforeTargets="GenerateReferenceAssemblySource">')
_p(2, '<MakeDir Directories="$(GenAPITargetDir)" />')
_p(1, '</Target>')
end
if prj.name == 'CitiMonoRef' then
_p(1, '<Import Project="%s" />', path.getabsolute("client/clrref/GenFacades.targets"))
end
end)
premake.override(premake.vstudio.nuget2010, "supportsPackageReferences", function(base, prj)
-- <PackageReference /> doesn't work for GenAPI (even if fixing `nuget.config` issue for source)
return false
end)
premake.override(premake.vstudio.dotnetbase, "nuGetReferences", function(base, prj)
-- and this'll fail as GenAPI doesn't have any lib/.../*.dll file
if prj.name == 'CitiMono' then
return
end
return base(prj)
end)
if _OPTIONS['game'] ~= 'launcher' then
project "CitiMono"
targetname "CitizenFX.Core"
language "C#"
kind "SharedLib"
-- Missing XML comment for publicly visible type or member
disablewarnings 'CS1591'
dotnetframework '4.6'
clr 'Unsafe'
csversion '7.3'
files { "client/clrcore/*.cs", "client/clrcore/Math/*.cs" }
files { "../vendor/ben-demystifier/src/Ben.Demystifier/**.cs" }
if _OPTIONS['game'] == 'five' then
files { "client/clrcore/NativesFive.cs" }
elseif _OPTIONS['game'] == 'rdr3' then
files { "client/clrcore/NativesRDR3.cs" }
elseif _OPTIONS['game'] == 'server' then
files { "client/clrcore/NativesServer.cs" }
elseif _OPTIONS['game'] == 'ny' then
files { "client/clrcore/NativesNY.cs" }
end
if _OPTIONS['game'] ~= 'server' then
defines { 'USE_HYPERDRIVE' }
if _OPTIONS['game'] == 'five' then
files { "client/clrcore/External/*.cs" }
end
else
files { "client/clrcore/Server/*.cs" }
end
if os.istarget('windows') then
nuget {
"Microsoft.DotNet.GenAPI:6.0.0-beta.21063.5",
"Microsoft.DotNet.GenFacades:6.0.0-beta.21063.5",
}
nugetsource "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json"
end
links {
"System.dll",
"Microsoft.CSharp.dll",
"System.Core.dll",
"../data/client/citizen/clr2/lib/mono/4.5/System.Reflection.Metadata.dll",
"../data/client/citizen/clr2/lib/mono/4.5/System.Collections.Immutable.dll",
"../data/client/citizen/clr2/lib/mono/4.5/MsgPack.dll"
}
if os.istarget('linux') then
links {
"/usr/lib/mono/4.5/Facades/System.Runtime.dll",
"/usr/lib/mono/4.5/Facades/System.IO.dll"
}
end
buildoptions '/debug:portable /langversion:7.3'
configuration "Debug*"
targetdir (binroot .. '/debug/citizen/clr2/lib/mono/4.5/')
configuration "Release*"
targetdir (binroot .. '/release/citizen/clr2/lib/mono/4.5/')
if _OPTIONS['game'] ~= 'server' then
project "CitiMonoSystemDrawingStub"
targetname "System.Drawing"
language "C#"
kind "SharedLib"
links { "CitiMono" }
files {
"client/clrref/System.Drawing.cs"
}
configuration "Debug*"
targetdir (binroot .. '/debug/citizen/clr2/lib/mono/4.5/')
configuration "Release*"
targetdir (binroot .. '/release/citizen/clr2/lib/mono/4.5/')
end
if os.istarget('windows') then
project "CitiMonoRef"
if _OPTIONS['game'] == 'server' then
targetname "CitizenFX.Core.Server"
else
targetname "CitizenFX.Core.Client"
end
language "C#"
kind "SharedLib"
dependson "CitiMono"
dotnetframework '4.6'
clr 'Unsafe'
csversion '7.3'
links { "System.dll", "System.Drawing.dll" }
files { "client/clrref/" .. _OPTIONS['game'] .. "/CitizenFX.Core.cs" }
buildoptions '/debug:portable /langversion:7.3'
configuration "Debug*"
targetdir (binroot .. '/debug/citizen/clr2/lib/mono/4.5/ref/')
configuration "Release*"
targetdir (binroot .. '/release/citizen/clr2/lib/mono/4.5/ref/')
end
end
group ""
-- TARGET: shared component
include "client/shared"
group "vendor"
if _OPTIONS['game'] ~= 'server' then
include "tools/dbg"
project "libcef_dll"
targetname "libcef_dll_wrapper"
language "C++"
kind "StaticLib"
defines { "USING_CEF_SHARED", "NOMINMAX", "WIN32", "WRAPPING_CEF_SHARED" }
flags { "NoIncrementalLink", "NoMinimalRebuild" }
local cefRoot = "../vendor/cef/"
if _OPTIONS['game'] == 'ny' then
cefRoot = "../vendor/cef32/"
end
includedirs { ".", cefRoot }
buildoptions "/MP"
files_project(cefRoot)
{
"libcef_dll/**.cc",
"libcef_dll/**.cpp",
"libcef_dll/**.h"
}
end
-- run components
group "components"
do_components()
-- vendor is last so it can trigger even if it were merely tagged
group "vendor"
do_vendor()
end, function(e)
print(e)
print(debug.traceback())
os.exit(1)
end)
|
if not modules then modules = { } end modules ['util-sql-imp-ffi'] = {
version = 1.001,
comment = "companion to util-sql.lua",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- I looked at luajit-mysql to see how the ffi mapping was done but it didn't work
-- out that well (at least not on windows) but I got the picture. As I have somewhat
-- different demands I simplified / redid the ffi bti and just took the swiglib
-- variant and adapted that.
local tonumber = tonumber
local concat = table.concat
local format, byte = string.format, string.byte
local lpegmatch = lpeg.match
local setmetatable, type = setmetatable, type
local sleep = os.sleep
local trace_sql = false trackers.register("sql.trace", function(v) trace_sql = v end)
local trace_queries = false trackers.register("sql.queries",function(v) trace_queries = v end)
local report_state = logs.reporter("sql","ffi")
if not utilities.sql then
require("util-sql")
end
ffi.cdef [[
/*
This is as lean and mean as possible. After all we just need a connection and
a query. The rest is handled already in the Lua code elsewhere.
*/
typedef void MYSQL_instance;
typedef void MYSQL_result;
typedef char **MYSQL_row;
typedef unsigned int MYSQL_offset;
typedef struct st_mysql_field {
char *name;
char *org_name;
char *table;
char *org_table;
char *db;
char *catalog;
char *def;
unsigned long length;
unsigned long max_length;
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags;
unsigned int decimals;
unsigned int charsetnr;
int type;
void *extension;
} MYSQL_field;
void free(void*ptr);
void * malloc(size_t size);
MYSQL_instance * mysql_init (
MYSQL_instance *mysql
);
MYSQL_instance * mysql_real_connect (
MYSQL_instance *mysql,
const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag
);
unsigned int mysql_errno (
MYSQL_instance *mysql
);
const char *mysql_error (
MYSQL_instance *mysql
);
/* int mysql_query (
MYSQL_instance *mysql,
const char *q
); */
int mysql_real_query (
MYSQL_instance *mysql,
const char *q,
unsigned long length
);
MYSQL_result * mysql_store_result (
MYSQL_instance *mysql
);
void mysql_free_result (
MYSQL_result *result
);
unsigned long long mysql_num_rows (
MYSQL_result *res
);
MYSQL_row mysql_fetch_row (
MYSQL_result *result
);
unsigned int mysql_num_fields (
MYSQL_result *res
);
/* MYSQL_field *mysql_fetch_field (
MYSQL_result *result
); */
MYSQL_field * mysql_fetch_fields (
MYSQL_result *res
);
MYSQL_offset mysql_field_seek(
MYSQL_result *result,
MYSQL_offset offset
);
void mysql_close(
MYSQL_instance *sock
);
/* unsigned long * mysql_fetch_lengths(
MYSQL_result *result
); */
]]
local sql = utilities.sql
----- mysql = ffi.load(os.name == "windows" and "libmysql" or "libmysqlclient")
----- mysql = ffilib(os.name == "windows" and "libmysql" or "libmysqlclient")
local mysql = ffilib(os.name == "windows" and "libmysql" or "libmysql")
if not mysql then
report_state("unable to load library")
end
local nofretries = 5
local retrydelay = 1
local cache = { }
local helpers = sql.helpers
local methods = sql.methods
local validspecification = helpers.validspecification
local querysplitter = helpers.querysplitter
local dataprepared = helpers.preparetemplate
local serialize = sql.serialize
local deserialize = sql.deserialize
local mysql_initialize = mysql.mysql_init
local mysql_open_connection = mysql.mysql_real_connect
local mysql_execute_query = mysql.mysql_real_query
local mysql_close_connection = mysql.mysql_close
local mysql_field_seek = mysql.mysql_field_seek
local mysql_num_fields = mysql.mysql_num_fields
local mysql_fetch_fields = mysql.mysql_fetch_fields
----- mysql_fetch_field = mysql.mysql_fetch_field
local mysql_num_rows = mysql.mysql_num_rows
local mysql_fetch_row = mysql.mysql_fetch_row
----- mysql_fetch_lengths = mysql.mysql_fetch_lengths
local mysql_init = mysql.mysql_init
local mysql_store_result = mysql.mysql_store_result
local mysql_free_result = mysql.mysql_free_result
local mysql_error_message = mysql.mysql_error
local NULL = ffi.cast("MYSQL_result *",0)
local ffi_tostring = ffi.string
local ffi_gc = ffi.gc
----- mysqldata = ffi.cast("MYSQL_instance*",mysql.malloc(1024*1024))
local instance = mysql.mysql_init(nil) -- (mysqldata)
local mysql_constant_false = false
local mysql_constant_true = true
local function finish(t)
local r = t._result_
if r then
ffi_gc(r,mysql_free_result)
end
end
local function getcolnames(t)
return t.names
end
local function getcoltypes(t)
return t.types
end
local function numrows(t)
return tonumber(t.nofrows)
end
local function list(t)
local result = t._result_
if result then
local row = mysql_fetch_row(result)
-- local len = mysql_fetch_lengths(result)
local result = { }
for i=1,t.noffields do
result[i] = ffi_tostring(row[i-1])
end
return result
end
end
local function hash(t)
local result = t._result_
local fields = t.names
if result then
local row = mysql_fetch_row(result)
-- local len = mysql_fetch_lengths(result)
local result = { }
for i=1,t.noffields do
result[fields[i]] = ffi_tostring(row[i-1])
end
return result
end
end
local function wholelist(t)
return fetch_all_rows(t._result_)
end
local mt = { __index = {
-- regular
finish = finish,
list = list,
hash = hash,
wholelist = wholelist,
-- compatibility
numrows = numrows,
getcolnames = getcolnames,
getcoltypes = getcoltypes,
-- fallback
_result_ = nil,
names = { },
types = { },
noffields = 0,
nofrows = 0,
}
}
local nt = setmetatable({},mt)
-- session
local function close(t)
mysql_close_connection(t._connection_)
end
local function execute(t,query)
if query and query ~= "" then
local connection = t._connection_
local result = mysql_execute_query(connection,query,#query)
if result == 0 then
local result = mysql_store_result(connection)
if result ~= NULL then
mysql_field_seek(result,0)
local nofrows = tonumber(mysql_num_rows(result) or 0)
local noffields = tonumber(mysql_num_fields(result))
local names = { }
local types = { }
local fields = mysql_fetch_fields(result)
for i=1,noffields do
local field = fields[i-1]
names[i] = ffi_tostring(field.name)
types[i] = tonumber(field.type) -- todo
end
local t = {
_result_ = result,
names = names,
types = types,
noffields = noffields,
nofrows = nofrows,
}
return setmetatable(t,mt)
else
return nt
end
end
end
return false
end
local mt = { __index = {
close = close,
execute = execute,
}
}
local function open(t,database,username,password,host,port)
local connection = mysql_open_connection(
t._session_,
host or "localhost",
username or "",
password or "",
database or "",
port or 0,
NULL,
0
)
if connection ~= NULL then
local t = {
_connection_ = connection,
}
return setmetatable(t,mt)
end
end
local function message(t)
return mysql_error_message(t._session_)
end
local function close(t)
-- dummy, as we have a global session
end
local mt = {
__index = {
connect = open,
close = close,
message = message,
}
}
local function initialize()
local session = {
_session_ = mysql_initialize(instance) -- maybe share, single thread anyway
}
return setmetatable(session,mt)
end
-- -- -- --
local function connect(session,specification)
return session:connect(
specification.database or "",
specification.username or "",
specification.password or "",
specification.host or "",
specification.port
)
end
local function error_in_connection(specification,action)
report_state("error in connection: [%s] user %s into %s at %s:%s",
action or "unknown",
specification.username or "no username",
specification.database or "no database",
specification.host or "no host",
specification.port or "no port"
)
end
local function datafetched(specification,query,converter)
if not query or query == "" then
report_state("no valid query")
return { }, { }
end
local id = specification.id
local session, connection
if id then
local c = cache[id]
if c then
session = c.session
connection = c.connection
end
if not connection then
session = initialize()
connection = connect(session,specification)
if not connection then
for i=1,nofretries do
sleep(retrydelay)
report_state("retrying to connect: [%s.%s] %s@%s to %s:%s",
id,i,
specification.database or "no database",
specification.username or "no username",
specification.host or "no host",
specification.port or "no port"
)
connection = connect(session,specification)
if connection then
break
end
end
end
if connection then
cache[id] = { session = session, connection = connection }
end
end
else
session = initialize()
connection = connect(session,specification)
if not connection then
for i=1,nofretries do
sleep(retrydelay)
report_state("retrying to connect: [%s] %s@%s to %s:%s",
i,
specification.database or "no database",
specification.username or "no username",
specification.host or "no host",
specification.port or "no port"
)
connection = connect(session,specification)
if connection then
break
end
end
end
end
if not connection then
report_state("error in connection: %s@%s to %s:%s",
specification.database or "no database",
specification.username or "no username",
specification.host or "no host",
specification.port or "no port"
)
return { }, { }
end
query = lpegmatch(querysplitter,query)
local result, message, okay
for i=1,#query do
local q = query[i]
local r, m = connection:execute(q)
if m then
report_state("error in query, stage: %s",string.collapsespaces(q or "?"))
message = message and format("%s\n%s",message,m) or m
end
if type(r) == "table" then
result = r
okay = true
elseif not m then
okay = true
end
end
local data, keys
if result then
if converter then
data = converter.ffi(result)
else
keys = result.names
data = { }
for i=1,result.nofrows do
data[i] = result:hash()
end
end
result:finish() -- result:close()
elseif message then
report_state("message %s",message)
end
if not keys then
keys = { }
end
if not data then
data = { }
end
if not id then
connection:close()
session:close()
end
return data, keys
end
local function execute(specification)
if trace_sql then
report_state("executing library")
end
if not validspecification(specification) then
report_state("error in specification")
return
end
local query = dataprepared(specification)
if not query then
report_state("error in preparation")
return
end
local data, keys = datafetched(specification,query,specification.converter)
if not data then
report_state("error in fetching")
return
end
local one = data[1]
if one then
setmetatable(data,{ __index = one } )
end
return data, keys
end
local wraptemplate = [[
----- mysql = ffi.load(os.name == "windows" and "libmysql" or "libmysqlclient")
local mysql = ffi.load(os.name == "windows" and "libmysql" or "libmysql")
local mysql_fetch_row = mysql.mysql_fetch_row
local ffi_tostring = ffi.string
local converters = utilities.sql.converters
local deserialize = utilities.sql.deserialize
local tostring = tostring
local tonumber = tonumber
local booleanstring = string.booleanstring
local NULL = ffi.cast("MYSQL_result *",0)
%s
return function(result)
if not result then
return { }
end
local nofrows = result.nofrows or 0
if nofrows == 0 then
return { }
end
local noffields = result.noffields or 0
local _result_ = result._result_
local target = { } -- no %s needed here
for i=1,nofrows do
local cells = { }
local row = mysql_fetch_row(_result_)
for j=1,noffields do
local s = row[j-1]
if s == NULL then
cells[j] = ""
else
cells[j] = ffi_tostring(s)
end
end
target[%s] = {
%s
}
end
result:finish() -- result:close()
return target
end
]]
local celltemplate = "cells[%s]"
methods.ffi = {
runner = function() end, -- never called
execute = execute,
initialize = initialize, -- returns session
usesfiles = false,
wraptemplate = wraptemplate,
celltemplate = celltemplate,
}
|
-----------------------------------
-- Area: Carpenters' Landing
-- NPC: Lourdaude
-- Type: Standard NPC
-- !pos 215.597 -2.689 -526.021 2
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
player:startEvent(26)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
require('.')
hashed_items = {}
items = "#" .. "foo-bar" .. "#"
for i = 1, #items - 2 do
table.insert(hashed_items, items:sub(i, i + 2))
end
print (hashed_items)
local dir = 'data/Translation/train/'
local input_vocab = dmn.HashVocab(dir .. 'input_vocab.txt', true)
local items = input_vocab:index("cats")
print(items)
print("Done") |
local talents = require 'talents'
describe ("talent definition,", function ( )
it ("should not observe any direct effects from passed structure", function ( )
local structure = { x = 0, }
local talent = talents.talent (structure)
assert.truthy (talents.provides (talent, "x"))
assert.falsy (talents.requires (talent, "y"))
assert.falsy (talents.provides (talent, "move"))
structure.y = talents.required ( )
assert.truthy (talents.provides (talent, "x"))
assert.falsy (talents.requires (talent, "y"))
function structure: move (x, y)
self.x = self.x + x
self.y = self.y + y
end
assert.truthy (talents.provides (talent, "x"))
assert.falsy (talents.requires (talent, "y"))
assert.falsy (talents.provides (talent, "move"))
structure.x = nil
assert.truthy (talents.provides (talent, "x"))
assert.falsy (talents.requires (talent, "y"))
assert.falsy (talents.provides (talent, "move"))
end)
end)
|
AddCSLuaFile()
ENT.Base = "gballoon_tower_base"
ENT.Type = "anim"
ENT.PrintName = "Mortar Tower"
ENT.Category = "#rotgb.category.tower"
ENT.Author = "Piengineer12"
ENT.Contact = "http://steamcommunity.com/id/Piengineer12/"
ENT.Purpose = "#rotgb.tower.gballoon_tower_11.purpose"
ENT.Instructions = ""
ENT.Spawnable = false
ENT.AdminOnly = false
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.Model = Model("models/hunter/tubes/tube1x1x1.mdl")
ENT.FireRate = 1
ENT.ShellAmt = 1
ENT.Cost = 500
ENT.DetectionRadius = 512
ENT.AttackDamage = 10
ENT.UserTargeting = true
ENT.AbilityCooldown = 30
ENT.rotgb_ExploRadius = 64
ENT.rotgb_TravelTime = 0.5
ENT.rotgb_Stun = 0
ENT.rotgb_StunMaxRgBE = 0
ENT.rotgb_FireDamage = 0
ENT.rotgb_FireDuration = 0
ENT.rotgb_AbilityType = 0
ENT.rotgb_HeavyMultiplier = 1
ENT.rotgb_Fragments = 0
ENT.UpgradeReference = {
{
Names = {"Faster Reload","High Impact Shells","Slippery Shells","Double Up","Artillery Cannons","Super Spread Cannon"},
Descs = {
"Slightly increases the tower's fire rate.",
"Enables the tower to pop Black gBalloons, Zebra gBalloons and Monochrome gBlimps.",
"Considerably increases the tower's fire rate and shells' speed.",
"Tremendously increases fire rate and two shells are fired at once!",
"The tower now fires three shells at once! Once every 30 seconds, shooting at this tower colossally increases its fire rate, shells' speed and causes its shots to stun gBalloons for 1 second! Lasts for 10 seconds when activated.",
"This tower fires a shell at each gBalloon per shot!",
},
Prices = {200,750,2000,15000,100000,350000},
Funcs = {
function(self)
self.FireRate = self.FireRate*1.5
end,
function(self)
self.rotgb_RespectPlayers = true
end,
function(self)
self.FireRate = self.FireRate*2
self.rotgb_TravelTime = self.rotgb_TravelTime/2
end,
function(self)
self.ShellAmt = self.ShellAmt*2
self.FireRate = self.FireRate*3
end,
function(self)
self.ShellAmt = self.ShellAmt*1.5
self.HasAbility = true
self.rotgb_AbilityType = bit.bor(self.rotgb_AbilityType, 1)
end,
function(self)
self.ShellAmt = math.huge
end
}
},
{
Names = {"Bigger Shells","Seeking Shells","Longer Cannon","Q.U.A.K.E. Shells","Sol Shells","Ω-Shells"},
Descs = {
"Slightly increases the shells' explosion radii.",
"Slightly increases the shells' speed and enables the tower to pop Hidden gBalloons.",
"Increases damage by 1 layer and increases range to infinite.",
"Considerably increases the shells' explosion radii and increases damage by 4 layers.",
"Increases damage by 24 layers! Shots will also set gBalloons on fire, popping 150 layers over 5 seconds.",
"Increases damage by 270 layers! Shots will also deal triple damage versus gBlimps."
},
Prices = {200,1000,5000,30000,300000,4.5e6},
Funcs = {
function(self)
self.rotgb_ExploRadius = self.rotgb_ExploRadius*1.5
end,
function(self)
self.rotgb_TravelTime = self.rotgb_TravelTime/1.5
self.SeeCamo = true
end,
function(self)
self.InfiniteRange = true
self.AttackDamage = self.AttackDamage + 10
self:SetModel("models/hunter/tubes/tube1x1x2.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
if IsValid(self:GetPhysicsObject()) then
self:GetPhysicsObject():EnableMotion(false)
end
end,
function(self)
self.rotgb_ExploRadius = self.rotgb_ExploRadius*2
self.AttackDamage = self.AttackDamage + 40
end,
function(self)
self.AttackDamage = self.AttackDamage + 240
self.rotgb_FireDamage = self.rotgb_FireDamage + 300
self.rotgb_FireDuration = self.rotgb_FireDuration + 5
end,
function(self)
self.AttackDamage = self.AttackDamage + 2700
self.rotgb_HeavyMultiplier = self.rotgb_HeavyMultiplier * 3
end
}
},
{
Names = {"Harder Shells", "Fragmentation Shells", "Shocking Shells", "Flaming Shells", "Blitz Cannon", "Greek Fire Cannon"},
Descs = {
"Increases the shells' damage by 1 layer.",
"Each shell yields 5 fragments on impact. Each fragment has a 20% chance to hit a random gBalloon, deals damage equal to the shell's explosion damage, travels up to twice of the shell's explosion radius and four times of the shell's speed, can pop Black gBalloons and can pass through walls.",
"Explosions stun gBalloons for 2 seconds, if they aren't immune to explosions. This upgrade can't stun gBlimps, but gBalloons stunned this way take 1 extra layer of damage from all sources.",
"Shells deal tremendously more damage versus gBlimps and Gray gBalloons, and can stun Red gBlimps and lower. Explosions and fragments will also set gBalloons on fire, popping 20 layers over 10 seconds.",
"Tremendously increases the number of shell fragments, considerably increases burning damage and shells can stun Green gBlimps and lower. Once every 30 seconds, shooting at this tower causes shells to be lobbed to every gBalloon on the map.",
"Shells can stun Purple gBlimps and lower, and gBalloons permanently lose all damage type immunities (if they aren't immune to explosions)! Also tremendously increases fire damage and slightly increases ability recharge rate. Blitz Cannon ability now also incrases fire damage to 12,000 layers per second, gives a 20% chance to deal 1,000x explosion damage versus gBlimps and causes ALL Mortar Towers' shells to stun and burn gBalloons at a rate similar to the Flaming Shells upgrade. The ability lasts for 10 seconds when activated."
},
-- 2, 6, 12, 102, 235.73, >=100,000
Prices = {450,1750,2500,37500,50000,35e6},
Funcs = {
function(self)
self.AttackDamage = self.AttackDamage + 10
end,
function(self)
self.rotgb_Fragments = self.rotgb_Fragments + 5
end,
function(self)
self.rotgb_Stun = self.rotgb_Stun + 2
self.rotgb_StunVulnerability = true
end,
function(self)
self.rotgb_HeavyMultiplier = self.rotgb_HeavyMultiplier * 3
self.rotgb_GrayHeavy = true
self.rotgb_StunMaxRgBE = self.rotgb_StunMaxRgBE + 4668
self.rotgb_FireDamage = self.rotgb_FireDamage + 20
self.rotgb_FireDuration = self.rotgb_FireDuration + 10
end,
function(self)
self.rotgb_Fragments = self.rotgb_Fragments * 3
self.rotgb_FireDamage = self.rotgb_FireDamage + 20
self.rotgb_StunMaxRgBE = self.rotgb_StunMaxRgBE + 22672 - 4668
self.HasAbility = true
self.rotgb_AbilityType = bit.bor(self.rotgb_AbilityType, 2)
end,
function(self)
self.rotgb_StunMaxRgBE = self.rotgb_StunMaxRgBE + 74000 - 22672
self.rotgb_WeakenStun = true
self.rotgb_FireDamage = self.rotgb_FireDamage + 80
self.AbilityCooldown = self.AbilityCooldown / 1.5
self.rotgb_AbilityType = bit.bor(self.rotgb_AbilityType, 4)
end
}
}
}
ENT.UpgradeLimits = {6,2,0}
function ENT:ROTGB_Initialize()
self:SetMaterial("phoenix_storms/metalset_1-2")
self:EmitSound("phx/kaboom.wav",60,100,0,CHAN_WEAPON)
end
function ENT:ROTGB_ApplyPerks()
self.rotgb_ExploRadius = self.rotgb_ExploRadius * (1+hook.Run("GetSkillAmount", "mortarTowerBombRadius")/100)
end
function ENT:FireFunction(tableOfBalloons)
self:SetModelScale(1.05)
self:SetModelScale(1,0.2)
self:EmitSound("weapons/crossbow/fire1.wav",75,150,1,CHAN_WEAPON)
local poses = {}
for i=1,self.ShellAmt do
if IsValid(tableOfBalloons[i]) then
table.insert(poses,tableOfBalloons[i]:GetPos())
else break
end
end
self:Bombshell(poses)
end
function ENT:Bombshell(poses)
timer.Simple(self.rotgb_TravelTime,function()
if IsValid(self) then
local shouldBlimpCrit = self.rotgb_HeavyCrits and math.random()<0.2
if self.rotgb_Fragments > 0 then
self:FireFragments(poses, shouldBlimpCrit)
end
local dmginfo = DamageInfo()
dmginfo:SetAmmoType(game.GetAmmoID("Grenade"))
dmginfo:SetAttacker(self:GetTowerOwner())
dmginfo:SetInflictor(self)
dmginfo:SetDamageType(self.rotgb_RespectPlayers and DMG_GENERIC or DMG_BLAST)
dmginfo:SetDamage(self.AttackDamage)
dmginfo:SetMaxDamage(self.AttackDamage)
local effdata = EffectData()
effdata:SetMagnitude(self.rotgb_ExploRadius/32)
effdata:SetScale(self.rotgb_ExploRadius/32)
for _,pos in pairs(poses) do
dmginfo:SetReportedPosition(pos)
effdata:SetOrigin(pos)
effdata:SetStart(pos)
--util.Effect("Explosion",effdata,true,true)
util.Effect("HelicopterMegaBomb",effdata,true,true)
if shouldBlimpCrit then
util.Effect("rotgb_crit",effdata,true,true)
end
EmitSound("phx/kaboom.wav", pos, 0, CHAN_WEAPON, 0.5, 75, SND_SHOULDPAUSE, math.random(80,120))
for k,v in pairs(ents.FindInSphere(pos,self.rotgb_ExploRadius)) do
if self:ValidTargetIgnoreRange(v) then
dmginfo:SetDamagePosition(v:GetPos())
if self.rotgb_Stun > 0 and v:DamageTypeCanDamage(dmginfo:GetDamageType()) and (not v:GetBalloonProperty("BalloonBlimp") or v:GetRgBE() <= self.rotgb_StunMaxRgBE) then
v:Stun(self.rotgb_Stun)
if self.rotgb_StunVulnerability then
v:InflictRotgBStatusEffect("shell_shocked", self.rotgb_Stun)
end
if self.rotgb_WeakenStun then
v:InflictRotgBStatusEffect("unimmune", math.huge)
end
end
if self.rotgb_FireDamage > 0 then
v:RotgB_Ignite(self.rotgb_FireDamage, self:GetTowerOwner(), self, self.rotgb_FireDuration)
end
if v:GetBalloonProperty("BalloonBlimp") then
dmginfo:ScaleDamage(self.rotgb_HeavyMultiplier)
if shouldBlimpCrit then
dmginfo:ScaleDamage(1000)
end
elseif self.rotgb_GrayHeavy and v:GetBalloonProperty("BalloonGray") then
dmginfo:ScaleDamage(3)
end
v:TakeDamageInfo(dmginfo)
if v:GetBalloonProperty("BalloonBlimp") then
dmginfo:ScaleDamage(1/self.rotgb_HeavyMultiplier)
elseif self.rotgb_GrayHeavy and v:GetBalloonProperty("BalloonGray") then
dmginfo:ScaleDamage(1/3)
if shouldBlimpCrit then
dmginfo:ScaleDamage(0.001)
end
end
end
end
end
end
end)
end
function ENT:FireFragments(poses, shouldBlimpCrit)
timer.Simple(self.rotgb_TravelTime/4,function()
if IsValid(self) then
local dmginfo = DamageInfo()
dmginfo:SetAmmoType(game.GetAmmoID("Pistol"))
dmginfo:SetAttacker(self:GetTowerOwner())
dmginfo:SetInflictor(self)
dmginfo:SetDamageType(DMG_BULLET)
dmginfo:SetDamage(self.AttackDamage)
dmginfo:SetMaxDamage(self.AttackDamage)
for _,pos in pairs(poses) do
local gBalloonsToHit = {}
dmginfo:SetReportedPosition(pos)
for i=1,self.rotgb_Fragments do
if math.random()<0.2 then
local possiblegBalloons = {}
for k,v in pairs(ents.FindInSphere(pos,self.rotgb_ExploRadius*2)) do
if self:ValidTargetIgnoreRange(v) then
possiblegBalloons[v] = true
end
end
for k,v in RandomPairs(possiblegBalloons) do
if not gBalloonsToHit[k] then
gBalloonsToHit[k] = true break
end
end
end
end
for balloon,_ in pairs(gBalloonsToHit) do
dmginfo:SetDamagePosition(balloon:GetPos())
if self.rotgb_FireDamage > 0 then
balloon:RotgB_Ignite(self.rotgb_FireDamage, self:GetTowerOwner(), self, self.rotgb_FireDuration)
end
if balloon:GetBalloonProperty("BalloonBlimp") then
dmginfo:ScaleDamage(self.rotgb_HeavyMultiplier)
if shouldBlimpCrit then
dmginfo:ScaleDamage(1000)
end
elseif self.rotgb_GrayHeavy and balloon:GetBalloonProperty("BalloonGray") then
dmginfo:ScaleDamage(3)
end
balloon:TakeDamageInfo(dmginfo)
if balloon:GetBalloonProperty("BalloonBlimp") then
dmginfo:ScaleDamage(1/self.rotgb_HeavyMultiplier)
if shouldBlimpCrit then
dmginfo:ScaleDamage(0.001)
end
elseif self.rotgb_GrayHeavy and balloon:GetBalloonProperty("BalloonGray") then
dmginfo:ScaleDamage(1/3)
end
end
end
end
end)
end
function ENT:TriggerAbility()
local abilityType = self.rotgb_AbilityType
if bit.band(abilityType, 1)==1 then
self:ApplyBuff(self, "ROTGB_TOWER_11_AC", 10, function(tower)
tower.rotgb_Stun = tower.rotgb_Stun + 1
tower.rotgb_StunMaxRgBE = tower.rotgb_StunMaxRgBE + 2e9
tower.FireRate = tower.FireRate*5
tower.rotgb_TravelTime = tower.rotgb_TravelTime/5
end, function(tower)
tower.rotgb_Stun = tower.rotgb_Stun - 1
tower.rotgb_StunMaxRgBE = tower.rotgb_StunMaxRgBE - 2e9
tower.FireRate = tower.FireRate/5
tower.rotgb_TravelTime = tower.rotgb_TravelTime*5
end)
end
if bit.band(abilityType, 4)==4 then
self:ApplyBuff(self, "ROTGB_TOWER_11_GFC", 10, function(tower)
tower.rotgb_FireDamage = tower.rotgb_FireDamage + 199880
tower.rotgb_HeavyCrits = true
end, function(tower)
tower.rotgb_FireDamage = tower.rotgb_FireDamage - 199880
tower.rotgb_HeavyCrits = nil
end)
for k,v in pairs(ents.FindByClass("gballoon_tower_11")) do
v:ApplyBuff(self, "ROTGB_TOWER_11_GFC_OTHER", 10, function(tower)
tower.rotgb_Stun = tower.rotgb_Stun + 2
tower.rotgb_StunMaxRgBE = tower.rotgb_StunMaxRgBE + 4668
tower.rotgb_FireDamage = tower.rotgb_FireDamage + 20
tower.rotgb_FireDuration = tower.rotgb_FireDuration + 10
end, function(tower)
tower.rotgb_Stun = tower.rotgb_Stun - 2
tower.rotgb_StunMaxRgBE = tower.rotgb_StunMaxRgBE - 4668
tower.rotgb_FireDamage = tower.rotgb_FireDamage - 20
tower.rotgb_FireDuration = tower.rotgb_FireDuration - 10
end)
end
end
if bit.band(abilityType, 2)==2 then
self:SetModelScale(1.05)
self:SetModelScale(1,0.2)
self:EmitSound("weapons/crossbow/fire1.wav",125,125,1,CHAN_WEAPON)
local poses = {}
for k,v in pairs(ROTGB_GetBalloons()) do
table.insert(poses,v:GetPos())
end
self:Bombshell(poses)
end
end |
pass = 0
function cpuplayers_updating()
local playerIndex = 0
for playerIndex = 0, Player_Count do
if (Player_IsAlive(playerIndex) == 1) then
if (Player_HasShipWithBuildQueue(playerIndex) == 1) then
if (Player_GetLevelOfDifficulty(playerIndex) > 0) then
--behaviour
if (pass == 0) then
if (cpuplayers == 1) then
Flag_Research(playerIndex, "cpuplayers_defensive")
Restrict_Research(playerIndex, "cpuplayers_aggressive")
Restrict_Research(playerIndex, "cpuplayers_dynamic")
elseif (cpuplayers == 2) then
Restrict_Research(playerIndex, "cpuplayers_defensive")
Restrict_Research(playerIndex, "cpuplayers_aggressive")
Restrict_Research(playerIndex, "cpuplayers_dynamic")
elseif (cpuplayers == 3) then
Restrict_Research(playerIndex, "cpuplayers_defensive")
Flag_Research(playerIndex, "cpuplayers_aggressive")
Restrict_Research(playerIndex, "cpuplayers_dynamic")
elseif (cpuplayers == 4) then
Restrict_Research(playerIndex, "cpuplayers_defensive")
Restrict_Research(playerIndex, "cpuplayers_aggressive")
Flag_Research(playerIndex, "cpuplayers_dynamic")
end
end
--no-rush time
if (norushtime > 0) then
if (pass == 0) then
--prevents the AI to attack
if (norushtime == 5) then
Flag_Research(playerIndex, "cpuplayers_norushtime5")
Restrict_Research(playerIndex, "cpuplayers_norushtime10")
Restrict_Research(playerIndex, "cpuplayers_norushtime15")
elseif (norushtime == 10) then
Restrict_Research(playerIndex, "cpuplayers_norushtime5")
Flag_Research(playerIndex, "cpuplayers_norushtime10")
Restrict_Research(playerIndex, "cpuplayers_norushtime15")
elseif (norushtime == 15) then
Restrict_Research(playerIndex, "cpuplayers_norushtime5")
Restrict_Research(playerIndex, "cpuplayers_norushtime10")
Flag_Research(playerIndex, "cpuplayers_norushtime15")
end
end
--prevents the AI to move
local mothership = PlayerRace_GetString(playerIndex, "def_type_mothership", "hgn_mothership")
local carrier = PlayerRace_GetString(playerIndex, "def_type_carrier", "hgn_carrier")
SobGroup_CreateIfNotExist("temp")
SobGroup_Clear("temp")
SobGroup_CreateIfNotExist("norushtime_nomove" .. playerIndex)
SobGroup_Clear("norushtime_nomove" .. playerIndex)
SobGroup_FillShipsByType("temp", "Player_Ships" .. playerIndex, mothership)
SobGroup_SobGroupAdd("norushtime_nomove" .. playerIndex, "temp")
SobGroup_FillShipsByType("temp", "Player_Ships" .. playerIndex, carrier)
SobGroup_SobGroupAdd("norushtime_nomove" .. playerIndex, "temp")
if norushtime > 1 then
SobGroup_AbilityActivate("norushtime_nomove" .. playerIndex, AB_Move, 0)
else
SobGroup_AbilityActivate("norushtime_nomove" .. playerIndex, AB_Move, 1)
end
end
--build speed balancing, based on level of difficulty
if (pass == 0) then
if ((Player_GetLevelOfDifficulty(playerIndex) == 1 or Player_GetLevelOfDifficulty(playerIndex) == 2)) then
Flag_Research(playerIndex, "AllShipBuildSpeed")
Restrict_Research(playerIndex, "AllShipBuildSpeedHard")
Restrict_Research(playerIndex, "AllShipBuildSpeedExpert")
elseif (Player_GetLevelOfDifficulty(playerIndex) == 3) then
Restrict_Research(playerIndex, "AllShipBuildSpeed")
Flag_Research(playerIndex, "AllShipBuildSpeedHard")
Restrict_Research(playerIndex, "AllShipBuildSpeedExpert")
elseif (Player_GetLevelOfDifficulty(playerIndex) == 4) then
Restrict_Research(playerIndex, "AllShipBuildSpeed")
Restrict_Research(playerIndex, "AllShipBuildSpeedHard")
Flag_Research(playerIndex, "AllShipBuildSpeedExpert")
end
end
--ru speed balancing, based on level of difficulty
if (pass == 0) then
if (Player_GetLevelOfDifficulty(playerIndex) == 3) then
Flag_Research(playerIndex, "ResourceCollectionRateHard")
Restrict_Research(playerIndex, "ResourceCollectionRateExpert")
elseif (Player_GetLevelOfDifficulty(playerIndex) == 4) then
Restrict_Research(playerIndex, "ResourceCollectionRateHard")
Flag_Research(playerIndex, "ResourceCollectionRateExpert")
end
end
--enables AI special weapons
if (pass == 0) then
AI_Special_Research = nil
dofilepath(PlayerRace_GetString(playerIndex, "path_ai_special", ""))
if (AI_Special_Research ~= nil) then
AI_Special_Research(playerIndex)
AI_Special_Research = nil
end
end
--relics
-- if (relics > 0) then
-- if (Universe_GameTime() > relic_start + 10) then
-- for i = 1, relic_max, 1 do
-- local sobname = "Relic" .. i
-- if (SobGroup_Empty(sobname) == 0) then
-- if (SobGroup_AreAnyOfTheseTypes(sobname, "Meg_Relic_RUGenerator") == 1) then
-- local relic_weight = 150
-- -- Don't need to clear this since FillProximitySobGroup will clear it
-- SobGroup_CreateIfNotExist("temp")
-- if (SobGroup_FillProximitySobGroup ("temp", "Player_Ships"..playerIndex, sobname, 50000) == 1) then
-- if (SobGroup_FillProximitySobGroup ("temp", "Player_Ships" .. playerIndex, sobname, 15000) == 1) then
-- relic_weight = relic_weight + 150
-- end
-- if ((playerIndex ~= SobGroup_OwnedBy(sobname)) and (SobGroup_OwnedBy(sobname) >= 0) and (AreAllied(playerIndex, SobGroup_OwnedBy(sobname)) == 0)) then
-- relic_weight = relic_weight + 150
-- if (Player_GetLevelOfDifficulty(SobGroup_OwnedBy(sobname)) > 0) then
-- relic_weight = relic_weight + 300
-- end
-- end
-- CPU_AddDefendSobGroup(playerIndex, sobname, relic_weight)
-- end
-- end
-- end
-- end
-- end
-- end
--crates
-- need to re-enable this if I want AI to use crates
-- if (crates > 0) then
-- if (Universe_GameTime() > timer_interval * 46) then -- need to replace this with correct crate timer value
-- for otherPlayerIndex = 0, Player_Count do
-- if (SobGroup_Empty("CrateSpawnGroup" .. otherPlayerIndex) == 0) then -- make sure this is the correct sobgroup name
-- if (SobGroup_AreAnyOfTheseTypes("CrateSpawnGroup" .. otherPlayerIndex, "Meg_Crate_HW1Container") == 1) then -- am I still using this ship type?
-- -- FillShipsByType does not clear out the destination sob group, so if we didn't create it then clear it
-- if (SobGroup_CreateIfNotExist("temp") == 0) then
-- SobGroup_Clear("temp")
-- end
-- -- FillProximitySobGroup clears the destination sob group, so we don't need to clear it if it already existed
-- SobGroup_CreateIfNotExist("temp1")
--
-- local scout = PlayerRace_GetString(playerIndex, "def_type_scout", "hgn_scout") -- I use tables instead of these strings
--
-- SobGroup_FillShipsByType("temp", "Player_Ships" .. playerIndex, scout)
--
-- if (SobGroup_FillProximitySobGroup("temp1", "temp", "CrateSpawnGroup" .. otherPlayerIndex, 25000) == 1) then
-- SobGroup_MoveToSobGroup("temp1", "CrateSpawnGroup" .. otherPlayerIndex)
-- end
-- end
-- end
-- end
-- end
-- end
end
end
end
end
if (pass == 0) then
Rule_Remove("cpuplayers_updating")
Rule_AddInterval("cpuplayers_updating",12)
end
pass = pass + 1
end
|
cfg = module("cfg/client")
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
local Tools = module("vrp", "lib/Tools")
tvRP = {}
Tunnel.bindInterface("vRP", tvRP)
vRPserver = Tunnel.getInterface("vRP")
Proxy.addInterface("vRP",tvRP)
function onClientMapStart(...)
if not Ran then ShutdownLoadingScreenNui() Ran = true end
DoScreenFadeOut(1000)
exports.spawnmanager:setAutoSpawn(true)
exports.spawnmanager:forceRespawn()
end
AddEventHandler('onClientMapStart', onClientMapStart)
function tvRP.teleport(x,y,z)
SetEntityCoords(PlayerPedId(),x+0.0001,y+0.0001,z+0.0001,1,0,0,1)
vRPserver._updatePos(x,y,z)
end
function tvRP.getUserHeading()
return GetEntityHeading(PlayerPedId())
end
function tvRP.clearWeapons()
RemoveAllPedWeapons(PlayerPedId(),true)
end
function tvRP.getPosition()
local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(),true))
local heading = GetEntityHeading(PlayerPedId())
return x,y,z,heading
end
function tvRP.isInside()
local x,y,z = tvRP.getPosition()
return not (GetInteriorAtCoords(x,y,z) == 0)
end
function tvRP.getSpeed()
local vx,vy,vz = table.unpack(GetEntityVelocity(PlayerPedId()))
return math.sqrt(vx*vx+vy*vy+vz*vz)
end
function tvRP.getCamDirection()
local heading = GetGameplayCamRelativeHeading()+GetEntityHeading(PlayerPedId())
local pitch = GetGameplayCamRelativePitch()
local x = -math.sin(heading*math.pi/180.0)
local y = math.cos(heading*math.pi/180.0)
local z = math.sin(pitch*math.pi/180.0)
local len = math.sqrt(x*x+y*y+z*z)
if len ~= 0 then
x = x/len
y = y/len
z = z/len
end
return x,y,z
end
function tvRP.notify(msg)
SetNotificationTextEntry("STRING")
AddTextComponentString(msg)
DrawNotification(true, false)
end
function tvRP.playScreenEffect(name, duration)
if duration >= 0 then
StartScreenEffect(name, 0, true)
Citizen.CreateThread(function()
Citizen.Wait(math.floor((duration+1)*1000))
StopScreenEffect(name)
end)
return end
StartScreenEffect(name, 0, true)
end
function tvRP.stopScreenEffect(name)
StopScreenEffect(name)
end
local anims = {}
local anim_ids = Tools.newIDGenerator()
function tvRP.playAnim(upper, seq, looping)
if seq.task then
tvRP.stopAnim(true)
local ped = PlayerPedId()
if seq.task == "PROP_HUMAN_SEAT_CHAIR_MP_PLAYER" then
local x,y,z = tvRP.getPosition()
TaskStartScenarioAtPosition(ped, seq.task, x, y, z-1, GetEntityHeading(ped), 0, 0, false)
return end
TaskStartScenarioInPlace(ped, seq.task, 0, not seq.play_exit)
return end
tvRP.stopAnim(upper)
local flags = 0
if upper then flags = flags+48 end
if looping then flags = flags+1 end
Citizen.CreateThread(function()
local id = anim_ids:gen()
anims[id] = true
for k,v in pairs(seq) do
local dict = v[1]
local name = v[2]
local loops = v[3] or 1
for i=1,loops do
if anims[id] then
local first = (k == 1 and i == 1)
local last = (k == #seq and i == loops)
RequestAnimDict(dict)
local i = 0
while not HasAnimDictLoaded(dict) and i < 1000 do -- max time, 10 seconds
Citizen.Wait(10)
RequestAnimDict(dict)
i = i+1
end
if HasAnimDictLoaded(dict) and anims[id] then
local inspeed = 8.0001
local outspeed = -8.0001
if not first then inspeed = 2.0001 end
if not last then outspeed = 2.0001 end
TaskPlayAnim(PlayerPedId(),dict,name,inspeed,outspeed,-1,flags,0,0,0,0)
end
Citizen.Wait(0)
while GetEntityAnimCurrentTime(PlayerPedId(),dict,name) <= 0.95 and IsEntityPlayingAnim(PlayerPedId(),dict,name,3) and anims[id] do
Citizen.Wait(0)
end
end
end
end
anim_ids:free(id)
anims[id] = nil
end)
end
function tvRP.stopAnim(upper)
anims = {}
if upper then
ClearPedSecondaryTask(PlayerPedId())
return end
ClearPedTasks(PlayerPedId())
end
local ragdoll = false
local function RagdollThread()
Citizen.CreateThread(function()
while true do
Citizen.Wait(10)
if not ragdoll then return end
SetPedToRagdoll(PlayerPedId(), 1000, 1000, 0, 0, 0, 0)
end
end)
end
function tvRP.setRagdoll(flag)
ragdoll = flag
RagdollThread()
end
AddEventHandler("playerSpawned",function()
TriggerServerEvent("vRPcli:playerSpawned")
end)
AddEventHandler("onPlayerDied",function(player,reason)
TriggerServerEvent("vRPcli:playerDied")
end)
AddEventHandler("onPlayerKilled",function(player,killer,reason)
TriggerServerEvent("vRPcli:playerDied")
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
if NetworkIsSessionStarted() then
TriggerServerEvent("Queue:playerActivated")
return end
end
end) |
local actions = {}
local g = require "global"
function actions.test()
return {
tile = -1,
deco = 80,
onJump = function(self) gooi.alert({text = "activated!"}) end,
onVisible = function(self) g.world.entities["mole"] = require("entities.enemies.mole")((self.x-0.5)*60, (self.y-1)*60) end,
onTouched = function(self) gooi.alert({text = "touched!"}) end
}
end
function actions.lobby()
return {
tile = -1,
deco = -1,
onVisible = function(self) g.game.unlocked.lobby = true end
}
end
function actions.unlockUG()
return {
tile = -1,
deco = -1,
onVisible = function(self) g.game.unlocked.underground = true end
}
end
function actions.UGDoor(x, y, map)
if g.game.unlocked.underground then
map.deco[y-1][x] = 88
table.insert(map.objects, {
id = "entry",
x = x,
y = y,
cur = 2,
goal = 0,
mapx = 3,
mapy = 3
})
return {
tile = -1,
deco = 96,
onJump = function(self)
g.world.changeMap(0, 2, 3)
end
}
else
return {
tile = -1,
deco = -1
}
end
end
function actions.abBall()
if g.game.abilities.ball then
return {
tile = -1,
deco = -1
}
else
return {
tile = -1,
deco = 80,
onTouched = function(self) g.states.learn:learn("ball") end
}
end
end
function actions.abAirjump()
if g.game.abilities.airjump then
return {
tile = -1,
deco = -1
}
else
return {
tile = -1,
deco = 81,
onTouched = function(self) g.states.learn:learn("airjump") end
}
end
end
function actions.finish()
return {
tile = -1,
deco = -1,
onTouched = function(self) Gamestate.push(g.states.finished) end
}
end
return actions |
function initLogging()
tmr.alarm(3, 1000 * timings.log, tmr.ALARM_AUTO, function()
require('logSensors')
logSensors()
package.loaded['logSensors'] = nil
logSensors = nil
end)
end
|
addition_table = function()
columns = 6
min = 2;
max = 8;
devide = min + math.random(max-min)
multiple = min + math.random(10 - devide)
q = {}
for i=0,columns-1 do
q[i] = {}
term1 = math.random(6)
term2 = min + math.random(7 - term1)
q[i][1] = devide * term1 * 5
q[i][2] = devide * term2 * 5
q[i][3] = q[i][1] + q[i][2]
if (q[i][1] < q[i][2]) then
xx = q[i][1]
q[i][1] = q[i][2]
q[i][2] = xx
end
q[i][4] = q[i][1] - q[i][2]
q[i][5] = term1 * 5 + term2 * 5
q[i][6] = q[i][4] * multiple
q[i][7] = math.random(3)
q[i][8] = q[i][7] + math.random(6-q[i][7] )
if (q[i][7] == 3 and q[i][8] == 5) then
q[i][8] = 6
end
end
style = {}
style["text-align"] = "center"
style["width"] = "50px"
text = lib.start_table()
text = text .. lib.start_row()
text = text .. lib.add_cell("a", style)
text = text .. lib.add_cell("b", style)
text = text .. lib.add_cell("a+b", style)
text = text .. lib.add_cell("a-b", style)
text = text .. lib.add_cell("(a+b) :" .. tostring(devide) , style)
text = text .. lib.add_cell("(a-b) ·" .. tostring(multiple) , style)
text = text .. lib.end_row()
for c=0,columns-1 do
text = text .. lib.start_row()
for r=1,6 do
if (q[c][7] == r or q[c][8] == r) then
text = text .. lib.add_cell(tostring(q[c][r]), style)
else
text = text .. lib.add_cell(lib.check_number(q[c][r]), style)
end
end
text = text .. lib.end_row()
end
text = text .. lib.end_table()
return text
end
|
AddCSLuaFile("shared.lua")
include('shared.lua')
/*-----------------------------------------------
*** Copyright (c) 2012-2019 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/
ENT.Model = {"models/vj_hlr/opfor/strooper.mdl"} -- The game will pick a random model from the table when the SNPC is spawned | Add as many as you want
ENT.StartHealth = 150
ENT.HullType = HULL_HUMAN
---------------------------------------------------------------------------------------------------------------------------------------------
ENT.VJ_NPC_Class = {"CLASS_RACE_X"} -- NPCs with the same class with be allied to each other
ENT.BloodColor = "Yellow" -- The blood type, this will determine what it should use (decal, particle, etc.)
ENT.CustomBlood_Decal = {"VJ_Blood_HL1_Yellow"} -- Decals to spawn when it's damaged
ENT.HasBloodPool = false -- Does it have a blood pool?
ENT.MeleeAttackDamage = 10
ENT.TimeUntilMeleeAttackDamage = false -- This counted in seconds | This calculates the time until it hits something
ENT.HasGrenadeAttack = true -- Should the SNPC have a grenade attack?
ENT.GrenadeAttackEntity = "obj_vj_hlrof_grenade_spore" -- The entity that the SNPC throws | Half Life 2 Grenade: "npc_grenade_frag"
ENT.AnimTbl_GrenadeAttack = {ACT_SPECIAL_ATTACK2} -- Grenade Attack Animations
ENT.GrenadeAttackAttachment = "eyes" -- The attachment that the grenade will spawn at
ENT.TimeUntilGrenadeIsReleased = 1.5 -- Time until the grenade is released
ENT.ThrowGrenadeChance = 1
ENT.Weapon_NoSpawnMenu = true -- If set to true, the NPC weapon setting in the spawnmenu will not be applied for this SNPC
ENT.DisableWeaponFiringGesture = true -- If set to true, it will disable the weapon firing gestures
ENT.MoveRandomlyWhenShooting = false -- Should it move randomly when shooting?
ENT.HasLostWeaponSightAnimation = true -- Set to true if you would like the SNPC to play a different animation when it has lost sight of the enemy and can't fire at it
ENT.AnimTbl_WeaponAttack = {ACT_RANGE_ATTACK1} -- Animation played when the SNPC does weapon attack | For VJ Weapons
ENT.AnimTbl_WeaponAttackCrouch = {ACT_RANGE_ATTACK2} -- Animation played when the SNPC does weapon attack while crouching | For VJ Weapons
ENT.AnimTbl_CallForHelp = {ACT_SIGNAL1} -- Call For Help Animations
ENT.CallForBackUpOnDamageAnimation = {ACT_SIGNAL3} -- Animation used if the SNPC does the CallForBackUpOnDamage function
ENT.AnimTbl_TakingCover = {ACT_CROUCHIDLE} -- The animation it plays when hiding in a covered position, leave empty to let the base decide
ENT.AnimTbl_AlertFriendsOnDeath = {ACT_IDLE_ANGRY} -- Animations it plays when an ally dies that also has AlertFriendsOnDeath set to true
ENT.HasDeathAnimation = true -- Does it play an animation when it dies?
ENT.AnimTbl_Death = {ACT_DIEBACKWARD,ACT_DIEFORWARD,ACT_DIE_GUTSHOT,ACT_DIE_HEADSHOT,ACT_DIESIMPLE} -- Death Animations
ENT.DeathAnimationTime = false -- Time until the SNPC spawns its corpse and gets removed
ENT.DisableFootStepSoundTimer = true -- If set to true, it will disable the time system for the footstep sound code, allowing you to use other ways like model events
-- ====== Flinching Code ====== --
ENT.CanFlinch = 1 -- 0 = Don't flinch | 1 = Flinch at any damage | 2 = Flinch only from certain damages
ENT.AnimTbl_Flinch = {ACT_SMALL_FLINCH} -- If it uses normal based animation, use this
-- ====== Sound File Paths ====== --
-- Leave blank if you don't want any sounds to play
ENT.SoundTbl_FootStep = {"vj_hlr/hl1_npc/player/boots1.wav","vj_hlr/hl1_npc/player/boots2.wav","vj_hlr/hl1_npc/player/boots3.wav","vj_hlr/hl1_npc/player/boots4.wav"}
ENT.SoundTbl_Idle = {"vj_hlr/hl1_npc/shocktrooper/st_idle.wav"}
ENT.SoundTbl_IdleDialogue = {"vj_hlr/hl1_npc/shocktrooper/st_question1.wav","vj_hlr/hl1_npc/shocktrooper/st_question2.wav"}
ENT.SoundTbl_IdleDialogueAnswer = {"vj_hlr/hl1_npc/shocktrooper/st_answer1.wav","vj_hlr/hl1_npc/shocktrooper/st_answer2.wav"}
ENT.SoundTbl_CombatIdle = {"vj_hlr/hl1_npc/shocktrooper/st_combat1.wav","vj_hlr/hl1_npc/shocktrooper/st_combat2.wav"}
ENT.SoundTbl_Alert = {"vj_hlr/hl1_npc/shocktrooper/st_alert1.wav","vj_hlr/hl1_npc/shocktrooper/st_alert2.wav","vj_hlr/hl1_npc/shocktrooper/st_alert3.wav","vj_hlr/hl1_npc/shocktrooper/st_alert4.wav"}
ENT.SoundTbl_GrenadeAttack = {"vj_hlr/hl1_npc/shocktrooper/st_grenadethrow.wav"}
ENT.SoundTbl_OnGrenadeSight = {"vj_hlr/hl1_npc/shocktrooper/st_runfromgrenade.wav"}
ENT.SoundTbl_OnKilledEnemy = {"vj_hlr/hl1_npc/shocktrooper/st_combat1.wav"}
ENT.OnGrenadeSightSoundPitch1 = 105
ENT.OnGrenadeSightSoundPitch2 = 110
-- Custom
ENT.Shocktrooper_Roach = NULL
ENT.Shocktrooper_BlinkingT = 0
ENT.Shocktrooper_SpawnEnt = true
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnInitialize()
self:SetCollisionBounds(Vector(20, 20, 90), Vector(-20, -20, 0))
self:SetBodygroup(1,0)
self:Give("weapon_vj_hl_strooperwep")
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnAcceptInput(key,activator,caller,data)
//print(key)
if key == "step" then
self:FootStepSoundCode()
end
if key == "attack" then
self:MeleeAttackCode()
end
if key == "rangeattack" then
local wep = self:GetActiveWeapon()
if IsValid(wep) then
wep:NPCShoot_Primary(ShootPos,ShootDir)
end
end
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnThink()
if self:Health() <= (self:GetMaxHealth() / 2.2) then
self.AnimTbl_Walk = {ACT_WALK_HURT}
self.AnimTbl_Run = {ACT_RUN_HURT}
self.AnimTbl_ShootWhileMovingWalk = {ACT_WALK_HURT}
self.AnimTbl_ShootWhileMovingRun = {ACT_RUN_HURT}
else
self.AnimTbl_Walk = {ACT_WALK}
self.AnimTbl_Run = {ACT_RUN}
self.AnimTbl_ShootWhileMovingWalk = {ACT_WALK}
self.AnimTbl_ShootWhileMovingRun = {ACT_RUN}
end
if self.Dead == false && CurTime() > self.Shocktrooper_BlinkingT then
timer.Simple(0.2,function() if IsValid(self) then self:SetSkin(1) end end)
timer.Simple(0.3,function() if IsValid(self) then self:SetSkin(2) end end)
timer.Simple(0.4,function() if IsValid(self) then self:SetSkin(3) end end)
timer.Simple(0.5,function() if IsValid(self) then self:SetSkin(0) end end)
self.Shocktrooper_BlinkingT = CurTime() + math.Rand(3,4.5)
end
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomOnDeath_BeforeCorpseSpawned(dmginfo,hitgroup)
self:SetBodygroup(1,1)
self:SetSkin(2)
if self.Shocktrooper_SpawnEnt == true then
self.Shocktrooper_Roach = ents.Create("npc_vj_hlrof_shockroach")
self.Shocktrooper_Roach:SetPos(self:GetAttachment(self:LookupAttachment("shock_roach")).Pos)//+ self:GetUp()*50)
self.Shocktrooper_Roach:SetAngles(self:GetAngles())
self.Shocktrooper_Roach:Spawn()
self.Shocktrooper_Roach:Activate()
self.Shocktrooper_Roach.VJ_NPC_Class = table.Merge(self.Shocktrooper_Roach.VJ_NPC_Class,self.VJ_NPC_Class)
self.Shocktrooper_Roach.Lifespan = true
end
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:SetUpGibesOnDeath(dmginfo,hitgroup)
self.HasDeathSounds = false
self.Shocktrooper_SpawnEnt = false
if self.HasGibDeathParticles == true then
local bloodeffect = EffectData()
bloodeffect:SetOrigin(self:GetPos() +self:OBBCenter())
bloodeffect:SetColor(VJ_Color2Byte(Color(255,221,35)))
bloodeffect:SetScale(120)
util.Effect("VJ_Blood1",bloodeffect)
local bloodspray = EffectData()
bloodspray:SetOrigin(self:GetPos() +self:OBBCenter())
bloodspray:SetScale(8)
bloodspray:SetFlags(3)
bloodspray:SetColor(1)
util.Effect("bloodspray",bloodspray)
util.Effect("bloodspray",bloodspray)
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos() +self:OBBCenter())
effectdata:SetScale(1)
util.Effect("StriderBlood",effectdata)
util.Effect("StriderBlood",effectdata)
end
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib1.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,40))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib2.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,20))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib3.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,30))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib4.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,35))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib5.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,40))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib6.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,20))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib7.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,30))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/strooper_gib8.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,35))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib1.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,40))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib2.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,20))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib3.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,30))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib4.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,35))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib5.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,50))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib6.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,55))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib7.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,40))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib8.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,45))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib9.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,25))})
self:CreateGibEntity("obj_vj_gib","models/vj_hlr/gibs/agib10.mdl",{BloodType="Yellow",BloodDecal="VJ_Blood_HL1_Yellow",Pos=self:LocalToWorld(Vector(0,0,15))})
return true -- Return to true if it gibbed!
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:CustomGibOnDeathSounds(dmginfo,hitgroup)
VJ_EmitSound(self,"vj_gib/default_gib_splat.wav",90,math.random(100,100))
return false
end
---------------------------------------------------------------------------------------------------------------------------------------------
function ENT:ThrowGrenadeCode(CustomEnt,NoOwner)
if self.Dead == true or self.Flinching == true or self.MeleeAttacking == true or (IsValid(self:GetEnemy()) && !self:Visible(self:GetEnemy())) then return end
//if self:VJ_ForwardIsHidingZone(self:NearestPoint(self:GetPos() +self:OBBCenter()),self:GetEnemy():EyePos()) == true then return end
local NoOwner = NoOwner or false
local getIsCustom = false
local gerModel = self.GrenadeAttackModel
local gerClass = self.GrenadeAttackEntity
local gerFussTime = self.GrenadeAttackFussTime
if IsValid(CustomEnt) then -- Custom nernagner gamal nernagner vor yete bidi nede
getIsCustom = true
gerModel = CustomEnt:GetModel()
gerClass = CustomEnt:GetClass()
CustomEnt:SetMoveType(MOVETYPE_NONE)
CustomEnt:SetParent(self)
CustomEnt:Fire("SetParentAttachment",self.GrenadeAttackAttachment)
//CustomEnt:SetPos(self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Pos)
CustomEnt:SetAngles(self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Ang)
if gerClass == "obj_vj_grenade" then
gerFussTime = math.abs(CustomEnt.FussTime - CustomEnt.TimeSinceSpawn)
elseif gerClass == "obj_handgrenade" or gerClass == "obj_spore" then
gerFussTime = 1
elseif gerClass == "npc_grenade_frag" or gerClass == "doom3_grenade" or gerClass == "fas2_thrown_m67" or gerClass == "cw_grenade_thrown" or gerClass == "cw_flash_thrown" or gerClass == "cw_smoke_thrown" then
gerFussTime = 1.5
elseif gerClass == "obj_cpt_grenade" then
gerFussTime = 2
end
end
self.ThrowingGrenade = true
self:CustomOnGrenadeAttack_BeforeThrowTime()
self:GrenadeAttackSoundCode()
if self.VJ_PlayingSequence == false && self.DisableGrenadeAttackAnimation == false then
self.CurrentAttackAnimation = VJ_PICKRANDOMTABLE(self.AnimTbl_GrenadeAttack)
self.PlayingAttackAnimation = true
timer.Simple(VJ_GetSequenceDuration(self,self.CurrentAttackAnimation) - 0.2,function()
if IsValid(self) then
self.PlayingAttackAnimation = false
end
end)
self:VJ_ACT_PLAYACTIVITY(self.CurrentAttackAnimation,self.GrenadeAttackAnimationStopAttacks,self:DecideAnimationLength(self.CurrentAttackAnimation,self.GrenadeAttackAnimationStopAttacksTime),false,self.GrenadeAttackAnimationDelay)
end
timer.Simple(self.TimeUntilGrenadeIsReleased,function()
if getIsCustom == true && !IsValid(CustomEnt) then return end
if IsValid(CustomEnt) then CustomEnt.VJHumanTossingAway = false CustomEnt:Remove() end
if IsValid(self) && self.Dead == false /*&& IsValid(self:GetEnemy())*/ then -- Yete SNPC ter artoon e...
local gerShootPos = self:GetPos() + self:GetForward()*200
if IsValid(self:GetEnemy()) then
gerShootPos = self:GetEnemy():GetPos()
else -- Yete teshnami chooni, nede amenan lav goghme
local iamarmo = self:VJ_CheckAllFourSides()
if iamarmo.Forward then gerShootPos = self:GetPos() + self:GetForward()*200; self:FaceCertainPosition(gerShootPos)
elseif iamarmo.Right then gerShootPos = self:GetPos() + self:GetRight()*200; self:FaceCertainPosition(gerShootPos)
elseif iamarmo.Left then gerShootPos = self:GetPos() + self:GetRight()*-200; self:FaceCertainPosition(gerShootPos)
elseif iamarmo.Backward then gerShootPos = self:GetPos() + self:GetForward()*-200; self:FaceCertainPosition(gerShootPos)
end
end
local gent = ents.Create(gerClass)
local getShootVel = (gerShootPos - self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Pos) + (self:GetUp()*math.random(450,500) + self:GetForward()*math.Rand(-100,-250) + self:GetRight()*math.Rand(self.GrenadeAttackVelRight1,self.GrenadeAttackVelRight2))
if IsValid(CustomEnt) then
getShootVel = (gerShootPos - self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Pos) + (self:GetUp()*math.random(self.GrenadeAttackVelUp1,self.GrenadeAttackVelUp2) + self:GetForward()*math.Rand(self.GrenadeAttackVelForward1,self.GrenadeAttackVelForward2) + self:GetRight()*math.Rand(self.GrenadeAttackVelRight1,self.GrenadeAttackVelRight2))
end
if NoOwner == false then gent:SetOwner(self) end
gent:SetPos(self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Pos)
gent:SetAngles(self:GetAttachment(self:LookupAttachment(self.GrenadeAttackAttachment)).Ang)
gent:SetModel(Model(gerModel))
if gerClass == "obj_vj_grenade" then
gent.FussTime = gerFussTime
elseif gerClass == "obj_cpt_grenade" then
gent:SetTimer(gerFussTime)
elseif gerClass == "obj_spore" then
gent:SetGrenade(true)
elseif gerClass == "ent_hl1_grenade" then
gent:ShootTimed(CustomEnt, getShootVel, gerFussTime)
elseif gerClass == "doom3_grenade" or gerClass == "obj_handgrenade" then
gent:SetExplodeDelay(gerFussTime)
elseif gerClass == "cw_grenade_thrown" or gerClass == "cw_flash_thrown" or gerClass == "cw_smoke_thrown" then
gent:SetOwner(self)
gent:Fuse(gerFussTime)
end
gent:Spawn()
gent:Activate()
if gerClass == "npc_grenade_frag" then gent:Input("SetTimer",self:GetOwner(),self:GetOwner(),gerFussTime) end
local phys = gent:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
phys:AddAngleVelocity(Vector(math.Rand(500,500),math.Rand(500,500),math.Rand(500,500)))
phys:SetVelocity(getShootVel)
end
self:CustomOnGrenadeAttack_OnThrow(gent)
end
self.ThrowingGrenade = false
end)
end
/*-----------------------------------------------
*** Copyright (c) 2012-2019 by DrVrej, All rights reserved. ***
No parts of this code or any of its contents may be reproduced, copied, modified or adapted,
without the prior written consent of the author, unless otherwise indicated for stand-alone materials.
-----------------------------------------------*/ |
-- File content is auto-generated. Do not modify.
local SymbolBase = require('mx._ctypes.symbol').SymbolBase
local _symbol_creator = require('mx._ctypes.symbol')._symbol_creator
local NameManager = require('mx.name').NameManager
local AttrScope = require('mx.attribute').AttrScope
local _Null = require('mx.base')._Null
---@class mx.symbol.gen__internal
local M = {}
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol[] | input data list
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._CachedOp(...)
end
--- Special op to copy data cross device
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._CrossDeviceCopy(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._CustomFunction(name, attr, out, kwargs)
end
--- Divides arguments element-wise.
---
--- The storage type of ``elemwise_div`` output is always dense
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Div(lhs, rhs, name, attr, out, kwargs)
end
--- Divide an array with a scalar.
---
--- ``_div_scalar`` only operates on data array of input if input is sparse.
---
--- For example, if input of shape (100, 100) has only 2 non zero elements,
--- i.e. input.data = [5, 6], scalar = nan,
--- it will result output.data = [nan, nan] instead of 10000 nans.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_scalar_op_basic.cc:L171
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._DivScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._EqualScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Greater(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._GreaterEqualScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._GreaterScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Greater_Equal(lhs, rhs, name, attr, out, kwargs)
end
--- Given the "legs" of a right triangle, return its hypotenuse.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_op_extended.cc:L79
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Hypot(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._HypotScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Lesser(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._LesserEqualScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._LesserScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Lesser_Equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._LogicalAndScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._LogicalOrScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._LogicalXorScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Logical_And(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Logical_Or(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Logical_Xor(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Maximum(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._MaximumScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Minimum(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._MinimumScalar(data, scalar, name, attr, out, kwargs)
end
--- Subtracts arguments element-wise.
---
--- The storage type of ``elemwise_sub`` output depends on storage types of inputs
---
--- - elemwise_sub(row_sparse, row_sparse) = row_sparse
--- - elemwise_sub(csr, csr) = csr
--- - elemwise_sub(default, csr) = default
--- - elemwise_sub(csr, default) = default
--- - elemwise_sub(default, rsp) = default
--- - elemwise_sub(rsp, default) = default
--- - otherwise, ``elemwise_sub`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Minus(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._MinusScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Mod(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._ModScalar(data, scalar, name, attr, out, kwargs)
end
--- Multiplies arguments element-wise.
---
--- The storage type of ``elemwise_mul`` output depends on storage types of inputs
---
--- - elemwise_mul(default, default) = default
--- - elemwise_mul(row_sparse, row_sparse) = row_sparse
--- - elemwise_mul(default, row_sparse) = row_sparse
--- - elemwise_mul(row_sparse, default) = row_sparse
--- - elemwise_mul(csr, csr) = csr
--- - otherwise, ``elemwise_mul`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Mul(lhs, rhs, name, attr, out, kwargs)
end
--- Multiply an array with a scalar.
---
--- ``_mul_scalar`` only operates on data array of input if input is sparse.
---
--- For example, if input of shape (100, 100) has only 2 non zero elements,
--- i.e. input.data = [5, 6], scalar = nan,
--- it will result output.data = [nan, nan] instead of 10000 nans.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_scalar_op_basic.cc:L149
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._MulScalar(data, scalar, name, attr, out, kwargs)
end
--- Stub for implementing an operator implemented in native frontend language with ndarray.
--- This function support variable length of positional input.
---
---
---@param data any @Symbol[] | Input data for the custom operator.
---@param info any @ptr, required
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._NDArray(...)
end
--- Stub for implementing an operator implemented in native frontend language.
--- This function support variable length of positional input.
---
---
---@param data any @Symbol[] | Input data for the custom operator.
---@param info any @ptr, required
---@param need_top_grad any @boolean, optional, default=1 | Whether this layer needs out grad for backward. Should be false for loss layers.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Native(...)
end
--- Place holder for variable who cannot perform gradient
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._NoGradient(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._NotEqualScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Not_Equal(lhs, rhs, name, attr, out, kwargs)
end
--- Adds arguments element-wise.
---
--- The storage type of ``elemwise_add`` output depends on storage types of inputs
---
--- - elemwise_add(row_sparse, row_sparse) = row_sparse
--- - elemwise_add(csr, csr) = csr
--- - elemwise_add(default, csr) = default
--- - elemwise_add(csr, default) = default
--- - elemwise_add(default, rsp) = default
--- - elemwise_add(rsp, default) = default
--- - otherwise, ``elemwise_add`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Plus(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._PlusScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._Power(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._PowerScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._RDivScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._RMinusScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._RModScalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._RPowerScalar(data, scalar, name, attr, out, kwargs)
end
--- Update function for AdamW optimizer. AdamW is seen as a modification of
--- Adam by decoupling the weight decay from the optimization steps taken w.r.t. the loss function.
---
--- Adam update consists of the following steps, where g represents gradient and m, v
--- are 1st and 2nd order moment estimates (mean and variance).
---
--- .. math::
---
--- g_t = \nabla J(W_{t-1})\\
--- m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t\\
--- v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
--- W_t = W_{t-1} - \eta_t (\alpha \frac{ m_t }{ \sqrt{ v_t } + \epsilon } + wd W_{t-1})
---
--- It updates the weights using::
---
--- m = beta1*m + (1-beta1)*grad
--- v = beta2*v + (1-beta2)*(grad**2)
--- w -= eta * (learning_rate * m / (sqrt(v) + epsilon) + w * wd)
---
--- Note that gradient is rescaled to grad = rescale_grad * grad. If rescale_grad is NaN, Inf, or 0,
--- the update is skipped.
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\contrib\adamw.cc:L120
--- This function support variable length of positional input.
---
---
---@param weight any @Symbol | Weight
---@param grad any @Symbol | Gradient
---@param mean any @Symbol | Moving mean
---@param var any @Symbol | Moving variance
---@param rescale_grad any @Symbol | Rescale gradient to rescale_grad * grad. If NaN, Inf, or 0, the update is skipped.
---@param lr any @float, required | Learning rate
---@param beta1 any @float, optional, default=0.899999976 | The decay rate for the 1st moment estimates.
---@param beta2 any @float, optional, default=0.999000013 | The decay rate for the 2nd moment estimates.
---@param epsilon any @float, optional, default=9.99999994e-09 | A small constant for numerical stability.
---@param wd any @float, optional, default=0 | Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
---@param eta any @float, required | Learning rate schedule multiplier
---@param clip_gradient any @float, optional, default=-1 | Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._adamw_update(weight, grad, mean, var, rescale_grad, lr, beta1, beta2, epsilon, wd, eta, clip_gradient, name, attr, out, kwargs)
end
--- Adds arguments element-wise.
---
--- The storage type of ``elemwise_add`` output depends on storage types of inputs
---
--- - elemwise_add(row_sparse, row_sparse) = row_sparse
--- - elemwise_add(csr, csr) = csr
--- - elemwise_add(default, csr) = default
--- - elemwise_add(csr, default) = default
--- - elemwise_add(default, rsp) = default
--- - elemwise_add(rsp, default) = default
--- - otherwise, ``elemwise_add`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._add(lhs, rhs, name, attr, out, kwargs)
end
--- Return evenly spaced values within a given interval. Similar to Numpy
--- This function support variable length of positional input.
---
---
---@param start any @double, required | Start of interval. The interval includes this value. The default start value is 0.
---@param stop any @double or None, optional, default=None | End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
---@param step any @double, optional, default=1 | Spacing between values.
---@param repeat_ any @int, optional, default='1' | The repeating time of all elements. E.g repeat=3, the element a will be repeated three times --> a, a, a.
---@param infer_range any @boolean, optional, default=0 | When set to True, infer the stop position from the start, step, repeat, and output tensor size.
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._arange(start, stop, step, repeat_, infer_range, ctx, dtype, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Activation(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_BatchNorm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_BatchNorm_v1(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_BilinearSampler(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_CachedOp(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Concat(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Convolution(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Convolution_v1(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Correlation(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Crop(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_CuDNNBatchNorm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Custom(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_CustomFunction(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Deconvolution(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Dropout(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Embedding(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_FullyConnected(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_GridGenerator(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_IdentityAttachKLSparseReg(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_InstanceNorm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_L2Normalization(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_LRN(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_LayerNorm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_LeakyReLU(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_MakeLoss(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Pad(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Pooling(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_Pooling_v1(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_RNN(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_ROIAlign(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_ROIPooling(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SVMOutput(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SequenceLast(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SequenceMask(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SequenceReverse(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SliceChannel(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SoftmaxActivation(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SoftmaxOutput(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SparseEmbedding(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SpatialTransformer(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_SwapAxis(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_UpSampling(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__CrossDeviceCopy(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__NDArray(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__Native(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_DeformableConvolution(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_DeformablePSROIPooling(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_MultiBoxDetection(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_MultiBoxPrior(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_MultiBoxTarget(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_MultiProposal(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_PSROIPooling(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_Proposal(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_SyncBatchNorm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_count_sketch(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_fft(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward__contrib_ifft(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_abs(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_add(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_amp_cast(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param grad any @Symbol[] | Gradients
---@param num_outputs any @int, required | Number of input/output pairs to be casted to the widest type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_amp_multicast(...)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arccos(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arccosh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arcsin(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arcsinh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arctan(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_arctanh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_batch_dot(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_add(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_div(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_hypot(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_maximum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_minimum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_mod(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_mul(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_power(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_broadcast_sub(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_cast(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_cbrt(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_clip(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_cond(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_AdaptiveAvgPooling2D(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_BilinearResize2D(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param is_ascend any @boolean, optional, default=0 | Use ascend order for scores instead of descending. Please set threshold accordingly.
---@param threshold any @float, required | Ignore matching when score < thresh, if is_ascend=false, or ignore score > thresh, if is_ascend=true.
---@param topk any @int, optional, default='-1' | Limit the number of matches to topk, set -1 for no limit
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_bipartite_matching(is_ascend, threshold, topk, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param axis any @int, optional, default='0' | An integer that represents the axis in NDArray to mask from.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_boolean_mask(axis, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param format any @{'center', 'corner'},optional, default='corner' | The box encoding type. "corner" means boxes are encoded as [xmin, ymin, xmax, ymax], "center" means boxes are encodes as [x, y, width, height].
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_box_iou(format, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param overlap_thresh any @float, optional, default=0.5 | Overlapping(IoU) threshold to suppress object with smaller score.
---@param valid_thresh any @float, optional, default=0 | Filter input boxes to those whose scores greater than valid_thresh.
---@param topk any @int, optional, default='-1' | Apply nms to topk boxes with descending scores, -1 to no restriction.
---@param coord_start any @int, optional, default='2' | Start index of the consecutive 4 coordinates.
---@param score_index any @int, optional, default='1' | Index of the scores/confidence of boxes.
---@param id_index any @int, optional, default='-1' | Optional, index of the class categories, -1 to disable.
---@param background_id any @int, optional, default='-1' | Optional, id of the background class which will be ignored in nms.
---@param force_suppress any @boolean, optional, default=0 | Optional, if set false and id_index is provided, nms will only apply to boxes belongs to the same category
---@param in_format any @{'center', 'corner'},optional, default='corner' | The input box encoding type. "corner" means boxes are encoded as [xmin, ymin, xmax, ymax], "center" means boxes are encodes as [x, y, width, height].
---@param out_format any @{'center', 'corner'},optional, default='corner' | The output box encoding type. "corner" means boxes are encoded as [xmin, ymin, xmax, ymax], "center" means boxes are encodes as [x, y, width, height].
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_contrib_box_nms(overlap_thresh, valid_thresh, topk, coord_start, score_index, id_index, background_id, force_suppress, in_format, out_format, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_copy(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_cos(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_cosh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_ctc_loss(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_degrees(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_diag(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_div(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_div_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param transpose_a any @boolean, optional, default=0 | If true then transpose the first input before dot.
---@param transpose_b any @boolean, optional, default=0 | If true then transpose the second input before dot.
---@param forward_stype any @{None, 'csr', 'default', 'row_sparse'},optional, default='None' | The desired storage type of the forward output given by user, if thecombination of input storage types and this hint does not matchany implemented ones, the dot operator will perform fallback operationand still produce an output of the desired storage type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_dot(transpose_a, transpose_b, forward_stype, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_erf(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_erfinv(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_expm1(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_foreach(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_gamma(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_gammaln(lhs, rhs, name, attr, out, kwargs)
end
--- Accumulates data according to indices and get the result. It's the backward of
--- `gather_nd`.
---
--- Given `data` with shape `(Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1})` and indices with shape
--- `(M, Y_0, ..., Y_{K-1})`, the output will have shape `(X_0, X_1, ..., X_{N-1})`,
--- where `M <= N`. If `M == N`, data shape should simply be `(Y_0, ..., Y_{K-1})`.
---
--- The elements in output is defined as follows::
---
--- output[indices[0, y_0, ..., y_{K-1}],
--- ...,
--- indices[M-1, y_0, ..., y_{K-1}],
--- x_M, ..., x_{N-1}] += data[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}]
---
--- all other entries in output are 0 or the original value if AddTo is triggered.
---
--- ### Examples
---
--- data = [2, 3, 0]
--- indices = [[1, 1, 0], [0, 1, 0]]
--- shape = (2, 2)
--- _backward_gather_nd(data, indices, shape) = [[0, 0], [2, 3]] # Same as scatter_nd
---
--- -- The difference between scatter_nd and scatter_nd_acc is the latter will accumulate
--- -- the values that point to the same index.
---
--- data = [2, 3, 0]
--- indices = [[1, 1, 0], [1, 1, 0]]
--- shape = (2, 2)
--- _backward_gather_nd(data, indices, shape) = [[0, 0], [0, 5]]
---
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | data
---@param indices any @Symbol | indices
---@param shape any @Shape(tuple), required | Shape of output.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_gather_nd(data, indices, shape, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_hard_sigmoid(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_hypot(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_hypot_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_image_crop(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_image_normalize(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_extractdiag(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_extracttrian(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_gelqf(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_gemm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_gemm2(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_inverse(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_makediag(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_maketrian(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_potrf(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_potri(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_sumlogdiag(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_syevd(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_syrk(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_trmm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linalg_trsm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_linear_reg_out(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_log(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_log10(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_log1p(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_log2(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param args any @Symbol[] | Positional input arguments
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_log_softmax(...)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_logistic_reg_out(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mae_reg_out(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_max(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_maximum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_maximum_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mean(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_min(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_minimum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_minimum_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mod(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mod_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_moments(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mul(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_mul_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_nanprod(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_nansum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_norm(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_pick(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_power(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_power_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_prod(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_radians(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_rcbrt(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_rdiv_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_reciprocal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_relu(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_repeat(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_reshape(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_reverse(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_rmod_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param scalar any @float | scalar value
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_rpower_scalar(lhs, rhs, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_rsqrt(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sample_multinomial(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sigmoid(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sign(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sin(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sinh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_slice(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_slice_axis(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_slice_like(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_smooth_l1(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param args any @Symbol[] | Positional input arguments
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_softmax(...)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_softmax_cross_entropy(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param args any @Symbol[] | Positional input arguments
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_softmin(...)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_softsign(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sparse_retain(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sqrt(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_square(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_square_sum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_squeeze(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_stack(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sub(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_sum(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_take(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_tan(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_tanh(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_tile(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_topk(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_where(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._backward_while_loop(name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._broadcast_backward(name, attr, out, kwargs)
end
--- Run a if-then-else using user-defined condition and computation
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\control_flow.cc:1212
--- This function support variable length of positional input.
---
---
---@param cond any @Symbol | Input graph for the condition.
---@param then_branch any @Symbol | Input graph for the then branch.
---@param else_branch any @Symbol | Input graph for the else branch.
---@param data any @Symbol[] | The input arrays that include data arrays and states.
---@param num_outputs any @int, required | The number of outputs of the subgraph.
---@param cond_input_locs any @, required | The locations of cond's inputs in the given inputs.
---@param then_input_locs any @, required | The locations of then's inputs in the given inputs.
---@param else_input_locs any @, required | The locations of else's inputs in the given inputs.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._cond(...)
end
--- Returns a copy of the input.
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_unary_op_basic.cc:218
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | The input array.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._copy(data, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @NDArray | input data
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._copyto(data, name, attr, out, kwargs)
end
--- Assign the rhs to a cropped subset of lhs.
---
--- Requirements
--- ------------
--- - output should be explicitly given and be the same as lhs.
--- - lhs and rhs are of the same data type, and on the same device.
---
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\matrix_op.cc:537
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | Source input
---@param rhs any @Symbol | value to assign
---@param begin any @Shape(tuple), required | starting indices for the slice operation, supports negative indices.
---@param end_ any @Shape(tuple), required | ending indices for the slice operation, supports negative indices.
---@param step any @Shape(tuple), optional, default=[] | step for the slice operation, supports negative values.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._crop_assign(lhs, rhs, begin, end_, step, name, attr, out, kwargs)
end
--- (Assign the scalar to a cropped subset of the input.
---
--- Requirements
--- ------------
--- - output should be explicitly given and be the same as input
--- )
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\matrix_op.cc:562
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Source input
---@param scalar any @double, optional, default=0 | The scalar value for assignment.
---@param begin any @Shape(tuple), required | starting indices for the slice operation, supports negative indices.
---@param end_ any @Shape(tuple), required | ending indices for the slice operation, supports negative indices.
---@param step any @Shape(tuple), optional, default=[] | step for the slice operation, supports negative values.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._crop_assign_scalar(data, scalar, begin, end_, step, name, attr, out, kwargs)
end
--- Pad image border with OpenCV.
---
--- This function support variable length of positional input.
---
---
---@param src any @NDArray | source image
---@param top any @int, required | Top margin.
---@param bot any @int, required | Bottom margin.
---@param left any @int, required | Left margin.
---@param right any @int, required | Right margin.
---@param type any @int, optional, default='0' | Filling type (default=cv2.BORDER_CONSTANT).
---@param value any @double, optional, default=0 | (Deprecated! Use ``values`` instead.) Fill with single value.
---@param values any @, optional, default=[] | Fill with value(RGB[A] or gray), up to 4 channels.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._cvcopyMakeBorder(src, top, bot, left, right, type, value, values, name, attr, out, kwargs)
end
--- Decode image with OpenCV.
--- Note: return image in RGB by default, instead of OpenCV's default BGR.
--- This function support variable length of positional input.
---
---
---@param buf any @NDArray | Buffer containing binary encoded image
---@param flag any @int, optional, default='1' | Convert decoded image to grayscale (0) or color (1).
---@param to_rgb any @boolean, optional, default=1 | Whether to convert decoded image to mxnet's default RGB format (instead of opencv's default BGR).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._cvimdecode(buf, flag, to_rgb, name, attr, out, kwargs)
end
--- Read and decode image with OpenCV.
--- Note: return image in RGB by default, instead of OpenCV's default BGR.
--- This function support variable length of positional input.
---
---
---@param filename any @string, required | Name of the image file to be loaded.
---@param flag any @int, optional, default='1' | Convert decoded image to grayscale (0) or color (1).
---@param to_rgb any @boolean, optional, default=1 | Whether to convert decoded image to mxnet's default RGB format (instead of opencv's default BGR).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._cvimread(filename, flag, to_rgb, name, attr, out, kwargs)
end
--- Resize image with OpenCV.
---
--- This function support variable length of positional input.
---
---
---@param src any @NDArray | source image
---@param w any @int, required | Width of resized image.
---@param h any @int, required | Height of resized image.
---@param interp any @int, optional, default='1' | Interpolation method (default=cv2.INTER_LINEAR).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._cvimresize(src, w, h, interp, name, attr, out, kwargs)
end
--- Divides arguments element-wise.
---
--- The storage type of ``elemwise_div`` output is always dense
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._div(lhs, rhs, name, attr, out, kwargs)
end
--- Divide an array with a scalar.
---
--- ``_div_scalar`` only operates on data array of input if input is sparse.
---
--- For example, if input of shape (100, 100) has only 2 non zero elements,
--- i.e. input.data = [5, 6], scalar = nan,
--- it will result output.data = [nan, nan] instead of 10000 nans.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_scalar_op_basic.cc:L171
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._div_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._equal_scalar(data, scalar, name, attr, out, kwargs)
end
--- Return a 2-D array with ones on the diagonal and zeros elsewhere.
--- This function support variable length of positional input.
---
---
---@param N any @, required | Number of rows in the output.
---@param M any @, optional, default=0 | Number of columns in the output. If 0, defaults to N
---@param k any @, optional, default=0 | Index of the diagonal. 0 (the default) refers to the main diagonal.A positive value refers to an upper diagonal.A negative value to a lower diagonal.
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._eye(N, M, k, ctx, dtype, name, attr, out, kwargs)
end
--- Run a for loop over an NDArray with user-defined computation
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\control_flow.cc:1090
--- This function support variable length of positional input.
---
---
---@param fn any @Symbol | Input graph.
---@param data any @Symbol[] | The input arrays that include data arrays and states.
---@param num_outputs any @int, required | The number of outputs of the subgraph.
---@param num_out_data any @int, required | The number of output data of the subgraph.
---@param in_state_locs any @, required | The locations of loop states among the inputs.
---@param in_data_locs any @, required | The locations of input data among the inputs.
---@param remain_locs any @, required | The locations of remaining data among the inputs.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._foreach(...)
end
--- fill target with a scalar value
--- This function support variable length of positional input.
---
---
---@param shape any @Shape(tuple), optional, default=None | The shape of the output
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param value any @double, required | Value with which to fill newly created tensor
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._full(shape, ctx, dtype, value, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._grad_add(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._greater(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._greater_equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._greater_equal_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._greater_scalar(data, scalar, name, attr, out, kwargs)
end
--- This operators implements the histogram function.
---
--- ### Example
--- x = [[0, 1], [2, 2], [3, 4]]
--- histo, bin_edges = histogram(data=x, bin_bounds=[], bin_cnt=5, range=(0,5))
--- histo = [1, 1, 2, 1, 1]
--- bin_edges = [0., 1., 2., 3., 4.]
--- histo, bin_edges = histogram(data=x, bin_bounds=[0., 2.1, 3.])
--- histo = [4, 1]
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\histogram.cc:L136
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Input ndarray
---@param bins any @Symbol | Input ndarray
---@param bin_cnt any @int or None, optional, default='None' | Number of bins for uniform case
---@param range any @, optional, default=None | The lower and upper range of the bins. if not provided, range is simply (a.min(), a.max()). values outside the range are ignored. the first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. while bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._histogram(data, bins, bin_cnt, range, name, attr, out, kwargs)
end
--- Given the "legs" of a right triangle, return its hypotenuse.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_op_extended.cc:L79
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._hypot(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._hypot_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | First input.
---@param rhs any @Symbol | Second input.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._identity_with_attr_like_rhs(lhs, rhs, name, attr, out, kwargs)
end
--- Decode an image, clip to (x0, y0, x1, y1), subtract mean, and write to buffer
--- This function support variable length of positional input.
---
---
---@param mean any @Symbol | image mean
---@param index any @int | buffer position for output
---@param x0 any @int | x0
---@param y0 any @int | y0
---@param x1 any @int | x1
---@param y1 any @int | y1
---@param c any @int | channel
---@param size any @int | length of str_img
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._imdecode(mean, index, x0, y0, x1, y1, c, size, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._lesser(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._lesser_equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._lesser_equal_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._lesser_scalar(data, scalar, name, attr, out, kwargs)
end
--- Return evenly spaced numbers over a specified interval. Similar to Numpy
--- This function support variable length of positional input.
---
---
---@param start any @double, required | Start of interval. The interval includes this value. The default start value is 0.
---@param stop any @double or None, optional, default=None | End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
---@param step any @double, optional, default=1 | Spacing between values.
---@param repeat_ any @int, optional, default='1' | The repeating time of all elements. E.g repeat=3, the element a will be repeated three times --> a, a, a.
---@param infer_range any @boolean, optional, default=0 | When set to True, infer the stop position from the start, step, repeat, and output tensor size.
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._linspace(start, stop, step, repeat_, infer_range, ctx, dtype, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_and(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_and_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_or(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_or_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_xor(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._logical_xor_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._maximum(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._maximum_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._minimum(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._minimum_scalar(data, scalar, name, attr, out, kwargs)
end
--- Subtracts arguments element-wise.
---
--- The storage type of ``elemwise_sub`` output depends on storage types of inputs
---
--- - elemwise_sub(row_sparse, row_sparse) = row_sparse
--- - elemwise_sub(csr, csr) = csr
--- - elemwise_sub(default, csr) = default
--- - elemwise_sub(csr, default) = default
--- - elemwise_sub(default, rsp) = default
--- - elemwise_sub(rsp, default) = default
--- - otherwise, ``elemwise_sub`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._minus(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._minus_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._mod(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._mod_scalar(data, scalar, name, attr, out, kwargs)
end
--- Update function for multi-precision AdamW optimizer.
---
--- AdamW is seen as a modification of Adam by decoupling the weight decay from the
--- optimization steps taken w.r.t. the loss function.
---
--- Adam update consists of the following steps, where g represents gradient and m, v
--- are 1st and 2nd order moment estimates (mean and variance).
---
--- .. math::
---
--- g_t = \nabla J(W_{t-1})\\
--- m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t\\
--- v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\
--- W_t = W_{t-1} - \eta_t (\alpha \frac{ m_t }{ \sqrt{ v_t } + \epsilon } + wd W_{t-1})
---
--- It updates the weights using::
---
--- m = beta1*m + (1-beta1)*grad
--- v = beta2*v + (1-beta2)*(grad**2)
--- w -= eta * (learning_rate * m / (sqrt(v) + epsilon) + w * wd)
---
--- Note that gradient is rescaled to grad = rescale_grad * grad. If rescale_grad is NaN, Inf, or 0,
--- the update is skipped.
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\contrib\adamw.cc:L77
--- This function support variable length of positional input.
---
---
---@param weight any @Symbol | Weight
---@param grad any @Symbol | Gradient
---@param mean any @Symbol | Moving mean
---@param var any @Symbol | Moving variance
---@param weight32 any @Symbol | Weight32
---@param rescale_grad any @Symbol | Rescale gradient to rescale_grad * grad. If NaN, Inf, or 0, the update is skipped.
---@param lr any @float, required | Learning rate
---@param beta1 any @float, optional, default=0.899999976 | The decay rate for the 1st moment estimates.
---@param beta2 any @float, optional, default=0.999000013 | The decay rate for the 2nd moment estimates.
---@param epsilon any @float, optional, default=9.99999994e-09 | A small constant for numerical stability.
---@param wd any @float, optional, default=0 | Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
---@param eta any @float, required | Learning rate schedule multiplier
---@param clip_gradient any @float, optional, default=-1 | Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._mp_adamw_update(weight, grad, mean, var, weight32, rescale_grad, lr, beta1, beta2, epsilon, wd, eta, clip_gradient, name, attr, out, kwargs)
end
--- Multiplies arguments element-wise.
---
--- The storage type of ``elemwise_mul`` output depends on storage types of inputs
---
--- - elemwise_mul(default, default) = default
--- - elemwise_mul(row_sparse, row_sparse) = row_sparse
--- - elemwise_mul(default, row_sparse) = row_sparse
--- - elemwise_mul(row_sparse, default) = row_sparse
--- - elemwise_mul(csr, csr) = csr
--- - otherwise, ``elemwise_mul`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._mul(lhs, rhs, name, attr, out, kwargs)
end
--- Multiply an array with a scalar.
---
--- ``_mul_scalar`` only operates on data array of input if input is sparse.
---
--- For example, if input of shape (100, 100) has only 2 non zero elements,
--- i.e. input.data = [5, 6], scalar = nan,
--- it will result output.data = [nan, nan] instead of 10000 nans.
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\elemwise_binary_scalar_op_basic.cc:L149
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._mul_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._not_equal(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._not_equal_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @NDArray | Left operand to the function.
---@param rhs any @NDArray | Right operand to the function.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._onehot_encode(lhs, rhs, name, attr, out, kwargs)
end
--- fill target with ones
--- This function support variable length of positional input.
---
---
---@param shape any @Shape(tuple), optional, default=[] | The shape of the output
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._ones(shape, ctx, dtype, name, attr, out, kwargs)
end
--- Adds arguments element-wise.
---
--- The storage type of ``elemwise_add`` output depends on storage types of inputs
---
--- - elemwise_add(row_sparse, row_sparse) = row_sparse
--- - elemwise_add(csr, csr) = csr
--- - elemwise_add(default, csr) = default
--- - elemwise_add(csr, default) = default
--- - elemwise_add(default, rsp) = default
--- - elemwise_add(rsp, default) = default
--- - otherwise, ``elemwise_add`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._plus(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._plus_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._power(lhs, rhs, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._power_scalar(data, scalar, name, attr, out, kwargs)
end
--- Converts a batch of index arrays into an array of flat indices. The operator follows numpy conventions so a single multi index is given by a column of the input matrix. The leading dimension may be left unspecified by using -1 as placeholder.
---
--- ### Examples
---
--- A = [[3,6,6],[4,5,1]]
--- ravel(A, shape=(7,6)) = [22,41,37]
--- ravel(A, shape=(-1,6)) = [22,41,37]
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\ravel.cc:L42
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Batch of multi-indices
---@param shape any @Shape(tuple), optional, default=None | Shape of the array into which the multi-indices apply.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._ravel_multi_index(data, shape, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._rdiv_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._rminus_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._rmod_scalar(data, scalar, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol[] | List of arrays to concatenate
---@param dim any @int, optional, default='1' | the dimension to be concated.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._rnn_param_concat(...)
end
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._rpower_scalar(data, scalar, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- exponential distributions with parameters lambda (rate).
---
--- The parameters of the distributions are provided as an input array.
--- Let *[s]* be the shape of the input array, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input array, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input value at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input array.
---
--- ### Examples
---
--- lam = [ 1.0, 8.5 ]
---
--- // Draw a single sample for each distribution
--- sample_exponential(lam) = [ 0.51837951, 0.09994757]
---
--- // Draw a vector containing two samples for each distribution
--- sample_exponential(lam, shape=(2)) = [[ 0.51837951, 0.19866663],
--- [ 0.09994757, 0.50447971]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L284
--- This function support variable length of positional input.
---
---
---@param lam any @Symbol | Lambda (rate) parameters of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_exponential(lam, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- gamma distributions with parameters *alpha* (shape) and *beta* (scale).
---
--- The parameters of the distributions are provided as input arrays.
--- Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input values at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input arrays.
---
--- ### Examples
---
--- alpha = [ 0.0, 2.5 ]
--- beta = [ 1.0, 0.7 ]
---
--- // Draw a single sample for each distribution
--- sample_gamma(alpha, beta) = [ 0. , 2.25797319]
---
--- // Draw a vector containing two samples for each distribution
--- sample_gamma(alpha, beta, shape=(2)) = [[ 0. , 0. ],
--- [ 2.25797319, 1.70734084]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L282
--- This function support variable length of positional input.
---
---
---@param alpha any @Symbol | Alpha (shape) parameters of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param beta any @Symbol | Beta (scale) parameters of the distributions.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_gamma(alpha, beta, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- generalized negative binomial distributions with parameters *mu* (mean) and *alpha* (dispersion).
---
--- The parameters of the distributions are provided as input arrays.
--- Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input values at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input arrays.
---
--- Samples will always be returned as a floating point data type.
---
--- ### Examples
---
--- mu = [ 2.0, 2.5 ]
--- alpha = [ 1.0, 0.1 ]
---
--- // Draw a single sample for each distribution
--- sample_generalized_negative_binomial(mu, alpha) = [ 0., 3.]
---
--- // Draw a vector containing two samples for each distribution
--- sample_generalized_negative_binomial(mu, alpha, shape=(2)) = [[ 0., 3.],
--- [ 3., 1.]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L293
--- This function support variable length of positional input.
---
---
---@param mu any @Symbol | Means of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param alpha any @Symbol | Alpha (dispersion) parameters of the distributions.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_generalized_negative_binomial(mu, alpha, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple multinomial distributions.
---
--- *data* is an *n* dimensional array whose last dimension has length *k*, where
--- *k* is the number of possible outcomes of each multinomial distribution. This
--- operator will draw *shape* samples from each distribution. If shape is empty
--- one sample will be drawn from each distribution.
---
--- If *get_prob* is true, a second array containing log likelihood of the drawn
--- samples will also be returned. This is usually used for reinforcement learning
--- where you can provide reward as head gradient for this array to estimate
--- gradient.
---
--- Note that the input distribution must be normalized, i.e. *data* must sum to
--- 1 along its last axis.
---
--- ### Examples
---
--- probs = [[0, 0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1, 0]]
---
--- // Draw a single sample for each distribution
--- sample_multinomial(probs) = [3, 0]
---
--- // Draw a vector containing two samples for each distribution
--- sample_multinomial(probs, shape=(2)) = [[4, 2],
--- [0, 0]]
---
--- // requests log likelihood
--- sample_multinomial(probs, get_prob=True) = [2, 1], [0.2, 0.3]
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Distribution probabilities. Must sum to one on the last axis.
---@param shape any @Shape(tuple), optional, default=[] | Shape to be sampled from each random distribution.
---@param get_prob any @boolean, optional, default=0 | Whether to also return the log probability of sampled result. This is usually used for differentiating through stochastic variables, e.g. in reinforcement learning.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='int32' | DType of the output in case this can't be inferred.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_multinomial(data, shape, get_prob, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- negative binomial distributions with parameters *k* (failure limit) and *p* (failure probability).
---
--- The parameters of the distributions are provided as input arrays.
--- Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input values at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input arrays.
---
--- Samples will always be returned as a floating point data type.
---
--- ### Examples
---
--- k = [ 20, 49 ]
--- p = [ 0.4 , 0.77 ]
---
--- // Draw a single sample for each distribution
--- sample_negative_binomial(k, p) = [ 15., 16.]
---
--- // Draw a vector containing two samples for each distribution
--- sample_negative_binomial(k, p, shape=(2)) = [[ 15., 50.],
--- [ 16., 12.]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L289
--- This function support variable length of positional input.
---
---
---@param k any @Symbol | Limits of unsuccessful experiments.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param p any @Symbol | Failure probabilities in each experiment.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_negative_binomial(k, p, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- normal distributions with parameters *mu* (mean) and *sigma* (standard deviation).
---
--- The parameters of the distributions are provided as input arrays.
--- Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input values at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input arrays.
---
--- ### Examples
---
--- mu = [ 0.0, 2.5 ]
--- sigma = [ 1.0, 3.7 ]
---
--- // Draw a single sample for each distribution
--- sample_normal(mu, sigma) = [-0.56410581, 0.95934606]
---
--- // Draw a vector containing two samples for each distribution
--- sample_normal(mu, sigma, shape=(2)) = [[-0.56410581, 0.2928229 ],
--- [ 0.95934606, 4.48287058]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L279
--- This function support variable length of positional input.
---
---
---@param mu any @Symbol | Means of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param sigma any @Symbol | Standard deviations of the distributions.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_normal(mu, sigma, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- Poisson distributions with parameters lambda (rate).
---
--- The parameters of the distributions are provided as an input array.
--- Let *[s]* be the shape of the input array, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input array, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input value at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input array.
---
--- Samples will always be returned as a floating point data type.
---
--- ### Examples
---
--- lam = [ 1.0, 8.5 ]
---
--- // Draw a single sample for each distribution
--- sample_poisson(lam) = [ 0., 13.]
---
--- // Draw a vector containing two samples for each distribution
--- sample_poisson(lam, shape=(2)) = [[ 0., 4.],
--- [ 13., 8.]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L286
--- This function support variable length of positional input.
---
---
---@param lam any @Symbol | Lambda (rate) parameters of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_poisson(lam, shape, dtype, name, attr, out, kwargs)
end
--- Concurrent sampling from multiple
--- uniform distributions on the intervals given by *[low,high)*.
---
--- The parameters of the distributions are provided as input arrays.
--- Let *[s]* be the shape of the input arrays, *n* be the dimension of *[s]*, *[t]*
--- be the shape specified as the parameter of the operator, and *m* be the dimension
--- of *[t]*. Then the output will be a *(n+m)*-dimensional array with shape *[s]x[t]*.
---
--- For any valid *n*-dimensional index *i* with respect to the input arrays, *output[i]*
--- will be an *m*-dimensional array that holds randomly drawn samples from the distribution
--- which is parameterized by the input values at index *i*. If the shape parameter of the
--- operator is not set, then one sample will be drawn per distribution and the output array
--- has the same shape as the input arrays.
---
--- ### Examples
---
--- low = [ 0.0, 2.5 ]
--- high = [ 1.0, 3.7 ]
---
--- // Draw a single sample for each distribution
--- sample_uniform(low, high) = [ 0.40451524, 3.18687344]
---
--- // Draw a vector containing two samples for each distribution
--- sample_uniform(low, high, shape=(2)) = [[ 0.40451524, 0.18017688],
--- [ 3.18687344, 3.68352246]]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\multisample_op.cc:L277
--- This function support variable length of positional input.
---
---
---@param low any @Symbol | Lower bounds of the distributions.
---@param shape any @Shape(tuple), optional, default=None | Shape to be sampled from each random distribution.
---@param dtype any @{'None', 'float16', 'float32', 'float64'},optional, default='None' | DType of the output in case this can't be inferred. Defaults to float32 if not defined (dtype=None).
---@param high any @Symbol | Upper bounds of the distributions.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_uniform(low, high, shape, dtype, name, attr, out, kwargs)
end
--- Draw random samples from an an approximately log-uniform
--- or Zipfian distribution without replacement.
---
--- This operation takes a 2-D shape `(batch_size, num_sampled)`,
--- and randomly generates *num_sampled* samples from the range of integers [0, range_max)
--- for each instance in the batch.
---
--- The elements in each instance are drawn without replacement from the base distribution.
--- The base distribution for this operator is an approximately log-uniform or Zipfian distribution:
---
--- P(class) = (log(class + 2) - log(class + 1)) / log(range_max + 1)
---
--- Additionaly, it also returns the number of trials used to obtain `num_sampled` samples for
--- each instance in the batch.
---
--- ### Example
---
--- samples, trials = _sample_unique_zipfian(750000, shape=(4, 8192))
--- unique(samples[0]) = 8192
--- unique(samples[3]) = 8192
--- trials[0] = 16435
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\random\unique_sample_op.cc:L66
--- This function support variable length of positional input.
---
---
---@param range_max any @int, required | The number of possible classes.
---@param shape any @Shape(tuple), optional, default=None | 2-D shape of the output, where shape[0] is the batch size, and shape[1] is the number of candidates to sample for each batch.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sample_unique_zipfian(range_max, shape, name, attr, out, kwargs)
end
--- Divides arguments element-wise. If the left-hand-side input is 'row_sparse', then
--- only the values which exist in the left-hand sparse array are computed. The 'missing' values
--- are ignored.
---
--- The storage type of ``_scatter_elemwise_div`` output depends on storage types of inputs
---
--- - _scatter_elemwise_div(row_sparse, row_sparse) = row_sparse
--- - _scatter_elemwise_div(row_sparse, dense) = row_sparse
--- - _scatter_elemwise_div(row_sparse, csr) = row_sparse
--- - otherwise, ``_scatter_elemwise_div`` behaves exactly like elemwise_div and generates output
--- with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._scatter_elemwise_div(lhs, rhs, name, attr, out, kwargs)
end
--- Subtracts a scalar to a tensor element-wise. If the left-hand-side input is
--- 'row_sparse' or 'csr', then only the values which exist in the left-hand sparse array are computed.
--- The 'missing' values are ignored.
---
--- The storage type of ``_scatter_minus_scalar`` output depends on storage types of inputs
---
--- - _scatter_minus_scalar(row_sparse, scalar) = row_sparse
--- - _scatter_minus_scalar(csr, scalar) = csr
--- - otherwise, ``_scatter_minus_scalar`` behaves exactly like _minus_scalar and generates output
--- with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._scatter_minus_scalar(data, scalar, name, attr, out, kwargs)
end
--- Adds a scalar to a tensor element-wise. If the left-hand-side input is
--- 'row_sparse' or 'csr', then only the values which exist in the left-hand sparse array are computed.
--- The 'missing' values are ignored.
---
--- The storage type of ``_scatter_plus_scalar`` output depends on storage types of inputs
---
--- - _scatter_plus_scalar(row_sparse, scalar) = row_sparse
--- - _scatter_plus_scalar(csr, scalar) = csr
--- - otherwise, ``_scatter_plus_scalar`` behaves exactly like _plus_scalar and generates output
--- with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | source input
---@param scalar any @float | scalar input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._scatter_plus_scalar(data, scalar, name, attr, out, kwargs)
end
--- This operator has the same functionality as scatter_nd
--- except that it does not reset the elements not indexed by the input
--- index `NDArray` in the input data `NDArray`. output should be explicitly
--- given and be the same as lhs.
---
--- ### Note: This operator is for internal use only.
---
--- ### Examples
---
--- data = [2, 3, 0]
--- indices = [[1, 1, 0], [0, 1, 0]]
--- out = [[1, 1], [1, 1]]
--- _scatter_set_nd(lhs=out, rhs=data, indices=indices, out=out)
--- out = [[0, 1], [2, 3]]
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | source input
---@param rhs any @Symbol | value to assign
---@param indices any @Symbol | indices
---@param shape any @Shape(tuple), required | Shape of output.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._scatter_set_nd(lhs, rhs, indices, shape, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param src any @real_t | Source input to the function.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._set_value(src, name, attr, out, kwargs)
end
--- _sg_mkldnn_conv
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\subgraph\mkldnn\mkldnn_conv.cc:L770
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sg_mkldnn_conv(name, attr, out, kwargs)
end
--- _sg_mkldnn_fully_connected
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\subgraph\mkldnn\mkldnn_fc.cc:L410
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sg_mkldnn_fully_connected(name, attr, out, kwargs)
end
--- Randomly shuffle the elements.
---
--- This shuffles the array along the first axis.
--- The order of the elements in each subarray does not change.
--- For example, if a 2D array is given, the order of the rows randomly changes,
--- but the order of the elements in each row does not change.
---
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Data to be shuffled.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._shuffle(data, name, attr, out, kwargs)
end
--- Assign the rhs to a cropped subset of lhs.
---
--- Requirements
--- ------------
--- - output should be explicitly given and be the same as lhs.
--- - lhs and rhs are of the same data type, and on the same device.
---
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\matrix_op.cc:537
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | Source input
---@param rhs any @Symbol | value to assign
---@param begin any @Shape(tuple), required | starting indices for the slice operation, supports negative indices.
---@param end_ any @Shape(tuple), required | ending indices for the slice operation, supports negative indices.
---@param step any @Shape(tuple), optional, default=[] | step for the slice operation, supports negative values.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._slice_assign(lhs, rhs, begin, end_, step, name, attr, out, kwargs)
end
--- (Assign the scalar to a cropped subset of the input.
---
--- Requirements
--- ------------
--- - output should be explicitly given and be the same as input
--- )
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\matrix_op.cc:562
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Source input
---@param scalar any @double, optional, default=0 | The scalar value for assignment.
---@param begin any @Shape(tuple), required | starting indices for the slice operation, supports negative indices.
---@param end_ any @Shape(tuple), required | ending indices for the slice operation, supports negative indices.
---@param step any @Shape(tuple), optional, default=[] | step for the slice operation, supports negative values.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._slice_assign_scalar(data, scalar, begin, end_, step, name, attr, out, kwargs)
end
--- Splits an array along a particular axis into multiple sub-arrays.
---
--- ### Example
---
--- x = [[[ 1.]
--- [ 2.]]
--- [[ 3.]
--- [ 4.]]
--- [[ 5.]
--- [ 6.]]]
--- x.shape = (3, 2, 1)
---
--- y = split_v2(x, axis=1, indices_or_sections=2) // a list of 2 arrays with shape (3, 1, 1)
--- y = [[[ 1.]]
--- [[ 3.]]
--- [[ 5.]]]
---
--- [[[ 2.]]
--- [[ 4.]]
--- [[ 6.]]]
---
--- y[0].shape = (3, 1, 1)
---
--- z = split_v2(x, axis=0, indices_or_sections=3) // a list of 3 arrays with shape (1, 2, 1)
--- z = [[[ 1.]
--- [ 2.]]]
---
--- [[[ 3.]
--- [ 4.]]]
---
--- [[[ 5.]
--- [ 6.]]]
---
--- z[0].shape = (1, 2, 1)
---
--- w = split_v2(x, axis=0, indices_or_sections=(1,)) // a list of 2 arrays with shape [(1, 2, 1), (2, 2, 1)]
--- w = [[[ 1.]
--- [ 2.]]]
---
--- [[[3.]
--- [4.]]
---
--- [[5.]
--- [6.]]]
---
--- w[0].shape = (1, 2, 1)
--- w[1].shape = (2, 2, 1)
---
--- `squeeze_axis=True` removes the axis with length 1 from the shapes of the output arrays.
--- **Note** that setting `squeeze_axis` to ``1`` removes axis with length 1 only
--- along the `axis` which it is split.
--- Also `squeeze_axis` can be set to true only if ``input.shape[axis] == indices_or_sections``.
---
--- ### Example
---
--- z = split_v2(x, axis=0, indices_or_sections=3, squeeze_axis=1) // a list of 3 arrays with shape (2, 1)
--- z = [[ 1.]
--- [ 2.]]
---
--- [[ 3.]
--- [ 4.]]
---
--- [[ 5.]
--- [ 6.]]
--- z[0].shape = (2, 1)
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\matrix_op.cc:L1192
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | The input
---@param indices any @Shape(tuple), required | Indices of splits. The elements should denote the boundaries of at which split is performed along the `axis`.
---@param axis any @int, optional, default='1' | Axis along which to split.
---@param squeeze_axis any @boolean, optional, default=0 | If true, Removes the axis with length 1 from the shapes of the output arrays. **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1 only along the `axis` which it is split. Also `squeeze_axis` can be set to ``true`` only if ``input.shape[axis] == num_outputs``.
---@param sections any @int, optional, default='0' | Number of sections if equally splitted. Default to 0 which means split by indices.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._split_v2(data, indices, axis, squeeze_axis, sections, name, attr, out, kwargs)
end
---
--- This function support variable length of positional input.
---
---
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._split_v2_backward(name, attr, out, kwargs)
end
--- Computes the square sum of array elements over a given axis
--- for row-sparse matrix. This is a temporary solution for fusing ops square and
--- sum together for row-sparse matrix to save memory for storing gradients.
--- It will become deprecated once the functionality of fusing operators is finished
--- in the future.
---
--- ### Example
---
--- dns = mx.nd.array([[0, 0], [1, 2], [0, 0], [3, 4], [0, 0]])
--- rsp = dns.tostype('row_sparse')
--- sum = mx.nd._internal._square_sum(rsp, axis=1)
--- sum = [0, 5, 0, 25, 0]
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\square_sum.cc:L63
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | The input
---@param axis any @Shape or None, optional, default=None | The axis or axes along which to perform the reduction. The default, `axis=()`, will compute over all elements into a scalar array with shape `(1,)`. If `axis` is int, a reduction is performed on a particular axis. If `axis` is a tuple of ints, a reduction is performed on all the axes specified in the tuple. If `exclude` is true, reduction will be performed on the axes that are NOT in axis instead. Negative values means indexing from right to left.
---@param keepdims any @boolean, optional, default=0 | If this is set to `True`, the reduced axes are left in the result as dimension with size one.
---@param exclude any @boolean, optional, default=0 | Whether to perform reduction on axis that are NOT in axis instead.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._square_sum(data, axis, keepdims, exclude, name, attr, out, kwargs)
end
--- Subtracts arguments element-wise.
---
--- The storage type of ``elemwise_sub`` output depends on storage types of inputs
---
--- - elemwise_sub(row_sparse, row_sparse) = row_sparse
--- - elemwise_sub(csr, csr) = csr
--- - elemwise_sub(default, csr) = default
--- - elemwise_sub(csr, default) = default
--- - elemwise_sub(default, rsp) = default
--- - elemwise_sub(rsp, default) = default
--- - otherwise, ``elemwise_sub`` generates output with default storage
---
---
--- This function support variable length of positional input.
---
---
---@param lhs any @Symbol | first input
---@param rhs any @Symbol | second input
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._sub(lhs, rhs, name, attr, out, kwargs)
end
--- Converts an array of flat indices into a batch of index arrays. The operator follows numpy conventions so a single multi index is given by a column of the output matrix. The leading dimension may be left unspecified by using -1 as placeholder.
---
--- ### Examples
---
--- A = [22,41,37]
--- unravel(A, shape=(7,6)) = [[3,6,6],[4,5,1]]
--- unravel(A, shape=(-1,6)) = [[3,6,6],[4,5,1]]
---
---
---
--- ### Defined in C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\ravel.cc:L67
--- This function support variable length of positional input.
---
---
---@param data any @Symbol | Array of flat indices
---@param shape any @Shape(tuple), optional, default=None | Shape of the array into which the multi-indices apply.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._unravel_index(data, shape, name, attr, out, kwargs)
end
--- Run a while loop over with user-defined condition and computation
---
--- From:C:\Jenkins\workspace\mxnet-tag\mxnet\src\operator\control_flow.cc:1151
--- This function support variable length of positional input.
---
---
---@param cond any @Symbol | Input graph for the loop condition.
---@param func any @Symbol | Input graph for the loop body.
---@param data any @Symbol[] | The input arrays that include data arrays and states.
---@param num_outputs any @int, required | The number of outputs of the subgraph.
---@param num_out_data any @int, required | The number of outputs from the function body.
---@param max_iterations any @int, required | Maximum number of iterations.
---@param cond_input_locs any @, required | The locations of cond's inputs in the given inputs.
---@param func_input_locs any @, required | The locations of func's inputs in the given inputs.
---@param func_var_locs any @, required | The locations of loop_vars among func's inputs.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._while_loop(...)
end
--- fill target with zeros
--- This function support variable length of positional input.
---
---
---@param shape any @Shape(tuple), optional, default=[] | The shape of the output
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @{'float16', 'float32', 'float64', 'int32', 'int64', 'int8', 'uint8'},optional, default='float32' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._zeros(shape, ctx, dtype, name, attr, out, kwargs)
end
--- fill target with zeros without default dtype
--- This function support variable length of positional input.
---
---
---@param shape any @Shape(tuple), optional, default=None | The shape of the output
---@param ctx any @string, optional, default='' | Context of output, in format [cpu|gpu|cpu_pinned](n).Only used for imperative calls.
---@param dtype any @int, optional, default='-1' | Target data type.
---@param name string @optional | Name of the resulting symbol.
---@return mx.symbol.Symbol @The result symbol.
function M._zeros_without_dtype(shape, ctx, dtype, name, attr, out, kwargs)
end
return M |
-- -------------------------------------------------------------------------- --
-- Bulk insert tests --
-- -------------------------------------------------------------------------- --
cursize=0
function prepare()
local i
db_connect()
for i = 0,num_threads-1 do
db_query([[
CREATE TABLE IF NOT EXISTS sbtest]] .. i .. [[ (
id INTEGER UNSIGNED NOT NULL,
k INTEGER UNSIGNED DEFAULT '0' NOT NULL,
PRIMARY KEY (id)
) ENGINE = InnoDB
]])
end
end
function event(thread_id)
local i
if (cursize == 0) then
db_bulk_insert_init("INSERT INTO sbtest" .. thread_id .. " VALUES")
end
cursize = cursize + 1
db_bulk_insert_next("(" .. cursize .. "," .. cursize .. ")")
end
function thread_done(thread_9d)
db_bulk_insert_done()
end
function cleanup()
local i
for i = 0,num_threads-1 do
print("Dropping table 'sbtest" .. i .. "'...")
db_query("DROP TABLE IF EXISTS sbtest".. i )
end
end
|
-- Copyright (c) 2019 Bart van Strien
-- See LICENSE file for more information
local co2 = {}
local co1 = require "coroutine"
co2.create = co1.create
co2.running = co1.running
co2.status = co1.status
co2.yield = co1.yield
-- Note: rename resume to presume
co2.presume = co1.resume
local function strip_traceback_header(traceback)
return traceback:gsub("^.-\n", "")
end
function co2.traceback(coro, level)
level = level or 0
local parts = {}
if coro then
table.insert(parts, debug.traceback(coro))
end
-- Note: for some reason debug.traceback needs a string to pass a level
-- But if you pass a string it adds a newline
table.insert(parts, debug.traceback("", 2 + level):sub(2))
for i = 2, #parts do
parts[i] = strip_traceback_header(parts[i])
end
return table.concat(parts, "\n\t-- coroutine boundary --\n")
end
-- xpresume is to presume what xpcall is to pcall
-- Except xpresume can also pass arguments
function co2.xpresume(coro, handler, ...)
local function dispatch(status, maybe_err, ...)
if status then
return true, maybe_err, ...
else
return false, handler(maybe_err, coro)
end
end
return dispatch(co2.presume(coro, ...))
end
local function generic_error_handler(msg, coro)
error(string.format("Coroutine failure: %s\n\nCoroutine %s", msg, debug.traceback(coro)))
end
-- resume then propagates the error, using a default generic error handler
-- which adds a coroutine stack trace
function co2.resume(coro, ...)
return select(2, co2.xpresume(coro, generic_error_handler, ...))
end
-- And co2.wrap is like coroutine.wrap, except it uses co2.resume, and thus
-- the same generic error handler
function co2.wrap(f)
local co = co2.create(f)
return function(...)
return co2.resume(co, ...)
end
end
return co2
|
local function bind(obj, method)
return function(...)
return method(obj, ...)
end
end
return bind
|
object_tangible_furniture_all_frn_all_chair_kitchen_s2 = object_tangible_furniture_all_shared_frn_all_chair_kitchen_s2:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_chair_kitchen_s2, "object/tangible/furniture/all/frn_all_chair_kitchen_s2.iff")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.